Documentation
¶
Overview ¶
Package debug renders a built statement with its arguments substituted, for reading.
The need is ordinary: when a query misbehaves you want to see what it says, and "$1 $2 $3" beside a slice of values is not that. The danger is equally ordinary: a function that hands back a SQL string with values already in it is one careless call away from being executed, and then the placeholders that made the statement safe are gone.
So the result is not a string. Rendered is a named string type, which prints exactly like a string and cannot be passed where a string is wanted without an explicit conversion:
db.ExecContext(ctx, debug.Interpolate(d, q)) // cannot use ... as string value in argument to ExecContext
Nobody writes that conversion by accident, which is the whole mechanism. It lives in contrib rather than the core for the same reason: reading a query is a development concern, and a package that only builds statements should not carry the tools for defeating them.
The output is for a human. It is not guaranteed to be valid SQL for any engine, it does not attempt the escaping rules of every type a driver accepts, and it must never be sent to a database.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Rendered ¶
type Rendered string
Rendered is a SQL statement with its arguments substituted, for reading.
It is deliberately not a string. See the package comment.
func Interpolate ¶
Interpolate substitutes q's arguments into its SQL.
The dialect is needed because placeholder syntax is the dialect's decision: asking it for Placeholder(1) and Placeholder(2) is how this works out whether markers are positional, as "?" is, or numbered, as "$1" is, without knowing anything about the engine.
Example ¶
package main
import (
"fmt"
"github.com/ubgo/sqlb/contrib/debug"
"github.com/ubgo/sqlb/dialect/postgres"
"github.com/ubgo/sqlb/expr"
"github.com/ubgo/sqlb/stmt"
)
func main() {
users := expr.Table{Name: "users", Alias: "u"}
id := expr.Col[int64](users, "id")
name := expr.Col[string](users, "name")
q, _ := stmt.NewSelect(postgres.Dialect{}).
Exprs(id, name).
From(users).
Where(expr.Eq(name, "O'Brien"), expr.Greater(id, 10)).
Limit(5).
Build()
// What you have without this package: the shape, and the values beside it.
fmt.Println("SQL :", q.SQL)
fmt.Println("Args:", q.Args)
// What you have with it: the statement as it will behave.
fmt.Println("Read:", debug.Interpolate(postgres.Dialect{}, q))
}
Output: SQL : SELECT "u"."id", "u"."name" FROM "users" AS "u" WHERE ("u"."name" = $1 AND "u"."id" > $2) LIMIT $3 Args: [O'Brien 10 5] Read: SELECT "u"."id", "u"."name" FROM "users" AS "u" WHERE ("u"."name" = 'O''Brien' AND "u"."id" > 10) LIMIT 5