本文整理汇总了Python中sqlalchemy.ext.compiler.compiles方法的典型用法代码示例。如果您正苦于以下问题:Python compiler.compiles方法的具体用法?Python compiler.compiles怎么用?Python compiler.compiles使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.ext.compiler
的用法示例。
在下文中一共展示了compiler.compiles方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _fixture
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def _fixture(self):
class SomeColThing(WrapsColumnExpression, ColumnElement):
def __init__(self, expression):
self.clause = coercions.expect(
roles.ExpressionElementRole, expression
)
@property
def wrapped_column_expression(self):
return self.clause
@compiles(SomeColThing)
def process(element, compiler, **kw):
return "SOME_COL_THING(%s)" % compiler.process(
element.clause, **kw
)
return SomeColThing
示例2: define_tables
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def define_tables(cls, metadata):
from sqlalchemy.sql import ColumnElement
from sqlalchemy.ext.compiler import compiles
counter = itertools.count()
class IncDefault(ColumnElement):
pass
@compiles(IncDefault)
def compile_(element, compiler, **kw):
return str(next(counter))
Table(
"t1",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(50)),
Column("insdef", Integer, default=IncDefault()),
Column("upddef", Integer, onupdate=IncDefault()),
)
示例3: test_conn_execute
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def test_conn_execute(self, connection):
from sqlalchemy.sql.expression import FunctionElement
from sqlalchemy.ext.compiler import compiles
class myfunc(FunctionElement):
type = Date()
@compiles(myfunc)
def compile_(elem, compiler, **kw):
return compiler.process(func.current_date())
x = connection.execute(func.current_date()).scalar()
y = connection.execute(func.current_date().select()).scalar()
z = connection.scalar(func.current_date())
q = connection.scalar(myfunc())
assert (x == y == z == q) is True
示例4: test_truly_unlabeled_sql_expressions
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def test_truly_unlabeled_sql_expressions(self):
users = self.tables.users
sess = Session()
class not_named_max(expression.ColumnElement):
name = "not_named_max"
@compiles(not_named_max)
def visit_max(element, compiler, **kw):
return "max(id)"
# assert that there is no "AS max_" or any label of any kind.
eq_(str(select([not_named_max()])), "SELECT max(id)")
# ColumnElement still handles it by applying label()
q = sess.query(not_named_max()).select_from(users)
eq_(q.all(), [(10,)])
示例5: test_column
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def test_column(self):
class MyThingy(ColumnClause):
def __init__(self, arg=None):
super(MyThingy, self).__init__(arg or "MYTHINGY!")
@compiles(MyThingy)
def visit_thingy(thingy, compiler, **kw):
return ">>%s<<" % thingy.name
self.assert_compile(
select([column("foo"), MyThingy()]), "SELECT foo, >>MYTHINGY!<<"
)
self.assert_compile(
select([MyThingy("x"), MyThingy("y")]).where(MyThingy() == 5),
"SELECT >>x<<, >>y<< WHERE >>MYTHINGY!<< = :MYTHINGY!_1",
)
示例6: test_create_column_skip
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def test_create_column_skip(self):
@compiles(CreateColumn)
def skip_xmin(element, compiler, **kw):
if element.element.name == "xmin":
return None
else:
return compiler.visit_create_column(element, **kw)
t = Table(
"t",
MetaData(),
Column("a", Integer),
Column("xmin", Integer),
Column("c", Integer),
)
self.assert_compile(
CreateTable(t), "CREATE TABLE t (a INTEGER, c INTEGER)"
)
示例7: test_types
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def test_types(self):
class MyType(TypeEngine):
pass
@compiles(MyType, "sqlite")
def visit_sqlite_type(type_, compiler, **kw):
return "SQLITE_FOO"
@compiles(MyType, "postgresql")
def visit_pg_type(type_, compiler, **kw):
return "POSTGRES_FOO"
from sqlalchemy.dialects.sqlite import base as sqlite
from sqlalchemy.dialects.postgresql import base as postgresql
self.assert_compile(MyType(), "SQLITE_FOO", dialect=sqlite.dialect())
self.assert_compile(
MyType(), "POSTGRES_FOO", dialect=postgresql.dialect()
)
示例8: test_callout_to_compiler
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def test_callout_to_compiler(self):
class InsertFromSelect(ClauseElement):
def __init__(self, table, select):
self.table = table
self.select = select
@compiles(InsertFromSelect)
def visit_insert_from_select(element, compiler, **kw):
return "INSERT INTO %s (%s)" % (
compiler.process(element.table, asfrom=True),
compiler.process(element.select),
)
t1 = table("mytable", column("x"), column("y"), column("z"))
self.assert_compile(
InsertFromSelect(t1, select([t1]).where(t1.c.x > 5)),
"INSERT INTO mytable (SELECT mytable.x, mytable.y, mytable.z "
"FROM mytable WHERE mytable.x > :x_1)",
)
示例9: test_functions
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def test_functions(self):
from sqlalchemy.dialects import postgresql
class MyUtcFunction(FunctionElement):
pass
@compiles(MyUtcFunction)
def visit_myfunc(element, compiler, **kw):
return "utcnow()"
@compiles(MyUtcFunction, "postgresql")
def visit_myfunc_pg(element, compiler, **kw):
return "timezone('utc', current_timestamp)"
self.assert_compile(
MyUtcFunction(), "utcnow()", use_default_dialect=True
)
self.assert_compile(
MyUtcFunction(),
"timezone('utc', current_timestamp)",
dialect=postgresql.dialect(),
)
示例10: test_function_subclasses_one
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def test_function_subclasses_one(self):
class Base(FunctionElement):
name = "base"
class Sub1(Base):
name = "sub1"
class Sub2(Base):
name = "sub2"
@compiles(Base)
def visit_base(element, compiler, **kw):
return element.name
@compiles(Sub1)
def visit_sub1(element, compiler, **kw):
return "FOO" + element.name
self.assert_compile(
select([Sub1(), Sub2()]),
"SELECT FOOsub1 AS sub1_1, sub2 AS sub2_1",
use_default_dialect=True,
)
示例11: _is_sqlalchemy_connectable
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def _is_sqlalchemy_connectable(con):
global _SQLALCHEMY_INSTALLED
if _SQLALCHEMY_INSTALLED is None:
try:
import sqlalchemy
_SQLALCHEMY_INSTALLED = True
from distutils.version import LooseVersion
ver = sqlalchemy.__version__
# For sqlalchemy versions < 0.8.2, the BIGINT type is recognized
# for a sqlite engine, which results in a warning when trying to
# read/write a DataFrame with int64 values. (GH7433)
if LooseVersion(ver) < LooseVersion('0.8.2'):
from sqlalchemy import BigInteger
from sqlalchemy.ext.compiler import compiles
@compiles(BigInteger, 'sqlite')
def compile_big_int_sqlite(type_, compiler, **kw):
return 'INTEGER'
except ImportError:
_SQLALCHEMY_INSTALLED = False
if _SQLALCHEMY_INSTALLED:
import sqlalchemy
return isinstance(con, sqlalchemy.engine.Connectable)
else:
return False
示例12: compiles
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def compiles(class_, *specs):
"""Register a function as a compiler for a
given :class:`.ClauseElement` type."""
def decorate(fn):
existing = class_.__dict__.get('_compiler_dispatcher', None)
existing_dispatch = class_.__dict__.get('_compiler_dispatch')
if not existing:
existing = _dispatcher()
if existing_dispatch:
existing.specs['default'] = existing_dispatch
# TODO: why is the lambda needed ?
setattr(class_, '_compiler_dispatch',
lambda *arg, **kw: existing(*arg, **kw))
setattr(class_, '_compiler_dispatcher', existing)
if specs:
for s in specs:
existing.specs[s] = fn
else:
existing.specs['default'] = fn
return fn
return decorate
示例13: visit_delete_limit
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def visit_delete_limit(element, compiler, **kw):
"""
Default compiler for the DeleteLimit clause element.
This compiles to a DELETE statement with a SELECT subquery which
has a limit set::
DELETE FROM ... WHERE id IN
(SELECT id FROM ... WHERE ... LIMIT ...)
However, this syntax is not supported by MySQL.
"""
select_stmt = select([element.table.c.id]).where(element.filter).limit(element.limit)
delete_stmt = element.table.delete().where(element.table.c.id.in_(select_stmt))
return compiler.process(delete_stmt)
示例14: visit_delete_limit_mysql
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def visit_delete_limit_mysql(element, compiler, **kw):
"""
Special compiler for the DeleteLimit clause element
for MySQL dialects. This compiles to a DELETE element
with a LIMIT::
DELETE FROM pidea_audit WHERE ... LIMIT ...
"""
return 'DELETE FROM {} WHERE {} LIMIT {:d}'.format(
compiler.process(element.table, asfrom=True),
compiler.process(element.filter), element.limit)
示例15: visit_BYTEINT
# 需要导入模块: from sqlalchemy.ext import compiler [as 别名]
# 或者: from sqlalchemy.ext.compiler import compiles [as 别名]
def visit_BYTEINT(self, type_, **kw):
return 'BYTEINT'
#@compiles(Select, 'teradata')
#def compile_select(element, compiler, **kw):
# """
# """
#
# if not getattr(element, '_window_visit', None):
# if element._limit is not None or element._offset is not None:
# limit, offset = element._limit, element._offset
#
# orderby=compiler.process(element._order_by_clause)
# if orderby:
# element = element._generate()
# element._window_visit=True
# #element._limit = None
# #element._offset = None cant set to none...
#
# # add a ROW NUMBER() OVER(ORDER BY) column
# element = element.column(sql.literal_column('ROW NUMBER() OVER (ORDER BY %s)' % orderby).label('rownum')).order_by(None)
#
# # wrap into a subquery
# limitselect = sql.select([c for c in element.alias().c if c.key != 'rownum'])
#
# limitselect._window_visit=True
# limitselect._is_wrapper=True
#
# if offset is not None:
# limitselect.append_whereclause(sql.column('rownum') > offset)
# if limit is not None:
# limitselect.append_whereclause(sql.column('rownum') <= (limit + offset))
# else:
# limitselect.append_whereclause(sql.column("rownum") <= limit)
#
# element = limitselect
#
# kw['iswrapper'] = getattr(element, '_is_wrapper', False)
# return compiler.visit_select(element, **kw)