Skip to content

Commit

Permalink
bulk_insert should work with no rows
Browse files Browse the repository at this point in the history
A fix was previously applied only in `bulk_uspert`.
  • Loading branch information
Photonios committed Feb 3, 2023
1 parent d668b76 commit 8f6bac6
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
12 changes: 6 additions & 6 deletions psqlextra/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,12 @@ def bulk_insert(
the models of the rows inserted with defaults for any fields not specified
"""

def is_empty(r):
return all([False for _ in r])

if not rows or is_empty(rows):
return []

if not self.conflict_target and not self.conflict_action:
# no special action required, use the standard Django bulk_create(..)
return super().bulk_create(
Expand Down Expand Up @@ -375,12 +381,6 @@ def bulk_upsert(
the models of the rows upserted
"""

def is_empty(r):
return all([False for _ in r])

if not rows or is_empty(rows):
return []

self.on_conflict(
conflict_target,
ConflictAction.UPDATE,
Expand Down
9 changes: 9 additions & 0 deletions tests/test_upsert.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from psqlextra.expressions import ExcludedCol
from psqlextra.fields import HStoreField
from psqlextra.query import ConflictAction

from .fake_model import get_fake_model

Expand Down Expand Up @@ -245,10 +246,18 @@ def test_upsert_bulk_no_rows():
{"name": models.CharField(max_length=255, null=True, unique=True)}
)

model.objects.on_conflict(ConflictAction.UPDATE, ["name"]).bulk_insert(
rows=[]
)

model.objects.bulk_upsert(conflict_target=["name"], rows=[])

model.objects.bulk_upsert(conflict_target=["name"], rows=None)

model.objects.on_conflict(ConflictAction.UPDATE, ["name"]).bulk_insert(
rows=None
)


def test_bulk_upsert_return_models():
"""Tests whether models are returned instead of dictionaries when
Expand Down

0 comments on commit 8f6bac6

Please sign in to comment.