Statement
struct StatementA statement prepared on the server, ready to run with new parameters.
Created by Connection.prepare. Preparing pays for parsing and planning
once; each Statement.execute or Statement.query then sends only the
name and the parameter values.
A prepared statement is session-local: it lives on the connection it
was prepared on, until that connection closes or Statement.deallocate
runs. Holding a Statement keeps that connection open -- it shares
ownership of the PGconn rather than borrowing it -- so a statement may
safely outlive the Connection value it came from, which matters because
Mojo destroys a value after its last use:
var stmt = conn.prepare("s", "SELECT 1") # the last mention of `conn`,
var res = stmt.query() # and the session is still up
An explicit Connection.close is the exception: it closes the session
there and then, and every statement on it raises SQLSTATE 08006
afterwards.
Example:
var stmt = conn.prepare("insert_row", "INSERT INTO t VALUES ($1, $2)")
for i in range(1000):
_ = stmt.execute(Params().int64(i).text("row"))
Note:
Errors raised through a Statement are recorded in
Connection.last_error: the statement holds a share of the same cell
the connection does.
Implements Movable
__init__
def __init__(out self, cell: ArcPointer[_ConnCell], name: String, sql: String) Record an already-prepared statement.
Connection.prepare is the only intended caller: it issues
PQprepare and checks the status before constructing this.
- Args
cell: The shared cell of the connection it was prepared on; a share of it is kept, so the connection stays open at least as long as this statement does.name: The server-side statement name.sql: The SQL it was prepared from.
name
def name(self) -> String The server-side statement name.
sql
def sql(self) -> String The SQL this statement was prepared from.
execute
def execute(self, params: Params = Params()) -> Int Run the statement and discard any rows.
- Args
params: The values for$1,$2, ....
Raises Error: A sqlstate.PostgresError if the server rejected the
command.
query
def query(self, params: Params = Params()) -> Result Run the statement and return its rows.
- Args
params: The values for$1,$2, ....
Raises Error: A sqlstate.PostgresError if the server rejected the
command.
deallocate
def deallocate(mut self) Drop the statement from the server session.
Rarely needed -- closing the connection drops every statement it prepared -- but a long-lived connection that prepares statements dynamically will otherwise accumulate them.
Raises Error: A sqlstate.PostgresError if DEALLOCATE failed, which
for an already-deallocated statement is SQLSTATE 26000.