From 2a403cb5447df5e3e85f595f08d27d061200d5e9 Mon Sep 17 00:00:00 2001 From: Edward Betts Date: Wed, 25 Sep 2019 13:22:42 +0100 Subject: [PATCH] Add database bits. --- depicts/database.py | 21 +++++++++++++++++++++ depicts/model.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 depicts/database.py create mode 100644 depicts/model.py diff --git a/depicts/database.py b/depicts/database.py new file mode 100644 index 0000000..7cd43fe --- /dev/null +++ b/depicts/database.py @@ -0,0 +1,21 @@ +from sqlalchemy import create_engine, func +from sqlalchemy.orm import scoped_session, sessionmaker + +session = scoped_session(sessionmaker()) + +def init_db(db_url): + session.configure(bind=get_engine(db_url)) + +def get_engine(db_url): + return create_engine(db_url, pool_recycle=3600, pool_size=20, max_overflow=40) + +def init_app(app, echo=False): + db_url = app.config['DB_URL'] + session.configure(bind=get_engine(db_url, echo=echo)) + + @app.teardown_appcontext + def shutdown_session(exception=None): + session.remove() + +def now_utc(): + return func.timezone('utc', func.now()) diff --git a/depicts/model.py b/depicts/model.py new file mode 100644 index 0000000..940a075 --- /dev/null +++ b/depicts/model.py @@ -0,0 +1,35 @@ +from sqlalchemy.ext.declarative import declarative_base +from .database import session +from sqlalchemy.schema import Column, ForeignKey +from sqlalchemy.types import Integer, String +from sqlalchemy.orm import column_property, relationship +from sqlalchemy.ext.associationproxy import association_proxy +from sqlalchemy.sql.expression import cast + +Base = declarative_base() +Base.query = session.query_property() + +class DepictsItem(Base): + __tablename__ = 'depicts' + item_id = Column(Integer, primary_key=True, autoincrement=False) + label = Column(String) + description = Column(String) + commons = Column(String) + count = Column(Integer) + qid = column_property('Q' + cast(item_id, String)) + db_alt_labels = relationship('DepictsItemAltLabel', + collection_class=set, + cascade='save-update, merge, delete, delete-orphan', + backref='item') + alt_labels = association_proxy('db_alt_labels', 'alt_label') + +class DepictsItemAltLabel(Base): + __tablename__ = 'depicts_alt_label' + item_id = Column(Integer, + ForeignKey('depicts.item_id'), + primary_key=True, + autoincrement=False) + alt_label = Column(String, primary_key=True) + + def __init__(self, alt_label): + self.alt_label = alt_label