Forge

Query builders

Generate SQL without executing it.

GitHub

The CRUD methods are thin wrappers over pure builder functions in the dbswitch package. You can call the builders directly to inspect the generated SQL (great for tests) or to run the statement with your own driver. Every builder takes a Dialect — pass postgres.Dialect{}.

d := postgres.Dialect{}

sql, args := dbswitch.BuildInsert(d, "users", map[string]any{"email": "a@b.com"})
// sql:  INSERT INTO "users" ("email") VALUES ($1)
// args: ["a@b.com"]

Available builders

FunctionReturns
BuildCreateTable(d Dialect, t Table)string
BuildInsert(d Dialect, table string, data map[string]any)(string, []any)
BuildSelect(d Dialect, table string, where map[string]any)(string, []any)
BuildUpdate(d Dialect, table string, set, where map[string]any)(string, []any, error)
BuildDelete(d Dialect, table string, where map[string]any)(string, []any, error)
BuildList(d Dialect, table string, opts ListOptions)(string, []any)
BuildCount(d Dialect, table string, filter map[string]any)(string, []any)

BuildUpdate and BuildDelete return an error if the where map is empty (the same guard the Update/Delete methods enforce). Column and table identifiers are quoted; values are returned as ordered args for parameterized execution.

The Dialect interface

A backend implements Dialect so the builders can target a specific database:

type Dialect interface {
	Placeholder(n int) string          // e.g. "$1" for Postgres
	QuoteIdentifier(name string) string
	ColumnTypeSQL(t ColumnType) string
	DefaultSQL(d DefaultValue) string
}

postgres.Dialect{} is the only implementation.

These builders — and Dialect itself — are a SQL-backend concept. MongoDB and DynamoDB are schemaless and talk to their drivers directly (BSON documents / DynamoDB AttributeValues), so they don't go through this layer at all. See Backends.

On this page