Skip to content

Partial upsert of an existing row no longer fails on an omitted NOT NULL column - #971

Merged
simonw merged 2 commits into
mainfrom
upsert-not-null-omitted
Nov 29, 2026
Merged

simonw merged 2 commits into
mainfrom
upsert-not-null-omitted

Conversation

@simonw

@simonw simonw commented Nov 29, 2026 •

Copy link
Copy Markdown
Owner

Fixes:

A partial upsert() against an existing row raised IntegrityError if it omitted a NOT NULL column with no default, even though the row already had a value for it.

Claude Fable 5.2 Medium
dogs.insert({"id": 1, "name": "Cleo", "color": "brown"}, pk="id", not_null={"name"})
dogs.upsert({"id": 1, "color": "black"})

Current buggy behavior produces:

sqlite3.IntegrityError: NOT NULL constraint failed: dogs.name

With this fix applied the upsert succeeds and dogs.get(1) returns:

{'id': 1, 'name': 'Cleo', 'color': 'black'}

SQLite checks NOT NULL on the row it would insert before ON CONFLICT applies, so the INSERT ... ON CONFLICT DO UPDATE introduced in 4.0 failed where the older implementation did not.

The change

In the native upsert path, any NOT NULL column without a default that the statement does not supply is added to the INSERT column list, with its value read from the existing row by a scalar subquery on the primary key:

INSERT INTO "dogs" ("id", "color", "name")
VALUES (?, ?, (SELECT "name" FROM "dogs" WHERE "id" = ?))
ON CONFLICT("id") DO UPDATE SET "color" = excluded."color"
  • For an existing row the subquery returns the stored value, and the column is left out of DO UPDATE SET.
  • For a new row the subquery returns NULL, so the upsert still raises IntegrityError rather than inventing a value.
  • When no such column is missing, the generated SQL is exactly what it was before (a test pins both shapes).
  • It adds no extra statements, so last_pk / last_rowid handling and atomicity are unchanged.

Trade-offs

  • The native upsert path now reads the table's columns (PRAGMA table_info) once per upsert() / upsert_all() call. insert_all() does the lookup once and passes it down, so it is not repeated for every chunk.
  • The legacy use_old_upsert=True path is not changed. It already handled the existing-row case; its behaviour of inserting "" for not_null columns on new rows is left alone.

Testing

New tests in tests/test_upsert.py: the repro on both upsert implementations, a new row missing the column still raising (for upsert and for an upsert_all mixing existing and new rows), a NOT NULL column with a default, a compound pk, and a 250-row upsert_all across batches. Full suite: 1553 passed, 4 skipped. Not run locally against SQLite 3.23.1 - that is left to CI.

Builds on #970 (now merged). The fill is applied per run of same-column records, so it also covers a mixed batch where only some records omit the NOT NULL column (tested).

🤖 Generated with Claude Code


📚 Documentation preview 📚: https://sqlite-utils--971.org.readthedocs.build/en/971/

@simonw
simonw force-pushed the upsert-not-null-omitted branch from 503fedb to ed40457 Compare November 29, 2026 19:56
@simonw
simonw changed the base branch from main to upsert-all-mixed-fields November 29, 2026 19:56
@codecov

codecov Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.80%. Comparing base (9d62418) to head (0d3b653).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #971      +/-   ##
==========================================
+ Coverage   94.76%   94.80%   +0.03%     
==========================================
  Files          10       10              
  Lines        4529     4544      +15     
==========================================
+ Hits         4292     4308      +16     
+ Misses        237      236       -1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@simonw
simonw force-pushed the upsert-not-null-omitted branch from ed40457 to 1075118 Compare November 29, 2026 20:05
The native INSERT ... ON CONFLICT DO UPDATE path failed with
IntegrityError when an upsert omitted a NOT NULL column without a
default, because SQLite checks NOT NULL on the would-be inserted row
before the conflict clause applies.

When the target table has such columns missing from the statement,
add them to the INSERT column list filled by a scalar subquery against
the existing row, and leave them out of DO UPDATE SET. Existing rows
keep their value; a genuinely new row gets NULL from the subquery and
still fails the constraint. SQL for the common case is unchanged.

Refs #878

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@simonw
simonw force-pushed the upsert-not-null-omitted branch from 1075118 to 1a7b73c Compare November 29, 2026 20:13
@simonw
simonw changed the base branch from upsert-all-mixed-fields to main November 29, 2026 20:13
Comment thread sqlite_utils/db.py Outdated
Comment on lines +4474 to +4478
required_cols = [
col.name
for col in self.columns
if col.notnull and col.default_value is None
]

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like an introspection in a loop which would affect performance.

Refs #878

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@simonw
simonw merged commit af0d6a0 into main Nov 29, 2026
82 checks passed
@simonw simonw added the bug Something isn't working label Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant