# Databases

> What each of the five supported databases can do, and where they differ.

Source: https://skudra.net/reference/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 | [Held by the transaction](#row-locks) with `_txlock=immediate` | No |
| `FULL JOIN` | Yes | No | No | Yes | Yes |
| [`Explain`](https://skudra.net/tooling/inspecting-queries.md#explain) | `EXPLAIN` | `EXPLAIN FORMAT=TREE`, from 8.0.16 | `EXPLAIN FORMAT=JSON`, from 10.1.2 | `EXPLAIN QUERY PLAN` | No |
| 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`.

```go
_, 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:

```go
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.

```go
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)` | `ant.Open` refuses the DSN, since foreign keys wouldn't be enforced. `_pragma=foreign_keys(0)` keeps them off on purpose |
| SQLite | `_pragma=busy_timeout(5000)` | `ant.Open` refuses the DSN, since a second writer would fail at once. The driver's `_busy_timeout=5000` and `_timeout=5000` count too. `busy_timeout(0)` keeps the driver's no-wait default on purpose |
| SQLite | `_txlock=immediate` | `ant.Open` refuses the DSN, since a transaction that reads and then writes could fail with `database is locked`. `_txlock=deferred` keeps the driver's default on purpose, and `_txlock=exclusive` also works. See [writers at once](#sqlite-writers-at-once) |

An empty value, such as `_txlock=`, makes no choice, and is refused as if it were missing. A pool given to `ant.Wrap` is not checked.

## 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`. That query finds the row by its key, so a model with no key keeps the zero values it was given in its database-filled columns there, and a key the database fills other than through `AUTO_INCREMENT`, such as a `Default` on the key, is refused with `ant.ErrUnsupported`.

After an update, the columns a model marks `readonly`, generated ones and those a trigger keeps, are read back by key in the same transaction on every database. A `SELECT` is used rather than `RETURNING`, since SQLite's `RETURNING` leaves out what triggers change and SQL Server refuses `OUTPUT` on a table with a trigger.

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.

`InsertFrom` with `WithConflict` reads its rows from a derived table there, with its columns renamed. Otherwise the update would take a column of the `SELECT` that has the table's column name for the table's own.

## Upsert on SQL Server

There is no `ON CONFLICT`, so `Upsert`, and `InsertMany` and `InsertFrom` with `WithConflict`, return `ErrUnsupported`. 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 `Set` that reads its own table is refused even through a derived table, so ant writes the rows as `INSERT ... SELECT`, which MySQL allows. A `SELECT` has no `DEFAULT`, so `InsertMany` with such a `Set` and a column left to its default is refused with `ErrUnsupported`.

## 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](https://skudra.net/transactions/retries.md).

`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.

SQLite has no row locks. A writable transaction on a database opened with `_txlock=immediate` or `_txlock=exclusive` begins with `BEGIN IMMEDIATE` or `BEGIN EXCLUSIVE`, which takes the database's write lock at once, so no other connection can change the rows until it ends. In such a transaction ant accepts `ForUpdate` and `ForShare` and leaves them out of the SQL, so the [transfer that locks both accounts](https://skudra.net/transactions.md#lock-rows-and-move-money) runs on SQLite as it does on PostgreSQL:

```sql
SELECT ... FROM "accounts" WHERE "accounts"."id" = ? LIMIT ?
```

Elsewhere on SQLite the lock returns `ErrUnsupported`, since nothing would hold the rows: outside a transaction, in an `ant.ReadOnly()` one, which the driver begins with a plain `BEGIN`, with `_txlock=deferred`, on a pool given to `ant.Wrap`, whose DSN ant never sees, and in a transaction given to `UseTx`. `ToSQL` takes no context, so it shows the query as written outside a transaction, and refuses the lock. `ToSQLContext`, `Debug` and `Explain` show what runs in the context's transaction.

## 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.

```go
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`. `ant.Open` refuses a DSN that leaves out any of the three, and its error names what is missing:

```text
ant: sqlite: the data source name needs _pragma=busy_timeout(5000) and _txlock=immediate; without them concurrent writes can fail with SQLITE_BUSY. Use _pragma=busy_timeout(0) or _txlock=deferred to keep a default on purpose
```

A DSN that opened on v0.5.0 with only `foreign_keys(1)` is refused from v0.5.1. A test database that only one goroutine writes can keep the driver's defaults by naming them: `_pragma=busy_timeout(0)&_txlock=deferred`.

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:

```go
db, err := ant.Open[AppDB](ctx, sqlite.Dialect, ":memory:?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)&_txlock=immediate")
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. After `Distinct` it adds `ORDER BY 1`, the first selected column, since SQL Server takes only items of the select list there. SQL Server refuses a `Limit` of zero.

## Ordering on SQL Server

SQL Server refuses an `ORDER BY` in a subquery, a derived table or a `WITH` unless it also pages (error 1033). There the order can't change which rows the nested query gives, so ant leaves it out of `Exists`, `InSub`, `SubOf`, `From`, `FromCTE`, `JoinSub` and every other nested query, and keeps it when the nested query has a `Limit` or an `Offset`, where it picks the rows. A query built once with an `OrderBy` can so be nested on every database.

`NULLS FIRST` and `NULLS LAST` are written as a `CASE` before the value on MySQL, MariaDB and SQL Server, and only for the two orders that move NULLs from where these databases put them, below every value: `Asc().NullsLast()` and `Desc().NullsFirst()`. Under `Distinct` that `CASE` is outside the select list, which SQL Server refuses, so those two orders return `ErrUnsupported` there before anything is sent.

## 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`](https://skudra.net/queries/subqueries-and-sets.md) 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.

- The MySQL, SQLite and SQL Server drivers take only what `database/sql` converts. On those four, `ant.Open` refuses a slice, map, array or plain struct field with no `driver.Valuer` and `sql.Scanner`, and names it. Store one with [`ant.JSON[T]`](https://skudra.net/models/custom-types.md#json), which works on every database. pgx converts them on PostgreSQL: a `[]string` is a `text[]`, a map or a struct `jsonb`.
- SQLite has no decimal type. A `decimal.Decimal` with a fraction is stored as a `REAL`, so `SumOf` and `Sum` add floats there: 1.10 + 2.20 reads back as 3.3000000000000003. The other four add decimals exactly. On SQLite, keep money in integer cents.
- An `sql.Null[uint64]` above `math.MaxInt64` is refused by `database/sql`, though a bare `uint64` field is not.
- pgx writes a pointer to a nil `json.RawMessage` as the JSON `null`, not as `NULL`.
- pgx writes a 16-byte `net.IP` that holds an IPv4 address, which is what `net.ParseIP` returns, to an `inet` as `::ffff:10.0.0.1`, which `<<` against an IPv4 network doesn't match. Call `To4` on it, or use `netip.Addr`.
- `ant.JSON` and `secure.Value` refuse text that isn't valid UTF-8, as a text column does. `encoding/json` would otherwise store U+FFFD in its place.

## Values ant converts

`database/sql` can't fill some types from what the drivers give, so ant reads them itself, wherever it scans a row:

- A `time.Duration`, `*time.Duration` or `sql.Null[time.Duration]` reads an integer as nanoseconds, and PostgreSQL's text for an `interval` in each `IntervalStyle`. A year counts 365.25 days, a month left over 30 and a day 24 hours, as `EXTRACT(EPOCH FROM ...)` counts them. An infinite interval, or one past about 292 years, is an error.
- A `net.IP`, `*net.IP` or `sql.Null[net.IP]` reads bytes as they are, and the text of an `inet` as an address. One with a netmask, such as `10.0.0.1/24`, is an error: read it into a `netip.Prefix`.
- A named byte slice, such as `json.RawMessage`, reads `NULL` as nil, as a `[]byte` does.
- A `float64`, `*float64` or `sql.Null[float64]` reads an interval as its nanoseconds, so `Avg`, `AvgOf` and `AvgRelated` of a `time.Duration` give nanoseconds from an `interval` column as from an integer one.
- A map with string keys reads JSON with `json.Number` for the numbers in its interfaces, as `ant.JSON` does.

On PostgreSQL these types also get PostgreSQL's own column: see [models to tables](https://skudra.net/migrations/models-to-tables.md#column-types).

## 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`, an `sql.Null` of 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 `IN` list 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.

An aggregate of a time column on SQLite, such as `MaxOf`, `MinOf`, `Max`, `Min`, `MaxRelated` or `MinRelated`, comes back from the driver as text, since the result has no declared column type. ant reads that text into a `time.Time`, `*time.Time`, `sql.NullTime`, `sql.Null[time.Time]` or `ant.DeletedAt`, in UTC, as it does a time column.

## Text comparison

Each database compares text by the column's collation, and the defaults differ, so the same `Eq`, `Like` and unique index match different rows. Measured on each server's default, with `José` and `ant` stored:

| | `Eq(&Name, "jose")` finds `José` | `Eq(&Name, "ANT")` finds `ant` | `Like(&Name, "JOS%")` finds `José` | A unique `ant@x.io` refuses `ANT@x.io` |
|---|---|---|---|---|
| PostgreSQL | No | No | No | No |
| MySQL, `utf8mb4_0900_ai_ci` | Yes | Yes | Yes | Yes |
| MariaDB, `utf8mb4_uca1400_ai_ci` | Yes | Yes | Yes | Yes |
| SQLite, `BINARY` | No | No | Yes, ASCII letters only | No |
| SQL Server, `SQL_Latin1_General_CP1_CI_AS` | No | Yes | Yes | Yes |

`ILike` ignores case on every database: natively on PostgreSQL, and as `LOWER(column) LIKE LOWER(pattern)` on the others. SQLite's `LOWER` folds ASCII letters only, so there `ILike(&Name, "JOSÉ")` doesn't find `José`. Accents count on PostgreSQL, SQLite and SQL Server, and not under the MySQL and MariaDB defaults.

For the same rows everywhere, give the column the collation you mean in its DDL, or store a normalized copy, such as an email in lower case, and compare that. `Collate` sets one for a single comparison, by a name each database spells its own way.

## 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.

A `uuid.UUID` is sent as its text, so outside PostgreSQL its column must take text, such as `char(36)`. On SQL Server a `uniqueidentifier` reads back in another byte order, so the key read from a row isn't the one written: see [UUID columns outside PostgreSQL](https://skudra.net/models/keys.md#uuid-columns-outside-postgresql).

## 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.
