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
75 changes: 55 additions & 20 deletions sqlite_utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -4440,35 +4440,70 @@ def build_insert_queries_and_params(
", ".join(pk_cols),
)
)
non_pk_cols = [c for c in all_columns if c not in pk_cols]
conflict_sql = ", ".join(quote_identifier(c) for c in pk_cols)

if self.db.supports_on_conflict and not self.db.use_old_upsert:
if non_pk_cols:
# DO UPDATE
assignments = []
for c in non_pk_cols:
c_quoted = quote_identifier(c)
assignments.append(f"{c_quoted} = excluded.{c_quoted}")
do_clause = "DO UPDATE SET " + ", ".join(assignments)
# A record should only update the columns it supplied, not every
# column seen in the batch (#873). Split the chunk into consecutive
# runs of records that supply the same columns - consecutive so that
# records are still applied in their original order.
runs: list[tuple[list[str], list[list[Any]]]] = []
previous_indexes = None
for record, record_values in zip(chunk, values):
indexes = tuple(
i
for i, c in enumerate(all_columns)
if list_mode or c in record or c == hash_id
)
run_values = [record_values[i] for i in indexes]
if runs and indexes == previous_indexes:
runs[-1][1].append(run_values)
else:
# All columns are in the PK – nothing to update.
do_clause = "DO NOTHING"
runs.append(([all_columns[i] for i in indexes], [run_values]))
previous_indexes = indexes

sql = (
f"INSERT INTO {quote_identifier(self.name)} ({columns_sql}) "
f"VALUES {row_placeholders_sql} "
f"ON CONFLICT({conflict_sql}) {do_clause}"
)
return [(sql, flat_params)]
if self.db.supports_on_conflict and not self.db.use_old_upsert:
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]
if non_pk_cols:
# DO UPDATE
assignments = []
for c in non_pk_cols:
c_quoted = quote_identifier(c)
assignments.append(f"{c_quoted} = excluded.{c_quoted}")
do_clause = "DO UPDATE SET " + ", ".join(assignments)
else:
# All columns are in the PK – nothing to update.
do_clause = "DO NOTHING"

columns_sql = ", ".join(quote_identifier(c) for c in run_columns)
placeholder_expr = ", ".join(
conversions.get(c, "?") for c in run_columns
)
row_placeholders_sql = ", ".join(
f"({placeholder_expr})" for _ in run_rows
)
sql = (
f"INSERT INTO {quote_identifier(self.name)} ({columns_sql}) "
f"VALUES {row_placeholders_sql} "
f"ON CONFLICT({conflict_sql}) {do_clause}"
)
queries_and_params.append(
(sql, list(itertools.chain.from_iterable(run_rows)))
)
return queries_and_params

# At this point we need compatibility UPSERT for SQLite < 3.24.0
# (INSERT OR IGNORE + second UPDATE stage)
queries_and_params = []
pks = pk_cols
self.last_pk = None
for record_values in values:
record = dict(zip(all_columns, record_values))
records = [
dict(zip(run_columns, row))
for run_columns, run_rows in runs
for row in run_rows
]
for record in records:
placeholders = list(pks)
# Need to populate not-null columns too, or INSERT OR IGNORE ignores
# them since it ignores the resulting integrity errors
Expand All @@ -4485,7 +4520,7 @@ def build_insert_queries_and_params(
(sql, [record[col] for col in pks] + ["" for _ in (not_null or [])])
)
# UPDATE "book" SET "name" = 'Programming' WHERE "id" = 1001;
set_cols = [col for col in all_columns if col not in pks]
set_cols = [col for col in record if col not in pks]
if set_cols:
sql2 = "UPDATE {} SET {pairs} WHERE {wheres}".format(
quote_identifier(self.name),
Expand Down
4 changes: 2 additions & 2 deletions tests/test_conversions.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def test_upsert_conversion_once(
use_old_upsert, method, first, second, conversion, expected_first, expected_second
):
db = Database(memory=True, use_old_upsert=use_old_upsert)
table = db["records"]
table = db.table("records")
for value, expected in (
(first, expected_first),
(second, expected_second),
Expand All @@ -74,7 +74,7 @@ def test_upsert_conversion_once(
@pytest.mark.parametrize("batch_size", (1, 100))
def test_upsert_all_converted_values_mixed_insert_update(use_old_upsert, batch_size):
db = Database(memory=True, use_old_upsert=use_old_upsert)
table = db["prices"]
table = db.table("prices")
table.insert({"id": 1, "amount": 1000, "note": "original"}, pk="id")
table.upsert_all(
[
Expand Down
127 changes: 127 additions & 0 deletions tests/test_upsert.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,130 @@ def test_upsert_compound_primary_key(fresh_db):
# .upsert_all() with a single item should set .last_pk
table.upsert_all([{"species": "cat", "id": 1, "age": 5}], pk=("species", "id"))
assert ("cat", 1) == table.last_pk


@pytest.mark.parametrize("use_old_upsert", (False, True))
def test_upsert_all_mixed_columns_leaves_omitted_columns_unchanged(use_old_upsert):
# https://github.com/simonw/sqlite-utils/issues/873
db = Database(memory=True, use_old_upsert=use_old_upsert)
table = db.table("dogs")
table.insert_all(
[{"id": 1, "name": "Cleo", "age": 5}, {"id": 2, "name": "Nixie", "age": 6}],
pk="id",
)
table.upsert_all(
[
{"id": 1, "age": 7},
{"id": 2, "name": "Nixie II"},
# A brand new row gets NULL for the columns it omits
{"id": 3, "name": "Pancakes"},
],
pk="id",
)
assert list(table.rows_where(order_by="id")) == [
{"id": 1, "name": "Cleo", "age": 7},
{"id": 2, "name": "Nixie II", "age": 6},
{"id": 3, "name": "Pancakes", "age": None},
]


@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
db = Database(memory=True, use_old_upsert=use_old_upsert)
table = db.table("dogs")
table.insert({"id": 1, "name": "Cleo", "age": 5}, pk="id")
table.upsert_all(
[
{"id": 1, "name": "First"},
{"id": 1, "age": 6},
{"id": 1, "name": "Second"},
],
pk="id",
)
assert list(table.rows) == [{"id": 1, "name": "Second", "age": 6}]


@pytest.mark.parametrize("use_old_upsert", (False, True))
def test_upsert_all_mixed_columns_across_chunks(use_old_upsert):
# Columns seen in an earlier chunk must not be nulled out in a later one
db = Database(memory=True, use_old_upsert=use_old_upsert)
table = db.table("dogs")
table.insert_all(
[{"id": 1, "name": "Cleo", "age": 5}, {"id": 2, "name": "Nixie", "age": 6}],
pk="id",
)
table.upsert_all(
[{"id": 1, "age": 7}, {"id": 2, "name": "Nixie II"}], pk="id", batch_size=1
)
assert list(table.rows_where(order_by="id")) == [
{"id": 1, "name": "Cleo", "age": 7},
{"id": 2, "name": "Nixie II", "age": 6},
]


@pytest.mark.parametrize("use_old_upsert", (False, True))
def test_upsert_all_mixed_columns_with_conversions(use_old_upsert):
db = Database(memory=True, use_old_upsert=use_old_upsert)
table = db.table("dogs")
table.insert_all(
[{"id": 1, "name": "Cleo", "age": 5}, {"id": 2, "name": "Nixie", "age": 6}],
pk="id",
)
table.upsert_all(
[{"id": 1, "age": 7}, {"id": 2, "name": "nixie ii"}],
pk="id",
conversions={"name": "upper(?)"},
)
assert list(table.rows_where(order_by="id")) == [
{"id": 1, "name": "Cleo", "age": 7},
{"id": 2, "name": "NIXIE II", "age": 6},
]


@pytest.mark.parametrize("use_old_upsert", (False, True))
def test_upsert_all_mixed_columns_with_hash_id(use_old_upsert):
db = Database(memory=True, use_old_upsert=use_old_upsert)
table = db.table("dogs")
table.insert_all(
[{"name": "Cleo", "age": 5}, {"name": "Nixie", "age": 6}],
hash_id="pk",
hash_id_columns=["name"],
)
table.upsert_all(
[{"name": "Cleo", "age": 7}, {"name": "Nixie"}],
hash_id="pk",
hash_id_columns=["name"],
)
assert [(r["name"], r["age"]) for r in table.rows_where(order_by="name")] == [
("Cleo", 7),
("Nixie", 6),
]


def test_upsert_all_homogeneous_batch_is_single_query(fresh_db):
if not fresh_db.supports_on_conflict:
pytest.skip("Needs SQLite 3.24+ for INSERT ... ON CONFLICT")
table = fresh_db.table("dogs")
table.insert({"id": 1, "name": "Cleo"}, pk="id")
queries = table.build_insert_queries_and_params(
extracts=None,
chunk=[{"id": 1, "name": "A"}, {"id": 2, "name": "B"}],
all_columns=["id", "name"],
hash_id=None,
hash_id_columns=None,
upsert=True,
pk="id",
not_null=None,
conversions={},
num_records_processed=2,
replace=False,
ignore=False,
)
assert queries == [
(
'INSERT INTO "dogs" ("id", "name") VALUES (?, ?), (?, ?) '
'ON CONFLICT("id") DO UPDATE SET "name" = excluded."name"',
[1, "A", 2, "B"],
)
]
Loading