Databases
ant runs on PostgreSQL, MySQL, MariaDB, SQLite and SQL Server. PostgreSQL has everything. The others run queries, writes, relations, change tracking and transactions, but have no migrations yet.
Support
| PostgreSQL | MySQL | MariaDB | SQLite | SQL Server | |
|---|---|---|---|---|---|
| Tested on | 13 to 18 | 8.4 | 11.8 | modernc 1.61 | 2022 |
| Dialect | postgres.Dialect | mysql.Dialect | mysql.MariaDB | sqlite.Dialect | sqlserver.Dialect |
| Driver name | pgx | mysql | mysql | sqlite | sqlserver |
| Queries, relations, tracking, transactions | Yes | Yes | Yes | Yes | Yes |
Migrations, EnsureCreated, SchemaOf | Yes | No | No | No | No |
Whole feature suite (tests/features) | Yes | No | No | No | No |
| Conformance suite | Yes | Yes | Yes | Yes | Yes |
Concurrency suite (tests/concurrency) | Yes | Yes | Yes | Yes | Yes |
| Upsert | Yes | Yes | Yes | Yes | No |
MERGE | From 15 | No | No | No | Yes |
| Row locks | Yes | Yes | ForUpdate only | No | No |
FULL JOIN | Yes | No | No | Yes | Yes |
| Lateral joins | Yes | Yes | No | No | No |
UpdateReturning | Yes | No | No | Yes | Yes |
DeleteReturning | Yes | No | Yes | Yes | Yes |
Today | Yes | Yes | Yes | No | No |
DatePart | Yes | No | No | No | No |
WITH in a subquery, as in Update or Delete after FromCTE or Recursive | Yes | Yes | Yes | Yes | No |
ILike, FILTER, NULLS FIRST | Native | Emulated | Emulated | ILike emulated | Emulated |
Only PostgreSQL runs the whole feature suite, because its tables are written in PostgreSQL's DDL. The smaller conformance suite covers what the dialects write differently, on every database.
Check for a missing feature
ant refuses before sending SQL, with an error that wraps ant.ErrUnsupported.
_, err := db.Users.Where(ant.Eq(&Users.ID, id)).DeleteReturning(ctx)
if errors.Is(err, ant.ErrUnsupported) {
log.Println("not on this database")
}
To check before building the query:
if dialect.Supports(db.Dialect(), dialect.Merge) {
log.Println("MERGE is available")
}
Error helpers such as ant.IsUniqueViolation work on all five databases, because each dialect translates its own error numbers.
Import a driver
Import a driver in your application. The exception is dialect/mysql, which imports go-sql-driver/mysql to read the driver's error numbers.
import _ "github.com/jackc/pgx/v5/stdlib" // PostgreSQL
import _ "github.com/go-sql-driver/mysql" // MySQL and MariaDB
import _ "modernc.org/sqlite" // SQLite
import _ "github.com/microsoft/go-mssqldb" // SQL Server
Set these in the DSN:
| Database | Setting | Without it |
|---|---|---|
| MySQL, MariaDB | parseTime=true | ant.Open refuses the DSN, since times would come back as bytes. A pool given to ant.Wrap is not checked |
| SQLite | _pragma=foreign_keys(1) | Foreign keys aren't enforced |
| SQLite | _pragma=busy_timeout(5000)&_txlock=immediate | A second writer fails at once. See writers at once |
Generated keys
MySQL has no RETURNING, so a key comes from LastInsertId, and other database-filled columns are read back with a second query. Rows with generated keys go in one at a time there, in both SaveChanges and InsertMany.
SQL Server reads a key back with OUTPUT, which it refuses on a table with triggers.
Upsert on MySQL and MariaDB
ON DUPLICATE KEY UPDATE has no target. Any unique key triggers it, not only the columns you name. If a different key is the one that collides, Upsert can't find the row by your columns and reports that it wrote nothing. Name the only unique key that can collide.
It takes no condition either. An Upsert of a copy that carries a version still checks it: each assignment keeps the stored value unless the version matches. A stale copy changes nothing and returns ErrConcurrency. This reads the affected-row count, so leave the driver's clientFoundRows off, as it is by default.
Upsert on SQL Server
There is no ON CONFLICT. Use ant.Merge, which ant writes with WITH (HOLDLOCK) there. Without it, two MERGE statements at once can both find no row and both insert it.
MERGE at once on PostgreSQL
PostgreSQL's documentation says a MERGE that inserts a row another MERGE inserted in the meantime fails with a unique violation, which the application retries. Upsert has no such failure on PostgreSQL.
Writes that read their own table on MySQL
MySQL refuses an UPDATE or DELETE whose subquery reads the table being written (error 1093). ant wraps such a subquery in a derived table, which MySQL reads first.
- A subquery whose columns share a name, or are expressions, needs MySQL 8.0.19 or later, for the derived table's column list.
- A correlated subquery needs 8.0.14.
- An upsert's
Setthat reads its own table is refused even through a derived table, so ant writes the rows asINSERT ... SELECT, which MySQL allows. ASELECThas noDEFAULT, soInsertManywith such aSetand a column left to its default is refused withErrUnsupported.
Retry deadlocks and conflicts
ant.IsRetryable, and so ant.Attempts, accept these failures:
| Database | Retried |
|---|---|
| PostgreSQL | 40001 (serialization failure), 40P01 (deadlock) |
| MySQL, MariaDB | Deadlocks |
| MariaDB | Error 1020. From 11.6 it rolls a transaction back when a row the transaction read changed since its snapshot |
| SQL Server | Deadlocks |
| SQLite | A busy database |
On MySQL, MariaDB and SQL Server a deadlock ends the whole transaction, so ant marks it lost: later statements return ant.ErrTxDone, and Tx rolls it back. See retries.
FirstOrCreate in a transaction reads the row another writer inserted first FOR UPDATE. On MySQL and MariaDB the insert that lost already holds a share lock on that row, so two such transactions can still deadlock there (MariaDB: error 1020). The error is retryable, so run them with ant.Attempts.
Row locks
ForUpdate and ForShare lock the rows a query returns. Count, Exists, the aggregates and the total of Page read no rows to lock, and PostgreSQL refuses a lock on them, so they run without it on every database. With IncludeJoined the lock is on the query's own table, FOR UPDATE OF, since PostgreSQL refuses to lock the nullable side of a left join. MariaDB has no OF, and locks the related rows as well.
Nested read-only transactions
A Tx inside another is a savepoint. On PostgreSQL ant.ReadOnly() holds there until the savepoint ends. MySQL, MariaDB, SQLite and SQL Server can't make a transaction read-only once it has begun, so it returns ant.ErrUnsupported. ant.Isolation on a nested Tx is ant.ErrNestedIsolation everywhere.
Averages on SQL Server
AVG there returns its argument's type, so the average of an integer column would lose its fraction. ant writes AVG(CAST(x AS FLOAT)), and Avg, AvgOf and AvgRelated give the same number on every database.
SQLite: writers at once
SQLite has one writer at a time. A second connection that writes fails at once with "database is locked" unless the DSN makes it wait. A transaction that reads and then writes can fail even then, unless it takes the write lock when it begins.
dsn := "file:app.db?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)&_txlock=immediate"
Without foreign_keys(1), SQLite accepts a row whose foreign key points at nothing. Without busy_timeout and _txlock=immediate, concurrent requests fail with database is locked.
An in-memory database, :memory:, is one per connection, so a table made on one connection is missing on the others in the pool. Keep the pool to one connection:
db, err := ant.Open[AppDB](ctx, sqlite.Dialect, ":memory:?_pragma=foreign_keys(1)")
if err != nil {
return err
}
db.DB().SetMaxOpenConns(1)
PRAGMA journal_mode=WAL lets readers go on while one connection writes. It stays with the file, so run it once at startup. Don't put it in the DSN, where every new connection would need the write lock to set it.
Paging on SQL Server
OFFSET ... FETCH needs an ORDER BY, so ant adds a meaningless one if the query has none. SQL Server refuses a Limit of zero.
Recursive queries on SQL Server
A recursive WITH there has no RECURSIVE keyword and joins its parts only with UNION ALL. That keeps a row each time it is reached and never ends a cycle. So ant makes each row carry the path of keys that reached it, doesn't follow a row already on its path, and returns one row per key, as UNION does elsewhere.
The path also lets ant lift SQL Server's limit of 100 levels with OPTION (MAXRECURSION 0). Count and Exists put the WITH at the start of their statement, the only place SQL Server takes one.
Long In lists
A list of more values than one statement can take as parameters is sent on PostgreSQL as one array, = ANY($1), when its values are plain and of one type. Elsewhere, and for a list of secrets or of mixed types, the driver refuses it. Use InSub or split the list.
| Database | Parameters in one statement |
|---|---|
| PostgreSQL, MySQL, MariaDB | 65,535 |
| SQLite | 32,766 |
| SQL Server | About 2,100. ant stays at 2,000 |
InsertMany, SaveChanges and Include split their work to fit. Your own In with a long list doesn't.
Values the drivers can't take
ant doesn't work around these limits of database/sql and drivers.
- An
sql.Null[uint64]abovemath.MaxInt64is refused bydatabase/sql, though a bareuint64field is not. NULLcan't be read into a named[]bytetype such asjson.RawMessageornet.IP. Use a pointer to it for a column that allowsNULL.- pgx hands an
INTERVALtodatabase/sqlas text, which doesn't convert to atime.Duration. Read it intopgtype.Interval, or store a number of microseconds. ant.JSONandsecure.Valuerefuse text that isn't valid UTF-8, as a text column does.encoding/jsonwould otherwise store U+FFFD in its place.
Times
SQLite stores times as text, and SQL Server's DATETIME2 has no zone, so ant binds UTC on both to keep one clock. MySQL's driver does the same.
The conversion applies to:
time.Time,*time.Time,sql.NullTime, ansql.Nullof a time, and a pointer to one- an interface that holds one
- types built on them, such as
ant.DeletedAt - arguments of raw queries, each element of an
INlist included
A driver.Valuer of your own is passed as it is, so have it return a time in UTC.
A time read back is held in UTC on every database, in each of those shapes, though pgx decodes TIMESTAMPTZ in the process's zone, so a time compares equal before and after a round trip and renders the same in JSON.
ant.Past and ant.Future compare with the server's own clock, so run the server in UTC. On SQLite and MySQL, CURRENT_TIMESTAMP has whole seconds.
Types
postgres.Array, postgres.JSONSet, postgres.Vector and the rest of dialect/postgres need PostgreSQL. A postgres.Array holds plain values, so reading an array with a NULL element is an error, not the text NULL, false or zero. Collate quotes its name, which SQL Server doesn't accept.
Rollbacks on SQL Server
go-mssqldb v1.11.2 rolls a transaction back with the context it began with. If that context has ended, it leaves a goroutine reading the connection after the connection went back to the pool, where the next statement races it.
ant avoids this for its own transactions (Tx, Begin, SaveChanges, DryRun). It begins them on a context that doesn't end, on a connection taken with yours, and rolls them back itself when yours ends. A transaction you begin yourself and pass to UseTx can meet the problem. On SQL Server, end it before its context does.
Add a dialect
A dialect implements dialect.Dialect. Its Render calls dialect.Render, and its Syntax method lists what differs from PostgreSQL. dialect.RegisterErrors connects its error codes. Migrations are a separate interface, schema.Dialect. See dialect/sqlite/sqlite.go, which is about 70 lines.