Python sqlalchemy.ext.declarative.declarative_base() Examples

The following are code examples for showing how to use sqlalchemy.ext.declarative.declarative_base(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: swaggerit   Author: dutradda   File: factory.py    MIT License 6 votes vote down vote up
def make_sqlalchemy_redis_base(
            name='ModelSQLAlchemyRedisBase',
            bind=None, metadata=None,
            mapper=None, key_separator=None,
            metaclass=ModelSQLAlchemyRedisBaseMeta,
            cls=ModelSQLAlchemyRedisBaseSuper,
            constructor=ModelSQLAlchemyRedisBaseSuper.__init__):
        base = declarative_base(
            name=name, metaclass=metaclass,
            cls=cls, bind=bind, metadata=metadata,
            mapper=mapper, constructor=constructor)

        if key_separator is not None:
           base.__key_separator__ = key_separator

        return base 
Example 2
Project: openhatch   Author: campbe13   File: test_database.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def test_pickle_hack_for_sqla_05(self):
        import sqlalchemy as sa
        from celery.db import session
        prev_base = session.ResultModelBase
        prev_ver, sa.__version__ = sa.__version__, "0.5.0"
        prev_models = sys.modules.pop("celery.db.models", None)
        try:
            from sqlalchemy.ext.declarative import declarative_base
            session.ResultModelBase = declarative_base()
            from celery.db.dfd042c7 import PickleType as Type1
            from celery.db.models import PickleType as Type2
            self.assertIs(Type1, Type2)
        finally:
            sys.modules["celery.db.models"] = prev_models
            sa.__version__ = prev_ver
            session.ResultModelBase = prev_base 
Example 3
Project: Flask_Blog   Author: sugarguo   File: fixtures.py    GNU General Public License v3.0 6 votes vote down vote up
def _with_register_classes(cls, fn):
        cls_registry = cls.classes

        class FindFixtureDeclarative(DeclarativeMeta):
            def __init__(cls, classname, bases, dict_):
                cls_registry[classname] = cls
                return DeclarativeMeta.__init__(
                    cls, classname, bases, dict_)

        class DeclarativeBasic(object):
            __table_cls__ = schema.Table

        _DeclBase = declarative_base(metadata=cls.metadata,
                                     metaclass=FindFixtureDeclarative,
                                     cls=DeclarativeBasic)
        cls.DeclarativeBasic = _DeclBase
        fn()

        if cls.metadata.tables and cls.run_create_tables:
            cls.metadata.create_all(config.db) 
Example 4
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_sql.py    MIT License 6 votes vote down vote up
def test_temporary_table(self):
        test_data = "Hello, World!"
        expected = DataFrame({"spam": [test_data]})
        Base = declarative.declarative_base()

        class Temporary(Base):
            __tablename__ = "temp_test"
            __table_args__ = {"prefixes": ["TEMPORARY"]}
            id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
            spam = sqlalchemy.Column(sqlalchemy.Unicode(30), nullable=False)

        Session = sa_session.sessionmaker(bind=self.conn)
        session = Session()
        with session.transaction:
            conn = session.connection()
            Temporary.__table__.create(conn)
            session.add(Temporary(spam=test_data))
            session.flush()
            df = sql.read_sql_query(sql=sqlalchemy.select([Temporary.spam]), con=conn)

        tm.assert_frame_equal(df, expected) 
Example 5
Project: recruit   Author: Frank-qlu   File: test_sql.py    Apache License 2.0 6 votes vote down vote up
def test_temporary_table(self):
        test_data = u'Hello, World!'
        expected = DataFrame({'spam': [test_data]})
        Base = declarative.declarative_base()

        class Temporary(Base):
            __tablename__ = 'temp_test'
            __table_args__ = {'prefixes': ['TEMPORARY']}
            id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
            spam = sqlalchemy.Column(sqlalchemy.Unicode(30), nullable=False)

        Session = sa_session.sessionmaker(bind=self.conn)
        session = Session()
        with session.transaction:
            conn = session.connection()
            Temporary.__table__.create(conn)
            session.add(Temporary(spam=test_data))
            session.flush()
            df = sql.read_sql_query(
                sql=sqlalchemy.select([Temporary.spam]),
                con=conn,
            )

        tm.assert_frame_equal(df, expected) 
Example 6
Project: jbox   Author: jpush   File: fixtures.py    MIT License 6 votes vote down vote up
def _with_register_classes(cls, fn):
        cls_registry = cls.classes

        class FindFixtureDeclarative(DeclarativeMeta):
            def __init__(cls, classname, bases, dict_):
                cls_registry[classname] = cls
                return DeclarativeMeta.__init__(
                    cls, classname, bases, dict_)

        class DeclarativeBasic(object):
            __table_cls__ = schema.Table

        _DeclBase = declarative_base(metadata=cls.metadata,
                                     metaclass=FindFixtureDeclarative,
                                     cls=DeclarativeBasic)
        cls.DeclarativeBasic = _DeclBase
        fn()

        if cls.metadata.tables and cls.run_create_tables:
            cls.metadata.create_all(config.db) 
Example 7
Project: Mahjong-Solitaire   Author: MEASHY   File: fixtures.py    MIT License 6 votes vote down vote up
def _with_register_classes(cls, fn):
        cls_registry = cls.classes

        class FindFixtureDeclarative(DeclarativeMeta):
            def __init__(cls, classname, bases, dict_):
                cls_registry[classname] = cls
                return DeclarativeMeta.__init__(
                    cls, classname, bases, dict_)

        class DeclarativeBasic(object):
            __table_cls__ = schema.Table

        _DeclBase = declarative_base(metadata=cls.metadata,
                                     metaclass=FindFixtureDeclarative,
                                     cls=DeclarativeBasic)
        cls.DeclarativeBasic = _DeclBase
        fn()

        if cls.metadata.tables and cls.run_create_tables:
            cls.metadata.create_all(config.db) 
Example 8
Project: Mahjong-Solitaire   Author: MEASHY   File: fixtures.py    MIT License 6 votes vote down vote up
def _with_register_classes(cls, fn):
        cls_registry = cls.classes

        class FindFixtureDeclarative(DeclarativeMeta):
            def __init__(cls, classname, bases, dict_):
                cls_registry[classname] = cls
                return DeclarativeMeta.__init__(
                    cls, classname, bases, dict_)

        class DeclarativeBasic(object):
            __table_cls__ = schema.Table

        _DeclBase = declarative_base(metadata=cls.metadata,
                                     metaclass=FindFixtureDeclarative,
                                     cls=DeclarativeBasic)
        cls.DeclarativeBasic = _DeclBase
        fn()

        if cls.metadata.tables and cls.run_create_tables:
            cls.metadata.create_all(config.db) 
Example 9
Project: oa_qian   Author: sunqb   File: fixtures.py    Apache License 2.0 6 votes vote down vote up
def _with_register_classes(cls, fn):
        cls_registry = cls.classes

        class FindFixtureDeclarative(DeclarativeMeta):
            def __init__(cls, classname, bases, dict_):
                cls_registry[classname] = cls
                return DeclarativeMeta.__init__(
                    cls, classname, bases, dict_)

        class DeclarativeBasic(object):
            __table_cls__ = schema.Table

        _DeclBase = declarative_base(metadata=cls.metadata,
                                     metaclass=FindFixtureDeclarative,
                                     cls=DeclarativeBasic)
        cls.DeclarativeBasic = _DeclBase
        fn()

        if cls.metadata.tables and cls.run_create_tables:
            cls.metadata.create_all(config.db) 
Example 10
Project: FUTU_Stop_Loss   Author: BigtoC   File: test_sql.py    MIT License 6 votes vote down vote up
def test_temporary_table(self):
        test_data = u'Hello, World!'
        expected = DataFrame({'spam': [test_data]})
        Base = declarative.declarative_base()

        class Temporary(Base):
            __tablename__ = 'temp_test'
            __table_args__ = {'prefixes': ['TEMPORARY']}
            id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
            spam = sqlalchemy.Column(sqlalchemy.Unicode(30), nullable=False)

        Session = sa_session.sessionmaker(bind=self.conn)
        session = Session()
        with session.transaction:
            conn = session.connection()
            Temporary.__table__.create(conn)
            session.add(Temporary(spam=test_data))
            session.flush()
            df = sql.read_sql_query(
                sql=sqlalchemy.select([Temporary.spam]),
                con=conn,
            )

        tm.assert_frame_equal(df, expected) 
Example 11
Project: supportportal   Author: maubot   File: bot.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def start(self) -> None:
        self.client.add_dispatcher(MembershipEventDispatcher)

        self.config.load_and_update()
        self.load_simple_vars()

        loader = ConfigTemplateLoader(self.config)
        self.jinja_env = JinjaEnvironment(loader=loader)

        base = declarative_base(cls=BaseClass, bind=self.database)
        self.case = Case.copy(bind=self.database, rebase=base)
        self.control_event = ControlEvent.copy(bind=self.database, rebase=base)
        self.case_accept = CaseAccept.copy(bind=self.database, rebase=base)
        base.metadata.create_all()

        self.agents = set()

        await self.update_agents()

        self.room_members = {}
        self.cases = {}
        self.locks = defaultdict(lambda: asyncio.Lock()) 
Example 12
Project: django-sorcery   Author: shosca   File: sqlalchemy.py    MIT License 6 votes vote down vote up
def _make_declarative(self, model):
        """
        Creates the base class that the models should inherit from
        ----------------------------------------------------------
        model: class
            The base class for the declarative_base to be inherited from
        """
        base = declarative_base(
            cls=model, metadata=self.metadata, metaclass=type(str("BaseMeta"), (BaseMeta,), {"db": self})
        )

        # allow to customize things in custom base model
        if not hasattr(base, "query_class"):
            base.query_class = self.query_class
        if not hasattr(base, "query"):
            base.query = self.queryproperty()
        if not hasattr(base, "objects"):
            base.objects = self.queryproperty()

        return base 
Example 13
Project: analyzePF   Author: analyzeDFIR   File: fixtures.py    MIT License 6 votes vote down vote up
def _with_register_classes(cls, fn):
        cls_registry = cls.classes

        class FindFixtureDeclarative(DeclarativeMeta):
            def __init__(cls, classname, bases, dict_):
                cls_registry[classname] = cls
                return DeclarativeMeta.__init__(
                    cls, classname, bases, dict_)

        class DeclarativeBasic(object):
            __table_cls__ = schema.Table

        _DeclBase = declarative_base(metadata=cls.metadata,
                                     metaclass=FindFixtureDeclarative,
                                     cls=DeclarativeBasic)
        cls.DeclarativeBasic = _DeclBase
        fn()

        if cls.metadata.tables and cls.run_create_tables:
            cls.metadata.create_all(config.db) 
Example 14
Project: vnpy_crypto   Author: birforce   File: test_sql.py    MIT License 6 votes vote down vote up
def test_temporary_table(self):
        test_data = u'Hello, World!'
        expected = DataFrame({'spam': [test_data]})
        Base = declarative.declarative_base()

        class Temporary(Base):
            __tablename__ = 'temp_test'
            __table_args__ = {'prefixes': ['TEMPORARY']}
            id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
            spam = sqlalchemy.Column(sqlalchemy.Unicode(30), nullable=False)

        Session = sa_session.sessionmaker(bind=self.conn)
        session = Session()
        with session.transaction:
            conn = session.connection()
            Temporary.__table__.create(conn)
            session.add(Temporary(spam=test_data))
            session.flush()
            df = sql.read_sql_query(
                sql=sqlalchemy.select([Temporary.spam]),
                con=conn,
            )

        tm.assert_frame_equal(df, expected) 
Example 15
Project: xuemc   Author: skycucumber   File: fixtures.py    GNU General Public License v2.0 6 votes vote down vote up
def _with_register_classes(cls, fn):
        cls_registry = cls.classes

        class FindFixtureDeclarative(DeclarativeMeta):
            def __init__(cls, classname, bases, dict_):
                cls_registry[classname] = cls
                return DeclarativeMeta.__init__(
                    cls, classname, bases, dict_)

        class DeclarativeBasic(object):
            __table_cls__ = schema.Table

        _DeclBase = declarative_base(metadata=cls.metadata,
                                     metaclass=FindFixtureDeclarative,
                                     cls=DeclarativeBasic)
        cls.DeclarativeBasic = _DeclBase
        fn()

        if cls.metadata.tables and cls.run_create_tables:
            cls.metadata.create_all(config.db) 
Example 16
Project: hera_mc   Author: HERA-Team   File: test_db_check.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def gen_relation_models():

    Base = declarative_base()

    class RelationTestModel(Base):
        __tablename__ = "validity_check_test_2"
        id = Column(Integer, primary_key=True)

    class RelationTestModel2(Base):
        __tablename__ = "validity_check_test_3"
        id = Column(Integer, primary_key=True)

        test_relationship_id = Column(ForeignKey("validity_check_test_2.id"))
        test_relationship = relationship(RelationTestModel,
                                         primaryjoin=test_relationship_id
                                         == RelationTestModel.id)

    return Base, RelationTestModel, RelationTestModel2 
Example 17
Project: hera_mc   Author: HERA-Team   File: test_db_check.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def gen_declarative():

    Base = declarative_base()

    class DeclarativeTestModel(Base):
        __tablename__ = "validity_check_test_4"
        id = Column(Integer, primary_key=True)

        @declared_attr
        def _password(self):
            return Column('password', String(256), nullable=False)

        @hybrid_property
        def password(self):
            return self._password

    return Base, DeclarativeTestModel 
Example 18
Project: chihu   Author: yelongyu   File: fixtures.py    GNU General Public License v3.0 6 votes vote down vote up
def _with_register_classes(cls, fn):
        cls_registry = cls.classes

        class FindFixtureDeclarative(DeclarativeMeta):
            def __init__(cls, classname, bases, dict_):
                cls_registry[classname] = cls
                return DeclarativeMeta.__init__(
                    cls, classname, bases, dict_)

        class DeclarativeBasic(object):
            __table_cls__ = schema.Table

        _DeclBase = declarative_base(metadata=cls.metadata,
                                     metaclass=FindFixtureDeclarative,
                                     cls=DeclarativeBasic)
        cls.DeclarativeBasic = _DeclBase
        fn()

        if cls.metadata.tables and cls.run_create_tables:
            cls.metadata.create_all(config.db) 
Example 19
Project: safrs   Author: thomaxxl   File: test_codegen.py    MIT License 6 votes vote down vote up
def test_no_inflect(metadata):
    Table("simple_items", metadata, Column("id", INTEGER, primary_key=True))

    assert (
        generate_code(metadata, noinflect=True)
        == """\
# coding: utf-8
from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
metadata = Base.metadata


class SimpleItems(Base):
    __tablename__ = 'simple_items'

    id = Column(Integer, primary_key=True)
"""
    ) 
Example 20
Project: safrs   Author: thomaxxl   File: test_codegen.py    MIT License 6 votes vote down vote up
def test_table_kwargs(metadata):
    Table("simple_items", metadata, Column("id", INTEGER, primary_key=True), schema="testschema")

    assert (
        generate_code(metadata)
        == """\
# coding: utf-8
from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
metadata = Base.metadata


class SimpleItem(Base):
    __tablename__ = 'simple_items'
    __table_args__ = {'schema': 'testschema'}

    id = Column(Integer, primary_key=True)
"""
    ) 
Example 21
Project: safrs   Author: thomaxxl   File: test_codegen.py    MIT License 6 votes vote down vote up
def test_server_default_double_quotes(metadata):
    Table("simple", metadata, Column("id", INTEGER, primary_key=True, server_default=text('nextval("foo")')))

    assert (
        generate_code(metadata)
        == """\
# coding: utf-8
from sqlalchemy import Column, Integer, text
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
metadata = Base.metadata


class Simple(Base):
    __tablename__ = 'simple'

    id = Column(Integer, primary_key=True, server_default=text("nextval(\\"foo\\")"))
"""
    ) 
Example 22
Project: safrs   Author: thomaxxl   File: test_codegen.py    MIT License 6 votes vote down vote up
def test_pascal(metadata):
    Table("CustomerAPIPreference", metadata, Column("id", INTEGER, primary_key=True))

    assert (
        generate_code(metadata)
        == """\
# coding: utf-8
from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
metadata = Base.metadata


class CustomerAPIPreference(Base):
    __tablename__ = 'CustomerAPIPreference'

    id = Column(Integer, primary_key=True)
"""
    ) 
Example 23
Project: safrs   Author: thomaxxl   File: test_codegen.py    MIT License 6 votes vote down vote up
def test_underscore(metadata):
    Table("customer_api_preference", metadata, Column("id", INTEGER, primary_key=True))

    assert (
        generate_code(metadata)
        == """\
# coding: utf-8
from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
metadata = Base.metadata


class CustomerApiPreference(Base):
    __tablename__ = 'customer_api_preference'

    id = Column(Integer, primary_key=True)
"""
    ) 
Example 24
Project: flasky   Author: RoseOu   File: fixtures.py    MIT License 5 votes vote down vote up
def _with_register_classes(cls, fn):
        cls_registry = cls.classes

        class FindFixtureDeclarative(DeclarativeMeta):
            def __init__(cls, classname, bases, dict_):
                cls_registry[classname] = cls
                return DeclarativeMeta.__init__(
                    cls, classname, bases, dict_)

        class DeclarativeBasic(object):
            __table_cls__ = schema.Table

        _DeclBase = declarative_base(metadata=cls.metadata,
                                     metaclass=FindFixtureDeclarative,
                                     cls=DeclarativeBasic)
        cls.DeclarativeBasic = _DeclBase
        fn()

        if cls.metadata.tables and cls.run_create_tables:
            cls.metadata.create_all(config.db) 
Example 25
Project: flasky   Author: RoseOu   File: api.py    MIT License 5 votes vote down vote up
def as_declarative(**kw):
    """
    Class decorator for :func:`.declarative_base`.

    Provides a syntactical shortcut to the ``cls`` argument
    sent to :func:`.declarative_base`, allowing the base class
    to be converted in-place to a "declarative" base::

        from sqlalchemy.ext.declarative import as_declarative

        @as_declarative()
        class Base(object):
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()
            id = Column(Integer, primary_key=True)

        class MyMappedClass(Base):
            # ...

    All keyword arguments passed to :func:`.as_declarative` are passed
    along to :func:`.declarative_base`.

    .. versionadded:: 0.8.3

    .. seealso::

        :func:`.declarative_base`

    """
    def decorate(cls):
        kw['cls'] = cls
        kw['name'] = cls.__name__
        return declarative_base(**kw)

    return decorate 
Example 26
Project: flasky   Author: RoseOu   File: __init__.py    MIT License 5 votes vote down vote up
def make_declarative_base(self):
        """Creates the declarative base."""
        base = declarative_base(cls=Model, name='Model',
                                metaclass=_BoundDeclarativeMeta)
        base.query = _QueryProperty(self)
        return base 
Example 27
Project: telethon-session-sqlalchemy   Author: tulir   File: sqlalchemy.py    MIT License 5 votes vote down vote up
def __init__(self, engine: Union[sql.engine.Engine, str] = None,
                 session: Optional[Union[orm.Session, scoped_session, bool]] = None,
                 table_prefix: str = "", table_base: Optional[declarative_base] = None,
                 manage_tables: bool = True) -> None:
        if isinstance(engine, str):
            engine = sql.create_engine(engine)

        self.db_engine = engine
        if session is None:
            db_factory = orm.sessionmaker(bind=self.db_engine)
            self.db = orm.scoping.scoped_session(db_factory)
        elif not session:
            self.db = None
        else:
            self.db = session

        table_base = table_base or declarative_base()
        (self.Version, self.Session, self.Entity,
         self.SentFile, self.UpdateState) = self.create_table_classes(self.db, table_prefix,
                                                                      table_base)
        self.alchemy_session_class = AlchemySession
        if not self.db:
            # Implicit core mode if there's no ORM session.
            self.core_mode = True

        if manage_tables:
            if not self.db:
                raise ValueError("Can't manage tables without an ORM session.")
            table_base.metadata.bind = self.db_engine
            if not self.db_engine.dialect.has_table(self.db_engine,
                                                    self.Version.__tablename__):
                table_base.metadata.create_all()
                self.db.add(self.Version(version=LATEST_VERSION))
                self.db.commit()
            else:
                self.check_and_upgrade_database() 
Example 28
Project: Flask_Blog   Author: sugarguo   File: api.py    GNU General Public License v3.0 5 votes vote down vote up
def as_declarative(**kw):
    """
    Class decorator for :func:`.declarative_base`.

    Provides a syntactical shortcut to the ``cls`` argument
    sent to :func:`.declarative_base`, allowing the base class
    to be converted in-place to a "declarative" base::

        from sqlalchemy.ext.declarative import as_declarative

        @as_declarative()
        class Base(object):
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()
            id = Column(Integer, primary_key=True)

        class MyMappedClass(Base):
            # ...

    All keyword arguments passed to :func:`.as_declarative` are passed
    along to :func:`.declarative_base`.

    .. versionadded:: 0.8.3

    .. seealso::

        :func:`.declarative_base`

    """
    def decorate(cls):
        kw['cls'] = cls
        kw['name'] = cls.__name__
        return declarative_base(**kw)

    return decorate 
Example 29
Project: Flask_Blog   Author: sugarguo   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def make_declarative_base(self, metadata=None):
        """Creates the declarative base."""
        base = declarative_base(cls=Model, name='Model',
                                metadata=metadata,
                                metaclass=_BoundDeclarativeMeta)
        base.query = _QueryProperty(self)
        return base 
Example 30
Project: monitor-python   Author: thznote   File: async_orm.py    MIT License 5 votes vote down vote up
def __call__(self):
        if not self._instance:
            self._instance = sa_declarative_base()
        return self._instance 
Example 31
Project: jbox   Author: jpush   File: api.py    MIT License 5 votes vote down vote up
def as_declarative(**kw):
    """
    Class decorator for :func:`.declarative_base`.

    Provides a syntactical shortcut to the ``cls`` argument
    sent to :func:`.declarative_base`, allowing the base class
    to be converted in-place to a "declarative" base::

        from sqlalchemy.ext.declarative import as_declarative

        @as_declarative()
        class Base(object):
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()
            id = Column(Integer, primary_key=True)

        class MyMappedClass(Base):
            # ...

    All keyword arguments passed to :func:`.as_declarative` are passed
    along to :func:`.declarative_base`.

    .. versionadded:: 0.8.3

    .. seealso::

        :func:`.declarative_base`

    """
    def decorate(cls):
        kw['cls'] = cls
        kw['name'] = cls.__name__
        return declarative_base(**kw)

    return decorate 
Example 32
Project: jbox   Author: jpush   File: __init__.py    MIT License 5 votes vote down vote up
def make_declarative_base(self, metadata=None):
        """Creates the declarative base."""
        base = declarative_base(cls=Model, name='Model',
                                metadata=metadata,
                                metaclass=_BoundDeclarativeMeta)
        base.query = _QueryProperty(self)
        return base 
Example 33
Project: QPYPI   Author: qpython-android   File: sqla.py    Apache License 2.0 5 votes vote down vote up
def register(cls, name):
        if name not in cls.databases:
            cls.databases[name] = declarative_base(cls=_Base)
        return cls.databases[name] 
Example 34
Project: json2db   Author: mrzhangboss   File: ModelFactory.py    MIT License 5 votes vote down vote up
def __init__(self, *args, model: RootModel,
                 factory: CommonModelFactory,
                 **kwargs):
        self.model = model
        self._model = {}
        self.factory = factory
        self._db_models = None
        self.Base = declarative_base()
        self.pk = self.factory.primary_key
        self.type_helper = self.factory.type_helper 
Example 35
Project: cellphonedb   Author: Teichlab   File: Database.py    MIT License 5 votes vote down vote up
def __init__(self, engine):
        self.engine = engine
        self.established_session = None
        self.base = declarative_base()
        self.base_model = None 
Example 36
Project: Mahjong-Solitaire   Author: MEASHY   File: test_types.py    MIT License 5 votes vote down vote up
def test_eval_none_flag_orm(self):
        from sqlalchemy.ext.declarative import declarative_base
        from sqlalchemy.orm import Session

        Base = declarative_base()

        class Data(Base):
            __table__ = self.tables.data_table

        s = Session(testing.db)

        d1 = Data(name='d1', data=None, nulldata=None)
        s.add(d1)
        s.commit()

        s.bulk_insert_mappings(
            Data, [{"name": "d2", "data": None, "nulldata": None}]
        )
        eq_(
            s.query(
                cast(self.tables.data_table.c.data, String(convert_unicode="force")),
                cast(self.tables.data_table.c.nulldata, String)
            ).filter(self.tables.data_table.c.name == 'd1').first(),
            ("null", None)
        )
        eq_(
            s.query(
                cast(self.tables.data_table.c.data, String(convert_unicode="force")),
                cast(self.tables.data_table.c.nulldata, String)
            ).filter(self.tables.data_table.c.name == 'd2').first(),
            ("null", None)
        ) 
Example 37
Project: Mahjong-Solitaire   Author: MEASHY   File: api.py    MIT License 5 votes vote down vote up
def as_declarative(**kw):
    """
    Class decorator for :func:`.declarative_base`.

    Provides a syntactical shortcut to the ``cls`` argument
    sent to :func:`.declarative_base`, allowing the base class
    to be converted in-place to a "declarative" base::

        from sqlalchemy.ext.declarative import as_declarative

        @as_declarative()
        class Base(object):
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()
            id = Column(Integer, primary_key=True)

        class MyMappedClass(Base):
            # ...

    All keyword arguments passed to :func:`.as_declarative` are passed
    along to :func:`.declarative_base`.

    .. versionadded:: 0.8.3

    .. seealso::

        :func:`.declarative_base`

    """
    def decorate(cls):
        kw['cls'] = cls
        kw['name'] = cls.__name__
        return declarative_base(**kw)

    return decorate 
Example 38
Project: Mahjong-Solitaire   Author: MEASHY   File: __init__.py    MIT License 5 votes vote down vote up
def make_declarative_base(self, metadata=None):
        """Creates the declarative base."""
        base = declarative_base(cls=Model, name='Model',
                                metadata=metadata,
                                metaclass=_BoundDeclarativeMeta)
        base.query = _QueryProperty(self)
        return base 
Example 39
Project: Mahjong-Solitaire   Author: MEASHY   File: api.py    MIT License 5 votes vote down vote up
def as_declarative(**kw):
    """
    Class decorator for :func:`.declarative_base`.

    Provides a syntactical shortcut to the ``cls`` argument
    sent to :func:`.declarative_base`, allowing the base class
    to be converted in-place to a "declarative" base::

        from sqlalchemy.ext.declarative import as_declarative

        @as_declarative()
        class Base(object):
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()
            id = Column(Integer, primary_key=True)

        class MyMappedClass(Base):
            # ...

    All keyword arguments passed to :func:`.as_declarative` are passed
    along to :func:`.declarative_base`.

    .. versionadded:: 0.8.3

    .. seealso::

        :func:`.declarative_base`

    """
    def decorate(cls):
        kw['cls'] = cls
        kw['name'] = cls.__name__
        return declarative_base(**kw)

    return decorate 
Example 40
Project: Mahjong-Solitaire   Author: MEASHY   File: __init__.py    MIT License 5 votes vote down vote up
def make_declarative_base(self, metadata=None):
        """Creates the declarative base."""
        base = declarative_base(cls=Model, name='Model',
                                metadata=metadata,
                                metaclass=_BoundDeclarativeMeta)
        base.query = _QueryProperty(self)
        return base 
Example 41
Project: oa_qian   Author: sunqb   File: api.py    Apache License 2.0 5 votes vote down vote up
def as_declarative(**kw):
    """
    Class decorator for :func:`.declarative_base`.

    Provides a syntactical shortcut to the ``cls`` argument
    sent to :func:`.declarative_base`, allowing the base class
    to be converted in-place to a "declarative" base::

        from sqlalchemy.ext.declarative import as_declarative

        @as_declarative()
        class Base(object):
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()
            id = Column(Integer, primary_key=True)

        class MyMappedClass(Base):
            # ...

    All keyword arguments passed to :func:`.as_declarative` are passed
    along to :func:`.declarative_base`.

    .. versionadded:: 0.8.3

    .. seealso::

        :func:`.declarative_base`

    """
    def decorate(cls):
        kw['cls'] = cls
        kw['name'] = cls.__name__
        return declarative_base(**kw)

    return decorate 
Example 42
Project: oa_qian   Author: sunqb   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def make_declarative_base(self):
        """Creates the declarative base."""
        base = declarative_base(cls=Model, name='Model',
                                metaclass=_BoundDeclarativeMeta)
        base.query = _QueryProperty(self)
        return base 
Example 43
Project: ProfesorDumbledoreBot   Author: pikaping   File: db.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_declarative_base():
    global __BASE

    if __BASE is None:
        __BASE = declarative_base()

    return __BASE 
Example 44
Project: versionalchemy   Author: NerdWalletOSS   File: test_user_table.py    MIT License 5 votes vote down vote up
def test_insert_into_unregistered_table_fails(self):
        Base_ = declarative_base()

        class UnregisteredTable(VAModelMixin, Base_):
            __tablename__ = 'unregistered_table'
            pid = Column(Integer, primary_key=True)
            col1 = Column(Integer)
        Base_.metadata.create_all(self.engine)
        self.session.add(UnregisteredTable(pid=1, col1=5))
        with self.assertRaises(LogTableCreationError):
            self.session.commit() 
Example 45
Project: fever-naacl-2018   Author: sheffieldnlp   File: session.py    Apache License 2.0 5 votes vote down vote up
def get_session(engine):
    Base = declarative_base()
    Session = sessionmaker(bind=engine)

    session =  Session()
    if not engine.dialect.has_table(engine, Page.__tablename__):
        Page.__table__.create(bind=engine,checkfirst=True)
    return session 
Example 46
Project: memologe   Author: sandkastenboys   File: objects.py    MIT License 5 votes vote down vote up
def __init__(self):

        if config["sqlite"] == "True":
            self.engine = create_engine("sqlite:///" + os.path.join("./", "new_db"))
        else:  # Mysql
            self.engine = create_engine(config["SQLALCHEMY_DATABASE_URI"])

        self.Session: sessionmaker = sessionmaker(bind=self.engine)
        self.Base: DeclarativeMeta = declarative_base()

        self.session = self.Session()
        self.connection = self.session.connection() 
Example 47
Project: analyzePF   Author: analyzeDFIR   File: test_types.py    MIT License 5 votes vote down vote up
def test_eval_none_flag_orm(self):
        from sqlalchemy.ext.declarative import declarative_base
        from sqlalchemy.orm import Session

        Base = declarative_base()

        class Data(Base):
            __table__ = self.tables.data_table

        s = Session(testing.db)

        d1 = Data(name='d1', data=None, nulldata=None)
        s.add(d1)
        s.commit()

        s.bulk_insert_mappings(
            Data, [{"name": "d2", "data": None, "nulldata": None}]
        )
        eq_(
            s.query(
                cast(self.tables.data_table.c.data, String(convert_unicode="force")),
                cast(self.tables.data_table.c.nulldata, String)
            ).filter(self.tables.data_table.c.name == 'd1').first(),
            ("null", None)
        )
        eq_(
            s.query(
                cast(self.tables.data_table.c.data, String(convert_unicode="force")),
                cast(self.tables.data_table.c.nulldata, String)
            ).filter(self.tables.data_table.c.name == 'd2').first(),
            ("null", None)
        ) 
Example 48
Project: analyzePF   Author: analyzeDFIR   File: api.py    MIT License 5 votes vote down vote up
def as_declarative(**kw):
    """
    Class decorator for :func:`.declarative_base`.

    Provides a syntactical shortcut to the ``cls`` argument
    sent to :func:`.declarative_base`, allowing the base class
    to be converted in-place to a "declarative" base::

        from sqlalchemy.ext.declarative import as_declarative

        @as_declarative()
        class Base(object):
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()
            id = Column(Integer, primary_key=True)

        class MyMappedClass(Base):
            # ...

    All keyword arguments passed to :func:`.as_declarative` are passed
    along to :func:`.declarative_base`.

    .. versionadded:: 0.8.3

    .. seealso::

        :func:`.declarative_base`

    """
    def decorate(cls):
        kw['cls'] = cls
        kw['name'] = cls.__name__
        return declarative_base(**kw)

    return decorate 
Example 49
Project: pybigquery   Author: mxmzdlv   File: test_sqlalchemy_bigquery.py    MIT License 5 votes vote down vote up
def test_create_table(engine):
    meta = MetaData()
    table = Table(
        'test_pybigquery.test_table_create', meta,
        Column('integer_c', sqlalchemy.Integer, doc="column description"),
        Column('float_c', sqlalchemy.Float),
        Column('decimal_c', sqlalchemy.DECIMAL),
        Column('string_c', sqlalchemy.String),
        Column('text_c', sqlalchemy.Text),
        Column('boolean_c', sqlalchemy.Boolean),
        Column('timestamp_c', sqlalchemy.TIMESTAMP),
        Column('datetime_c', sqlalchemy.DATETIME),
        Column('date_c', sqlalchemy.DATE),
        Column('time_c', sqlalchemy.TIME),
        Column('binary_c', sqlalchemy.BINARY),
        bigquery_description="test table description",
        bigquery_friendly_name="test table name"
    )
    meta.create_all(engine)
    meta.drop_all(engine)

    # Test creating tables with declarative_base
    Base = declarative_base()

    class TableTest(Base):
        __tablename__ = 'test_pybigquery.test_table_create2'
        integer_c = Column(sqlalchemy.Integer, primary_key=True)
        float_c = Column(sqlalchemy.Float)

    Base.metadata.create_all(engine)
    Base.metadata.drop_all(engine) 
Example 50
Project: xuemc   Author: skycucumber   File: api.py    GNU General Public License v2.0 5 votes vote down vote up
def as_declarative(**kw):
    """
    Class decorator for :func:`.declarative_base`.

    Provides a syntactical shortcut to the ``cls`` argument
    sent to :func:`.declarative_base`, allowing the base class
    to be converted in-place to a "declarative" base::

        from sqlalchemy.ext.declarative import as_declarative

        @as_declarative()
        class Base(object):
            @declared_attr
            def __tablename__(cls):
                return cls.__name__.lower()
            id = Column(Integer, primary_key=True)

        class MyMappedClass(Base):
            # ...

    All keyword arguments passed to :func:`.as_declarative` are passed
    along to :func:`.declarative_base`.

    .. versionadded:: 0.8.3

    .. seealso::

        :func:`.declarative_base`

    """
    def decorate(cls):
        kw['cls'] = cls
        kw['name'] = cls.__name__
        return declarative_base(**kw)

    return decorate