Ejemplo n.º 1
0
    def __init__(self, config, Model=None, engine_config_prefix=''):
        self.Model = model.make_declarative_base() if Model is None else Model
        self.config = config

        engine_config = self.config['engine']

        self.engine = engine_from_config(engine_config, prefix=engine_config_prefix)

        session_config = self.config.get('session', {})
        session_config['bind'] = self.engine
        session_config.setdefault('autocommit', False)
        session_config.setdefault('autoflush', True)
        session_config.setdefault('query_cls', query.Query)

        self.session = orm.scoped_session(orm.sessionmaker())
        self.session.configure(**session_config)

        if self.Model:
            model.extend_declarative_base(self.Model, self.session)
Ejemplo n.º 2
0
from sqlalchemy import orm, types, Column, ForeignKey
from sqlalchemy.ext.hybrid import hybrid_property

from alchy import model, query
from alchy.types import DeclarativeEnum


Model = model.make_declarative_base()


class Foo(Model):
    __tablename__ = 'foo'

    _id             = Column(types.Integer(), primary_key=True)
    string          = Column(types.String())
    number          = Column(types.Integer())
    boolean         = Column(types.Boolean(), default=True)
    deferred1_col1  = orm.deferred(Column(types.Boolean()), group='deferred_1')
    deferred1_col2  = orm.deferred(Column(types.Boolean()), group='deferred_1')
    deferred2_col3  = orm.deferred(Column(types.Boolean()), group='deferred_2')
    deferred2_col4  = orm.deferred(Column(types.Boolean()), group='deferred_2')

    bars = orm.relationship('Bar', lazy=True)
    quxs = orm.relationship('Qux', lazy=True)

    __advanced_search__ = {
        'foo_string': lambda value: Foo.string.like('%{0}%'.format(value)),
        'foo_number': lambda value: Foo.number == value
    }
Ejemplo n.º 3
0
class TestMultipleEngineBinds(TestBase):
    class config(object):
        binds = [
            'sqlite:///bind0.test.db',
            'sqlite:///bind1.test.db',
            'sqlite:///bind2.test.db'
        ]

        SQLALCHEMY_DATABASE_URI = binds[0]
        SQLALCHEMY_BINDS = {
            'bind1': binds[1],
            'bind2': {
                'SQLALCHEMY_DATABASE_URI': binds[2]
            }
        }

    Model = model.make_declarative_base()

    class Bind0(Model):
        _id = Column(types.Integer(), primary_key=True)

    class Bind1(Model):
        __bind_key__ = 'bind1'

        _id = Column(types.Integer(), primary_key=True)

    class Bind2(Model):
        __bind_key__ = 'bind2'

        _id = Column(types.Integer(), primary_key=True)

    def setUp(self):
        self.db = manager.Manager(config=self.config, Model=self.Model)
        self.db.create_all()

        self.engine0 = self.db.engine
        self.engine1 = self.db.get_engine('bind1')
        self.engine2 = self.db.get_engine('bind2')

    def tearDown(self):
        for db in glob.glob('*.test.db'):
            os.remove(db)

    def test_bind_engines(self):
        """Test that each bind engine is accessible and configured properly."""
        self.assertEqual(
            str(self.db.engine.url), self.config.binds[0])
        self.assertEqual(
            str(self.db.get_engine('bind1').url), self.config.binds[1])
        self.assertEqual(
            str(self.db.get_engine('bind2').url), self.config.binds[2])

    def test_bind_tables(self):
        """Test that tables are created in the proper database."""
        self.assertEqual(
            self.engine0.execute('select * from bind0').fetchall(), [])
        self.assertEqual(
            self.engine1.execute('select * from bind1').fetchall(), [])
        self.assertEqual(
            self.engine2.execute('select * from bind2').fetchall(), [])

        try:
            self.engine0.execute('select * from bind1')
        except Exception as e:
            self.assertIn('no such table', str(e))

        try:
            self.engine0.execute('select * from bind2')
        except Exception as e:
            self.assertIn('no such table', str(e))

        try:
            self.engine1.execute('select * from bind0')
        except Exception as e:
            self.assertIn('no such table', str(e))

        try:
            self.engine1.execute('select * from bind2')
        except Exception as e:
            self.assertIn('no such table', str(e))

        try:
            self.engine2.execute('select * from bind0')
        except Exception as e:
            self.assertIn('no such table', str(e))

        try:
            self.engine2.execute('select * from bind1')
        except Exception as e:
            self.assertIn('no such table', str(e))

    def test_bind_inserts(self):
        """Test that records are inserted into the proper database when using
        models."""
        self.db.add_commit(self.Bind0())
        self.db.add_commit(self.Bind1())
        self.db.add_commit(self.Bind2())

        self.assertTrue(self.Bind0.query.count() > 0)
        self.assertEqual(
            self.Bind0.query.count(),
            self.engine0.execute('select count(*) from bind0').fetchone()[0])

        self.assertTrue(self.Bind1.query.count() > 0)
        self.assertEqual(
            self.Bind1.query.count(),
            self.engine1.execute('select count(*) from bind1').fetchone()[0])

        self.assertTrue(self.Bind2.query.count() > 0)
        self.assertEqual(
            self.Bind2.query.count(),
            self.engine2.execute('select count(*) from bind2').fetchone()[0])

    def test_create_drop_all_by_bind(self):
        """Test that create/drop all can be used to target a specific bind."""
        self.db.drop_all(bind='bind1')

        self.assertEqual(
            self.engine0.execute('select * from bind0').fetchall(), [])
        self.assertEqual(
            self.engine2.execute('select * from bind2').fetchall(), [])

        try:
            self.engine1.execute('select * from bind1')
        except Exception as e:
            self.assertIn('no such table', str(e))

        self.db.create_all(bind='bind1')

        self.assertEqual(
            self.engine1.execute('select * from bind1').fetchall(), [])

        self.db.drop_all(bind=['bind1', 'bind2'])

        try:
            self.engine1.execute('select * from bind1')
        except Exception as e:
            self.assertIn('no such table', str(e))

        try:
            self.engine2.execute('select * from bind2')
        except Exception as e:
            self.assertIn('no such table', str(e))

        self.db.create_all(bind=['bind1', 'bind2'])

        self.assertEqual(
            self.engine1.execute('select * from bind1').fetchall(), [])
        self.assertEqual(
            self.engine2.execute('select * from bind2').fetchall(), [])

    def test_reflect(self):
        """Test that existing database tables can be reflected."""
        rdb = manager.Manager(
            config={'SQLALCHEMY_DATABASE_URI': self.config.binds[0]})

        self.assertEqual(len(rdb.metadata.tables), 0)

        rdb.reflect()

        self.assertEqual(len(rdb.metadata.tables), 1)
        self.assertIn('bind0', rdb.metadata.tables)
Ejemplo n.º 4
0
# -*- coding: utf-8 -*-
from alchy.model import ModelBase, make_declarative_base
from flask_security import UserMixin, RoleMixin
from sqlalchemy import orm, types, Column, ForeignKey, Table

from . import login_manager
from ..bases import AutoTableMixin

BaseAuthModel = make_declarative_base(Base=ModelBase,
                                      # Meta=Trackable
                                      )

roles_users = Table('roles_users', BaseAuthModel.metadata,
                    Column('user_id', types.Integer(), ForeignKey('users.id')),
                    Column('role_id', types.Integer(), ForeignKey('roles.id')))


class Role(AutoTableMixin, RoleMixin, BaseAuthModel):
    """Allows users to have different roles"""

    __tablename__ = 'roles'

    id = Column(types.Integer, primary_key=True)
    name = Column(types.String, unique=True)
    description = Column(types.String)

    def __init__(self, name, description='', permissions=None):
        self.name = name
        self.description = description

    def __repr__(self):
Ejemplo n.º 5
0
from sqlalchemy import orm, types, Column, ForeignKey
from sqlalchemy.ext.hybrid import hybrid_property

from alchy import model, query
from alchy.types import DeclarativeEnum

Model = model.make_declarative_base()


class FooQuery(query.QueryModel):
    __search_filters__ = {
        'foo_string': lambda value: Foo.string.contains(value),
        'foo_string2': lambda value: Foo.string2.contains(value),
        'foo_number': lambda value: Foo.number == value,
        'bar_string': lambda value: Foo.bars.any(Bar.string.contains(value))
    }

    __advanced_search__ = ['foo_string', 'foo_string2', 'foo_number']
    __simple_search__ = ['foo_string', 'foo_string2', 'bar_string']


class Foo(Model):
    __tablename__ = 'foo'
    query_class = FooQuery

    _id = Column(types.Integer(), primary_key=True)
    string = Column(types.String())
    string2 = Column(types.String())
    number = Column(types.Integer())
    boolean = Column(types.Boolean(), default=True)
    deferred1_col1 = orm.deferred(Column(types.Boolean()), group='deferred_1')
Ejemplo n.º 6
0
# -*- coding: utf-8 -*-
"""
Base platform for intertwine.
"""
import flask
from alchy import Manager
from alchy.model import extend_declarative_base, make_declarative_base
from flask_bootstrap import Bootstrap

from .bases import BaseIntertwineMeta, BaseIntertwineModel
from .__metadata__ import *  # noqa

# Set up base model and database connection, and attach query property
IntertwineModel = make_declarative_base(Base=BaseIntertwineModel,
                                        Meta=BaseIntertwineMeta)

intertwine_db = Manager(Model=IntertwineModel)
extend_declarative_base(IntertwineModel, session=intertwine_db.session)

from . import auth, communities, content, geos, main, problems, signup  # noqa

IntertwineModel.initialize_table_model_map()


def create_app(name=None, config=None):
    """Creates an app based on a config file

    Args:
        config: Configuration

    Returns:
Ejemplo n.º 7
0
# -*- coding: utf-8 -*-
import re
from collections import namedtuple

from alchy.model import ModelBase, make_declarative_base
from sqlalchemy import (orm, types, Column, ForeignKey, Index,
                        PrimaryKeyConstraint, ForeignKeyConstraint)

from intertwine.utils.mixins import AutoTablenameMixin, KeyedUp

BaseGeoDataModel = make_declarative_base(Base=ModelBase)


class State(KeyedUp, AutoTablenameMixin, BaseGeoDataModel):
    STATE = 'state'
    TERRITORY = 'territory'
    FEDERAL_DISTRICT = 'federal district'

    name = Column(types.String(60), unique=True)  # Texas
    stusps = Column(types.String(2), unique=True)  # TX
    statefp = Column(types.String(2), primary_key=True)  # 48
    statens = Column(types.String(8), unique=True)  # 01779801

    KEYED_UP_FIELDS = ('name', 'stusps', 'statefp', 'statens')

    TERRITORIES = {'PR', 'AS', 'GU', 'MP', 'UM', 'VI'}
    SMALL_TERRITORIES = {'AS', 'GU', 'MP', 'UM', 'VI'}

    STATES_WITH_MCDS = {
        # Additional beyond STATES_WITH_MCDS_AS_GOVERNMENTAL_UNITS:
        # 'AR', 'IA', 'LA', 'MD', 'MS', 'NC', 'TN', 'VA', 'WV', 'PR',