def test_sti_custom_tablename():
    """Test Single Table Inheritance with a custom table name.
    """
    db = SQLAlchemy('sqlite://')

    class Employee(db.Model):
        __tablename__ = 'sti_custom_employee'

        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))
        manager_data = db.Column(db.String(50))
        engineer_info = db.Column(db.String(50))
        type = db.Column(db.String(20))

        __mapper_args__ = {
            'polymorphic_on': type,
            'polymorphic_identity': 'employee'
        }

    class Manager(Employee):
        __mapper_args__ = {
            'polymorphic_identity': 'manager'
        }

    class Engineer(Employee):
        __mapper_args__ = {
            'polymorphic_identity': 'engineer'
        }

    assert Employee.__tablename__ == 'sti_custom_employee'
    assert Manager.__tablename__ == 'sti_custom_employee'
    assert Engineer.__tablename__ == 'sti_custom_employee'
    db.expunge_all()
def test_sti_custom_tablename():
    """Test Single Table Inheritance with a custom table name.
    """
    db = SQLAlchemy('sqlite://')

    class Employee(db.Model):
        __tablename__ = 'sti_custom_employee'

        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))
        manager_data = db.Column(db.String(50))
        engineer_info = db.Column(db.String(50))
        type = db.Column(db.String(20))

        __mapper_args__ = {
            'polymorphic_on': type,
            'polymorphic_identity': 'employee'
        }

    class Manager(Employee):
        __mapper_args__ = {'polymorphic_identity': 'manager'}

    class Engineer(Employee):
        __mapper_args__ = {'polymorphic_identity': 'engineer'}

    assert Employee.__tablename__ == 'sti_custom_employee'
    assert Manager.__tablename__ == 'sti_custom_employee'
    assert Engineer.__tablename__ == 'sti_custom_employee'
    db.expunge_all()
def test_jti_custom_tablename():
    """Test Joined Table Inheritance with a custom table name.
    """
    db = SQLAlchemy('sqlite://')

    class Person(db.Model):
        __tablename__ = 'jti_custom_people'
        id = db.Column(db.Integer, primary_key=True)
        discriminator = db.Column('type', db.String(50))
        __mapper_args__ = {'polymorphic_on': discriminator}

    class Engineer(Person):
        __tablename__ = 'jti_custom_engineers'
        __mapper_args__ = {'polymorphic_identity': 'engineer'}
        id = db.Column(db.Integer, db.ForeignKey(Person.id), primary_key=True)
        primary_language = db.Column(db.String(50))

    class Teacher(Person):
        __tablename__ = 'jti_custom_teachers'
        __mapper_args__ = {'polymorphic_identity': 'teacher'}
        id = db.Column(db.Integer, db.ForeignKey(Person.id), primary_key=True)
        primary_language = db.Column(db.String(50))

    assert Person.__tablename__ == 'jti_custom_people'
    assert Engineer.__tablename__ == 'jti_custom_engineers'
    assert Teacher.__tablename__ == 'jti_custom_teachers'
    db.expunge_all()
def test_sti_auto_tablename():
    """Test Single Table Inheritance with an autonatically
    asigned table name.
    """
    db = SQLAlchemy('sqlite://')

    class SaEmployee(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))
        manager_data = db.Column(db.String(50))
        engineer_info = db.Column(db.String(50))
        type = db.Column(db.String(20))

        __mapper_args__ = {
            'polymorphic_on': type,
            'polymorphic_identity': 'employee'
        }

    class SaManager(SaEmployee):
        __mapper_args__ = {
            'polymorphic_identity': 'manager'
        }

    class SaEngineer(SaEmployee):
        __mapper_args__ = {
            'polymorphic_identity': 'engineer'
        }

    assert SaEmployee.__tablename__ == 'sa_employees'
    assert SaManager.__tablename__ == 'sa_employees'
    assert SaEngineer.__tablename__ == 'sa_employees'
    db.expunge_all()
def test_cti_auto_tablename():
    """Test Concrete Table Inheritance with an autonatically
    asigned table name.
    """
    db = SQLAlchemy('sqlite://')

    class Person(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))

    class Engineer(Person):
        __mapper_args__ = {'concrete': True}
        id = db.Column(db.Integer, primary_key=True)
        primary_language = db.Column(db.String(50))
        name = db.Column(db.String(50))

    class Teacher(Person):
        __tablename__ = 'cti_auto_teachers'
        __mapper_args__ = {'concrete': True}
        id = db.Column(db.Integer, primary_key=True)
        primary_language = db.Column(db.String(50))
        name = db.Column(db.String(50))

    assert Person.__tablename__ == 'people'
    assert Engineer.__tablename__ == 'engineers'
    assert Teacher.__tablename__ == 'cti_auto_teachers'
    db.expunge_all()
def test_jti_custom_tablename():
    """Test Joined Table Inheritance with a custom table name.
    """
    db = SQLAlchemy('sqlite://')

    class Person(db.Model):
        __tablename__ = 'jti_custom_people'
        id = db.Column(db.Integer, primary_key=True)
        discriminator = db.Column('type', db.String(50))
        __mapper_args__ = {'polymorphic_on': discriminator}

    class Engineer(Person):
        __tablename__ = 'jti_custom_engineers'
        __mapper_args__ = {'polymorphic_identity': 'engineer'}
        id = db.Column(db.Integer, db.ForeignKey(Person.id), primary_key=True)
        primary_language = db.Column(db.String(50))

    class Teacher(Person):
        __tablename__ = 'jti_custom_teachers'
        __mapper_args__ = {'polymorphic_identity': 'teacher'}
        id = db.Column(db.Integer, db.ForeignKey(Person.id), primary_key=True)
        primary_language = db.Column(db.String(50))

    assert Person.__tablename__ == 'jti_custom_people'
    assert Engineer.__tablename__ == 'jti_custom_engineers'
    assert Teacher.__tablename__ == 'jti_custom_teachers'
    db.expunge_all()
def test_cti_auto_tablename():
    """Test Concrete Table Inheritance with an autonatically
    asigned table name.
    """
    db = SQLAlchemy('sqlite://')

    class Person(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))

    class Engineer(Person):
        __mapper_args__ = {'concrete': True}
        id = db.Column(db.Integer, primary_key=True)
        primary_language = db.Column(db.String(50))
        name = db.Column(db.String(50))

    class Teacher(Person):
        __tablename__ = 'cti_auto_teachers'
        __mapper_args__ = {'concrete': True}
        id = db.Column(db.Integer, primary_key=True)
        primary_language = db.Column(db.String(50))
        name = db.Column(db.String(50))

    assert Person.__tablename__ == 'people'
    assert Engineer.__tablename__ == 'engineers'
    assert Teacher.__tablename__ == 'cti_auto_teachers'
    db.expunge_all()
def test_acti_auto_tablename():
    """Test Abstract Concrete Table Inheritance with an autonatically
    asigned table name.
    """
    db = SQLAlchemy('sqlite://')

    class Employee(AbstractConcreteBase, db.Model):
        pass

    class Manager(Employee):
        __tablename__ = 'acti_auto_managers'
        employee_id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))
        manager_data = db.Column(db.String(40))
        __mapper_args__ = {'polymorphic_identity': 'manager', 'concrete': True}

    class AaEngineer(Employee):
        employee_id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))
        engineer_info = db.Column(db.String(40))
        __mapper_args__ = {
            'polymorphic_identity': 'engineer',
            'concrete': True
        }

    assert Manager.__tablename__ == 'acti_auto_managers'
    assert AaEngineer.__tablename__ == 'aa_engineers'
    db.expunge_all()
def test_acti_auto_tablename():
    """Test Abstract Concrete Table Inheritance with an autonatically
    asigned table name.
    """
    db = SQLAlchemy('sqlite://')

    class Employee(AbstractConcreteBase, db.Model):
        pass

    class Manager(Employee):
        __tablename__ = 'acti_auto_managers'
        employee_id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))
        manager_data = db.Column(db.String(40))
        __mapper_args__ = {
            'polymorphic_identity': 'manager',
            'concrete': True
        }

    class AaEngineer(Employee):
        employee_id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))
        engineer_info = db.Column(db.String(40))
        __mapper_args__ = {
            'polymorphic_identity': 'engineer',
            'concrete': True
        }

    assert Manager.__tablename__ == 'acti_auto_managers'
    assert AaEngineer.__tablename__ == 'aa_engineers'
    db.expunge_all()
def test_sti_auto_tablename():
    """Test Single Table Inheritance with an autonatically
    asigned table name.
    """
    db = SQLAlchemy('sqlite://')

    class SaEmployee(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(50))
        manager_data = db.Column(db.String(50))
        engineer_info = db.Column(db.String(50))
        type = db.Column(db.String(20))

        __mapper_args__ = {
            'polymorphic_on': type,
            'polymorphic_identity': 'employee'
        }

    class SaManager(SaEmployee):
        __mapper_args__ = {'polymorphic_identity': 'manager'}

    class SaEngineer(SaEmployee):
        __mapper_args__ = {'polymorphic_identity': 'engineer'}

    assert SaEmployee.__tablename__ == 'sa_employees'
    assert SaManager.__tablename__ == 'sa_employees'
    assert SaEngineer.__tablename__ == 'sa_employees'
    db.expunge_all()
Exemple #11
0
def test_custom_poolclass():
    class _CustomPool(pool.StaticPool):
        _do_return_conn = mock.MagicMock()

    db = SQLAlchemy(URI1, poolclass=_CustomPool)
    db.create_all()

    _CustomPool._do_return_conn.assert_called_once()
Exemple #12
0
def test_session_options(uri1):
    class _CustomPool(pool.StaticPool):
        _do_return_conn = mock.MagicMock()

    db = SQLAlchemy(uri1, poolclass=_CustomPool)
    db.create_all()

    _CustomPool._do_return_conn.assert_called_once()
def test_custom_poolclass():

    class _CustomPool(pool.StaticPool):
        _do_return_conn = mock.MagicMock()

    db = SQLAlchemy(URI1, poolclass=_CustomPool)
    db.create_all()

    _CustomPool._do_return_conn.assert_called_once()
def test_id_mixin():
    db = SQLAlchemy(URI1)

    class IDMixin(object):
        id = db.Column(db.Integer, primary_key=True)

    class Model(db.Model, IDMixin):
        field = db.Column(db.String)

    db.create_all()

    assert Model.__tablename__ == 'models'
    assert hasattr(Model, 'id')
Exemple #15
0
def test_id_mixin():
    db = SQLAlchemy(URI1)

    class IDMixin(object):
        id = db.Column(db.Integer, primary_key=True)

    class Model(db.Model, IDMixin):
        field = db.Column(db.String)

    db.create_all()

    assert Model.__tablename__ == 'models'
    assert hasattr(Model, 'id')
def test_define_table():
    db = SQLAlchemy(URI1)
    db.Table(
        'foobar',
        db.Column('foo', db.UnicodeText),
        db.Column('bar', db.UnicodeText),
    )
    db.Table(
        'fizzbuzz',
        db.metadata,
        db.Column('fizz', db.Integer),
        db.Column('buzz', db.Integer),
    )
    db.create_all()
def test_mixin_no_tablename():
    """Test for a tablename NOT defined in a mixin.
    """
    db = SQLAlchemy('sqlite://')

    class BaseMixin(object):
        @declared_attr
        def id(cls):
            return db.Column(db.Integer, primary_key=True)

    class MEngineer(BaseMixin, db.Model):
        name = db.Column(db.String(50))

    assert MEngineer.__tablename__ == 'm_engineers'
    db.expunge_all()
Exemple #18
0
def test_custom_metaclass():
    class _CustomMeta(DefaultMeta):
        def __init__(self, name, bases, dic):
            DefaultMeta.__init__(self, name, bases, dic)
            if hasattr(self, 'id'):
                setattr(self, 'test', 1)

    db = SQLAlchemy(URI1, metaclass=_CustomMeta)

    class Model(db.Model):
        id = db.Column(db.Integer, primary_key=True)

    db.create_all()

    assert Model.test == 1
def test_mixin_no_tablename():
    """Test for a tablename NOT defined in a mixin.
    """
    db = SQLAlchemy('sqlite://')

    class BaseMixin(object):
        @declared_attr
        def id(cls):
            return db.Column(db.Integer, primary_key=True)

    class MEngineer(BaseMixin, db.Model):
        name = db.Column(db.String(50))

    assert MEngineer.__tablename__ == 'm_engineers'
    db.expunge_all()
Exemple #20
0
def test_api():
    db = SQLAlchemy()
    assert db.metadata == db.Model.metadata
    assert db.query
    assert callable(db.drop_all)
    assert callable(db.rollback)
    assert callable(db.add)
    assert callable(db.add_all)
    assert callable(db.begin)
    assert callable(db.begin_nested)
    assert callable(db.commit)
    assert callable(db.connection)
    assert callable(db.delete)
    assert callable(db.execute)
    assert callable(db.expire)
    assert callable(db.expire_all)
    assert callable(db.expunge)
    assert callable(db.expunge_all)
    assert callable(db.flush)
    assert callable(db.invalidate)
    assert callable(db.is_modified)
    assert callable(db.merge)
    assert callable(db.prepare)
    assert callable(db.prune)
    assert callable(db.refresh)
    assert callable(db.rollback)
    assert callable(db.scalar)
Exemple #21
0
    def connect(self, database_uri, **kwargs):
        kwargs.setdefault("pool_size", 5)
        kwargs.setdefault("pool_recycle", 2 * 60 * 60)

        # developers need to know when the ORM object needs to reload from the db
        kwargs.setdefault("expire_on_commit", False)
        self._session = SQLAlchemy(database_uri, **kwargs)
def init_db():
    global db
    if not db:
        db = SQLAlchemy(os.getenv("DATABASE_URL",
                                  "sqlite:///localhost.sqlite"))

    return db
def test_mixin_tablename():
    """Test for a tablename defined in a mixin.
    """
    db = SQLAlchemy('sqlite://')

    class EmployeeMixin(object):
        __tablename__ = 'mixin_tablename'

        @declared_attr
        def id(cls):
            return db.Column(db.Integer, primary_key=True)

    class Engineer(EmployeeMixin, db.Model):
        name = db.Column(db.String(50))

    assert Engineer.__tablename__ == 'mixin_tablename'
    db.expunge_all()
def test_mixin_tablename():
    """Test for a tablename defined in a mixin.
    """
    db = SQLAlchemy('sqlite://')

    class EmployeeMixin(object):
        __tablename__ = 'mixin_tablename'

        @declared_attr
        def id(cls):
            return db.Column(db.Integer, primary_key=True)

    class Engineer(EmployeeMixin, db.Model):
        name = db.Column(db.String(50))

    assert Engineer.__tablename__ == 'mixin_tablename'
    db.expunge_all()
def test_custom_metaclass():

    class _CustomMeta(DefaultMeta):

        def __init__(self, name, bases, dic):
            DefaultMeta.__init__(self, name, bases, dic)
            if hasattr(self, 'id'):
                setattr(self, 'test', 1)

    db = SQLAlchemy(URI1, metaclass=_CustomMeta)

    class Model(db.Model):
        id = db.Column(db.Integer, primary_key=True)

    db.create_all()

    assert Model.test == 1
def test_declared_attr_mixin_overwritten_tablename():
    """Test for a tablename defined as a @declared_attr in a mixin but overwritten
    """
    db = SQLAlchemy('sqlite://')

    class EmployeeMixin(object):
        @declared_attr
        def __tablename__(cls):
            return 'declared_attr_mixin_tablename'

        @declared_attr
        def id(cls):
            return db.Column(db.Integer, primary_key=True)

    class Engineer(EmployeeMixin, db.Model):
        __tablename__ = 'declared_attr_mixin_overwritten_engineers'
        name = db.Column(db.String(50))

    assert Engineer.__tablename__ == 'declared_attr_mixin_overwritten_engineers'
    db.expunge_all()
def test_declared_attr_mixin_overwritten_tablename():
    """Test for a tablename defined as a @declared_attr in a mixin but overwritten
    """
    db = SQLAlchemy('sqlite://')

    class EmployeeMixin(object):
        @declared_attr
        def __tablename__(cls):
            return 'declared_attr_mixin_tablename'

        @declared_attr
        def id(cls):
            return db.Column(db.Integer, primary_key=True)

    class Engineer(EmployeeMixin, db.Model):
        __tablename__ = 'declared_attr_mixin_overwritten_engineers'
        name = db.Column(db.String(50))

    assert Engineer.__tablename__ == 'declared_attr_mixin_overwritten_engineers'
    db.expunge_all()
Exemple #28
0
def test_model_helpers():
    db = SQLAlchemy()

    class Row(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(60), nullable=False)
        created_at = db.Column(db.DateTime,
                               nullable=False,
                               default=datetime.utcnow)

    db.create_all()
    db.add(Row(name='a'))
    db.flush()
    row = db.query(Row).first()

    assert str(row) == '<Row>'
    assert dict(row)['name'] == 'a'
Exemple #29
0
def test_define_table():
    db = SQLAlchemy(URI1)
    db.Table(
        'foobar',
        db.Column('foo', db.UnicodeText),
        db.Column('bar', db.UnicodeText),
    )
    db.Table(
        'fizzbuzz',
        db.metadata,
        db.Column('fizz', db.Integer),
        db.Column('buzz', db.Integer),
    )
    db.create_all()
def test_model_helpers():
    db = SQLAlchemy()

    class Row(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(60), nullable=False)
        created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

    db.create_all()
    db.add(Row(name='a'))
    db.flush()
    row = db.query(Row).first()

    assert str(row) == '<Row>'
    assert dict(row)['name'] == 'a'
def get_db():
    # determine the database URL
    db_user = os.environ.get('CLOUD_SQL_USERNAME')
    db_password = os.environ.get('CLOUD_SQL_PASSWORD')
    db_name = os.environ.get('CLOUD_SQL_DATABASE_NAME')
    db_connection_name = os.environ.get('CLOUD_SQL_CONNECTION_NAME')

    if db_user and db_password and db_name and db_connection_name:  # if on google cloud, connect to PostgreSQL
        sqla_db_uri = f"postgresql://{db_user}:{db_password}@/{db_name}?host=/cloudsql/{db_connection_name}"
    else:  # if on localhost, use SQLite
        if os.getenv('TESTING', '').startswith('yes'):
            sqla_db_uri = "sqlite:///:memory:"
        else:
            sqla_db_uri = "sqlite:///localhost.sqlite"

    db = SQLAlchemy(sqla_db_uri)

    return db
Exemple #32
0
import os
from flask import Flask, render_template, request, redirect
from sqla_wrapper import SQLAlchemy
from sqlalchemy_pagination import paginate

app = Flask(__name__)

# the replace method is needed due to this issue: https://help.heroku.com/ZKNTJQSK/why-is-sqlalchemy-1-4-x-not-connecting-to-heroku-postgres
db_url = os.getenv("DATABASE_URL",
                   "sqlite:///db.sqlite").replace("postgres://",
                                                  "postgresql://", 1)
db = SQLAlchemy(db_url)


class Message(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    author = db.Column(db.String, unique=False)
    text = db.Column(db.String, unique=False)


db.create_all()


@app.route("/", methods=["GET"])
def index():
    page = request.args.get("page")

    if not page:
        page = 1

    messages_query = db.query(Message)
Exemple #33
0
 def connect(self):
     return SQLAlchemy(self.get_database_uri(), pool_pre_ping=True)
Exemple #34
0
import os
from sqla_wrapper import SQLAlchemy

db = SQLAlchemy(os.getenv("DATABASE_URL", "sqlite:///secret_number.sqlite"))


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String)
    email = db.Column(db.String, unique=True)
    password = db.Column(db.String)
    secret_number = db.Column(db.Integer)
    attempts = db.Column(db.Integer)
    games_played = db.Column(db.Integer)
    session_token = db.Column(db.String)
def create_test_model():
    db = SQLAlchemy('sqlite://')

    class Item(db.Model):
        id = db.Column(db.Integer, primary_key=True)

    class Part(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        item_id = db.Column(db.Integer, db.ForeignKey(Item.id))
        item = db.relationship('Item', backref='parts')

    db.create_all()

    for _i in range(1, 26):
        item = Item()
        db.add(item)
    db.commit()

    item = db.query(Item).first()
    for _j in range(1, 26):
        db.add(Part(item=item))
    db.commit()

    return db, Item, Part
Exemple #36
0
import os
import datetime
from sqla_wrapper import SQLAlchemy
from sqlalchemy import Integer, ForeignKey, String, Column
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm import relationship

db = SQLAlchemy(os.getenv("DATABASE_URL", "sqlite:///game.sqlite"))


class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, unique=True)
    email = db.Column(db.String, unique=True)
    password = db.Column(db.String, )
    session_token = db.Column(db.String, )
    secret_number = db.Column(db.Integer, unique=False)
    games = db.Column(db.Integer, )
    wins = db.Column(db.Integer, )
    score = db.Column(db.JSON, nullable=True)
    losses = db.Column(db.Integer, )
    online = db.Column(db.Boolean, default=False)
    offline = db.Column(db.Boolean, default=True)
    deleted = db.Column(db.Boolean, default=False)
    date = db.Column(db.DateTime,
                     nullable=False,
                     default=datetime.datetime.now())


class Message(db.Model):
Exemple #37
0
from sqla_wrapper import SQLAlchemy
import os
db = SQLAlchemy(
    os.getenv("DATABASE_URL",
              "sqlite:///podatkovna-baza.sqlite?check_same_thread=False"))


class Komentar(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    avtor = db.Column(db.String)
    vsebina = db.Column(db.String)


class Uporabnik(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    ime = db.Column(db.String)
    email = db.Column(db.String)
    geslo = db.Column(db.String)
    sejna_vrednost = db.Column(db.String)
    je_blokiran = db.Column(db.Boolean, default=False)
import os
from sqla_wrapper import SQLAlchemy

db = SQLAlchemy(os.getenv("DATABASE_URL", "sqlite:///localhost.sqlite"),
                connect_args={"check_same_thread": False})


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, unique=True)
    email = db.Column(db.String, unique=True)
    secret_number = db.Column(db.Integer, unique=False)
    city = db.Column(db.String, unique=False)
    password = db.Column(db.String, unique=True)
    session_token = db.Column(db.String)
    deleted = db.Column(db.Boolean, default=False)
Exemple #39
0
import os
from sqla_wrapper import SQLAlchemy

db = SQLAlchemy(
    os.getenv("DATABASE_URL",
              "sqlite:///localhost.sqlite?check_same_thread=False"))
Exemple #40
0
import os
from sqla_wrapper import SQLAlchemy

# the replace method is needed due to this issue: https://help.heroku.com/ZKNTJQSK/why-is-sqlalchemy-1-4-x-not-connecting-to-heroku-postgres
db_url = os.getenv("DATABASE_URL", "sqlite:///db.sqlite").replace("postgres://", "postgresql://", 1)
db = SQLAlchemy(db_url)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, unique=True)  # a username must be unique!
    email = db.Column(db.String, unique=True)  # email must be unique!
def test_multiple_databases():
    db1 = SQLAlchemy(URI1)
    db2 = SQLAlchemy(URI2)
    ToDo1 = create_test_model(db1)
    ToDo2 = create_test_model(db2)
    db1.create_all()
    db2.create_all()

    db1.add(ToDo1('A', 'a'))
    db1.add(ToDo1('B', 'b'))
    db2.add(ToDo2('Q', 'q'))
    db1.add(ToDo1('C', 'c'))
    db1.commit()
    db2.commit()

    assert db1.query(ToDo1).count() == 3
    assert db2.query(ToDo2).count() == 1
Exemple #42
0
from loguru import logger
from sqla_wrapper import SQLAlchemy
from sqlalchemy import BigInteger, Column, Integer, String
from sqlalchemy.exc import SQLAlchemyError

from shot import conf
from .utils import db_session_scope

db = SQLAlchemy(conf.db_uri, scopefunc=db_session_scope)


class BaseModel(db.Model):
    __abstract__ = True

    @classmethod
    def get_by_id(cls, model_id):
        try:
            return db.query(cls).get(model_id)
        except SQLAlchemyError:
            logger.exception()
            raise


class Admin(BaseModel):
    admin_id = Column(Integer, primary_key=True)
    chat_id = Column(BigInteger, unique=True)


class Channel(BaseModel):
    channel_id = Column(Integer, primary_key=True)
    chat_id = Column(BigInteger, unique=True)
def test_aggregated_query():
    db = SQLAlchemy(URI1)

    class Unit(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(60))
        price = db.Column(db.Integer)

    db.create_all()
    db.add(Unit(price=25))
    db.add(Unit(price=5))
    db.add(Unit(price=10))
    db.add(Unit(price=3))
    db.commit()

    res = db.query(db.func.sum(Unit.price).label('price')).first()
    assert res.price == 43
def test_reconfigure():
    db = SQLAlchemy(URI1, echo=False)

    class Model(db.Model):
        id = db.Column(db.Integer, primary_key=True)

    db.create_all()
    db.add(Model())
    db.commit()

    class CustomQuery(BaseQuery):
        some_attr = 1

    db.reconfigure(query_cls=CustomQuery)
    assert isinstance(db.query(Model), CustomQuery)
    assert db.query(Model).some_attr == 1
Exemple #45
0
import os
from sqla_wrapper import SQLAlchemy

db = SQLAlchemy(
    os.getenv("DATABASE_URL", "sqlite:///localhost.sqlite")
)  # this connects to a database either on Heroku or on localhost


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, unique=True)
    email = db.Column(db.String, unique=True)
    secret_number = db.Column(db.Integer)
    password = db.Column(db.String)
    session_token = db.Column(db.String)
    deleted = db.Column(db.Boolean, default=False)
Exemple #46
0
import os
from sqla_wrapper import SQLAlchemy

db = SQLAlchemy(
    os.getenv(
        "DATABASE_URL",
        "postgres://*****:*****@ec2-79-125-4-72.eu-west-1.compute.amazonaws.com:5432/dfs70agbsg1d5n"
    ))


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, unique=True)
    email = db.Column(db.String, unique=True)
    password = db.Column(db.String)
    secret_number = db.Column(db.Integer)
Exemple #47
0
import os
from sqla_wrapper import SQLAlchemy

db = SQLAlchemy(os.getenv("DATABASE_URL", "sqlite:///localhost.sqlite"))


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, unique=True)
    email = db.Column(db.String, unique=True)
    secret_number = db.Column(db.Integer, unique=True)
    password = db.Column(db.String)
    token_session = db.Column(db.String)
    delete = db.Column(db.Boolean, default=False)
def test_query():
    db = SQLAlchemy(URI1)
    ToDo = create_test_model(db)
    db.create_all()

    db.add(ToDo('First', 'The text'))
    db.add(ToDo('Second', 'The text'))
    db.flush()

    titles = ' '.join(x.title for x in db.query(ToDo).all())
    assert titles == 'First Second'

    data = db.query(ToDo).filter(ToDo.title == 'First').all()
    assert len(data) == 1