@cslug/database 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/api.md CHANGED
@@ -121,8 +121,29 @@ and `$$` bodies are fine). A first line `-- cslug:no-transaction` runs the file
121
121
  | `Migrator.create(dir, name)` | Writes an empty, timestamped file |
122
122
  | `FRAMEWORK_MIGRATIONS` | cslug's own (e.g. `cslug_idempotency`), always run first |
123
123
 
124
- A failing migration is rolled back entirely and the error names the file. (`cslug migrate*` commands arrive
125
- with `@cslug/cli` in M3. The table differ, `--from-tables`, comes later.)
124
+ A failing migration is rolled back entirely and the error names the file.
125
+
126
+ `cslug db:shell` opens `psql` on `config database.url` (`-c` / `--command` runs one statement). The password is
127
+ passed through `PGPASSWORD`, not on the command line.
128
+
129
+ ### The table differ
130
+
131
+ `cslug make:migration --from-tables` compares `app/tables/` with the database and writes the SQL; `cslug db:diff`
132
+ prints the same changes (and the SQL with `--sql`) without writing a file.
133
+
134
+ | | |
135
+ |---|---|
136
+ | `loadTables(rootDir)` | The tables `app/tables/` exports |
137
+ | `tableSpec(table)` / `introspect(db)` | Both sides in one shape (`TableSpec`): columns (type as `format_type()` reports it, nullability, default), unique, check (`oneOf`) and foreign-key constraints, indexes. `introspect` reads the `public` schema and skips `cslug_*` tables (packages migrate those) |
138
+ | `renameCandidates(desired, actual)` | A column in the database only and one in the tables only, same table and type: maybe a rename (the command asks; without a terminal it assumes a rename, which keeps the data) |
139
+ | `diffSchemas(desired, actual, renames?)` | `Change[]` (`{ table, label, up, down, warning? }`): new tables (referenced ones first), added / dropped / renamed columns, type, nullability and default changes, constraints and indexes compared by name and definition, dropped tables |
140
+ | `migrationSql(changes)` | `-- up` in order, `-- down` in reverse |
141
+
142
+ Constraint names follow PostgreSQL's defaults (`t_col_key`, `t_col_fkey`, `t_col_check`), so a table created by a
143
+ generated migration diffs clean; a rename also renames the column's constraints and indexes. Changes that can lose
144
+ data or fail on existing rows (a dropped column or table, a type change, `not null` without a default) are listed as
145
+ `-- review:` comments at the top of the file. Anything else (views, triggers, data migrations, custom `check()`) is
146
+ hand-written SQL.
126
147
 
127
148
  ## Factories and seeders
128
149
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cslug/database",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "PostgreSQL on Bun.sql: typed tables, query builder, sql tag, repositories, migrations.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -28,6 +28,6 @@
28
28
  "bun": ">=1.3.14"
29
29
  },
30
30
  "peerDependencies": {
31
- "@cslug/core": "0.3.0"
31
+ "@cslug/core": "0.4.1"
32
32
  }
33
33
  }
package/src/commands.ts CHANGED
@@ -1,7 +1,17 @@
1
- import { existsSync, readdirSync } from 'node:fs'
1
+ import { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { arg, Command, flag, names } from '@cslug/core'
4
4
  import { Database } from './database'
5
+ import {
6
+ type Change,
7
+ diffSchemas,
8
+ introspect,
9
+ loadTables,
10
+ migrationSql,
11
+ type RenameCandidate,
12
+ renameCandidates,
13
+ tableSpec,
14
+ } from './differ'
5
15
  import { isSeeder } from './factory'
6
16
  import { Migrator } from './migrator'
7
17
 
@@ -26,6 +36,22 @@ abstract class DatabaseCommand extends Command {
26
36
  }
27
37
  return true
28
38
  }
39
+ /** Diff `app/tables/` against the database, asking about possible renames; prints each change. */
40
+ protected async schemaChanges(): Promise<Change[]> {
41
+ const desired = (await loadTables(this.app.rootDir)).map(tableSpec)
42
+ const actual = await introspect(this.app.resolve(Database))
43
+ const renames: RenameCandidate[] = []
44
+ for (const c of renameCandidates(desired, actual)) {
45
+ const answer = await this.choose(`${c.table}.${c.from} → ${c.to}: rename or drop+add?`, ['rename', 'drop+add'])
46
+ if (answer === 'rename') renames.push(c)
47
+ }
48
+ const changes = diffSchemas(desired, actual, renames)
49
+ for (const change of changes) {
50
+ this.line(` ${change.label}`)
51
+ if (change.warning) this.warn(change.warning)
52
+ }
53
+ return changes
54
+ }
29
55
  protected async seed(only?: string): Promise<number> {
30
56
  const dir = join(this.app.rootDir, 'database/seeders')
31
57
  if (!existsSync(dir)) {
@@ -125,27 +151,96 @@ export class DbSeedCommand extends DatabaseCommand {
125
151
  }
126
152
  }
127
153
 
128
- /** `cslug make:migration add_claims_index` → database/migrations/20261126_101500_add_claims_index.sql. */
129
- export class MakeMigrationCommand extends Command {
154
+ const stamp = (now: Date) => {
155
+ const pad = (n: number) => String(n).padStart(2, '0')
156
+ return `${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}_${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}`
157
+ }
158
+
159
+ /**
160
+ * `cslug make:migration add_claims_index` → an empty `database/migrations/<stamp>_add_claims_index.sql`;
161
+ * `cslug make:migration --from-tables` → the SQL that brings the database to `app/tables/` (renames are asked).
162
+ */
163
+ export class MakeMigrationCommand extends DatabaseCommand {
130
164
  static signature = 'make:migration'
131
- static description = 'Create an empty SQL migration'
165
+ static description = 'Create a SQL migration: empty, or --from-tables (diff app/tables against the database)'
132
166
  static boot = false
133
- static args = { name: arg.string().describe('snake_case, e.g. create_claims') }
134
-
135
- handle({ name }: Command.Args<typeof MakeMigrationCommand>) {
136
- const now = this.clock.now()
137
- const pad = (n: number) => String(n).padStart(2, '0')
138
- const stamp = `${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}_${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}`
139
- const snakeName = names(name).snake
140
- const table = /^create_(\w+)$/.exec(snakeName)?.[1]
141
- return this.generate(
142
- STUBS,
143
- table ? 'migration.create.stub' : 'migration.stub',
144
- `database/migrations/${stamp}_${snakeName}.sql`,
145
- { table: table ?? '' },
146
- )
147
- ? 0
148
- : 1
167
+ static args = {
168
+ name: arg.string().optional().describe('snake_case, e.g. create_claims'),
169
+ fromTables: flag.boolean().describe('Write the SQL for what app/tables changed'),
170
+ }
171
+
172
+ async handle({ name, fromTables }: Command.Args<typeof MakeMigrationCommand>) {
173
+ if (!fromTables) {
174
+ if (!name) {
175
+ this.error('A name, or --from-tables')
176
+ return 2
177
+ }
178
+ const snakeName = names(name).snake
179
+ const table = /^create_(\w+)$/.exec(snakeName)?.[1]
180
+ const target = `database/migrations/${stamp(this.clock.now())}_${snakeName}.sql`
181
+ const stub = table ? 'migration.create.stub' : 'migration.stub'
182
+ return this.generate(STUBS, stub, target, { table: table ?? '' }) ? 0 : 1
183
+ }
184
+ await this.app.start()
185
+ const changes = await this.schemaChanges()
186
+ if (!changes.length) {
187
+ this.info('Nothing to migrate: the database matches app/tables')
188
+ return 0
189
+ }
190
+ const tables = [...new Set(changes.map((c) => c.table))]
191
+ const created = changes.every((c) => c.label.startsWith('+ table'))
192
+ const fallback = tables.length === 1 ? `${created ? 'create' : 'update'}_${tables[0]}` : 'update_schema'
193
+ const file = `database/migrations/${stamp(this.clock.now())}_${names(name ?? fallback).snake}.sql`
194
+ const review = changes.filter((c) => c.warning).map((c) => `-- review: ${c.warning}\n`)
195
+ mkdirSync(join(this.app.rootDir, 'database/migrations'), { recursive: true })
196
+ writeFileSync(join(this.app.rootDir, file), `${review.join('')}${migrationSql(changes)}`)
197
+ this.success(file)
198
+ return 0
199
+ }
200
+ }
201
+
202
+ /**
203
+ * `cslug db:shell`: `psql` on the app's database (`config database.url`). The password goes through `PGPASSWORD`,
204
+ * never the command line (where `ps` shows it). `--command` runs one statement and exits.
205
+ */
206
+ export class DbShellCommand extends Command {
207
+ static signature = 'db:shell'
208
+ static description = 'Open psql on the app database'
209
+ static boot = false
210
+ static args = { command: flag.string().optional().alias('c').describe('Run one SQL statement and exit') }
211
+
212
+ async handle({ command }: Command.Args<typeof DbShellCommand>) {
213
+ const configured = this.app.config<string | undefined>('database.url')
214
+ if (!configured) {
215
+ this.error('No database configured (config/database.ts → url)')
216
+ return 1
217
+ }
218
+ const psql = Bun.which('psql')
219
+ if (!psql) {
220
+ this.error('psql is not installed (Debian/Ubuntu: apt install postgresql-client; macOS: brew install libpq)')
221
+ return 1
222
+ }
223
+ const url = new URL(configured)
224
+ const password = decodeURIComponent(url.password)
225
+ url.password = ''
226
+ const proc = Bun.spawn([psql, url.toString(), ...(command ? ['-c', command] : [])], {
227
+ stdio: ['inherit', 'inherit', 'inherit'],
228
+ env: { ...process.env, ...(password ? { PGPASSWORD: password } : {}) },
229
+ })
230
+ return await proc.exited
231
+ }
232
+ }
233
+
234
+ /** `cslug db:diff`: what `make:migration --from-tables` would write, without writing it. */
235
+ export class DbDiffCommand extends DatabaseCommand {
236
+ static signature = 'db:diff'
237
+ static description = 'Show the drift between app/tables and the database (writes nothing)'
238
+ static args = { sql: flag.boolean().describe('Print the SQL too') }
239
+
240
+ async handle({ sql }: Command.Args<typeof DbDiffCommand>) {
241
+ const changes = await this.schemaChanges()
242
+ if (!changes.length) this.info('No drift: the database matches app/tables')
243
+ else if (sql) this.line(`\n${migrationSql(changes)}`)
149
244
  }
150
245
  }
151
246
 
@@ -179,6 +274,8 @@ export const databaseCommands = [
179
274
  MigrateFreshCommand,
180
275
  DbSeedCommand,
181
276
  MakeMigrationCommand,
277
+ DbDiffCommand,
278
+ DbShellCommand,
182
279
  make('table', 'app/tables'),
183
280
  make('repository', 'app/repositories'),
184
281
  make('factory', 'database/factories'),
package/src/differ.ts ADDED
@@ -0,0 +1,383 @@
1
+ import { existsSync, readdirSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import type { Database } from './database'
4
+ import { sql } from './sql'
5
+ import { Table } from './table'
6
+
7
+ /** The tables `app/tables/` exports (subfolders included), in file order. */
8
+ export async function loadTables(rootDir: string): Promise<Table[]> {
9
+ const dir = join(rootDir, 'app/tables')
10
+ const tables: Table[] = []
11
+ if (existsSync(dir))
12
+ for (const file of (readdirSync(dir, { recursive: true }) as string[])
13
+ .filter((f) => /(?<!\.test)\.ts$/.test(f))
14
+ .sort())
15
+ for (const value of Object.values(await import(join(dir, file))))
16
+ if (value instanceof Table && !tables.includes(value)) tables.push(value)
17
+ return tables
18
+ }
19
+
20
+ // ── one shape for both sides: what the tables want and what the database has ─────────────────────────
21
+
22
+ export type ColumnSpec = { name: string; type: string; nullable: boolean; default?: string; primary?: boolean }
23
+ /** Constraints and indexes by name. Names follow PostgreSQL's defaults (`t_col_key`, `t_col_fkey`, `t_col_check`). */
24
+ export type TableSpec = {
25
+ name: string
26
+ columns: ColumnSpec[]
27
+ uniques: { name: string; column: string }[]
28
+ checks: { name: string; column: string; values: string[] }[]
29
+ foreignKeys: { name: string; column: string; table: string; references: string; onDelete?: string }[]
30
+ indexes: { name: string; columns: string[]; unique: boolean }[]
31
+ }
32
+
33
+ /** `timestamptz` → `timestamp with time zone`, as `format_type()` reports it. */
34
+ const TYPES: [RegExp, string][] = [
35
+ [/^timestamptz$/, 'timestamp with time zone'],
36
+ [/^timestamp$/, 'timestamp without time zone'],
37
+ [/^varchar\((\d+)\)$/, 'character varying($1)'],
38
+ [/^char\((\d+)\)$/, 'character($1)'],
39
+ [/^int$/, 'integer'],
40
+ [/^bool$/, 'boolean'],
41
+ ]
42
+ const pgType = (type: string) => TYPES.reduce((t, [re, to]) => t.replace(re, to), type.toLowerCase())
43
+ /** `'draft'::text` → `'draft'`, so defaults compare as written. */
44
+ const plainDefault = (expr: string) =>
45
+ expr.replace(/::[a-z ]+(\(\d+(,\d+)?\))?(\[\])?/g, '').replace(/^\((.*)\)$/, '$1')
46
+ const literal = (v: unknown) => (typeof v === 'string' ? `'${v.replace(/'/g, "''")}'` : v === null ? 'null' : String(v))
47
+
48
+ export function tableSpec(t: Table): TableSpec {
49
+ const spec: TableSpec = {
50
+ name: t.name,
51
+ columns: [],
52
+ uniques: [],
53
+ checks: [],
54
+ foreignKeys: [],
55
+ indexes: [...t.indexes],
56
+ }
57
+ for (const [key, { def }] of Object.entries(t.columns)) {
58
+ const name = t.sqlNames.get(key) as string
59
+ const value = def.defaultSql ?? (def.defaultValue === undefined ? undefined : literal(def.defaultValue))
60
+ spec.columns.push({
61
+ name,
62
+ type: pgType(def.sqlType),
63
+ nullable: def.nullable,
64
+ ...(value === undefined ? {} : { default: value }),
65
+ ...(def.primary ? { primary: true } : {}),
66
+ })
67
+ if (def.unique) spec.uniques.push({ name: `${t.name}_${name}_key`, column: name })
68
+ if (def.oneOf) spec.checks.push({ name: `${t.name}_${name}_check`, column: name, values: [...def.oneOf] })
69
+ if (def.references)
70
+ spec.foreignKeys.push({
71
+ name: `${t.name}_${name}_fkey`,
72
+ column: name,
73
+ table: def.references.table().name,
74
+ references: def.references.column,
75
+ ...(def.references.onDelete ? { onDelete: def.references.onDelete.toLowerCase() } : {}),
76
+ })
77
+ }
78
+ return spec
79
+ }
80
+
81
+ /** The app's tables in the `public` schema (not `cslug_*`, which packages migrate), as the catalog has them. */
82
+ export async function introspect(db: Database): Promise<TableSpec[]> {
83
+ const own = sql`n.nspname = 'public' and left(c.relname, 6) <> 'cslug_'`
84
+ const columns = await db.many<{
85
+ table: string
86
+ name: string
87
+ type: string
88
+ nullable: boolean
89
+ default: string | null
90
+ }>(
91
+ sql`select c.relname as table, a.attname as name, format_type(a.atttypid, a.atttypmod) as type,
92
+ not a.attnotnull as nullable, pg_get_expr(d.adbin, d.adrelid) as default
93
+ from pg_class c join pg_namespace n on n.oid = c.relnamespace
94
+ join pg_attribute a on a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped
95
+ left join pg_attrdef d on d.adrelid = c.oid and d.adnum = a.attnum
96
+ where c.relkind = 'r' and ${own} order by c.relname, a.attnum`,
97
+ )
98
+ const constraints = await db.many<{ table: string; name: string; type: string; def: string; columns: string[] }>(
99
+ sql`select c.relname as table, k.conname as name, k.contype::text as type, pg_get_constraintdef(k.oid) as def,
100
+ array(select a.attname::text from unnest(k.conkey) with ordinality x(n, o)
101
+ join pg_attribute a on a.attrelid = k.conrelid and a.attnum = x.n order by x.o) as columns
102
+ from pg_constraint k join pg_class c on c.oid = k.conrelid join pg_namespace n on n.oid = c.relnamespace
103
+ where ${own}`,
104
+ )
105
+ const indexes = await db.many<{ table: string; name: string; unique: boolean; columns: string[] }>(
106
+ sql`select c.relname as table, i.relname as name, x.indisunique as unique,
107
+ array(select a.attname::text from unnest(x.indkey::int2[]) with ordinality k(n, o)
108
+ join pg_attribute a on a.attrelid = c.oid and a.attnum = k.n order by k.o) as columns
109
+ from pg_index x join pg_class i on i.oid = x.indexrelid join pg_class c on c.oid = x.indrelid
110
+ join pg_namespace n on n.oid = c.relnamespace
111
+ where ${own} and not exists (select 1 from pg_constraint k where k.conindid = x.indexrelid)`,
112
+ )
113
+ const tables = new Map<string, TableSpec>()
114
+ const of = (name: string) => {
115
+ const t = tables.get(name) ?? { name, columns: [], uniques: [], checks: [], foreignKeys: [], indexes: [] }
116
+ tables.set(name, t)
117
+ return t
118
+ }
119
+ for (const c of columns)
120
+ of(c.table).columns.push({
121
+ name: c.name,
122
+ type: c.type,
123
+ nullable: c.nullable,
124
+ ...(c.default === null ? {} : { default: c.default }),
125
+ })
126
+ for (const k of constraints) {
127
+ const t = of(k.table)
128
+ const column = k.columns[0] as string
129
+ if (k.type === 'p') for (const c of t.columns) if (k.columns.includes(c.name)) c.primary = true
130
+ if (k.type === 'u') t.uniques.push({ name: k.name, column })
131
+ if (k.type === 'c')
132
+ t.checks.push({
133
+ name: k.name,
134
+ column,
135
+ values: [...k.def.matchAll(/'((?:[^']|'')*)'::/g)].map((m) => m[1] as string),
136
+ })
137
+ const fk = /REFERENCES (\S+)\((\w+)\)(?: ON DELETE ([A-Z ]+))?/.exec(k.def)
138
+ if (k.type === 'f' && fk)
139
+ t.foreignKeys.push({
140
+ name: k.name,
141
+ column,
142
+ table: (fk[1] as string).replace(/"/g, ''),
143
+ references: fk[2] as string,
144
+ ...(fk[3] ? { onDelete: fk[3].toLowerCase() } : {}),
145
+ })
146
+ }
147
+ for (const i of indexes) of(i.table).indexes.push({ name: i.name, columns: i.columns, unique: i.unique })
148
+ return [...tables.values()]
149
+ }
150
+
151
+ // ── the diff ─────────────────────────────────────────────────────────────────────────────────────────
152
+
153
+ /** One change: what it does, the SQL to apply it and to revert it, and a warning to review. */
154
+ export type Change = { table: string; label: string; up: string[]; down: string[]; warning?: string }
155
+ /** A column that may have been renamed: `from` is in the database only, `to` in the tables only, same type. */
156
+ export type RenameCandidate = { table: string; from: string; to: string }
157
+
158
+ const columnSql = (t: TableSpec, c: ColumnSpec) => {
159
+ const check = t.checks.find((k) => k.column === c.name)
160
+ const fk = t.foreignKeys.find((k) => k.column === c.name)
161
+ return [
162
+ `${c.name} ${c.type}`,
163
+ c.primary ? 'primary key' : c.nullable ? '' : 'not null',
164
+ c.default === undefined ? '' : `default ${c.default}`,
165
+ t.uniques.some((u) => u.column === c.name) ? 'unique' : '',
166
+ check ? `check (${c.name} in (${check.values.map(literal).join(', ')}))` : '',
167
+ fk ? `references ${fk.table} (${fk.references})${fk.onDelete ? ` on delete ${fk.onDelete}` : ''}` : '',
168
+ ]
169
+ .filter(Boolean)
170
+ .join(' ')
171
+ }
172
+ const indexSql = (t: string, i: TableSpec['indexes'][number]) =>
173
+ `create ${i.unique ? 'unique ' : ''}index ${i.name} on ${t} (${i.columns.join(', ')});`
174
+ const createTable = (t: TableSpec) => [
175
+ `create table ${t.name} (\n${t.columns.map((c) => ` ${columnSql(t, c)}`).join(',\n')}\n);`,
176
+ ...t.indexes.map((i) => indexSql(t.name, i)),
177
+ ]
178
+ const byName = <T extends { name: string }>(list: T[]) => new Map(list.map((x) => [x.name, x]))
179
+ const sameDefault = (a?: string, b?: string) =>
180
+ (a === undefined ? undefined : plainDefault(a)) === (b === undefined ? undefined : plainDefault(b))
181
+
182
+ /** Columns dropped and added in one table with the same type: maybe a rename (the command asks). */
183
+ export function renameCandidates(desired: TableSpec[], actual: TableSpec[]): RenameCandidate[] {
184
+ const found: RenameCandidate[] = []
185
+ for (const want of desired) {
186
+ const have = actual.find((t) => t.name === want.name)
187
+ if (!have) continue
188
+ const added = want.columns.filter((c) => !have.columns.some((h) => h.name === c.name))
189
+ for (const old of have.columns.filter((h) => !want.columns.some((c) => c.name === h.name))) {
190
+ const to = added.find((c) => c.type === old.type && !found.some((f) => f.table === want.name && f.to === c.name))
191
+ if (to) found.push({ table: want.name, from: old.name, to: to.name })
192
+ }
193
+ }
194
+ return found
195
+ }
196
+
197
+ /** What turns `actual` into `desired`. `renames` are the candidates confirmed as renames. */
198
+ export function diffSchemas(desired: TableSpec[], actual: TableSpec[], renames: RenameCandidate[] = []): Change[] {
199
+ const changes: Change[] = []
200
+ const have = byName(actual)
201
+ const want = byName(desired)
202
+ // new tables, referenced ones first
203
+ const created = desired.filter((t) => !have.has(t.name))
204
+ const order = (t: TableSpec, seen = new Set<string>()): number =>
205
+ seen.has(t.name)
206
+ ? 0
207
+ : 1 +
208
+ Math.max(
209
+ 0,
210
+ ...t.foreignKeys
211
+ .map((f) => created.find((c) => c.name === f.table && c.name !== t.name))
212
+ .filter((c): c is TableSpec => !!c)
213
+ .map((c) => order(c, new Set([...seen, t.name]))),
214
+ )
215
+ for (const t of [...created].sort((a, b) => order(a) - order(b)))
216
+ changes.push({ table: t.name, label: `+ table ${t.name}`, up: createTable(t), down: [`drop table ${t.name};`] })
217
+
218
+ for (const t of desired) {
219
+ const old = have.get(t.name)
220
+ if (!old) continue
221
+ const a = `alter table ${t.name}`
222
+ const renamed = renames.filter((r) => r.table === t.name)
223
+ for (const r of renamed) {
224
+ // PostgreSQL keeps constraint and index names on a column rename: rename them to the default names too
225
+ const affected = [
226
+ ...[...old.uniques, ...old.checks, ...old.foreignKeys].map((x) => ({ name: x.name, index: false })),
227
+ ...old.indexes.map((x) => ({ name: x.name, index: true })),
228
+ ].filter((x) => x.name.includes(`_${r.from}_`))
229
+ const to = (n: string) => n.replace(`_${r.from}_`, `_${r.to}_`)
230
+ const rename = (index: boolean, from: string, into: string) =>
231
+ index ? `alter index ${from} rename to ${into};` : `${a} rename constraint ${from} to ${into};`
232
+ changes.push({
233
+ table: t.name,
234
+ label: `~ column ${t.name}.${r.from} → ${r.to}`,
235
+ up: [`${a} rename column ${r.from} to ${r.to};`, ...affected.map((x) => rename(x.index, x.name, to(x.name)))],
236
+ down: [...affected.map((x) => rename(x.index, to(x.name), x.name)), `${a} rename column ${r.to} to ${r.from};`],
237
+ })
238
+ }
239
+ const current = (name: string) =>
240
+ old.columns.find((c) => c.name === (renamed.find((r) => r.to === name)?.from ?? name))
241
+ for (const c of t.columns) {
242
+ const was = current(c.name)
243
+ if (!was) {
244
+ changes.push({
245
+ table: t.name,
246
+ label: `+ column ${t.name}.${c.name} ${c.type}`,
247
+ up: [`${a} add column ${columnSql(t, c)};`],
248
+ down: [`${a} drop column ${c.name};`],
249
+ ...(!c.nullable && c.default === undefined
250
+ ? { warning: `${t.name}.${c.name} is not null without a default: fails if the table has rows` }
251
+ : {}),
252
+ })
253
+ continue
254
+ }
255
+ const col = `${a} alter column ${c.name}`
256
+ if (was.type !== c.type)
257
+ changes.push({
258
+ table: t.name,
259
+ label: `~ column ${t.name}.${c.name} ${c.type} (was ${was.type})`,
260
+ up: [`${col} type ${c.type};`],
261
+ down: [`${col} type ${was.type};`],
262
+ warning: `${t.name}.${c.name}: a type change may need \`using ${c.name}::${c.type}\``,
263
+ })
264
+ if (was.nullable !== c.nullable && !c.primary)
265
+ changes.push({
266
+ table: t.name,
267
+ label: `~ column ${t.name}.${c.name} ${c.nullable ? 'nullable' : 'not null'}`,
268
+ up: [`${col} ${c.nullable ? 'drop' : 'set'} not null;`],
269
+ down: [`${col} ${c.nullable ? 'set' : 'drop'} not null;`],
270
+ })
271
+ if (!sameDefault(was.default, c.default))
272
+ changes.push({
273
+ table: t.name,
274
+ label: `~ column ${t.name}.${c.name} default ${c.default ?? 'none'}`,
275
+ up: [c.default === undefined ? `${col} drop default;` : `${col} set default ${c.default};`],
276
+ down: [
277
+ was.default === undefined ? `${col} drop default;` : `${col} set default ${plainDefault(was.default)};`,
278
+ ],
279
+ })
280
+ }
281
+ for (const c of old.columns)
282
+ if (!t.columns.some((w) => w.name === c.name) && !renamed.some((r) => r.from === c.name))
283
+ changes.push({
284
+ table: t.name,
285
+ label: `- column ${t.name}.${c.name}`,
286
+ up: [`${a} drop column ${c.name};`],
287
+ down: [`${a} add column ${columnSql(old, c)};`],
288
+ warning: `${t.name}.${c.name} is dropped with its data`,
289
+ })
290
+ changes.push(...constraintChanges(t, renamed.length ? renamedSpec(old, renamed) : old))
291
+ }
292
+
293
+ for (const t of actual)
294
+ if (!want.has(t.name))
295
+ changes.push({
296
+ table: t.name,
297
+ label: `- table ${t.name}`,
298
+ up: [`drop table ${t.name};`],
299
+ down: createTable(t),
300
+ warning: `table ${t.name} is dropped with its data (not in app/tables/)`,
301
+ })
302
+ return changes
303
+ }
304
+
305
+ /** `old` as it is after the renames: columns, and the constraint and index names derived from them. */
306
+ function renamedSpec(old: TableSpec, renamed: RenameCandidate[]): TableSpec {
307
+ const col = (c: string) => renamed.find((r) => r.from === c)?.to ?? c
308
+ const name = (n: string) => renamed.reduce((x, r) => x.replace(`_${r.from}_`, `_${r.to}_`), n)
309
+ return {
310
+ name: old.name,
311
+ columns: old.columns.map((c) => ({ ...c, name: col(c.name) })),
312
+ uniques: old.uniques.map((u) => ({ name: name(u.name), column: col(u.column) })),
313
+ checks: old.checks.map((k) => ({ ...k, name: name(k.name), column: col(k.column) })),
314
+ foreignKeys: old.foreignKeys.map((f) => ({ ...f, name: name(f.name), column: col(f.column) })),
315
+ indexes: old.indexes.map((i) => ({ ...i, name: name(i.name), columns: i.columns.map(col) })),
316
+ }
317
+ }
318
+
319
+ /** A table's unique, check and foreign-key constraints as `name → definition`. */
320
+ const constraintsOf = (t: TableSpec) =>
321
+ new Map<string, string>([
322
+ ...t.uniques.map((u) => [u.name, `unique (${u.column})`] as const),
323
+ ...t.checks.map((k) => [k.name, `check (${k.column} in (${k.values.map(literal).join(', ')}))`] as const),
324
+ ...t.foreignKeys.map(
325
+ (f) =>
326
+ [
327
+ f.name,
328
+ `foreign key (${f.column}) references ${f.table} (${f.references})${f.onDelete ? ` on delete ${f.onDelete}` : ''}`,
329
+ ] as const,
330
+ ),
331
+ ])
332
+
333
+ /** Constraints and indexes, compared by name and definition. */
334
+ function constraintChanges(t: TableSpec, old: TableSpec): Change[] {
335
+ const changes: Change[] = []
336
+ const a = `alter table ${t.name}`
337
+ const [now, was] = [constraintsOf(t), constraintsOf(old)]
338
+ for (const [name, def] of now) {
339
+ const before = was.get(name)
340
+ if (before === def) continue
341
+ changes.push({
342
+ table: t.name,
343
+ label: `${before ? '~' : '+'} constraint ${name}`,
344
+ up: [...(before ? [`${a} drop constraint ${name};`] : []), `${a} add constraint ${name} ${def};`],
345
+ down: [`${a} drop constraint ${name};`, ...(before ? [`${a} add constraint ${name} ${before};`] : [])],
346
+ })
347
+ }
348
+ for (const [name, def] of was)
349
+ if (!now.has(name))
350
+ changes.push({
351
+ table: t.name,
352
+ label: `- constraint ${name}`,
353
+ up: [`${a} drop constraint ${name};`],
354
+ down: [`${a} add constraint ${name} ${def};`],
355
+ })
356
+ const wasIndex = byName(old.indexes)
357
+ for (const i of t.indexes) {
358
+ const y = wasIndex.get(i.name)
359
+ if (y && y.unique === i.unique && y.columns.join() === i.columns.join()) continue
360
+ changes.push({
361
+ table: t.name,
362
+ label: `${y ? '~' : '+'} index ${i.name}`,
363
+ up: [...(y ? [`drop index ${i.name};`] : []), indexSql(t.name, i)],
364
+ down: [`drop index ${i.name};`, ...(y ? [indexSql(t.name, y)] : [])],
365
+ })
366
+ }
367
+ for (const y of old.indexes)
368
+ if (!t.indexes.some((i) => i.name === y.name))
369
+ changes.push({
370
+ table: t.name,
371
+ label: `- index ${y.name}`,
372
+ up: [`drop index ${y.name};`],
373
+ down: [indexSql(t.name, y)],
374
+ })
375
+ return changes
376
+ }
377
+
378
+ /** The migration file: `-- up` in order, `-- down` in reverse. */
379
+ export const migrationSql = (changes: Change[]) =>
380
+ `-- up\n${changes.flatMap((c) => c.up).join('\n')}\n\n-- down\n${[...changes]
381
+ .reverse()
382
+ .flatMap((c) => c.down)
383
+ .join('\n')}\n`
package/src/index.ts CHANGED
@@ -26,15 +26,34 @@ export {
26
26
  uuid,
27
27
  varchar,
28
28
  } from './columns'
29
- export { DbSeedCommand, databaseCommands, MigrateCommand } from './commands'
29
+ export {
30
+ DbDiffCommand,
31
+ DbSeedCommand,
32
+ DbShellCommand,
33
+ databaseCommands,
34
+ MakeMigrationCommand,
35
+ MigrateCommand,
36
+ } from './commands'
30
37
  export { Database, type DatabaseConfig, type Json, Queryable, Transaction, type TransactionOptions } from './database'
38
+ export {
39
+ type Change,
40
+ type ColumnSpec,
41
+ diffSchemas,
42
+ introspect,
43
+ loadTables,
44
+ migrationSql,
45
+ type RenameCandidate,
46
+ renameCandidates,
47
+ type TableSpec,
48
+ tableSpec,
49
+ } from './differ'
31
50
  export { decrypt, encrypt, setEncryptionKey } from './encryption'
32
51
  export { isRetryable, QueryError, RowCountError, SerializationError, UniqueViolationError } from './errors'
33
52
  export { Factory, type FactoryContext, type FactoryValues, factory, isSeeder, type Seeder, seeder } from './factory'
34
53
  export { Fake } from './fake'
35
54
  export { addMigrations, FRAMEWORK_MIGRATIONS, type MigrationStatus, Migrator, parseMigration } from './migrator'
36
55
  export { between, eq, gt, gte, ilike, inList, isNull, like, lt, lte, ne, not, notIn, notNull, Op } from './operators'
37
- export { DatabaseProvider } from './provider'
56
+ export { DatabaseProvider, describeTables } from './provider'
38
57
  export { type Page, Query, type Where } from './query'
39
58
  export { belongsTo, hasMany, preload } from './relations'
40
59
  export { Repository, type RepositoryApi } from './repository'
package/src/provider.ts CHANGED
@@ -1,12 +1,34 @@
1
1
  import { HEALTH_CHECKS, healthCheck, Logger, ServiceProvider } from '@cslug/core'
2
2
  import { databaseCommands } from './commands'
3
3
  import { Database, type DatabaseConfig } from './database'
4
+ import { loadTables } from './differ'
4
5
  import { setEncryptionKey } from './encryption'
5
6
 
7
+ /** The tables exported by `app/tables/*.ts` (`cslug describe tables`): columns, keys, indexes, references. */
8
+ export async function describeTables(rootDir: string) {
9
+ const tables = await loadTables(rootDir)
10
+ return tables.map((t) => ({
11
+ name: t.name,
12
+ primaryKey: t.primaryKey,
13
+ columns: Object.entries(t.columns).map(([key, { def }]) => ({
14
+ name: t.sqlNames.get(key),
15
+ key,
16
+ type: def.sqlType,
17
+ nullable: def.nullable,
18
+ ...(def.unique ? { unique: true } : {}),
19
+ ...(def.oneOf ? { oneOf: def.oneOf } : {}),
20
+ ...(def.defaultSql ? { default: def.defaultSql } : {}),
21
+ ...(def.references ? { references: `${def.references.table().name}.${def.references.column}` } : {}),
22
+ })),
23
+ indexes: t.indexes,
24
+ }))
25
+ }
26
+
6
27
  /** Binds `Database` from `config('database')`, checks the connection at boot, closes the pool at shutdown. */
7
28
  export class DatabaseProvider extends ServiceProvider {
8
29
  register() {
9
30
  this.commands(databaseCommands)
31
+ this.describe('tables', () => describeTables(this.app.rootDir))
10
32
  setEncryptionKey(this.app.config<string | undefined>('app.key'))
11
33
  this.app.singleton(Database, (c) => {
12
34
  const config = this.app.config<DatabaseConfig | undefined>('database')