@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
package/src/site-search.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { ObjectTypes, type SiteSearchLevel } from '@crombolo/core'
|
|
8
8
|
import type { Db } from './database.ts'
|
|
9
9
|
import { DbDate, fromDbBool } from './dialect.ts'
|
|
10
|
+
import { sql } from './query.ts'
|
|
10
11
|
import { publishedValueRows } from './repositories/documents.ts'
|
|
11
12
|
import { hiddenElementProperties } from './search.ts'
|
|
12
13
|
import { searchTerms, searchWords, valueText } from './search-text.ts'
|
|
@@ -51,8 +52,6 @@ const LEVELS: readonly SiteSearchLevel[] = ['high', 'normal', 'low']
|
|
|
51
52
|
|
|
52
53
|
const folded = (texts: readonly string[]) => texts.flatMap(searchWords).join(' ')
|
|
53
54
|
|
|
54
|
-
const marks = (n: number) => Array.from({ length: n }, () => '?').join(', ')
|
|
55
|
-
|
|
56
55
|
/**
|
|
57
56
|
* What the site-search index holds for a page: a row per published culture,
|
|
58
57
|
* or one invariant row, from the values that culture shows visitors. Nothing
|
|
@@ -62,14 +61,26 @@ const marks = (n: number) => Array.from({ length: n }, () => '?').join(', ')
|
|
|
62
61
|
* here and inside blocks.
|
|
63
62
|
*/
|
|
64
63
|
export async function siteEntriesFor(db: Db, nodeId: number): Promise<SiteSearchEntry[]> {
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
64
|
+
const node = await db.q
|
|
65
|
+
.selectFrom('node as n')
|
|
66
|
+
.innerJoin('content as c', 'c.node_id', 'n.id')
|
|
67
|
+
.innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
|
|
68
|
+
.innerJoin('document as d', 'd.node_id', 'n.id')
|
|
69
|
+
.select((eb) => [
|
|
70
|
+
'n.node_object_type',
|
|
71
|
+
'n.trashed',
|
|
72
|
+
'c.content_type_id',
|
|
73
|
+
'ct.site_search',
|
|
74
|
+
'ct.is_element',
|
|
75
|
+
'd.published',
|
|
76
|
+
eb
|
|
77
|
+
.selectFrom('content_type_template as t')
|
|
78
|
+
.select((sub) => sub.fn.countAll().as('n'))
|
|
79
|
+
.whereRef('t.content_type_node_id', '=', 'ct.node_id')
|
|
80
|
+
.as('components'),
|
|
81
|
+
])
|
|
82
|
+
.where('n.id', '=', nodeId)
|
|
83
|
+
.executeTakeFirst()
|
|
73
84
|
if (
|
|
74
85
|
!node ||
|
|
75
86
|
String(node.node_object_type) !== ObjectTypes.Document ||
|
|
@@ -81,19 +92,30 @@ export async function siteEntriesFor(db: Db, nodeId: number): Promise<SiteSearch
|
|
|
81
92
|
)
|
|
82
93
|
return []
|
|
83
94
|
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
[
|
|
88
|
-
|
|
95
|
+
const invariant = await db.q
|
|
96
|
+
.selectFrom('content_version as cv')
|
|
97
|
+
.innerJoin('document_version as dv', 'dv.id', 'cv.id')
|
|
98
|
+
.select(['cv.id', 'cv.text'])
|
|
99
|
+
.where('cv.node_id', '=', nodeId)
|
|
100
|
+
.where('dv.published', '=', db.dialect.boolValue(true) as boolean)
|
|
101
|
+
.orderBy('cv.id', 'desc')
|
|
102
|
+
.limit(1)
|
|
103
|
+
.executeTakeFirst()
|
|
89
104
|
if (!invariant) return []
|
|
90
105
|
const cultures = (
|
|
91
|
-
await db.
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
106
|
+
await db.q
|
|
107
|
+
.selectFrom('document_culture_variation as dcv')
|
|
108
|
+
.innerJoin('language as l', 'l.id', 'dcv.language_id')
|
|
109
|
+
.select([
|
|
110
|
+
'dcv.language_id',
|
|
111
|
+
'l.iso_code',
|
|
112
|
+
'dcv.published_event_id',
|
|
113
|
+
'dcv.published_name',
|
|
114
|
+
'dcv.name',
|
|
115
|
+
])
|
|
116
|
+
.where('dcv.node_id', '=', nodeId)
|
|
117
|
+
.where('dcv.published', '=', db.dialect.boolValue(true) as boolean)
|
|
118
|
+
.execute()
|
|
97
119
|
).map((row) => ({
|
|
98
120
|
languageId: Number(row.language_id),
|
|
99
121
|
culture: String(row.iso_code).toLowerCase(),
|
|
@@ -103,15 +125,27 @@ export async function siteEntriesFor(db: Db, nodeId: number): Promise<SiteSearch
|
|
|
103
125
|
|
|
104
126
|
const latest = Math.max(Number(invariant.id), ...cultures.map((c) => c.eventId))
|
|
105
127
|
const history = (
|
|
106
|
-
await db.
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
128
|
+
await db.q
|
|
129
|
+
.selectFrom('property_value as pv')
|
|
130
|
+
.innerJoin('property_type as p', 'p.id', 'pv.property_type_id')
|
|
131
|
+
.select([
|
|
132
|
+
'pv.id',
|
|
133
|
+
'pv.event_id',
|
|
134
|
+
'pv.property_type_id',
|
|
135
|
+
'pv.language_id',
|
|
136
|
+
'pv.segment',
|
|
137
|
+
'pv.varchar_value',
|
|
138
|
+
'pv.text_value',
|
|
139
|
+
'p.alias',
|
|
140
|
+
'p.site_search',
|
|
141
|
+
])
|
|
142
|
+
.where('pv.node_id', '=', nodeId)
|
|
143
|
+
.where('pv.event_id', '<=', latest)
|
|
144
|
+
.where('p.retired_at', 'is', null)
|
|
145
|
+
.where('p.searchable', '=', db.dialect.boolValue(true))
|
|
146
|
+
.where('p.site_search', '<>', 'off')
|
|
147
|
+
.orderBy('pv.id')
|
|
148
|
+
.execute()
|
|
115
149
|
).map((row) => ({
|
|
116
150
|
eventId: Number(row.event_id),
|
|
117
151
|
propertyTypeId: Number(row.property_type_id),
|
|
@@ -125,9 +159,7 @@ export async function siteEntriesFor(db: Db, nodeId: number): Promise<SiteSearch
|
|
|
125
159
|
const shown = publishedValueRows(history, Number(invariant.id), cultures).filter(
|
|
126
160
|
(row) => row.segment === null,
|
|
127
161
|
)
|
|
128
|
-
const hidden = await hiddenElementProperties(db,
|
|
129
|
-
db.dialect.boolValue(false),
|
|
130
|
-
])
|
|
162
|
+
const hidden = await hiddenElementProperties(db, true)
|
|
131
163
|
|
|
132
164
|
const entry = (culture: string, languageId: number | null, name: string): SiteSearchEntry => {
|
|
133
165
|
const text: SiteSearchText = { name, high: [], normal: [], low: [] }
|
|
@@ -147,23 +179,22 @@ export async function writeSiteEntries(
|
|
|
147
179
|
nodeId: number,
|
|
148
180
|
entries: readonly SiteSearchEntry[],
|
|
149
181
|
): Promise<void> {
|
|
150
|
-
await tx.
|
|
151
|
-
const
|
|
182
|
+
await tx.q.deleteFrom('site_search_document').where('node_id', '=', nodeId).execute()
|
|
183
|
+
const indexedAt = DbDate.toDb(new Date())
|
|
152
184
|
for (const entry of entries)
|
|
153
|
-
await tx.
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
entry.
|
|
159
|
-
folded(
|
|
160
|
-
folded(entry.text.
|
|
161
|
-
folded(entry.text.
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
)
|
|
185
|
+
await tx.q
|
|
186
|
+
.insertInto('site_search_document')
|
|
187
|
+
.values({
|
|
188
|
+
node_id: nodeId,
|
|
189
|
+
culture: entry.culture,
|
|
190
|
+
name: folded([entry.text.name]),
|
|
191
|
+
high: folded(entry.text.high),
|
|
192
|
+
normal: folded(entry.text.normal),
|
|
193
|
+
low: folded(entry.text.low),
|
|
194
|
+
text: JSON.stringify(entry.text),
|
|
195
|
+
indexed_at: indexedAt,
|
|
196
|
+
})
|
|
197
|
+
.execute()
|
|
167
198
|
}
|
|
168
199
|
|
|
169
200
|
/**
|
|
@@ -185,45 +216,65 @@ export class SiteSearch {
|
|
|
185
216
|
): Promise<{ total: number; items: SiteSearchHit[] }> {
|
|
186
217
|
const terms = searchTerms(term)
|
|
187
218
|
if (terms.length === 0) return { total: 0, items: [] }
|
|
188
|
-
const
|
|
189
|
-
const params: unknown[] = [
|
|
190
|
-
this.#db.dialect.fullTextQuery(terms),
|
|
191
|
-
options.culture.toLowerCase(),
|
|
192
|
-
'',
|
|
193
|
-
this.#db.dialect.boolValue(false),
|
|
194
|
-
]
|
|
219
|
+
const dialect = this.#db.dialect
|
|
195
220
|
const types = options.types?.filter(Boolean) ?? []
|
|
196
|
-
if (types.length > 0) {
|
|
197
|
-
where.push(`ct.alias IN (${marks(types.length)})`)
|
|
198
|
-
params.push(...types)
|
|
199
|
-
}
|
|
200
221
|
const denied = options.access?.denied ?? []
|
|
201
222
|
const allowed = options.access?.allowed ?? []
|
|
202
|
-
|
|
223
|
+
const hits = this.#db.q
|
|
224
|
+
.selectFrom(dialect.siteSearchMatches(dialect.fullTextQuery(terms)).as('h'))
|
|
225
|
+
.innerJoin('site_search_document as s', 's.id', 'h.row_id')
|
|
226
|
+
.innerJoin('node as n', 'n.id', 's.node_id')
|
|
227
|
+
.innerJoin('content as c', 'c.node_id', 'n.id')
|
|
228
|
+
.innerJoin('content_type as ct', 'ct.node_id', 'c.content_type_id')
|
|
229
|
+
.where('s.culture', 'in', [options.culture.toLowerCase(), ''])
|
|
230
|
+
.where('n.trashed', '=', dialect.boolValue(false) as boolean)
|
|
231
|
+
.$if(types.length > 0, (q) => q.where('ct.alias', 'in', types))
|
|
203
232
|
// Closed: under a denied node, with no allowed node between it and the page.
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
233
|
+
.$if(denied.length > 0, (q) =>
|
|
234
|
+
q.where(({ not, exists, selectFrom }) =>
|
|
235
|
+
not(
|
|
236
|
+
exists(
|
|
237
|
+
selectFrom('node as p')
|
|
238
|
+
.select((eb) => eb.lit(1).as('one'))
|
|
239
|
+
.where('p.id', 'in', denied)
|
|
240
|
+
.where((eb) =>
|
|
241
|
+
eb.or([
|
|
242
|
+
eb('p.id', '=', eb.ref('n.id')),
|
|
243
|
+
eb('n.path', 'like', sql<string>`${eb.ref('p.path')} || ',%'`),
|
|
244
|
+
]),
|
|
245
|
+
)
|
|
246
|
+
.$if(allowed.length > 0, (sub) =>
|
|
247
|
+
sub.where(({ not, exists, selectFrom }) =>
|
|
248
|
+
not(
|
|
249
|
+
exists(
|
|
250
|
+
selectFrom('node as q')
|
|
251
|
+
.select((eb) => eb.lit(1).as('one'))
|
|
252
|
+
.where('q.id', 'in', allowed)
|
|
253
|
+
.where((eb) =>
|
|
254
|
+
eb.or([
|
|
255
|
+
eb('q.id', '=', eb.ref('n.id')),
|
|
256
|
+
eb('n.path', 'like', sql<string>`${eb.ref('q.path')} || ',%'`),
|
|
257
|
+
]),
|
|
258
|
+
)
|
|
259
|
+
.where((eb) =>
|
|
260
|
+
eb('q.path', 'like', sql<string>`${eb.ref('p.path')} || ',%'`),
|
|
261
|
+
),
|
|
262
|
+
),
|
|
263
|
+
),
|
|
264
|
+
),
|
|
265
|
+
),
|
|
266
|
+
),
|
|
267
|
+
),
|
|
268
|
+
),
|
|
212
269
|
)
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
const [count] = await this.#db.query<{ n: number }>(`SELECT COUNT(*) AS n ${from}`, params)
|
|
222
|
-
const rows = await this.#db.query<Record<string, unknown>>(
|
|
223
|
-
`SELECT n.unique_id AS key, s.culture, s.text, h.score ${from}
|
|
224
|
-
ORDER BY h.score DESC, n.id LIMIT ? OFFSET ?`,
|
|
225
|
-
[...params, options.take, options.skip],
|
|
226
|
-
)
|
|
270
|
+
const count = await hits.select((eb) => eb.fn.countAll().as('n')).executeTakeFirst()
|
|
271
|
+
const rows = await hits
|
|
272
|
+
.select(['n.unique_id as key', 's.culture', 's.text', 'h.score'])
|
|
273
|
+
.orderBy('h.score', 'desc')
|
|
274
|
+
.orderBy('n.id')
|
|
275
|
+
.limit(options.take)
|
|
276
|
+
.offset(options.skip)
|
|
277
|
+
.execute()
|
|
227
278
|
return {
|
|
228
279
|
total: Number(count?.n ?? 0),
|
|
229
280
|
items: rows.map((row) => ({
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Writes the types of crombolo's own tables from a migrated SQLite and Postgres
|
|
3
|
+
* database (story 221), so queries are checked against both engines at once.
|
|
4
|
+
* `bun run db:types` writes them; a dialect-suite test fails when they drift.
|
|
5
|
+
*/
|
|
6
|
+
import type { Db } from './database.ts'
|
|
7
|
+
|
|
8
|
+
interface Column {
|
|
9
|
+
name: string
|
|
10
|
+
/** The Postgres type name (`int4`, `timestamptz`), or SQLite's declared type, lower case. */
|
|
11
|
+
type: string
|
|
12
|
+
nullable: boolean
|
|
13
|
+
generated: boolean
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
type Tables = Map<string, Map<string, Column>>
|
|
17
|
+
|
|
18
|
+
const FTS_SHADOW = /_(data|idx|content|docsize|config)$/
|
|
19
|
+
|
|
20
|
+
async function sqliteTables(db: Db): Promise<Tables> {
|
|
21
|
+
const masters = await db.query<{ name: string; sql: string | null }>(
|
|
22
|
+
"SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",
|
|
23
|
+
)
|
|
24
|
+
const virtual = masters
|
|
25
|
+
.filter((m) => /^\s*create\s+virtual/i.test(m.sql ?? ''))
|
|
26
|
+
.map((m) => m.name)
|
|
27
|
+
const tables: Tables = new Map()
|
|
28
|
+
for (const { name } of masters) {
|
|
29
|
+
if (virtual.includes(name)) continue
|
|
30
|
+
if (virtual.some((v) => name.startsWith(`${v}_`) && FTS_SHADOW.test(name))) continue
|
|
31
|
+
const info = await db.query<{
|
|
32
|
+
name: string
|
|
33
|
+
type: string
|
|
34
|
+
notnull: number
|
|
35
|
+
dflt_value: string | null
|
|
36
|
+
pk: number
|
|
37
|
+
}>(`PRAGMA table_info("${name}")`)
|
|
38
|
+
const columns = new Map<string, Column>()
|
|
39
|
+
for (const c of info) {
|
|
40
|
+
// An INTEGER PRIMARY KEY is the rowid, which SQLite assigns.
|
|
41
|
+
const rowid = c.pk === 1 && c.type.toUpperCase() === 'INTEGER'
|
|
42
|
+
columns.set(c.name, {
|
|
43
|
+
name: c.name,
|
|
44
|
+
type: c.type.toLowerCase(),
|
|
45
|
+
nullable: c.notnull === 0 && c.pk === 0,
|
|
46
|
+
generated: c.dflt_value !== null || rowid,
|
|
47
|
+
})
|
|
48
|
+
}
|
|
49
|
+
tables.set(name, columns)
|
|
50
|
+
}
|
|
51
|
+
return tables
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function postgresTables(db: Db): Promise<Tables> {
|
|
55
|
+
const rows = await db.query<{
|
|
56
|
+
table_name: string
|
|
57
|
+
column_name: string
|
|
58
|
+
udt_name: string
|
|
59
|
+
is_nullable: string
|
|
60
|
+
column_default: string | null
|
|
61
|
+
is_identity: string
|
|
62
|
+
}>(
|
|
63
|
+
`SELECT c.table_name, c.column_name, c.udt_name, c.is_nullable, c.column_default, c.is_identity
|
|
64
|
+
FROM information_schema.columns c
|
|
65
|
+
JOIN information_schema.tables t
|
|
66
|
+
ON t.table_schema = c.table_schema AND t.table_name = c.table_name
|
|
67
|
+
WHERE c.table_schema = current_schema() AND t.table_type = 'BASE TABLE'`,
|
|
68
|
+
)
|
|
69
|
+
const tables: Tables = new Map()
|
|
70
|
+
for (const r of rows) {
|
|
71
|
+
let columns = tables.get(r.table_name)
|
|
72
|
+
if (!columns) {
|
|
73
|
+
columns = new Map()
|
|
74
|
+
tables.set(r.table_name, columns)
|
|
75
|
+
}
|
|
76
|
+
columns.set(r.column_name, {
|
|
77
|
+
name: r.column_name,
|
|
78
|
+
type: r.udt_name.toLowerCase(),
|
|
79
|
+
nullable: r.is_nullable === 'YES',
|
|
80
|
+
generated: r.column_default !== null || r.is_identity === 'YES',
|
|
81
|
+
})
|
|
82
|
+
}
|
|
83
|
+
return tables
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The TypeScript type of a column, named by an alias declared in the generated file. */
|
|
87
|
+
function typeOf(type: string): string {
|
|
88
|
+
if (/^(int2|int4|integer|smallint)$/.test(type)) return 'number'
|
|
89
|
+
if (type === 'int8' || type === 'bigint') return 'BigInteger'
|
|
90
|
+
if (type === 'bool' || type === 'boolean') return 'Bool'
|
|
91
|
+
if (/^timestamp/.test(type)) return 'Timestamp'
|
|
92
|
+
if (type === 'numeric') return 'Decimal'
|
|
93
|
+
if (/^(float4|float8|real|double)/.test(type)) return 'number'
|
|
94
|
+
if (type === 'bytea' || type === 'blob') return 'Bytes'
|
|
95
|
+
if (type === 'tsvector') return 'unknown'
|
|
96
|
+
return 'string'
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Postgres knows more than SQLite's declared types do, so its type leads where both have one. */
|
|
100
|
+
function merge(sqlite: Column | undefined, postgres: Column | undefined): Column {
|
|
101
|
+
const lead = (postgres ?? sqlite) as Column
|
|
102
|
+
return {
|
|
103
|
+
name: lead.name,
|
|
104
|
+
type: lead.type,
|
|
105
|
+
nullable: (sqlite?.nullable ?? false) || (postgres?.nullable ?? false),
|
|
106
|
+
generated: (sqlite?.generated ?? false) || (postgres?.generated ?? false),
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/
|
|
111
|
+
const key = (name: string) => (IDENTIFIER.test(name) ? name : `'${name}'`)
|
|
112
|
+
|
|
113
|
+
const PREAMBLE = `// Generated by \`bun run db:types\` from freshly migrated SQLite and Postgres
|
|
114
|
+
// databases (story 221). Do not edit: add a migration and regenerate.
|
|
115
|
+
import type { ColumnType, Generated } from 'kysely'
|
|
116
|
+
|
|
117
|
+
/** SQLite answers 0 or 1; write \`dialect.boolValue(…)\`, read through \`fromDbBool\`. */
|
|
118
|
+
type Bool = ColumnType<boolean | number, boolean | number, boolean | number>
|
|
119
|
+
/** Postgres answers a Date, SQLite an ISO string; write \`DbDate.toDb\`, read through \`DbDate.fromDb\`. */
|
|
120
|
+
type Timestamp = ColumnType<Date | string, string, string>
|
|
121
|
+
type Decimal = ColumnType<string | number, string | number, string | number>
|
|
122
|
+
type BigInteger = ColumnType<number | string | bigint, number | bigint, number | bigint>
|
|
123
|
+
type Bytes = Uint8Array
|
|
124
|
+
/** A column with a default, so an insert may leave it out, whatever its read and write types. */
|
|
125
|
+
type Default<C> = C extends ColumnType<infer S, infer I, infer U>
|
|
126
|
+
? ColumnType<S, I | undefined, U>
|
|
127
|
+
: Generated<C>
|
|
128
|
+
`
|
|
129
|
+
|
|
130
|
+
/** The generated file's text for the two migrated databases. */
|
|
131
|
+
export async function tableTypes(sqlite: Db, postgres: Db): Promise<string> {
|
|
132
|
+
const [lite, pg] = await Promise.all([sqliteTables(sqlite), postgresTables(postgres)])
|
|
133
|
+
const names = [...new Set([...lite.keys(), ...pg.keys()])].sort()
|
|
134
|
+
const out = [PREAMBLE, 'export interface CoreTables {']
|
|
135
|
+
for (const table of names) {
|
|
136
|
+
const a = lite.get(table)
|
|
137
|
+
const b = pg.get(table)
|
|
138
|
+
const only = !a ? ' // Postgres only' : !b ? ' // SQLite only' : ''
|
|
139
|
+
out.push(` ${key(table)}: {${only}`)
|
|
140
|
+
const columns = [...new Set([...(a?.keys() ?? []), ...(b?.keys() ?? [])])].sort()
|
|
141
|
+
for (const name of columns) {
|
|
142
|
+
const c = merge(a?.get(name), b?.get(name))
|
|
143
|
+
let t = typeOf(c.type)
|
|
144
|
+
if (c.nullable) t = `${t} | null`
|
|
145
|
+
if (c.generated) t = t === 'number' || t === 'string' ? `Generated<${t}>` : `Default<${t}>`
|
|
146
|
+
out.push(` ${key(name)}: ${t}`)
|
|
147
|
+
}
|
|
148
|
+
out.push(' }')
|
|
149
|
+
}
|
|
150
|
+
out.push('}', '')
|
|
151
|
+
return out.join('\n')
|
|
152
|
+
}
|