Skip to Content
fusion-orm
Guides

Debugging queries

Four tools for seeing what fusion-orm actually runs — ToSQL, DryRun, Debug, and the logger — plus a workflow for hunting bugs.

When a query misbehaves, the question is always the same: what SQL ran, with what values? fusion-orm gives you four escalating tools to answer it, plus a structured hook for production. All of them are cheap to reach for; none require changing the query itself.

ToolWhat you getUse it when
ToSQLA display string, vars interpolated and escapedYou want to eyeball one statement, e.g. in a test failure
DryRunStatement.SQL + Statement.Vars on a chain, unexecutedYou want the machine-readable SQL and the bound vars separately
Debug()A derivative that logs every statement at Info levelYou want traces for a specific code path during development
The loggerPer-statement traces, slow-query warnings, error linesYou want ambient visibility, especially slow SQL in production
SlogQueryHookStructured slog events around every executionYou want query events in your structured log pipeline

ToSQL — render and interpolate

ToSQL runs a query function in a DryRun session, then interpolates the captured vars through the dialector for display:

// ToSQL renders the SQL that queryFn would produce, without executing it.
// queryFn runs in a DryRun session; the captured statement text is
// interpolated through the dialector for display:
//
//	sql := db.ToSQL(func(tx *fusion.DB) *fusion.DB {
//	    return tx.Exec("SELECT * FROM users WHERE id = ?", 1)
//	})

The interpolation is escape-safe — quotes are doubled, not stripped, so what you read is what the database would compare:

got := db.ToSQL(func(tx *DB) *DB {
	return tx.Exec("SELECT * FROM users WHERE name = ?", "O'Brien")
})
want := "SELECT * FROM users WHERE name = 'O''Brien'"

Because the chain is copy-on-write, the queryFn builds on a throwaway derivative; the receiver is untouched. An empty chain renders as the empty string (fusion_test.go:146).

DryRun — capture without executing

Session(&Session{DryRun: true}) produces a derivative whose finishers build the statement and stop. The SQL text and vars land on the chain's Statement:

tx := db.Session(&Session{DryRun: true}).Exec("SELECT * FROM users WHERE id = ?", 7)
// tx.Statement.SQL  == "SELECT * FROM users WHERE id = ?"
// tx.Statement.Vars == []any{7}
// the root config is untouched: db.Config.DryRun == false

Unlike ToSQL, DryRun keeps SQL and vars separate — placeholders stay placeholders. That is the form you want when a value is secret, when you want to paste the pair into a driver-level reproducer, or when you want to assert on a var programmatically. Statement.SQL is a []byte and Statement.Vars a []any (statement.go:24).

DryRun also works mid-chain: build your query as usual, then call .Session(&fusion.Session{DryRun: true}) right before the finisher to capture what that exact chain would run.

Debug() — log a code path

Debug() returns a derivative whose logger is LogMode(logger.Info) — every statement executed through it emits a trace line:

// Debug returns a derivative that logs every SQL trace at Info level.
func (db *DB) Debug() *DB {
	tx := db.getInstance()
	return tx.Session(&Session{Logger: db.Logger.LogMode(logger.Info)})
}

Use it when the default logger (Warn) is too quiet but you only want verbosity for one suspicious call, not the whole process:

db.Debug().Model(&User{}).Where("name = ?", "Ada").Find(&users)

Like every session flag, the Info level lives on the derivative only — the root logger keeps its configured level.

The logger — ambient tracing and slow SQL

The default logger writes gorm-parity trace lines to stdout at Warn with a 200 ms slow threshold (logger/logger.go:94):

[0.123ms] [rows:1] SELECT * FROM users WHERE id = 1
SLOW SQL >= 200ms [0.300ms] [rows:1] SELECT ...
ERROR record not found [1.000ms] [rows:-1] SELECT ...

Every knob lives on logger.Config:

// Config tunes a logger built with New.
type Config struct {
	// SlowThreshold marks traces slower than this as warnings. Zero
	// disables slow-SQL detection.
	SlowThreshold time.Duration
	// LogLevel gates output; the zero value means Warn.
	LogLevel LogLevel
	// IgnoreRecordNotFoundError suppresses traces whose error is
	// ErrRecordNotFound (common and expected on First/Take/Last misses).
	IgnoreRecordNotFoundError bool
	// ParameterizedQueries strips bound variables from logged SQL so
	// user data never reaches the log.
	ParameterizedQueries bool
	// Colorful enables ANSI colors in the stdlib writer output.
	Colorful bool
}

Slow-SQL lines are the workhorse: they fire at Warn even when Info is off, so a slow query surfaces without turning on full tracing. The format is asserted in the test suite:

w := &bufWriter{}
l := New(w, Config{LogLevel: Warn, SlowThreshold: time.Nanosecond})
begin := time.Now().Add(-time.Hour)
l.Trace(context.Background(), begin, func() (string, int64) {
	return "SELECT slow", -1
}, nil)
// output begins: "SLOW SQL >= 1ns " ... "[rows:-1] SELECT slow"

Values in logs

By default the stdlib and slog loggers interpolate bound vars into the trace line for readability. Set ParameterizedQueries: true in the logger config to drop the vars and log placeholder text only — the ParamsFilter interface then returns the params list empty (logger/logger.go:182).

For structured logging, swap the sink for logger.NewSlogLogger (logger/slog.go:19) — trace events become slog records with duration/sql/rows/error attributes, gated by the same Config.

SlogQueryHook — structured query events

Where the logger traces statements, SlogQueryHook observes executions — a QueryHook that logs one structured event per completed statement:

// SlogQueryHook logs completed statements through log/slog without
// recording bound parameter values.
type SlogQueryHook struct {
	Logger *slog.Logger
	Level  slog.Level
}

Attach it to a session with QueryHook (query_hook.go:102). The hook emits sql, duration_ms, rows, and error when set — and never the bound parameters. The test asserts exactly that:

hook := &SlogQueryHook{Logger: slog.New(slog.NewTextHandler(&out, nil)), Level: slog.LevelInfo}
db.QueryHook(hook).Exec(`INSERT INTO slog_users (name) VALUES (?)`, "secret-value")
// out contains the SQL text but never "secret-value"

Use the hook when query events belong in the same slog pipeline as the rest of your application logs; use the logger when you want gorm-style trace lines and slow-query detection.

A debugging workflow

When a statement does the wrong thing, work down this list:

  1. Reproduce with DryRun. Rerun the exact chain under Session(&fusion.Session{DryRun: true}) so nothing touches the database. If you cannot reproduce it dry, the problem is data, not SQL.
  2. Inspect Statement.SQL and Statement.Vars. The captured text is what the builder produced — check the clause order, the table name, the quoted identifiers. Check the vars for values you did not expect.
  3. Check dialect feature gating. Operations that depend on a dialect capability fail with ErrUnsupportedFeature, and the error names the flag: an errors.As on *fusion.UnsupportedFeatureError gives you its Feature field (errors.go:67). For example, FindInBatches over a composite primary key requires the RowValues feature (finisher_api.go:395).
  4. Check the error slot wrap chain. Every failure flows through the chain's single error slot: the first error is kept as the wrap head so errors.Is keeps matching the original sentinel, and execution layers wrap on the way out ("query users: ..." — callbacks_default.go:189). Branch on sentinels with errors.Is, never on message text (errors.go:83).

Bug hunt: the vanishing rows

A classic report: "the user exists, I can see it in the table, but the query returns nothing." Hunt it with DryRun.

Step 1 — reproduce. The model embeds fusion.DeletedAt; the query looks innocent:

tx := db.Model(&User{}).
	Where("name = ?", "Ada").
	Session(&fusion.Session{DryRun: true}).
	Find(&users)
fmt.Println(string(tx.Statement.SQL), tx.Statement.Vars)

Step 2 — inspect. The captured SQL is not what you wrote:

SELECT * FROM "users" WHERE name = ? AND "deleted_at" IS NULL

There is the culprit: the schema has a soft-delete field, so the builder appends the live-row predicate to every query (soft_delete.go:135). The row you are looking for was soft-deleted, and deleted_at IS NULL correctly excludes it.

Step 3 — fix deliberately. If you truly want deleted rows in this one query, opt out with Unscoped (chainable_api.go:80):

db.Unscoped().Model(&User{}).Where("name = ?", "Ada").Find(&users)

Unscoped disables soft-delete filtering — and soft-delete DELETE rewriting — for that statement only. To bring a soft-deleted row back, use Restore (soft_delete.go:227) rather than a hand-written UPDATE.

DryRun never lies about scope

The soft-delete predicate is injected at build time, so DryRun and ToSQL always show it — including when it rides along on preloads issued from an unscoped statement (chainable_api.go:78).

Next

On this page