Skip to Content
fusion-orm
Querying

Raw clauses

Clauses and the clause package — expressions, conditions, upserts, joins, CTEs, and RETURNING.

When to drop a level

The chainable API covers common cases. For everything else — upserts, hand-built WHERE groups, CTEs, RETURNING — register clause builders directly:

// Clauses registers custom clause builders, replacing same-named clauses.
func (db *DB) Clauses(conds ...clause.Interface) *DB {
	tx := db.getInstance()
	for _, c := range conds {
		if c != nil {
			tx.Statement.AddClause(c)
		}
	}
	return tx
}

A clause is anything with a name and a byte-builder:

// Interface is a named, orderable SQL clause.
type Interface interface {
	Name() string
	Build(Builder)
}

AddClause replaces any clause with the same name — the statement registry keeps one instance per slot, which is also why Order re-reads and re-appends the previous clause instead of stacking duplicates. Builders render in a fixed canonical order:

"with", "select", "insert", "update", "delete", "from", "join", "set", "values",

(through where, order, limit, and the rest — see Statement for the full order). Builders never perform I/O and never import the schema layer; they only append bytes through a Builder bound to the dialect.

Expressions and conditions

// Expression is a SQL fragment with positional ? placeholders and vars.
type Expression struct {
	SQL  string
	Vars []any
}

// Expr creates an expression. Each ? in sql consumes the next var.
func Expr(sql string, vars ...any) Expression

Expression.Build replaces each ? with the dialect placeholder — ? on SQLite, $1, $2, … on PostgreSQL. A ? beyond the available vars renders nothing.

Conditions group expressions under a join word, and can nest:

// Condition is one joined group of a WHERE clause.
type Condition struct {
	Join string // "AND" (default) or "OR"
	// Conds renders a parenthesized nested group — used to keep OR groups
	// intact when another predicate is appended after them. When set, Exprs
	// is ignored.
	Conds []Condition
	Exprs []Expression
}

clause.Or and clause.And are shorthands for a condition with multiple expressions:

// Or marks the next WHERE group as OR-joined.
func Or(exprs ...Expression) Condition { return Condition{Join: "OR", Exprs: exprs} }

// And marks the next WHERE group as AND-joined.
func And(exprs ...Expression) Condition { return Condition{Join: "AND", Exprs: exprs} }

A hand-built WHERE with an OR group:

sql := db.ToSQL(func(tx *DB) *DB {
	return tx.Table("audit_plain_users").
		Clauses(clause.Where{Conds: []clause.Condition{
			clause.Or(clause.Expr("name = ?", "a"), clause.Expr("name = ?", "b")),
		}}).
		Find(&[]auditPlainUser{})
})
WHERE name = 'a' OR name = 'b'

As the only condition it renders unparenthesized. The moment another condition joins the list, a multi-expression condition is parenthesized — appending an AND predicate to a OR b yields (a OR b) AND x, never a OR b AND x (see Conditions → precedence).

OnConflict — upserts

// OnConflict renders ON CONFLICT (cols) DO NOTHING / DO UPDATE SET ...
type OnConflict struct {
	Columns       []string
	DoNothing     bool
	UpdateColumns []string
	// UpdateAll expands to every non-primary-key column of the model;
	// Statement.BuildClauses fills UpdateColumns and falls back to the
	// primary key as the conflict target.
	UpdateAll bool
}

Golden rendering:

{
	"on conflict update", OnConflict{Columns: []string{"email"}, UpdateColumns: []string{"name"}},
	`ON CONFLICT ("email") DO UPDATE SET "name" = EXCLUDED."name"`,
	`ON CONFLICT ("email") DO UPDATE SET "name" = EXCLUDED."name"`, nil,
},
ON CONFLICT ("email") DO UPDATE SET "name" = EXCLUDED."name"

DoNothing: true renders DO NOTHING instead. Two safety rules are tested at runtime against a real engine (TestOnConflictRuntimeUpsert in audit_fixes_test.go): the clause only renders on dialects with the InsertOnConflict feature, and an upsert with update columns but no conflict target never emits the invalid ON CONFLICT () — the empty target is omitted.

Joins

// Join renders a JOIN clause. Relation joins set Table/Alias/On; raw joins
// set Raw, in which case the expression is rendered verbatim (with bound
// variables from Expr).
type Join struct {
	Type   string
	Table  string
	Alias  string
	On     []Expression
	Raw    Expression
	HasRaw bool
}

A relation-style join with alias and ON conditions:

{
	"join relation", Join{
		Type: "LEFT", Table: "profiles", Alias: "profile",
		On: []Expression{Expr(`"users"."id" = "profile"."user_id"`)},
	},
	`LEFT JOIN "profiles" "profile" ON "users"."id" = "profile"."user_id"`,
	`LEFT JOIN "profiles" "profile" ON "users"."id" = "profile"."user_id"`, nil,
},
LEFT JOIN "profiles" "profile" ON "users"."id" = "profile"."user_id"

An empty Type defaults to INNER; multiple On expressions AND together. Raw joins (HasRaw: true) render the expression verbatim — that is what the chainable Joins("LEFT JOIN …") produces under the hood.

With — CTEs

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

The subquery is a raw string rendered as-is:

WITH "active" AS (SELECT 1) 

Returning

// Returning renders RETURNING columns on dialects with the feature.
type Returning struct {
	Columns []string
}
RETURNING "id"

The clause is a no-op on dialects without the Returning feature flag, so attaching it unconditionally is safe.

Locking

clause.Locking{Enabled: true} renders FOR UPDATE — the same clause the Locking chainable registers.

Next

On this page