def declarative_base(cls=None, bind_key=None, **kw): return _declarative_base(cls=type( 'ModelCRUD', (cls, ModelCRUD) if cls else (ModelCRUD, ), {'__bind_key__': bind_key or DEFAULT_BIND_KEY}, ), metaclass=BoundDeclarativeMeta, **kw)
def declarative_base(cls=None, bind_key=None, **kw): return _declarative_base( cls=type( 'ModelCRUD', (cls, ModelCRUD) if cls else (ModelCRUD, ), {'__bind_key__': bind_key or DEFAULT_BIND_KEY}, ), metaclass=BoundDeclarativeMeta, **kw )
def declarative_base(): """Creates a new declarative base class. Wraps SQLAlchemy ``declarative_base`` by adding two new fields to the returned base class: a ``session`` property and a ``query`` property handy to execute queries.""" Session = create_session() Base = _declarative_base() Base.session = Session Base.query = Session.query_property() return Base
def declarative_base(cls=ModelBase, metadata=None, metaclass=ModelMeta, **kargs): """Function that converts a normal class into a SQLAlchemy declarative base class. Args: cls (type): A type to use as the base for the generated declarative base class. May be a class or tuple of classes. Defaults to :class:`ModelBase`. metadata (MetaData, optional): An optional MetaData instance. All Table objects implicitly declared by subclasses of the base will share this MetaData. A MetaData instance will be created if none is provided. If not passed in, `cls.metadata` will be used if set. Defaults to ``None``. metaclass (DeclarativeMeta, optional): A metaclass or ``__metaclass__`` compatible callable to use as the meta type of the generated declarative base class. If not passed in, `cls.metaclass` will be used if set. Defaults to :class:`ModelMeta`. Keyword Args: All other keyword arguments are passed to ``sqlalchemy.ext.declarative.declarative_base``. Returns: class: Declarative base class """ kargs['cls'] = cls kargs.setdefault('name', cls.__name__) if hasattr(cls, '__init__'): kargs.setdefault('constructor', cls.__init__) if metadata: kargs['metadata'] = metadata if metaclass: kargs['metaclass'] = metaclass Base = _declarative_base(**kargs) if metaclass: Base.metaclass = metaclass return Base
def declarative_base(): if not declarative_base._instance: declarative_base._instance = _declarative_base() return declarative_base._instance
from sqlalchemy import Float as _Float from sqlalchemy import Date as _Date from sqlalchemy import Boolean as _Boolean from sqlalchemy.orm import relationship as _relationship from sqlalchemy.ext.declarative import declarative_base as _declarative_base # MyVariant functions import myvariant # Flags from .ref import PopFlag as _PopFlag __all__ = ["SNP", "Phenotype", "PhenoCats", "Platform", "Population"] Base = _declarative_base() """The SQLAlchemy Base for the database.""" ############################################################################### # Association Tables # ############################################################################### snp_pheno_assoc = _Table( 'snp_pheno_association', Base.metadata, _Column('snp_id', _BigInteger, _ForeignKey('snps.id')), _Column('pheno_id', _Integer, _ForeignKey('pheno_cats.id'))) study_pheno_assoc = _Table( 'study_pheno_association', Base.metadata, _Column('study_id', _Integer, _ForeignKey('studies.id')), _Column('pheno_id', _Integer, _ForeignKey('pheno_cats.id')))
def save(self): DBSession.add(self) DBSession.flush() @classmethod def query(cls): return DBSession.query(cls) @classmethod def all(cls): return cls.query().all() # XXX: Newer versions of sqlalchemy have a decorator variant 'as_declarative' Base = _declarative_base(cls=Base) # XXX: not the best of names def init_session(engine, create=False): DBSession.configure(bind=engine) if create: Base.metadata.create_all(engine) else: Base.metadata.bind = engine # Upper bounds from RFC 5280 _UB_CN_LEN = 64 _UB_OU_LEN = 64
from __future__ import unicode_literals, print_function __all__=["DeclarativeBase"] from common import * from sqlalchemy import MetaData as _MetaData from sqlalchemy.ext.declarative import declarative_base as _declarative_base #DeclarativeBase = _declarative_base(metadata=_MetaData()) DeclarativeBase = _declarative_base() from sqlalchemy import Column, String, Integer, DateTime, Boolean class _XYZ(DeclarativeBase): debug("XYZ start") __tablename__ = "XYZ" __table_args__ = {'sqlite_autoincrement': True} c1 = Column(Integer, primary_key=True) c2 = Column(String()) c3 = Column(DateTime) c4 = Column(Boolean) @classmethod def dropTable(cls): try: table = DeclarativeBase.metadata.tables[cls.__tablename__] engine = SqlAlchemyEngine().getEngine() table.drop(engine, checkfirst=True) except: pass @classmethod def createTable(cls):
from config import * from sqlalchemy import MetaData as _MetaData from sqlalchemy.ext.declarative import declarative_base as _declarative_base DeclarativeBase = _declarative_base(metadata=_MetaData())
''' engine = _create_engine(conf.get('DB', 'URI'), convert_unicode=True, pool_recycle=pool_recycle) session = _scoped_session( _sessionmaker(autocommit=autocommit, autoflush=autoflush, bind=engine)) # The following dumb assignments on session are just to trick pylint # so that it doesn't report "missing attribute" every time the session is used session.add = session.add session.commit = session.commit session.delete = session.delete session.flush = session.flush session.get_bind = session.get_bind session.query = session.query session.refresh = session.refresh session.rollback = session.rollback return session BASE = _declarative_base() from arao_secret.db import model def create_tables(db_session): ''' Create tables into existent DataBase. ''' BASE.metadata.create_all(db_session.bind)
# Released under terms of the MIT/X/Expat Licence. See COPYING for details. import warnings as _warnings from ibid.db.types import TypeDecorator, Integer, DateTime, Boolean, \ IbidUnicode, IbidUnicodeText from sqlalchemy import Table, Column, ForeignKey, Index, UniqueConstraint, \ PassiveDefault, or_, and_, MetaData as _MetaData from sqlalchemy.orm import eagerload, relation, synonym from sqlalchemy.sql import func from sqlalchemy.ext.declarative import declarative_base as _declarative_base from sqlalchemy.exceptions import IntegrityError, SADeprecationWarning metadata = _MetaData() Base = _declarative_base(metadata=metadata) from ibid.db.versioned_schema import VersionedSchema, SchemaVersionException, \ schema_version_check, upgrade_schemas # We use SQLAlchemy 0.4 compatible .save_or_update() functions _warnings.filterwarnings('ignore', 'Use session.add\(\)', SADeprecationWarning) def get_regexp_op(session): "Return a regexp operator" if session.bind.engine.name in ('postgres', 'postgresql'): return lambda x, y: x.op('~')(y) else: return lambda x, y: x.op('REGEXP')(y)
try: bind_key = d.pop('__bind_key__', None) if not bind_key: for base in bases: if getattr(base, '__bind_key__', None): bind_key = getattr(base, '__bind_key__') break else: bind_key = DEFAULT_BIND_KEY self.__table__.info['bind_key'] = bind_key except AttributeError: pass def declarative_base(cls=None, bind_key=None, **kw): return _declarative_base( cls=type( 'ModelCRUD', (cls, ModelCRUD) if cls else (ModelCRUD, ), {'__bind_key__': bind_key or DEFAULT_BIND_KEY}, ), metaclass=BoundDeclarativeMeta, **kw ) BaseModel = _declarative_base(cls=ModelCRUD, metaclass=BoundDeclarativeMeta)
# Released under terms of the MIT/X/Expat Licence. See COPYING for details. import warnings as _warnings from ibid.db.types import TypeDecorator, Integer, DateTime, Boolean, \ IbidUnicode, IbidUnicodeText from sqlalchemy import Table, Column, ForeignKey, Index, UniqueConstraint, \ PassiveDefault, or_, and_, MetaData as _MetaData from sqlalchemy.orm import eagerload, relation, synonym from sqlalchemy.sql import func from sqlalchemy.ext.declarative import declarative_base as _declarative_base from sqlalchemy.exceptions import IntegrityError, SADeprecationWarning metadata = _MetaData() Base = _declarative_base(metadata=metadata) from ibid.db.versioned_schema import VersionedSchema, SchemaVersionException, \ schema_version_check, upgrade_schemas # We use SQLAlchemy 0.4 compatible .save_or_update() functions _warnings.filterwarnings('ignore', 'Use session.add\(\)', SADeprecationWarning) def get_regexp_op(session): "Return a regexp operator" if session.bind.engine.name in ('postgres', 'postgresql'): return lambda x, y: x.op('~')(y) else: return lambda x, y: x.op('REGEXP')(y) # vi: set et sta sw=4 ts=4:
def __init__(self, name, bases, d): DeclarativeMeta.__init__(self, name, bases, d) try: bind_key = d.pop('__bind_key__', None) if not bind_key: for base in bases: if getattr(base, '__bind_key__', None): bind_key = getattr(base, '__bind_key__') break else: bind_key = DEFAULT_BIND_KEY self.__table__.info['bind_key'] = bind_key except AttributeError: pass def declarative_base(cls=None, bind_key=None, **kw): return _declarative_base(cls=type( 'ModelCRUD', (cls, ModelCRUD) if cls else (ModelCRUD, ), {'__bind_key__': bind_key or DEFAULT_BIND_KEY}, ), metaclass=BoundDeclarativeMeta, **kw) BaseModel = _declarative_base(cls=ModelCRUD, metaclass=BoundDeclarativeMeta)