Skip to Content
fusion-orm
Dialects

Dialects

The Dialector interface, the shared BaseDialect appenders with their injection guards, and how to add a new dialect.

A dialector is fusion-orm's entire point of contact with a database product. It renders identifiers and literals, picks the bind-placeholder style, opens the connection pool, declares which optional SQL capabilities it supports, and — optionally — translates driver errors onto fusion's sentinels. Everything upstream of database/sql is dialect-agnostic; everything dialect-specific lives behind this interface.

Two dialects ship in-tree:

  • SQLite — sqlite.Open(dsn), pure Go via modernc.org/sqlite (registered as driver "sqlite").
  • PostgreSQL — postgres.Open(dsn), via the pgx/v5 stdlib adapter (registered as driver "pgx").

Drivers are supplied by the caller's module: importing the dialect package is what registers the driver, and Initialize simply calls sql.Open(driverName, dsn).

The Dialector interface

type Dialector interface {
	// Name returns the dialect name.
	Name() Name
	// Features returns the capability bitset the dialect supports.
	Features() feature.Feature
	// Initialize opens and returns the underlying connection pool. The
	// caller owns the returned pool.
	Initialize() (*sql.DB, error)
	// IdentQuote returns the identifier quote byte (e.g. '"').
	IdentQuote() byte
	// QuoteTo appends ident, quoted for this dialect. Dotted paths are
	// quoted segment by segment and "*" passes through unquoted.
	QuoteTo(b []byte, ident string) []byte
	// BindVarTo appends the placeholder for the 1-based parameter index
	// ("?" or "$1").
	BindVarTo(b []byte, index int) []byte

	// Value appenders.
	AppendNull(b []byte) []byte
	AppendBool(b []byte, v bool) []byte
	AppendInt64(b []byte, v int64) []byte
	AppendUint64(b []byte, v uint64) []byte
	AppendFloat64(b []byte, v float64) []byte
	AppendString(b []byte, v string) []byte
	AppendBytes(b []byte, v []byte) []byte
	AppendTime(b []byte, v time.Time) []byte
	AppendJSON(b []byte, v []byte) []byte
}

Name() returns one of the two constants:

const (
	// SQLite is the pure-Go SQLite dialect.
	SQLite Name = "sqlite"
	// Postgres is the PostgreSQL dialect.
	Postgres Name = "postgres"
)

The placeholder styles diverge exactly where you would expect — SQLite renders ?, PostgreSQL renders $n:

// BindVarToQuestion appends "?" regardless of index (SQLite style).
func (BaseDialect) BindVarToQuestion(b []byte, _ int) []byte {
	return append(b, '?')
}

// BindVarToDollar appends "$n" (PostgreSQL style).
func (BaseDialect) BindVarToDollar(b []byte, index int) []byte {
	b = append(b, '$')
	return AppendUint64(b, uint64(index))
}

One optional extension exists: ErrorTranslator maps driver-level constraint errors onto the shared sentinels (ErrDuplicatedKey, ErrForeignKeyViolated, ErrCheckConstraintViolated). It is enabled with Config.TranslateError.

// ErrorTranslator is an optional Dialector capability: it maps driver-level
// constraint errors onto the fusion sentinel errors
// (ErrDuplicatedKey / ErrForeignKeyViolated / ErrCheckConstraintViolated).
// Enabled via Config.TranslateError.
type ErrorTranslator interface {
	Translate(err error) error
}

BaseDialect: shared appenders with security guards

BaseDialect implements every appender; concrete dialects embed it and override only what differs (SQLite's X'...' byte literal, the placeholder style). The appenders are where injection is won or lost, so they carry explicit guards. From the interface's own contract:

// The value appenders (AppendString and friends) render literals; they must
// never string-concatenate user data — quoting and escaping only. AppendString
// rejects NUL bytes, and the numeric appenders guard against rendering a
// negative literal directly after '-' (which would form a "--" line comment,
// CVE-2024-44906 class).

Concretely:

  • NUL byte rejection. AppendString fails closed — it embeds dialect.ErrStringNUL into the rendered SQL rather than silently stripping the byte, because a stripped value would differ from the one the caller supplied.
// ErrStringNUL is reported when a string value contains a NUL byte (0x00).
// Silently stripping it would store a value different from the one the
// caller supplied; PostgreSQL rejects NUL in text outright.
var ErrStringNUL = errors.New("fusion: string contains a NUL byte (0x00)")
  • Line-comment injection guard. A negative literal appended right after a trailing - would form -- and comment out the rest of the statement. The guard inserts a space; it mirrors bun's fix for the CVE-2024-44906 class.
// guardLineComment inserts a space when a negative numeric literal would be
// appended immediately after a '-'. Without it, "col-?" formatted with -1
// becomes "col--1", where "--" starts a SQL line comment usable for
// injection. Mirrors bun's fix for CVE-2024-44906.
func guardLineComment(b []byte, negative bool) []byte {
	if negative && len(b) > 0 && b[len(b)-1] == '-' {
		return append(b, ' ')
	}
	return b
}
  • Quote-doubling. String literals double ' per the SQL standard; identifiers (via QuoteTo) double the dialect's quote byte and quote each dotted segment, with * passing through unquoted.
  • AppendJSON keeps the quote-doubling path authoritative even across embedded backslashes, so a crafted "\'" sequence cannot break out of the literal, and strips raw NUL bytes (JSON never contains them unescaped).
  • AppendBytes renders a hex byte literal — PostgreSQL-style '\x...' in the base, overridden to SQLite's X'...'.

You almost never call appenders yourself, but Explain does — it interpolates bound variables into a query string for display, using the dialector's appenders (guards included):

// Explain interpolates vars into query for logging and ToSQL output. It
// understands both "?" and "$n" placeholders, skips quoted string and
// identifier sections, and renders values through the dialector's appenders
// (including the line-comment guard).
func Explain(d Dialector, query string, vars ...any) string {

Never string-concatenate user data

The dialects own quoting and escaping. Build queries from placeholders and bind values — Where("name = ?", name) — and let the appenders render literals. Raw concatenation of user input bypasses every guard above.

Opening a database

// Open returns a Dialector that will open dsn (a file path, ":memory:", or a
// modernc DSN such as "file:test.db?_pragma=busy_timeout(5000)").
// Open returns a Dialector that will open dsn (a URL such as
// "postgres://user:pass@localhost/db" or a keyword/value string).
db, err := fusion.Open(sqlite.Open("app.db"))
// or
db, err := fusion.Open(postgres.Open("postgres://user:pass@localhost/app"))

Open pings the pool unless Config.DisableAutomaticPing is set, and the dialector's Initialize returns the *sql.DB the session will use.

Adding a new dialect

Supporting a new database requires no core changes: implement Dialector (embedding BaseDialect covers every appender — override BindVarTo and any literal syntax that differs), declare your capability set with a bitwise OR of feature flags, and implement Translate if you want error translation. Query builders and the migrator branch on the flags, never on dialect-name strings — see feature flags.

A minimal sketch (interface shape only — not runnable as-is):

type MyDBDialector struct {
	dialect.BaseDialect // inherit all appenders
	dsn                 string
}

func Open(dsn string) dialect.Dialector {
	return &MyDBDialector{
		BaseDialect: dialect.NewBaseDialect('`'), // your quote byte
		dsn:         dsn,
	}
}

func (d *MyDBDialector) Name() dialect.Name { return "mydb" }
func (d *MyDBDialector) Features() feature.Feature {
	return feature.CTE | feature.Savepoint | feature.SelectExists
}
func (d *MyDBDialector) Initialize() (*sql.DB, error) {
	return sql.Open("mydb", d.dsn) // your driver registration
}
func (d *MyDBDialector) BindVarTo(b []byte, index int) []byte {
	return d.BindVarToQuestion(b, index)
}
// QuoteTo and the value appenders come from BaseDialect.

Next

On this page