Skip to content

Commit

Permalink
fix(django): add error when trying to insert binary data
Browse files Browse the repository at this point in the history
  • Loading branch information
taylor-cedar committed Nov 13, 2023
1 parent f19c154 commit 9bd7b6d
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 2 deletions.
8 changes: 7 additions & 1 deletion django_bulk_load/django.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import base64
import csv
import os
from io import StringIO
from typing import Any, Iterable, List, NamedTuple, Optional, Tuple, Type

Expand Down Expand Up @@ -69,7 +71,11 @@ def models_to_tsv_buffer(
row = []
for include_field in include_fields:
field_val = django_field_to_value(obj, include_field, connection)
if field_val is None:
if isinstance(field_val, connection.Database.Binary):
# We can migrate to psychopg 3 which has more advanced copy commands for binary once we upgrade
# Django to 4.1+
raise ValueError("Binary data is not supported in bulk operations")
elif field_val is None:
row.append(NULL_CHARACTER)
elif isinstance(field_val, Json):
row.append(field_val.dumps(field_val.adapted))
Expand Down
8 changes: 7 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@ services:
- .:/python
working_dir: /python
depends_on:
- db
db:
condition: service_healthy
db:
image: postgres:10
healthcheck:
test: [ "CMD-SHELL", "pg_isready -U postgres" ]
interval: 5s
timeout: 5s
retries: 5
environment:
- POSTGRES_PASSWORD=postgres
14 changes: 14 additions & 0 deletions tests/test_bulk_insert_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,17 @@ def test_errors_when_mix_of_pk_and_not(self):
unsaved_model_with_pk,
unsaved_model_without_pk
])

def test_errors_when_uploading_binary(self):
unsaved_model1 = TestComplexModel(
binary_field=b"hello2",
)
unsaved_model2 = TestComplexModel(
binary_field=b"hello2",
)

with self.assertRaises(ValueError):
bulk_insert_models([
unsaved_model1,
unsaved_model2
])
1 change: 1 addition & 0 deletions tests/test_project/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class TestComplexModel(models.Model):
test_foreign = models.ForeignKey(
TestForeignKeyModel, on_delete=models.PROTECT, null=True
)
binary_field = models.BinaryField(null=True)



Expand Down

0 comments on commit 9bd7b6d

Please sign in to comment.