Python sqlalchemy.ext.declarative.declarative_base() Examples

The following are 30 code examples of sqlalchemy.ext.declarative.declarative_base(). 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 also want to check out all available functions/classes of the module sqlalchemy.ext.declarative , or try the search function .
Example #1
Source File: test_codegen.py    From safrs with 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 #2
Source File: test_serialize.py    From sqlalchemy-jsonapi with 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 #3
Source File: test_codegen.py    From safrs with 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 #4
Source File: fixtures.py    From Fluid-Designer with 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 #5
Source File: test_sql.py    From predictive-maintenance-using-machine-learning with 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
Source File: database.py    From cookiecutter-aiohttp-sqlalchemy with 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 #7
Source File: database.py    From cookiecutter-aiohttp-sqlalchemy with 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 #8
Source File: test_codegen.py    From safrs with 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 #9
Source File: database.py    From schematizer with 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 #10
Source File: test_codegen.py    From safrs with 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 #11
Source File: fixtures.py    From planespotter with 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 #12
Source File: test_codegen.py    From safrs with 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 #13
Source File: 8f966b9c467a_set_conn_type_as_non_nullable.py    From airflow with 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 #14
Source File: test_sql.py    From vnpy_crypto with 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
Source File: test_codegen.py    From safrs with 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 #16
Source File: test_codegen.py    From safrs with 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 #17
Source File: test_codegen.py    From safrs with 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 #18
Source File: BBDD.py    From timecop with 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 #19
Source File: database_application.py    From sci-pype with 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 #20
Source File: pytest_fixtures.py    From nameko-sqlalchemy with 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 #21
Source File: fixtures.py    From jbox with 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 #22
Source File: test_sql.py    From recruit with 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 #23
Source File: fixtures.py    From pyRevit with 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 #24
Source File: 004.py    From openmoves with 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 #25
Source File: conftest.py    From sqlalchemy-json-api with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def base():
    return declarative_base() 
Example #26
Source File: test_serialize.py    From sqlalchemy-jsonapi with MIT License 5 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)

        self.User = User
        self.Base.metadata.create_all(self.engine) 
Example #27
Source File: api.py    From Fluid-Designer with 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 #28
Source File: __init__.py    From evesrp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _patch_metadata():
    naming_convention = {
        'fk': ('fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s'
                '_%(referred_column_0_name)s'),
        'pk': 'pk_%(table_name)s',
        'ix': 'ix_%(table_name)s_%(column_0_name)s',
        'ck': 'ck_%(table_name)s_%(constraint_name)s',
        'uq': 'uq_%(table_name)s_%(column_0_name)s',
    }
    metadata = MetaData(naming_convention=naming_convention)
    base = declarative_base(cls=flask_sqlalchemy.Model, name='Model',
                            metaclass=flask_sqlalchemy._BoundDeclarativeMeta,
                            metadata=metadata)
    base.query = flask_sqlalchemy._QueryProperty(db)
    db.Model = base 
Example #29
Source File: test_internals.py    From sqlakeyset with The Unlicense 5 votes vote down vote up
def test_flask_sqla_compat():
    # test djrobstep#18 for regression
    class T(declarative_base()):
        __tablename__ = 't'
        i = Column(Integer, primary_key=True)
    desc = {
        'name': 'T',
        'type': T,
        'aliased': False,
        'expr': class_mapper(T),
        'entity': T,
    }
    mapping = derive_order_key(OC(T.i), desc, 0)
    assert isinstance(mapping, AttributeColumn) 
Example #30
Source File: 005.py    From openmoves with MIT License 5 votes vote down vote up
def changeActivity(old, new):
    Base = declarative_base()
    Session = sessionmaker(bind=op.get_bind())

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

    session = Session()
    session.query(Move).filter(Move.activity == old).update({'activity': new})
    session.commit()