Documentation
¶
Overview ¶
Package dialect translates SQL written in a non-SQLite dialect (MySQL, PostgreSQL, or GoogleSQL) into SQLite SQL so it can run against the SQLite engine that backs filesql. Storage is always SQLite; only the query text a caller supplies is translated.
The translation is best-effort compatibility, not a full emulator. It handles three classes of input:
- Known incompatibilities that have a SQLite equivalent are rewritten (for example MySQL's backtick identifiers become double-quoted identifiers, and PostgreSQL's "expr::type" becomes "CAST(expr AS type)").
- Known constructs with no SQLite equivalent (QUALIFY, arrays, STRUCT types, LATERAL, DISTINCT ON, PostgreSQL's set-returning functions, MySQL's XOR, ...) are rejected with ErrUnsupportedSyntax so the caller sees a clear error instead of a confusing engine message: an array literal reached SQLite as identifier quoting and came back as "no such column: 1,2,3", and generate_series as "no such table", each naming something the query never wrote.
- Anything else is passed through unchanged and left to SQLite to accept or reject.
Function gaps (NOW, DATE_FORMAT, TO_CHAR, SPLIT_PART, SAFE_DIVIDE, DIV, WIDTH_BUCKET, ...) are filled by user-defined functions registered into the SQLite driver via RegisterFunctions rather than by rewriting the SQL. The MySQL-only ones are in mysql_functions.go and mysql_time.go and the PostgreSQL-only ones in postgresql_functions.go, registered under the names each engine gives them: a name that is not a SQLite keyword and that no other dialect means something else by needs no rewrite, and keeping the call text as the query wrote it keeps the result column's name with it. STRCMP is the one whose answer is an approximation rather than a match: it folds case, which MySQL's default collation does, and not accents, which that collation also does.
The TIME functions have a file of their own because a MySQL TIME is not a point on a clock. It is a signed span running from -838:59:59 to 838:59:59, so SEC_TO_TIME answers 100:00:00 for 360000 and TIME_FORMAT prints an hour field of three digits with a sign in front of the whole result, none of which a time.Time holds. What that file cannot carry is MySQL's fractional-seconds precision, which comes from the type of each argument rather than its value: MySQL prints SEC_TO_TIME('3661') as 01:01:01.000000 and this prints 01:01:01, because SQLite has no type to take the six from.
Arithmetic reaches the same helpers by the other route, rewriting the operator into a call, where a dialect disagrees with SQLite about the answer. Division disagrees twice over: MySQL and GoogleSQL divide two integers into a real where SQLite and PostgreSQL answer an integer, and a zero divisor raises in PostgreSQL and GoogleSQL where SQLite and MySQL answer NULL. So "/" is rewritten for all three dialects and the remainder for the two that raise, with GoogleSQL's SAFE_DIVIDE left as the way to ask for the NULL.
Casts go through the same mechanism for a different reason. SQLite's own CAST applies type affinity, which is close enough to look right and different enough to be wrong: it truncates where the dialects round, and it coerces a value the target type cannot represent instead of rejecting it. Each dialect therefore rewrites CAST (and PostgreSQL's "::", and GoogleSQL's SAFE_CAST) into a helper that converts with that dialect's rules and returns ErrInvalidCast for a value it cannot represent.
A name SQLite shares with a dialect needs the same treatment when the two mean different things by it, since the call runs and answers a plausible value. LOG is the natural logarithm in MySQL and GoogleSQL and the base-ten one in SQLite, MySQL's FORMAT groups a number where SQLite's is printf, PostgreSQL's to_hex converts an integer where GoogleSQL's hexes bytes, MySQL's QUOTE escapes with a backslash where SQLite doubles the quote, its ASCII answers a byte where PostgreSQL's answers a code point, and LEFT, RIGHT and REGEXP_REPLACE each read a negative length or a fourth argument their own way. Those calls are rewritten to a helper named for the dialect rather than left to the name SQLite already has. GoogleSQL's FORMAT prints its own %t and %T verbs there; a boolean reaches the helper as the integer SQLite stores, so it prints as 0 or 1.
Collation is part of what a call means. MySQL's default collation folds case, so its LIKE and its REGEXP both match a letter in either case, and both are routed to helpers that do. The operators are left alone: "=", IN, BETWEEN, ORDER BY, DISTINCT and GROUP BY compare inside the engine, where a token rewrite cannot reach every one of them, so under the MySQL dialect they compare the way SQLite does and 'abc' = 'ABC' is false here and true in MySQL.
Bit operations have a ceiling this package cannot lift. MySQL computes them on an unsigned 64-bit value, and SQLite has no unsigned 64-bit integer to answer with. The shifts are rewritten because their bits genuinely differ: SQLite's ">>" copies the sign bit where MySQL brings in zeros, and SQLite reads a negative shift count as a shift the other way. What stays different is only how a result with its top bit set is spelled: MySQL prints ~0 as 18446744073709551615 and this prints -1, the same bits under the only reading SQLite has for them.
Lexing is per dialect, because what counts as a string, an identifier, a comment, or an escape differs between them: a double-quoted literal is a string in MySQL and an identifier in PostgreSQL, block comments nest in PostgreSQL and not elsewhere, and only some dialects decode an escape that names a character by its number. Reading a literal by the wrong dialect's rules is the worst kind of failure this package can have, because the translation succeeds and the query answers from a value the caller never wrote, so each of those rules is configured rather than assumed.
GoogleSQL's own file holds the two kinds of name it needs. Some are BigQuery functions SQLite has nothing like -- CONTAINS_SUBSTR, EDIT_DISTANCE, IEEE_DIVIDE, the base32 pair. The rest are names another dialect here already means something else by: BigQuery's MD5 and SHA1 answer bytes where PostgreSQL's MD5 and MySQL's SHA1 answer hexadecimal text, so TO_HEX(MD5(x)) -- the spelling BigQuery's documentation uses to print a digest -- hexed the hex; and DATE, DATETIME and TIME are constructors where SQLite has functions of those names that read a time value and modifiers, so DATE(2024, 3, 5) found nothing it could read and answered NULL. Its TIME family needs arithmetic of its own for the same reason MySQL's does: a BigQuery TIME is a time of day, so TIME_ADD wraps around midnight rather than moving to another day.
BigQuery's SAFE. prefix is a wrapper rather than a name: SAFE.f(args) becomes safe_call('f', args), which runs f and answers NULL where f could not compute a value from what it was given. It runs after the call pass, so what it wraps is whatever that pass turned the call into. Two kinds of failure are still reported rather than answered with a NULL, because neither is about the data: a name nothing here defines, and an argument count the function does not have. A function SQLite computes itself is out of reach from a user-defined function, so the prefix is dropped there and the call runs as written -- those are the ones that do not raise in the first place.
TO_CHAR has a file of its own for the same kind of reason: its template is a language rather than a set of names, and it cannot be translated into a Go layout string. A Go layout has one spelling per field, so MONTH, Month and month would be one answer where PostgreSQL gives three, it has no fixed-width form for the nine columns PostgreSQL pads a day or a month name to, and a pattern with no Go equivalent has to be copied out as literal text, which is how TO_CHAR(d, 'DDD') answered "05D". postgresql_template.go scans the template into its elements and renders one at a time, for the numeric templates as well as the date ones, and TO_DATE and TO_TIMESTAMP read their templates through the same scanner.
What the translation cannot reach is SQLite's type system. SQLite has five storage classes -- NULL, INTEGER, REAL, TEXT and BLOB -- and so no boolean, no interval, no array and no arbitrary-precision numeric, and a construct whose answer is one of those has nowhere to land. A comparison answers 1 or 0 rather than true or false; an INTERVAL literal is translatable only as the right operand of date arithmetic, and anywhere else it is refused with ErrUnsupportedSyntax rather than passed on to fail as a syntax error naming something else; an array literal and the set-returning functions are refused for the same reason; and the functions whose answer is one of those types -- PostgreSQL's AGE, JUSTIFY_DAYS, REGEXP_MATCH, SCALE and TRIM_SCALE, and BigQuery's ARRAY_AGG, APPROX_QUANTILES and the rest of its array-returning aggregates -- are not implemented, since there would be no value to return. A time zone is the other thing there is no type for, so BigQuery's forms that take one are refused rather than answered unshifted, which would be a different instant.
The clock follows from the same absence. NOW, CURDATE, CURTIME, UNIX_TIMESTAMP, PostgreSQL's now and its two fixed siblings, and BigQuery's CURRENT_DATETIME all read UTC, which is what SQLite's own CURRENT_TIMESTAMP answers and what BigQuery answers when no zone is named; MySQL and PostgreSQL answer a session zone that has no counterpart here. Each of them is fixed at the start of the statement, so every row of one result carries the same reading and so does every place the statement names one of them. PostgreSQL's clock_timestamp and timeofday are the exception and advance while the statement runs, which is what they are for.
One consequence of that has no error to report it: subtracting one timestamp from another is an interval in PostgreSQL and an ordinary subtraction to SQLite, so "ts2 - ts1" answers a number rather than a span, and for two dates in the same year it answers 0. The operands are columns as often as literals and a token rewrite cannot see their types, so there is no shape to match on; DATE_PART and DATE_DIFF are the ways to ask this question here.
Comparison is the other place the engine has the last word. "=", IN, BETWEEN, ORDER BY, DISTINCT and GROUP BY compare inside SQLite, so a string and a number are different values here where PostgreSQL coerces them, and '5' = 5 is false.
The SQLite dialect is the identity translation: Translate returns the input unchanged.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrUnknownDialect indicates a dialect name that does not map to a built-in // dialect. ErrUnknownDialect = errors.New("dialect: unknown SQL dialect") // ErrUnsupportedSyntax indicates a construct that is valid in the source // dialect but has no equivalent on the SQLite backend. ErrUnsupportedSyntax = errors.New("dialect: syntax not supported on SQLite backend") // ErrInvalidSyntax indicates the query could not be tokenized (for example an // unterminated string or identifier). ErrInvalidSyntax = errors.New("dialect: invalid SQL syntax") )
Sentinel errors returned by this package. Use errors.Is to check for them.
var ErrDivideByZero = errors.New("dialect: division by zero")
ErrDivideByZero reports a division by zero in a dialect that raises for it. It stands on its own rather than wrapping ErrInvalidCast, which is about a value a target type cannot represent: a division by zero converts nothing, and an error reading "invalid cast: division by zero" sent the reader looking at CAST expressions their query does not contain.
var ErrInvalidCast = errors.New("dialect: invalid cast")
ErrInvalidCast indicates a value the target type cannot represent, in a dialect that treats that as an error rather than a coerced fallback.
Functions ¶
func RegisterFunctions ¶
func RegisterFunctions() error
RegisterFunctions registers the dialect helper functions (REGEXP, NOW, DATE_FORMAT, DATE_PART, ...) into the modernc.org/sqlite driver so translated queries that call them succeed. Registration is process-global and applies to connections opened afterward, so callers should invoke it during startup, before opening the database that runs dialect queries.
It is idempotent and safe to call multiple times and from multiple goroutines; the functions are registered only once. The functions are always registered as a set regardless of which dialect is in use, so a helper such as SPLIT_PART is available even under the SQLite dialect.
func Translate ¶
Translate converts a query written in dialect d into SQLite SQL. When d is SQLite the input is returned unchanged, and a dialect this package does not implement is refused rather than passed through. Errors wrap ErrUnsupportedSyntax, ErrInvalidSyntax, or ErrUnknownDialect.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/nao1215/filesql/dialect"
_ "modernc.org/sqlite"
)
func main() {
// MySQL quotes an identifier with backticks. SQLite accepts those too, for
// compatibility, and translation normalizes them to its own double-quote
// form so the query that reaches the engine is standard SQL.
sqlite, err := dialect.Translate(dialect.MySQL, "SELECT `name` FROM `users`")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(sqlite)
// A construct SQLite has no equivalent for is refused rather than passed
// through to fail as something else.
_, err = dialect.Translate(dialect.PostgreSQL, "SELECT DISTINCT ON (dept) name FROM staff")
fmt.Println(errors.Is(err, dialect.ErrUnsupportedSyntax))
}
Output: SELECT "name" FROM "users" true
Example (GoogleSQL) ¶
package main
import (
"context"
"database/sql"
"fmt"
"github.com/nao1215/filesql/dialect"
_ "modernc.org/sqlite"
)
func main() {
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
// Three BigQuery constructs SQLite has no form for: a date built out of
// its fields, a digest printed as hexadecimal, and the SAFE. prefix, which
// answers NULL where the call would have raised.
for _, query := range []string{
`SELECT FORMAT_DATE('%Y-%m-%d', DATE(2024, 3, 5))`,
`SELECT TO_HEX(MD5('abc'))`,
`SELECT IFNULL(SAFE.PARSE_DATE('%Y-%m-%d', 'not a date'), 'unparsed')`,
} {
translated, err := dialect.Translate(dialect.GoogleSQL, query)
if err != nil {
fmt.Println(err)
return
}
var answer string
if err := db.QueryRowContext(context.Background(), translated).Scan(&answer); err != nil {
fmt.Println(err)
return
}
fmt.Println(answer)
}
}
Output: 2024-03-05 900150983cd24fb0d6963f7d28e17f72 unparsed
Example (PostgreSQL) ¶
package main
import (
"context"
"database/sql"
"fmt"
"github.com/nao1215/filesql/dialect"
_ "modernc.org/sqlite"
)
func main() {
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
fmt.Println(err)
return
}
defer db.Close()
// Three PostgreSQL constructs SQLite has no form for: a TO_CHAR template,
// GREATEST over a column that has a NULL in it, and a range whose bounds
// are written in either order.
for _, query := range []string{
`SELECT TO_CHAR(DATE '2024-03-05', 'FMDay, DD FMMonth YYYY')`,
`SELECT GREATEST(1, NULL, 2)`,
`SELECT 5 BETWEEN SYMMETRIC 7 AND 3`,
} {
translated, err := dialect.Translate(dialect.PostgreSQL, query)
if err != nil {
fmt.Println(err)
return
}
var answer string
if err := db.QueryRowContext(context.Background(), translated).Scan(&answer); err != nil {
fmt.Println(err)
return
}
fmt.Println(answer)
}
}
Output: Tuesday, 05 March 2024 2 1
Types ¶
type Dialect ¶
type Dialect string
Dialect is a SQL dialect accepted at query time. The storage engine is always SQLite; a Dialect only selects how a caller's query text is interpreted before it reaches SQLite.
const ( // SQLite is the native dialect. Translate returns the input unchanged. SQLite Dialect = "sqlite" // MySQL accepts MySQL query syntax. MySQL Dialect = "mysql" // PostgreSQL accepts PostgreSQL query syntax. PostgreSQL Dialect = "postgresql" // GoogleSQL accepts GoogleSQL (BigQuery / Cloud Spanner) query syntax. GoogleSQL Dialect = "googlesql" )
func Dialects ¶
func Dialects() []Dialect
Dialects returns every built-in dialect in a stable order.
Example ¶
package main
import (
"fmt"
"github.com/nao1215/filesql/dialect"
_ "modernc.org/sqlite"
)
func main() {
fmt.Println(dialect.Dialects())
}
Output: [sqlite mysql postgresql googlesql]
func Parse ¶
Parse maps a user-supplied dialect name to a Dialect. Matching is case-insensitive and ignores surrounding whitespace. Aliases are accepted: "sqlite3" for SQLite; "postgres" and "pg" for PostgreSQL; "bigquery", "spanner", and "zetasql" for GoogleSQL. An unrecognized name returns ErrUnknownDialect.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/nao1215/filesql/dialect"
_ "modernc.org/sqlite"
)
func main() {
// Matching ignores case and surrounding space, and the aliases each
// project is also known by are accepted.
for _, name := range []string{"MySQL", " pg ", "bigquery", "oracle"} {
d, err := dialect.Parse(name)
if err != nil {
fmt.Printf("%q: %v\n", name, errors.Is(err, dialect.ErrUnknownDialect))
continue
}
fmt.Printf("%q: %s\n", name, d)
}
}
Output: "MySQL": mysql " pg ": postgresql "bigquery": googlesql "oracle": true
func (Dialect) DisplayName ¶ added in v0.34.0
DisplayName returns the dialect spelled the way its own project spells it, for a message a person reads. A dialect with no spelling here reads back as its wire value, so a name a caller built by conversion still has something to print; the zero Dialect has neither and returns "". It lives beside Dialects() so a dialect added to one arrives in the other, instead of every caller keeping its own table of names.
Example ¶
package main
import (
"fmt"
"github.com/nao1215/filesql/dialect"
_ "modernc.org/sqlite"
)
func main() {
// The wire value is a lowercase identifier, which is right for a flag and
// wrong in a sentence a person reads.
fmt.Println(dialect.PostgreSQL, "->", dialect.PostgreSQL.DisplayName())
fmt.Println(dialect.GoogleSQL, "->", dialect.GoogleSQL.DisplayName())
}
Output: postgresql -> PostgreSQL googlesql -> GoogleSQL