Here are the examples of the python api sqlalchemy.select.where taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
134 Examples
5
Example 1
def get_current_state(job):
"""Returns the current state of the job, fetched from the database.
Note that you usually don't need to use this method. The jobs
object state, especially when just fetched from the database, is
most probably accurate. This method exists to check the job states
after job execution of long running jobs.
:param job: the job
:returns: the jobs state as stored in the database
"""
t = Job.__table__
q = select([t.c.state]).where(t.c.id == job.id)
conn = engine.connect()
r = conn.execute(q)
state = r.fetchone()[0]
conn.close()
return state
3
Example 2
Project: sqlalchemy Source File: test_insert.py
def test_insert_from_select_select(self):
table1 = self.tables.mytable
sel = select([table1.c.myid, table1.c.name]).where(
table1.c.name == 'foo')
ins = self.tables.myothertable.insert().\
from_select(("otherid", "othername"), sel)
self.assert_compile(
ins,
"INSERT INTO myothertable (otherid, othername) "
"SELECT mytable.myid, mytable.name FROM mytable "
"WHERE mytable.name = :name_1",
checkparams={"name_1": "foo"}
)
3
Example 3
Project: ibis Source File: test_sqlalchemy.py
def test_where_correlated_subquery(self):
expr = self._case_where_correlated_subquery()
foo = self._to_sqla(self.foo)
t0 = foo.alias('t0')
t1 = foo.alias('t1')
subq = (sa.select([F.avg(t1.c.y).label('mean')])
.where(t0.c.dept_id == t1.c.dept_id))
stmt = sa.select([t0]).where(t0.c.y > subq)
self._compare_sqla(expr, stmt)
3
Example 4
Project: lrrbot Source File: storm.py
def get(engine, metadata, counter):
storm = metadata.tables['storm']
with engine.begin() as conn:
row = conn.execute(sqlalchemy.select([storm.c[counter]])
.where(storm.c.date == datetime.datetime.now(config['timezone']).date())) \
.first()
if row is not None:
return row[0]
return 0
3
Example 5
def test_alias(self):
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(
s,
"SELECT mytable.myid, mytable.name, mytable.description "
"FROM mytable, (select id, name from user) AS t "
"WHERE mytable.myid = t.id"
)
3
Example 6
Project: sqlalchemy Source File: test_compiler.py
def test_delete_schema_multipart_needs_quoting(self):
metadata = MetaData()
tbl = Table(
'test', metadata,
Column('id', Integer, primary_key=True),
schema='banana split.paj')
self.assert_compile(tbl.delete(tbl.c.id == 1),
'DELETE FROM [banana split].paj.test WHERE '
'[banana split].paj.test.id = :id_1')
s = select([tbl.c.id]).where(tbl.c.id == 1)
self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)),
'DELETE FROM [banana split].paj.test WHERE '
'[banana split].paj.test.id IN ('
'SELECT [banana split].paj.test.id FROM '
'[banana split].paj.test WHERE '
'[banana split].paj.test.id = :id_1)')
3
Example 7
def mkshield(self):
route = self.tables.routes
rel = self.osmdata.relation.data
sel = select([rel.c.tags, route.data.c.country, route.data.c.level])\
.where(rel.c.id == route.data.c.id)
donesyms = set()
with self.engine.begin() as conn:
for r in conn.execution_options(stream_results=True).execute(sel):
sym = route.symbols.create(TagStore(r["tags"]), r["country"],
r["level"])
if sym is not None:
symid = sym.get_id()
if symid not in donesyms:
donesyms.add(symid)
route.symbols.write(sym, True)
3
Example 8
Project: sqlalchemy Source File: short_selects.py
@Profiler.profile
def test_core_new_stmt_each_time(n):
"""test core, creating a new statement each time."""
with engine.connect() as conn:
for id_ in random.sample(ids, n):
stmt = select([Customer.__table__]).where(Customer.id == id_)
row = conn.execute(stmt).first()
tuple(row)
3
Example 9
Project: sqlalchemy Source File: short_selects.py
@Profiler.profile
def test_core_reuse_stmt_compiled_cache(n):
"""test core, reusing the same statement + compiled cache."""
compiled_cache = {}
stmt = select([Customer.__table__]).where(Customer.id == bindparam('id'))
with engine.connect().\
execution_options(compiled_cache=compiled_cache) as conn:
for id_ in random.sample(ids, n):
row = conn.execute(stmt, id=id_).first()
tuple(row)
3
Example 10
Project: lrrbot Source File: live.py
@bot.command("live unregister")
@asyncio.coroutine
def unregister_self(lrrbot, conn, event, respond_to):
"""
Command: !live unregister
Unregister your channel as a fanstreamer channel.
"""
channel = irc.client.NickMask(event.source).nick.lower()
users = lrrbot.metadata.tables["users"]
with lrrbot.engine.begin() as pg_conn:
token, = pg_conn.execute(sqlalchemy.select([users.c.twitch_oauth])
.where(users.c.name == config["username"])).first()
yield from twitch.unfollow_channel(channel, token)
conn.privmsg(respond_to, "Channel '%s' removed from the fanstreamer list." % channel)
3
Example 11
Project: sqlalchemy Source File: test_insert.py
def test_insert_from_select_with_python_defaults(self):
metadata = MetaData()
table = Table('sometable', metadata,
Column('id', Integer, primary_key=True),
Column('foo', Integer, default=12))
table1 = self.tables.mytable
sel = select([table1.c.myid]).where(table1.c.name == 'foo')
ins = table.insert().\
from_select(["id"], sel)
self.assert_compile(
ins,
"INSERT INTO sometable (id, foo) SELECT "
"mytable.myid, :foo AS anon_1 "
"FROM mytable WHERE mytable.name = :name_1",
# value filled in at execution time
checkparams={"name_1": "foo", "foo": None}
)
3
Example 12
Project: sqlalchemy Source File: test_insert.py
def test_insert_select_return_defaults(self):
table1 = self.tables.mytable
sel = select([table1.c.myid, table1.c.name]).where(
table1.c.name == 'foo')
ins = self.tables.myothertable.insert().\
from_select(("otherid", "othername"), sel).\
return_defaults(self.tables.myothertable.c.otherid)
self.assert_compile(
ins,
"INSERT INTO myothertable (otherid, othername) "
"SELECT mytable.myid, mytable.name FROM mytable "
"WHERE mytable.name = %(name_1)s",
checkparams={"name_1": "foo"}
)
3
Example 13
def test_delete_schema(self):
metadata = MetaData()
tbl = Table('test', metadata, Column('id', Integer,
primary_key=True), schema='paj')
self.assert_compile(tbl.delete(tbl.c.id == 1),
'DELETE FROM paj.test WHERE paj.test.id = '
':id_1')
s = select([tbl.c.id]).where(tbl.c.id == 1)
self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)),
'DELETE FROM paj.test WHERE paj.test.id IN '
'(SELECT paj.test.id FROM paj.test '
'WHERE paj.test.id = :id_1)')
3
Example 14
Project: CloudBot Source File: karma.py
@hook.command('karma', 'k')
def karma(text, db):
"""k/karma <nick> -- returns karma stats for <nick>"""
query = db.execute(
select([karma_table])
.where(karma_table.c.nick_vote == text.lower())
).fetchone()
if not query:
return "That user has no karma :("
else:
return "{} has \x02{}\x02 karma!".format(text, query['up_karma'] - query['down_karma'])
3
Example 15
Project: ibis Source File: test_sqlalchemy.py
def test_where_simple_comparisons(self):
expr = self._case_where_simple_comparisons()
st = self.sa_star1.alias('t0')
clause = sql.and_(st.c.f > L(0), st.c.c < (st.c.f * L(2)))
expected = sa.select([st]).where(clause)
self._compare_sqla(expr, expected)
3
Example 16
@cherrypy.expose
def geometry(self, oid, factor=None, **params):
w = cherrypy.request.app.config['DB']['map'].tables.ways.data
if factor is None:
field = w.c.geom
else:
field = w.c.geom.ST_Simplify(w.c.geom.ST_NPoints()/int(factor))
field = field.ST_AsGeoJSON()
res = cherrypy.request.db.execute(sa.select([field]).where(w.c.id==oid)).first()
return self.create_geometry_response(res)
3
Example 17
def test_unicode(self):
m = MetaData()
t = Table(ue('\u6e2c\u8a66'), m,
Column(ue('\u6e2c\u8a66_id'), Integer))
expr = select([t]).where(t.c[ue('\u6e2c\u8a66_id')] == 5)
expr2 = serializer.loads(serializer.dumps(expr, -1), m)
self.assert_compile(
expr2,
ue('SELECT "\u6e2c\u8a66"."\u6e2c\u8a66_id" FROM "\u6e2c\u8a66" '
'WHERE "\u6e2c\u8a66"."\u6e2c\u8a66_id" = :\u6e2c\u8a66_id_1'),
dialect="default"
)
3
Example 18
Project: waymarked-trails-site Source File: routes.py
def build_geometry(self, osmid):
# find all relation parts
h = self.hierarchy_table.data
parts = select([h.c.child]).where(h.c.parent == osmid)
# stick them together
s = self.segment_table.data
sel = select([func.st_linemerge(func.st_collect(s.c.geom))])\
.where(s.c.rels.op('&& ARRAY')(parts))
return self.thread.conn.scalar(sel)
3
Example 19
Project: pgcontents Source File: query.py
def get_remote_checkpoint(db, user_id, api_path, checkpoint_id, decrypt_func):
db_path = from_api_filename(api_path)
fields = [remote_checkpoints.c.content]
result = db.execute(
select(
fields,
).where(
and_(
remote_checkpoints.c.user_id == user_id,
remote_checkpoints.c.path == db_path,
remote_checkpoints.c.id == int(checkpoint_id),
),
)
).first() # NOTE: This applies a LIMIT 1 to the query.
if result is None:
raise NoSuchCheckpoint(api_path, checkpoint_id)
return to_dict_with_content(fields, result, decrypt_func)
3
Example 20
Project: lrrbot Source File: live.py
@bot.command("live register")
@asyncio.coroutine
def register_self(lrrbot, conn, event, respond_to):
"""
Command: !live register
Register your channel as a fanstreamer channel.
"""
channel = irc.client.NickMask(event.source).nick.lower()
users = lrrbot.metadata.tables["users"]
with lrrbot.engine.begin() as pg_conn:
token, = pg_conn.execute(sqlalchemy.select([users.c.twitch_oauth])
.where(users.c.name == config["username"])).first()
yield from twitch.follow_channel(channel, token)
conn.privmsg(respond_to, "Channel '%s' added to the fanstreamer list." % channel)
3
Example 21
Project: sqlalchemy Source File: test_insert.py
def test_insert_from_select_no_defaults(self):
metadata = MetaData()
table = Table('sometable', metadata,
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, include_defaults=False)
self.assert_compile(
ins,
"INSERT INTO sometable (id) SELECT mytable.myid "
"FROM mytable WHERE mytable.name = :name_1",
checkparams={"name_1": "foo"}
)
3
Example 22
Project: sqlalchemy Source File: test_insert.py
def test_insert_from_select_with_sql_defaults(self):
metadata = MetaData()
table = Table('sometable', metadata,
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)
self.assert_compile(
ins,
"INSERT INTO sometable (id, foo) SELECT "
"mytable.myid, foobar() AS foobar_1 "
"FROM mytable WHERE mytable.name = :name_1",
checkparams={"name_1": "foo"}
)
3
Example 23
Project: pgcontents Source File: query.py
def select_file_ids(db, user_id):
"""
Get all file ids for a user.
"""
return list(
db.execute(
select([files.c.id])
.where(files.c.user_id == user_id)
)
)
3
Example 24
Project: sqlalchemy Source File: test_select.py
def test_plain_union(self):
table = self.tables.some_table
s1 = select([table]).where(table.c.id == 2)
s2 = select([table]).where(table.c.id == 3)
u1 = union(s1, s2)
self._assert_result(
u1.order_by(u1.c.id),
[(2, 2, 3), (3, 3, 4)]
)
3
Example 25
Project: sqlalchemy Source File: test_insert.py
def test_insert_from_select_override_defaults(self):
metadata = MetaData()
table = Table('sometable', metadata,
Column('id', Integer, primary_key=True),
Column('foo', Integer, default=12))
table1 = self.tables.mytable
sel = select(
[table1.c.myid, table1.c.myid.label('q')]).where(
table1.c.name == 'foo')
ins = table.insert().\
from_select(["id", "foo"], sel)
self.assert_compile(
ins,
"INSERT INTO sometable (id, foo) SELECT "
"mytable.myid, mytable.myid AS q "
"FROM mytable WHERE mytable.name = :name_1",
checkparams={"name_1": "foo"}
)
3
Example 26
Project: sqlalchemy Source File: test_insert.py
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')
ins = self.tables.myothertable.insert().\
from_select(("otherid", "othername"), sel)
assert_raises_message(
exc.InvalidRequestError,
"This construct already inserts from a SELECT",
ins.values, othername="5"
)
3
Example 27
Project: sqlalchemy Source File: test_insert.py
def test_insert_select(self):
table1 = self.tables.mytable
sel = select([table1.c.myid, table1.c.name]).where(
table1.c.name == 'foo')
ins = self.tables.myothertable.insert().\
from_select(("otherid", "othername"), sel)
self.assert_compile(
ins,
"INSERT INTO myothertable (otherid, othername) "
"SELECT mytable.myid, mytable.name FROM mytable "
"WHERE mytable.name = %(name_1)s",
checkparams={"name_1": "foo"}
)
3
Example 28
Project: sqlalchemy Source File: test_types.py
def _test_index_criteria(self, crit, expected):
self._criteria_fixture()
with config.db.connect() as conn:
stmt = select([self.tables.data_table.c.name]).where(crit)
eq_(
conn.scalar(stmt),
expected
)
literal_sql = str(stmt.compile(
config.db, compile_kwargs={"literal_binds": True}))
eq_(conn.scalar(literal_sql), expected)
3
Example 29
Project: sqlalchemy Source File: test_text.py
def test_cte(self):
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(
s,
"WITH t AS (select id, name from user) "
"SELECT mytable.myid, mytable.name, mytable.description "
"FROM mytable, t WHERE mytable.myid = t.id"
)
3
Example 30
Project: sqlalchemy-redshift Source File: test_delete_stmt.py
def test_delete_stmt_subquery():
del_stmt = sa.delete(
orders
).where(
orders.c.customer_id.in_(
sa.select(
[customers.c.id]
).where(customers.c.email.endswith('test.com'))
)
)
expected = """
DELETE FROM orders
WHERE orders.customer_id IN
(SELECT customers.id
FROM customers
WHERE (customers.email LIKE '%%' || 'test.com'))"""
assert clean(compile_query(del_stmt)) == clean(expected)
3
Example 31
Project: sqlalchemy Source File: test_text.py
def test_scalar_subquery(self):
t = text("select id from user").columns(id=Integer)
subq = t.as_scalar()
assert subq.type._type_affinity is Integer()._type_affinity
s = select([table1.c.myid, subq]).where(table1.c.myid == subq)
self.assert_compile(
s,
"SELECT mytable.myid, (select id from user) AS anon_1 "
"FROM mytable WHERE mytable.myid = (select id from user)"
)
3
Example 32
Project: sqlalchemy Source File: test_compiler.py
def test_delete_schema_multipart(self):
metadata = MetaData()
tbl = Table(
'test', metadata,
Column('id', Integer,
primary_key=True),
schema='banana.paj')
self.assert_compile(tbl.delete(tbl.c.id == 1),
'DELETE FROM banana.paj.test WHERE '
'banana.paj.test.id = :id_1')
s = select([tbl.c.id]).where(tbl.c.id == 1)
self.assert_compile(tbl.delete().where(tbl.c.id.in_(s)),
'DELETE FROM banana.paj.test WHERE '
'banana.paj.test.id IN (SELECT banana.paj.test.id '
'FROM banana.paj.test WHERE '
'banana.paj.test.id = :id_1)')
3
Example 33
Project: pgcontents Source File: query.py
def directories_in_directory(db, user_id, db_dirname):
"""
Return subdirectories of a directory.
"""
fields = _directory_default_fields()
rows = db.execute(
select(
fields,
).where(
_is_in_directory(directories, user_id, db_dirname),
)
)
return [to_dict_no_content(fields, row) for row in rows]
3
Example 34
Project: sqlalchemy Source File: test_insert.py
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')
ins = self.tables.myothertable.insert().values(othername="5")
assert_raises_message(
exc.InvalidRequestError,
"This construct already inserts value expressions",
ins.from_select, ("otherid", "othername"), sel
)
3
Example 35
@cherrypy.expose
def geometry(self, oid, factor=None, **params):
r = cherrypy.request.app.config['DB']['map'].tables.routes.data
if factor is None:
field = r.c.geom
else:
field = r.c.geom.ST_Simplify(r.c.geom.ST_NPoints()/int(factor))
field = field.ST_AsGeoJSON()
res = cherrypy.request.db.execute(sa.select([field]).where(r.c.id==oid)).first()
return self.create_geometry_response(res)
3
Example 36
Project: sqlalchemy Source File: test_compiler.py
def test_delete_schema_multipart_both_need_quoting(self):
metadata = MetaData()
tbl = Table('test', metadata, Column('id', Integer,
primary_key=True),
schema='banana split.paj with a space')
self.assert_compile(tbl.delete(tbl.c.id == 1),
'DELETE FROM [banana split].[paj with a '
'space].test WHERE [banana split].[paj '
'with a space].test.id = :id_1')
s = select([tbl.c.id]).where(tbl.c.id == 1)
self.assert_compile(
tbl.delete().where(tbl.c.id.in_(s)),
"DELETE FROM [banana split].[paj with a space].test "
"WHERE [banana split].[paj with a space].test.id IN "
"(SELECT [banana split].[paj with a space].test.id "
"FROM [banana split].[paj with a space].test "
"WHERE [banana split].[paj with a space].test.id = :id_1)"
)
3
Example 37
@cherrypy.expose
def last_update(self):
status = cherrypy.request.app.config['DB']['map'].osmdata.status
mtype = cherrypy.request.app.config['Global']['BASENAME']
sel = sa.select([status.c.date]).where(status.c.part == mtype)
date = cherrypy.request.db.scalar(sel)
return date.isoformat() if date is not None else (dt.utcnow().isoformat() + 'Z')
3
Example 38
Project: plenario Source File: etl_tests.py
def test_update_with_change(self):
drop_if_exists(self.unloaded_meta.dataset_name)
etl = PlenarioETL(self.unloaded_meta, source_path=self.radio_path)
table = etl.add()
changed_path = os.path.join(fixtures_path, 'community_radio_events_changed.csv')
etl = PlenarioETL(self.unloaded_meta, source_path=changed_path)
etl.update()
sel = sa.select([table.c.date]).where(table.c.event_name == 'baz')
changed_date = app_engine.execute(sel).fetchone()[0]
self.assertEqual(changed_date, date(1993, 11, 10))
3
Example 39
def transform_tags(self, osmid, tags):
outtags, difficulty = _basic_tag_transform(osmid, tags)
# we don't support hierarchy at the moment
outtags['top'] = True
# find all relation parts
h = self.hierarchy_table.data
parts = select([h.c.child]).where(h.c.parent == osmid)
# get the geometry
s = self.segment_table.data
sel = select([func.st_linemerge(func.st_collect(s.c.geom))])\
.where(s.c.rels.op('&& ARRAY')(parts))
outtags['geom'] = self.thread.conn.scalar(sel)
outtags['symbol'] = self.symbols.create_write(tags, '', difficulty)
return outtags
3
Example 40
Project: sqlalchemy Source File: test_insert.py
def test_insert_from_select_returning(self):
table1 = self.tables.mytable
sel = select([table1.c.myid, table1.c.name]).where(
table1.c.name == 'foo')
ins = self.tables.myothertable.insert().\
from_select(("otherid", "othername"), sel).returning(
self.tables.myothertable.c.otherid
)
self.assert_compile(
ins,
"INSERT INTO myothertable (otherid, othername) "
"SELECT mytable.myid, mytable.name FROM mytable "
"WHERE mytable.name = %(name_1)s RETURNING myothertable.otherid",
checkparams={"name_1": "foo"},
dialect="postgresql"
)
3
Example 41
Project: lrrbot Source File: pubsub.py
def _token_for(self, user):
users = self.metadata.tables["users"]
with self.engine.begin() as conn:
row = conn.execute(sqlalchemy.select([users.c.twitch_oauth]).where(users.c.name == user)).first()
if row is not None:
return row[0]
raise Exception("User %r not found" % user)
3
Example 42
def get_info(self, gameno):
where = and_(game.c.source_id == source.c.id, game.c.id == self.games[gameno][0])
result = self.engine.execute(select([source.c.info]).where(where)).first()
if result is None:
return None
else:
return result[0]
3
Example 43
Project: lrrbot Source File: storm.py
def get_combined(engine, metadata):
combined_count = 0
storm = metadata.tables['storm']
with engine.begin() as conn:
for counter in COMBINED_COUNTERS:
row = conn.execute(sqlalchemy.select([storm.c[counter]])
.where(storm.c.date == datetime.datetime.now(config['timezone']).date())) \
.first()
if row is not None:
combined_count += row[0]
return combined_count
3
Example 44
Project: sqlalchemy Source File: test_insert.py
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')
ins = self.tables.myothertable.insert().\
from_select(("othername", "otherid"), sel)
self.assert_compile(
ins,
"INSERT INTO myothertable (othername, otherid) "
"SELECT mytable.name, mytable.myid FROM mytable "
"WHERE mytable.name = :name_1",
checkparams={"name_1": "foo"}
)
3
Example 45
Project: sqlalchemy Source File: short_selects.py
@Profiler.profile
def test_core_reuse_stmt(n):
"""test core, reusing the same statement (but recompiling each time)."""
stmt = select([Customer.__table__]).where(Customer.id == bindparam('id'))
with engine.connect() as conn:
for id_ in random.sample(ids, n):
row = conn.execute(stmt, id=id_).first()
tuple(row)
3
Example 46
Project: pychess Source File: database.py
def build_where_bitboards(self, ply, bb):
if ply:
bb_where = and_(bitboard.c.ply == ply, bitboard.c.bitboard == bb - self.DB_MAXINT_SHIFT)
stmt = select([bitboard.c.game_id]).where(bb_where)
self.where_bitboards = and_(game.c.id.in_(stmt))
self.ply = ply
else:
self.where_bitboards = None
self.ply = None
3
Example 47
def _dir_exists(db, user_id, db_dirname):
"""
Internal implementation of dir_exists.
Expects a db-style path name.
"""
return db.execute(
select(
[func.count(directories.c.name)],
).where(
and_(
directories.c.user_id == user_id,
directories.c.name == db_dirname,
),
)
).scalar() != 0
3
Example 48
Project: pgcontents Source File: query.py
def select_remote_checkpoint_ids(db, user_id):
"""
Get all file ids for a user.
"""
return list(
db.execute(
select([remote_checkpoints.c.id])
.where(remote_checkpoints.c.user_id == user_id)
)
)
3
Example 49
Project: sqlalchemy Source File: test_select.py
def test_select_from_plain_union(self):
table = self.tables.some_table
s1 = select([table]).where(table.c.id == 2)
s2 = select([table]).where(table.c.id == 3)
u1 = union(s1, s2).alias().select()
self._assert_result(
u1.order_by(u1.c.id),
[(2, 2, 3), (3, 3, 4)]
)
3
Example 50
Project: sqlalchemy Source File: test_insert.py
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')
ins = table2.insert().\
from_select((table2.c.otherid, table2.c.othername), sel)
self.assert_compile(
ins,
"INSERT INTO myothertable (otherid, othername) "
"SELECT mytable.myid, mytable.name FROM mytable "
"WHERE mytable.name = :name_1",
checkparams={"name_1": "foo"}
)