Skip to Content
fusion-orm
Querying

Raw SQL, Row/Rows/Scan, ToSQL & DryRun

Escape hatches — Exec, manual row scanning, SQL preview, and captured-but-unexecuted statements.

Exec

// Exec executes raw SQL with bound arguments and returns a derived
// instance carrying Error and RowsAffected. The statement is traced through
// the session logger; with Config.DryRun set the SQL and args are captured
// on Statement instead of being executed (see ToSQL).
//
//	tx := db.Exec("UPDATE users SET active = ?", true)
//	if tx.Error != nil { ... }
func (db *DB) Exec(sql string, args ...any) *DB {

Exec is for statements that return no rows — DDL, updates, deletes. Arguments bind positionally; errors are recorded on the returned derivative, never panicked:

tx := db.Exec("SELECT * FROM missing_table")
if tx.Error == nil {
	t.Fatal("expected error for missing table")
}
if db.Error != nil {
	t.Errorf("root Error = %v, want nil", db.Error)
}

RowsAffected reports how many rows the statement touched. Under a DryRun session, Exec captures SQL and vars on Statement instead of executing (see DryRun below).

Row — one row, manual scan

// Row builds the query and returns the first row for manual scanning.
// rowBuildErrorSQL fails against every dialect with a deterministic error
// (no such table), giving Row().Scan something to report when the query
// could not be built.
const rowBuildErrorSQL = `SELECT 1 FROM "__fusion_row_build_error"`

func (db *DB) Row() *sql.Row {

Row applies scopes, builds the chain, and hands back a standard-library *sql.Row:

row := db.Model(&crudUser{}).Where("name = ?", "alice").Select("age").Row()
if row == nil {
	t.Fatal("Row returned nil")
}
var age int
if err := row.Scan(&age); err != nil || age != 30 {
	t.Errorf("Row.Scan = %v, age=%d", err, age)
}

Row never returns nil on a build error (GORM #7575 class): a nil *sql.Row would panic in your Scan. Instead it returns a sentinel row against a table that cannot exist, whose Scan fails deterministically. Because *sql.Row cannot carry a custom error, the build error is also surfaced on the receiver:

m := db.Model(42) // invalid model: build fails
row := m.Row()    // never nil
if m.Error != nil {
	// the real error is here
}

Rows — iterate, then close

// Rows builds the query through the row processor and returns the result
// set; the caller must close it.
func (db *DB) Rows() (*sql.Rows, error)

The caller owns the result set and must close it:

rows, err := db.Model(&crudUser{}).Order("id").Rows()
if err != nil {
	t.Fatalf("Rows: %v", err)
}
defer rows.Close()
n := 0
for rows.Next() {
	n++
}

Rows are standard *sql.Rows — combine them with rows.Scan and the usual database/sql loop.

Scan — the finisher that fits everything

// Scan runs the accumulated query into dest.
func (db *DB) Scan(dest any) *DB

The destination decides the strategy: struct, slice of structs, map, or scalar. Reduced projections make unusual destinations natural:

var mapped map[string]any
if err := db.Model(&crudUser{}).Select("name, age").Find(&mapped).Error; err != nil {
	t.Fatalf("map Find: %v", err)
}
var total int64
if err := db.Model(&crudUser{}).Select(`COUNT(*) AS total`).Scan(&total).Error; err != nil || total != 3 {
	t.Errorf("scalar Scan = %d, %v", total, err)
}

Scanning also honors dotted column aliases for mounted relations — Select(id, name, 'mounted' AS profile__bio) populates a nested Profile pointer (see Select & Distinct).

ToSQL — preview the exact SQL

// 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)
//	})
func (db *DB) ToSQL(queryFn func(tx *DB) *DB) string {

The chain runs in a throwaway DryRun session, and the captured statement is interpolated for display — including string escaping:

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'"
SELECT * FROM users WHERE name = 'O''Brien'

Edge cases, all tested: an empty chain returns "", and a queryFn that returns nil returns "" rather than panicking. ToSQL is byte-stable across calls — the same chain twice yields identical text, which is what map-condition sorting protects (Conditions).

For display, not execution

Interpolation exists so logs and error reports are readable. The escaped string is not re-parsed by fusion-orm; execution always binds variables.

DryRun — capture without executing

func TestDryRunCapturesSQL(t *testing.T) {
	db := openTestDB(t)

	tx := db.Session(&Session{DryRun: true}).Exec("SELECT * FROM users WHERE id = ?", 7)
	if tx.Error != nil {
		t.Fatalf("dry-run Exec: %v", tx.Error)
	}
	if got := string(tx.Statement.SQL); got != "SELECT * FROM users WHERE id = ?" {
		t.Errorf("captured SQL = %q", got)
	}
	if len(tx.Statement.Vars) != 1 || tx.Statement.Vars[0] != 7 {
		t.Errorf("captured vars = %v", tx.Statement.Vars)
	}

The captured SQL keeps its placeholders (? on SQLite, $1 on PostgreSQL) with the vars alongside in Statement.Vars — this is the raw material ToSQL interpolates. The flag is session-scoped: the root config's DryRun stays false, so ToSQL and DryRun never leak into production sessions (Chaining).

Next

On this page