Skip to content

Add owned PostgreSQL and SQLite connections with bounded statement reuse - #88

Open
elcritch wants to merge 5 commits into
Araq:masterfrom
elcritch:feature/owned-postgres-plan-cache
Open

elcritch wants to merge 5 commits into
Araq:masterfrom
elcritch:feature/owned-postgres-plan-cache

Conversation

@elcritch

@elcritch elcritch commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

What this solves

This PR lets an application reuse prepared queries in PostgreSQL and SQLite while keeping memory use and connection cleanup under control.

Imagine an app repeatedly asking, "Find the customer with this ID." The ID changes, but the query's structure stays the same. The database can save that structure as a prepared statement, which can reduce the work needed for later requests.

An earlier version of Ormin created a new saved PostgreSQL statement on every call. Those statements accumulated while the connection stayed open, causing memory use to grow. PR #87 fixed that by running PostgreSQL queries without keeping named statements. This PR adds controlled reuse back as an optional feature, and adds an owned connection with statement reuse for SQLite too.

How it works

Each backend provides a ManagedDbConn that owns one connection and manages its saved queries:

  • It keeps up to 64 different queries by default.
  • Repeating a saved query reuses it with the new input values.
  • New queries beyond the limit still run normally, without being retained in the cache.
  • Setting maxPlans = 0 turns caching off.

The connection has one clear owner. You can transfer ownership, but you cannot copy it into two independent owners. Under ARC/ORC, when the owner leaves scope—or you explicitly call close()—it releases its connection and saved statements. This helps prevent forgotten connections and accidental double cleanup.

Inline query:/query(T): blocks and generated createProc/createIter calls accept the owned connection, including single-row queries and INSERT ... RETURNING. Existing raw PostgreSQL and SQLite connections remain available. Using a closed managed connection raises DbError.

SQLite behavior

Open an owned SQLite connection with openManaged("app.sqlite") or openManaged(":memory:").

A SQLite statement can be used by only one active query at a time. If an outer iterator is still using a cached statement, a nested query with the same SQL gets a temporary statement. Temporary statements are finalized when the query exits; cached statements are reset and their bound values cleared. Cleanup also runs when a conversion raises or an iterator exits early.

db.reset() clears the cache without reopening the database, preserving in-memory data and transaction state. It raises DbError while managed statements are active. SQLite's prepare_v2 can recompile statements after schema changes; execution errors are reported to the caller.

Closing an owner invalidates its outstanding managed statements. SQLite's close_v2 allows outstanding temporary or borrowed handles to finish cleanup before the underlying connection is fully released.

PostgreSQL behavior

Open an owned PostgreSQL connection with openManaged("host=localhost dbname=app user=app"). db.reset() reconnects and clears the cache.

Saved PostgreSQL statements belong to one database session. Use a direct connection or a session pooler that keeps the same session. Transaction pooling, which can switch sessions between transactions, is unsuitable.

If a saved statement disappears or its result shape becomes invalid after a database change, Ormin reports the error and switches to ordinary execution for that session. Connection failures are also reported to the caller. Ormin does not automatically repeat a failed PostgreSQL query, because repeating something like an order insertion could create a duplicate. Callers can explicitly reset and retry when appropriate.

Ownership and interop

Use each owned connection from one thread at a time, and pass it as var ManagedDbConn to query helpers. borrowRaw provides a temporary handle for other database APIs. Callers must not close that handle, reset a borrowed PostgreSQL session, or finalize statements owned by Ormin. Clean up any statements or handles created through the borrowed handle yourself.

Validation

  • nim test and nim test_postgres passed with Nim 2.2.12 against SQLite and an isolated PostgreSQL 14.25 instance.
  • nim buildexamples passed with the Atlas examples feature enabled.
  • The SQLite managed-connection suite passed with debug ORC, release ARC, danger mode, AddressSanitizer/UBSan, and Nim 2.0.16.
  • Compile-fail checks verify that managed connections and SQLite statement owners cannot be copied.
  • Both backends now have committed tests for transaction commit, rollback after a constraint error, and recovery through nested savepoints.
  • SQLite tests also cover cache bounds and disabled caching, nested queries, stale bindings, typed/JSON/nullable values, blobs and timestamps, prepare and execution errors, schema changes, moves, reset, early iterator exits, and closing with outstanding statements. SQLite close callbacks and statement inspection verify cleanup.
  • PostgreSQL tests cover bounded plan reuse, generated queries, move/close/reset, backend termination, missing plans, schema changes, single-row queries, and result cleanup after success and failures.

Local macOS PostgreSQL runs supplied Homebrew's libpq runtime path through compiler flags. This remains a draft for API and lifecycle review.

@elcritch

Copy link
Copy Markdown
Contributor Author

This is a bigger change. In theory it should be worthwhile but I'll need to review it before it's ready to consider.

@elcritch
elcritch force-pushed the feature/owned-postgres-plan-cache branch from 56e87f1 to 8d7071c Compare November 13, 2026 15:12
@elcritch elcritch changed the title Add owned PostgreSQL sessions with bounded prepared-plan reuse Add owned PostgreSQL and SQLite connections with bounded statement reuse Nov 13, 2026
@elcritch
elcritch marked this pull request as ready for review November 13, 2026 18:48
@elcritch

Copy link
Copy Markdown
Contributor Author

Got around to finishing this. The "ManagedDbConn" allows prepared statement sharing. Should help Postgres spend less time setting up queries.

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.

1 participant