Python sqlalchemy.ext.declarative.declarative_base() Examples

The following are 30 code examples for showing how to use sqlalchemy.ext.declarative.declarative_base(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module sqlalchemy.ext.declarative , or try the search function .

Example 1
Project: recruit   Author: Frank-qlu   File: test_sql.py    License: 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 2
Project: jbox   Author: jpush   File: fixtures.py    License: 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 3
Project: vnpy_crypto   Author: birforce   File: test_sql.py    License: 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 4
Project: airflow   Author: apache   File: 8f966b9c467a_set_conn_type_as_non_nullable.py    License: Apache License 2.0 6 votes vote down vote up
def upgrade():
    """Apply Set conn_type as non-nullable"""

    Base = declarative_base()

    class Connection(Base):
        __tablename__ = "connection"

        id = sa.Column(sa.Integer(), primary_key=True)
        conn_id = sa.Column(sa.String(250))
        conn_type = sa.Column(sa.String(500))

    # Generate run type for existing records
    connection = op.get_bind()
    sessionmaker = sa.orm.sessionmaker()
    session = sessionmaker(bind=connection)

    # imap_default was missing it's type, let's fix that up
    session.query(Connection).filter_by(conn_id="imap_default", conn_type=None).update(
        {Connection.conn_type: "imap"}, synchronize_session=False
    )
    session.commit()

    with op.batch_alter_table("connection", schema=None) as batch_op:
        batch_op.alter_column("conn_type", existing_type=sa.VARCHAR(length=500), nullable=False) 
Example 5
Project: safrs   Author: thomaxxl   File: test_codegen.py    License: GNU General Public License v3.0 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 6
Project: safrs   Author: thomaxxl   File: test_codegen.py    License: GNU General Public License v3.0 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 7
Project: safrs   Author: thomaxxl   File: test_codegen.py    License: GNU General Public License v3.0 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 8
Project: safrs   Author: thomaxxl   File: test_codegen.py    License: GNU General Public License v3.0 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 9
Project: safrs   Author: thomaxxl   File: test_codegen.py    License: GNU General Public License v3.0 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 10
Project: safrs   Author: thomaxxl   File: test_codegen.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_pascal_multiple_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 11
Project: safrs   Author: thomaxxl   File: test_codegen.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_metadata_column(metadata):
    Table("simple", metadata, Column("id", INTEGER, primary_key=True), Column("metadata", VARCHAR))

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

Base = declarative_base()
metadata = Base.metadata


class Simple(Base):
    __tablename__ = 'simple'

    id = Column(Integer, primary_key=True)
    metadata_ = Column('metadata', String)
"""
    ) 
Example 12
Project: safrs   Author: thomaxxl   File: test_codegen.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_mysql_timestamp(metadata):
    Table("simple", metadata, Column("id", INTEGER, primary_key=True), Column("timestamp", mysql.TIMESTAMP))

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

Base = declarative_base()
metadata = Base.metadata


class Simple(Base):
    __tablename__ = 'simple'

    id = Column(Integer, primary_key=True)
    timestamp = Column(TIMESTAMP)
"""
    ) 
Example 13
Project: openmoves   Author: bwaldvogel   File: 004.py    License: MIT License 6 votes vote down vote up
def calculateAverageTemperatures():
    Base = declarative_base()
    Session = sessionmaker(bind=op.get_bind())

    class Sample(Base):
        __tablename__ = 'sample'
        id = sa.Column(sa.Integer, name="id", primary_key=True)
        moveId = sa.Column(sa.Integer, name="move_id", nullable=False)
        temperature = sa.Column(sa.Float, name='temperature')

    class Move(Base):
        __tablename__ = 'move'
        id = sa.Column(sa.Integer, name="id", primary_key=True)
        temperature_avg = sa.Column(sa.Float, name='temperature_avg')

    session = Session()
    averageTemperatures = dict(session.query(Sample.moveId, func.avg(Sample.temperature)).group_by(Sample.moveId).filter(Sample.temperature > 0).all())

    for move in session.query(Move):
        if move.id in averageTemperatures:
            move.temperature_avg = averageTemperatures[move.id]

    session.commit() 
Example 14
Project: nameko-sqlalchemy   Author: nameko   File: pytest_fixtures.py    License: Apache License 2.0 6 votes vote down vote up
def model_base():
    """Override this fixture to return declarative base of your model

    http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/api.html

    .. code-block:: python

        from sqlalchemy.ext.declarative import declarative_base

        class Base(object):
            pass

        DeclarativeBase = declarative_base(cls=Base)

        class User(DeclarativeBase):
            __tablename__ = "users"

            id = Column(Integer, primary_key=True)

        @pytest.fixture(scope='session')
        def model_base():
            return DeclarativeBase
    """
    raise NotImplementedError("Fixture `model_base` has to be overwritten") 
Example 15
Project: timecop   Author: BBVA   File: BBDD.py    License: Apache License 2.0 6 votes vote down vote up
def init_database():

    Base = declarative_base()

    class Model(Base):
        __tablename__ = 'models'
        TS_name = Column(String(250), nullable=False,primary_key=True)
        TS_winner_name = Column(String(250), nullable=False)
        TS_model = Column(LargeBinary())
        TS_model_params = Column(String(250))
        TS_metric = Column(Numeric)
        TS_update = Column('TS_update', DATETIME, index=False, nullable=False,primary_key=True,default=datetime.datetime.utcnow)

    class TS(Base):
        __tablename__ = 'timeseries'
        TS_name = Column(String(250), nullable=False,primary_key=True)
        TS_data = Column(Text())
        TS_update = Column('TS_update', DATETIME, index=False, nullable=False,primary_key=True,default=datetime.datetime.utcnow)


    DB_NAME = 'sqlite:///Timecop_modelsv1.db'
    engine = create_engine(DB_NAME)
    #self.__db.echo = True
    Base.metadata.create_all(engine) 
Example 16
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 17
Project: Fluid-Designer   Author: Microvellum   File: fixtures.py    License: 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 18
Project: schematizer   Author: Yelp   File: database.py    License: Apache License 2.0 6 votes vote down vote up
def _get_declarative_base():
    try:
        if FORCE_AVOID_INTERNAL_PACKAGES:
            # TODO(DATAPIPE-1506|abrar): Currently we have
            # force_avoid_internal_packages as a means of simulating an absence
            # of a yelp's internal package. And all references
            # of force_avoid_internal_packages have to be removed from
            # schematizer after we have completely ready for open source.
            raise ImportError
        from yelp_conn.session import declarative_base
    except ImportError:
        from sqlalchemy.ext.declarative import declarative_base
    return declarative_base()


# The common declarative base used by every data model. 
Example 19
Project: sqlalchemy-jsonapi   Author: ColtonProvias   File: test_serialize.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        """Configure sqlalchemy and session."""
        self.engine = create_engine('sqlite://')
        Session = sessionmaker(bind=self.engine)
        self.session = Session()
        self.Base = declarative_base()

        class User(self.Base):
            __tablename__ = 'users'
            id = Column(Integer, primary_key=True)
            first_name = Column(String(50), nullable=False)
            age = Column(Integer, nullable=False)
            username = Column(String(50), unique=True, nullable=False)
            is_admin = Column(Boolean, default=False)
            date_joined = Column(DateTime)

        self.User = User
        self.Base.metadata.create_all(self.engine) 
Example 20
Project: cookiecutter-aiohttp-sqlalchemy   Author: aalhour   File: database.py    License: MIT License 6 votes vote down vote up
def __init__(self):
        ###
        # Private database engine and metadata attributes.
        #
        self._engine = None
        self._metadata = MetaData(schema=db_option('schema'))

        ###
        # Session Factory classes, later initialized in self.initialize() method.
        #
        # The self.Session corresponds to a session factory that doesn't expire ORM instances from memory
        #   after getting committed.
        #
        # The self.OnCommitExpiringSession corresponds to a session factory that expires ORM instances from
        #   memory after getting committed.
        #
        self.Session = None
        self.OnCommitExpiringSession = None

        ###
        # Declarative Base Model class.
        #
        self.BaseModel = declarative_base(
            cls=BaseModelMixin,
            metadata=MetaData(schema=db_option('schema'))) 
Example 21
Project: cookiecutter-aiohttp-sqlalchemy   Author: aalhour   File: database.py    License: MIT License 6 votes vote down vote up
def __init__(self):
        ###
        # Private database engine and metadata attributes.
        #
        self._engine = None
        self._metadata = MetaData(schema=db_option('schema'))

        ###
        # Session Factory classes, later initialized in self.initialize() method.
        #
        # The self.Session corresponds to a session factory that doesn't expire ORM instances from memory
        #   after getting committed.
        #
        # The self.OnCommitExpiringSession corresponds to a session factory that expires ORM instances from
        #   memory after getting committed.
        #
        self.Session = None
        self.OnCommitExpiringSession = None

        ###
        # Declarative Base Model class.
        #
        self.BaseModel = declarative_base(
            cls=BaseModelMixin,
            metadata=MetaData(schema=db_option('schema'))) 
Example 22
Project: planespotter   Author: yfauser   File: fixtures.py    License: 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 23
Project: sci-pype   Author: jay-johnson   File: database_application.py    License: Apache License 2.0 6 votes vote down vote up
def connect(self):

        self.build_connection_string()
        if self.m_connection_str == None:
            self.lg("Not connecting to this database", 0)
            return None
        
        self.lg("Connecting to databases(" + str(self.m_connection_str) + ") Autocommit(" + str(self.m_autocommit) + ") Autoflush(" + str(self.m_autoflush) + ")", 7)

        Base = declarative_base()

        self.m_engine       = create_engine(self.m_connection_str,
                                                echo=False)

        self.m_connection   = self.m_engine.connect()
        self.m_session      = scoped_session(sessionmaker(autocommit  = self.m_autocommit,
                                                            autoflush = self.m_autoflush,
                                                            bind      = self.m_engine))

        self.lg("Connected to DB(" + str(self.m_name) + ") DBTables(" + str(self.m_database_name) + ")", 7)
        return None
    # end of connect 
Example 24
Project: pyRevit   Author: eirannejad   File: fixtures.py    License: 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 25
Project: telethon-session-sqlalchemy   Author: tulir   File: sqlalchemy.py    License: 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 26
Project: jbox   Author: jpush   File: api.py    License: 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 27
Project: jbox   Author: jpush   File: __init__.py    License: 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 28
Project: cellphonedb   Author: Teichlab   File: Database.py    License: 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 29
Project: fever-naacl-2018   Author: sheffieldnlp   File: session.py    License: 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 30
Project: airflow   Author: apache   File: 952da73b5eff_add_dag_code_table.py    License: Apache License 2.0 5 votes vote down vote up
def upgrade():
    """Create DagCode Table."""
    from sqlalchemy.ext.declarative import declarative_base

    Base = declarative_base()

    class SerializedDagModel(Base):
        __tablename__ = 'serialized_dag'

        # There are other columns here, but these are the only ones we need for the SELECT/UPDATE we are doing
        dag_id = sa.Column(sa.String(250), primary_key=True)
        fileloc = sa.Column(sa.String(2000), nullable=False)
        fileloc_hash = sa.Column(sa.BigInteger, nullable=False)

    """Apply add source code table"""
    op.create_table('dag_code',  # pylint: disable=no-member
                    sa.Column('fileloc_hash', sa.BigInteger(),
                              nullable=False, primary_key=True, autoincrement=False),
                    sa.Column('fileloc', sa.String(length=2000), nullable=False),
                    sa.Column('source_code', sa.UnicodeText(), nullable=False),
                    sa.Column('last_updated', sa.TIMESTAMP(timezone=True), nullable=False))

    conn = op.get_bind()
    if conn.dialect.name not in ('sqlite'):
        if conn.dialect.name == "mssql":
            op.drop_index('idx_fileloc_hash', 'serialized_dag')

        op.alter_column(table_name='serialized_dag', column_name='fileloc_hash',
                        type_=sa.BigInteger(), nullable=False)
        if conn.dialect.name == "mssql":
            op.create_index('idx_fileloc_hash', 'serialized_dag', ['fileloc_hash'])

    sessionmaker = sa.orm.sessionmaker()
    session = sessionmaker(bind=conn)
    serialized_dags = session.query(SerializedDagModel).all()
    for dag in serialized_dags:
        dag.fileloc_hash = DagCode.dag_fileloc_hash(dag.fileloc)
        session.merge(dag)
    session.commit()