Skip to content

feat: add prepared statement support (prepare/query_prepared) - #126

Open
Taure wants to merge 3 commits into
erleans:mainfrom
Taure:feat/prepared-statements
Open

Taure wants to merge 3 commits into
erleans:mainfrom
Taure:feat/prepared-statements

Conversation

@Taure

@Taure Taure commented Mar 22, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Add pgo:prepare/2,3 — parse a named prepared statement, returns {ok, Name, ParameterOIDs}
  • Add pgo:query_prepared/3,4 — execute a prepared statement by name, skipping PARSE entirely
  • Add pgo_prepared_cache module — ETS-based cache for statement metadata
  • 13 new Common Test cases

Motivation

pgo currently uses unnamed statements ("") for every query, forcing PostgreSQL to parse and plan each one. Named prepared statements allow skipping the PARSE step on repeated queries, sending only BIND→DESCRIBE→EXECUTE→SYNC.

Benchmarks with erlperf show:

  • select_one_by_id: +65% throughput (6,500 → 10,700 ops/sec)
  • count(*): +61% (7,300 → 11,800 ops/sec)
  • select 100 rows: +20% (1,500 → 1,800 ops/sec)

Usage

%% Prepare once, execute many times on same connection
pgo:with_conn(default, fun() ->
    {ok, _Name, OIDs} = pgo:prepare("my_query",
        "SELECT * FROM users WHERE id = $1"),
    #{rows := Rows} = pgo:query_prepared("my_query", [42], OIDs)
end).

Test plan

  • 13 new prepared statement CT cases pass
  • All 57 existing tests still pass (70 total)

Add named prepared statement API:
- pgo:prepare/2,3 — parse and cache named statement, returns parameter OIDs
- pgo:query_prepared/3,4 — execute prepared statement (skips PARSE)
- pgo_prepared_cache — ETS-based statement metadata cache

The prepared_query path sends only BIND+DESCRIBE+EXECUTE+SYNC,
skipping the PARSE step entirely. This eliminates server-side query
parsing and planning on repeated queries.

Includes 13 new Common Test cases covering prepare, query_prepared,
error handling, rows_as_maps, and with_conn usage.
@Taure
Taure force-pushed the feat/prepared-statements branch from 83a13de to 9f2ff5f Compare March 22, 2026 15:25
Taure added 2 commits March 22, 2026 19:18
query_prepared now transparently prepares statements on connections
that haven't seen them yet. On first use of a connection, it calls
pgo_handler:prepare before executing. Subsequent calls on the same
connection skip the prepare step via ETS-based tracking.

- pgo_prepared_cache tracks {ConnectionPid, StatementName} pairs
- maybe_prepare_on_conn/3 handles auto-prepare in pgo:query_prepared
- Handles "already prepared" (42P05) gracefully
- New test: auto_prepare_across_pool with pool_size=5 and 20 queries
Use edoc comments instead of -doc/-moduledoc attributes for
OTP 26 compatibility.
Comment thread src/pgo.erl
Pool = maps:get(pool, Options, default),
PoolOptions = maps:get(pool_options, Options, []),
DecodeOptions = maps:get(decode_opts, Options, []),
case checkout(Pool, PoolOptions) of

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Any existing transaction is ignored?


%% @doc Store a prepared statement's query and parameter OIDs.
-spec store(iodata(), iodata(), [pg_types:oid()]) -> ok.
store(Name, Query, OIDs) ->

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Does this need to be per-pool?

Or maybe the whole cache should be per-pool and started in the supervisor with the pool?

-define(CONN_TABLE, pgo_prepared_conn_cache).

%% @doc Initialize cache tables. Safe to call multiple times.
init() ->

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Should be a process so it can be supervised and the tables aren't owned by whoever called init?

Comment thread src/pgo.erl
end.

maybe_prepare_on_conn(Owner, NameBin, Conn) ->
Key = {Owner, NameBin},

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Using Owner means that the underlying postgres connection may have reconnected and lost the prepared statement. This needs to be keyed on the actual socket maybe or do a flush when the Owner has to reconnect.

Comment thread src/pgo.erl
{ok, Ref={_, _, _, Holder}, Conn=#conn{owner=Owner, decode_opts=DefaultDecodeOpts}} ->
try
NameBin = iolist_to_binary(Name),
_ = maybe_prepare_on_conn(Owner, NameBin, Conn),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Won't this mean if preparing fails it'll continue on and ultimately return the wrong error message when it should tell the user why the preparation failed?

Comment thread src/pgo.erl

-spec query_prepared(iodata(), list(), [pg_types:oid()], options()) -> result().
query_prepared(Name, Params, ParameterOIDs, Options) ->
pgo_prepared_cache:init(),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why setup caches here like this?

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