minato_query (minato v1.2.0)
View SourceRunning SQL on a connection, in both of the protocol's two query paths.
simple/2 is the simple query protocol: one message, any number of statements,
every value in the text format, and no parameters. query/3 is the extended
protocol: Parse, Describe, Bind, Execute, Sync, with parameters sent
as parameters and results asked for in the binary format wherever minato has a
codec for the type.
Both take a connection and hand one back, because the connection carries the bytes that have arrived but not been read. A result and a connection to carry on from is the whole return value:
{ok, #{rows := [{1}]}, Conn1} = minato_query:query(Conn, ~"SELECT $1::int", [1]).Which formats are asked for
Describe says what the parameter types are and what the result columns are,
and minato_codec:preferred_format/1 turns each of those OIDs into binary for
a type minato has a codec for and text for one it does not. A column of an
extension type therefore still arrives, as its text representation, rather than
failing the query.
RowDescription from a Describe reports every column as text, because the
formats are not chosen until Bind. minato replaces those with what it asked
for before decoding, since believing the description would decode binary bytes
as text on the first integer column.
Errors leave the connection usable
A statement that fails is a normal outcome. {error, {pgsql_error, Fields}, Conn} hands the connection back because the extended protocol says a failed
statement is discarded until Sync, and this module reads on to
ReadyForQuery before returning, so the connection really is ready.
A connection returned in the error tuple is usable. One that is not usable is
not returned: {error, {socket, _}} has no connection in it, because a socket
that failed mid-message leaves the stream at an unknown offset, and there is
nothing to hand back that could be trusted.
A value that does not fit is the caller's, not the connection's
A parameter that will not encode, the wrong number of parameters, and a value
from the server that will not decode all raise, error({minato_codec, _}) or
error({minato_query, _}), because there is no result to return. None of them
costs the connection. Before the raise the exchange is ended with Sync, an
answer that was being read is read to its ReadyForQuery, and a statement
cached/4 parsed for the call is closed again, so the connection that was
passed in is the one to carry on with. It is closed only if it could not be
put back, and then says so on its next use.
What is not here
No transactions and no LISTEN. Both are session state rather than statements,
and both need the connection to be pinned to the caller for longer than one
query, so they belong with the pool that hands connections out.
Summary
Types
What went wrong.
Decoding options, plus how long the statement may run.
The map carried by an error({minato_query, Report}) exception.
A parsed statement on the server, with what it takes and what it returns.
Functions
cached/4 with the default decoding options.
Run a statement, parsing it once per connection and keeping it.
Close a prepared statement and free what the server holds for it.
execute/4 with the default decoding options.
Run a prepared statement.
Parse a statement under a name and keep it for the life of the connection.
query/4 with the default decoding options.
Run one statement with parameters, through the extended protocol.
simple/3 with the default decoding options.
Run one or more statements through the simple query protocol.
Types
-type conn() :: minato_conn:conn().
-type error() :: minato_conn:error().
What went wrong.
Every failure here comes from the connection layer or from the server. A parameter count that does not match raises instead of being returned, because it is a bug in the caller rather than a condition to branch on.
-type opts() :: #{timeout => timeout(), return_rows_as_maps => boolean(), column_name_as_atom => boolean(), uuid_format => string | binary, datetime_format => datetime | microseconds, numeric_format => binary | float}.
Decoding options, plus how long the statement may run.
#{timeout => timeout(),
return_rows_as_maps => boolean(),
column_name_as_atom => boolean(),
uuid_format => string | binary,
datetime_format => datetime | microseconds,
numeric_format => binary | float}Everything but timeout is passed to minato_protocol unchanged. timeout
becomes a deadline on the statement: when it expires the statement is cancelled
on the server rather than abandoned, and comes back as 57014 with the
connection still usable. It defaults to the connection's own read timeout, so a
statement that outlives that costs a statement rather than a connection. See
minato_conn:deadline/2.
timeout is a number of milliseconds, an integer that is not negative, or
infinity. Anything else raises
error({minato_query, #{message := options, reason := {invalid_option, timeout}}})
before the statement is sent, so the connection that was passed in is the one
to carry on with. It used to be a badarith, or a statement that was cancelled
as soon as it was sent.
The map carried by an error({minato_query, Report}) exception.
-type result() :: minato_protocol:result().
-opaque statement()
A parsed statement on the server, with what it takes and what it returns.
Belongs to the connection it was prepared on: a name is only meaningful to the session that parsed it, so a statement cannot be carried to another connection.
Functions
-spec cached(conn(), iodata(), [term()]) -> {ok, result(), conn()} | {error, error(), conn()} | {error, error()}.
cached/4 with the default decoding options.
-spec cached(conn(), iodata(), [term()], opts()) -> {ok, result(), conn()} | {error, error(), conn()} | {error, error()}.
Run a statement, parsing it once per connection and keeping it.
The same SQL on the same connection costs one round trip after the first, which
is what query/3 cannot do: it parses unnamed every time, because it has
nowhere to keep anything. A pooled caller gets a different connection each time
and would pay the parse on each of them; a connection that keeps its statements
pays it once per connection instead.
The cache is the connection's, bounded by prepared_statements in
minato_conn:opts/0, and a connection that is full runs anything new unnamed.
A workload with unbounded distinct SQL therefore gets the uncached path rather
than an unbounded pile of parsed statements in the backend.
A kept statement the server stops accepting
A statement is kept with what the server made of it when it was parsed: its plan, the types of its parameters and the columns of its result. Changing a table under it can make any of those wrong, and that is not an error the caller can do anything with. So where the server's answer says the statement may have gone stale, it is dropped from the cache, parsed again and run once more, and only what the second run answers is returned:
0A000, the result is not the one the plan was made for;26000, the server no longer has the statement, because something on the session ranDEALLOCATEor a pooler handed the call to another backend;08P01from the bind, which is a pooler having parsed the statement afresh where it has another number of columns;- an error of class
42for a statement with parameters, or a value that will not encode as the type kept here, when asking the server again shows the parameter types have changed. If they have not, the error or the raise was about the call and is what the caller gets, at the cost of that one question.
Never twice, and never inside a transaction the error has aborted, where parsing again could only fail: there the statement is dropped and closed, and the server's error is returned as it came.
A value that will not encode is raised at once inside any transaction, open or
aborted, and nothing is sent: the question would be a Parse in the caller's
transaction, and a statement that no longer parses would abort it over what is
usually a mistake in the call. A statement that has gone stale there is found
by the server at the next bind.
Only a refusal that arrives before BindComplete counts, which is where the
server checks the plan and before anything has run. A statement that fails
once it is running has failed, whatever code it fails with: it is returned and
not run a second time, since what it did outside its transaction, a nextval
or a dblink call, would be done twice.
What this cannot see is a statement that still runs and now answers with other types in the same number of columns, which happens behind a pooler that prepares statements itself. See "PgBouncer and connection poolers" in the configuration guide.
Close a prepared statement and free what the server holds for it.
A connection that is handed back to a pool with a hundred one-off named statements on it is a connection leaking server memory for the rest of its life.
-spec execute(conn(), statement(), [term()]) -> {ok, result(), conn()} | {error, error(), conn()} | {error, error()}.
execute/4 with the default decoding options.
-spec execute(conn(), statement(), [term()], opts()) -> {ok, result(), conn()} | {error, error(), conn()} | {error, error()}.
Run a prepared statement.
Raises error({minato_query, t:report/0}) when the number of parameters does
not match what the statement was described as taking. That is a bug in the
caller rather than a condition to branch on: the server would refuse it too, a
round trip later and with a worse message.
The connection is put back to ready before the exception is raised, with a
Sync and a read to ReadyForQuery. Raising in the middle of an extended query
cycle would otherwise leave a connection that is only good for closing, which is
a heavy price for what is usually a typo. A parameter that will not encode
raises error({minato_codec, _}) in the same way.
-spec prepare(conn(), binary(), iodata()) -> {ok, statement(), conn()} | {error, error(), conn()} | {error, error()}.
Parse a statement under a name and keep it for the life of the connection.
The describe round trip happens here rather than on every execute/3, which is
the point: a statement run in a loop costs one round trip a time. Preparing is
one round trip itself: Parse, Describe and Sync in one write.
The name is the caller's. A name already in use is refused with 42P05, so
close/2 it first to parse something else under it.
The answer is given the connection's timeout as its deadline, as a statement
with no timeout of its own is. A server that has not finished it by then,
whatever it sends in the meantime, costs the connection:
{error, {socket, timeout}}.
-spec query(conn(), iodata(), [term()]) -> {ok, result(), conn()} | {error, error(), conn()} | {error, error()}.
query/4 with the default decoding options.
-spec query(conn(), iodata(), [term()], opts()) -> {ok, result(), conn()} | {error, error(), conn()} | {error, error()}.
Run one statement with parameters, through the extended protocol.
The statement is parsed unnamed, so it is replaced by the next one and nothing
accumulates on the server. A statement that will run again belongs in
prepare/3, which parses it once and keeps it.
Two round trips: Parse and Describe have to be answered before the
parameters can be encoded, because their types are the server's to decide.
That is the price of not guessing them, and prepare/3 pays it once.
-spec simple(conn(), iodata()) -> {ok, [result()], conn()} | {error, error(), conn()} | {error, error()}.
simple/3 with the default decoding options.
-spec simple(conn(), iodata(), opts()) -> {ok, [result()], conn()} | {error, error(), conn()} | {error, error()}.
Run one or more statements through the simple query protocol.
Answers with one result per statement, in order, which is why this is the only function here that returns a list. Every value comes back in the text format, because the simple query protocol has nowhere to ask for anything else.
There are no parameters. A value pasted into the SQL is an injection waiting to
be found, so anything with a value in it belongs in query/3.