本文整理汇总了Python中sqlalchemy.literal方法的典型用法代码示例。如果您正苦于以下问题:Python sqlalchemy.literal方法的具体用法?Python sqlalchemy.literal怎么用?Python sqlalchemy.literal使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy
的用法示例。
在下文中一共展示了sqlalchemy.literal方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: define_tables
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def define_tables(cls, metadata):
Table('autoinc_pk', metadata,
Column('id', Integer, primary_key=True,
test_needs_autoincrement=True),
Column('data', String(50))
)
Table('manual_pk', metadata,
Column('id', Integer, primary_key=True, autoincrement=False),
Column('data', String(50))
)
Table('includes_defaults', metadata,
Column('id', Integer, primary_key=True,
test_needs_autoincrement=True),
Column('data', String(50)),
Column('x', Integer, default=5),
Column('y', Integer,
default=literal_column("2", type_=Integer) + literal(2)))
示例2: _literal
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def _literal(t, expr):
if isinstance(expr, ir.IntervalScalar):
if expr.type().unit in {'ms', 'ns'}:
raise com.UnsupportedOperationError(
'MySQL does not allow operation '
'with INTERVAL offset {}'.format(expr.type().unit)
)
text_unit = expr.type().resolution.upper()
value = expr.op().value
return sa.text('INTERVAL :value {}'.format(text_unit)).bindparams(
value=value
)
elif isinstance(expr, ir.SetScalar):
return list(map(sa.literal, expr.op().value))
else:
value = expr.op().value
if isinstance(value, pd.Timestamp):
value = value.to_pydatetime()
return sa.literal(value)
示例3: before_compile
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def before_compile(query):
"""ensure all queries for VersionedStartEnd include criteria """
for ent in query.column_descriptions:
entity = ent["entity"]
if entity is None:
continue
insp = inspect(ent["entity"])
mapper = getattr(insp, "mapper", None)
if mapper and issubclass(mapper.class_, VersionedStartEnd):
query = query.enable_assertions(False).filter(
# using a literal "now" because SQLite's "between"
# seems to be inclusive. In practice, this would be
# ``func.now()`` and we'd be using PostgreSQL
literal(
current_time() + datetime.timedelta(seconds=1)
).between(ent["entity"].start, ent["entity"].end)
)
return query
示例4: test_limit_six
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def test_limit_six(self):
t = table("sometable", column("col1"), column("col2"))
s = (
select([t])
.limit(10)
.offset(literal(10) + literal(20))
.order_by(t.c.col2)
)
self.assert_compile(
s,
"SELECT anon_1.col1, anon_1.col2 FROM (SELECT anon_2.col1 AS "
"col1, anon_2.col2 AS col2, ROWNUM AS ora_rn FROM "
"(SELECT sometable.col1 AS col1, sometable.col2 AS col2 "
"FROM sometable ORDER BY sometable.col2) anon_2 WHERE "
"ROWNUM <= :param_1 + :param_2 + :param_3) anon_1 "
"WHERE ora_rn > :param_2 + :param_3",
checkparams={"param_1": 10, "param_2": 10, "param_3": 20},
)
示例5: test_update_sql_expr
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def test_update_sql_expr(self):
stmt = insert(self.table).values(
[{"id": 1, "bar": "ab"}, {"id": 2, "bar": "b"}]
)
stmt = stmt.on_duplicate_key_update(
bar=func.coalesce(stmt.inserted.bar),
baz=stmt.inserted.baz + "some literal",
)
expected_sql = (
"INSERT INTO foos (id, bar) VALUES (%s, %s), (%s, %s) ON "
"DUPLICATE KEY UPDATE bar = coalesce(VALUES(bar)), "
"baz = (concat(VALUES(baz), %s))"
)
self.assert_compile(
stmt,
expected_sql,
checkparams={
"id_m0": 1,
"bar_m0": "ab",
"id_m1": 2,
"bar_m1": "b",
"baz_1": "some literal",
},
)
示例6: test_type_coerce_existing_typed
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def test_type_coerce_existing_typed(self, connection):
MyType = self.MyType
coerce_fn = type_coerce
t = self.tables.t
# type_coerce does upgrade the given expression to the
# given type.
connection.execute(
t.insert().values(data=coerce_fn(literal("d1"), MyType))
)
eq_(
connection.execute(
select([coerce_fn(t.c.data, MyType)])
).fetchall(),
[("BIND_INd1BIND_OUT",)],
)
示例7: test_select_composition_four
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def test_select_composition_four(self):
# test that use_labels doesn't interfere with literal columns
self.assert_compile(
select(
[
text("column1"),
column("column2"),
column("column3").label("bar"),
table1.c.myid,
],
from_obj=table1,
use_labels=True,
),
"SELECT column1, column2, column3 AS bar, "
"mytable.myid AS mytable_myid "
"FROM mytable",
)
示例8: test_select_composition_five
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def test_select_composition_five(self):
# test that use_labels doesn't interfere
# with literal columns that have textual labels
self.assert_compile(
select(
[
text("column1 AS foobar"),
text("column2 AS hoho"),
table1.c.myid,
],
from_obj=table1,
use_labels=True,
),
"SELECT column1 AS foobar, column2 AS hoho, "
"mytable.myid AS mytable_myid FROM mytable",
)
示例9: test_select_composition_six
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def test_select_composition_six(self):
# test that "auto-labeling of subquery columns"
# doesn't interfere with literal columns,
# exported columns don't get quoted.
# [ticket:4730] refines this but for the moment the behavior with
# no columns is being maintained.
self.assert_compile(
select(
[
literal_column("column1 AS foobar"),
literal_column("column2 AS hoho"),
table1.c.myid,
],
from_obj=[table1],
)
.subquery()
.select(),
"SELECT anon_1.column1 AS foobar, anon_1.column2 AS hoho, "
"anon_1.myid FROM "
"(SELECT column1 AS foobar, column2 AS hoho, "
"mytable.myid AS myid FROM mytable) AS anon_1",
)
示例10: test_or_and_as_columns
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def test_or_and_as_columns(self, connection):
true, false = literal(True), literal(False)
eq_(connection.execute(select([and_(true, false)])).scalar(), False)
eq_(connection.execute(select([and_(true, true)])).scalar(), True)
eq_(connection.execute(select([or_(true, false)])).scalar(), True)
eq_(connection.execute(select([or_(false, false)])).scalar(), False)
eq_(
connection.execute(select([not_(or_(false, false))])).scalar(),
True,
)
row = connection.execute(
select(
[or_(false, false).label("x"), and_(true, false).label("y")]
)
).first()
assert row.x == False # noqa
assert row.y == False # noqa
row = connection.execute(
select([or_(true, false).label("x"), and_(true, false).label("y")])
).first()
assert row.x == True # noqa
assert row.y == False # noqa
示例11: test_column_accessor_labels_w_dots
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def test_column_accessor_labels_w_dots(self, connection):
users = self.tables.users
connection.execute(users.insert(), dict(user_id=1, user_name="john"))
# test using literal tablename.colname
r = connection.execute(
text(
'select users.user_id AS "users.user_id", '
'users.user_name AS "users.user_name" '
"from users",
bind=testing.db,
).execution_options(sqlite_raw_colnames=True)
).first()
eq_(r._mapping["users.user_id"], 1)
eq_(r._mapping["users.user_name"], "john")
not_in_("user_name", r._mapping)
eq_(list(r._fields), ["users.user_id", "users.user_name"])
示例12: _test_result_processor
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def _test_result_processor(self, cls, use_cache):
class MyType(TypeDecorator):
impl = String()
def process_result_value(self, value, dialect):
return "HI " + value
with self._proxy_fixture(cls):
with self.engine.connect() as conn:
if use_cache:
cache = {}
conn = conn.execution_options(compiled_cache=cache)
stmt = select([literal("THERE", type_=MyType())])
for i in range(2):
r = conn.execute(stmt)
eq_(r.scalar(), "HI THERE")
示例13: test_select_from_aliased_w_subclass
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def test_select_from_aliased_w_subclass(self):
Engineer = self.classes.Engineer
sess = create_session()
a1 = aliased(Engineer)
self.assert_compile(
sess.query(a1.employee_id).select_from(a1),
"SELECT employees_1.employee_id AS employees_1_employee_id "
"FROM employees AS employees_1 WHERE employees_1.type "
"IN ([POSTCOMPILE_type_1])",
)
self.assert_compile(
sess.query(literal("1")).select_from(a1),
"SELECT :param_1 AS anon_1 FROM employees AS employees_1 "
"WHERE employees_1.type IN ([POSTCOMPILE_type_1])",
)
示例14: test_union_literal_expressions_compile
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def test_union_literal_expressions_compile(self):
"""test that column expressions translate during
the _from_statement() portion of union(), others"""
User = self.classes.User
s = Session()
q1 = s.query(User, literal("x"))
q2 = s.query(User, literal_column("'y'"))
q3 = q1.union(q2)
self.assert_compile(
q3,
"SELECT anon_1.users_id AS anon_1_users_id, "
"anon_1.users_name AS anon_1_users_name, "
"anon_1.anon_2 AS anon_1_anon_2 FROM "
"(SELECT users.id AS users_id, users.name AS users_name, "
":param_1 AS anon_2 FROM users "
"UNION SELECT users.id AS users_id, users.name AS users_name, "
"'y' FROM users) AS anon_1",
)
示例15: for_filling
# 需要导入模块: import sqlalchemy [as 别名]
# 或者: from sqlalchemy import literal [as 别名]
def for_filling(self, dialect):
# NOTE(sileht): This must be used only for patching resource type
# to fill all row with a default value and then switch back the
# server_default to None
if self.fill is None:
return None
# NOTE(sileht): server_default must be converted in sql element
return sqlalchemy.literal(self.fill)