Skip to Content
fusion-orm

Prepared statements

An opt-in LRU+TTL prepared-statement cache with refcounting, ErrBadConn recovery, and transaction-scoped caches.

Setting PrepareStmt: true in the config wraps the connection pool in a prepared-statement cache: each distinct SQL string is prepared once, stored in an LRU list with an optional TTL, and reused for every later execution (fusion.go:77).

db, err := fusion.Open(sqlite.Open(dsn), &fusion.Config{
	PrepareStmt:           true,
	PreparedStmtCacheSize: 1000, // the default
	PreparedStmtTTL:       0,    // no expiry
})

Configuration

FieldDefaultMeaning
PrepareStmtfalseEnables the cache. Open installs the wrapper around the dialector's pool (fusion.go:206).
PreparedStmtCacheSize1000Upper bound on cached statements; the least-recently-used entry is evicted beyond it (fusion.go:79, prepared_stmt.go:34).
PreparedStmtTTL0 (no expiry)Entries older than the TTL are re-prepared on next use (fusion.go:81, prepared_stmt.go:49).

With PrepareStmt: false, statements execute directly through database/sql with no caching layer.

What gets cached

The cache key is the final SQL string with placeholders in place — not the bound variables. Two executions of the same Where("name = ?", x) shape share one prepared statement regardless of the argument, while a query built with interpolated literals prepares a fresh entry. Ping is forwarded to the wrapped pool, so Open's automatic ping and caller pings keep working with the cache enabled (prepared_stmt.go:204).

Refcounted entries

A cached statement can never be closed under a caller that is using it. Every acquisition takes a reference; eviction retires the entry — it leaves the cache immediately — but the underlying *sql.Stmt is closed only when its last in-flight holder releases it (prepared_stmt.go:17-24):

// refs counts in-flight acquisitions of this entry; retired marks it
// as gone from the cache. Both are guarded by stmtCache.mu, and the
// underlying *sql.Stmt is only Closed when retired is set and refs
// reaches zero — so a statement handed to a caller can never be
// closed under it by a concurrent LRU eviction (GORM #7831 class).

Each get returns a release func the caller must invoke exactly once — the execution paths in the ORM do this via defer (prepared_stmt.go:41). A concurrent prepare of the same query resolves to a single winner; the loser closes its statement and joins the cached entry (prepared_stmt.go:64-70).

ErrBadConn recovery

If an execution fails with driver.ErrBadConn — the classic symptom of a schema change or a broken connection — the cache drops that statement and retries once directly against the underlying pool, transparently to the caller (prepared_stmt.go:168):

result, err := stmt.ExecContext(ctx, args...)
if errors.Is(err, driver.ErrBadConn) {
	p.cache.remove(query)
	return p.pool.ExecContext(ctx, query, args...)
}

The same recovery covers QueryContext (prepared_stmt.go:182) and the transaction-scoped paths.

Transactions get their own cache

Beginning a transaction through a cached pool wraps the *sql.Tx in a transaction-scoped cache (preparedTx) with the same semantics (prepared_stmt.go:222). The cache is drained when the transaction commits or rolls back, so statements prepared inside a transaction never leak past its lifetime (prepared_stmt.go:291-309).

AutoMigrate invalidates the cache

DDL can leave cached statements pointing at a stale schema — the GORM #7255 class of bug. db.Migrator() registers an invalidator on the migrator, and AutoMigrate calls it after any DDL, dropping every cached statement — pool-scoped and transaction-scoped (fusion.go:378, prepared_stmt.go:211).

// After AutoMigrate adds a column:
if pool.cache.len() != 0 {
	t.Errorf("prepared cache still holds %d entries after AutoMigrate (GORM #7255)", pool.cache.len())
}

Verifying the cache

The cache lives behind the ConnPool interface, so it is observable by type assertion — this is how the package tests check that Open installed the wrapper and that entries were cached (prepared_stmt_test.go:64):

pool, ok := db.Config.ConnPool.(*preparedPool)
if !ok {
	t.Fatal("PrepareStmt did not install the wrapper")
}
if pool.cache.len() == 0 || pool.cache.len() > 4 {
	t.Errorf("cache size = %d", pool.cache.len())
}

Unexported type

preparedPool is unexported, so the assertion works only inside the fusion package's own tests. Outside, verify behaviorally: enable PrepareStmt, run the same query twice, and observe a single PrepareContext through a wrapping ConnPool or the query logger.

When to enable it

Enable when your workload re-executes the same statement shapes — the typical web app does — and parse/plan time is measurable on your driver. PostgreSQL's planner in particular benefits from prepared plans.

Skip it when statements are highly dynamic (every query distinct — the cache would just churn), when memory is tight (each cached statement holds driver-side state), or when a driver handles statement caching itself.

The cache is bounded and self-healing: LRU eviction caps memory, TTL re-prepares stale plans, refcounts prevent use-after-close, and ErrBadConn recovery plus AutoMigrate invalidation handle schema drift.

Next

On this page