@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.
- package/package.json +3 -2
- package/src/audit.ts +163 -133
- package/src/change-report.ts +66 -43
- package/src/cluster.ts +119 -59
- package/src/content-query.ts +205 -200
- package/src/{bundle-tables → custom-tables}/builder.ts +104 -12
- package/src/custom-tables/chain.ts +150 -0
- package/src/custom-tables/ddl.ts +159 -0
- package/src/custom-tables/handle.ts +141 -0
- package/src/{bundle-tables → custom-tables}/index.ts +3 -2
- package/src/custom-tables/names.ts +94 -0
- package/src/custom-tables/owners.ts +299 -0
- package/src/{bundle-tables → custom-tables}/schema.ts +263 -90
- package/src/custom-tables/values.ts +181 -0
- package/src/database.ts +40 -5
- package/src/dialect.ts +43 -16
- package/src/index.ts +8 -1
- package/src/migrations.ts +130 -88
- package/src/query.ts +158 -0
- package/src/relations.ts +49 -28
- package/src/repositories/approvals.ts +130 -89
- package/src/repositories/bundle-grants.ts +74 -0
- package/src/repositories/bundles.ts +85 -76
- package/src/repositories/content-applied.ts +47 -28
- package/src/repositories/content-events.ts +114 -67
- package/src/repositories/content-notifications.ts +102 -74
- package/src/repositories/content-types.ts +449 -320
- package/src/repositories/data-types.ts +105 -56
- package/src/repositories/delivery-member-tokens.ts +37 -28
- package/src/repositories/dictionary.ts +77 -58
- package/src/repositories/documents.ts +956 -580
- package/src/repositories/domains.ts +28 -16
- package/src/repositories/dynamic-roots.ts +32 -17
- package/src/repositories/external-logins.ts +38 -24
- package/src/repositories/folders.ts +7 -4
- package/src/repositories/form-entries.ts +120 -103
- package/src/repositories/form-workflows.ts +87 -62
- package/src/repositories/jobs.ts +296 -0
- package/src/repositories/languages.ts +51 -38
- package/src/repositories/log-searches.ts +7 -5
- package/src/repositories/media-access.ts +173 -123
- package/src/repositories/media-listing.ts +155 -92
- package/src/repositories/members.ts +189 -162
- package/src/repositories/nodes.ts +227 -181
- package/src/repositories/notifications.ts +22 -17
- package/src/repositories/public-access.ts +77 -61
- package/src/repositories/redirects.ts +113 -70
- package/src/repositories/references.ts +55 -44
- package/src/repositories/remote-jobs.ts +45 -35
- package/src/repositories/tags.ts +11 -10
- package/src/repositories/templates.ts +24 -14
- package/src/repositories/transfer-answers.ts +58 -50
- package/src/repositories/transfer-runs.ts +93 -75
- package/src/repositories/two-factor.ts +74 -55
- package/src/repositories/user-data.ts +54 -36
- package/src/repositories/users.ts +345 -300
- package/src/repositories/webhooks.ts +196 -137
- package/src/schema/bundle-grants.ts +32 -0
- package/src/schema/jobs.ts +56 -0
- package/src/schema/plan.ts +4 -0
- package/src/schema-ops.ts +15 -12
- package/src/schema-state.ts +53 -38
- package/src/search.ts +175 -129
- package/src/setup.ts +17 -13
- package/src/site-search.ts +134 -83
- package/src/table-types.ts +152 -0
- package/src/tables.gen.ts +859 -0
- package/src/tree-invariants.ts +21 -12
- package/src/url-options.ts +17 -13
- package/src/workflow-store.ts +17 -13
- package/src/bundle-tables/capability.ts +0 -377
- package/src/bundle-tables/chain.ts +0 -105
- package/src/bundle-tables/ddl.ts +0 -124
- package/src/bundle-tables/guard.ts +0 -116
- package/src/bundle-tables/names.ts +0 -58
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* An owner's declaration, compiled: its steps in order, each with the schema it
|
|
3
3
|
* starts from and the one it leaves, its kind, and its checksum. And the rules
|
|
4
4
|
* a declaration is held to, which core's own plan is held to as well — a
|
|
5
5
|
* contract only in a major, and only removing what an earlier release added.
|
|
6
|
-
*
|
|
6
|
+
* docs/data-model.md, "Custom tables".
|
|
7
7
|
*/
|
|
8
|
+
import type { Kysely } from 'kysely'
|
|
9
|
+
import type { DialectName } from '../dialect.ts'
|
|
8
10
|
import { mayShipContract } from '../migrations.ts'
|
|
9
11
|
import {
|
|
10
12
|
type ColumnSpec,
|
|
@@ -15,41 +17,61 @@ import {
|
|
|
15
17
|
schemaBuilder,
|
|
16
18
|
type TablesShape,
|
|
17
19
|
} from './builder.ts'
|
|
18
|
-
import {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
indexName,
|
|
22
|
-
lengthProblem,
|
|
23
|
-
logicalNameProblem,
|
|
24
|
-
physicalTable,
|
|
25
|
-
} from './names.ts'
|
|
26
|
-
|
|
27
|
-
/** One step of a bundle's chain, as the bundle writes it. */
|
|
20
|
+
import { indexName, logicalNameProblem, SITE_OWNER } from './names.ts'
|
|
21
|
+
|
|
22
|
+
/** One step of an owner's chain, written with the builder. */
|
|
28
23
|
export interface BundleStep {
|
|
29
|
-
/** Unique within the
|
|
24
|
+
/** Unique within the owner; what the ledger records and a refusal names. */
|
|
30
25
|
name: string
|
|
31
|
-
/** The
|
|
26
|
+
/** The owner's own release that ships this step. */
|
|
32
27
|
release: string
|
|
33
28
|
up(s: SchemaBuilder): Op<unknown> | readonly Op<unknown>[]
|
|
34
29
|
/**
|
|
35
30
|
* Writes data once `up` has run, in the same transaction, over the tables as
|
|
36
|
-
* they now are. Untyped, because a step's
|
|
37
|
-
*
|
|
31
|
+
* they now are, through the owner's Kysely handle. Untyped, because a step's
|
|
32
|
+
* shape is only known once the steps before it are.
|
|
38
33
|
*/
|
|
39
|
-
backfill?(
|
|
34
|
+
backfill?(db: BackfillDatabase): Promise<void>
|
|
40
35
|
}
|
|
41
36
|
|
|
37
|
+
/**
|
|
38
|
+
* A step of the site's in SQL, for what the builder cannot say (story 189): run
|
|
39
|
+
* as written, statement by statement, under the site's role. Untyped, so the
|
|
40
|
+
* shape after it is declared by hand. Bundles cannot have one.
|
|
41
|
+
*/
|
|
42
|
+
export interface SqlStep {
|
|
43
|
+
name: string
|
|
44
|
+
release: string
|
|
45
|
+
/** `expand` unless it removes something. */
|
|
46
|
+
kind?: StepKind
|
|
47
|
+
sql:
|
|
48
|
+
| readonly string[]
|
|
49
|
+
| { readonly sqlite: readonly string[]; readonly postgres: readonly string[] }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export type SiteStep = BundleStep | SqlStep
|
|
53
|
+
|
|
42
54
|
// biome-ignore lint/suspicious/noExplicitAny: the shape at a step is not known to the step's own type
|
|
43
|
-
export type
|
|
55
|
+
export type BackfillDatabase = Kysely<any>
|
|
44
56
|
|
|
45
|
-
/**
|
|
46
|
-
export interface
|
|
57
|
+
/** An owner's declared tables: the site's, or a bundle's under its id. */
|
|
58
|
+
export interface CustomTables<
|
|
59
|
+
S extends TablesShape = TablesShape,
|
|
60
|
+
Step extends SiteStep = SiteStep,
|
|
61
|
+
> {
|
|
62
|
+
/** `site`, or the bundle's id. */
|
|
47
63
|
readonly id: string
|
|
48
|
-
readonly steps: readonly
|
|
64
|
+
readonly steps: readonly Step[]
|
|
49
65
|
/** Type-level only: the shape after every step. */
|
|
50
66
|
readonly __shape?: S
|
|
51
67
|
}
|
|
52
68
|
|
|
69
|
+
/** A bundle's declared tables: what `ServerBundle.tables` holds. */
|
|
70
|
+
export type BundleTables<S extends TablesShape = TablesShape> = CustomTables<S, BundleStep>
|
|
71
|
+
|
|
72
|
+
/** The site's declared tables: what `database.tables` holds in the config. */
|
|
73
|
+
export type SiteTables<S extends TablesShape = TablesShape> = CustomTables<S>
|
|
74
|
+
|
|
53
75
|
/**
|
|
54
76
|
* Declares a bundle's tables. Nothing is checked or run here: the declaration
|
|
55
77
|
* is checked when the bundle is wired, so every problem is reported at once.
|
|
@@ -61,6 +83,15 @@ export function defineBundleTables<const Steps extends readonly BundleStep[]>(
|
|
|
61
83
|
return Object.freeze({ id, steps: Object.freeze([...steps]) })
|
|
62
84
|
}
|
|
63
85
|
|
|
86
|
+
/** Declares the site's own tables, checked when the site boots. */
|
|
87
|
+
export function defineSiteTables<const Steps extends readonly SiteStep[]>(
|
|
88
|
+
steps: Steps,
|
|
89
|
+
): SiteTables<ShapeOf<Steps>> {
|
|
90
|
+
return Object.freeze({ id: SITE_OWNER, steps: Object.freeze([...steps]) })
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const isSqlStep = (step: SiteStep): step is SqlStep => 'sql' in step
|
|
94
|
+
|
|
64
95
|
export interface ResolvedColumn {
|
|
65
96
|
name: string
|
|
66
97
|
spec: ColumnSpec
|
|
@@ -72,22 +103,22 @@ export interface ResolvedIndex {
|
|
|
72
103
|
name: string
|
|
73
104
|
columns: string[]
|
|
74
105
|
unique: boolean
|
|
106
|
+
descending?: string[]
|
|
107
|
+
where?: { column: string; is: 'null' | 'not null' }
|
|
75
108
|
addedIn: { step: string; release: string }
|
|
76
109
|
}
|
|
77
110
|
|
|
78
111
|
export interface ResolvedTable {
|
|
79
112
|
name: string
|
|
80
|
-
physical: string
|
|
81
113
|
columns: Map<string, ResolvedColumn>
|
|
82
114
|
/** By the columns they cover, joined with commas. */
|
|
83
115
|
indexes: Map<string, ResolvedIndex>
|
|
84
116
|
addedIn: { step: string; release: string }
|
|
85
117
|
}
|
|
86
118
|
|
|
87
|
-
/**
|
|
119
|
+
/** An owner's tables at one point in its chain. */
|
|
88
120
|
export interface ResolvedSchema {
|
|
89
121
|
id: string
|
|
90
|
-
prefix: string
|
|
91
122
|
tables: Map<string, ResolvedTable>
|
|
92
123
|
}
|
|
93
124
|
|
|
@@ -101,6 +132,8 @@ export interface CompiledStep {
|
|
|
101
132
|
to: string
|
|
102
133
|
kind: StepKind
|
|
103
134
|
operations: Operation[]
|
|
135
|
+
/** A SQL step's statements, per dialect. */
|
|
136
|
+
sql?: { sqlite: readonly string[]; postgres: readonly string[] }
|
|
104
137
|
/** A hash of the operations, so a step edited after it shipped is caught. */
|
|
105
138
|
checksum: string
|
|
106
139
|
/** For a contract: the step that added the first thing it removes. */
|
|
@@ -120,19 +153,31 @@ export interface CompiledTables {
|
|
|
120
153
|
problems: string[]
|
|
121
154
|
}
|
|
122
155
|
|
|
123
|
-
|
|
124
|
-
|
|
156
|
+
/**
|
|
157
|
+
* Where an owner's state is kept. 062's prefixed tables used
|
|
158
|
+
* `Crombolo.Bundle.<id>.State`; a new key starts every chain again in the
|
|
159
|
+
* owner's own schema or file.
|
|
160
|
+
*/
|
|
161
|
+
export const tablesStateKey = (id: string): string => `Crombolo.Tables.${id}.State`
|
|
162
|
+
export const tablesInitialState = (id: string): string => `tables:${id}:0`
|
|
125
163
|
const stateAt = (id: string, position: number, name: string): string =>
|
|
126
|
-
`
|
|
164
|
+
`tables:${id}:${position}:${name}`
|
|
165
|
+
|
|
166
|
+
/** A SQL step's statements on one dialect. */
|
|
167
|
+
export function sqlStatements(
|
|
168
|
+
step: { sql?: CompiledStep['sql'] },
|
|
169
|
+
dialect: DialectName,
|
|
170
|
+
): readonly string[] {
|
|
171
|
+
return step.sql?.[dialect] ?? []
|
|
172
|
+
}
|
|
127
173
|
|
|
128
174
|
const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/
|
|
129
175
|
const STEP_NAME = /^[a-z0-9][a-z0-9._-]{0,99}$/
|
|
130
176
|
/** What a string default may hold: it is written into DDL as a literal. */
|
|
131
177
|
const SAFE_DEFAULT = /^[A-Za-z0-9 _.:@/-]{0,200}$/
|
|
132
178
|
const MAX_VARCHAR = 10_485_760
|
|
133
|
-
/**
|
|
134
|
-
const
|
|
135
|
-
const RESERVED_COLUMNS = new Set(['and', 'or'])
|
|
179
|
+
/** The most digits a decimal may declare, a common limit across engines. */
|
|
180
|
+
const MAX_PRECISION = 38
|
|
136
181
|
|
|
137
182
|
export function compareRelease(a: string, b: string): number {
|
|
138
183
|
const pa = a.split(/[.+-]/).map(Number)
|
|
@@ -173,20 +218,32 @@ function specProblem(spec: ColumnSpec, where: string): string | undefined {
|
|
|
173
218
|
if (!Number.isInteger(length) || length < 1 || length > MAX_VARCHAR)
|
|
174
219
|
return `${where} is a varchar of length ${spec.length}, which must be a whole number from 1`
|
|
175
220
|
}
|
|
221
|
+
if (spec.type === 'decimal') {
|
|
222
|
+
const { precision = 0, scale = -1 } = spec
|
|
223
|
+
if (!Number.isInteger(precision) || precision < 1 || precision > MAX_PRECISION)
|
|
224
|
+
return `${where} is a decimal of precision ${spec.precision}, which must be a whole number from 1 to ${MAX_PRECISION}`
|
|
225
|
+
if (!Number.isInteger(scale) || scale < 0 || scale > precision)
|
|
226
|
+
return `${where} is a decimal of scale ${spec.scale}, which must be a whole number from 0 to its precision`
|
|
227
|
+
}
|
|
176
228
|
if (spec.primaryKey && spec.nullable) return `${where} is a primary key, so it cannot be nullable`
|
|
229
|
+
if (spec.references?.onDelete === 'set null' && !spec.nullable)
|
|
230
|
+
return `${where} is set to null when what it points at is deleted, so it must be nullable`
|
|
177
231
|
if (spec.default === undefined) return undefined
|
|
178
232
|
if (spec.type === 'json' || spec.type === 'timestamp')
|
|
179
233
|
return `${where} is ${spec.type}, which cannot have a default`
|
|
180
234
|
const expected =
|
|
181
235
|
spec.type === 'boolean'
|
|
182
236
|
? 'boolean'
|
|
183
|
-
: spec.type === 'integer' || spec.type === 'bigint'
|
|
237
|
+
: spec.type === 'integer' || spec.type === 'bigint' || spec.type === 'decimal'
|
|
184
238
|
? 'number'
|
|
185
239
|
: 'string'
|
|
186
240
|
if (typeof spec.default !== expected)
|
|
187
241
|
return `${where} has the default ${JSON.stringify(spec.default)}, which is not a ${expected}`
|
|
188
|
-
if (
|
|
189
|
-
|
|
242
|
+
if (
|
|
243
|
+
typeof spec.default === 'number' &&
|
|
244
|
+
(spec.type === 'decimal' ? !Number.isFinite(spec.default) : !Number.isSafeInteger(spec.default))
|
|
245
|
+
)
|
|
246
|
+
return `${where} has the default ${spec.default}, which is not a ${spec.type === 'decimal' ? 'finite number' : 'whole number'}`
|
|
190
247
|
if (typeof spec.default === 'string' && !SAFE_DEFAULT.test(spec.default))
|
|
191
248
|
return `${where} has a default with characters a default may not hold: letters, digits, spaces and _ . : @ / - only`
|
|
192
249
|
return undefined
|
|
@@ -197,6 +254,55 @@ const WIDER: Record<string, readonly string[]> = {
|
|
|
197
254
|
integer: ['bigint'],
|
|
198
255
|
}
|
|
199
256
|
|
|
257
|
+
/** The column types a foreign key may join: the same, or integers of either width. */
|
|
258
|
+
const keyFamily = (spec: ColumnSpec): string =>
|
|
259
|
+
spec.type === 'integer' || spec.type === 'bigint'
|
|
260
|
+
? 'integer'
|
|
261
|
+
: spec.type === 'varchar'
|
|
262
|
+
? 'text'
|
|
263
|
+
: spec.type
|
|
264
|
+
|
|
265
|
+
/** Why a column's foreign key cannot be made, or undefined when it can. */
|
|
266
|
+
function referenceProblem(
|
|
267
|
+
schema: ResolvedSchema,
|
|
268
|
+
where: string,
|
|
269
|
+
spec: ColumnSpec,
|
|
270
|
+
self?: { name: string; columns: Map<string, ResolvedColumn> },
|
|
271
|
+
): string | undefined {
|
|
272
|
+
const ref = spec.references
|
|
273
|
+
if (!ref) return undefined
|
|
274
|
+
const target =
|
|
275
|
+
self && ref.table === self.name ? { columns: self.columns } : schema.tables.get(ref.table)
|
|
276
|
+
if (!target) return `${where} points at "${ref.table}", which is not one of this owner's tables`
|
|
277
|
+
const key =
|
|
278
|
+
ref.column === undefined
|
|
279
|
+
? [...target.columns.values()].find((column) => column.spec.primaryKey)
|
|
280
|
+
: target.columns.get(ref.column)
|
|
281
|
+
if (!key) return `${where} points at "${ref.table}.${ref.column}", which does not exist`
|
|
282
|
+
if (!key.spec.primaryKey && !key.spec.unique)
|
|
283
|
+
return `${where} points at "${ref.table}.${key.name}", which is neither a primary key nor unique`
|
|
284
|
+
if (keyFamily(key.spec) !== keyFamily(spec))
|
|
285
|
+
return `${where} is ${spec.type} and points at "${ref.table}.${key.name}", which is ${key.spec.type}`
|
|
286
|
+
if (!['cascade', 'restrict', 'set null'].includes(ref.onDelete))
|
|
287
|
+
return `${where} has the delete rule "${ref.onDelete}", which is not cascade, restrict or set null`
|
|
288
|
+
return undefined
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function columnIndexes(
|
|
292
|
+
table: string,
|
|
293
|
+
column: string,
|
|
294
|
+
spec: ColumnSpec,
|
|
295
|
+
at: { step: string; release: string },
|
|
296
|
+
): ResolvedIndex | undefined {
|
|
297
|
+
if (spec.primaryKey || !(spec.indexed || spec.unique)) return undefined
|
|
298
|
+
return {
|
|
299
|
+
name: indexName(table, [column]),
|
|
300
|
+
columns: [column],
|
|
301
|
+
unique: spec.unique === true,
|
|
302
|
+
addedIn: at,
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
200
306
|
/** Applies one operation, or says why it cannot be applied. */
|
|
201
307
|
function apply(
|
|
202
308
|
schema: ResolvedSchema,
|
|
@@ -210,40 +316,31 @@ function apply(
|
|
|
210
316
|
case 'createTable': {
|
|
211
317
|
const nameProblem = logicalNameProblem('table', op.table)
|
|
212
318
|
if (nameProblem) return `${label}: ${nameProblem}`
|
|
213
|
-
if (RESERVED_TABLES.has(op.table)) return `${label}: the table name "${op.table}" is reserved`
|
|
214
319
|
if (table) return `${label} creates "${op.table}", which already exists`
|
|
215
|
-
const physical = physicalTable(schema.id, op.table)
|
|
216
|
-
const tooLong = lengthProblem(physical)
|
|
217
|
-
if (tooLong) return `${label}: ${tooLong}`
|
|
218
320
|
const columns = new Map<string, ResolvedColumn>()
|
|
219
321
|
const entries = Object.entries(op.columns)
|
|
220
322
|
if (entries.length === 0) return `${label} creates "${op.table}" with no columns`
|
|
221
323
|
for (const [name, spec] of entries) {
|
|
222
324
|
const problem =
|
|
223
|
-
logicalNameProblem('column', name) ??
|
|
224
|
-
(RESERVED_COLUMNS.has(name) ? `the column name "${name}" is reserved` : undefined) ??
|
|
225
|
-
specProblem(spec, `"${op.table}.${name}"`)
|
|
325
|
+
logicalNameProblem('column', name) ?? specProblem(spec, `"${op.table}.${name}"`)
|
|
226
326
|
if (problem) return `${label}: ${problem}`
|
|
227
327
|
columns.set(name, { name, spec, addedIn: at })
|
|
228
328
|
}
|
|
229
329
|
const keys = [...columns.values()].filter((column) => column.spec.primaryKey)
|
|
230
330
|
if (keys.length !== 1)
|
|
231
331
|
return `${label} creates "${op.table}" with ${keys.length} primary keys, not one`
|
|
232
|
-
const
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
332
|
+
for (const column of columns.values()) {
|
|
333
|
+
const problem = referenceProblem(schema, `"${op.table}.${column.name}"`, column.spec, {
|
|
334
|
+
name: op.table,
|
|
335
|
+
columns,
|
|
336
|
+
})
|
|
337
|
+
if (problem) return `${label}: ${problem}`
|
|
338
|
+
}
|
|
339
|
+
const created: ResolvedTable = { name: op.table, columns, indexes: new Map(), addedIn: at }
|
|
340
|
+
for (const column of columns.values()) {
|
|
341
|
+
const index = columnIndexes(op.table, column.name, column.spec, at)
|
|
342
|
+
if (index) created.indexes.set(column.name, index)
|
|
238
343
|
}
|
|
239
|
-
for (const column of columns.values())
|
|
240
|
-
if (column.spec.indexed && !column.spec.primaryKey)
|
|
241
|
-
created.indexes.set(column.name, {
|
|
242
|
-
name: indexName(schema.id, op.table, [column.name]),
|
|
243
|
-
columns: [column.name],
|
|
244
|
-
unique: false,
|
|
245
|
-
addedIn: at,
|
|
246
|
-
})
|
|
247
344
|
schema.tables.set(op.table, created)
|
|
248
345
|
return undefined
|
|
249
346
|
}
|
|
@@ -251,10 +348,8 @@ function apply(
|
|
|
251
348
|
if (!table) return `${label} adds a column to "${op.table}", which does not exist`
|
|
252
349
|
const problem =
|
|
253
350
|
logicalNameProblem('column', op.column) ??
|
|
254
|
-
(
|
|
255
|
-
|
|
256
|
-
: undefined) ??
|
|
257
|
-
specProblem(op.spec, `"${op.table}.${op.column}"`)
|
|
351
|
+
specProblem(op.spec, `"${op.table}.${op.column}"`) ??
|
|
352
|
+
referenceProblem(schema, `"${op.table}.${op.column}"`, op.spec)
|
|
258
353
|
if (problem) return `${label}: ${problem}`
|
|
259
354
|
if (table.columns.has(op.column))
|
|
260
355
|
return `${label} adds "${op.table}.${op.column}", which exists`
|
|
@@ -262,14 +357,14 @@ function apply(
|
|
|
262
357
|
return `${label} adds a primary key to "${op.table}", which a table has already`
|
|
263
358
|
if (!op.spec.nullable && op.spec.default === undefined)
|
|
264
359
|
return `${label} adds "${op.table}.${op.column}" neither nullable nor with a default, which the rows already there cannot satisfy`
|
|
360
|
+
// SQLite adds a column with a foreign key only when it starts out null.
|
|
361
|
+
if (op.spec.references && (!op.spec.nullable || op.spec.default !== undefined))
|
|
362
|
+
return `${label} adds "${op.table}.${op.column}" with a foreign key, which an added column may have only when it is nullable without a default`
|
|
363
|
+
if (op.spec.unique)
|
|
364
|
+
return `${label} adds "${op.table}.${op.column}" as unique; add it, then a unique index in a step of its own`
|
|
265
365
|
table.columns.set(op.column, { name: op.column, spec: op.spec, addedIn: at })
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
name: indexName(schema.id, op.table, [op.column]),
|
|
269
|
-
columns: [op.column],
|
|
270
|
-
unique: false,
|
|
271
|
-
addedIn: at,
|
|
272
|
-
})
|
|
366
|
+
const index = columnIndexes(op.table, op.column, op.spec, at)
|
|
367
|
+
if (index) table.indexes.set(op.column, index)
|
|
273
368
|
return undefined
|
|
274
369
|
}
|
|
275
370
|
case 'addIndex': {
|
|
@@ -278,12 +373,23 @@ function apply(
|
|
|
278
373
|
for (const column of op.columns)
|
|
279
374
|
if (!table.columns.has(column))
|
|
280
375
|
return `${label} indexes "${op.table}.${column}", which does not exist`
|
|
376
|
+
for (const column of op.descending ?? [])
|
|
377
|
+
if (!op.columns.includes(column))
|
|
378
|
+
return `${label} sorts "${op.table}.${column}" descending, which the index does not cover`
|
|
379
|
+
if (op.where) {
|
|
380
|
+
if (!table.columns.has(op.where.column))
|
|
381
|
+
return `${label} limits an index to rows by "${op.table}.${op.where.column}", which does not exist`
|
|
382
|
+
if (op.where.is !== 'null' && op.where.is !== 'not null')
|
|
383
|
+
return `${label} limits an index to rows where a column is "${op.where.is}", not "null" or "not null"`
|
|
384
|
+
}
|
|
281
385
|
const key = op.columns.join(',')
|
|
282
386
|
if (table.indexes.has(key)) return `${label} indexes "${op.table}" (${key}) twice`
|
|
283
387
|
table.indexes.set(key, {
|
|
284
|
-
name: indexName(
|
|
388
|
+
name: indexName(op.table, op.columns),
|
|
285
389
|
columns: [...op.columns],
|
|
286
390
|
unique: op.unique,
|
|
391
|
+
...(op.descending ? { descending: [...op.descending] } : {}),
|
|
392
|
+
...(op.where ? { where: { ...op.where } } : {}),
|
|
287
393
|
addedIn: at,
|
|
288
394
|
})
|
|
289
395
|
return undefined
|
|
@@ -298,33 +404,58 @@ function apply(
|
|
|
298
404
|
(from.type === to.type &&
|
|
299
405
|
from.type === 'varchar' &&
|
|
300
406
|
(to.length ?? 0) > (from.length ?? 0)) ||
|
|
407
|
+
(from.type === to.type &&
|
|
408
|
+
from.type === 'decimal' &&
|
|
409
|
+
(to.scale ?? 0) >= (from.scale ?? 0) &&
|
|
410
|
+
(to.precision ?? 0) - (to.scale ?? 0) >= (from.precision ?? 0) - (from.scale ?? 0) &&
|
|
411
|
+
(to.precision ?? 0) > (from.precision ?? 0)) ||
|
|
301
412
|
(from.type !== to.type && (WIDER[from.type] ?? []).includes(to.type))
|
|
413
|
+
const size = (spec: ColumnSpec) =>
|
|
414
|
+
spec.length ? `(${spec.length})` : spec.precision ? `(${spec.precision},${spec.scale})` : ''
|
|
302
415
|
if (!wider)
|
|
303
|
-
return `${label} changes "${op.table}.${op.column}" from ${from.type}${
|
|
416
|
+
return `${label} changes "${op.table}.${op.column}" from ${from.type}${size(from)} to ${to.type}${size(to)}, which is not wider`
|
|
304
417
|
if (
|
|
305
418
|
to.nullable !== from.nullable ||
|
|
306
419
|
to.default !== from.default ||
|
|
307
|
-
to.primaryKey !== from.primaryKey
|
|
420
|
+
to.primaryKey !== from.primaryKey ||
|
|
421
|
+
JSON.stringify(to.references) !== JSON.stringify(from.references)
|
|
308
422
|
)
|
|
309
423
|
return `${label} widens "${op.table}.${op.column}" and changes more than its type`
|
|
310
424
|
const problem = specProblem(to, `"${op.table}.${op.column}"`)
|
|
311
425
|
if (problem) return `${label}: ${problem}`
|
|
312
|
-
table.columns.set(op.column, {
|
|
426
|
+
table.columns.set(op.column, {
|
|
427
|
+
...column,
|
|
428
|
+
spec: { ...to, indexed: from.indexed, unique: from.unique },
|
|
429
|
+
})
|
|
313
430
|
return undefined
|
|
314
431
|
}
|
|
315
|
-
case 'dropTable':
|
|
432
|
+
case 'dropTable': {
|
|
316
433
|
if (!table) return `${label} drops "${op.table}", which does not exist`
|
|
434
|
+
for (const other of schema.tables.values())
|
|
435
|
+
if (other.name !== op.table)
|
|
436
|
+
for (const column of other.columns.values())
|
|
437
|
+
if (column.spec.references?.table === op.table)
|
|
438
|
+
return `${label} drops "${op.table}" while "${other.name}.${column.name}" points at it; drop that first`
|
|
317
439
|
schema.tables.delete(op.table)
|
|
318
440
|
return undefined
|
|
441
|
+
}
|
|
319
442
|
case 'dropColumn': {
|
|
320
443
|
const column = table?.columns.get(op.column)
|
|
321
444
|
if (!table || !column)
|
|
322
445
|
return `${label} drops "${op.table}.${op.column}", which does not exist`
|
|
323
446
|
if (column.spec.primaryKey)
|
|
324
447
|
return `${label} drops "${op.table}.${op.column}", the primary key`
|
|
448
|
+
if (column.spec.references)
|
|
449
|
+
return `${label} drops "${op.table}.${op.column}", which is a foreign key; SQLite cannot drop one`
|
|
325
450
|
for (const index of table.indexes.values())
|
|
326
|
-
if (index.columns.includes(op.column))
|
|
451
|
+
if (index.columns.includes(op.column) || index.where?.column === op.column)
|
|
327
452
|
return `${label} drops "${op.table}.${op.column}" while an index covers it; drop the index first`
|
|
453
|
+
for (const other of schema.tables.values())
|
|
454
|
+
for (const pointing of other.columns.values()) {
|
|
455
|
+
const ref = pointing.spec.references
|
|
456
|
+
if (ref?.table === op.table && ref.column === op.column)
|
|
457
|
+
return `${label} drops "${op.table}.${op.column}" while "${other.name}.${pointing.name}" points at it`
|
|
458
|
+
}
|
|
328
459
|
table.columns.delete(op.column)
|
|
329
460
|
return undefined
|
|
330
461
|
}
|
|
@@ -352,19 +483,19 @@ function removedAddedIn(
|
|
|
352
483
|
|
|
353
484
|
const DROPS = new Set(['dropTable', 'dropColumn', 'dropIndex'])
|
|
354
485
|
|
|
486
|
+
const hash = (value: string): string => new Bun.CryptoHasher('sha256').update(value).digest('hex')
|
|
487
|
+
|
|
355
488
|
/**
|
|
356
489
|
* Compiles a declaration, collecting every problem rather than stopping at the
|
|
357
|
-
* first. `version` is the
|
|
490
|
+
* first. `version` is the owner's own: no step may claim a release after it.
|
|
358
491
|
*/
|
|
359
|
-
export function
|
|
492
|
+
export function compileTables(tables: CustomTables, version?: string): CompiledTables {
|
|
360
493
|
const id = tables.id
|
|
361
494
|
const problems: string[] = []
|
|
362
|
-
|
|
363
|
-
if (idProblem) problems.push(idProblem)
|
|
364
|
-
let schema: ResolvedSchema = { id, prefix: bundlePrefix(id), tables: new Map() }
|
|
495
|
+
let schema: ResolvedSchema = { id, tables: new Map() }
|
|
365
496
|
const steps: CompiledStep[] = []
|
|
366
497
|
const names = new Set<string>()
|
|
367
|
-
let from =
|
|
498
|
+
let from = tablesInitialState(id)
|
|
368
499
|
let previous: string | undefined
|
|
369
500
|
|
|
370
501
|
for (const [index, step] of tables.steps.entries()) {
|
|
@@ -383,9 +514,54 @@ export function compileBundleTables(tables: BundleTables, version?: string): Com
|
|
|
383
514
|
problems.push(`${label} ships in ${step.release}, before the step ahead of it (${previous})`)
|
|
384
515
|
if (version && compareRelease(step.release, version) > 0)
|
|
385
516
|
problems.push(
|
|
386
|
-
`${label} ships in ${step.release}, which is later than this release
|
|
517
|
+
`${label} ships in ${step.release}, which is later than this release (${version})`,
|
|
387
518
|
)
|
|
388
519
|
previous = step.release
|
|
520
|
+
const to = stateAt(id, index + 1, step.name)
|
|
521
|
+
|
|
522
|
+
if (isSqlStep(step)) {
|
|
523
|
+
if (id !== SITE_OWNER) {
|
|
524
|
+
problems.push(`${label} is SQL, which only the site's own tables may use`)
|
|
525
|
+
continue
|
|
526
|
+
}
|
|
527
|
+
const sql = Array.isArray(step.sql)
|
|
528
|
+
? { sqlite: step.sql as readonly string[], postgres: step.sql as readonly string[] }
|
|
529
|
+
: (step.sql as { sqlite: readonly string[]; postgres: readonly string[] })
|
|
530
|
+
const empty = !Array.isArray(sql.sqlite) || !Array.isArray(sql.postgres)
|
|
531
|
+
if (empty || sql.sqlite.length === 0 || sql.postgres.length === 0) {
|
|
532
|
+
problems.push(`${label} has no SQL for both engines`)
|
|
533
|
+
continue
|
|
534
|
+
}
|
|
535
|
+
if ([...sql.sqlite, ...sql.postgres].some((statement) => typeof statement !== 'string'))
|
|
536
|
+
problems.push(`${label} has a statement that is not a string`)
|
|
537
|
+
const kind: StepKind = step.kind ?? 'expand'
|
|
538
|
+
if (kind !== 'expand' && kind !== 'contract')
|
|
539
|
+
problems.push(`${label} is of the kind "${kind}", not expand or contract`)
|
|
540
|
+
if (kind === 'contract' && !mayShipContract(step.release))
|
|
541
|
+
problems.push(
|
|
542
|
+
`${label} removes something in ${step.release}, but from 1.0 a contract may only ship in a major release (x.0.0)`,
|
|
543
|
+
)
|
|
544
|
+
// The builder does not follow what SQL does, so the tables a SQL step
|
|
545
|
+
// makes are changed by SQL steps.
|
|
546
|
+
const before = clone(schema)
|
|
547
|
+
steps.push({
|
|
548
|
+
name: step.name,
|
|
549
|
+
release: step.release,
|
|
550
|
+
position: index + 1,
|
|
551
|
+
from,
|
|
552
|
+
to,
|
|
553
|
+
kind,
|
|
554
|
+
operations: [],
|
|
555
|
+
sql: { sqlite: [...sql.sqlite], postgres: [...sql.postgres] },
|
|
556
|
+
checksum: hash(canonical(sql)),
|
|
557
|
+
contracts: undefined,
|
|
558
|
+
before,
|
|
559
|
+
after: clone(schema),
|
|
560
|
+
backfill: undefined,
|
|
561
|
+
})
|
|
562
|
+
from = to
|
|
563
|
+
continue
|
|
564
|
+
}
|
|
389
565
|
|
|
390
566
|
let operations: Operation[]
|
|
391
567
|
try {
|
|
@@ -426,11 +602,10 @@ export function compileBundleTables(tables: BundleTables, version?: string): Com
|
|
|
426
602
|
}
|
|
427
603
|
if (kind === 'contract' && !mayShipContract(step.release))
|
|
428
604
|
problems.push(
|
|
429
|
-
`${label} removes something in ${step.release}, but from
|
|
605
|
+
`${label} removes something in ${step.release}, but from 1.0 a contract may only ship in a major release (x.0.0)`,
|
|
430
606
|
)
|
|
431
607
|
schema = working
|
|
432
608
|
|
|
433
|
-
const to = stateAt(id, index + 1, step.name)
|
|
434
609
|
steps.push({
|
|
435
610
|
name: step.name,
|
|
436
611
|
release: step.release,
|
|
@@ -440,7 +615,7 @@ export function compileBundleTables(tables: BundleTables, version?: string): Com
|
|
|
440
615
|
kind,
|
|
441
616
|
operations,
|
|
442
617
|
// Bare hex: the ledger's checksum column holds 64 characters.
|
|
443
|
-
checksum:
|
|
618
|
+
checksum: hash(canonical(operations)),
|
|
444
619
|
contracts,
|
|
445
620
|
before,
|
|
446
621
|
after: clone(schema),
|
|
@@ -451,8 +626,8 @@ export function compileBundleTables(tables: BundleTables, version?: string): Com
|
|
|
451
626
|
|
|
452
627
|
return {
|
|
453
628
|
id,
|
|
454
|
-
stateKey:
|
|
455
|
-
initialState:
|
|
629
|
+
stateKey: tablesStateKey(id),
|
|
630
|
+
initialState: tablesInitialState(id),
|
|
456
631
|
steps,
|
|
457
632
|
schema,
|
|
458
633
|
problems,
|
|
@@ -464,20 +639,18 @@ export function compileBundleTables(tables: BundleTables, version?: string): Com
|
|
|
464
639
|
* own test suite, so it is held to the same rules before it ships as it is when
|
|
465
640
|
* a site wires it.
|
|
466
641
|
*/
|
|
467
|
-
export function assertBundleTables(tables:
|
|
468
|
-
const { problems } =
|
|
642
|
+
export function assertBundleTables(tables: CustomTables, version: string): void {
|
|
643
|
+
const { problems } = compileTables(tables, version)
|
|
469
644
|
if (problems.length > 0)
|
|
470
|
-
throw new Error(
|
|
471
|
-
`The bundle "${tables.id}"'s tables break the rules:\n- ${problems.join('\n- ')}`,
|
|
472
|
-
)
|
|
645
|
+
throw new Error(`The tables of "${tables.id}" break the rules:\n- ${problems.join('\n- ')}`)
|
|
473
646
|
}
|
|
474
647
|
|
|
475
648
|
/** `breaking` exactly when this release of the bundle ships a contract: what its package.json declares. */
|
|
476
649
|
export function bundleTablesCompatibility(
|
|
477
|
-
tables:
|
|
650
|
+
tables: CustomTables,
|
|
478
651
|
version: string,
|
|
479
652
|
): 'compatible' | 'breaking' {
|
|
480
|
-
return
|
|
653
|
+
return compileTables(tables).steps.some(
|
|
481
654
|
(step) => step.kind === 'contract' && compareRelease(step.release, version) === 0,
|
|
482
655
|
)
|
|
483
656
|
? 'breaking'
|