Skip to content

Commit

Permalink
Allow fields/columns to be list of strings with bulk INSERT.
Browse files Browse the repository at this point in the history
Refs #1712.
  • Loading branch information
coleifer committed Sep 8, 2018
1 parent 925890c commit fb2268a
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 3 deletions.
13 changes: 11 additions & 2 deletions peewee.py
Expand Up @@ -2208,8 +2208,17 @@ def _generate_insert(self, insert, ctx):
columns = sorted(accum, key=lambda obj: obj.get_sort_key(ctx))
rows_iter = itertools.chain(iter((row,)), rows_iter)
else:
columns = list(columns)
value_lookups = dict((column, column) for column in columns)
clean_columns = []
value_lookups = {}
for column in columns:
if isinstance(column, basestring):
column_obj = getattr(self.table, column)
else:
column_obj = column
value_lookups[column_obj] = column
clean_columns.append(column_obj)

columns = clean_columns
for col in sorted(defaults, key=lambda obj: obj.get_sort_key(ctx)):
if col not in value_lookups:
columns.append(col)
Expand Down
15 changes: 14 additions & 1 deletion tests/model_sql.py
Expand Up @@ -14,7 +14,7 @@

class TestModelSQL(ModelDatabaseTestCase):
database = get_in_memory_db()
requires = [Category, Note, Person, Relationship]
requires = [Category, Note, Person, Relationship, User]

def test_select(self):
query = (Person
Expand Down Expand Up @@ -281,6 +281,19 @@ def test_insert_many(self):
'VALUES (?, ?), (?, ?)'),
[1, 'note-1', 2, 'note-2'])

def test_insert_many_list_with_fields(self):
data = [(i,) for i in ('charlie', 'huey', 'zaizee')]
query = User.insert_many(data, fields=[User.username])
self.assertSQL(query, (
'INSERT INTO "users" ("username") VALUES (?), (?), (?)'),
['charlie', 'huey', 'zaizee'])

# Use field name instead of field obj.
query = User.insert_many(data, fields=['username'])
self.assertSQL(query, (
'INSERT INTO "users" ("username") VALUES (?), (?), (?)'),
['charlie', 'huey', 'zaizee'])

def test_insert_query(self):
select = (Person
.select(Person.id, Person.first)
Expand Down
13 changes: 13 additions & 0 deletions tests/sql.py
Expand Up @@ -509,6 +509,19 @@ def test_insert_list(self):
'INSERT INTO "person" ("name") VALUES (?), (?), (?)'),
['charlie', 'huey', 'zaizee'])

def test_insert_list_with_columns(self):
data = [(i,) for i in ('charlie', 'huey', 'zaizee')]
query = Person.insert(data, columns=[Person.name])
self.assertSQL(query, (
'INSERT INTO "person" ("name") VALUES (?), (?), (?)'),
['charlie', 'huey', 'zaizee'])

# Use column name instead of column instance.
query = Person.insert(data, columns=['name'])
self.assertSQL(query, (
'INSERT INTO "person" ("name") VALUES (?), (?), (?)'),
['charlie', 'huey', 'zaizee'])

def test_insert_query(self):
source = User.select(User.c.username).where(User.c.admin == False)
query = Person.insert(source, columns=[Person.name])
Expand Down

0 comments on commit fb2268a

Please sign in to comment.