def make_declarative_base(self, metadata=None): """Creates the declarative base.""" base = declarative_base(cls=Model, name='Model', metadata=metadata, metaclass=ModelDeclarativeMeta) base.query = _QueryProperty(self) return base
def make_declarative_base(self, model, metadata=None): """Creates the declarative base.""" base = declarative_base(cls=model, name='Model', metadata=metadata, metaclass=CachingMeta) base.query = _QueryProperty(self) return base
def make_declarative_base(self): base = declarative_base(cls=self.BaseModel, name='Model', metaclass=self.DeclarativeMeta) base.query = _QueryProperty(self) base.db = self return base
def make_declarative_base(self, metadata=None): # in this case we're just using a custom Model class, # but you can change the DelcarativeMeta or other stuff as well base = declarative_base(cls=MyModel, name='Model', metadata=metadata, metaclass=_BoundDeclarativeMeta, constructor=_my_declarative_constructor) base.query = _QueryProperty(self) return base
def make_declarative_base(self, model, metadata=None, query_class=BaseQuery) -> BaseModel: model = declarative_base(model=model, metadata=metadata) if not getattr(model, 'query_class', None): model.query_class = query_class model.query = _QueryProperty(self) return model
def register_base(self, Base): """Register an external raw SQLAlchemy declarative base. Allows usage of the base with our session management and adds convenience query property using self.Query by default. """ self.external_bases.append(Base) for c in list(Base._decl_class_registry.values()): if isinstance(c, type): if not hasattr(c, 'query') and not hasattr(c, 'query_class'): c.query_class = self.Query if not hasattr(c, 'query'): c.query = flask_sqlalchemy._QueryProperty(self)
def make_declarative_base(self, model, metadata=None): """change declarative base""" base = declarative_base(cls=SoccerModel, name='Model', metadata=metadata, metaclass=_BoundDeclarativeMeta) if not getattr(base, 'query_class', None): base.query_class = self.query_class base.query = _QueryProperty(self) return base
def make_declarative_base(self, model, metadata=None): if not isinstance(model, DeclarativeMeta): model = declarative_base( cls=model, name="Model", metadata=metadata, metaclass=CombinedMeta ) if metadata is not None and model.metadata is not metadata: model.metadata = metadata if not getattr(model, "query_class", None): model.query_class = self.Query model.query = _QueryProperty(self) return model
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
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
def make_declarative_base(self, metadata=None): metadata = MetaData( naming_convention={ 'pk': 'pk_%(table_name)s', 'fk': 'fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s', 'uq': 'uq_%(table_name)s_%(column_0_name)s', 'ix': 'ix_%(table_name)s_%(column_0_name)s', 'ck': 'ck_%(table_name)s_%(constraint_name)s', }) base = declarative_base(metadata=metadata, cls=self.BaseModel, name='Model', metaclass=self.DeclarativeMeta) base.query = _QueryProperty(self) base.db = self return base
def __init__(self): super(AlchemyBase, self).__init__() def fk_fixed_width(constraint, table): str_tokens = [table.name] +\ [element.parent.name for element in constraint.elements] +\ [element.target_fullname for element in constraint.elements] guid = uuid.uuid5(uuid.NAMESPACE_OID, "_".join(str_tokens).encode('ascii')) return str(guid) convention = { "fk_fixed_width": fk_fixed_width, "ix": 'ix_%(column_0_label)s', "uq": "uq_%(table_name)s_%(column_0_name)s", "ck": "ck_%(table_name)s_%(column_0_name)s", "fk": "fk_%(fk_fixed_width)s", "pk": "pk_%(table_name)s" } metadata = MetaData(naming_convention=convention) self.Model = declarative_base(metadata=metadata, cls=Model, name='Model', metaclass=_BoundDeclarativeMeta) self.Model.query = _QueryProperty(self)
def register_base(self, Base): """ Register an external raw SQLAlchemy declarative base. Allows usage of the base with our session management and adds convenience query property using self.Query by default. """ self.external_bases.append(Base) for c in Base._decl_class_registry.values(): if isinstance(c, type): if not hasattr(c, 'query') and not hasattr(c, 'query_class'): c.query_class = self.Query if not hasattr(c, 'query'): c.query = flask_sqlalchemy._QueryProperty(self) # for name in dir(c): # attr = getattr(c, name) # if type(attr) == orm.attributes.InstrumentedAttribute: # if hasattr(attr.prop, 'query_class'): # attr.prop.query_class = self.Query # if hasattr(c , 'rel_dynamic'): # c.rel_dynamic.prop.query_class = self.Query
args = '(%s)' % ', '.join(format(reprs())) classy = type(self).__name__ return classy + args @declared_attr def __table_args__(cls): return getattr(cls, '__table_constraints__', ()) + (Model.default_table_kwargs, ) @declared_attr def __tablename__(cls): return cls.__name__.lower() db = flask_sqlalchemy.SQLAlchemy() db.Model = declarative_base(cls=Model) db.Model.query = flask_sqlalchemy._QueryProperty(db) # set timezone for mysql @event.listens_for(sqlalchemy.pool.Pool, "connect") def set_timezone(dbapi_con, con_record): cursor = dbapi_con.cursor() cursor.execute("SET time_zone = '+0:00'") cursor.close() # We need to check the string lengths because MySQL silently truncates string # values which are too long def check_string_length(cls, key, inst): prop = inst.prop # Only interested in simple columns, not relations
import sqlalchemy from eisitirio import app from eisitirio.database import custom_model DB = flask_sqlalchemy.SQLAlchemy(app.APP) # Awkward hack to use a custom model class. Flask-SQLAlchemy 3.0 (in beta as of # 2016-01-11) has a model_class parameter to the above constructor, which should # be used once v3.0 is released as stable. DB.Model = declarative.declarative_base( cls=custom_model.CustomModel, name="Model".encode("us-ascii"), metadata=None, metaclass=custom_model.CustomModelMeta, ) DB.Model.query = flask_sqlalchemy._QueryProperty(DB) # pylint: disable=protected-access @sqlalchemy.event.listens_for(sqlalchemy.Table, "column_reflect") def column_reflect(_, unused, column_info): """Change the presented types of columns to avoid confusing alembic.""" if isinstance(column_info["type"], mysql.TINYINT): column_info["type"] = sqlalchemy.Boolean() if isinstance(column_info["type"], mysql.MEDIUMTEXT): column_info["type"] = sqlalchemy.UnicodeText(length=65536) if isinstance(column_info["type"], mysql.TEXT): column_info["type"] = sqlalchemy.UnicodeText(length=256)
def make_declarative_base(self, model, metadata=None): base = Model base.query = _QueryProperty(self) return base
from jinja2 import evalcontextfilter, Markup, escape import re from configuration.models import create_tables from configuration.persistence import Base import configuration.web_configuration from teams.user import User app = Flask(__name__) app.config.from_object(configuration.web_configuration.ConfigClass) # Initialize Flask extensions db = SQLAlchemy(app) # Initialize Flask-SQLAlchemy # Add needed query support to base class TODO: investigate difference from db.Model Base.query = _QueryProperty(db) Base.query_class = BaseQuery create_tables(db.engine) # Setup Flask-User db_adapter = SQLAlchemyAdapter(db, User) # Register the User model user_manager = UserManager(db_adapter, app) # Initialize Flask-User def register_modules(): from scoreboard.status.controllers import mod_status as status_module from scoreboard.services.controllers import mod_services as services_module from scoreboard.credentials.controllers import mod_credentials as credentials_module from scoreboard.score.controllers import mod_scoring as scoring_module from scoreboard.users.controllers import mod_users as users_module app.register_blueprint(status_module)
if isinstance(value, Decimal): return str(value) return value def process_result_value(self, value, dialect): if dialect.name == "sqlite": if value is None: return None return Decimal(value) return value db.Numeric = SqliteNumeric class BaseMapper(object): # Allows us to run query on the class directly, instead of through a # session query_class = BaseQuery query = None standard_join = [] # setup our base mapper and database metadata metadata = db.MetaData() base = declarative_base(cls=BaseMapper, metaclass=DefaultMeta, metadata=metadata, name='Model') base.query = _QueryProperty(db) db.Model = base
def make_declarative_base(self): """Creates the declarative base.""" base = declarative_base(cls=Model, name='Model', metaclass=ModelDeclarativeMeta) base.query = _QueryProperty(self) return base
def sqlite_adapt_class(cls, engine): if engine != 'postgresql': # stop from making invalid indexes on sql. I only have indexes as table # args at the moment so i remove all cls.__table_args__ = None for name, type_ in [m for m in getmembers(cls) ]: # if '_' not in m[0]]: # if '_' not in m[0]]: replacement_type_ = _check_member(type_) if replacement_type_: setattr(cls, name, sqlalchemy.Column(replacement_type_)) from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy(session_options={'expire_on_commit': False}) Model = declarative_base(cls=BaseModel, name='Model', metaclass=SQLiteAdaptor) Model.query = _QueryProperty(db) db.Model = Model class RequiredFields(Model): __abstract__ = True created_at = db.Column(db.DateTime, default=db.func.now()) updated_at = db.Column(db.DateTime, nullable=True, default=None, onupdate=db.func.now()) deleted_at = db.Column(db.DateTime, nullable=True, default=None) @staticmethod def create_tsvector(col):
def make_declarative_base(self, metadata=None): """Creates the declarative base.""" base = Model base.query = _QueryProperty(self) return base
from sqlalchemy.ext import declarative import sqlalchemy from eisitirio import app from eisitirio.database import custom_model DB = flask_sqlalchemy.SQLAlchemy(app.APP) # Awkward hack to use a custom model class. Flask-SQLAlchemy 3.0 (in beta as of # 2016-01-11) has a model_class parameter to the above constructor, which should # be used once v3.0 is released as stable. DB.Model = declarative.declarative_base( cls=custom_model.CustomModel, name='Model'.encode('us-ascii'), metadata=None, metaclass=custom_model.CustomModelMeta ) DB.Model.query = flask_sqlalchemy._QueryProperty(DB) # pylint: disable=protected-access @sqlalchemy.event.listens_for(sqlalchemy.Table, "column_reflect") def column_reflect(_, unused, column_info): """Change the presented types of columns to avoid confusing alembic.""" if isinstance(column_info['type'], mysql.TINYINT): column_info['type'] = sqlalchemy.Boolean() if isinstance(column_info['type'], mysql.MEDIUMTEXT): column_info['type'] = sqlalchemy.UnicodeText(length=65536) if isinstance(column_info['type'], mysql.TEXT): column_info['type'] = sqlalchemy.UnicodeText(length=256)