@crombolo/data 0.37.0 → 0.38.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.
Files changed (75) hide show
  1. package/package.json +3 -2
  2. package/src/audit.ts +163 -133
  3. package/src/change-report.ts +66 -43
  4. package/src/cluster.ts +119 -59
  5. package/src/content-query.ts +205 -200
  6. package/src/{bundle-tables → custom-tables}/builder.ts +104 -12
  7. package/src/custom-tables/chain.ts +150 -0
  8. package/src/custom-tables/ddl.ts +159 -0
  9. package/src/custom-tables/handle.ts +141 -0
  10. package/src/{bundle-tables → custom-tables}/index.ts +3 -2
  11. package/src/custom-tables/names.ts +94 -0
  12. package/src/custom-tables/owners.ts +299 -0
  13. package/src/{bundle-tables → custom-tables}/schema.ts +263 -90
  14. package/src/custom-tables/values.ts +181 -0
  15. package/src/database.ts +40 -5
  16. package/src/dialect.ts +43 -16
  17. package/src/index.ts +8 -1
  18. package/src/migrations.ts +130 -88
  19. package/src/query.ts +158 -0
  20. package/src/relations.ts +49 -28
  21. package/src/repositories/approvals.ts +130 -89
  22. package/src/repositories/bundle-grants.ts +74 -0
  23. package/src/repositories/bundles.ts +85 -76
  24. package/src/repositories/content-applied.ts +47 -28
  25. package/src/repositories/content-events.ts +114 -67
  26. package/src/repositories/content-notifications.ts +102 -74
  27. package/src/repositories/content-types.ts +449 -320
  28. package/src/repositories/data-types.ts +105 -56
  29. package/src/repositories/delivery-member-tokens.ts +37 -28
  30. package/src/repositories/dictionary.ts +77 -58
  31. package/src/repositories/documents.ts +956 -580
  32. package/src/repositories/domains.ts +28 -16
  33. package/src/repositories/dynamic-roots.ts +32 -17
  34. package/src/repositories/external-logins.ts +38 -24
  35. package/src/repositories/folders.ts +7 -4
  36. package/src/repositories/form-entries.ts +120 -103
  37. package/src/repositories/form-workflows.ts +87 -62
  38. package/src/repositories/jobs.ts +296 -0
  39. package/src/repositories/languages.ts +51 -38
  40. package/src/repositories/log-searches.ts +7 -5
  41. package/src/repositories/media-access.ts +173 -123
  42. package/src/repositories/media-listing.ts +155 -92
  43. package/src/repositories/members.ts +189 -162
  44. package/src/repositories/nodes.ts +227 -181
  45. package/src/repositories/notifications.ts +22 -17
  46. package/src/repositories/public-access.ts +77 -61
  47. package/src/repositories/redirects.ts +113 -70
  48. package/src/repositories/references.ts +55 -44
  49. package/src/repositories/remote-jobs.ts +45 -35
  50. package/src/repositories/tags.ts +11 -10
  51. package/src/repositories/templates.ts +24 -14
  52. package/src/repositories/transfer-answers.ts +58 -50
  53. package/src/repositories/transfer-runs.ts +93 -75
  54. package/src/repositories/two-factor.ts +74 -55
  55. package/src/repositories/user-data.ts +54 -36
  56. package/src/repositories/users.ts +345 -300
  57. package/src/repositories/webhooks.ts +196 -137
  58. package/src/schema/bundle-grants.ts +32 -0
  59. package/src/schema/jobs.ts +56 -0
  60. package/src/schema/plan.ts +4 -0
  61. package/src/schema-ops.ts +15 -12
  62. package/src/schema-state.ts +53 -38
  63. package/src/search.ts +175 -129
  64. package/src/setup.ts +17 -13
  65. package/src/site-search.ts +134 -83
  66. package/src/table-types.ts +152 -0
  67. package/src/tables.gen.ts +859 -0
  68. package/src/tree-invariants.ts +21 -12
  69. package/src/url-options.ts +17 -13
  70. package/src/workflow-store.ts +17 -13
  71. package/src/bundle-tables/capability.ts +0 -377
  72. package/src/bundle-tables/chain.ts +0 -105
  73. package/src/bundle-tables/ddl.ts +0 -124
  74. package/src/bundle-tables/guard.ts +0 -116
  75. package/src/bundle-tables/names.ts +0 -58
@@ -1,14 +1,13 @@
1
1
  /**
2
- * The declarative builder a bundle writes its tables with. `docs/bundles.md`,
3
- * Part 4.
2
+ * The declarative builder custom tables are written with (stories 062, 189).
3
+ * docs/data-model.md, "Custom tables".
4
4
  *
5
- * It is the only way a bundle writes schema: there is no SQL in it, and no
6
- * escape hatch to some. A step's `up` returns the operations it wants, as plain
7
- * data, which is what makes a step checkable before it runs — linted for
8
- * expand and contract, hashed for its checksum, rendered for `upgrade --plan` —
9
- * and what lets the final shape of every table be worked out from the
10
- * declaration's types alone.
5
+ * A step's `up` returns the operations it wants, as plain data, which is what
6
+ * makes a step checkable before it runs — linted for expand and contract,
7
+ * hashed for its checksum, rendered for `upgrade --plan` — and what lets the
8
+ * final shape of every table be worked out from the declaration's types alone.
11
9
  */
10
+ import type { ColumnType as KyselyColumn } from 'kysely'
12
11
 
13
12
  export type ColumnType =
14
13
  | 'uuid'
@@ -19,18 +18,35 @@ export type ColumnType =
19
18
  | 'boolean'
20
19
  | 'timestamp'
21
20
  | 'json'
21
+ | 'decimal'
22
22
 
23
23
  /** A scalar a default may be: what DDL can carry as a literal. */
24
24
  export type DefaultValue = string | number | boolean
25
25
 
26
+ export type OnDelete = 'cascade' | 'restrict' | 'set null'
27
+
28
+ /** A foreign key to another of the same owner's tables. */
29
+ export interface Reference {
30
+ table: string
31
+ /** The column it points at; the table's primary key when not given. */
32
+ column?: string
33
+ onDelete: OnDelete
34
+ }
35
+
26
36
  export interface ColumnSpec {
27
37
  type: ColumnType
28
38
  /** For `varchar`. */
29
39
  length?: number
40
+ /** For `decimal`: digits in all, and after the point. */
41
+ precision?: number
42
+ scale?: number
30
43
  nullable: boolean
31
44
  default?: DefaultValue
32
45
  primaryKey: boolean
33
46
  indexed: boolean
47
+ /** Its own unique index. */
48
+ unique?: boolean
49
+ references?: Reference
34
50
  }
35
51
 
36
52
  /** What a column holds, as the capability reads and writes it. */
@@ -51,6 +67,21 @@ interface ValueOf {
51
67
  boolean: boolean
52
68
  timestamp: Date
53
69
  json: JsonValue
70
+ /** Exact on Postgres; on SQLite, to about 15 significant digits. */
71
+ decimal: string
72
+ }
73
+
74
+ /** What a column accepts when written. */
75
+ interface WriteOf {
76
+ uuid: string
77
+ varchar: string
78
+ text: string
79
+ integer: number
80
+ bigint: number
81
+ boolean: boolean
82
+ timestamp: Date | string
83
+ json: JsonValue
84
+ decimal: string | number
54
85
  }
55
86
 
56
87
  /**
@@ -67,11 +98,21 @@ export interface Column<
67
98
  nullable(): Column<T, true, D>
68
99
  /** What a row gets when an insert leaves it out. */
69
100
  default(
70
- value: T extends 'json' ? never : ValueOf[T] extends Date ? never : ValueOf[T],
101
+ value: T extends 'json'
102
+ ? never
103
+ : T extends 'decimal'
104
+ ? number
105
+ : ValueOf[T] extends Date
106
+ ? never
107
+ : ValueOf[T],
71
108
  ): Column<T, N, true>
72
109
  primaryKey(): Column<T, N, D>
73
110
  /** Gives the column an index of its own. */
74
111
  indexed(): Column<T, N, D>
112
+ /** Gives the column a unique index of its own. */
113
+ unique(): Column<T, N, D>
114
+ /** A foreign key to another of this owner's tables: its primary key, unless `column` names another. */
115
+ references(table: string, options?: { column?: string; onDelete?: OnDelete }): Column<T, N, D>
75
116
  /** Type-level only: what the column holds. */
76
117
  readonly __value?: ValueOf[T]
77
118
  readonly __nullable?: N
@@ -86,6 +127,16 @@ function column<T extends ColumnType>(type: T, spec: Partial<ColumnSpec> = {}):
86
127
  default: (value: DefaultValue) => make({ ...s, default: value }),
87
128
  primaryKey: () => make({ ...s, primaryKey: true }),
88
129
  indexed: () => make({ ...s, indexed: true }),
130
+ unique: () => make({ ...s, unique: true }),
131
+ references: (table: string, options: { column?: string; onDelete?: OnDelete } = {}) =>
132
+ make({
133
+ ...s,
134
+ references: {
135
+ table,
136
+ ...(options.column ? { column: options.column } : {}),
137
+ onDelete: options.onDelete ?? 'restrict',
138
+ },
139
+ }),
89
140
  }) as Column<T, boolean, boolean>
90
141
  return make({ type, nullable: false, primaryKey: false, indexed: false, ...spec }) as Column<T>
91
142
  }
@@ -95,12 +146,32 @@ export type Columns = Record<string, Column<ColumnType, boolean, boolean>>
95
146
  export type Operation =
96
147
  | { op: 'createTable'; table: string; columns: Record<string, ColumnSpec> }
97
148
  | { op: 'addColumn'; table: string; column: string; spec: ColumnSpec }
98
- | { op: 'addIndex'; table: string; columns: string[]; unique: boolean }
149
+ | {
150
+ op: 'addIndex'
151
+ table: string
152
+ columns: string[]
153
+ unique: boolean
154
+ /** Columns the index sorts descending. */
155
+ descending?: string[]
156
+ /** A partial index: only rows where this column is, or is not, null. */
157
+ where?: IndexWhere
158
+ }
99
159
  | { op: 'widenColumn'; table: string; column: string; spec: ColumnSpec }
100
160
  | { op: 'dropTable'; table: string }
101
161
  | { op: 'dropColumn'; table: string; column: string }
102
162
  | { op: 'dropIndex'; table: string; columns: string[] }
103
163
 
164
+ export interface IndexWhere {
165
+ column: string
166
+ is: 'null' | 'not null'
167
+ }
168
+
169
+ export interface IndexOptions {
170
+ unique?: boolean
171
+ descending?: readonly string[]
172
+ where?: IndexWhere
173
+ }
174
+
104
175
  /** An operation, carrying at the type level what it does to the schema. */
105
176
  export type Op<Effect = never> = Operation & { readonly __effect?: Effect }
106
177
 
@@ -139,6 +210,7 @@ export interface SchemaBuilder {
139
210
  boolean(): Column<'boolean'>
140
211
  timestamp(): Column<'timestamp'>
141
212
  json(): Column<'json'>
213
+ decimal(precision: number, scale: number): Column<'decimal'>
142
214
 
143
215
  createTable<T extends string, C extends Columns>(table: T, columns: C): Op<CreateTable<T, C>>
144
216
  /** A new column must be nullable or have a default, so it adds under live rows. */
@@ -147,7 +219,7 @@ export interface SchemaBuilder {
147
219
  column: K,
148
220
  spec: C,
149
221
  ): Op<AddColumn<T, K, C>>
150
- addIndex(table: string, columns: readonly string[], options?: { unique?: boolean }): Op
222
+ addIndex(table: string, columns: readonly string[], options?: IndexOptions): Op
151
223
  /** Longer text, or a wider integer; never narrower, never another kind. */
152
224
  widenColumn(table: string, column: string, spec: Column<ColumnType, boolean, boolean>): Op
153
225
  dropTable<T extends string>(table: T): Op<DropTable<T>>
@@ -171,6 +243,7 @@ export const schemaBuilder: SchemaBuilder = Object.freeze<SchemaBuilder>({
171
243
  boolean: () => column('boolean'),
172
244
  timestamp: () => column('timestamp'),
173
245
  json: () => column('json'),
246
+ decimal: (precision: number, scale: number) => column('decimal', { precision, scale }),
174
247
  createTable: (table, columns) => ({ op: 'createTable', table, columns: specs(columns) }) as never,
175
248
  addColumn: (table, name, spec) =>
176
249
  ({ op: 'addColumn', table, column: name, spec: spec.spec }) as never,
@@ -179,6 +252,8 @@ export const schemaBuilder: SchemaBuilder = Object.freeze<SchemaBuilder>({
179
252
  table,
180
253
  columns: [...columns],
181
254
  unique: options.unique ?? false,
255
+ ...(options.descending?.length ? { descending: [...options.descending] } : {}),
256
+ ...(options.where ? { where: { column: options.where.column, is: options.where.is } } : {}),
182
257
  }),
183
258
  widenColumn: (table, name, spec) => ({ op: 'widenColumn', table, column: name, spec: spec.spec }),
184
259
  dropTable: (table) => ({ op: 'dropTable', table }) as never,
@@ -253,7 +328,7 @@ type LastOf<U> =
253
328
  UnionToIntersection<U extends unknown ? () => U : never> extends () => infer R ? R : never
254
329
  type UnionToTuple<U, L = LastOf<U>> = [U] extends [never] ? [] : [...UnionToTuple<Exclude<U, L>>, L]
255
330
 
256
- /** The shape after every step, in order: what `context.host.tables` is typed from. */
331
+ /** The shape after every step, in order: what an owner's Kysely handle is typed from. */
257
332
  export type ShapeOf<
258
333
  Steps extends readonly unknown[],
259
334
  S extends TablesShape = Record<never, never>,
@@ -262,3 +337,20 @@ export type ShapeOf<
262
337
  ? ShapeOf<Rest, Flatten<ApplyAll<S, EffectOf<Effects<R>>>>>
263
338
  : ShapeOf<Rest, S>
264
339
  : S
340
+
341
+ // ------------------------------------------------------------ Kysely's types
342
+
343
+ type KyselyColumnOf<C> =
344
+ C extends Column<infer T, infer N, infer D>
345
+ ? KyselyColumn<
346
+ N extends true ? ValueOf[T] | null : ValueOf[T],
347
+ | (N extends true ? WriteOf[T] | null : WriteOf[T])
348
+ | (N extends true ? undefined : D extends true ? undefined : never),
349
+ N extends true ? WriteOf[T] | null : WriteOf[T]
350
+ >
351
+ : never
352
+
353
+ /** A shape's tables as Kysely's database interface. */
354
+ export type KyselyTablesOf<S extends TablesShape> = {
355
+ [T in keyof S]: { [K in keyof S[T]]: KyselyColumnOf<S[T][K]> }
356
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * An owner's compiled steps as a migration chain, run by the same `migrate`,
3
+ * under the same lock and into the same ledger as core's — only its state key,
4
+ * its ledger rows' `bundle` and where its steps run differ (story 189). And
5
+ * purging one: dropping its schema or file whole, because a purged bundle is
6
+ * one the site no longer wires.
7
+ */
8
+ import { existsSync, rmSync } from 'node:fs'
9
+ import type { Kysely } from 'kysely'
10
+ import type { Db } from '../database.ts'
11
+ import { deleteKeyValue, type Migration, MigrationPlan, recordInLedger } from '../migrations.ts'
12
+ import { renderStep } from './ddl.ts'
13
+ import { tablesDatabase } from './handle.ts'
14
+ import { asOwner, forgetOwner, type OwnerPlace, openOwner } from './owners.ts'
15
+ import type { CompiledStep, CompiledTables } from './schema.ts'
16
+
17
+ /**
18
+ * Where an owner's steps run, filled once its place is known: at boot, after
19
+ * the database is connected and the place provisioned.
20
+ */
21
+ export interface OwnerSlot {
22
+ place?: OwnerPlace
23
+ /** SQLite: the owner's own connection. */
24
+ db?: Db
25
+ }
26
+
27
+ function migrationOf(step: CompiledStep): Migration {
28
+ return {
29
+ from: step.from,
30
+ to: step.to,
31
+ name: step.name,
32
+ kind: step.kind,
33
+ release: step.release,
34
+ contracts: step.contracts,
35
+ checksum: step.checksum,
36
+ async up(db) {
37
+ for (const statement of renderStep(db.dialect, step)) await db.exec(statement)
38
+ },
39
+ backfill: step.backfill
40
+ ? (db) =>
41
+ (step.backfill as NonNullable<CompiledStep['backfill']>)(tablesDatabase(db, step.after))
42
+ : undefined,
43
+ }
44
+ }
45
+
46
+ /** The chain `migrate` walks. Throws when the declaration has problems: compile first. */
47
+ export function tablesPlan(compiled: CompiledTables, slot: OwnerSlot = {}): MigrationPlan {
48
+ if (compiled.problems.length > 0)
49
+ throw new Error(
50
+ `The tables of "${compiled.id}" cannot be planned:\n- ${compiled.problems.join('\n- ')}`,
51
+ )
52
+ return new MigrationPlan(compiled.steps.map(migrationOf), {
53
+ stateKey: compiled.stateKey,
54
+ initialState: compiled.initialState,
55
+ bundle: compiled.id,
56
+ runStep: (tx, step) => {
57
+ if (!slot.place) throw new Error(`The tables of "${compiled.id}" have no place yet.`)
58
+ return asOwner(tx, slot.place, slot.db, step)
59
+ },
60
+ })
61
+ }
62
+
63
+ /**
64
+ * Creates an owner's tables directly, step by step, without its ledger or its
65
+ * state. Only for proving what core's own migrations do around them: an install
66
+ * is always `migrate`.
67
+ */
68
+ export async function applyStepsUnledgered(owned: Db, compiled: CompiledTables): Promise<void> {
69
+ for (const migration of tablesPlan(compiled).migrations)
70
+ await owned.transaction(async (tx) => {
71
+ await migration.up(tx)
72
+ await migration.backfill?.(tx)
73
+ })
74
+ }
75
+
76
+ /** The tables in an owner's schema or file. */
77
+ export async function ownerTablesIn(db: Db, place: OwnerPlace): Promise<string[]> {
78
+ if (place.dialect === 'sqlite') {
79
+ if (!place.file || (place.file !== ':memory:' && !existsSync(place.file))) return []
80
+ const owned = await openOwner(db, place)
81
+ try {
82
+ const rows = await owned.query<{ name: string }>(owned.dialect.tableNames)
83
+ return rows
84
+ .map((row) => row.name)
85
+ .filter((name) => !name.startsWith('sqlite_'))
86
+ .sort()
87
+ } finally {
88
+ if (place.file !== ':memory:') await owned.close()
89
+ }
90
+ }
91
+ const rows = await (
92
+ db.q as unknown as Kysely<{
93
+ 'information_schema.tables': { table_name: string; table_schema: string; table_type: string }
94
+ }>
95
+ )
96
+ .selectFrom('information_schema.tables')
97
+ .select('table_name')
98
+ .where('table_schema', '=', place.schema)
99
+ .where('table_type', '=', 'BASE TABLE')
100
+ .orderBy('table_name')
101
+ .execute()
102
+ return rows.map((row) => row.table_name)
103
+ }
104
+
105
+ /**
106
+ * Drops the owner's schema and role, or deletes its file, and forgets its state
107
+ * and role, so adding it again starts its chain from the beginning. Ledgered as
108
+ * a `purge`. A role the CMS may not drop is left, and said.
109
+ */
110
+ export async function purgeOwnerTables(
111
+ db: Db,
112
+ place: OwnerPlace,
113
+ options: { by?: string; stateKey: string },
114
+ ): Promise<{ tables: string[]; roleLeft?: string }> {
115
+ const tables = await ownerTablesIn(db, place)
116
+ const started = performance.now()
117
+ let roleLeft: string | undefined
118
+ if (place.dialect === 'sqlite') {
119
+ if (place.file && place.file !== ':memory:')
120
+ for (const suffix of ['', '-wal', '-shm']) rmSync(`${place.file}${suffix}`, { force: true })
121
+ else {
122
+ // In memory there is no file to delete, so its tables go one by one.
123
+ const owned = await openOwner(db, place)
124
+ for (const table of tables) await owned.q.schema.dropTable(table).execute()
125
+ }
126
+ } else if (place.role) {
127
+ const role = place.role
128
+ await db.transaction(async (tx) => {
129
+ await asOwner(tx, place, undefined, (owned) =>
130
+ owned.q.schema.dropSchema(place.schema).ifExists().cascade().execute(),
131
+ )
132
+ })
133
+ try {
134
+ await db.exec(`DROP ROLE IF EXISTS ${db.dialect.quote(role)}`)
135
+ } catch {
136
+ roleLeft = role
137
+ }
138
+ await forgetOwner(db, place.id)
139
+ }
140
+ await deleteKeyValue(db, options.stateKey)
141
+ await recordInLedger(db, {
142
+ name: `purge ${place.id}`,
143
+ kind: 'purge',
144
+ durationMs: Math.round(performance.now() - started),
145
+ appliedBy: options.by ?? null,
146
+ note: tables.length > 0 ? `dropped ${tables.join(', ')}` : 'no tables',
147
+ bundle: place.id,
148
+ })
149
+ return { tables, ...(roleLeft ? { roleLeft } : {}) }
150
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * A step's operations as SQL, per dialect, unqualified: they run in the
3
+ * owner's own schema or file. Every identifier comes from the resolved schema
4
+ * and is quoted here, and every default is a literal the builder already
5
+ * checked.
6
+ */
7
+ import type { ColumnDefinitionBuilder, Compilable } from 'kysely'
8
+ import type { Dialect } from '../dialect.ts'
9
+ import { compilerFor, sql } from '../query.ts'
10
+ import type { ColumnSpec, Operation } from './builder.ts'
11
+ import { type CompiledStep, type ResolvedSchema, sqlStatements } from './schema.ts'
12
+
13
+ /**
14
+ * The column type, from the dialect seam. Text compares case-sensitively on
15
+ * both; a uuid compares without case on both, as Postgres's own type does.
16
+ */
17
+ export function columnType(dialect: Dialect, spec: ColumnSpec): string {
18
+ const t = dialect.types
19
+ switch (spec.type) {
20
+ case 'uuid':
21
+ return dialect.name === 'sqlite' ? 'TEXT COLLATE NOCASE' : t.uuid
22
+ case 'varchar':
23
+ return t.varcharExact(spec.length ?? 1)
24
+ case 'text':
25
+ return t.text
26
+ case 'integer':
27
+ return t.integer
28
+ case 'bigint':
29
+ return t.bigint
30
+ case 'boolean':
31
+ return t.boolean
32
+ case 'timestamp':
33
+ return t.timestamp
34
+ case 'json':
35
+ return t.json
36
+ case 'decimal':
37
+ // NUMERIC affinity on SQLite, so a sum and an order are by value, not text.
38
+ return `NUMERIC(${spec.precision ?? 1}, ${spec.scale ?? 0})`
39
+ }
40
+ }
41
+
42
+ function literal(dialect: Dialect, value: string | number | boolean): string {
43
+ if (typeof value === 'boolean')
44
+ return dialect.name === 'postgres' ? (value ? 'TRUE' : 'FALSE') : value ? '1' : '0'
45
+ if (typeof value === 'number') return String(value)
46
+ return `'${value.replaceAll("'", "''")}'`
47
+ }
48
+
49
+ /** A column's type and constraints, as the schema builder takes them. */
50
+ function defineColumn(dialect: Dialect, spec: ColumnSpec, schema: ResolvedSchema, self?: string) {
51
+ return (column: ColumnDefinitionBuilder): ColumnDefinitionBuilder => {
52
+ let defined = column
53
+ if (!spec.nullable) defined = defined.notNull()
54
+ if (spec.default !== undefined)
55
+ defined = defined.defaultTo(sql.raw(literal(dialect, spec.default)))
56
+ const ref = spec.references
57
+ if (ref) {
58
+ const target = ref.column ?? primaryKeyOf(schema, ref.table, self)
59
+ defined = defined.references(`${ref.table}.${target}`).onDelete(ref.onDelete)
60
+ }
61
+ return defined
62
+ }
63
+ }
64
+
65
+ function primaryKeyOf(schema: ResolvedSchema, table: string, self?: string): string {
66
+ const found = schema.tables.get(table)
67
+ const key = found && [...found.columns.values()].find((column) => column.spec.primaryKey)
68
+ if (!key) throw new Error(`no primary key on "${table}"${self ? ` for "${self}"` : ''}`)
69
+ return key.name
70
+ }
71
+
72
+ /** The statements one operation runs, against the schema as it stood before it. */
73
+ export function renderOperation(
74
+ dialect: Dialect,
75
+ before: ResolvedSchema,
76
+ after: ResolvedSchema,
77
+ op: Operation,
78
+ ): string[] {
79
+ const schema = compilerFor(dialect).schema
80
+ const type = (spec: ColumnSpec) => sql.raw(columnType(dialect, spec))
81
+ const table = after.tables.get(op.table) ?? before.tables.get(op.table)
82
+ if (!table) throw new Error(`no table "${op.table}" to render ${op.op} against`)
83
+ const statements: Compilable[] = []
84
+ const indexFor = (columns: readonly string[]) => {
85
+ const index = (after.tables.get(op.table) ?? table).indexes.get(columns.join(','))
86
+ if (!index) throw new Error(`no index on "${op.table}" (${columns.join(',')})`)
87
+ return index
88
+ }
89
+ const createIndex = (columns: readonly string[]) => {
90
+ const index = indexFor(columns)
91
+ const descending = new Set(index.descending ?? [])
92
+ let create = schema
93
+ .createIndex(index.name)
94
+ .on(table.name)
95
+ .columns(index.columns.map((column) => (descending.has(column) ? `${column} desc` : column)))
96
+ if (index.unique) create = create.unique()
97
+ if (index.where)
98
+ create = create.where(index.where.column, index.where.is === 'null' ? 'is' : 'is not', null)
99
+ statements.push(create)
100
+ }
101
+
102
+ switch (op.op) {
103
+ case 'createTable': {
104
+ let create = schema.createTable(table.name)
105
+ for (const [name, spec] of Object.entries(op.columns))
106
+ create = create.addColumn(name, type(spec), (column) => {
107
+ const defined = defineColumn(dialect, spec, after, table.name)(column)
108
+ return spec.primaryKey ? defined.primaryKey() : defined
109
+ })
110
+ statements.push(create)
111
+ for (const [name, spec] of Object.entries(op.columns))
112
+ if ((spec.indexed || spec.unique) && !spec.primaryKey) createIndex([name])
113
+ break
114
+ }
115
+ case 'addColumn':
116
+ statements.push(
117
+ schema
118
+ .alterTable(table.name)
119
+ .addColumn(op.column, type(op.spec), defineColumn(dialect, op.spec, after)),
120
+ )
121
+ if (op.spec.indexed) createIndex([op.column])
122
+ break
123
+ case 'addIndex':
124
+ createIndex(op.columns)
125
+ break
126
+ case 'widenColumn':
127
+ // SQLite stores by affinity and enforces no length, so a wider type is
128
+ // already what it holds; only Postgres has anything to change.
129
+ if (dialect.name === 'postgres')
130
+ statements.push(
131
+ schema
132
+ .alterTable(table.name)
133
+ .alterColumn(op.column, (column) => column.setDataType(type(op.spec))),
134
+ )
135
+ break
136
+ case 'dropTable':
137
+ statements.push(schema.dropTable(table.name))
138
+ break
139
+ case 'dropColumn':
140
+ statements.push(schema.alterTable(table.name).dropColumn(op.column))
141
+ break
142
+ case 'dropIndex': {
143
+ const index = before.tables.get(op.table)?.indexes.get(op.columns.join(','))
144
+ if (!index) throw new Error(`no index on "${op.table}" (${op.columns.join(',')})`)
145
+ statements.push(schema.dropIndex(index.name))
146
+ break
147
+ }
148
+ }
149
+ return statements.map((statement) => statement.compile().sql)
150
+ }
151
+
152
+ /** Every statement a step runs, in order: a SQL step's as written. */
153
+ export function renderStep(
154
+ dialect: Dialect,
155
+ step: Pick<CompiledStep, 'before' | 'after' | 'operations' | 'sql'>,
156
+ ): string[] {
157
+ if (step.sql) return [...sqlStatements(step, dialect.name)]
158
+ return step.operations.flatMap((op) => renderOperation(dialect, step.before, step.after, op))
159
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * The Kysely handle on an owner's tables (story 189): what a named query's `db`
3
+ * and a bundle's `context.bundle.database` are. It runs on the owner's own
4
+ * connection, so it reaches nothing else, and converts values so the same code
5
+ * reads and writes the same on both engines (`values.ts`).
6
+ *
7
+ * `db.transaction().execute(async (trx) => …)` is Kysely's own: here it holds
8
+ * one transaction on the owner's connection until the callback settles.
9
+ */
10
+ import {
11
+ type CompiledQuery,
12
+ type DatabaseConnection,
13
+ type DatabaseIntrospector,
14
+ type Driver,
15
+ Kysely,
16
+ type Dialect as KyselyDialect,
17
+ PostgresAdapter,
18
+ PostgresIntrospector,
19
+ type QueryResult,
20
+ SqliteAdapter,
21
+ SqliteIntrospector,
22
+ SqliteQueryCompiler,
23
+ } from 'kysely'
24
+ import type { Db } from '../database.ts'
25
+ import { PlaceholderCompiler, readsRows } from '../query.ts'
26
+ import type { KyselyTablesOf, TablesShape } from './builder.ts'
27
+ import type { CustomTables, ResolvedSchema } from './schema.ts'
28
+ import { PortableValues, portableParam } from './values.ts'
29
+
30
+ /** A handle on an owner's tables, typed from its steps. */
31
+ export type TablesDatabase<T extends CustomTables = CustomTables> =
32
+ T extends CustomTables<infer S> ? Kysely<KyselyTablesOf<S>> : never
33
+
34
+ /** A handle typed from a shape, for one declared by hand after a SQL step. */
35
+ export type ShapeDatabase<S extends TablesShape> = Kysely<KyselyTablesOf<S>>
36
+
37
+ const ROLLBACK = Symbol('rollback')
38
+
39
+ /**
40
+ * One acquisition of the owner's connection. Outside a transaction each
41
+ * statement stands alone; inside one, the statements share the `Db`
42
+ * transaction opened at `begin` and held open until `commit` or `rollback`.
43
+ */
44
+ class OwnerConnection implements DatabaseConnection {
45
+ readonly #db: Db
46
+ #tx: Db | undefined
47
+ #settle: ((commit: boolean) => void) | undefined
48
+ #done: Promise<void> | undefined
49
+
50
+ constructor(db: Db) {
51
+ this.#db = db
52
+ }
53
+
54
+ async begin(): Promise<void> {
55
+ let opened!: (tx: Db) => void
56
+ const ready = new Promise<Db>((resolve) => {
57
+ opened = resolve
58
+ })
59
+ this.#done = this.#db
60
+ .transaction(
61
+ (tx) =>
62
+ new Promise<void>((resolve, reject) => {
63
+ this.#settle = (commit) => (commit ? resolve() : reject(ROLLBACK))
64
+ opened(tx)
65
+ }),
66
+ )
67
+ .catch((error: unknown) => {
68
+ if (error !== ROLLBACK) throw error
69
+ })
70
+ this.#tx = await Promise.race([
71
+ ready,
72
+ this.#done.then(() => {
73
+ throw new Error('The transaction ended before it began.')
74
+ }),
75
+ ])
76
+ }
77
+
78
+ async end(commit: boolean): Promise<void> {
79
+ this.#settle?.(commit)
80
+ try {
81
+ await this.#done
82
+ } finally {
83
+ this.#tx = undefined
84
+ this.#settle = undefined
85
+ this.#done = undefined
86
+ }
87
+ }
88
+
89
+ async executeQuery<R>(compiled: CompiledQuery): Promise<QueryResult<R>> {
90
+ const db = this.#tx ?? this.#db
91
+ const params = (compiled.parameters as unknown[]).map((value) =>
92
+ portableParam(db.dialect, value),
93
+ )
94
+ if (readsRows(compiled)) return { rows: await db.query<R>(compiled.sql, params) }
95
+ await db.exec(compiled.sql, params)
96
+ return { rows: [] }
97
+ }
98
+
99
+ // biome-ignore lint/correctness/useYield: refuses before streaming anything
100
+ async *streamQuery<R>(): AsyncIterableIterator<QueryResult<R>> {
101
+ throw new Error('Streaming is not supported; page with limit and offset instead.')
102
+ }
103
+ }
104
+
105
+ class OwnerDriver implements Driver {
106
+ readonly #db: Db
107
+ constructor(db: Db) {
108
+ this.#db = db
109
+ }
110
+ async init(): Promise<void> {}
111
+ async acquireConnection(): Promise<DatabaseConnection> {
112
+ return new OwnerConnection(this.#db)
113
+ }
114
+ async beginTransaction(connection: DatabaseConnection): Promise<void> {
115
+ await (connection as OwnerConnection).begin()
116
+ }
117
+ async commitTransaction(connection: DatabaseConnection): Promise<void> {
118
+ await (connection as OwnerConnection).end(true)
119
+ }
120
+ async rollbackTransaction(connection: DatabaseConnection): Promise<void> {
121
+ await (connection as OwnerConnection).end(false)
122
+ }
123
+ async releaseConnection(): Promise<void> {}
124
+ async destroy(): Promise<void> {}
125
+ }
126
+
127
+ /** The handle on an owner's tables, over the connection that reaches only them. */
128
+ export function tablesDatabase<S extends TablesShape = TablesShape>(
129
+ db: Db,
130
+ schema: ResolvedSchema,
131
+ ): Kysely<KyselyTablesOf<S>> {
132
+ const postgres = db.dialect.name === 'postgres'
133
+ const dialect: KyselyDialect = {
134
+ createAdapter: () => (postgres ? new PostgresAdapter() : new SqliteAdapter()),
135
+ createDriver: () => new OwnerDriver(db),
136
+ createQueryCompiler: () => (postgres ? new PlaceholderCompiler() : new SqliteQueryCompiler()),
137
+ createIntrospector: (k: Kysely<unknown>): DatabaseIntrospector =>
138
+ postgres ? new PostgresIntrospector(k) : new SqliteIntrospector(k),
139
+ }
140
+ return new Kysely<KyselyTablesOf<S>>({ dialect, plugins: [new PortableValues(schema)] })
141
+ }
@@ -1,7 +1,8 @@
1
1
  export * from './builder.ts'
2
- export * from './capability.ts'
3
2
  export * from './chain.ts'
4
3
  export * from './ddl.ts'
5
- export * from './guard.ts'
4
+ export * from './handle.ts'
6
5
  export * from './names.ts'
6
+ export * from './owners.ts'
7
7
  export * from './schema.ts'
8
+ export * from './values.ts'