Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions sqlite_utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -4305,6 +4305,14 @@ def _convert_multi(
self.transform(drop=(column,))
return self

def _not_null_columns_without_default(self) -> list[str]:
"Columns an INSERT must supply a value for, used by upsert - see #878"
return [
col.name
for col in self.columns
if col.notnull and col.default_value is None
]

def build_insert_queries_and_params(
self,
extracts,
Expand All @@ -4320,6 +4328,7 @@ def build_insert_queries_and_params(
replace,
ignore,
list_mode=False,
required_columns=None,
):
"""
Given a list ``chunk`` of records that should be written to *this* table,
Expand Down Expand Up @@ -4465,6 +4474,19 @@ def build_insert_queries_and_params(
previous_indexes = indexes

if self.db.supports_on_conflict and not self.db.use_old_upsert:
# SQLite checks NOT NULL on the row to be inserted before ON
# CONFLICT kicks in, so a partial upsert of an existing row fails
# if it omits a NOT NULL column that has no default. Fill those
# columns from the existing row - for a new row the subquery
# returns NULL and the constraint still fails, as it should.
# https://github.com/simonw/sqlite-utils/issues/878
# insert_all() looks these up once and passes them in, to avoid
# repeating the schema query for every chunk
if required_columns is None:
required_columns = self._not_null_columns_without_default()
pk_where_sql = " AND ".join(
f"{quote_identifier(c)} = {conversions.get(c, '?')}" for c in pk_cols
)
queries_and_params = []
for run_columns, run_rows in runs:
non_pk_cols = [c for c in run_columns if c not in pk_cols]
Expand All @@ -4483,6 +4505,27 @@ def build_insert_queries_and_params(
placeholder_expr = ", ".join(
conversions.get(c, "?") for c in run_columns
)
provided = {fold_identifier_case(c) for c in run_columns}
fill_cols = [
c
for c in required_columns
if fold_identifier_case(c) not in provided
]
if fill_cols:
columns_sql += ", " + ", ".join(
quote_identifier(c) for c in fill_cols
)
placeholder_expr += ", " + ", ".join(
f"(SELECT {quote_identifier(c)} FROM "
f"{quote_identifier(self.name)} WHERE {pk_where_sql})"
for c in fill_cols
)
# Each subquery needs this row's primary key values
run_pk_indexes = [run_columns.index(c) for c in pk_cols]
run_rows = [
row + [row[i] for i in run_pk_indexes] * len(fill_cols)
for row in run_rows
]
row_placeholders_sql = ", ".join(
f"({placeholder_expr})" for _ in run_rows
)
Expand Down Expand Up @@ -4566,6 +4609,7 @@ def insert_chunk(
replace,
ignore,
list_mode=False,
required_columns=None,
) -> sqlite3.Cursor | None:
queries_and_params = self.build_insert_queries_and_params(
extracts,
Expand All @@ -4581,6 +4625,7 @@ def insert_chunk(
replace,
ignore,
list_mode,
required_columns,
)
result = None
with self.db.atomic():
Expand Down Expand Up @@ -4611,6 +4656,7 @@ def insert_chunk(
replace,
ignore,
list_mode,
required_columns,
)

result = self.insert_chunk(
Expand All @@ -4628,6 +4674,7 @@ def insert_chunk(
replace,
ignore,
list_mode,
required_columns,
)

else:
Expand Down Expand Up @@ -4857,6 +4904,7 @@ def insert_all(
with self.db.atomic():
self.db.execute(f"DELETE FROM {quote_identifier(self.name)};")
result = None
required_columns: list[str] | None = None
for chunk in chunks(itertools.chain([first_record], records_iter), batch_size):
chunk = list(chunk)
num_records_processed += len(chunk)
Expand Down Expand Up @@ -4920,6 +4968,16 @@ def insert_all(

first = False

if (
upsert
and required_columns is None
and self.db.supports_on_conflict
and not self.db.use_old_upsert
):
# Looked up once here, after the table is known to exist,
# rather than once for every chunk
required_columns = self._not_null_columns_without_default()

result = self.insert_chunk(
alter,
extracts,
Expand All @@ -4935,6 +4993,7 @@ def insert_all(
replace,
ignore,
list_mode,
required_columns,
)

# If we only handled a single row populate self.last_pk
Expand Down
158 changes: 158 additions & 0 deletions tests/test_upsert.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import sqlite3

import pytest

from sqlite_utils import Database
Expand Down Expand Up @@ -212,6 +214,66 @@ def test_upsert_all_mixed_columns_leaves_omitted_columns_unchanged(use_old_upser
]


@pytest.mark.parametrize("use_old_upsert", (False, True))
def test_upsert_existing_row_omitting_not_null_column(use_old_upsert):
# https://github.com/simonw/sqlite-utils/issues/878
db = Database(memory=True, use_old_upsert=use_old_upsert)
dogs = db.table("dogs")
dogs.insert({"id": 1, "name": "Cleo", "color": "brown"}, pk="id", not_null={"name"})
dogs.upsert({"id": 1, "color": "black"})
assert dogs.get(1) == {"id": 1, "name": "Cleo", "color": "black"}
assert dogs.last_pk == 1


def test_upsert_new_row_omitting_not_null_column_errors(fresh_db):
# A partial upsert that would create a new row must not invent a value
# for a NOT NULL column - it should fail the constraint
if not fresh_db.supports_on_conflict:
pytest.skip("Legacy upsert silently ignores the failed INSERT")
dogs = fresh_db.table("dogs")
dogs.insert({"id": 1, "name": "Cleo", "color": "brown"}, pk="id", not_null={"name"})
with pytest.raises(sqlite3.IntegrityError):
dogs.upsert({"id": 2, "color": "black"})
with pytest.raises(sqlite3.IntegrityError):
dogs.upsert_all([{"id": 1, "color": "black"}, {"id": 2, "color": "black"}])
# Nothing should have been written by the failed upserts
assert list(dogs.rows) == [{"id": 1, "name": "Cleo", "color": "brown"}]


def test_upsert_omitting_not_null_column_with_default(fresh_db):
fresh_db.execute(
"create table dogs (id integer primary key, "
"name text not null default 'Unknown', color text)"
)
dogs = fresh_db.table("dogs")
dogs.insert({"id": 1, "name": "Cleo", "color": "brown"})
dogs.upsert_all([{"id": 1, "color": "black"}, {"id": 2, "color": "white"}])
assert list(dogs.rows) == [
{"id": 1, "name": "Cleo", "color": "black"},
{"id": 2, "name": "Unknown", "color": "white"},
]


@pytest.mark.parametrize("use_old_upsert", (False, True))
def test_upsert_compound_pk_omitting_not_null_column(use_old_upsert):
db = Database(memory=True, use_old_upsert=use_old_upsert)
pets = db.table("pets")
pets.insert_all(
[
{"species": "dog", "id": 1, "name": "Cleo", "age": 4},
{"species": "cat", "id": 1, "name": "Catbag", "age": 2},
],
pk=("species", "id"),
not_null={"name"},
)
pets.upsert({"species": "dog", "id": 1, "age": 5}, pk=("species", "id"))
assert pets.last_pk == ("dog", 1)
assert list(pets.rows) == [
{"species": "dog", "id": 1, "name": "Cleo", "age": 5},
{"species": "cat", "id": 1, "name": "Catbag", "age": 2},
]


@pytest.mark.parametrize("use_old_upsert", (False, True))
def test_upsert_all_mixed_columns_same_pk_twice(use_old_upsert):
# Records are applied in order, even when the same pk appears twice
Expand Down Expand Up @@ -312,3 +374,99 @@ def test_upsert_all_homogeneous_batch_is_single_query(fresh_db):
[1, "A", 2, "B"],
)
]


@pytest.mark.parametrize("use_old_upsert", (False, True))
def test_upsert_all_omitting_not_null_column(use_old_upsert):
db = Database(memory=True, use_old_upsert=use_old_upsert)
dogs = db.table("dogs")
dogs.insert_all(
[{"id": i, "name": f"Dog {i}", "age": 1} for i in range(1, 251)],
pk="id",
not_null={"name"},
)
# Different casing for the pk and a conversion on a non-pk column
dogs.upsert_all(
[{"ID": i, "age": i, "color": "brown"} for i in range(1, 251)],
pk="id",
batch_size=100,
conversions={"color": "upper(?)"},
alter=True,
)
rows = list(dogs.rows)
assert len(rows) == 250
assert rows[0] == {"id": 1, "name": "Dog 1", "age": 1, "color": "BROWN"}
assert rows[-1] == {"id": 250, "name": "Dog 250", "age": 250, "color": "BROWN"}


def test_upsert_omitting_not_null_column_sql(fresh_db):
# The subquery is only added when an omitted column is NOT NULL without
# a default - otherwise the SQL is unchanged
if not fresh_db.supports_on_conflict:
pytest.skip("Needs SQLite with ON CONFLICT support")
dogs = fresh_db.table("dogs")
dogs.insert({"id": 1, "name": "Cleo", "color": "brown"}, pk="id", not_null={"name"})
common_args = (None, None, True, "id", None, {}, 1, False, False)
sql, params = dogs.build_insert_queries_and_params(
{}, [{"id": 1, "name": "Pancakes"}], ["id", "name"], *common_args
)[0]
assert sql == (
'INSERT INTO "dogs" ("id", "name") VALUES (?, ?) '
'ON CONFLICT("id") DO UPDATE SET "name" = excluded."name"'
)
assert params == [1, "Pancakes"]
sql, params = dogs.build_insert_queries_and_params(
{},
[{"id": 1, "color": "black"}, {"id": 2, "color": "white"}],
["id", "color"],
*common_args,
)[0]
assert sql == (
'INSERT INTO "dogs" ("id", "color", "name") VALUES '
'(?, ?, (SELECT "name" FROM "dogs" WHERE "id" = ?)), '
'(?, ?, (SELECT "name" FROM "dogs" WHERE "id" = ?)) '
'ON CONFLICT("id") DO UPDATE SET "color" = excluded."color"'
)
assert params == [1, "black", 1, 2, "white", 2]


def test_upsert_all_mixed_columns_omitting_not_null_column():
# A record that omits a NOT NULL column other records in the batch supply
db = Database(memory=True)
dogs = db.table("dogs")
dogs.insert_all(
[
{"id": 1, "name": "Cleo", "color": "brown"},
{"id": 2, "name": "Pancakes", "color": "black"},
],
pk="id",
not_null={"name"},
)
dogs.upsert_all(
[{"id": 1, "color": "white"}, {"id": 2, "name": "Pancakes II"}],
)
assert list(dogs.rows_where(order_by="id")) == [
{"id": 1, "name": "Cleo", "color": "white"},
{"id": 2, "name": "Pancakes II", "color": "black"},
]


def test_upsert_all_looks_up_not_null_columns_once():
# The schema lookup for #878 should happen once per call, not per chunk
queries = []
db = Database(memory=True, tracer=lambda sql, params: queries.append(sql))
if not db.supports_on_conflict:
pytest.skip("Needs SQLite 3.24+ for INSERT ... ON CONFLICT")
dogs = db.table("dogs")
dogs.insert({"id": 0, "name": "Cleo"}, pk="id", not_null={"name"})

def table_info_count(batch_size):
queries.clear()
dogs.upsert_all(
[{"id": i, "name": "Dog {}".format(i)} for i in range(50)],
pk="id",
batch_size=batch_size,
)
return len([q for q in queries if "table_info" in q])

assert table_info_count(batch_size=5) == table_info_count(batch_size=50)
Loading