def setup_method(self, method): self.Model = declarative_base() make_versioned(options=self.options) driver = os.environ.get('DB', 'sqlite') driver = get_driver_name(driver) versioning_manager.plugins = self.plugins versioning_manager.transaction_cls = self.transaction_cls versioning_manager.user_cls = self.user_cls self.engine = create_engine(get_dns_from_driver(driver)) # self.engine.echo = True self.connection = self.engine.connect() self.create_models() sa.orm.configure_mappers() if hasattr(self, 'Article'): self.ArticleVersion = version_class(self.Article) if hasattr(self, 'Tag'): try: self.TagVersion = version_class(self.Tag) except ClassNotVersioned: pass self.create_tables() Session = sessionmaker(bind=self.connection) self.session = Session(autoflush=False)
def setup_method(self, method): # Mock the event registering of Flask-SQLAlchemy. Currently there is no # way of unregistering Flask-SQLAlchemy event listeners, hence the # event listeners would affect other tests. flexmock(_SessionSignalEvents).should_receive("register") self.db = SQLAlchemy() make_versioned() versioning_manager.transaction_cls = TransactionFactory() versioning_manager.options["native_versioning"] = uses_native_versioning() self.create_models() sa.orm.configure_mappers() self.app = Flask(__name__) # self.app.config['SQLALCHEMY_ECHO'] = True self.app.config["SQLALCHEMY_DATABASE_URI"] = get_dns_from_driver( get_driver_name(os.environ.get("DB", "sqlite")) ) self.db.init_app(self.app) self.app.secret_key = "secret" self.app.debug = True self.client = self.app.test_client() self.context = self.app.test_request_context() self.context.push() self.db.create_all()
def setup_versioning(self): make_versioned( plugins=[self.meta_plugin, self.athana_continuum_plugin], options={ 'native_versioning': True, 'base_classes': (MtVersionBase, DeclarativeBase), 'extension_schema': config.get("database.extension_schema", "public") } )
def init_versioning(self, app, database, versioning_manager=None): """Initialize the versioning support using SQLAlchemy-Continuum.""" try: pkg_resources.get_distribution('sqlalchemy_continuum') except pkg_resources.DistributionNotFound: # pragma: no cover default_versioning = False else: default_versioning = True app.config.setdefault('DB_VERSIONING', default_versioning) if not app.config['DB_VERSIONING']: return if not default_versioning: # pragma: no cover raise RuntimeError( 'Please install extra versioning support first by running ' 'pip install invenio-db[versioning].' ) # Now we can import SQLAlchemy-Continuum. from sqlalchemy_continuum import make_versioned from sqlalchemy_continuum import versioning_manager as default_vm from sqlalchemy_continuum.plugins import FlaskPlugin # Try to guess user model class: if 'DB_VERSIONING_USER_MODEL' not in app.config: # pragma: no cover try: pkg_resources.get_distribution('invenio_accounts') except pkg_resources.DistributionNotFound: user_cls = None else: user_cls = 'User' else: user_cls = app.config.get('DB_VERSIONING_USER_MODEL') plugins = [FlaskPlugin()] if user_cls else [] # Call make_versioned() before your models are defined. self.versioning_manager = versioning_manager or default_vm make_versioned( user_cls=user_cls, manager=self.versioning_manager, plugins=plugins, ) # Register models that have been loaded beforehand. builder = self.versioning_manager.builder for tbl in database.metadata.tables.values(): builder.instrument_versioned_classes( database.mapper, get_class_by_table(database.Model, tbl) )
def setup_method(self, method): # Mock the event registering of Flask-SQLAlchemy. Currently there is no # way of unregistering Flask-SQLAlchemy event listeners, hence the # event listeners would affect other tests. flexmock(_SessionSignalEvents).should_receive('register') self.db = SQLAlchemy() make_versioned() self.create_models() sa.orm.configure_mappers() self.app = Flask(__name__) self.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' self.db.init_app(self.app) self.app.secret_key = 'secret' self.app.debug = True self.client = self.app.test_client() self.context = self.app.test_request_context() self.context.push() self.db.create_all()
import pkg_resources import uuid from invenio_db import db from sqlalchemy_continuum import make_versioned from sqlalchemy_utils.models import Timestamp from sqlalchemy_utils.types import JSONType, UUIDType try: pkg_resources.get_distribution('invenio_accounts') except pkg_resources.DistributionNotFound: user_cls = None else: from invenio_accounts.models import User as user_cls make_versioned(user_cls=user_cls) class RecordMetadata(db.Model, Timestamp): """Represent a record metadata inside the SQL database. Additionally it contains two columns ``created`` and ``updated`` with automatically managed timestamps. """ # Enables SQLAlchemy-Continuum versioning __versioned__ = {} __tablename__ = 'records_metadata' id = db.Column(
install_logging = False naming_convention = { "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_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", "pk": "pk_%(table_name)s" } db = SQLAlchemy(metadata=MetaData(naming_convention=naming_convention)) cache = Cache() csrf = CsrfProtect() migrate = Migrate() manager = VersioningManager(options={'strategy': 'subquery'}) make_versioned(manager=manager, plugins=[FlaskPlugin()]) mail = Mail() cdn = CDN() login_manager = LoginManager() assets = Environment() toolbar = DebugToolbarExtension() gocardless_client = None pyscss = get_filter('pyscss', style='compressed') assets.register('css_main', Bundle('css/main.scss', output='gen/main-packed.css', depends='css/*.scss', filters=pyscss)) assets.register('css_admin', Bundle('css/admin.scss', output='gen/admin-packed.css', depends='css/*.scss',
from flask import _request_ctx_stack from flask_sqlalchemy import SQLAlchemy from sqlalchemy_continuum import make_versioned from sqlalchemy_continuum.plugins import FlaskPlugin from sqlalchemy_utils import force_auto_coercion from memorizer.user import get_user def fetch_current_user_id(): # Return None if we are outside of request context. if _request_ctx_stack.top is None: return return getattr(get_user(), 'id', None) db = SQLAlchemy() force_auto_coercion() make_versioned( plugins=[FlaskPlugin(current_user_id_factory=fetch_current_user_id)])
from flask import _request_ctx_stack from flask_sqlalchemy import SQLAlchemy from sqlalchemy_continuum import make_versioned from sqlalchemy_continuum.plugins import FlaskPlugin from sqlalchemy_utils import force_auto_coercion from memorizer.user import get_user def fetch_current_user_id(): # Return None if we are outside of request context. if _request_ctx_stack.top is None: return return getattr(get_user(), 'id', None) db = SQLAlchemy() force_auto_coercion() make_versioned(plugins=[FlaskPlugin(current_user_id_factory=fetch_current_user_id)])
def test_versioning(native_versioning, versioning_strategy, property_mod_tracking): transaction_column_name = 'transaction_id' end_transaction_column_name = 'end_transaction_id' plugins = [TransactionChangesPlugin(), TransactionMetaPlugin()] if property_mod_tracking: plugins.append(PropertyModTrackerPlugin()) transaction_cls = TransactionFactory() user_cls = None Model = declarative_base() options = { 'create_models': True, 'native_versioning': native_versioning, 'base_classes': (Model, ), 'strategy': versioning_strategy, 'transaction_column_name': transaction_column_name, 'end_transaction_column_name': end_transaction_column_name, } make_versioned(options=options) dns = 'postgresql://*****:*****@localhost/sqlalchemy_continuum_test' versioning_manager.plugins = plugins versioning_manager.transaction_cls = transaction_cls versioning_manager.user_cls = user_cls engine = create_engine(dns) # engine.echo = True class Article(Model): __tablename__ = 'article' __versioned__ = copy(options) id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) name = sa.Column(sa.Unicode(255), nullable=False) content = sa.Column(sa.UnicodeText) description = sa.Column(sa.UnicodeText) class Tag(Model): __tablename__ = 'tag' __versioned__ = copy(options) id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) article_id = sa.Column(sa.Integer, sa.ForeignKey(Article.id)) article = sa.orm.relationship(Article, backref='tags') sa.orm.configure_mappers() connection = engine.connect() Model.metadata.create_all(connection) Session = sessionmaker(bind=connection) session = Session(autoflush=False) session.execute('CREATE EXTENSION IF NOT EXISTS hstore') Model.metadata.create_all(connection) start = time() for i in range(20): for i in range(20): session.add(Article(name=u'Article', tags=[Tag(), Tag()])) session.commit() print 'Testing with:' print ' native_versioning=%r' % native_versioning print ' versioning_strategy=%r' % versioning_strategy print ' property_mod_tracking=%r' % property_mod_tracking print colored('%r seconds' % (time() - start), 'red') Model.metadata.drop_all(connection) remove_versioning() versioning_manager.reset() session.close_all() session.expunge_all() Model.metadata.drop_all(connection) engine.dispose() connection.close()
import sqlalchemy_continuum def fetch_current_user(): from flask.globals import _app_ctx_stack, _request_ctx_stack from flask import g if _app_ctx_stack.top is None or _request_ctx_stack.top is None: return try: return g.current_user.id except AttributeError: return sqlalchemy_continuum.make_versioned( plugins=[sqlalchemy_continuum.plugins.FlaskPlugin(fetch_current_user)]) from .role import Role, Permission from .user import User from .icd10 import Icd10Modifier, Icd10ModifierClass, Icd10Class from .patient import Patient from .address import Address from .bed import Bed from .ward import Ward from .department import Department from .hospital import Hospital from .problem_encounter import problem_encounter_association_table from .problem import Problem from .notes import Note,\ History from .encounters import Encounter,\
from flask import Flask, request, g, abort from flask_sqlalchemy import SQLAlchemy from flask_babelex import Babel from flask_migrate import Migrate from flask_wtf import CsrfProtect from functools import wraps from sqlalchemy_continuum.plugins import FlaskPlugin from sqlalchemy_continuum import make_versioned from .util.page import PathToSlugConvertor app = Flask("canella") # Configuration app.config.from_pyfile('config.py') app.url_map.converters['slug'] = PathToSlugConvertor # Extentions db = SQLAlchemy(app) make_versioned(plugins=[FlaskPlugin()]) babel = Babel(app) migrate = Migrate(app=app, db=db) csrf = CsrfProtect(app) from .main import *
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test for SQLAlchemy, Alembic, sqlalchemy-continuum """ from __future__ import unicode_literals, division, absolute_import, \ print_function from sqlalchemy import Table, Column, Integer, String, Boolean, DateTime,\ Sequence, ForeignKey, MetaData from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy_continuum import make_versioned make_versioned() Base = declarative_base(metadata=MetaData(schema='continuum')) customer_roles_table = Table('customer_roles', Base.metadata, Column('customerid', Integer, ForeignKey('customers.id'), primary_key=True), Column('roleid', Integer, ForeignKey('roles.id'), primary_key=True)) class Customer(Base): """Customer account.""" __versioned__ = {} __tablename__ = 'customers'
from flask import Flask, url_for from flask.ext.login import LoginManager import sqlalchemy as sa from sqlalchemy_continuum import make_versioned, versioning_manager from sqlalchemy_continuum.ext.flask import ( versioning_manager as flask_versioning_manager ) from tests import TestCase make_versioned(manager=flask_versioning_manager) class TestFlaskVersioningManager(TestCase): def setup_class(cls): versioning_manager.options['versioning'] = False flask_versioning_manager.options['versioning'] = True def teardown_class(cls): versioning_manager.options['versioning'] = True flask_versioning_manager.options['versioning'] = False def setup_method(self, method): TestCase.setup_method(self, method) self.app = Flask(__name__) self.app.secret_key = 'secret' self.app.debug = True self.setup_views() login_manager = LoginManager() login_manager.init_app(self.app) self.client = self.app.test_client()
import sqlalchemy as sa from six import PY3 from pytest import mark from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy_continuum import make_versioned, versioning_manager from sqlalchemy_continuum.ext.flask import ( versioning_manager as flask_versioning_manager ) warnings.simplefilter('error', sa.exc.SAWarning) make_versioned(options={'strategy': 'subquery'}) class QueryPool(object): queries = [] @sa.event.listens_for(sa.engine.Engine, 'before_cursor_execute') def log_sql( conn, cursor, statement, parameters, context, executemany ):
def test_versioning( native_versioning, versioning_strategy, property_mod_tracking ): transaction_column_name = 'transaction_id' end_transaction_column_name = 'end_transaction_id' plugins = [TransactionChangesPlugin(), TransactionMetaPlugin()] if property_mod_tracking: plugins.append(PropertyModTrackerPlugin()) transaction_cls = TransactionFactory() user_cls = None Model = declarative_base() options = { 'create_models': True, 'native_versioning': native_versioning, 'base_classes': (Model, ), 'strategy': versioning_strategy, 'transaction_column_name': transaction_column_name, 'end_transaction_column_name': end_transaction_column_name, } make_versioned(options=options) dns = 'postgres://postgres@localhost/sqlalchemy_continuum_test' versioning_manager.plugins = plugins versioning_manager.transaction_cls = transaction_cls versioning_manager.user_cls = user_cls engine = create_engine(dns) # engine.echo = True connection = engine.connect() class Article(Model): __tablename__ = 'article' __versioned__ = copy(options) id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) name = sa.Column(sa.Unicode(255), nullable=False) content = sa.Column(sa.UnicodeText) description = sa.Column(sa.UnicodeText) class Tag(Model): __tablename__ = 'tag' __versioned__ = copy(options) id = sa.Column(sa.Integer, autoincrement=True, primary_key=True) article_id = sa.Column(sa.Integer, sa.ForeignKey(Article.id)) article = sa.orm.relationship(Article, backref='tags') sa.orm.configure_mappers() Model.metadata.create_all(connection) Session = sessionmaker(bind=connection) session = Session(autoflush=False) session.execute('CREATE EXTENSION IF NOT EXISTS hstore') Model.metadata.create_all(connection) start = time() for i in range(20): for i in range(20): session.add(Article(name=u'Article', tags=[Tag(), Tag()])) session.commit() print 'Testing with:' print ' native_versioning=%r' % native_versioning print ' versioning_strategy=%r' % versioning_strategy print ' property_mod_tracking=%r' % property_mod_tracking print colored('%r seconds' % (time() - start), 'red') Model.metadata.drop_all(connection) remove_versioning() versioning_manager.reset() session.close_all() session.expunge_all() Model.metadata.drop_all(connection) engine.dispose() connection.close()
from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy_continuum import make_versioned from sqlalchemy_continuum.plugins import FlaskPlugin make_versioned(plugins=[FlaskPlugin()], options={'strategy': 'subquery'}) db = SQLAlchemy()
LoggingMode, get_ip_if_allowed, version_privacy_predicate, ) make_versioned( user_cls=None, manager=ConditionalVersioningManager( # Conditionally Disable the versioning based on each # project's privacy preferences tracking_predicate=version_privacy_predicate, # Patch in a fix to a SQLAchemy-Continuum Bug. # See patch_sqlalchemy_continuum.py builder=PatchedBuilder(), ), plugins=[ FlaskPlugin( # Redirect to our own function, which respects user preferences # on IP address collection remote_addr_factory=get_ip_if_allowed, # Suppress the plugin's attempt to grab a user id, # which imports the flask_login module (causing an error) current_user_id_factory=lambda: None, ) ], ) db = SQLAlchemy() class Project(db.Model):
return self.create(model, defaults, **kwargs) csp = { 'default-src': '\'self\'', 'style-src': '\'self\'', 'font-src': '\'self\'', 'form-action': '\'self\'' } db = SQLAlchemy() db.get = MethodType(db_get, db) db.create = MethodType(db_create, db) db.get_or_create = MethodType(db_get_or_create, db) make_versioned(plugins=[FlaskPlugin(), PropertyModTrackerPlugin()]) migrate = Migrate(db=db, directory=SQLALCHEMY_MIGRATE_REPO) talisman = Talisman() login_manager = LoginManager() tracker = Blueprint('tracker', __name__) def create_app(script_info=None): app = Flask(__name__) app.config.from_object('config') db.init_app(app) migrate.init_app(app) orm.configure_mappers() talisman.init_app(
from flask import _app_ctx_stack, _request_ctx_stack, g from sqlalchemy.orm import configure_mappers from sqlalchemy_continuum import make_versioned from sqlalchemy_continuum.plugins import FlaskPlugin, PropertyModTrackerPlugin def fetch_current_user_id(): """Fetch the current user id value for version logging and auditing""" try: return g.current_user.id except AttributeError: return make_versioned(plugins=[FlaskPlugin(current_user_id_factory=fetch_current_user_id), PropertyModTrackerPlugin()]) from . import user, role, app_permission, app_group, source_data from .fhir import address, codesets, email_address, organization, patient, phone_number configure_mappers()
# Copyright © 2019 Province of British Columbia # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Create SQLAlchenmy and Schema managers. These will get initialized by the application using the models """ from flask_marshmallow import Marshmallow from flask_sqlalchemy import SQLAlchemy from sqlalchemy_continuum import make_versioned from sqlalchemy_continuum.plugins import ActivityPlugin # by convention in the Flask community these are lower case, # whereas pylint wants them upper case ma = Marshmallow() # pylint: disable=invalid-name db = SQLAlchemy() # pylint: disable=invalid-name activity_plugin = ActivityPlugin() # pylint: disable=invalid-name make_versioned(user_cls=None, plugins=[activity_plugin])
"""Copyright 2015 Rafal Kowalski""" from flask.ext.sqlalchemy import SQLAlchemy from sqlalchemy_continuum import make_versioned from sqlalchemy_continuum.plugins import FlaskPlugin make_versioned(plugins=[FlaskPlugin()], options={"strategy": "subquery"}) db = SQLAlchemy()
from sqlalchemy_continuum import make_versioned import sqlalchemy as sa from flask_continuum import VersioningMixin from db import db from datetime import datetime from cerberus import Validator make_versioned(user_cls=None) class BrandCategoryModel(db.Model, VersioningMixin): __versioned__ = {} __tablename__ = 'brandcategory' category_id = db.Column(db.Integer, primary_key=True, autoincrement=True) token = db.Column(db.Unicode(80)) category_name = db.Column(db.Unicode(255)) logo = db.Column(db.Unicode(255)) created_by = db.Column(db.Integer) created_on = db.Column(db.DateTime) modified_by = db.Column(db.Integer) modified_on = db.Column(db.DateTime) deleted_by = db.Column(db.Integer) deleted_on = db.Column(db.DateTime) sa.orm.configure_mappers() def __init__(self, category_name, logo): self.category_name = category_name self.logo = logo
from flask_sqlalchemy import SQLAlchemy from sqlalchemy_continuum import make_versioned from sqlalchemy_continuum.plugins import FlaskPlugin make_versioned(plugins=[FlaskPlugin()], options={ 'strategy': 'subquery' }) db = SQLAlchemy()
# # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from flask.ext.babel import Babel from flask.ext.login import LoginManager from flask.ext.mail import Mail from flask.ext.sqlalchemy import SQLAlchemy from flask_wtf.csrf import CsrfProtect from raven.contrib.flask import Sentry from sqlalchemy_continuum import make_versioned csrf = CsrfProtect() db = SQLAlchemy() login_manager = LoginManager() mail = Mail() sentry = Sentry() babel = Babel() make_versioned(user_cls=None)
import pkg_resources import uuid from invenio_db import db from sqlalchemy_continuum import make_versioned from sqlalchemy_utils.models import Timestamp from sqlalchemy_utils.types import JSONType, UUIDType try: pkg_resources.get_distribution('invenio_accounts') except pkg_resources.DistributionNotFound: user_cls = None else: from invenio_accounts.models import User as user_cls make_versioned(user_cls=user_cls) class RecordMetadata(db.Model, Timestamp): """Represent a record metadata inside the SQL database. Additionally it contains two columns ``created`` and ``updated`` with automatically managed timestamps. """ # Enables SQLAlchemy-Continuum versioning __versioned__ = {} __tablename__ = 'record' id = db.Column(
from sqlalchemy_continuum.plugins import TransactionMetaPlugin from sqlalchemy.orm import mapper from sqlalchemy.orm.interfaces import * from sqlalchemy import event from flask import current_app import copy import types from sqlalchemy import inspect as sainspect import inspect from silverflask import db from silverflask.helper import classproperty meta_plugin = TransactionMetaPlugin() make_versioned(plugins=[meta_plugin]) import logging logger = logging.getLogger("SilverFlask") versioned_classes = [] versioned_tables = [] created_tables = [] def create_live_table(cls): tablename = cls.__tablename__ + "_live" if tablename in created_tables or cls.__tablename__ in created_tables: return created_tables.append(tablename)
import math from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from werkzeug.security import generate_password_hash, check_password_hash from markdown import markdown import bleach from flask import current_app, request, url_for from flask.ext.login import UserMixin, AnonymousUserMixin, current_user from . import db, login_manager from .exceptions import ValidationError import sqlalchemy as sa from sqlalchemy_continuum import make_versioned from sqlalchemy_continuum.plugins import ActivityPlugin, FlaskPlugin activity_plugin = ActivityPlugin() make_versioned(plugins=[activity_plugin, FlaskPlugin()]) class Permission: FOLLOW = 0x01 COMMENT = 0x02 ASK = 0x04 ANSWER = 0x08 MODERATE_COMMENTS = 0x10 ADMINISTER = 0x80 class Role(db.Model): __tablename__ = 'roles' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True)
from sqlalchemy_continuum.plugins import FlaskPlugin from sqlalchemy_continuum import make_versioned, version_class from flask.globals import _app_ctx_stack, _request_ctx_stack def fetch_current_user_id(): from flask.ext.login import current_user # Return None if we are outside of request context. if _app_ctx_stack.top is None or _request_ctx_stack.top is None: return try: return current_user.user_id except AttributeError: return flask_plugin = FlaskPlugin(current_user_id_factory=fetch_current_user_id) make_versioned(plugins=[flask_plugin]) from .permission import Permission from .role import Role from .user import User from .gtfs import * orm.configure_mappers() from .tag import Tag from .tag import AgencyTag
from sqlalchemy import Column, Integer, String, ForeignKey, Sequence, UniqueConstraint, Unicode from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, validates, configure_mappers from sqlalchemy_continuum import make_versioned from sqlalchemy_continuum.plugins import FlaskPlugin, PropertyModTrackerPlugin, TransactionChangesPlugin make_versioned(plugins=[ FlaskPlugin(), PropertyModTrackerPlugin(), TransactionChangesPlugin() ], user_cls=None) Schema = declarative_base() class Pack(Schema): """ :type id: int :type name: str :type instances: List[Instance] :type parent_id: int :type parent: Pack|None """ __tablename__ = 'packs' __versioned__ = {} id = Column(Integer, Sequence('pack_id_seq'), primary_key=True) name = Column(String(255), unique=True, nullable=False) instances = relationship('Instance',