SLOPDB / DOCUMENTATION / PREPARED STATEMENTS

Prepared statements

Database.Prepare parses one SQL statement once. Use anonymous ? placeholders for values, including LIMIT and OFFSET. Executions bind typed values into private reusable ASTs and skip SQL tokenization and parsing. Eligible statements also reuse validated column bindings, primary-key lookup recipes, update target and affected-index bindings, tuple-range predicate and index-coverage templates, and typed aggregate instruction programs.

Each execution rebuilds physical keys and scan bounds from its private arguments and evaluates access costs against current statistics. Catalog and statistics changes invalidate compiled metadata; local transaction DDL and rollback are also recognized. Row data, query results, locks, snapshots and iterators are never cached. Joins, subqueries and unsupported operator shapes continue through the ordinary planner and executor.

Stmt.PlanStats() reports lifetime Builds and Hits. Each pooled execution tree owns its mutable programs exclusively, so concurrent executions can build more than one template without sharing registers or parameter cells. Pool eviction can also cause a rebuild. These counters describe structure reuse, not result cache hits or a promise that a particular physical index will always be chosen.

Statements owned by a session or transaction retain one private binding under that session's execution gate. Garbage collection does not evict this binding; catalog/statistics changes and transaction rollback still invalidate its plans. Argument references are cleared after each execution. Database-wide shared statements keep their concurrent execution-tree pool.

stmt, err := database.Prepare("SELECT balance FROM customer WHERE w_id=? AND d_id=? AND c_id=?")
if err != nil {
    return err
}
defer stmt.Close()

result, err := stmt.ExecContext(ctx, 1, 2, 3)

A statement prepared on a database can be shared concurrently across its sessions and transactions. Execute it on a transaction to use that transaction's locks and private writes:

update, err := database.Prepare("UPDATE stock SET quantity=quantity-? WHERE w_id=? AND i_id=?")
if err != nil {
    return err
}
defer update.Close()

tx, err := database.BeginContext(ctx)
if err != nil {
    return err
}
defer tx.Rollback()
if _, err = tx.ExecPreparedContext(ctx, update, 5, 1, 42); err != nil {
    return err
}
return tx.Commit()

Session.Prepare and Tx.Prepare bind the statement to that session or transaction; their statement's Exec methods execute there. A bound statement cannot be moved to another session or used after the original context closes. Database-prepared statements can be passed to Session.ExecPrepared or Tx.ExecPrepared, but cannot be moved to another database. The context variants are PrepareContext, ExecContext, and ExecPreparedContext. Per-call timeout settings are available through Stmt.ExecWithOptions, Stmt.ExecContextWithOptions, and session/transaction ExecPreparedContextWithOptions.

Stmt.NumInput reports the required argument count. Bindings accept signed Go integers, unsigned integers up to MaxInt64, finite floating-point values, strings, booleans (SQL integer 0/1), []byte blobs, sql.Value, and nil for SQL NULL. Blob arguments are copied. A nil []byte binds NULL; an empty non-nil slice binds an empty blob. Wrong argument counts, unsupported values, non-finite reals, and integers outside the signed 64-bit range fail before SQL execution. SQL text inside a string argument remains data.

Parameters stand for expressions, not identifiers, aliases, SQL fragments, or persistent schema definitions. Named and numbered parameters are not supported. Multi-statement strings are rejected by Prepare. Parameterized schema statements (including defaults, checks, views, and triggers) are rejected; constant schema statements can still be prepared and reused. A bound integer in ORDER BY ? or GROUP BY ? is a constant expression, not a column ordinal.

Close is idempotent and rejects new executions with db.ErrStmtClosed; an already-started execution may finish. Closing a statement does not close its session or roll back its transaction.

Reuse SELECT result buffers

Session.ExecPreparedInto lets a reader reuse its own result buffers:

var result db.ExecResult
for _, id := range ids {
    _, err := session.ExecPreparedInto(&result, stmt, id)
    if err != nil {
        return err
    }
    // Consume this result before the next call that uses result.
    consume(result.Rows)
}

A prepared point SELECT reuses the column slice, row map, and BLOB capacity. The caller gives up all old contents on entry. Do not retain aliases to these buffers across calls or share a destination between concurrent readers. Use one destination per reader. On error, its contents are unspecified. Other query shapes and writes use their normal executor and replace the result. Cancellation, statement snapshots, transaction rules, and validation are the same as for ExecPrepared. Context and per-call options are available through ExecPreparedContextInto and ExecPreparedContextWithOptionsInto.

The ordinary API continues to return independent results that can be retained. Point SELECTs decode only columns needed by the projection and WHERE predicate, so an unselected text or BLOB field is not copied.

Prepared root reads compile namespace and system-view classification once and retain the private bound AST and read recipe when no rewrite is needed. Other namespace paths retain normal resolution; schema, dialect, temporary-table and catalog changes still invalidate affected recipes. Point recipes also cache immutable projection and decoding metadata instead of parsing declared types for every returned value.

Reusable destinations retain their row and BLOB storage across empty results. WHERE-only values use private, bounded scratch and never retain a projected caller buffer. Exact signed-integer primary-key predicates can omit redundant residual evaluation only after the compiled key proof and this execution's binding checks succeed. Extra, duplicate, volatile and error-producing conditions retain normal evaluation and validation.

The SELECT benchmark exposes -reuse-results; use a fixed API mode and runtime configuration when comparing engine versions.

Prepared plan counters use 128 independent counter shards. A private bound AST gets its shard when it is created and keeps it through metadata invalidation. The hot query path does not update a global counter. PlanStats sums the shards; totals are exact when executions are idle. A read during execution can observe increments from different moments, as with the previous separate counters.

64-bit pagination

SELECT, compound SELECT, UPDATE, and DELETE store both Limit and Offset as explicit int64 fields. Text literals and prepared arguments support the full signed 64-bit range; out-of-range literals and arguments are rejected rather than narrowed to the platform's int. A bound LIMIT/OFFSET value must be an integer, not NULL, a string, or a real. Negative LIMIT retains the existing unlimited convention; negative OFFSET becomes zero.

Scan windows saturate LIMIT + OFFSET at MaxInt64 to prevent overflow. Result slicing converts an offset or limit to a native index only after comparing it with the actual slice length. Large pagination values do not cause a proportional preallocation. Explicit int64 AST fields change source compatibility for code constructing ASTs with native int variables; convert those fields with int64(value).

TPC-C-inspired tester

The tester now defaults to prepared statements. Every workload statement and stock-level IN-list arity is prepared before measurement; there is no fallback to parsing SQL during the prepared workload. Preparation duration and execution mode are recorded in JSON. Loading, preflight, accounting checks, and reopening remain outside the benchmark window. The prepared path uses a prepared COMMIT; the SQL text comparison uses the same workload templates, parameters, transaction order, and scale.

go run ./cmd/tpcc -workers 10 -duration 1m -json /tmp/slopdb-tpcc-prepared-results.json
go run ./cmd/tpcc -workers 10 -duration 1m -prepared=false -json /tmp/slopdb-tpcc-text-results.json

WAL stays enabled and WAL fsync remains disabled by default. This is a reduced, TPC-C-inspired workload, not a compliant TPC-C score.

Retained bindings for SQL adapters

The lower-level sql.PreparedQuery.NewBinding() API creates a *sql.PreparedBinding that retains one private execution tree across garbage collections. PreparedBinding.Bind(args) returns a *sql.BoundQuery; release it with BoundQuery.Release() before binding again. Release clears argument references while retaining reusable plan storage. A binding must have one serialized owner and cannot be used concurrently. Database-wide concurrent callers should use PreparedQuery.Bind instead. Native session and transaction statements manage their own private binding automatically.

For adapters that already parsed a literal SELECT, parsed-query execution combines reusable point and bounded-read result storage with a streaming fallback. At the SQL layer, sql.LiteralPointSelectEligible(stmt) is only a syntactic filter. Schema.TrySelectPointInto(stmt, dst) must also prove the lookup against the catalog. Schema.TrySelectReadInto(stmt, dst) extends this to eligible small signed-integer primary-key IN and range reads; callers at this layer must hold the normal statement snapshot and catalog locks. A false handled result has not evaluated SQL, so ordinary execution can follow. Application code should use the session API to obtain those lifecycle guarantees.

Project documentation and source-verified API notes · e5e2eb2View source on GitHub ↗