Documentation
¶
Overview ¶
Package dialect defines the interface each database implements, plus helpers they share.
Index ¶
- func AppendNumbered(dst []byte, prefix string, n int) []byte
- func AppendQuoteWith(dst []byte, ident, open, close string) []byte
- func Arg(d Dialect, v any) any
- func Bind(d Dialect, query string, args []any) (string, []any, error)
- func Numbered(prefix string, n int) string
- func QuoteWith(ident, open, close string) string
- func RegisterErrors(state func(error) string)
- func Render(d Dialect, stmt qb.Statement) (string, []any, error)
- func StateOf(err error) string
- func Supports(d Dialect, f Feature) bool
- type Appender
- type BeginLocker
- type ChangedRowsOnly
- type DSNChecker
- type Dialect
- type Feature
- type Syntactic
- type Syntax
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AppendNumbered ¶ added in v0.3.1
AppendNumbered appends what Numbered returns to dst.
func AppendQuoteWith ¶ added in v0.3.1
AppendQuoteWith appends what QuoteWith returns to dst.
func Arg ¶ added in v0.3.1
Arg returns v as Render binds it for d: by pointer if only its pointer converts itself, and in UTC where d's database drops a time's zone. It lets a caller that keeps a statement's text bind new values to it, as ant's cache of statement shapes does.
func Bind ¶
Bind prepares raw SQL for d. Three forms of argument are accepted:
- The dialect's own placeholders, such as $1, pass through unchanged.
- sql.Named arguments are written @name.
- Otherwise ? works as a placeholder, but only when the query uses no numbered placeholders and has exactly one ? per argument. PostgreSQL also has a ? operator on jsonb, and those queries fail one of these tests.
With @name or ?, a slice directly inside IN (...) expands to one placeholder per element, and an empty slice becomes NULL. Anywhere else a slice is one value, so = ANY(@ids) passes an array. Text in strings, quoted identifiers, comments, and dollar quotes is left alone, as are operators like @>.
On a database whose columns keep no zone, times among the bound values are put in UTC, after lists are expanded, so each element is.
func RegisterErrors ¶
RegisterErrors adds a function that turns a driver's error into a SQLSTATE code, or "", for a database whose driver does not report one. A dialect calls it when imported, which is what lets ant.IsUniqueViolation work everywhere.
func Render ¶
Render converts a statement to SQL using d's placeholders and quoting. Dialects call it from their Render method, and describe what differs with Syntax.
Types ¶
type Appender ¶ added in v0.3.1
type Appender interface {
// AppendQuote appends the quoted identifier to dst.
AppendQuote(dst []byte, ident string) []byte
// AppendPlaceholder appends the bind parameter for position n to dst.
AppendPlaceholder(dst []byte, n int) []byte
}
Appender is implemented by a dialect that can write a quoted identifier and a placeholder straight into the statement being rendered. It is optional: Render uses it when it is there, which saves an allocation for every identifier and placeholder of every statement, and Quote and Placeholder when it is not. The two must write what Quote and Placeholder return.
type BeginLocker ¶ added in v0.6.0
type BeginLocker interface {
// BeginLocks reports whether a writable transaction on a pool opened with
// dsn holds the write lock from its start.
BeginLocks(dsn string) bool
}
BeginLocker is implemented by a dialect whose writable transactions can hold the database's write lock from their start, as SQLite's do with _txlock=immediate or exclusive. A row lock in one adds nothing then, so ant leaves it out there, on a database that has none, rather than refuse it.
type ChangedRowsOnly ¶ added in v0.5.0
type ChangedRowsOnly interface {
// CountsChangedRows reports whether affected counts changed rows only.
CountsChangedRows() bool
}
ChangedRowsOnly is implemented by a dialect whose driver counts only the rows an UPDATE altered, not the rows it matched. Saving a value a row already holds then reports zero, which reads as the row having gone, so ant checks the row is still there before it calls that a conflict. Implementing this says nothing about INSERT: a conflict that changed nothing still reports zero, and ant keeps reading that as "the conflict did nothing".
type DSNChecker ¶ added in v0.3.2
type DSNChecker interface {
// CheckDSN reports what the data source name is missing, or nil.
CheckDSN(dsn string) error
}
DSNChecker is implemented by a dialect whose driver needs an option in the data source name for its rows to scan into the types ant maps columns to. Open calls it before connecting, so a DSN that would fail on the first read is refused where it is written rather than at the first query that scans a column the option governs.
type Dialect ¶
type Dialect interface {
// Name identifies the dialect, such as "postgres".
Name() string
// DriverName is the database/sql driver to open. The application imports
// the driver, so ant has no dependency on it.
DriverName() string
// Placeholder returns the bind parameter for position n, counted from 1.
Placeholder(n int) string
// Quote quotes an identifier.
Quote(ident string) string
// SupportsReturning reports whether an INSERT can hand back columns, through
// RETURNING or an equivalent. Without it, keys come from LastInsertId.
SupportsReturning() bool
// Render converts a statement to SQL and its arguments.
Render(stmt qb.Statement) (sql string, args []any, err error)
}
Dialect adapts ant to one database.
type Feature ¶
type Feature string
Feature names something that not every database has.
const ( FullJoin Feature = "FULL JOIN" LateralJoin Feature = "lateral joins" Merge Feature = "MERGE" RowLocks Feature = "row locks" OnConflict Feature = "ON CONFLICT" ConflictWhere Feature = "a condition on an upsert" ReturningInsert Feature = "returning rows from INSERT" ReturningUpdate Feature = "returning rows from UPDATE" ReturningDelete Feature = "returning rows from DELETE" DefaultKeyword Feature = "DEFAULT in a VALUES list" DateCast Feature = "CAST to date with CURRENT_DATE" DatePart Feature = "DATE_PART" SubqueryWith Feature = "WITH inside a subquery" // ReadOnlyInTx is making a transaction read-only once it has begun, as a // Tx nested in another does. ReadOnlyInTx Feature = "READ ONLY inside a transaction" // ExplainPlan is a statement that returns a query's plan as rows, which SQL // Server has only as a session setting. ExplainPlan Feature = "EXPLAIN" // DistinctNullsOrder is NULLS FIRST or NULLS LAST that moves NULLs in a // SELECT DISTINCT, which emulating it puts outside the select list. DistinctNullsOrder Feature = "NULLS FIRST or NULLS LAST against the default order in a SELECT DISTINCT" )
The features a dialect can lack. Render reports one with ant.ErrUnsupported, rather than leaving the database to refuse the SQL.
type Syntactic ¶
type Syntactic interface {
Syntax() *Syntax
}
Syntactic is implemented by a dialect whose SQL differs from PostgreSQL's.
type Syntax ¶
type Syntax struct {
// Missing lists the features the database lacks.
Missing []Feature
// OffsetFetch writes OFFSET n ROWS FETCH NEXT m ROWS ONLY for paging, which
// needs an ORDER BY, so one is added if the query has none.
OffsetFetch bool
// Unlimited is the LIMIT to write when a query has only an OFFSET, for a
// database that cannot have one without the other.
Unlimited string
// Output writes OUTPUT INSERTED.x in place of RETURNING x.
Output bool
// DuplicateKey writes ON DUPLICATE KEY UPDATE in place of ON CONFLICT.
DuplicateKey bool
// EmptyValues writes VALUES () in place of DEFAULT VALUES.
EmptyValues bool
// NoILike turns ILIKE into a LIKE between lowered values.
NoILike bool
// NoFilter turns an aggregate's FILTER into a CASE inside it.
NoFilter bool
// FloatAvg casts the argument of AVG to a float, for a database whose AVG of
// an integer column is an integer, with the fraction cut off.
FloatAvg bool
// NoNullsOrder turns NULLS FIRST and NULLS LAST into a CASE before the value,
// for a database that sorts NULL below every value, as MySQL, MariaDB and SQL
// Server do. Only an order that moves NULLs from there gets the CASE.
NoNullsOrder bool
// NoNestedOrder leaves the ORDER BY off a subquery, derived table or CTE with
// no paging, for a database that refuses one there. It cannot change which
// rows the nested query yields.
NoNestedOrder bool
// NoBooleans turns EXISTS used as a value into a CASE.
NoBooleans bool
// NoRowIn spells out multi-column IN as ORs.
NoRowIn bool
// BareSets leaves the parentheses off UNION members.
BareSets bool
// ValuesUnion writes a VALUES source as SELECTs joined by UNION ALL, for a
// database that cannot name its columns.
ValuesUnion bool
// WrapLimitedIn puts a derived table around a subquery with a LIMIT or an
// OFFSET inside IN, for a database that refuses it directly.
WrapLimitedIn bool
// WrapSelfReads puts a derived table around a subquery of an UPDATE or DELETE
// that reads the table being written, for a database that refuses such a read
// but reads a derived table, which it materializes first.
WrapSelfReads bool
// HintInSelect moves an optimizer hint to just after SELECT.
HintInSelect bool
// MergeSemicolon ends MERGE with the semicolon the database demands.
MergeSemicolon bool
// MergeHoldLock locks the key ranges a MERGE reads until it ends, for a
// database whose MERGE otherwise lets two at once both find no row and
// both insert it.
MergeHoldLock bool
// NoLockOf leaves the OF table off a row lock, for a database that has no
// such clause. It then locks the rows of every table the statement reads.
NoLockOf bool
// TransactSavepoints uses SAVE TRANSACTION, which has no release.
TransactSavepoints bool
// RetryEndsTx says a deadlock or serialization failure rolls back the whole
// transaction, not only the statement, so a savepoint cannot recover from it.
RetryEndsTx bool
// RecursiveUnionAll writes a recursive WITH without RECURSIVE and joins its
// members with UNION ALL, for a database that demands both. A CTE with a Key
// then carries the path of keys that reached each row, which stops a cycle,
// is read once per key, as UNION would leave it, and lifts the database's
// limit on how deep the recursion goes.
RecursiveUnionAll bool
// RunsWhileStreaming says a connection can run a statement while it streams
// the rows of another, as an Each loop does. Otherwise, on a transaction or
// a context from UseConn, ant refuses a statement inside the loop with
// ant.ErrQueryInEach, rather than leave the driver to fail or to wait for
// rows nobody reads.
RunsWhileStreaming bool
// UTCTimes binds times in UTC, for a database whose columns drop the zone, so
// that every stored time is on one clock.
UTCTimes bool
// PlainValues says the driver writes and reads only what database/sql
// converts, where pgx converts slices, maps and structs itself. Open then
// refuses a field of a type database/sql can't pass or fill, naming it,
// rather than leave the first write to fail with the driver's message.
PlainValues bool
// Explain is the command put before a query to read its plan, such as
// EXPLAIN QUERY PLAN. The plan's text is in the last column of each row it
// returns. Empty is EXPLAIN.
Explain string
// Functions renames functions, such as LENGTH to LEN.
Functions map[string]string
// MaxParameters is the most bound values in one statement. The default is
// PostgreSQL's 65535.
MaxParameters int
// NoArrayParams leaves an IN list that would pass MaxParameters as it is,
// for a database that takes no array as a parameter. Otherwise such a list
// of plain values of one type is bound as one array, = ANY(?).
NoArrayParams bool
}
Syntax says where a dialect's SQL differs from what Render writes, which is PostgreSQL's. The zero value changes nothing, so a dialect states only its differences.
func (*Syntax) ExplainCommand ¶ added in v0.6.0
ExplainCommand returns the command put before a query to read its plan.
func (*Syntax) ParameterLimit ¶
ParameterLimit returns the most bound values in one statement.
func (*Syntax) SavepointCommands ¶
SavepointCommands returns the commands that take a savepoint's name. An empty release means the database has no such command, and nothing needs running.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package mysql holds the MySQL and MariaDB dialects.
|
Package mysql holds the MySQL and MariaDB dialects. |
|
Package postgres is the PostgreSQL dialect.
|
Package postgres is the PostgreSQL dialect. |
|
pgxext
Package pgxext holds PostgreSQL features that database/sql cannot reach and that need pgx itself, so that ant and dialect/postgres stay free of any driver.
|
Package pgxext holds PostgreSQL features that database/sql cannot reach and that need pgx itself, so that ant and dialect/postgres stay free of any driver. |
|
Package sqlite is the SQLite dialect.
|
Package sqlite is the SQLite dialect. |
|
Package sqlserver is the SQL Server dialect.
|
Package sqlserver is the SQL Server dialect. |