Skip to content

Fix upsert ON CONFLICT: missing :identifier expr + numbered parameters#95

Merged
ocean merged 6 commits into
ocean:mainfrom
AlanMcCann:fix/upsert-on-conflict-identifier
May 11, 2026
Merged

Fix upsert ON CONFLICT: missing :identifier expr + numbered parameters#95
ocean merged 6 commits into
ocean:mainfrom
AlanMcCann:fix/upsert-on-conflict-identifier

Conversation

@AlanMcCann
Copy link
Copy Markdown
Contributor

@AlanMcCann AlanMcCann commented Apr 27, 2026

Two bugs in SQL generation that cause "near ?: syntax error" on any INSERT ... ON CONFLICT DO UPDATE query:

  1. Missing :identifier expression handler. Ecto generates ON CONFLICT UPDATE clauses using fragment expressions containing {:identifier, _, ["column_name"]} tuples. Without a matching expr/3 clause, these fall through to the catch-all which returns bare "?", producing invalid SQL like: SET "col" = EXCLUDED.?

  2. Bare ? parameter placeholders. SQLite requires numbered positional parameters (?1, ?2, ...) when a statement contains multiple parameter groups (INSERT values + ON CONFLICT UPDATE). The ecto_sqlite3 adapter already uses this pattern.

Fixes all upsert operations including Ash Framework's upsert? actions.

Summary by CodeRabbit

  • Bug Fixes
    • SQL generation for INSERTs, upserts and IN-clauses now uses consistent numbered parameter placeholders and correctly quotes identifiers, improving reliability of conflict-resolution and value binding.
  • Tests
    • Added and updated tests to cover parameter numbering and upsert behaviors via repository insert operations, ensuring correct runtime outcomes.

Review Change Stack

Two bugs in SQL generation that cause "near ?: syntax error" on any
INSERT ... ON CONFLICT DO UPDATE query:

1. Missing :identifier expression handler. Ecto generates ON CONFLICT
   UPDATE clauses using fragment expressions containing {:identifier, _,
   ["column_name"]} tuples. Without a matching expr/3 clause, these fall
   through to the catch-all which returns bare "?", producing invalid SQL
   like: SET "col" = EXCLUDED.?

2. Bare ? parameter placeholders. SQLite requires numbered positional
   parameters (?1, ?2, ...) when a statement contains multiple parameter
   groups (INSERT values + ON CONFLICT UPDATE). The ecto_sqlite3 adapter
   already uses this pattern.

Fixes all upsert operations including Ash Framework's upsert? actions.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 27, 2026

Warning

Rate limit exceeded

@ocean has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 49 minutes and 41 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4b54d1a7-63a1-4e54-ba08-f7fc648d5e9c

📥 Commits

Reviewing files that changed from the base of the PR and between 791f1d2 and 7831ce1.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • test/ecto_connection_test.exs
  • test/ecto_integration_test.exs

Walkthrough

The LibSQL adapter now generates numbered SQLite positional bind parameters (?1, ?2, ...) for INSERT VALUES, pinned parameters, and IN-list expansions; it adds identifier node printing and updates tests to expect numbered placeholders.

Changes

LibSQL Insert Parameter Binding

Layer / File(s) Summary
INSERT VALUES renumbering
lib/ecto/adapters/libsql/connection.ex
insert/7 computes a counter offset and uses encode_insert_values/2 to emit VALUES tuples with numbered positional binds across all rows.
Pinned parameter & identifier printing
lib/ecto/adapters/libsql/connection.ex
Expression printing renders {:^, [], [ix]} as numbered placeholders (?{ix+1}) and handles {:identifier, ..., [name]} via quote_name/1.
IN-clause pinned-list expansion
lib/ecto/adapters/libsql/connection.ex
Pinned lists in IN clauses expand to numbered placeholders per element; empty lists remain an always-false predicate.
Connection tests
test/ecto_connection_test.exs
Adds test coverage for numbered placeholders in IN expressions and updates on_conflict INSERT assertions to expect ?1, ?2, ....
Integration tests
test/ecto_integration_test.exs
Adds Repo.insert upsert integration tests for on_conflict with conflict_target: :email covering replace_all, nothing, and field-specific replace.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 I hop through VALUES, counting each bind,

?1, ?2, ?3 — neat numbers I find.
Identifiers quoted, IN lists aligned,
Conflicts well-handled, tidy and kind.
🥕✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarises the main changes: fixing upsert ON CONFLICT bugs by adding missing identifier expression handling and implementing numbered SQL parameters.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/ecto/adapters/libsql/connection.ex`:
- Around line 1184-1189: The IN with a bound list branch still emits bare "?"
placeholders; update the clause handling the pattern {:in, _, [left, {:^, _, [_,
length]}]} inside expr/3 to emit numbered placeholders like the generic {:^, [],
[ix]} clause does: generate a sequence of "?" + Integer.to_string(start_index)
through "?" + Integer.to_string(start_index + length - 1) (matching the same
numbering scheme used by expr({:^,[],[ix]},...)), join them with ", " and return
the full parenthesized placeholder list so SQLite gets ?1, ?2, ... for IN ^list.
Ensure you reference and reuse the same index base/offset logic used by
expr({:^,...}) so numbering remains consistent across other parameter groups.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7f519f1b-e1b3-479f-8e81-0e161b5058ae

📥 Commits

Reviewing files that changed from the base of the PR and between b9d0647 and 6ba8838.

📒 Files selected for processing (1)
  • lib/ecto/adapters/libsql/connection.ex

Comment thread lib/ecto/adapters/libsql/connection.ex
@ocean
Copy link
Copy Markdown
Owner

ocean commented May 10, 2026

Thanks @AlanMcCann ! Sorry I didn't see this right away, and was already in the process of making some updates and fixes, so I've fixed this issue in my branch. Should be another release out soon.

@AlanMcCann
Copy link
Copy Markdown
Contributor Author

@ocean Thanks!

ocean added 2 commits May 11, 2026 08:54
- Update all 8 test assertions from VALUES (?, ?) to VALUES (?1, ?2, ...)
  to match the numbered parameter format introduced in this PR.
- Fix the IN with bound list handler to also use numbered parameters
  (?start+1, ..., ?start+length) consistent with the rest of the adapter,
  resolving the gap flagged by CodeRabbit.
- Guard the empty-list case (length=0) explicitly, using
  "IN (SELECT NULL WHERE 1=0)" since SQLite rejects IN ().
- Add connection-level tests for numbered IN parameter generation,
  including the non-zero start index case.
- Add four integration tests exercising Repo.insert with on_conflict:
  :replace_all, :nothing, {:replace, fields}, and insert-without-conflict,
  proving the upsert fix works end-to-end against a real database.
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
test/ecto_connection_test.exs (1)

582-635: ⚡ Quick win

Add a direct empty-IN list assertion to lock the guard branch.

You now test numbered expansion well; adding a {:^, [], [0, 0]} case would pin the IN (SELECT NULL WHERE 1=0) behaviour and prevent regressions on that edge path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/ecto_connection_test.exs` around lines 582 - 635, Add a new test in the
same "IN clause parameter numbering" describe block that constructs a query like
the others but with the bound IN list node using {:^, [], [0, 0]} (start_ix=0,
length=0), call Connection.all(query) |> IO.iodata_to_binary() and assert the
produced SQL contains the empty-IN sentinel clause (e.g. assert sql =~ ~s["id"
IN (SELECT NULL WHERE 1=0)]), thereby locking the guard branch that handles
zero-length IN lists.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/ecto_integration_test.exs`:
- Around line 943-959: The test "Repo.insert with on_conflict: :replace_all
upserts an existing record" currently only asserts email and row count, so fetch
the persisted record after the upsert and assert the updated field was actually
stored: after calling TestRepo.insert (the updated binding), query the DB for
the User by email (e.g., TestRepo.get_by/User.get_by equivalent) and assert that
the name equals "Alice Updated" to ensure the on_conflict :replace_all truly
persisted the change.

---

Nitpick comments:
In `@test/ecto_connection_test.exs`:
- Around line 582-635: Add a new test in the same "IN clause parameter
numbering" describe block that constructs a query like the others but with the
bound IN list node using {:^, [], [0, 0]} (start_ix=0, length=0), call
Connection.all(query) |> IO.iodata_to_binary() and assert the produced SQL
contains the empty-IN sentinel clause (e.g. assert sql =~ ~s["id" IN (SELECT
NULL WHERE 1=0)]), thereby locking the guard branch that handles zero-length IN
lists.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 962d481e-630e-45b4-a43a-99b2c491c170

📥 Commits

Reviewing files that changed from the base of the PR and between 6ba8838 and 791f1d2.

📒 Files selected for processing (3)
  • lib/ecto/adapters/libsql/connection.ex
  • test/ecto_connection_test.exs
  • test/ecto_integration_test.exs
🚧 Files skipped from review as they are similar to previous changes (1)
  • lib/ecto/adapters/libsql/connection.ex

Comment thread test/ecto_integration_test.exs
@ocean ocean merged commit 6a7813c into ocean:main May 11, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants