Skip to Content
fusion-orm
Guides

Complex queries

CTEs, subqueries, aggregates, window functions, and locking — what the builder can express today, and where you drop to raw SQL.

fusion-orm's builder is deliberately SQL-first: clauses are pure byte builders rendered by the dialect. That makes the "complex query" surface easy to reason about — anything that renders, renders honestly. This page covers what the chain can express today, and is explicit where it cannot.

CTEs — clause.With

The with clause is clause.With: a CTE name and a raw subquery string rendered as-is (clause/query.go:169):

// With renders a WITH cte AS (subquery) prefix.
type With struct {
	CTEName  string
	Subquery string
}

Register it through Clauses, which replaces same-named clauses and renders in the canonical slot order — with builds first, before select and from (statement.go:74):

chain
db.Clauses(clause.With{
  CTEName:  "adults",
  Subquery: "SELECT id FROM users WHERE age >= 18",
}).
  Model(&crudUser{}).
  Where("id IN (SELECT id FROM adults)").
  Find(&users)
SQL
WITH "adults" AS (SELECT id FROM users WHERE age >= 18)
SELECT * FROM "crud_users"
WHERE id IN (SELECT id FROM adults)
postgres · $n placeholderswith builds first (slot 1 of 16)src: composed — clause/query.go:169, statement.go:74

The same chain, verbatim from the composed example above (clause/query.go:169, chainable_api.go:262, statement.go:74):

sql := db.ToSQL(func(tx *DB) *DB {
	return tx.Clauses(clause.With{
		CTEName:  "adults",
		Subquery: "SELECT id FROM users WHERE age >= 18",
	}).
		Model(&crudUser{}).
		Where("id IN (SELECT id FROM adults)").
		Find(&[]crudUser{})
})

The CTE name is identifier-quoted by the dialect ("adults"); the subquery body passes through verbatim. The golden for the builder itself is WITH "active" AS (SELECT 1) (clause_test.go:70).

Because the subquery is a raw string, it cannot bind vars — if the CTE body needs parameters, inline them only if they are constants you control. Everything below the CTE (Where, Order, …) binds normally.

Subqueries — clause.Expr under Where

There is no subquery-builder object; the tool is a raw SQL fragment with ? placeholders. Where("...", args...) wraps the string in clause.Expr, whose Build replaces each ? with the dialect placeholder and consumes the next var (clause/clause.go:34):

sql := db.ToSQL(func(tx *DB) *DB {
	return tx.Model(&crudUser{}).
		Where("id IN (SELECT user_id FROM posts WHERE title LIKE ?)", "%go%").
		Find(&[]crudUser{})
})
SELECT * FROM "crud_users" WHERE id IN (SELECT user_id FROM posts WHERE title LIKE '%go%')

Bound vars flow through the subquery exactly like a top-level predicate — on PostgreSQL the ? becomes $1 on the wire, not an interpolated literal (the tabs above show ToSQL's display form). For hand-built WHERE groups around subqueries — OR between two Expr fragments — register clause.Where directly via Clauses (see Raw clauses); Joins("LEFT JOIN …") accepts raw join fragments with args the same way (chainable_api.go:88).

Aggregates + Scan

A Select entry containing spaces or parentheses renders verbatim (clause/query.go:28), so aggregate calls survive intact. Scan the result into a scalar — the test-suite pattern:

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)
}
SELECT COUNT(*) AS total FROM "crud_users"

Scan accepts scalars, structs, slices, and maps (scan.go:88); Pluck pulls one column into a slice, rendering it quoted like any column (finisher_api.go:318):

var ages []int64
if err := db.Model(&crudUser{}).Order("id").Pluck("age", &ages).Error; err != nil {
	t.Fatalf("Pluck: %v", err)
}
SELECT "age" FROM "crud_users" ORDER BY id

One row, not one row per group

COUNT(*) AS total produces a global aggregate — exactly one row. The chain cannot emit GROUP BY, so one-row-per-group reports are not expressible here. The honest options are on GROUP BY & HAVING: scalar aggregates through the chain, per-group aggregates through the pool.

Window functions — raw Select fragments

Raw passthrough in Select.Build is the rule, not an aggregate special case: any column string containing (, ), or a space is written verbatim (clause/query.go:28). Window functions therefore render:

sql := db.ToSQL(func(tx *DB) *DB {
	return tx.Model(&crudUser{}).
		Select("id", "name", "ROW_NUMBER() OVER (ORDER BY id) AS rn").
		Where("age > ?", 18).
		Find(&[]crudUser{})
})
SELECT "id", "name", ROW_NUMBER() OVER (ORDER BY id) AS rn FROM "crud_users" WHERE age > 18

Two honesty notes:

  • Plain names are quoted ("id"); fragments with parentheses pass through unquoted. Keep each expression comma-free — Select splits arguments and strings on commas (chainable_api.go:120), so a window frame with a comma must stay in its own argument.
  • The struct scanner maps columns against the model's schema and skips unmapped columns (scan.go:179) — rn will not land on a crudUser. To consume computed columns, use Row/Rows for a manual scan (finisher_api.go:332), or model a report struct and query through the pool (GROUP BY & HAVING shows the shape).

Locking — FOR UPDATE

Locking(true) is a chainable that registers clause.Locking (chainable_api.go:256); the builder renders FOR UPDATE (clause/query.go:163, golden at clause_test.go:66):

tx := db.Model(&crudUser{}).Where("id = ?", 1).Locking(true).Find(&user)
SELECT * FROM "crud_users" WHERE id = 1 FOR UPDATE

The clause has no feature gate — it renders verbatim on both dialects — so only enable it against databases that support row-level locking. On PostgreSQL, FOR UPDATE only holds its lock to the end of a transaction, so pair it with Transaction or Begin.

Honest limits

Two gaps, stated plainly:

  • No Group()/Having() chainables. They are named in the design targets but not implemented — no clause.Group builder, no GROUP BY slot. Anything showing a Group/Having chain on a *DB is not this library. See GROUP BY & HAVING for what works.
  • No query-builder subquery objects. Bun's pattern of composing a structured query object into a predicate (Where("id IN ?", <subquery>)) has no equivalent here. Raw clause.Expr fragments are the tool, as shown above.

Next

On this page