@cslug/database 0.5.0 → 0.6.0
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 +13 -6
- package/package.json +2 -2
- package/src/columns.ts +26 -0
- package/src/database.ts +3 -3
- package/src/differ.ts +104 -16
- package/src/index.ts +3 -0
- package/src/provider.ts +2 -0
- package/src/query.ts +26 -7
- package/src/repository.ts +10 -3
- package/src/table.ts +62 -12
package/docs/api.md
CHANGED
|
@@ -13,18 +13,23 @@
|
|
|
13
13
|
| `date()` | `date` | `'YYYY-MM-DD'` |
|
|
14
14
|
| `timestamp()` | `timestamptz` | `Date` |
|
|
15
15
|
| `jsonb<T>()` / `translated()` | `jsonb` | `T` / `{ fr?, en?, … }` |
|
|
16
|
+
| `custom<T>(sqlType)` | any type (`tsvector`, `inet`…) | `T` (default `string`), as the driver returns it |
|
|
16
17
|
| `amount()` / `currency()` | `bigint` / `char(3)` | money |
|
|
17
18
|
| `shortCode('ALB')` | `text unique` | `ALB-7K2Q9F`, generated |
|
|
18
19
|
| `timestamps()` / `softDeletes()` | `created_at`, `updated_at` / `deleted_at` | `Date` / `Date \| null` |
|
|
19
20
|
|
|
20
21
|
Modifiers: `.nullable()` (columns are NOT NULL otherwise), `.default(v)`, `.defaultSql('now()')`, `.unique()`,
|
|
21
|
-
`.references(() => table, { onDelete })`, `.check(sql\`…\`)`.
|
|
22
|
+
`.references(() => table, { onDelete })`, `.check(sql\`…\`)`, `.generatedAs((c) => sql)` (`generated always as (…)
|
|
23
|
+
stored`; `c(key)` quotes a sibling's SQL name; never written by inserts or updates; not in `NewRow`), `.hidden()` (left
|
|
24
|
+
out of selects, `RETURNING` and `Row`). Types: `Generated`, `Hidden`.
|
|
22
25
|
|
|
23
26
|
## Tables
|
|
24
27
|
|
|
25
|
-
`table(name, columns, { indexes: (t) => [t.index('a', 'b'), t.unique('c')
|
|
26
|
-
`c.<key>` (column refs for the sql tag), `star`,
|
|
27
|
-
`
|
|
28
|
+
`table(name, columns, { indexes: (t) => [t.index('a', 'b'), t.unique('c'), t.using('gin', 'search'),
|
|
29
|
+
t.using('gin', ['name', 'gin_trgm_ops'])] })` → `Table` with: `c.<key>` (column refs for the sql tag), `star`,
|
|
30
|
+
`selection` (`star`, or the visible columns when some are hidden), `generatedSql`, `sqlNames`, `primaryKey`,
|
|
31
|
+
`softDeletes`, `fromDb(row, extras?)`, `toDb(values)` (generated columns skipped). `IndexDef` has `using` and `ops`
|
|
32
|
+
(an operator class per column, `null` for the default). Types: `Row<typeof t>`, `NewRow<typeof t>`. Keys are camelCase in TS, snake_case in SQL.
|
|
28
33
|
|
|
29
34
|
Reading converts driver values: `date` → `'YYYY-MM-DD'`, `bigint` → bigint, `numeric` → string, `char(n)` trimmed.
|
|
30
35
|
|
|
@@ -77,6 +82,8 @@ Binds `Database` from `config('database')`, pings at boot, closes at shutdown.
|
|
|
77
82
|
| `where({ key: value \| null \| op })` | AND of conditions; `null` → IS NULL; `undefined` keys ignored (so `...(cond && {…})` works). Keys and value types are checked against the table |
|
|
78
83
|
| operators | `eq ne gt gte lt lte between inList notIn like ilike isNull notNull not(op)`. `inList([])` matches nothing |
|
|
79
84
|
| `orWhere({...})` / `whereSql(sql\`…\`)` | OR group / raw condition |
|
|
85
|
+
| `orderBySql(sql\`…\`)` | A raw sort term, after the others |
|
|
86
|
+
| `selectSql(name, sql<V>\`…\`)` | A computed value on each row: `Query<T, R & { name: V }>` (as the driver returns it) |
|
|
80
87
|
| `orderBy(key, 'asc' \| 'desc', { nulls: 'first' \| 'last' })` | Chainable |
|
|
81
88
|
| `limit`, `offset`, `select(...keys)` | `select` narrows the row type to `Pick<Row, K>` |
|
|
82
89
|
| `lockForUpdate({ skipLocked?, noWait? })` | Must be inside a transaction (clear error otherwise) |
|
|
@@ -134,9 +141,9 @@ prints the same changes (and the SQL with `--sql`) without writing a file.
|
|
|
134
141
|
| | |
|
|
135
142
|
|---|---|
|
|
136
143
|
| `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) |
|
|
144
|
+
| `tableSpec(table)` / `introspect(db)` | Both sides in one shape (`TableSpec`): columns (type as `format_type()` reports it, nullability, default, generated expression + hash), unique, check (`oneOf`) and foreign-key constraints, indexes (columns, method, operator classes). `introspect` reads the `public` schema and skips `cslug_*` tables (packages migrate those) |
|
|
138
145
|
| `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 |
|
|
146
|
+
| `diffSchemas(desired, actual, renames?)` | `Change[]` (`{ table, label, up, down, warning? }`): new tables (referenced ones first), added / dropped / renamed columns, type, nullability and default changes, generated expressions (`set expression`, from the hash in the column comment; a column that becomes or stops being generated is dropped and added again, with its indexes), constraints and indexes compared by name and definition (method and operator classes included), dropped tables |
|
|
140
147
|
| `migrationSql(changes)` | `-- up` in order, `-- down` in reverse |
|
|
141
148
|
|
|
142
149
|
Constraint names follow PostgreSQL's defaults (`t_col_key`, `t_col_fkey`, `t_col_check`), so a table created by a
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cslug/database",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
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.
|
|
31
|
+
"@cslug/core": "0.6.0"
|
|
32
32
|
}
|
|
33
33
|
}
|
package/src/columns.ts
CHANGED
|
@@ -32,8 +32,20 @@ export type ColumnDef = {
|
|
|
32
32
|
touch?: boolean
|
|
33
33
|
/** Stored encrypted (AES-256-GCM with APP_KEY); decrypted on read; cannot be queried by value. */
|
|
34
34
|
encrypted?: boolean
|
|
35
|
+
/**
|
|
36
|
+
* A stored generated column: the SQL expression, built from the other columns' quoted SQL names
|
|
37
|
+
* (`generated always as (…) stored`). The app never writes it.
|
|
38
|
+
*/
|
|
39
|
+
generated?: (column: (key: string) => string) => string
|
|
40
|
+
/** Left out of selects and of `Row` (a search vector, a large derived value); still queryable in SQL. */
|
|
41
|
+
hidden?: boolean
|
|
35
42
|
}
|
|
36
43
|
|
|
44
|
+
/** A column the database computes (`generatedAs`): never part of an insert or update. */
|
|
45
|
+
export type Generated = { readonly _generated: true }
|
|
46
|
+
/** A column left out of selects and rows (`hidden()`). */
|
|
47
|
+
export type Hidden = { readonly _hidden: true }
|
|
48
|
+
|
|
37
49
|
/**
|
|
38
50
|
* A column. `T` is its TypeScript value type; `N` whether it accepts null; `D` whether inserts may omit it
|
|
39
51
|
* (it has a default or is generated).
|
|
@@ -73,6 +85,18 @@ export class Column<T, N extends boolean = false, D extends boolean = false> {
|
|
|
73
85
|
check(expression: SqlFragment<unknown>): this {
|
|
74
86
|
return this.with({ check: expression }) as this
|
|
75
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* Computed by PostgreSQL from other columns of the row: `generated always as (…) stored`.
|
|
90
|
+
* `column(key)` gives a sibling's quoted SQL name: `numeric(10, 2).generatedAs((c) => `${c('price')} * 1.2`)`.
|
|
91
|
+
* Inserts and updates leave it out; the migration differ creates it and follows expression changes.
|
|
92
|
+
*/
|
|
93
|
+
generatedAs(expression: (column: (key: string) => string) => string): Column<T, N, true> & Generated {
|
|
94
|
+
return this.with<T, N, true>({ generated: expression }) as Column<T, N, true> & Generated
|
|
95
|
+
}
|
|
96
|
+
/** Leave it out of selects and of `Row` (it stays usable in `whereSql`, `orderBySql` and indexes). */
|
|
97
|
+
hidden(): this & Hidden {
|
|
98
|
+
return this.with({ hidden: true }) as this & Hidden
|
|
99
|
+
}
|
|
76
100
|
}
|
|
77
101
|
|
|
78
102
|
/** A text column restricted to values: typed as the union and checked by a CHECK constraint. */
|
|
@@ -122,6 +146,8 @@ export const date = () => col<string>('date', 'date')
|
|
|
122
146
|
/** An instant, `timestamptz` (stored in UTC), as a `Date`. */
|
|
123
147
|
export const timestamp = () => col<Date>('timestamp', 'timestamptz')
|
|
124
148
|
export const jsonb = <T>() => col<T>('jsonb', 'jsonb')
|
|
149
|
+
/** Any other PostgreSQL type, read as the driver returns it: `custom<string>('tsvector')`, `custom('inet')`. */
|
|
150
|
+
export const custom = <T = string>(sqlType: string) => col<T>('text', sqlType)
|
|
125
151
|
/** Money in minor units. */
|
|
126
152
|
export const amount = () => col<bigint>('bigint', 'bigint')
|
|
127
153
|
/** ISO 4217 code. */
|
package/src/database.ts
CHANGED
|
@@ -50,10 +50,10 @@ export abstract class Queryable {
|
|
|
50
50
|
|
|
51
51
|
/** Run a query; rows keyed in camelCase, or mapped and typed by `table`. */
|
|
52
52
|
async many<T>(query: SqlFragment<T>): Promise<T[]>
|
|
53
|
-
async many<T extends Table>(query: SqlFragment<unknown>, table: T): Promise<Row<T>[]>
|
|
54
|
-
async many(query: SqlFragment<unknown>, table?: Table): Promise<unknown[]> {
|
|
53
|
+
async many<T extends Table>(query: SqlFragment<unknown>, table: T, extras?: readonly string[]): Promise<Row<T>[]>
|
|
54
|
+
async many(query: SqlFragment<unknown>, table?: Table, extras: readonly string[] = []): Promise<unknown[]> {
|
|
55
55
|
const rows = await this.run(query)
|
|
56
|
-
return table ? rows.map((r) => table.fromDb(r)) : rows.map(camelKeys)
|
|
56
|
+
return table ? rows.map((r) => table.fromDb(r, extras)) : rows.map(camelKeys)
|
|
57
57
|
}
|
|
58
58
|
|
|
59
59
|
/** Exactly one row, else `RowCountError`. */
|
package/src/differ.ts
CHANGED
|
@@ -19,7 +19,16 @@ export async function loadTables(rootDir: string): Promise<Table[]> {
|
|
|
19
19
|
|
|
20
20
|
// ── one shape for both sides: what the tables want and what the database has ─────────────────────────
|
|
21
21
|
|
|
22
|
-
export type ColumnSpec = {
|
|
22
|
+
export type ColumnSpec = {
|
|
23
|
+
name: string
|
|
24
|
+
type: string
|
|
25
|
+
nullable: boolean
|
|
26
|
+
default?: string
|
|
27
|
+
primary?: boolean
|
|
28
|
+
/** `generated always as (expression) stored`; `hash` (kept in the column comment) tells when it changed. */
|
|
29
|
+
generated?: { expression: string; hash: string }
|
|
30
|
+
}
|
|
31
|
+
type IndexSpec = { name: string; columns: string[]; unique: boolean; using?: string; ops?: (string | null)[] }
|
|
23
32
|
/** Constraints and indexes by name. Names follow PostgreSQL's defaults (`t_col_key`, `t_col_fkey`, `t_col_check`). */
|
|
24
33
|
export type TableSpec = {
|
|
25
34
|
name: string
|
|
@@ -27,9 +36,13 @@ export type TableSpec = {
|
|
|
27
36
|
uniques: { name: string; column: string }[]
|
|
28
37
|
checks: { name: string; column: string; values: string[] }[]
|
|
29
38
|
foreignKeys: { name: string; column: string; table: string; references: string; onDelete?: string }[]
|
|
30
|
-
indexes:
|
|
39
|
+
indexes: IndexSpec[]
|
|
31
40
|
}
|
|
32
41
|
|
|
42
|
+
/** Short hash of a generated expression, kept in the column comment (`cslug:generated <hash>`). */
|
|
43
|
+
const hashOf = (expression: string) => new Bun.CryptoHasher('sha1').update(expression).digest('hex').slice(0, 12)
|
|
44
|
+
const COMMENT = /^cslug:generated (\w+)$/
|
|
45
|
+
|
|
33
46
|
/** `timestamptz` → `timestamp with time zone`, as `format_type()` reports it. */
|
|
34
47
|
const TYPES: [RegExp, string][] = [
|
|
35
48
|
[/^timestamptz$/, 'timestamp with time zone'],
|
|
@@ -52,17 +65,25 @@ export function tableSpec(t: Table): TableSpec {
|
|
|
52
65
|
uniques: [],
|
|
53
66
|
checks: [],
|
|
54
67
|
foreignKeys: [],
|
|
55
|
-
indexes:
|
|
68
|
+
indexes: t.indexes.map((i) => ({
|
|
69
|
+
name: i.name,
|
|
70
|
+
columns: i.columns,
|
|
71
|
+
unique: i.unique,
|
|
72
|
+
...(i.using && i.using !== 'btree' ? { using: i.using } : {}),
|
|
73
|
+
...(i.ops?.some(Boolean) ? { ops: i.ops } : {}),
|
|
74
|
+
})),
|
|
56
75
|
}
|
|
57
76
|
for (const [key, { def }] of Object.entries(t.columns)) {
|
|
58
77
|
const name = t.sqlNames.get(key) as string
|
|
59
78
|
const value = def.defaultSql ?? (def.defaultValue === undefined ? undefined : literal(def.defaultValue))
|
|
79
|
+
const generated = t.generatedSql.get(key)
|
|
60
80
|
spec.columns.push({
|
|
61
81
|
name,
|
|
62
82
|
type: pgType(def.sqlType),
|
|
63
83
|
nullable: def.nullable,
|
|
64
|
-
...(value === undefined ? {} : { default: value }),
|
|
84
|
+
...(value === undefined || generated ? {} : { default: value }),
|
|
65
85
|
...(def.primary ? { primary: true } : {}),
|
|
86
|
+
...(generated ? { generated: { expression: generated, hash: hashOf(generated) } } : {}),
|
|
66
87
|
})
|
|
67
88
|
if (def.unique) spec.uniques.push({ name: `${t.name}_${name}_key`, column: name })
|
|
68
89
|
if (def.oneOf) spec.checks.push({ name: `${t.name}_${name}_check`, column: name, values: [...def.oneOf] })
|
|
@@ -87,9 +108,12 @@ export async function introspect(db: Database): Promise<TableSpec[]> {
|
|
|
87
108
|
type: string
|
|
88
109
|
nullable: boolean
|
|
89
110
|
default: string | null
|
|
111
|
+
generated: string
|
|
112
|
+
comment: string | null
|
|
90
113
|
}>(
|
|
91
114
|
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
|
|
115
|
+
not a.attnotnull as nullable, pg_get_expr(d.adbin, d.adrelid) as default, a.attgenerated::text as generated,
|
|
116
|
+
col_description(c.oid, a.attnum) as comment
|
|
93
117
|
from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
94
118
|
join pg_attribute a on a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped
|
|
95
119
|
left join pg_attrdef d on d.adrelid = c.oid and d.adnum = a.attnum
|
|
@@ -102,11 +126,22 @@ export async function introspect(db: Database): Promise<TableSpec[]> {
|
|
|
102
126
|
from pg_constraint k join pg_class c on c.oid = k.conrelid join pg_namespace n on n.oid = c.relnamespace
|
|
103
127
|
where ${own}`,
|
|
104
128
|
)
|
|
105
|
-
const indexes = await db.many<{
|
|
106
|
-
|
|
129
|
+
const indexes = await db.many<{
|
|
130
|
+
table: string
|
|
131
|
+
name: string
|
|
132
|
+
unique: boolean
|
|
133
|
+
columns: string[]
|
|
134
|
+
using: string
|
|
135
|
+
ops: (string | null)[]
|
|
136
|
+
}>(
|
|
137
|
+
sql`select c.relname as table, i.relname as name, x.indisunique as unique, am.amname::text as using,
|
|
107
138
|
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
|
|
139
|
+
join pg_attribute a on a.attrelid = c.oid and a.attnum = k.n order by k.o) as columns,
|
|
140
|
+
array(select case when oc.opcdefault then null else oc.opcname::text end
|
|
141
|
+
from unnest(x.indclass::oid[]) with ordinality k(oid, o) join pg_opclass oc on oc.oid = k.oid
|
|
142
|
+
order by k.o) as ops
|
|
109
143
|
from pg_index x join pg_class i on i.oid = x.indexrelid join pg_class c on c.oid = x.indrelid
|
|
144
|
+
join pg_am am on am.oid = i.relam
|
|
110
145
|
join pg_namespace n on n.oid = c.relnamespace
|
|
111
146
|
where ${own} and not exists (select 1 from pg_constraint k where k.conindid = x.indexrelid)`,
|
|
112
147
|
)
|
|
@@ -121,7 +156,11 @@ export async function introspect(db: Database): Promise<TableSpec[]> {
|
|
|
121
156
|
name: c.name,
|
|
122
157
|
type: c.type,
|
|
123
158
|
nullable: c.nullable,
|
|
124
|
-
...(c.
|
|
159
|
+
...(c.generated === 's'
|
|
160
|
+
? { generated: { expression: c.default ?? '', hash: COMMENT.exec(c.comment ?? '')?.[1] ?? '' } }
|
|
161
|
+
: c.default === null
|
|
162
|
+
? {}
|
|
163
|
+
: { default: c.default }),
|
|
125
164
|
})
|
|
126
165
|
for (const k of constraints) {
|
|
127
166
|
const t = of(k.table)
|
|
@@ -144,7 +183,14 @@ export async function introspect(db: Database): Promise<TableSpec[]> {
|
|
|
144
183
|
...(fk[3] ? { onDelete: fk[3].toLowerCase() } : {}),
|
|
145
184
|
})
|
|
146
185
|
}
|
|
147
|
-
for (const i of indexes)
|
|
186
|
+
for (const i of indexes)
|
|
187
|
+
of(i.table).indexes.push({
|
|
188
|
+
name: i.name,
|
|
189
|
+
columns: i.columns,
|
|
190
|
+
unique: i.unique,
|
|
191
|
+
...(i.using !== 'btree' ? { using: i.using } : {}),
|
|
192
|
+
...(i.ops.some(Boolean) ? { ops: i.ops } : {}),
|
|
193
|
+
})
|
|
148
194
|
return [...tables.values()]
|
|
149
195
|
}
|
|
150
196
|
|
|
@@ -160,6 +206,7 @@ const columnSql = (t: TableSpec, c: ColumnSpec) => {
|
|
|
160
206
|
const fk = t.foreignKeys.find((k) => k.column === c.name)
|
|
161
207
|
return [
|
|
162
208
|
`${c.name} ${c.type}`,
|
|
209
|
+
c.generated ? `generated always as (${c.generated.expression}) stored` : '',
|
|
163
210
|
c.primary ? 'primary key' : c.nullable ? '' : 'not null',
|
|
164
211
|
c.default === undefined ? '' : `default ${c.default}`,
|
|
165
212
|
t.uniques.some((u) => u.column === c.name) ? 'unique' : '',
|
|
@@ -169,10 +216,21 @@ const columnSql = (t: TableSpec, c: ColumnSpec) => {
|
|
|
169
216
|
.filter(Boolean)
|
|
170
217
|
.join(' ')
|
|
171
218
|
}
|
|
172
|
-
const indexSql = (t: string, i:
|
|
173
|
-
`create ${i.unique ? 'unique ' : ''}index ${i.name} on ${t}
|
|
219
|
+
const indexSql = (t: string, i: IndexSpec) =>
|
|
220
|
+
`create ${i.unique ? 'unique ' : ''}index ${i.name} on ${t}${i.using ? ` using ${i.using}` : ''} (${i.columns
|
|
221
|
+
.map((c, n) => (i.ops?.[n] ? `${c} ${i.ops[n]}` : c))
|
|
222
|
+
.join(', ')});`
|
|
223
|
+
const sameIndex = (a: IndexSpec, b: IndexSpec) =>
|
|
224
|
+
a.unique === b.unique &&
|
|
225
|
+
a.columns.join() === b.columns.join() &&
|
|
226
|
+
(a.using ?? 'btree') === (b.using ?? 'btree') &&
|
|
227
|
+
(a.ops ?? []).map((o) => o ?? '').join() === (b.ops ?? []).map((o) => o ?? '').join()
|
|
228
|
+
/** The comment that records a generated column's expression hash (`null` clears it). */
|
|
229
|
+
const commentSql = (t: string, c: ColumnSpec) =>
|
|
230
|
+
`comment on column ${t}.${c.name} is ${c.generated ? `'cslug:generated ${c.generated.hash}'` : 'null'};`
|
|
174
231
|
const createTable = (t: TableSpec) => [
|
|
175
232
|
`create table ${t.name} (\n${t.columns.map((c) => ` ${columnSql(t, c)}`).join(',\n')}\n);`,
|
|
233
|
+
...t.columns.filter((c) => c.generated).map((c) => commentSql(t.name, c)),
|
|
176
234
|
...t.indexes.map((i) => indexSql(t.name, i)),
|
|
177
235
|
]
|
|
178
236
|
const byName = <T extends { name: string }>(list: T[]) => new Map(list.map((x) => [x.name, x]))
|
|
@@ -243,16 +301,46 @@ export function diffSchemas(desired: TableSpec[], actual: TableSpec[], renames:
|
|
|
243
301
|
if (!was) {
|
|
244
302
|
changes.push({
|
|
245
303
|
table: t.name,
|
|
246
|
-
label: `+ column ${t.name}.${c.name} ${c.type}`,
|
|
247
|
-
up: [`${a} add column ${columnSql(t, c)}
|
|
304
|
+
label: `+ column ${t.name}.${c.name} ${c.type}${c.generated ? ' (generated)' : ''}`,
|
|
305
|
+
up: [`${a} add column ${columnSql(t, c)};`, ...(c.generated ? [commentSql(t.name, c)] : [])],
|
|
248
306
|
down: [`${a} drop column ${c.name};`],
|
|
249
|
-
...(!c.nullable && c.default === undefined
|
|
307
|
+
...(!c.nullable && c.default === undefined && !c.generated
|
|
250
308
|
? { warning: `${t.name}.${c.name} is not null without a default: fails if the table has rows` }
|
|
251
309
|
: {}),
|
|
252
310
|
})
|
|
253
311
|
continue
|
|
254
312
|
}
|
|
255
313
|
const col = `${a} alter column ${c.name}`
|
|
314
|
+
if (!!was.generated !== !!c.generated) {
|
|
315
|
+
// a column cannot become generated in place: drop it and add it again (its indexes go with it)
|
|
316
|
+
const indexes = (spec: TableSpec) => spec.indexes.filter((i) => i.columns.includes(c.name))
|
|
317
|
+
changes.push({
|
|
318
|
+
table: t.name,
|
|
319
|
+
label: `~ column ${t.name}.${c.name} ${c.generated ? 'now generated' : 'no longer generated'}`,
|
|
320
|
+
up: [
|
|
321
|
+
`${a} drop column ${c.name};`,
|
|
322
|
+
`${a} add column ${columnSql(t, c)};`,
|
|
323
|
+
...(c.generated ? [commentSql(t.name, c)] : []),
|
|
324
|
+
...indexes(t).map((i) => indexSql(t.name, i)),
|
|
325
|
+
],
|
|
326
|
+
down: [
|
|
327
|
+
`${a} drop column ${c.name};`,
|
|
328
|
+
`${a} add column ${columnSql(old, was)};`,
|
|
329
|
+
...(was.generated ? [commentSql(t.name, was)] : []),
|
|
330
|
+
...indexes(old).map((i) => indexSql(t.name, i)),
|
|
331
|
+
],
|
|
332
|
+
warning: `${t.name}.${c.name} is dropped and added again: its values${c.generated ? '' : ' (computed until now)'} are lost`,
|
|
333
|
+
})
|
|
334
|
+
continue
|
|
335
|
+
}
|
|
336
|
+
if (c.generated && was.generated && c.generated.hash !== was.generated.hash)
|
|
337
|
+
changes.push({
|
|
338
|
+
table: t.name,
|
|
339
|
+
label: `~ column ${t.name}.${c.name} generated expression`,
|
|
340
|
+
up: [`${col} set expression as (${c.generated.expression});`, commentSql(t.name, c)],
|
|
341
|
+
down: [`${col} set expression as (${was.generated.expression});`, commentSql(t.name, was)],
|
|
342
|
+
warning: `${t.name}.${c.name}: changing a generated expression rewrites the table (PostgreSQL 17+)`,
|
|
343
|
+
})
|
|
256
344
|
if (was.type !== c.type)
|
|
257
345
|
changes.push({
|
|
258
346
|
table: t.name,
|
|
@@ -356,7 +444,7 @@ function constraintChanges(t: TableSpec, old: TableSpec): Change[] {
|
|
|
356
444
|
const wasIndex = byName(old.indexes)
|
|
357
445
|
for (const i of t.indexes) {
|
|
358
446
|
const y = wasIndex.get(i.name)
|
|
359
|
-
if (y && y
|
|
447
|
+
if (y && sameIndex(y, i)) continue
|
|
360
448
|
changes.push({
|
|
361
449
|
table: t.name,
|
|
362
450
|
label: `${y ? '~' : '+'} index ${i.name}`,
|
package/src/index.ts
CHANGED
package/src/provider.ts
CHANGED
|
@@ -19,6 +19,8 @@ export async function describeTables(rootDir: string) {
|
|
|
19
19
|
...(def.oneOf ? { oneOf: def.oneOf } : {}),
|
|
20
20
|
...(def.defaultSql ? { default: def.defaultSql } : {}),
|
|
21
21
|
...(def.references ? { references: `${def.references.table().name}.${def.references.column}` } : {}),
|
|
22
|
+
...(def.generated ? { generated: true } : {}),
|
|
23
|
+
...(def.hidden ? { hidden: true } : {}),
|
|
22
24
|
})),
|
|
23
25
|
indexes: t.indexes,
|
|
24
26
|
}))
|
package/src/query.ts
CHANGED
|
@@ -10,7 +10,7 @@ export type Where<T extends Table> = {
|
|
|
10
10
|
[K in keyof Row<T>]?: Row<T>[K] | Op<NonNullable<Row<T>[K]>> | (null extends Row<T>[K] ? null : never) | undefined
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
-
type Order = { key: string; dir: 'asc' | 'desc'; nulls?: 'first' | 'last' }
|
|
13
|
+
type Order = { key: string; dir: 'asc' | 'desc'; nulls?: 'first' | 'last' } | { sql: SqlFragment<unknown> }
|
|
14
14
|
type Trashed = 'without' | 'with' | 'only'
|
|
15
15
|
|
|
16
16
|
export type Page<R> = { data: R[]; meta: { page: number; perPage: number; total: number; lastPage: number } }
|
|
@@ -49,6 +49,8 @@ export class Query<T extends Table, R = Row<T>> {
|
|
|
49
49
|
columns?: string[]
|
|
50
50
|
lock?: 'update' | 'update skip locked' | 'update nowait'
|
|
51
51
|
trashed: Trashed
|
|
52
|
+
/** Computed values added to each row: `[name, expression]`. */
|
|
53
|
+
extras?: [string, SqlFragment<unknown>][]
|
|
52
54
|
} = { ands: [], ors: [], order: [], trashed: 'without' },
|
|
53
55
|
) {}
|
|
54
56
|
|
|
@@ -80,6 +82,19 @@ export class Query<T extends Table, R = Row<T>> {
|
|
|
80
82
|
return this.with({ order: [...this.state.order, { key, dir, nulls: options.nulls }] })
|
|
81
83
|
}
|
|
82
84
|
|
|
85
|
+
/** A raw ORDER BY term, after the others: `.orderBySql(sql\`ts_rank_cd(${t.c.search}, ${q}) desc\`)`. */
|
|
86
|
+
orderBySql(term: SqlFragment<unknown>): Query<T, R> {
|
|
87
|
+
return this.with({ order: [...this.state.order, { sql: term }] })
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Add a computed value to each row, as `name`: `.selectSql('rank', sql<number>\`ts_rank_cd(…)\`)`. The value
|
|
92
|
+
* comes as the driver returns it (no column conversion).
|
|
93
|
+
*/
|
|
94
|
+
selectSql<K extends string, V = unknown>(name: K, expression: SqlFragment<V>): Query<T, R & { [P in K]: V }> {
|
|
95
|
+
return this.with<R & { [P in K]: V }>({ extras: [...(this.state.extras ?? []), [name, expression]] })
|
|
96
|
+
}
|
|
97
|
+
|
|
83
98
|
limit(n: number): Query<T, R> {
|
|
84
99
|
return this.with({ limit: n })
|
|
85
100
|
}
|
|
@@ -132,14 +147,17 @@ export class Query<T extends Table, R = Row<T>> {
|
|
|
132
147
|
/** The SELECT statement. */
|
|
133
148
|
toSql(): SqlFragment<unknown> {
|
|
134
149
|
const t = this.table
|
|
135
|
-
const
|
|
150
|
+
const base = this.state.columns
|
|
136
151
|
? sql.join(this.state.columns.map((k) => (t.c as Record<string, unknown>)[k]))
|
|
137
|
-
: t.
|
|
152
|
+
: sql`${t.selection}`
|
|
153
|
+
const extras = (this.state.extras ?? []).map(([name, expression]) => sql`${expression} as ${sql.ident(name)}`)
|
|
154
|
+
const cols = extras.length ? sql.join([base, ...extras]) : base
|
|
138
155
|
const order = this.state.order.length
|
|
139
156
|
? sql` order by ${sql.join(
|
|
140
|
-
this.state.order.map(
|
|
141
|
-
|
|
142
|
-
|
|
157
|
+
this.state.order.map((o) =>
|
|
158
|
+
'sql' in o
|
|
159
|
+
? o.sql
|
|
160
|
+
: sql`${(t.c as Record<string, unknown>)[o.key]} ${sql.raw(o.dir)}${o.nulls ? sql.raw(` nulls ${o.nulls}`) : sql.empty}`,
|
|
143
161
|
),
|
|
144
162
|
)}`
|
|
145
163
|
: sql.empty
|
|
@@ -158,7 +176,8 @@ export class Query<T extends Table, R = Row<T>> {
|
|
|
158
176
|
}
|
|
159
177
|
|
|
160
178
|
async all(): Promise<R[]> {
|
|
161
|
-
|
|
179
|
+
const extras = (this.state.extras ?? []).map(([name]) => name)
|
|
180
|
+
return (await this.db().many(this.toSql(), this.table, extras)) as R[]
|
|
162
181
|
}
|
|
163
182
|
|
|
164
183
|
async first(): Promise<R | null> {
|
package/src/repository.ts
CHANGED
|
@@ -124,6 +124,10 @@ export function Repository<T extends Table>(table: T) {
|
|
|
124
124
|
protected prepare(values: Record<string, unknown>): Record<string, unknown> {
|
|
125
125
|
const out = { ...values }
|
|
126
126
|
for (const [key, column] of Object.entries(table.columns)) {
|
|
127
|
+
if (column.def.generated) {
|
|
128
|
+
delete out[key] // computed by PostgreSQL: never written
|
|
129
|
+
continue
|
|
130
|
+
}
|
|
127
131
|
if (out[key] !== undefined) continue
|
|
128
132
|
if (column.def.generate) out[key] = column.def.generate()
|
|
129
133
|
else if (column.def.defaultValue !== undefined) out[key] = column.def.defaultValue
|
|
@@ -147,13 +151,16 @@ export function Repository<T extends Table>(table: T) {
|
|
|
147
151
|
keys.map((k) => (p[k] === undefined ? sql`default` : writeValue(p[k], table.columns[k] as never))),
|
|
148
152
|
)})`,
|
|
149
153
|
)
|
|
150
|
-
return this.exec.many(
|
|
154
|
+
return this.exec.many(
|
|
155
|
+
sql`insert into ${table} (${names}) values ${sql.join(rows)} returning ${table.selection}`,
|
|
156
|
+
table,
|
|
157
|
+
)
|
|
151
158
|
}
|
|
152
159
|
|
|
153
160
|
async update(id: unknown, values: Partial<Row<T>>) {
|
|
154
161
|
const where = whereSql(table, this.byId(id))
|
|
155
162
|
const row = await this.exec.maybeOne(
|
|
156
|
-
sql`update ${table} set ${setClause(table, values as Record<string, unknown>)} where ${where} returning
|
|
163
|
+
sql`update ${table} set ${setClause(table, values as Record<string, unknown>)} where ${where} returning ${table.selection}`,
|
|
157
164
|
table,
|
|
158
165
|
)
|
|
159
166
|
if (!row) throw new NotFoundError(this.resource, String(id))
|
|
@@ -180,7 +187,7 @@ export function Repository<T extends Table>(table: T) {
|
|
|
180
187
|
const row = await this.exec.maybeOne(
|
|
181
188
|
sql`insert into ${table} (${sql.join(keys.map((k) => sql.ident(table.sqlNames.get(k) as string)))})
|
|
182
189
|
values (${sql.join(keys.map((k) => writeValue(p[k], table.columns[k] as never)))})
|
|
183
|
-
on conflict (${conflict}) ${action} returning
|
|
190
|
+
on conflict (${conflict}) ${action} returning ${table.selection}`,
|
|
184
191
|
table,
|
|
185
192
|
)
|
|
186
193
|
return (
|
package/src/table.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AnyColumn, Column } from './columns'
|
|
1
|
+
import type { AnyColumn, Column, Generated, Hidden } from './columns'
|
|
2
2
|
import { decrypt } from './encryption'
|
|
3
3
|
import { IDENT, quote, type SqlIdentifier } from './sql'
|
|
4
4
|
|
|
@@ -10,13 +10,21 @@ type OptionalKeys<C extends Columns> = {
|
|
|
10
10
|
[K in keyof C]: C[K] extends Column<unknown, boolean, true> ? K : never
|
|
11
11
|
}[keyof C]
|
|
12
12
|
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
type HiddenKeys<C extends Columns> = { [K in keyof C]: C[K] extends Hidden ? K : never }[keyof C]
|
|
14
|
+
type GeneratedKeys<C extends Columns> = { [K in keyof C]: C[K] extends Generated ? K : never }[keyof C]
|
|
15
|
+
type Writable<C extends Columns> = Exclude<keyof C, GeneratedKeys<C>>
|
|
15
16
|
|
|
16
|
-
/** What
|
|
17
|
+
/** What a SELECT returns: every column but the hidden ones, nullable ones as `T | null`. */
|
|
18
|
+
export type Row<T extends Table> = Flatten<{
|
|
19
|
+
[K in Exclude<keyof T['columns'], HiddenKeys<T['columns']>>]: ValueOf<T['columns'][K]>
|
|
20
|
+
}>
|
|
21
|
+
|
|
22
|
+
/** What an INSERT needs: NOT NULL columns without a default are required; the rest optional; generated ones absent. */
|
|
17
23
|
export type NewRow<T extends Table> = Flatten<
|
|
18
|
-
{
|
|
19
|
-
[K in OptionalKeys<T['columns']
|
|
24
|
+
{
|
|
25
|
+
[K in Exclude<Writable<T['columns']>, OptionalKeys<T['columns']>>]: ValueOf<T['columns'][K]>
|
|
26
|
+
} & {
|
|
27
|
+
[K in Extract<Writable<T['columns']>, OptionalKeys<T['columns']>>]?: ValueOf<T['columns'][K]>
|
|
20
28
|
}
|
|
21
29
|
>
|
|
22
30
|
|
|
@@ -26,11 +34,17 @@ export const snake = (s: string) => s.replace(/[A-Z]/g, (c) => `_${c.toLowerCase
|
|
|
26
34
|
/** A column reference that renders as `"table"."column"` in the sql tag. */
|
|
27
35
|
export type ColumnRef = SqlIdentifier & { readonly name: string; readonly key: string; readonly table: string }
|
|
28
36
|
|
|
29
|
-
|
|
37
|
+
/**
|
|
38
|
+
* An index: its columns, and for other access methods than btree `using` (`gin`, `gist`, `brin`, `hash`) and an
|
|
39
|
+
* operator class per column (`gin_trgm_ops`; null for the default).
|
|
40
|
+
*/
|
|
41
|
+
export type IndexDef = { columns: string[]; unique: boolean; name: string; using?: string; ops?: (string | null)[] }
|
|
30
42
|
|
|
31
43
|
type IndexBuilder<C extends Columns> = {
|
|
32
44
|
index(...keys: (keyof C & string)[]): IndexDef
|
|
33
45
|
unique(...keys: (keyof C & string)[]): IndexDef
|
|
46
|
+
/** `t.using('gin', 'search')`, `t.using('gin', ['title', 'gin_trgm_ops'])`: `<table>_<columns>_<method>_idx`. */
|
|
47
|
+
using(method: string, ...keys: ((keyof C & string) | [keyof C & string, string])[]): IndexDef
|
|
34
48
|
}
|
|
35
49
|
|
|
36
50
|
/** A typed table: columns, keys and indexes; `table()` creates one. */
|
|
@@ -44,6 +58,10 @@ export class Table<C extends Columns = Columns> implements SqlIdentifier {
|
|
|
44
58
|
readonly sqlNames: ReadonlyMap<string, string>
|
|
45
59
|
readonly indexes: IndexDef[]
|
|
46
60
|
readonly primaryKey: string
|
|
61
|
+
/** What a SELECT lists: `"t".*`, or the visible columns when some are hidden. */
|
|
62
|
+
readonly selection: SqlIdentifier
|
|
63
|
+
/** Generated columns: TS key → their SQL expression. */
|
|
64
|
+
readonly generatedSql: ReadonlyMap<string, string>
|
|
47
65
|
|
|
48
66
|
constructor(
|
|
49
67
|
readonly name: string,
|
|
@@ -61,6 +79,26 @@ export class Table<C extends Columns = Columns> implements SqlIdentifier {
|
|
|
61
79
|
this.sqlNames = names
|
|
62
80
|
this.c = refs as Table<C>['c']
|
|
63
81
|
this.star = { [IDENT]: `${quote(name)}.*` }
|
|
82
|
+
const hidden = Object.entries(columns).filter(([, c]) => c.def.hidden)
|
|
83
|
+
this.selection = hidden.length
|
|
84
|
+
? {
|
|
85
|
+
[IDENT]: Object.keys(columns)
|
|
86
|
+
.filter((k) => !columns[k]?.def.hidden)
|
|
87
|
+
.map((k) => refs[k]?.[IDENT])
|
|
88
|
+
.join(', '),
|
|
89
|
+
}
|
|
90
|
+
: this.star
|
|
91
|
+
const generated = new Map<string, string>()
|
|
92
|
+
for (const [key, column] of Object.entries(columns))
|
|
93
|
+
if (column.def.generated)
|
|
94
|
+
generated.set(
|
|
95
|
+
key,
|
|
96
|
+
column.def.generated((k) => {
|
|
97
|
+
if (!(k in columns)) throw new Error(`${name}.${key}: generatedAs() refers to an unknown column "${k}"`)
|
|
98
|
+
return quote(snake(k))
|
|
99
|
+
}),
|
|
100
|
+
)
|
|
101
|
+
this.generatedSql = generated
|
|
64
102
|
this.primaryKey = Object.entries(columns).find(([, c]) => c.def.primary)?.[0] ?? 'id'
|
|
65
103
|
const builder: IndexBuilder<C> = {
|
|
66
104
|
index: (...keys) => ({
|
|
@@ -73,6 +111,17 @@ export class Table<C extends Columns = Columns> implements SqlIdentifier {
|
|
|
73
111
|
unique: true,
|
|
74
112
|
name: `${name}_${keys.map(snake).join('_')}_key`,
|
|
75
113
|
}),
|
|
114
|
+
using: (method, ...keys) => {
|
|
115
|
+
const cols = keys.map((k) => snake(Array.isArray(k) ? k[0] : k))
|
|
116
|
+
const ops = keys.map((k) => (Array.isArray(k) ? k[1] : null))
|
|
117
|
+
return {
|
|
118
|
+
columns: cols,
|
|
119
|
+
unique: false,
|
|
120
|
+
name: `${name}_${cols.join('_')}_${method}_idx`,
|
|
121
|
+
using: method,
|
|
122
|
+
...(ops.some(Boolean) ? { ops } : {}),
|
|
123
|
+
}
|
|
124
|
+
},
|
|
76
125
|
}
|
|
77
126
|
this.indexes = options.indexes?.(builder) ?? []
|
|
78
127
|
}
|
|
@@ -82,12 +131,13 @@ export class Table<C extends Columns = Columns> implements SqlIdentifier {
|
|
|
82
131
|
return 'deletedAt' in this.columns
|
|
83
132
|
}
|
|
84
133
|
|
|
85
|
-
/** A database row (snake_case, driver types) → the app row (camelCase, cslug types). */
|
|
86
|
-
fromDb(raw: Record<string, unknown
|
|
134
|
+
/** A database row (snake_case, driver types) → the app row (camelCase, cslug types); `extras` are copied as is. */
|
|
135
|
+
fromDb(raw: Record<string, unknown>, extras: readonly string[] = []): Row<this> {
|
|
87
136
|
const out: Record<string, unknown> = {}
|
|
137
|
+
for (const name of extras) out[name] = raw[name]
|
|
88
138
|
for (const [key, column] of Object.entries(this.columns)) {
|
|
89
139
|
const name = this.sqlNames.get(key) as string
|
|
90
|
-
if (!(name in raw)) continue
|
|
140
|
+
if (!(name in raw) || column.def.hidden) continue
|
|
91
141
|
const value = raw[name]
|
|
92
142
|
out[key] =
|
|
93
143
|
column.def.encrypted && typeof value === 'string' ? decrypt(value) : convertFromDb(value, column.def.kind)
|
|
@@ -95,12 +145,12 @@ export class Table<C extends Columns = Columns> implements SqlIdentifier {
|
|
|
95
145
|
return out as Row<this>
|
|
96
146
|
}
|
|
97
147
|
|
|
98
|
-
/** App values (camelCase) → `[sqlName, value]` pairs, for known columns only. */
|
|
148
|
+
/** App values (camelCase) → `[sqlName, value]` pairs, for known, writable (not generated) columns only. */
|
|
99
149
|
toDb(values: Record<string, unknown>): [string, unknown, AnyColumn][] {
|
|
100
150
|
const out: [string, unknown, AnyColumn][] = []
|
|
101
151
|
for (const [key, value] of Object.entries(values)) {
|
|
102
152
|
const column = this.columns[key]
|
|
103
|
-
if (!column || value === undefined) continue
|
|
153
|
+
if (!column || value === undefined || column.def.generated) continue
|
|
104
154
|
out.push([this.sqlNames.get(key) as string, value, column])
|
|
105
155
|
}
|
|
106
156
|
return out
|