Пример #1
0
def use_simple_names():
    get_col_name = lambda el, *args, **kwargs: str(el.element.name)
    try:
        yield compiles(sql.compiler._CompileLabel)(get_col_name)
    except:
        pass
    finally:
        deregister(sql.compiler._CompileLabel)
Пример #2
0
    def bulk_save_objects_with_replace(self, objects):
        '''
        Like Session.bulk_save_objects, but replaces any whose primary key is
        already present. Only works on SQLite.
        '''

        # https://stackoverflow.com/questions/2218304/sqlalchemy-insert-ignore
        # This is a bit hacky, because the deregister call will remove *all*
        # visitors, not the one we just registered. But I don't see a better
        # way right now.
        def _prefix_insert_with_replace(insert, compiler, **kw):
            return compiler.visit_insert(insert.prefix_with('OR REPLACE'),
                                         **kw)

        compiles(Insert)(_prefix_insert_with_replace)
        try:
            self.bulk_save_objects(objects)
        finally:
            deregister(Insert)
Пример #3
0
def compiles_many(func=None, to=None, types=()):
    if not func:
        return partial(compiles_many, to=to, types=types)
    return reduce(lambda f, t: compiles(t, to)(f), types, func)
Пример #4
0
def _compiles_sqlite(cls, fn):
    def _compile_sqlite(element, compiler, **kw):
        return "{}({})".format(fn, compiler.process(element.clauses, **kw))

    compiles(globals()[cls], "sqlite")(_compile_sqlite)
Пример #5
0
def _compiles_default(cls):
    def _compile_default(element, compiler, **kw):
        return "{}({})".format(cls, compiler.process(element.clauses, **kw))

    compiles(globals()[cls])(_compile_default)
Пример #6
0
    def __init__(self, expr):
        self.expr = expression._literal_as_binds(expr)


@compiles(array, 'postgresql')
Пример #7
0
        return False


class array_agg(expression.ColumnElement):
    type = StaticArray()

    def __init__(self, expr, order_by=None):
        self.expr = expression._literal_as_binds(expr)

        if order_by is not None:
            self.order_by = expression._literal_as_binds(order_by)
        else:
            self.order_by = None


@compiles(array_agg, 'postgresql')
def _compile_array_agg_postgresql(element, compiler, **kw):
    buf = StringIO()
    buf.write('array(select x from unnest(array_agg(')
    buf.write(compiler.process(element.expr))
    if element.order_by is not None:
        buf.write(' ORDER BY ')
        buf.write(compiler.process(element.order_by))
    buf.write(')) x WHERE x IS NOT NULL)')
    return buf.getvalue()


class array(expression.ColumnElement):
    type = StaticArray()

    def __init__(self, expr):
Пример #8
0
    "TimeStamp": types.DATETIME,
}

# The below is copy/pasted from https://github.com/sqlalchemy-redshift/sqlalchemy-redshift
# (file sqlalchemy_redshift/dialect.py) to enable use of alembic
# with a 3rd-party SQLAlchemy Dialect
try:
    import alembic
except ImportError:
    pass
else:
    from packaging.version import Version
    from alembic.ddl import postgresql
    from alembic.ddl.base import RenameTable

    compiles(RenameTable, "fauna")(postgresql.visit_rename_table)

    if Version(alembic.__version__) >= Version("1.0.6"):
        from alembic.ddl.base import ColumnComment

        compiles(ColumnComment, "fauna")(postgresql.visit_column_comment)

    class FaunaImpl(postgresql.PostgresqlImpl):
        """Fauna implementation for use by Alembic."""

        __dialect__ = "fauna"


class FaunaExecutionContext(default.DefaultExecutionContext):  # pylint: disable=abstract-method
    """Context for the execution of a query or multiple queries."""
    @property
Пример #9
0
mod_dict = globals()


class pi(GenericFunction):
    type = Float


def _compile_trigd_default(trig):
    def compilefunc(element, compiler, **kw):
        arg, = element.clauses
        return compiler.process(trig(arg * pi()), **kw)

    return compilefunc


def _compile_trigd_postgresql(element, compiler, **kw):
    return compiler.visit_function(element)


for name in ['cos', 'sin', 'tan']:
    mod_dict[name] = type(name, (ReturnTypeFromArgs, ), {})
    __all__.append(name)
    named = f'{name}d'
    mod_dict[named] = type(named, (ReturnTypeFromArgs, ), {})
    compiles(mod_dict[named])(_compile_trigd_default(mod_dict[name]))
    compiles(mod_dict[named], 'postgresql')(_compile_trigd_postgresql)

del mod_dict, GenericFunction, ReturnTypeFromArgs, \
    _compile_trigd_default, _compile_trigd_postgresql
__all__ = tuple(__all__)
Пример #10
0
def compiles_many(func=None, to=None, types=()):
    if not func:
        return partial(compiles_many, to=to, types=types)
    return reduce(lambda f, t: compiles(t, to)(f), types, func)
Пример #11
0
    def _make_proxy(self, selectable, name=None):
        return self.column._make_proxy(selectable, name)
        
@compiles(RawColumn)
Пример #12
0

class CompoundSparqlStatement(SparqlMappingStatement):
    def __init__(self, clauses):
        super(CompoundSparqlStatement, self).__init__(clauses[0])
        self.clauses = clauses
        self.supports_execution = all((c.supports_execution for c in clauses))
        if self.supports_execution:
            self._execution_options = clauses[0]._execution_options

    def _compile(self, compiler, **kwargs):
        return "\n".join(
            (compiler.process(clause, **kwargs) for clause in self.clauses))


compiles(CompoundSparqlStatement)(CompoundSparqlStatement._compile)


class WrapSparqlStatement(SparqlStatement):
    def __init__(self, statement):
        super(WrapSparqlStatement, self).__init__(statement.nsm)
        self.statement = statement
        self.supports_execution = statement.supports_execution
        if self.supports_execution:
            self._execution_options = statement._execution_options

    def _compile(self, compiler, **kwargs):
        known_prefixes = set()
        if isinstance(self.nsm, VirtuosoNamespaceManager):
            known_prefixes = set(self.nsm.v_prefixes.values())
        prefixes = [
Пример #13
0
def _compiles(cls, fn):
    def _compile(element, compiler, **kw):
        return "{}({})".format(fn, compiler.process(element.clauses, **kw))
    compiles(globals()[cls], "sqlite")(_compile)
Пример #14
0
from sqlalchemy.ext.compiler import compiles

try:
    from alembic.ddl import postgresql
except ImportError:
    pass
else:
    from alembic.ddl.base import AlterColumn, RenameTable
    compiles(AlterColumn, 'greenplum')(postgresql.visit_column_type)
    compiles(RenameTable, 'greenplum')(postgresql.visit_rename_table)

    class GreenplumImpl(postgresql.PostgresqlImpl):
        __dialect__ = 'greenplum'
        transactional_ddl = True
Пример #15
0
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import (
    BinaryExpression, BooleanClauseList, Delete
)
from sqlalchemy.types import VARCHAR, NullType

from .commands import CopyCommand, UnloadFromSelect
from .compat import string_types

try:
    from alembic.ddl import postgresql
except ImportError:
    pass
else:
    from alembic.ddl.base import RenameTable
    compiles(RenameTable, 'redshift')(postgresql.visit_rename_table)

    class RedshiftImpl(postgresql.PostgresqlImpl):
        __dialect__ = 'redshift'

__all__ = ['CopyCommand', 'UnloadFromSelect', 'RedshiftDialect']


# Regex for parsing and identity constraint out of adsrc, e.g.:
#   "identity"(445178, 0, '1,1'::text)
IDENTITY_RE = re.compile(r"""
    "identity" \(
      (?P<current>-?\d+)
      ,\s
      (?P<base>-?\d+)
      ,\s
Пример #16
0
                       Encoding, CreateLibraryCommand, AlterTableAppendCommand,
                       RefreshMaterializedView)
from .ddl import (CreateMaterializedView, DropMaterializedView,
                  get_table_attributes)

sa_version = Version(sa.__version__)

try:
    import alembic
except ImportError:
    pass
else:
    from alembic.ddl import postgresql

    from alembic.ddl.base import RenameTable
    compiles(RenameTable, 'redshift')(postgresql.visit_rename_table)

    if Version(alembic.__version__) >= Version('1.0.6'):
        from alembic.ddl.base import ColumnComment
        compiles(ColumnComment, 'redshift')(postgresql.visit_column_comment)

    class RedshiftImpl(postgresql.PostgresqlImpl):
        __dialect__ = 'redshift'


# "Each dialect provides the full set of typenames supported by that backend
# with its __all__ collection
# https://docs.sqlalchemy.org/en/13/core/type_basics.html#vendor-specific-types
__all__ = ('SMALLINT', 'INTEGER', 'BIGINT', 'DECIMAL', 'REAL', 'BOOLEAN',
           'CHAR', 'DATE', 'TIMESTAMP', 'VARCHAR', 'DOUBLE_PRECISION',
           'TIMESTAMPTZ', 'CopyCommand', 'UnloadFromSelect', 'RedshiftDialect',
Пример #17
0
from sqlalchemy.engine import reflection
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import (BinaryExpression, BooleanClauseList,
                                       Delete)
from sqlalchemy.types import VARCHAR, NullType

from .commands import CopyCommand, UnloadFromSelect
from .compat import string_types

try:
    from alembic.ddl import postgresql
except ImportError:
    pass
else:
    from alembic.ddl.base import RenameTable
    compiles(RenameTable, 'redshift')(postgresql.visit_rename_table)

    class RedshiftImpl(postgresql.PostgresqlImpl):
        __dialect__ = 'redshift'


__all__ = ['CopyCommand', 'UnloadFromSelect', 'RedshiftDialect']

# Regex for parsing and identity constraint out of adsrc, e.g.:
#   "identity"(445178, 0, '1,1'::text)
IDENTITY_RE = re.compile(
    r"""
    "identity" \(
      (?P<current>-?\d+)
      ,\s
      (?P<base>-?\d+)
Пример #18
0
class RdfLiteralStmt(ClauseElement):
    def __init__(self, literal, nsm=None):
        self.nsm = nsm
        self.literal = literal

    def __bool__(self):
        # Avoid many tedious "is not None"
        return True

    def _compile(self, compiler, **kwargs):
        nsm = kwargs.get('nsm', self.nsm)
        return self.literal.n3(nsm)


compiles(RdfLiteralStmt)(RdfLiteralStmt._compile)


class Mapping(object):
    def __init__(self, name, nsm=None):
        self.name = name
        self.nsm = nsm

    def patterns_iter(self):
        return ()

    @staticmethod
    def resolve_argument(arg, classes):
        if isinstance(
                arg,
            (InstrumentedAttribute, ClauseElement, GroundedClassAlias)):