Esempio n. 1
0
def engine_descriptors():
    """Provide a listing of all the database implementations supported.
    
    This method will be removed in 0.5.

    """
    result = []
    for module in sqlalchemy.databases.__all__:
        module = getattr(
            __import__('sqlalchemy.databases.%s' % module).databases, module)
        result.append(module.descriptor())
    return result


engine_descriptors = util.deprecated()(engine_descriptors)

default_strategy = 'plain'


def create_engine(*args, **kwargs):
    """Create a new Engine instance.

    The standard method of specifying the engine is via URL as the
    first positional argument, to indicate the appropriate database
    dialect and connection arguments, with additional keyword
    arguments sent as options to the dialect and resulting Engine.

    The URL is a string in the form
    ``dialect://user:password@host/dbname[?key=value..]``, where
    ``dialect`` is a name such as ``mysql``, ``oracle``, ``postgres``,
Esempio n. 2
0
def _deferred_relation(cls, prop):
    if isinstance(prop, PropertyLoader) and isinstance(prop.argument, basestring):
        arg = prop.argument
        def return_cls():
            try:
                return cls._decl_class_registry[arg]
            except KeyError:
                raise exceptions.InvalidRequestError("When compiling mapper %s, could not locate a declarative class named %r.  Consider adding this property to the %r class after both dependent classes have been defined." % (prop.parent, arg, prop.parent.class_))
        prop.argument = return_cls

    return prop

def declared_synonym(prop, name):
    """Deprecated.  Use synonym(name, descriptor=prop)."""
    return _orm_synonym(name, descriptor=prop)
declared_synonym = util.deprecated(None, False)(declared_synonym)

def synonym_for(name, map_column=False):
    """Decorator, make a Python @property a query synonym for a column.

    A decorator version of [sqlalchemy.orm#synonym()].  The function being
    decorated is the 'descriptor', otherwise passes its arguments through
    to synonym()::

      @synonym_for('col')
      @property
      def prop(self):
          return 'special sauce'

    The regular ``synonym()`` is also usable directly in a declarative
    setting and may be convenient for read/write properties::
Esempio n. 3
0
class PGCompiler(compiler.DefaultCompiler):
    operators = compiler.DefaultCompiler.operators.copy()
    operators.update({
        sql_operators.mod:
        '%%',
        sql_operators.ilike_op:
        lambda x, y, escape=None: '%s ILIKE %s' % (x, y) +
        (escape and ' ESCAPE \'%s\'' % escape or ''),
        sql_operators.notilike_op:
        lambda x, y, escape=None: '%s NOT ILIKE %s' % (x, y) +
        (escape and ' ESCAPE \'%s\'' % escape or ''),
        sql_operators.match_op:
        lambda x, y: '%s @@ to_tsquery(%s)' % (x, y),
    })

    functions = compiler.DefaultCompiler.functions.copy()
    functions.update({
        'TIMESTAMP':
        util.deprecated(
            message="Use a literal string 'timestamp <value>' instead")(
                lambda x: 'TIMESTAMP %s' % x),
    })

    def visit_sequence(self, seq):
        if seq.optional:
            return None
        else:
            return "nextval('%s')" % self.preparer.format_sequence(seq)

    def post_process_text(self, text):
        if '%%' in text:
            util.warn(
                "The SQLAlchemy psycopg2 dialect now automatically escapes '%' in text() expressions to '%%'."
            )
        return text.replace('%', '%%')

    def limit_clause(self, select):
        text = ""
        if select._limit is not None:
            text += " \n LIMIT " + str(select._limit)
        if select._offset is not None:
            if select._limit is None:
                text += " \n LIMIT ALL"
            text += " OFFSET " + str(select._offset)
        return text

    def get_select_precolumns(self, select):
        if select._distinct:
            if isinstance(select._distinct, bool):
                return "DISTINCT "
            elif isinstance(select._distinct, (list, tuple)):
                return "DISTINCT ON (" + ', '.join(
                    [(isinstance(col, basestring) and col or self.process(col))
                     for col in select._distinct]) + ") "
            else:
                return "DISTINCT ON (" + unicode(select._distinct) + ") "
        else:
            return ""

    def for_update_clause(self, select):
        if select.for_update == 'nowait':
            return " FOR UPDATE NOWAIT"
        else:
            return super(PGCompiler, self).for_update_clause(select)

    def _append_returning(self, text, stmt):
        returning_cols = stmt.kwargs['postgres_returning']

        def flatten_columnlist(collist):
            for c in collist:
                if isinstance(c, expression.Selectable):
                    for co in c.columns:
                        yield co
                else:
                    yield c

        columns = [
            self.process(c, within_columns_clause=True)
            for c in flatten_columnlist(returning_cols)
        ]
        text += ' RETURNING ' + string.join(columns, ', ')
        return text

    def visit_update(self, update_stmt):
        text = super(PGCompiler, self).visit_update(update_stmt)
        if 'postgres_returning' in update_stmt.kwargs:
            return self._append_returning(text, update_stmt)
        else:
            return text

    def visit_insert(self, insert_stmt):
        text = super(PGCompiler, self).visit_insert(insert_stmt)
        if 'postgres_returning' in insert_stmt.kwargs:
            return self._append_returning(text, insert_stmt)
        else:
            return text

    def visit_extract(self, extract, **kwargs):
        field = self.extract_map.get(extract.field, extract.field)
        return "EXTRACT(%s FROM %s::timestamp)" % (field,
                                                   self.process(extract.expr))
Esempio n. 4
0
    'SchemaIterator', 'DefaultRunner',
    ]

def engine_descriptors():
    """Provide a listing of all the database implementations supported.
    
    This method will be removed in 0.5.

    """
    result = []
    for module in sqlalchemy.databases.__all__:
        module = getattr(
            __import__('sqlalchemy.databases.%s' % module).databases, module)
        result.append(module.descriptor())
    return result
engine_descriptors = util.deprecated()(engine_descriptors)


default_strategy = 'plain'
def create_engine(*args, **kwargs):
    """Create a new Engine instance.

    The standard method of specifying the engine is via URL as the
    first positional argument, to indicate the appropriate database
    dialect and connection arguments, with additional keyword
    arguments sent as options to the dialect and resulting Engine.

    The URL is a string in the form
    ``dialect://user:password@host/dbname[?key=value..]``, where
    ``dialect`` is a name such as ``mysql``, ``oracle``, ``postgres``,
    etc.  Alternatively, the URL can be an instance of
Esempio n. 5
0
            except KeyError:
                raise exceptions.InvalidRequestError(
                    "When compiling mapper %s, could not locate a declarative class named %r.  Consider adding this property to the %r class after both dependent classes have been defined."
                    % (prop.parent, arg, prop.parent.class_))

        prop.argument = return_cls

    return prop


def declared_synonym(prop, name):
    """Deprecated.  Use synonym(name, descriptor=prop)."""
    return _orm_synonym(name, descriptor=prop)


declared_synonym = util.deprecated(None, False)(declared_synonym)


def synonym_for(name, map_column=False):
    """Decorator, make a Python @property a query synonym for a column.

    A decorator version of [sqlalchemy.orm#synonym()].  The function being
    decorated is the 'descriptor', otherwise passes its arguments through
    to synonym()::

      @synonym_for('col')
      @property
      def prop(self):
          return 'special sauce'

    The regular ``synonym()`` is also usable directly in a declarative
Esempio n. 6
0
                                                     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

assign_mapper = util.deprecated(
    "assign_mapper is deprecated. Use scoped_session() instead.")(assign_mapper)
Esempio n. 7
0
                                                     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

assign_mapper = util.deprecated(
    assign_mapper, "assign_mapper is deprecated. Use scoped_session() instead.")