| 1 |
package dbtest |
| 2 |
|
| 3 |
import ( |
| 4 |
"database/sql" |
| 5 |
"fmt" |
| 6 |
"sort" |
| 7 |
"strings" |
| 8 |
"testing" |
| 9 |
|
| 10 |
"github.com/stretchr/testify/require" |
| 11 |
) |
| 12 |
|
| 13 |
// Querier is the subset of *sql.DB / *db.DB needed to introspect a schema. |
| 14 |
type Querier interface { |
| 15 |
Query(query string, args ...any) (*sql.Rows, error) |
| 16 |
} |
| 17 |
|
| 18 |
// SQLiteSchema returns a normalized, comparable description of the database schema: tables |
| 19 |
// with their columns, named indexes, and foreign keys. Column order, declared type spelling |
| 20 |
// (INT vs INTEGER) and default values are not part of the description, so the schema produced |
| 21 |
// by a migration chain can be compared to a freshly created one. |
| 22 |
func SQLiteSchema(t testing.TB, d Querier) string { |
| 23 |
t.Helper() |
| 24 |
lines := make([]string, 0) |
| 25 |
for _, table := range sqliteTables(t, d) { |
| 26 |
lines = append(lines, "table "+table) |
| 27 |
lines = append(lines, sqliteColumns(t, d, table)...) |
| 28 |
lines = append(lines, sqliteForeignKeys(t, d, table)...) |
| 29 |
lines = append(lines, sqliteIndexes(t, d, table)...) |
| 30 |
} |
| 31 |
return strings.Join(lines, "\n") |
| 32 |
} |
| 33 |
|
| 34 |
// PostgresSchema is SQLiteSchema's PostgreSQL counterpart, describing the current schema's |
| 35 |
// tables, columns, constraints and indexes in a normalized, comparable way. |
| 36 |
func PostgresSchema(t testing.TB, d Querier) string { |
| 37 |
t.Helper() |
| 38 |
lines := make([]string, 0) |
| 39 |
for _, table := range postgresTables(t, d) { |
| 40 |
lines = append(lines, "table "+table) |
| 41 |
lines = append(lines, postgresColumns(t, d, table)...) |
| 42 |
} |
| 43 |
lines = append(lines, postgresConstraints(t, d)...) |
| 44 |
lines = append(lines, postgresIndexes(t, d)...) |
| 45 |
return strings.Join(lines, "\n") |
| 46 |
} |
| 47 |
|
| 48 |
func sqliteTables(t testing.TB, d Querier) []string { |
| 49 |
t.Helper() |
| 50 |
return queryStrings(t, d, `SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name`) |
| 51 |
} |
| 52 |
|
| 53 |
func sqliteColumns(t testing.TB, d Querier, table string) []string { |
| 54 |
t.Helper() |
| 55 |
rows, err := d.Query(fmt.Sprintf(`PRAGMA table_info(%q)`, table)) |
| 56 |
require.Nil(t, err) |
| 57 |
defer rows.Close() |
| 58 |
lines := make([]string, 0) |
| 59 |
for rows.Next() { |
| 60 |
var cid, notNull, pk int |
| 61 |
var name, typ string |
| 62 |
var dflt sql.NullString |
| 63 |
require.Nil(t, rows.Scan(&cid, &name, &typ, ¬Null, &dflt, &pk)) |
| 64 |
typ = strings.ToUpper(typ) |
| 65 |
if typ == "INT" { // INT and INTEGER are the same affinity; migrations spell them inconsistently |
| 66 |
typ = "INTEGER" |
| 67 |
} |
| 68 |
lines = append(lines, fmt.Sprintf(" col %s %s notnull=%d pk=%d", name, typ, notNull, pk)) |
| 69 |
} |
| 70 |
require.Nil(t, rows.Err()) |
| 71 |
sort.Strings(lines) |
| 72 |
return lines |
| 73 |
} |
| 74 |
|
| 75 |
func sqliteForeignKeys(t testing.TB, d Querier, table string) []string { |
| 76 |
t.Helper() |
| 77 |
rows, err := d.Query(fmt.Sprintf(`PRAGMA foreign_key_list(%q)`, table)) |
| 78 |
require.Nil(t, err) |
| 79 |
defer rows.Close() |
| 80 |
lines := make([]string, 0) |
| 81 |
for rows.Next() { |
| 82 |
var id, seq int |
| 83 |
var refTable, from, onUpdate, onDelete, match string |
| 84 |
var to sql.NullString // NULL when referencing the parent's primary key implicitly |
| 85 |
require.Nil(t, rows.Scan(&id, &seq, &refTable, &from, &to, &onUpdate, &onDelete, &match)) |
| 86 |
lines = append(lines, fmt.Sprintf(" fk %s -> %s(%s) on_delete=%s", from, refTable, to.String, onDelete)) |
| 87 |
} |
| 88 |
require.Nil(t, rows.Err()) |
| 89 |
sort.Strings(lines) |
| 90 |
return lines |
| 91 |
} |
| 92 |
|
| 93 |
func sqliteIndexes(t testing.TB, d Querier, table string) []string { |
| 94 |
t.Helper() |
| 95 |
rows, err := d.Query(fmt.Sprintf(`PRAGMA index_list(%q)`, table)) |
| 96 |
require.Nil(t, err) |
| 97 |
type index struct { |
| 98 |
name string |
| 99 |
unique, partial int |
| 100 |
} |
| 101 |
indexes := make([]index, 0) |
| 102 |
for rows.Next() { |
| 103 |
var seq, unique, partial int |
| 104 |
var name, origin string |
| 105 |
require.Nil(t, rows.Scan(&seq, &name, &unique, &origin, &partial)) |
| 106 |
// Skip auto-indexes backing PRIMARY KEY/UNIQUE table constraints; those are described |
| 107 |
// by the column and constraint listings already |
| 108 |
if strings.HasPrefix(name, "sqlite_autoindex_") { |
| 109 |
continue |
| 110 |
} |
| 111 |
indexes = append(indexes, index{name, unique, partial}) |
| 112 |
} |
| 113 |
require.Nil(t, rows.Err()) |
| 114 |
require.Nil(t, rows.Close()) |
| 115 |
lines := make([]string, 0, len(indexes)) |
| 116 |
for _, idx := range indexes { |
| 117 |
cols := queryStrings(t, d, fmt.Sprintf(`SELECT name FROM pragma_index_info(%q) ORDER BY seqno`, idx.name)) |
| 118 |
lines = append(lines, fmt.Sprintf(" index %s unique=%d partial=%d cols=(%s)", idx.name, idx.unique, idx.partial, strings.Join(cols, ","))) |
| 119 |
} |
| 120 |
sort.Strings(lines) |
| 121 |
return lines |
| 122 |
} |
| 123 |
|
| 124 |
func postgresTables(t testing.TB, d Querier) []string { |
| 125 |
t.Helper() |
| 126 |
return queryStrings(t, d, `SELECT table_name FROM information_schema.tables WHERE table_schema = current_schema() AND table_type = 'BASE TABLE' ORDER BY table_name`) |
| 127 |
} |
| 128 |
|
| 129 |
func postgresColumns(t testing.TB, d Querier, table string) []string { |
| 130 |
t.Helper() |
| 131 |
rows, err := d.Query(`SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = $1 ORDER BY column_name`, table) |
| 132 |
require.Nil(t, err) |
| 133 |
defer rows.Close() |
| 134 |
lines := make([]string, 0) |
| 135 |
for rows.Next() { |
| 136 |
var name, typ, nullable string |
| 137 |
require.Nil(t, rows.Scan(&name, &typ, &nullable)) |
| 138 |
lines = append(lines, fmt.Sprintf(" col %s %s nullable=%s", name, typ, nullable)) |
| 139 |
} |
| 140 |
require.Nil(t, rows.Err()) |
| 141 |
return lines |
| 142 |
} |
| 143 |
|
| 144 |
func postgresConstraints(t testing.TB, d Querier) []string { |
| 145 |
t.Helper() |
| 146 |
return queryStrings(t, d, ` |
| 147 |
SELECT 'constraint ' || conrelid::regclass::text || ': ' || pg_get_constraintdef(oid) |
| 148 |
FROM pg_constraint |
| 149 |
WHERE connamespace = current_schema()::regnamespace |
| 150 |
ORDER BY 1 |
| 151 |
`) |
| 152 |
} |
| 153 |
|
| 154 |
func postgresIndexes(t testing.TB, d Querier) []string { |
| 155 |
t.Helper() |
| 156 |
rows, err := d.Query(`SELECT indexname, indexdef, schemaname FROM pg_indexes WHERE schemaname = current_schema() ORDER BY indexname`) |
| 157 |
require.Nil(t, err) |
| 158 |
defer rows.Close() |
| 159 |
lines := make([]string, 0) |
| 160 |
for rows.Next() { |
| 161 |
var name, def, schema string |
| 162 |
require.Nil(t, rows.Scan(&name, &def, &schema)) |
| 163 |
// The index definition qualifies the table with the (test-specific) schema name; strip |
| 164 |
// it so snapshots from different test schemas compare equal |
| 165 |
def = strings.ReplaceAll(def, schema+".", "") |
| 166 |
lines = append(lines, "index "+def) |
| 167 |
} |
| 168 |
require.Nil(t, rows.Err()) |
| 169 |
return lines |
| 170 |
} |
| 171 |
|
| 172 |
func queryStrings(t testing.TB, d Querier, query string) []string { |
| 173 |
t.Helper() |
| 174 |
rows, err := d.Query(query) |
| 175 |
require.Nil(t, err) |
| 176 |
defer rows.Close() |
| 177 |
values := make([]string, 0) |
| 178 |
for rows.Next() { |
| 179 |
var value string |
| 180 |
require.Nil(t, rows.Scan(&value)) |
| 181 |
values = append(values, value) |
| 182 |
} |
| 183 |
require.Nil(t, rows.Err()) |
| 184 |
return values |
| 185 |
} |