def test_sqlalchemy_version(): def parse_int(s): try: return int(s) except ValueError: return -1 sqla_version_info = tuple(map(parse_int, __version__.split('.')[:3])) assert sqla_version_info >= SQLA_COMPAT_VERSION_INFO assert __version__.split('.')[:3] >= SQLA_COMPAT_VERSION.split('.')[:2]
def register(session, initial_state=STATUS_ACTIVE, transaction_manager=zope_transaction.manager, keep_session=False): """Register ZopeTransaction listener events on the given Session or Session factory/class. This function requires at least SQLAlchemy 0.7 and makes use of the newer sqlalchemy.event package in order to register event listeners on the given Session. The session argument here may be a Session class or subclass, a sessionmaker or scoped_session instance, or a specific Session instance. Event listening will be specific to the scope of the type of argument passed, including specificity to its subclass as well as its identity. """ from sqlalchemy import __version__ assert tuple(int(x) for x in __version__.split(".")) >= (0, 7), \ "SQLAlchemy version 0.7 or greater required to use register()" from sqlalchemy import event ext = ZopeTransactionExtension( initial_state=initial_state, transaction_manager=transaction_manager, keep_session=keep_session, ) event.listen(session, "after_begin", ext.after_begin) event.listen(session, "after_attach", ext.after_attach) event.listen(session, "after_flush", ext.after_flush) event.listen(session, "after_bulk_update", ext.after_bulk_update) event.listen(session, "after_bulk_delete", ext.after_bulk_delete) event.listen(session, "before_commit", ext.before_commit)
def edit(self, for_package_id=None, from_app_id=None): """ Add/Edit an application record, after submission the browser will be redirected to the referer page """ if not userinfo.is_admin(): controller.http_redirect(controller.base_url() + '/login/') # We need these to fill the combo box # do it here to avoid autoflush later categories = ApplicationsCategory.query.all() source_package = None application = None # the app info can be loaded from an app_id or for a package id if from_app_id: application = app_by_id(from_app_id) if not application: return "Application ID not found" elif for_package_id: package_id = for_package_id package = Package.query.filter_by(id=package_id).one() if not package: return "Package id %d not found" % package_id source_package = package.source or package.package if source_package: # we got a package hint application = Application.query.filter_by(\ source_package = source_package).first() if not application: # app was not found, create new application = Application() application.source_package = source_package # Automatically set app name to source package # usefull hint on "for_package_id" if not application.name: application.name = source_package # No changes here, save will be performed on edit_submit database.rollback() if sa_version.split(".") < ["0", "5", "0"]: database.clear() # Set the screenshot filename screenshot_filename = "" id = application.id if id: screenshot_filename = "/media/screens/%d/%d_t.png" % (id, id) return template.render("app_edit.html" \ , application = application \ , categories = categories \ , screenshot_filename = screenshot_filename \ )
def edit(self, for_package_id = None, from_app_id = None): """ Add/Edit an application record, after submission the browser will be redirected to the referer page """ if not userinfo.is_admin(): controller.http_redirect(controller.base_url()+'/login/') # We need these to fill the combo box # do it here to avoid autoflush later categories = ApplicationsCategory.query.all() source_package = None application = None # the app info can be loaded from an app_id or for a package id if from_app_id: application = app_by_id(from_app_id) if not application: return "Application ID not found" elif for_package_id: package_id = for_package_id package = Package.query.filter_by(id = package_id).one() if not package: return "Package id %d not found" % package_id source_package = package.source or package.package if source_package: # we got a package hint application = Application.query.filter_by(\ source_package = source_package).first() if not application: # app was not found, create new application = Application() application.source_package = source_package # Automatically set app name to source package # usefull hint on "for_package_id" if not application.name: application.name = source_package # No changes here, save will be performed on edit_submit database.rollback() if sa_version.split(".") < ["0", "5", "0"]: database.clear() # Set the screenshot filename screenshot_filename = "" id = application.id if id: screenshot_filename = "/media/screens/%d/%d_t.png" % (id, id) return template.render("app_edit.html" \ , application = application \ , categories = categories \ , screenshot_filename = screenshot_filename \ )
def setup_once(): # type: () -> None try: version = tuple(map(int, SQLALCHEMY_VERSION.split("b")[0].split("."))) except (TypeError, ValueError): raise DidNotEnable( "Unparsable SQLAlchemy version: {}".format(SQLALCHEMY_VERSION) ) if version < (1, 2): raise DidNotEnable("SQLAlchemy 1.2 or newer required.") listen(Engine, "before_cursor_execute", _before_cursor_execute) listen(Engine, "after_cursor_execute", _after_cursor_execute) listen(Engine, "handle_error", _handle_error)
def patch(patch_none='empty'): from sqlalchemy import __version__ if tuple(map(int, __version__.split('.')[:2])) >= (0, 9): def f(func, exception=False): def _construct(cls, operator, continue_on, skip_on, *clauses, **kw): c = [] for clause in clauses: if clause is not None: c.append(clause) else: if exception: raise Exception("Found None condition, in %r" % clauses) return func(operator, continue_on, skip_on, *c, **kw) return _construct import sqlalchemy.sql.elements as exp _f = f(exp.BooleanClauseList._construct, patch_none=='exception') exp.BooleanClauseList._construct = classmethod(_f)
def engine(connection_string=None): global _engines connection_string = connection_string or oz.settings["db"] if connection_string not in _engines: kwargs = dict(echo=oz.settings["debug_sql"]) if oz.settings["db_pool_size"]: kwargs["pool_size"] = oz.settings["db_pool_size"] if oz.settings["db_max_overflow"]: kwargs["max_overflow"] = oz.settings["db_max_overflow"] if oz.settings["db_pool_timeout"]: kwargs["pool_timeout"] = oz.settings["db_pool_timeout"] if oz.settings["db_pool_pre_ping"]: major, minor, *patch = sa_version.split(".") major = int(major) minor = int(minor) if patch: patch, *_ = patch[0].split("b") patch = int(patch) else: patch = None # Do not cast patch, as it could be beta/alpha .. may not even exist. if major > 1 and (minor > 2 or (minor == 2 and patch and patch >= 3)): # We can use the native pool_pre_ping kwargs["pool_pre_ping"] = oz.settings["db_pool_pre_ping"] else: # We are on an old version of pg. Use the event-based # pre-ping event.listen(Engine, "engine_connect", _ping_connection) first_engine = len(_engines) == 0 _engines[connection_string] = create_engine(connection_string, **kwargs) if first_engine: after_fork.registered = True register_after_fork(after_fork, after_fork) return _engines[connection_string]
import json import pickle import zlib from pybald.db import engine, dump_engine from pybald.util import camel_to_underscore, pluralize import project # from project import mc # from sqlalchemy.orm.interfaces import SessionExtension from sqlalchemy.ext.mutable import Mutable from sqlalchemy import __version__ as sa_ver sa_maj_ver, sa_min_ver, sa_rev_ver = sa_ver.split(".") if int(sa_min_ver) >= 7: from sqlalchemy.orm.attributes import flag_modified else: from sqlalchemy.orm.attributes import instance_dict, NO_VALUE def flag_modified(instance, key): state, dict_ = instance_state(instance), instance_dict(instance) impl = state.manager[key].impl state.modified_event(dict_, impl, True, NO_VALUE) session_args = {} if project.green:
# Copyright (C) 2007 Alexandre Conrad, alexandre (dot) conrad (at) gmail (dot) com # # This module is part of FormAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import cgi import warnings import logging from six import string_types logger = logging.getLogger('formalchemy.' + __name__) MIN_SA_VERSION = '0.5' from sqlalchemy import __version__ if __version__.split('.') < MIN_SA_VERSION.split('.'): raise ImportError('Version %s or later of SQLAlchemy required' % MIN_SA_VERSION) from sqlalchemy.orm.attributes import InstrumentedAttribute from sqlalchemy.orm.properties import SynonymProperty, CompositeProperty from sqlalchemy.orm import configure_mappers, object_session, class_mapper from sqlalchemy.orm.session import Session from sqlalchemy.orm.scoping import ScopedSession from sqlalchemy.orm.dynamic import DynamicAttributeImpl from sqlalchemy.orm.exc import UnmappedInstanceError from sqlalchemy.util import OrderedDict from formalchemy import multidict try: from werkzeug.datastructures import MultiDict as WerkzeugMD except ImportError: class WerkzeugMD:
# -*- coding: utf-8 -*- from cherrypy.process import plugins from sqlalchemy import create_engine, MetaData, __version__ as sa_version from sqlalchemy.orm import scoped_session, sessionmaker __all__ = ['SAEnginePlugin'] if sa_version.split('.') < ['0', '7', '4']: raise ImportError('Version 0.7.4 or later of SQLAlchemy required.') class SAEnginePlugin(plugins.SimplePlugin): """ SQLAlchemy integration for CherryPy =================================== Usage: In your application configuration: [sqlalchemy] engine.url = "postgresql+psycopg2://user:password@host/db" engine.echo = False engine.echo_pool = False engine.pool_size = 5 engine.pool_timeout = 30 engine.pool_recycle = -1 engine.max_overflow = 10 engine.convert_unicode = False
# (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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import sys import os from collections import namedtuple from sqlalchemy import __version__ as sql_version sqlalchemy_version2 = ([int(x) for x in sql_version.split('.')] >= [2,0,0]) # if installed via pip this variable is set to true (empty file with name .HOMEDIR present) HOME_CONFIG = os.path.isfile(os.path.join(os.path.dirname(os.path.abspath(__file__)), '.HOMEDIR')) #In executables updater is not available, so variable is set to False there UPDATER_AVAILABLE = True # Base dir is parent of current file, necessary if called from different folder BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),os.pardir)) STATIC_DIR = os.path.join(BASE_DIR, 'cps', 'static') TEMPLATES_DIR = os.path.join(BASE_DIR, 'cps', 'templates') TRANSLATIONS_DIR = os.path.join(BASE_DIR, 'cps', 'translations') if HOME_CONFIG: home_dir = os.path.join(os.path.expanduser("~"),".calibre-web")
# | KIND, either express or implied. See the License for the specific | # | language governing permissions and limitations under the License. | # +--------------------------------------------------------------------------+ # | Authors: Alex Pitigoi, Abhigyan Agrawal, Rahul Priyadarshi | # | Contributors: Jaimy Azle, Mike Bayer | # +--------------------------------------------------------------------------+ from .base import DB2ExecutionContext, DB2Dialect from sqlalchemy import processors, types as sa_types, util from sqlalchemy import __version__ as SA_Version from sqlalchemy.exc import ArgumentError if util.py3k: long = int SA_Version = [long(ver_token) for ver_token in SA_Version.split('.')[0:2]] if SA_Version < [0, 8]: from sqlalchemy.engine.base import ResultProxy else: from sqlalchemy.engine import ResultProxy class _IBM_Numeric_ibm_db(sa_types.Numeric): def result_processor(self, dialect, coltype): if self.asdecimal: return None else: return processors.to_float
If you set *echo* to True, SQLAlchemy will print the SQL statements. *convert_unicode* should always be True and you should always use unicode strings with SQLAlchemy! When you are at the interpreter you can do: from sqlalchemy_tool import configure_session_for_app configure_session_for_app(your_cherrypy_app) """ from sqlalchemy import MetaData, create_engine, __version__ as sa_version from sqlalchemy.orm import scoped_session, sessionmaker if sa_version.split(".") < ["0", "5", "0"]: raise ImportError("Version 0.5 or later of SQLAlchemy required.") metadata = MetaData() session = scoped_session(sessionmaker(autoflush=True, autocommit=False)) mapper = session.mapper # A dict in which keys are connection strings and values are SA engine objects _engines = {} def configure_session(dburi="sqlite:///database.sqlite", echo=False, convert_unicode=True): """This function is called on each request. Tool configuration is automatically passed to it as arguments. It gets a *dburi*, creates a corresponding SQLAlchemy engine if it doesn't exist,
""" import datetime, re from sqlalchemy import types as sa_types from sqlalchemy import schema as sa_schema from sqlalchemy import util from sqlalchemy.sql import compiler from sqlalchemy.sql import operators from sqlalchemy.engine import default from sqlalchemy import __version__ as SA_Version from . import reflection as ibm_reflection from sqlalchemy.types import BLOB, CHAR, CLOB, DATE, DATETIME, INTEGER,\ SMALLINT, BIGINT, DECIMAL, NUMERIC, REAL, TIME, TIMESTAMP,\ VARCHAR, FLOAT SA_Version = [int(ver_token) for ver_token in SA_Version.split('.')[0:2]] # as documented from: # http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.doc/admin/r0001095.htm RESERVED_WORDS = set( ['activate', 'disallow', 'locale', 'result', 'add', 'disconnect', 'localtime', 'result_set_locator', 'after', 'distinct', 'localtimestamp', 'return', 'alias', 'do', 'locator', 'returns', 'all', 'double', 'locators', 'revoke', 'allocate', 'drop', 'lock', 'right', 'allow', 'dssize', 'lockmax', 'rollback', 'alter', 'dynamic', 'locksize', 'routine', 'and', 'each', 'long', 'row', 'any', 'editproc', 'loop', 'row_number', 'as', 'else', 'maintained', 'rownumber', 'asensitive', 'elseif', 'materialized', 'rows', 'associate', 'enable', 'maxvalue', 'rowset', 'asutime', 'encoding', 'microsecond', 'rrn', 'at', 'encryption', 'microseconds', 'run', 'attributes', 'end', 'minute', 'savepoint', 'audit', 'end-exec', 'minutes', 'schema', 'authorization', 'ending', 'minvalue', 'scratchpad', 'aux', 'erase', 'mode', 'scroll', 'auxiliary', 'escape', 'modifies', 'search', 'before', 'every', 'month', 'second',
### import logging from zope import interface, component from zope.publisher.interfaces import IPublisherRequest, IPublishTraverse from z3c.traverser.interfaces import ITraverserPlugin from z3c.traverser.traverser import PluggableTraverser from alchemist.traversal.interfaces import IManagedContainer from alchemist.traversal.collection import CollectionTraverser from ore.alchemist import sa2zs, interfaces from sqlalchemy import orm, __version__ as sa_version sa_version = map(int, sa_version.split(".")) # logging_setup = False import bungeni.models.interfaces import bungeni.ui.content def catalyst(_context, class_, descriptor, #view_module=None, # !+? interface_module=bungeni.models.interfaces, #container_module=None, # !+? ui_module=bungeni.ui.content,
# 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 sqlalchemy import create_engine, __version__ as sqlalchemy_version from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy.orm.exc import ObjectDeletedError from sqlalchemy.orm.session import object_session from sqlalchemy.orm import object_mapper from cms import config # We need version 0.7.3 because of the __abstract__ keyword. sqlalchemy_version = tuple(int(x) for x in sqlalchemy_version.split(".")) assert sqlalchemy_version >= (0, 7, 3), \ "Please install SQLAlchemy >= 0.7.3." db_string = config.database.replace("%s", config.data_dir) db = create_engine(db_string, echo=config.database_debug, pool_size=20, pool_recycle=120) Session = sessionmaker(db, twophase=config.twophase_commit) ScopedSession = scoped_session(Session) # For two-phases transactions: #Session = sessionmaker(db, twophase=True) # TODO: decide which one of the following is better.
class CommandError(Exception): pass from sqlalchemy import __version__ def _safe_int(value): try: return int(value) except: return 0 _vers = tuple([_safe_int(x) for x in __version__.split(".")]) sqla_06 = _vers > (0, 6) sqla_07 = _vers > (0, 7) if not sqla_06: raise CommandError("SQLAlchemy 0.6 or greater is required. " "Version 0.7 or above required for full featureset.") def requires_07(feature): if not sqla_07: raise CommandError("The %s feature requires " "SQLAlchemy 0.7 or greater." % feature) try: width = int(os.environ['COLUMNS'])
def after_init_apps(sender): from uliweb import orm from uliweb.utils.common import import_attr from uliweb.core.SimpleFrame import __app_alias__ orm.set_debug_query(settings.get_var('ORM/DEBUG_LOG')) orm.set_auto_create(settings.get_var('ORM/AUTO_CREATE')) orm.set_pk_type(settings.get_var('ORM/PK_TYPE')) orm.set_auto_set_model(False) orm.set_lazy_model_init(True) orm.set_check_max_length(settings.get_var('ORM/CHECK_MAX_LENGTH')) orm.set_nullable(settings.get_var('ORM/NULLABLE')) orm.set_server_default(settings.get_var('ORM/SERVER_DEFAULT')) orm.set_manytomany_index_reverse( settings.get_var('ORM/MANYTOMANY_INDEX_REVERSE')) convert_path = settings.get_var('ORM/TABLENAME_CONVERTER') convert = import_attr(convert_path) if convert_path else None orm.set_tablename_converter(convert) patch_none = settings.get_var('ORM/PATCH_NONE') if patch_none: from sqlalchemy import __version__ if tuple(map(int, __version__.split('.')[:2])) >= (0, 9): import sqlalchemy.sql.elements as exp if patch_none == 'empty': exp.and_ = and_empty(exp.and_) elif patch_none == 'exception': exp.and_ = and_exception(exp.and_) #judge if transaction middle has not install then set #AUTO_DOTRANSACTION is False if 'transaction' in settings.MIDDLEWARES: orm.set_auto_transaction_in_web(True) else: orm.set_auto_transaction_in_web( settings.get_var('ORM/AUTO_TRANSACTION_IN_WEB')) orm.set_auto_transaction_in_notweb( settings.get_var('ORM/AUTO_TRANSACTION_IN_NOTWEB')) d = { 'connection_string': settings.get_var('ORM/CONNECTION'), 'connection_type': settings.get_var('ORM/CONNECTION_TYPE'), 'debug_log': settings.get_var('ORM/DEBUG_LOG'), 'connection_args': settings.get_var('ORM/CONNECTION_ARGS'), 'strategy': settings.get_var('ORM/STRATEGY'), } orm.engine_manager.add('default', d) for name, d in settings.get_var('ORM/CONNECTIONS').items(): x = { 'connection_string': d.get('CONNECTION', ''), 'debug_log': d.get('DEBUG_LOG', None), 'connection_args': d.get('CONNECTION_ARGS', {}), 'strategy': d.get('STRATEGY', 'threadlocal'), 'connection_type': d.get('CONNECTION_TYPE', 'long'), 'duplication': d.get('DUPLICATION', False), } orm.engine_manager.add(name, x) if 'MODELS_CONFIG' in settings: for name, v in settings.MODELS_CONFIG.items(): orm.set_model_config(name, v) if 'MODELS' in settings: for name, model_path in settings.MODELS.items(): if not model_path: continue if isinstance(model_path, (str, unicode)): path = model_path else: raise Exception("Model path should be a string but %r found" % model_path) for k, v in __app_alias__.iteritems(): if path.startswith(k): path = v + path[len(k):] break orm.set_model(path, name)
def after_init_apps(sender): from uliweb import orm from uliweb.utils.common import import_attr from uliweb.core.SimpleFrame import __app_alias__ orm.set_debug_query(settings.get_var('ORM/DEBUG_LOG')) orm.set_auto_create(settings.get_var('ORM/AUTO_CREATE')) orm.set_pk_type(settings.get_var('ORM/PK_TYPE')) orm.set_auto_set_model(False) orm.set_lazy_model_init(True) orm.set_check_max_length(settings.get_var('ORM/CHECK_MAX_LENGTH')) orm.set_nullable(settings.get_var('ORM/NULLABLE')) orm.set_server_default(settings.get_var('ORM/SERVER_DEFAULT')) orm.set_manytomany_index_reverse(settings.get_var('ORM/MANYTOMANY_INDEX_REVERSE')) convert_path = settings.get_var('ORM/TABLENAME_CONVERTER') convert = import_attr(convert_path) if convert_path else None orm.set_tablename_converter(convert) patch_none = settings.get_var('ORM/PATCH_NONE') if patch_none: from sqlalchemy import __version__ if tuple(map(int, __version__.split('.')[:2])) >= (0, 9): import sqlalchemy.sql.elements as exp if patch_none == 'empty': exp.and_ = and_empty(exp.and_) elif patch_none == 'exception': exp.and_ = and_exception(exp.and_) #judge if transaction middle has not install then set #AUTO_DOTRANSACTION is False if 'transaction' in settings.MIDDLEWARES: orm.set_auto_transaction_in_web(True) else: orm.set_auto_transaction_in_web(settings.get_var('ORM/AUTO_TRANSACTION_IN_WEB')) orm.set_auto_transaction_in_notweb(settings.get_var('ORM/AUTO_TRANSACTION_IN_NOTWEB')) d = {'connection_string':settings.get_var('ORM/CONNECTION'), 'connection_type':settings.get_var('ORM/CONNECTION_TYPE'), 'debug_log':settings.get_var('ORM/DEBUG_LOG'), 'connection_args':settings.get_var('ORM/CONNECTION_ARGS'), 'strategy':settings.get_var('ORM/STRATEGY'), } orm.engine_manager.add('default', d) for name, d in settings.get_var('ORM/CONNECTIONS').items(): x = {'connection_string':d.get('CONNECTION', ''), 'debug_log':d.get('DEBUG_LOG', None), 'connection_args':d.get('CONNECTION_ARGS', {}), 'strategy':d.get('STRATEGY', 'threadlocal'), 'connection_type':d.get('CONNECTION_TYPE', 'long') } orm.engine_manager.add(name, x) if 'MODELS_CONFIG' in settings: for name, v in settings.MODELS_CONFIG.items(): orm.set_model_config(name, v) if 'MODELS' in settings: for name, model_path in settings.MODELS.items(): if not model_path: continue if isinstance(model_path, (str, unicode)): path = model_path else: raise Exception("Model path should be a string but %r found" % model_path) for k, v in __app_alias__.iteritems(): if path.startswith(k): path = v + path[len(k):] break orm.set_model(path, name)
# 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 sqlalchemy import create_engine, __version__ as sqlalchemy_version from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy.orm.exc import ObjectDeletedError from sqlalchemy.orm.session import object_session from sqlalchemy.orm import object_mapper from cms import config # We need version 0.7.3 because of the __abstract__ keyword. sqlalchemy_version = tuple(int(x) for x in sqlalchemy_version.split(".")) assert sqlalchemy_version >= (0, 7, 3), \ "Please install SQLAlchemy >= 0.7.3." db_string = config.database.replace("%s", config.data_dir) db = create_engine(db_string, echo=config.database_debug, pool_size=20, pool_recycle=120) Session = sessionmaker(db, twophase=config.twophase_commit) ScopedSession = scoped_session(Session) # For two-phases transactions: #Session = sessionmaker(db, twophase=True)
""" This module extends SQLAlchemy and provides additional DDL [#]_ support. .. [#] SQL Data Definition Language """ import re import warnings import sqlalchemy from sqlalchemy import __version__ as _sa_version warnings.simplefilter('always', DeprecationWarning) _sa_version = tuple(int(re.match("\d+", x).group(0)) for x in _sa_version.split(".")) SQLA_07 = _sa_version >= (0, 7) SQLA_08 = _sa_version >= (0, 8) del re del _sa_version from rhodecode.lib.dbmigrate.migrate.changeset.schema import * from rhodecode.lib.dbmigrate.migrate.changeset.constraint import * sqlalchemy.schema.Table.__bases__ += (ChangesetTable,) sqlalchemy.schema.Column.__bases__ += (ChangesetColumn,) sqlalchemy.schema.Index.__bases__ += (ChangesetIndex,) sqlalchemy.schema.DefaultClause.__bases__ += (ChangesetDefaultClause,)
""" SqlAlchemy version tools """ from sqlalchemy import __version__ as SA_VERSION # SqlAlchemy version tuple SA_VERSION_TUPLE: tuple[int, ...] = tuple(map(int, SA_VERSION.split('.'))) # SqlAlchemy minor version: 1.X or 2.X SA_VERSION_MINOR: tuple[int, int] = SA_VERSION_TUPLE[:2] # type: ignore # SqlAlchemy version bools SA_13 = SA_VERSION_MINOR == (1, 3) SA_14 = SA_VERSION_MINOR == (1, 4) SA_20 = SA_VERSION_MINOR == (2, 0)
""" This module extends SQLAlchemy and provides additional DDL [#]_ support. .. [#] SQL Data Definition Language """ import re import warnings import sqlalchemy from sqlalchemy import __version__ as _sa_version warnings.simplefilter('always', DeprecationWarning) _sa_version = tuple(int(re.match("\d+", x).group(0)) for x in _sa_version.split(".")) SQLA_06 = _sa_version >= (0, 6) SQLA_07 = _sa_version >= (0, 7) del re del _sa_version from rhodecode.lib.dbmigrate.migrate.changeset.schema import * from rhodecode.lib.dbmigrate.migrate.changeset.constraint import * sqlalchemy.schema.Table.__bases__ += (ChangesetTable,) sqlalchemy.schema.Column.__bases__ += (ChangesetColumn,) sqlalchemy.schema.Index.__bases__ += (ChangesetIndex,) sqlalchemy.schema.DefaultClause.__bases__ += (ChangesetDefaultClause,)
from __future__ import absolute_import import uuid from sqlalchemy import __version__, types, util from sqlalchemy.dialects import mssql, postgresql from .scalar_coercible import ScalarCoercible sqlalchemy_version = tuple([int(v) for v in __version__.split(".")]) class UUIDType(ScalarCoercible, types.TypeDecorator): """ Stores a UUID in the database natively when it can and falls back to a BINARY(16) or a CHAR(32) when it can't. :: from sqlalchemy_utils import UUIDType import uuid class User(Base): __tablename__ = 'user' # Pass `binary=False` to fallback to CHAR instead of BINARY id = sa.Column( UUIDType(binary=False), primary_key=True, default=uuid.uuid4 )
def checkSqlalchemy(): a_version = __version__.split('.') if len(a_version) > 2 and str(a_version[0]) == str(SA_MAJOR) and str(a_version[1]) <= str(SA_MINOR): return True else: return False
# Copyright (C) 2007 Alexandre Conrad, alexandre (dot) conrad (at) gmail (dot) com # # This module is part of FormAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import cgi import warnings import logging logger = logging.getLogger('formalchemy.' + __name__) MIN_SA_VERSION = '0.4.5' from sqlalchemy import __version__ if __version__.split('.') < MIN_SA_VERSION.split('.'): raise ImportError('Version %s or later of SQLAlchemy required' % MIN_SA_VERSION) from sqlalchemy.orm.attributes import InstrumentedAttribute from sqlalchemy.orm.properties import SynonymProperty from sqlalchemy.orm import compile_mappers, object_session, class_mapper from sqlalchemy.orm.session import Session from sqlalchemy.orm.scoping import ScopedSession from sqlalchemy.orm.dynamic import DynamicAttributeImpl from sqlalchemy.util import OrderedDict import fields, fatypes compile_mappers() # initializes InstrumentedAttributes try: # 0.5
### import logging from zope import interface, component from zope.publisher.interfaces import IPublisherRequest, IPublishTraverse from z3c.traverser.interfaces import ITraverserPlugin from z3c.traverser.traverser import PluggableTraverser from alchemist.traversal.interfaces import IManagedContainer from alchemist.traversal.collection import CollectionTraverser from ore.alchemist import sa2zs, interfaces from sqlalchemy import orm, __version__ as sa_version sa_version = map(int, sa_version.split(".")) # logging_setup = False import bungeni.models.interfaces import bungeni.ui.content def catalyst( _context, class_, descriptor, #view_module=None, # !+? interface_module=bungeni.models.interfaces,
def test_sqlalchemy_version(): assert list(map(int, __version__.split('.')[:2])) == list(VERSION_INFO[:2]) assert __version__.split('.')[:2] == VERSION.split('.')[:2]
""" This module extends SQLAlchemy and provides additional DDL [#]_ support. .. [#] SQL Data Definition Language """ import re import warnings import sqlalchemy from sqlalchemy import __version__ as _sa_version warnings.simplefilter('always', DeprecationWarning) _sa_version = tuple(int(re.match("\d+", x).group(0)) for x in _sa_version.split(".")) SQLA_07 = _sa_version >= (0, 7) SQLA_08 = _sa_version >= (0, 8) del re del _sa_version from migrate.changeset.schema import * from migrate.changeset.constraint import * sqlalchemy.schema.Table.__bases__ += (ChangesetTable, ) sqlalchemy.schema.Column.__bases__ += (ChangesetColumn, ) sqlalchemy.schema.Index.__bases__ += (ChangesetIndex, ) sqlalchemy.schema.DefaultClause.__bases__ += (ChangesetDefaultClause, )
import re import inspect import time import random import uuid class CommandError(Exception): pass from sqlalchemy import __version__ def _safe_int(value): try: return int(value) except: return 0 _vers = tuple([_safe_int(x) for x in __version__.split(".")]) sqla_06 = _vers > (0, 6) sqla_07 = _vers > (0, 7) if not sqla_06: raise CommandError( "SQLAlchemy 0.6 or greater is required. " "Version 0.7 or above required for full featureset.") def requires_07(feature): if not sqla_07: raise CommandError( "The %s feature requires " "SQLAlchemy 0.7 or greater." % feature ) try:
""" This module extends SQLAlchemy and provides additional DDL [#]_ support. .. [#] SQL Data Definition Language """ import re import warnings import sqlalchemy from sqlalchemy import __version__ as _sa_version warnings.simplefilter('always', DeprecationWarning) _sa_version = tuple( int(re.match("\d+", x).group(0)) for x in _sa_version.split(".")) SQLA_06 = _sa_version >= (0, 6) SQLA_07 = _sa_version >= (0, 7) del re del _sa_version from migrate.changeset.schema import * from migrate.changeset.constraint import * sqlalchemy.schema.Table.__bases__ += (ChangesetTable, ) sqlalchemy.schema.Column.__bases__ += (ChangesetColumn, ) sqlalchemy.schema.Index.__bases__ += (ChangesetIndex, ) sqlalchemy.schema.DefaultClause.__bases__ += (ChangesetDefaultClause, )
def test_sqlalchemy_version(): sqla_version_info = list(map(int, __version__.split('.')[:2])) assert sqla_version_info >= list(VERSION_INFO[:2]) assert __version__.split('.')[:2] >= VERSION.split('.')[:2]
def sqla_version_tuple(): from sqlalchemy import __version__ return tuple(int(i) for i in __version__.split("."))
If you set *echo* to True, SQLAlchemy will print the SQL statements. *convert_unicode* should always be True and you should always use unicode strings with SQLAlchemy! When you are at the interpreter you can do: from sqlalchemy_tool import configure_session_for_app configure_session_for_app(your_cherrypy_app) ''' from sqlalchemy import MetaData, create_engine, __version__ as sa_version from sqlalchemy.orm import scoped_session, sessionmaker if sa_version.split(".") < ["0", "5", "0"]: raise ImportError("Version 0.5 or later of SQLAlchemy required.") metadata = MetaData() session = scoped_session(sessionmaker(autoflush=True, autocommit=False)) #mapper = session.mapper # A dict in which keys are connection strings and values are SA engine objects _engines = {} def configure_session(dburi='sqlite:///database.sqlite', echo=False, convert_unicode=True): """This function is called on each request. Tool configuration is automatically passed to it as arguments.