예제 #1
0
def get_history(obj, key, passive=PASSIVE_OFF):
    """Return a :class:`.History` record for the given object 
    and attribute key.

    :param obj: an object whose class is instrumented by the
      attributes package.

    :param key: string attribute name.

    :param passive: indicates if the attribute should be
      loaded from the database if not already present (:attr:`.PASSIVE_NO_FETCH`), and
      if the attribute should be not initialized to a blank value otherwise
      (:attr:`.PASSIVE_NO_INITIALIZE`). Default is :attr:`PASSIVE_OFF`.

    """
    if passive is True:
        util.warn_deprecated("Passing True for 'passive' is deprecated. "
                             "Use attributes.PASSIVE_NO_INITIALIZE")
        passive = PASSIVE_NO_INITIALIZE
    elif passive is False:
        util.warn_deprecated("Passing False for 'passive' is "
                             "deprecated.  Use attributes.PASSIVE_OFF")
        passive = PASSIVE_OFF

    return get_state_history(instance_state(obj), key, passive)
예제 #2
0
파일: base.py 프로젝트: advatar/thevault
 def visit_create_index(self, create):
     preparer = self.preparer
     index = create.element
     text = "CREATE "
     if index.unique:
         text += "UNIQUE "
     text += "INDEX %s ON %s (%s)" \
             % (preparer.quote(
                 self._validate_identifier(index.name, True), index.quote),
                preparer.format_table(index.table),
                ', '.join([preparer.format_column(c) 
                             for c in index.columns]))
     
     if "postgres_where" in index.kwargs:
         whereclause = index.kwargs['postgres_where']
         util.warn_deprecated(
                 "The 'postgres_where' argument has been renamed "
                 "to 'postgresql_where'.")
     elif 'postgresql_where' in index.kwargs:
         whereclause = index.kwargs['postgresql_where']
     else:
         whereclause = None
         
     if whereclause is not None:
         whereclause = sql_util.expression_as_ddl(whereclause)
         where_compiled = self.sql_compiler.process(whereclause)
         text += " WHERE " + where_compiled
     return text
예제 #3
0
    def dbapi(cls):

        warn_deprecated(
            "Google Cloud SQL now recommends creating connections via the "
            "MySQLdb dialect directly, using the URL format "
            "mysql+mysqldb://root@/<dbname>?unix_socket=/cloudsql/"
            "<projectid>:<instancename>"
        )

        # from django:
        # http://code.google.com/p/googleappengine/source/
        #     browse/trunk/python/google/storage/speckle/
        # python/django/backend/base.py#118
        # see also [ticket:2649]
        # see also http://stackoverflow.com/q/14224679/34549
        from google.appengine.api import apiproxy_stub_map

        if _is_dev_environment():
            from google.appengine.api import rdbms_mysqldb
            return rdbms_mysqldb
        elif apiproxy_stub_map.apiproxy.GetStub('rdbms'):
            from google.storage.speckle.python.api import rdbms_apiproxy
            return rdbms_apiproxy
        else:
            from google.storage.speckle.python.api import rdbms_googleapi
            return rdbms_googleapi
예제 #4
0
파일: base.py 프로젝트: dreamwave/rad
 def visit_create_index(self, create):
     preparer = self.preparer
     index = create.element
     text = "CREATE "
     if index.unique:
         text += "UNIQUE "
     text += "INDEX %s ON %s (%s)" \
                 % (preparer.quote(self._validate_identifier(index.name, True), index.quote),
                    preparer.format_table(index.table),
                    ', '.join([preparer.format_column(c) for c in index.columns]))
     
     if "postgres_where" in index.kwargs:
         whereclause = index.kwargs['postgres_where']
         util.warn_deprecated("The 'postgres_where' argument has been renamed to 'postgresql_where'.")
     elif 'postgresql_where' in index.kwargs:
         whereclause = index.kwargs['postgresql_where']
     else:
         whereclause = None
         
     if whereclause is not None:
         compiler = self._compile(whereclause, None)
         # this might belong to the compiler class
         inlined_clause = str(compiler) % dict(
             [(key,bind.value) for key,bind in compiler.binds.iteritems()])
         text += " WHERE " + inlined_clause
     return text
예제 #5
0
 def __init__(self, *args, **kwargs):
     util.warn_deprecated(
         "The Sybase dialect is deprecated and will be removed "
         "in a future version.",
         version="1.4",
     )
     super(SybaseDialect, self).__init__(*args, **kwargs)
예제 #6
0
    def visit_create_index(self, create):
        preparer = self.preparer
        index = create.element
        text = "CREATE "
        if index.unique:
            text += "UNIQUE "
        text += "INDEX %s ON %s (%s)" \
                % (preparer.quote(
                    self._index_identifier(index.name), index.quote),
                   preparer.format_table(index.table),
                   ', '.join([preparer.format_column(c)
                                for c in index.columns]))

        if "postgres_where" in index.kwargs:
            whereclause = index.kwargs['postgres_where']
            util.warn_deprecated(
                "The 'postgres_where' argument has been renamed "
                "to 'postgresql_where'.")
        elif 'postgresql_where' in index.kwargs:
            whereclause = index.kwargs['postgresql_where']
        else:
            whereclause = None

        if whereclause is not None:
            whereclause = sql_util.expression_as_ddl(whereclause)
            where_compiled = self.sql_compiler.process(whereclause)
            text += " WHERE " + where_compiled
        return text
예제 #7
0
def get_history(obj, key, passive=PASSIVE_OFF):
    """Return a :class:`.History` record for the given object 
    and attribute key.

    :param obj: an object whose class is instrumented by the
      attributes package.

    :param key: string attribute name.

    :param passive: indicates if the attribute should be
      loaded from the database if not already present (:attr:`.PASSIVE_NO_FETCH`), and
      if the attribute should be not initialized to a blank value otherwise
      (:attr:`.PASSIVE_NO_INITIALIZE`). Default is :attr:`PASSIVE_OFF`.

    """
    if passive is True:
        util.warn_deprecated("Passing True for 'passive' is deprecated. "
                                "Use attributes.PASSIVE_NO_INITIALIZE")
        passive = PASSIVE_NO_INITIALIZE
    elif passive is False:
        util.warn_deprecated("Passing False for 'passive' is "
                                "deprecated.  Use attributes.PASSIVE_OFF")
        passive = PASSIVE_OFF

    return get_state_history(instance_state(obj), key, passive)
예제 #8
0
    def dbapi(cls):

        warn_deprecated(
            "Google Cloud SQL now recommends creating connections via the "
            "MySQLdb dialect directly, using the URL format "
            "mysql+mysqldb://root@/<dbname>?unix_socket=/cloudsql/"
            "<projectid>:<instancename>")

        # from django:
        # http://code.google.com/p/googleappengine/source/
        #     browse/trunk/python/google/storage/speckle/
        # python/django/backend/base.py#118
        # see also [ticket:2649]
        # see also http://stackoverflow.com/q/14224679/34549
        from google.appengine.api import apiproxy_stub_map

        if _is_dev_environment():
            from google.appengine.api import rdbms_mysqldb

            return rdbms_mysqldb
        elif apiproxy_stub_map.apiproxy.GetStub("rdbms"):
            from google.storage.speckle.python.api import rdbms_apiproxy

            return rdbms_apiproxy
        else:
            from google.storage.speckle.python.api import rdbms_googleapi

            return rdbms_googleapi
예제 #9
0
 def compare_values(self, x, y):
     if self.comparator:
         return self.comparator(x, y)
     elif self.mutable and not hasattr(x, '__eq__') and x is not None:
         util.warn_deprecated("Objects stored with PickleType when mutable=True must implement __eq__() for reliable comparison.")
         return self.pickler.dumps(x, self.protocol) == self.pickler.dumps(y, self.protocol)
     else:
         return x == y
예제 #10
0
 def __init__(self, *args, **kwargs):
     util.warn_deprecated(
         "The firebird dialect is deprecated and will be removed "
         "in a future version. This dialect is superseded by the external "
         "dialect https://github.com/pauldex/sqlalchemy-firebird.",
         version="1.4",
     )
     super(FBDialect, self).__init__(*args, **kwargs)
예제 #11
0
파일: base.py 프로젝트: DavidMartins00/Site
 def __init__(self, *args, **kwargs):
     util.warn_deprecated(
         "The Sybase dialect is deprecated and will be removed "
         "in a future version. This dialect is superseded by the external "
         "dialect https://github.com/gordthompson/sqlalchemy-sybase.",
         version="1.4",
     )
     super(SybaseDialect, self).__init__(*args, **kwargs)
예제 #12
0
 def compare_values(self, x, y):
     if self.comparator:
         return self.comparator(x, y)
     elif self.mutable and not hasattr(x, '__eq__') and x is not None:
         util.warn_deprecated("Objects stored with PickleType when mutable=True must implement __eq__() for reliable comparison.")
         return self.pickler.dumps(x, self.protocol) == self.pickler.dumps(y, self.protocol)
     else:
         return x == y
예제 #13
0
 def __init__(self, class_, *columns, **kwargs):
     if 'comparator' in kwargs:
         util.warn_deprecated("The 'comparator' argument to CompositeProperty is deprecated.  Use comparator_factory.")
         kwargs['comparator_factory'] = kwargs['comparator']
     super(CompositeProperty, self).__init__(*columns, **kwargs)
     self._col_position_map = util.column_dict((c, i) for i, c in enumerate(columns))
     self.composite_class = class_
     self.strategy_class = strategies.CompositeColumnLoader
 def dialect_impl(self, dialect, **kwargs):
     _for_ddl = kwargs.pop("_for_ddl", False)
     if _for_ddl and self.length is None:
         label = util.to_ascii(_for_ddl is True and "" or (' for column "%s"' % str(_for_ddl)))
         util.warn_deprecated(
             "Using String type with no length for CREATE TABLE "
             "is deprecated; use the Text type explicitly" + label
         )
     return TypeEngine.dialect_impl(self, dialect, **kwargs)
예제 #15
0
파일: default.py 프로젝트: babbel4ever/PBI
    def __init__(self,
                 convert_unicode=False,
                 assert_unicode=False,
                 encoding='utf-8',
                 paramstyle=None,
                 dbapi=None,
                 implicit_returning=None,
                 label_length=None,
                 **kwargs):

        if not getattr(self, 'ported_sqla_06', True):
            util.warn(
                "The %s dialect is not yet ported to SQLAlchemy 0.6/0.7" %
                self.name)

        self.convert_unicode = convert_unicode
        if assert_unicode:
            util.warn_deprecated(
                "assert_unicode is deprecated. "
                "SQLAlchemy emits a warning in all cases where it "
                "would otherwise like to encode a Python unicode object "
                "into a specific encoding but a plain bytestring is "
                "received. "
                "This does *not* apply to DBAPIs that coerce Unicode "
                "natively.")

        self.encoding = encoding
        self.positional = False
        self._ischema = None
        self.dbapi = dbapi
        if paramstyle is not None:
            self.paramstyle = paramstyle
        elif self.dbapi is not None:
            self.paramstyle = self.dbapi.paramstyle
        else:
            self.paramstyle = self.default_paramstyle
        if implicit_returning is not None:
            self.implicit_returning = implicit_returning
        self.positional = self.paramstyle in ('qmark', 'format', 'numeric')
        self.identifier_preparer = self.preparer(self)
        self.type_compiler = self.type_compiler(self)

        if label_length and label_length > self.max_identifier_length:
            raise exc.ArgumentError(
                "Label length of %d is greater than this dialect's"
                " maximum identifier length of %d" %
                (label_length, self.max_identifier_length))
        self.label_length = label_length

        if self.description_encoding == 'use_encoding':
            self._description_decoder = processors.to_unicode_processor_factory(
                encoding)
        elif self.description_encoding is not None:
            self._description_decoder = processors.to_unicode_processor_factory(
                self.description_encoding)
        self._encoder = codecs.getencoder(self.encoding)
        self._decoder = processors.to_unicode_processor_factory(self.encoding)
예제 #16
0
 def dialect_impl(self, dialect, **kwargs):
     _for_ddl = kwargs.pop('_for_ddl', False)
     if _for_ddl and self.length is None:
         label = util.to_ascii(_for_ddl is True and ''
                               or (' for column "%s"' % str(_for_ddl)))
         util.warn_deprecated(
             "Using String type with no length for CREATE TABLE "
             "is deprecated; use the Text type explicitly" + label)
     return TypeEngine.dialect_impl(self, dialect, **kwargs)
예제 #17
0
    def __init__(
        self,
        convert_unicode=False,
        assert_unicode=False,
        encoding="utf-8",
        paramstyle=None,
        dbapi=None,
        implicit_returning=None,
        label_length=None,
        **kwargs
    ):

        if not getattr(self, "ported_sqla_06", True):
            util.warn("The %s dialect is not yet ported to SQLAlchemy 0.6/0.7" % self.name)

        self.convert_unicode = convert_unicode
        if assert_unicode:
            util.warn_deprecated(
                "assert_unicode is deprecated. "
                "SQLAlchemy emits a warning in all cases where it "
                "would otherwise like to encode a Python unicode object "
                "into a specific encoding but a plain bytestring is "
                "received. "
                "This does *not* apply to DBAPIs that coerce Unicode "
                "natively."
            )

        self.encoding = encoding
        self.positional = False
        self._ischema = None
        self.dbapi = dbapi
        if paramstyle is not None:
            self.paramstyle = paramstyle
        elif self.dbapi is not None:
            self.paramstyle = self.dbapi.paramstyle
        else:
            self.paramstyle = self.default_paramstyle
        if implicit_returning is not None:
            self.implicit_returning = implicit_returning
        self.positional = self.paramstyle in ("qmark", "format", "numeric")
        self.identifier_preparer = self.preparer(self)
        self.type_compiler = self.type_compiler(self)

        if label_length and label_length > self.max_identifier_length:
            raise exc.ArgumentError(
                "Label length of %d is greater than this dialect's"
                " maximum identifier length of %d" % (label_length, self.max_identifier_length)
            )
        self.label_length = label_length

        if self.description_encoding == "use_encoding":
            self._description_decoder = processors.to_unicode_processor_factory(encoding)
        elif self.description_encoding is not None:
            self._description_decoder = processors.to_unicode_processor_factory(self.description_encoding)
        self._encoder = codecs.getencoder(self.encoding)
        self._decoder = processors.to_unicode_processor_factory(self.encoding)
예제 #18
0
 def __init__(self, class_, *columns, **kwargs):
     if "comparator" in kwargs:
         util.warn_deprecated(
             "The 'comparator' argument to CompositeProperty is deprecated.  Use comparator_factory."
         )
         kwargs["comparator_factory"] = kwargs["comparator"]
     super(CompositeProperty, self).__init__(*columns, **kwargs)
     self._col_position_map = util.column_dict((c, i) for i, c in enumerate(columns))
     self.composite_class = class_
     self.strategy_class = strategies.CompositeColumnLoader
예제 #19
0
 def _pop_deprecated_kwargs(self, kwargs):
     auto_setinputsizes = kwargs.pop("auto_setinputsizes", None)
     exclude_setinputsizes = kwargs.pop("exclude_setinputsizes", None)
     if auto_setinputsizes or exclude_setinputsizes:
         util.warn_deprecated(
             "auto_setinputsizes and exclude_setinputsizes are deprecated. "
             "Modern cx_Oracle only requires that LOB types are part "
             "of this behavior, and these parameters no longer have any "
             "effect.")
     allow_twophase = kwargs.pop("allow_twophase", None)
     if allow_twophase is not None:
         util.warn.deprecated(
             "allow_twophase is deprecated.  The cx_Oracle dialect no "
             "longer supports two-phase transaction mode.")
예제 #20
0
 def _pop_deprecated_kwargs(self, kwargs):
     auto_setinputsizes = kwargs.pop('auto_setinputsizes', None)
     exclude_setinputsizes = kwargs.pop('exclude_setinputsizes', None)
     if auto_setinputsizes or exclude_setinputsizes:
         util.warn_deprecated(
             "auto_setinputsizes and exclude_setinputsizes are deprecated. "
             "Modern cx_Oracle only requires that LOB types are part "
             "of this behavior, and these parameters no longer have any "
             "effect.")
     allow_twophase = kwargs.pop('allow_twophase', None)
     if allow_twophase is not None:
         util.warn.deprecated(
             "allow_twophase is deprecated.  The cx_Oracle dialect no "
             "longer supports two-phase transaction mode."
         )
예제 #21
0
def assign_mapper(ctx, class_, *args, **kwargs):
    util.warn_deprecated(
        "assign_mapper is deprecated. Use scoped_session() instead.")
    extension = kwargs.pop('extension', None)
    if extension is not None:
        extension = util.to_list(extension)
        extension.append(ctx.mapper_extension)
    else:
        extension = ctx.mapper_extension

    validate = kwargs.pop('validate', False)

    if not isinstance(getattr(class_, '__init__'), types.MethodType):

        def __init__(self, **kwargs):
            for key, value in kwargs.items():
                if validate:
                    if not self.mapper.get_property(
                            key, resolve_synonyms=False, raiseerr=False):
                        raise exceptions.ArgumentError(
                            "Invalid __init__ argument: '%s'" % key)
                setattr(self, key, value)

        class_.__init__ = __init__

    class query(object):
        def __getattr__(self, key):
            return getattr(ctx.current.query(class_), key)

        def __call__(self):
            return ctx.current.query(class_)

    if not hasattr(class_, 'query'):
        class_.query = query()

    for name in ('get', 'filter', 'filter_by', 'select', 'select_by',
                 'selectfirst', 'selectfirst_by', 'selectone', 'selectone_by',
                 'get_by', 'join_to', 'join_via', 'count', 'count_by',
                 'options', 'instances'):
        _monkeypatch_query_method(name, ctx, class_)
    for name in ('refresh', 'expire', 'delete', 'expunge', 'update'):
        _monkeypatch_session_method(name, ctx, class_)

    m = mapper(class_, extension=extension, *args, **kwargs)
    class_.mapper = m
    return m
예제 #22
0
    def __init__(self, precision=10, scale=2, asdecimal=True, length=None):
        """
        Construct a Numeric.

        :param precision: the numeric precision for use in DDL ``CREATE TABLE``.

        :param scale: the numeric scale for use in DDL ``CREATE TABLE``.

        :param asdecimal: default True.  If False, values will be
          returned as-is from the DB-API, and may be either
          ``Decimal`` or ``float`` types depending on the DB-API in
          use.

        """
        if length:
            util.warn_deprecated("'length' is deprecated for Numeric.  Use 'scale'.")
            scale = length
        self.precision = precision
        self.scale = scale
        self.asdecimal = asdecimal
예제 #23
0
    def __init__(self, precision=10, scale=2, asdecimal=True, length=None):
        """
        Construct a Numeric.

        :param precision: the numeric precision for use in DDL ``CREATE TABLE``.

        :param scale: the numeric scale for use in DDL ``CREATE TABLE``.

        :param asdecimal: default True.  If False, values will be
          returned as-is from the DB-API, and may be either
          ``Decimal`` or ``float`` types depending on the DB-API in
          use.

        """
        if length:
            util.warn_deprecated("'length' is deprecated for Numeric.  Use 'scale'.")
            scale = length
        self.precision = precision
        self.scale = scale
        self.asdecimal = asdecimal
예제 #24
0
파일: __init__.py 프로젝트: greghaynes/xsbs
def create_session(bind=None, **kwargs):
    """Create a new :class:`~sqlalchemy.orm.session.Session`.

    :param bind: optional, a single Connectable to use for all
      database access in the created
      :class:`~sqlalchemy.orm.session.Session`.

    :param \*\*kwargs: optional, passed through to the
      :class:`Session` constructor.

    :returns: an :class:`~sqlalchemy.orm.session.Session` instance

    The defaults of create_session() are the opposite of that of
    :func:`sessionmaker`; ``autoflush`` and ``expire_on_commit`` are
    False, ``autocommit`` is True.  In this sense the session acts
    more like the "classic" SQLAlchemy 0.3 session with these.

    Usage::

      >>> from sqlalchemy.orm import create_session
      >>> session = create_session()

    It is recommended to use :func:`sessionmaker` instead of
    create_session().

    """
    if 'transactional' in kwargs:
        sa_util.warn_deprecated(
            "The 'transactional' argument to sessionmaker() is deprecated; "
            "use autocommit=True|False instead.")
        if 'autocommit' in kwargs:
            raise TypeError('Specify autocommit *or* transactional, not both.')
        kwargs['autocommit'] = not kwargs.pop('transactional')

    kwargs.setdefault('autoflush', False)
    kwargs.setdefault('autocommit', True)
    kwargs.setdefault('expire_on_commit', False)
    return _Session(bind=bind, **kwargs)
예제 #25
0
def create_session(bind=None, **kwargs):
    """Create a new :class:`~sqlalchemy.orm.session.Session`.

    :param bind: optional, a single Connectable to use for all
      database access in the created
      :class:`~sqlalchemy.orm.session.Session`.

    :param \*\*kwargs: optional, passed through to the
      :class:`Session` constructor.

    :returns: an :class:`~sqlalchemy.orm.session.Session` instance

    The defaults of create_session() are the opposite of that of
    :func:`sessionmaker`; ``autoflush`` and ``expire_on_commit`` are
    False, ``autocommit`` is True.  In this sense the session acts
    more like the "classic" SQLAlchemy 0.3 session with these.

    Usage::

      >>> from sqlalchemy.orm import create_session
      >>> session = create_session()

    It is recommended to use :func:`sessionmaker` instead of
    create_session().

    """
    if 'transactional' in kwargs:
        sa_util.warn_deprecated(
            "The 'transactional' argument to sessionmaker() is deprecated; "
            "use autocommit=True|False instead.")
        if 'autocommit' in kwargs:
            raise TypeError('Specify autocommit *or* transactional, not both.')
        kwargs['autocommit'] = not kwargs.pop('transactional')

    kwargs.setdefault('autoflush', False)
    kwargs.setdefault('autocommit', True)
    kwargs.setdefault('expire_on_commit', False)
    return _Session(bind=bind, **kwargs)
예제 #26
0
파일: shard.py 프로젝트: rlanger/Rondo
# orm/shard.py
# Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php

from sqlalchemy import util

util.warn_deprecated("Horizontal sharding is now importable via "
                     "'import sqlalchemy.ext.horizontal_shard")

from sqlalchemy.ext.horizontal_shard import *
예제 #27
0
    def create_connect_args(self, url):
        opts = dict(url.query)

        for opt in ('use_ansi', 'auto_convert_lobs'):
            if opt in opts:
                util.warn_deprecated(
                    "cx_oracle dialect option %r should only be passed to "
                    "create_engine directly, not within the URL string" % opt)
                util.coerce_kw_type(opts, opt, bool)
                setattr(self, opt, opts.pop(opt))

        database = url.database
        service_name = opts.pop('service_name', None)
        if database or service_name:
            # if we have a database, then we have a remote host
            port = url.port
            if port:
                port = int(port)
            else:
                port = 1521

            if database and service_name:
                raise exc.InvalidRequestError(
                    '"service_name" option shouldn\'t '
                    'be used with a "database" part of the url')
            if database:
                makedsn_kwargs = {'sid': database}
            if service_name:
                makedsn_kwargs = {'service_name': service_name}

            dsn = self.dbapi.makedsn(url.host, port, **makedsn_kwargs)
        else:
            # we have a local tnsname
            dsn = url.host

        if dsn is not None:
            opts['dsn'] = dsn
        if url.password is not None:
            opts['password'] = url.password
        if url.username is not None:
            opts['user'] = url.username

        if self._cx_oracle_threaded is not None:
            opts.setdefault("threaded", self._cx_oracle_threaded)

        def convert_cx_oracle_constant(value):
            if isinstance(value, util.string_types):
                try:
                    int_val = int(value)
                except ValueError:
                    value = value.upper()
                    return getattr(self.dbapi, value)
                else:
                    return int_val
            else:
                return value

        util.coerce_kw_type(opts, 'mode', convert_cx_oracle_constant)
        util.coerce_kw_type(opts, 'threaded', bool)
        util.coerce_kw_type(opts, 'events', bool)
        util.coerce_kw_type(opts, 'purity', convert_cx_oracle_constant)

        return ([], opts)
예제 #28
0
    def __init__(self,
                 auto_convert_lobs=True,
                 coerce_to_unicode=True,
                 coerce_to_decimal=True,
                 arraysize=50,
                 threaded=None,
                 **kwargs):

        OracleDialect.__init__(self, **kwargs)
        self.arraysize = arraysize
        if threaded is not None:
            util.warn_deprecated(
                "The 'threaded' parameter to the cx_oracle dialect "
                "itself is deprecated.  The value now defaults to False in "
                "any case.  To pass an explicit True value, use the "
                "create_engine connect_args dictionary or add ?threaded=true "
                "to the URL string."
            )
            self._cx_oracle_threaded = threaded
        self.auto_convert_lobs = auto_convert_lobs
        self.coerce_to_unicode = coerce_to_unicode
        self.coerce_to_decimal = coerce_to_decimal
        if self._use_nchar_for_unicode:
            self.colspecs = self.colspecs.copy()
            self.colspecs[sqltypes.Unicode] = _OracleUnicodeStringNCHAR
            self.colspecs[sqltypes.UnicodeText] = _OracleUnicodeTextNCLOB

        cx_Oracle = self.dbapi

        if cx_Oracle is None:
            self._include_setinputsizes = {}
            self.cx_oracle_ver = (0, 0, 0)
        else:
            self.cx_oracle_ver = self._parse_cx_oracle_ver(cx_Oracle.version)
            if self.cx_oracle_ver < (5, 2) and self.cx_oracle_ver > (0, 0, 0):
                raise exc.InvalidRequestError(
                    "cx_Oracle version 5.2 and above are supported")

            self._has_native_int = hasattr(cx_Oracle, "NATIVE_INT")

            self._include_setinputsizes = {
                cx_Oracle.NCLOB, cx_Oracle.CLOB, cx_Oracle.LOB,
                cx_Oracle.NCHAR, cx_Oracle.FIXED_NCHAR,
                cx_Oracle.BLOB, cx_Oracle.FIXED_CHAR, cx_Oracle.TIMESTAMP,
                _OracleInteger, _OracleBINARY_FLOAT, _OracleBINARY_DOUBLE
            }

            self._paramval = lambda value: value.getvalue()

            # https://github.com/oracle/python-cx_Oracle/issues/176#issuecomment-386821291
            # https://github.com/oracle/python-cx_Oracle/issues/224
            self._values_are_lists = self.cx_oracle_ver >= (6, 3)
            if self._values_are_lists:
                cx_Oracle.__future__.dml_ret_array_val = True

                def _returningval(value):
                    try:
                        return value.values[0][0]
                    except IndexError:
                        return None

                self._returningval = _returningval
            else:
                self._returningval = self._paramval

        self._is_cx_oracle_6 = self.cx_oracle_ver >= (6, )
예제 #29
0
 def __init__(self, session_factory=None, scopefunc=None):
     warn_deprecated("SessionContext is deprecated.  Use scoped_session().")
     if session_factory is None:
         session_factory=create_session
     super(SessionContext, self).__init__(session_factory, scopefunc=scopefunc)
예제 #30
0
 def __init__(self, *args, **kwargs):
     warn_deprecated("SessionContextExt is deprecated.  Use ScopedSession(enhance_classes=True)")
     super(SessionContextExt, self).__init__(*args, **kwargs)
예제 #31
0
 def do(self, *args, **kwargs):
     query = Query(class_, session=ctx.current)
     util.warn_deprecated('Query methods on the class are deprecated; use %s.query.%s instead' % (class_.__name__, name))
     return getattr(query, name)(*args, **kwargs)
예제 #32
0
 def do(self, *args, **kwargs):
     query = Query(class_, session=ctx.current)
     util.warn_deprecated('Query methods on the class are deprecated; use %s.query.%s instead' % (class_.__name__, name))
     return getattr(query, name)(*args, **kwargs)
예제 #33
0
 def __init__(self, *args, **kwargs):
     """Support implementations that were passing arguments"""
     if args or kwargs:
         util.warn_deprecated("Passing arguments to type object "
                 "constructor %s is deprecated" % self.__class__)
예제 #34
0
    def __init__(self, argument, secondary=None, primaryjoin=None, secondaryjoin=None, entity_name=None, foreign_keys=None, foreignkey=None, uselist=None, private=False, association=None, order_by=False, attributeext=None, backref=None, is_backref=False, post_update=False, cascade=None, viewonly=False, lazy=True, collection_class=None, passive_deletes=False, passive_updates=True, remote_side=None, enable_typechecks=True, join_depth=None, strategy_class=None):
        self.uselist = uselist
        self.argument = argument
        self.entity_name = entity_name
        self.secondary = secondary
        self.primaryjoin = primaryjoin
        self.secondaryjoin = secondaryjoin
        self.post_update = post_update
        self.direction = None
        self.viewonly = viewonly
        self.lazy = lazy
        self.foreign_keys = util.to_set(foreign_keys)
        self._legacy_foreignkey = util.to_set(foreignkey)
        if foreignkey:
            util.warn_deprecated('foreignkey option is deprecated; see docs for details')
        self.collection_class = collection_class
        self.passive_deletes = passive_deletes
        self.passive_updates = passive_updates
        self.remote_side = util.to_set(remote_side)
        self.enable_typechecks = enable_typechecks
        self.comparator = PropertyLoader.Comparator(self)
        self.join_depth = join_depth
        
        if strategy_class:
            self.strategy_class = strategy_class
        elif self.lazy == 'dynamic':
            from sqlalchemy.orm import dynamic
            self.strategy_class = dynamic.DynaLoader
        elif self.lazy is False:
            self.strategy_class = strategies.EagerLoader
        elif self.lazy is None:
            self.strategy_class = strategies.NoLoader
        else:
            self.strategy_class = strategies.LazyLoader

        self._reverse_property = None
        
        if cascade is not None:
            self.cascade = CascadeOptions(cascade)
        else:
            if private:
                util.warn_deprecated('private option is deprecated; see docs for details')
                self.cascade = CascadeOptions("all, delete-orphan")
            else:
                self.cascade = CascadeOptions("save-update, merge")

        if self.passive_deletes == 'all' and ("delete" in self.cascade or "delete-orphan" in self.cascade):
            raise exceptions.ArgumentError("Can't set passive_deletes='all' in conjunction with 'delete' or 'delete-orphan' cascade")

        self.association = association
        if association:
            util.warn_deprecated('association option is deprecated; see docs for details')
        self.order_by = order_by
        self.attributeext=attributeext
        if isinstance(backref, str):
            # propigate explicitly sent primary/secondary join conditions to the BackRef object if
            # just a string was sent
            if secondary is not None:
                # reverse primary/secondary in case of a many-to-many
                self.backref = BackRef(backref, primaryjoin=secondaryjoin, secondaryjoin=primaryjoin, passive_updates=self.passive_updates)
            else:
                self.backref = BackRef(backref, primaryjoin=primaryjoin, secondaryjoin=secondaryjoin, passive_updates=self.passive_updates)
        else:
            self.backref = backref
        self.is_backref = is_backref
예제 #35
0
"""
information schema implementation.

This module is deprecated and will not be present in this form in SQLAlchemy 0.6.

"""
from sqlalchemy import util

util.warn_deprecated("the information_schema module is deprecated.")

import sqlalchemy.sql as sql
import sqlalchemy.exc as exc
from sqlalchemy import select, MetaData, Table, Column, String, Integer
from sqlalchemy.schema import DefaultClause, ForeignKeyConstraint

ischema = MetaData()

schemata = Table("schemata", ischema,
    Column("catalog_name", String),
    Column("schema_name", String),
    Column("schema_owner", String),
    schema="information_schema")

tables = Table("tables", ischema,
    Column("table_catalog", String),
    Column("table_schema", String),
    Column("table_name", String),
    Column("table_type", String),
    schema="information_schema")

columns = Table("columns", ischema,
예제 #36
0
    def __init__(self, argument, secondary=None, primaryjoin=None, secondaryjoin=None, entity_name=None, foreign_keys=None, foreignkey=None, uselist=None, private=False, association=None, order_by=False, attributeext=None, backref=None, is_backref=False, post_update=False, cascade=None, viewonly=False, lazy=True, collection_class=None, passive_deletes=False, passive_updates=True, remote_side=None, enable_typechecks=True, join_depth=None, strategy_class=None, _local_remote_pairs=None):
        self.uselist = uselist
        self.argument = argument
        self.entity_name = entity_name
        self.secondary = secondary
        self.primaryjoin = primaryjoin
        self.secondaryjoin = secondaryjoin
        self.post_update = post_update
        self.direction = None
        self.viewonly = viewonly
        self.lazy = lazy
        self.foreign_keys = util.to_set(foreign_keys)
        self._legacy_foreignkey = util.to_set(foreignkey)
        if foreignkey:
            util.warn_deprecated('foreignkey option is deprecated; see docs for details')
        self.collection_class = collection_class
        self.passive_deletes = passive_deletes
        self.passive_updates = passive_updates
        self.remote_side = util.to_set(remote_side)
        self.enable_typechecks = enable_typechecks
        self.comparator = PropertyLoader.Comparator(self)
        self.join_depth = join_depth
        self._arg_local_remote_pairs = _local_remote_pairs
        util.set_creation_order(self)
        
        if strategy_class:
            self.strategy_class = strategy_class
        elif self.lazy == 'dynamic':
            from sqlalchemy.orm import dynamic
            self.strategy_class = dynamic.DynaLoader
        elif self.lazy is False:
            self.strategy_class = strategies.EagerLoader
        elif self.lazy is None:
            self.strategy_class = strategies.NoLoader
        else:
            self.strategy_class = strategies.LazyLoader

        self._reverse_property = None
        
        if cascade is not None:
            self.cascade = CascadeOptions(cascade)
        else:
            if private:
                util.warn_deprecated('private option is deprecated; see docs for details')
                self.cascade = CascadeOptions("all, delete-orphan")
            else:
                self.cascade = CascadeOptions("save-update, merge")

        if self.passive_deletes == 'all' and ("delete" in self.cascade or "delete-orphan" in self.cascade):
            raise exceptions.ArgumentError("Can't set passive_deletes='all' in conjunction with 'delete' or 'delete-orphan' cascade")

        self.association = association
        if association:
            util.warn_deprecated('association option is deprecated; see docs for details')
        self.order_by = order_by
        self.attributeext=attributeext
        if isinstance(backref, str):
            # propigate explicitly sent primary/secondary join conditions to the BackRef object if
            # just a string was sent
            if secondary is not None:
                # reverse primary/secondary in case of a many-to-many
                self.backref = BackRef(backref, primaryjoin=secondaryjoin, secondaryjoin=primaryjoin, passive_updates=self.passive_updates)
            else:
                self.backref = BackRef(backref, primaryjoin=primaryjoin, secondaryjoin=secondaryjoin, passive_updates=self.passive_updates)
        else:
            self.backref = backref
        self.is_backref = is_backref
예제 #37
0
    def __init__(self,
                    creator, recycle=-1, echo=None,
                    use_threadlocal=False,
                    logging_name=None,
                    reset_on_return=True,
                    listeners=None,
                    events=None,
                    _dispatch=None):
        """
        Construct a Pool.

        :param creator: a callable function that returns a DB-API
          connection object.  The function will be called with
          parameters.

        :param recycle: If set to non -1, number of seconds between
          connection recycling, which means upon checkout, if this
          timeout is surpassed the connection will be closed and
          replaced with a newly opened connection. Defaults to -1.

        :param logging_name:  String identifier which will be used within
          the "name" field of logging records generated within the
          "sqlalchemy.pool" logger. Defaults to a hexstring of the object's
          id.

        :param echo: If True, connections being pulled and retrieved
          from the pool will be logged to the standard output, as well
          as pool sizing information.  Echoing can also be achieved by
          enabling logging for the "sqlalchemy.pool"
          namespace. Defaults to False.

        :param use_threadlocal: If set to True, repeated calls to
          :meth:`connect` within the same application thread will be
          guaranteed to return the same connection object, if one has
          already been retrieved from the pool and has not been
          returned yet.  Offers a slight performance advantage at the
          cost of individual transactions by default.  The
          :meth:`unique_connection` method is provided to bypass the
          threadlocal behavior installed into :meth:`connect`.

        :param reset_on_return: If true, reset the database state of
          connections returned to the pool.  This is typically a
          ROLLBACK to release locks and transaction resources.
          Disable at your own peril.  Defaults to True.

        :param events: a list of 2-tuples, each of the form
         ``(callable, target)`` which will be passed to event.listen()
         upon construction.   Provided here so that event listeners
         can be assigned via ``create_engine`` before dialect-level
         listeners are applied.

        :param listeners: Deprecated.  A list of
          :class:`~sqlalchemy.interfaces.PoolListener`-like objects or
          dictionaries of callables that receive events when DB-API
          connections are created, checked out and checked in to the
          pool.  This has been superseded by
          :func:`~sqlalchemy.event.listen`.

        """
        if logging_name:
            self.logging_name = self._orig_logging_name = logging_name
        else:
            self._orig_logging_name = None

        log.instance_logger(self, echoflag=echo)
        self._threadconns = threading.local()
        self._creator = creator
        self._recycle = recycle
        self._use_threadlocal = use_threadlocal
        if reset_on_return in ('rollback', True, reset_rollback):
            self._reset_on_return = reset_rollback
        elif reset_on_return in (None, False, reset_none):
            self._reset_on_return = reset_none
        elif reset_on_return in ('commit', reset_commit):
            self._reset_on_return = reset_commit
        else:
            raise exc.ArgumentError(
                        "Invalid value for 'reset_on_return': %r"
                                    % reset_on_return)

        self.echo = echo
        if _dispatch:
            self.dispatch._update(_dispatch, only_propagate=False)
        if events:
            for fn, target in events:
                event.listen(self, target, fn)
        if listeners:
            util.warn_deprecated(
                        "The 'listeners' argument to Pool (and "
                        "create_engine()) is deprecated.  Use event.listen().")
            for l in listeners:
                self.add_listener(l)
예제 #38
0
# backwards compat with the old name
from sqlalchemy.util import warn_deprecated

warn_deprecated(
    "The SQLAlchemy PostgreSQL dialect has been renamed from 'postgres' to 'postgresql'. "
    "The new URL format is postgresql[+driver]://<user>:<pass>@<host>/<dbname>"
    )
    
from sqlalchemy.dialects.postgresql import *
from sqlalchemy.dialects.postgresql import base
예제 #39
0
# orm/shard.py
# Copyright (C) 2005-2011 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php

from sqlalchemy import util

util.warn_deprecated(
    "Horizontal sharding is now importable via "
    "'import sqlalchemy.ext.horizontal_shard"
)

from sqlalchemy.ext.horizontal_shard import *

"""
information schema implementation.

This module is deprecated and will not be present in this form in SQLAlchemy 0.6.

"""
from sqlalchemy import util

util.warn_deprecated("the information_schema module is deprecated.")

import sqlalchemy.sql as sql
import sqlalchemy.exc as exc
from sqlalchemy import select, MetaData, Table, Column, String, Integer
from sqlalchemy.schema import DefaultClause, ForeignKeyConstraint

ischema = MetaData()

schemata = Table("schemata",
                 ischema,
                 Column("catalog_name", String),
                 Column("schema_name", String),
                 Column("schema_owner", String),
                 schema="information_schema")

tables = Table("tables",
               ischema,
               Column("table_catalog", String),
               Column("table_schema", String),
               Column("table_name", String),
               Column("table_type", String),
               schema="information_schema")
예제 #41
0
# dialects/postgres.py
# Copyright (C) 2005-2014 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php

# backwards compat with the old name
from sqlalchemy.util import warn_deprecated

warn_deprecated(
    "The SQLAlchemy PostgreSQL dialect has been renamed from 'postgres' to "
    "'postgresql'. The new URL format is "
    "postgresql[+driver]://<user>:<pass>@<host>/<dbname>"
)

from sqlalchemy.dialects.postgresql import *
from sqlalchemy.dialects.postgresql import base
예제 #42
0
    def __init__(self,
                    creator, recycle=-1, echo=None,
                    use_threadlocal=False,
                    logging_name=None,
                    reset_on_return=True,
                    listeners=None,
                    events=None,
                    _dispatch=None):
        """
        Construct a Pool.

        :param creator: a callable function that returns a DB-API
          connection object.  The function will be called with
          parameters.

        :param recycle: If set to non -1, number of seconds between
          connection recycling, which means upon checkout, if this
          timeout is surpassed the connection will be closed and
          replaced with a newly opened connection. Defaults to -1.

        :param logging_name:  String identifier which will be used within
          the "name" field of logging records generated within the
          "sqlalchemy.pool" logger. Defaults to a hexstring of the object's
          id.

        :param echo: If True, connections being pulled and retrieved
          from the pool will be logged to the standard output, as well
          as pool sizing information.  Echoing can also be achieved by
          enabling logging for the "sqlalchemy.pool"
          namespace. Defaults to False.

        :param use_threadlocal: If set to True, repeated calls to
          :meth:`connect` within the same application thread will be
          guaranteed to return the same connection object, if one has
          already been retrieved from the pool and has not been
          returned yet.  Offers a slight performance advantage at the
          cost of individual transactions by default.  The
          :meth:`unique_connection` method is provided to bypass the
          threadlocal behavior installed into :meth:`connect`.

        :param reset_on_return: If true, reset the database state of
          connections returned to the pool.  This is typically a
          ROLLBACK to release locks and transaction resources.
          Disable at your own peril.  Defaults to True.

        :param events: a list of 2-tuples, each of the form
         ``(callable, target)`` which will be passed to event.listen()
         upon construction.   Provided here so that event listeners
         can be assigned via ``create_engine`` before dialect-level
         listeners are applied.

        :param listeners: Deprecated.  A list of
          :class:`~sqlalchemy.interfaces.PoolListener`-like objects or
          dictionaries of callables that receive events when DB-API
          connections are created, checked out and checked in to the
          pool.  This has been superseded by
          :func:`~sqlalchemy.event.listen`.

        """
        if logging_name:
            self.logging_name = self._orig_logging_name = logging_name
        else:
            self._orig_logging_name = None

        log.instance_logger(self, echoflag=echo)
        self._threadconns = threading.local()
        self._creator = creator
        self._recycle = recycle
        self._use_threadlocal = use_threadlocal
        if reset_on_return in ('rollback', True, reset_rollback):
            self._reset_on_return = reset_rollback
        elif reset_on_return in (None, False, reset_none):
            self._reset_on_return = reset_none
        elif reset_on_return in ('commit', reset_commit):
            self._reset_on_return = reset_commit
        else:
            raise exc.ArgumentError(
                        "Invalid value for 'reset_on_return': %r"
                                    % reset_on_return)

        self.echo = echo
        if _dispatch:
            self.dispatch._update(_dispatch, only_propagate=False)
        if events:
            for fn, target in events:
                event.listen(self, target, fn)
        if listeners:
            util.warn_deprecated(
                        "The 'listeners' argument to Pool (and "
                        "create_engine()) is deprecated.  Use event.listen().")
            for l in listeners:
                self.add_listener(l)