dialect

package
v0.46.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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.

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.

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.

The SQLite dialect is the identity translation: Translate returns the input unchanged.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrUnknownDialect indicates a dialect name that does not map to a built-in
	// dialect and has no registered translator.
	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.

View Source
var ErrDivideByZero = fmt.Errorf("%w: division by zero", ErrInvalidCast)

ErrDivideByZero reports a division by zero in a dialect that raises for it.

View Source
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 RegisterTranslator

func RegisterTranslator(name Dialect, fn TranslatorFunc)

RegisterTranslator installs a custom translator for name, replacing the built-in translator if one exists. It is the extension point for future parser-based translators. It is safe for concurrent use.

Example
package main

import (
	"errors"
	"fmt"
	"strings"

	"github.com/nao1215/filesql/dialect"
)

func main() {
	const shouty = dialect.Dialect("shouty")

	dialect.RegisterTranslator(shouty, func(query string) (string, error) {
		return strings.ToUpper(query), nil
	})

	sqlite, err := dialect.Translate(shouty, "select * from users")
	fmt.Println(sqlite, err)

	// The registry is global, so a translator installed for a test is removed
	// again. Registering nil is how a name is taken back out.
	dialect.RegisterTranslator(shouty, nil)

	_, err = dialect.Translate(shouty, "select * from users")
	fmt.Println(errors.Is(err, dialect.ErrUnknownDialect))
}
Output:
SELECT * FROM USERS <nil>
true

func Translate

func Translate(d Dialect, query string) (string, error)

Translate converts a query written in dialect d into SQLite SQL. When d is SQLite the input is returned unchanged. A custom translator registered with RegisterTranslator takes precedence over the built-in one. Errors wrap ErrUnsupportedSyntax, ErrInvalidSyntax, or ErrUnknownDialect.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/nao1215/filesql/dialect"
)

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

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"
)

func main() {
	fmt.Println(dialect.Dialects())
}
Output:
[sqlite mysql postgresql googlesql]

func Parse

func Parse(name string) (Dialect, error)

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"
)

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

func (d Dialect) DisplayName() string

DisplayName returns the dialect spelled the way its own project spells it, for a message a person reads. A dialect with no spelling here — one installed by RegisterTranslator — reads back as its wire value, so any dialect with a name has one 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"
)

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

type TranslatorFunc

type TranslatorFunc func(query string) (string, error)

TranslatorFunc converts a single query written in some dialect into SQLite SQL.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL