Friday, June 26, 2015

Postgres INHERITS partition table with Flask SQLAlchemy

Sqlachemy

Sqlalchemy version 1.0.0 released a feature to support postgres inheritance. Had a quite a time to implement in a Flask-Sqlalchemy.

 1 from app import db, app, bcrypt, redis
 2 
 3 class GarrisonProperty(db.Model):
 4     __tablename__ = 'garrison_properties'
 5 
 6     id = db.Column(db.Integer(), primary_key=True)
 7     building_id =  db.Column(db.Integer())
 8     level = db.Column(db.Integer())
 9     build_cost = db.Column(db.Integer())
10     build_time = db.Column(db.Integer())
11 
12 class Townhall(db.Model):
13     __tablename__ = "townhall"
14     __table_args__ = (
15     ¦   db.PrimaryKeyConstraint('building_id', 'level'),
16     ¦   {'postgresql_inherits' : 'garrison_properties'}
17     )
18 
19     id = db.Column(db.Integer())
20     building_id =  db.Column(db.Integer())
21     level = db.Column(db.Integer())
22     build_cost = db.Column(db.Integer())
23     build_time = db.Column(db.Integer())
24     unlocks = db.Column(db.Integer())

We wanted something that is simple and doesn't really want to the SQLAlchemy join. By this implementation, it should simplify our database structure.

We had to bring all the attributes from the parent model (GarrisonProperty) into the child just to have the access. The db shouldn't do any duplicates for it.



Source:
https://bitbucket.org/zzzeek/sqlalchemy/issue/2051/support-postgresql-table-options

No comments:

Post a Comment