Return row count for bulk inserts.

Note: postgres will continue to return a cursor iterator over the
inserted primary-keys by default. To disable this and retrieve a
rowcount instead, specify an empty returning, e.g. `.returning()`.
This commit is contained in:
Charles Leifer
2019-09-30 10:01:54 -05:00
parent 254e9b58e7
commit ab43376697
3 changed files with 37 additions and 1 deletions
+7
View File
@@ -7,6 +7,13 @@ https://github.com/coleifer/peewee/releases
## master
* Bulk insert (`insert_many()` and `insert_from()`) will now return the row
count instead of the last insert ID. If you are using Postgres, peewee will
continue to return a cursor that provides an iterator over the newly-inserted
primary-key values by default. This behavior is being retained by default for
compatibility. Postgres users can simply specify an empty `returning()` call
to disable the cursor and retrieve the rowcount instead.
[View commits](https://github.com/coleifer/peewee/compare/3.11.2...master)
## 3.11.2
+3 -1
View File
@@ -2627,6 +2627,8 @@ class Insert(_WriteQuery):
def handle_result(self, database, cursor):
if self._return_cursor:
return cursor
if self._query_type != Insert.SIMPLE and not self._returning:
return database.rows_affected(cursor)
return database.last_insert_id(cursor, self._query_type)
@@ -3651,7 +3653,7 @@ class PostgresqlDatabase(Database):
def last_insert_id(self, cursor, query_type=None):
try:
return cursor if query_type else cursor[0][0]
return cursor if query_type != Insert.SIMPLE else cursor[0][0]
except (IndexError, KeyError, TypeError):
pass
+27
View File
@@ -369,6 +369,33 @@ class TestModelAPIs(ModelTestCase):
self.assertEqual(list(sorted(CPK.select().tuples())), [
('k1', 1, 10), ('k2', 2, 2), ('k3', 3, 30)])
@requires_models(User)
def test_insert_rowcount(self):
User.create(username='u0') # Ensure that last insert ID != rowcount.
iq = User.insert_many([(u,) for u in ('u1', 'u2', 'u3')])
if IS_POSTGRESQL:
iq = iq.returning()
self.assertEqual(iq.execute(), 3)
# Now explicitly specify empty returning() for all DBs.
iq = User.insert_many([(u,) for u in ('u4', 'u5')]).returning()
self.assertEqual(iq.execute(), 2)
query = (User
.select(User.username.concat('-x'))
.where(User.username.in_(['u1', 'u2'])))
iq = User.insert_from(query, ['username'])
if IS_POSTGRESQL:
iq = iq.returning()
self.assertEqual(iq.execute(), 2)
query = (User
.select(User.username.concat('-y'))
.where(User.username.in_(['u3', 'u4'])))
iq = User.insert_from(query, ['username']).returning()
self.assertEqual(iq.execute(), 2)
@requires_models(User, Tweet)
def test_get_shortcut(self):
huey = self.add_user('huey')