SQLite from Go: connections, drivers and types · 3 MIN READ
Type affinity, dynamic typing and STRICT tables
Predict the storage class SQLite gives each value from a column's declared type, see what Go receives when scanning into any, and use STRICT tables to reject values that do not fit.
In most databases a column has a type and every value in it has that type. In SQLite a value carries its own storage class (NULL, INTEGER, REAL, TEXT or BLOB) and the column only has an affinity, a preference applied when a conversion is lossless. VARCHAR(3) does not limit length and a column named INTEGER can hold the word abc. STRICT tables, available since SQLite 3.37, restore the rules you probably expected.
sqlite · A MAP OF THE IDEA
- Declare STRICT table
- Pick INT/REAL/TEXT/BLOB
- Add CHECK constraints
- Scan into exact types
Useful when
- STRICT turns silent type drift into insert-time errors.
- Affinity still converts lossless input such as "42".
Watch out
- Ordinary tables accept any value in any column.
- STRICT schemas need SQLite 3.37 or newer to read.
Implementation & operation cost: A STRICT keyword and a few CHECK constraints per table; existing tables need a rebuild to adopt them.
Five affinities from the declared type
SQLite derives an affinity from the declared type by substring rules: a type containing INT has INTEGER affinity; CHAR, CLOB or TEXT gives TEXT; BLOB or no type gives BLOB (also called none); REAL, FLOA or DOUB gives REAL; anything else, such as NUMERIC, DECIMAL, BOOLEAN or DATETIME, gives NUMERIC. So VARCHAR(255) is TEXT affinity with no length limit, BOOLEAN stores 0 and 1 as integers, and DATETIME stores whatever you give it. Lengths and precisions in parentheses are parsed and ignored.
Watch the conversions
The program inserts the same six Go values into five columns of an ordinary table and prints typeof() for each, plus the Go type database/sql returns when scanning the INTEGER column into any. A second table is declared STRICT, where the declared type must be INT, INTEGER, REAL, TEXT, BLOB or ANY and a value that cannot be converted losslessly is a constraint error.
package main
import (
"context"
"database/sql"
"fmt"
"log"
_ "modernc.org/sqlite"
)
func main() {
ctx := context.Background()
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(1) // one in-memory database for the whole program
if _, err := db.ExecContext(ctx, `
CREATE TABLE loose (n INTEGER, r REAL, t TEXT, code VARCHAR(3), x);
CREATE TABLE strict (n INTEGER, t TEXT, x ANY) STRICT;`); err != nil {
log.Fatal(err)
}
// Affinity converts when it can do so losslessly; otherwise the value is kept as given.
inputs := []struct {
label string
v any
}{{`"42"`, "42"}, {`"4.0"`, "4.0"}, {"7.5", 7.5}, {`"abc"`, "abc"}, {"int 10", 10}, {"[]byte", []byte{0xCA, 0xFE}}}
for _, in := range inputs {
v := in.v
if _, err := db.ExecContext(ctx, "INSERT INTO loose (n, r, t, code, x) VALUES (?, ?, ?, ?, ?)", v, v, v, v, v); err != nil {
log.Fatal(err)
}
}
rows, err := db.QueryContext(ctx, "SELECT typeof(n), typeof(r), typeof(t), typeof(code), typeof(x), n FROM loose")
if err != nil {
log.Fatal(err)
}
fmt.Println("input INTEGER REAL TEXT VARCHAR none Go value in n")
for i := 0; rows.Next(); i++ {
var tn, tr, tt, tc, tx string
var n any
if err := rows.Scan(&tn, &tr, &tt, &tc, &tx, &n); err != nil {
log.Fatal(err)
}
fmt.Printf("%-9s %-8s %-8s %-8s %-8s %-8s %T\n", inputs[i].label, tn, tr, tt, tc, tx, n)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
rows.Close()
var long string
if _, err := db.ExecContext(ctx, "INSERT INTO loose (code) VALUES (?)", "far longer than three"); err != nil {
log.Fatal(err)
}
if err := db.QueryRowContext(ctx, "SELECT code FROM loose WHERE length(code) > 3").Scan(&long); err != nil {
log.Fatal(err)
}
fmt.Printf("VARCHAR(3) kept %d characters\n", len(long))
// STRICT tables reject values that cannot be converted losslessly.
for _, v := range []any{"42", "abc", 4.0, 4.5} {
_, err := db.ExecContext(ctx, "INSERT INTO strict (n) VALUES (?)", v)
fmt.Printf("STRICT INTEGER <- %T %v: %v\n", v, v, errText(err))
}
var stored string
if err := db.QueryRowContext(ctx, "SELECT group_concat(typeof(n) || ':' || n, ' ') FROM strict").Scan(&stored); err != nil {
log.Fatal(err)
}
fmt.Println("STRICT rows:", stored)
_, err = db.ExecContext(ctx, "CREATE TABLE bad (created DATETIME) STRICT")
fmt.Println("STRICT with DATETIME:", errText(err))
}
func errText(err error) string {
if err == nil {
return "ok"
}
return err.Error()
}The text "42" and "4.0" become integers in the INTEGER column, real in the REAL column, and stay text in the TEXT and untyped columns. 7.5 stays real in INTEGER because converting it would lose the fraction, and "abc" stays text there. Scanning into any returns int64, float64, string or []uint8 according to the stored class, row by row. VARCHAR(3) kept 21 characters. In the STRICT table "42" and 4.0 are converted and stored as integers, while "abc" and 4.5 fail with extended code 3091, SQLITE_CONSTRAINT_DATATYPE, and DATETIME is not an allowed type at all.
What Go code sees
Because the storage class can vary from row to row, a scan target must accept every class the column can actually contain. Scanning into int64 works for INTEGER values and for text that parses as an integer, and fails for "abc"; scanning into string accepts most classes; scanning into any exposes the stored class directly. With ordinary tables, the only way to know is to control every writer. Comparisons also follow storage classes: an INTEGER is always less than any TEXT, so a column that mixes "10" and 9 sorts in surprising ways.
Make the schema say what it means
Declare new tables STRICT unless you have a reason not to, and use CHECK constraints for the rules affinity never enforced: length(code) <= 3, flag IN (0, 1), or a time format. A STRICT table can still have an ANY column for genuinely dynamic data. Existing tables cannot be switched to STRICT with ALTER TABLE; they are rebuilt with the copy-and-rename procedure from the migrations lesson. Tools and older SQLite versions before 3.37 cannot read a schema that uses STRICT, which matters if you hand database files to other programs.
CREATE TABLE products (
id INTEGER PRIMARY KEY,
code TEXT NOT NULL CHECK (length(code) <= 12),
price INTEGER NOT NULL CHECK (price >= 0), -- cents
active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)),
extra ANY
) STRICT;STRICT rejects text in price and active, the CHECK constraints add the length, range and boolean rules affinity never had, money is stored as integer cents rather than REAL, and the ANY column keeps one deliberately dynamic field.
TAKE THIS WITH YOU
SQLite values carry their own type; columns only have an affinity that converts losslessly when it can. Declared lengths are ignored, so add CHECK constraints, and prefer STRICT tables so that wrong types fail at insert time instead of surfacing in a later Scan.
Check your understanding
In an ordinary (non-STRICT) table, what happens when you insert the text "abc" into a column declared INTEGER?
Go to the source
Progress stays in this browser. No account needed.