sqltx

package
v1.6.26 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: BSD-3-Clause Imports: 10 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sqltx carries a database/sql transaction from the flow engine to the connector activities that must enlist in it (FLOGO-19484).

The registry is ONE context key holding an immutable map[connID]*Handle, replaced copy-on-write. Copy-on-write is mandatory: with FLOGO_FLOW_EXECUTE_BRANCHES_CONCURRENTLY=true sibling branches read the map simultaneously, so WithHandle must never mutate a map that is already visible to another goroutine.

Keying by connection id is what keeps the transaction scoped: an activity only enlists when it uses the very connection the transactional subflow declared. Two different connections inside one subflow cannot cross-contaminate.

Index

Constants

This section is empty.

Variables

View Source
var ErrTxFinished = fmt.Errorf(
	"SUBFLOW-TX-005: the enclosing transactional subflow has already ended; this statement was not executed: %w",
	sql.ErrTxDone)

ErrTxFinished is returned by PrepareCached after the finalizer has committed or rolled back. It WRAPS sql.ErrTxDone so connectors may use errors.Is(err, sql.ErrTxDone) while the user-facing text names the subflow instead of the opaque "sql: transaction has already been committed or rolled back".

View Source
var NoRelease = func() {}

NoRelease is the release func for a statement the caller does not own: the process-wide cache owns it on the non-enlisted path, and the transaction owns it on the memoised path. Callers always `defer release()`, so having a shared no-op keeps every call site the same shape.

Functions

func ConnIDs

func ConnIDs(ctx context.Context) []string

ConnIDs returns the connection ids ctx carries, unordered. Used by the nested-transaction guard and by the D13 warning message.

func HasAny

func HasAny(ctx context.Context) bool

HasAny reports whether ctx carries any handle at all. This is the fast path every connector takes before doing anything else: one ctx.Value walk on the non-transactional path.

func Propagate

func Propagate(src, dst context.Context) context.Context

Propagate copies src's registry onto dst, preserving dst's own cancellation and deadline.

It returns dst UNCHANGED - identically, with no allocation - when src carries no registry. That identity matters: flow's TestGoContextEvalCtxOverride asserts GoContext() returns exactly the context it was given, and every non-transactional flow goes through this path.

func WithHandle

func WithHandle(ctx context.Context, connID string, h *Handle) context.Context

WithHandle returns a context carrying h for connID.

It is a no-op when h is nil or connID is empty, so a caller can never store a typed nil that later reads back as a non-nil interface.

func Without

func Without(ctx context.Context) context.Context

Without strips the registry. Used for detached subflows, which outlive the transaction and must never enlist in it.

Types

type Handle

type Handle struct {
	// contains filtered or unexported fields
}

Handle is the ambient transaction for exactly one transactional subflow invocation.

THREE MUTEXES, ONE OF WHICH - mu - IS THE ONLY ONE A CONNECTOR EVER TOUCHES. A single mutex self-deadlocks: the connector takes the operation lock at the top of PreparedQuery and then calls getStatement, which re-enters the handle, and sync.Mutex is not reentrant.

mu      the D3 SERIALISATION lock. A connector takes it at the TOP of a whole Prepared*
        operation and releases it only after *sql.Rows has been fully drained, because
        database/sql pins the transaction's single connection until the Rows is closed.
        Exposed as Lock/Unlock/TryLockFor.
stmtsMu guards the statement memo, the done flag and the warn set ONLY.
opMu    guards the in-flight statement-cancel registrations ONLY.

The lock order is acyclic because nothing inside this package ever takes mu, and opMu and stmtsMu are never held simultaneously. That is what makes PrepareCached, MarkDone, IsDone, WarnOnce and OpContext safe to call with mu held, which is the normal case.

Every method is nil-receiver safe: connectors call them on values that are nil on the non-transactional path.

func FromContext

func FromContext(ctx context.Context, connID string) *Handle

FromContext returns the handle registered for connID, or nil. Safe on a nil context.

func FromManager

func FromManager(ctx context.Context, m connection.Manager, logger log.Logger) *Handle

FromManager returns the ambient transaction handle for m, or nil.

It is the ONLY entry point a connector needs, and it is the single home of the foreign-connection warning, so all four connectors get identical wording for free.

Safe on a nil context: core/support/test.TestActivityContext.GoContext() returns nil, and so does flow's LegacyCtx, and both are on paths connectors already take.

On the non-transactional path this costs one ctx.Value walk, because HasAny short-circuits before the manager is inspected at all.

func NewHandle

func NewHandle(connID string, db *sql.DB, tx *sql.Tx, baseCtx context.Context) *Handle

NewHandle builds a handle for a transaction that has already been begun.

func (*Handle) CancelInFlight

func (h *Handle) CancelInFlight()

CancelInFlight cancels EVERY statement context OpContext has handed out and not yet released. The finalizer calls it on the ROLLBACK path only.

func (*Handle) ConnID

func (h *Handle) ConnID() string

ConnID is the connection id this transaction was opened on.

func (*Handle) Context

func (h *Handle) Context() context.Context

Context returns the transaction's own context, for read-only use such as a parent. To EXECUTE a statement use OpContext instead, so the finalizer can interrupt it.

func (*Handle) DB

func (h *Handle) DB() *sql.DB

DB is the pool the transaction was taken from.

func (*Handle) IsDone

func (h *Handle) IsDone() bool

IsDone reports whether the transaction has been finalised. A nil handle counts as done.

func (*Handle) Lock

func (h *Handle) Lock()

Lock takes the D3 operation lock. It must wrap a WHOLE Prepared* operation, including full row drainage.

func (*Handle) MarkDone

func (h *Handle) MarkDone()

MarkDone is called by the finalizer BEFORE Commit or Rollback. Afterwards PrepareCached returns ErrTxFinished rather than a statement the commit is about to close.

func (*Handle) MemoSaturated

func (h *Handle) MemoSaturated() bool

MemoSaturated reports whether the statement memo hit its cap, so the connector can emit one diagnostic. See maxCachedStmts for what this does and does not tell you.

func (*Handle) MemoSaturatedOnce

func (h *Handle) MemoSaturatedOnce() bool

MemoSaturatedOnce is MemoSaturated, but true at most once per handle, for a one-shot log.

func (*Handle) OpContext

func (h *Handle) OpContext(timeout time.Duration) (context.Context, context.CancelFunc)

OpContext returns the context a connector must use to EXECUTE a statement inside the transaction, plus its release func.

The parent is baseCtx, NOT context.Background(): a per-statement context.WithTimeout(context.Background(), queryTimeout) firing mid-statement cancels the query on the connection the transaction is pinned to and typically poisons it. Cancelling baseCtx itself is not an option either - database/sql's watchdog would roll the transaction back.

Registrations are TOKEN-KEYED. A single cancel slot loses B's registration when two operations overlap, and then A's release clears B's, leaving CancelInFlight unable to unwedge anything. Overlap should not happen under the D3 discipline, but the handle must not depend on discipline it cannot enforce.

A timeout of zero or less means no deadline.

func (*Handle) PrepareCached

func (h *Handle) PrepareCached(sqlText string) (*sql.Stmt, func(), error)

PrepareCached prepares sqlText ON THE TRANSACTION and memoises it for the transaction's lifetime.

On the enlisted path we must NEVER touch the pool. sql.DB.Prepare acquires a SECOND pooled connection while the transaction pins one; at maxOpenConnection:1 - an ordinary user setting - that is a hard deadlock with no deadline to break it. Tx.PrepareContext uses the transaction's already-pinned connection and appends to tx.stmts so Commit/Rollback closes it.

The returned release func MUST be deferred by the caller. It is a no-op for a memoised statement, which the transaction owns and closes; it closes the statement only when the memo was at its cap and this statement was prepared for this call alone. Never Close the returned statement directly - use release.

Safe to call with or without the operation lock held.

func (*Handle) PrepareCachedContext

func (h *Handle) PrepareCachedContext(ctx context.Context, sqlText string) (*sql.Stmt, func(), error)

PrepareCachedContext is PrepareCached with an explicit context for the PREPARE itself.

func (*Handle) TryLockFor

func (h *Handle) TryLockFor(d time.Duration) bool

TryLockFor polls Mutex.TryLock until d elapses. It exists so the engine finalizer never blocks forever behind an abandoned execTimeout Eval goroutine. Acquiring the lock is BEST EFFORT on the rollback path: the finalizer rolls back either way, after CancelInFlight.

func (*Handle) Tx

func (h *Handle) Tx() *sql.Tx

Tx is the underlying transaction.

func (*Handle) Unlock

func (h *Handle) Unlock()

Unlock releases the D3 operation lock.

func (*Handle) WarnOnce

func (h *Handle) WarnOnce(key string) bool

WarnOnce reports whether the caller should emit a warning for key on this handle. True exactly once per handle per key - that is, once per transactional subflow invocation per foreign connection, never process-wide.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL