From a2f992a37ed3807bde61365a6c1072ae28b36599 Mon Sep 17 00:00:00 2001 From: Mike Bayer Date: Mon, 3 Aug 2009 00:36:36 +0000 Subject: [PATCH] renamed last_inserted_ids() to inserted_primary_key --- 06CHANGES | 3 ++ doc/build/metadata.rst | 2 +- doc/build/sqlexpression.rst | 4 +- .../dialects/informix/informixdb.py | 2 +- lib/sqlalchemy/dialects/postgresql/base.py | 4 +- lib/sqlalchemy/engine/base.py | 45 ++++++++++--------- lib/sqlalchemy/engine/default.py | 28 +++++------- lib/sqlalchemy/orm/mapper.py | 2 +- lib/sqlalchemy/sql/compiler.py | 9 +++- test/aaa_profiling/test_zoomark.py | 20 ++++----- test/dialect/test_mssql.py | 6 +-- test/dialect/test_postgresql.py | 14 +++--- test/engine/test_execute.py | 2 +- test/sql/test_defaults.py | 24 +++++----- test/sql/test_functions.py | 2 +- test/sql/test_query.py | 10 ++--- 16 files changed, 94 insertions(+), 83 deletions(-) diff --git a/06CHANGES b/06CHANGES index bc2eb56f65..4c7f9ca693 100644 --- a/06CHANGES +++ b/06CHANGES @@ -25,6 +25,9 @@ generated sequence value (i.e. MySQL, MS-SQL) now work correctly when there is a composite primary key where the "autoincrement" column is not the first primary key column in the table. + + - the last_inserted_ids() method has been renamed to the descriptor + "inserted_primary_key". - engines - transaction isolation level may be specified with diff --git a/doc/build/metadata.rst b/doc/build/metadata.rst index f79c637ee0..464b764bf1 100644 --- a/doc/build/metadata.rst +++ b/doc/build/metadata.rst @@ -396,7 +396,7 @@ The above SQL functions are usually executed "inline" with the INSERT or UPDATE * the ``inline=True`` flag is not set on the ``Insert()`` or ``Update()`` construct. -For a statement execution which is not an executemany, the returned ``ResultProxy`` will contain a collection accessible via ``result.postfetch_cols()`` which contains a list of all ``Column`` objects which had an inline-executed default. Similarly, all parameters which were bound to the statement, including all Python and SQL expressions which were pre-executed, are present in the ``last_inserted_params()`` or ``last_updated_params()`` collections on ``ResultProxy``. The ``last_inserted_ids()`` collection contains a list of primary key values for the row inserted. +For a statement execution which is not an executemany, the returned ``ResultProxy`` will contain a collection accessible via ``result.postfetch_cols()`` which contains a list of all ``Column`` objects which had an inline-executed default. Similarly, all parameters which were bound to the statement, including all Python and SQL expressions which were pre-executed, are present in the ``last_inserted_params()`` or ``last_updated_params()`` collections on ``ResultProxy``. The ``inserted_primary_key`` collection contains a list of primary key values for the row inserted. DDL-Level Defaults ------------------- diff --git a/doc/build/sqlexpression.rst b/doc/build/sqlexpression.rst index 387013cacc..2bcaa631d2 100644 --- a/doc/build/sqlexpression.rst +++ b/doc/build/sqlexpression.rst @@ -143,10 +143,10 @@ What about the ``result`` variable we got when we called ``execute()`` ? As the .. sourcecode:: pycon+sql - >>> result.last_inserted_ids() + >>> result.inserted_primary_key [1] -The value of ``1`` was automatically generated by SQLite, but only because we did not specify the ``id`` column in our ``Insert`` statement; otherwise, our explicit value would have been used. In either case, SQLAlchemy always knows how to get at a newly generated primary key value, even though the method of generating them is different across different databases; each databases' ``Dialect`` knows the specific steps needed to determine the correct value (or values; note that ``last_inserted_ids()`` returns a list so that it supports composite primary keys). +The value of ``1`` was automatically generated by SQLite, but only because we did not specify the ``id`` column in our ``Insert`` statement; otherwise, our explicit value would have been used. In either case, SQLAlchemy always knows how to get at a newly generated primary key value, even though the method of generating them is different across different databases; each databases' ``Dialect`` knows the specific steps needed to determine the correct value (or values; note that ``inserted_primary_key`` returns a list so that it supports composite primary keys). Executing Multiple Statements ============================== diff --git a/lib/sqlalchemy/dialects/informix/informixdb.py b/lib/sqlalchemy/dialects/informix/informixdb.py index 68c4feebbe..4e929e024d 100644 --- a/lib/sqlalchemy/dialects/informix/informixdb.py +++ b/lib/sqlalchemy/dialects/informix/informixdb.py @@ -37,7 +37,7 @@ class InfoExecutionContext(default.DefaultExecutionContext): # 4 - offset of the error into the SQL statement # 5 - rowid after insert def post_exec(self): - if getattr(self.compiled, "isinsert", False) and self.last_inserted_ids() is None: + if getattr(self.compiled, "isinsert", False) and self.inserted_primary_key is None: self._last_inserted_ids = [self.cursor.sqlerrd[1]] elif hasattr( self.compiled , 'offset' ): self.cursor.offset( self.compiled.offset ) diff --git a/lib/sqlalchemy/dialects/postgresql/base.py b/lib/sqlalchemy/dialects/postgresql/base.py index a865f069bd..23e1445488 100644 --- a/lib/sqlalchemy/dialects/postgresql/base.py +++ b/lib/sqlalchemy/dialects/postgresql/base.py @@ -748,9 +748,11 @@ class PGDialect(default.DefaultDialect): (attype, name)) coltype = sqltypes.NULLTYPE # adjust the default value + autoincrement = False if default is not None: match = re.search(r"""(nextval\(')([^']+)('.*$)""", default) if match is not None: + autoincrement = True # the default is related to a Sequence sch = schema if '.' not in match.group(2) and sch is not None: @@ -759,7 +761,7 @@ class PGDialect(default.DefaultDialect): default = match.group(1) + ('"%s"' % sch) + '.' + match.group(2) + match.group(3) column_info = dict(name=name, type=coltype, nullable=nullable, - default=default) + default=default, autoincrement=autoincrement) columns.append(column_info) return columns diff --git a/lib/sqlalchemy/engine/base.py b/lib/sqlalchemy/engine/base.py index 538ab88918..a48f650508 100644 --- a/lib/sqlalchemy/engine/base.py +++ b/lib/sqlalchemy/engine/base.py @@ -119,9 +119,9 @@ class Dialect(object): implicit_returning use RETURNING or equivalent during INSERT execution in order to load newly generated primary keys and other column defaults in one execution, - which are then available via last_inserted_ids(). + which are then available via inserted_primary_key. If an insert statement has returning() specified explicitly, - the "implicit" functionality is not used and last_inserted_ids() + the "implicit" functionality is not used and inserted_primary_key will not be available. dbapi_type_map @@ -532,17 +532,6 @@ class ExecutionContext(object): raise NotImplementedError() - def last_inserted_ids(self): - """Return the list of the primary key values for the last insert statement executed. - - This does not apply to straight textual clauses; only to - ``sql.Insert`` objects compiled against a ``schema.Table`` - object. The order of items in the list is the same as that of - the Table's 'primary_key' attribute. - """ - - raise NotImplementedError() - def last_inserted_params(self): """Return a dictionary of the full parameter dictionary for the last compiled INSERT statement. @@ -1078,6 +1067,7 @@ class Connection(Connectable): self._cursor_executemany(context.cursor, context.statement, context.parameters, context=context) else: self._cursor_execute(context.cursor, context.statement, context.parameters[0], context=context) + if context.compiled: context.post_exec() if context.isinsert and not context.executemany: @@ -1647,7 +1637,7 @@ class ResultProxy(object): consistent across backends. Usage of this method is normally unnecessary; the - last_inserted_ids() method provides a + inserted_primary_key method provides a tuple of primary key values for a newly inserted row, regardless of database backend. @@ -1668,11 +1658,12 @@ class ResultProxy(object): self.rowcount self.close() # autoclose elif self.context.isinsert and \ + not self.context.executemany and \ not self.context._is_explicit_returning: # an insert, no explicit returning(), may need # to fetch rows which were created via implicit # returning, then close - self.context.last_inserted_ids(self) + self.context._fetch_implicit_returning(self) self.close() return self @@ -1799,14 +1790,28 @@ class ResultProxy(object): raise StopIteration else: yield row + + @util.memoized_property + def inserted_primary_key(self): + """Return the primary key for the row just inserted. + + This only applies to single row insert() constructs which + did not explicitly specify returning(). - def last_inserted_ids(self): - """Return ``last_inserted_ids()`` from the underlying ExecutionContext. - - See ExecutionContext for details. """ - return self.context.last_inserted_ids(self) + if not self.context.isinsert: + raise exc.InvalidRequestError("Statement is not an insert() expression construct.") + elif self.context._is_explicit_returning: + raise exc.InvalidRequestError("Can't call inserted_primary_key when returning() is used.") + + return self.context._inserted_primary_key + @util.deprecated("Use inserted_primary_key") + def last_inserted_ids(self): + """deprecated. use inserted_primary_key.""" + + return self.inserted_primary_key + def last_updated_params(self): """Return ``last_updated_params()`` from the underlying ExecutionContext. diff --git a/lib/sqlalchemy/engine/default.py b/lib/sqlalchemy/engine/default.py index 6f468540c6..ac4dc278ce 100644 --- a/lib/sqlalchemy/engine/default.py +++ b/lib/sqlalchemy/engine/default.py @@ -15,7 +15,7 @@ as the base class for their own corresponding classes. import re, random from sqlalchemy.engine import base, reflection from sqlalchemy.sql import compiler, expression -from sqlalchemy import exc, types as sqltypes +from sqlalchemy import exc, types as sqltypes, util AUTOCOMMIT_REGEXP = re.compile(r'\s*(?:UPDATE|INSERT|CREATE|DELETE|DROP|ALTER)', re.I | re.UNICODE) @@ -263,7 +263,7 @@ class DefaultExecutionContext(base.ExecutionContext): self.isinsert = self.isupdate = self.isdelete = self.executemany = self.should_autocommit = False self.cursor = self.create_cursor() - @property + @util.memoized_property def _is_explicit_returning(self): return self.compiled and \ getattr(self.compiled.statement, '_returning', False) @@ -389,18 +389,16 @@ class DefaultExecutionContext(base.ExecutionContext): def post_insert(self): if self.dialect.postfetch_lastrowid and \ - (not len(self._last_inserted_ids) or \ - None in self._last_inserted_ids): + (not len(self._inserted_primary_key) or \ + None in self._inserted_primary_key): table = self.compiled.statement.table lastrowid = self.get_lastrowid() - self._last_inserted_ids = [c is table._autoincrement_column and lastrowid or v - for c, v in zip(table.primary_key, self._last_inserted_ids) + self._inserted_primary_key = [c is table._autoincrement_column and lastrowid or v + for c, v in zip(table.primary_key, self._inserted_primary_key) ] - def last_inserted_ids(self, resultproxy): - if not self.isinsert: - raise exc.InvalidRequestError("Statement is not an insert() expression construct.") + def _fetch_implicit_returning(self, resultproxy): if self.dialect.implicit_returning and \ not self.compiled.statement._returning and \ @@ -409,13 +407,9 @@ class DefaultExecutionContext(base.ExecutionContext): table = self.compiled.statement.table row = resultproxy.first() - self._last_inserted_ids = [v is not None and v or row[c] - for c, v in zip(table.primary_key, self._last_inserted_ids) + self._inserted_primary_key = [v is not None and v or row[c] + for c, v in zip(table.primary_key, self._inserted_primary_key) ] - return self._last_inserted_ids - - else: - return self._last_inserted_ids def last_inserted_params(self): return self._last_inserted_params @@ -468,7 +462,7 @@ class DefaultExecutionContext(base.ExecutionContext): def __process_defaults(self): """Generate default values for compiled insert/update statements, - and generate last_inserted_ids() collection. + and generate inserted_primary_key collection. """ if self.executemany: @@ -503,7 +497,7 @@ class DefaultExecutionContext(base.ExecutionContext): compiled_parameters[c.key] = val if self.isinsert: - self._last_inserted_ids = [compiled_parameters.get(c.key, None) + self._inserted_primary_key = [compiled_parameters.get(c.key, None) for c in self.compiled.statement.table.primary_key] self._last_inserted_params = compiled_parameters else: diff --git a/lib/sqlalchemy/orm/mapper.py b/lib/sqlalchemy/orm/mapper.py index b502c55aa4..c2c57825e3 100644 --- a/lib/sqlalchemy/orm/mapper.py +++ b/lib/sqlalchemy/orm/mapper.py @@ -1397,7 +1397,7 @@ class Mapper(object): statement = table.insert() for state, params, mapper, connection, value_params in insert: c = connection.execute(statement.values(value_params), params) - primary_key = c.last_inserted_ids() + primary_key = c.inserted_primary_key if primary_key is not None: # set primary key attributes diff --git a/lib/sqlalchemy/sql/compiler.py b/lib/sqlalchemy/sql/compiler.py index a4ab763ea8..c4a4390f21 100644 --- a/lib/sqlalchemy/sql/compiler.py +++ b/lib/sqlalchemy/sql/compiler.py @@ -781,6 +781,13 @@ class SQLCompiler(engine.Compiled): # create a list of column assignment clauses as tuples values = [] + #need_pks = self.isinsert and not self.inline + + #implicit_returning = need_pks and \ + # self.dialect.implicit_returning and \ + # stmt.table.implicit_returning and \ + # not self.statement._returning and \ + implicit_returning = self.dialect.implicit_returning and \ stmt.table.implicit_returning @@ -808,7 +815,7 @@ class SQLCompiler(engine.Compiled): ) and \ not self.inline and \ not self.statement._returning: - + if implicit_returning: if isinstance(c.default, schema.Sequence): proc = self.process(c.default) diff --git a/test/aaa_profiling/test_zoomark.py b/test/aaa_profiling/test_zoomark.py index a1f6277df8..dede684090 100644 --- a/test/aaa_profiling/test_zoomark.py +++ b/test/aaa_profiling/test_zoomark.py @@ -75,13 +75,13 @@ class ZooMarkTest(TestBase): Opens=datetime.time(8, 15, 59), LastEscape=datetime.datetime(2004, 7, 29, 5, 6, 7), Admission=4.95, - ).last_inserted_ids()[0] + ).inserted_primary_key[0] sdz = Zoo.insert().execute(Name =u'San Diego Zoo', Founded = datetime.date(1935, 9, 13), Opens = datetime.time(9, 0, 0), Admission = 0, - ).last_inserted_ids()[0] + ).inserted_primary_key[0] Zoo.insert().execute( Name = u'Montr\xe9al Biod\xf4me', @@ -91,26 +91,26 @@ class ZooMarkTest(TestBase): ) seaworld = Zoo.insert().execute( - Name =u'Sea_World', Admission = 60).last_inserted_ids()[0] + Name =u'Sea_World', Admission = 60).inserted_primary_key[0] # Let's add a crazy futuristic Zoo to test large date values. lp = Zoo.insert().execute(Name =u'Luna Park', Founded = datetime.date(2072, 7, 17), Opens = datetime.time(0, 0, 0), Admission = 134.95, - ).last_inserted_ids()[0] + ).inserted_primary_key[0] # Animals leopardid = Animal.insert().execute(Species=u'Leopard', Lifespan=73.5, - ).last_inserted_ids()[0] + ).inserted_primary_key[0] Animal.update(Animal.c.ID==leopardid).execute(ZooID=wap, LastEscape=datetime.datetime(2004, 12, 21, 8, 15, 0, 999907)) - lion = Animal.insert().execute(Species=u'Lion', ZooID=wap).last_inserted_ids()[0] + lion = Animal.insert().execute(Species=u'Lion', ZooID=wap).inserted_primary_key[0] Animal.insert().execute(Species=u'Slug', Legs=1, Lifespan=.75) tiger = Animal.insert().execute(Species=u'Tiger', ZooID=sdz - ).last_inserted_ids()[0] + ).inserted_primary_key[0] # Override Legs.default with itself just to make sure it works. Animal.insert().execute(Species=u'Bear', Legs=4) @@ -118,15 +118,15 @@ class ZooMarkTest(TestBase): Animal.insert().execute(Species=u'Centipede', Legs=100) emp = Animal.insert().execute(Species=u'Emperor Penguin', Legs=2, - ZooID=seaworld).last_inserted_ids()[0] + ZooID=seaworld).inserted_primary_key[0] adelie = Animal.insert().execute(Species=u'Adelie Penguin', Legs=2, - ZooID=seaworld).last_inserted_ids()[0] + ZooID=seaworld).inserted_primary_key[0] Animal.insert().execute(Species=u'Millipede', Legs=1000000, ZooID=sdz) # Add a mother and child to test relationships bai_yun = Animal.insert().execute(Species=u'Ape', Name=u'Bai Yun', - Legs=2).last_inserted_ids()[0] + Legs=2).inserted_primary_key[0] Animal.insert().execute(Species=u'Ape', Name=u'Hua Mei', Legs=2, MotherID=bai_yun) diff --git a/test/dialect/test_mssql.py b/test/dialect/test_mssql.py index 989b538bd6..423310db62 100644 --- a/test/dialect/test_mssql.py +++ b/test/dialect/test_mssql.py @@ -229,7 +229,7 @@ class IdentityInsertTest(TestBase, AssertsCompiledSQL): eq_([(9, 'Python')], list(cats)) result = cattable.insert().values(description='PHP').execute() - eq_([10], result.last_inserted_ids()) + eq_([10], result.inserted_primary_key) lastcat = cattable.select().order_by(desc(cattable.c.id)).execute() eq_((10, 'PHP'), lastcat.first()) @@ -357,9 +357,9 @@ class QueryTest(TestBase): try: tr = con.begin() r = con.execute(t2.insert(), descr='hello') - self.assert_(r.last_inserted_ids() == [200]) + self.assert_(r.inserted_primary_key == [200]) r = con.execute(t1.insert(), descr='hello') - self.assert_(r.last_inserted_ids() == [100]) + self.assert_(r.inserted_primary_key == [100]) finally: tr.commit() diff --git a/test/dialect/test_postgresql.py b/test/dialect/test_postgresql.py index 3e3884ebe6..f78bf83f43 100644 --- a/test/dialect/test_postgresql.py +++ b/test/dialect/test_postgresql.py @@ -187,11 +187,11 @@ class InsertTest(TestBase, AssertsExecutionResults): def go(): # execute with explicit id r = table.insert().execute({'id':30, 'data':'d1'}) - assert r.last_inserted_ids() == [30] + assert r.inserted_primary_key == [30] # execute with prefetch id r = table.insert().execute({'data':'d2'}) - assert r.last_inserted_ids() == [1] + assert r.inserted_primary_key == [1] # executemany with explicit ids table.insert().execute({'id':31, 'data':'d3'}, {'id':32, 'data':'d4'}) @@ -255,7 +255,7 @@ class InsertTest(TestBase, AssertsExecutionResults): def go(): table.insert().execute({'id':30, 'data':'d1'}) r = table.insert().execute({'data':'d2'}) - assert r.last_inserted_ids() == [5] + assert r.inserted_primary_key == [5] table.insert().execute({'id':31, 'data':'d3'}, {'id':32, 'data':'d4'}) table.insert().execute({'data':'d5'}, {'data':'d6'}) table.insert(inline=True).execute({'id':33, 'data':'d7'}) @@ -307,11 +307,11 @@ class InsertTest(TestBase, AssertsExecutionResults): def go(): # execute with explicit id r = table.insert().execute({'id':30, 'data':'d1'}) - assert r.last_inserted_ids() == [30] + assert r.inserted_primary_key == [30] # execute with prefetch id r = table.insert().execute({'data':'d2'}) - assert r.last_inserted_ids() == [1] + assert r.inserted_primary_key == [1] # executemany with explicit ids table.insert().execute({'id':31, 'data':'d3'}, {'id':32, 'data':'d4'}) @@ -372,7 +372,7 @@ class InsertTest(TestBase, AssertsExecutionResults): def go(): table.insert().execute({'id':30, 'data':'d1'}) r = table.insert().execute({'data':'d2'}) - assert r.last_inserted_ids() == [5] + assert r.inserted_primary_key == [5] table.insert().execute({'id':31, 'data':'d3'}, {'id':32, 'data':'d4'}) table.insert().execute({'data':'d5'}, {'data':'d6'}) table.insert(inline=True).execute({'id':33, 'data':'d7'}) @@ -828,7 +828,7 @@ class MiscTest(TestBase, AssertsExecutionResults, AssertsCompiledSQL): t = Table("speedy_users", meta, autoload=True) r = t.insert().execute(user_name='user', user_password='lala') - assert r.last_inserted_ids() == [1] + assert r.inserted_primary_key == [1] l = t.select().execute().fetchall() assert l == [(1, 'user', 'lala')] finally: diff --git a/test/engine/test_execute.py b/test/engine/test_execute.py index d42ffc5c7c..d6c2af6f0b 100644 --- a/test/engine/test_execute.py +++ b/test/engine/test_execute.py @@ -152,7 +152,7 @@ class ProxyConnectionTest(TestBase): ("DROP TABLE t1", {}, None) ] - if engine.dialect.preexecute_pk_sequences: + if True: # or engine.dialect.preexecute_pk_sequences: cursor = [ ("CREATE TABLE t1", {}, ()), ("INSERT INTO t1 (c1, c2)", {'c2': 'some data', 'c1': 5}, [5, 'some data']), diff --git a/test/sql/test_defaults.py b/test/sql/test_defaults.py index 87a1a24ddf..5638dad77f 100644 --- a/test/sql/test_defaults.py +++ b/test/sql/test_defaults.py @@ -337,7 +337,7 @@ class DefaultTest(testing.TestBase): @testing.fails_on('firebird', 'Data type unknown') def test_update(self): r = t.insert().execute() - pk = r.last_inserted_ids()[0] + pk = r.inserted_primary_key[0] t.update(t.c.col1==pk).execute(col4=None, col5=None) ctexec = currenttime.scalar() l = t.select(t.c.col1==pk).execute() @@ -350,7 +350,7 @@ class DefaultTest(testing.TestBase): @testing.fails_on('firebird', 'Data type unknown') def test_update_values(self): r = t.insert().execute() - pk = r.last_inserted_ids()[0] + pk = r.inserted_primary_key[0] t.update(t.c.col1==pk, values={'col3': 55}).execute() l = t.select(t.c.col1==pk).execute() l = l.first() @@ -385,11 +385,11 @@ class PKDefaultTest(_base.TablesTest): engine = engines.testing_engine(options={'implicit_returning':returning}) engine.execute(t2.insert(), nextid=1) r = engine.execute(t1.insert(), data='hi') - eq_([1], r.last_inserted_ids()) + eq_([1], r.inserted_primary_key) engine.execute(t2.insert(), nextid=2) r = engine.execute(t1.insert(), data='there') - eq_([2], r.last_inserted_ids()) + eq_([2], r.inserted_primary_key) class PKIncrementTest(_base.TablesTest): run_define_tables = 'each' @@ -408,25 +408,25 @@ class PKIncrementTest(_base.TablesTest): def _test_autoincrement(self, bind): ids = set() rs = bind.execute(aitable.insert(), int1=1) - last = rs.last_inserted_ids()[0] + last = rs.inserted_primary_key[0] self.assert_(last) self.assert_(last not in ids) ids.add(last) rs = bind.execute(aitable.insert(), str1='row 2') - last = rs.last_inserted_ids()[0] + last = rs.inserted_primary_key[0] self.assert_(last) self.assert_(last not in ids) ids.add(last) rs = bind.execute(aitable.insert(), int1=3, str1='row 3') - last = rs.last_inserted_ids()[0] + last = rs.inserted_primary_key[0] self.assert_(last) self.assert_(last not in ids) ids.add(last) rs = bind.execute(aitable.insert(values={'int1':func.length('four')})) - last = rs.last_inserted_ids()[0] + last = rs.inserted_primary_key[0] self.assert_(last) self.assert_(last not in ids) ids.add(last) @@ -490,7 +490,7 @@ class AutoIncrementTest(_base.TablesTest): single.create() r = single.insert().execute() - id_ = r.last_inserted_ids()[0] + id_ = r.inserted_primary_key[0] eq_(id_, 1) eq_(1, sa.select([func.count(sa.text('*'))], from_obj=single).scalar()) @@ -502,7 +502,7 @@ class AutoIncrementTest(_base.TablesTest): nodes.create() r = nodes.insert().execute(data='foo') - id_ = r.last_inserted_ids()[0] + id_ = r.inserted_primary_key[0] nodes.insert().execute(data='bar', parent_id=id_) @testing.fails_on('sqlite', 'FIXME: unknown') @@ -571,8 +571,8 @@ class SequenceTest(testing.TestBase): cartitems.insert().execute(description='there') r = cartitems.insert().execute(description='lala') - assert r.last_inserted_ids() and r.last_inserted_ids()[0] is not None - id_ = r.last_inserted_ids()[0] + assert r.inserted_primary_key and r.inserted_primary_key[0] is not None + id_ = r.inserted_primary_key[0] eq_(1, sa.select([func.count(cartitems.c.cart_id)], diff --git a/test/sql/test_functions.py b/test/sql/test_functions.py index 187036c74c..7a0f12cac3 100644 --- a/test/sql/test_functions.py +++ b/test/sql/test_functions.py @@ -231,7 +231,7 @@ class ExecuteTest(TestBase): assert t.select().execute().first()['value'] == 5 r = t.insert(values=dict(value=func.length("sfsaafsda"))).execute() - id = r.last_inserted_ids()[0] + id = r.inserted_primary_key[0] 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 diff --git a/test/sql/test_query.py b/test/sql/test_query.py index 2e56e0d3ec..e746d6d4c0 100644 --- a/test/sql/test_query.py +++ b/test/sql/test_query.py @@ -58,7 +58,7 @@ class QueryTest(TestBase): assert users.select(users.c.user_id==7).execute().first()['user_name'] == 'fred' def test_lastrow_accessor(self): - """Tests the last_inserted_ids() and lastrow_has_id() functions.""" + """Tests the inserted_primary_key and lastrow_has_id() functions.""" def insert_values(engine, table, values): """ @@ -70,11 +70,11 @@ class QueryTest(TestBase): result = engine.execute(table.insert(), **values) ret = values.copy() - for col, id in zip(table.primary_key, result.last_inserted_ids()): + for col, id in zip(table.primary_key, result.inserted_primary_key): ret[col.key] = id if result.lastrow_has_defaults(): - criterion = and_(*[col==id for col, id in zip(table.primary_key, result.last_inserted_ids())]) + criterion = and_(*[col==id for col, id in zip(table.primary_key, result.inserted_primary_key)]) row = engine.execute(table.select(criterion)).first() for c in table.c: ret[c.key] = row[c] @@ -160,11 +160,11 @@ class QueryTest(TestBase): metadata.create_all() r = related.insert().values(id=12).execute() - id = r.last_inserted_ids()[0] + id = r.inserted_primary_key[0] assert id==12 r = t6.insert().values(manual_id=id).execute() - eq_(r.last_inserted_ids(), [12, 1]) + eq_(r.inserted_primary_key, [12, 1]) def test_autoclose_on_insert(self): if testing.against('firebird', 'postgresql', 'oracle', 'mssql'): -- 2.47.3