@hamur/db 0.0.0-stage → 0.0.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/LICENSE +22 -0
- package/README.md +38 -2
- package/dist/chunks/browser-bun-sql-2yeva2qv.js +53 -0
- package/dist/chunks/browser-bun-sqlite-xxptm4db.js +72 -0
- package/dist/chunks/browser-client-ehmpv0kf.js +130 -0
- package/dist/chunks/browser-d1-a16d23f0.js +8 -0
- package/dist/chunks/browser-index-3t2ajr9m.js +510 -0
- package/dist/chunks/browser-index-kf697bfy.js +113 -0
- package/dist/chunks/browser-index-ppkx8k0t.js +28 -0
- package/dist/chunks/bun-bun-sql-vaz9ggc8.js +54 -0
- package/dist/chunks/bun-bun-sqlite-qcd011rm.js +73 -0
- package/dist/chunks/bun-client-cnt1ddnf.js +131 -0
- package/dist/chunks/bun-d1-d36z1pyr.js +9 -0
- package/dist/chunks/bun-index-06tj00dn.js +11 -0
- package/dist/chunks/bun-index-9na2zkqq.js +224 -0
- package/dist/chunks/bun-index-b47nngck.js +352 -0
- package/dist/chunks/bun-index-hrx1eqma.js +29 -0
- package/dist/chunks/bun-index-pd6k99dv.js +114 -0
- package/dist/src/cli.js +1692 -0
- package/dist/src/devtools.js +153 -0
- package/dist/src/index.js +1491 -0
- package/dist/src/server/index.js +584 -0
- package/dist/src/storage/define.js +7 -0
- package/dist/types/src/build/connections.d.ts +8 -0
- package/dist/types/src/build/databases.d.ts +20 -0
- package/dist/types/src/build/factories.d.ts +6 -0
- package/dist/types/src/build/migrations.d.ts +21 -0
- package/dist/types/src/build/queue.d.ts +7 -0
- package/dist/types/src/build/schema.d.ts +50 -0
- package/dist/types/src/build/tables.d.ts +7 -0
- package/dist/types/src/build/types.d.ts +4 -0
- package/dist/types/src/cli.d.ts +26 -0
- package/dist/types/src/connectors/bun-sql.d.ts +3 -0
- package/dist/types/src/connectors/bun-sqlite.d.ts +3 -0
- package/dist/types/src/connectors/client-fakes.d.ts +57 -0
- package/dist/types/src/connectors/client.d.ts +3 -0
- package/dist/types/src/connectors/d1-fake.d.ts +32 -0
- package/dist/types/src/connectors/d1.d.ts +26 -0
- package/dist/types/src/connectors/node-sqlite.d.ts +3 -0
- package/dist/types/src/connectors/node-test.d.ts +17 -0
- package/dist/types/src/connectors/suite.d.ts +13 -0
- package/dist/types/src/devtools.d.ts +6 -0
- package/dist/types/src/index.d.ts +25 -0
- package/dist/types/src/module.d.ts +6 -0
- package/dist/types/src/options.d.ts +9 -0
- package/dist/types/src/runtime/connector.d.ts +53 -0
- package/dist/types/src/runtime/database.d.ts +15 -0
- package/dist/types/src/runtime/migrate.d.ts +56 -0
- package/dist/types/src/runtime/query.d.ts +12 -0
- package/dist/types/src/runtime/queue-process.d.ts +1 -0
- package/dist/types/src/runtime/queue.d.ts +85 -0
- package/dist/types/src/runtime/registry.d.ts +16 -0
- package/dist/types/src/server/client.d.ts +3 -0
- package/dist/types/src/server/databases.d.ts +4 -0
- package/dist/types/src/server/define-factory.d.ts +9 -0
- package/dist/types/src/server/devtools-routes.d.ts +4 -0
- package/dist/types/src/server/devtools.d.ts +26 -0
- package/dist/types/src/server/door-dev.d.ts +3 -0
- package/dist/types/src/server/door.d.ts +2 -0
- package/dist/types/src/server/factory-core.d.ts +12 -0
- package/dist/types/src/server/factory.d.ts +6 -0
- package/dist/types/src/server/fake.d.ts +35 -0
- package/dist/types/src/server/index.d.ts +12 -0
- package/dist/types/src/server/migrations.d.ts +5 -0
- package/dist/types/src/server/page.d.ts +26 -0
- package/dist/types/src/server/plugin.d.ts +1 -0
- package/dist/types/src/server/queue.d.ts +6 -0
- package/dist/types/src/server/table-entities.d.ts +33 -0
- package/dist/types/src/server/task.d.ts +6 -0
- package/dist/types/src/storage/define.d.ts +12 -0
- package/dist/types/src/storage/driver.d.ts +36 -0
- package/dist/types/src/storage/index.d.ts +3 -0
- package/dist/types/src/types.d.ts +103 -0
- package/package.json +40 -4
- package/src/build/connections.ts +225 -0
- package/src/build/databases.ts +101 -0
- package/src/build/factories.ts +135 -0
- package/src/build/migrations.ts +247 -0
- package/src/build/queue.ts +29 -0
- package/src/build/schema.ts +636 -0
- package/src/build/tables.ts +20 -0
- package/src/build/types.ts +46 -0
- package/src/cli.ts +153 -0
- package/src/connectors/bun-sql.ts +68 -0
- package/src/connectors/bun-sqlite.ts +69 -0
- package/src/connectors/client-fakes.ts +257 -0
- package/src/connectors/client.ts +161 -0
- package/src/connectors/d1-fake.ts +92 -0
- package/src/connectors/d1.ts +151 -0
- package/src/connectors/node-sqlite.ts +83 -0
- package/src/connectors/node-test.ts +31 -0
- package/src/connectors/suite.ts +406 -0
- package/src/devtools.ts +264 -0
- package/src/env.d.ts +28 -0
- package/src/index.ts +46 -0
- package/src/module.ts +36 -0
- package/src/options.ts +104 -0
- package/src/runtime/connector.ts +87 -0
- package/src/runtime/database.ts +353 -0
- package/src/runtime/migrate.ts +307 -0
- package/src/runtime/query.ts +82 -0
- package/src/runtime/queue-process.ts +39 -0
- package/src/runtime/queue.ts +380 -0
- package/src/runtime/registry.ts +61 -0
- package/src/server/client.ts +6 -0
- package/src/server/databases.ts +24 -0
- package/src/server/define-factory.ts +22 -0
- package/src/server/devtools-routes.ts +34 -0
- package/src/server/devtools.ts +205 -0
- package/src/server/door-dev.ts +6 -0
- package/src/server/door.ts +4 -0
- package/src/server/factory-core.ts +91 -0
- package/src/server/factory.ts +19 -0
- package/src/server/fake.ts +348 -0
- package/src/server/index.ts +17 -0
- package/src/server/migrations.ts +26 -0
- package/src/server/page.ts +181 -0
- package/src/server/plugin.ts +14 -0
- package/src/server/queue.ts +38 -0
- package/src/server/table-entities.ts +29 -0
- package/src/server/task.ts +15 -0
- package/src/storage/define.ts +12 -0
- package/src/storage/driver.ts +419 -0
- package/src/storage/index.ts +7 -0
- package/src/types.ts +101 -0
|
@@ -0,0 +1,636 @@
|
|
|
1
|
+
import type { Dialect } from "../types.ts"
|
|
2
|
+
|
|
3
|
+
interface Token {
|
|
4
|
+
kind: "word" | "ident" | "string" | "punct"
|
|
5
|
+
text: string
|
|
6
|
+
/** A word in lower case; empty for the others, so a quoted identifier never matches a keyword. */
|
|
7
|
+
lower: string
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const DOLLAR = /^\$(?:[A-Za-z_\u0080-\uffff][A-Za-z0-9_\u0080-\uffff]*)?\$/
|
|
11
|
+
const WORD = /[A-Za-z0-9_$\u0080-]/
|
|
12
|
+
|
|
13
|
+
const token = (kind: Token["kind"], text: string): Token => ({
|
|
14
|
+
kind,
|
|
15
|
+
text,
|
|
16
|
+
lower: kind === "word" ? text.toLowerCase() : "",
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
/** Quoted identifiers kept, comments and strings reduced to one token each, so a `;` or `(` inside them never splits a statement. */
|
|
20
|
+
export function tokenize(sql: string, dialect: Dialect): Token[] {
|
|
21
|
+
const tokens: Token[] = []
|
|
22
|
+
let i = 0
|
|
23
|
+
const quoted = (close: string, escapes: boolean): string => {
|
|
24
|
+
let text = ""
|
|
25
|
+
i++
|
|
26
|
+
while (i < sql.length) {
|
|
27
|
+
const char = sql[i]!
|
|
28
|
+
if (char === "\\" && escapes && i + 1 < sql.length) {
|
|
29
|
+
text += sql[i + 1]
|
|
30
|
+
i += 2
|
|
31
|
+
} else if (char === close) {
|
|
32
|
+
if (sql[i + 1] === close) {
|
|
33
|
+
text += close
|
|
34
|
+
i += 2
|
|
35
|
+
} else {
|
|
36
|
+
i++
|
|
37
|
+
return text
|
|
38
|
+
}
|
|
39
|
+
} else {
|
|
40
|
+
text += char
|
|
41
|
+
i++
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return text
|
|
45
|
+
}
|
|
46
|
+
while (i < sql.length) {
|
|
47
|
+
const char = sql[i]!
|
|
48
|
+
if (/\s/.test(char)) i++
|
|
49
|
+
else if (char === "-" && sql[i + 1] === "-") i = sql.indexOf("\n", i) < 0 ? sql.length : sql.indexOf("\n", i)
|
|
50
|
+
else if (char === "#" && dialect === "mysql") i = sql.indexOf("\n", i) < 0 ? sql.length : sql.indexOf("\n", i)
|
|
51
|
+
else if (char === "/" && sql[i + 1] === "*")
|
|
52
|
+
i = sql.indexOf("*/", i + 2) < 0 ? sql.length : sql.indexOf("*/", i + 2) + 2
|
|
53
|
+
else if (char === "'") {
|
|
54
|
+
const prev = tokens.at(-1)
|
|
55
|
+
const escapeString =
|
|
56
|
+
dialect === "postgres" && prev?.kind === "word" && prev.lower === "e" && sql[i - 1] === prev.text
|
|
57
|
+
tokens.push(token("string", quoted("'", dialect === "mysql" || escapeString)))
|
|
58
|
+
} else if (char === '"') tokens.push(token("ident", quoted('"', dialect === "mysql")))
|
|
59
|
+
else if (char === "`") tokens.push(token("ident", quoted("`", false)))
|
|
60
|
+
else if (char === "[" && !/^\[\s*\d*\s*\]/.test(sql.slice(i, i + 12))) {
|
|
61
|
+
const end = sql.indexOf("]", i)
|
|
62
|
+
const stop = end < 0 ? sql.length : end
|
|
63
|
+
tokens.push(token("ident", sql.slice(i + 1, stop)))
|
|
64
|
+
i = stop + 1
|
|
65
|
+
} else if (char === "$" && dialect === "postgres" && DOLLAR.test(sql.slice(i, i + 64))) {
|
|
66
|
+
const tag = DOLLAR.exec(sql.slice(i, i + 64))![0]
|
|
67
|
+
const end = sql.indexOf(tag, i + tag.length)
|
|
68
|
+
tokens.push(token("string", ""))
|
|
69
|
+
i = end < 0 ? sql.length : end + tag.length
|
|
70
|
+
} else if (WORD.test(char)) {
|
|
71
|
+
const start = i
|
|
72
|
+
while (i < sql.length && WORD.test(sql[i]!)) i++
|
|
73
|
+
tokens.push(token("word", sql.slice(start, i)))
|
|
74
|
+
} else {
|
|
75
|
+
tokens.push(token("punct", char))
|
|
76
|
+
i++
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return tokens
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const isWord = (tok: Token | undefined, ...words: string[]) => tok?.kind === "word" && words.includes(tok.lower)
|
|
83
|
+
const isPunct = (tok: Token | undefined, text: string) => tok?.kind === "punct" && tok.text === text
|
|
84
|
+
|
|
85
|
+
const ROUTINES = ["procedure", "function", "trigger", "event"]
|
|
86
|
+
const BLOCK_SUFFIXES = ["if", "loop", "while", "repeat"]
|
|
87
|
+
|
|
88
|
+
const isRoutine = (statement: Token[]) =>
|
|
89
|
+
isWord(statement[0], "create") && statement.slice(1, 10).some((tok) => isWord(tok, ...ROUTINES))
|
|
90
|
+
|
|
91
|
+
/** Splits at `;`, except inside the `BEGIN … END` body of a procedure, function, trigger or event: it is one statement, whose DDL never reaches the types. */
|
|
92
|
+
function statements(tokens: Token[]): Token[][] {
|
|
93
|
+
const out: Token[][] = []
|
|
94
|
+
let current: Token[] = []
|
|
95
|
+
let depth = 0
|
|
96
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
97
|
+
const tok = tokens[i]!
|
|
98
|
+
if (isPunct(tok, ";") && (depth <= 0 || !isRoutine(current))) {
|
|
99
|
+
if (current.length) out.push(current)
|
|
100
|
+
current = []
|
|
101
|
+
depth = 0
|
|
102
|
+
continue
|
|
103
|
+
}
|
|
104
|
+
if (isWord(tok, "begin", "case")) depth++
|
|
105
|
+
else if (isWord(tok, "end") && !isWord(tokens[i + 1], ...BLOCK_SUFFIXES)) depth--
|
|
106
|
+
current.push(tok)
|
|
107
|
+
}
|
|
108
|
+
if (current.length) out.push(current)
|
|
109
|
+
return out
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** MySQL `DELIMITER //` lines: the text between two of them is cut at the delimiter, each piece being one statement. */
|
|
113
|
+
function delimited(sql: string): Array<{ sql: string; whole: boolean }> {
|
|
114
|
+
const out: Array<{ sql: string; whole: boolean }> = []
|
|
115
|
+
let delimiter = ";"
|
|
116
|
+
let chunk = ""
|
|
117
|
+
const flush = () => {
|
|
118
|
+
if (!chunk.trim()) return
|
|
119
|
+
if (delimiter === ";") out.push({ sql: chunk, whole: false })
|
|
120
|
+
else for (const piece of chunk.split(delimiter)) if (piece.trim()) out.push({ sql: piece, whole: true })
|
|
121
|
+
chunk = ""
|
|
122
|
+
}
|
|
123
|
+
for (const line of sql.split("\n")) {
|
|
124
|
+
const match = /^\s*delimiter\s+(\S+)/i.exec(line)
|
|
125
|
+
if (match) {
|
|
126
|
+
flush()
|
|
127
|
+
delimiter = match[1]!
|
|
128
|
+
} else chunk += `${line}\n`
|
|
129
|
+
}
|
|
130
|
+
flush()
|
|
131
|
+
return out
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Splits at `,` outside any parentheses. */
|
|
135
|
+
function splitTop(tokens: Token[]): Token[][] {
|
|
136
|
+
const out: Token[][] = []
|
|
137
|
+
let depth = 0
|
|
138
|
+
let current: Token[] = []
|
|
139
|
+
for (const tok of tokens) {
|
|
140
|
+
if (isPunct(tok, "(")) depth++
|
|
141
|
+
else if (isPunct(tok, ")")) depth--
|
|
142
|
+
if (depth === 0 && isPunct(tok, ",")) {
|
|
143
|
+
out.push(current)
|
|
144
|
+
current = []
|
|
145
|
+
} else current.push(tok)
|
|
146
|
+
}
|
|
147
|
+
if (current.length) out.push(current)
|
|
148
|
+
return out
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The index of the `)` that closes the `(` at `open`, or -1. */
|
|
152
|
+
function closing(tokens: Token[], open: number): number {
|
|
153
|
+
let depth = 0
|
|
154
|
+
for (let i = open; i < tokens.length; i++) {
|
|
155
|
+
if (isPunct(tokens[i], "(")) depth++
|
|
156
|
+
else if (isPunct(tokens[i], ")") && --depth === 0) return i
|
|
157
|
+
}
|
|
158
|
+
return -1
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export interface Column {
|
|
162
|
+
name: string
|
|
163
|
+
/** The TypeScript type without `| null`. */
|
|
164
|
+
base: string
|
|
165
|
+
notNull: boolean
|
|
166
|
+
primary: boolean
|
|
167
|
+
/** Whether PRIMARY KEY makes the column not null: always, except on SQLite where only `INTEGER PRIMARY KEY` (the rowid), STRICT and WITHOUT ROWID do. */
|
|
168
|
+
pkNotNull: boolean
|
|
169
|
+
/** A `DEFAULT` clause. */
|
|
170
|
+
hasDefault: boolean
|
|
171
|
+
/** The database fills the value: `GENERATED`, identity, `serial`, `AUTO_INCREMENT`, `AUTOINCREMENT`. */
|
|
172
|
+
auto: boolean
|
|
173
|
+
/** The declared type is exactly `INTEGER`, so a SQLite `PRIMARY KEY` on it is the rowid. */
|
|
174
|
+
integer: boolean
|
|
175
|
+
/** Set when the column's type is `unknown` for a type typegen does not read. */
|
|
176
|
+
warning?: string
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export interface Table {
|
|
180
|
+
name: string
|
|
181
|
+
columns: Map<string, Column>
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export interface MigrationSource {
|
|
185
|
+
file: string
|
|
186
|
+
sql: string
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export interface Schema {
|
|
190
|
+
tables: Map<string, Table>
|
|
191
|
+
warnings: string[]
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const POSTGRES: Record<string, string> = {
|
|
195
|
+
integer: "number",
|
|
196
|
+
int: "number",
|
|
197
|
+
smallint: "number",
|
|
198
|
+
real: "number",
|
|
199
|
+
"double precision": "number",
|
|
200
|
+
serial: "number",
|
|
201
|
+
smallserial: "number",
|
|
202
|
+
bigint: "string",
|
|
203
|
+
bigserial: "string",
|
|
204
|
+
numeric: "string",
|
|
205
|
+
decimal: "string",
|
|
206
|
+
text: "string",
|
|
207
|
+
varchar: "string",
|
|
208
|
+
char: "string",
|
|
209
|
+
uuid: "string",
|
|
210
|
+
boolean: "boolean",
|
|
211
|
+
timestamp: "Date",
|
|
212
|
+
timestamptz: "Date",
|
|
213
|
+
date: "Date",
|
|
214
|
+
bytea: "Uint8Array",
|
|
215
|
+
json: "unknown",
|
|
216
|
+
jsonb: "unknown",
|
|
217
|
+
}
|
|
218
|
+
const MYSQL: Record<string, string> = {
|
|
219
|
+
int: "number",
|
|
220
|
+
integer: "number",
|
|
221
|
+
tinyint: "number",
|
|
222
|
+
smallint: "number",
|
|
223
|
+
mediumint: "number",
|
|
224
|
+
float: "number",
|
|
225
|
+
double: "number",
|
|
226
|
+
"double precision": "number",
|
|
227
|
+
real: "number",
|
|
228
|
+
boolean: "number",
|
|
229
|
+
bool: "number",
|
|
230
|
+
bigint: "number | string",
|
|
231
|
+
serial: "number | string",
|
|
232
|
+
decimal: "string",
|
|
233
|
+
numeric: "string",
|
|
234
|
+
varchar: "string",
|
|
235
|
+
char: "string",
|
|
236
|
+
text: "string",
|
|
237
|
+
tinytext: "string",
|
|
238
|
+
mediumtext: "string",
|
|
239
|
+
longtext: "string",
|
|
240
|
+
datetime: "Date",
|
|
241
|
+
timestamp: "Date",
|
|
242
|
+
date: "Date",
|
|
243
|
+
blob: "Uint8Array",
|
|
244
|
+
tinyblob: "Uint8Array",
|
|
245
|
+
mediumblob: "Uint8Array",
|
|
246
|
+
longblob: "Uint8Array",
|
|
247
|
+
binary: "Uint8Array",
|
|
248
|
+
varbinary: "Uint8Array",
|
|
249
|
+
json: "unknown",
|
|
250
|
+
}
|
|
251
|
+
const POSTGRES_ALIASES: Record<string, string> = {
|
|
252
|
+
int4: "integer",
|
|
253
|
+
int2: "smallint",
|
|
254
|
+
int8: "bigint",
|
|
255
|
+
float4: "real",
|
|
256
|
+
float: "double precision",
|
|
257
|
+
serial2: "smallserial",
|
|
258
|
+
serial4: "serial",
|
|
259
|
+
serial8: "bigserial",
|
|
260
|
+
float8: "double precision",
|
|
261
|
+
bool: "boolean",
|
|
262
|
+
"character varying": "varchar",
|
|
263
|
+
character: "char",
|
|
264
|
+
bpchar: "char",
|
|
265
|
+
"timestamp with time zone": "timestamptz",
|
|
266
|
+
"timestamp without time zone": "timestamp",
|
|
267
|
+
}
|
|
268
|
+
const IGNORED_TYPE_WORDS = new Set(["unsigned", "signed", "zerofill"])
|
|
269
|
+
|
|
270
|
+
/** SQLite types a column by its declared name (the "INT", "CHAR", "CLOB", "TEXT", "REAL", "FLOA", "DOUB" and "BLOB" rules of its type affinity); a name matching none is `unknown`. */
|
|
271
|
+
function sqliteType(type: string): string | undefined {
|
|
272
|
+
const name = type.toUpperCase()
|
|
273
|
+
if (name === "NUMERIC") return "number"
|
|
274
|
+
if (name.includes("INT")) return "number"
|
|
275
|
+
if (/CHAR|CLOB|TEXT/.test(name)) return "string"
|
|
276
|
+
if (name.includes("BLOB")) return "Uint8Array"
|
|
277
|
+
if (/REAL|FLOA|DOUB/.test(name)) return "number"
|
|
278
|
+
return undefined
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** The TypeScript type of a declared column type, or undefined for one typegen does not read. */
|
|
282
|
+
export function mapType(dialect: Dialect, declared: string): string | undefined {
|
|
283
|
+
let type = declared
|
|
284
|
+
.toLowerCase()
|
|
285
|
+
.split(/\s+/)
|
|
286
|
+
.filter((word) => word && !IGNORED_TYPE_WORDS.has(word))
|
|
287
|
+
.join(" ")
|
|
288
|
+
if (dialect === "sqlite") return sqliteType(type)
|
|
289
|
+
if (dialect === "postgres") {
|
|
290
|
+
type = POSTGRES_ALIASES[type] ?? type
|
|
291
|
+
return POSTGRES[type]
|
|
292
|
+
}
|
|
293
|
+
return MYSQL[type]
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const TYPE_STOPS = new Set([
|
|
297
|
+
"not",
|
|
298
|
+
"null",
|
|
299
|
+
"primary",
|
|
300
|
+
"default",
|
|
301
|
+
"references",
|
|
302
|
+
"check",
|
|
303
|
+
"unique",
|
|
304
|
+
"constraint",
|
|
305
|
+
"collate",
|
|
306
|
+
"generated",
|
|
307
|
+
"as",
|
|
308
|
+
"auto_increment",
|
|
309
|
+
"autoincrement",
|
|
310
|
+
"comment",
|
|
311
|
+
"on",
|
|
312
|
+
"key",
|
|
313
|
+
"charset",
|
|
314
|
+
"invisible",
|
|
315
|
+
"visible",
|
|
316
|
+
"after",
|
|
317
|
+
"first",
|
|
318
|
+
"stored",
|
|
319
|
+
"virtual",
|
|
320
|
+
"storage",
|
|
321
|
+
"compression",
|
|
322
|
+
])
|
|
323
|
+
|
|
324
|
+
const CONSTRAINTS = new Set(["constraint", "primary", "unique", "check", "foreign", "like"])
|
|
325
|
+
const MYSQL_INDEXES = new Set(["key", "index", "fulltext", "spatial"])
|
|
326
|
+
|
|
327
|
+
/** The key of a table or column name in `Schema`: only Postgres tells the case of a name apart. */
|
|
328
|
+
export const nameKey = (dialect: Dialect, name: string): string => (dialect === "postgres" ? name : name.toLowerCase())
|
|
329
|
+
|
|
330
|
+
class Reader {
|
|
331
|
+
schema: Schema = { tables: new Map(), warnings: [] }
|
|
332
|
+
file = ""
|
|
333
|
+
|
|
334
|
+
constructor(private dialect: Dialect) {}
|
|
335
|
+
|
|
336
|
+
private display(tok: Token): string {
|
|
337
|
+
return this.dialect === "postgres" && tok.kind === "word" ? tok.text.toLowerCase() : tok.text
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
private key(display: string): string {
|
|
341
|
+
return nameKey(this.dialect, display)
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** A table constraint or index entry of a column list, as opposed to a column. `key` is reserved in MySQL, so only there an unquoted one starts an index; `exclude` is a Postgres constraint only before `USING` or `(`. */
|
|
345
|
+
private isConstraint(item: Token[]): boolean {
|
|
346
|
+
const first = item[0]
|
|
347
|
+
if (first?.kind !== "word") return false
|
|
348
|
+
if (CONSTRAINTS.has(first.lower)) return true
|
|
349
|
+
if (this.dialect === "mysql" && MYSQL_INDEXES.has(first.lower)) return true
|
|
350
|
+
return (
|
|
351
|
+
this.dialect === "postgres" && first.lower === "exclude" && (isWord(item[1], "using") || isPunct(item[1], "("))
|
|
352
|
+
)
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
private warn(message: string): void {
|
|
356
|
+
this.schema.warnings.push(`${this.file}: ${message}`)
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** A possibly qualified name (`public.todos`): its last part. */
|
|
360
|
+
private name(s: Token[], from: number): { display: string; next: number } | undefined {
|
|
361
|
+
if (s[from]?.kind !== "word" && s[from]?.kind !== "ident") return undefined
|
|
362
|
+
let i = from
|
|
363
|
+
while (isPunct(s[i + 1], ".") && (s[i + 2]?.kind === "word" || s[i + 2]?.kind === "ident")) i += 2
|
|
364
|
+
return { display: this.display(s[i]!), next: i + 1 }
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
private ifClause(s: Token[], i: number, ...words: string[]): number {
|
|
368
|
+
return words.every((word, k) => isWord(s[i + k], word)) ? i + words.length : i
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
statement(s: Token[]): void {
|
|
372
|
+
if (isWord(s[0], "create")) {
|
|
373
|
+
let i = 1
|
|
374
|
+
if (isWord(s[i], "or") && isWord(s[i + 1], "replace")) i += 2
|
|
375
|
+
if (isWord(s[i], "unlogged")) i++
|
|
376
|
+
if (isWord(s[i], "table")) this.createTable(s, i + 1)
|
|
377
|
+
} else if (isWord(s[0], "rename") && isWord(s[1], "table")) this.renameTables(s)
|
|
378
|
+
else if (isWord(s[0], "drop") && isWord(s[1], "table")) this.dropTable(s, 2)
|
|
379
|
+
else if (isWord(s[0], "alter") && isWord(s[1], "table")) this.alterTable(s, 2)
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
private createTable(s: Token[], from: number): void {
|
|
383
|
+
const i = this.ifClause(s, from, "if", "not", "exists")
|
|
384
|
+
const ifNotExists = i !== from
|
|
385
|
+
const name = this.name(s, i)
|
|
386
|
+
if (!name) return
|
|
387
|
+
const key = this.key(name.display)
|
|
388
|
+
if (ifNotExists && this.schema.tables.has(key)) return
|
|
389
|
+
this.schema.tables.delete(key)
|
|
390
|
+
if (!isPunct(s[name.next], "(")) {
|
|
391
|
+
this.warn(
|
|
392
|
+
`CREATE TABLE ${name.display} without a column list is not read; ${JSON.stringify(name.display)} has no Row type`,
|
|
393
|
+
)
|
|
394
|
+
return
|
|
395
|
+
}
|
|
396
|
+
const end = closing(s, name.next)
|
|
397
|
+
if (end < 0) {
|
|
398
|
+
this.warn(
|
|
399
|
+
`CREATE TABLE ${name.display} has unbalanced parentheses and is not read; ${JSON.stringify(name.display)} has no Row type`,
|
|
400
|
+
)
|
|
401
|
+
return
|
|
402
|
+
}
|
|
403
|
+
const table: Table = { name: name.display, columns: new Map() }
|
|
404
|
+
const items = splitTop(s.slice(name.next + 1, end))
|
|
405
|
+
for (const item of items) if (!this.isConstraint(item)) this.item(table, item)
|
|
406
|
+
for (const item of items) if (this.isConstraint(item)) this.item(table, item)
|
|
407
|
+
const options = s.slice(end + 1)
|
|
408
|
+
if (isWord(options[0], "inherits"))
|
|
409
|
+
this.warn(
|
|
410
|
+
`CREATE TABLE ${name.display} INHERITS is not read; the columns of the parent table are missing from Row<${JSON.stringify(name.display)}>`,
|
|
411
|
+
)
|
|
412
|
+
const strict =
|
|
413
|
+
this.dialect === "sqlite" &&
|
|
414
|
+
options.some((tok, k) => isWord(tok, "strict") || (isWord(tok, "without") && isWord(options[k + 1], "rowid")))
|
|
415
|
+
if (strict) for (const column of table.columns.values()) column.pkNotNull = true
|
|
416
|
+
this.schema.tables.set(key, table)
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** MySQL `RENAME TABLE a TO b, c TO d`. */
|
|
420
|
+
private renameTables(s: Token[]): void {
|
|
421
|
+
let i = 2
|
|
422
|
+
for (;;) {
|
|
423
|
+
const from = this.name(s, i)
|
|
424
|
+
if (!from || !isWord(s[from.next], "to")) return
|
|
425
|
+
const to = this.name(s, from.next + 1)
|
|
426
|
+
if (!to) return
|
|
427
|
+
const table = this.schema.tables.get(this.key(from.display))
|
|
428
|
+
if (table) this.renameTable(this.key(from.display), table, s[to.next - 1])
|
|
429
|
+
if (!isPunct(s[to.next], ",")) return
|
|
430
|
+
i = to.next + 1
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** One entry of a column list: a column, or a constraint (only its `PRIMARY KEY` columns matter). */
|
|
435
|
+
private item(table: Table, item: Token[], ifNotExists = false): void {
|
|
436
|
+
if (!item.length) return
|
|
437
|
+
if (this.isConstraint(item)) {
|
|
438
|
+
if (isWord(item[0], "like")) {
|
|
439
|
+
this.warn(`LIKE in table ${JSON.stringify(table.name)} is not read; its columns have no type`)
|
|
440
|
+
return
|
|
441
|
+
}
|
|
442
|
+
const at = item.findIndex((tok, k) => isWord(tok, "primary") && isWord(item[k + 1], "key"))
|
|
443
|
+
if (at < 0) return
|
|
444
|
+
const open = item.findIndex((tok, k) => k > at && isPunct(tok, "("))
|
|
445
|
+
const close = open < 0 ? -1 : closing(item, open)
|
|
446
|
+
if (close < 0) return
|
|
447
|
+
for (const part of splitTop(item.slice(open + 1, close))) {
|
|
448
|
+
const column =
|
|
449
|
+
part[0] && (part[0].kind === "word" || part[0].kind === "ident")
|
|
450
|
+
? table.columns.get(this.key(this.display(part[0])))
|
|
451
|
+
: undefined
|
|
452
|
+
if (column) column.primary = true
|
|
453
|
+
}
|
|
454
|
+
return
|
|
455
|
+
}
|
|
456
|
+
const nameTok = item[0]!
|
|
457
|
+
if (nameTok.kind !== "word" && nameTok.kind !== "ident") return
|
|
458
|
+
const display = this.display(nameTok)
|
|
459
|
+
const key = this.key(display)
|
|
460
|
+
if (ifNotExists && table.columns.has(key)) return
|
|
461
|
+
table.columns.set(key, this.column(table, display, item.slice(1)))
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
private column(table: Table, name: string, rest: Token[]): Column {
|
|
465
|
+
const words: string[] = []
|
|
466
|
+
let array = false
|
|
467
|
+
let i = 0
|
|
468
|
+
for (; i < rest.length; i++) {
|
|
469
|
+
const tok = rest[i]!
|
|
470
|
+
if (tok.kind === "word") {
|
|
471
|
+
if (TYPE_STOPS.has(tok.lower) || (tok.lower === "character" && isWord(rest[i + 1], "set"))) break
|
|
472
|
+
words.push(tok.lower)
|
|
473
|
+
} else if (isPunct(tok, "(")) {
|
|
474
|
+
const close = closing(rest, i)
|
|
475
|
+
if (close < 0) break
|
|
476
|
+
i = close
|
|
477
|
+
} else if (isPunct(tok, "[")) {
|
|
478
|
+
array = true
|
|
479
|
+
i = rest.findIndex((t, k) => k > i && isPunct(t, "]"))
|
|
480
|
+
if (i < 0) break
|
|
481
|
+
} else break
|
|
482
|
+
}
|
|
483
|
+
let notNull = false
|
|
484
|
+
let primary = false
|
|
485
|
+
let hasDefault = false
|
|
486
|
+
let auto = false
|
|
487
|
+
let depth = 0
|
|
488
|
+
for (let k = i; k < rest.length; k++) {
|
|
489
|
+
const tok = rest[k]!
|
|
490
|
+
if (isPunct(tok, "(")) depth++
|
|
491
|
+
else if (isPunct(tok, ")")) depth--
|
|
492
|
+
else if (depth === 0) {
|
|
493
|
+
if (isWord(tok, "not") && isWord(rest[k + 1], "null")) notNull = true
|
|
494
|
+
else if (isWord(tok, "primary") && isWord(rest[k + 1], "key")) primary = true
|
|
495
|
+
else if (isWord(tok, "identity")) notNull = auto = true
|
|
496
|
+
else if (isWord(tok, "default")) hasDefault = true
|
|
497
|
+
else if (isWord(tok, "generated", "auto_increment", "autoincrement")) auto = true
|
|
498
|
+
else if (isWord(tok, "as") && isPunct(rest[k + 1], "(")) auto = true
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
const declared = words.join(" ")
|
|
502
|
+
if (words.length === 1 && /^(serial|smallserial|bigserial|serial2|serial4|serial8)$/.test(declared))
|
|
503
|
+
notNull = auto = true
|
|
504
|
+
if (this.dialect === "mysql" && declared === "serial") notNull = auto = true
|
|
505
|
+
const where = `${JSON.stringify(table.name)}.${JSON.stringify(name)}`
|
|
506
|
+
const column: Column = {
|
|
507
|
+
name,
|
|
508
|
+
base: "unknown",
|
|
509
|
+
notNull,
|
|
510
|
+
primary,
|
|
511
|
+
pkNotNull: this.dialect !== "sqlite" || declared === "integer",
|
|
512
|
+
hasDefault,
|
|
513
|
+
auto,
|
|
514
|
+
integer: declared === "integer" && !array,
|
|
515
|
+
}
|
|
516
|
+
const shown = declared + (array ? "[]" : "")
|
|
517
|
+
const base = array ? undefined : mapType(this.dialect, declared)
|
|
518
|
+
if (base) column.base = base
|
|
519
|
+
else
|
|
520
|
+
column.warning = `${this.file}: column ${where} has ${shown ? `type ${JSON.stringify(shown)}, which typegen does not read` : "no type"}; Row types it unknown`
|
|
521
|
+
return column
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
private dropTable(s: Token[], from: number): void {
|
|
525
|
+
let i = this.ifClause(s, from, "if", "exists")
|
|
526
|
+
for (;;) {
|
|
527
|
+
const name = this.name(s, i)
|
|
528
|
+
if (!name) return
|
|
529
|
+
this.schema.tables.delete(this.key(name.display))
|
|
530
|
+
if (!isPunct(s[name.next], ",")) return
|
|
531
|
+
i = name.next + 1
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
private alterTable(s: Token[], from: number): void {
|
|
536
|
+
let i = this.ifClause(s, from, "if", "exists")
|
|
537
|
+
if (isWord(s[i], "only")) i++
|
|
538
|
+
const name = this.name(s, i)
|
|
539
|
+
if (!name) return
|
|
540
|
+
const key = this.key(name.display)
|
|
541
|
+
const table = this.schema.tables.get(key)
|
|
542
|
+
if (!table) return
|
|
543
|
+
for (const action of splitTop(s.slice(name.next))) this.action(key, table, action)
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
private action(key: string, table: Table, a: Token[]): void {
|
|
547
|
+
const verb = a[0]?.kind === "word" ? a[0].lower : ""
|
|
548
|
+
if (verb === "add") {
|
|
549
|
+
let j = 1
|
|
550
|
+
if (isWord(a[j], "column")) j++
|
|
551
|
+
if (isPunct(a[j], "(")) {
|
|
552
|
+
const close = closing(a, j)
|
|
553
|
+
for (const item of splitTop(a.slice(j + 1, close < 0 ? a.length : close))) this.item(table, item)
|
|
554
|
+
return
|
|
555
|
+
}
|
|
556
|
+
const afterIf = this.ifClause(a, j, "if", "not", "exists")
|
|
557
|
+
this.item(table, a.slice(afterIf), afterIf !== j)
|
|
558
|
+
} else if (verb === "drop") {
|
|
559
|
+
let j = 1
|
|
560
|
+
if (isWord(a[j], "constraint", "primary", "foreign", "index", "key", "check", "unique", "partition")) return
|
|
561
|
+
if (isWord(a[j], "column")) j++
|
|
562
|
+
j = this.ifClause(a, j, "if", "exists")
|
|
563
|
+
const column = this.name(a, j)
|
|
564
|
+
if (column) table.columns.delete(this.key(column.display))
|
|
565
|
+
} else if (verb === "rename") {
|
|
566
|
+
let j = 1
|
|
567
|
+
if (isWord(a[j], "constraint", "index", "key")) return
|
|
568
|
+
if (isWord(a[j], "to", "as")) return this.renameTable(key, table, a[j + 1])
|
|
569
|
+
if (isWord(a[j], "column")) j++
|
|
570
|
+
if (!isWord(a[j + 1], "to", "as")) return this.renameTable(key, table, a[j])
|
|
571
|
+
const from = a[j]
|
|
572
|
+
const to = a[j + 2]
|
|
573
|
+
if (!from || !to) return
|
|
574
|
+
const oldKey = this.key(this.display(from))
|
|
575
|
+
const column = table.columns.get(oldKey)
|
|
576
|
+
if (!column) return
|
|
577
|
+
const display = this.display(to)
|
|
578
|
+
const renamed = new Map<string, Column>()
|
|
579
|
+
for (const [k, value] of table.columns) {
|
|
580
|
+
if (k === oldKey)
|
|
581
|
+
renamed.set(this.key(display), {
|
|
582
|
+
...column,
|
|
583
|
+
name: display,
|
|
584
|
+
warning: column.warning?.replace(JSON.stringify(column.name), JSON.stringify(display)),
|
|
585
|
+
})
|
|
586
|
+
else renamed.set(k, value)
|
|
587
|
+
}
|
|
588
|
+
table.columns = renamed
|
|
589
|
+
} else if (
|
|
590
|
+
verb === "modify" ||
|
|
591
|
+
verb === "change" ||
|
|
592
|
+
(verb === "alter" && a.some((tok) => isWord(tok, "type", "null")))
|
|
593
|
+
) {
|
|
594
|
+
this.warn(
|
|
595
|
+
`ALTER TABLE ${table.name} ${verb.toUpperCase()} is not read; Row<${JSON.stringify(table.name)}> may differ from the database`,
|
|
596
|
+
)
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
private renameTable(key: string, table: Table, to: Token | undefined): void {
|
|
601
|
+
if (!to || (to.kind !== "word" && to.kind !== "ident")) return
|
|
602
|
+
const display = this.display(to)
|
|
603
|
+
this.schema.tables.delete(key)
|
|
604
|
+
table.name = display
|
|
605
|
+
this.schema.tables.set(this.key(display), table)
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/** The tables the migrations leave, read in order; any statement but `CREATE TABLE`, `ALTER TABLE` and `DROP TABLE` is ignored. */
|
|
610
|
+
export function readSchema(dialect: Dialect, migrations: readonly MigrationSource[]): Schema {
|
|
611
|
+
const reader = new Reader(dialect)
|
|
612
|
+
for (const { file, sql } of migrations) {
|
|
613
|
+
reader.file = file
|
|
614
|
+
const pieces = dialect === "mysql" && /^\s*delimiter\s/im.test(sql) ? delimited(sql) : [{ sql, whole: false }]
|
|
615
|
+
for (const piece of pieces) {
|
|
616
|
+
const tokens = tokenize(piece.sql, dialect)
|
|
617
|
+
for (const statement of piece.whole ? [tokens] : statements(tokens)) reader.statement(statement)
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
return reader.schema
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/** The warnings of columns that are still in a table at the end, after the ones raised while reading. */
|
|
624
|
+
export function warningsOf(schema: Schema): string[] {
|
|
625
|
+
const columns = [...schema.tables.values()].flatMap((table) => [...table.columns.values()])
|
|
626
|
+
return [...schema.warnings, ...columns.flatMap((column) => (column.warning ? [column.warning] : []))]
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
const isNullable = (column: Column) => !column.notNull && !(column.primary && column.pkNotNull)
|
|
630
|
+
|
|
631
|
+
export const typeOfColumn = (column: Column): string =>
|
|
632
|
+
isNullable(column) && column.base !== "unknown" ? `${column.base} | null` : column.base
|
|
633
|
+
|
|
634
|
+
/** A column an insert may leave out: nullable, with a default, filled by the database, or SQLite's rowid alias. */
|
|
635
|
+
export const isOptionalOnInsert = (column: Column, dialect: Dialect): boolean =>
|
|
636
|
+
isNullable(column) || column.hasDefault || column.auto || (dialect === "sqlite" && column.primary && column.integer)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { HamurContext } from "hamur/kit"
|
|
2
|
+
import { resolvedOptions } from "../module.ts"
|
|
3
|
+
import { loadMigrations } from "./migrations.ts"
|
|
4
|
+
import { nameKey, readSchema } from "./schema.ts"
|
|
5
|
+
|
|
6
|
+
/** Why a module cannot keep `columns` in the app's `table`, as the migrations leave it; `undefined` when it can. */
|
|
7
|
+
export async function tableProblem(
|
|
8
|
+
hamur: HamurContext,
|
|
9
|
+
{ connection = "default", table, columns }: { connection?: string; table: string; columns: readonly string[] },
|
|
10
|
+
): Promise<string | undefined> {
|
|
11
|
+
const options = resolvedOptions.get(hamur)
|
|
12
|
+
if (!options || !Object.hasOwn(options.connections, connection))
|
|
13
|
+
return `db.connections has no ${JSON.stringify(connection)}`
|
|
14
|
+
const { dialect } = options.connections[connection]!
|
|
15
|
+
const { tables } = readSchema(dialect, (await loadMigrations(hamur, options))[connection] ?? [])
|
|
16
|
+
const found = tables.get(nameKey(dialect, table))
|
|
17
|
+
if (!found) return `no migration of ${JSON.stringify(connection)} creates table ${JSON.stringify(table)}`
|
|
18
|
+
const missing = columns.find((column) => !found.columns.has(nameKey(dialect, column)))
|
|
19
|
+
return missing === undefined ? undefined : `table ${JSON.stringify(table)} has no column ${JSON.stringify(missing)}`
|
|
20
|
+
}
|