eq_(s.execute().fetchall(), [
('no ', ), ('no ', ), ('no ', ), ('yes', ),
('no ', ), ('no ', ),
- ])
+ ])
else:
eq_(s.execute().fetchall(), [
('no', ), ('no', ), ('no', ), ('yes', ),
('no', ), ('no', ),
- ])
+ ])
@testing.fails_on('firebird', 'FIXME: unknown')
def testcase_with_dict(self):
from sqlalchemy import Integer, String, MetaData, Table, Column, select, \
func, not_, cast, text, tuple_, exists, update, bindparam,\
literal, and_, null, type_coerce, alias, or_, literal_column,\
- Float, TIMESTAMP, Numeric, Date, Text, collate, union, except_,\
+ Float, TIMESTAMP, Numeric, Date, Text, union, except_,\
intersect, union_all, Boolean, distinct, join, outerjoin, asc, desc,\
over, subquery, case, true
import decimal
from sqlalchemy.sql.expression import ClauseList, _literal_as_text, HasPrefixes
from sqlalchemy.engine import default
from sqlalchemy.dialects import mysql, mssql, postgresql, oracle, \
- sqlite, sybase
+ sqlite, sybase
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql import compiler
table1 = table('mytable',
- column('myid', Integer),
- column('name', String),
- column('description', String),
-)
+ column('myid', Integer),
+ column('name', String),
+ column('description', String),
+ )
table2 = table(
'myothertable',
)
users = table('users',
- column('user_id'),
- column('user_name'),
- column('password'),
-)
+ column('user_id'),
+ column('user_name'),
+ column('password'),
+ )
addresses = table('addresses',
- column('address_id'),
- column('user_id'),
- column('street'),
- column('city'),
- column('state'),
- column('zip')
-)
+ column('address_id'),
+ column('user_id'),
+ column('street'),
+ column('city'),
+ column('state'),
+ column('zip')
+ )
keyed = Table('keyed', metadata,
- Column('x', Integer, key='colx'),
- Column('y', Integer, key='coly'),
- Column('z', Integer),
-)
+ Column('x', Integer, key='colx'),
+ Column('y', Integer, key='coly'),
+ Column('z', Integer),
+ )
class SelectTest(fixtures.TestBase, AssertsCompiledSQL):
'columns; use this object directly within a '
'column-level expression.',
lambda: hasattr(
- select([table1.c.myid]).as_scalar().self_group(),
- 'columns'))
+ select([table1.c.myid]).as_scalar().self_group(),
+ 'columns'))
assert_raises_message(
exc.InvalidRequestError,
'Scalar Select expression has no '
'columns; use this object directly within a '
'column-level expression.',
lambda: hasattr(select([table1.c.myid]).as_scalar(),
- 'columns'))
+ 'columns'))
else:
assert not hasattr(
- select([table1.c.myid]).as_scalar().self_group(),
- 'columns')
+ select([table1.c.myid]).as_scalar().self_group(),
+ 'columns')
assert not hasattr(select([table1.c.myid]).as_scalar(), 'columns')
def test_prefix_constructor(self):
class Pref(HasPrefixes):
+
def _generate(self):
return self
assert_raises(exc.ArgumentError,
- Pref().prefix_with,
- "some prefix", not_a_dialect=True
- )
+ Pref().prefix_with,
+ "some prefix", not_a_dialect=True
+ )
def test_table_select(self):
self.assert_compile(table1.select(),
"SELECT mytable.myid, mytable.name, "
"mytable.description FROM mytable")
- self.assert_compile(select([table1, table2]),
- "SELECT mytable.myid, mytable.name, mytable.description, "
- "myothertable.otherid, myothertable.othername FROM mytable, "
- "myothertable")
+ self.assert_compile(
+ select(
+ [
+ table1,
+ table2]),
+ "SELECT mytable.myid, mytable.name, mytable.description, "
+ "myothertable.otherid, myothertable.othername FROM mytable, "
+ "myothertable")
def test_invalid_col_argument(self):
assert_raises(exc.ArgumentError, select, table1)
def test_limit_offset(self):
for lim, offset, exp, params in [
(5, 10, "LIMIT :param_1 OFFSET :param_2",
- {'param_1':5, 'param_2':10}),
- (None, 10, "LIMIT -1 OFFSET :param_1", {'param_1':10}),
- (5, None, "LIMIT :param_1", {'param_1':5}),
+ {'param_1': 5, 'param_2': 10}),
+ (None, 10, "LIMIT -1 OFFSET :param_1", {'param_1': 10}),
+ (5, None, "LIMIT :param_1", {'param_1': 5}),
(0, 0, "LIMIT :param_1 OFFSET :param_2",
- {'param_1':0, 'param_2':0}),
+ {'param_1': 0, 'param_2': 0}),
]:
self.assert_compile(
select([1]).limit(lim).offset(offset),
checkparams=params
)
-
-
def test_select_precol_compile_ordering(self):
s1 = select([column('x')]).select_from('a').limit(5).as_scalar()
s2 = select([s1]).limit(10)
class MyCompiler(compiler.SQLCompiler):
+
def get_select_precolumns(self, select):
result = ""
if select._limit:
- result += "FIRST %s " % self.process(literal(select._limit))
+ result += "FIRST %s " % self.process(
+ literal(
+ select._limit))
if select._offset:
- result += "SKIP %s " % self.process(literal(select._offset))
+ result += "SKIP %s " % self.process(
+ literal(
+ select._offset))
return result
def limit_clause(self, select):
dialect=dialect
)
-
def test_from_subquery(self):
"""tests placing select statements in the column clause of
another select, for the
self.assert_compile(
select(
[s],
- s.c.myid == 7
- ),
- "SELECT myid, name, description FROM (SELECT mytable.myid AS myid, "
- "mytable.name AS name, mytable.description AS description "
- "FROM mytable "
- "WHERE mytable.name = :name_1) WHERE myid = :myid_1")
+ s.c.myid == 7),
+ "SELECT myid, name, description FROM "
+ "(SELECT mytable.myid AS myid, "
+ "mytable.name AS name, mytable.description AS description "
+ "FROM mytable "
+ "WHERE mytable.name = :name_1) WHERE myid = :myid_1")
sq = select([table1])
self.assert_compile(
).alias('sq')
sqstring = "SELECT mytable.myid AS mytable_myid, mytable.name AS "\
- "mytable_name, mytable.description AS mytable_description, "\
- "myothertable.otherid AS myothertable_otherid, "\
- "myothertable.othername AS myothertable_othername FROM "\
- "mytable, myothertable WHERE mytable.myid = :myid_1 AND "\
- "myothertable.otherid = mytable.myid"
+ "mytable_name, mytable.description AS mytable_description, "\
+ "myothertable.otherid AS myothertable_otherid, "\
+ "myothertable.othername AS myothertable_othername FROM "\
+ "mytable, myothertable WHERE mytable.myid = :myid_1 AND "\
+ "myothertable.otherid = mytable.myid"
self.assert_compile(
- sq.select(),
- "SELECT sq.mytable_myid, sq.mytable_name, "
- "sq.mytable_description, sq.myothertable_otherid, "
- "sq.myothertable_othername FROM (%s) AS sq" % sqstring)
+ sq.select(),
+ "SELECT sq.mytable_myid, sq.mytable_name, "
+ "sq.mytable_description, sq.myothertable_otherid, "
+ "sq.myothertable_othername FROM (%s) AS sq" % sqstring)
sq2 = select(
[sq],
).alias('sq2')
self.assert_compile(
- sq2.select(),
- "SELECT sq2.sq_mytable_myid, sq2.sq_mytable_name, "
- "sq2.sq_mytable_description, sq2.sq_myothertable_otherid, "
- "sq2.sq_myothertable_othername FROM "
- "(SELECT sq.mytable_myid AS "
- "sq_mytable_myid, sq.mytable_name AS sq_mytable_name, "
- "sq.mytable_description AS sq_mytable_description, "
- "sq.myothertable_otherid AS sq_myothertable_otherid, "
- "sq.myothertable_othername AS sq_myothertable_othername "
- "FROM (%s) AS sq) AS sq2" % sqstring)
+ sq2.select(),
+ "SELECT sq2.sq_mytable_myid, sq2.sq_mytable_name, "
+ "sq2.sq_mytable_description, sq2.sq_myothertable_otherid, "
+ "sq2.sq_myothertable_othername FROM "
+ "(SELECT sq.mytable_myid AS "
+ "sq_mytable_myid, sq.mytable_name AS sq_mytable_name, "
+ "sq.mytable_description AS sq_mytable_description, "
+ "sq.myothertable_otherid AS sq_myothertable_otherid, "
+ "sq.myothertable_othername AS sq_myothertable_othername "
+ "FROM (%s) AS sq) AS sq2" % sqstring)
def test_select_from_clauselist(self):
self.assert_compile(
select([ClauseList(column('a'), column('b'))]
- ).select_from('sometable'),
+ ).select_from('sometable'),
'SELECT a, b FROM sometable'
)
# using alternate keys.
a, b, c = Column('a', Integer, key='b'), \
- Column('b', Integer), \
- Column('c', Integer, key='a')
+ Column('b', Integer), \
+ Column('c', Integer, key='a')
self.assert_compile(
select([a, b, c, a, b, c]),
"SELECT a, b, c", dialect=default.DefaultDialect()
self.assert_compile(
select([bindparam('a'), bindparam('b'), bindparam('c')]),
"SELECT :a AS anon_1, :b AS anon_2, :c AS anon_3",
- dialect=default.DefaultDialect(paramstyle='named')
+ dialect=default.DefaultDialect(paramstyle='named')
)
self.assert_compile(
select([bindparam('a'), bindparam('b'), bindparam('c')]),
"SELECT ? AS anon_1, ? AS anon_2, ? AS anon_3",
- dialect=default.DefaultDialect(paramstyle='qmark'),
+ dialect=default.DefaultDialect(paramstyle='qmark'),
)
self.assert_compile(
s2 = s1.alias()
s3 = select([s2], use_labels=True)
self.assert_compile(s3,
- "SELECT anon_1.x AS anon_1_x, "
- "anon_1.y AS anon_1_y, "
- "anon_1.z AS anon_1_z FROM "
- "(SELECT keyed.x AS x, keyed.y "
- "AS y, keyed.z AS z FROM keyed) AS anon_1")
+ "SELECT anon_1.x AS anon_1_x, "
+ "anon_1.y AS anon_1_y, "
+ "anon_1.z AS anon_1_z FROM "
+ "(SELECT keyed.x AS x, keyed.y "
+ "AS y, keyed.z AS z FROM keyed) AS anon_1")
s4 = s3.alias()
s5 = select([s4], use_labels=True)
self.assert_compile(s5,
- "SELECT anon_1.anon_2_x AS anon_1_anon_2_x, "
- "anon_1.anon_2_y AS anon_1_anon_2_y, "
- "anon_1.anon_2_z AS anon_1_anon_2_z "
- "FROM (SELECT anon_2.x AS anon_2_x, "
- "anon_2.y AS anon_2_y, "
- "anon_2.z AS anon_2_z FROM "
- "(SELECT keyed.x AS x, keyed.y AS y, keyed.z "
- "AS z FROM keyed) AS anon_2) AS anon_1"
- )
+ "SELECT anon_1.anon_2_x AS anon_1_anon_2_x, "
+ "anon_1.anon_2_y AS anon_1_anon_2_y, "
+ "anon_1.anon_2_z AS anon_1_anon_2_z "
+ "FROM (SELECT anon_2.x AS anon_2_x, "
+ "anon_2.y AS anon_2_y, "
+ "anon_2.z AS anon_2_z FROM "
+ "(SELECT keyed.x AS x, keyed.y AS y, keyed.z "
+ "AS z FROM keyed) AS anon_2) AS anon_1"
+ )
def test_exists(self):
s = select([table1.c.myid]).where(table1.c.myid == 5)
self.assert_compile(exists(s),
- "EXISTS (SELECT mytable.myid FROM mytable "
- "WHERE mytable.myid = :myid_1)"
- )
+ "EXISTS (SELECT mytable.myid FROM mytable "
+ "WHERE mytable.myid = :myid_1)"
+ )
self.assert_compile(exists(s.as_scalar()),
- "EXISTS (SELECT mytable.myid FROM mytable "
- "WHERE mytable.myid = :myid_1)"
- )
+ "EXISTS (SELECT mytable.myid FROM mytable "
+ "WHERE mytable.myid = :myid_1)"
+ )
self.assert_compile(exists([table1.c.myid], table1.c.myid
- == 5).select(),
+ == 5).select(),
'SELECT EXISTS (SELECT mytable.myid FROM '
'mytable WHERE mytable.myid = :myid_1)',
params={'mytable_myid': 5})
self.assert_compile(select([table1, exists([1],
- from_obj=table2)]),
+ from_obj=table2)]),
'SELECT mytable.myid, mytable.name, '
'mytable.description, EXISTS (SELECT 1 '
'FROM myothertable) FROM mytable',
params={})
- self.assert_compile(select([table1, exists([1],
- from_obj=table2).label('foo')]),
+ self.assert_compile(select([table1,
+ exists([1],
+ from_obj=table2).label('foo')]),
'SELECT mytable.myid, mytable.name, '
'mytable.description, EXISTS (SELECT 1 '
'FROM myothertable) AS foo FROM mytable',
params={})
- self.assert_compile(table1.select(exists().where(table2.c.otherid
- == table1.c.myid).correlate(table1)),
- 'SELECT mytable.myid, mytable.name, '
- 'mytable.description FROM mytable WHERE '
- 'EXISTS (SELECT * FROM myothertable WHERE '
- 'myothertable.otherid = mytable.myid)')
- self.assert_compile(table1.select(exists().where(table2.c.otherid
- == table1.c.myid).correlate(table1)),
- 'SELECT mytable.myid, mytable.name, '
- 'mytable.description FROM mytable WHERE '
- 'EXISTS (SELECT * FROM myothertable WHERE '
- 'myothertable.otherid = mytable.myid)')
- self.assert_compile(table1.select(exists().where(table2.c.otherid
- == table1.c.myid).correlate(table1)
- ).replace_selectable(table2,
- table2.alias()),
- 'SELECT mytable.myid, mytable.name, '
- 'mytable.description FROM mytable WHERE '
- 'EXISTS (SELECT * FROM myothertable AS '
- 'myothertable_1 WHERE myothertable_1.otheri'
- 'd = mytable.myid)')
- self.assert_compile(table1.select(exists().where(table2.c.otherid
- == table1.c.myid).correlate(table1)).select_from(
- table1.join(table2,
- table1.c.myid
- == table2.c.otherid)).replace_selectable(table2,
- table2.alias()),
- 'SELECT mytable.myid, mytable.name, '
- 'mytable.description FROM mytable JOIN '
- 'myothertable AS myothertable_1 ON '
- 'mytable.myid = myothertable_1.otherid '
- 'WHERE EXISTS (SELECT * FROM myothertable '
- 'AS myothertable_1 WHERE '
- 'myothertable_1.otherid = mytable.myid)')
+ self.assert_compile(
+ table1.select(
+ exists().where(
+ table2.c.otherid == table1.c.myid).correlate(table1)),
+ 'SELECT mytable.myid, mytable.name, '
+ 'mytable.description FROM mytable WHERE '
+ 'EXISTS (SELECT * FROM myothertable WHERE '
+ 'myothertable.otherid = mytable.myid)')
+ self.assert_compile(
+ table1.select(
+ exists().where(
+ table2.c.otherid == table1.c.myid).correlate(table1)),
+ 'SELECT mytable.myid, mytable.name, '
+ 'mytable.description FROM mytable WHERE '
+ 'EXISTS (SELECT * FROM myothertable WHERE '
+ 'myothertable.otherid = mytable.myid)')
+ self.assert_compile(
+ table1.select(
+ exists().where(
+ table2.c.otherid == table1.c.myid).correlate(table1)
+ ).replace_selectable(
+ table2,
+ table2.alias()),
+ 'SELECT mytable.myid, mytable.name, '
+ 'mytable.description FROM mytable WHERE '
+ 'EXISTS (SELECT * FROM myothertable AS '
+ 'myothertable_1 WHERE myothertable_1.otheri'
+ 'd = mytable.myid)')
+ self.assert_compile(
+ table1.select(
+ exists().where(
+ table2.c.otherid == table1.c.myid).correlate(table1)).
+ select_from(
+ table1.join(
+ table2,
+ table1.c.myid == table2.c.otherid)).
+ replace_selectable(
+ table2,
+ table2.alias()),
+ 'SELECT mytable.myid, mytable.name, '
+ 'mytable.description FROM mytable JOIN '
+ 'myothertable AS myothertable_1 ON '
+ 'mytable.myid = myothertable_1.otherid '
+ 'WHERE EXISTS (SELECT * FROM myothertable '
+ 'AS myothertable_1 WHERE '
+ 'myothertable_1.otherid = mytable.myid)')
self.assert_compile(
select([
"myothertable.otherid = :otherid_2)) AS anon_1"
)
-
def test_where_subquery(self):
s = select([addresses.c.street], addresses.c.user_id
== users.c.user_id, correlate=True).alias('s')
"(SELECT addresses.street AS street FROM "
"addresses, users WHERE addresses.user_id = "
"users.user_id) AS s")
- self.assert_compile(table1.select(table1.c.myid
- == select([table1.c.myid], table1.c.name
- == 'jack')),
- 'SELECT mytable.myid, mytable.name, '
- 'mytable.description FROM mytable WHERE '
- 'mytable.myid = (SELECT mytable.myid FROM '
- 'mytable WHERE mytable.name = :name_1)')
- self.assert_compile(table1.select(table1.c.myid
- == select([table2.c.otherid], table1.c.name
- == table2.c.othername)),
- 'SELECT mytable.myid, mytable.name, '
- 'mytable.description FROM mytable WHERE '
- 'mytable.myid = (SELECT '
- 'myothertable.otherid FROM myothertable '
- 'WHERE mytable.name = myothertable.othernam'
- 'e)')
+ self.assert_compile(table1.select(
+ table1.c.myid == select(
+ [table1.c.myid],
+ table1.c.name == 'jack')),
+ 'SELECT mytable.myid, mytable.name, '
+ 'mytable.description FROM mytable WHERE '
+ 'mytable.myid = (SELECT mytable.myid FROM '
+ 'mytable WHERE mytable.name = :name_1)')
+ self.assert_compile(
+ table1.select(
+ table1.c.myid == select(
+ [table2.c.otherid],
+ table1.c.name == table2.c.othername
+ )
+ ),
+ 'SELECT mytable.myid, mytable.name, '
+ 'mytable.description FROM mytable WHERE '
+ 'mytable.myid = (SELECT '
+ 'myothertable.otherid FROM myothertable '
+ 'WHERE mytable.name = myothertable.othernam'
+ 'e)')
self.assert_compile(table1.select(exists([1], table2.c.otherid
- == table1.c.myid)),
+ == table1.c.myid)),
'SELECT mytable.myid, mytable.name, '
'mytable.description FROM mytable WHERE '
'EXISTS (SELECT 1 FROM myothertable WHERE '
'myothertable.otherid = mytable.myid)')
talias = table1.alias('ta')
s = subquery('sq2', [talias], exists([1], table2.c.otherid
- == talias.c.myid))
+ == talias.c.myid))
self.assert_compile(select([s, table1]),
'SELECT sq2.myid, sq2.name, '
'sq2.description, mytable.myid, '
'myothertable WHERE myothertable.otherid = '
'ta.myid)) AS sq2, mytable')
-
# test constructing the outer query via append_column(), which
# occurs in the ORM's Query object
'EXISTS (SELECT 1 FROM myothertable WHERE '
'myothertable.otherid = mytable.myid)')
-
def test_orderby_subquery(self):
- self.assert_compile(table1.select(order_by=[select([table2.c.otherid],
- table1.c.myid == table2.c.otherid)]),
- 'SELECT mytable.myid, mytable.name, '
- 'mytable.description FROM mytable ORDER BY '
- '(SELECT myothertable.otherid FROM '
- 'myothertable WHERE mytable.myid = '
- 'myothertable.otherid)')
+ self.assert_compile(
+ table1.select(
+ order_by=[
+ select(
+ [
+ table2.c.otherid],
+ table1.c.myid == table2.c.otherid)]),
+ 'SELECT mytable.myid, mytable.name, '
+ 'mytable.description FROM mytable ORDER BY '
+ '(SELECT myothertable.otherid FROM '
+ 'myothertable WHERE mytable.myid = '
+ 'myothertable.otherid)')
self.assert_compile(table1.select(order_by=[
desc(select([table2.c.otherid],
- table1.c.myid == table2.c.otherid))]),
+ table1.c.myid == table2.c.otherid))]),
'SELECT mytable.myid, mytable.name, '
'mytable.description FROM mytable ORDER BY '
'(SELECT myothertable.otherid FROM '
s = select([table1.c.myid]).alias()
self.assert_compile(select([table1.c.myid]).where(table1.c.myid
- == s),
+ == s),
'SELECT mytable.myid FROM mytable WHERE '
'mytable.myid = (SELECT mytable.myid FROM '
'mytable)')
self.assert_compile(select([table1.c.myid]).where(s
- > table1.c.myid),
+ > table1.c.myid),
'SELECT mytable.myid FROM mytable WHERE '
'mytable.myid < (SELECT mytable.myid FROM '
'mytable)')
'SELECT (SELECT mytable.myid FROM mytable) '
'- :param_1 AS anon_1')
self.assert_compile(select([select([table1.c.name]).as_scalar()
- + literal('x')]),
+ + literal('x')]),
'SELECT (SELECT mytable.name FROM mytable) '
'|| :param_1 AS anon_1')
self.assert_compile(select([s > literal(8)]),
'SELECT (SELECT mytable.myid FROM mytable) '
'> :param_1 AS anon_1')
self.assert_compile(select([select([table1.c.name]).label('foo'
- )]),
+ )]),
'SELECT (SELECT mytable.name FROM mytable) '
'AS foo')
'object directly within a column-level expression.'
zips = table('zips',
- column('zipcode'),
- column('latitude'),
- column('longitude'),
- )
+ column('zipcode'),
+ column('latitude'),
+ column('longitude'),
+ )
places = table('places',
- column('id'),
- column('nm')
- )
+ column('id'),
+ column('nm')
+ )
zip = '12345'
qlat = select([zips.c.latitude], zips.c.zipcode == zip).\
- correlate(None).as_scalar()
+ correlate(None).as_scalar()
qlng = select([zips.c.longitude], zips.c.zipcode == zip).\
- correlate(None).as_scalar()
+ correlate(None).as_scalar()
q = select([places.c.id, places.c.nm, zips.c.zipcode,
- func.latlondist(qlat, qlng).label('dist')],
- zips.c.zipcode == zip,
- order_by=['dist', places.c.nm]
- )
+ func.latlondist(qlat, qlng).label('dist')],
+ zips.c.zipcode == zip,
+ order_by=['dist', places.c.nm]
+ )
self.assert_compile(q,
'SELECT places.id, places.nm, '
zalias = zips.alias('main_zip')
qlat = select([zips.c.latitude], zips.c.zipcode == zalias.c.zipcode).\
- as_scalar()
+ as_scalar()
qlng = select([zips.c.longitude], zips.c.zipcode == zalias.c.zipcode).\
- as_scalar()
+ as_scalar()
q = select([places.c.id, places.c.nm, zalias.c.zipcode,
- func.latlondist(qlat, qlng).label('dist')],
+ func.latlondist(qlat, qlng).label('dist')],
order_by=['dist', places.c.nm])
self.assert_compile(q,
'SELECT places.id, places.nm, '
def test_label_comparison_two(self):
self.assert_compile(
- label('bar', column('foo', type_=String)) + 'foo',
- 'foo || :param_1')
-
+ label('bar', column('foo', type_=String)) + 'foo',
+ 'foo || :param_1')
def test_order_by_labels_enabled(self):
lab1 = (table1.c.myid + 12).label('foo')
dialect = default.DefaultDialect()
self.assert_compile(select([lab1, lab2]).order_by(lab1, desc(lab2)),
- "SELECT mytable.myid + :myid_1 AS foo, "
- "somefunc(mytable.name) AS bar FROM mytable "
- "ORDER BY foo, bar DESC",
- dialect=dialect
- )
+ "SELECT mytable.myid + :myid_1 AS foo, "
+ "somefunc(mytable.name) AS bar FROM mytable "
+ "ORDER BY foo, bar DESC",
+ dialect=dialect
+ )
# the function embedded label renders as the function
self.assert_compile(
# binary expressions render as the expression without labels
self.assert_compile(select([lab1, lab2]).order_by(lab1 + "test"),
- "SELECT mytable.myid + :myid_1 AS foo, "
- "somefunc(mytable.name) AS bar FROM mytable "
- "ORDER BY mytable.myid + :myid_1 + :param_1",
- dialect=dialect
- )
+ "SELECT mytable.myid + :myid_1 AS foo, "
+ "somefunc(mytable.name) AS bar FROM mytable "
+ "ORDER BY mytable.myid + :myid_1 + :param_1",
+ dialect=dialect
+ )
# labels within functions in the columns clause render
# with the expression
"foo(mytable.myid + :myid_1) AS foo_1 FROM mytable "
"ORDER BY foo, foo(mytable.myid + :myid_1)",
dialect=dialect
- )
-
+ )
lx = (table1.c.myid + table1.c.myid).label('lx')
ly = (func.lower(table1.c.name) + table1.c.description).label('ly')
"lower(mytable.name) || mytable.description AS ly "
"FROM mytable ORDER BY lx, ly DESC",
dialect=dialect
- )
+ )
def test_order_by_labels_disabled(self):
lab1 = (table1.c.myid + 12).label('foo')
lab2 = func.somefunc(table1.c.name).label('bar')
dialect = default.DefaultDialect()
dialect.supports_simple_order_by_label = False
- self.assert_compile(select([lab1, lab2]).order_by(lab1, desc(lab2)),
+ self.assert_compile(
+ select(
+ [
+ lab1,
+ lab2]).order_by(
+ lab1,
+ desc(lab2)),
"SELECT mytable.myid + :myid_1 AS foo, "
"somefunc(mytable.name) AS bar FROM mytable "
"ORDER BY mytable.myid + :myid_1, somefunc(mytable.name) DESC",
- dialect=dialect
- )
+ dialect=dialect)
self.assert_compile(
select([lab1, lab2]).order_by(func.hoho(lab1), desc(lab2)),
"SELECT mytable.myid + :myid_1 AS foo, "
def test_conjunctions(self):
a, b, c = 'a', 'b', 'c'
x = and_(a, b, c)
- assert isinstance(x.type, Boolean)
+ assert isinstance(x.type, Boolean)
assert str(x) == 'a AND b AND c'
self.assert_compile(
select([x.label('foo')]),
self.assert_compile(
and_(table1.c.myid == 12, table1.c.name == 'asdf',
- table2.c.othername == 'foo', "sysdate() = today()"),
- "mytable.myid = :myid_1 AND mytable.name = :name_1 "\
+ table2.c.othername == 'foo', "sysdate() = today()"),
+ "mytable.myid = :myid_1 AND mytable.name = :name_1 "
"AND myothertable.othername = "
":othername_1 AND sysdate() = today()"
)
"sysdate() = today()",
),
'mytable.myid = :myid_1 AND (myothertable.othername = '
- ':othername_1 OR myothertable.othername = :othername_2 OR '
- 'myothertable.otherid = :otherid_1) AND sysdate() = '
- 'today()',
+ ':othername_1 OR myothertable.othername = :othername_2 OR '
+ 'myothertable.otherid = :otherid_1) AND sysdate() = '
+ 'today()',
checkparams={'othername_1': 'asdf', 'othername_2': 'foo',
- 'otherid_1': 9, 'myid_1': 12}
+ 'otherid_1': 9, 'myid_1': 12}
)
# test a generator
self.assert_compile(
select([t]).where(and_(t.c.x == 5,
- or_(and_(or_(t.c.x == 7))))),
+ or_(and_(or_(t.c.x == 7))))),
"SELECT t.x FROM t WHERE t.x = :x_1 AND t.x = :x_2"
)
self.assert_compile(
select([t]).where(and_(or_(t.c.x == 12,
- and_(or_(t.c.x == 8))))),
+ and_(or_(t.c.x == 8))))),
"SELECT t.x FROM t WHERE t.x = :x_1 OR t.x = :x_2"
)
self.assert_compile(
- select([t]).where(and_(or_(or_(t.c.x == 12),
- and_(or_(), or_(and_(t.c.x == 8)), and_())))),
+ select([t]).
+ where(
+ and_(
+ or_(
+ or_(t.c.x == 12),
+ and_(
+ or_(),
+ or_(and_(t.c.x == 8)),
+ and_()
+ )
+ )
+ )
+ ),
"SELECT t.x FROM t WHERE t.x = :x_1 OR t.x = :x_2"
)
"SELECT count(DISTINCT mytable.myid) AS count_1 FROM mytable"
)
-
def test_where_empty(self):
self.assert_compile(
select([table1.c.myid]).where(and_()),
def test_multiple_col_binds(self):
self.assert_compile(
select(["*"], or_(table1.c.myid == 12, table1.c.myid == 'asdf',
- table1.c.myid == 'foo')),
+ table1.c.myid == 'foo')),
"SELECT * FROM mytable WHERE mytable.myid = :myid_1 "
"OR mytable.myid = :myid_2 OR mytable.myid = :myid_3"
)
self.assert_compile(
table2.select(order_by=[
- table2.c.otherid, table2.c.othername.desc().nullslast()]),
+ table2.c.otherid, table2.c.othername.desc().nullslast()]),
"SELECT myothertable.otherid, myothertable.othername FROM "
"myothertable ORDER BY myothertable.otherid, "
"myothertable.othername DESC NULLS LAST"
self.assert_compile(
table2.select(order_by=[
- table2.c.otherid.nullslast(),
- table2.c.othername.desc().nullsfirst()]),
+ table2.c.otherid.nullslast(),
+ table2.c.othername.desc().nullsfirst()]),
"SELECT myothertable.otherid, myothertable.othername FROM "
"myothertable ORDER BY myothertable.otherid NULLS LAST, "
"myothertable.othername DESC NULLS FIRST"
self.assert_compile(
table2.select(order_by=[table2.c.otherid.nullsfirst(),
- table2.c.othername.desc()]),
+ table2.c.othername.desc()]),
"SELECT myothertable.otherid, myothertable.othername FROM "
"myothertable ORDER BY myothertable.otherid NULLS FIRST, "
"myothertable.othername DESC"
self.assert_compile(
table2.select(order_by=[table2.c.otherid.nullsfirst(),
- table2.c.othername.desc().nullslast()]),
+ table2.c.othername.desc().nullslast()]),
"SELECT myothertable.otherid, myothertable.othername FROM "
"myothertable ORDER BY myothertable.otherid NULLS FIRST, "
"myothertable.othername DESC NULLS LAST"
def test_orderby_groupby(self):
self.assert_compile(
table2.select(order_by=[table2.c.otherid,
- asc(table2.c.othername)]),
+ asc(table2.c.othername)]),
"SELECT myothertable.otherid, myothertable.othername FROM "
"myothertable ORDER BY myothertable.otherid, "
"myothertable.othername ASC"
# generative order_by
self.assert_compile(
- table2.select().order_by(table2.c.otherid).\
- order_by(table2.c.othername.desc()),
+ table2.select().order_by(table2.c.otherid).
+ order_by(table2.c.othername.desc()),
"SELECT myothertable.otherid, myothertable.othername FROM "
"myothertable ORDER BY myothertable.otherid, "
"myothertable.othername DESC"
self.assert_compile(
table2.select().order_by(table2.c.otherid).
- order_by(table2.c.othername.desc()
- ).order_by(None),
+ order_by(table2.c.othername.desc()
+ ).order_by(None),
"SELECT myothertable.otherid, myothertable.othername "
"FROM myothertable"
)
self.assert_compile(
select(
- [table2.c.othername, func.count(table2.c.otherid)],
- group_by=[table2.c.othername]),
+ [table2.c.othername, func.count(table2.c.otherid)],
+ group_by=[table2.c.othername]),
"SELECT myothertable.othername, "
"count(myothertable.otherid) AS count_1 "
"FROM myothertable GROUP BY myothertable.othername"
# generative group by
self.assert_compile(
select([table2.c.othername, func.count(table2.c.otherid)]).
- group_by(table2.c.othername),
+ group_by(table2.c.othername),
"SELECT myothertable.othername, "
"count(myothertable.otherid) AS count_1 "
"FROM myothertable GROUP BY myothertable.othername"
self.assert_compile(
select([table2.c.othername, func.count(table2.c.otherid)]).
- group_by(table2.c.othername).group_by(None),
+ group_by(table2.c.othername).group_by(None),
"SELECT myothertable.othername, "
"count(myothertable.otherid) AS count_1 "
"FROM myothertable"
self.assert_compile(
select([table2.c.othername, func.count(table2.c.otherid)],
- group_by=[table2.c.othername],
- order_by=[table2.c.othername]),
+ group_by=[table2.c.othername],
+ order_by=[table2.c.othername]),
"SELECT myothertable.othername, "
"count(myothertable.otherid) AS count_1 "
"FROM myothertable "
table1.select, table1.c.myid == 7, for_update='unknown_mode'
)
-
def test_alias(self):
# test the alias for a table1. column names stay the same,
# table name "changes" to "foo".
# also, only use one column from the second table and all columns
# from the first table1.
q = select(
- [table1, table2.c.otherid],
- table1.c.myid == table2.c.otherid, use_labels=True
- )
+ [table1, table2.c.otherid],
+ table1.c.myid == table2.c.otherid, use_labels=True
+ )
# make an alias of the "selectable". column names
# stay the same (i.e. the labels), table name "changes" to "t2view".
"t2view.mytable_description AS t2view_mytable_description, "
"t2view.myothertable_otherid AS t2view_myothertable_otherid FROM "
"(SELECT mytable.myid AS mytable_myid, "
- "mytable.name AS mytable_name, "
+ "mytable.name AS mytable_name, "
"mytable.description AS mytable_description, "
- "myothertable.otherid AS "
+ "myothertable.otherid AS "
"myothertable_otherid FROM mytable, myothertable "
- "WHERE mytable.myid = "
+ "WHERE mytable.myid = "
"myothertable.otherid) AS t2view "
- "WHERE t2view.mytable_myid = :mytable_myid_1"
+ "WHERE t2view.mytable_myid = :mytable_myid_1"
)
-
def test_prefix(self):
self.assert_compile(
- table1.select().prefix_with("SQL_CALC_FOUND_ROWS").\
- prefix_with("SQL_SOME_WEIRD_MYSQL_THING"),
+ table1.select().prefix_with("SQL_CALC_FOUND_ROWS").
+ prefix_with("SQL_SOME_WEIRD_MYSQL_THING"),
"SELECT SQL_CALC_FOUND_ROWS SQL_SOME_WEIRD_MYSQL_THING "
"mytable.myid, mytable.name, mytable.description FROM mytable"
)
def test_prefix_dialect_specific(self):
self.assert_compile(
table1.select().prefix_with("SQL_CALC_FOUND_ROWS",
- dialect='sqlite').\
- prefix_with("SQL_SOME_WEIRD_MYSQL_THING",
- dialect='mysql'),
+ dialect='sqlite').
+ prefix_with("SQL_SOME_WEIRD_MYSQL_THING",
+ dialect='mysql'),
"SELECT SQL_SOME_WEIRD_MYSQL_THING "
"mytable.myid, mytable.name, mytable.description FROM mytable",
dialect=mysql.dialect()
SQL in the columns clause."""
dialect = default.DefaultDialect()
+
class Compiler(dialect.statement_compiler):
ansi_bind_rules = True
dialect.statement_compiler = Compiler
assert_raises_message(
exc.CompileError,
- "Bind parameter 'foo' without a renderable value not allowed here.",
- bindparam("foo").in_([]).compile, dialect=dialect
- )
-
+ "Bind parameter 'foo' without a "
+ "renderable value not allowed here.",
+ bindparam("foo").in_(
+ []).compile,
+ dialect=dialect)
def test_literal(self):
self.assert_compile(select([literal('foo')]),
- "SELECT :param_1 AS anon_1")
+ "SELECT :param_1 AS anon_1")
- self.assert_compile(select([literal("foo") + literal("bar")],
- from_obj=[table1]),
+ self.assert_compile(
+ select(
+ [
+ literal("foo") +
+ literal("bar")],
+ from_obj=[table1]),
"SELECT :param_1 || :param_2 AS anon_1 FROM mytable")
def test_calculated_columns(self):
value_tbl = table('values',
- column('id', Integer),
- column('val1', Float),
- column('val2', Float),
- )
+ column('id', Integer),
+ column('val1', Float),
+ column('val2', Float),
+ )
self.assert_compile(
- select([value_tbl.c.id, (value_tbl.c.val2 -
- value_tbl.c.val1) / value_tbl.c.val1]),
- "SELECT values.id, (values.val2 - values.val1) "
- "/ values.val1 AS anon_1 FROM values"
- )
+ select([value_tbl.c.id, (value_tbl.c.val2 -
+ value_tbl.c.val1) / value_tbl.c.val1]),
+ "SELECT values.id, (values.val2 - values.val1) "
+ "/ values.val1 AS anon_1 FROM values"
+ )
self.assert_compile(
- select([value_tbl.c.id], (value_tbl.c.val2 -
- value_tbl.c.val1) / value_tbl.c.val1 > 2.0),
- "SELECT values.id FROM values WHERE "
- "(values.val2 - values.val1) / values.val1 > :param_1"
- )
+ select([
+ value_tbl.c.id],
+ (value_tbl.c.val2 - value_tbl.c.val1) /
+ value_tbl.c.val1 > 2.0),
+ "SELECT values.id FROM values WHERE "
+ "(values.val2 - values.val1) / values.val1 > :param_1"
+ )
self.assert_compile(
- select([value_tbl.c.id], value_tbl.c.val1 /
- (value_tbl.c.val2 - value_tbl.c.val1) /
- value_tbl.c.val1 > 2.0),
- "SELECT values.id FROM values WHERE "
- "(values.val1 / (values.val2 - values.val1)) "
- "/ values.val1 > :param_1"
- )
+ select([value_tbl.c.id], value_tbl.c.val1 /
+ (value_tbl.c.val2 - value_tbl.c.val1) /
+ value_tbl.c.val1 > 2.0),
+ "SELECT values.id FROM values WHERE "
+ "(values.val1 / (values.val2 - values.val1)) "
+ "/ values.val1 > :param_1"
+ )
def test_percent_chars(self):
t = table("table%name",
- column("percent%"),
- column("%(oneofthese)s"),
- column("spaces % more spaces"),
- )
+ column("percent%"),
+ column("%(oneofthese)s"),
+ column("spaces % more spaces"),
+ )
self.assert_compile(
t.select(use_labels=True),
- '''SELECT "table%name"."percent%" AS "table%name_percent%", '''\
- '''"table%name"."%(oneofthese)s" AS '''\
- '''"table%name_%(oneofthese)s", '''\
- '''"table%name"."spaces % more spaces" AS '''\
- '''"table%name_spaces % '''\
+ '''SELECT "table%name"."percent%" AS "table%name_percent%", '''
+ '''"table%name"."%(oneofthese)s" AS '''
+ '''"table%name_%(oneofthese)s", '''
+ '''"table%name"."spaces % more spaces" AS '''
+ '''"table%name_spaces % '''
'''more spaces" FROM "table%name"'''
)
-
def test_joins(self):
self.assert_compile(
join(table2, table1, table1.c.myid == table2.c.otherid).select(),
self.assert_compile(
select(
- [table1],
+ [table1],
from_obj=[join(table1, table2, table1.c.myid
- == table2.c.otherid)]
+ == table2.c.otherid)]
),
- "SELECT mytable.myid, mytable.name, mytable.description FROM "
- "mytable JOIN myothertable ON mytable.myid = myothertable.otherid")
+ "SELECT mytable.myid, mytable.name, mytable.description FROM "
+ "mytable JOIN myothertable ON mytable.myid = myothertable.otherid")
self.assert_compile(
select(
[join(join(table1, table2, table1.c.myid == table2.c.otherid),
- table3, table1.c.myid == table3.c.userid)]
+ table3, table1.c.myid == table3.c.userid)]
),
"SELECT mytable.myid, mytable.name, mytable.description, "
"myothertable.otherid, myothertable.othername, "
self.assert_compile(
join(users, addresses, users.c.user_id ==
- addresses.c.user_id).select(),
+ addresses.c.user_id).select(),
"SELECT users.user_id, users.user_name, users.password, "
"addresses.address_id, addresses.user_id, addresses.street, "
"addresses.city, addresses.state, addresses.zip "
)
self.assert_compile(
- select([table1, table2, table3],
+ select([table1, table2, table3],
- from_obj=[join(table1, table2,
- table1.c.myid == table2.c.otherid).
- outerjoin(table3,
- table1.c.myid == table3.c.userid)]
- ),
- "SELECT mytable.myid, mytable.name, mytable.description, "
- "myothertable.otherid, myothertable.othername, "
- "thirdtable.userid,"
- " thirdtable.otherstuff FROM mytable "
- "JOIN myothertable ON mytable.myid "
- "= myothertable.otherid LEFT OUTER JOIN thirdtable "
- "ON mytable.myid ="
- " thirdtable.userid"
- )
+ from_obj=[join(table1, table2,
+ table1.c.myid == table2.c.otherid).
+ outerjoin(table3,
+ table1.c.myid == table3.c.userid)]
+ ),
+ "SELECT mytable.myid, mytable.name, mytable.description, "
+ "myothertable.otherid, myothertable.othername, "
+ "thirdtable.userid,"
+ " thirdtable.otherstuff FROM mytable "
+ "JOIN myothertable ON mytable.myid "
+ "= myothertable.otherid LEFT OUTER JOIN thirdtable "
+ "ON mytable.myid ="
+ " thirdtable.userid"
+ )
self.assert_compile(
- select([table1, table2, table3],
- from_obj=[outerjoin(table1,
- join(table2, table3, table2.c.otherid
- == table3.c.userid),
- table1.c.myid == table2.c.otherid)]
- ),
- "SELECT mytable.myid, mytable.name, mytable.description, "
- "myothertable.otherid, myothertable.othername, "
- "thirdtable.userid,"
- " thirdtable.otherstuff FROM mytable LEFT OUTER JOIN "
- "(myothertable "
- "JOIN thirdtable ON myothertable.otherid = "
- "thirdtable.userid) ON "
- "mytable.myid = myothertable.otherid"
- )
+ select([table1, table2, table3],
+ from_obj=[outerjoin(table1,
+ join(table2, table3, table2.c.otherid
+ == table3.c.userid),
+ table1.c.myid == table2.c.otherid)]
+ ),
+ "SELECT mytable.myid, mytable.name, mytable.description, "
+ "myothertable.otherid, myothertable.othername, "
+ "thirdtable.userid,"
+ " thirdtable.otherstuff FROM mytable LEFT OUTER JOIN "
+ "(myothertable "
+ "JOIN thirdtable ON myothertable.otherid = "
+ "thirdtable.userid) ON "
+ "mytable.myid = myothertable.otherid"
+ )
query = select(
- [table1, table2],
- or_(
- table1.c.name == 'fred',
- table1.c.myid == 10,
- table2.c.othername != 'jack',
- "EXISTS (select yay from foo where boo = lar)"
- ),
- from_obj=[outerjoin(table1, table2,
+ [table1, table2],
+ or_(
+ table1.c.name == 'fred',
+ table1.c.myid == 10,
+ table2.c.othername != 'jack',
+ "EXISTS (select yay from foo where boo = lar)"
+ ),
+ from_obj=[outerjoin(table1, table2,
table1.c.myid == table2.c.otherid)]
- )
- self.assert_compile(query,
- "SELECT mytable.myid, mytable.name, mytable.description, "
+ )
+ self.assert_compile(
+ query, "SELECT mytable.myid, mytable.name, mytable.description, "
"myothertable.otherid, myothertable.othername "
"FROM mytable LEFT OUTER JOIN myothertable ON mytable.myid = "
"myothertable.otherid WHERE mytable.name = :name_1 OR "
"mytable.myid = :myid_1 OR myothertable.othername != :othername_1 "
- "OR EXISTS (select yay from foo where boo = lar)",
- )
+ "OR EXISTS (select yay from foo where boo = lar)", )
def test_compound_selects(self):
assert_raises_message(
)
x = union(
- select([table1], table1.c.myid == 5),
- select([table1], table1.c.myid == 12),
- order_by=[table1.c.myid],
+ select([table1], table1.c.myid == 5),
+ select([table1], table1.c.myid == 12),
+ order_by=[table1.c.myid],
)
- self.assert_compile(x,
- "SELECT mytable.myid, mytable.name, "
- "mytable.description "
- "FROM mytable WHERE "
- "mytable.myid = :myid_1 UNION "
- "SELECT mytable.myid, mytable.name, mytable.description "
- "FROM mytable WHERE mytable.myid = :myid_2 "
- "ORDER BY mytable.myid")
+ self.assert_compile(
+ x, "SELECT mytable.myid, mytable.name, "
+ "mytable.description "
+ "FROM mytable WHERE "
+ "mytable.myid = :myid_1 UNION "
+ "SELECT mytable.myid, mytable.name, mytable.description "
+ "FROM mytable WHERE mytable.myid = :myid_2 "
+ "ORDER BY mytable.myid")
x = union(
- select([table1]),
- select([table1])
+ select([table1]),
+ select([table1])
)
x = union(x, select([table1]))
- self.assert_compile(x,
- "(SELECT mytable.myid, mytable.name, mytable.description "
- "FROM mytable UNION SELECT mytable.myid, mytable.name, "
- "mytable.description FROM mytable) UNION SELECT mytable.myid,"
- " mytable.name, mytable.description FROM mytable")
+ self.assert_compile(
+ x, "(SELECT mytable.myid, mytable.name, mytable.description "
+ "FROM mytable UNION SELECT mytable.myid, mytable.name, "
+ "mytable.description FROM mytable) UNION SELECT mytable.myid,"
+ " mytable.name, mytable.description FROM mytable")
u1 = union(
select([table1.c.myid, table1.c.name]),
select([table2]),
select([table3])
)
- self.assert_compile(u1,
- "SELECT mytable.myid, mytable.name "
- "FROM mytable UNION SELECT myothertable.otherid, "
- "myothertable.othername FROM myothertable "
- "UNION SELECT thirdtable.userid, thirdtable.otherstuff "
- "FROM thirdtable")
+ self.assert_compile(
+ u1, "SELECT mytable.myid, mytable.name "
+ "FROM mytable UNION SELECT myothertable.otherid, "
+ "myothertable.othername FROM myothertable "
+ "UNION SELECT thirdtable.userid, thirdtable.otherstuff "
+ "FROM thirdtable")
assert u1.corresponding_column(table2.c.otherid) is u1.c.myid
self.assert_compile(
union(
select([table1.c.myid, table1.c.name,
- func.max(table1.c.description)],
- table1.c.name == 'name2',
- group_by=[table1.c.myid, table1.c.name]),
+ func.max(table1.c.description)],
+ table1.c.name == 'name2',
+ group_by=[table1.c.myid, table1.c.name]),
table1.select(table1.c.name == 'name1')
),
"SELECT mytable.myid, mytable.name, "
union(
select([literal(100).label('value')]),
select([literal(200).label('value')])
- ),
- "SELECT :param_1 AS value UNION SELECT :param_2 AS value"
+ ),
+ "SELECT :param_1 AS value UNION SELECT :param_2 AS value"
)
self.assert_compile(
"SELECT thirdtable.userid FROM thirdtable)"
)
-
s = select([column('foo'), column('bar')])
# ORDER BY's even though not supported by
# all DB's, are rendered if requested
- self.assert_compile(union(s.order_by("foo"), s.order_by("bar")),
- "SELECT foo, bar ORDER BY foo UNION SELECT foo, bar ORDER BY bar"
- )
+ self.assert_compile(
+ union(
+ s.order_by("foo"),
+ s.order_by("bar")),
+ "SELECT foo, bar ORDER BY foo UNION SELECT foo, bar ORDER BY bar")
# self_group() is honored
self.assert_compile(
union(s.order_by("foo").self_group(),
- s.order_by("bar").limit(10).self_group()),
+ s.order_by("bar").limit(10).self_group()),
"(SELECT foo, bar ORDER BY foo) UNION (SELECT foo, "
- "bar ORDER BY bar LIMIT :param_1)",
+ "bar ORDER BY bar LIMIT :param_1)",
{'param_1': 10}
)
union(s, union(s, union(s, s))),
"SELECT foo, bar FROM bat UNION (SELECT foo, bar FROM bat "
"UNION (SELECT foo, bar FROM bat "
- "UNION SELECT foo, bar FROM bat))"
+ "UNION SELECT foo, bar FROM bat))"
)
self.assert_compile(
select([union(s, s).alias()]),
'SELECT anon_1.foo, anon_1.bar FROM '
'(SELECT foo, bar FROM bat UNION '
- 'SELECT foo, bar FROM bat) AS anon_1'
+ 'SELECT foo, bar FROM bat) AS anon_1'
)
self.assert_compile(
select([except_(s, s).alias()]),
'SELECT anon_1.foo, anon_1.bar FROM '
'(SELECT foo, bar FROM bat EXCEPT '
- 'SELECT foo, bar FROM bat) AS anon_1'
+ 'SELECT foo, bar FROM bat) AS anon_1'
)
# this query sqlite specifically chokes on
),
"SELECT anon_1.foo, anon_1.bar FROM "
"(SELECT foo, bar FROM bat EXCEPT "
- "SELECT foo, bar FROM bat) AS anon_1 "
+ "SELECT foo, bar FROM bat) AS anon_1 "
"UNION SELECT foo, bar FROM bat"
)
"UNION (SELECT foo, bar FROM bat "
"UNION SELECT foo, bar FROM bat)")
-
self.assert_compile(
union(
intersect(s, s),
),
"(SELECT foo, bar FROM bat INTERSECT SELECT foo, bar FROM bat) "
"UNION (SELECT foo, bar FROM bat INTERSECT "
- "SELECT foo, bar FROM bat)"
+ "SELECT foo, bar FROM bat)"
)
def test_binds(self):
for (
- stmt,
- expected_named_stmt,
- expected_positional_stmt,
- expected_default_params_dict,
- expected_default_params_list,
- test_param_dict,
- expected_test_params_dict,
- expected_test_params_list
- ) in [
- (
- select(
- [table1, table2],
- and_(
- table1.c.myid == table2.c.otherid,
- table1.c.name == bindparam('mytablename')
- )),
- "SELECT mytable.myid, mytable.name, mytable.description, "
- "myothertable.otherid, myothertable.othername FROM mytable, "
- "myothertable WHERE mytable.myid = myothertable.otherid "
- "AND mytable.name = :mytablename",
- "SELECT mytable.myid, mytable.name, mytable.description, "
- "myothertable.otherid, myothertable.othername FROM mytable, "
- "myothertable WHERE mytable.myid = myothertable.otherid AND "
- "mytable.name = ?",
- {'mytablename':None}, [None],
- {'mytablename':5}, {'mytablename':5}, [5]
- ),
- (
- select([table1], or_(table1.c.myid == bindparam('myid'),
- table2.c.otherid == bindparam('myid'))),
- "SELECT mytable.myid, mytable.name, mytable.description "
- "FROM mytable, myothertable WHERE mytable.myid = :myid "
- "OR myothertable.otherid = :myid",
- "SELECT mytable.myid, mytable.name, mytable.description "
- "FROM mytable, myothertable WHERE mytable.myid = ? "
- "OR myothertable.otherid = ?",
- {'myid': None}, [None, None],
- {'myid': 5}, {'myid': 5}, [5, 5]
- ),
- (
- text("SELECT mytable.myid, mytable.name, mytable.description FROM "
- "mytable, myothertable WHERE mytable.myid = :myid OR "
- "myothertable.otherid = :myid"),
- "SELECT mytable.myid, mytable.name, mytable.description FROM "
- "mytable, myothertable WHERE mytable.myid = :myid OR "
- "myothertable.otherid = :myid",
- "SELECT mytable.myid, mytable.name, mytable.description FROM "
- "mytable, myothertable WHERE mytable.myid = ? OR "
- "myothertable.otherid = ?",
- {'myid':None}, [None, None],
- {'myid': 5}, {'myid': 5}, [5, 5]
- ),
- (
- select([table1], or_(table1.c.myid ==
- bindparam('myid', unique=True),
- table2.c.otherid ==
- bindparam('myid', unique=True))),
- "SELECT mytable.myid, mytable.name, mytable.description FROM "
- "mytable, myothertable WHERE mytable.myid = "
- ":myid_1 OR myothertable.otherid = :myid_2",
- "SELECT mytable.myid, mytable.name, mytable.description FROM "
- "mytable, myothertable WHERE mytable.myid = ? "
- "OR myothertable.otherid = ?",
- {'myid_1':None, 'myid_2':None}, [None, None],
- {'myid_1': 5, 'myid_2': 6}, {'myid_1': 5, 'myid_2': 6}, [5, 6]
- ),
- (
+ stmt,
+ expected_named_stmt,
+ expected_positional_stmt,
+ expected_default_params_dict,
+ expected_default_params_list,
+ test_param_dict,
+ expected_test_params_dict,
+ expected_test_params_list
+ ) in [
+ (
+ select(
+ [table1, table2],
+ and_(
+ table1.c.myid == table2.c.otherid,
+ table1.c.name == bindparam('mytablename')
+ )),
+ "SELECT mytable.myid, mytable.name, mytable.description, "
+ "myothertable.otherid, myothertable.othername FROM mytable, "
+ "myothertable WHERE mytable.myid = myothertable.otherid "
+ "AND mytable.name = :mytablename",
+ "SELECT mytable.myid, mytable.name, mytable.description, "
+ "myothertable.otherid, myothertable.othername FROM mytable, "
+ "myothertable WHERE mytable.myid = myothertable.otherid AND "
+ "mytable.name = ?",
+ {'mytablename': None}, [None],
+ {'mytablename': 5}, {'mytablename': 5}, [5]
+ ),
+ (
+ select([table1], or_(table1.c.myid == bindparam('myid'),
+ table2.c.otherid == bindparam('myid'))),
+ "SELECT mytable.myid, mytable.name, mytable.description "
+ "FROM mytable, myothertable WHERE mytable.myid = :myid "
+ "OR myothertable.otherid = :myid",
+ "SELECT mytable.myid, mytable.name, mytable.description "
+ "FROM mytable, myothertable WHERE mytable.myid = ? "
+ "OR myothertable.otherid = ?",
+ {'myid': None}, [None, None],
+ {'myid': 5}, {'myid': 5}, [5, 5]
+ ),
+ (
+ text("SELECT mytable.myid, mytable.name, "
+ "mytable.description FROM "
+ "mytable, myothertable WHERE mytable.myid = :myid OR "
+ "myothertable.otherid = :myid"),
+ "SELECT mytable.myid, mytable.name, mytable.description FROM "
+ "mytable, myothertable WHERE mytable.myid = :myid OR "
+ "myothertable.otherid = :myid",
+ "SELECT mytable.myid, mytable.name, mytable.description FROM "
+ "mytable, myothertable WHERE mytable.myid = ? OR "
+ "myothertable.otherid = ?",
+ {'myid': None}, [None, None],
+ {'myid': 5}, {'myid': 5}, [5, 5]
+ ),
+ (
+ select([table1], or_(table1.c.myid ==
+ bindparam('myid', unique=True),
+ table2.c.otherid ==
+ bindparam('myid', unique=True))),
+ "SELECT mytable.myid, mytable.name, mytable.description FROM "
+ "mytable, myothertable WHERE mytable.myid = "
+ ":myid_1 OR myothertable.otherid = :myid_2",
+ "SELECT mytable.myid, mytable.name, mytable.description FROM "
+ "mytable, myothertable WHERE mytable.myid = ? "
+ "OR myothertable.otherid = ?",
+ {'myid_1': None, 'myid_2': None}, [None, None],
+ {'myid_1': 5, 'myid_2': 6}, {'myid_1': 5, 'myid_2': 6}, [5, 6]
+ ),
+ (
bindparam('test', type_=String, required=False) + text("'hi'"),
":test || 'hi'",
"? || 'hi'",
- {'test':None}, [None],
- {}, {'test':None}, [None]
- ),
- (
+ {'test': None}, [None],
+ {}, {'test': None}, [None]
+ ),
+ (
# testing select.params() here - bindparam() objects
# must get required flag set to False
- select([table1], or_(table1.c.myid == bindparam('myid'),
- table2.c.otherid == bindparam('myotherid'))).\
- params({'myid':8, 'myotherid':7}),
- "SELECT mytable.myid, mytable.name, mytable.description FROM "
- "mytable, myothertable WHERE mytable.myid = "
- ":myid OR myothertable.otherid = :myotherid",
- "SELECT mytable.myid, mytable.name, mytable.description FROM "
- "mytable, myothertable WHERE mytable.myid = "
- "? OR myothertable.otherid = ?",
- {'myid': 8, 'myotherid': 7}, [8, 7],
- {'myid': 5}, {'myid': 5, 'myotherid': 7}, [5, 7]
- ),
- (
- select([table1], or_(table1.c.myid ==
- bindparam('myid', value=7, unique=True),
- table2.c.otherid ==
- bindparam('myid', value=8, unique=True))),
- "SELECT mytable.myid, mytable.name, mytable.description FROM "
- "mytable, myothertable WHERE mytable.myid = "
- ":myid_1 OR myothertable.otherid = :myid_2",
- "SELECT mytable.myid, mytable.name, mytable.description FROM "
- "mytable, myothertable WHERE mytable.myid = "
- "? OR myothertable.otherid = ?",
- {'myid_1': 7, 'myid_2': 8}, [7, 8],
- {'myid_1': 5, 'myid_2': 6}, {'myid_1': 5, 'myid_2': 6}, [5, 6]
- ),
- ]:
-
- self.assert_compile(stmt, expected_named_stmt,
- params=expected_default_params_dict)
- self.assert_compile(stmt, expected_positional_stmt,
- dialect=sqlite.dialect())
- nonpositional = stmt.compile()
- positional = stmt.compile(dialect=sqlite.dialect())
- pp = positional.params
- eq_([pp[k] for k in positional.positiontup],
- expected_default_params_list)
-
- eq_(nonpositional.construct_params(test_param_dict),
- expected_test_params_dict)
- pp = positional.construct_params(test_param_dict)
- eq_(
- [pp[k] for k in positional.positiontup],
- expected_test_params_list
- )
+ select(
+ [table1],
+ or_(
+ table1.c.myid == bindparam('myid'),
+ table2.c.otherid == bindparam('myotherid')
+ )).params({'myid': 8, 'myotherid': 7}),
+ "SELECT mytable.myid, mytable.name, mytable.description FROM "
+ "mytable, myothertable WHERE mytable.myid = "
+ ":myid OR myothertable.otherid = :myotherid",
+ "SELECT mytable.myid, mytable.name, mytable.description FROM "
+ "mytable, myothertable WHERE mytable.myid = "
+ "? OR myothertable.otherid = ?",
+ {'myid': 8, 'myotherid': 7}, [8, 7],
+ {'myid': 5}, {'myid': 5, 'myotherid': 7}, [5, 7]
+ ),
+ (
+ select([table1], or_(table1.c.myid ==
+ bindparam('myid', value=7, unique=True),
+ table2.c.otherid ==
+ bindparam('myid', value=8, unique=True))),
+ "SELECT mytable.myid, mytable.name, mytable.description FROM "
+ "mytable, myothertable WHERE mytable.myid = "
+ ":myid_1 OR myothertable.otherid = :myid_2",
+ "SELECT mytable.myid, mytable.name, mytable.description FROM "
+ "mytable, myothertable WHERE mytable.myid = "
+ "? OR myothertable.otherid = ?",
+ {'myid_1': 7, 'myid_2': 8}, [7, 8],
+ {'myid_1': 5, 'myid_2': 6}, {'myid_1': 5, 'myid_2': 6}, [5, 6]
+ ),
+ ]:
+
+ self.assert_compile(stmt, expected_named_stmt,
+ params=expected_default_params_dict)
+ self.assert_compile(stmt, expected_positional_stmt,
+ dialect=sqlite.dialect())
+ nonpositional = stmt.compile()
+ positional = stmt.compile(dialect=sqlite.dialect())
+ pp = positional.params
+ eq_([pp[k] for k in positional.positiontup],
+ expected_default_params_list)
+
+ eq_(nonpositional.construct_params(test_param_dict),
+ expected_test_params_dict)
+ pp = positional.construct_params(test_param_dict)
+ eq_(
+ [pp[k] for k in positional.positiontup],
+ expected_test_params_list
+ )
# check that params() doesn't modify original statement
s = select([table1], or_(table1.c.myid == bindparam('myid'),
- table2.c.otherid ==
- bindparam('myotherid')))
+ table2.c.otherid ==
+ bindparam('myotherid')))
s2 = s.params({'myid': 8, 'myotherid': 7})
s3 = s2.params({'myid': 9})
assert s.compile().params == {'myid': None, 'myotherid': None}
# test using same 'unique' param object twice in one compile
s = select([table1.c.myid]).where(table1.c.myid == 12).as_scalar()
s2 = select([table1, s], table1.c.myid == s)
- self.assert_compile(s2,
- "SELECT mytable.myid, mytable.name, mytable.description, "
- "(SELECT mytable.myid FROM mytable WHERE mytable.myid = "\
+ self.assert_compile(
+ s2, "SELECT mytable.myid, mytable.name, mytable.description, "
+ "(SELECT mytable.myid FROM mytable WHERE mytable.myid = "
":myid_1) AS anon_1 FROM mytable WHERE mytable.myid = "
"(SELECT mytable.myid FROM mytable WHERE mytable.myid = :myid_1)")
positional = s2.compile(dialect=sqlite.dialect())
# check that conflicts with "unique" params are caught
s = select([table1], or_(table1.c.myid == 7,
- table1.c.myid == bindparam('myid_1')))
+ table1.c.myid == bindparam('myid_1')))
assert_raises_message(exc.CompileError,
- "conflicts with unique bind parameter "
- "of the same name",
- str, s)
+ "conflicts with unique bind parameter "
+ "of the same name",
+ str, s)
s = select([table1], or_(table1.c.myid == 7, table1.c.myid == 8,
- table1.c.myid == bindparam('myid_1')))
+ table1.c.myid == bindparam('myid_1')))
assert_raises_message(exc.CompileError,
- "conflicts with unique bind parameter "
- "of the same name",
- str, s)
+ "conflicts with unique bind parameter "
+ "of the same name",
+ str, s)
def _test_binds_no_hash_collision(self):
"""test that construct_params doesn't corrupt dict
eq_(len(set(pp)), total_params, '%s %s' % (len(set(pp)), len(pp)))
eq_(len(set(pp.values())), total_params)
-
def test_bind_as_col(self):
t = table('foo', column('id'))
)
def test_bind_params_missing(self):
- assert_raises_message(exc.InvalidRequestError,
+ assert_raises_message(
+ exc.InvalidRequestError,
r"A value is required for bind parameter 'x'",
- select([table1]).where(
- and_(
- table1.c.myid == bindparam("x", required=True),
- table1.c.name == bindparam("y", required=True)
- )
- ).compile().construct_params,
+ select(
+ [table1]).where(
+ and_(
+ table1.c.myid == bindparam("x", required=True),
+ table1.c.name == bindparam("y", required=True)
+ )
+ ).compile().construct_params,
params=dict(y=5)
)
- assert_raises_message(exc.InvalidRequestError,
+ assert_raises_message(
+ exc.InvalidRequestError,
r"A value is required for bind parameter 'x'",
- select([table1]).where(
- table1.c.myid == bindparam("x", required=True)
- ).compile().construct_params
- )
+ select(
+ [table1]).where(
+ table1.c.myid == bindparam(
+ "x",
+ required=True)).compile().construct_params)
- assert_raises_message(exc.InvalidRequestError,
+ assert_raises_message(
+ exc.InvalidRequestError,
r"A value is required for bind parameter 'x', "
- "in parameter group 2",
- select([table1]).where(
- and_(
- table1.c.myid == bindparam("x", required=True),
- table1.c.name == bindparam("y", required=True)
- )
- ).compile().construct_params,
- params=dict(y=5),
- _group_number=2
- )
+ "in parameter group 2",
+ select(
+ [table1]).where(
+ and_(
+ table1.c.myid == bindparam("x", required=True),
+ table1.c.name == bindparam("y", required=True)
+ )
+ ).compile().construct_params,
+ params=dict(y=5), _group_number=2)
- assert_raises_message(exc.InvalidRequestError,
+ assert_raises_message(
+ exc.InvalidRequestError,
r"A value is required for bind parameter 'x', "
- "in parameter group 2",
- select([table1]).where(
- table1.c.myid == bindparam("x", required=True)
- ).compile().construct_params,
- _group_number=2
- )
-
-
-
+ "in parameter group 2",
+ select(
+ [table1]).where(
+ table1.c.myid == bindparam(
+ "x",
+ required=True)).compile().construct_params,
+ _group_number=2)
def test_tuple(self):
self.assert_compile(
tuple_(table1.c.myid, table1.c.name).in_(
- [(1, 'foo'), (5, 'bar')]),
+ [(1, 'foo'), (5, 'bar')]),
"(mytable.myid, mytable.name) IN "
"((:param_1, :param_2), (:param_3, :param_4))"
)
self.assert_compile(
tuple_(table1.c.myid, table1.c.name).in_(
- [tuple_(table2.c.otherid, table2.c.othername)]
- ),
+ [tuple_(table2.c.otherid, table2.c.othername)]
+ ),
"(mytable.myid, mytable.name) IN "
"((myothertable.otherid, myothertable.othername))"
)
self.assert_compile(
tuple_(table1.c.myid, table1.c.name).in_(
- select([table2.c.otherid, table2.c.othername])
- ),
+ select([table2.c.otherid, table2.c.othername])
+ ),
"(mytable.myid, mytable.name) IN (SELECT "
"myothertable.otherid, myothertable.othername FROM myothertable)"
)
-
def test_cast(self):
tbl = table('casttest',
column('id', Integer),
def check_results(dialect, expected_results, literal):
eq_(len(expected_results), 5,
- 'Incorrect number of expected results')
+ 'Incorrect number of expected results')
eq_(str(cast(tbl.c.v1, Numeric).compile(dialect=dialect)),
- 'CAST(casttest.v1 AS %s)' % expected_results[0])
+ 'CAST(casttest.v1 AS %s)' % expected_results[0])
eq_(str(cast(tbl.c.v1, Numeric(12, 9)).compile(dialect=dialect)),
- 'CAST(casttest.v1 AS %s)' % expected_results[1])
+ 'CAST(casttest.v1 AS %s)' % expected_results[1])
eq_(str(cast(tbl.c.ts, Date).compile(dialect=dialect)),
- 'CAST(casttest.ts AS %s)' % expected_results[2])
+ 'CAST(casttest.ts AS %s)' % expected_results[2])
eq_(str(cast(1234, Text).compile(dialect=dialect)),
- 'CAST(%s AS %s)' % (literal, expected_results[3]))
+ 'CAST(%s AS %s)' % (literal, expected_results[3]))
eq_(str(cast('test', String(20)).compile(dialect=dialect)),
- 'CAST(%s AS %s)' % (literal, expected_results[4]))
+ 'CAST(%s AS %s)' % (literal, expected_results[4]))
# fixme: shoving all of this dialect-specific stuff in one test
# is now officialy completely ridiculous AND non-obviously omits
# coverage on other dialects.
- sel = select([tbl, cast(tbl.c.v1, Numeric)]).compile(dialect=dialect)
+ sel = select([tbl, cast(tbl.c.v1, Numeric)]).compile(
+ dialect=dialect)
if isinstance(dialect, type(mysql.dialect())):
eq_(str(sel),
- "SELECT casttest.id, casttest.v1, casttest.v2, casttest.ts, "
- "CAST(casttest.v1 AS DECIMAL) AS anon_1 \nFROM casttest")
+ "SELECT casttest.id, casttest.v1, casttest.v2, "
+ "casttest.ts, "
+ "CAST(casttest.v1 AS DECIMAL) AS anon_1 \nFROM casttest")
else:
eq_(str(sel),
- "SELECT casttest.id, casttest.v1, casttest.v2, "
- "casttest.ts, CAST(casttest.v1 AS NUMERIC) AS "
- "anon_1 \nFROM casttest")
+ "SELECT casttest.id, casttest.v1, casttest.v2, "
+ "casttest.ts, CAST(casttest.v1 AS NUMERIC) AS "
+ "anon_1 \nFROM casttest")
# first test with PostgreSQL engine
- check_results(postgresql.dialect(), ['NUMERIC', 'NUMERIC(12, 9)',
- 'DATE', 'TEXT', 'VARCHAR(20)'], '%(param_1)s')
+ check_results(
+ postgresql.dialect(), [
+ 'NUMERIC', 'NUMERIC(12, 9)', 'DATE', 'TEXT', 'VARCHAR(20)'],
+ '%(param_1)s')
# then the Oracle engine
- check_results(oracle.dialect(), ['NUMERIC', 'NUMERIC(12, 9)',
- 'DATE', 'CLOB', 'VARCHAR2(20 CHAR)'], ':param_1')
+ check_results(
+ oracle.dialect(), [
+ 'NUMERIC', 'NUMERIC(12, 9)', 'DATE',
+ 'CLOB', 'VARCHAR2(20 CHAR)'],
+ ':param_1')
# then the sqlite engine
check_results(sqlite.dialect(), ['NUMERIC', 'NUMERIC(12, 9)',
- 'DATE', 'TEXT', 'VARCHAR(20)'], '?')
+ 'DATE', 'TEXT', 'VARCHAR(20)'], '?')
# then the MySQL engine
check_results(mysql.dialect(), ['DECIMAL', 'DECIMAL(12, 9)',
- 'DATE', 'CHAR', 'CHAR(20)'], '%s')
+ 'DATE', 'CHAR', 'CHAR(20)'], '%s')
self.assert_compile(cast(text('NULL'), Integer),
'CAST(NULL AS INTEGER)',
"SELECT x + foo() OVER () AS anon_1"
)
-
def test_date_between(self):
import datetime
table = Table('dt', metadata,
- Column('date', Date))
+ Column('date', Date))
self.assert_compile(
table.select(table.c.date.between(datetime.date(2006, 6, 1),
- datetime.date(2006, 6, 5))),
+ datetime.date(2006, 6, 5))),
"SELECT dt.date FROM dt WHERE dt.date BETWEEN :date_1 AND :date_2",
checkparams={'date_1': datetime.date(2006, 6, 1),
- 'date_2': datetime.date(2006, 6, 5)})
+ 'date_2': datetime.date(2006, 6, 5)})
self.assert_compile(
table.select(sql.between(table.c.date, datetime.date(2006, 6, 1),
- datetime.date(2006, 6, 5))),
+ datetime.date(2006, 6, 5))),
"SELECT dt.date FROM dt WHERE dt.date BETWEEN :date_1 AND :date_2",
checkparams={'date_1': datetime.date(2006, 6, 1),
- 'date_2': datetime.date(2006, 6, 5)})
-
+ 'date_2': datetime.date(2006, 6, 5)})
def test_delayed_col_naming(self):
my_str = Column(String)
f1 = func.hoho(table1.c.name)
s1 = select([table1.c.myid, table1.c.myid.label('foobar'),
- f1,
- func.lala(table1.c.name).label('gg')])
+ f1,
+ func.lala(table1.c.name).label('gg')])
eq_(
list(s1.c.keys()),
cast(table1.c.name, Numeric),
literal('x'),
)
- for col, key, expr, label in (
+ for col, key, expr, lbl in (
(table1.c.name, 'name', 'mytable.name', None),
(exprs[0], str(exprs[0]), 'mytable.myid = :myid_1', 'anon_1'),
(exprs[1], str(exprs[1]), 'hoho(mytable.myid)', 'hoho_1'),
(exprs[2], str(exprs[2]),
- 'CAST(mytable.name AS NUMERIC)', 'anon_1'),
+ 'CAST(mytable.name AS NUMERIC)', 'anon_1'),
(t1.c.col1, 'col1', 'mytable.col1', None),
(column('some wacky thing'), 'some wacky thing',
'"some wacky thing"', ''),
s1 = select([col], from_obj=t)
assert list(s1.c.keys()) == [key], list(s1.c.keys())
- if label:
- self.assert_compile(s1,
- "SELECT %s AS %s FROM mytable" % (expr, label))
+ if lbl:
+ self.assert_compile(
+ s1, "SELECT %s AS %s FROM mytable" %
+ (expr, lbl))
else:
self.assert_compile(s1, "SELECT %s FROM mytable" % (expr,))
s1 = select([s1])
- if label:
- self.assert_compile(s1,
- "SELECT %s FROM (SELECT %s AS %s FROM mytable)" %
- (label, expr, label))
+ if lbl:
+ self.assert_compile(
+ s1, "SELECT %s FROM (SELECT %s AS %s FROM mytable)" %
+ (lbl, expr, lbl))
elif col.table is not None:
# sqlite rule labels subquery columns
- self.assert_compile(s1,
- "SELECT %s FROM (SELECT %s AS %s FROM mytable)" %
- (key, expr, key))
+ self.assert_compile(
+ s1, "SELECT %s FROM (SELECT %s AS %s FROM mytable)" %
+ (key, expr, key))
else:
self.assert_compile(s1,
- "SELECT %s FROM (SELECT %s FROM mytable)" %
- (expr, expr))
+ "SELECT %s FROM (SELECT %s FROM mytable)" %
+ (expr, expr))
def test_hints(self):
s = select([table1.c.myid]).with_hint(table1, "test hint %(name)s")
subs4 = select([
table1, table2
- ]).select_from(table1.join(table2, table1.c.myid == table2.c.otherid)).\
+ ]).select_from(
+ table1.join(table2, table1.c.myid == table2.c.otherid)).\
with_hint(table1, 'hint1')
s4 = select([table3]).select_from(
- table3.join(
- subs4,
- subs4.c.othername == table3.c.otherstuff
- )
- ).\
- with_hint(table3, 'hint3')
-
+ table3.join(
+ subs4,
+ subs4.c.othername == table3.c.otherstuff
+ )
+ ).\
+ with_hint(table3, 'hint3')
t1 = table('QuotedName', column('col1'))
s6 = select([t1.c.col1]).where(t1.c.col1 > 10).\
- with_hint(t1, '%(name)s idx1')
+ with_hint(t1, '%(name)s idx1')
a2 = t1.alias('SomeName')
s7 = select([a2.c.col1]).where(a2.c.col1 > 10).\
- with_hint(a2, '%(name)s idx1')
+ with_hint(a2, '%(name)s idx1')
mysql_d, oracle_d, sybase_d = \
- mysql.dialect(), \
- oracle.dialect(), \
- sybase.dialect()
+ mysql.dialect(), \
+ oracle.dialect(), \
+ sybase.dialect()
for stmt, dialect, expected in [
- (s, mysql_d,
- "SELECT mytable.myid FROM mytable test hint mytable"),
- (s, oracle_d,
- "SELECT /*+ test hint mytable */ mytable.myid FROM mytable"),
- (s, sybase_d,
- "SELECT mytable.myid FROM mytable test hint mytable"),
- (s2, mysql_d,
- "SELECT mytable.myid FROM mytable"),
- (s2, oracle_d,
- "SELECT /*+ index(mytable idx) */ mytable.myid FROM mytable"),
- (s2, sybase_d,
- "SELECT mytable.myid FROM mytable WITH HINT INDEX idx"),
- (s3, mysql_d,
- "SELECT mytable_1.myid FROM mytable AS mytable_1 "
- "index(mytable_1 hint)"),
- (s3, oracle_d,
- "SELECT /*+ index(mytable_1 hint) */ mytable_1.myid FROM "
- "mytable mytable_1"),
- (s3, sybase_d,
- "SELECT mytable_1.myid FROM mytable AS mytable_1 "
- "index(mytable_1 hint)"),
- (s4, mysql_d,
- "SELECT thirdtable.userid, thirdtable.otherstuff FROM thirdtable "
- "hint3 INNER JOIN (SELECT mytable.myid, mytable.name, "
- "mytable.description, myothertable.otherid, "
- "myothertable.othername FROM mytable hint1 INNER "
- "JOIN myothertable ON mytable.myid = myothertable.otherid) "
- "ON othername = thirdtable.otherstuff"),
- (s4, sybase_d,
- "SELECT thirdtable.userid, thirdtable.otherstuff FROM thirdtable "
- "hint3 JOIN (SELECT mytable.myid, mytable.name, "
- "mytable.description, myothertable.otherid, "
- "myothertable.othername FROM mytable hint1 "
- "JOIN myothertable ON mytable.myid = myothertable.otherid) "
- "ON othername = thirdtable.otherstuff"),
- (s4, oracle_d,
- "SELECT /*+ hint3 */ thirdtable.userid, thirdtable.otherstuff "
- "FROM thirdtable JOIN (SELECT /*+ hint1 */ mytable.myid,"
- " mytable.name, mytable.description, myothertable.otherid,"
- " myothertable.othername FROM mytable JOIN myothertable ON"
- " mytable.myid = myothertable.otherid) ON othername ="
- " thirdtable.otherstuff"),
-# TODO: figure out dictionary ordering solution here
-# (s5, oracle_d,
-# "SELECT /*+ hint3 */ /*+ hint1 */ thirdtable.userid, "
-# "thirdtable.otherstuff "
-# "FROM thirdtable JOIN (SELECT mytable.myid,"
-# " mytable.name, mytable.description, myothertable.otherid,"
-# " myothertable.othername FROM mytable JOIN myothertable ON"
-# " mytable.myid = myothertable.otherid) ON othername ="
-# " thirdtable.otherstuff"),
- (s6, oracle_d,
+ (s, mysql_d,
+ "SELECT mytable.myid FROM mytable test hint mytable"),
+ (s, oracle_d,
+ "SELECT /*+ test hint mytable */ mytable.myid FROM mytable"),
+ (s, sybase_d,
+ "SELECT mytable.myid FROM mytable test hint mytable"),
+ (s2, mysql_d,
+ "SELECT mytable.myid FROM mytable"),
+ (s2, oracle_d,
+ "SELECT /*+ index(mytable idx) */ mytable.myid FROM mytable"),
+ (s2, sybase_d,
+ "SELECT mytable.myid FROM mytable WITH HINT INDEX idx"),
+ (s3, mysql_d,
+ "SELECT mytable_1.myid FROM mytable AS mytable_1 "
+ "index(mytable_1 hint)"),
+ (s3, oracle_d,
+ "SELECT /*+ index(mytable_1 hint) */ mytable_1.myid FROM "
+ "mytable mytable_1"),
+ (s3, sybase_d,
+ "SELECT mytable_1.myid FROM mytable AS mytable_1 "
+ "index(mytable_1 hint)"),
+ (s4, mysql_d,
+ "SELECT thirdtable.userid, thirdtable.otherstuff "
+ "FROM thirdtable "
+ "hint3 INNER JOIN (SELECT mytable.myid, mytable.name, "
+ "mytable.description, myothertable.otherid, "
+ "myothertable.othername FROM mytable hint1 INNER "
+ "JOIN myothertable ON mytable.myid = myothertable.otherid) "
+ "ON othername = thirdtable.otherstuff"),
+ (s4, sybase_d,
+ "SELECT thirdtable.userid, thirdtable.otherstuff "
+ "FROM thirdtable "
+ "hint3 JOIN (SELECT mytable.myid, mytable.name, "
+ "mytable.description, myothertable.otherid, "
+ "myothertable.othername FROM mytable hint1 "
+ "JOIN myothertable ON mytable.myid = myothertable.otherid) "
+ "ON othername = thirdtable.otherstuff"),
+ (s4, oracle_d,
+ "SELECT /*+ hint3 */ thirdtable.userid, thirdtable.otherstuff "
+ "FROM thirdtable JOIN (SELECT /*+ hint1 */ mytable.myid,"
+ " mytable.name, mytable.description, myothertable.otherid,"
+ " myothertable.othername FROM mytable JOIN myothertable ON"
+ " mytable.myid = myothertable.otherid) ON othername ="
+ " thirdtable.otherstuff"),
+ # TODO: figure out dictionary ordering solution here
+ # (s5, oracle_d,
+ # "SELECT /*+ hint3 */ /*+ hint1 */ thirdtable.userid, "
+ # "thirdtable.otherstuff "
+ # "FROM thirdtable JOIN (SELECT mytable.myid,"
+ # " mytable.name, mytable.description, myothertable.otherid,"
+ # " myothertable.othername FROM mytable JOIN myothertable ON"
+ # " mytable.myid = myothertable.otherid) ON othername ="
+ # " thirdtable.otherstuff"),
+ (s6, oracle_d,
"""SELECT /*+ "QuotedName" idx1 */ "QuotedName".col1 """
"""FROM "QuotedName" WHERE "QuotedName".col1 > :col1_1"""),
- (s7, oracle_d,
- """SELECT /*+ SomeName idx1 */ "SomeName".col1 FROM """
- """"QuotedName" "SomeName" WHERE "SomeName".col1 > :col1_1"""),
+ (s7, oracle_d,
+ """SELECT /*+ SomeName idx1 */ "SomeName".col1 FROM """
+ """"QuotedName" "SomeName" WHERE "SomeName".col1 > :col1_1"""),
]:
self.assert_compile(
stmt,
def test_literal_as_text_nonstring_raise(self):
assert_raises(exc.ArgumentError,
- and_, ("a",), ("b",)
- )
+ and_, ("a",), ("b",)
+ )
class UnsupportedTest(fixtures.TestBase):
+
def test_unsupported_element_str_visit_name(self):
from sqlalchemy.sql.expression import ClauseElement
+
class SomeElement(ClauseElement):
__visit_name__ = 'some_element'
def test_unsupported_element_meth_visit_name(self):
from sqlalchemy.sql.expression import ClauseElement
+
class SomeElement(ClauseElement):
+
@classmethod
def __visit_name__(cls):
return "some_element"
def test_unsupported_operator(self):
from sqlalchemy.sql.expression import BinaryExpression
+
def myop(x, y):
pass
binary = BinaryExpression(column("foo"), column("bar"), myop)
@classmethod
def setup_class(cls):
from sqlalchemy.sql.expression import ColumnClause, TableClause
+
class CatchCol(ColumnClause):
pass
def _do_test(self, element):
d = default.DefaultDialect()
d.statement_compiler(d, element,
- compile_kwargs={"canary": True})
+ compile_kwargs={"canary": True})
def test_binary(self):
self._do_test(self.column == 5)
def test_select(self):
s = select([self.column]).select_from(self.table).\
- where(self.column == self.criterion).\
- order_by(self.column)
+ where(self.column == self.criterion).\
+ order_by(self.column)
self._do_test(s)
def test_case(self):
class CRUDTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
-
def test_correlated_update(self):
# test against a straight text subquery
- u = update(table1, values={
- table1.c.name:
- text("(select name from mytable where id=mytable.id)")})
- self.assert_compile(u,
- "UPDATE mytable SET name=(select name from mytable "
- "where id=mytable.id)")
+ u = update(
+ table1,
+ values={
+ table1.c.name:
+ text("(select name from mytable where id=mytable.id)")
+ }
+ )
+ self.assert_compile(
+ u,
+ "UPDATE mytable SET name=(select name from mytable "
+ "where id=mytable.id)")
mt = table1.alias()
u = update(table1, values={
- table1.c.name:
- select([mt.c.name], mt.c.myid == table1.c.myid)
- })
- self.assert_compile(u,
- "UPDATE mytable SET name=(SELECT mytable_1.name FROM "
- "mytable AS mytable_1 WHERE "
- "mytable_1.myid = mytable.myid)")
+ table1.c.name:
+ select([mt.c.name], mt.c.myid == table1.c.myid)
+ })
+ self.assert_compile(
+ u, "UPDATE mytable SET name=(SELECT mytable_1.name FROM "
+ "mytable AS mytable_1 WHERE "
+ "mytable_1.myid = mytable.myid)")
# test against a regular constructed subquery
s = select([table2], table2.c.otherid == table1.c.myid)
u = update(table1, table1.c.name == 'jack', values={table1.c.name: s})
- self.assert_compile(u,
- "UPDATE mytable SET name=(SELECT myothertable.otherid, "
- "myothertable.othername FROM myothertable WHERE "
- "myothertable.otherid = mytable.myid) "
- "WHERE mytable.name = :name_1")
+ self.assert_compile(
+ u, "UPDATE mytable SET name=(SELECT myothertable.otherid, "
+ "myothertable.othername FROM myothertable WHERE "
+ "myothertable.otherid = mytable.myid) "
+ "WHERE mytable.name = :name_1")
# test a non-correlated WHERE clause
s = select([table2.c.othername], table2.c.otherid == 7)
u = update(table1, table1.c.name == s)
self.assert_compile(u,
- "UPDATE mytable SET myid=:myid, name=:name, "
- "description=:description WHERE mytable.name = "
- "(SELECT myothertable.othername FROM myothertable "
- "WHERE myothertable.otherid = :otherid_1)")
+ "UPDATE mytable SET myid=:myid, name=:name, "
+ "description=:description WHERE mytable.name = "
+ "(SELECT myothertable.othername FROM myothertable "
+ "WHERE myothertable.otherid = :otherid_1)")
# test one that is actually correlated...
s = select([table2.c.othername], table2.c.otherid == table1.c.myid)
u = table1.update(table1.c.name == s)
self.assert_compile(u,
- "UPDATE mytable SET myid=:myid, name=:name, "
- "description=:description WHERE mytable.name = "
- "(SELECT myothertable.othername FROM myothertable "
- "WHERE myothertable.otherid = mytable.myid)")
+ "UPDATE mytable SET myid=:myid, name=:name, "
+ "description=:description WHERE mytable.name = "
+ "(SELECT myothertable.othername FROM myothertable "
+ "WHERE myothertable.otherid = mytable.myid)")
# test correlated FROM implicit in WHERE and SET clauses
u = table1.update().values(name=table2.c.othername)\
.where(table2.c.otherid == table1.c.myid)
- self.assert_compile(u,
- "UPDATE mytable SET name=myothertable.othername "
- "FROM myothertable WHERE myothertable.otherid = mytable.myid")
+ self.assert_compile(
+ u, "UPDATE mytable SET name=myothertable.othername "
+ "FROM myothertable WHERE myothertable.otherid = mytable.myid")
u = table1.update().values(name='foo')\
.where(table2.c.otherid == table1.c.myid)
- self.assert_compile(u,
- "UPDATE mytable SET name=:name "
- "FROM myothertable WHERE myothertable.otherid = mytable.myid")
+ self.assert_compile(
+ u, "UPDATE mytable SET name=:name "
+ "FROM myothertable WHERE myothertable.otherid = mytable.myid")
self.assert_compile(u,
- "UPDATE mytable SET name=:name "
- "FROM mytable, myothertable WHERE "
- "myothertable.otherid = mytable.myid",
- dialect=mssql.dialect())
+ "UPDATE mytable SET name=:name "
+ "FROM mytable, myothertable WHERE "
+ "myothertable.otherid = mytable.myid",
+ dialect=mssql.dialect())
self.assert_compile(u.where(table2.c.othername == mt.c.name),
- "UPDATE mytable SET name=:name "
- "FROM mytable, myothertable, mytable AS mytable_1 "
- "WHERE myothertable.otherid = mytable.myid "
- "AND myothertable.othername = mytable_1.name",
- dialect=mssql.dialect())
+ "UPDATE mytable SET name=:name "
+ "FROM mytable, myothertable, mytable AS mytable_1 "
+ "WHERE myothertable.otherid = mytable.myid "
+ "AND myothertable.othername = mytable_1.name",
+ dialect=mssql.dialect())
def test_binds_that_match_columns(self):
"""test bind params named after column names
assert_raises(exc.CompileError, u.values(x=7).compile)
self.assert_compile(u.values(y=7),
- "UPDATE foo SET y=:y WHERE foo.x = :x")
+ "UPDATE foo SET y=:y WHERE foo.x = :x")
assert_raises(exc.CompileError,
- u.values(x=7).compile, column_keys=['x', 'y'])
+ u.values(x=7).compile, column_keys=['x', 'y'])
assert_raises(exc.CompileError, u.compile, column_keys=['x', 'y'])
- self.assert_compile(u.values(x=3 + bindparam('x')),
- "UPDATE foo SET x=(:param_1 + :x) WHERE foo.x = :x")
+ self.assert_compile(
+ u.values(
+ x=3 +
+ bindparam('x')),
+ "UPDATE foo SET x=(:param_1 + :x) WHERE foo.x = :x")
- self.assert_compile(u.values(x=3 + bindparam('x')),
- "UPDATE foo SET x=(:param_1 + :x) WHERE foo.x = :x",
- params={'x': 1})
+ self.assert_compile(
+ u.values(
+ x=3 +
+ bindparam('x')),
+ "UPDATE foo SET x=(:param_1 + :x) WHERE foo.x = :x",
+ params={
+ 'x': 1})
- self.assert_compile(u.values(x=3 + bindparam('x')),
- "UPDATE foo SET x=(:param_1 + :x), y=:y WHERE foo.x = :x",
- params={'x': 1, 'y': 2})
+ self.assert_compile(
+ u.values(
+ x=3 +
+ bindparam('x')),
+ "UPDATE foo SET x=(:param_1 + :x), y=:y WHERE foo.x = :x",
+ params={
+ 'x': 1,
+ 'y': 2})
i = t.insert().values(x=3 + bindparam('x'))
self.assert_compile(i,
- "INSERT INTO foo (x) VALUES ((:param_1 + :x))")
- self.assert_compile(i,
- "INSERT INTO foo (x, y) VALUES ((:param_1 + :x), :y)",
- params={'x': 1, 'y': 2})
+ "INSERT INTO foo (x) VALUES ((:param_1 + :x))")
+ self.assert_compile(
+ i,
+ "INSERT INTO foo (x, y) VALUES ((:param_1 + :x), :y)",
+ params={
+ 'x': 1,
+ 'y': 2})
i = t.insert().values(x=bindparam('y'))
self.assert_compile(i, "INSERT INTO foo (x) VALUES (:y)")
i = t.insert().values(x=3 + bindparam('x2'))
self.assert_compile(i,
- "INSERT INTO foo (x) VALUES ((:param_1 + :x2))")
- self.assert_compile(i,
- "INSERT INTO foo (x) VALUES ((:param_1 + :x2))", params={})
- self.assert_compile(i,
- "INSERT INTO foo (x, y) VALUES ((:param_1 + :x2), :y)",
- params={'x': 1, 'y': 2})
- self.assert_compile(i,
- "INSERT INTO foo (x, y) VALUES ((:param_1 + :x2), :y)",
- params={'x2': 1, 'y': 2})
+ "INSERT INTO foo (x) VALUES ((:param_1 + :x2))")
+ self.assert_compile(
+ i,
+ "INSERT INTO foo (x) VALUES ((:param_1 + :x2))",
+ params={})
+ self.assert_compile(
+ i,
+ "INSERT INTO foo (x, y) VALUES ((:param_1 + :x2), :y)",
+ params={
+ 'x': 1,
+ 'y': 2})
+ self.assert_compile(
+ i,
+ "INSERT INTO foo (x, y) VALUES ((:param_1 + :x2), :y)",
+ params={
+ 'x2': 1,
+ 'y': 2})
def test_unconsumed_names(self):
t = table("t", column("x"), column("y"))
exc.CompileError,
"Unconsumed column names: j",
t.update().values(x=5, j=7).values({t2.c.z: 5}).
- where(t.c.x == t2.c.q).compile,
+ where(t.c.x == t2.c.q).compile,
)
# bindparam names don't get counted
column_keys=['j']
)
-
def test_labels_no_collision(self):
t = table('foo', column('id'), column('foo_id'))
"UPDATE foo SET id=:id, foo_id=:foo_id WHERE foo.id = :foo_id_1"
)
+
class DDLTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
def _illegal_type_fixture(self):
class MyType(types.TypeEngine):
pass
+
@compiles(MyType)
def compile(element, compiler, **kw):
raise exc.CompileError("Couldn't compile type")
def test_reraise_of_column_spec_issue(self):
MyType = self._illegal_type_fixture()
t1 = Table('t', MetaData(),
- Column('x', MyType())
- )
+ Column('x', MyType())
+ )
assert_raises_message(
exc.CompileError,
r"\(in table 't', column 'x'\): Couldn't compile type",
def test_reraise_of_column_spec_issue_unicode(self):
MyType = self._illegal_type_fixture()
t1 = Table('t', MetaData(),
- Column(u('méil'), MyType())
- )
+ Column(u('méil'), MyType())
+ )
assert_raises_message(
exc.CompileError,
u(r"\(in table 't', column 'méil'\): Couldn't compile type"),
def test_system_flag(self):
m = MetaData()
t = Table('t', m, Column('x', Integer),
- Column('y', Integer, system=True),
- Column('z', Integer))
+ Column('y', Integer, system=True),
+ Column('z', Integer))
self.assert_compile(
schema.CreateTable(t),
"CREATE TABLE t (x INTEGER, z INTEGER)"
def test_insert(self):
m = MetaData()
foo = Table('foo', m,
- Column('id', Integer))
+ Column('id', Integer))
t = Table('test', m,
- Column('col1', Integer, default=func.foo(1)),
- Column('col2', Integer, default=select(
- [func.coalesce(func.max(foo.c.id))])),
- )
+ Column('col1', Integer, default=func.foo(1)),
+ Column('col2', Integer, default=select(
+ [func.coalesce(func.max(foo.c.id))])),
+ )
- self.assert_compile(t.insert(inline=True, values={}),
- "INSERT INTO test (col1, col2) VALUES (foo(:foo_1), "
- "(SELECT coalesce(max(foo.id)) AS coalesce_1 FROM "
- "foo))")
+ self.assert_compile(
+ t.insert(
+ inline=True, values={}),
+ "INSERT INTO test (col1, col2) VALUES (foo(:foo_1), "
+ "(SELECT coalesce(max(foo.id)) AS coalesce_1 FROM "
+ "foo))")
def test_update(self):
m = MetaData()
foo = Table('foo', m,
- Column('id', Integer))
+ Column('id', Integer))
t = Table('test', m,
- Column('col1', Integer, onupdate=func.foo(1)),
- Column('col2', Integer, onupdate=select(
- [func.coalesce(func.max(foo.c.id))])),
- Column('col3', String(30))
- )
+ Column('col1', Integer, onupdate=func.foo(1)),
+ Column('col2', Integer, onupdate=select(
+ [func.coalesce(func.max(foo.c.id))])),
+ Column('col3', String(30))
+ )
self.assert_compile(t.update(inline=True, values={'col3': 'foo'}),
- "UPDATE test SET col1=foo(:foo_1), col2=(SELECT "
- "coalesce(max(foo.id)) AS coalesce_1 FROM foo), "
- "col3=:col3")
+ "UPDATE test SET col1=foo(:foo_1), col2=(SELECT "
+ "coalesce(max(foo.id)) AS coalesce_1 FROM foo), "
+ "col3=:col3")
+
class SchemaTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
def test_select(self):
self.assert_compile(table4.select(),
- "SELECT remote_owner.remotetable.rem_id, "
- "remote_owner.remotetable.datatype_id,"
- " remote_owner.remotetable.value "
- "FROM remote_owner.remotetable")
-
- self.assert_compile(table4.select(and_(table4.c.datatype_id == 7,
- table4.c.value == 'hi')),
- "SELECT remote_owner.remotetable.rem_id, "
- "remote_owner.remotetable.datatype_id,"
- " remote_owner.remotetable.value "
- "FROM remote_owner.remotetable WHERE "
- "remote_owner.remotetable.datatype_id = :datatype_id_1 AND"
- " remote_owner.remotetable.value = :value_1")
+ "SELECT remote_owner.remotetable.rem_id, "
+ "remote_owner.remotetable.datatype_id,"
+ " remote_owner.remotetable.value "
+ "FROM remote_owner.remotetable")
+
+ self.assert_compile(
+ table4.select(
+ and_(
+ table4.c.datatype_id == 7,
+ table4.c.value == 'hi')),
+ "SELECT remote_owner.remotetable.rem_id, "
+ "remote_owner.remotetable.datatype_id,"
+ " remote_owner.remotetable.value "
+ "FROM remote_owner.remotetable WHERE "
+ "remote_owner.remotetable.datatype_id = :datatype_id_1 AND"
+ " remote_owner.remotetable.value = :value_1")
s = table4.select(and_(table4.c.datatype_id == 7,
- table4.c.value == 'hi'), use_labels=True)
- self.assert_compile(s, "SELECT remote_owner.remotetable.rem_id AS"
+ table4.c.value == 'hi'), use_labels=True)
+ self.assert_compile(
+ s, "SELECT remote_owner.remotetable.rem_id AS"
" remote_owner_remotetable_rem_id, "
"remote_owner.remotetable.datatype_id AS"
" remote_owner_remotetable_datatype_id, "
# multi-part schema name
self.assert_compile(table5.select(),
- 'SELECT "dbo.remote_owner".remotetable.rem_id, '
- '"dbo.remote_owner".remotetable.datatype_id, '
- '"dbo.remote_owner".remotetable.value '
- 'FROM "dbo.remote_owner".remotetable'
- )
+ 'SELECT "dbo.remote_owner".remotetable.rem_id, '
+ '"dbo.remote_owner".remotetable.datatype_id, '
+ '"dbo.remote_owner".remotetable.value '
+ 'FROM "dbo.remote_owner".remotetable'
+ )
# multi-part schema name labels - convert '.' to '_'
self.assert_compile(table5.select(use_labels=True),
- 'SELECT "dbo.remote_owner".remotetable.rem_id AS'
- ' dbo_remote_owner_remotetable_rem_id, '
- '"dbo.remote_owner".remotetable.datatype_id'
- ' AS dbo_remote_owner_remotetable_datatype_id,'
- ' "dbo.remote_owner".remotetable.value AS '
- 'dbo_remote_owner_remotetable_value FROM'
- ' "dbo.remote_owner".remotetable'
- )
+ 'SELECT "dbo.remote_owner".remotetable.rem_id AS'
+ ' dbo_remote_owner_remotetable_rem_id, '
+ '"dbo.remote_owner".remotetable.datatype_id'
+ ' AS dbo_remote_owner_remotetable_datatype_id,'
+ ' "dbo.remote_owner".remotetable.value AS '
+ 'dbo_remote_owner_remotetable_value FROM'
+ ' "dbo.remote_owner".remotetable'
+ )
def test_alias(self):
a = alias(table4, 'remtable')
def test_update(self):
self.assert_compile(
- table4.update(table4.c.value == 'test',
- values={table4.c.datatype_id: 12}),
- "UPDATE remote_owner.remotetable SET datatype_id=:datatype_id "
- "WHERE remote_owner.remotetable.value = :value_1")
+ table4.update(table4.c.value == 'test',
+ values={table4.c.datatype_id: 12}),
+ "UPDATE remote_owner.remotetable SET datatype_id=:datatype_id "
+ "WHERE remote_owner.remotetable.value = :value_1")
def test_insert(self):
self.assert_compile(table4.insert(values=(2, 5, 'test')),
- "INSERT INTO remote_owner.remotetable "
- "(rem_id, datatype_id, value) VALUES "
- "(:rem_id, :datatype_id, :value)")
-
+ "INSERT INTO remote_owner.remotetable "
+ "(rem_id, datatype_id, value) VALUES "
+ "(:rem_id, :datatype_id, :value)")
class CorrelateTest(fixtures.TestBase, AssertsCompiledSQL):
def test_dont_overcorrelate(self):
self.assert_compile(select([table1], from_obj=[table1,
- table1.select()]),
+ table1.select()]),
"SELECT mytable.myid, mytable.name, "
"mytable.description FROM mytable, (SELECT "
"mytable.myid AS myid, mytable.name AS "
def _assert_where_correlated(self, stmt):
self.assert_compile(
- stmt,
- "SELECT t2.a FROM t2 WHERE t2.a = "
- "(SELECT t1.a FROM t1 WHERE t1.a = t2.a)")
+ stmt,
+ "SELECT t2.a FROM t2 WHERE t2.a = "
+ "(SELECT t1.a FROM t1 WHERE t1.a = t2.a)")
def _assert_where_all_correlated(self, stmt):
self.assert_compile(
- stmt,
- "SELECT t1.a, t2.a FROM t1, t2 WHERE t2.a = "
- "(SELECT t1.a WHERE t1.a = t2.a)")
+ stmt,
+ "SELECT t1.a, t2.a FROM t1, t2 WHERE t2.a = "
+ "(SELECT t1.a WHERE t1.a = t2.a)")
# note there's no more "backwards" correlation after
# we've done #2746
- #def _assert_where_backwards_correlated(self, stmt):
+ # def _assert_where_backwards_correlated(self, stmt):
# self.assert_compile(
# stmt,
# "SELECT t2.a FROM t2 WHERE t2.a = "
# "(SELECT t1.a FROM t2 WHERE t1.a = t2.a)")
- #def _assert_column_backwards_correlated(self, stmt):
+ # def _assert_column_backwards_correlated(self, stmt):
# self.assert_compile(stmt,
# "SELECT t2.a, (SELECT t1.a FROM t2 WHERE t1.a = t2.a) "
# "AS anon_1 FROM t2")
def _assert_column_correlated(self, stmt):
- self.assert_compile(stmt,
- "SELECT t2.a, (SELECT t1.a FROM t1 WHERE t1.a = t2.a) "
- "AS anon_1 FROM t2")
+ self.assert_compile(
+ stmt,
+ "SELECT t2.a, (SELECT t1.a FROM t1 WHERE t1.a = t2.a) "
+ "AS anon_1 FROM t2")
def _assert_column_all_correlated(self, stmt):
- self.assert_compile(stmt,
- "SELECT t1.a, t2.a, "
- "(SELECT t1.a WHERE t1.a = t2.a) AS anon_1 FROM t1, t2")
-
+ self.assert_compile(
+ stmt,
+ "SELECT t1.a, t2.a, "
+ "(SELECT t1.a WHERE t1.a = t2.a) AS anon_1 FROM t1, t2")
def _assert_having_correlated(self, stmt):
self.assert_compile(stmt,
- "SELECT t2.a FROM t2 HAVING t2.a = "
- "(SELECT t1.a FROM t1 WHERE t1.a = t2.a)")
+ "SELECT t2.a FROM t2 HAVING t2.a = "
+ "(SELECT t1.a FROM t1 WHERE t1.a = t2.a)")
def _assert_from_uncorrelated(self, stmt):
- self.assert_compile(stmt,
- "SELECT t2.a, anon_1.a FROM t2, "
- "(SELECT t1.a AS a FROM t1, t2 WHERE t1.a = t2.a) AS anon_1")
+ self.assert_compile(
+ stmt,
+ "SELECT t2.a, anon_1.a FROM t2, "
+ "(SELECT t1.a AS a FROM t1, t2 WHERE t1.a = t2.a) AS anon_1")
def _assert_from_all_uncorrelated(self, stmt):
- self.assert_compile(stmt,
- "SELECT t1.a, t2.a, anon_1.a FROM t1, t2, "
- "(SELECT t1.a AS a FROM t1, t2 WHERE t1.a = t2.a) AS anon_1")
+ self.assert_compile(
+ stmt,
+ "SELECT t1.a, t2.a, anon_1.a FROM t1, t2, "
+ "(SELECT t1.a AS a FROM t1, t2 WHERE t1.a = t2.a) AS anon_1")
def _assert_where_uncorrelated(self, stmt):
self.assert_compile(stmt,
- "SELECT t2.a FROM t2 WHERE t2.a = "
- "(SELECT t1.a FROM t1, t2 WHERE t1.a = t2.a)")
+ "SELECT t2.a FROM t2 WHERE t2.a = "
+ "(SELECT t1.a FROM t1, t2 WHERE t1.a = t2.a)")
def _assert_column_uncorrelated(self, stmt):
self.assert_compile(stmt,
- "SELECT t2.a, (SELECT t1.a FROM t1, t2 "
- "WHERE t1.a = t2.a) AS anon_1 FROM t2")
+ "SELECT t2.a, (SELECT t1.a FROM t1, t2 "
+ "WHERE t1.a = t2.a) AS anon_1 FROM t2")
def _assert_having_uncorrelated(self, stmt):
self.assert_compile(stmt,
- "SELECT t2.a FROM t2 HAVING t2.a = "
- "(SELECT t1.a FROM t1, t2 WHERE t1.a = t2.a)")
+ "SELECT t2.a FROM t2 HAVING t2.a = "
+ "(SELECT t1.a FROM t1, t2 WHERE t1.a = t2.a)")
def _assert_where_single_full_correlated(self, stmt):
self.assert_compile(stmt,
- "SELECT t1.a FROM t1 WHERE t1.a = (SELECT t1.a)")
+ "SELECT t1.a FROM t1 WHERE t1.a = (SELECT t1.a)")
def test_correlate_semiauto_where(self):
t1, t2, s1 = self._fixture()
self._assert_where_correlated(
- select([t2]).where(t2.c.a == s1.correlate(t2)))
+ select([t2]).where(t2.c.a == s1.correlate(t2)))
def test_correlate_semiauto_column(self):
t1, t2, s1 = self._fixture()
self._assert_column_correlated(
- select([t2, s1.correlate(t2).as_scalar()]))
+ select([t2, s1.correlate(t2).as_scalar()]))
def test_correlate_semiauto_from(self):
t1, t2, s1 = self._fixture()
self._assert_from_uncorrelated(
- select([t2, s1.correlate(t2).alias()]))
+ select([t2, s1.correlate(t2).alias()]))
def test_correlate_semiauto_having(self):
t1, t2, s1 = self._fixture()
self._assert_having_correlated(
- select([t2]).having(t2.c.a == s1.correlate(t2)))
+ select([t2]).having(t2.c.a == s1.correlate(t2)))
def test_correlate_except_inclusion_where(self):
t1, t2, s1 = self._fixture()
self._assert_where_correlated(
- select([t2]).where(t2.c.a == s1.correlate_except(t1)))
+ select([t2]).where(t2.c.a == s1.correlate_except(t1)))
def test_correlate_except_exclusion_where(self):
t1, t2, s1 = self._fixture()
self._assert_where_uncorrelated(
- select([t2]).where(t2.c.a == s1.correlate_except(t2)))
+ select([t2]).where(t2.c.a == s1.correlate_except(t2)))
def test_correlate_except_inclusion_column(self):
t1, t2, s1 = self._fixture()
self._assert_column_correlated(
- select([t2, s1.correlate_except(t1).as_scalar()]))
+ select([t2, s1.correlate_except(t1).as_scalar()]))
def test_correlate_except_exclusion_column(self):
t1, t2, s1 = self._fixture()
self._assert_column_uncorrelated(
- select([t2, s1.correlate_except(t2).as_scalar()]))
+ select([t2, s1.correlate_except(t2).as_scalar()]))
def test_correlate_except_inclusion_from(self):
t1, t2, s1 = self._fixture()
self._assert_from_uncorrelated(
- select([t2, s1.correlate_except(t1).alias()]))
+ select([t2, s1.correlate_except(t1).alias()]))
def test_correlate_except_exclusion_from(self):
t1, t2, s1 = self._fixture()
self._assert_from_uncorrelated(
- select([t2, s1.correlate_except(t2).alias()]))
+ select([t2, s1.correlate_except(t2).alias()]))
def test_correlate_except_none(self):
t1, t2, s1 = self._fixture()
self._assert_where_all_correlated(
- select([t1, t2]).where(t2.c.a == s1.correlate_except(None)))
+ select([t1, t2]).where(t2.c.a == s1.correlate_except(None)))
def test_correlate_except_having(self):
t1, t2, s1 = self._fixture()
self._assert_having_correlated(
- select([t2]).having(t2.c.a == s1.correlate_except(t1)))
+ select([t2]).having(t2.c.a == s1.correlate_except(t1)))
def test_correlate_auto_where(self):
t1, t2, s1 = self._fixture()
self._assert_where_correlated(
- select([t2]).where(t2.c.a == s1))
+ select([t2]).where(t2.c.a == s1))
def test_correlate_auto_column(self):
t1, t2, s1 = self._fixture()
self._assert_column_correlated(
- select([t2, s1.as_scalar()]))
+ select([t2, s1.as_scalar()]))
def test_correlate_auto_from(self):
t1, t2, s1 = self._fixture()
self._assert_from_uncorrelated(
- select([t2, s1.alias()]))
+ select([t2, s1.alias()]))
def test_correlate_auto_having(self):
t1, t2, s1 = self._fixture()
self._assert_having_correlated(
- select([t2]).having(t2.c.a == s1))
+ select([t2]).having(t2.c.a == s1))
def test_correlate_disabled_where(self):
t1, t2, s1 = self._fixture()
self._assert_where_uncorrelated(
- select([t2]).where(t2.c.a == s1.correlate(None)))
+ select([t2]).where(t2.c.a == s1.correlate(None)))
def test_correlate_disabled_column(self):
t1, t2, s1 = self._fixture()
self._assert_column_uncorrelated(
- select([t2, s1.correlate(None).as_scalar()]))
+ select([t2, s1.correlate(None).as_scalar()]))
def test_correlate_disabled_from(self):
t1, t2, s1 = self._fixture()
self._assert_from_uncorrelated(
- select([t2, s1.correlate(None).alias()]))
+ select([t2, s1.correlate(None).alias()]))
def test_correlate_disabled_having(self):
t1, t2, s1 = self._fixture()
self._assert_having_uncorrelated(
- select([t2]).having(t2.c.a == s1.correlate(None)))
+ select([t2]).having(t2.c.a == s1.correlate(None)))
def test_correlate_all_where(self):
t1, t2, s1 = self._fixture()
self._assert_where_all_correlated(
- select([t1, t2]).where(t2.c.a == s1.correlate(t1, t2)))
+ select([t1, t2]).where(t2.c.a == s1.correlate(t1, t2)))
def test_correlate_all_column(self):
t1, t2, s1 = self._fixture()
self._assert_column_all_correlated(
- select([t1, t2, s1.correlate(t1, t2).as_scalar()]))
+ select([t1, t2, s1.correlate(t1, t2).as_scalar()]))
def test_correlate_all_from(self):
t1, t2, s1 = self._fixture()
self._assert_from_all_uncorrelated(
- select([t1, t2, s1.correlate(t1, t2).alias()]))
+ select([t1, t2, s1.correlate(t1, t2).alias()]))
def test_correlate_where_all_unintentional(self):
t1, t2, s1 = self._fixture()
s = select([t1.c.a])
s2 = select([t1]).where(t1.c.a == s)
self.assert_compile(s2,
- "SELECT t1.a FROM t1 WHERE t1.a = "
- "(SELECT t1.a FROM t1)")
+ "SELECT t1.a FROM t1 WHERE t1.a = "
+ "(SELECT t1.a FROM t1)")
def test_correlate_semiauto_where_singlefrom(self):
t1, t2, s1 = self._fixture()
# new as of #2668
t1, t2, s1 = self._fixture()
self.assert_compile(s1.correlate(t1, t2),
- "SELECT t1.a FROM t1, t2 WHERE t1.a = t2.a")
+ "SELECT t1.a FROM t1, t2 WHERE t1.a = t2.a")
def test_correlate_except_froms(self):
# new as of #2748
s2 = select([func.foo(s.c.b)]).as_scalar()
s3 = select([t1], order_by=s2)
- self.assert_compile(s3,
- "SELECT t1.a FROM t1 ORDER BY "
+ self.assert_compile(
+ s3, "SELECT t1.a FROM t1 ORDER BY "
"(SELECT foo(s.b) AS foo_1 FROM "
- "(SELECT t2.b AS b FROM t2 WHERE t1.a = t2.a) AS s)"
- )
+ "(SELECT t2.b AS b FROM t2 WHERE t1.a = t2.a) AS s)")
def test_multilevel_froms_correlation(self):
# new as of #2748
p = table('parent', column('id'))
c = table('child', column('id'), column('parent_id'), column('pos'))
- s = c.select().where(c.c.parent_id == p.c.id).order_by(c.c.pos).limit(1)
+ s = c.select().where(
+ c.c.parent_id == p.c.id).order_by(
+ c.c.pos).limit(1)
s = s.correlate(p)
s = exists().select_from(s).where(s.c.id == 1)
s = select([p]).where(s)
- self.assert_compile(s,
- "SELECT parent.id FROM parent WHERE EXISTS (SELECT * "
+ self.assert_compile(
+ s, "SELECT parent.id FROM parent WHERE EXISTS (SELECT * "
"FROM (SELECT child.id AS id, child.parent_id AS parent_id, "
"child.pos AS pos FROM child WHERE child.parent_id = parent.id "
"ORDER BY child.pos LIMIT :param_1) WHERE id = :id_1)")
s = select([t1]).where(t1.c.x == t2.c.y).\
where(t2.c.y == t3.c.z).correlate_except(t1)
- self.assert_compile(s,
+ self.assert_compile(
+ s,
"SELECT t1.x FROM t1, t2, t3 WHERE t1.x = t2.y AND t2.y = t3.z")
def test_multilevel_implicit_correlation_disabled(self):
s3 = select([t1]).where(t1.c.x == s2.as_scalar())
self.assert_compile(s3,
- "SELECT t1.x FROM t1 "
- "WHERE t1.x = (SELECT t3.z "
- "FROM t3 "
- "WHERE t3.z = (SELECT t1.x "
- "FROM t1, t2 "
- "WHERE t1.x = t2.y))"
- )
+ "SELECT t1.x FROM t1 "
+ "WHERE t1.x = (SELECT t3.z "
+ "FROM t3 "
+ "WHERE t3.z = (SELECT t1.x "
+ "FROM t1, t2 "
+ "WHERE t1.x = t2.y))"
+ )
def test_from_implicit_correlation_disabled(self):
# test that implicit correlation with immediate and
s3 = select([t1, s2])
self.assert_compile(s3,
- "SELECT t1.x, y, x FROM t1, "
- "(SELECT t2.y AS y, x FROM t2, "
- "(SELECT t1.x AS x FROM t1, t2 WHERE t1.x = t2.y))"
- )
+ "SELECT t1.x, y, x FROM t1, "
+ "(SELECT t2.y AS y, x FROM t2, "
+ "(SELECT t1.x AS x FROM t1, t2 WHERE t1.x = t2.y))"
+ )
+
class CoercionTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = default.DefaultDialect(supports_native_boolean=True)
def _fixture(self):
m = MetaData()
return Table('foo', m,
- Column('id', Integer))
+ Column('id', Integer))
bool_table = table('t', column('x', Boolean))
class ResultMapTest(fixtures.TestBase):
+
"""test the behavior of the 'entry stack' and the determination
when the result_map needs to be populated.
"""
+
def test_compound_populates(self):
t = Table('t', MetaData(), Column('a', Integer), Column('b', Integer))
stmt = select([t]).union(select([t]))
comp = stmt.compile()
eq_(
comp.result_map,
- {'a': ('a', (t.c.a, 'a', 'a'), t.c.a.type),
+ {'a': ('a', (t.c.a, 'a', 'a'), t.c.a.type),
'b': ('b', (t.c.b, 'b', 'b'), t.c.b.type)}
)
comp = stmt.compile()
eq_(
comp.result_map,
- {'a': ('a', (t.c.a, 'a', 'a'), t.c.a.type)}
+ {'a': ('a', (t.c.a, 'a', 'a'), t.c.a.type)}
)
def test_compound_only_top_populates(self):
comp = stmt.compile()
eq_(
comp.result_map,
- {'a': ('a', (t.c.a, 'a', 'a'), t.c.a.type)},
+ {'a': ('a', (t.c.a, 'a', 'a'), t.c.a.type)},
)
def test_label_plus_element(self):
tc_anon_label = comp.result_map['a_1'][1][0]
eq_(
comp.result_map,
- {
+ {
'a': ('a', (t.c.a, 'a', 'a'), t.c.a.type),
'bar': ('bar', (l1, 'bar'), l1.type),
'a_1': ('%%(%d a)s' % id(tc), (tc_anon_label, 'a_1'), tc.type),
- },
+ },
)
def test_label_conflict_union(self):
t1 = Table('t1', MetaData(), Column('a', Integer),
- Column('b', Integer))
+ Column('b', Integer))
t2 = Table('t2', MetaData(), Column('t1_a', Integer))
union = select([t2]).union(select([t2])).alias()
t1_alias = t1.alias()
stmt = select([t1, t1_alias]).select_from(
- t1.join(union, t1.c.a == union.c.t1_a)).apply_labels()
+ t1.join(union, t1.c.a == union.c.t1_a)).apply_labels()
comp = stmt.compile()
eq_(
set(comp.result_map),
CheckConstraint, func, text
from sqlalchemy import exc, schema
from sqlalchemy.testing import fixtures, AssertsExecutionResults, \
- AssertsCompiledSQL
+ AssertsCompiledSQL
from sqlalchemy import testing
from sqlalchemy.engine import default
from sqlalchemy.testing import engines
from sqlalchemy.testing.assertsql import AllOf, RegexSQL, ExactSQL, CompiledSQL
from sqlalchemy.sql import table, column
+
class ConstraintGenTest(fixtures.TestBase, AssertsExecutionResults):
__dialect__ = 'default'
__backend__ = True
-
@testing.provide_metadata
def test_pk_fk_constraint_create(self):
metadata = self.metadata
Table('employees', metadata,
- Column('id', Integer),
- Column('soc', String(40)),
- Column('name', String(30)),
- PrimaryKeyConstraint('id', 'soc')
- )
+ Column('id', Integer),
+ Column('soc', String(40)),
+ Column('name', String(30)),
+ PrimaryKeyConstraint('id', 'soc')
+ )
Table('elements', metadata,
- Column('id', Integer),
- Column('stuff', String(30)),
- Column('emp_id', Integer),
- Column('emp_soc', String(40)),
- PrimaryKeyConstraint('id', name='elements_primkey'),
- ForeignKeyConstraint(['emp_id', 'emp_soc'],
- ['employees.id', 'employees.soc'])
- )
+ Column('id', Integer),
+ Column('stuff', String(30)),
+ Column('emp_id', Integer),
+ Column('emp_soc', String(40)),
+ PrimaryKeyConstraint('id', name='elements_primkey'),
+ ForeignKeyConstraint(['emp_id', 'emp_soc'],
+ ['employees.id', 'employees.soc'])
+ )
self.assert_sql_execution(
testing.db,
lambda: metadata.create_all(checkfirst=False),
CompiledSQL('CREATE TABLE employees ('
- 'id INTEGER NOT NULL, '
- 'soc VARCHAR(40) NOT NULL, '
- 'name VARCHAR(30), '
- 'PRIMARY KEY (id, soc)'
- ')'
- ),
+ 'id INTEGER NOT NULL, '
+ 'soc VARCHAR(40) NOT NULL, '
+ 'name VARCHAR(30), '
+ 'PRIMARY KEY (id, soc)'
+ ')'
+ ),
CompiledSQL('CREATE TABLE elements ('
- 'id INTEGER NOT NULL, '
- 'stuff VARCHAR(30), '
- 'emp_id INTEGER, '
- 'emp_soc VARCHAR(40), '
- 'CONSTRAINT elements_primkey PRIMARY KEY (id), '
- 'FOREIGN KEY(emp_id, emp_soc) '
- 'REFERENCES employees (id, soc)'
- ')'
- )
+ 'id INTEGER NOT NULL, '
+ 'stuff VARCHAR(30), '
+ 'emp_id INTEGER, '
+ 'emp_soc VARCHAR(40), '
+ 'CONSTRAINT elements_primkey PRIMARY KEY (id), '
+ 'FOREIGN KEY(emp_id, emp_soc) '
+ 'REFERENCES employees (id, soc)'
+ ')'
+ )
)
-
@testing.provide_metadata
def test_cyclic_fk_table_constraint_create(self):
metadata = self.metadata
Table("a", metadata,
- Column('id', Integer, primary_key=True),
- Column('bid', Integer),
- ForeignKeyConstraint(["bid"], ["b.id"])
- )
- Table("b", metadata,
- Column('id', Integer, primary_key=True),
- Column("aid", Integer),
- ForeignKeyConstraint(["aid"], ["a.id"], use_alter=True, name="bfk")
- )
+ Column('id', Integer, primary_key=True),
+ Column('bid', Integer),
+ ForeignKeyConstraint(["bid"], ["b.id"])
+ )
+ Table(
+ "b", metadata, Column(
+ 'id', Integer, primary_key=True), Column(
+ "aid", Integer), ForeignKeyConstraint(
+ ["aid"], ["a.id"], use_alter=True, name="bfk"))
self._assert_cyclic_constraint(metadata)
@testing.provide_metadata
metadata = self.metadata
Table("a", metadata,
- Column('id', Integer, primary_key=True),
- Column('bid', Integer, ForeignKey("b.id")),
- )
+ Column('id', Integer, primary_key=True),
+ Column('bid', Integer, ForeignKey("b.id")),
+ )
Table("b", metadata,
- Column('id', Integer, primary_key=True),
- Column("aid", Integer,
- ForeignKey("a.id", use_alter=True, name="bfk")
- ),
- )
+ Column('id', Integer, primary_key=True),
+ Column("aid", Integer,
+ ForeignKey("a.id", use_alter=True, name="bfk")
+ ),
+ )
self._assert_cyclic_constraint(metadata)
def _assert_cyclic_constraint(self, metadata):
assertions = [
CompiledSQL('CREATE TABLE b ('
- 'id INTEGER NOT NULL, '
- 'aid INTEGER, '
- 'PRIMARY KEY (id)'
- ')'
- ),
+ 'id INTEGER NOT NULL, '
+ 'aid INTEGER, '
+ 'PRIMARY KEY (id)'
+ ')'
+ ),
CompiledSQL('CREATE TABLE a ('
- 'id INTEGER NOT NULL, '
- 'bid INTEGER, '
- 'PRIMARY KEY (id), '
- 'FOREIGN KEY(bid) REFERENCES b (id)'
- ')'
- ),
+ 'id INTEGER NOT NULL, '
+ 'bid INTEGER, '
+ 'PRIMARY KEY (id), '
+ 'FOREIGN KEY(bid) REFERENCES b (id)'
+ ')'
+ ),
]
if testing.db.dialect.supports_alter:
assertions.append(
CompiledSQL('ALTER TABLE b ADD CONSTRAINT bfk '
- 'FOREIGN KEY(aid) REFERENCES a (id)')
+ 'FOREIGN KEY(aid) REFERENCES a (id)')
)
self.assert_sql_execution(
testing.db,
assertions.extend([
CompiledSQL("DROP TABLE a"),
CompiledSQL("DROP TABLE b"),
- ])
+ ])
self.assert_sql_execution(
testing.db,
lambda: metadata.drop_all(checkfirst=False),
metadata = self.metadata
Table('foo', metadata,
- Column('id', Integer, primary_key=True),
- Column('x', Integer),
- Column('y', Integer),
- CheckConstraint('x>y'))
+ Column('id', Integer, primary_key=True),
+ Column('x', Integer),
+ Column('y', Integer),
+ CheckConstraint('x>y'))
Table('bar', metadata,
- Column('id', Integer, primary_key=True),
- Column('x', Integer, CheckConstraint('x>7')),
- Column('z', Integer)
- )
+ Column('id', Integer, primary_key=True),
+ Column('x', Integer, CheckConstraint('x>7')),
+ Column('z', Integer)
+ )
self.assert_sql_execution(
testing.db,
lambda: metadata.create_all(checkfirst=False),
AllOf(
CompiledSQL('CREATE TABLE foo ('
- 'id INTEGER NOT NULL, '
- 'x INTEGER, '
- 'y INTEGER, '
- 'PRIMARY KEY (id), '
- 'CHECK (x>y)'
- ')'
- ),
+ 'id INTEGER NOT NULL, '
+ 'x INTEGER, '
+ 'y INTEGER, '
+ 'PRIMARY KEY (id), '
+ 'CHECK (x>y)'
+ ')'
+ ),
CompiledSQL('CREATE TABLE bar ('
- 'id INTEGER NOT NULL, '
- 'x INTEGER CHECK (x>7), '
- 'z INTEGER, '
- 'PRIMARY KEY (id)'
- ')'
- )
+ 'id INTEGER NOT NULL, '
+ 'x INTEGER CHECK (x>7), '
+ 'z INTEGER, '
+ 'PRIMARY KEY (id)'
+ ')'
+ )
)
)
metadata = self.metadata
Table('foo', metadata,
- Column('id', Integer, primary_key=True),
- Column('value', String(30), unique=True))
+ Column('id', Integer, primary_key=True),
+ Column('value', String(30), unique=True))
Table('bar', metadata,
- Column('id', Integer, primary_key=True),
- Column('value', String(30)),
- Column('value2', String(30)),
- UniqueConstraint('value', 'value2', name='uix1')
- )
+ Column('id', Integer, primary_key=True),
+ Column('value', String(30)),
+ Column('value2', String(30)),
+ UniqueConstraint('value', 'value2', name='uix1')
+ )
self.assert_sql_execution(
testing.db,
lambda: metadata.create_all(checkfirst=False),
AllOf(
CompiledSQL('CREATE TABLE foo ('
- 'id INTEGER NOT NULL, '
- 'value VARCHAR(30), '
- 'PRIMARY KEY (id), '
- 'UNIQUE (value)'
- ')'),
+ 'id INTEGER NOT NULL, '
+ 'value VARCHAR(30), '
+ 'PRIMARY KEY (id), '
+ 'UNIQUE (value)'
+ ')'),
CompiledSQL('CREATE TABLE bar ('
- 'id INTEGER NOT NULL, '
- 'value VARCHAR(30), '
- 'value2 VARCHAR(30), '
- 'PRIMARY KEY (id), '
- 'CONSTRAINT uix1 UNIQUE (value, value2)'
- ')')
+ 'id INTEGER NOT NULL, '
+ 'value VARCHAR(30), '
+ 'value2 VARCHAR(30), '
+ 'PRIMARY KEY (id), '
+ 'CONSTRAINT uix1 UNIQUE (value, value2)'
+ ')')
)
)
RegexSQL("^CREATE TABLE"),
AllOf(
CompiledSQL('CREATE INDEX employee_name_index ON '
- 'employees (last_name, first_name)', []),
+ 'employees (last_name, first_name)', []),
CompiledSQL('CREATE UNIQUE INDEX employee_email_index ON '
- 'employees (email_address)', [])
+ 'employees (email_address)', [])
)
)
Column('lastName', String(30)),
Column('emailAddress', String(30)))
-
-
Index('employeeNameIndex',
- employees.c.lastName, employees.c.firstName)
+ employees.c.lastName, employees.c.firstName)
Index('employeeEmailIndex',
- employees.c.emailAddress, unique=True)
+ employees.c.emailAddress, unique=True)
self.assert_sql_execution(
- testing.db,
- lambda: metadata.create_all(checkfirst=False),
- RegexSQL("^CREATE TABLE"),
- AllOf(
- CompiledSQL('CREATE INDEX "employeeNameIndex" ON '
- '"companyEmployees" ("lastName", "firstName")', []),
- CompiledSQL('CREATE UNIQUE INDEX "employeeEmailIndex" ON '
- '"companyEmployees" ("emailAddress")', [])
- )
- )
+ testing.db, lambda: metadata.create_all(
+ checkfirst=False), RegexSQL("^CREATE TABLE"), AllOf(
+ CompiledSQL(
+ 'CREATE INDEX "employeeNameIndex" ON '
+ '"companyEmployees" ("lastName", "firstName")', []),
+ CompiledSQL(
+ 'CREATE UNIQUE INDEX "employeeEmailIndex" ON '
+ '"companyEmployees" ("emailAddress")', [])))
@testing.provide_metadata
def test_index_create_inline(self):
Column('winner', String(30)))
Index('sport_announcer', events.c.sport, events.c.announcer,
- unique=True)
+ unique=True)
Index('idx_winners', events.c.winner)
eq_(
set(ix.name for ix in events.indexes),
set(['ix_events_name', 'ix_events_location',
- 'sport_announcer', 'idx_winners'])
+ 'sport_announcer', 'idx_winners'])
)
self.assert_sql_execution(
RegexSQL("^CREATE TABLE events"),
AllOf(
ExactSQL('CREATE UNIQUE INDEX ix_events_name ON events '
- '(name)'),
+ '(name)'),
ExactSQL('CREATE INDEX ix_events_location ON events '
- '(location)'),
+ '(location)'),
ExactSQL('CREATE UNIQUE INDEX sport_announcer ON events '
- '(sport, announcer)'),
+ '(sport, announcer)'),
ExactSQL('CREATE INDEX idx_winners ON events (winner)')
)
)
metadata = self.metadata
t = Table('sometable', metadata,
- Column('id', Integer, primary_key=True),
- Column('data', String(50))
- )
+ Column('id', Integer, primary_key=True),
+ Column('data', String(50))
+ )
Index('myindex', t.c.data.desc())
self.assert_sql_execution(
testing.db,
lambda: t.create(testing.db),
CompiledSQL('CREATE TABLE sometable (id INTEGER NOT NULL, '
- 'data VARCHAR(50), PRIMARY KEY (id))'),
+ 'data VARCHAR(50), PRIMARY KEY (id))'),
ExactSQL('CREATE INDEX myindex ON sometable (data DESC)')
)
+
class ConstraintCompilationTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
"DROP INDEX foo.xyz"
)
-
def test_too_long_index_name(self):
dialect = testing.db.dialect.__class__()
]:
t1 = Table(tname, MetaData(),
- Column(cname, Integer, index=True),
- )
+ Column(cname, Integer, index=True),
+ )
ix1 = list(t1.indexes)[0]
self.assert_compile(
assert_raises(
exc.IdentifierError,
schema.CreateIndex(Index(
- "this_other_name_is_too_long_for_what_were_doing",
- t1.c.c)).compile,
+ "this_other_name_is_too_long_for_what_were_doing",
+ t1.c.c)).compile,
dialect=dialect
)
def test_functional_index(self):
metadata = MetaData()
x = Table('x', metadata,
- Column('q', String(50))
- )
+ Column('q', String(50))
+ )
idx = Index('y', func.lower(x.c.q))
self.assert_compile(
metadata = MetaData()
idx = Index('y', text("some_function(q)"))
t = Table('x', metadata,
- Column('q', String(50))
- )
+ Column('q', String(50))
+ )
t.append_constraint(idx)
self.assert_compile(
schema.CreateIndex(idx),
metadata = MetaData()
idx = Index('y', text("some_function(q)"))
x = Table('x', metadata,
- Column('q', String(50)),
- idx
- )
+ Column('q', String(50)),
+ idx
+ )
self.assert_compile(
schema.CreateIndex(idx),
"CREATE INDEX y ON x (some_function(q))"
)
-
def test_index_declaration_inline(self):
metadata = MetaData()
t1 = Table('t1', metadata,
- Column('x', Integer),
- Column('y', Integer),
- Index('foo', 'x', 'y')
- )
+ Column('x', Integer),
+ Column('y', Integer),
+ Index('foo', 'x', 'y')
+ )
self.assert_compile(
schema.CreateIndex(list(t1.indexes)[0]),
"CREATE INDEX foo ON t1 (x, y)"
sql = str(schema.CreateTable(t).compile(dialect=dialect))
assert 'NOT DEFERRABLE' in sql
-
t = Table('tbl', MetaData(),
Column('a', Integer),
Column('b', Integer),
assert 'INITIALLY DEFERRED' in sql
def test_column_level_ck_name(self):
- t = Table('tbl', MetaData(),
- Column('a', Integer, CheckConstraint("a > 5",
- name="ck_a_greater_five"))
- )
+ t = Table(
+ 'tbl',
+ MetaData(),
+ Column(
+ 'a',
+ Integer,
+ CheckConstraint(
+ "a > 5",
+ name="ck_a_greater_five")))
self.assert_compile(
schema.CreateTable(t),
"CREATE TABLE tbl (a INTEGER CONSTRAINT "
"ck_a_greater_five CHECK (a > 5))"
)
+
def test_deferrable_pk(self):
factory = lambda **kw: PrimaryKeyConstraint('a', **kw)
self._test_deferrable(factory)
def test_multiple(self):
m = MetaData()
Table("foo", m,
- Column('id', Integer, primary_key=True),
- Column('bar', Integer, primary_key=True)
- )
+ Column('id', Integer, primary_key=True),
+ Column('bar', Integer, primary_key=True)
+ )
tb = Table("some_table", m,
- Column('id', Integer, primary_key=True),
- Column('foo_id', Integer, ForeignKey('foo.id')),
- Column('foo_bar', Integer, ForeignKey('foo.bar')),
- )
+ Column('id', Integer, primary_key=True),
+ Column('foo_id', Integer, ForeignKey('foo.id')),
+ Column('foo_bar', Integer, ForeignKey('foo.bar')),
+ )
self.assert_compile(
schema.CreateTable(tb),
"CREATE TABLE some_table ("
- "id INTEGER NOT NULL, "
- "foo_id INTEGER, "
- "foo_bar INTEGER, "
- "PRIMARY KEY (id), "
- "FOREIGN KEY(foo_id) REFERENCES foo (id), "
- "FOREIGN KEY(foo_bar) REFERENCES foo (bar))"
+ "id INTEGER NOT NULL, "
+ "foo_id INTEGER, "
+ "foo_bar INTEGER, "
+ "PRIMARY KEY (id), "
+ "FOREIGN KEY(foo_id) REFERENCES foo (id), "
+ "FOREIGN KEY(foo_bar) REFERENCES foo (bar))"
)
def test_empty_pkc(self):
self.assert_compile(
schema.CreateTable(t),
"CREATE TABLE tbl (a INTEGER, b INTEGER CHECK (a < b) "
- "DEFERRABLE INITIALLY DEFERRED)"
+ "DEFERRABLE INITIALLY DEFERRED)"
)
def test_use_alter(self):
m = MetaData()
Table('t', m,
- Column('a', Integer),
- )
+ Column('a', Integer),
+ )
Table('t2', m,
- Column('a', Integer, ForeignKey('t.a', use_alter=True,
- name='fk_ta')),
- Column('b', Integer, ForeignKey('t.a', name='fk_tb'))
- )
+ Column('a', Integer, ForeignKey('t.a', use_alter=True,
+ name='fk_ta')),
+ Column('b', Integer, ForeignKey('t.a', name='fk_tb'))
+ )
e = engines.mock_engine(dialect_name='postgresql')
m.create_all(e)
e.assert_sql([
'CREATE TABLE t (a INTEGER)',
'CREATE TABLE t2 (a INTEGER, b INTEGER, CONSTRAINT fk_tb '
- 'FOREIGN KEY(b) REFERENCES t (a))',
+ 'FOREIGN KEY(b) REFERENCES t (a))',
'ALTER TABLE t2 '
- 'ADD CONSTRAINT fk_ta FOREIGN KEY(a) REFERENCES t (a)',
+ 'ADD CONSTRAINT fk_ta FOREIGN KEY(a) REFERENCES t (a)',
'ALTER TABLE t2 DROP CONSTRAINT fk_ta',
'DROP TABLE t2',
'DROP TABLE t'
t = Table('tbl', m,
Column('a', Integer),
Column('b', Integer)
- )
+ )
t2 = Table('t2', m,
- Column('a', Integer),
- Column('b', Integer)
- )
+ Column('a', Integer),
+ Column('b', Integer)
+ )
return t, t2
t, t2 = self._constraint_create_fixture()
CheckConstraint('a < b', name="my_test_constraint",
- deferrable=True, initially='DEFERRED',
- table=t)
+ deferrable=True, initially='DEFERRED',
+ table=t)
# before we create an AddConstraint,
# the CONSTRAINT comes out inline
"a INTEGER, "
"b INTEGER, "
"CONSTRAINT my_test_constraint CHECK (a < b) "
- "DEFERRABLE INITIALLY DEFERRED"
+ "DEFERRABLE INITIALLY DEFERRED"
")"
)
t, t2 = self._constraint_create_fixture()
constraint = CheckConstraint('a < b', name="my_test_constraint",
- deferrable=True, initially='DEFERRED',
- table=t)
+ deferrable=True, initially='DEFERRED',
+ table=t)
self.assert_compile(
schema.AddConstraint(constraint),
"ALTER TABLE tbl ADD CONSTRAINT my_test_constraint "
- "CHECK (a < b) DEFERRABLE INITIALLY DEFERRED"
+ "CHECK (a < b) DEFERRABLE INITIALLY DEFERRED"
)
def test_external_ck_constraint_cancels_internal(self):
t, t2 = self._constraint_create_fixture()
constraint = CheckConstraint('a < b', name="my_test_constraint",
- deferrable=True, initially='DEFERRED',
- table=t)
+ deferrable=True, initially='DEFERRED',
+ table=t)
schema.AddConstraint(constraint)
t, t2 = self._constraint_create_fixture()
constraint = CheckConstraint('a < b', name="my_test_constraint",
- deferrable=True, initially='DEFERRED',
- table=t)
+ deferrable=True, initially='DEFERRED',
+ table=t)
self.assert_compile(
schema.DropConstraint(constraint),
t, t2 = self._constraint_create_fixture()
constraint = CheckConstraint('a < b', name="my_test_constraint",
- deferrable=True, initially='DEFERRED',
- table=t)
+ deferrable=True, initially='DEFERRED',
+ table=t)
self.assert_compile(
schema.DropConstraint(constraint, cascade=True),
class ConstraintAPITest(fixtures.TestBase):
+
def test_double_fk_usage_raises(self):
f = ForeignKey('b.id')
t = Table('tbl', m,
Column('a', Integer),
Column('b', Integer)
- )
+ )
t2 = Table('t2', m,
- Column('a', Integer),
- Column('b', Integer)
- )
+ Column('a', Integer),
+ Column('b', Integer)
+ )
for c in (
UniqueConstraint(t.c.a),
t = Table('tbl', m,
Column('a', Integer),
Column('b', Integer)
- )
+ )
t2 = Table('t2', m,
- Column('a', Integer),
- Column('b', Integer)
- )
+ Column('a', Integer),
+ Column('b', Integer)
+ )
UniqueConstraint(t.c.a)
CheckConstraint(t.c.a > 5)
t = Table('tbl', m,
Column('a', Integer),
Column('b', Integer)
- )
+ )
ck = CheckConstraint(t.c.a > 5)
ck2 = ck.copy()
assert ck in t.constraints
assert ck2 not in t.constraints
-
def test_ambig_check_constraint_auto_append(self):
m = MetaData()
t = Table('tbl', m,
Column('a', Integer),
Column('b', Integer)
- )
+ )
t2 = Table('t2', m,
- Column('a', Integer),
- Column('b', Integer)
- )
+ Column('a', Integer),
+ Column('b', Integer)
+ )
c = CheckConstraint(t.c.a > t2.c.b)
assert c not in t.constraints
assert c not in t2.constraints
metadata = MetaData()
t1 = Table('t1', metadata,
- Column('x', Integer)
- )
+ Column('x', Integer)
+ )
t2 = Table('t2', metadata,
- Column('y', Integer)
- )
+ Column('y', Integer)
+ )
assert_raises_message(
exc.ArgumentError,
"Column 't2.y' is not part of table 't1'.",
metadata = MetaData()
t1 = Table('t1', metadata,
- Column('x', Integer)
- )
+ Column('x', Integer)
+ )
assert_raises_message(
exc.ArgumentError,
"Index 'bar' is against table 't1', and "
"cannot be associated with table 't2'.",
Table, 't2', metadata,
- Column('y', Integer),
- Index('bar', t1.c.x)
+ Column('y', Integer),
+ Index('bar', t1.c.x)
)
def test_raise_index_nonexistent_name(self):
schema.CreateIndex(idx).compile
)
-
def test_no_warning_w_no_columns(self):
idx = Index(name="foo")
def test_raise_clauseelement_not_a_column(self):
m = MetaData()
t2 = Table('t2', m, Column('x', Integer))
+
class SomeClass(object):
+
def __clause_element__(self):
return t2
assert_raises(
from sqlalchemy.engine import default
from sqlalchemy.exc import CompileError
+
class CTETest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
def test_nonrecursive(self):
orders = table('orders',
- column('region'),
- column('amount'),
- column('product'),
- column('quantity')
- )
+ column('region'),
+ column('amount'),
+ column('product'),
+ column('quantity')
+ )
regional_sales = select([
- orders.c.region,
- func.sum(orders.c.amount).label('total_sales')
- ]).group_by(orders.c.region).cte("regional_sales")
+ orders.c.region,
+ func.sum(orders.c.amount).label('total_sales')
+ ]).group_by(orders.c.region).cte("regional_sales")
top_regions = select([regional_sales.c.region]).\
- where(
- regional_sales.c.total_sales >
- select([
- func.sum(regional_sales.c.total_sales)/10
- ])
- ).cte("top_regions")
+ where(
+ regional_sales.c.total_sales > select([
+ func.sum(regional_sales.c.total_sales) / 10
+ ])
+ ).cte("top_regions")
s = select([
- orders.c.region,
- orders.c.product,
- func.sum(orders.c.quantity).label("product_units"),
- func.sum(orders.c.amount).label("product_sales")
- ]).where(orders.c.region.in_(
- select([top_regions.c.region])
- )).group_by(orders.c.region, orders.c.product)
+ orders.c.region,
+ orders.c.product,
+ func.sum(orders.c.quantity).label("product_units"),
+ func.sum(orders.c.amount).label("product_sales")
+ ]).where(orders.c.region.in_(
+ select([top_regions.c.region])
+ )).group_by(orders.c.region, orders.c.product)
# needs to render regional_sales first as top_regions
# refers to it
def test_recursive(self):
parts = table('parts',
- column('part'),
- column('sub_part'),
- column('quantity'),
- )
+ column('part'),
+ column('sub_part'),
+ column('quantity'),
+ )
included_parts = select([
- parts.c.sub_part,
- parts.c.part,
- parts.c.quantity]).\
- where(parts.c.part=='our part').\
- cte(recursive=True)
+ parts.c.sub_part,
+ parts.c.part,
+ parts.c.quantity]).\
+ where(parts.c.part == 'our part').\
+ cte(recursive=True)
incl_alias = included_parts.alias()
parts_alias = parts.alias()
select([
parts_alias.c.sub_part,
parts_alias.c.part,
- parts_alias.c.quantity]).\
- where(parts_alias.c.part==incl_alias.c.sub_part)
- )
+ parts_alias.c.quantity]).
+ where(parts_alias.c.part == incl_alias.c.sub_part)
+ )
s = select([
included_parts.c.sub_part,
func.sum(included_parts.c.quantity).label('total_quantity')]).\
select_from(included_parts.join(
- parts,included_parts.c.part==parts.c.part)).\
+ parts, included_parts.c.part == parts.c.part)).\
group_by(included_parts.c.sub_part)
- self.assert_compile(s,
- "WITH RECURSIVE anon_1(sub_part, part, quantity) "
- "AS (SELECT parts.sub_part AS sub_part, parts.part "
- "AS part, parts.quantity AS quantity FROM parts "
- "WHERE parts.part = :part_1 UNION SELECT parts_1.sub_part AS sub_part, "
- "parts_1.part AS part, parts_1.quantity "
- "AS quantity FROM parts AS parts_1, anon_1 AS anon_2 "
- "WHERE parts_1.part = anon_2.sub_part) "
- "SELECT anon_1.sub_part, "
- "sum(anon_1.quantity) AS total_quantity FROM anon_1 "
- "JOIN parts ON anon_1.part = parts.part "
- "GROUP BY anon_1.sub_part"
- )
+ self.assert_compile(
+ s, "WITH RECURSIVE anon_1(sub_part, part, quantity) "
+ "AS (SELECT parts.sub_part AS sub_part, parts.part "
+ "AS part, parts.quantity AS quantity FROM parts "
+ "WHERE parts.part = :part_1 UNION "
+ "SELECT parts_1.sub_part AS sub_part, "
+ "parts_1.part AS part, parts_1.quantity "
+ "AS quantity FROM parts AS parts_1, anon_1 AS anon_2 "
+ "WHERE parts_1.part = anon_2.sub_part) "
+ "SELECT anon_1.sub_part, "
+ "sum(anon_1.quantity) AS total_quantity FROM anon_1 "
+ "JOIN parts ON anon_1.part = parts.part "
+ "GROUP BY anon_1.sub_part")
# quick check that the "WITH RECURSIVE" varies per
# dialect
- self.assert_compile(s,
- "WITH anon_1(sub_part, part, quantity) "
- "AS (SELECT parts.sub_part AS sub_part, parts.part "
- "AS part, parts.quantity AS quantity FROM parts "
- "WHERE parts.part = :part_1 UNION SELECT parts_1.sub_part AS sub_part, "
- "parts_1.part AS part, parts_1.quantity "
- "AS quantity FROM parts AS parts_1, anon_1 AS anon_2 "
- "WHERE parts_1.part = anon_2.sub_part) "
- "SELECT anon_1.sub_part, "
- "sum(anon_1.quantity) AS total_quantity FROM anon_1 "
- "JOIN parts ON anon_1.part = parts.part "
- "GROUP BY anon_1.sub_part",
- dialect=mssql.dialect()
- )
+ self.assert_compile(
+ s, "WITH anon_1(sub_part, part, quantity) "
+ "AS (SELECT parts.sub_part AS sub_part, parts.part "
+ "AS part, parts.quantity AS quantity FROM parts "
+ "WHERE parts.part = :part_1 UNION "
+ "SELECT parts_1.sub_part AS sub_part, "
+ "parts_1.part AS part, parts_1.quantity "
+ "AS quantity FROM parts AS parts_1, anon_1 AS anon_2 "
+ "WHERE parts_1.part = anon_2.sub_part) "
+ "SELECT anon_1.sub_part, "
+ "sum(anon_1.quantity) AS total_quantity FROM anon_1 "
+ "JOIN parts ON anon_1.part = parts.part "
+ "GROUP BY anon_1.sub_part", dialect=mssql.dialect())
def test_recursive_union_no_alias_one(self):
s1 = select([literal(0).label("x")])
)
s2 = select([cte])
self.assert_compile(s2,
- "WITH RECURSIVE cte(x) AS "
- "(SELECT :param_1 AS x UNION ALL "
- "SELECT cte.x + :x_1 AS anon_1 "
- "FROM cte WHERE cte.x < :x_2) "
- "SELECT cte.x FROM cte"
- )
-
+ "WITH RECURSIVE cte(x) AS "
+ "(SELECT :param_1 AS x UNION ALL "
+ "SELECT cte.x + :x_1 AS anon_1 "
+ "FROM cte WHERE cte.x < :x_2) "
+ "SELECT cte.x FROM cte"
+ )
def test_recursive_union_no_alias_two(self):
"""
t = t.union_all(select([t.c.n + 1]).where(t.c.n < 100))
s = select([func.sum(t.c.n)])
self.assert_compile(s,
- "WITH RECURSIVE t(n) AS "
- "(SELECT values(:values_1) AS n "
- "UNION ALL SELECT t.n + :n_1 AS anon_1 "
- "FROM t "
- "WHERE t.n < :n_2) "
- "SELECT sum(t.n) AS sum_1 FROM t"
- )
+ "WITH RECURSIVE t(n) AS "
+ "(SELECT values(:values_1) AS n "
+ "UNION ALL SELECT t.n + :n_1 AS anon_1 "
+ "FROM t "
+ "WHERE t.n < :n_2) "
+ "SELECT sum(t.n) AS sum_1 FROM t"
+ )
def test_recursive_union_no_alias_three(self):
# like test one, but let's refer to the CTE
s2 = select([cte, bar])
self.assert_compile(s2,
- "WITH RECURSIVE cte(x) AS "
- "(SELECT :param_1 AS x UNION ALL "
- "SELECT cte.x + :x_1 AS anon_1 "
- "FROM cte WHERE cte.x < :x_2), "
- "bar AS (SELECT cte.x AS x FROM cte) "
- "SELECT cte.x, bar.x FROM cte, bar"
- )
-
+ "WITH RECURSIVE cte(x) AS "
+ "(SELECT :param_1 AS x UNION ALL "
+ "SELECT cte.x + :x_1 AS anon_1 "
+ "FROM cte WHERE cte.x < :x_2), "
+ "bar AS (SELECT cte.x AS x FROM cte) "
+ "SELECT cte.x, bar.x FROM cte, bar"
+ )
def test_recursive_union_no_alias_four(self):
# like test one and three, but let's refer
# includes "inner" cte
s2 = select([cte, bar])
self.assert_compile(s2,
- "WITH RECURSIVE cte(x) AS "
- "(SELECT :param_1 AS x UNION ALL "
- "SELECT cte.x + :x_1 AS anon_1 "
- "FROM cte WHERE cte.x < :x_2), "
- "bar AS (SELECT cte.x AS x FROM cte) "
- "SELECT cte.x, bar.x FROM cte, bar"
- )
+ "WITH RECURSIVE cte(x) AS "
+ "(SELECT :param_1 AS x UNION ALL "
+ "SELECT cte.x + :x_1 AS anon_1 "
+ "FROM cte WHERE cte.x < :x_2), "
+ "bar AS (SELECT cte.x AS x FROM cte) "
+ "SELECT cte.x, bar.x FROM cte, bar"
+ )
# bar rendered, only includes "inner" cte,
# "outer" cte isn't present
s2 = select([bar])
self.assert_compile(s2,
- "WITH RECURSIVE cte(x) AS "
- "(SELECT :param_1 AS x), "
- "bar AS (SELECT cte.x AS x FROM cte) "
- "SELECT bar.x FROM bar"
- )
+ "WITH RECURSIVE cte(x) AS "
+ "(SELECT :param_1 AS x), "
+ "bar AS (SELECT cte.x AS x FROM cte) "
+ "SELECT bar.x FROM bar"
+ )
# bar rendered, but then the "outer"
# cte is rendered.
s2 = select([bar, cte])
- self.assert_compile(s2,
- "WITH RECURSIVE bar AS (SELECT cte.x AS x FROM cte), "
- "cte(x) AS "
- "(SELECT :param_1 AS x UNION ALL "
- "SELECT cte.x + :x_1 AS anon_1 "
- "FROM cte WHERE cte.x < :x_2) "
-
- "SELECT bar.x, cte.x FROM bar, cte"
- )
+ self.assert_compile(
+ s2, "WITH RECURSIVE bar AS (SELECT cte.x AS x FROM cte), "
+ "cte(x) AS "
+ "(SELECT :param_1 AS x UNION ALL "
+ "SELECT cte.x + :x_1 AS anon_1 "
+ "FROM cte WHERE cte.x < :x_2) "
+ "SELECT bar.x, cte.x FROM bar, cte")
def test_conflicting_names(self):
"""test a flat out name conflict."""
s1 = select([1])
- c1= s1.cte(name='cte1', recursive=True)
+ c1 = s1.cte(name='cte1', recursive=True)
s2 = select([1])
c2 = s2.cte(name='cte1', recursive=True)
s = select([c1, c2])
assert_raises_message(
- CompileError,
- "Multiple, unrelated CTEs found "
- "with the same name: 'cte1'",
- s.compile
+ CompileError,
+ "Multiple, unrelated CTEs found "
+ "with the same name: 'cte1'",
+ s.compile
)
-
-
-
def test_union(self):
orders = table('orders',
- column('region'),
- column('amount'),
- )
+ column('region'),
+ column('amount'),
+ )
regional_sales = select([
- orders.c.region,
- orders.c.amount
- ]).cte("regional_sales")
+ orders.c.region,
+ orders.c.amount
+ ]).cte("regional_sales")
- s = select([regional_sales.c.region]).\
- where(
- regional_sales.c.amount > 500
- )
+ s = select(
+ [regional_sales.c.region]).where(
+ regional_sales.c.amount > 500
+ )
self.assert_compile(s,
- "WITH regional_sales AS "
- "(SELECT orders.region AS region, "
- "orders.amount AS amount FROM orders) "
- "SELECT regional_sales.region "
- "FROM regional_sales WHERE "
- "regional_sales.amount > :amount_1")
+ "WITH regional_sales AS "
+ "(SELECT orders.region AS region, "
+ "orders.amount AS amount FROM orders) "
+ "SELECT regional_sales.region "
+ "FROM regional_sales WHERE "
+ "regional_sales.amount > :amount_1")
s = s.union_all(
- select([regional_sales.c.region]).\
- where(
- regional_sales.c.amount < 300
- )
+ select([regional_sales.c.region]).
+ where(
+ regional_sales.c.amount < 300
+ )
)
self.assert_compile(s,
- "WITH regional_sales AS "
- "(SELECT orders.region AS region, "
- "orders.amount AS amount FROM orders) "
- "SELECT regional_sales.region FROM regional_sales "
- "WHERE regional_sales.amount > :amount_1 "
- "UNION ALL SELECT regional_sales.region "
- "FROM regional_sales WHERE "
- "regional_sales.amount < :amount_2")
+ "WITH regional_sales AS "
+ "(SELECT orders.region AS region, "
+ "orders.amount AS amount FROM orders) "
+ "SELECT regional_sales.region FROM regional_sales "
+ "WHERE regional_sales.amount > :amount_1 "
+ "UNION ALL SELECT regional_sales.region "
+ "FROM regional_sales WHERE "
+ "regional_sales.amount < :amount_2")
def test_reserved_quote(self):
orders = table('orders',
- column('order'),
- )
+ column('order'),
+ )
s = select([orders.c.order]).cte("regional_sales", recursive=True)
s = select([s.c.order])
self.assert_compile(s,
- 'WITH RECURSIVE regional_sales("order") AS '
- '(SELECT orders."order" AS "order" '
- "FROM orders)"
- ' SELECT regional_sales."order" '
- "FROM regional_sales"
- )
+ 'WITH RECURSIVE regional_sales("order") AS '
+ '(SELECT orders."order" AS "order" '
+ "FROM orders)"
+ ' SELECT regional_sales."order" '
+ "FROM regional_sales"
+ )
def test_multi_subq_quote(self):
cte = select([literal(1).label("id")]).cte(name='CTE')
'(SELECT "CTE".id AS id FROM "CTE") AS anon_2'
)
-
def test_positional_binds(self):
orders = table('orders',
- column('order'),
- )
+ column('order'),
+ )
s = select([orders.c.order, literal("x")]).cte("regional_sales")
s = select([s.c.order, literal("y")])
dialect = default.DefaultDialect()
dialect.positional = True
dialect.paramstyle = 'numeric'
- self.assert_compile(s,
+ self.assert_compile(
+ s,
'WITH regional_sales AS (SELECT orders."order" '
'AS "order", :1 AS anon_2 FROM orders) SELECT '
'regional_sales."order", :2 AS anon_1 FROM regional_sales',
- checkpositional=('x', 'y'),
- dialect=dialect
- )
+ checkpositional=(
+ 'x',
+ 'y'),
+ dialect=dialect)
- self.assert_compile(s.union(s),
- 'WITH regional_sales AS (SELECT orders."order" '
+ self.assert_compile(
+ s.union(s), 'WITH regional_sales AS (SELECT orders."order" '
'AS "order", :1 AS anon_2 FROM orders) SELECT '
'regional_sales."order", :2 AS anon_1 FROM regional_sales '
'UNION SELECT regional_sales."order", :3 AS anon_1 '
- 'FROM regional_sales',
- checkpositional=('x', 'y', 'y'),
- dialect=dialect
- )
+ 'FROM regional_sales', checkpositional=(
+ 'x', 'y', 'y'), dialect=dialect)
s = select([orders.c.order]).\
- where(orders.c.order=='x').cte("regional_sales")
- s = select([s.c.order]).where(s.c.order=="y")
- self.assert_compile(s,
- 'WITH regional_sales AS (SELECT orders."order" AS '
+ where(orders.c.order == 'x').cte("regional_sales")
+ s = select([s.c.order]).where(s.c.order == "y")
+ self.assert_compile(
+ s, 'WITH regional_sales AS (SELECT orders."order" AS '
'"order" FROM orders WHERE orders."order" = :1) '
'SELECT regional_sales."order" FROM regional_sales '
- 'WHERE regional_sales."order" = :2',
- checkpositional=('x', 'y'),
- dialect=dialect
- )
+ 'WHERE regional_sales."order" = :2', checkpositional=(
+ 'x', 'y'), dialect=dialect)
def test_positional_binds_2(self):
orders = table('orders',
- column('order'),
- )
+ column('order'),
+ )
s = select([orders.c.order, literal("x")]).cte("regional_sales")
s = select([s.c.order, literal("y")])
dialect = default.DefaultDialect()
dialect.positional = True
dialect.paramstyle = 'numeric'
s1 = select([orders.c.order]).where(orders.c.order == 'x').\
- cte("regional_sales_1")
+ cte("regional_sales_1")
s1a = s1.alias()
s2 = select([orders.c.order == 'y', s1a.c.order,
- orders.c.order, s1.c.order]).\
- where(orders.c.order == 'z').\
- cte("regional_sales_2")
-
+ orders.c.order, s1.c.order]).\
+ where(orders.c.order == 'z').\
+ cte("regional_sales_2")
s3 = select([s2])
'regional_sales_2."order" FROM regional_sales_2',
checkpositional=('x', 'y', 'z'), dialect=dialect)
-
def test_all_aliases(self):
orders = table('order', column('order'))
s = select([orders.c.order]).cte("regional_sales")
'regional_sales AS anon_2 WHERE anon_1."order" > anon_2."order"'
)
- s3 = select([orders]).select_from(orders.join(r1, r1.c.order == orders.c.order))
+ s3 = select(
+ [orders]).select_from(
+ orders.join(
+ r1,
+ r1.c.order == orders.c.order))
self.assert_compile(
s3,
'(SELECT "order"."order" AS "order" '
'FROM "order")'
' SELECT "order"."order" '
- 'FROM "order" JOIN regional_sales AS anon_1 ON anon_1."order" = "order"."order"'
- )
\ No newline at end of file
+ 'FROM "order" JOIN regional_sales AS anon_1 '
+ 'ON anon_1."order" = "order"."order"'
+ )
from sqlalchemy.testing import fixtures
from sqlalchemy.sql.ddl import SchemaGenerator, SchemaDropper
-from sqlalchemy.engine import default
from sqlalchemy import MetaData, Table, Column, Integer, Sequence
from sqlalchemy import schema
from sqlalchemy.testing.mock import Mock
+
class EmitDDLTest(fixtures.TestBase):
+
def _mock_connection(self, item_exists):
def has_item(connection, name, schema):
return item_exists(name)
supports_sequences=True,
has_table=Mock(side_effect=has_item),
has_sequence=Mock(side_effect=has_item)
- )
- )
+ )
+ )
def _mock_create_fixture(self, checkfirst, tables,
- item_exists=lambda item: False):
+ item_exists=lambda item: False):
connection = self._mock_connection(item_exists)
return SchemaGenerator(connection.dialect, connection,
- checkfirst=checkfirst,
- tables=tables)
+ checkfirst=checkfirst,
+ tables=tables)
def _mock_drop_fixture(self, checkfirst, tables,
- item_exists=lambda item: True):
+ item_exists=lambda item: True):
connection = self._mock_connection(item_exists)
return SchemaDropper(connection.dialect, connection,
- checkfirst=checkfirst,
- tables=tables)
+ checkfirst=checkfirst,
+ tables=tables)
def _table_fixture(self):
m = MetaData()
return (m, ) + tuple(
- Table('t%d' % i, m, Column('x', Integer))
- for i in range(1, 6)
- )
+ Table('t%d' % i, m, Column('x', Integer))
+ for i in range(1, 6)
+ )
def _table_seq_fixture(self):
m = MetaData()
return m, t1, t2, s1, s2
-
def test_create_seq_checkfirst(self):
m, t1, t2, s1, s2 = self._table_seq_fixture()
- generator = self._mock_create_fixture(True, [t1, t2],
- item_exists=lambda t: t not in ("t1", "s1")
- )
+ generator = self._mock_create_fixture(
+ True, [
+ t1, t2], item_exists=lambda t: t not in (
+ "t1", "s1"))
self._assert_create([t1, s1], generator, m)
-
def test_drop_seq_checkfirst(self):
m, t1, t2, s1, s2 = self._table_seq_fixture()
- generator = self._mock_drop_fixture(True, [t1, t2],
- item_exists=lambda t: t in ("t1", "s1")
- )
+ generator = self._mock_drop_fixture(
+ True, [
+ t1, t2], item_exists=lambda t: t in (
+ "t1", "s1"))
self._assert_drop([t1, s1], generator, m)
def test_create_collection_checkfirst(self):
m, t1, t2, t3, t4, t5 = self._table_fixture()
- generator = self._mock_create_fixture(True, [t2, t3, t4],
- item_exists=lambda t: t not in ("t2", "t4")
- )
+ generator = self._mock_create_fixture(
+ True, [
+ t2, t3, t4], item_exists=lambda t: t not in (
+ "t2", "t4"))
self._assert_create_tables([t2, t4], generator, m)
def test_drop_collection_checkfirst(self):
m, t1, t2, t3, t4, t5 = self._table_fixture()
- generator = self._mock_drop_fixture(True, [t2, t3, t4],
- item_exists=lambda t: t in ("t2", "t4")
- )
+ generator = self._mock_drop_fixture(
+ True, [
+ t2, t3, t4], item_exists=lambda t: t in (
+ "t2", "t4"))
self._assert_drop_tables([t2, t4], generator, m)
def test_create_collection_nocheck(self):
m, t1, t2, t3, t4, t5 = self._table_fixture()
- generator = self._mock_create_fixture(False, [t2, t3, t4],
- item_exists=lambda t: t not in ("t2", "t4")
- )
+ generator = self._mock_create_fixture(
+ False, [
+ t2, t3, t4], item_exists=lambda t: t not in (
+ "t2", "t4"))
self._assert_create_tables([t2, t3, t4], generator, m)
def test_create_empty_collection(self):
m, t1, t2, t3, t4, t5 = self._table_fixture()
- generator = self._mock_create_fixture(True, [],
- item_exists=lambda t: t not in ("t2", "t4")
- )
+ generator = self._mock_create_fixture(
+ True,
+ [],
+ item_exists=lambda t: t not in (
+ "t2",
+ "t4"))
self._assert_create_tables([], generator, m)
def test_drop_empty_collection(self):
m, t1, t2, t3, t4, t5 = self._table_fixture()
- generator = self._mock_drop_fixture(True, [],
- item_exists=lambda t: t in ("t2", "t4")
- )
+ generator = self._mock_drop_fixture(
+ True,
+ [],
+ item_exists=lambda t: t in (
+ "t2",
+ "t4"))
self._assert_drop_tables([], generator, m)
def test_drop_collection_nocheck(self):
m, t1, t2, t3, t4, t5 = self._table_fixture()
- generator = self._mock_drop_fixture(False, [t2, t3, t4],
- item_exists=lambda t: t in ("t2", "t4")
- )
+ generator = self._mock_drop_fixture(
+ False, [
+ t2, t3, t4], item_exists=lambda t: t in (
+ "t2", "t4"))
self._assert_drop_tables([t2, t3, t4], generator, m)
def test_create_metadata_checkfirst(self):
m, t1, t2, t3, t4, t5 = self._table_fixture()
- generator = self._mock_create_fixture(True, None,
- item_exists=lambda t: t not in ("t2", "t4")
- )
+ generator = self._mock_create_fixture(
+ True,
+ None,
+ item_exists=lambda t: t not in (
+ "t2",
+ "t4"))
self._assert_create_tables([t2, t4], generator, m)
def test_drop_metadata_checkfirst(self):
m, t1, t2, t3, t4, t5 = self._table_fixture()
- generator = self._mock_drop_fixture(True, None,
- item_exists=lambda t: t in ("t2", "t4")
- )
+ generator = self._mock_drop_fixture(
+ True,
+ None,
+ item_exists=lambda t: t in (
+ "t2",
+ "t4"))
self._assert_drop_tables([t2, t4], generator, m)
def test_create_metadata_nocheck(self):
m, t1, t2, t3, t4, t5 = self._table_fixture()
- generator = self._mock_create_fixture(False, None,
- item_exists=lambda t: t not in ("t2", "t4")
- )
+ generator = self._mock_create_fixture(
+ False,
+ None,
+ item_exists=lambda t: t not in (
+ "t2",
+ "t4"))
self._assert_create_tables([t1, t2, t3, t4, t5], generator, m)
def test_drop_metadata_nocheck(self):
m, t1, t2, t3, t4, t5 = self._table_fixture()
- generator = self._mock_drop_fixture(False, None,
- item_exists=lambda t: t in ("t2", "t4")
- )
+ generator = self._mock_drop_fixture(
+ False,
+ None,
+ item_exists=lambda t: t in (
+ "t2",
+ "t4"))
self._assert_drop_tables([t1, t2, t3, t4, t5], generator, m)
def _assert_create(self, elements, generator, argument):
self._assert_ddl(
- (schema.CreateTable, schema.CreateSequence),
- elements, generator, argument)
+ (schema.CreateTable, schema.CreateSequence),
+ elements, generator, argument)
def _assert_drop(self, elements, generator, argument):
self._assert_ddl(
- (schema.DropTable, schema.DropSequence),
- elements, generator, argument)
+ (schema.DropTable, schema.DropSequence),
+ elements, generator, argument)
def _assert_ddl(self, ddl_cls, elements, generator, argument):
generator.traverse_single(argument)
c = call_[1][0]
assert isinstance(c, ddl_cls)
assert c.element in elements, "element %r was not expected"\
- % c.element
+ % c.element
elements.remove(c.element)
assert not elements, "elements remain in list: %r" % elements
is_oracle = testing.against('oracle')
class MyClass(object):
+
@classmethod
def gen_default(cls, ctx):
return "hi"
pass
class fn3(object):
+
def __init__(self, x, y):
pass
class FN4(object):
+
def __call__(self, x, y):
pass
fn4 = FN4()
fn5 = list
class fn6a(object):
+
def __init__(self, x):
eq_(x, "context")
class fn6b(object):
+
def __init__(self, x, y=3):
eq_(x, "context")
class FN7(object):
+
def __call__(self, x):
eq_(x, "context")
fn7 = FN7()
class FN8(object):
+
def __call__(self, x, y=3):
eq_(x, "context")
fn8 = FN8()
class SpecialTypePKTest(fixtures.TestBase):
+
"""test process_result_value in conjunction with primary key columns.
Also tests that "autoincrement" checks are against
#! coding:utf-8
-from sqlalchemy import Column, Integer, String, Table, delete, select, and_, or_
+from sqlalchemy import Column, Integer, String, Table, delete, select, and_, \
+ or_
from sqlalchemy.dialects import mysql
from sqlalchemy.testing import AssertsCompiledSQL, fixtures
class _DeleteTestBase(object):
+
@classmethod
def define_tables(cls, metadata):
Table('mytable', metadata,
self.assert_compile(
table1.delete().
- where(table1.c.myid == 7).
- where(table1.c.name == 'somename'),
+ where(table1.c.myid == 7).
+ where(table1.c.name == 'somename'),
'DELETE FROM mytable '
'WHERE mytable.myid = :myid_1 '
'AND mytable.name = :name_1')
prefix_with('C', 'D')
self.assert_compile(stmt,
- 'DELETE C D FROM mytable')
+ 'DELETE C D FROM mytable')
self.assert_compile(stmt,
- 'DELETE A B C D FROM mytable',
- dialect=mysql.dialect())
+ 'DELETE A B C D FROM mytable',
+ dialect=mysql.dialect())
def test_alias(self):
table1 = self.tables.mytable
talias1 = table1.alias('t1')
stmt = delete(talias1).where(talias1.c.myid == 7)
- self.assert_compile(stmt,
+ self.assert_compile(
+ stmt,
'DELETE FROM mytable AS t1 WHERE t1.myid = :myid_1')
def test_correlated(self):
# test a non-correlated WHERE clause
s = select([table2.c.othername], table2.c.otherid == 7)
self.assert_compile(delete(table1, table1.c.name == s),
- 'DELETE FROM mytable '
- 'WHERE mytable.name = ('
- 'SELECT myothertable.othername '
- 'FROM myothertable '
- 'WHERE myothertable.otherid = :otherid_1'
- ')')
+ 'DELETE FROM mytable '
+ 'WHERE mytable.name = ('
+ 'SELECT myothertable.othername '
+ 'FROM myothertable '
+ 'WHERE myothertable.otherid = :otherid_1'
+ ')')
# test one that is actually correlated...
s = select([table2.c.othername], table2.c.otherid == table1.c.myid)
self.assert_compile(table1.delete(table1.c.name == s),
- 'DELETE FROM mytable '
- 'WHERE mytable.name = ('
- 'SELECT myothertable.othername '
- 'FROM myothertable '
- 'WHERE myothertable.otherid = mytable.myid'
- ')')
+ 'DELETE FROM mytable '
+ 'WHERE mytable.name = ('
+ 'SELECT myothertable.othername '
+ 'FROM myothertable '
+ 'WHERE myothertable.otherid = mytable.myid'
+ ')')
from sqlalchemy.testing import eq_
import datetime
-from sqlalchemy import *
+from sqlalchemy import func, select, Integer, literal, DateTime, Table, \
+ Column, Sequence, MetaData, extract, Date, String, bindparam
from sqlalchemy.sql import table, column
from sqlalchemy import sql, util
from sqlalchemy.sql.compiler import BIND_TEMPLATES
for dialect in all_dialects(exclude=('sybase', )):
bindtemplate = BIND_TEMPLATES[dialect.paramstyle]
self.assert_compile(func.current_timestamp(),
- "CURRENT_TIMESTAMP", dialect=dialect)
+ "CURRENT_TIMESTAMP", dialect=dialect)
self.assert_compile(func.localtime(), "LOCALTIME", dialect=dialect)
if dialect.name in ('firebird',):
self.assert_compile(func.nosuchfunction(),
- "nosuchfunction", dialect=dialect)
+ "nosuchfunction", dialect=dialect)
else:
self.assert_compile(func.nosuchfunction(),
- "nosuchfunction()", dialect=dialect)
+ "nosuchfunction()", dialect=dialect)
# test generic function compile
class fake_func(GenericFunction):
GenericFunction.__init__(self, arg, **kwargs)
self.assert_compile(
- fake_func('foo'),
- "fake_func(%s)" %
- bindtemplate % {'name': 'param_1', 'position': 1},
- dialect=dialect)
+ fake_func('foo'),
+ "fake_func(%s)" %
+ bindtemplate % {'name': 'param_1', 'position': 1},
+ dialect=dialect)
def test_use_labels(self):
self.assert_compile(select([func.foo()], use_labels=True),
- "SELECT foo() AS foo_1"
- )
+ "SELECT foo() AS foo_1"
+ )
+
def test_underscores(self):
self.assert_compile(func.if_(), "if()")
self.assert_compile(
fn, "coalesce(:param_1, :param_2)"
)
+
def test_custom_default_namespace(self):
class myfunc(GenericFunction):
pass
for fn in [func.coalesce, func.max, func.min, func.sum]:
for args, type_ in [
- ((datetime.date(2007, 10, 5),
- datetime.date(2005, 10, 15)), sqltypes.Date),
- ((3, 5), sqltypes.Integer),
- ((decimal.Decimal(3), decimal.Decimal(5)),
- sqltypes.Numeric),
- (("foo", "bar"), sqltypes.String),
- ((datetime.datetime(2007, 10, 5, 8, 3, 34),
- datetime.datetime(2005, 10, 15, 14, 45, 33)),
- sqltypes.DateTime)
- ]:
+ ((datetime.date(2007, 10, 5),
+ datetime.date(2005, 10, 15)), sqltypes.Date),
+ ((3, 5), sqltypes.Integer),
+ ((decimal.Decimal(3), decimal.Decimal(5)),
+ sqltypes.Numeric),
+ (("foo", "bar"), sqltypes.String),
+ ((datetime.datetime(2007, 10, 5, 8, 3, 34),
+ datetime.datetime(2005, 10, 15, 14, 45, 33)),
+ sqltypes.DateTime)
+ ]:
assert isinstance(fn(*args).type, type_), \
- "%s / %r != %s" % (fn(), fn(*args).type, type_)
+ "%s / %r != %s" % (fn(), fn(*args).type, type_)
assert isinstance(func.concat("foo", "bar").type, sqltypes.String)
-
def test_assorted(self):
table1 = table('mytable',
- column('myid', Integer),
- )
+ column('myid', Integer),
+ )
table2 = table(
'myothertable',
# test an expression with a function
self.assert_compile(func.lala(3, 4, literal("five"),
- table1.c.myid) * table2.c.otherid,
- "lala(:lala_1, :lala_2, :param_1, mytable.myid) * "
- "myothertable.otherid")
+ table1.c.myid) * table2.c.otherid,
+ "lala(:lala_1, :lala_2, :param_1, mytable.myid) * "
+ "myothertable.otherid")
# test it in a SELECT
- self.assert_compile(select([func.count(table1.c.myid)]),
+ self.assert_compile(select(
+ [func.count(table1.c.myid)]),
"SELECT count(mytable.myid) AS count_1 FROM mytable")
# test a "dotted" function name
- self.assert_compile(select([func.foo.bar.lala(table1.c.myid)]),
+ self.assert_compile(select([func.foo.bar.lala(
+ table1.c.myid)]),
"SELECT foo.bar.lala(mytable.myid) AS lala_1 FROM mytable")
# test the bind parameter name with a "dotted" function name is
# only the name (limits the length of the bind param name)
self.assert_compile(select([func.foo.bar.lala(12)]),
- "SELECT foo.bar.lala(:lala_2) AS lala_1")
+ "SELECT foo.bar.lala(:lala_2) AS lala_1")
# test a dotted func off the engine itself
self.assert_compile(func.lala.hoho(7), "lala.hoho(:hoho_1)")
# test None becomes NULL
- self.assert_compile(func.my_func(1, 2, None, 3),
- "my_func(:my_func_1, :my_func_2, NULL, :my_func_3)")
+ self.assert_compile(
+ func.my_func(
+ 1,
+ 2,
+ None,
+ 3),
+ "my_func(:my_func_1, :my_func_2, NULL, :my_func_3)")
# test pickling
self.assert_compile(
- util.pickle.loads(util.pickle.dumps(
- func.my_func(1, 2, None, 3))),
- "my_func(:my_func_1, :my_func_2, NULL, :my_func_3)")
+ util.pickle.loads(util.pickle.dumps(
+ func.my_func(1, 2, None, 3))),
+ "my_func(:my_func_1, :my_func_2, NULL, :my_func_3)")
# assert func raises AttributeError for __bases__ attribute, since
# its not a class fixes pydoc
assert True
def test_functions_with_cols(self):
- users = table('users', column('id'), column('name'), column('fullname'))
- calculate = select([column('q'), column('z'), column('r')],
- from_obj=[func.calculate(bindparam('x', None), bindparam('y', None))])
+ users = table(
+ 'users',
+ column('id'),
+ column('name'),
+ column('fullname'))
+ calculate = select([column('q'), column('z'), column('r')], from_obj=[
+ func.calculate(
+ bindparam('x', None), bindparam('y', None)
+ )])
self.assert_compile(select([users], users.c.id > calculate.c.z),
- "SELECT users.id, users.name, users.fullname "
- "FROM users, (SELECT q, z, r "
- "FROM calculate(:x, :y)) "
- "WHERE users.id > z"
- )
+ "SELECT users.id, users.name, users.fullname "
+ "FROM users, (SELECT q, z, r "
+ "FROM calculate(:x, :y)) "
+ "WHERE users.id > z"
+ )
s = select([users], users.c.id.between(
calculate.alias('c1').unique_params(x=17, y=45).c.z,
calculate.alias('c2').unique_params(x=5, y=12).c.z))
- self.assert_compile(s,
- "SELECT users.id, users.name, users.fullname "
+ self.assert_compile(
+ s, "SELECT users.id, users.name, users.fullname "
"FROM users, (SELECT q, z, r "
"FROM calculate(:x_1, :y_1)) AS c1, (SELECT q, z, r "
"FROM calculate(:x_2, :y_2)) AS c2 "
- "WHERE users.id BETWEEN c1.z AND c2.z",
- checkparams={'y_1': 45, 'x_1': 17, 'y_2': 12, 'x_2': 5})
+ "WHERE users.id BETWEEN c1.z AND c2.z", checkparams={
+ 'y_1': 45, 'x_1': 17, 'y_2': 12, 'x_2': 5})
def test_non_functions(self):
expr = func.cast("foo", Integer)
expr = func.extract("year", datetime.date(2010, 12, 5))
self.assert_compile(expr, "EXTRACT(year FROM :param_1)")
+
class ExecuteTest(fixtures.TestBase):
+
@engines.close_first
def tearDown(self):
pass
-
def test_conn_execute(self):
from sqlalchemy.sql.expression import FunctionElement
from sqlalchemy.ext.compiler import compiles
eq_(ret.context.execution_options, {'foo': 'bar'})
ret.close()
-
@engines.close_first
def test_update(self):
"""
meta = MetaData(testing.db)
t = Table('t1', meta,
- Column('id', Integer, Sequence('t1idseq', optional=True),
- primary_key=True),
- Column('value', Integer)
- )
+ Column('id', Integer, Sequence('t1idseq', optional=True),
+ primary_key=True),
+ Column('value', Integer)
+ )
t2 = Table('t2', meta,
- Column('id', Integer, Sequence('t2idseq', optional=True),
- primary_key=True),
- Column('value', Integer, default=7),
- Column('stuff', String(20), onupdate="thisisstuff")
- )
+ Column('id', Integer, Sequence('t2idseq', optional=True),
+ primary_key=True),
+ Column('value', Integer, default=7),
+ Column('stuff', String(20), onupdate="thisisstuff")
+ )
meta.create_all()
try:
t.insert(values=dict(value=func.length("one"))).execute()
assert t.select(t.c.id == id).execute().first()['value'] == 9
t.update(values={t.c.value: func.length("asdf")}).execute()
assert t.select().execute().first()['value'] == 4
- print("--------------------------")
t2.insert().execute()
t2.insert(values=dict(value=func.length("one"))).execute()
t2.insert(values=dict(value=func.length("asfda") + -19)).\
- execute(stuff="hi")
+ execute(stuff="hi")
res = exec_sorted(select([t2.c.value, t2.c.stuff]))
eq_(res, [(-14, 'hi'), (3, None), (7, None)])
t2.update(values=dict(value=func.length("asdsafasd"))).\
- execute(stuff="some stuff")
+ execute(stuff="some stuff")
assert select([t2.c.value, t2.c.stuff]).execute().fetchall() == \
- [(9, "some stuff"), (9, "some stuff"),
- (9, "some stuff")]
+ [(9, "some stuff"), (9, "some stuff"),
+ (9, "some stuff")]
t2.delete().execute()
)
t2.update(values={t2.c.value: func.length("asfdaasdf"),
- t2.c.stuff: "foo"}).execute()
+ t2.c.stuff: "foo"}).execute()
print("HI", select([t2.c.value, t2.c.stuff]).execute().first())
eq_(select([t2.c.value, t2.c.stuff]).execute().first(),
- (9, "foo")
+ (9, "foo")
)
finally:
meta.drop_all()
y = func.current_date(bind=testing.db).select().execute().scalar()
z = func.current_date(bind=testing.db).scalar()
w = select(['*'], from_obj=[func.current_date(bind=testing.db)]).\
- scalar()
+ scalar()
# construct a column-based FROM object out of a function,
# like in [ticket:172]
s = select([sql.column('date', type_=DateTime)],
- from_obj=[func.current_date(bind=testing.db)])
+ from_obj=[func.current_date(bind=testing.db)])
q = s.execute().first()[s.c.date]
r = s.alias('datequery').select().scalar()
return sorted([tuple(row)
for row in statement.execute(*args, **kw).fetchall()])
-
-from sqlalchemy import *
from sqlalchemy.sql import table, column, ClauseElement, operators
-from sqlalchemy.sql.expression import _clone, _from_objects
+from sqlalchemy.sql.expression import _clone, _from_objects
+from sqlalchemy import func, select, Integer, Table, \
+ Column, MetaData, extract, String, bindparam, tuple_, and_, union, text,\
+ case, ForeignKey
from sqlalchemy.testing import fixtures, AssertsExecutionResults, \
AssertsCompiledSQL
from sqlalchemy import testing
from sqlalchemy.sql import util as sql_util
from sqlalchemy.testing import eq_, is_, assert_raises, assert_raises_message
+A = B = t1 = t2 = t3 = table1 = table2 = table3 = table4 = None
+
+
class TraversalTest(fixtures.TestBase, AssertsExecutionResults):
+
"""test ClauseVisitor's traversal, particularly its
ability to copy and modify a ClauseElement in place."""
struct = B(a1, A("expr2"), B(A("expr1b"), A("expr2b")), A("expr3"))
struct2 = B(a1, A("expr2"), B(A("expr1b"), A("expr2b")), A("expr3"))
struct3 = B(a1, A("expr2"), B(A("expr1b"),
- A("expr2bmodified")), A("expr3"))
+ A("expr2bmodified")), A("expr3"))
assert a1.is_other(a1)
assert struct.is_other(struct)
def test_clone(self):
struct = B(A("expr1"), A("expr2"), B(A("expr1b"),
- A("expr2b")), A("expr3"))
+ A("expr2b")), A("expr3"))
class Vis(CloningVisitor):
+
def visit_a(self, a):
pass
+
def visit_b(self, b):
pass
def test_no_clone(self):
struct = B(A("expr1"), A("expr2"), B(A("expr1b"),
- A("expr2b")), A("expr3"))
+ A("expr2b")), A("expr3"))
class Vis(ClauseVisitor):
+
def visit_a(self, a):
pass
+
def visit_b(self, b):
pass
def test_change_in_place(self):
struct = B(A("expr1"), A("expr2"), B(A("expr1b"),
- A("expr2b")), A("expr3"))
+ A("expr2b")), A("expr3"))
struct2 = B(A("expr1"), A("expr2modified"), B(A("expr1b"),
- A("expr2b")), A("expr3"))
+ A("expr2b")), A("expr3"))
struct3 = B(A("expr1"), A("expr2"), B(A("expr1b"),
- A("expr2bmodified")), A("expr3"))
+ A("expr2bmodified")), A("expr3"))
class Vis(CloningVisitor):
+
def visit_a(self, a):
if a.expr == "expr2":
a.expr = "expr2modified"
+
def visit_b(self, b):
pass
assert struct2 == s2
class Vis2(CloningVisitor):
+
def visit_a(self, a):
if a.expr == "expr2b":
a.expr = "expr2bmodified"
+
def visit_b(self, b):
pass
set(ClauseVisitor().iterate(bin))
assert set(ClauseVisitor().iterate(bin)) == set([foo, bar, bin])
+
class BinaryEndpointTraversalTest(fixtures.TestBase):
+
"""test the special binary product visit"""
def _assert_traversal(self, expr, expected):
canary = []
+
def visit(binary, l, r):
canary.append((binary.operator, l, r))
print(binary.operator, l, r)
expr = tuple_(
a, b, b1 == tuple_(b1a, b1b == d), c
) > tuple_(
- func.go(e + f)
- )
+ func.go(e + f)
+ )
self._assert_traversal(
expr,
[
]
)
+
class ClauseTest(fixtures.TestBase, AssertsCompiledSQL):
+
"""test copy-in-place behavior of various ClauseElements."""
__dialect__ = 'default'
def setup_class(cls):
global t1, t2, t3
t1 = table("table1",
- column("col1"),
- column("col2"),
- column("col3"),
- )
+ column("col1"),
+ column("col2"),
+ column("col3"),
+ )
t2 = table("table2",
- column("col1"),
- column("col2"),
- column("col3"),
- )
+ column("col1"),
+ column("col2"),
+ column("col3"),
+ )
t3 = Table('table3', MetaData(),
- Column('col1', Integer),
- Column('col2', Integer)
- )
+ Column('col1', Integer),
+ Column('col2', Integer)
+ )
def test_binary(self):
clause = t1.c.col2 == t2.c.col2
def test_binary_anon_label_quirk(self):
t = table('t1', column('col1'))
-
f = t.c.col1 * 5
self.assert_compile(select([f]),
- "SELECT t1.col1 * :col1_1 AS anon_1 FROM t1")
+ "SELECT t1.col1 * :col1_1 AS anon_1 FROM t1")
f.anon_label
a = t.alias()
f = sql_util.ClauseAdapter(a).traverse(f)
- self.assert_compile(select([f]),
- "SELECT t1_1.col1 * :col1_1 AS anon_1 FROM t1 AS t1_1")
+ self.assert_compile(
+ select(
+ [f]),
+ "SELECT t1_1.col1 * :col1_1 AS anon_1 FROM t1 AS t1_1")
def test_join(self):
clause = t1.join(t2, t1.c.col2 == t2.c.col2)
assert str(clause) == str(CloningVisitor().traverse(clause))
class Vis(CloningVisitor):
+
def visit_binary(self, binary):
binary.right = t2.c.col3
def test_text(self):
clause = text(
- "select * from table where foo=:bar",
- bindparams=[bindparam('bar')])
+ "select * from table where foo=:bar",
+ bindparams=[bindparam('bar')])
c1 = str(clause)
+
class Vis(CloningVisitor):
+
def visit_textclause(self, text):
text.text = text.text + " SOME MODIFIER=:lala"
text._bindparams['lala'] = bindparam('lala')
s2 = select([t1])
s2_assert = str(s2)
s3_assert = str(select([t1], t1.c.col2 == 7))
+
class Vis(CloningVisitor):
+
def visit_select(self, select):
select.append_whereclause(t1.c.col2 == 7)
s3 = Vis().traverse(s2)
assert str(s2) == s2_assert
print(str(s2))
print(str(s3))
+
class Vis(ClauseVisitor):
+
def visit_select(self, select):
select.append_whereclause(t1.c.col2 == 7)
Vis().traverse(s2)
assert str(s2) == s3_assert
s4_assert = str(select([t1], and_(t1.c.col2 == 7, t1.c.col3 == 9)))
+
class Vis(CloningVisitor):
+
def visit_select(self, select):
select.append_whereclause(t1.c.col3 == 9)
s4 = Vis().traverse(s3)
assert str(s3) == s3_assert
s5_assert = str(select([t1], and_(t1.c.col2 == 7, t1.c.col1 == 9)))
+
class Vis(CloningVisitor):
+
def visit_binary(self, binary):
if binary.left is t1.c.col3:
binary.left = t1.c.col1
u2 = u.params(id_param=7)
u3 = u.params(id_param=10)
assert str(u) == str(u2) == str(u3)
- assert u2.compile().params == {'id_param':7}
- assert u3.compile().params == {'id_param':10}
+ assert u2.compile().params == {'id_param': 7}
+ assert u3.compile().params == {'id_param': 10}
def test_in(self):
expr = t1.c.col1.in_(['foo', 'bar'])
def test_adapt_union(self):
u = union(
- t1.select().where(t1.c.col1 == 4),
- t1.select().where(t1.c.col1 == 5)
- ).alias()
+ t1.select().where(t1.c.col1 == 4),
+ t1.select().where(t1.c.col1 == 5)
+ ).alias()
assert sql_util.ClauseAdapter(u).traverse(t1) is u
s2 = CloningVisitor().traverse(s).alias()
s3 = select([s], s.c.col2 == s2.c.col2)
- self.assert_compile(s3,
- "SELECT anon_1.col1, anon_1.col2, anon_1.col3 FROM "
+ self.assert_compile(
+ s3, "SELECT anon_1.col1, anon_1.col2, anon_1.col3 FROM "
"(SELECT table1.col1 AS col1, table1.col2 AS col2, "
"table1.col3 AS col3 FROM table1 WHERE table1.col1 = :param_1) "
"AS anon_1, "
s = select([t1], t1.c.col1 == 4).alias()
s2 = CloningVisitor().traverse(s).alias()
s3 = select([s], s.c.col2 == s2.c.col2)
- self.assert_compile(s3,
- "SELECT anon_1.col1, anon_1.col2, anon_1.col3 FROM "
+ self.assert_compile(
+ s3, "SELECT anon_1.col1, anon_1.col2, anon_1.col3 FROM "
"(SELECT table1.col1 AS col1, table1.col2 AS col2, "
"table1.col3 AS col3 FROM table1 WHERE table1.col1 = :col1_1) "
"AS anon_1, "
def test_extract(self):
s = select([extract('foo', t1.c.col1).label('col1')])
- self.assert_compile(s,
- "SELECT EXTRACT(foo FROM table1.col1) AS col1 FROM table1")
+ self.assert_compile(
+ s,
+ "SELECT EXTRACT(foo FROM table1.col1) AS col1 FROM table1")
s2 = CloningVisitor().traverse(s).alias()
s3 = select([s2.c.col1])
- self.assert_compile(s,
- "SELECT EXTRACT(foo FROM table1.col1) AS col1 FROM table1")
+ self.assert_compile(
+ s,
+ "SELECT EXTRACT(foo FROM table1.col1) AS col1 FROM table1")
self.assert_compile(s3,
- "SELECT anon_1.col1 FROM (SELECT EXTRACT(foo FROM "
- "table1.col1) AS col1 FROM table1) AS anon_1")
-
+ "SELECT anon_1.col1 FROM (SELECT EXTRACT(foo FROM "
+ "table1.col1) AS col1 FROM table1) AS anon_1")
@testing.emits_warning('.*replaced by another column with the same key')
def test_alias(self):
subq = t2.select().alias('subq')
s = select([t1.c.col1, subq.c.col1],
- from_obj=[t1, subq,
- t1.join(subq, t1.c.col1 == subq.c.col2)]
- )
+ from_obj=[t1, subq,
+ t1.join(subq, t1.c.col1 == subq.c.col2)]
+ )
orig = str(s)
s2 = CloningVisitor().traverse(s)
assert orig == str(s) == str(s2)
subq = subq.alias('subq')
s = select([t1.c.col1, subq.c.col1],
- from_obj=[t1, subq,
- t1.join(subq, t1.c.col1 == subq.c.col2)]
- )
+ from_obj=[t1, subq,
+ t1.join(subq, t1.c.col1 == subq.c.col2)]
+ )
s5 = CloningVisitor().traverse(s)
assert orig == str(s) == str(s5)
def test_correlated_select(self):
s = select(['*'], t1.c.col1 == t2.c.col1,
- from_obj=[t1, t2]).correlate(t2)
+ from_obj=[t1, t2]).correlate(t2)
class Vis(CloningVisitor):
+
def visit_select(self, select):
select.append_whereclause(t1.c.col2 == 7)
self.assert_compile(
- select([t2]).where(t2.c.col1 == Vis().traverse(s)),
- "SELECT table2.col1, table2.col2, table2.col3 "
- "FROM table2 WHERE table2.col1 = "
- "(SELECT * FROM table1 WHERE table1.col1 = table2.col1 "
- "AND table1.col2 = :col2_1)"
- )
+ select([t2]).where(t2.c.col1 == Vis().traverse(s)),
+ "SELECT table2.col1, table2.col2, table2.col3 "
+ "FROM table2 WHERE table2.col1 = "
+ "(SELECT * FROM table1 WHERE table1.col1 = table2.col1 "
+ "AND table1.col2 = :col2_1)"
+ )
def test_this_thing(self):
s = select([t1]).where(t1.c.col1 == 'foo').alias()
s = select([1], t1.c.col1 == t1a.c.col1, from_obj=t1a).correlate(t1a)
s = select([t1]).where(t1.c.col1 == s)
- self.assert_compile(s,
- "SELECT table1.col1, table1.col2, table1.col3 FROM table1 "
+ self.assert_compile(
+ s, "SELECT table1.col1, table1.col2, table1.col3 FROM table1 "
"WHERE table1.col1 = "
"(SELECT 1 FROM table1, table1 AS table1_1 "
- "WHERE table1.col1 = table1_1.col1)"
- )
+ "WHERE table1.col1 = table1_1.col1)")
s = CloningVisitor().traverse(s)
- self.assert_compile(s,
- "SELECT table1.col1, table1.col2, table1.col3 FROM table1 "
+ self.assert_compile(
+ s, "SELECT table1.col1, table1.col2, table1.col3 FROM table1 "
"WHERE table1.col1 = "
"(SELECT 1 FROM table1, table1 AS table1_1 "
- "WHERE table1.col1 = table1_1.col1)")
+ "WHERE table1.col1 = table1_1.col1)")
def test_select_fromtwice_two(self):
s = select([t1]).where(t1.c.col1 == 'foo').alias()
s2 = select([1], t1.c.col1 == s.c.col1, from_obj=s).correlate(t1)
s3 = select([t1]).where(t1.c.col1 == s2)
- self.assert_compile(s3,
- "SELECT table1.col1, table1.col2, table1.col3 "
- "FROM table1 WHERE table1.col1 = "
- "(SELECT 1 FROM "
- "(SELECT table1.col1 AS col1, table1.col2 AS col2, "
- "table1.col3 AS col3 FROM table1 "
- "WHERE table1.col1 = :col1_1) "
- "AS anon_1 WHERE table1.col1 = anon_1.col1)"
- )
+ self.assert_compile(
+ s3, "SELECT table1.col1, table1.col2, table1.col3 "
+ "FROM table1 WHERE table1.col1 = "
+ "(SELECT 1 FROM "
+ "(SELECT table1.col1 AS col1, table1.col2 AS col2, "
+ "table1.col3 AS col3 FROM table1 "
+ "WHERE table1.col1 = :col1_1) "
+ "AS anon_1 WHERE table1.col1 = anon_1.col1)")
s4 = ReplacingCloningVisitor().traverse(s3)
- self.assert_compile(s4,
- "SELECT table1.col1, table1.col2, table1.col3 "
- "FROM table1 WHERE table1.col1 = "
- "(SELECT 1 FROM "
- "(SELECT table1.col1 AS col1, table1.col2 AS col2, "
- "table1.col3 AS col3 FROM table1 "
- "WHERE table1.col1 = :col1_1) "
- "AS anon_1 WHERE table1.col1 = anon_1.col1)"
- )
+ self.assert_compile(
+ s4, "SELECT table1.col1, table1.col2, table1.col3 "
+ "FROM table1 WHERE table1.col1 = "
+ "(SELECT 1 FROM "
+ "(SELECT table1.col1 AS col1, table1.col2 AS col2, "
+ "table1.col3 AS col3 FROM table1 "
+ "WHERE table1.col1 = :col1_1) "
+ "AS anon_1 WHERE table1.col1 = anon_1.col1)")
+
class ClauseAdapterTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
def setup_class(cls):
global t1, t2
t1 = table("table1",
- column("col1"),
- column("col2"),
- column("col3"),
- )
+ column("col1"),
+ column("col2"),
+ column("col3"),
+ )
t2 = table("table2",
- column("col1"),
- column("col2"),
- column("col3"),
- )
+ column("col1"),
+ column("col2"),
+ column("col3"),
+ )
def test_correlation_on_clone(self):
t1alias = t1.alias('t1alias')
s = vis.traverse(s)
assert t2alias not in s._froms # not present because it's been
- # cloned
+ # cloned
assert t1alias in s._froms # present because the adapter placed
- # it there
+ # it there
# correlate list on "s" needs to take into account the full
# _cloned_set for each element in _froms when correlating
't2alias.col1 = (SELECT * FROM table1 AS '
't1alias)')
s = select(['*'], from_obj=[t1alias,
- t2alias]).correlate(t2alias).as_scalar()
+ t2alias]).correlate(t2alias).as_scalar()
self.assert_compile(select(['*'], t2alias.c.col1 == s),
'SELECT * FROM table2 AS t2alias WHERE '
't2alias.col1 = (SELECT * FROM table1 AS '
t1alias = t1.alias('t1alias')
vis = sql_util.ClauseAdapter(t1alias)
self.assert_compile(vis.traverse(select(['*'], t1.c.col1
- == t2.c.col2)),
+ == t2.c.col2)),
'SELECT * FROM table1 AS t1alias, table2 '
'WHERE t1alias.col1 = table2.col2')
def test_table_to_alias_5(self):
t1alias = t1.alias('t1alias')
vis = sql_util.ClauseAdapter(t1alias)
- self.assert_compile(vis.traverse(select(['*'], t1.c.col1
- == t2.c.col2, from_obj=[t1, t2])),
- 'SELECT * FROM table1 AS t1alias, table2 '
- 'WHERE t1alias.col1 = table2.col2')
+ self.assert_compile(
+ vis.traverse(
+ select(
+ ['*'],
+ t1.c.col1 == t2.c.col2,
+ from_obj=[
+ t1,
+ t2])),
+ 'SELECT * FROM table1 AS t1alias, table2 '
+ 'WHERE t1alias.col1 = table2.col2')
def test_table_to_alias_6(self):
t1alias = t1.alias('t1alias')
vis = sql_util.ClauseAdapter(t1alias)
self.assert_compile(
- select([t1alias, t2]).where(t1alias.c.col1 ==
- vis.traverse(select(['*'],
- t1.c.col1 == t2.c.col2,
- from_obj=[t1, t2]).correlate(t1))),
- "SELECT t1alias.col1, t1alias.col2, t1alias.col3, "
- "table2.col1, table2.col2, table2.col3 "
- "FROM table1 AS t1alias, table2 WHERE t1alias.col1 = "
- "(SELECT * FROM table2 WHERE t1alias.col1 = table2.col2)"
- )
+ select([t1alias, t2]).where(
+ t1alias.c.col1 == vis.traverse(
+ select(['*'], t1.c.col1 == t2.c.col2, from_obj=[t1, t2]).
+ correlate(t1)
+ )
+ ),
+ "SELECT t1alias.col1, t1alias.col2, t1alias.col3, "
+ "table2.col1, table2.col2, table2.col3 "
+ "FROM table1 AS t1alias, table2 WHERE t1alias.col1 = "
+ "(SELECT * FROM table2 WHERE t1alias.col1 = table2.col2)"
+ )
def test_table_to_alias_7(self):
t1alias = t1.alias('t1alias')
vis = sql_util.ClauseAdapter(t1alias)
self.assert_compile(
- select([t1alias, t2]).where(t1alias.c.col1 ==
- vis.traverse(select(['*'],
- t1.c.col1 == t2.c.col2,
- from_obj=[t1, t2]).correlate(t2))),
- "SELECT t1alias.col1, t1alias.col2, t1alias.col3, "
- "table2.col1, table2.col2, table2.col3 "
- "FROM table1 AS t1alias, table2 "
- "WHERE t1alias.col1 = "
- "(SELECT * FROM table1 AS t1alias "
- "WHERE t1alias.col1 = table2.col2)")
+ select([t1alias, t2]).
+ where(t1alias.c.col1 == vis.traverse(
+ select(['*'], t1.c.col1 == t2.c.col2, from_obj=[t1, t2]).
+ correlate(t2))),
+ "SELECT t1alias.col1, t1alias.col2, t1alias.col3, "
+ "table2.col1, table2.col2, table2.col3 "
+ "FROM table1 AS t1alias, table2 "
+ "WHERE t1alias.col1 = "
+ "(SELECT * FROM table1 AS t1alias "
+ "WHERE t1alias.col1 = table2.col2)")
def test_table_to_alias_8(self):
t1alias = t1.alias('t1alias')
vis = sql_util.ClauseAdapter(t1alias)
- self.assert_compile(vis.traverse(case([(t1.c.col1 == 5,
- t1.c.col2)], else_=t1.c.col1)),
- 'CASE WHEN (t1alias.col1 = :col1_1) THEN '
- 't1alias.col2 ELSE t1alias.col1 END')
+ self.assert_compile(
+ vis.traverse(case([(t1.c.col1 == 5, t1.c.col2)], else_=t1.c.col1)),
+ 'CASE WHEN (t1alias.col1 = :col1_1) THEN '
+ 't1alias.col2 ELSE t1alias.col1 END')
def test_table_to_alias_9(self):
t1alias = t1.alias('t1alias')
vis = sql_util.ClauseAdapter(t1alias)
- self.assert_compile(vis.traverse(case([(5, t1.c.col2)],
- value=t1.c.col1, else_=t1.c.col1)),
- 'CASE t1alias.col1 WHEN :param_1 THEN '
- 't1alias.col2 ELSE t1alias.col1 END')
-
+ self.assert_compile(
+ vis.traverse(
+ case(
+ [
+ (5,
+ t1.c.col2)],
+ value=t1.c.col1,
+ else_=t1.c.col1)),
+ 'CASE t1alias.col1 WHEN :param_1 THEN '
+ 't1alias.col2 ELSE t1alias.col1 END')
def test_table_to_alias_10(self):
s = select(['*'], from_obj=[t1]).alias('foo')
'table1 AS t1alias')
assert list(_from_objects(ff)) == [t1alias]
- #def test_table_to_alias_2(self):
+ # def test_table_to_alias_2(self):
# TODO: self.assert_compile(vis.traverse(select([func.count(t1.c
# .col1).l abel('foo')]), clone=True), "SELECT
# count(t1alias.col1) AS foo FROM table1 AS t1alias")
t2alias = t2.alias('t2alias')
vis.chain(sql_util.ClauseAdapter(t2alias))
self.assert_compile(vis.traverse(select(['*'], t1.c.col1
- == t2.c.col2)),
+ == t2.c.col2)),
'SELECT * FROM table1 AS t1alias, table2 '
'AS t2alias WHERE t1alias.col1 = '
't2alias.col2')
vis = sql_util.ClauseAdapter(t1alias)
t2alias = t2.alias('t2alias')
vis.chain(sql_util.ClauseAdapter(t2alias))
- self.assert_compile(vis.traverse(select(['*'], t1.c.col1
- == t2.c.col2, from_obj=[t1, t2])),
- 'SELECT * FROM table1 AS t1alias, table2 '
- 'AS t2alias WHERE t1alias.col1 = '
- 't2alias.col2')
+ self.assert_compile(
+ vis.traverse(
+ select(
+ ['*'],
+ t1.c.col1 == t2.c.col2,
+ from_obj=[
+ t1,
+ t2])),
+ 'SELECT * FROM table1 AS t1alias, table2 '
+ 'AS t2alias WHERE t1alias.col1 = '
+ 't2alias.col2')
def test_table_to_alias_16(self):
t1alias = t1.alias('t1alias')
vis.chain(sql_util.ClauseAdapter(t2alias))
self.assert_compile(
select([t1alias, t2alias]).where(
- t1alias.c.col1 ==
- vis.traverse(select(['*'],
- t1.c.col1 == t2.c.col2,
- from_obj=[t1, t2]).correlate(t1))
- ),
- "SELECT t1alias.col1, t1alias.col2, t1alias.col3, "
- "t2alias.col1, t2alias.col2, t2alias.col3 "
- "FROM table1 AS t1alias, table2 AS t2alias "
- "WHERE t1alias.col1 = "
- "(SELECT * FROM table2 AS t2alias "
- "WHERE t1alias.col1 = t2alias.col2)"
- )
+ t1alias.c.col1 ==
+ vis.traverse(select(['*'],
+ t1.c.col1 == t2.c.col2,
+ from_obj=[t1, t2]).correlate(t1))
+ ),
+ "SELECT t1alias.col1, t1alias.col2, t1alias.col3, "
+ "t2alias.col1, t2alias.col2, t2alias.col3 "
+ "FROM table1 AS t1alias, table2 AS t2alias "
+ "WHERE t1alias.col1 = "
+ "(SELECT * FROM table2 AS t2alias "
+ "WHERE t1alias.col1 = t2alias.col2)"
+ )
def test_table_to_alias_17(self):
t1alias = t1.alias('t1alias')
t2alias = t2.alias('t2alias')
vis.chain(sql_util.ClauseAdapter(t2alias))
self.assert_compile(
- t2alias.select().where(t2alias.c.col2 ==
- vis.traverse(select(['*'],
+ t2alias.select().where(
+ t2alias.c.col2 == vis.traverse(
+ select(
+ ['*'],
t1.c.col1 == t2.c.col2,
- from_obj=[t1, t2]).correlate(t2))),
- 'SELECT t2alias.col1, t2alias.col2, t2alias.col3 '
- 'FROM table2 AS t2alias WHERE t2alias.col2 = '
- '(SELECT * FROM table1 AS t1alias WHERE '
- 't1alias.col1 = t2alias.col2)')
+ from_obj=[
+ t1,
+ t2]).correlate(t2))),
+ 'SELECT t2alias.col1, t2alias.col2, t2alias.col3 '
+ 'FROM table2 AS t2alias WHERE t2alias.col2 = '
+ '(SELECT * FROM table1 AS t1alias WHERE '
+ 't1alias.col1 = t2alias.col2)')
def test_include_exclude(self):
m = MetaData()
a = Table('a', m,
- Column('id', Integer, primary_key=True),
- Column('xxx_id', Integer,
- ForeignKey('a.id', name='adf', use_alter=True)
- )
- )
+ Column('id', Integer, primary_key=True),
+ Column('xxx_id', Integer,
+ ForeignKey('a.id', name='adf', use_alter=True)
+ )
+ )
e = (a.c.id == a.c.xxx_id)
assert str(e) == "a.id = a.xxx_id"
b = a.alias()
- e = sql_util.ClauseAdapter( b, include= set([ a.c.id ]),
- equivalents= { a.c.id: set([ a.c.id]) }
- ).traverse( e)
+ e = sql_util.ClauseAdapter(b, include=set([a.c.id]),
+ equivalents={a.c.id: set([a.c.id])}
+ ).traverse(e)
assert str(e) == "a_1.id = a.xxx_id"
# force a recursion overflow, by linking a.c.x<->c.c.x, and
# asking for a nonexistent col. corresponding_column should prevent
# endless depth.
- adapt = sql_util.ClauseAdapter(b,
- equivalents={a.c.x: set([c.c.x]), c.c.x: set([a.c.x])})
+ adapt = sql_util.ClauseAdapter(
+ b, equivalents={a.c.x: set([c.c.x]), c.c.x: set([a.c.x])})
assert adapt._corresponding_column(a.c.x, False) is None
def test_multilevel_equivalents(self):
# two levels of indirection from c.x->b.x->a.x, requires recursive
# corresponding_column call
- adapt = sql_util.ClauseAdapter(alias,
- equivalents={b.c.x: set([a.c.x]), c.c.x: set([b.c.x])})
+ adapt = sql_util.ClauseAdapter(
+ alias, equivalents={b.c.x: set([a.c.x]), c.c.x: set([b.c.x])})
assert adapt._corresponding_column(a.c.x, False) is alias.c.x
assert adapt._corresponding_column(c.c.x, False) is alias.c.x
def test_join_to_alias(self):
metadata = MetaData()
a = Table('a', metadata,
- Column('id', Integer, primary_key=True))
+ Column('id', Integer, primary_key=True))
b = Table('b', metadata,
- Column('id', Integer, primary_key=True),
- Column('aid', Integer, ForeignKey('a.id')),
- )
+ Column('id', Integer, primary_key=True),
+ Column('aid', Integer, ForeignKey('a.id')),
+ )
c = Table('c', metadata,
- Column('id', Integer, primary_key=True),
- Column('bid', Integer, ForeignKey('b.id')),
- )
+ Column('id', Integer, primary_key=True),
+ Column('bid', Integer, ForeignKey('b.id')),
+ )
d = Table('d', metadata,
- Column('id', Integer, primary_key=True),
- Column('aid', Integer, ForeignKey('a.id')),
- )
+ Column('id', Integer, primary_key=True),
+ Column('aid', Integer, ForeignKey('a.id')),
+ )
j1 = a.outerjoin(b)
j2 = select([j1], use_labels=True)
assert not t1.is_derived_from(select([t1]))
assert t1.alias().is_derived_from(t1)
-
s1 = select([t1, t2]).alias('foo')
s2 = select([s1]).limit(5).offset(10).alias()
assert s2.is_derived_from(s1)
'LIMIT :param_1 OFFSET :param_2) AS anon_1 '
'LEFT OUTER JOIN table1 AS bar ON '
'anon_1.col1 = bar.col1', {'param_1': 5,
- 'param_2': 10})
+ 'param_2': 10})
def test_functions(self):
self.assert_compile(
- sql_util.ClauseAdapter(t1.alias()).\
- traverse(func.count(t1.c.col1)),
- 'count(table1_1.col1)')
+ sql_util.ClauseAdapter(t1.alias()).
+ traverse(func.count(t1.c.col1)),
+ 'count(table1_1.col1)')
s = select([func.count(t1.c.col1)])
self.assert_compile(sql_util.ClauseAdapter(t1.alias()).traverse(s),
'SELECT count(table1_1.col1) AS count_1 '
def test_recursive(self):
metadata = MetaData()
a = Table('a', metadata,
- Column('id', Integer, primary_key=True))
+ Column('id', Integer, primary_key=True))
b = Table('b', metadata,
- Column('id', Integer, primary_key=True),
- Column('aid', Integer, ForeignKey('a.id')),
- )
+ Column('id', Integer, primary_key=True),
+ Column('aid', Integer, ForeignKey('a.id')),
+ )
c = Table('c', metadata,
- Column('id', Integer, primary_key=True),
- Column('bid', Integer, ForeignKey('b.id')),
- )
+ Column('id', Integer, primary_key=True),
+ Column('bid', Integer, ForeignKey('b.id')),
+ )
d = Table('d', metadata,
- Column('id', Integer, primary_key=True),
- Column('aid', Integer, ForeignKey('a.id')),
- )
+ Column('id', Integer, primary_key=True),
+ Column('aid', Integer, ForeignKey('a.id')),
+ )
u = union(
a.join(b).select().apply_labels(),
).alias()
self.assert_compile(
- sql_util.ClauseAdapter(u).\
- traverse(select([c.c.bid]).where(c.c.bid == u.c.b_aid)),
- "SELECT c.bid "\
+ sql_util.ClauseAdapter(u).
+ traverse(select([c.c.bid]).where(c.c.bid == u.c.b_aid)),
+ "SELECT c.bid "
"FROM c, (SELECT a.id AS a_id, b.id AS b_id, b.aid AS b_aid "
"FROM a JOIN b ON a.id = b.aid UNION SELECT a.id AS a_id, d.id "
"AS d_id, d.aid AS d_aid "
"WHERE c.bid = anon_1.b_aid"
)
+
class SpliceJoinsTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
return table(name, column('col1'), column('col2'),
column('col3'))
- table1, table2, table3, table4 = [_table(name) for name in
- ('table1', 'table2', 'table3', 'table4')]
+ table1, table2, table3, table4 = [
+ _table(name) for name in (
+ 'table1', 'table2', 'table3', 'table4')]
def test_splice(self):
t1, t2, t3, t4 = table1, table2, table1.alias(), table2.alias()
- j = t1.join(t2, t1.c.col1 == t2.c.col1).join(t3, t2.c.col1
- == t3.c.col1).join(t4, t4.c.col1 == t1.c.col1)
+ j = t1.join(
+ t2,
+ t1.c.col1 == t2.c.col1).join(
+ t3,
+ t2.c.col1 == t3.c.col1).join(
+ t4,
+ t4.c.col1 == t1.c.col1)
s = select([t1]).where(t1.c.col2 < 5).alias()
self.assert_compile(sql_util.splice_joins(s, j),
'(SELECT table1.col1 AS col1, table1.col2 '
def test_splice_2(self):
t2a = table2.alias()
t3a = table3.alias()
- j1 = table1.join(t2a, table1.c.col1 == t2a.c.col1).join(t3a,
- t2a.c.col2 == t3a.c.col2)
+ j1 = table1.join(
+ t2a,
+ table1.c.col1 == t2a.c.col1).join(
+ t3a,
+ t2a.c.col2 == t3a.c.col2)
t2b = table4.alias()
j2 = table1.join(t2b, table1.c.col3 == t2b.c.col3)
self.assert_compile(sql_util.splice_joins(table1, j1),
self.assert_compile(sql_util.splice_joins(table1, j2),
'table1 JOIN table4 AS table4_1 ON '
'table1.col3 = table4_1.col3')
- self.assert_compile(sql_util.splice_joins(sql_util.splice_joins(table1,
- j1), j2),
- 'table1 JOIN table2 AS table2_1 ON '
- 'table1.col1 = table2_1.col1 JOIN table3 '
- 'AS table3_1 ON table2_1.col2 = '
- 'table3_1.col2 JOIN table4 AS table4_1 ON '
- 'table1.col3 = table4_1.col3')
+ self.assert_compile(
+ sql_util.splice_joins(
+ sql_util.splice_joins(
+ table1,
+ j1),
+ j2),
+ 'table1 JOIN table2 AS table2_1 ON '
+ 'table1.col1 = table2_1.col1 JOIN table3 '
+ 'AS table3_1 ON table2_1.col2 = '
+ 'table3_1.col2 JOIN table4 AS table4_1 ON '
+ 'table1.col3 = table4_1.col3')
class SelectTest(fixtures.TestBase, AssertsCompiledSQL):
+
"""tests the generative capability of Select"""
__dialect__ = 'default'
def setup_class(cls):
global t1, t2
t1 = table("table1",
- column("col1"),
- column("col2"),
- column("col3"),
- )
+ column("col1"),
+ column("col2"),
+ column("col3"),
+ )
t2 = table("table2",
- column("col1"),
- column("col2"),
- column("col3"),
- )
-
+ column("col1"),
+ column("col2"),
+ column("col3"),
+ )
def test_columns(self):
s = t1.select()
'SELECT table1.col1, table1.col2, '
'table1.col3 FROM table1')
-
def test_prefixes(self):
s = t1.select()
self.assert_compile(s,
assert_raises(
exc.ArgumentError,
select().execution_options,
- isolation_level='READ_COMMITTED'
+ isolation_level='READ_COMMITTED'
)
# this feature not available yet
s = text('select 42', execution_options=dict(foo='bar'))
assert s._execution_options == dict(foo='bar')
+
class ValuesBaseTest(fixtures.TestBase, AssertsCompiledSQL):
+
"""Tests the generative capability of Insert, Update"""
__dialect__ = 'default'
def setup_class(cls):
global t1, t2
t1 = table("table1",
- column("col1"),
- column("col2"),
- column("col3"),
- )
+ column("col1"),
+ column("col2"),
+ column("col3"),
+ )
t2 = table("table2",
- column("col1"),
- column("col2"),
- column("col3"),
- )
+ column("col1"),
+ column("col2"),
+ column("col3"),
+ )
def test_prefixes(self):
i = t1.insert()
eq_(i.parameters, None)
i = i.values([(5, 6, 7), (8, 9, 10)])
eq_(i.parameters, [
- {"col1": 5, "col2": 6, "col3": 7},
- {"col1": 8, "col2": 9, "col3": 10},
- ]
+ {"col1": 5, "col2": 6, "col3": 7},
+ {"col1": 8, "col2": 9, "col3": 10},
+ ]
)
def test_inline_values_single(self):
class _InsertTestBase(object):
+
@classmethod
def define_tables(cls, metadata):
Table('mytable', metadata,
table1 = self.tables.mytable
self.assert_compile(insert(table1),
- 'INSERT INTO mytable (myid, name, description) '
- 'VALUES (:myid, :name, :description)')
+ 'INSERT INTO mytable (myid, name, description) '
+ 'VALUES (:myid, :name, :description)')
def test_insert_with_values_dict(self):
table1 = self.tables.mytable
'name': 'jack'
}
- self.assert_compile(insert(table1, dict(myid=3, name='jack')),
+ self.assert_compile(
+ insert(
+ table1,
+ dict(
+ myid=3,
+ name='jack')),
'INSERT INTO mytable (myid, name) VALUES (:myid, :name)',
checkparams=checkparams)
}
self.assert_compile(insert(table1, (3, 'jack', 'mydescription')),
- 'INSERT INTO mytable (myid, name, description) '
- 'VALUES (:myid, :name, :description)',
- checkparams=checkparams)
+ 'INSERT INTO mytable (myid, name, description) '
+ 'VALUES (:myid, :name, :description)',
+ checkparams=checkparams)
def test_insert_with_values_func(self):
table1 = self.tables.mytable
self.assert_compile(insert(table1, values=dict(myid=func.lala())),
- 'INSERT INTO mytable (myid) VALUES (lala())')
+ 'INSERT INTO mytable (myid) VALUES (lala())')
def test_insert_with_user_supplied_bind_params(self):
table1 = self.tables.mytable
table1.c.name: bindparam('username')
}
- self.assert_compile(insert(table1, values),
+ self.assert_compile(
+ insert(
+ table1,
+ values),
'INSERT INTO mytable (myid, name) VALUES (:userid, :username)')
def test_insert_values(self):
values1 = {table1.c.myid: bindparam('userid')}
values2 = {table1.c.name: bindparam('username')}
- self.assert_compile(insert(table1, values=values1).values(values2),
+ self.assert_compile(
+ insert(
+ table1,
+ values=values1).values(values2),
'INSERT INTO mytable (myid, name) VALUES (:userid, :username)')
def test_prefix_with(self):
prefix_with('A', 'B', dialect='mysql').\
prefix_with('C', 'D')
- self.assert_compile(stmt,
+ self.assert_compile(
+ stmt,
'INSERT C D INTO mytable (myid, name, description) '
'VALUES (:myid, :name, :description)')
- self.assert_compile(stmt,
+ self.assert_compile(
+ stmt,
'INSERT A B C D INTO mytable (myid, name, description) '
- 'VALUES (%s, %s, %s)', dialect=mysql.dialect())
+ 'VALUES (%s, %s, %s)',
+ dialect=mysql.dialect())
def test_inline_default(self):
metadata = MetaData()
table = Table('sometable', metadata,
- Column('id', Integer, primary_key=True),
- Column('foo', Integer, default=func.foobar()))
+ Column('id', Integer, primary_key=True),
+ Column('foo', Integer, default=func.foobar()))
self.assert_compile(table.insert(values={}, inline=True),
- 'INSERT INTO sometable (foo) VALUES (foobar())')
+ 'INSERT INTO sometable (foo) VALUES (foobar())')
- self.assert_compile(table.insert(inline=True),
- 'INSERT INTO sometable (foo) VALUES (foobar())', params={})
+ self.assert_compile(
+ table.insert(
+ inline=True),
+ 'INSERT INTO sometable (foo) VALUES (foobar())',
+ params={})
def test_insert_returning_not_in_default(self):
table1 = self.tables.mytable
def test_insert_from_select_select(self):
table1 = self.tables.mytable
- sel = select([table1.c.myid, table1.c.name]).where(table1.c.name == 'foo')
+ sel = select([table1.c.myid, table1.c.name]).where(
+ table1.c.name == 'foo')
ins = self.tables.myothertable.insert().\
- from_select(("otherid", "othername"), sel)
+ from_select(("otherid", "othername"), sel)
self.assert_compile(
ins,
"INSERT INTO myothertable (otherid, othername) "
def test_insert_from_select_select_alt_ordering(self):
table1 = self.tables.mytable
- sel = select([table1.c.name, table1.c.myid]).where(table1.c.name == 'foo')
+ sel = select([table1.c.name, table1.c.myid]).where(
+ table1.c.name == 'foo')
ins = self.tables.myothertable.insert().\
- from_select(("othername", "otherid"), sel)
+ from_select(("othername", "otherid"), sel)
self.assert_compile(
ins,
"INSERT INTO myothertable (othername, otherid) "
def test_insert_from_select_select_no_defaults(self):
metadata = MetaData()
table = Table('sometable', metadata,
- Column('id', Integer, primary_key=True),
- Column('foo', Integer, default=func.foobar()))
+ Column('id', Integer, primary_key=True),
+ Column('foo', Integer, default=func.foobar()))
table1 = self.tables.mytable
sel = select([table1.c.myid]).where(table1.c.name == 'foo')
ins = table.insert().\
- from_select(["id"], sel)
+ from_select(["id"], sel)
self.assert_compile(
ins,
"INSERT INTO sometable (id) SELECT mytable.myid "
def test_insert_mix_select_values_exception(self):
table1 = self.tables.mytable
- sel = select([table1.c.myid, table1.c.name]).where(table1.c.name == 'foo')
+ sel = select([table1.c.myid, table1.c.name]).where(
+ table1.c.name == 'foo')
ins = self.tables.myothertable.insert().\
- from_select(("otherid", "othername"), sel)
+ from_select(("otherid", "othername"), sel)
assert_raises_message(
exc.InvalidRequestError,
"This construct already inserts from a SELECT",
def test_insert_mix_values_select_exception(self):
table1 = self.tables.mytable
- sel = select([table1.c.myid, table1.c.name]).where(table1.c.name == 'foo')
+ sel = select([table1.c.myid, table1.c.name]).where(
+ table1.c.name == 'foo')
ins = self.tables.myothertable.insert().values(othername="5")
assert_raises_message(
exc.InvalidRequestError,
def test_insert_from_select_table(self):
table1 = self.tables.mytable
ins = self.tables.myothertable.insert().\
- from_select(("otherid", "othername"), table1)
+ from_select(("otherid", "othername"), table1)
# note we aren't checking the number of columns right now
self.assert_compile(
ins,
select([name, description])
)
ins = mytable.insert().\
- from_select(
- [mytable.c.name, mytable.c.description], sel)
+ from_select(
+ [mytable.c.name, mytable.c.description], sel)
self.assert_compile(
ins,
"INSERT INTO mytable (name, description) "
- "SELECT name, mytable.description FROM mytable "
- "UNION SELECT name, desc"
+ "SELECT name, mytable.description FROM mytable "
+ "UNION SELECT name, desc"
)
+
def test_insert_from_select_col_values(self):
table1 = self.tables.mytable
table2 = self.tables.myothertable
- sel = select([table1.c.myid, table1.c.name]).where(table1.c.name == 'foo')
+ sel = select([table1.c.myid, table1.c.name]).where(
+ table1.c.name == 'foo')
ins = table2.insert().\
- from_select((table2.c.otherid, table2.c.othername), sel)
+ from_select((table2.c.otherid, table2.c.othername), sel)
self.assert_compile(
ins,
"INSERT INTO myothertable (otherid, othername) "
stmt = table1.insert().values({}) # hide from 2to3
self.assert_compile(stmt,
- 'INSERT INTO mytable DEFAULT VALUES',
- dialect=dialect)
+ 'INSERT INTO mytable DEFAULT VALUES',
+ dialect=dialect)
def test_supports_empty_insert_false(self):
table1 = self.tables.mytable
dialect.supports_empty_insert = dialect.supports_default_values = False
stmt = table1.insert().values({}) # hide from 2to3
- assert_raises_message(exc.CompileError,
+ assert_raises_message(
+ exc.CompileError,
"The 'default' dialect with current database version "
- "settings does not support empty inserts.",
- stmt.compile, dialect=dialect)
+ "settings does not support empty inserts.",
+ stmt.compile,
+ dialect=dialect)
def _test_insert_with_empty_collection_values(self, collection):
table1 = self.tables.mytable
ins = table1.insert().values(collection)
self.assert_compile(ins,
- 'INSERT INTO mytable () VALUES ()',
- checkparams={})
+ 'INSERT INTO mytable () VALUES ()',
+ checkparams={})
# empty dict populates on next values call
self.assert_compile(ins.values(myid=3),
- 'INSERT INTO mytable (myid) VALUES (:myid)',
- checkparams={'myid': 3})
+ 'INSERT INTO mytable (myid) VALUES (:myid)',
+ checkparams={'myid': 3})
def test_insert_with_empty_list_values(self):
self._test_insert_with_empty_collection_values([])
assert_raises_message(
exc.CompileError,
"The 'default' dialect with current database version settings "
- "does not support in-place multirow inserts.",
+ "does not support in-place multirow inserts.",
stmt.compile, dialect=dialect)
def test_named(self):
dialect = default.DefaultDialect()
dialect.supports_multivalues_insert = True
- self.assert_compile(table1.insert().values(values),
+ self.assert_compile(
+ table1.insert().values(values),
'INSERT INTO mytable (myid, name, description) VALUES '
- '(:myid_0, :name_0, :description_0), '
- '(:myid_1, :name_1, :description_1), '
- '(:myid_2, :name_2, :description_2)',
- checkparams=checkparams, dialect=dialect)
+ '(:myid_0, :name_0, :description_0), '
+ '(:myid_1, :name_1, :description_1), '
+ '(:myid_2, :name_2, :description_2)',
+ checkparams=checkparams,
+ dialect=dialect)
def test_positional(self):
table1 = self.tables.mytable
dialect.paramstyle = 'format'
dialect.positional = True
- self.assert_compile(table1.insert().values(values),
+ self.assert_compile(
+ table1.insert().values(values),
'INSERT INTO mytable (myid, name, description) VALUES '
'(%s, %s, %s), (%s, %s, %s), (%s, %s, %s)',
- checkpositional=checkpositional, dialect=dialect)
+ checkpositional=checkpositional,
+ dialect=dialect)
def test_inline_default(self):
metadata = MetaData()
table = Table('sometable', metadata,
- Column('id', Integer, primary_key=True),
- Column('data', String),
- Column('foo', Integer, default=func.foobar()))
+ Column('id', Integer, primary_key=True),
+ Column('data', String),
+ Column('foo', Integer, default=func.foobar()))
values = [
{'id': 1, 'data': 'data1'},
'foo_1': 'plainfoo',
}
- self.assert_compile(table.insert().values(values),
+ self.assert_compile(
+ table.insert().values(values),
'INSERT INTO sometable (id, data, foo) VALUES '
'(%(id_0)s, %(data_0)s, foobar()), '
'(%(id_1)s, %(data_1)s, %(foo_1)s), '
'(%(id_2)s, %(data_2)s, foobar())',
- checkparams=checkparams, dialect=postgresql.dialect())
+ checkparams=checkparams,
+ dialect=postgresql.dialect())
def test_sql_functions(self):
metadata = MetaData()
table = Table('sometable', metadata,
- Column('id', Integer, primary_key=True),
- Column('data', String),
- Column('foo', Integer))
+ Column('id', Integer, primary_key=True),
+ Column('data', String),
+ Column('foo', Integer))
values = [
{"id": 1, "data": "foo", "foo": func.foob()},
'data_4': 'bar'
}
- self.assert_compile(table.insert().values(values),
+ self.assert_compile(
+ table.insert().values(values),
"INSERT INTO sometable (id, data, foo) VALUES "
"(%(id_0)s, %(data_0)s, foob()), "
"(%(id_1)s, %(data_1)s, foob()), "
"(%(id_2)s, %(data_2)s, bar()), "
"(%(id_3)s, %(data_3)s, %(foo_3)s), "
"(%(id_4)s, %(data_4)s, foob())",
- checkparams=checkparams, dialect=postgresql.dialect())
+ checkparams=checkparams,
+ dialect=postgresql.dialect())
def test_server_default(self):
metadata = MetaData()
table = Table('sometable', metadata,
- Column('id', Integer, primary_key=True),
- Column('data', String),
- Column('foo', Integer, server_default=func.foobar()))
+ Column('id', Integer, primary_key=True),
+ Column('data', String),
+ Column('foo', Integer, server_default=func.foobar()))
values = [
{'id': 1, 'data': 'data1'},
'data_2': 'data3',
}
- self.assert_compile(table.insert().values(values),
+ self.assert_compile(
+ table.insert().values(values),
'INSERT INTO sometable (id, data) VALUES '
'(%(id_0)s, %(data_0)s), '
'(%(id_1)s, %(data_1)s), '
'(%(id_2)s, %(data_2)s)',
- checkparams=checkparams, dialect=postgresql.dialect())
+ checkparams=checkparams,
+ dialect=postgresql.dialect())
def test_server_default_absent_value(self):
metadata = MetaData()
table = Table('sometable', metadata,
- Column('id', Integer, primary_key=True),
- Column('data', String),
- Column('foo', Integer, server_default=func.foobar()))
+ Column('id', Integer, primary_key=True),
+ Column('data', String),
+ Column('foo', Integer, server_default=func.foobar()))
values = [
{'id': 1, 'data': 'data1', 'foo': 'plainfoo'},
# note the effect here is that the first set of params
# takes effect for the rest of them, when one is absent
- self.assert_compile(table.insert().values(values),
+ self.assert_compile(
+ table.insert().values(values),
'INSERT INTO sometable (id, data, foo) VALUES '
'(%(id_0)s, %(data_0)s, %(foo_0)s), '
'(%(id_1)s, %(data_1)s, %(foo_0)s), '
'(%(id_2)s, %(data_2)s, %(foo_2)s)',
- checkparams=checkparams, dialect=postgresql.dialect())
+ checkparams=checkparams,
+ dialect=postgresql.dialect())
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import is_
+
class TestCoreInspection(fixtures.TestBase):
def test_table(self):
t = Table('t', MetaData(),
- Column('x', Integer)
- )
+ Column('x', Integer)
+ )
is_(inspect(t), t)
assert t.is_selectable
def test_select(self):
t = Table('t', MetaData(),
- Column('x', Integer)
- )
+ Column('x', Integer)
+ )
s = t.select()
is_(inspect(s), s)
c = Column('x', Integer)
is_(inspect(c), c)
assert not c.is_selectable
- assert not hasattr(c, 'selectable')
\ No newline at end of file
+ assert not hasattr(c, 'selectable')
-from sqlalchemy import Table, Column, Integer, MetaData, ForeignKey, select, exists, union
-from sqlalchemy.testing import fixtures, AssertsCompiledSQL, eq_
+from sqlalchemy import Table, Column, Integer, MetaData, ForeignKey, \
+ select, exists, union
+from sqlalchemy.testing import fixtures, AssertsCompiledSQL
from sqlalchemy import util
from sqlalchemy.engine import default
from sqlalchemy import testing
a = Table('a', m,
- Column('id', Integer, primary_key=True)
- )
+ Column('id', Integer, primary_key=True)
+ )
b = Table('b', m,
- Column('id', Integer, primary_key=True),
- Column('a_id', Integer, ForeignKey('a.id'))
- )
+ Column('id', Integer, primary_key=True),
+ Column('a_id', Integer, ForeignKey('a.id'))
+ )
b_a = Table('b_a', m,
- Column('id', Integer, primary_key=True),
- )
+ Column('id', Integer, primary_key=True),
+ )
b1 = Table('b1', m,
- Column('id', Integer, primary_key=True),
- Column('a_id', Integer, ForeignKey('a.id'))
- )
+ Column('id', Integer, primary_key=True),
+ Column('a_id', Integer, ForeignKey('a.id'))
+ )
b2 = Table('b2', m,
- Column('id', Integer, primary_key=True),
- Column('a_id', Integer, ForeignKey('a.id'))
- )
+ Column('id', Integer, primary_key=True),
+ Column('a_id', Integer, ForeignKey('a.id'))
+ )
a_to_b = Table('a_to_b', m,
- Column('a_id', Integer, ForeignKey('a.id')),
- Column('b_id', Integer, ForeignKey('b.id')),
- )
+ Column('a_id', Integer, ForeignKey('a.id')),
+ Column('b_id', Integer, ForeignKey('b.id')),
+ )
c = Table('c', m,
- Column('id', Integer, primary_key=True),
- Column('b_id', Integer, ForeignKey('b.id'))
- )
+ Column('id', Integer, primary_key=True),
+ Column('b_id', Integer, ForeignKey('b.id'))
+ )
d = Table('d', m,
- Column('id', Integer, primary_key=True),
- Column('c_id', Integer, ForeignKey('c.id'))
- )
+ Column('id', Integer, primary_key=True),
+ Column('c_id', Integer, ForeignKey('c.id'))
+ )
e = Table('e', m,
- Column('id', Integer, primary_key=True)
- )
+ Column('id', Integer, primary_key=True)
+ )
f = Table('f', m,
- Column('id', Integer, primary_key=True),
- Column('a_id', ForeignKey('a.id'))
- )
+ Column('id', Integer, primary_key=True),
+ Column('a_id', ForeignKey('a.id'))
+ )
b_key = Table('b_key', m,
- Column('id', Integer, primary_key=True, key='bid'),
- )
+ Column('id', Integer, primary_key=True, key='bid'),
+ )
a_to_b_key = Table('a_to_b_key', m,
- Column('aid', Integer, ForeignKey('a.id')),
- Column('bid', Integer, ForeignKey('b_key.bid')),
- )
+ Column('aid', Integer, ForeignKey('a.id')),
+ Column('bid', Integer, ForeignKey('b_key.bid')),
+ )
+
class _JoinRewriteTestBase(AssertsCompiledSQL):
+
def _test(self, s, assert_):
self.assert_compile(
s,
j2 = a.join(j1)
s = select([a, b_key.c.bid], use_labels=True).\
- select_from(j2)
+ select_from(j2)
self._test(s, self._a_bkeyassoc)
j2 = a.join(j1)
s = select([a, bkey_alias.c.bid], use_labels=True).\
- select_from(j2)
+ select_from(j2)
self._test(s, self._a_bkeyassoc_aliased)
where(b.c.id == 2).\
where(c.c.id == 3).\
where(d.c.id == 4).\
- order_by(a.c.id, b.c.id, c.c.id, d.c.id)
+ order_by(a.c.id, b.c.id, c.c.id, d.c.id)
self._test(
s,
def test_a_bc_comma_a1_selbc(self):
# test here we're emulating is
- # test.orm.inheritance.test_polymorphic_rel:PolymorphicJoinsTest.test_multi_join
+ # test.orm.inheritance.test_polymorphic_rel:
+ # PolymorphicJoinsTest.test_multi_join
j1 = b.join(c)
j2 = b.join(c).select(use_labels=True).alias()
j3 = a.join(j1)
j4 = a_a.join(j2)
s = select([a, a_a, b, c, j2], use_labels=True).\
- select_from(j3).select_from(j4).order_by(j2.c.b_id)
+ select_from(j3).select_from(j4).order_by(j2.c.b_id)
self._test(
s,
# TODO: if we put straight a_to_b_alias here,
# it fails to alias the columns clause.
- s = select([a, a_to_b_alias.c.a_id, a_to_b_alias.c.b_id,
- b_alias.c.id, b_alias.c.a_id,
- exists().select_from(c).where(c.c.b_id == b_alias.c.id).label(None)
- ], use_labels=True).select_from(j2)
+ s = select([a,
+ a_to_b_alias.c.a_id,
+ a_to_b_alias.c.b_id,
+ b_alias.c.id,
+ b_alias.c.a_id,
+ exists().select_from(c).
+ where(c.c.b_id == b_alias.c.id).label(None)],
+ use_labels=True).select_from(j2)
self._test(
s,
b_j2 = b.join(j2)
s = union(
- select([b_j1], use_labels=True),
- select([b_j2], use_labels=True)
- ).select(use_labels=True)
+ select([b_j1], use_labels=True),
+ select([b_j2], use_labels=True)
+ ).select(use_labels=True)
self._test(
s,
# this involves annotations so try to loop those in.
j1 = b.join(b_a, b.c.id == b_a.c.id)
annot = [
- b.c.id._annotate({}),
- b.c.a_id._annotate({}),
- b_a.c.id._annotate({})
- ]
+ b.c.id._annotate({}),
+ b.c.a_id._annotate({}),
+ b_a.c.id._annotate({})
+ ]
s = select(annot).select_from(j1).apply_labels().alias()
class JoinRewriteTest(_JoinRewriteTestBase, fixtures.TestBase):
+
"""test rendering of each join with right-nested rewritten as
aliased SELECT statements.."""
return dialect
_a__b_dc = (
- "SELECT a.id AS a_id, anon_1.b_id AS b_id, "
- "anon_1.b_a_id AS b_a_id, anon_1.c_id AS c_id, "
- "anon_1.c_b_id AS c_b_id, anon_1.d_id AS d_id, "
- "anon_1.d_c_id AS d_c_id "
- "FROM a JOIN (SELECT b.id AS b_id, b.a_id AS b_a_id, "
- "anon_2.c_id AS c_id, anon_2.c_b_id AS c_b_id, "
- "anon_2.d_id AS d_id, anon_2.d_c_id AS d_c_id "
- "FROM b JOIN (SELECT c.id AS c_id, c.b_id AS c_b_id, "
- "d.id AS d_id, d.c_id AS d_c_id "
- "FROM c JOIN d ON c.id = d.c_id) AS anon_2 "
- "ON b.id = anon_2.c_b_id) AS anon_1 ON a.id = anon_1.b_a_id "
- "WHERE anon_1.b_id = :id_1 AND anon_1.c_id = :id_2 AND "
- "anon_1.d_id = :id_3 "
- "ORDER BY a.id, anon_1.b_id, anon_1.c_id, anon_1.d_id"
- )
+ "SELECT a.id AS a_id, anon_1.b_id AS b_id, "
+ "anon_1.b_a_id AS b_a_id, anon_1.c_id AS c_id, "
+ "anon_1.c_b_id AS c_b_id, anon_1.d_id AS d_id, "
+ "anon_1.d_c_id AS d_c_id "
+ "FROM a JOIN (SELECT b.id AS b_id, b.a_id AS b_a_id, "
+ "anon_2.c_id AS c_id, anon_2.c_b_id AS c_b_id, "
+ "anon_2.d_id AS d_id, anon_2.d_c_id AS d_c_id "
+ "FROM b JOIN (SELECT c.id AS c_id, c.b_id AS c_b_id, "
+ "d.id AS d_id, d.c_id AS d_c_id "
+ "FROM c JOIN d ON c.id = d.c_id) AS anon_2 "
+ "ON b.id = anon_2.c_b_id) AS anon_1 ON a.id = anon_1.b_a_id "
+ "WHERE anon_1.b_id = :id_1 AND anon_1.c_id = :id_2 AND "
+ "anon_1.d_id = :id_3 "
+ "ORDER BY a.id, anon_1.b_id, anon_1.c_id, anon_1.d_id"
+ )
_a_bc = (
- "SELECT a.id AS a_id, anon_1.b_id AS b_id, "
- "anon_1.b_a_id AS b_a_id, anon_1.c_id AS c_id, "
- "anon_1.c_b_id AS c_b_id FROM a JOIN "
- "(SELECT b.id AS b_id, b.a_id AS b_a_id, "
- "c.id AS c_id, c.b_id AS c_b_id "
- "FROM b JOIN c ON b.id = c.b_id) AS anon_1 "
- "ON a.id = anon_1.b_a_id "
- "WHERE anon_1.b_id = :id_1 AND anon_1.c_id = :id_2 "
- "ORDER BY a.id, anon_1.b_id, anon_1.c_id"
- )
+ "SELECT a.id AS a_id, anon_1.b_id AS b_id, "
+ "anon_1.b_a_id AS b_a_id, anon_1.c_id AS c_id, "
+ "anon_1.c_b_id AS c_b_id FROM a JOIN "
+ "(SELECT b.id AS b_id, b.a_id AS b_a_id, "
+ "c.id AS c_id, c.b_id AS c_b_id "
+ "FROM b JOIN c ON b.id = c.b_id) AS anon_1 "
+ "ON a.id = anon_1.b_a_id "
+ "WHERE anon_1.b_id = :id_1 AND anon_1.c_id = :id_2 "
+ "ORDER BY a.id, anon_1.b_id, anon_1.c_id"
+ )
_a_bc_comma_a1_selbc = (
- "SELECT a.id AS a_id, a_1.id AS a_1_id, anon_1.b_id AS b_id, "
- "anon_1.b_a_id AS b_a_id, anon_1.c_id AS c_id, "
- "anon_1.c_b_id AS c_b_id, anon_2.b_id AS anon_2_b_id, "
- "anon_2.b_a_id AS anon_2_b_a_id, anon_2.c_id AS anon_2_c_id, "
- "anon_2.c_b_id AS anon_2_c_b_id FROM a "
- "JOIN (SELECT b.id AS b_id, b.a_id AS b_a_id, c.id AS c_id, "
- "c.b_id AS c_b_id FROM b JOIN c ON b.id = c.b_id) AS anon_1 "
- "ON a.id = anon_1.b_a_id, "
- "a AS a_1 JOIN "
- "(SELECT b.id AS b_id, b.a_id AS b_a_id, "
- "c.id AS c_id, c.b_id AS c_b_id "
- "FROM b JOIN c ON b.id = c.b_id) AS anon_2 "
- "ON a_1.id = anon_2.b_a_id ORDER BY anon_2.b_id"
- )
+ "SELECT a.id AS a_id, a_1.id AS a_1_id, anon_1.b_id AS b_id, "
+ "anon_1.b_a_id AS b_a_id, anon_1.c_id AS c_id, "
+ "anon_1.c_b_id AS c_b_id, anon_2.b_id AS anon_2_b_id, "
+ "anon_2.b_a_id AS anon_2_b_a_id, anon_2.c_id AS anon_2_c_id, "
+ "anon_2.c_b_id AS anon_2_c_b_id FROM a "
+ "JOIN (SELECT b.id AS b_id, b.a_id AS b_a_id, c.id AS c_id, "
+ "c.b_id AS c_b_id FROM b JOIN c ON b.id = c.b_id) AS anon_1 "
+ "ON a.id = anon_1.b_a_id, "
+ "a AS a_1 JOIN "
+ "(SELECT b.id AS b_id, b.a_id AS b_a_id, "
+ "c.id AS c_id, c.b_id AS c_b_id "
+ "FROM b JOIN c ON b.id = c.b_id) AS anon_2 "
+ "ON a_1.id = anon_2.b_a_id ORDER BY anon_2.b_id"
+ )
_a_bkeyassoc = (
"SELECT a.id AS a_id, anon_1.b_key_id AS b_key_id "
"a_to_b_key.bid AS a_to_b_key_bid FROM b_key "
"JOIN a_to_b_key ON b_key.id = a_to_b_key.bid) AS anon_1 "
"ON a.id = anon_1.a_to_b_key_aid"
- )
+ )
_a_bkeyassoc_aliased = (
"SELECT a.id AS a_id, anon_1.b_key_1_id AS b_key_1_id "
"a_to_b_key_1.bid AS a_to_b_key_1_bid FROM b_key AS b_key_1 "
"JOIN a_to_b_key AS a_to_b_key_1 ON b_key_1.id = a_to_b_key_1.bid) AS "
"anon_1 ON a.id = anon_1.a_to_b_key_1_aid"
- )
+ )
_a_bkeyselect_bkey = (
"SELECT a.id AS a_id, anon_2.anon_1_aid AS anon_1_aid, "
"anon_2.anon_1_bid AS anon_1_bid, anon_2.b_key_id AS b_key_id "
- "FROM a JOIN (SELECT anon_1.aid AS anon_1_aid, anon_1.bid AS anon_1_bid, "
- "b_key.id AS b_key_id "
- "FROM (SELECT a_to_b_key.aid AS aid, a_to_b_key.bid AS bid "
- "FROM a_to_b_key) AS anon_1 "
- "JOIN b_key ON b_key.id = anon_1.bid) AS anon_2 ON a.id = anon_2.anon_1_aid"
- )
+ "FROM a JOIN (SELECT anon_1.aid AS anon_1_aid, "
+ "anon_1.bid AS anon_1_bid, "
+ "b_key.id AS b_key_id "
+ "FROM (SELECT a_to_b_key.aid AS aid, a_to_b_key.bid AS bid "
+ "FROM a_to_b_key) AS anon_1 "
+ "JOIN b_key ON b_key.id = anon_1.bid) AS anon_2 "
+ "ON a.id = anon_2.anon_1_aid")
_a_atobalias_balias_c_w_exists = (
"SELECT a.id AS a_id, "
- "anon_1.a_to_b_1_a_id AS a_to_b_1_a_id, anon_1.a_to_b_1_b_id AS a_to_b_1_b_id, "
+ "anon_1.a_to_b_1_a_id AS a_to_b_1_a_id, "
+ "anon_1.a_to_b_1_b_id AS a_to_b_1_b_id, "
"anon_1.b_1_id AS b_1_id, anon_1.b_1_a_id AS b_1_a_id, "
"EXISTS (SELECT * FROM c WHERE c.b_id = anon_1.b_1_id) AS anon_2 "
"FROM a LEFT OUTER JOIN (SELECT a_to_b_1.a_id AS a_to_b_1_a_id, "
- "a_to_b_1.b_id AS a_to_b_1_b_id, b_1.id AS b_1_id, b_1.a_id AS b_1_a_id "
+ "a_to_b_1.b_id AS a_to_b_1_b_id, b_1.id AS b_1_id, "
+ "b_1.a_id AS b_1_a_id "
"FROM a_to_b AS a_to_b_1 "
"JOIN b AS b_1 ON b_1.id = a_to_b_1.b_id) AS anon_1 "
- "ON a.id = anon_1.a_to_b_1_a_id"
- )
+ "ON a.id = anon_1.a_to_b_1_a_id")
_a_atobalias_balias = (
"SELECT a.id AS a_id, anon_1.a_to_b_1_a_id AS a_to_b_1_a_id, "
"anon_1.a_to_b_1_b_id AS a_to_b_1_b_id, anon_1.b_1_id AS b_1_id, "
"anon_1.b_1_a_id AS b_1_a_id FROM a LEFT OUTER JOIN "
- "(SELECT a_to_b_1.a_id AS a_to_b_1_a_id, a_to_b_1.b_id AS a_to_b_1_b_id, "
+ "(SELECT a_to_b_1.a_id AS a_to_b_1_a_id, "
+ "a_to_b_1.b_id AS a_to_b_1_b_id, "
"b_1.id AS b_1_id, b_1.a_id AS b_1_a_id FROM a_to_b AS a_to_b_1 "
- "JOIN b AS b_1 ON b_1.id = a_to_b_1.b_id) AS anon_1 ON a.id = anon_1.a_to_b_1_a_id"
- )
+ "JOIN b AS b_1 ON b_1.id = a_to_b_1.b_id) AS anon_1 "
+ "ON a.id = anon_1.a_to_b_1_a_id")
_b_ab1_union_c_ab2 = (
"SELECT b_id AS b_id, b_a_id AS b_a_id, a_id AS a_id, b1_id AS b1_id, "
"b1_a_id AS b1_a_id FROM "
"(SELECT b.id AS b_id, b.a_id AS b_a_id, anon_1.a_id AS a_id, "
- "anon_1.b1_id AS b1_id, anon_1.b1_a_id AS b1_a_id "
- "FROM b JOIN (SELECT a.id AS a_id, b1.id AS b1_id, b1.a_id AS b1_a_id "
- "FROM a JOIN b1 ON a.id = b1.a_id) AS anon_1 ON anon_1.a_id = b.a_id "
+ "anon_1.b1_id AS b1_id, anon_1.b1_a_id AS b1_a_id "
+ "FROM b JOIN (SELECT a.id AS a_id, b1.id AS b1_id, b1.a_id AS b1_a_id "
+ "FROM a JOIN b1 ON a.id = b1.a_id) AS anon_1 ON anon_1.a_id = b.a_id "
"UNION "
"SELECT b.id AS b_id, b.a_id AS b_a_id, anon_2.a_id AS a_id, "
"anon_2.b2_id AS b2_id, anon_2.b2_a_id AS b2_a_id "
"FROM a JOIN b2 ON a.id = b2.a_id)"
)
+
class JoinPlainTest(_JoinRewriteTestBase, fixtures.TestBase):
+
"""test rendering of each join with normal nesting."""
@util.classproperty
def __dialect__(cls):
_a_bkeyselect_bkey = (
"SELECT a.id AS a_id, b_key.id AS b_key_id FROM a JOIN "
"((SELECT a_to_b_key.aid AS aid, a_to_b_key.bid AS bid "
- "FROM a_to_b_key) AS anon_1 JOIN b_key ON b_key.id = anon_1.bid) "
+ "FROM a_to_b_key) AS anon_1 JOIN b_key ON b_key.id = anon_1.bid) "
"ON a.id = anon_1.aid"
)
_a__b_dc = (
- "SELECT a.id AS a_id, b.id AS b_id, "
- "b.a_id AS b_a_id, c.id AS c_id, "
- "c.b_id AS c_b_id, d.id AS d_id, "
- "d.c_id AS d_c_id "
- "FROM a JOIN (b JOIN (c JOIN d ON c.id = d.c_id) "
- "ON b.id = c.b_id) ON a.id = b.a_id "
- "WHERE b.id = :id_1 AND c.id = :id_2 AND "
- "d.id = :id_3 "
- "ORDER BY a.id, b.id, c.id, d.id"
- )
-
+ "SELECT a.id AS a_id, b.id AS b_id, "
+ "b.a_id AS b_a_id, c.id AS c_id, "
+ "c.b_id AS c_b_id, d.id AS d_id, "
+ "d.c_id AS d_c_id "
+ "FROM a JOIN (b JOIN (c JOIN d ON c.id = d.c_id) "
+ "ON b.id = c.b_id) ON a.id = b.a_id "
+ "WHERE b.id = :id_1 AND c.id = :id_2 AND "
+ "d.id = :id_3 "
+ "ORDER BY a.id, b.id, c.id, d.id"
+ )
_a_bc = (
- "SELECT a.id AS a_id, b.id AS b_id, "
- "b.a_id AS b_a_id, c.id AS c_id, "
- "c.b_id AS c_b_id FROM a JOIN "
- "(b JOIN c ON b.id = c.b_id) "
- "ON a.id = b.a_id "
- "WHERE b.id = :id_1 AND c.id = :id_2 "
- "ORDER BY a.id, b.id, c.id"
- )
+ "SELECT a.id AS a_id, b.id AS b_id, "
+ "b.a_id AS b_a_id, c.id AS c_id, "
+ "c.b_id AS c_b_id FROM a JOIN "
+ "(b JOIN c ON b.id = c.b_id) "
+ "ON a.id = b.a_id "
+ "WHERE b.id = :id_1 AND c.id = :id_2 "
+ "ORDER BY a.id, b.id, c.id"
+ )
_a_bc_comma_a1_selbc = (
- "SELECT a.id AS a_id, a_1.id AS a_1_id, b.id AS b_id, "
- "b.a_id AS b_a_id, c.id AS c_id, "
- "c.b_id AS c_b_id, anon_1.b_id AS anon_1_b_id, "
- "anon_1.b_a_id AS anon_1_b_a_id, anon_1.c_id AS anon_1_c_id, "
- "anon_1.c_b_id AS anon_1_c_b_id FROM a "
- "JOIN (b JOIN c ON b.id = c.b_id) "
- "ON a.id = b.a_id, "
- "a AS a_1 JOIN "
- "(SELECT b.id AS b_id, b.a_id AS b_a_id, "
- "c.id AS c_id, c.b_id AS c_b_id "
- "FROM b JOIN c ON b.id = c.b_id) AS anon_1 "
- "ON a_1.id = anon_1.b_a_id ORDER BY anon_1.b_id"
- )
+ "SELECT a.id AS a_id, a_1.id AS a_1_id, b.id AS b_id, "
+ "b.a_id AS b_a_id, c.id AS c_id, "
+ "c.b_id AS c_b_id, anon_1.b_id AS anon_1_b_id, "
+ "anon_1.b_a_id AS anon_1_b_a_id, anon_1.c_id AS anon_1_c_id, "
+ "anon_1.c_b_id AS anon_1_c_b_id FROM a "
+ "JOIN (b JOIN c ON b.id = c.b_id) "
+ "ON a.id = b.a_id, "
+ "a AS a_1 JOIN "
+ "(SELECT b.id AS b_id, b.a_id AS b_a_id, "
+ "c.id AS c_id, c.b_id AS c_b_id "
+ "FROM b JOIN c ON b.id = c.b_id) AS anon_1 "
+ "ON a_1.id = anon_1.b_a_id ORDER BY anon_1.b_id"
+ )
_a_bkeyassoc = (
"SELECT a.id AS a_id, b_key.id AS b_key_id "
"FROM a JOIN "
"(b_key JOIN a_to_b_key ON b_key.id = a_to_b_key.bid) "
"ON a.id = a_to_b_key.aid"
- )
+ )
_a_bkeyassoc_aliased = (
"SELECT a.id AS a_id, b_key_1.id AS b_key_1_id FROM a "
_a_atobalias_balias_c_w_exists = (
"SELECT a.id AS a_id, a_to_b_1.a_id AS a_to_b_1_a_id, "
- "a_to_b_1.b_id AS a_to_b_1_b_id, b_1.id AS b_1_id, b_1.a_id AS b_1_a_id, "
+ "a_to_b_1.b_id AS a_to_b_1_b_id, b_1.id AS b_1_id, "
+ "b_1.a_id AS b_1_a_id, "
"EXISTS (SELECT * FROM c WHERE c.b_id = b_1.id) AS anon_1 "
"FROM a LEFT OUTER JOIN "
"(a_to_b AS a_to_b_1 JOIN b AS b_1 ON b_1.id = a_to_b_1.b_id) "
- "ON a.id = a_to_b_1.a_id"
- )
+ "ON a.id = a_to_b_1.a_id")
_a_atobalias_balias = (
"SELECT a.id AS a_id, a_to_b_1.a_id AS a_to_b_1_a_id, "
_b_ab1_union_c_ab2 = (
"SELECT b_id AS b_id, b_a_id AS b_a_id, a_id AS a_id, b1_id AS b1_id, "
"b1_a_id AS b1_a_id FROM "
- "(SELECT b.id AS b_id, b.a_id AS b_a_id, a.id AS a_id, b1.id AS b1_id, "
+ "(SELECT b.id AS b_id, b.a_id AS b_a_id, a.id AS a_id, "
+ "b1.id AS b1_id, "
"b1.a_id AS b1_a_id FROM b "
"JOIN (a JOIN b1 ON a.id = b1.a_id) ON a.id = b.a_id "
"UNION "
"SELECT b.id AS b_id, b.a_id AS b_a_id, a.id AS a_id, b2.id AS b2_id, "
"b2.a_id AS b2_a_id FROM b "
- "JOIN (a JOIN b2 ON a.id = b2.a_id) ON a.id = b.a_id)"
- )
+ "JOIN (a JOIN b2 ON a.id = b2.a_id) ON a.id = b.a_id)")
_b_a_id_double_overlap_annotated = (
"SELECT anon_1.b_id AS anon_1_b_id, anon_1.b_a_id AS anon_1_b_a_id, "
"FROM a JOIN b2 ON a.id = b2.a_id)"
)
+
class JoinNoUseLabelsTest(_JoinRewriteTestBase, fixtures.TestBase):
+
@util.classproperty
def __dialect__(cls):
dialect = default.DefaultDialect()
_a_bkeyselect_bkey = (
"SELECT a.id, b_key.id FROM a JOIN ((SELECT a_to_b_key.aid AS aid, "
- "a_to_b_key.bid AS bid FROM a_to_b_key) AS anon_1 "
- "JOIN b_key ON b_key.id = anon_1.bid) ON a.id = anon_1.aid"
+ "a_to_b_key.bid AS bid FROM a_to_b_key) AS anon_1 "
+ "JOIN b_key ON b_key.id = anon_1.bid) ON a.id = anon_1.aid"
)
_a__b_dc = (
- "SELECT a.id, b.id, "
- "b.a_id, c.id, "
- "c.b_id, d.id, "
- "d.c_id "
- "FROM a JOIN (b JOIN (c JOIN d ON c.id = d.c_id) "
- "ON b.id = c.b_id) ON a.id = b.a_id "
- "WHERE b.id = :id_1 AND c.id = :id_2 AND "
- "d.id = :id_3 "
- "ORDER BY a.id, b.id, c.id, d.id"
- )
+ "SELECT a.id, b.id, "
+ "b.a_id, c.id, "
+ "c.b_id, d.id, "
+ "d.c_id "
+ "FROM a JOIN (b JOIN (c JOIN d ON c.id = d.c_id) "
+ "ON b.id = c.b_id) ON a.id = b.a_id "
+ "WHERE b.id = :id_1 AND c.id = :id_2 AND "
+ "d.id = :id_3 "
+ "ORDER BY a.id, b.id, c.id, d.id"
+ )
_a_bc = (
- "SELECT a.id, b.id, "
- "b.a_id, c.id, "
- "c.b_id FROM a JOIN "
- "(b JOIN c ON b.id = c.b_id) "
- "ON a.id = b.a_id "
- "WHERE b.id = :id_1 AND c.id = :id_2 "
- "ORDER BY a.id, b.id, c.id"
- )
+ "SELECT a.id, b.id, "
+ "b.a_id, c.id, "
+ "c.b_id FROM a JOIN "
+ "(b JOIN c ON b.id = c.b_id) "
+ "ON a.id = b.a_id "
+ "WHERE b.id = :id_1 AND c.id = :id_2 "
+ "ORDER BY a.id, b.id, c.id"
+ )
_a_bc_comma_a1_selbc = (
- "SELECT a.id, a_1.id, b.id, "
- "b.a_id, c.id, "
- "c.b_id, anon_1.b_id, "
- "anon_1.b_a_id, anon_1.c_id, "
- "anon_1.c_b_id FROM a "
- "JOIN (b JOIN c ON b.id = c.b_id) "
- "ON a.id = b.a_id, "
- "a AS a_1 JOIN "
- "(SELECT b.id AS b_id, b.a_id AS b_a_id, "
- "c.id AS c_id, c.b_id AS c_b_id "
- "FROM b JOIN c ON b.id = c.b_id) AS anon_1 "
- "ON a_1.id = anon_1.b_a_id ORDER BY anon_1.b_id"
- )
+ "SELECT a.id, a_1.id, b.id, "
+ "b.a_id, c.id, "
+ "c.b_id, anon_1.b_id, "
+ "anon_1.b_a_id, anon_1.c_id, "
+ "anon_1.c_b_id FROM a "
+ "JOIN (b JOIN c ON b.id = c.b_id) "
+ "ON a.id = b.a_id, "
+ "a AS a_1 JOIN "
+ "(SELECT b.id AS b_id, b.a_id AS b_a_id, "
+ "c.id AS c_id, c.b_id AS c_b_id "
+ "FROM b JOIN c ON b.id = c.b_id) AS anon_1 "
+ "ON a_1.id = anon_1.b_a_id ORDER BY anon_1.b_id"
+ )
_a_bkeyassoc = (
"SELECT a.id, b_key.id FROM a JOIN (b_key JOIN a_to_b_key "
"ON b_key.id = a_to_b_key.bid) ON a.id = a_to_b_key.aid"
- )
+ )
_a_bkeyassoc_aliased = (
"SELECT a.id, b_key_1.id FROM a JOIN (b_key AS b_key_1 "
"FROM a JOIN b2 ON a.id = b2.a_id)"
)
+
class JoinExecTest(_JoinRewriteTestBase, fixtures.TestBase):
+
"""invoke the SQL on the current backend to ensure compatibility"""
__backend__ = True
def test_a_atobalias_balias_c_w_exists(self):
super(JoinExecTest, self).test_a_atobalias_balias_c_w_exists()
- @testing.only_on("sqlite", "non-standard aliasing rules used at the moment, "
- "possibly fix this or add another test that uses "
- "cross-compatible aliasing")
+ @testing.only_on(
+ "sqlite",
+ "non-standard aliasing rules used at the moment, "
+ "possibly fix this or add another test that uses "
+ "cross-compatible aliasing")
def test_b_ab1_union_b_ab2(self):
super(JoinExecTest, self).test_b_ab1_union_b_ab2()
+
class DialectFlagTest(fixtures.TestBase, AssertsCompiledSQL):
+
def test_dialect_flag(self):
d1 = default.DefaultDialect(supports_right_nested_joins=True)
d2 = default.DefaultDialect(supports_right_nested_joins=False)
self.assert_compile(
s,
- "SELECT a.id AS a_id, b.id AS b_id, b.a_id AS b_a_id, c.id AS c_id, "
+ "SELECT a.id AS a_id, b.id AS b_id, b.a_id AS b_a_id, "
+ "c.id AS c_id, "
"c.b_id AS c_b_id FROM a JOIN (b JOIN c ON b.id = c.b_id) "
"ON a.id = b.a_id",
- dialect=d1
- )
+ dialect=d1)
self.assert_compile(
- s,
- "SELECT a.id AS a_id, anon_1.b_id AS b_id, "
+ s, "SELECT a.id AS a_id, anon_1.b_id AS b_id, "
"anon_1.b_a_id AS b_a_id, "
"anon_1.c_id AS c_id, anon_1.c_b_id AS c_b_id "
- "FROM a JOIN (SELECT b.id AS b_id, b.a_id AS b_a_id, c.id AS c_id, "
+ "FROM a JOIN (SELECT b.id AS b_id, b.a_id AS b_a_id, "
+ "c.id AS c_id, "
"c.b_id AS c_b_id FROM b JOIN c ON b.id = c.b_id) AS anon_1 "
- "ON a.id = anon_1.b_a_id",
- dialect=d2
- )
+ "ON a.id = anon_1.b_a_id", dialect=d2)
__dialect__ = 'DefaultDialect'
table1 = table('some_large_named_table',
- column('this_is_the_primarykey_column'),
- column('this_is_the_data_column')
- )
+ column('this_is_the_primarykey_column'),
+ column('this_is_the_data_column')
+ )
table2 = table('table_with_exactly_29_characs',
- column('this_is_the_primarykey_column'),
- column('this_is_the_data_column')
- )
+ column('this_is_the_primarykey_column'),
+ column('this_is_the_data_column')
+ )
def _length_fixture(self, length=IDENT_LENGTH, positional=False):
dialect = default.DefaultDialect()
self.assert_compile(
self.table2.alias().select(),
'SELECT '
- 'table_with_exactly_29_c_1.'
- 'this_is_the_primarykey_column, '
- 'table_with_exactly_29_c_1.this_is_the_data_column '
+ 'table_with_exactly_29_c_1.'
+ 'this_is_the_primarykey_column, '
+ 'table_with_exactly_29_c_1.this_is_the_data_column '
'FROM '
- 'table_with_exactly_29_characs '
+ 'table_with_exactly_29_characs '
'AS table_with_exactly_29_c_1',
dialect=self._length_fixture()
)
on = table1.c.this_is_the_data_column == ta.c.this_is_the_data_column
self.assert_compile(
select([table1, ta]).select_from(table1.join(ta, on)).
- where(ta.c.this_is_the_data_column == 'data3'),
+ where(ta.c.this_is_the_data_column == 'data3'),
'SELECT '
- 'some_large_named_table.this_is_the_primarykey_column, '
- 'some_large_named_table.this_is_the_data_column, '
- 'table_with_exactly_29_c_1.this_is_the_primarykey_column, '
- 'table_with_exactly_29_c_1.this_is_the_data_column '
+ 'some_large_named_table.this_is_the_primarykey_column, '
+ 'some_large_named_table.this_is_the_data_column, '
+ 'table_with_exactly_29_c_1.this_is_the_primarykey_column, '
+ 'table_with_exactly_29_c_1.this_is_the_data_column '
'FROM '
- 'some_large_named_table '
+ 'some_large_named_table '
'JOIN '
- 'table_with_exactly_29_characs '
+ 'table_with_exactly_29_characs '
'AS '
- 'table_with_exactly_29_c_1 '
+ 'table_with_exactly_29_c_1 '
'ON '
- 'some_large_named_table.this_is_the_data_column = '
- 'table_with_exactly_29_c_1.this_is_the_data_column '
+ 'some_large_named_table.this_is_the_data_column = '
+ 'table_with_exactly_29_c_1.this_is_the_data_column '
'WHERE '
- 'table_with_exactly_29_c_1.this_is_the_data_column = '
- ':this_is_the_data_column_1',
+ 'table_with_exactly_29_c_1.this_is_the_data_column = '
+ ':this_is_the_data_column_1',
dialect=self._length_fixture()
)
def test_too_long_name_disallowed(self):
m = MetaData()
t = Table('this_name_is_too_long_for_what_were_doing_in_this_test',
- m, Column('foo', Integer))
+ m, Column('foo', Integer))
eng = self._engine_fixture()
methods = (t.create, t.drop, m.create_all, m.drop_all)
for meth in methods:
compiled = s.compile(dialect=self._length_fixture())
assert set(compiled.result_map['some_large_named_table__2'][1]).\
- issuperset(
- [
- 'some_large_named_table_this_is_the_data_column',
- 'some_large_named_table__2',
- table1.c.this_is_the_data_column
- ]
- )
+ issuperset(
+ [
+ 'some_large_named_table_this_is_the_data_column',
+ 'some_large_named_table__2',
+ table1.c.this_is_the_data_column
+ ]
+ )
assert set(compiled.result_map['some_large_named_table__1'][1]).\
- issuperset(
- [
- 'some_large_named_table_this_is_the_primarykey_column',
- 'some_large_named_table__1',
- table1.c.this_is_the_primarykey_column
- ]
- )
+ issuperset(
+ [
+ 'some_large_named_table_this_is_the_primarykey_column',
+ 'some_large_named_table__1',
+ table1.c.this_is_the_primarykey_column
+ ]
+ )
def test_result_map_use_labels(self):
table1 = self.table1
s = table1.select().apply_labels().\
- order_by(table1.c.this_is_the_primarykey_column)
+ order_by(table1.c.this_is_the_primarykey_column)
self._assert_labeled_table1_select(s)
# generated result map corresponds to the selected table, not the
# select query
s = table1.select(use_labels=True,
- order_by=[table1.c.this_is_the_primarykey_column]).\
- limit(2)
+ order_by=[table1.c.this_is_the_primarykey_column]).\
+ limit(2)
self._assert_labeled_table1_select(s)
def test_result_map_subquery(self):
table1 = self.table1
s = table1.select(
- table1.c.this_is_the_primarykey_column == 4).\
- alias('foo')
+ table1.c.this_is_the_primarykey_column == 4).\
+ alias('foo')
s2 = select([s])
compiled = s2.compile(dialect=self._length_fixture())
assert \
set(compiled.result_map['this_is_the_data_column'][1]).\
issuperset(['this_is_the_data_column',
- s.c.this_is_the_data_column])
+ s.c.this_is_the_data_column])
assert \
set(compiled.result_map['this_is_the_primarykey_column'][1]).\
issuperset(['this_is_the_primarykey_column',
- s.c.this_is_the_primarykey_column])
+ s.c.this_is_the_primarykey_column])
def test_result_map_anon_alias(self):
table1 = self.table1
q = table1.select(table1.c.this_is_the_primarykey_column == 4).alias()
s = select([q]).apply_labels()
- self.assert_compile(s,
- 'SELECT '
- 'anon_1.this_is_the_primarykey_column '
- 'AS anon_1_this_is_the_prim_1, '
- 'anon_1.this_is_the_data_column '
- 'AS anon_1_this_is_the_data_2 '
+ self.assert_compile(
+ s, 'SELECT '
+ 'anon_1.this_is_the_primarykey_column '
+ 'AS anon_1_this_is_the_prim_1, '
+ 'anon_1.this_is_the_data_column '
+ 'AS anon_1_this_is_the_data_2 '
'FROM ('
- 'SELECT '
- 'some_large_named_table.'
- 'this_is_the_primarykey_column '
- 'AS this_is_the_primarykey_column, '
- 'some_large_named_table.this_is_the_data_column '
- 'AS this_is_the_data_column '
- 'FROM '
- 'some_large_named_table '
- 'WHERE '
- 'some_large_named_table.this_is_the_primarykey_column '
- '= :this_is_the_primarykey__1'
- ') '
- 'AS anon_1',
- dialect=dialect)
+ 'SELECT '
+ 'some_large_named_table.'
+ 'this_is_the_primarykey_column '
+ 'AS this_is_the_primarykey_column, '
+ 'some_large_named_table.this_is_the_data_column '
+ 'AS this_is_the_data_column '
+ 'FROM '
+ 'some_large_named_table '
+ 'WHERE '
+ 'some_large_named_table.this_is_the_primarykey_column '
+ '= :this_is_the_primarykey__1'
+ ') '
+ 'AS anon_1', dialect=dialect)
compiled = s.compile(dialect=dialect)
assert set(compiled.result_map['anon_1_this_is_the_data_2'][1]).\
- issuperset([
- 'anon_1_this_is_the_data_2',
- q.corresponding_column(
- table1.c.this_is_the_data_column)
- ])
+ issuperset([
+ 'anon_1_this_is_the_data_2',
+ q.corresponding_column(
+ table1.c.this_is_the_data_column)
+ ])
assert set(compiled.result_map['anon_1_this_is_the_prim_1'][1]).\
- issuperset([
- 'anon_1_this_is_the_prim_1',
- q.corresponding_column(
- table1.c.this_is_the_primarykey_column)
- ])
+ issuperset([
+ 'anon_1_this_is_the_prim_1',
+ q.corresponding_column(
+ table1.c.this_is_the_primarykey_column)
+ ])
def test_column_bind_labels_1(self):
table1 = self.table1
__dialect__ = 'DefaultDialect'
table1 = table('some_large_named_table',
- column('this_is_the_primarykey_column'),
- column('this_is_the_data_column')
- )
+ column('this_is_the_primarykey_column'),
+ column('this_is_the_data_column')
+ )
table2 = table('table_with_exactly_29_characs',
- column('this_is_the_primarykey_column'),
- column('this_is_the_data_column')
- )
+ column('this_is_the_primarykey_column'),
+ column('this_is_the_data_column')
+ )
def test_adjustable_1(self):
table1 = self.table1
table1.c.this_is_the_primarykey_column == 4).alias('foo')
x = select([q])
compile_dialect = default.DefaultDialect(label_length=10)
- self.assert_compile(x,
- 'SELECT '
- 'foo.this_1, foo.this_2 '
+ self.assert_compile(
+ x, 'SELECT '
+ 'foo.this_1, foo.this_2 '
'FROM ('
- 'SELECT '
- 'some_large_named_table.this_is_the_primarykey_column '
- 'AS this_1, '
- 'some_large_named_table.this_is_the_data_column '
- 'AS this_2 '
- 'FROM '
- 'some_large_named_table '
- 'WHERE '
- 'some_large_named_table.this_is_the_primarykey_column '
- '= :this_1'
- ') '
- 'AS foo',
- dialect=compile_dialect)
+ 'SELECT '
+ 'some_large_named_table.this_is_the_primarykey_column '
+ 'AS this_1, '
+ 'some_large_named_table.this_is_the_data_column '
+ 'AS this_2 '
+ 'FROM '
+ 'some_large_named_table '
+ 'WHERE '
+ 'some_large_named_table.this_is_the_primarykey_column '
+ '= :this_1'
+ ') '
+ 'AS foo', dialect=compile_dialect)
def test_adjustable_2(self):
table1 = self.table1
x = select([q])
compile_dialect = default.DefaultDialect(label_length=10)
- self.assert_compile(x,
- 'SELECT '
- 'foo.this_1, foo.this_2 '
+ self.assert_compile(
+ x, 'SELECT '
+ 'foo.this_1, foo.this_2 '
'FROM ('
- 'SELECT '
- 'some_large_named_table.this_is_the_primarykey_column '
- 'AS this_1, '
- 'some_large_named_table.this_is_the_data_column '
- 'AS this_2 '
- 'FROM '
- 'some_large_named_table '
- 'WHERE '
- 'some_large_named_table.this_is_the_primarykey_column '
- '= :this_1'
- ') '
- 'AS foo',
- dialect=compile_dialect)
+ 'SELECT '
+ 'some_large_named_table.this_is_the_primarykey_column '
+ 'AS this_1, '
+ 'some_large_named_table.this_is_the_data_column '
+ 'AS this_2 '
+ 'FROM '
+ 'some_large_named_table '
+ 'WHERE '
+ 'some_large_named_table.this_is_the_primarykey_column '
+ '= :this_1'
+ ') '
+ 'AS foo', dialect=compile_dialect)
def test_adjustable_3(self):
table1 = self.table1
table1.c.this_is_the_primarykey_column == 4).alias('foo')
x = select([q])
- self.assert_compile(x,
- 'SELECT '
- 'foo._1, foo._2 '
+ self.assert_compile(
+ x, 'SELECT '
+ 'foo._1, foo._2 '
'FROM ('
- 'SELECT '
- 'some_large_named_table.this_is_the_primarykey_column '
- 'AS _1, '
- 'some_large_named_table.this_is_the_data_column '
- 'AS _2 '
- 'FROM '
- 'some_large_named_table '
- 'WHERE '
- 'some_large_named_table.this_is_the_primarykey_column '
- '= :_1'
- ') '
- 'AS foo',
- dialect=compile_dialect)
+ 'SELECT '
+ 'some_large_named_table.this_is_the_primarykey_column '
+ 'AS _1, '
+ 'some_large_named_table.this_is_the_data_column '
+ 'AS _2 '
+ 'FROM '
+ 'some_large_named_table '
+ 'WHERE '
+ 'some_large_named_table.this_is_the_primarykey_column '
+ '= :_1'
+ ') '
+ 'AS foo', dialect=compile_dialect)
def test_adjustable_4(self):
table1 = self.table1
x = select([q], use_labels=True)
compile_dialect = default.DefaultDialect(label_length=10)
- self.assert_compile(x,
- 'SELECT '
- 'anon_1.this_2 AS anon_1, '
- 'anon_1.this_4 AS anon_3 '
+ self.assert_compile(
+ x, 'SELECT '
+ 'anon_1.this_2 AS anon_1, '
+ 'anon_1.this_4 AS anon_3 '
'FROM ('
- 'SELECT '
- 'some_large_named_table.this_is_the_primarykey_column '
- 'AS this_2, '
- 'some_large_named_table.this_is_the_data_column '
- 'AS this_4 '
- 'FROM '
- 'some_large_named_table '
- 'WHERE '
- 'some_large_named_table.this_is_the_primarykey_column '
- '= :this_1'
- ') '
- 'AS anon_1',
- dialect=compile_dialect)
+ 'SELECT '
+ 'some_large_named_table.this_is_the_primarykey_column '
+ 'AS this_2, '
+ 'some_large_named_table.this_is_the_data_column '
+ 'AS this_4 '
+ 'FROM '
+ 'some_large_named_table '
+ 'WHERE '
+ 'some_large_named_table.this_is_the_primarykey_column '
+ '= :this_1'
+ ') '
+ 'AS anon_1', dialect=compile_dialect)
def test_adjustable_5(self):
table1 = self.table1
x = select([q], use_labels=True)
compile_dialect = default.DefaultDialect(label_length=4)
- self.assert_compile(x,
- 'SELECT '
- '_1._2 AS _1, '
- '_1._4 AS _3 '
+ self.assert_compile(
+ x, 'SELECT '
+ '_1._2 AS _1, '
+ '_1._4 AS _3 '
'FROM ('
- 'SELECT '
- 'some_large_named_table.this_is_the_primarykey_column '
- 'AS _2, '
- 'some_large_named_table.this_is_the_data_column '
- 'AS _4 '
- 'FROM '
- 'some_large_named_table '
- 'WHERE '
- 'some_large_named_table.this_is_the_primarykey_column '
- '= :_1'
- ') '
- 'AS _1',
- dialect=compile_dialect)
+ 'SELECT '
+ 'some_large_named_table.this_is_the_primarykey_column '
+ 'AS _2, '
+ 'some_large_named_table.this_is_the_data_column '
+ 'AS _4 '
+ 'FROM '
+ 'some_large_named_table '
+ 'WHERE '
+ 'some_large_named_table.this_is_the_primarykey_column '
+ '= :_1'
+ ') '
+ 'AS _1', dialect=compile_dialect)
def test_adjustable_result_schema_column_1(self):
table1 = self.table1
q = table1.select(
table1.c.this_is_the_primarykey_column == 4).apply_labels().\
- alias('foo')
+ alias('foo')
dialect = default.DefaultDialect(label_length=10)
compiled = q.compile(dialect=dialect)
anon = a_table.alias()
- j1 = other_table.outerjoin(anon,
- anon.c.id == other_table.c.thirty_characters_table_id)
+ j1 = other_table.outerjoin(
+ anon,
+ anon.c.id == other_table.c.thirty_characters_table_id)
self.assert_compile(
select([other_table, anon]).
- select_from(j1).apply_labels(),
+ select_from(j1).apply_labels(),
'SELECT '
- 'other_thirty_characters_table_.id '
- 'AS other_thirty_characters__1, '
- 'other_thirty_characters_table_.thirty_characters_table_id '
- 'AS other_thirty_characters__2, '
- 'thirty_characters_table__1.id '
- 'AS thirty_characters_table__3 '
+ 'other_thirty_characters_table_.id '
+ 'AS other_thirty_characters__1, '
+ 'other_thirty_characters_table_.thirty_characters_table_id '
+ 'AS other_thirty_characters__2, '
+ 'thirty_characters_table__1.id '
+ 'AS thirty_characters_table__3 '
'FROM '
- 'other_thirty_characters_table_ '
+ 'other_thirty_characters_table_ '
'LEFT OUTER JOIN '
- 'thirty_characters_table_xxxxxx AS thirty_characters_table__1 '
+ 'thirty_characters_table_xxxxxx AS thirty_characters_table__1 '
'ON thirty_characters_table__1.id = '
- 'other_thirty_characters_table_.thirty_characters_table_id',
+ 'other_thirty_characters_table_.thirty_characters_table_id',
dialect=compile_dialect)
def test_colnames_longer_than_labels_lowercase(self):
# needs to have all characters
s = select([a1])
self.assert_compile(select([a1]),
- 'SELECT asdf.abcde FROM a AS asdf',
- dialect=dialect)
+ 'SELECT asdf.abcde FROM a AS asdf',
+ dialect=dialect)
compiled = s.compile(dialect=dialect)
assert set(compiled.result_map['abcde'][1]).issuperset([
'abcde', a1.c.abcde, 'abcde'])
# column still there, but short label
s = select([a1]).apply_labels()
self.assert_compile(s,
- 'SELECT asdf.abcde AS _1 FROM a AS asdf',
- dialect=dialect)
+ 'SELECT asdf.abcde AS _1 FROM a AS asdf',
+ dialect=dialect)
compiled = s.compile(dialect=dialect)
assert set(compiled.result_map['_1'][1]).issuperset([
'asdf_abcde', a1.c.abcde, '_1'])
from sqlalchemy.testing import eq_, is_, mock
from contextlib import contextmanager
+
class MetaDataTest(fixtures.TestBase, ComparesTables):
+
def test_metadata_connect(self):
metadata = MetaData()
t1 = Table('table1', metadata,
- Column('col1', Integer, primary_key=True),
- Column('col2', String(20)))
+ Column('col1', Integer, primary_key=True),
+ Column('col2', String(20)))
metadata.bind = testing.db
metadata.create_all()
try:
Column('baz', String(), unique=True),
Column(Integer(), primary_key=True),
Column('bar', Integer(), Sequence('foo_seq'), primary_key=True,
- key='bar'),
+ key='bar'),
Column(Integer(), ForeignKey('bat.blah'), doc="this is a col"),
Column('bar', Integer(), ForeignKey('bat.blah'), primary_key=True,
- key='bar'),
+ key='bar'),
Column('bar', Integer(), info={'foo': 'bar'}),
]:
c2 = col.copy()
for attr in ('name', 'type', 'nullable',
- 'primary_key', 'key', 'unique', 'info',
- 'doc'):
+ 'primary_key', 'key', 'unique', 'info',
+ 'doc'):
eq_(getattr(col, attr), getattr(c2, attr))
eq_(len(col.foreign_keys), len(c2.foreign_keys))
if col.default:
def test_col_subclass_copy(self):
class MyColumn(schema.Column):
+
def __init__(self, *args, **kw):
self.widget = kw.pop('widget', None)
super(MyColumn, self).__init__(*args, **kw)
def test_uninitialized_column_copy_events(self):
msgs = []
+
def write(c, t):
msgs.append("attach %s.%s" % (t.name, c.name))
c1 = Column('foo', String())
def test_dupe_tables(self):
metadata = self.metadata
Table('table1', metadata,
- Column('col1', Integer, primary_key=True),
- Column('col2', String(20)))
+ Column('col1', Integer, primary_key=True),
+ Column('col2', String(20)))
metadata.create_all()
Table('table1', metadata, autoload=True)
+
def go():
Table('table1', metadata,
- Column('col1', Integer, primary_key=True),
- Column('col2', String(20)))
+ Column('col1', Integer, primary_key=True),
+ Column('col2', String(20)))
assert_raises_message(
tsa.exc.InvalidRequestError,
- "Table 'table1' is already defined for this "
- "MetaData instance. Specify 'extend_existing=True' "
- "to redefine options and columns on an existing "
- "Table object.",
+ "Table 'table1' is already defined for this "
+ "MetaData instance. Specify 'extend_existing=True' "
+ "to redefine options and columns on an existing "
+ "Table object.",
go
)
t1 = Table('t', m, c1, c2)
kw = dict(onupdate="X",
- ondelete="Y", use_alter=True, name='f1',
- deferrable="Z", initially="Q", link_to_name=True)
+ ondelete="Y", use_alter=True, name='f1',
+ deferrable="Z", initially="Q", link_to_name=True)
fk1 = ForeignKey(c1, **kw)
fk2 = ForeignKeyConstraint((c1,), (c2,), **kw)
def test_fk_given_non_col_clauseelem(self):
class Foo(object):
+
def __clause_element__(self):
return bindparam('x')
assert_raises_message(
def test_fk_given_col_non_table_clauseelem(self):
t = Table('t', MetaData(), Column('x', Integer))
+
class Foo(object):
+
def __clause_element__(self):
return t.alias().c.x
getattr, list(a.foreign_keys)[0], "column"
)
-
-
def test_pickle_metadata_sequence_restated(self):
m1 = MetaData()
Table('a', m1,
- Column('id', Integer, primary_key=True),
- Column('x', Integer, Sequence("x_seq")))
+ Column('id', Integer, primary_key=True),
+ Column('x', Integer, Sequence("x_seq")))
m2 = pickle.loads(pickle.dumps(m1))
s2 = Sequence("x_seq")
t2 = Table('a', m2,
- Column('id', Integer, primary_key=True),
- Column('x', Integer, s2),
- extend_existing=True)
+ Column('id', Integer, primary_key=True),
+ Column('x', Integer, s2),
+ extend_existing=True)
assert m2._sequences['x_seq'] is t2.c.x.default
assert m2._sequences['x_seq'] is s2
-
def test_sequence_restated_replaced(self):
"""Test restatement of Sequence replaces."""
m1 = MetaData()
s1 = Sequence("x_seq")
t = Table('a', m1,
- Column('x', Integer, s1)
- )
+ Column('x', Integer, s1)
+ )
assert m1._sequences['x_seq'] is s1
s2 = Sequence('x_seq')
Table('a', m1,
- Column('x', Integer, s2),
- extend_existing=True
- )
+ Column('x', Integer, s2),
+ extend_existing=True
+ )
assert t.c.x.default is s2
assert m1._sequences['x_seq'] is s2
-
def test_pickle_metadata_sequence_implicit(self):
m1 = MetaData()
Table('a', m1,
- Column('id', Integer, primary_key=True),
- Column('x', Integer, Sequence("x_seq")))
+ Column('id', Integer, primary_key=True),
+ Column('x', Integer, Sequence("x_seq")))
m2 = pickle.loads(pickle.dumps(m1))
def test_pickle_metadata_schema(self):
m1 = MetaData()
Table('a', m1,
- Column('id', Integer, primary_key=True),
- Column('x', Integer, Sequence("x_seq")),
- schema='y')
+ Column('id', Integer, primary_key=True),
+ Column('x', Integer, Sequence("x_seq")),
+ schema='y')
m2 = pickle.loads(pickle.dumps(m1))
Table('a', m2, schema='y',
- extend_existing=True)
+ extend_existing=True)
eq_(m2._schemas, m1._schemas)
m4 = MetaData()
for i, (name, metadata, schema, quote_schema,
- exp_schema, exp_quote_schema) in enumerate([
- ('t1', m1, None, None, 'sch1', None),
- ('t2', m1, 'sch2', None, 'sch2', None),
- ('t3', m1, 'sch2', True, 'sch2', True),
- ('t4', m1, 'sch1', None, 'sch1', None),
- ('t1', m2, None, None, 'sch1', True),
- ('t2', m2, 'sch2', None, 'sch2', None),
- ('t3', m2, 'sch2', True, 'sch2', True),
- ('t4', m2, 'sch1', None, 'sch1', None),
- ('t1', m3, None, None, 'sch1', False),
- ('t2', m3, 'sch2', None, 'sch2', None),
- ('t3', m3, 'sch2', True, 'sch2', True),
- ('t4', m3, 'sch1', None, 'sch1', None),
- ('t1', m4, None, None, None, None),
- ('t2', m4, 'sch2', None, 'sch2', None),
- ('t3', m4, 'sch2', True, 'sch2', True),
- ('t4', m4, 'sch1', None, 'sch1', None),
- ]):
+ exp_schema, exp_quote_schema) in enumerate([
+ ('t1', m1, None, None, 'sch1', None),
+ ('t2', m1, 'sch2', None, 'sch2', None),
+ ('t3', m1, 'sch2', True, 'sch2', True),
+ ('t4', m1, 'sch1', None, 'sch1', None),
+ ('t1', m2, None, None, 'sch1', True),
+ ('t2', m2, 'sch2', None, 'sch2', None),
+ ('t3', m2, 'sch2', True, 'sch2', True),
+ ('t4', m2, 'sch1', None, 'sch1', None),
+ ('t1', m3, None, None, 'sch1', False),
+ ('t2', m3, 'sch2', None, 'sch2', None),
+ ('t3', m3, 'sch2', True, 'sch2', True),
+ ('t4', m3, 'sch1', None, 'sch1', None),
+ ('t1', m4, None, None, None, None),
+ ('t2', m4, 'sch2', None, 'sch2', None),
+ ('t3', m4, 'sch2', True, 'sch2', True),
+ ('t4', m4, 'sch1', None, 'sch1', None),
+ ]):
kw = {}
if schema is not None:
kw['schema'] = schema
t = Table(name, metadata, **kw)
eq_(t.schema, exp_schema, "test %d, table schema" % i)
eq_(t.schema.quote if t.schema is not None else None,
- exp_quote_schema,
- "test %d, table quote_schema" % i)
+ exp_quote_schema,
+ "test %d, table quote_schema" % i)
seq = Sequence(name, metadata=metadata, **kw)
eq_(seq.schema, exp_schema, "test %d, seq schema" % i)
eq_(seq.schema.quote if seq.schema is not None else None,
- exp_quote_schema,
- "test %d, seq quote_schema" % i)
+ exp_quote_schema,
+ "test %d, seq quote_schema" % i)
def test_manual_dependencies(self):
meta = MetaData()
def test_nonexistent(self):
assert_raises(tsa.exc.NoSuchTableError, Table,
- 'fake_table',
- MetaData(testing.db), autoload=True)
+ 'fake_table',
+ MetaData(testing.db), autoload=True)
def test_assorted_repr(self):
t1 = Table("foo", MetaData(), Column("x", Integer))
(i1, "Index('bar', Column('x', Integer(), table=<foo>))"),
(schema.FetchedValue(), "FetchedValue()"),
(ck,
- "CheckConstraint("
- "%s"
- ", name='someconstraint')" % repr(ck.sqltext)),
+ "CheckConstraint("
+ "%s"
+ ", name='someconstraint')" % repr(ck.sqltext)),
):
eq_(
repr(const),
from sqlalchemy.testing.schema import Table
meta = MetaData()
- table = Table('mytable', meta,
- Column('myid', Integer, Sequence('foo_id_seq'), primary_key=True),
- Column('name', String(40), nullable=True),
- Column('foo', String(40), nullable=False, server_default='x',
- server_onupdate='q'),
- Column('bar', String(40), nullable=False, default='y',
- onupdate='z'),
- Column('description', String(30),
- CheckConstraint("description='hi'")),
+ table = Table(
+ 'mytable',
+ meta,
+ Column(
+ 'myid',
+ Integer,
+ Sequence('foo_id_seq'),
+ primary_key=True),
+ Column(
+ 'name',
+ String(40),
+ nullable=True),
+ Column(
+ 'foo',
+ String(40),
+ nullable=False,
+ server_default='x',
+ server_onupdate='q'),
+ Column(
+ 'bar',
+ String(40),
+ nullable=False,
+ default='y',
+ onupdate='z'),
+ Column(
+ 'description',
+ String(30),
+ CheckConstraint("description='hi'")),
UniqueConstraint('name'),
- test_needs_fk=True
- )
-
- table2 = Table('othertable', meta,
- Column('id', Integer, Sequence('foo_seq'), primary_key=True),
- Column('myid', Integer,
- ForeignKey('mytable.myid'),
- ),
- test_needs_fk=True
- )
+ test_needs_fk=True)
+
+ table2 = Table(
+ 'othertable',
+ meta,
+ Column(
+ 'id',
+ Integer,
+ Sequence('foo_seq'),
+ primary_key=True),
+ Column(
+ 'myid',
+ Integer,
+ ForeignKey('mytable.myid'),
+ ),
+ test_needs_fk=True)
def test_to_metadata():
meta2 = MetaData()
assert c.columns.contains_column(table_c.c.name)
assert not c.columns.contains_column(table.c.name)
-
finally:
meta.drop_all(testing.db)
a2 = a.tometadata(m2)
assert b2.c.y.references(a2.c.x)
-
def test_change_schema(self):
meta = MetaData()
table = Table('mytable', meta,
- Column('myid', Integer, primary_key=True),
- Column('name', String(40), nullable=True),
- Column('description', String(30),
- CheckConstraint("description='hi'")),
- UniqueConstraint('name'),
- )
+ Column('myid', Integer, primary_key=True),
+ Column('name', String(40), nullable=True),
+ Column('description', String(30),
+ CheckConstraint("description='hi'")),
+ UniqueConstraint('name'),
+ )
table2 = Table('othertable', meta,
- Column('id', Integer, primary_key=True),
- Column('myid', Integer, ForeignKey('mytable.myid')),
- )
+ Column('id', Integer, primary_key=True),
+ Column('myid', Integer, ForeignKey('mytable.myid')),
+ )
meta2 = MetaData()
table_c = table.tometadata(meta2, schema='someschema')
table2_c = table2.tometadata(meta2, schema='someschema')
eq_(str(table_c.join(table2_c).onclause), str(table_c.c.myid
- == table2_c.c.myid))
+ == table2_c.c.myid))
eq_(str(table_c.join(table2_c).onclause),
'someschema.mytable.myid = someschema.othertable.myid')
meta = MetaData()
table = Table('mytable', meta,
- Column('myid', Integer, primary_key=True),
- Column('name', String(40), nullable=True),
- Column('description', String(30),
- CheckConstraint("description='hi'")),
- UniqueConstraint('name'),
+ Column('myid', Integer, primary_key=True),
+ Column('name', String(40), nullable=True),
+ Column('description', String(30),
+ CheckConstraint("description='hi'")),
+ UniqueConstraint('name'),
+ schema='myschema',
+ )
+
+ table2 = Table(
+ 'othertable',
+ meta,
+ Column(
+ 'id',
+ Integer,
+ primary_key=True),
+ Column(
+ 'myid',
+ Integer,
+ ForeignKey('myschema.mytable.myid')),
schema='myschema',
)
- table2 = Table('othertable', meta,
- Column('id', Integer, primary_key=True),
- Column('myid', Integer, ForeignKey('myschema.mytable.myid')),
- schema='myschema',
- )
-
meta2 = MetaData()
table_c = table.tometadata(meta2)
table2_c = table2.tometadata(meta2)
eq_(str(table_c.join(table2_c).onclause), str(table_c.c.myid
- == table2_c.c.myid))
+ == table2_c.c.myid))
eq_(str(table_c.join(table2_c).onclause),
'myschema.mytable.myid = myschema.othertable.myid')
existing_schema = t2.schema
if schema:
t2c = t2.tometadata(m2, schema=schema,
- referred_schema_fn=referred_schema_fn)
+ referred_schema_fn=referred_schema_fn)
eq_(t2c.schema, schema)
else:
t2c = t2.tometadata(m2, referred_schema_fn=referred_schema_fn)
m = MetaData()
t2 = Table('t2', m, Column('y', Integer,
- ForeignKey('q.t1.x')), schema="q")
+ ForeignKey('q.t1.x')), schema="q")
self._assert_fk(t2, None, "q.t1.x")
m = MetaData()
t2 = Table('t2', m, Column('y', Integer,
- ForeignKey('q.t1.x')), schema="q")
+ ForeignKey('q.t1.x')), schema="q")
self._assert_fk(t2, "z", "z.t1.x")
t1 = Table('t1', m, Column('x', Integer), schema='q')
t2 = Table('t2', m, Column('y', Integer,
- ForeignKey(t1.c.x)), schema='q')
+ ForeignKey(t1.c.x)), schema='q')
self._assert_fk(t2, None, "q.t1.x")
-
def test_fk_and_referent_has_same_schema_col_new_schema(self):
m = MetaData()
t1 = Table('t1', m, Column('x', Integer), schema='q')
t2 = Table('t2', m, Column('y', Integer,
- ForeignKey(t1.c.x)), schema='q')
+ ForeignKey(t1.c.x)), schema='q')
self._assert_fk(t2, 'z', "z.t1.x")
def test_fk_and_referent_has_diff_schema_string_retain_schema(self):
m = MetaData()
t2 = Table('t2', m, Column('y', Integer,
- ForeignKey('p.t1.x')), schema="q")
+ ForeignKey('p.t1.x')), schema="q")
self._assert_fk(t2, None, "p.t1.x")
m = MetaData()
t2 = Table('t2', m, Column('y', Integer,
- ForeignKey('p.t1.x')), schema="q")
+ ForeignKey('p.t1.x')), schema="q")
self._assert_fk(t2, "z", "p.t1.x")
t1 = Table('t1', m, Column('x', Integer), schema='p')
t2 = Table('t2', m, Column('y', Integer,
- ForeignKey(t1.c.x)), schema='q')
+ ForeignKey(t1.c.x)), schema='q')
self._assert_fk(t2, None, "p.t1.x")
-
def test_fk_and_referent_has_diff_schema_col_new_schema(self):
m = MetaData()
t1 = Table('t1', m, Column('x', Integer), schema='p')
t2 = Table('t2', m, Column('y', Integer,
- ForeignKey(t1.c.x)), schema='q')
+ ForeignKey(t1.c.x)), schema='q')
self._assert_fk(t2, 'z', "p.t1.x")
def test_fk_custom_system(self):
m = MetaData()
t2 = Table('t2', m, Column('y', Integer,
- ForeignKey('p.t1.x')), schema='q')
+ ForeignKey('p.t1.x')), schema='q')
def ref_fn(table, to_schema, constraint, referred_schema):
assert table is t2
return "h"
self._assert_fk(t2, 'z', "h.t1.x", referred_schema_fn=ref_fn)
-
def test_copy_info(self):
m = MetaData()
fk = ForeignKey('t2.id')
t.info['tinfo'] = True
t.primary_key.info['pkinfo'] = True
fkc = [const for const in t.constraints if
- isinstance(const, ForeignKeyConstraint)][0]
+ isinstance(const, ForeignKeyConstraint)][0]
fkc.info['fkcinfo'] = True
m2 = MetaData()
eq_(t2.primary_key.info, {"pkinfo": True})
fkc2 = [const for const in t2.constraints
- if isinstance(const, ForeignKeyConstraint)][0]
+ if isinstance(const, ForeignKeyConstraint)][0]
eq_(fkc2.info, {"fkcinfo": True})
ck2 = [const for const in
- t2.constraints if isinstance(const, CheckConstraint)][0]
+ t2.constraints if isinstance(const, CheckConstraint)][0]
eq_(ck2.info, {"ckinfo": True})
-
def test_dialect_kwargs(self):
meta = MetaData()
table = Table('mytable', meta,
- Column('myid', Integer, primary_key=True),
- mysql_engine='InnoDB',
- )
+ Column('myid', Integer, primary_key=True),
+ mysql_engine='InnoDB',
+ )
meta2 = MetaData()
table_c = table.tometadata(meta2)
meta = MetaData()
table = Table('mytable', meta,
- Column('id', Integer, primary_key=True),
- Column('data1', Integer, index=True),
- Column('data2', Integer),
- )
+ Column('id', Integer, primary_key=True),
+ Column('data1', Integer, index=True),
+ Column('data2', Integer),
+ )
Index('multi', table.c.data1, table.c.data2),
meta2 = MetaData()
def _get_key(i):
return [i.name, i.unique] + \
- sorted(i.kwargs.items()) + \
- list(i.columns.keys())
+ sorted(i.kwargs.items()) + \
+ list(i.columns.keys())
eq_(
sorted([_get_key(i) for i in table.indexes]),
meta1 = MetaData()
table1 = Table('mytable', meta1,
- Column('myid', Integer, primary_key=True),
- )
+ Column('myid', Integer, primary_key=True),
+ )
meta2 = MetaData()
table2 = Table('mytable', meta2,
- Column('yourid', Integer, primary_key=True),
- )
+ Column('yourid', Integer, primary_key=True),
+ )
table_c = table1.tometadata(meta2)
table_d = table2.tometadata(meta2)
def test_default_schema_metadata(self):
meta = MetaData(schema='myschema')
- table = Table('mytable', meta,
- Column('myid', Integer, primary_key=True),
- Column('name', String(40), nullable=True),
- Column('description', String(30), CheckConstraint("description='hi'")),
+ table = Table(
+ 'mytable',
+ meta,
+ Column(
+ 'myid',
+ Integer,
+ primary_key=True),
+ Column(
+ 'name',
+ String(40),
+ nullable=True),
+ Column(
+ 'description',
+ String(30),
+ CheckConstraint("description='hi'")),
UniqueConstraint('name'),
)
- table2 = Table('othertable', meta,
- Column('id', Integer, primary_key=True),
- Column('myid', Integer, ForeignKey('myschema.mytable.myid')),
- )
+ table2 = Table(
+ 'othertable', meta, Column(
+ 'id', Integer, primary_key=True), Column(
+ 'myid', Integer, ForeignKey('myschema.mytable.myid')), )
meta2 = MetaData(schema='someschema')
table_c = table.tometadata(meta2, schema=None)
table2_c = table2.tometadata(meta2, schema=None)
eq_(str(table_c.join(table2_c).onclause),
- str(table_c.c.myid == table2_c.c.myid))
+ str(table_c.c.myid == table2_c.c.myid))
eq_(str(table_c.join(table2_c).onclause),
- "someschema.mytable.myid = someschema.othertable.myid")
+ "someschema.mytable.myid = someschema.othertable.myid")
def test_strip_schema(self):
meta = MetaData()
table = Table('mytable', meta,
- Column('myid', Integer, primary_key=True),
- Column('name', String(40), nullable=True),
- Column('description', String(30),
- CheckConstraint("description='hi'")),
- UniqueConstraint('name'),
- )
+ Column('myid', Integer, primary_key=True),
+ Column('name', String(40), nullable=True),
+ Column('description', String(30),
+ CheckConstraint("description='hi'")),
+ UniqueConstraint('name'),
+ )
table2 = Table('othertable', meta,
- Column('id', Integer, primary_key=True),
- Column('myid', Integer, ForeignKey('mytable.myid')),
- )
+ Column('id', Integer, primary_key=True),
+ Column('myid', Integer, ForeignKey('mytable.myid')),
+ )
meta2 = MetaData()
table_c = table.tometadata(meta2, schema=None)
table2_c = table2.tometadata(meta2, schema=None)
eq_(str(table_c.join(table2_c).onclause), str(table_c.c.myid
- == table2_c.c.myid))
+ == table2_c.c.myid))
eq_(str(table_c.join(table2_c).onclause),
'mytable.myid = othertable.myid')
+
class TableTest(fixtures.TestBase, AssertsCompiledSQL):
+
@testing.skip_if('mssql', 'different col format')
def test_prefixes(self):
from sqlalchemy import Table
table1 = Table("temporary_table_1", MetaData(),
- Column("col1", Integer),
- prefixes=["TEMPORARY"])
+ Column("col1", Integer),
+ prefixes=["TEMPORARY"])
self.assert_compile(
schema.CreateTable(table1),
)
table2 = Table("temporary_table_2", MetaData(),
- Column("col1", Integer),
- prefixes=["VIRTUAL"])
+ Column("col1", Integer),
+ prefixes=["VIRTUAL"])
self.assert_compile(
schema.CreateTable(table2),
"CREATE VIRTUAL TABLE temporary_table_2 (col1 INTEGER)"
m = MetaData()
t = Table('t', m,
- Column('id', Integer, primary_key=True)
- )
+ Column('id', Integer, primary_key=True)
+ )
is_(t._autoincrement_column, t.c.id)
t = Table('t', m,
- Column('id', Integer, primary_key=True),
- extend_existing=True
- )
+ Column('id', Integer, primary_key=True),
+ extend_existing=True
+ )
is_(t._autoincrement_column, t.c.id)
def test_pk_args_standalone(self):
m = MetaData()
t = Table('t', m,
- Column('x', Integer, primary_key=True),
- PrimaryKeyConstraint(mssql_clustered=True)
- )
+ Column('x', Integer, primary_key=True),
+ PrimaryKeyConstraint(mssql_clustered=True)
+ )
eq_(
list(t.primary_key), [t.c.x]
)
def test_pk_cols_sets_flags(self):
m = MetaData()
t = Table('t', m,
- Column('x', Integer),
- Column('y', Integer),
- Column('z', Integer),
- PrimaryKeyConstraint('x', 'y')
- )
+ Column('x', Integer),
+ Column('y', Integer),
+ Column('z', Integer),
+ PrimaryKeyConstraint('x', 'y')
+ )
eq_(t.c.x.primary_key, True)
eq_(t.c.y.primary_key, True)
eq_(t.c.z.primary_key, False)
assert_raises_message(
exc.SAWarning,
"Table 't' specifies columns 'x' as primary_key=True, "
- "not matching locally specified columns 'q'",
+ "not matching locally specified columns 'q'",
Table, 't', m,
- Column('x', Integer, primary_key=True),
- Column('q', Integer),
- PrimaryKeyConstraint('q')
+ Column('x', Integer, primary_key=True),
+ Column('q', Integer),
+ PrimaryKeyConstraint('q')
)
def test_pk_col_mismatch_two(self):
assert_raises_message(
exc.SAWarning,
"Table 't' specifies columns 'a', 'b', 'c' as primary_key=True, "
- "not matching locally specified columns 'b', 'c'",
+ "not matching locally specified columns 'b', 'c'",
Table, 't', m,
- Column('a', Integer, primary_key=True),
- Column('b', Integer, primary_key=True),
- Column('c', Integer, primary_key=True),
- PrimaryKeyConstraint('b', 'c')
+ Column('a', Integer, primary_key=True),
+ Column('b', Integer, primary_key=True),
+ Column('c', Integer, primary_key=True),
+ PrimaryKeyConstraint('b', 'c')
)
@testing.emits_warning("Table 't'")
def test_pk_col_mismatch_three(self):
m = MetaData()
t = Table('t', m,
- Column('x', Integer, primary_key=True),
- Column('q', Integer),
- PrimaryKeyConstraint('q')
- )
+ Column('x', Integer, primary_key=True),
+ Column('q', Integer),
+ PrimaryKeyConstraint('q')
+ )
eq_(list(t.primary_key), [t.c.q])
@testing.emits_warning("Table 't'")
def test_pk_col_mismatch_four(self):
m = MetaData()
t = Table('t', m,
- Column('a', Integer, primary_key=True),
- Column('b', Integer, primary_key=True),
- Column('c', Integer, primary_key=True),
- PrimaryKeyConstraint('b', 'c')
- )
+ Column('a', Integer, primary_key=True),
+ Column('b', Integer, primary_key=True),
+ Column('c', Integer, primary_key=True),
+ PrimaryKeyConstraint('b', 'c')
+ )
eq_(list(t.primary_key), [t.c.b, t.c.c])
def test_pk_always_flips_nullable(self):
class SchemaTypeTest(fixtures.TestBase):
+
class MyType(sqltypes.SchemaType, sqltypes.TypeEngine):
column = None
table = None
self.evt_targets += (target,)
class MyTypeWImpl(MyType):
+
def _gen_dialect_impl(self, dialect):
return self.adapt(SchemaTypeTest.MyTypeImpl)
def test_ad_hoc_schema_equiv_fk(self):
m = MetaData()
t1 = Table('t1', m, Column('x', Integer), schema="foo")
- t2 = Table('t2', m, Column('x', Integer, ForeignKey('t1.x')), schema="foo")
+ t2 = Table(
+ 't2',
+ m,
+ Column(
+ 'x',
+ Integer,
+ ForeignKey('t1.x')),
+ schema="foo")
assert_raises(
exc.NoReferencedTableError,
lambda: t2.c.x.references(t1.c.x)
m = MetaData(schema="foo")
t1 = Table('t1', m, Column('x', Integer))
t2 = Table('t2', m, Column('x', Integer, ForeignKey('t1.x')),
- schema="bar")
+ schema="bar")
assert t2.c.x.references(t1.c.x)
def test_default_schema_metadata_fk_alt_local_raises(self):
def test_iteration(self):
metadata = MetaData()
- table1 = Table('table1', metadata, Column('col1', Integer,
- primary_key=True), schema='someschema')
- table2 = Table('table2', metadata, Column('col1', Integer,
- primary_key=True), Column('col2', Integer,
- ForeignKey('someschema.table1.col1')),
- schema='someschema')
+ table1 = Table(
+ 'table1',
+ metadata,
+ Column(
+ 'col1',
+ Integer,
+ primary_key=True),
+ schema='someschema')
+ table2 = Table(
+ 'table2',
+ metadata,
+ Column(
+ 'col1',
+ Integer,
+ primary_key=True),
+ Column(
+ 'col2',
+ Integer,
+ ForeignKey('someschema.table1.col1')),
+ schema='someschema')
t1 = str(schema.CreateTable(table1).compile(bind=testing.db))
t2 = str(schema.CreateTable(table2).compile(bind=testing.db))
class UseExistingTest(fixtures.TablesTest):
+
@classmethod
def define_tables(cls, metadata):
Table('users', metadata,
- Column('id', Integer, primary_key=True),
- Column('name', String(30)))
+ Column('id', Integer, primary_key=True),
+ Column('name', String(30)))
def _useexisting_fixture(self):
meta2 = MetaData(testing.db)
def test_exception_no_flags(self):
meta2 = self._useexisting_fixture()
+
def go():
Table('users', meta2, Column('name',
- Unicode), autoload=True)
+ Unicode), autoload=True)
assert_raises_message(
exc.InvalidRequestError,
- "Table 'users' is already defined for this "\
- "MetaData instance.",
+ "Table 'users' is already defined for this "
+ "MetaData instance.",
go
)
-
def test_keep_plus_existing_raises(self):
meta2 = self._useexisting_fixture()
assert_raises(
exc.ArgumentError,
Table, 'users', meta2, keep_existing=True,
- extend_existing=True
+ extend_existing=True
)
@testing.uses_deprecated()
assert_raises(
exc.ArgumentError,
Table, 'users', meta2, useexisting=True,
- extend_existing=True
+ extend_existing=True
)
def test_keep_existing_no_dupe_constraints(self):
meta2 = self._notexisting_fixture()
users = Table('users', meta2,
- Column('id', Integer),
- Column('name', Unicode),
- UniqueConstraint('name'),
- keep_existing=True
- )
+ Column('id', Integer),
+ Column('name', Unicode),
+ UniqueConstraint('name'),
+ keep_existing=True
+ )
assert 'name' in users.c
assert 'id' in users.c
eq_(len(users.constraints), 2)
u2 = Table('users', meta2,
- Column('id', Integer),
- Column('name', Unicode),
- UniqueConstraint('name'),
- keep_existing=True
- )
+ Column('id', Integer),
+ Column('name', Unicode),
+ UniqueConstraint('name'),
+ keep_existing=True
+ )
eq_(len(u2.constraints), 2)
def test_extend_existing_dupes_constraints(self):
meta2 = self._notexisting_fixture()
users = Table('users', meta2,
- Column('id', Integer),
- Column('name', Unicode),
- UniqueConstraint('name'),
- extend_existing=True
- )
+ Column('id', Integer),
+ Column('name', Unicode),
+ UniqueConstraint('name'),
+ extend_existing=True
+ )
assert 'name' in users.c
assert 'id' in users.c
eq_(len(users.constraints), 2)
u2 = Table('users', meta2,
- Column('id', Integer),
- Column('name', Unicode),
- UniqueConstraint('name'),
- extend_existing=True
- )
+ Column('id', Integer),
+ Column('name', Unicode),
+ UniqueConstraint('name'),
+ extend_existing=True
+ )
# constraint got duped
eq_(len(u2.constraints), 3)
def test_keep_existing_add_column(self):
meta2 = self._useexisting_fixture()
users = Table('users', meta2,
- Column('foo', Integer),
- autoload=True,
+ Column('foo', Integer),
+ autoload=True,
keep_existing=True)
assert "foo" not in users.c
assert isinstance(users.c.name.type, Unicode)
@testing.skip_if(
- lambda: testing.db.dialect.requires_name_normalize,
- "test depends on lowercase as case insensitive")
+ lambda: testing.db.dialect.requires_name_normalize,
+ "test depends on lowercase as case insensitive")
def test_keep_existing_quote_no_orig(self):
meta2 = self._notexisting_fixture()
users = Table('users', meta2, quote=True,
- autoload=True,
+ autoload=True,
keep_existing=True)
assert users.name.quote
def test_keep_existing_add_column_no_orig(self):
meta2 = self._notexisting_fixture()
users = Table('users', meta2,
- Column('foo', Integer),
- autoload=True,
+ Column('foo', Integer),
+ autoload=True,
keep_existing=True)
assert "foo" in users.c
def test_keep_existing_add_column_no_reflection(self):
meta2 = self._useexisting_fixture()
users = Table('users', meta2,
- Column('foo', Integer),
+ Column('foo', Integer),
keep_existing=True)
assert "foo" not in users.c
tsa.exc.ArgumentError,
"Can't redefine 'quote' or 'quote_schema' arguments",
Table, 'users', meta2, quote=True, autoload=True,
- extend_existing=True
+ extend_existing=True
)
def test_extend_existing_add_column(self):
meta2 = self._useexisting_fixture()
users = Table('users', meta2,
- Column('foo', Integer),
- autoload=True,
+ Column('foo', Integer),
+ autoload=True,
extend_existing=True)
assert "foo" in users.c
assert isinstance(users.c.name.type, Unicode)
@testing.skip_if(
- lambda: testing.db.dialect.requires_name_normalize,
- "test depends on lowercase as case insensitive")
+ lambda: testing.db.dialect.requires_name_normalize,
+ "test depends on lowercase as case insensitive")
def test_extend_existing_quote_no_orig(self):
meta2 = self._notexisting_fixture()
users = Table('users', meta2, quote=True,
- autoload=True,
+ autoload=True,
extend_existing=True)
assert users.name.quote
def test_extend_existing_add_column_no_orig(self):
meta2 = self._notexisting_fixture()
users = Table('users', meta2,
- Column('foo', Integer),
- autoload=True,
+ Column('foo', Integer),
+ autoload=True,
extend_existing=True)
assert "foo" in users.c
tsa.exc.ArgumentError,
"Can't redefine 'quote' or 'quote_schema' arguments",
Table, 'users', meta2, quote=True,
- extend_existing=True
+ extend_existing=True
)
def test_extend_existing_add_column_no_reflection(self):
meta2 = self._useexisting_fixture()
users = Table('users', meta2,
- Column('foo', Integer),
+ Column('foo', Integer),
extend_existing=True)
assert "foo" in users.c
+
class IndexTest(fixtures.TestBase):
+
def _assert(self, t, i, columns=True):
eq_(t.indexes, set([i]))
if columns:
class ConstraintTest(fixtures.TestBase):
+
def _single_fixture(self):
m = MetaData()
t1 = Table('t1', m,
- Column('a', Integer),
- Column('b', Integer)
- )
+ Column('a', Integer),
+ Column('b', Integer)
+ )
t2 = Table('t2', m,
- Column('a', Integer, ForeignKey('t1.a'))
- )
+ Column('a', Integer, ForeignKey('t1.a'))
+ )
t3 = Table('t3', m,
- Column('a', Integer)
- )
+ Column('a', Integer)
+ )
return t1, t2, t3
def test_table_references(self):
def test_related_column_not_present_atfirst_ok(self):
m = MetaData()
base_table = Table("base", m,
- Column("id", Integer, primary_key=True)
- )
+ Column("id", Integer, primary_key=True)
+ )
fk = ForeignKey('base.q')
derived_table = Table("derived", m,
- Column("id", None, fk,
- primary_key=True),
- )
+ Column("id", None, fk,
+ primary_key=True),
+ )
base_table.append_column(Column('q', Integer))
assert fk.column is base_table.c.q
assert_raises_message(
exc.ArgumentError,
r"ForeignKeyConstraint on t1\(x, y\) refers to "
- "multiple remote tables: t2 and t3",
+ "multiple remote tables: t2 and t3",
Table,
't1', m, Column('x', Integer), Column('y', Integer),
ForeignKeyConstraint(['x', 'y'], ['t2.x', 't3.y'])
assert_raises_message(
exc.ArgumentError,
r"ForeignKeyConstraint on t1\(x, y\) refers to "
- "multiple remote tables: t2 and t3",
+ "multiple remote tables: t2 and t3",
Table,
't1', m, Column('x', Integer), Column('y', Integer),
ForeignKeyConstraint(['x', 'y'], [t2.c.x, t3.c.y])
# no error is raised for this one right now.
# which is a minor bug.
Table('t1', m, Column('x', Integer), Column('y', Integer),
- ForeignKeyConstraint(['x', 'y'], [x, y])
- )
+ ForeignKeyConstraint(['x', 'y'], [x, y])
+ )
- t2 = Table('t2', m, x)
- t3 = Table('t3', m, y)
+ Table('t2', m, x)
+ Table('t3', m, y)
def test_constraint_copied_to_proxy_ok(self):
m = MetaData()
- t1 = Table('t1', m, Column('id', Integer, primary_key=True))
+ Table('t1', m, Column('id', Integer, primary_key=True))
t2 = Table('t2', m, Column('id', Integer, ForeignKey('t1.id'),
- primary_key=True))
+ primary_key=True))
s = tsa.select([t2])
t2fk = list(t2.c.id.foreign_keys)[0]
def test_type_propagate_composite_fk_string(self):
metadata = MetaData()
- a = Table('a', metadata,
- Column('key1', Integer, primary_key=True),
- Column('key2', String(40), primary_key=True))
+ Table(
+ 'a', metadata,
+ Column('key1', Integer, primary_key=True),
+ Column('key2', String(40), primary_key=True))
b = Table('b', metadata,
Column('a_key1', None),
def test_type_propagate_standalone_fk_string(self):
metadata = MetaData()
- a = Table('a', metadata,
- Column('key1', Integer, primary_key=True))
+ Table(
+ 'a', metadata,
+ Column('key1', Integer, primary_key=True))
b = Table('b', metadata,
Column('a_key1', None, ForeignKey("a.key1")),
def test_type_propagate_chained_string_source_first(self):
metadata = MetaData()
- a = Table('a', metadata,
- Column('key1', Integer, primary_key=True))
+ Table(
+ 'a', metadata,
+ Column('key1', Integer, primary_key=True)
+ )
b = Table('b', metadata,
Column('a_key1', None, ForeignKey("a.key1")),
Column('b_key1', None, ForeignKey("b.a_key1")),
)
- a = Table('a', metadata,
- Column('key1', Integer, primary_key=True))
+ Table(
+ 'a', metadata,
+ Column('key1', Integer, primary_key=True))
assert isinstance(b.c.a_key1.type, Integer)
assert isinstance(c.c.b_key1.type, Integer)
c1 = Column('x', Integer)
class CThing(object):
+
def __init__(self, c):
self.c = c
+
def __clause_element__(self):
return self.c
def test_column_accessor_string_no_parent_table(self):
fk = ForeignKey("sometable.somecol")
- c1 = Column('x', fk)
+ Column('x', fk)
assert_raises_message(
exc.InvalidRequestError,
"this ForeignKey's parent column is not yet "
def test_column_accessor_string_no_target_table(self):
fk = ForeignKey("sometable.somecol")
c1 = Column('x', fk)
- t1 = Table('t', MetaData(), c1)
+ Table('t', MetaData(), c1)
assert_raises_message(
exc.NoReferencedTableError,
"Foreign key associated with column 't.x' could not find "
fk = ForeignKey("sometable.somecol")
c1 = Column('x', fk)
m = MetaData()
- t1 = Table('t', m, c1)
- t2 = Table("sometable", m, Column('notsomecol', Integer))
+ Table('t', m, c1)
+ Table("sometable", m, Column('notsomecol', Integer))
assert_raises_message(
exc.NoReferencedColumnError,
"Could not initialize target column for ForeignKey "
class ColumnDefinitionTest(AssertsCompiledSQL, fixtures.TestBase):
+
"""Test Column() construction."""
__dialect__ = 'default'
def columns(self):
return [Column(Integer),
- Column('b', Integer),
- Column(Integer),
- Column('d', Integer),
- Column(Integer, name='e'),
- Column(type_=Integer),
- Column(Integer()),
- Column('h', Integer()),
- Column(type_=Integer())]
+ Column('b', Integer),
+ Column(Integer),
+ Column('d', Integer),
+ Column(Integer, name='e'),
+ Column(type_=Integer),
+ Column(Integer()),
+ Column('h', Integer()),
+ Column(type_=Integer())]
def test_basic(self):
c = self.columns()
def test_bogus(self):
assert_raises(exc.ArgumentError, Column, 'foo', name='bar')
assert_raises(exc.ArgumentError, Column, 'foo', Integer,
- type_=Integer())
+ type_=Integer())
def test_custom_subclass_proxy(self):
"""test proxy generation of a Column subclass, can be compiled."""
from sqlalchemy.sql import select
class MyColumn(Column):
+
def _constructor(self, name, type, **kw):
kw['name'] = name
return MyColumn(type, **kw)
name = MyColumn(String)
name.name = 'name'
t1 = Table('foo', MetaData(),
- id,
- name
- )
+ id,
+ name
+ )
# goofy thing
eq_(t1.c.name.my_goofy_thing(), "hi")
from sqlalchemy.sql import select
class MyColumn(Column):
+
def __init__(self, type, **kw):
Column.__init__(self, type, **kw)
name = MyColumn(String)
name.name = 'name'
t1 = Table('foo', MetaData(),
- id,
- name
- )
+ id,
+ name
+ )
assert_raises_message(
TypeError,
"Could not create a copy of this <class "
return compiler.visit_create_column(element, **kw)
text = "%s SPECIAL DIRECTIVE %s" % (
- column.name,
- compiler.type_compiler.process(column.type)
- )
+ column.name,
+ compiler.type_compiler.process(column.type)
+ )
default = compiler.get_column_default_string(column)
if default is not None:
text += " DEFAULT " + default
if column.constraints:
text += " ".join(
- compiler.process(const)
- for const in column.constraints)
+ compiler.process(const)
+ for const in column.constraints)
return text
- t = Table('mytable', MetaData(),
- Column('x', Integer, info={"special": True}, primary_key=True),
- Column('y', String(50)),
- Column('z', String(20), info={"special": True})
- )
+ t = Table(
+ 'mytable', MetaData(),
+ Column('x', Integer, info={
+ "special": True}, primary_key=True),
+ Column('y', String(50)),
+ Column('z', String(20), info={
+ "special": True}))
self.assert_compile(
schema.CreateTable(t),
"CREATE TABLE mytable (x SPECIAL DIRECTIVE INTEGER "
- "NOT NULL, y VARCHAR(50), "
- "z SPECIAL DIRECTIVE VARCHAR(20), PRIMARY KEY (x))"
+ "NOT NULL, y VARCHAR(50), "
+ "z SPECIAL DIRECTIVE VARCHAR(20), PRIMARY KEY (x))"
)
deregister(schema.CreateColumn)
+
class ColumnDefaultsTest(fixtures.TestBase):
+
"""test assignment of default fixures to columns"""
def _fixture(self, *arg, **kw):
assert c.onupdate.arg == target
assert c.onupdate.column is c
+
class ColumnOptionsTest(fixtures.TestBase):
def test_default_generators(self):
self._no_error(Column("foo", ForeignKey('bar.id'), default="foo"))
self._no_error(Column("foo", ForeignKey('bar.id'), Sequence("a")))
-
def test_column_info(self):
c1 = Column('foo', String, info={'x': 'y'})
c.info['bar'] = 'zip'
assert c.info['bar'] == 'zip'
+
class CatchAllEventsTest(fixtures.RemovesEvents, fixtures.TestBase):
def test_all_events(self):
canary = []
+
def before_attach(obj, parent):
canary.append("%s->%s" % (obj.__class__.__name__,
- parent.__class__.__name__))
+ parent.__class__.__name__))
def after_attach(obj, parent):
canary.append("%s->%s" % (obj.__class__.__name__, parent))
- self.event_listen(schema.SchemaItem, "before_parent_attach", before_attach)
- self.event_listen(schema.SchemaItem, "after_parent_attach", after_attach)
+ self.event_listen(
+ schema.SchemaItem,
+ "before_parent_attach",
+ before_attach)
+ self.event_listen(
+ schema.SchemaItem,
+ "after_parent_attach",
+ after_attach)
m = MetaData()
Table('t1', m,
- Column('id', Integer, Sequence('foo_id'), primary_key=True),
- Column('bar', String, ForeignKey('t2.id'))
- )
+ Column('id', Integer, Sequence('foo_id'), primary_key=True),
+ Column('bar', String, ForeignKey('t2.id'))
+ )
Table('t2', m,
- Column('id', Integer, primary_key=True),
- )
+ Column('id', Integer, primary_key=True),
+ )
eq_(
canary,
def evt(target):
def before_attach(obj, parent):
canary.append("%s->%s" % (target.__name__,
- parent.__class__.__name__))
+ parent.__class__.__name__))
def after_attach(obj, parent):
assert hasattr(obj, 'name') # so we can change it
m = MetaData()
Table('t1', m,
- Column('id', Integer, Sequence('foo_id'), primary_key=True),
- Column('bar', String, ForeignKey('t2.id'), index=True),
- Column('bat', Integer, unique=True),
- )
+ Column('id', Integer, Sequence('foo_id'), primary_key=True),
+ Column('bar', String, ForeignKey('t2.id'), index=True),
+ Column('bat', Integer, unique=True),
+ )
Table('t2', m,
- Column('id', Integer, primary_key=True),
- Column('bar', Integer),
- Column('bat', Integer),
- CheckConstraint("bar>5"),
- UniqueConstraint('bar', 'bat'),
- Index(None, 'bar', 'bat')
- )
+ Column('id', Integer, primary_key=True),
+ Column('bar', Integer),
+ Column('bat', Integer),
+ CheckConstraint("bar>5"),
+ UniqueConstraint('bar', 'bat'),
+ Index(None, 'bar', 'bat')
+ )
eq_(
canary,
[
]
)
+
class DialectKWArgTest(fixtures.TestBase):
+
@contextmanager
def _fixture(self):
from sqlalchemy.engine.default import DefaultDialect
+
class ParticipatingDialect(DefaultDialect):
construct_arguments = [
(schema.Index, {
def test_nonparticipating(self):
with self._fixture():
- idx = Index('a', 'b', 'c', nonparticipating_y=True, nonparticipating_q=5)
+ idx = Index(
+ 'a',
+ 'b',
+ 'c',
+ nonparticipating_y=True,
+ nonparticipating_q=5)
eq_(
idx.dialect_kwargs,
{
assert_raises_message(
TypeError,
"Additional arguments should be named "
- "<dialectname>_<argument>, got 'foobar'",
+ "<dialectname>_<argument>, got 'foobar'",
Index, 'a', 'b', 'c', foobar=True
)
+
def test_unknown_dialect_warning(self):
with self._fixture():
assert_raises_message(
def test_unknown_dialect_warning_still_populates_multiple(self):
with self._fixture():
idx = Index('a', 'b', 'c', unknown_y=True, unknown_z=5,
- otherunknown_foo='bar', participating_y=8)
+ otherunknown_foo='bar', participating_y=8)
eq_(
idx.dialect_options,
{
)
eq_(idx.dialect_kwargs,
{'unknown_z': 5, 'participating_y': 8,
- 'unknown_y': True,
- 'otherunknown_foo': 'bar'}
- ) # still populates
+ 'unknown_y': True,
+ 'otherunknown_foo': 'bar'}
+ ) # still populates
def test_runs_safekwarg(self):
with mock.patch("sqlalchemy.util.safe_kwarg",
- lambda arg: "goofy_%s" % arg):
+ lambda arg: "goofy_%s" % arg):
with self._fixture():
idx = Index('a', 'b')
idx.kwargs[u'participating_x'] = 7
def test_combined(self):
with self._fixture():
idx = Index('a', 'b', 'c', participating_x=7,
- nonparticipating_y=True)
+ nonparticipating_y=True)
eq_(
idx.dialect_options,
participating_x=7,
participating2_x=15,
participating2_y="lazy"
- )
+ )
eq_(
idx.dialect_options,
{
m = MetaData()
fk = ForeignKey('t2.id', participating_foobar=True)
t = Table('t', m, Column('id', Integer, fk))
- fkc = [c for c in t.constraints if isinstance(c, ForeignKeyConstraint)][0]
+ fkc = [
+ c for c in t.constraints if isinstance(
+ c,
+ ForeignKeyConstraint)][0]
eq_(
fkc.dialect_kwargs,
{'participating_foobar': True}
with self._fixture():
m = MetaData()
t = Table('x', m, Column('x', Integer),
- participating2_xyz='foo',
- participating2_engine='InnoDB',
- )
+ participating2_xyz='foo',
+ participating2_engine='InnoDB',
+ )
eq_(
t.dialect_kwargs,
{
t = Table('x', m, Column('x', Integer), participating2_foobar=5)
assert 'foobar' in t.dialect_options['participating2']
-
def test_update(self):
with self._fixture():
idx = Index('a', 'b', 'c', participating_x=20)
eq_(idx.dialect_kwargs, {
- "participating_x": 20,
- })
+ "participating_x": 20,
+ })
idx._validate_dialect_kwargs({
- "participating_x": 25,
- "participating_z_one": "default"})
+ "participating_x": 25,
+ "participating_z_one": "default"})
eq_(idx.dialect_options, {
- "participating": {"x": 25, "y": False, "z_one": "default"}
- })
+ "participating": {"x": 25, "y": False, "z_one": "default"}
+ })
eq_(idx.dialect_kwargs, {
- "participating_x": 25,
- 'participating_z_one': "default"
- })
+ "participating_x": 25,
+ 'participating_z_one': "default"
+ })
idx._validate_dialect_kwargs({
- "participating_x": 25,
- "participating_z_one": "default"})
+ "participating_x": 25,
+ "participating_z_one": "default"})
eq_(idx.dialect_options, {
- "participating": {"x": 25, "y": False, "z_one": "default"}
- })
+ "participating": {"x": 25, "y": False, "z_one": "default"}
+ })
eq_(idx.dialect_kwargs, {
- "participating_x": 25,
- 'participating_z_one': "default"
- })
+ "participating_x": 25,
+ 'participating_z_one': "default"
+ })
idx._validate_dialect_kwargs({
- "participating_y": True,
- 'participating2_y': "p2y"})
+ "participating_y": True,
+ 'participating2_y': "p2y"})
eq_(idx.dialect_options, {
- "participating": {"x": 25, "y": True, "z_one": "default"},
- "participating2": {"y": "p2y", "pp": "default", "x": 9}
- })
+ "participating": {"x": 25, "y": True, "z_one": "default"},
+ "participating2": {"y": "p2y", "pp": "default", "x": 9}
+ })
eq_(idx.dialect_kwargs, {
- "participating_x": 25,
- "participating_y": True,
- 'participating2_y': "p2y",
- "participating_z_one": "default"})
+ "participating_x": 25,
+ "participating_y": True,
+ 'participating2_y': "p2y",
+ "participating_z_one": "default"})
def test_key_error_kwargs_no_dialect(self):
with self._fixture():
assert_raises(
KeyError,
- idx.dialect_options['nonparticipating'].__getitem__, 'asdfaso890'
- )
+ idx.dialect_options['nonparticipating'].__getitem__,
+ 'asdfaso890')
def test_ad_hoc_participating_via_opt(self):
with self._fixture():
assert_raises_message(
exc.ArgumentError,
"Dialect 'nonparticipating' does have keyword-argument "
- "validation and defaults enabled configured",
+ "validation and defaults enabled configured",
Index.argument_for, "nonparticipating", "xyzqpr", False
)
-
def test_add_new_arguments_invalid_dialect(self):
with self._fixture():
assert_raises_message(
m1 = MetaData(naming_convention=naming_convention)
u1 = Table('user', m1,
- Column('id', Integer, primary_key=True),
- Column('version', Integer, primary_key=True),
- Column('data', String(30)),
- schema=table_schema
- )
+ Column('id', Integer, primary_key=True),
+ Column('version', Integer, primary_key=True),
+ Column('data', String(30)),
+ schema=table_schema
+ )
return u1
def test_uq_name(self):
u1 = self._fixture(naming_convention={
- "uq": "uq_%(table_name)s_%(column_0_name)s"
- })
+ "uq": "uq_%(table_name)s_%(column_0_name)s"
+ })
uq = UniqueConstraint(u1.c.data)
eq_(uq.name, "uq_user_data")
def test_column_attached_ck_name(self):
m = MetaData(naming_convention={
- "ck": "ck_%(table_name)s_%(constraint_name)s"
- })
+ "ck": "ck_%(table_name)s_%(constraint_name)s"
+ })
ck = CheckConstraint('x > 5', name='x1')
Table('t', m, Column('x', ck))
eq_(ck.name, "ck_t_x1")
def test_table_attached_ck_name(self):
m = MetaData(naming_convention={
- "ck": "ck_%(table_name)s_%(constraint_name)s"
- })
+ "ck": "ck_%(table_name)s_%(constraint_name)s"
+ })
ck = CheckConstraint('x > 5', name='x1')
Table('t', m, Column('x', Integer), ck)
eq_(ck.name, "ck_t_x1")
t.append_constraint(uq)
eq_(uq.name, "my_special_key")
-
def test_fk_name_schema(self):
u1 = self._fixture(naming_convention={
- "fk": "fk_%(table_name)s_%(column_0_name)s_"
- "%(referred_table_name)s_%(referred_column_0_name)s"
- }, table_schema="foo")
+ "fk": "fk_%(table_name)s_%(column_0_name)s_"
+ "%(referred_table_name)s_%(referred_column_0_name)s"
+ }, table_schema="foo")
m1 = u1.metadata
a1 = Table('address', m1,
- Column('id', Integer, primary_key=True),
- Column('user_id', Integer),
- Column('user_version_id', Integer)
- )
+ Column('id', Integer, primary_key=True),
+ Column('user_id', Integer),
+ Column('user_version_id', Integer)
+ )
fk = ForeignKeyConstraint(['user_id', 'user_version_id'],
- ['foo.user.id', 'foo.user.version'])
+ ['foo.user.id', 'foo.user.version'])
a1.append_constraint(fk)
eq_(fk.name, "fk_address_user_id_user_id")
-
def test_fk_attrs(self):
u1 = self._fixture(naming_convention={
- "fk": "fk_%(table_name)s_%(column_0_name)s_"
- "%(referred_table_name)s_%(referred_column_0_name)s"
- })
+ "fk": "fk_%(table_name)s_%(column_0_name)s_"
+ "%(referred_table_name)s_%(referred_column_0_name)s"
+ })
m1 = u1.metadata
a1 = Table('address', m1,
- Column('id', Integer, primary_key=True),
- Column('user_id', Integer),
- Column('user_version_id', Integer)
- )
+ Column('id', Integer, primary_key=True),
+ Column('user_id', Integer),
+ Column('user_version_id', Integer)
+ )
fk = ForeignKeyConstraint(['user_id', 'user_version_id'],
- ['user.id', 'user.version'])
+ ['user.id', 'user.version'])
a1.append_constraint(fk)
eq_(fk.name, "fk_address_user_id_user_id")
-
def test_custom(self):
def key_hash(const, table):
return "HASH_%s" % table.name
u1 = self._fixture(naming_convention={
- "fk": "fk_%(table_name)s_%(key_hash)s",
- "key_hash": key_hash
- })
+ "fk": "fk_%(table_name)s_%(key_hash)s",
+ "key_hash": key_hash
+ })
m1 = u1.metadata
a1 = Table('address', m1,
- Column('id', Integer, primary_key=True),
- Column('user_id', Integer),
- Column('user_version_id', Integer)
- )
+ Column('id', Integer, primary_key=True),
+ Column('user_id', Integer),
+ Column('user_version_id', Integer)
+ )
fk = ForeignKeyConstraint(['user_id', 'user_version_id'],
- ['user.id', 'user.version'])
+ ['user.id', 'user.version'])
a1.append_constraint(fk)
eq_(fk.name, "fk_address_HASH_address")
def test_schematype_ck_name_boolean(self):
m1 = MetaData(naming_convention={
- "ck": "ck_%(table_name)s_%(constraint_name)s"})
+ "ck": "ck_%(table_name)s_%(constraint_name)s"})
u1 = Table('user', m1,
- Column('x', Boolean(name='foo'))
- )
+ Column('x', Boolean(name='foo'))
+ )
# constraint is not hit
eq_(
[c for c in u1.constraints
def test_schematype_ck_name_enum(self):
m1 = MetaData(naming_convention={
- "ck": "ck_%(table_name)s_%(constraint_name)s"})
+ "ck": "ck_%(table_name)s_%(constraint_name)s"})
u1 = Table('user', m1,
- Column('x', Enum('a', 'b', name='foo'))
- )
+ Column('x', Enum('a', 'b', name='foo'))
+ )
eq_(
[c for c in u1.constraints
if isinstance(c, CheckConstraint)][0].name, "foo"
self.assert_compile(
schema.CreateTable(u1),
'CREATE TABLE "user" ('
- "x VARCHAR(1), "
- "CONSTRAINT ck_user_foo CHECK (x IN ('a', 'b'))"
+ "x VARCHAR(1), "
+ "CONSTRAINT ck_user_foo CHECK (x IN ('a', 'b'))"
")"
)
def test_schematype_ck_name_propagate_conv(self):
m1 = MetaData(naming_convention={
- "ck": "ck_%(table_name)s_%(constraint_name)s"})
+ "ck": "ck_%(table_name)s_%(constraint_name)s"})
u1 = Table('user', m1,
- Column('x', Enum('a', 'b', name=naming.conv('foo')))
- )
+ Column('x', Enum('a', 'b', name=naming.conv('foo')))
+ )
eq_(
[c for c in u1.constraints
if isinstance(c, CheckConstraint)][0].name, "foo"
self.assert_compile(
schema.CreateTable(u1),
'CREATE TABLE "user" ('
- "x VARCHAR(1), "
- "CONSTRAINT foo CHECK (x IN ('a', 'b'))"
+ "x VARCHAR(1), "
+ "CONSTRAINT foo CHECK (x IN ('a', 'b'))"
")"
)
'CREATE TABLE "user" (x BOOLEAN, CHECK (x IN (0, 1)))'
)
-
def test_ck_constraint_redundant_event(self):
u1 = self._fixture(naming_convention={
- "ck": "ck_%(table_name)s_%(constraint_name)s"})
+ "ck": "ck_%(table_name)s_%(constraint_name)s"})
ck1 = CheckConstraint(u1.c.version > 3, name='foo')
u1.append_constraint(ck1)
u1.append_constraint(ck1)
eq_(ck1.name, "ck_user_foo")
-
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.sql import column, desc, asc, literal, collate, null, true, false
from sqlalchemy.sql.expression import BinaryExpression, \
- ClauseList, Grouping, \
- UnaryExpression, select, union, func, tuple_
+ ClauseList, Grouping, \
+ UnaryExpression, select, union, func, tuple_
from sqlalchemy.sql import operators, table
import operator
from sqlalchemy import String, Integer, LargeBinary
from sqlalchemy.schema import Column, Table, MetaData
from sqlalchemy.types import TypeEngine, TypeDecorator, UserDefinedType, Boolean
from sqlalchemy.dialects import mysql, firebird, postgresql, oracle, \
- sqlite, mssql
+ sqlite, mssql
from sqlalchemy import util
import datetime
import collections
from sqlalchemy import and_, not_, between, or_
from sqlalchemy.sql import true, false, null
+
class LoopOperate(operators.ColumnOperators):
+
def operate(self, op, *other, **kwargs):
return op
+
class DefaultColumnComparatorTest(fixtures.TestBase):
def _do_scalar_test(self, operator, compare_to):
def _do_operate_test(self, operator, right=column('right')):
left = column('left')
- assert left.comparator.operate(operator, right).compare(
- BinaryExpression(_literal_as_text(left), _literal_as_text(right), operator)
- )
-
- assert operator(left, right).compare(
- BinaryExpression(_literal_as_text(left), _literal_as_text(right), operator)
- )
+ assert left.comparator.operate(
+ operator,
+ right).compare(
+ BinaryExpression(
+ _literal_as_text(left),
+ _literal_as_text(right),
+ operator))
+
+ assert operator(
+ left,
+ right).compare(
+ BinaryExpression(
+ _literal_as_text(left),
+ _literal_as_text(right),
+ operator))
self._loop_test(operator, right)
def test_in(self):
left = column('left')
assert left.comparator.operate(operators.in_op, [1, 2, 3]).compare(
- BinaryExpression(
- left,
- Grouping(ClauseList(
- literal(1), literal(2), literal(3)
- )),
- operators.in_op
- )
+ BinaryExpression(
+ left,
+ Grouping(ClauseList(
+ literal(1), literal(2), literal(3)
+ )),
+ operators.in_op
)
+ )
self._loop_test(operators.in_op, [1, 2, 3])
def test_notin(self):
left = column('left')
assert left.comparator.operate(operators.notin_op, [1, 2, 3]).compare(
- BinaryExpression(
- left,
- Grouping(ClauseList(
- literal(1), literal(2), literal(3)
- )),
- operators.notin_op
- )
+ BinaryExpression(
+ left,
+ Grouping(ClauseList(
+ literal(1), literal(2), literal(3)
+ )),
+ operators.notin_op
)
+ )
self._loop_test(operators.notin_op, [1, 2, 3])
def test_in_no_accept_list_of_non_column_element(self):
def test_in_no_accept_non_list_thing_with_getitem(self):
# test [ticket:2726]
class HasGetitem(String):
+
class comparator_factory(String.Comparator):
+
def __getitem__(self, value):
return value
def test_concat(self):
self._do_operate_test(operators.concat_op)
+
class CustomUnaryOperatorTest(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = 'default'
def _factorial_fixture(self):
class MyInteger(Integer):
+
class comparator_factory(Integer.Comparator):
+
def factorial(self):
return UnaryExpression(self.expr,
- modifier=operators.custom_op("!"),
- type_=MyInteger)
+ modifier=operators.custom_op("!"),
+ type_=MyInteger)
def factorial_prefix(self):
return UnaryExpression(self.expr,
- operator=operators.custom_op("!!"),
- type_=MyInteger)
+ operator=operators.custom_op("!!"),
+ type_=MyInteger)
def __invert__(self):
return UnaryExpression(self.expr,
- operator=operators.custom_op("!!!"),
- type_=MyInteger)
+ operator=operators.custom_op("!!!"),
+ type_=MyInteger)
return MyInteger
assert_raises_message(
exc.CompileError,
"Unary expression does not support operator and "
- "modifier simultaneously",
+ "modifier simultaneously",
UnaryExpression(literal("x"),
- operator=operators.custom_op("x"),
- modifier=operators.custom_op("y")).compile
+ operator=operators.custom_op("x"),
+ modifier=operators.custom_op("y")).compile
)
+
class _CustomComparatorTests(object):
+
def test_override_builtin(self):
c1 = Column('foo', self._add_override_factory())
self._assert_add_override(c1)
def test_column_proxy(self):
t = Table('t', MetaData(),
- Column('foo', self._add_override_factory())
- )
+ Column('foo', self._add_override_factory())
+ )
proxied = t.select().c.foo
self._assert_add_override(proxied)
self._assert_and_override(proxied)
def test_alias_proxy(self):
t = Table('t', MetaData(),
- Column('foo', self._add_override_factory())
- )
+ Column('foo', self._add_override_factory())
+ )
proxied = t.alias().c.foo
self._assert_add_override(proxied)
self._assert_and_override(proxied)
expr.op("goofy_and")(text("5"))
)
+
class CustomComparatorTest(_CustomComparatorTests, fixtures.TestBase):
+
def _add_override_factory(self):
class MyInteger(Integer):
+
class comparator_factory(TypeEngine.Comparator):
+
def __init__(self, expr):
self.expr = expr
class TypeDecoratorComparatorTest(_CustomComparatorTests, fixtures.TestBase):
+
def _add_override_factory(self):
class MyInteger(TypeDecorator):
impl = Integer
class comparator_factory(TypeDecorator.Comparator):
+
def __init__(self, expr):
self.expr = expr
def __and__(self, other):
return self.expr.op("goofy_and")(other)
-
return MyInteger
-class TypeDecoratorWVariantComparatorTest(_CustomComparatorTests, fixtures.TestBase):
+
+class TypeDecoratorWVariantComparatorTest(
+ _CustomComparatorTests,
+ fixtures.TestBase):
+
def _add_override_factory(self):
class SomeOtherInteger(Integer):
+
class comparator_factory(TypeEngine.Comparator):
+
def __init__(self, expr):
self.expr = expr
impl = Integer
class comparator_factory(TypeDecorator.Comparator):
+
def __init__(self, expr):
self.expr = expr
return MyInteger().with_variant(SomeOtherInteger, "mysql")
-class CustomEmbeddedinTypeDecoratorTest(_CustomComparatorTests, fixtures.TestBase):
+class CustomEmbeddedinTypeDecoratorTest(
+ _CustomComparatorTests,
+ fixtures.TestBase):
+
def _add_override_factory(self):
class MyInteger(Integer):
+
class comparator_factory(TypeEngine.Comparator):
+
def __init__(self, expr):
self.expr = expr
def __and__(self, other):
return self.expr.op("goofy_and")(other)
-
class MyDecInteger(TypeDecorator):
impl = MyInteger
return MyDecInteger
+
class NewOperatorTest(_CustomComparatorTests, fixtures.TestBase):
+
def _add_override_factory(self):
class MyInteger(Integer):
+
class comparator_factory(TypeEngine.Comparator):
+
def __init__(self, expr):
self.expr = expr
def _assert_not_and_override(self, expr):
pass
+
class ExtensionOperatorTest(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = 'default'
def test_contains(self):
class MyType(UserDefinedType):
+
class comparator_factory(UserDefinedType.Comparator):
+
def contains(self, other, **kw):
return self.op("->")(other)
def test_getitem(self):
class MyType(UserDefinedType):
+
class comparator_factory(UserDefinedType.Comparator):
+
def __getitem__(self, index):
return self.op("->")(index)
def test_op_not_an_iterator(self):
# see [ticket:2726]
class MyType(UserDefinedType):
+
class comparator_factory(UserDefinedType.Comparator):
+
def __getitem__(self, index):
return self.op("->")(index)
def test_lshift(self):
class MyType(UserDefinedType):
+
class comparator_factory(UserDefinedType.Comparator):
+
def __lshift__(self, other):
return self.op("->")(other)
def test_rshift(self):
class MyType(UserDefinedType):
+
class comparator_factory(UserDefinedType.Comparator):
+
def __rshift__(self, other):
return self.op("->")(other)
class BooleanEvalTest(fixtures.TestBase, testing.AssertsCompiledSQL):
+
"""test standalone booleans being wrapped in an AsBoolean, as well
as true/false compilation."""
class ConjunctionTest(fixtures.TestBase, testing.AssertsCompiledSQL):
+
"""test interaction of and_()/or_() with boolean , null constants
"""
__dialect__ = default.DefaultDialect(supports_native_boolean=True)
def test_four(self):
x = column('x')
self.assert_compile(
- and_(or_(x == 5), or_(x == 7)),
- "x = :x_1 AND x = :x_2")
-
+ and_(or_(x == 5), or_(x == 7)),
+ "x = :x_1 AND x = :x_2")
def test_five(self):
x = column("x")
def test_six_pt_five(self):
x = column("x")
self.assert_compile(select([x]).where(or_(x == 7, true())),
- "SELECT x WHERE true")
+ "SELECT x WHERE true")
- self.assert_compile(select([x]).where(or_(x == 7, true())),
- "SELECT x WHERE 1 = 1",
- dialect=default.DefaultDialect(supports_native_boolean=False))
+ self.assert_compile(
+ select(
+ [x]).where(
+ or_(
+ x == 7,
+ true())),
+ "SELECT x WHERE 1 = 1",
+ dialect=default.DefaultDialect(
+ supports_native_boolean=False))
def test_seven(self):
x = column("x")
self.assert_compile(
- and_(true(), x == 7, true(), x == 9),
- "x = :x_1 AND x = :x_2")
+ and_(true(), x == 7, true(), x == 9),
+ "x = :x_1 AND x = :x_2")
def test_eight(self):
x = column("x")
self.assert_compile(
- or_(false(), x == 7, false(), x == 9),
- "x = :x_1 OR x = :x_2")
+ or_(false(), x == 7, false(), x == 9),
+ "x = :x_1 OR x = :x_2")
def test_nine(self):
x = column("x")
class OperatorPrecedenceTest(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = 'default'
-
table1 = table('mytable',
- column('myid', Integer),
- column('name', String),
- column('description', String),
- )
+ column('myid', Integer),
+ column('name', String),
+ column('description', String),
+ )
table2 = table('op', column('field'))
def test_operator_precedence_1(self):
self.assert_compile(
- self.table2.select((self.table2.c.field == 5) == None),
+ self.table2.select((self.table2.c.field == 5) == None),
"SELECT op.field FROM op WHERE (op.field = :field_1) IS NULL")
def test_operator_precedence_2(self):
self.assert_compile(
- self.table2.select(
- (self.table2.c.field + 5) == self.table2.c.field),
+ self.table2.select(
+ (self.table2.c.field + 5) == self.table2.c.field),
"SELECT op.field FROM op WHERE op.field + :field_1 = op.field")
def test_operator_precedence_3(self):
self.assert_compile(
- self.table2.select((self.table2.c.field + 5) * 6),
+ self.table2.select((self.table2.c.field + 5) * 6),
"SELECT op.field FROM op WHERE (op.field + :field_1) * :param_1")
def test_operator_precedence_4(self):
- self.assert_compile(self.table2.select((self.table2.c.field * 5) + 6),
+ self.assert_compile(
+ self.table2.select(
+ (self.table2.c.field * 5) + 6),
"SELECT op.field FROM op WHERE op.field * :field_1 + :param_1")
def test_operator_precedence_5(self):
self.assert_compile(self.table2.select(
5 + self.table2.c.field.in_([5, 6])),
- "SELECT op.field FROM op WHERE :param_1 + "
- "(op.field IN (:field_1, :field_2))")
+ "SELECT op.field FROM op WHERE :param_1 + "
+ "(op.field IN (:field_1, :field_2))")
def test_operator_precedence_6(self):
self.assert_compile(self.table2.select(
- (5 + self.table2.c.field).in_([5, 6])),
+ (5 + self.table2.c.field).in_([5, 6])),
"SELECT op.field FROM op WHERE :field_1 + op.field "
- "IN (:param_1, :param_2)")
+ "IN (:param_1, :param_2)")
def test_operator_precedence_7(self):
self.assert_compile(self.table2.select(
- not_(and_(self.table2.c.field == 5,
- self.table2.c.field == 7))),
+ not_(and_(self.table2.c.field == 5,
+ self.table2.c.field == 7))),
"SELECT op.field FROM op WHERE NOT "
- "(op.field = :field_1 AND op.field = :field_2)")
+ "(op.field = :field_1 AND op.field = :field_2)")
def test_operator_precedence_8(self):
- self.assert_compile(self.table2.select(not_(self.table2.c.field == 5)),
+ self.assert_compile(
+ self.table2.select(
+ not_(
+ self.table2.c.field == 5)),
"SELECT op.field FROM op WHERE op.field != :field_1")
def test_operator_precedence_9(self):
self.assert_compile(self.table2.select(
- not_(self.table2.c.field.between(5, 6))),
+ not_(self.table2.c.field.between(5, 6))),
"SELECT op.field FROM op WHERE "
- "op.field NOT BETWEEN :field_1 AND :field_2")
+ "op.field NOT BETWEEN :field_1 AND :field_2")
def test_operator_precedence_10(self):
- self.assert_compile(self.table2.select(not_(self.table2.c.field) == 5),
+ self.assert_compile(
+ self.table2.select(
+ not_(
+ self.table2.c.field) == 5),
"SELECT op.field FROM op WHERE (NOT op.field) = :param_1")
def test_operator_precedence_11(self):
self.assert_compile(self.table2.select(
- (self.table2.c.field == self.table2.c.field).\
- between(False, True)),
+ (self.table2.c.field == self.table2.c.field).
+ between(False, True)),
"SELECT op.field FROM op WHERE (op.field = op.field) "
- "BETWEEN :param_1 AND :param_2")
+ "BETWEEN :param_1 AND :param_2")
def test_operator_precedence_12(self):
self.assert_compile(self.table2.select(
- between((self.table2.c.field == self.table2.c.field),
- False, True)),
+ between((self.table2.c.field == self.table2.c.field),
+ False, True)),
"SELECT op.field FROM op WHERE (op.field = op.field) "
- "BETWEEN :param_1 AND :param_2")
+ "BETWEEN :param_1 AND :param_2")
def test_operator_precedence_13(self):
- self.assert_compile(self.table2.select(
- self.table2.c.field.match(
- self.table2.c.field).is_(None)),
+ self.assert_compile(
+ self.table2.select(
+ self.table2.c.field.match(
+ self.table2.c.field).is_(None)),
"SELECT op.field FROM op WHERE (op.field MATCH op.field) IS NULL")
def test_operator_precedence_collate_1(self):
def test_operator_precedence_collate_5(self):
self.assert_compile(
select([self.table1.c.name]).order_by(
- self.table1.c.name.collate('utf-8').desc()),
+ self.table1.c.name.collate('utf-8').desc()),
"SELECT mytable.name FROM mytable "
"ORDER BY mytable.name COLLATE utf-8 DESC"
)
def test_operator_precedence_collate_6(self):
self.assert_compile(
select([self.table1.c.name]).order_by(
- self.table1.c.name.collate('utf-8').desc().nullslast()),
+ self.table1.c.name.collate('utf-8').desc().nullslast()),
"SELECT mytable.name FROM mytable "
"ORDER BY mytable.name COLLATE utf-8 DESC NULLS LAST"
)
def test_operator_precedence_collate_7(self):
self.assert_compile(
select([self.table1.c.name]).order_by(
- self.table1.c.name.collate('utf-8').asc()),
+ self.table1.c.name.collate('utf-8').asc()),
"SELECT mytable.name FROM mytable "
"ORDER BY mytable.name COLLATE utf-8 ASC"
)
def test_commutative_operators(self):
self.assert_compile(
- literal("a") + literal("b") * literal("c"),
- ":param_1 || :param_2 * :param_3"
+ literal("a") + literal("b") * literal("c"),
+ ":param_1 || :param_2 * :param_3"
)
def test_op_operators(self):
self.assert_compile(
self.table1.select(self.table1.c.myid.op('hoho')(12) == 14),
"SELECT mytable.myid, mytable.name, mytable.description FROM "
- "mytable WHERE (mytable.myid hoho :myid_1) = :param_1"
+ "mytable WHERE (mytable.myid hoho :myid_1) = :param_1"
)
def test_op_operators_comma_precedence(self):
self.assert_compile(op2, "mytable.myid hoho :myid_1 lala :param_1")
self.assert_compile(op3, "(mytable.myid hoho :myid_1) lala :param_1")
+
class OperatorAssociativityTest(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = 'default'
f = column('f')
self.assert_compile((f - f).label('foo') - f, "(f - f) - f")
-
def test_associativity_5(self):
f = column('f')
self.assert_compile(f - (f - f), "f - (f - f)")
f = column('f')
self.assert_compile(f / (f / (f - f)), "f / (f / (f - f))")
+
class InTest(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = 'default'
table1 = table('mytable',
- column('myid', Integer),
- )
+ column('myid', Integer),
+ )
table2 = table(
'myothertable',
column('otherid', Integer),
def test_in_1(self):
self.assert_compile(self.table1.c.myid.in_(['a']),
- "mytable.myid IN (:myid_1)")
+ "mytable.myid IN (:myid_1)")
def test_in_2(self):
self.assert_compile(~self.table1.c.myid.in_(['a']),
- "mytable.myid NOT IN (:myid_1)")
+ "mytable.myid NOT IN (:myid_1)")
def test_in_3(self):
self.assert_compile(self.table1.c.myid.in_(['a', 'b']),
- "mytable.myid IN (:myid_1, :myid_2)")
+ "mytable.myid IN (:myid_1, :myid_2)")
def test_in_4(self):
self.assert_compile(self.table1.c.myid.in_(iter(['a', 'b'])),
- "mytable.myid IN (:myid_1, :myid_2)")
+ "mytable.myid IN (:myid_1, :myid_2)")
def test_in_5(self):
self.assert_compile(self.table1.c.myid.in_([literal('a')]),
- "mytable.myid IN (:param_1)")
+ "mytable.myid IN (:param_1)")
def test_in_6(self):
self.assert_compile(self.table1.c.myid.in_([literal('a'), 'b']),
- "mytable.myid IN (:param_1, :myid_1)")
+ "mytable.myid IN (:param_1, :myid_1)")
def test_in_7(self):
self.assert_compile(
- self.table1.c.myid.in_([literal('a'), literal('b')]),
- "mytable.myid IN (:param_1, :param_2)")
+ self.table1.c.myid.in_([literal('a'), literal('b')]),
+ "mytable.myid IN (:param_1, :param_2)")
def test_in_8(self):
self.assert_compile(self.table1.c.myid.in_(['a', literal('b')]),
- "mytable.myid IN (:myid_1, :param_1)")
+ "mytable.myid IN (:myid_1, :param_1)")
def test_in_9(self):
self.assert_compile(self.table1.c.myid.in_([literal(1) + 'a']),
- "mytable.myid IN (:param_1 + :param_2)")
+ "mytable.myid IN (:param_1 + :param_2)")
def test_in_10(self):
self.assert_compile(self.table1.c.myid.in_([literal('a') + 'a', 'b']),
- "mytable.myid IN (:param_1 || :param_2, :myid_1)")
+ "mytable.myid IN (:param_1 || :param_2, :myid_1)")
def test_in_11(self):
- self.assert_compile(self.table1.c.myid.in_([literal('a') + \
- literal('a'), literal('b')]),
- "mytable.myid IN (:param_1 || :param_2, :param_3)")
+ self.assert_compile(
+ self.table1.c.myid.in_(
+ [
+ literal('a') +
+ literal('a'),
+ literal('b')]),
+ "mytable.myid IN (:param_1 || :param_2, :param_3)")
def test_in_12(self):
self.assert_compile(self.table1.c.myid.in_([1, literal(3) + 4]),
- "mytable.myid IN (:myid_1, :param_1 + :param_2)")
+ "mytable.myid IN (:myid_1, :param_1 + :param_2)")
def test_in_13(self):
self.assert_compile(self.table1.c.myid.in_([literal('a') < 'b']),
- "mytable.myid IN (:param_1 < :param_2)")
+ "mytable.myid IN (:param_1 < :param_2)")
def test_in_14(self):
self.assert_compile(self.table1.c.myid.in_([self.table1.c.myid]),
- "mytable.myid IN (mytable.myid)")
+ "mytable.myid IN (mytable.myid)")
def test_in_15(self):
self.assert_compile(self.table1.c.myid.in_(['a', self.table1.c.myid]),
- "mytable.myid IN (:myid_1, mytable.myid)")
+ "mytable.myid IN (:myid_1, mytable.myid)")
def test_in_16(self):
self.assert_compile(self.table1.c.myid.in_([literal('a'),
- self.table1.c.myid]),
- "mytable.myid IN (:param_1, mytable.myid)")
+ self.table1.c.myid]),
+ "mytable.myid IN (:param_1, mytable.myid)")
def test_in_17(self):
- self.assert_compile(self.table1.c.myid.in_([literal('a'), \
- self.table1.c.myid + 'a']),
- "mytable.myid IN (:param_1, mytable.myid + :myid_1)")
+ self.assert_compile(
+ self.table1.c.myid.in_(
+ [
+ literal('a'),
+ self.table1.c.myid +
+ 'a']),
+ "mytable.myid IN (:param_1, mytable.myid + :myid_1)")
def test_in_18(self):
- self.assert_compile(self.table1.c.myid.in_([literal(1), 'a' + \
- self.table1.c.myid]),
- "mytable.myid IN (:param_1, :myid_1 + mytable.myid)")
+ self.assert_compile(
+ self.table1.c.myid.in_(
+ [
+ literal(1),
+ 'a' +
+ self.table1.c.myid]),
+ "mytable.myid IN (:param_1, :myid_1 + mytable.myid)")
def test_in_19(self):
self.assert_compile(self.table1.c.myid.in_([1, 2, 3]),
- "mytable.myid IN (:myid_1, :myid_2, :myid_3)")
+ "mytable.myid IN (:myid_1, :myid_2, :myid_3)")
def test_in_20(self):
self.assert_compile(self.table1.c.myid.in_(
- select([self.table2.c.otherid])),
- "mytable.myid IN (SELECT myothertable.otherid FROM myothertable)")
+ select([self.table2.c.otherid])),
+ "mytable.myid IN (SELECT myothertable.otherid FROM myothertable)")
def test_in_21(self):
self.assert_compile(~self.table1.c.myid.in_(
select([self.table2.c.otherid])),
- "mytable.myid NOT IN (SELECT myothertable.otherid FROM myothertable)")
+ "mytable.myid NOT IN (SELECT myothertable.otherid FROM myothertable)")
def test_in_22(self):
self.assert_compile(
- self.table1.c.myid.in_(
- text("SELECT myothertable.otherid FROM myothertable")
- ),
- "mytable.myid IN (SELECT myothertable.otherid "
- "FROM myothertable)"
+ self.table1.c.myid.in_(
+ text("SELECT myothertable.otherid FROM myothertable")
+ ),
+ "mytable.myid IN (SELECT myothertable.otherid "
+ "FROM myothertable)"
)
@testing.emits_warning('.*empty sequence.*')
def test_in_23(self):
self.assert_compile(self.table1.c.myid.in_([]),
- "mytable.myid != mytable.myid")
+ "mytable.myid != mytable.myid")
def test_in_24(self):
self.assert_compile(
select([self.table1.c.myid.in_(select([self.table2.c.otherid]))]),
"SELECT mytable.myid IN (SELECT myothertable.otherid "
- "FROM myothertable) AS anon_1 FROM mytable"
+ "FROM myothertable) AS anon_1 FROM mytable"
)
def test_in_25(self):
self.assert_compile(
select([self.table1.c.myid.in_(
- select([self.table2.c.otherid]).as_scalar())]),
+ select([self.table2.c.otherid]).as_scalar())]),
"SELECT mytable.myid IN (SELECT myothertable.otherid "
- "FROM myothertable) AS anon_1 FROM mytable"
+ "FROM myothertable) AS anon_1 FROM mytable"
)
def test_in_26(self):
self.assert_compile(self.table1.c.myid.in_(
union(
- select([self.table1.c.myid], self.table1.c.myid == 5),
- select([self.table1.c.myid], self.table1.c.myid == 12),
+ select([self.table1.c.myid], self.table1.c.myid == 5),
+ select([self.table1.c.myid], self.table1.c.myid == 12),
)
- ), "mytable.myid IN ("\
- "SELECT mytable.myid FROM mytable WHERE mytable.myid = :myid_1 "\
- "UNION SELECT mytable.myid FROM mytable WHERE mytable.myid = :myid_2)")
+ ), "mytable.myid IN ("
+ "SELECT mytable.myid FROM mytable WHERE mytable.myid = :myid_1 "
+ "UNION SELECT mytable.myid FROM mytable WHERE mytable.myid = :myid_2)")
def test_in_27(self):
# test that putting a select in an IN clause does not
# blow away its ORDER BY clause
self.assert_compile(
select([self.table1, self.table2],
- self.table2.c.otherid.in_(
- select([self.table2.c.otherid],
- order_by=[self.table2.c.othername],
- limit=10, correlate=False)
- ),
+ self.table2.c.otherid.in_(
+ select([self.table2.c.otherid],
+ order_by=[self.table2.c.othername],
+ limit=10, correlate=False)
+ ),
from_obj=[self.table1.join(self.table2,
- self.table1.c.myid == self.table2.c.otherid)],
+ self.table1.c.myid == self.table2.c.otherid)],
order_by=[self.table1.c.myid]
),
"SELECT mytable.myid, "
- "myothertable.otherid, myothertable.othername FROM mytable "\
+ "myothertable.otherid, myothertable.othername FROM mytable "
"JOIN myothertable ON mytable.myid = myothertable.otherid "
- "WHERE myothertable.otherid IN (SELECT myothertable.otherid "\
+ "WHERE myothertable.otherid IN (SELECT myothertable.otherid "
"FROM myothertable ORDER BY myothertable.othername "
"LIMIT :param_1) ORDER BY mytable.myid",
{'param_1': 10}
@testing.emits_warning('.*empty sequence.*')
def test_in_29(self):
self.assert_compile(self.table1.c.myid.notin_([]),
- "mytable.myid = mytable.myid")
+ "mytable.myid = mytable.myid")
@testing.emits_warning('.*empty sequence.*')
def test_in_30(self):
self.assert_compile(~self.table1.c.myid.in_([]),
- "mytable.myid = mytable.myid")
+ "mytable.myid = mytable.myid")
class MathOperatorTest(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = 'default'
table1 = table('mytable',
- column('myid', Integer),
- )
+ column('myid', Integer),
+ )
def _test_math_op(self, py_op, sql_op):
for (lhs, rhs, res) in (
(self.table1.c.myid, 'b', 'mytable.myid %s :myid_1'),
(self.table1.c.myid, literal(2.7), 'mytable.myid %s :param_1'),
(self.table1.c.myid, self.table1.c.myid,
- 'mytable.myid %s mytable.myid'),
+ 'mytable.myid %s mytable.myid'),
(literal(5), 8, ':param_1 %s :param_2'),
(literal(6), self.table1.c.myid, ':param_1 %s mytable.myid'),
(literal(7), literal(5.5), ':param_1 %s :param_2'),
- ):
+ ):
self.assert_compile(py_op(lhs, rhs), res % sql_op)
def test_math_op_add(self):
else:
self._test_math_op(operator.div, '/')
+
class ComparisonOperatorTest(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = 'default'
table1 = table('mytable',
- column('myid', Integer),
- )
+ column('myid', Integer),
+ )
def test_pickle_operators_one(self):
clause = (self.table1.c.myid == 12) & \
- self.table1.c.myid.between(15, 20) & \
- self.table1.c.myid.like('hoho')
+ self.table1.c.myid.between(15, 20) & \
+ self.table1.c.myid.like('hoho')
eq_(str(clause), str(util.pickle.loads(util.pickle.dumps(clause))))
def test_pickle_operators_two(self):
(self.table1.c.myid, 'b', 'mytable.myid', ':myid_1'),
(self.table1.c.myid, literal('b'), 'mytable.myid', ':param_1'),
(self.table1.c.myid, self.table1.c.myid,
- 'mytable.myid', 'mytable.myid'),
+ 'mytable.myid', 'mytable.myid'),
(literal('a'), 'b', ':param_1', ':param_2'),
(literal('a'), self.table1.c.myid, ':param_1', 'mytable.myid'),
(literal('a'), literal('b'), ':param_1', ':param_2'),
(dt, literal('b'), ':param_2', ':param_1'),
(literal('b'), dt, ':param_1', ':param_2'),
- ):
+ ):
# the compiled clause should match either (e.g.):
# 'a' < 'b' -or- 'b' > 'a'.
def test_comparison_operators_ge(self):
self._test_comparison_op(operator.ge, '>=', '<=')
+
class NonZeroTest(fixtures.TestBase):
+
def _raises(self, expr):
assert_raises_message(
TypeError,
expr2 = (c1 > 5).label(None)
self._assert_false(expr1 == expr2)
+
class NegationTest(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = 'default'
table1 = table('mytable',
- column('myid', Integer),
- column('name', String),
- )
+ column('myid', Integer),
+ column('name', String),
+ )
def test_negate_operators_1(self):
for (py_op, op) in (
def test_negate_operators_2(self):
self.assert_compile(
- self.table1.select((self.table1.c.myid != 12) &
- ~(self.table1.c.name == 'john')),
- "SELECT mytable.myid, mytable.name FROM "
+ self.table1.select((self.table1.c.myid != 12) &
+ ~(self.table1.c.name == 'john')),
+ "SELECT mytable.myid, mytable.name FROM "
"mytable WHERE mytable.myid != :myid_1 "
"AND mytable.name != :name_1"
)
def test_negate_operators_3(self):
self.assert_compile(
- self.table1.select((self.table1.c.myid != 12) &
- ~(self.table1.c.name.between('jack', 'john'))),
- "SELECT mytable.myid, mytable.name FROM "
- "mytable WHERE mytable.myid != :myid_1 AND "\
- "mytable.name NOT BETWEEN :name_1 AND :name_2"
+ self.table1.select((self.table1.c.myid != 12) &
+ ~(self.table1.c.name.between('jack', 'john'))),
+ "SELECT mytable.myid, mytable.name FROM "
+ "mytable WHERE mytable.myid != :myid_1 AND "
+ "mytable.name NOT BETWEEN :name_1 AND :name_2"
)
def test_negate_operators_4(self):
self.assert_compile(
- self.table1.select((self.table1.c.myid != 12) &
- ~and_(self.table1.c.name == 'john',
- self.table1.c.name == 'ed',
- self.table1.c.name == 'fred')),
- "SELECT mytable.myid, mytable.name FROM "
- "mytable WHERE mytable.myid != :myid_1 AND "\
- "NOT (mytable.name = :name_1 AND mytable.name = :name_2 "
- "AND mytable.name = :name_3)"
+ self.table1.select((self.table1.c.myid != 12) &
+ ~and_(self.table1.c.name == 'john',
+ self.table1.c.name == 'ed',
+ self.table1.c.name == 'fred')),
+ "SELECT mytable.myid, mytable.name FROM "
+ "mytable WHERE mytable.myid != :myid_1 AND "
+ "NOT (mytable.name = :name_1 AND mytable.name = :name_2 "
+ "AND mytable.name = :name_3)"
)
def test_negate_operators_5(self):
self.assert_compile(
- self.table1.select((self.table1.c.myid != 12) & ~self.table1.c.name),
- "SELECT mytable.myid, mytable.name FROM "
- "mytable WHERE mytable.myid != :myid_1 AND NOT mytable.name"
- )
-
+ self.table1.select(
+ (self.table1.c.myid != 12) & ~self.table1.c.name),
+ "SELECT mytable.myid, mytable.name FROM "
+ "mytable WHERE mytable.myid != :myid_1 AND NOT mytable.name")
class LikeTest(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = 'default'
table1 = table('mytable',
- column('myid', Integer),
- column('name', String),
- )
+ column('myid', Integer),
+ column('name', String),
+ )
def test_like_1(self):
self.assert_compile(
- self.table1.c.myid.like('somstr'),
- "mytable.myid LIKE :myid_1")
+ self.table1.c.myid.like('somstr'),
+ "mytable.myid LIKE :myid_1")
def test_like_2(self):
self.assert_compile(
- ~self.table1.c.myid.like('somstr'),
- "mytable.myid NOT LIKE :myid_1")
+ ~self.table1.c.myid.like('somstr'),
+ "mytable.myid NOT LIKE :myid_1")
def test_like_3(self):
self.assert_compile(
- self.table1.c.myid.like('somstr', escape='\\'),
- "mytable.myid LIKE :myid_1 ESCAPE '\\'")
+ self.table1.c.myid.like('somstr', escape='\\'),
+ "mytable.myid LIKE :myid_1 ESCAPE '\\'")
def test_like_4(self):
self.assert_compile(
- ~self.table1.c.myid.like('somstr', escape='\\'),
- "mytable.myid NOT LIKE :myid_1 ESCAPE '\\'")
+ ~self.table1.c.myid.like('somstr', escape='\\'),
+ "mytable.myid NOT LIKE :myid_1 ESCAPE '\\'")
def test_like_5(self):
self.assert_compile(
- self.table1.c.myid.ilike('somstr', escape='\\'),
- "lower(mytable.myid) LIKE lower(:myid_1) ESCAPE '\\'")
+ self.table1.c.myid.ilike('somstr', escape='\\'),
+ "lower(mytable.myid) LIKE lower(:myid_1) ESCAPE '\\'")
def test_like_6(self):
self.assert_compile(
- ~self.table1.c.myid.ilike('somstr', escape='\\'),
- "lower(mytable.myid) NOT LIKE lower(:myid_1) ESCAPE '\\'")
+ ~self.table1.c.myid.ilike('somstr', escape='\\'),
+ "lower(mytable.myid) NOT LIKE lower(:myid_1) ESCAPE '\\'")
def test_like_7(self):
self.assert_compile(
- self.table1.c.myid.ilike('somstr', escape='\\'),
- "mytable.myid ILIKE %(myid_1)s ESCAPE '\\\\'",
- dialect=postgresql.dialect())
+ self.table1.c.myid.ilike('somstr', escape='\\'),
+ "mytable.myid ILIKE %(myid_1)s ESCAPE '\\\\'",
+ dialect=postgresql.dialect())
def test_like_8(self):
self.assert_compile(
- ~self.table1.c.myid.ilike('somstr', escape='\\'),
- "mytable.myid NOT ILIKE %(myid_1)s ESCAPE '\\\\'",
- dialect=postgresql.dialect())
+ ~self.table1.c.myid.ilike('somstr', escape='\\'),
+ "mytable.myid NOT ILIKE %(myid_1)s ESCAPE '\\\\'",
+ dialect=postgresql.dialect())
def test_like_9(self):
self.assert_compile(
- self.table1.c.name.ilike('%something%'),
- "lower(mytable.name) LIKE lower(:name_1)")
+ self.table1.c.name.ilike('%something%'),
+ "lower(mytable.name) LIKE lower(:name_1)")
def test_like_10(self):
self.assert_compile(
- self.table1.c.name.ilike('%something%'),
- "mytable.name ILIKE %(name_1)s",
- dialect=postgresql.dialect())
+ self.table1.c.name.ilike('%something%'),
+ "mytable.name ILIKE %(name_1)s",
+ dialect=postgresql.dialect())
def test_like_11(self):
self.assert_compile(
- ~self.table1.c.name.ilike('%something%'),
- "lower(mytable.name) NOT LIKE lower(:name_1)")
+ ~self.table1.c.name.ilike('%something%'),
+ "lower(mytable.name) NOT LIKE lower(:name_1)")
def test_like_12(self):
self.assert_compile(
- ~self.table1.c.name.ilike('%something%'),
- "mytable.name NOT ILIKE %(name_1)s",
- dialect=postgresql.dialect())
+ ~self.table1.c.name.ilike('%something%'),
+ "mytable.name NOT ILIKE %(name_1)s",
+ dialect=postgresql.dialect())
+
class BetweenTest(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = 'default'
table1 = table('mytable',
- column('myid', Integer),
- column('name', String),
- )
+ column('myid', Integer),
+ column('name', String),
+ )
def test_between_1(self):
self.assert_compile(
- self.table1.c.myid.between(1, 2),
- "mytable.myid BETWEEN :myid_1 AND :myid_2")
+ self.table1.c.myid.between(1, 2),
+ "mytable.myid BETWEEN :myid_1 AND :myid_2")
def test_between_2(self):
self.assert_compile(
- ~self.table1.c.myid.between(1, 2),
- "mytable.myid NOT BETWEEN :myid_1 AND :myid_2")
+ ~self.table1.c.myid.between(1, 2),
+ "mytable.myid NOT BETWEEN :myid_1 AND :myid_2")
def test_between_3(self):
self.assert_compile(
- self.table1.c.myid.between(1, 2, symmetric=True),
- "mytable.myid BETWEEN SYMMETRIC :myid_1 AND :myid_2")
+ self.table1.c.myid.between(1, 2, symmetric=True),
+ "mytable.myid BETWEEN SYMMETRIC :myid_1 AND :myid_2")
def test_between_4(self):
self.assert_compile(
- ~self.table1.c.myid.between(1, 2, symmetric=True),
- "mytable.myid NOT BETWEEN SYMMETRIC :myid_1 AND :myid_2")
+ ~self.table1.c.myid.between(1, 2, symmetric=True),
+ "mytable.myid NOT BETWEEN SYMMETRIC :myid_1 AND :myid_2")
def test_between_5(self):
self.assert_compile(
- between(self.table1.c.myid, 1, 2, symmetric=True),
- "mytable.myid BETWEEN SYMMETRIC :myid_1 AND :myid_2")
+ between(self.table1.c.myid, 1, 2, symmetric=True),
+ "mytable.myid BETWEEN SYMMETRIC :myid_1 AND :myid_2")
def test_between_6(self):
self.assert_compile(
- ~between(self.table1.c.myid, 1, 2, symmetric=True),
- "mytable.myid NOT BETWEEN SYMMETRIC :myid_1 AND :myid_2")
-
+ ~between(self.table1.c.myid, 1, 2, symmetric=True),
+ "mytable.myid NOT BETWEEN SYMMETRIC :myid_1 AND :myid_2")
class MatchTest(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = 'default'
table1 = table('mytable',
- column('myid', Integer),
- column('name', String),
- )
+ column('myid', Integer),
+ column('name', String),
+ )
def test_match_1(self):
self.assert_compile(self.table1.c.myid.match('somstr'),
- "mytable.myid MATCH ?",
- dialect=sqlite.dialect())
+ "mytable.myid MATCH ?",
+ dialect=sqlite.dialect())
def test_match_2(self):
- self.assert_compile(self.table1.c.myid.match('somstr'),
- "MATCH (mytable.myid) AGAINST (%s IN BOOLEAN MODE)",
- dialect=mysql.dialect())
+ self.assert_compile(
+ self.table1.c.myid.match('somstr'),
+ "MATCH (mytable.myid) AGAINST (%s IN BOOLEAN MODE)",
+ dialect=mysql.dialect())
def test_match_3(self):
self.assert_compile(self.table1.c.myid.match('somstr'),
- "CONTAINS (mytable.myid, :myid_1)",
- dialect=mssql.dialect())
+ "CONTAINS (mytable.myid, :myid_1)",
+ dialect=mssql.dialect())
def test_match_4(self):
self.assert_compile(self.table1.c.myid.match('somstr'),
- "mytable.myid @@ to_tsquery(%(myid_1)s)",
- dialect=postgresql.dialect())
+ "mytable.myid @@ to_tsquery(%(myid_1)s)",
+ dialect=postgresql.dialect())
def test_match_5(self):
self.assert_compile(self.table1.c.myid.match('somstr'),
- "CONTAINS (mytable.myid, :myid_1)",
- dialect=oracle.dialect())
+ "CONTAINS (mytable.myid, :myid_1)",
+ dialect=oracle.dialect())
+
class ComposedLikeOperatorsTest(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = 'default'
dialect=mysql.dialect()
)
+
class CustomOpTest(fixtures.TestBase):
+
def test_is_comparison(self):
c = column('x')
c2 = column('y')
assert operators.is_comparison(op1)
assert not operators.is_comparison(op2)
+
class TupleTypingTest(fixtures.TestBase):
def _assert_types(self, expr):
eq_(expr.clauses[2].type._type_affinity, LargeBinary()._type_affinity)
def test_type_coersion_on_eq(self):
- a, b, c = column('a', Integer), column('b', String), column('c', LargeBinary)
+ a, b, c = column(
+ 'a', Integer), column(
+ 'b', String), column(
+ 'c', LargeBinary)
t1 = tuple_(a, b, c)
expr = t1 == (3, 'hi', 'there')
self._assert_types(expr.right)
def test_type_coersion_on_in(self):
- a, b, c = column('a', Integer), column('b', String), column('c', LargeBinary)
+ a, b, c = column(
+ 'a', Integer), column(
+ 'b', String), column(
+ 'c', LargeBinary)
t1 = tuple_(a, b, c)
expr = t1.in_([(3, 'hi', 'there'), (4, 'Q', 'P')])
eq_(len(expr.right.clauses), 2)
Column('user_id', Integer, ForeignKey('query_users.user_id')),
Column('address', String(30)),
test_needs_acid=True
- )
+ )
users2 = Table(
'u2', metadata,
eng = engines.testing_engine()
class ExcCtx(sqlite.base.SQLiteExecutionContext):
+
def get_lastrowid(self):
return 0
eng.dialect.execution_ctx_cls = ExcCtx
row = testing.db.execute(select([1])).first()
class unprintable(object):
+
def __str__(self):
raise ValueError("nope")
class TableInsertTest(fixtures.TablesTest):
+
"""test for consistent insert behavior across dialects
regarding the inline=True flag, lower-case 't' tables.
class CompoundTest(fixtures.TestBase):
+
"""test compound statements like UNION, INTERSECT, particularly their
ability to nest on different databases."""
class JoinTest(fixtures.TestBase):
+
"""Tests join execution.
The compiled SQL emitted by the dialect might be ANSI joins or
"""Execute a statement and assert that rows returned equal expected."""
found = sorted([tuple(row)
- for row in statement.execute().fetchall()])
+ for row in statement.execute().fetchall()])
eq_(found, sorted(expected))
from sqlalchemy.sql.elements import quoted_name, _truncated_label, _anonymous_label
from sqlalchemy.testing.util import picklers
+
class QuoteExecTest(fixtures.TestBase):
__backend__ = True
metadata = MetaData(testing.db)
table1 = Table('WorstCase1', metadata,
- Column('lowercase', Integer, primary_key=True),
- Column('UPPERCASE', Integer),
- Column('MixedCase', Integer),
- Column('ASC', Integer, key='a123'))
+ Column('lowercase', Integer, primary_key=True),
+ Column('UPPERCASE', Integer),
+ Column('MixedCase', Integer),
+ Column('ASC', Integer, key='a123'))
table2 = Table('WorstCase2', metadata,
- Column('desc', Integer, primary_key=True, key='d123'),
- Column('Union', Integer, key='u123'),
- Column('MixedCase', Integer))
+ Column('desc', Integer, primary_key=True, key='d123'),
+ Column('Union', Integer, key='u123'),
+ Column('MixedCase', Integer))
table1.create()
table2.create()
else:
testing.db.execute("CREATE TABLE tab1 (id INTEGER)")
testing.db.execute('CREATE TABLE %s (id INTEGER)' %
- preparer.quote_identifier("tab2"))
+ preparer.quote_identifier("tab2"))
testing.db.execute('CREATE TABLE %s (id INTEGER)' %
- preparer.quote_identifier("TAB3"))
+ preparer.quote_identifier("TAB3"))
testing.db.execute('CREATE TABLE %s (id INTEGER)' %
- preparer.quote_identifier("TAB4"))
+ preparer.quote_identifier("TAB4"))
t1 = Table('tab1', self.metadata,
- Column('id', Integer, primary_key=True),
- )
+ Column('id', Integer, primary_key=True),
+ )
t2 = Table('tab2', self.metadata,
- Column('id', Integer, primary_key=True),
- quote=True
- )
+ Column('id', Integer, primary_key=True),
+ quote=True
+ )
t3 = Table('TAB3', self.metadata,
- Column('id', Integer, primary_key=True),
- )
+ Column('id', Integer, primary_key=True),
+ )
t4 = Table('TAB4', self.metadata,
- Column('id', Integer, primary_key=True),
- quote=True)
+ Column('id', Integer, primary_key=True),
+ quote=True)
insp = inspect(testing.db)
assert testing.db.has_table(t1.name)
assert testing.db.has_table(t4.name)
eq_([c['name'] for c in insp.get_columns(t4.name)], ['id'])
-
-
def test_basic(self):
table1.insert().execute(
{'lowercase': 1, 'UPPERCASE': 2, 'MixedCase': 3, 'a123': 4},
result = select(columns, use_labels=True).execute().fetchall()
assert(result == [(1, 2, 3), (2, 2, 3), (4, 3, 2)])
+
class QuoteTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
metadata = MetaData(testing.db)
table1 = Table('WorstCase1', metadata,
- Column('lowercase', Integer, primary_key=True),
- Column('UPPERCASE', Integer),
- Column('MixedCase', Integer),
- Column('ASC', Integer, key='a123'))
+ Column('lowercase', Integer, primary_key=True),
+ Column('UPPERCASE', Integer),
+ Column('MixedCase', Integer),
+ Column('ASC', Integer, key='a123'))
table2 = Table('WorstCase2', metadata,
- Column('desc', Integer, primary_key=True, key='d123'),
- Column('Union', Integer, key='u123'),
- Column('MixedCase', Integer))
+ Column('desc', Integer, primary_key=True, key='d123'),
+ Column('Union', Integer, key='u123'),
+ Column('MixedCase', Integer))
@testing.crashes('oracle', 'FIXME: unknown, verify not fails_on')
@testing.requires.subqueries
self.assert_compile(
table1.select(distinct=True).alias('LaLa').select(),
'SELECT '
- '"LaLa".lowercase, '
- '"LaLa"."UPPERCASE", '
- '"LaLa"."MixedCase", '
- '"LaLa"."ASC" '
+ '"LaLa".lowercase, '
+ '"LaLa"."UPPERCASE", '
+ '"LaLa"."MixedCase", '
+ '"LaLa"."ASC" '
'FROM ('
- 'SELECT DISTINCT '
- '"WorstCase1".lowercase AS lowercase, '
- '"WorstCase1"."UPPERCASE" AS "UPPERCASE", '
- '"WorstCase1"."MixedCase" AS "MixedCase", '
- '"WorstCase1"."ASC" AS "ASC" '
- 'FROM "WorstCase1"'
+ 'SELECT DISTINCT '
+ '"WorstCase1".lowercase AS lowercase, '
+ '"WorstCase1"."UPPERCASE" AS "UPPERCASE", '
+ '"WorstCase1"."MixedCase" AS "MixedCase", '
+ '"WorstCase1"."ASC" AS "ASC" '
+ 'FROM "WorstCase1"'
') AS "LaLa"'
)
# Create table with quote defaults
metadata = MetaData()
t1 = Table('t1', metadata,
- Column('col1', Integer),
- schema='foo')
+ Column('col1', Integer),
+ schema='foo')
# Note that the names are not quoted b/c they are all lower case
result = 'CREATE TABLE foo.t1 (col1 INTEGER)'
# Create the same table with quotes set to True now
metadata = MetaData()
t1 = Table('t1', metadata,
- Column('col1', Integer, quote=True),
- schema='foo', quote=True, quote_schema=True)
+ Column('col1', Integer, quote=True),
+ schema='foo', quote=True, quote_schema=True)
# Note that the names are now quoted
result = 'CREATE TABLE "foo"."t1" ("col1" INTEGER)'
# Create table with quote defaults
metadata = MetaData()
t1 = Table('TABLE1', metadata,
- Column('COL1', Integer),
- schema='FOO')
+ Column('COL1', Integer),
+ schema='FOO')
# Note that the names are quoted b/c they are not all lower case
result = 'CREATE TABLE "FOO"."TABLE1" ("COL1" INTEGER)'
# Create the same table with quotes set to False now
metadata = MetaData()
t1 = Table('TABLE1', metadata,
- Column('COL1', Integer, quote=False),
- schema='FOO', quote=False, quote_schema=False)
+ Column('COL1', Integer, quote=False),
+ schema='FOO', quote=False, quote_schema=False)
# Note that the names are now unquoted
result = 'CREATE TABLE FOO.TABLE1 (COL1 INTEGER)'
# Create table with quote defaults
metadata = MetaData()
t1 = Table('Table1', metadata,
- Column('Col1', Integer),
- schema='Foo')
+ Column('Col1', Integer),
+ schema='Foo')
# Note that the names are quoted b/c they are not all lower case
result = 'CREATE TABLE "Foo"."Table1" ("Col1" INTEGER)'
# Create the same table with quotes set to False now
metadata = MetaData()
t1 = Table('Table1', metadata,
- Column('Col1', Integer, quote=False),
- schema='Foo', quote=False, quote_schema=False)
+ Column('Col1', Integer, quote=False),
+ schema='Foo', quote=False, quote_schema=False)
# Note that the names are now unquoted
result = 'CREATE TABLE Foo.Table1 (Col1 INTEGER)'
# Create table with quote defaults
metadata = MetaData()
t1 = Table('35table', metadata,
- Column('25column', Integer),
- schema='45schema')
+ Column('25column', Integer),
+ schema='45schema')
# Note that the names are quoted b/c the initial
# character is in ['$','0', '1' ... '9']
# Create the same table with quotes set to False now
metadata = MetaData()
t1 = Table('35table', metadata,
- Column('25column', Integer, quote=False),
- schema='45schema', quote=False, quote_schema=False)
+ Column('25column', Integer, quote=False),
+ schema='45schema', quote=False, quote_schema=False)
# Note that the names are now unquoted
result = 'CREATE TABLE 45schema.35table (25column INTEGER)'
# Create table with quote defaults
metadata = MetaData()
t1 = Table('$table', metadata,
- Column('$column', Integer),
- schema='$schema')
+ Column('$column', Integer),
+ schema='$schema')
# Note that the names are quoted b/c the initial
# character is in ['$','0', '1' ... '9']
# Create the same table with quotes set to False now
metadata = MetaData()
t1 = Table('$table', metadata,
- Column('$column', Integer, quote=False),
- schema='$schema', quote=False, quote_schema=False)
+ Column('$column', Integer, quote=False),
+ schema='$schema', quote=False, quote_schema=False)
# Note that the names are now unquoted
result = 'CREATE TABLE $schema.$table ($column INTEGER)'
# Create table with quote defaults
metadata = MetaData()
table = Table('foreign', metadata,
- Column('col1', Integer),
- Column('from', Integer),
- Column('order', Integer),
- schema='create')
+ Column('col1', Integer),
+ Column('from', Integer),
+ Column('order', Integer),
+ schema='create')
# Note that the names are quoted b/c they are reserved words
x = select([table.c.col1, table.c['from'], table.c.order])
self.assert_compile(x,
- 'SELECT '
- '"create"."foreign".col1, '
- '"create"."foreign"."from", '
- '"create"."foreign"."order" '
- 'FROM "create"."foreign"'
- )
+ 'SELECT '
+ '"create"."foreign".col1, '
+ '"create"."foreign"."from", '
+ '"create"."foreign"."order" '
+ 'FROM "create"."foreign"'
+ )
# Create the same table with quotes set to False now
metadata = MetaData()
table = Table('foreign', metadata,
- Column('col1', Integer),
- Column('from', Integer, quote=False),
- Column('order', Integer, quote=False),
- schema='create', quote=False, quote_schema=False)
+ Column('col1', Integer),
+ Column('from', Integer, quote=False),
+ Column('order', Integer, quote=False),
+ schema='create', quote=False, quote_schema=False)
# Note that the names are now unquoted
x = select([table.c.col1, table.c['from'], table.c.order])
self.assert_compile(x,
- 'SELECT '
- 'create.foreign.col1, '
- 'create.foreign.from, '
- 'create.foreign.order '
- 'FROM create.foreign'
- )
+ 'SELECT '
+ 'create.foreign.col1, '
+ 'create.foreign.from, '
+ 'create.foreign.order '
+ 'FROM create.foreign'
+ )
def test_subquery_one(self):
# Lower case names, should not quote
metadata = MetaData()
t1 = Table('t1', metadata,
- Column('col1', Integer),
- schema='foo')
+ Column('col1', Integer),
+ schema='foo')
a = t1.select().alias('anon')
b = select([1], a.c.col1 == 2, from_obj=a)
self.assert_compile(b,
- 'SELECT 1 '
- 'FROM ('
- 'SELECT '
- 'foo.t1.col1 AS col1 '
- 'FROM '
- 'foo.t1'
- ') AS anon '
- 'WHERE anon.col1 = :col1_1'
- )
+ 'SELECT 1 '
+ 'FROM ('
+ 'SELECT '
+ 'foo.t1.col1 AS col1 '
+ 'FROM '
+ 'foo.t1'
+ ') AS anon '
+ 'WHERE anon.col1 = :col1_1'
+ )
def test_subquery_two(self):
# Lower case names, quotes on, should quote
metadata = MetaData()
t1 = Table('t1', metadata,
- Column('col1', Integer, quote=True),
- schema='foo', quote=True, quote_schema=True)
+ Column('col1', Integer, quote=True),
+ schema='foo', quote=True, quote_schema=True)
a = t1.select().alias('anon')
b = select([1], a.c.col1 == 2, from_obj=a)
self.assert_compile(b,
- 'SELECT 1 '
- 'FROM ('
- 'SELECT '
- '"foo"."t1"."col1" AS "col1" '
- 'FROM '
- '"foo"."t1"'
- ') AS anon '
- 'WHERE anon."col1" = :col1_1'
- )
+ 'SELECT 1 '
+ 'FROM ('
+ 'SELECT '
+ '"foo"."t1"."col1" AS "col1" '
+ 'FROM '
+ '"foo"."t1"'
+ ') AS anon '
+ 'WHERE anon."col1" = :col1_1'
+ )
def test_subquery_three(self):
# Not lower case names, should quote
metadata = MetaData()
t1 = Table('T1', metadata,
- Column('Col1', Integer),
- schema='Foo')
+ Column('Col1', Integer),
+ schema='Foo')
a = t1.select().alias('Anon')
b = select([1], a.c.Col1 == 2, from_obj=a)
self.assert_compile(b,
- 'SELECT 1 '
- 'FROM ('
- 'SELECT '
- '"Foo"."T1"."Col1" AS "Col1" '
- 'FROM '
- '"Foo"."T1"'
- ') AS "Anon" '
- 'WHERE '
- '"Anon"."Col1" = :Col1_1'
- )
+ 'SELECT 1 '
+ 'FROM ('
+ 'SELECT '
+ '"Foo"."T1"."Col1" AS "Col1" '
+ 'FROM '
+ '"Foo"."T1"'
+ ') AS "Anon" '
+ 'WHERE '
+ '"Anon"."Col1" = :Col1_1'
+ )
def test_subquery_four(self):
# Not lower case names, quotes off, should not quote
metadata = MetaData()
t1 = Table('T1', metadata,
- Column('Col1', Integer, quote=False),
- schema='Foo', quote=False, quote_schema=False)
+ Column('Col1', Integer, quote=False),
+ schema='Foo', quote=False, quote_schema=False)
a = t1.select().alias('Anon')
b = select([1], a.c.Col1 == 2, from_obj=a)
self.assert_compile(b,
- 'SELECT 1 '
- 'FROM ('
- 'SELECT '
- 'Foo.T1.Col1 AS Col1 '
- 'FROM '
- 'Foo.T1'
- ') AS "Anon" '
- 'WHERE '
- '"Anon".Col1 = :Col1_1'
- )
+ 'SELECT 1 '
+ 'FROM ('
+ 'SELECT '
+ 'Foo.T1.Col1 AS Col1 '
+ 'FROM '
+ 'Foo.T1'
+ ') AS "Anon" '
+ 'WHERE '
+ '"Anon".Col1 = :Col1_1'
+ )
def test_simple_order_by_label(self):
m = MetaData()
# Lower case names, should not quote
metadata = MetaData()
t1 = Table('t1', metadata,
- Column('col1', Integer))
+ Column('col1', Integer))
t2 = Table('t2', metadata,
- Column('col1', Integer),
- Column('t1col1', Integer, ForeignKey('t1.col1')))
+ Column('col1', Integer),
+ Column('t1col1', Integer, ForeignKey('t1.col1')))
self.assert_compile(t2.join(t1).select(),
- 'SELECT '
- 't2.col1, t2.t1col1, t1.col1 '
- 'FROM '
- 't2 '
- 'JOIN '
- 't1 ON t1.col1 = t2.t1col1'
- )
+ 'SELECT '
+ 't2.col1, t2.t1col1, t1.col1 '
+ 'FROM '
+ 't2 '
+ 'JOIN '
+ 't1 ON t1.col1 = t2.t1col1'
+ )
# Lower case names, quotes on, should quote
metadata = MetaData()
t1 = Table('t1', metadata,
- Column('col1', Integer, quote=True),
- quote=True)
- t2 = Table('t2', metadata,
- Column('col1', Integer, quote=True),
- Column('t1col1', Integer, ForeignKey('t1.col1'), quote=True),
- quote=True)
+ Column('col1', Integer, quote=True),
+ quote=True)
+ t2 = Table(
+ 't2',
+ metadata,
+ Column(
+ 'col1',
+ Integer,
+ quote=True),
+ Column(
+ 't1col1',
+ Integer,
+ ForeignKey('t1.col1'),
+ quote=True),
+ quote=True)
self.assert_compile(t2.join(t1).select(),
- 'SELECT '
- '"t2"."col1", "t2"."t1col1", "t1"."col1" '
- 'FROM '
- '"t2" '
- 'JOIN '
- '"t1" ON "t1"."col1" = "t2"."t1col1"'
- )
+ 'SELECT '
+ '"t2"."col1", "t2"."t1col1", "t1"."col1" '
+ 'FROM '
+ '"t2" '
+ 'JOIN '
+ '"t1" ON "t1"."col1" = "t2"."t1col1"'
+ )
# Not lower case names, should quote
metadata = MetaData()
t1 = Table('T1', metadata,
- Column('Col1', Integer))
+ Column('Col1', Integer))
t2 = Table('T2', metadata,
- Column('Col1', Integer),
- Column('T1Col1', Integer, ForeignKey('T1.Col1')))
+ Column('Col1', Integer),
+ Column('T1Col1', Integer, ForeignKey('T1.Col1')))
self.assert_compile(t2.join(t1).select(),
- 'SELECT '
- '"T2"."Col1", "T2"."T1Col1", "T1"."Col1" '
- 'FROM '
- '"T2" '
- 'JOIN '
- '"T1" ON "T1"."Col1" = "T2"."T1Col1"'
- )
+ 'SELECT '
+ '"T2"."Col1", "T2"."T1Col1", "T1"."Col1" '
+ 'FROM '
+ '"T2" '
+ 'JOIN '
+ '"T1" ON "T1"."Col1" = "T2"."T1Col1"'
+ )
# Not lower case names, quotes off, should not quote
metadata = MetaData()
t1 = Table('T1', metadata,
- Column('Col1', Integer, quote=False),
- quote=False)
- t2 = Table('T2', metadata,
- Column('Col1', Integer, quote=False),
- Column('T1Col1', Integer, ForeignKey('T1.Col1'), quote=False),
- quote=False)
+ Column('Col1', Integer, quote=False),
+ quote=False)
+ t2 = Table(
+ 'T2',
+ metadata,
+ Column(
+ 'Col1',
+ Integer,
+ quote=False),
+ Column(
+ 'T1Col1',
+ Integer,
+ ForeignKey('T1.Col1'),
+ quote=False),
+ quote=False)
self.assert_compile(t2.join(t1).select(),
- 'SELECT '
- 'T2.Col1, T2.T1Col1, T1.Col1 '
- 'FROM '
- 'T2 '
- 'JOIN '
- 'T1 ON T1.Col1 = T2.T1Col1'
- )
+ 'SELECT '
+ 'T2.Col1, T2.T1Col1, T1.Col1 '
+ 'FROM '
+ 'T2 '
+ 'JOIN '
+ 'T1 ON T1.Col1 = T2.T1Col1'
+ )
def test_label_and_alias(self):
# Lower case names, should not quote
metadata = MetaData()
table = Table('t1', metadata,
- Column('col1', Integer))
+ Column('col1', Integer))
x = select([table.c.col1.label('label1')]).alias('alias1')
self.assert_compile(select([x.c.label1]),
- 'SELECT '
- 'alias1.label1 '
- 'FROM ('
- 'SELECT '
- 't1.col1 AS label1 '
- 'FROM t1'
- ') AS alias1'
- )
+ 'SELECT '
+ 'alias1.label1 '
+ 'FROM ('
+ 'SELECT '
+ 't1.col1 AS label1 '
+ 'FROM t1'
+ ') AS alias1'
+ )
# Not lower case names, should quote
metadata = MetaData()
table = Table('T1', metadata,
- Column('Col1', Integer))
+ Column('Col1', Integer))
x = select([table.c.Col1.label('Label1')]).alias('Alias1')
self.assert_compile(select([x.c.Label1]),
- 'SELECT '
- '"Alias1"."Label1" '
- 'FROM ('
- 'SELECT '
- '"T1"."Col1" AS "Label1" '
- 'FROM "T1"'
- ') AS "Alias1"'
- )
+ 'SELECT '
+ '"Alias1"."Label1" '
+ 'FROM ('
+ 'SELECT '
+ '"T1"."Col1" AS "Label1" '
+ 'FROM "T1"'
+ ') AS "Alias1"'
+ )
def test_literal_column_already_with_quotes(self):
# Lower case names
metadata = MetaData()
table = Table('t1', metadata,
- Column('col1', Integer))
+ Column('col1', Integer))
# Note that 'col1' is already quoted (literal_column)
columns = [sql.literal_column("'col1'").label('label1')]
x = select(columns, from_obj=[table]).alias('alias1')
x = x.select()
self.assert_compile(x,
- 'SELECT '
- 'alias1.label1 '
- 'FROM ('
- 'SELECT '
- '\'col1\' AS label1 '
- 'FROM t1'
- ') AS alias1'
- )
+ 'SELECT '
+ 'alias1.label1 '
+ 'FROM ('
+ 'SELECT '
+ '\'col1\' AS label1 '
+ 'FROM t1'
+ ') AS alias1'
+ )
# Not lower case names
metadata = MetaData()
table = Table('T1', metadata,
- Column('Col1', Integer))
+ Column('Col1', Integer))
# Note that 'Col1' is already quoted (literal_column)
columns = [sql.literal_column("'Col1'").label('Label1')]
x = select(columns, from_obj=[table]).alias('Alias1')
x = x.select()
self.assert_compile(x,
- 'SELECT '
- '"Alias1"."Label1" '
- 'FROM ('
- 'SELECT '
- '\'Col1\' AS "Label1" '
- 'FROM "T1"'
- ') AS "Alias1"'
- )
+ 'SELECT '
+ '"Alias1"."Label1" '
+ 'FROM ('
+ 'SELECT '
+ '\'Col1\' AS "Label1" '
+ 'FROM "T1"'
+ ') AS "Alias1"'
+ )
def test_apply_labels_should_quote(self):
# Not lower case names, should quote
metadata = MetaData()
t1 = Table('T1', metadata,
- Column('Col1', Integer),
- schema='Foo')
+ Column('Col1', Integer),
+ schema='Foo')
self.assert_compile(t1.select().apply_labels(),
- 'SELECT '
- '"Foo"."T1"."Col1" AS "Foo_T1_Col1" '
- 'FROM '
- '"Foo"."T1"'
- )
+ 'SELECT '
+ '"Foo"."T1"."Col1" AS "Foo_T1_Col1" '
+ 'FROM '
+ '"Foo"."T1"'
+ )
def test_apply_labels_shouldnt_quote(self):
# Not lower case names, quotes off
metadata = MetaData()
t1 = Table('T1', metadata,
- Column('Col1', Integer, quote=False),
- schema='Foo', quote=False, quote_schema=False)
+ Column('Col1', Integer, quote=False),
+ schema='Foo', quote=False, quote_schema=False)
# TODO: is this what we really want here ?
# what if table/schema *are* quoted?
self.assert_compile(t1.select().apply_labels(),
- 'SELECT '
- 'Foo.T1.Col1 AS Foo_T1_Col1 '
- 'FROM '
- 'Foo.T1'
- )
+ 'SELECT '
+ 'Foo.T1.Col1 AS Foo_T1_Col1 '
+ 'FROM '
+ 'Foo.T1'
+ )
def test_quote_flag_propagate_check_constraint(self):
m = MetaData()
'SELECT "t2".x AS "t2_x" FROM "t2"'
)
+
class PreparerTest(fixtures.TestBase):
+
"""Test the db-agnostic quoting services of IdentifierPreparer."""
def test_unformat(self):
a_eq(unformat('`foo`.bar'), ['foo', 'bar'])
a_eq(unformat('`foo`.`b``a``r`.`baz`'), ['foo', 'b`a`r', 'baz'])
+
class QuotedIdentTest(fixtures.TestBase):
+
def test_concat_quotetrue(self):
q1 = quoted_name("x", True)
self._assert_not_quoted("y" + q1)
def _assert_not_quoted(self, value):
assert not isinstance(value, quoted_name)
-
from sqlalchemy.testing.schema import Table, Column
from sqlalchemy.types import TypeDecorator
from sqlalchemy.testing import fixtures, AssertsExecutionResults, engines, \
- assert_raises_message
+ assert_raises_message
from sqlalchemy import exc as sa_exc
import itertools
+
class ReturningTest(fixtures.TestBase, AssertsExecutionResults):
__requires__ = 'returning',
__backend__ = True
return None
return value + "BAR"
- table = Table('tables', meta,
- Column('id', Integer, primary_key=True, test_needs_autoincrement=True),
- Column('persons', Integer),
- Column('full', Boolean),
- Column('goofy', GoofyType(50))
- )
+ table = Table(
+ 'tables', meta, Column(
+ 'id', Integer, primary_key=True, test_needs_autoincrement=True), Column(
+ 'persons', Integer), Column(
+ 'full', Boolean), Column(
+ 'goofy', GoofyType(50)))
table.create(checkfirst=True)
def teardown(self):
table.drop()
def test_column_targeting(self):
- result = table.insert().returning(table.c.id, table.c.full).execute({'persons': 1, 'full': False})
+ result = table.insert().returning(
+ table.c.id, table.c.full).execute({'persons': 1, 'full': False})
row = result.first()
assert row[table.c.id] == row['id'] == 1
assert row[table.c.full] == row['full'] == False
result = table.insert().values(persons=5, full=True, goofy="somegoofy").\
- returning(table.c.persons, table.c.full, table.c.goofy).execute()
+ returning(table.c.persons, table.c.full, table.c.goofy).execute()
row = result.first()
assert row[table.c.persons] == row['persons'] == 5
- assert row[table.c.full] == row['full'] == True
+ assert row[table.c.full] == row['full']
eq_(row[table.c.goofy], row['goofy'])
eq_(row['goofy'], "FOOsomegoofyBAR")
@testing.fails_on('firebird', "fb can't handle returning x AS y")
def test_labeling(self):
result = table.insert().values(persons=6).\
- returning(table.c.persons.label('lala')).execute()
+ returning(table.c.persons.label('lala')).execute()
row = result.first()
assert row['lala'] == 6
- @testing.fails_on('firebird', "fb/kintersbasdb can't handle the bind params")
+ @testing.fails_on(
+ 'firebird',
+ "fb/kintersbasdb can't handle the bind params")
@testing.fails_on('oracle+zxjdbc', "JDBC driver bug")
def test_anon_expressions(self):
result = table.insert().values(goofy="someOTHERgoofy").\
- returning(func.lower(table.c.goofy, type_=GoofyType)).execute()
+ returning(func.lower(table.c.goofy, type_=GoofyType)).execute()
row = result.first()
eq_(row[0], "foosomeothergoofyBAR")
result = table.insert().values(persons=12).\
- returning(table.c.persons + 18).execute()
+ returning(table.c.persons + 18).execute()
row = result.first()
eq_(row[0], 30)
def test_update_returning(self):
- table.insert().execute([{'persons': 5, 'full': False}, {'persons': 3, 'full': False}])
+ table.insert().execute(
+ [{'persons': 5, 'full': False}, {'persons': 3, 'full': False}])
- result = table.update(table.c.persons > 4, dict(full=True)).returning(table.c.id).execute()
+ result = table.update(
+ table.c.persons > 4, dict(
+ full=True)).returning(
+ table.c.id).execute()
eq_(result.fetchall(), [(1,)])
- result2 = select([table.c.id, table.c.full]).order_by(table.c.id).execute()
+ result2 = select([table.c.id, table.c.full]).order_by(
+ table.c.id).execute()
eq_(result2.fetchall(), [(1, True), (2, False)])
def test_insert_returning(self):
- result = table.insert().returning(table.c.id).execute({'persons': 1, 'full': False})
+ result = table.insert().returning(
+ table.c.id).execute({'persons': 1, 'full': False})
eq_(result.fetchall(), [(1,)])
@testing.requires.multivalues_inserts
def test_multirow_returning(self):
ins = table.insert().returning(table.c.id, table.c.persons).values(
- [
- {'persons': 1, 'full': False},
- {'persons': 2, 'full': True},
- {'persons': 3, 'full': False},
- ]
- )
+ [
+ {'persons': 1, 'full': False},
+ {'persons': 2, 'full': True},
+ {'persons': 3, 'full': False},
+ ]
+ )
result = testing.db.execute(ins)
eq_(
- result.fetchall(),
- [(1, 1), (2, 2), (3, 3)]
+ result.fetchall(),
+ [(1, 1), (2, 2), (3, 3)]
)
def test_no_ipk_on_returning(self):
result = testing.db.execute(
- table.insert().returning(table.c.id),
- {'persons': 1, 'full': False}
- )
+ table.insert().returning(table.c.id),
+ {'persons': 1, 'full': False}
+ )
assert_raises_message(
sa_exc.InvalidRequestError,
"Can't call inserted_primary_key when returning\(\) is used.",
else:
literal_true = "1"
- result4 = testing.db.execute('insert into tables (id, persons, "full") '
- 'values (5, 10, %s) returning persons' % literal_true)
+ result4 = testing.db.execute(
+ 'insert into tables (id, persons, "full") '
+ 'values (5, 10, %s) returning persons' %
+ literal_true)
eq_([dict(row) for row in result4], [{'persons': 10}])
def test_delete_returning(self):
- table.insert().execute([{'persons': 5, 'full': False}, {'persons': 3, 'full': False}])
+ table.insert().execute(
+ [{'persons': 5, 'full': False}, {'persons': 3, 'full': False}])
- result = table.delete(table.c.persons > 4).returning(table.c.id).execute()
+ result = table.delete(
+ table.c.persons > 4).returning(
+ table.c.id).execute()
eq_(result.fetchall(), [(1,)])
- result2 = select([table.c.id, table.c.full]).order_by(table.c.id).execute()
- eq_(result2.fetchall(), [(2, False),])
+ result2 = select([table.c.id, table.c.full]).order_by(
+ table.c.id).execute()
+ eq_(result2.fetchall(), [(2, False), ])
+
class SequenceReturningTest(fixtures.TestBase):
__requires__ = 'returning', 'sequences'
global table, seq
seq = Sequence('tid_seq')
table = Table('tables', meta,
- Column('id', Integer, seq, primary_key=True),
- Column('data', String(50))
- )
+ Column('id', Integer, seq, primary_key=True),
+ Column('data', String(50))
+ )
table.create(checkfirst=True)
def teardown(self):
assert r.first() == (1, )
assert seq.execute() == 2
+
class KeyReturningTest(fixtures.TestBase, AssertsExecutionResults):
+
"""test returning() works with columns that define 'key'."""
__requires__ = 'returning',
meta = MetaData(testing.db)
global table
- table = Table('tables', meta,
- Column('id', Integer, primary_key=True, key='foo_id', test_needs_autoincrement=True),
- Column('data', String(20)),
+ table = Table(
+ 'tables',
+ meta,
+ Column(
+ 'id',
+ Integer,
+ primary_key=True,
+ key='foo_id',
+ test_needs_autoincrement=True),
+ Column(
+ 'data',
+ String(20)),
)
table.create(checkfirst=True)
@testing.exclude('firebird', '<', (2, 0), '2.0+ feature')
@testing.exclude('postgresql', '<', (8, 2), '8.2+ feature')
def test_insert(self):
- result = table.insert().returning(table.c.foo_id).execute(data='somedata')
+ result = table.insert().returning(
+ table.c.foo_id).execute(
+ data='somedata')
row = result.first()
assert row[table.c.foo_id] == row['id'] == 1
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())
- )
+ 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()))
def test_chained_insert_pk(self):
t1 = self.tables.t1
result = testing.db.execute(
- t1.insert().values(upddef=1).return_defaults(t1.c.insdef)
- )
+ t1.insert().values(upddef=1).return_defaults(t1.c.insdef)
+ )
eq_(
[result.returned_defaults[k] for k in (t1.c.id, t1.c.insdef)],
[1, 0]
def test_arg_insert_pk(self):
t1 = self.tables.t1
result = testing.db.execute(
- t1.insert(return_defaults=[t1.c.insdef]).values(upddef=1)
- )
+ t1.insert(return_defaults=[t1.c.insdef]).values(upddef=1)
+ )
eq_(
[result.returned_defaults[k] for k in (t1.c.id, t1.c.insdef)],
[1, 0]
def test_chained_update_pk(self):
t1 = self.tables.t1
testing.db.execute(
- t1.insert().values(upddef=1)
- )
+ t1.insert().values(upddef=1)
+ )
result = testing.db.execute(t1.update().values(data='d1').
- return_defaults(t1.c.upddef))
+ return_defaults(t1.c.upddef))
eq_(
[result.returned_defaults[k] for k in (t1.c.upddef,)],
[1]
def test_arg_update_pk(self):
t1 = self.tables.t1
testing.db.execute(
- t1.insert().values(upddef=1)
- )
+ t1.insert().values(upddef=1)
+ )
result = testing.db.execute(t1.update(return_defaults=[t1.c.upddef]).
- values(data='d1'))
+ values(data='d1'))
eq_(
[result.returned_defaults[k] for k in (t1.c.upddef,)],
[1]
t1 = self.tables.t1
result = testing.db.execute(
- t1.insert().values(upddef=1).return_defaults(t1.c.data)
- )
+ t1.insert().values(upddef=1).return_defaults(t1.c.data)
+ )
eq_(
[result.returned_defaults[k] for k in (t1.c.id, t1.c.data,)],
[1, None]
t1 = self.tables.t1
testing.db.execute(
- t1.insert().values(upddef=1)
- )
- result = testing.db.execute(t1.update().
- values(upddef=2).return_defaults(t1.c.data))
+ t1.insert().values(upddef=1)
+ )
+ result = testing.db.execute(
+ t1.update(). values(
+ upddef=2).return_defaults(
+ t1.c.data))
eq_(
[result.returned_defaults[k] for k in (t1.c.data,)],
[None]
def test_insert_non_default_plus_default(self):
t1 = self.tables.t1
result = testing.db.execute(
- t1.insert().values(upddef=1).return_defaults(
- t1.c.data, t1.c.insdef)
- )
+ t1.insert().values(upddef=1).return_defaults(
+ t1.c.data, t1.c.insdef)
+ )
eq_(
dict(result.returned_defaults),
{"id": 1, "data": None, "insdef": 0}
def test_update_non_default_plus_default(self):
t1 = self.tables.t1
testing.db.execute(
- t1.insert().values(upddef=1)
- )
+ t1.insert().values(upddef=1)
+ )
result = testing.db.execute(t1.update().
- values(insdef=2).return_defaults(
- t1.c.data, t1.c.upddef))
+ values(insdef=2).return_defaults(
+ t1.c.data, t1.c.upddef))
eq_(
dict(result.returned_defaults),
{"data": None, 'upddef': 1}
)
+
class ImplicitReturningFlag(fixtures.TestBase):
__backend__ = True
def test_flag_turned_off(self):
- e = engines.testing_engine(options={'implicit_returning':False})
+ e = engines.testing_engine(options={'implicit_returning': False})
assert e.dialect.implicit_returning is False
c = e.connect()
assert e.dialect.implicit_returning is False
def test_flag_turned_on(self):
- e = engines.testing_engine(options={'implicit_returning':True})
+ e = engines.testing_engine(options={'implicit_returning': True})
assert e.dialect.implicit_returning is True
c = e.connect()
assert e.dialect.implicit_returning is True
def test_flag_turned_default(self):
supports = [False]
+
def go():
supports[0] = True
testing.requires.returning(go)()
class FoundRowsTest(fixtures.TestBase, AssertsExecutionResults):
+
"""tests rowcount functionality"""
__requires__ = ('sane_rowcount', )
global employees_table, metadata
metadata = MetaData(testing.db)
- employees_table = Table('employees', metadata,
- Column('employee_id', Integer,
- Sequence('employee_id_seq', optional=True),
- primary_key=True),
- Column('name', String(50)),
- Column('department', String(1)),
- )
+ employees_table = Table(
+ 'employees', metadata, Column(
+ 'employee_id', Integer, Sequence(
+ 'employee_id_seq', optional=True), primary_key=True), Column(
+ 'name', String(50)), Column(
+ 'department', String(1)), )
metadata.create_all()
def setup(self):
global data
- data = [ ('Angela', 'A'),
- ('Andrew', 'A'),
- ('Anand', 'A'),
- ('Bob', 'B'),
- ('Bobette', 'B'),
- ('Buffy', 'B'),
- ('Charlie', 'C'),
- ('Cynthia', 'C'),
- ('Chris', 'C') ]
+ data = [('Angela', 'A'),
+ ('Andrew', 'A'),
+ ('Anand', 'A'),
+ ('Bob', 'B'),
+ ('Bobette', 'B'),
+ ('Buffy', 'B'),
+ ('Charlie', 'C'),
+ ('Cynthia', 'C'),
+ ('Chris', 'C')]
i = employees_table.insert()
- i.execute(*[{'name':n, 'department':d} for n, d in data])
+ i.execute(*[{'name': n, 'department': d} for n, d in data])
+
def teardown(self):
employees_table.delete().execute()
def test_update_rowcount1(self):
# WHERE matches 3, 3 rows changed
department = employees_table.c.department
- r = employees_table.update(department=='C').execute(department='Z')
+ r = employees_table.update(department == 'C').execute(department='Z')
print("expecting 3, dialect reports %s" % r.rowcount)
assert r.rowcount == 3
def test_update_rowcount2(self):
# WHERE matches 3, 0 rows changed
department = employees_table.c.department
- r = employees_table.update(department=='C').execute(department='C')
+ r = employees_table.update(department == 'C').execute(department='C')
print("expecting 3, dialect reports %s" % r.rowcount)
assert r.rowcount == 3
def test_delete_rowcount(self):
# WHERE matches 3, 3 rows deleted
department = employees_table.c.department
- r = employees_table.delete(department=='C').execute()
+ r = employees_table.delete(department == 'C').execute()
print("expecting 3, dialect reports %s" % r.rowcount)
assert r.rowcount == 3
-
metadata = MetaData()
table1 = Table('table1', metadata,
- Column('col1', Integer, primary_key=True),
- Column('col2', String(20)),
- Column('col3', Integer),
- Column('colx', Integer),
+ Column('col1', Integer, primary_key=True),
+ Column('col2', String(20)),
+ Column('col3', Integer),
+ Column('colx', Integer),
-)
+ )
table2 = Table('table2', metadata,
- Column('col1', Integer, primary_key=True),
- Column('col2', Integer, ForeignKey('table1.col1')),
- Column('col3', String(20)),
- Column('coly', Integer),
-)
+ Column('col1', Integer, primary_key=True),
+ Column('col2', Integer, ForeignKey('table1.col1')),
+ Column('col3', String(20)),
+ Column('coly', Integer),
+ )
keyed = Table('keyed', metadata,
- Column('x', Integer, key='colx'),
- Column('y', Integer, key='coly'),
- Column('z', Integer),
-)
+ Column('x', Integer, key='colx'),
+ Column('y', Integer, key='coly'),
+ Column('z', Integer),
+ )
-class SelectableTest(fixtures.TestBase, AssertsExecutionResults, AssertsCompiledSQL):
+
+class SelectableTest(
+ fixtures.TestBase,
+ AssertsExecutionResults,
+ AssertsCompiledSQL):
__dialect__ = 'default'
def test_indirect_correspondence_on_labels(self):
# same column three times
s = select([table1.c.col1.label('c2'), table1.c.col1,
- table1.c.col1.label('c1')])
+ table1.c.col1.label('c1')])
# this tests the same thing as
# test_direct_correspondence_on_labels below -
s = select([t])._clone()
assert c in s.c.bar.proxy_set
-
def test_no_error_on_unsupported_expr_key(self):
from sqlalchemy.dialects.postgresql import ARRAY
set([s3c1])
)
-
def test_distance_on_aliases(self):
a1 = table1.alias('a1')
for s in (select([a1, table1], use_labels=True),
tojoin = select([
literal_column('1').label('a'),
literal_column('2').label('b')
- ])
+ ])
basefrom = basesel.alias('basefrom')
joinfrom = tojoin.alias('joinfrom')
sel = select([basefrom.c.a])
assert sel.corresponding_column(table1.c.col1) \
is sel.c.table1_col1
- assert sel.corresponding_column(table1.c.col1,
- require_embedded=True) is sel.c.table1_col1
+ assert sel.corresponding_column(
+ table1.c.col1,
+ require_embedded=True) is sel.c.table1_col1
assert table1.corresponding_column(sel.c.table1_col1) \
is table1.c.col1
assert table1.corresponding_column(sel.c.table1_col1,
- require_embedded=True) is None
-
+ require_embedded=True) is None
def test_join_against_join(self):
j = outerjoin(table1, table2, table1.c.col1 == table2.c.col2)
# with a certain Table, against a column in a Union where one of
# its underlying Selects matches to that same Table
- u = select([table1.c.col1, table1.c.col2, table1.c.col3,
- table1.c.colx, null().label('coly'
- )]).union(select([table2.c.col1, table2.c.col2,
- table2.c.col3, null().label('colx'),
- table2.c.coly]))
+ u = select([table1.c.col1,
+ table1.c.col2,
+ table1.c.col3,
+ table1.c.colx,
+ null().label('coly')]).union(select([table2.c.col1,
+ table2.c.col2,
+ table2.c.col3,
+ null().label('colx'),
+ table2.c.coly]))
s1 = table1.select(use_labels=True)
s2 = table2.select(use_labels=True)
assert u1.corresponding_column(table1.c.colx) is u1.c.col2
assert u1.corresponding_column(table1.c.col3) is u1.c.col1
-
def test_singular_union(self):
- u = union(select([table1.c.col1, table1.c.col2,
- table1.c.col3]), select([table1.c.col1,
- table1.c.col2, table1.c.col3]))
+ u = union(select([table1.c.col1, table1.c.col2, table1.c.col3]), select(
+ [table1.c.col1, table1.c.col2, table1.c.col3]))
u = union(select([table1.c.col1, table1.c.col2, table1.c.col3]))
assert u.c.col1 is not None
assert u.c.col2 is not None
# same as testunion, except its an alias of the union
- u = select([table1.c.col1, table1.c.col2, table1.c.col3,
- table1.c.colx, null().label('coly'
- )]).union(select([table2.c.col1, table2.c.col2,
- table2.c.col3, null().label('colx'),
- table2.c.coly])).alias('analias')
+ u = select([table1.c.col1,
+ table1.c.col2,
+ table1.c.col3,
+ table1.c.colx,
+ null().label('coly')]).union(select([table2.c.col1,
+ table2.c.col2,
+ table2.c.col3,
+ null().label('colx'),
+ table2.c.coly])).alias('analias')
s1 = table1.select(use_labels=True)
s2 = table2.select(use_labels=True)
assert u.corresponding_column(s1.c.table1_col2) is u.c.col2
def test_union_of_text(self):
s1 = select([table1.c.col1, table1.c.col2])
s2 = text("select col1, col2 from foo").columns(
- column('col1'), column('col2'))
+ column('col1'), column('col2'))
u1 = union(s1, s2)
assert u1.corresponding_column(s1.c.col1) is u1.c.col1
s2 = select([table2.c.col1, table2.c.col2, table2.c.col3])
u1 = union(s1, s2)
- assert u1.corresponding_column(s1.c._all_columns[0]) is u1.c._all_columns[0]
+ assert u1.corresponding_column(
+ s1.c._all_columns[0]) is u1.c._all_columns[0]
assert u1.corresponding_column(s2.c.col1) is u1.c._all_columns[0]
assert u1.corresponding_column(s1.c.col2) is u1.c.col2
assert u1.corresponding_column(s2.c.col2) is u1.c.col2
s2 = select([table2.c.col1, table2.c.col2, table2.c.col3])
u1 = union(s1, s2)
- assert u1.corresponding_column(s1.c._all_columns[0]) is u1.c._all_columns[0]
+ assert u1.corresponding_column(
+ s1.c._all_columns[0]) is u1.c._all_columns[0]
assert u1.corresponding_column(s2.c.col1) is u1.c._all_columns[0]
assert u1.corresponding_column(s1.c.col2) is u1.c.col2
assert u1.corresponding_column(s2.c.col2) is u1.c.col2
assert u1.corresponding_column(table2.c.col1) is u1.c._all_columns[0]
assert u1.corresponding_column(table2.c.col3) is u1.c._all_columns[2]
-
def test_select_union(self):
# like testaliasunion, but off a Select off the union.
- u = select([table1.c.col1, table1.c.col2, table1.c.col3,
- table1.c.colx, null().label('coly'
- )]).union(select([table2.c.col1, table2.c.col2,
- table2.c.col3, null().label('colx'),
- table2.c.coly])).alias('analias')
+ u = select([table1.c.col1,
+ table1.c.col2,
+ table1.c.col3,
+ table1.c.colx,
+ null().label('coly')]).union(select([table2.c.col1,
+ table2.c.col2,
+ table2.c.col3,
+ null().label('colx'),
+ table2.c.coly])).alias('analias')
s = select([u])
s1 = table1.select(use_labels=True)
s2 = table2.select(use_labels=True)
# same as testunion, except its an alias of the union
- u = select([table1.c.col1, table1.c.col2, table1.c.col3,
- table1.c.colx, null().label('coly'
- )]).union(select([table2.c.col1, table2.c.col2,
- table2.c.col3, null().label('colx'),
- table2.c.coly])).alias('analias')
+ u = select([table1.c.col1,
+ table1.c.col2,
+ table1.c.col3,
+ table1.c.colx,
+ null().label('coly')]).union(select([table2.c.col1,
+ table2.c.col2,
+ table2.c.col3,
+ null().label('colx'),
+ table2.c.coly])).alias('analias')
j1 = table1.join(table2)
assert u.corresponding_column(j1.c.table1_colx) is u.c.colx
assert j1.corresponding_column(u.c.colx) is j1.c.table1_colx
def test_column_labels(self):
a = select([table1.c.col1.label('acol1'),
- table1.c.col2.label('acol2'),
- table1.c.col3.label('acol3')])
+ table1.c.col2.label('acol2'),
+ table1.c.col3.label('acol3')])
j = join(a, table2)
criterion = a.c.acol1 == table2.c.col2
self.assert_(criterion.compare(j.onclause))
def test_table_joined_to_select_of_table(self):
metadata = MetaData()
a = Table('a', metadata,
- Column('id', Integer, primary_key=True))
+ Column('id', Integer, primary_key=True))
j2 = select([a.c.id.label('aid')]).alias('bar')
eq_(c2._from_objects, [t])
self.assert_compile(select([c1]),
- "SELECT t.c1 FROM t")
+ "SELECT t.c1 FROM t")
self.assert_compile(select([c2]),
- "SELECT t.c2 FROM t")
+ "SELECT t.c2 FROM t")
def test_from_list_deferred_whereclause(self):
c1 = Column('c1', Integer)
eq_(c2._from_objects, [t])
self.assert_compile(select([c1]),
- "SELECT t.c1 FROM t")
+ "SELECT t.c1 FROM t")
self.assert_compile(select([c2]),
- "SELECT t.c2 FROM t")
+ "SELECT t.c2 FROM t")
def test_from_list_deferred_fromlist(self):
m = MetaData()
eq_(c1._from_objects, [t2])
self.assert_compile(select([c1]),
- "SELECT t2.c1 FROM t2")
+ "SELECT t2.c1 FROM t2")
def test_from_list_deferred_cloning(self):
c1 = Column('c1', Integer)
table2 = table('t2', column('b'))
s1 = select([table1.c.a, table2.c.b])
self.assert_compile(s1,
- "SELECT t1.a, t2.b FROM t1, t2"
- )
+ "SELECT t1.a, t2.b FROM t1, t2"
+ )
s2 = s1.with_only_columns([table2.c.b])
self.assert_compile(s2,
- "SELECT t2.b FROM t2"
- )
+ "SELECT t2.b FROM t2"
+ )
s3 = sql_util.ClauseAdapter(table1).traverse(s1)
self.assert_compile(s3,
- "SELECT t1.a, t2.b FROM t1, t2"
- )
+ "SELECT t1.a, t2.b FROM t1, t2"
+ )
s4 = s3.with_only_columns([table2.c.b])
self.assert_compile(s4,
- "SELECT t2.b FROM t2"
- )
+ "SELECT t2.b FROM t2"
+ )
def test_from_list_warning_against_existing(self):
c1 = Column('c1', Integer)
class RefreshForNewColTest(fixtures.TestBase):
+
def test_join_uninit(self):
a = table('a', column('x'))
b = table('b', column('y'))
j._refresh_for_new_column(q)
assert j.c.b_q is q
-
def test_join_samename_init(self):
a = table('a', column('x'))
b = table('b', column('y'))
q = column('q')
a.append_column(q)
assert_raises_message(
- NotImplementedError,
- "CompoundSelect constructs don't support addition of "
- "columns to underlying selectables",
- s3._refresh_for_new_column, q
+ NotImplementedError,
+ "CompoundSelect constructs don't support addition of "
+ "columns to underlying selectables",
+ s3._refresh_for_new_column, q
)
+
def test_nested_join_uninit(self):
a = table('a', column('x'))
b = table('b', column('y'))
j._refresh_for_new_column(q)
assert j.c.b_q is q
+
class AnonLabelTest(fixtures.TestBase):
+
"""Test behaviors fixed by [ticket:2168]."""
def test_anon_labels_named_column(self):
c1 = literal_column('x')
eq_(str(select([c1.label('y')])), "SELECT x AS y")
+
class JoinAliasingTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
"JOIN (c JOIN d ON c.c = d.d) ON b.b = c.c) AS anon_1"
)
+
class JoinConditionTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
m = MetaData()
t1 = Table('t1', m, Column('id', Integer))
t2 = Table('t2', m,
- Column('id', Integer),
- Column('t1id', ForeignKey('t1.id')))
+ Column('id', Integer),
+ Column('t1id', ForeignKey('t1.id')))
t3 = Table('t3', m,
- Column('id', Integer),
- Column('t1id', ForeignKey('t1.id')),
- Column('t2id', ForeignKey('t2.id')))
+ Column('id', Integer),
+ Column('t1id', ForeignKey('t1.id')),
+ Column('t2id', ForeignKey('t2.id')))
t4 = Table('t4', m, Column('id', Integer),
- Column('t2id', ForeignKey('t2.id')))
+ Column('t2id', ForeignKey('t2.id')))
t5 = Table('t5', m,
- Column('t1id1', ForeignKey('t1.id')),
- Column('t1id2', ForeignKey('t1.id')),
- )
+ Column('t1id1', ForeignKey('t1.id')),
+ Column('t1id2', ForeignKey('t1.id')),
+ )
t1t2 = t1.join(t2)
t2t3 = t2.join(t3)
(t2t3.join(t1), t4, None, t2t3.c.t2_id == t4.c.t2id),
(t2t3.join(t1), t4, t1, t2t3.c.t2_id == t4.c.t2id),
(t1t2, t2t3, t2, t1t2.c.t2_id == t2t3.c.t3_t2id),
- ]:
- assert expected.compare(sql_util.join_condition(left,
- right, a_subset=a_subset))
-
+ ]:
+ assert expected.compare(
+ sql_util.join_condition(
+ left,
+ right,
+ a_subset=a_subset))
# these are ambiguous, or have no joins
for left, right, a_subset in [
# these are right-nested joins
j = t1t2.join(t2t3)
assert j.onclause.compare(t2.c.id == t3.c.t2id)
- self.assert_compile(j,
- "t1 JOIN t2 ON t1.id = t2.t1id JOIN "
- "(t2 JOIN t3 ON t2.id = t3.t2id) ON t2.id = t3.t2id")
+ self.assert_compile(
+ j, "t1 JOIN t2 ON t1.id = t2.t1id JOIN "
+ "(t2 JOIN t3 ON t2.id = t3.t2id) ON t2.id = t3.t2id")
st2t3 = t2t3.select(use_labels=True)
j = t1t2.join(st2t3)
assert j.onclause.compare(t2.c.id == st2t3.c.t3_t2id)
- self.assert_compile(j,
- "t1 JOIN t2 ON t1.id = t2.t1id JOIN "
- "(SELECT t2.id AS t2_id, t2.t1id AS t2_t1id, "
- "t3.id AS t3_id, t3.t1id AS t3_t1id, t3.t2id AS t3_t2id "
- "FROM t2 JOIN t3 ON t2.id = t3.t2id) ON t2.id = t3_t2id")
-
+ self.assert_compile(
+ j, "t1 JOIN t2 ON t1.id = t2.t1id JOIN "
+ "(SELECT t2.id AS t2_id, t2.t1id AS t2_t1id, "
+ "t3.id AS t3_id, t3.t1id AS t3_t1id, t3.t2id AS t3_t2id "
+ "FROM t2 JOIN t3 ON t2.id = t3.t2id) ON t2.id = t3_t2id")
def test_join_multiple_equiv_fks(self):
m = MetaData()
t1 = Table('t1', m,
- Column('id', Integer, primary_key=True)
- )
- t2 = Table('t2', m,
- Column('t1id', Integer, ForeignKey('t1.id'), ForeignKey('t1.id'))
- )
+ Column('id', Integer, primary_key=True)
+ )
+ t2 = Table(
+ 't2',
+ m,
+ Column(
+ 't1id',
+ Integer,
+ ForeignKey('t1.id'),
+ ForeignKey('t1.id')))
assert sql_util.join_condition(t1, t2).compare(t1.c.id == t2.c.t1id)
# try to get coverage to get the "continue" statements
# in the loop...
t1 = Table('t1', m,
- Column('y', Integer, ForeignKey('t22.id')),
- Column('x', Integer, ForeignKey('t2.id')),
- Column('q', Integer, ForeignKey('t22.id')),
- )
+ Column('y', Integer, ForeignKey('t22.id')),
+ Column('x', Integer, ForeignKey('t2.id')),
+ Column('q', Integer, ForeignKey('t22.id')),
+ )
t2 = Table('t2', m, Column('id', Integer))
assert sql_util.join_condition(t1, t2).compare(t1.c.x == t2.c.id)
assert sql_util.join_condition(t2, t1).compare(t1.c.x == t2.c.id)
def test_join_cond_no_such_unrelated_column(self):
m = MetaData()
t1 = Table('t1', m, Column('x', Integer, ForeignKey('t2.id')),
- Column('y', Integer, ForeignKey('t3.q')))
+ Column('y', Integer, ForeignKey('t3.q')))
t2 = Table('t2', m, Column('id', Integer))
Table('t3', m, Column('id', Integer))
assert sql_util.join_condition(t1, t2).compare(t1.c.x == t2.c.id)
exc.NoReferencedColumnError,
"Could not initialize target column for "
"ForeignKey 't2.q' on table 't1': "
- "table 't2' has no column named 'q'",
+ "table 't2' has no column named 'q'",
sql_util.join_condition, t1, t2
)
exc.NoReferencedColumnError,
"Could not initialize target column for "
"ForeignKey 't2.q' on table 't1': "
- "table 't2' has no column named 'q'",
+ "table 't2' has no column named 'q'",
sql_util.join_condition, t2, t1
)
+
class PrimaryKeyTest(fixtures.TestBase, AssertsExecutionResults):
def test_join_pk_collapse_implicit(self):
meta = MetaData()
a = Table('a', meta, Column('id', Integer, primary_key=True))
b = Table('b', meta, Column('id', Integer, ForeignKey('a.id'),
- primary_key=True))
+ primary_key=True))
c = Table('c', meta, Column('id', Integer, ForeignKey('b.id'),
- primary_key=True))
+ primary_key=True))
d = Table('d', meta, Column('id', Integer, ForeignKey('c.id'),
- primary_key=True))
+ primary_key=True))
assert c.c.id.references(b.c.id)
assert not d.c.id.references(a.c.id)
assert list(a.join(b).primary_key) == [a.c.id]
assert list(d.join(c).join(b).primary_key) == [b.c.id]
assert list(a.join(b).join(c).join(d).primary_key) == [a.c.id]
-
def test_join_pk_collapse_explicit(self):
"""test that redundant columns in a join get 'collapsed' into a
minimal primary key, which is the root column along a chain of
a = Table('a', meta, Column('id', Integer, primary_key=True),
Column('x', Integer))
b = Table('b', meta, Column('id', Integer, ForeignKey('a.id'),
- primary_key=True), Column('x', Integer))
+ primary_key=True), Column('x', Integer))
c = Table('c', meta, Column('id', Integer, ForeignKey('b.id'),
- primary_key=True), Column('x', Integer))
+ primary_key=True), Column('x', Integer))
d = Table('d', meta, Column('id', Integer, ForeignKey('c.id'),
- primary_key=True), Column('x', Integer))
+ primary_key=True), Column('x', Integer))
print(list(a.join(b, a.c.x == b.c.id).primary_key))
assert list(a.join(b, a.c.x == b.c.id).primary_key) == [a.c.id]
assert list(b.join(c, b.c.x == c.c.id).primary_key) == [b.c.id]
== [b.c.id]
assert list(b.join(c, c.c.id == b.c.x).join(d).primary_key) \
== [b.c.id]
- assert list(d.join(b, d.c.id == b.c.id).join(c, b.c.id
- == c.c.x).primary_key) == [b.c.id]
+ assert list(
+ d.join(
+ b,
+ d.c.id == b.c.id).join(
+ c,
+ b.c.id == c.c.x).primary_key) == [
+ b.c.id]
assert list(a.join(b).join(c, c.c.id
- == b.c.x).join(d).primary_key) == [a.c.id]
+ == b.c.x).join(d).primary_key) == [a.c.id]
assert list(a.join(b, and_(a.c.id == b.c.id, a.c.x
- == b.c.id)).primary_key) == [a.c.id]
+ == b.c.id)).primary_key) == [a.c.id]
def test_init_doesnt_blowitaway(self):
meta = MetaData()
a = Table('a', meta,
- Column('id', Integer, primary_key=True),
- Column('x', Integer))
+ Column('id', Integer, primary_key=True),
+ Column('x', Integer))
b = Table('b', meta,
- Column('id', Integer, ForeignKey('a.id'), primary_key=True),
- Column('x', Integer))
+ Column('id', Integer, ForeignKey('a.id'), primary_key=True),
+ Column('x', Integer))
j = a.join(b)
assert list(j.primary_key) == [a.c.id]
def test_non_column_clause(self):
meta = MetaData()
a = Table('a', meta,
- Column('id', Integer, primary_key=True),
- Column('x', Integer))
+ Column('id', Integer, primary_key=True),
+ Column('x', Integer))
b = Table('b', meta,
- Column('id', Integer, ForeignKey('a.id'), primary_key=True),
- Column('x', Integer, primary_key=True))
+ Column('id', Integer, ForeignKey('a.id'), primary_key=True),
+ Column('x', Integer, primary_key=True))
j = a.join(b, and_(a.c.id == b.c.id, b.c.x == 5))
assert str(j) == "a JOIN b ON a.id = b.id AND b.x = :x_1", str(j)
metadata = MetaData()
employee = Table('Employee', metadata,
- Column('name', String(100)),
- Column('id', Integer, primary_key=True),
- )
+ Column('name', String(100)),
+ Column('id', Integer, primary_key=True),
+ )
engineer = Table('Engineer', metadata,
- Column('id', Integer,
- ForeignKey('Employee.id'), primary_key=True))
-
+ Column('id', Integer,
+ ForeignKey('Employee.id'), primary_key=True))
eq_(util.column_set(employee.join(engineer, employee.c.id
- == engineer.c.id).primary_key),
+ == engineer.c.id).primary_key),
util.column_set([employee.c.id]))
eq_(util.column_set(employee.join(engineer, engineer.c.id
- == employee.c.id).primary_key),
+ == employee.c.id).primary_key),
util.column_set([employee.c.id]))
class ReduceTest(fixtures.TestBase, AssertsExecutionResults):
+
def test_reduce(self):
meta = MetaData()
t1 = Table('t1', meta,
- Column('t1id', Integer, primary_key=True),
- Column('t1data', String(30)))
- t2 = Table('t2', meta,
- Column('t2id', Integer, ForeignKey('t1.t1id'), primary_key=True),
- Column('t2data', String(30)))
- t3 = Table('t3', meta,
- Column('t3id', Integer, ForeignKey('t2.t2id'), primary_key=True),
- Column('t3data', String(30)))
+ Column('t1id', Integer, primary_key=True),
+ Column('t1data', String(30)))
+ t2 = Table(
+ 't2',
+ meta,
+ Column(
+ 't2id',
+ Integer,
+ ForeignKey('t1.t1id'),
+ primary_key=True),
+ Column(
+ 't2data',
+ String(30)))
+ t3 = Table(
+ 't3',
+ meta,
+ Column(
+ 't3id',
+ Integer,
+ ForeignKey('t2.t2id'),
+ primary_key=True),
+ Column(
+ 't3data',
+ String(30)))
eq_(util.column_set(sql_util.reduce_columns([
t1.c.t1id,
t2.c.t2data,
t3.c.t3id,
t3.c.t3data,
- ])), util.column_set([t1.c.t1id, t1.c.t1data, t2.c.t2data,
- t3.c.t3data]))
-
+ ])), util.column_set([t1.c.t1id, t1.c.t1data, t2.c.t2data,
+ t3.c.t3data]))
def test_reduce_selectable(self):
metadata = MetaData()
engineers = Table('engineers', metadata,
- Column('engineer_id', Integer, primary_key=True),
+ Column('engineer_id', Integer, primary_key=True),
Column('engineer_name', String(50)))
managers = Table('managers', metadata,
- Column('manager_id', Integer, primary_key=True),
+ Column('manager_id', Integer, primary_key=True),
Column('manager_name', String(50)))
s = select([engineers,
- managers]).where(engineers.c.engineer_name
- == managers.c.manager_name)
+ managers]).where(engineers.c.engineer_name
+ == managers.c.manager_name)
eq_(util.column_set(sql_util.reduce_columns(list(s.c), s)),
util.column_set([s.c.engineer_id, s.c.engineer_name,
- s.c.manager_id]))
+ s.c.manager_id]))
def test_reduce_generation(self):
m = MetaData()
t1 = Table('t1', m, Column('x', Integer, primary_key=True),
- Column('y', Integer))
+ Column('y', Integer))
t2 = Table('t2', m, Column('z', Integer, ForeignKey('t1.x')),
- Column('q', Integer))
+ Column('q', Integer))
s1 = select([t1, t2])
s2 = s1.reduce_columns(only_synonyms=False)
eq_(
set([t1.c.x, t1.c.y, t2.c.z, t2.c.q])
)
-
def test_reduce_only_synonym_fk(self):
m = MetaData()
t1 = Table('t1', m, Column('x', Integer, primary_key=True),
- Column('y', Integer))
+ Column('y', Integer))
t2 = Table('t2', m, Column('x', Integer, ForeignKey('t1.x')),
- Column('q', Integer, ForeignKey('t1.y')))
+ Column('q', Integer, ForeignKey('t1.y')))
s1 = select([t1, t2])
s1 = s1.reduce_columns(only_synonyms=True)
eq_(
def test_reduce_only_synonym_lineage(self):
m = MetaData()
t1 = Table('t1', m, Column('x', Integer, primary_key=True),
- Column('y', Integer),
- Column('z', Integer)
- )
+ Column('y', Integer),
+ Column('z', Integer)
+ )
# test that the first appearance in the columns clause
# wins - t1 is first, t1.c.x wins
s1 = select([t1])
s2 = select([t1, s1]).where(t1.c.x == s1.c.x).where(s1.c.y == t1.c.z)
eq_(
- set(s2.reduce_columns().inner_columns),
- set([t1.c.x, t1.c.y, t1.c.z, s1.c.y, s1.c.z])
+ set(s2.reduce_columns().inner_columns),
+ set([t1.c.x, t1.c.y, t1.c.z, s1.c.y, s1.c.z])
)
# reverse order, s1.c.x wins
s1 = select([t1])
s2 = select([s1, t1]).where(t1.c.x == s1.c.x).where(s1.c.y == t1.c.z)
eq_(
- set(s2.reduce_columns().inner_columns),
- set([s1.c.x, t1.c.y, t1.c.z, s1.c.y, s1.c.z])
+ set(s2.reduce_columns().inner_columns),
+ set([s1.c.x, t1.c.y, t1.c.z, s1.c.y, s1.c.z])
)
def test_reduce_aliased_join(self):
metadata = MetaData()
- people = Table('people', metadata, Column('person_id', Integer,
- Sequence('person_id_seq', optional=True),
- primary_key=True), Column('name', String(50)),
- Column('type', String(30)))
+ people = Table(
+ 'people', metadata, Column(
+ 'person_id', Integer, Sequence(
+ 'person_id_seq', optional=True), primary_key=True), Column(
+ 'name', String(50)), Column(
+ 'type', String(30)))
engineers = Table(
'engineers',
metadata,
Column('person_id', Integer, ForeignKey('people.person_id'
- ), primary_key=True),
+ ), primary_key=True),
Column('status', String(30)),
Column('engineer_name', String(50)),
Column('primary_language', String(50)),
- )
- managers = Table('managers', metadata, Column('person_id',
- Integer, ForeignKey('people.person_id'),
- primary_key=True), Column('status',
- String(30)), Column('manager_name',
- String(50)))
+ )
+ managers = Table(
+ 'managers', metadata, Column(
+ 'person_id', Integer, ForeignKey('people.person_id'), primary_key=True), Column(
+ 'status', String(30)), Column(
+ 'manager_name', String(50)))
pjoin = \
people.outerjoin(engineers).outerjoin(managers).\
select(use_labels=True).alias('pjoin'
- )
+ )
eq_(util.column_set(sql_util.reduce_columns([pjoin.c.people_person_id,
- pjoin.c.engineers_person_id, pjoin.c.managers_person_id])),
+ pjoin.c.engineers_person_id,
+ pjoin.c.managers_person_id])),
util.column_set([pjoin.c.people_person_id]))
def test_reduce_aliased_union(self):
metadata = MetaData()
- item_table = Table('item', metadata, Column('id', Integer,
- ForeignKey('base_item.id'),
- primary_key=True), Column('dummy', Integer,
- default=0))
- base_item_table = Table('base_item', metadata, Column('id',
- Integer, primary_key=True),
- Column('child_name', String(255),
- default=None))
+ item_table = Table(
+ 'item',
+ metadata,
+ Column(
+ 'id',
+ Integer,
+ ForeignKey('base_item.id'),
+ primary_key=True),
+ Column(
+ 'dummy',
+ Integer,
+ default=0))
+ base_item_table = Table(
+ 'base_item', metadata, Column(
+ 'id', Integer, primary_key=True), Column(
+ 'child_name', String(255), default=None))
from sqlalchemy.orm.util import polymorphic_union
item_join = polymorphic_union({
- 'BaseItem':
- base_item_table.select(
- base_item_table.c.child_name
- == 'BaseItem'),
+ 'BaseItem':
+ base_item_table.select(
+ base_item_table.c.child_name
+ == 'BaseItem'),
'Item': base_item_table.join(item_table)},
- None, 'item_join')
+ None, 'item_join')
eq_(util.column_set(sql_util.reduce_columns([item_join.c.id,
- item_join.c.dummy, item_join.c.child_name])),
- util.column_set([item_join.c.id, item_join.c.dummy,
- item_join.c.child_name]))
+ item_join.c.dummy,
+ item_join.c.child_name])),
+ util.column_set([item_join.c.id,
+ item_join.c.dummy,
+ item_join.c.child_name]))
def test_reduce_aliased_union_2(self):
metadata = MetaData()
page_table = Table('page', metadata, Column('id', Integer,
- primary_key=True))
+ primary_key=True))
magazine_page_table = Table('magazine_page', metadata,
Column('page_id', Integer,
- ForeignKey('page.id'),
- primary_key=True))
- classified_page_table = Table('classified_page', metadata,
- Column('magazine_page_id', Integer,
- ForeignKey('magazine_page.page_id'), primary_key=True))
+ ForeignKey('page.id'),
+ primary_key=True))
+ classified_page_table = Table(
+ 'classified_page',
+ metadata,
+ Column(
+ 'magazine_page_id',
+ Integer,
+ ForeignKey('magazine_page.page_id'),
+ primary_key=True))
# this is essentially the union formed by the ORM's
# polymorphic_union function. we define two versions with
# classified_page.magazine_page_id
pjoin = union(
- select([
- page_table.c.id,
- magazine_page_table.c.page_id,
- classified_page_table.c.magazine_page_id
- ]).
- select_from(
- page_table.join(magazine_page_table).
- join(classified_page_table)),
-
- select([
- page_table.c.id,
- magazine_page_table.c.page_id,
- cast(null(), Integer).label('magazine_page_id')
- ]).
- select_from(page_table.join(magazine_page_table))
- ).alias('pjoin')
- eq_(util.column_set(sql_util.reduce_columns([pjoin.c.id,
- pjoin.c.page_id, pjoin.c.magazine_page_id])),
- util.column_set([pjoin.c.id]))
+ select([
+ page_table.c.id,
+ magazine_page_table.c.page_id,
+ classified_page_table.c.magazine_page_id
+ ]).
+ select_from(
+ page_table.join(magazine_page_table).
+ join(classified_page_table)),
+
+ select([
+ page_table.c.id,
+ magazine_page_table.c.page_id,
+ cast(null(), Integer).label('magazine_page_id')
+ ]).
+ select_from(page_table.join(magazine_page_table))
+ ).alias('pjoin')
+ eq_(util.column_set(sql_util.reduce_columns(
+ [pjoin.c.id, pjoin.c.page_id, pjoin.c.magazine_page_id])), util.column_set([pjoin.c.id]))
# the first selectable has a CAST, which is a placeholder for
# classified_page.magazine_page_id in the second selectable.
# first selectable only.
pjoin = union(select([
- page_table.c.id,
- magazine_page_table.c.page_id,
- cast(null(), Integer).label('magazine_page_id')
- ]).
- select_from(page_table.join(magazine_page_table)),
-
- select([
- page_table.c.id,
- magazine_page_table.c.page_id,
- classified_page_table.c.magazine_page_id
- ]).
- select_from(page_table.join(magazine_page_table).
- join(classified_page_table))
- ).alias('pjoin')
- eq_(util.column_set(sql_util.reduce_columns([pjoin.c.id,
- pjoin.c.page_id, pjoin.c.magazine_page_id])),
- util.column_set([pjoin.c.id]))
+ page_table.c.id,
+ magazine_page_table.c.page_id,
+ cast(null(), Integer).label('magazine_page_id')
+ ]).
+ select_from(page_table.join(magazine_page_table)),
+
+ select([
+ page_table.c.id,
+ magazine_page_table.c.page_id,
+ classified_page_table.c.magazine_page_id
+ ]).
+ select_from(page_table.join(magazine_page_table).
+ join(classified_page_table))
+ ).alias('pjoin')
+ eq_(util.column_set(sql_util.reduce_columns(
+ [pjoin.c.id, pjoin.c.page_id, pjoin.c.magazine_page_id])), util.column_set([pjoin.c.id]))
+
class DerivedTest(fixtures.TestBase, AssertsExecutionResults):
+
def test_table(self):
meta = MetaData()
assert t1.is_derived_from(t1)
assert not t2.is_derived_from(t1)
-
def test_alias(self):
meta = MetaData()
t1 = Table('t1', meta, Column('c1', Integer, primary_key=True),
assert select([t1, t2]).alias('foo').is_derived_from(t1)
assert not t2.select().alias('foo').is_derived_from(t1)
+
class AnnotationsTest(fixtures.TestBase):
def test_hashing(self):
def test_basic_attrs(self):
t = Table('t', MetaData(),
- Column('x', Integer, info={'q': 'p'}),
- Column('y', Integer, key='q'))
+ Column('x', Integer, info={'q': 'p'}),
+ Column('y', Integer, key='q'))
x_a = t.c.x._annotate({})
y_a = t.c.q._annotate({})
t.c.x.info['z'] = 'h'
def test_custom_constructions(self):
from sqlalchemy.schema import Column
+
class MyColumn(Column):
+
def __init__(self):
Column.__init__(self, 'foo', Integer)
_constructor = Column
# [ticket:2918]
from sqlalchemy.schema import Column
from sqlalchemy.sql.elements import AnnotatedColumnElement
+
class MyColumn(Column):
pass
assert isinstance(
- MyColumn('x', Integer)._annotate({"foo": "bar"}),
- AnnotatedColumnElement)
+ MyColumn('x', Integer)._annotate({"foo": "bar"}),
+ AnnotatedColumnElement)
def test_custom_construction_correct_anno_expr(self):
# [ticket:2918]
from sqlalchemy.schema import Column
+
class MyColumn(Column):
pass
inner = select([s1])
- assert inner.corresponding_column(t2.c.col1,
- require_embedded=False) \
- is inner.corresponding_column(t2.c.col1,
- require_embedded=True) is inner.c.col1
- assert inner.corresponding_column(t1.c.col1,
- require_embedded=False) \
- is inner.corresponding_column(t1.c.col1,
- require_embedded=True) is inner.c.col1
+ assert inner.corresponding_column(
+ t2.c.col1,
+ require_embedded=False) is inner.corresponding_column(
+ t2.c.col1,
+ require_embedded=True) is inner.c.col1
+ assert inner.corresponding_column(
+ t1.c.col1,
+ require_embedded=False) is inner.corresponding_column(
+ t1.c.col1,
+ require_embedded=True) is inner.c.col1
def test_annotated_visit(self):
table1 = table('table1', column("col1"), column("col2"))
bin = table1.c.col1 == bindparam('foo', value=None)
assert str(bin) == "table1.col1 = :foo"
+
def visit_binary(b):
b.right = table1.c.col2
b2 = visitors.cloned_traverse(bin, {}, {'binary': visit_binary})
assert str(b2) == "table1.col1 = table1.col2"
-
b3 = visitors.cloned_traverse(bin._annotate({}), {}, {'binary':
- visit_binary})
+ visit_binary})
assert str(b3) == 'table1.col1 = table1.col2'
def visit_binary(b):
table1 = table('table1', column('col1'), column('col2'))
for expr, expected in [(table1.c.col1, 'table1.col1'),
(table1.c.col1 == 5,
- 'table1.col1 = :col1_1'),
+ 'table1.col1 = :col1_1'),
(table1.c.col1.in_([2, 3, 4]),
- 'table1.col1 IN (:col1_1, :col1_2, '
- ':col1_3)')]:
+ 'table1.col1 IN (:col1_1, :col1_2, '
+ ':col1_3)')]:
eq_(str(expr), expected)
eq_(str(expr._annotate({})), expected)
eq_(str(sql_util._deep_annotate(expr, {})), expected)
- eq_(str(sql_util._deep_annotate(expr, {},
- exclude=[table1.c.col1])), expected)
+ eq_(str(sql_util._deep_annotate(
+ expr, {}, exclude=[table1.c.col1])), expected)
def test_deannotate(self):
table1 = table('table1', column("col1"), column("col2"))
assert '_orm_adapt' in elem
for elem in b3._annotations, b3.left._annotations, \
- b4._annotations, b4.left._annotations:
+ b4._annotations, b4.left._annotations:
assert elem == {}
assert b2.left is not bin.left
table2 = table('table2', column('y'))
a1 = table1.alias()
s = select([a1.c.x]).select_from(
- a1.join(table2, a1.c.x == table2.c.y)
- )
+ a1.join(table2, a1.c.x == table2.c.y)
+ )
for sel in (
sql_util._deep_deannotate(s),
visitors.cloned_traverse(s, {}, {}),
# re49563072578
eq_(str(s), str(sel))
-
def test_annotate_varied_annot_same_col(self):
"""test two instances of the same column with different annotations
preserving them when deep_annotate is run on them.
"""
t1 = table('table1', column("col1"), column("col2"))
- s = select([t1.c.col1._annotate({"foo":"bar"})])
- s2 = select([t1.c.col1._annotate({"bat":"hoho"})])
+ s = select([t1.c.col1._annotate({"foo": "bar"})])
+ s2 = select([t1.c.col1._annotate({"bat": "hoho"})])
s3 = s.union(s2)
sel = sql_util._deep_annotate(s3, {"new": "thing"})
def test_deannotate_2(self):
table1 = table('table1', column("col1"), column("col2"))
j = table1.c.col1._annotate({"remote": True}) == \
- table1.c.col2._annotate({"local": True})
+ table1.c.col2._annotate({"local": True})
j2 = sql_util._deep_deannotate(j)
eq_(
j.left._annotations, {"remote": True}
def test_deannotate_3(self):
table1 = table('table1', column("col1"), column("col2"),
- column("col3"), column("col4"))
+ column("col3"), column("col4"))
j = and_(
- table1.c.col1._annotate({"remote": True}) ==
- table1.c.col2._annotate({"local": True}),
- table1.c.col3._annotate({"remote": True}) ==
- table1.c.col4._annotate({"local": True})
+ table1.c.col1._annotate({"remote": True}) ==
+ table1.c.col2._annotate({"local": True}),
+ table1.c.col3._annotate({"remote": True}) ==
+ table1.c.col4._annotate({"local": True})
)
j2 = sql_util._deep_deannotate(j)
eq_(
table2 = table('table2', column('y'))
a1 = table1.alias()
s = select([a1.c.x]).select_from(
- a1.join(table2, a1.c.x == table2.c.y)
- )
+ a1.join(table2, a1.c.x == table2.c.y)
+ )
assert_s = select([select([s])])
for fn in (
sel = fn(select([fn(select([fn(s)]))]))
eq_(str(assert_s), str(sel))
-
def test_bind_unique_test(self):
table('t', column('a'), column('b'))
assert (c2 == 5).left._annotations == {"foo": "bar", "bat": "hoho"}
+
class WithLabelsTest(fixtures.TestBase):
+
def _assert_labels_warning(self, s):
assert_raises_message(
exc.SAWarning,
)
self._assert_result_keys(sel, ['t1_a', 't2_b'])
+
class SelectProxyTest(fixtures.TestBase):
+
def _fixture(self):
m = MetaData()
t = Table('t', m, Column('x', Integer), Column('y', Integer))
def _mapping(self, stmt):
compiled = stmt.compile()
return dict(
- (elem, key)
- for key, elements in compiled.result_map.items()
- for elem in elements[1]
- )
+ (elem, key)
+ for key, elements in compiled.result_map.items()
+ for elem in elements[1]
+ )
def test_select_label_alt_name(self):
t = self._fixture()
assert l1 in mapping
assert ta.c.x not in mapping
+
class ForUpdateTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
eq_(s2._for_update_arg.read, True)
eq_(s2._for_update_arg.of, [t.c.c])
self.assert_compile(s2,
- "SELECT t.c FROM t FOR SHARE OF t",
- dialect="postgresql")
+ "SELECT t.c FROM t FOR SHARE OF t",
+ dialect="postgresql")
def test_adapt(self):
t = table('t', column('c'))
s2 = sql_util.ClauseAdapter(a).traverse(s)
eq_(s2._for_update_arg.of, [a.c.c])
self.assert_compile(s2,
- "SELECT t_1.c FROM t AS t_1 FOR SHARE OF t_1",
- dialect="postgresql")
+ "SELECT t_1.c FROM t AS t_1 FOR SHARE OF t_1",
+ dialect="postgresql")
from sqlalchemy.testing import fixtures, AssertsCompiledSQL, eq_, assert_raises_message
from sqlalchemy import text, select, Integer, String, Float, \
- bindparam, and_, func, literal_column, exc, MetaData, Table, Column
+ bindparam, and_, func, literal_column, exc, MetaData, Table, Column
from sqlalchemy.types import NullType
from sqlalchemy.sql import table, column
table1 = table('mytable',
- column('myid', Integer),
- column('name', String),
- column('description', String),
-)
+ column('myid', Integer),
+ column('name', String),
+ column('description', String),
+ )
table2 = table(
'myothertable',
column('othername', String),
)
+
class CompileTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
"select * from foo where lala = bar"
)
+
class SelectCompositionTest(fixtures.TestBase, AssertsCompiledSQL):
+
"""test the usage of text() implicit within the select() construct
when strings are passed."""
["foobar(a)", "pk_foo_bar(syslaal)"],
"a = 12",
from_obj=["foobar left outer join lala on foobar.foo = lala.foo"]
- ),
+ ),
"SELECT foobar(a), pk_foo_bar(syslaal) FROM foobar "
"left outer join lala on foobar.foo = lala.foo WHERE a = 12"
)
s = s.order_by("column1")
s.append_from("table1")
self.assert_compile(s, "SELECT column1, column2 FROM table1 WHERE "
- "column1=12 AND column2=19 ORDER BY column1")
+ "column1=12 AND column2=19 ORDER BY column1")
def test_select_composition_three(self):
self.assert_compile(
select(["column1", "column2"],
- from_obj=table1).alias('somealias').select(),
+ from_obj=table1).alias('somealias').select(),
"SELECT somealias.column1, somealias.column2 FROM "
"(SELECT column1, column2 FROM mytable) AS somealias"
)
# test that use_labels doesn't interfere with literal columns
self.assert_compile(
select(["column1", "column2", table1.c.myid], from_obj=table1,
- use_labels=True),
+ use_labels=True),
"SELECT column1, column2, mytable.myid AS mytable_myid "
"FROM mytable"
)
# with literal columns that have textual labels
self.assert_compile(
select(["column1 AS foobar", "column2 AS hoho", table1.c.myid],
- from_obj=table1, use_labels=True),
+ from_obj=table1, use_labels=True),
"SELECT column1 AS foobar, column2 AS hoho, "
"mytable.myid AS mytable_myid FROM mytable"
)
# exported columns don't get quoted
self.assert_compile(
select(["column1 AS foobar", "column2 AS hoho", table1.c.myid],
- from_obj=[table1]).select(),
+ from_obj=[table1]).select(),
"SELECT column1 AS foobar, column2 AS hoho, myid FROM "
"(SELECT column1 AS foobar, column2 AS hoho, "
- "mytable.myid AS myid FROM mytable)"
+ "mytable.myid AS myid FROM mytable)"
)
def test_select_composition_seven(self):
"foo.f = t.id",
from_obj=["(select f from bar where lala=heyhey) foo"]
),
- "SELECT t.myid, t.name, t.description, foo.f FROM mytable AS t, "
- "(select f from bar where lala=heyhey) foo WHERE foo.f = t.id")
+ "SELECT t.myid, t.name, t.description, foo.f FROM mytable AS t, "
+ "(select f from bar where lala=heyhey) foo WHERE foo.f = t.id")
def test_select_bundle_columns(self):
self.assert_compile(select(
table1.c.myid == table2.c.otherid,
)
),
- "SELECT mytable.myid, mytable.name, mytable.description, "
- "myothertable.otherid, sysdate(), foo, bar, lala "
- "FROM mytable, myothertable WHERE foo.id = foofoo(lala) AND "
- "datetime(foo) = Today AND mytable.myid = myothertable.otherid")
+ "SELECT mytable.myid, mytable.name, mytable.description, "
+ "myothertable.otherid, sysdate(), foo, bar, lala "
+ "FROM mytable, myothertable WHERE foo.id = foofoo(lala) AND "
+ "datetime(foo) = Today AND mytable.myid = myothertable.otherid")
+
class BindParamTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
def test_legacy(self):
t = text("select * from foo where lala=:bar and hoho=:whee",
- bindparams=[bindparam('bar', 4), bindparam('whee', 7)])
+ bindparams=[bindparam('bar', 4), bindparam('whee', 7)])
self.assert_compile(
t,
t = text("select * from table :foo :bar :bat")
self._assert_type_map(t, {"foo": NullType(),
- "bar": NullType(),
- "bat": NullType()})
+ "bar": NullType(),
+ "bat": NullType()})
t = t.bindparams(bindparam('foo', type_=String))
self._assert_type_map(t, {"foo": String(),
- "bar": NullType(),
- "bat": NullType()})
+ "bar": NullType(),
+ "bat": NullType()})
t = t.bindparams(bindparam('bar', type_=Integer))
self._assert_type_map(t, {"foo": String(),
- "bar": Integer(),
- "bat": NullType()})
+ "bar": Integer(),
+ "bat": NullType()})
t = t.bindparams(bat=45.564)
self._assert_type_map(t, {"foo": String(),
- "bar": Integer(),
- "bat": Float()})
-
+ "bar": Integer(),
+ "bat": Float()})
def test_binds_compiled_named(self):
self.assert_compile(
text("select * from foo where lala=:bar and hoho=:whee").
- bindparams(bar=4, whee=7),
- "select * from foo where lala=%(bar)s and hoho=%(whee)s",
- checkparams={'bar': 4, 'whee': 7},
- dialect="postgresql"
+ bindparams(bar=4, whee=7),
+ "select * from foo where lala=%(bar)s and hoho=%(whee)s",
+ checkparams={'bar': 4, 'whee': 7},
+ dialect="postgresql"
)
def test_binds_compiled_positional(self):
self.assert_compile(
text("select * from foo where lala=:bar and hoho=:whee").
- bindparams(bar=4, whee=7),
- "select * from foo where lala=? and hoho=?",
- checkparams={'bar': 4, 'whee': 7},
- dialect="sqlite"
+ bindparams(bar=4, whee=7),
+ "select * from foo where lala=? and hoho=?",
+ checkparams={'bar': 4, 'whee': 7},
+ dialect="sqlite"
)
def test_missing_bind_kw(self):
exc.ArgumentError,
"This text\(\) construct doesn't define a bound parameter named 'bar'",
text(":foo").bindparams,
- foo=5, bar=7
- )
+ foo=5,
+ bar=7)
def test_missing_bind_posn(self):
assert_raises_message(
exc.ArgumentError,
"This text\(\) construct doesn't define a bound parameter named 'bar'",
text(":foo").bindparams,
- bindparam('foo', value=5), bindparam('bar', value=7)
- )
+ bindparam(
+ 'foo',
+ value=5),
+ bindparam(
+ 'bar',
+ value=7))
def test_escaping_colons(self):
# test escaping out text() params with a backslash
self.assert_compile(
text("select * from foo where clock='05:06:07' "
- "and mork='\:mindy'"),
+ "and mork='\:mindy'"),
"select * from foo where clock='05:06:07' and mork=':mindy'",
checkparams={},
params={},
dialect="postgresql"
)
-
def test_text_in_select_nonfrom(self):
generate_series = text("generate_series(:x, :y, :z) as s(a)").\
- bindparams(x=None, y=None, z=None)
+ bindparams(x=None, y=None, z=None)
s = select([
- (func.current_date() + literal_column("s.a")).label("dates")
- ]).select_from(generate_series)
+ (func.current_date() + literal_column("s.a")).label("dates")
+ ]).select_from(generate_series)
self.assert_compile(
- s,
- "SELECT CURRENT_DATE + s.a AS dates FROM "
- "generate_series(:x, :y, :z) as s(a)",
- checkparams={'y': None, 'x': None, 'z': None}
- )
+ s,
+ "SELECT CURRENT_DATE + s.a AS dates FROM "
+ "generate_series(:x, :y, :z) as s(a)",
+ checkparams={'y': None, 'x': None, 'z': None}
+ )
self.assert_compile(
- s.params(x=5, y=6, z=7),
- "SELECT CURRENT_DATE + s.a AS dates FROM "
- "generate_series(:x, :y, :z) as s(a)",
- checkparams={'y': 6, 'x': 5, 'z': 7}
- )
+ s.params(x=5, y=6, z=7),
+ "SELECT CURRENT_DATE + s.a AS dates FROM "
+ "generate_series(:x, :y, :z) as s(a)",
+ checkparams={'y': 6, 'x': 5, 'z': 7}
+ )
+
class AsFromTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
def test_basic_toplevel_resultmap_positional(self):
t = text("select id, name from user").columns(
- column('id', Integer),
- column('name')
- )
+ column('id', Integer),
+ column('name')
+ )
compiled = t.compile()
- eq_(
- compiled.result_map,
- {
- 'id': ('id', (t.c.id._proxies[0], 'id', 'id'), t.c.id.type),
- 'name': ('name', (t.c.name._proxies[0], 'name', 'name'), t.c.name.type)
- }
- )
+ eq_(compiled.result_map,
+ {'id': ('id',
+ (t.c.id._proxies[0],
+ 'id',
+ 'id'),
+ t.c.id.type),
+ 'name': ('name',
+ (t.c.name._proxies[0],
+ 'name',
+ 'name'),
+ t.c.name.type)})
def test_basic_toplevel_resultmap(self):
t = text("select id, name from user").columns(id=Integer, name=String)
compiled = t.compile()
- eq_(
- compiled.result_map,
- {
- 'id': ('id', (t.c.id._proxies[0], 'id', 'id'), t.c.id.type),
- 'name': ('name', (t.c.name._proxies[0], 'name', 'name'), t.c.name.type)
- }
- )
+ eq_(compiled.result_map,
+ {'id': ('id',
+ (t.c.id._proxies[0],
+ 'id',
+ 'id'),
+ t.c.id.type),
+ 'name': ('name',
+ (t.c.name._proxies[0],
+ 'name',
+ 'name'),
+ t.c.name.type)})
def test_basic_subquery_resultmap(self):
t = text("select id, name from user").columns(id=Integer, name=String)
stmt = select([table1.c.myid]).select_from(
- table1.join(t, table1.c.myid == t.c.id))
+ table1.join(t, table1.c.myid == t.c.id))
compiled = stmt.compile()
eq_(
compiled.result_map,
{
"myid": ("myid",
- (table1.c.myid, "myid", "myid"), table1.c.myid.type),
+ (table1.c.myid, "myid", "myid"), table1.c.myid.type),
}
)
def test_column_collection_ordered(self):
t = text("select a, b, c from foo").columns(column('a'),
- column('b'), column('c'))
+ column('b'), column('c'))
eq_(t.c.keys(), ['a', 'b', 'c'])
def test_column_collection_pos_plus_bykey(self):
# overlapping positional names + type names
- t = text("select a, b, c from foo").columns(column('a'),
- column('b'), b=Integer, c=String)
+ t = text("select a, b, c from foo").columns(
+ column('a'),
+ column('b'),
+ b=Integer,
+ c=String)
eq_(t.c.keys(), ['a', 'b', 'c'])
eq_(t.c.b.type._type_affinity, Integer)
eq_(t.c.c.type._type_affinity, String)
-
def _xy_table_fixture(self):
m = MetaData()
t = Table('t', m, Column('x', Integer), Column('y', Integer))
def _mapping(self, stmt):
compiled = stmt.compile()
return dict(
- (elem, key)
- for key, elements in compiled.result_map.items()
- for elem in elements[1]
- )
+ (elem, key)
+ for key, elements in compiled.result_map.items()
+ for elem in elements[1]
+ )
def test_select_label_alt_name(self):
t = self._xy_table_fixture()
assert ta.c.x not in mapping
def test_cte(self):
- t = text("select id, name from user").columns(id=Integer, name=String).cte('t')
+ t = text("select id, name from user").columns(
+ id=Integer,
+ name=String).cte('t')
s = select([table1]).where(table1.c.myid == t.c.id)
self.assert_compile(
"FROM mytable, t WHERE mytable.myid = t.id"
)
-
def test_alias(self):
- t = text("select id, name from user").columns(id=Integer, name=String).alias('t')
+ t = text("select id, name from user").columns(
+ id=Integer,
+ name=String).alias('t')
s = select([table1]).where(table1.c.myid == t.c.id)
self.assert_compile(
eq_(
set(t.element._bindparams),
set(["bat", "foo", "bar"])
- )
\ No newline at end of file
+ )
class _ExprFixture(object):
+
def _fixture(self):
class MyString(String):
+
def bind_expression(self, bindvalue):
return func.lower(bindvalue)
return func.lower(col)
test_table = Table(
- 'test_table',
- MetaData(), Column('x', String), Column('y', MyString)
+ 'test_table',
+ MetaData(), Column('x', String), Column('y', MyString)
)
return test_table
+
class SelectTest(_ExprFixture, fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
table = self._fixture()
self.assert_compile(
- table.insert(),
- "INSERT INTO test_table (x, y) VALUES (:x, lower(:y))"
+ table.insert(),
+ "INSERT INTO test_table (x, y) VALUES (:x, lower(:y))"
)
self.assert_compile(
- table.insert().values(y="hi"),
- "INSERT INTO test_table (y) VALUES (lower(:y))"
+ table.insert().values(y="hi"),
+ "INSERT INTO test_table (y) VALUES (lower(:y))"
)
def test_select_binds(self):
"test_table WHERE test_table.y = lower(:y_1)"
)
+
class DerivedTest(_ExprFixture, fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = 'default'
self.assert_compile(
table.select().select(),
"SELECT x, lower(y) AS y FROM (SELECT test_table.x "
- "AS x, test_table.y AS y FROM test_table)"
+ "AS x, test_table.y AS y FROM test_table)"
)
def test_select_from_alias(self):
self.assert_compile(
table.select().alias().select(),
"SELECT anon_1.x, lower(anon_1.y) AS y FROM (SELECT "
- "test_table.x AS x, test_table.y AS y "
- "FROM test_table) AS anon_1"
+ "test_table.x AS x, test_table.y AS y "
+ "FROM test_table) AS anon_1"
)
def test_select_from_aliased_join(self):
s2 = table.select().alias()
j = s1.join(s2, s1.c.x == s2.c.x)
s3 = j.select()
- self.assert_compile(s3,
- "SELECT anon_1.x, lower(anon_1.y) AS y, anon_2.x, "
+ self.assert_compile(
+ s3, "SELECT anon_1.x, lower(anon_1.y) AS y, anon_2.x, "
"lower(anon_2.y) AS y "
"FROM (SELECT test_table.x AS x, test_table.y AS y "
"FROM test_table) AS anon_1 JOIN (SELECT "
"test_table.x AS x, test_table.y AS y "
- "FROM test_table) AS anon_2 ON anon_1.x = anon_2.x"
- )
+ "FROM test_table) AS anon_2 ON anon_1.x = anon_2.x")
+
class RoundTripTestBase(object):
+
def test_round_trip(self):
testing.db.execute(
self.tables.test_table.insert(),
# conversion back to upper
eq_(
testing.db.execute(
- select([self.tables.test_table]).\
+ select([self.tables.test_table]).
order_by(self.tables.test_table.c.y)
).fetchall(),
[
{"x": "X1", "y": "Y1"},
)
row = testing.db.execute(select([self.tables.test_table]).
- apply_labels()).first()
+ apply_labels()).first()
eq_(
row[self.tables.test_table.c.y],
"Y1"
{"x": "X1", "y": "Y1"},
)
row = testing.db.execute(select([
- self.tables.test_table.c.x.label('xbar'),
- self.tables.test_table.c.y.label('ybar')
- ])).first()
+ self.tables.test_table.c.x.label('xbar'),
+ self.tables.test_table.c.y.label('ybar')
+ ])).first()
eq_(
row[self.tables.test_table.c.y],
"Y1"
)
+
class StringRoundTripTest(fixtures.TablesTest, RoundTripTestBase):
+
@classmethod
def define_tables(cls, metadata):
class MyString(String):
+
def bind_expression(self, bindvalue):
return func.lower(bindvalue)
return func.upper(col)
Table(
- 'test_table',
- metadata,
- Column('x', String(50)),
- Column('y', MyString(50)
- )
+ 'test_table',
+ metadata,
+ Column('x', String(50)),
+ Column('y', MyString(50)
+ )
)
class TypeDecRoundTripTest(fixtures.TablesTest, RoundTripTestBase):
+
@classmethod
def define_tables(cls, metadata):
class MyString(TypeDecorator):
impl = String
+
def bind_expression(self, bindvalue):
return func.lower(bindvalue)
return func.upper(col)
Table(
- 'test_table',
- metadata,
- Column('x', String(50)),
- Column('y', MyString(50)
- )
+ 'test_table',
+ metadata,
+ Column('x', String(50)),
+ Column('y', MyString(50)
+ )
)
+
class ReturningTest(fixtures.TablesTest):
__requires__ = 'returning',
@classmethod
def define_tables(cls, metadata):
class MyString(String):
+
def column_expression(self, col):
return func.lower(col)
Table(
- 'test_table',
- metadata, Column('x', String(50)),
- Column('y', MyString(50), server_default="YVALUE")
+ 'test_table',
+ metadata, Column('x', String(50)),
+ Column('y', MyString(50), server_default="YVALUE")
)
@testing.provide_metadata
def test_insert_returning(self):
table = self.tables.test_table
result = testing.db.execute(
- table.insert().returning(table.c.y),
- {"x": "xvalue"}
+ table.insert().returning(table.c.y),
+ {"x": "xvalue"}
)
eq_(
result.first(),
("yvalue",)
)
-
-
class AdaptTest(fixtures.TestBase):
+
def _all_dialect_modules(self):
return [
getattr(dialects, d)
class TypeAffinityTest(fixtures.TestBase):
+
def test_type_affinity(self):
for type_, affin in [
(String(), String),
class PickleMetadataTest(fixtures.TestBase):
+
def testmeta(self):
for loads, dumps in picklers():
column_types = [
class UserDefinedTest(fixtures.TablesTest, AssertsCompiledSQL):
+
"""tests user-defined types."""
def test_processing(self):
def test_user_defined_typedec_impl_bind(self):
class TypeOne(types.TypeEngine):
+
def bind_processor(self, dialect):
def go(value):
return value + " ONE"
return go
class TypeTwo(types.TypeEngine):
+
def bind_processor(self, dialect):
def go(value):
return value + " TWO"
def test_user_defined_dialect_specific_args(self):
class MyType(types.UserDefinedType):
+
def __init__(self, foo='foo', **kwargs):
super(MyType, self).__init__()
self.foo = foo
@classmethod
def define_tables(cls, metadata):
class MyType(types.UserDefinedType):
+
def get_col_spec(self):
return "VARCHAR(100)"
return MyNewIntType()
class MyNewIntSubClass(MyNewIntType):
+
def process_result_value(self, value, dialect):
return value * 15
# test coerce from nulltype - e.g. use an object that
# does't match to a known type
class MyObj(object):
+
def __str__(self):
return "THISISMYOBJ"
t.insert().values(data=coerce_fn('d1', MyType)).execute()
class MyFoob(object):
+
def __clause_element__(self):
return t.c.data
class VariantTest(fixtures.TestBase, AssertsCompiledSQL):
+
def setup(self):
class UTypeOne(types.UserDefinedType):
+
def get_col_spec(self):
return "UTYPEONE"
return process
class UTypeTwo(types.UserDefinedType):
+
def get_col_spec(self):
return "UTYPETWO"
return process
class UTypeThree(types.UserDefinedType):
+
def get_col_spec(self):
return "UTYPETHREE"
class UnicodeTest(fixtures.TestBase):
+
"""Exercise the Unicode and related types.
Note: unicode round trip tests are now in
('mysql', 'mysqlconnector'),
('sqlite', 'pysqlite'),
('oracle', 'zxjdbc'),
- )
+ )
eq_(
testing.db.dialect.returns_unicode_strings,
class EnumTest(AssertsCompiledSQL, fixtures.TestBase):
+
@classmethod
def setup_class(cls):
global enum_table, non_native_enum_table, metadata
def test_non_native_constraint_custom_type(self):
class Foob(object):
+
def __init__(self, name):
self.name = name
class MyEnum(types.SchemaType, TypeDecorator):
+
def __init__(self, values):
self.impl = Enum(
*[v.name for v in values], name="myenum",
global test_table, meta, MyCustomType, MyTypeDec
class MyCustomType(types.UserDefinedType):
+
def get_col_spec(self):
return "INT"
return process
class MyOldCustomType(MyCustomType):
+
def adapt_operator(self, op):
return {
operators.add: operators.sub,
eq_(
test_table.select().execute().fetchall(),
[(1, 'somedata', datetime.date(2007, 10, 15), 25,
- 'BIND_INfooBIND_OUT')]
+ 'BIND_INfooBIND_OUT')]
)
def test_bind_adapt(self):
class NumericRawSQLTest(fixtures.TestBase):
+
"""Test what DBAPIs and dialects return without any typing
information supplied at the SQLA level.
"""
+
def _fixture(self, metadata, type, data):
t = Table('t', metadata, Column("val", type))
metadata.create_all()
class IntervalTest(fixtures.TestBase, AssertsExecutionResults):
+
@classmethod
def setup_class(cls):
global interval_table, metadata
def test_non_native_adapt(self):
interval = Interval(native=False)
adapted = interval.dialect_impl(testing.db.dialect)
- assert type(adapted) is Interval
+ assert isinstance(adapted, Interval)
assert adapted.native is False
eq_(str(adapted), "DATETIME")
class BooleanTest(
fixtures.TablesTest, AssertsExecutionResults, AssertsCompiledSQL):
+
"""test edge cases for booleans. Note that the main boolean test suite
is now in testing/suite/test_types.py
def test_non_native_constraint_custom_type(self):
class Foob(object):
+
def __init__(self, value):
self.value = value
class PickleTest(fixtures.TestBase):
+
def test_eq_comparison(self):
p1 = PickleType()
class CallableTest(fixtures.TestBase):
+
@classmethod
def setup_class(cls):
global meta
from sqlalchemy.testing.schema import Table, Column
from sqlalchemy.util import u, ue
+
class UnicodeSchemaTest(fixtures.TestBase):
__requires__ = ('unicode_ddl',)
__backend__ = True
metadata = MetaData(testing.db)
t1 = Table(u('unitable1'), metadata,
- Column(u('méil'), Integer, primary_key=True),
- Column(ue('\u6e2c\u8a66'), Integer),
- test_needs_fk=True,
- )
- t2 = Table(u('Unitéble2'), metadata,
- Column(u('méil'), Integer, primary_key=True, key="a"),
- Column(ue('\u6e2c\u8a66'), Integer, ForeignKey(u('unitable1.méil')),
- key="b"
- ),
+ Column(u('méil'), Integer, primary_key=True),
+ Column(ue('\u6e2c\u8a66'), Integer),
test_needs_fk=True,
- )
+ )
+ t2 = Table(
+ u('Unitéble2'),
+ metadata,
+ Column(
+ u('méil'),
+ Integer,
+ primary_key=True,
+ key="a"),
+ Column(
+ ue('\u6e2c\u8a66'),
+ Integer,
+ ForeignKey(
+ u('unitable1.méil')),
+ key="b"),
+ test_needs_fk=True,
+ )
# Few DBs support Unicode foreign keys
if testing.against('sqlite'):
metadata.drop_all()
def test_insert(self):
- t1.insert().execute({u('méil'):1, ue('\u6e2c\u8a66'):5})
- t2.insert().execute({u('a'):1, u('b'):1})
+ t1.insert().execute({u('méil'): 1, ue('\u6e2c\u8a66'): 5})
+ t2.insert().execute({u('a'): 1, u('b'): 1})
t3.insert().execute({ue('\u6e2c\u8a66_id'): 1,
ue('unitable1_\u6e2c\u8a66'): 5,
u('Unitéble2_b'): 1,
u('Unitéble2_b'): 1,
ue('\u6e2c\u8a66_self'): 1})
- self.assert_(tt1.select(order_by=desc(u('méil'))).execute().fetchall() ==
- [(2, 7), (1, 5)])
- self.assert_(tt2.select(order_by=desc(u('méil'))).execute().fetchall() ==
- [(2, 2), (1, 1)])
+ self.assert_(
+ tt1.select(
+ order_by=desc(
+ u('méil'))).execute().fetchall() == [
+ (2, 7), (1, 5)])
+ self.assert_(
+ tt2.select(
+ order_by=desc(
+ u('méil'))).execute().fetchall() == [
+ (2, 2), (1, 1)])
self.assert_(tt3.select(order_by=desc(ue('\u6e2c\u8a66_id'))).
execute().fetchall() ==
[(2, 7, 2, 2), (1, 5, 1, 1)])
def test_repr(self):
m = MetaData()
- t = Table(ue('\u6e2c\u8a66'), m, Column(ue('\u6e2c\u8a66_id'), Integer))
+ t = Table(
+ ue('\u6e2c\u8a66'),
+ m,
+ Column(
+ ue('\u6e2c\u8a66_id'),
+ Integer))
# I hardly understand what's going on with the backslashes in
# this one on py2k vs. py3k
- eq_(
- repr(t),
- (
- "Table('\\u6e2c\\u8a66', MetaData(bind=None), "
- "Column('\\u6e2c\\u8a66_id', Integer(), table=<\u6e2c\u8a66>), "
- "schema=None)"))
-
+ eq_(repr(t),
+ ("Table('\\u6e2c\\u8a66', MetaData(bind=None), "
+ "Column('\\u6e2c\\u8a66_id', Integer(), table=<\u6e2c\u8a66>), "
+ "schema=None)"))
class _UpdateFromTestBase(object):
+
@classmethod
def define_tables(cls, metadata):
Table('mytable', metadata,
self.assert_compile(
table1.update().
- where(table1.c.myid == 7).
- values({table1.c.myid: 5}),
+ where(table1.c.myid == 7).
+ values({table1.c.myid: 5}),
'UPDATE mytable SET myid=:myid WHERE mytable.myid = :myid_1',
checkparams={'myid': 5, 'myid_1': 7})
self.assert_compile(
update(table1,
- whereclause=table1.c.name == bindparam('crit'),
- values={table1.c.name: 'hi'}),
+ whereclause=table1.c.name == bindparam('crit'),
+ values={table1.c.name: 'hi'}),
'UPDATE mytable SET name=:name WHERE mytable.name = :crit',
params={'crit': 'notthere'},
checkparams={'crit': 'notthere', 'name': 'hi'})
self.assert_compile(
update(table1,
- table1.c.myid == 12,
- values={table1.c.name: table1.c.myid}),
+ table1.c.myid == 12,
+ values={table1.c.name: table1.c.myid}),
'UPDATE mytable '
'SET name=mytable.myid, description=:description '
'WHERE mytable.myid = :myid_1',
update(table1, table1.c.myid == 12, values=v1).values(v2),
'UPDATE mytable '
'SET '
- 'name=(mytable.name || :name_1), '
- 'description=:description '
+ 'name=(mytable.name || :name_1), '
+ 'description=:description '
'WHERE mytable.myid = :myid_1',
params={'description': 'test'})
table1.c.name: table1.c.name + 'lala',
table1.c.myid: func.do_stuff(table1.c.myid, literal('hoho'))
}
- self.assert_compile(update(table1,
- (table1.c.myid == func.hoho(4)) &
- (table1.c.name == literal('foo') +
- table1.c.name + literal('lala')),
- values=values),
+ self.assert_compile(
+ update(
+ table1,
+ (table1.c.myid == func.hoho(4)) & (
+ table1.c.name == literal('foo') +
+ table1.c.name +
+ literal('lala')),
+ values=values),
'UPDATE mytable '
'SET '
- 'myid=do_stuff(mytable.myid, :param_1), '
- 'name=(mytable.name || :name_1) '
+ 'myid=do_stuff(mytable.myid, :param_1), '
+ 'name=(mytable.name || :name_1) '
'WHERE '
- 'mytable.myid = hoho(:hoho_1) AND '
- 'mytable.name = :param_2 || mytable.name || :param_3')
+ 'mytable.myid = hoho(:hoho_1) AND '
+ 'mytable.name = :param_2 || mytable.name || :param_3')
def test_where_empty(self):
table1 = self.tables.mytable
self.assert_compile(
- table1.update().where(and_()),
- "UPDATE mytable SET myid=:myid, name=:name, description=:description"
- )
+ table1.update().where(
+ and_()),
+ "UPDATE mytable SET myid=:myid, name=:name, description=:description")
self.assert_compile(
- table1.update().where(or_()),
- "UPDATE mytable SET myid=:myid, name=:name, description=:description"
- )
+ table1.update().where(
+ or_()),
+ "UPDATE mytable SET myid=:myid, name=:name, description=:description")
def test_prefix_with(self):
table1 = self.tables.mytable
prefix_with('C', 'D')
self.assert_compile(stmt,
- 'UPDATE C D mytable SET myid=:myid, name=:name, '
- 'description=:description')
+ 'UPDATE C D mytable SET myid=:myid, name=:name, '
+ 'description=:description')
- self.assert_compile(stmt,
+ self.assert_compile(
+ stmt,
'UPDATE A B C D mytable SET myid=%s, name=%s, description=%s',
dialect=mysql.dialect())
-
def test_update_to_expression(self):
"""test update from an expression.
expr = func.foo(table1.c.myid)
eq_(expr.key, None)
self.assert_compile(table1.update().values({expr: 'bar'}),
- 'UPDATE mytable SET foo(myid)=:param_1')
+ 'UPDATE mytable SET foo(myid)=:param_1')
def test_update_bound_ordering(self):
"""test that bound parameters between the UPDATE and FROM clauses
table2 = self.tables.myothertable
sel = select([table2]).where(table2.c.otherid == 5).alias()
upd = table1.update().\
- where(table1.c.name == sel.c.othername).\
- values(name='foo')
+ where(table1.c.name == sel.c.othername).\
+ values(name='foo')
dialect = default.DefaultDialect()
dialect.positional = True
)
-
class UpdateFromCompileTest(_UpdateFromTestBase, fixtures.TablesTest,
AssertsCompiledSQL):
__dialect__ = 'default'
# in values. The behavior here isn't really defined
self.assert_compile(
update(talias1, talias1.c.myid == 7).
- values({table1.c.name: "fred"}),
+ values({table1.c.name: "fred"}),
'UPDATE mytable AS t1 '
'SET name=:name '
'WHERE t1.myid = :myid_1')
# as an "extra table", hence we see the full table name rendered.
self.assert_compile(
update(talias1, table1.c.myid == 7).
- values({table1.c.name: 'fred'}),
+ values({table1.c.name: 'fred'}),
'UPDATE mytable AS t1 '
'SET name=:mytable_name '
'FROM mytable '
'WHERE mytable.myid = :myid_1',
checkparams={'mytable_name': 'fred', 'myid_1': 7},
- )
+ )
def test_alias_two_mysql(self):
table1 = self.tables.mytable
self.assert_compile(
update(talias1, table1.c.myid == 7).
- values({table1.c.name: 'fred'}),
+ values({table1.c.name: 'fred'}),
"UPDATE mytable AS t1, mytable SET mytable.name=%s "
"WHERE mytable.myid = %s",
checkparams={'mytable_name': 'fred', 'myid_1': 7},
self.assert_compile(
users.update().
- values(name='newname').\
- values({addresses.c.name: "new address"}).\
- where(users.c.id == addresses.c.user_id),
+ values(name='newname').
+ values({addresses.c.name: "new address"}).
+ where(users.c.id == addresses.c.user_id),
"UPDATE users, addresses SET addresses.name=%s, "
- "users.name=%s WHERE users.id = addresses.user_id",
+ "users.name=%s WHERE users.id = addresses.user_id",
checkparams={'addresses_name': 'new address', 'name': 'newname'},
dialect='mysql'
)
self.assert_compile(
users.update().
- values(name='newname').
- where(users.c.id == addresses.c.user_id).
- where(addresses.c.email_address == 'e1'),
+ values(name='newname').
+ where(users.c.id == addresses.c.user_id).
+ where(addresses.c.email_address == 'e1'),
'UPDATE users '
'SET name=:name FROM addresses '
'WHERE '
- 'users.id = addresses.user_id AND '
- 'addresses.email_address = :email_address_1',
+ 'users.id = addresses.user_id AND '
+ 'addresses.email_address = :email_address_1',
checkparams={'email_address_1': 'e1', 'name': 'newname'})
def test_render_multi_table(self):
self.assert_compile(
users.update().
- values(name='newname').
- where(users.c.id == addresses.c.user_id).
- where(addresses.c.email_address == 'e1').
- where(addresses.c.id == dingalings.c.address_id).
- where(dingalings.c.id == 2),
+ values(name='newname').
+ where(users.c.id == addresses.c.user_id).
+ where(addresses.c.email_address == 'e1').
+ where(addresses.c.id == dingalings.c.address_id).
+ where(dingalings.c.id == 2),
'UPDATE users '
'SET name=:name '
'FROM addresses, dingalings '
'WHERE '
- 'users.id = addresses.user_id AND '
- 'addresses.email_address = :email_address_1 AND '
- 'addresses.id = dingalings.address_id AND '
- 'dingalings.id = :id_1',
+ 'users.id = addresses.user_id AND '
+ 'addresses.email_address = :email_address_1 AND '
+ 'addresses.id = dingalings.address_id AND '
+ 'dingalings.id = :id_1',
checkparams=checkparams)
def test_render_table_mysql(self):
self.assert_compile(
users.update().
- values(name='newname').
- where(users.c.id == addresses.c.user_id).
- where(addresses.c.email_address == 'e1'),
+ values(name='newname').
+ where(users.c.id == addresses.c.user_id).
+ where(addresses.c.email_address == 'e1'),
'UPDATE users, addresses '
'SET users.name=%s '
'WHERE '
- 'users.id = addresses.user_id AND '
- 'addresses.email_address = %s',
+ 'users.id = addresses.user_id AND '
+ 'addresses.email_address = %s',
checkparams={'email_address_1': 'e1', 'name': 'newname'},
dialect=mysql.dialect())
subq = select(cols).where(addresses.c.id == 7).alias()
self.assert_compile(
users.update().
- values(name='newname').
- where(users.c.id == subq.c.user_id).
- where(subq.c.email_address == 'e1'),
+ values(name='newname').
+ where(users.c.id == subq.c.user_id).
+ where(subq.c.email_address == 'e1'),
'UPDATE users '
'SET name=:name FROM ('
- 'SELECT '
- 'addresses.id AS id, '
- 'addresses.user_id AS user_id, '
- 'addresses.email_address AS email_address '
- 'FROM addresses '
- 'WHERE addresses.id = :id_1'
+ 'SELECT '
+ 'addresses.id AS id, '
+ 'addresses.user_id AS user_id, '
+ 'addresses.email_address AS email_address '
+ 'FROM addresses '
+ 'WHERE addresses.id = :id_1'
') AS anon_1 '
'WHERE users.id = anon_1.user_id '
'AND anon_1.email_address = :email_address_1',
testing.db.execute(
addresses.update().
- values(email_address=users.c.name).
- where(users.c.id == addresses.c.user_id).
- where(users.c.name == 'ed'))
+ values(email_address=users.c.name).
+ where(users.c.id == addresses.c.user_id).
+ where(users.c.name == 'ed'))
expected = [
(1, 7, 'x', 'jack@bean.com'),
a1 = addresses.alias()
testing.db.execute(
addresses.update().
- values(email_address=users.c.name).
- where(users.c.id == a1.c.user_id).
- where(users.c.name == 'ed').
- where(a1.c.id == addresses.c.id)
+ values(email_address=users.c.name).
+ where(users.c.id == a1.c.user_id).
+ where(users.c.name == 'ed').
+ where(a1.c.id == addresses.c.id)
)
expected = [
testing.db.execute(
addresses.update().
- values(email_address=users.c.name).
- where(users.c.id == addresses.c.user_id).
- where(users.c.name == 'ed').
- where(addresses.c.id == dingalings.c.address_id).
- where(dingalings.c.id == 1))
+ values(email_address=users.c.name).
+ where(users.c.id == addresses.c.user_id).
+ where(users.c.name == 'ed').
+ where(addresses.c.id == dingalings.c.address_id).
+ where(dingalings.c.id == 1))
expected = [
(1, 7, 'x', 'jack@bean.com'),
testing.db.execute(
addresses.update().
- values(values).
- where(users.c.id == addresses.c.user_id).
- where(users.c.name == 'ed'))
+ values(values).
+ where(users.c.id == addresses.c.user_id).
+ where(users.c.name == 'ed'))
expected = [
(1, 7, 'x', 'jack@bean.com'),
testing.db.execute(
addresses.update().
- values(values).
- where(users.c.id == addresses.c.user_id).
- where(users.c.name == 'ed'))
+ values(values).
+ where(users.c.id == addresses.c.user_id).
+ where(users.c.name == 'ed'))
expected = [
(1, 7, 'x', 'jack@bean.com'),
test_needs_autoincrement=True),
Column('user_id', None, ForeignKey('users.id')),
Column('email_address', String(50), nullable=False),
- )
+ )
Table('foobar', metadata,
Column('id', Integer, primary_key=True,
Column('user_id', None, ForeignKey('users.id')),
Column('data', String(30)),
Column('some_update', String(30), onupdate='im the other update')
- )
+ )
@classmethod
def fixtures(cls):
ret = testing.db.execute(
addresses.update().
- values(values).
- where(users.c.id == addresses.c.user_id).
- where(users.c.name == 'ed'))
+ values(values).
+ where(users.c.id == addresses.c.user_id).
+ where(users.c.name == 'ed'))
eq_(set(ret.prefetch_cols()), set([users.c.some_update]))
ret = testing.db.execute(
users.update().
- values(values).
- where(users.c.id == foobar.c.user_id).
- where(users.c.name == 'ed'))
+ values(values).
+ where(users.c.id == foobar.c.user_id).
+ where(users.c.name == 'ed'))
eq_(
set(ret.prefetch_cols()),
ret = testing.db.execute(
addresses.update().
- values({'email_address': users.c.name}).
- where(users.c.id == addresses.c.user_id).
- where(users.c.name == 'ed'))
+ values({'email_address': users.c.name}).
+ where(users.c.id == addresses.c.user_id).
+ where(users.c.name == 'ed'))
eq_(ret.prefetch_cols(), [])
[flake8]
show-source = True
-ignore = E711,E265,H305,H307,H402,H405,H703,H803,H904
+ignore = E711,E712,F841,F811
exclude=.venv,.git,.tox,dist,doc,*egg,build