@fabrika/db 0.9.0-dev.10 → 0.9.0-dev.12
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 +5 -5
- package/src/codegen-sqlite.ts +8 -5
- package/src/codegen.ts +64 -27
- package/src/index.ts +2 -0
- package/src/orm-types.ts +18 -10
- package/src/orm.ts +19 -5
- package/src/policy.ts +58 -9
- package/src/store.ts +4 -0
- package/src/tables.ts +3 -0
- package/src/testing-shared.ts +166 -42
- package/src/testing-sqlite.ts +8 -2
- package/src/testing.ts +8 -2
- package/src/vocabulary-tables.ts +88 -17
- package/types/src/codegen.d.ts +24 -11
- package/types/src/index.d.ts +1 -1
- package/types/src/orm-types.d.ts +14 -9
- package/types/src/orm.d.ts +5 -0
- package/types/src/policy.d.ts +6 -2
- package/types/src/tables.d.ts +1 -1
- package/types/src/testing-shared.d.ts +29 -10
- package/types/src/testing-sqlite.d.ts +1 -1
- package/types/src/testing.d.ts +1 -1
- package/types/src/vocabulary-tables.d.ts +82 -16
package/src/testing-shared.ts
CHANGED
|
@@ -46,6 +46,11 @@ export interface WorldRow {
|
|
|
46
46
|
* Each occurs in no other fixture, so one found in an answer to another scope is a leaked row.
|
|
47
47
|
*/
|
|
48
48
|
readonly markers: readonly string[]
|
|
49
|
+
/**
|
|
50
|
+
* The values of the text columns of a row the table already held under a known scope value (`seedWorlds`' `scopes`),
|
|
51
|
+
* which no fixture wrote and other rows may share; empty for a row the fixture inserted.
|
|
52
|
+
*/
|
|
53
|
+
readonly stored: readonly string[]
|
|
49
54
|
}
|
|
50
55
|
|
|
51
56
|
/** One seeded row of an application table, which lies in no dimension. */
|
|
@@ -73,6 +78,8 @@ export interface SeededApplicationRows {
|
|
|
73
78
|
export interface SeededRow {
|
|
74
79
|
readonly key: string
|
|
75
80
|
readonly markers: readonly string[]
|
|
81
|
+
/** Deletes the row, the rows its foreign keys made the fixture insert, and every row that refers to them. */
|
|
82
|
+
readonly remove: () => Promise<void>
|
|
76
83
|
}
|
|
77
84
|
|
|
78
85
|
/**
|
|
@@ -94,12 +101,19 @@ export interface IsolationWorlds {
|
|
|
94
101
|
readonly own: WorldRow
|
|
95
102
|
readonly other: WorldRow
|
|
96
103
|
/**
|
|
97
|
-
* Deletes both rows of the table
|
|
98
|
-
*
|
|
104
|
+
* Deletes both rows of the table it inserted, every container row it inserted when it was given known scope values,
|
|
105
|
+
* and every row that refers to them, however deep; the other containers stay. A case whose rows hold pinned values or
|
|
106
|
+
* known scope values removes them, so the next case can seed the same values again under a unique index.
|
|
99
107
|
*/
|
|
100
108
|
readonly remove: () => Promise<void>
|
|
101
109
|
}
|
|
102
110
|
|
|
111
|
+
/**
|
|
112
|
+
* Known values of dimensions, by dimension: the own world's and the other world's, which differ. A dimension whose values
|
|
113
|
+
* are a fixed set (an enum the input names it by) takes these instead of fresh ones.
|
|
114
|
+
*/
|
|
115
|
+
export type ScopeValues = Readonly<Record<string, { readonly own: string; readonly other: string }>>
|
|
116
|
+
|
|
103
117
|
/** What a test kit seeds through, over its migrated schema. */
|
|
104
118
|
export interface TestSeeding {
|
|
105
119
|
/**
|
|
@@ -108,13 +122,17 @@ export interface TestSeeding {
|
|
|
108
122
|
* marker, so a seed of one, or of a column that places the row, throws. `pins` (column → value) give a text column of
|
|
109
123
|
* `table` a known value instead of its marker: the value in the own row, and `<value>-other` in the other row, which
|
|
110
124
|
* counts among the other row's markers, so a leak of it is still found. A pin of a column that places the row, or of
|
|
111
|
-
* no text column, throws.
|
|
125
|
+
* no text column, throws. `scopes` place each world in known values of a dimension instead of fresh ones: a row of
|
|
126
|
+
* the table that owns it with that key is used as it is stored (a migration wrote it), its containers' values with it,
|
|
127
|
+
* and is inserted otherwise. A stored row of `table` itself takes no `values` or `pins`: they throw. A seed that throws
|
|
128
|
+
* removes what it inserted.
|
|
112
129
|
*/
|
|
113
130
|
seedWorlds<DB, P>(
|
|
114
131
|
tables: Tables<DB, P>,
|
|
115
132
|
table: string,
|
|
116
133
|
values?: Readonly<Record<string, SampleValue>>,
|
|
117
134
|
pins?: Readonly<Record<string, string>>,
|
|
135
|
+
scopes?: ScopeValues,
|
|
118
136
|
): Promise<IsolationWorlds>
|
|
119
137
|
/**
|
|
120
138
|
* Seeds one row of the application table `table`: its key, version and creator stamped, `values` (column → value)
|
|
@@ -133,11 +151,11 @@ export interface TestSeeding {
|
|
|
133
151
|
rows: Readonly<Record<string, Readonly<Record<string, SampleValue>>>>,
|
|
134
152
|
): Promise<SeededApplicationRows>
|
|
135
153
|
/**
|
|
136
|
-
* Seeds one row of `table`, a child or dimension table that lies in the object
|
|
137
|
-
* seeded
|
|
138
|
-
* the markers it holds.
|
|
154
|
+
* Seeds one row of `table`, a child or dimension table that lies in the object `under`'s chain starts at (a row
|
|
155
|
+
* `seedWorlds` seeded, or a value of its chain with the values outside it), placed in that chain: the row a fixture
|
|
156
|
+
* names by id, such as a note's comment. Answers its key and the markers it holds.
|
|
139
157
|
*/
|
|
140
|
-
seedUnder<DB, P>(tables: Tables<DB, P>, table: string, under: WorldRow): Promise<SeededRow>
|
|
158
|
+
seedUnder<DB, P>(tables: Tables<DB, P>, table: string, under: Pick<WorldRow, 'chain'>): Promise<SeededRow>
|
|
141
159
|
/**
|
|
142
160
|
* Values for the policy's insert columns of `table` that its schema accepts: every required one, sampled; a file
|
|
143
161
|
* column a seeded file. `beside` is a row `seedWorlds` seeded that the inserted row will lie beside, in the same
|
|
@@ -245,8 +263,12 @@ export interface SeedingBackend {
|
|
|
245
263
|
* (`checkLimit`, `foreignKeyLimit`, `uniqueValueLimit`).
|
|
246
264
|
*/
|
|
247
265
|
insert(table: string, values: ReadonlyMap<string, SampleValue>): Promise<Readonly<Record<string, unknown>>>
|
|
248
|
-
/** One row of `table
|
|
249
|
-
firstRow(
|
|
266
|
+
/** One row of `table` that holds `where` (column → value; every row when empty), of `columns`, or `undefined` when none does. */
|
|
267
|
+
firstRow(
|
|
268
|
+
table: string,
|
|
269
|
+
columns: readonly string[],
|
|
270
|
+
where?: ReadonlyMap<string, SampleValue>,
|
|
271
|
+
): Promise<Readonly<Record<string, unknown>> | undefined>
|
|
250
272
|
insertFile(file: SeededFile): Promise<void>
|
|
251
273
|
/**
|
|
252
274
|
* Deletes `rows` (each found by its `match`; one already gone is skipped) and every row that refers to one of them,
|
|
@@ -356,6 +378,9 @@ function scopedModel<DB, P>(tables: Tables<DB, P>, table: string): { readonly mo
|
|
|
356
378
|
if (model === undefined) {
|
|
357
379
|
throw new Error(`${table} is not a table of the policies`)
|
|
358
380
|
}
|
|
381
|
+
if (model.view) {
|
|
382
|
+
throw new Error(`${table} is a view, whose rows come from the tables it reads: seed those instead`)
|
|
383
|
+
}
|
|
359
384
|
return { models, model }
|
|
360
385
|
}
|
|
361
386
|
|
|
@@ -673,35 +698,132 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
673
698
|
/** The value a pin gives the row of `world`: as written in the own row, distinct in the other. */
|
|
674
699
|
const pinnedValue = (value: string, world: string): string => (world === 'own' ? value : `${value}-${world}`)
|
|
675
700
|
|
|
701
|
+
/**
|
|
702
|
+
* The dimension values the row of `owner` keyed `key` lies in, as the table stores it: its own, then each container's;
|
|
703
|
+
* `undefined` when the table holds no such row.
|
|
704
|
+
*/
|
|
705
|
+
async function storedChain(owner: TableModel, key: string): Promise<ReadonlyMap<string, string> | undefined> {
|
|
706
|
+
const scope = owner.scope
|
|
707
|
+
if (scope.mode !== 'dimension') return undefined
|
|
708
|
+
const row = await backend.firstRow(owner.name, [scope.key, ...owner.chain.map((link) => link.column)], new Map([[scope.key, key]]))
|
|
709
|
+
if (row === undefined) return undefined
|
|
710
|
+
const chain = new Map([[scope.dimension, key]])
|
|
711
|
+
for (const link of owner.chain) chain.set(link.dimension, String(keyValue(row[link.column], `${owner.name}.${link.column}`)))
|
|
712
|
+
return chain
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* The dimension values a row of `model` lies in for `world`, as far as `scopes` know them: each known value, and every
|
|
717
|
+
* value a stored row of a known one holds. `stored` are the dimensions whose row a table holds already.
|
|
718
|
+
*/
|
|
719
|
+
async function knownValues(
|
|
720
|
+
models: TableModels,
|
|
721
|
+
model: TableModel,
|
|
722
|
+
world: 'own' | 'other',
|
|
723
|
+
scopes: ScopeValues,
|
|
724
|
+
): Promise<{ readonly values: Map<string, string>; readonly stored: ReadonlySet<string> }> {
|
|
725
|
+
const own = model.scope.mode === 'dimension' ? [model.scope.dimension] : []
|
|
726
|
+
const dimensions = [...own, ...model.chain.map((link) => link.dimension)].filter((dimension) => Object.hasOwn(scopes, dimension))
|
|
727
|
+
const values = new Map<string, string>()
|
|
728
|
+
for (const dimension of dimensions) {
|
|
729
|
+
const known = scopes[dimension]
|
|
730
|
+
if (known !== undefined) values.set(dimension, world === 'own' ? known.own : known.other)
|
|
731
|
+
}
|
|
732
|
+
const stored = new Set<string>()
|
|
733
|
+
for (const dimension of dimensions) {
|
|
734
|
+
const owner = ownerOf(models, dimension)
|
|
735
|
+
const value = values.get(dimension)
|
|
736
|
+
const chain = owner === undefined || value === undefined ? undefined : await storedChain(owner, value)
|
|
737
|
+
for (const [type, found] of chain ?? []) {
|
|
738
|
+
const expected = values.get(type)
|
|
739
|
+
if (expected !== undefined && expected !== found) {
|
|
740
|
+
throw new Error(`the stored ${dimension} '${value}' lies in the ${type} '${found}', not in the known '${expected}'`)
|
|
741
|
+
}
|
|
742
|
+
values.set(type, found)
|
|
743
|
+
stored.add(type)
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
return { values, stored }
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/** The values of the text columns that would hold a marker in the stored row of `model` keyed `key`. */
|
|
750
|
+
async function storedTexts(model: TableModel, key: string): Promise<string[]> {
|
|
751
|
+
const scope = model.scope
|
|
752
|
+
if (scope.mode !== 'dimension') return []
|
|
753
|
+
const names: string[] = []
|
|
754
|
+
for (const column of columnsOf(model.name)) {
|
|
755
|
+
if (await holdsMarker(model, model.name, column)) names.push(column.name)
|
|
756
|
+
}
|
|
757
|
+
if (names.length === 0) return []
|
|
758
|
+
const row = await backend.firstRow(model.name, names, new Map([[scope.key, key]]))
|
|
759
|
+
return names.flatMap((name) => {
|
|
760
|
+
const value = row?.[name]
|
|
761
|
+
return typeof value === 'string' && value !== '' ? [value] : []
|
|
762
|
+
})
|
|
763
|
+
}
|
|
764
|
+
|
|
676
765
|
async function seedWorld(
|
|
677
766
|
models: TableModels,
|
|
678
767
|
model: TableModel,
|
|
679
|
-
world:
|
|
768
|
+
world: 'own' | 'other',
|
|
680
769
|
seed: Readonly<Record<string, SampleValue>>,
|
|
681
770
|
pins: Readonly<Record<string, string>>,
|
|
771
|
+
scopes: ScopeValues,
|
|
682
772
|
inserted: InsertedRow[],
|
|
683
773
|
): Promise<{ readonly world: Omit<WorldRow, 'updates'>; readonly row: ReadonlyMap<string, SampleValue> }> {
|
|
684
774
|
const markers: string[] = []
|
|
685
|
-
const values = new Map<string, string>()
|
|
686
|
-
const links: readonly Container[] = model.chain
|
|
687
|
-
for (const link of links) {
|
|
688
|
-
values.set(link.dimension, scopeValue(model.name, link.column, link.dimension, world))
|
|
689
|
-
}
|
|
690
775
|
const scope = model.scope
|
|
691
776
|
if (scope.mode !== 'dimension' && scope.mode !== 'child') {
|
|
692
777
|
throw new Error(`${model.name} is not a dimension or child table`)
|
|
693
778
|
}
|
|
694
|
-
const
|
|
695
|
-
|
|
696
|
-
|
|
779
|
+
const { values, stored } = await knownValues(models, model, world, scopes)
|
|
780
|
+
const links: readonly Container[] = model.chain
|
|
781
|
+
for (const link of links) {
|
|
782
|
+
if (!values.has(link.dimension)) values.set(link.dimension, scopeValue(model.name, link.column, link.dimension, world))
|
|
783
|
+
}
|
|
784
|
+
const own = scope.mode === 'dimension' ? scope.dimension : undefined
|
|
785
|
+
const key = (own === undefined ? undefined : values.get(own)) ?? scopeValue(model.name, scope.key, own ?? model.name, world)
|
|
786
|
+
if (own !== undefined) {
|
|
787
|
+
values.set(own, key)
|
|
788
|
+
}
|
|
789
|
+
const worldRow = (row: ReadonlyMap<string, SampleValue>, stored: readonly string[]) => {
|
|
790
|
+
const chain = [
|
|
791
|
+
...(own === undefined ? [] : [{ type: own, value: key }]),
|
|
792
|
+
...links.flatMap((link) => {
|
|
793
|
+
const value = values.get(link.dimension)
|
|
794
|
+
return value === undefined ? [] : [{ type: link.dimension, value }]
|
|
795
|
+
}),
|
|
796
|
+
]
|
|
797
|
+
const seeded = {
|
|
798
|
+
key,
|
|
799
|
+
parent: scope.mode === 'child' ? (values.get(links[0]?.dimension ?? '') ?? null) : null,
|
|
800
|
+
scope: values.get(grantDimension(models, model)) ?? key,
|
|
801
|
+
chain,
|
|
802
|
+
markers,
|
|
803
|
+
stored,
|
|
804
|
+
}
|
|
805
|
+
return { world: seeded, row }
|
|
697
806
|
}
|
|
698
|
-
|
|
807
|
+
if (own !== undefined && stored.has(own)) {
|
|
808
|
+
if (Object.keys(seed).length > 0 || Object.keys(pins).length > 0) {
|
|
809
|
+
throw new Error(
|
|
810
|
+
`${model.name} already holds the ${own} '${key}' (a migration wrote it), so a case writes no seed or pin into it; seed the state of a row the case inserts`,
|
|
811
|
+
)
|
|
812
|
+
}
|
|
813
|
+
return worldRow(new Map(), await storedTexts(model, key))
|
|
814
|
+
}
|
|
815
|
+
// Containers first, outermost first: a composite foreign key needs its target row. A stored one is used as it is.
|
|
699
816
|
for (let index = links.length - 1; index >= 0; index--) {
|
|
700
817
|
const link = links[index]
|
|
701
818
|
const owner = link === undefined ? undefined : ownerOf(models, link.dimension)
|
|
702
819
|
const value = link === undefined ? undefined : values.get(link.dimension)
|
|
703
|
-
if (owner
|
|
704
|
-
|
|
820
|
+
if (link === undefined || owner === undefined || owner.name === model.name || value === undefined || stored.has(link.dimension)) continue
|
|
821
|
+
// With known values, every container goes with the worlds: one of a known value, so the next case can insert it
|
|
822
|
+
// again, and one inside a stored row, which no removal of that row reaches.
|
|
823
|
+
const tracked = Object.keys(scopes).length > 0 ? inserted : undefined
|
|
824
|
+
await insert(models, owner.name, placement(owner, values, value), markers, 0, tracked)
|
|
825
|
+
if (tracked !== undefined && owner.scope.mode === 'dimension') {
|
|
826
|
+
tracked.push({ table: owner.name, match: new Map([[owner.scope.key, value]]) })
|
|
705
827
|
}
|
|
706
828
|
}
|
|
707
829
|
const assigned = placement(model, values, key)
|
|
@@ -731,22 +853,7 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
731
853
|
}
|
|
732
854
|
const { row } = await insert(models, model.name, assigned, markers)
|
|
733
855
|
inserted.push({ table: model.name, match: new Map([[scope.key, key]]) })
|
|
734
|
-
|
|
735
|
-
const chain = [
|
|
736
|
-
...(scope.mode === 'dimension' ? [{ type: scope.dimension, value: key }] : []),
|
|
737
|
-
...links.flatMap((link) => {
|
|
738
|
-
const value = values.get(link.dimension)
|
|
739
|
-
return value === undefined ? [] : [{ type: link.dimension, value }]
|
|
740
|
-
}),
|
|
741
|
-
]
|
|
742
|
-
const seeded = {
|
|
743
|
-
key,
|
|
744
|
-
parent: scope.mode === 'child' ? (values.get(links[0]?.dimension ?? '') ?? null) : null,
|
|
745
|
-
scope: values.get(dimension) ?? key,
|
|
746
|
-
chain,
|
|
747
|
-
markers,
|
|
748
|
-
}
|
|
749
|
-
return { world: seeded, row }
|
|
856
|
+
return worldRow(row, [])
|
|
750
857
|
}
|
|
751
858
|
|
|
752
859
|
/** A seeded row's values of the policy's update columns: as written, or a sample where the database filled the column. */
|
|
@@ -759,12 +866,27 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
759
866
|
}
|
|
760
867
|
|
|
761
868
|
return {
|
|
762
|
-
async seedWorlds(tables, table, values = {}, pins = {}) {
|
|
869
|
+
async seedWorlds(tables, table, values = {}, pins = {}, scopes = {}) {
|
|
763
870
|
const { models, model } = scopedModel(tables, table)
|
|
764
871
|
const dimension = grantDimension(models, model)
|
|
872
|
+
for (const [name, known] of Object.entries(scopes)) {
|
|
873
|
+
if (known.own === known.other) throw new Error(`the two worlds share the ${name} '${known.own}'; each needs a value of its own`)
|
|
874
|
+
}
|
|
765
875
|
const inserted: InsertedRow[] = []
|
|
766
|
-
|
|
767
|
-
|
|
876
|
+
let own: Awaited<ReturnType<typeof seedWorld>>
|
|
877
|
+
let other: Awaited<ReturnType<typeof seedWorld>>
|
|
878
|
+
try {
|
|
879
|
+
own = await seedWorld(models, model, 'own', values, pins, scopes, inserted)
|
|
880
|
+
other = await seedWorld(models, model, 'other', values, pins, scopes, inserted)
|
|
881
|
+
} catch (error) {
|
|
882
|
+
// A row of a known value left behind would pass for one a migration wrote in every later case.
|
|
883
|
+
try {
|
|
884
|
+
await backend.remove(inserted)
|
|
885
|
+
} catch (cleanup) {
|
|
886
|
+
throw new AggregateError([error, cleanup], 'the isolation fixture could not seed the worlds, nor remove what it had seeded')
|
|
887
|
+
}
|
|
888
|
+
throw error
|
|
889
|
+
}
|
|
768
890
|
// Sampled once both rows are written: a number a unique index covers is the next above what the table holds.
|
|
769
891
|
return {
|
|
770
892
|
dimension,
|
|
@@ -830,8 +952,10 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
830
952
|
}
|
|
831
953
|
const key = scopeValue(table, scope.key, scope.mode === 'dimension' ? scope.dimension : table, 'under')
|
|
832
954
|
const markers: string[] = []
|
|
833
|
-
|
|
834
|
-
|
|
955
|
+
const inserted: InsertedRow[] = []
|
|
956
|
+
await insert(models, table, placement(model, values, key), markers, 0, inserted)
|
|
957
|
+
inserted.push({ table, match: new Map([[scope.key, key]]) })
|
|
958
|
+
return { key, markers, remove: () => backend.remove(inserted) }
|
|
835
959
|
},
|
|
836
960
|
async sampleInsert(tables, table, beside) {
|
|
837
961
|
const { models, model } = scopedModel(tables, table)
|
package/src/testing-sqlite.ts
CHANGED
|
@@ -45,6 +45,7 @@ export {
|
|
|
45
45
|
type ApplicationRow,
|
|
46
46
|
type IsolationWorlds,
|
|
47
47
|
type SampleValue,
|
|
48
|
+
type ScopeValues,
|
|
48
49
|
SEEDED_OBJECT_VERSION,
|
|
49
50
|
type SeededApplicationRows,
|
|
50
51
|
type SeededRow,
|
|
@@ -487,8 +488,13 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
|
|
|
487
488
|
throw seedLimit(error, table) ?? error
|
|
488
489
|
}
|
|
489
490
|
},
|
|
490
|
-
async firstRow(table, selected) {
|
|
491
|
-
|
|
491
|
+
async firstRow(table, selected, where = new Map()) {
|
|
492
|
+
const names = [...where.keys()]
|
|
493
|
+
const condition = names.length === 0 ? '' : ` WHERE ${names.map((name) => `${quoted(name)} = ?`).join(' AND ')}`
|
|
494
|
+
return exec(
|
|
495
|
+
`SELECT ${selected.map(quoted).join(', ')} FROM ${quoted(table)}${condition} LIMIT 1`,
|
|
496
|
+
...names.map((name) => binding(where.get(name) ?? null)),
|
|
497
|
+
)[0]
|
|
492
498
|
},
|
|
493
499
|
async insertFile(file) {
|
|
494
500
|
exec(
|
package/src/testing.ts
CHANGED
|
@@ -48,6 +48,7 @@ export {
|
|
|
48
48
|
type ApplicationRow,
|
|
49
49
|
type IsolationWorlds,
|
|
50
50
|
type SampleValue,
|
|
51
|
+
type ScopeValues,
|
|
51
52
|
SEEDED_OBJECT_VERSION,
|
|
52
53
|
type SeededApplicationRows,
|
|
53
54
|
type SeededRow,
|
|
@@ -448,8 +449,13 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
|
|
|
448
449
|
const [returned] = z.array(z.record(z.string(), z.unknown())).parse(stored)
|
|
449
450
|
return returned ?? {}
|
|
450
451
|
},
|
|
451
|
-
async firstRow(table, columns) {
|
|
452
|
-
const
|
|
452
|
+
async firstRow(table, columns, where = new Map()) {
|
|
453
|
+
const names = [...where.keys()]
|
|
454
|
+
const condition = names.length === 0 ? '' : ` WHERE ${names.map((name, index) => `${quoted(name)} = $${index + 1}`).join(' AND ')}`
|
|
455
|
+
const selected: unknown = await seeder.unsafe(
|
|
456
|
+
`SELECT ${columns.map(quoted).join(', ')} FROM ${quoted(schema)}.${quoted(table)}${condition} LIMIT 1`,
|
|
457
|
+
names.map((name) => where.get(name) ?? null),
|
|
458
|
+
)
|
|
453
459
|
return z.array(z.record(z.string(), z.unknown())).parse(selected)[0]
|
|
454
460
|
},
|
|
455
461
|
async insertFile(file) {
|
package/src/vocabulary-tables.ts
CHANGED
|
@@ -1,20 +1,40 @@
|
|
|
1
1
|
// The table policies of the vocabulary form, `defineTables(vocabulary, columns)`: how an application writes them, with
|
|
2
2
|
// containment taken from the vocabulary, and the normalized policies the kit and the handles read. Types only.
|
|
3
3
|
|
|
4
|
-
import type {
|
|
4
|
+
import type {
|
|
5
|
+
ColumnList,
|
|
6
|
+
ColumnPolicies,
|
|
7
|
+
FilePolicies,
|
|
8
|
+
RecordActions,
|
|
9
|
+
ReferencePolicy,
|
|
10
|
+
TableAction,
|
|
11
|
+
TableActions,
|
|
12
|
+
Tables,
|
|
13
|
+
VersionColumn,
|
|
14
|
+
} from './policy'
|
|
5
15
|
|
|
6
16
|
declare const databaseType: unique symbol
|
|
17
|
+
declare const viewNames: unique symbol
|
|
7
18
|
|
|
8
19
|
/**
|
|
9
|
-
* The generated column list (`src/db/schema.generated.ts`), which also carries the schema's row types
|
|
10
|
-
* `defineTables(vocabulary, columns)` takes no type argument. The
|
|
20
|
+
* The generated column list (`src/db/schema.generated.ts`), which also carries the schema's row types and the names of
|
|
21
|
+
* its views, so that `defineTables(vocabulary, columns)` takes no type argument. The brands are type-only: no value
|
|
22
|
+
* has either property.
|
|
11
23
|
*/
|
|
12
|
-
export type TypedColumnList<DB> = ColumnList<DB> & {
|
|
24
|
+
export type TypedColumnList<DB, Views extends keyof DB & string = never> = ColumnList<DB> & {
|
|
25
|
+
readonly [databaseType]?: DB
|
|
26
|
+
readonly [viewNames]?: { readonly views: Views }
|
|
27
|
+
}
|
|
13
28
|
|
|
14
29
|
/** The row types a typed column list carries; `never` for a list without them. */
|
|
15
30
|
export type ColumnTypes<C> = typeof databaseType extends keyof C ? C extends { readonly [databaseType]?: infer DB } ? Exclude<DB, undefined> : never
|
|
16
31
|
: never
|
|
17
32
|
|
|
33
|
+
/** The views a typed column list names; `never` for a list without views. */
|
|
34
|
+
export type ColumnViews<C> = typeof viewNames extends keyof C
|
|
35
|
+
? C extends { readonly [viewNames]?: { readonly views: infer Views extends string } } ? Views : never
|
|
36
|
+
: never
|
|
37
|
+
|
|
18
38
|
/**
|
|
19
39
|
* What `defineTables(vocabulary, columns)` reads of `@fabrika/app/contract`'s `defineVocabulary` result: the action
|
|
20
40
|
* and dimension names, and each dimension's container. `@fabrika/db` does not import `@fabrika/app`.
|
|
@@ -126,6 +146,43 @@ type AuthoredChildPolicy<Table extends string, Col extends string, A extends str
|
|
|
126
146
|
& {
|
|
127
147
|
readonly scope: ChildScopes<Table, Col, S, P>
|
|
128
148
|
}
|
|
149
|
+
/** What a view's policy holds besides its scope: read actions only, no write list and no stamped column. */
|
|
150
|
+
type ViewIsReadOnly = 'a view is never written: its actions are read, appRead and appCount'
|
|
151
|
+
|
|
152
|
+
/** The write actions a view's policy may not name, each typed as the message: a literal is not checked for excess keys. */
|
|
153
|
+
interface NoWriteActions {
|
|
154
|
+
readonly insert?: ViewIsReadOnly
|
|
155
|
+
readonly update?: ViewIsReadOnly
|
|
156
|
+
readonly delete?: ViewIsReadOnly
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
interface ReadOnlyFields<Col extends string, A extends string> {
|
|
160
|
+
readonly actions: { readonly read: TableAction<A>; readonly appRead?: readonly A[]; readonly appCount?: readonly A[] } & NoWriteActions
|
|
161
|
+
readonly insert?: never
|
|
162
|
+
readonly update?: never
|
|
163
|
+
readonly version?: never
|
|
164
|
+
readonly createdBy?: never
|
|
165
|
+
readonly queue?: never
|
|
166
|
+
readonly files?: never
|
|
167
|
+
readonly columns?: { readonly [C in Col]?: { readonly read: A; readonly write?: never } }
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** A view read as a child table: its parent's `Ref` and `Within` read it; nothing writes it (ADR-0072). */
|
|
171
|
+
type AuthoredChildViewPolicy<Table extends string, Col extends string, A extends string, S, P> = ReadOnlyFields<Col, A> & {
|
|
172
|
+
readonly scope: ChildScopes<Table, Col, S, P>
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** A view's policy as written: a read-only child, or a reference table every site reads. */
|
|
176
|
+
export type VocabularyViewPolicy<Table extends string, Col extends string, A extends string, S = unknown, P = unknown> = S extends
|
|
177
|
+
{ readonly child: unknown } ? AuthoredChildViewPolicy<Table, Col, A, S, P>
|
|
178
|
+
: S extends { readonly reference: unknown } ? ReferenceViewPolicy<Col, A>
|
|
179
|
+
: AuthoredChildViewPolicy<Table, Col, A, S, P> | ReferenceViewPolicy<Col, A>
|
|
180
|
+
|
|
181
|
+
type ReferenceViewPolicy<Col extends string, A extends string> = ReferencePolicy<Col, A> & {
|
|
182
|
+
readonly actions: NoWriteActions
|
|
183
|
+
readonly columns?: { readonly [C in Col]?: { readonly read: A; readonly write?: never } }
|
|
184
|
+
}
|
|
185
|
+
|
|
129
186
|
/** An application table's scope: why its rows belong to no dimension; `key` defaults to `id`. */
|
|
130
187
|
type AuthoredApplicationPolicy<Col extends string, A extends string, Ver extends Col> = WritableFields<Col, A, Ver> & {
|
|
131
188
|
readonly scope: { readonly app: string } & KeyField<Col>
|
|
@@ -157,15 +214,24 @@ type AnyTablePolicy<DB, V, T extends keyof DB & string> = VocabularyTablePolicy<
|
|
|
157
214
|
VersionColumn<DB[T]>
|
|
158
215
|
>
|
|
159
216
|
|
|
217
|
+
/** The policy of view `T` with nothing stated: both forms, any parent. */
|
|
218
|
+
type AnyViewPolicy<DB, V, T extends keyof DB & string> = VocabularyViewPolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>>
|
|
219
|
+
|
|
160
220
|
/**
|
|
161
|
-
* Every table of the schema, and no other, maps to a policy; a
|
|
162
|
-
* `P` is the policies as written, which picks each table's form by the scope it
|
|
163
|
-
* map's own annotation states nothing narrower, so it is checked against every
|
|
221
|
+
* Every table of the schema, and no other, maps to a policy; a view `Views` names may (ADR-0072). A misspelt action or
|
|
222
|
+
* dimension fails at its own line. `P` is the policies as written, which picks each table's form by the scope it
|
|
223
|
+
* states; a policy written under this map's own annotation states nothing narrower, so it is checked against every
|
|
224
|
+
* form.
|
|
164
225
|
*/
|
|
165
|
-
export type VocabularyPolicyMap<DB, V, P = unknown> =
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
226
|
+
export type VocabularyPolicyMap<DB, V, P = unknown, Views extends string = never> =
|
|
227
|
+
& {
|
|
228
|
+
readonly [T in Exclude<keyof DB & string, Views>]: AnyTablePolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyTablePolicy<DB, V, T>
|
|
229
|
+
: VocabularyTablePolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, V, VersionColumn<DB[T]>, StatedScope<P, T>, P>
|
|
230
|
+
}
|
|
231
|
+
& {
|
|
232
|
+
readonly [T in Views & keyof DB & string]?: AnyViewPolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyViewPolicy<DB, V, T>
|
|
233
|
+
: VocabularyViewPolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, StatedScope<P, T>, P>
|
|
234
|
+
}
|
|
169
235
|
|
|
170
236
|
type Flat<T> = { [K in keyof T]: T[K] }
|
|
171
237
|
|
|
@@ -192,15 +258,20 @@ type NormalScope<S, V, P> = S extends { readonly dimension: infer D extends stri
|
|
|
192
258
|
: S extends { readonly app: infer R extends string } ? { readonly app: R; readonly key: KeyOf<S> }
|
|
193
259
|
: S
|
|
194
260
|
|
|
261
|
+
/** A view's normalized policy says so, which the handle types read: no site writes it. */
|
|
262
|
+
type ViewMark<T, Views> = T extends Views ? { readonly view: true } : unknown
|
|
263
|
+
|
|
195
264
|
/**
|
|
196
265
|
* The policies as the layer models them: every dimension table's key and container, and every child's key and
|
|
197
|
-
* column, stated as the vocabulary and the conventions derive them.
|
|
266
|
+
* column, stated as the vocabulary and the conventions derive them; each view marked.
|
|
198
267
|
*/
|
|
199
|
-
export type NormalizedPolicies<P, V> = {
|
|
200
|
-
readonly [T in keyof P]: P[T] extends { readonly scope: infer S }
|
|
268
|
+
export type NormalizedPolicies<P, V, Views = never> = {
|
|
269
|
+
readonly [T in keyof P]: P[T] extends { readonly scope: infer S }
|
|
270
|
+
? Flat<Omit<P[T], 'scope' | 'view'> & { readonly scope: NormalScope<S, V, P> } & ViewMark<T, Views>>
|
|
271
|
+
: P[T]
|
|
201
272
|
}
|
|
202
273
|
|
|
203
|
-
/** Takes the policies of exactly the tables of the schema, written in the vocabulary form. */
|
|
204
|
-
export type DefineVocabularyPolicies<DB, V> = <const P extends VocabularyPolicyMap<DB, V, P>>(
|
|
274
|
+
/** Takes the policies of exactly the tables of the schema, and of any of its views, written in the vocabulary form. */
|
|
275
|
+
export type DefineVocabularyPolicies<DB, V, Views extends string = never> = <const P extends VocabularyPolicyMap<DB, V, P, Views>>(
|
|
205
276
|
policies: P & { readonly [K in Exclude<keyof P, keyof DB>]: never },
|
|
206
|
-
) => Tables<DB, NormalizedPolicies<P, V>>
|
|
277
|
+
) => Tables<DB, NormalizedPolicies<P, V, Views>>
|
package/types/src/codegen.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ export declare class CodegenError extends Error {
|
|
|
14
14
|
}
|
|
15
15
|
declare const catalogColumnSchema: z.ZodObject<{
|
|
16
16
|
table_name: z.ZodString;
|
|
17
|
+
view: z.ZodBoolean;
|
|
17
18
|
column_name: z.ZodString;
|
|
18
19
|
type_name: z.ZodString;
|
|
19
20
|
type_type: z.ZodString;
|
|
@@ -61,20 +62,27 @@ export interface DescribedColumn {
|
|
|
61
62
|
/** The column list field that names the column: a day, a timestamp, a JSON column, or (on SQLite) a boolean. */
|
|
62
63
|
readonly list: 'dates' | 'timestamps' | 'booleans' | 'json' | undefined;
|
|
63
64
|
}
|
|
64
|
-
/**
|
|
65
|
+
/**
|
|
66
|
+
* A column `describe` leaves out of the module: a generated column, or a view's column, of a type the data layer does
|
|
67
|
+
* not read.
|
|
68
|
+
*/
|
|
65
69
|
export interface LeftOut {
|
|
66
|
-
/** The column's type, as its author wrote it. */
|
|
70
|
+
/** The column's type, as its author wrote it (empty: a SQLite view's expression, which has none). */
|
|
67
71
|
readonly leftOut: string;
|
|
72
|
+
readonly of: LeftOutKind;
|
|
68
73
|
}
|
|
74
|
+
/** Why a column is left out rather than refused: it is computed, by a generated column or by a view. */
|
|
75
|
+
export type LeftOutKind = 'generated' | 'view';
|
|
69
76
|
/** A column the module leaves out; only `ctx.sql` reaches it. */
|
|
70
77
|
export interface LeftOutColumn {
|
|
71
78
|
readonly table: string;
|
|
72
79
|
readonly column: string;
|
|
73
80
|
/** Its type, as its author wrote it. */
|
|
74
81
|
readonly type: string;
|
|
82
|
+
readonly of: LeftOutKind;
|
|
75
83
|
}
|
|
76
84
|
/** What codegen says of a left-out column: in the module, `name` is the column; in its output, `table.column`. */
|
|
77
|
-
export declare function leftOutText(name: string, type: string): string;
|
|
85
|
+
export declare function leftOutText(name: string, type: string, of: LeftOutKind): string;
|
|
78
86
|
/** Why a left-out column refuses the schema: the table would lose a key, or a foreign key a column. */
|
|
79
87
|
export declare function leftOutRefusal(path: string, what: string): CodegenError;
|
|
80
88
|
/** The text of `SCHEMA_FILE`, and the columns it leaves out, for the command to name. */
|
|
@@ -94,20 +102,25 @@ export interface NamedColumn {
|
|
|
94
102
|
readonly table_name: string;
|
|
95
103
|
readonly column_name: string;
|
|
96
104
|
}
|
|
105
|
+
/** A column of a table or of a view, as `renderTables` reads it. */
|
|
106
|
+
export interface RelationColumn extends NamedColumn {
|
|
107
|
+
/** The relation is a view: read-only, with no key or foreign key. */
|
|
108
|
+
readonly view: boolean;
|
|
109
|
+
}
|
|
97
110
|
/**
|
|
98
|
-
* The generated module: one interface per application table, the `DB` map Kysely and `defineTables` take,
|
|
99
|
-
* runtime column list with each table's foreign keys to application tables
|
|
100
|
-
* Deterministic for a given catalog, so `fabrika db codegen --verify` can compare text.
|
|
111
|
+
* The generated module: one interface per application table and view, the `DB` map Kysely and `defineTables` take,
|
|
112
|
+
* and the runtime column list with each table's foreign keys to application tables and each view marked; with the
|
|
113
|
+
* columns it leaves out. Deterministic for a given catalog, so `fabrika db codegen --verify` can compare text.
|
|
101
114
|
*/
|
|
102
115
|
export declare function renderSchema(catalog: readonly CatalogColumn[], foreignKeys?: readonly CatalogForeignKey[]): GeneratedModule;
|
|
103
116
|
/**
|
|
104
117
|
* `renderSchema` over columns of any database: `describe` gives each column's types and list field, refuses a type the
|
|
105
|
-
* data layer does not read, or answers `LeftOut` for a generated column of such a type. That column
|
|
106
|
-
* module but for a comment where it stands, so no handle reads or writes it and only `ctx.sql`
|
|
107
|
-
* key that names it, and a table it would leave without a column, are refused
|
|
108
|
-
* not rendered; keys keep the given order.
|
|
118
|
+
* data layer does not read, or answers `LeftOut` for a generated column or a view's column of such a type. That column
|
|
119
|
+
* is left out of the module but for a comment where it stands, so no handle reads or writes it and only `ctx.sql`
|
|
120
|
+
* reaches it; a foreign key that names it, and a table it would leave without a column, are refused, and a view left
|
|
121
|
+
* without a column is left out whole. A foreign key's `constraint_name` is not rendered; keys keep the given order.
|
|
109
122
|
*/
|
|
110
|
-
export declare function renderTables<C extends
|
|
123
|
+
export declare function renderTables<C extends RelationColumn>(catalog: readonly C[], foreignKeys: readonly ForeignKeyColumns[], describe: (column: C) => DescribedColumn | LeftOut): GeneratedModule;
|
|
111
124
|
/** Introspects the migrated schema, checked against the migrations' manifest, and renders the module for `SCHEMA_FILE`. */
|
|
112
125
|
export declare function generateSchema(url: string, schema: string, objects: readonly DatabaseObject[]): Promise<GeneratedModule>;
|
|
113
126
|
export {};
|
package/types/src/index.d.ts
CHANGED
|
@@ -8,4 +8,4 @@ export type { AnyDbIndex, ChildRows, ContainedRows, CountOptions, DataKind, DbIn
|
|
|
8
8
|
export { type ChildPolicy, type ChildScope, type ColumnList, defineTables, type DimensionPolicy, type DimensionScope, type InsertValues, isTables, readTables, type RecordActions, type ReferencePolicy, type ReferenceScope, type RowOf, type TableActions, type TableInsert, Tables, type TableUpdate, type UpdateValues, type VersionColumn, type VocabularyTables, } from './policy';
|
|
9
9
|
export { type AggregateRow, type AggregateSpec, type ChildListScope, type DataLayer, type DataLayerRuntime, scoped, type ScopedDatabase, } from './store';
|
|
10
10
|
export { type TablePolicies, tablePolicies } from './tables';
|
|
11
|
-
export type { ColumnTypes, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, } from './vocabulary-tables';
|
|
11
|
+
export type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, VocabularyViewPolicy, } from './vocabulary-tables';
|