Skip to content

Instantly share code, notes, and snippets.

@inklesspen
Created January 6, 2009 05:03
Show Gist options
  • Save inklesspen/43675 to your computer and use it in GitHub Desktop.
Save inklesspen/43675 to your computer and use it in GitHub Desktop.
"""The application's model objects"""
import sqlalchemy as sa
from sqlalchemy import orm
import re
from central_library.model import meta
def init_model(engine):
"""Call me before using any of the tables or classes in the model"""
sm = orm.sessionmaker(autoflush=True, autocommit=False, bind=engine)
meta.engine = engine
meta.Session = orm.scoped_session(sm)
meta.Session.mapper(User, users_table, properties = {"loans": orm.relation(Loan, backref='user')})
meta.Session.mapper(Entity, entities_table, properties = {"items": orm.relation(Item, backref='entity')})
meta.Session.mapper(Item, items_table, properties = {"loans": orm.relation(Loan, backref='item')})
meta.Session.mapper(Loan, loans_table)
users_table = sa.Table("users", meta.metadata,
sa.Column("user_id", sa.types.Integer, primary_key=True),
sa.Column("name", sa.types.Unicode(200), nullable=False),
sa.Column("address", sa.types.UnicodeText, nullable=False),
sa.Column("is_staff", sa.types.Boolean, nullable=False, default=False)
)
entities_table = sa.Table("entities", meta.metadata,
sa.Column("entity_id", sa.types.Integer, primary_key=True),
sa.Column("title", sa.types.Unicode(200), nullable=False),
sa.Column("author", sa.types.Unicode(200), nullable=False),
sa.Column("ean", sa.types.String(13), nullable=True, unique=True),
sa.Column("pub_date", sa.types.Date, nullable=True),
sa.Column("kind", sa.types.String(50), nullable=False),
)
items_table = sa.Table("items", meta.metadata,
sa.Column("item_id", sa.types.Integer, primary_key=True),
sa.Column("entity_id", sa.types.Integer, sa.ForeignKey("entities.entity_id"), nullable=False),
sa.Column("acquired_date", sa.types.Date, nullable=False),
sa.Column("condition_notes", sa.types.UnicodeText, nullable=True),
)
loans_table = sa.Table("loans", meta.metadata,
sa.Column("user_id", sa.types.Integer, sa.ForeignKey("users.user_id"), primary_key=True),
sa.Column("item_id", sa.types.Integer, sa.ForeignKey("items.item_id"), primary_key=True),
sa.Column("due_date", sa.types.Date, primary_key=True),
)
class OrmObject(object):
pass
# def __init__(self, **kwargs):
class User(OrmObject):
def __repr__(self):
return "<User('%d', '%s', '%s', '%s')>" % (self.user_id, self.name, self.address, self.is_staff)
class Entity(OrmObject):
@orm.validates('kind')
def _validate_kind(self, key, kind):
assert kind in ['book', "video", "audio", "software"]
return kind
@orm.validates('ean')
def _validate_ean(self, key, ean):
ean = re.sub(r"\D", "", ean)
assert len(ean) == 13
return ean
class Item(OrmObject):
pass
class Loan(OrmObject):
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment