@forinda/kickjs-db 5.1.0 → 5.2.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/README.md +1 -1
- package/dist/devtools-events.d.mts +22 -0
- package/dist/devtools-events.d.mts.map +1 -0
- package/dist/devtools-events.mjs +11 -0
- package/dist/index.d.mts +49 -191
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +369 -75
- package/dist/index.mjs.map +1 -1
- package/dist/pg.d.mts +1 -1
- package/dist/pg.mjs +2 -2
- package/dist/{types-BcfY4esK.mjs → types-D-Fmgq-a.mjs} +2 -2
- package/dist/{types-BcfY4esK.mjs.map → types-D-Fmgq-a.mjs.map} +1 -1
- package/dist/{types-D2FzsPow.d.mts → types-Dc9RQGSf.d.mts} +1 -1
- package/dist/{types-D2FzsPow.d.mts.map → types-Dc9RQGSf.d.mts.map} +1 -1
- package/dist/types-DlFKeljT.d.mts +255 -0
- package/dist/types-DlFKeljT.d.mts.map +1 -0
- package/package.json +14 -3
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @forinda/kickjs-db v5.1
|
|
2
|
+
* @forinda/kickjs-db v5.2.1
|
|
3
3
|
*
|
|
4
4
|
* Copyright (c) Felix Orinda
|
|
5
5
|
*
|
|
@@ -8,13 +8,13 @@
|
|
|
8
8
|
*
|
|
9
9
|
* @license MIT
|
|
10
10
|
*/
|
|
11
|
-
import { n as KICK_GENERATED, r as KICK_NOT_NULL, t as ColumnBuilder } from "./types-
|
|
11
|
+
import { n as KICK_GENERATED, r as KICK_NOT_NULL, t as ColumnBuilder } from "./types-D-Fmgq-a.mjs";
|
|
12
12
|
import { createHash } from "node:crypto";
|
|
13
13
|
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
|
14
14
|
import { existsSync } from "node:fs";
|
|
15
15
|
import path from "node:path";
|
|
16
16
|
import { createToken, defineAdapter } from "@forinda/kickjs";
|
|
17
|
-
import { Kysely, sql } from "kysely";
|
|
17
|
+
import { ColumnNode, ColumnUpdateNode, InsertQueryNode, Kysely, PrimitiveValueListNode, ReferenceNode, SelectAllNode, SelectQueryNode, SelectionNode, TableNode, UpdateQueryNode, ValueListNode, ValueNode, ValuesNode, sql } from "kysely";
|
|
18
18
|
import { EventEmitter } from "node:events";
|
|
19
19
|
import { pathToFileURL } from "node:url";
|
|
20
20
|
//#region src/snapshot/extract.ts
|
|
@@ -100,7 +100,7 @@ function renderSchemaSource(snapshot) {
|
|
|
100
100
|
const usedColumnHelpers = /* @__PURE__ */ new Set();
|
|
101
101
|
const tableSources = [];
|
|
102
102
|
for (const table of Object.values(snapshot.tables)) tableSources.push(renderTable(table, usedColumnHelpers));
|
|
103
|
-
const helpers = ["table", ...Array.from(usedColumnHelpers).
|
|
103
|
+
const helpers = ["table", ...Array.from(usedColumnHelpers).toSorted()];
|
|
104
104
|
if (Object.values(snapshot.tables).some((t) => t.indexes.some((i) => !isAutoUniqueName(t.name, i)))) helpers.push("index");
|
|
105
105
|
if (Object.values(snapshot.tables).some((t) => t.indexes.some((i) => i.unique && !isAutoUniqueName(t.name, i))) && !helpers.includes("unique")) helpers.push("unique");
|
|
106
106
|
return [
|
|
@@ -310,6 +310,7 @@ function diffEnumsCreatePhase(prev, next, changes) {
|
|
|
310
310
|
const prior = prevEnums[name];
|
|
311
311
|
if (!prior) continue;
|
|
312
312
|
const priorValues = new Set(prior.values);
|
|
313
|
+
const nextValues = new Set(e.values);
|
|
313
314
|
const nextValueList = e.values;
|
|
314
315
|
for (let i = 0; i < nextValueList.length; i++) {
|
|
315
316
|
const value = nextValueList[i];
|
|
@@ -323,6 +324,12 @@ function diffEnumsCreatePhase(prev, next, changes) {
|
|
|
323
324
|
...beforeIsExisting ? { before } : {}
|
|
324
325
|
});
|
|
325
326
|
}
|
|
327
|
+
const removed = prior.values.filter((v) => !nextValues.has(v));
|
|
328
|
+
if (removed.length > 0) changes.push({
|
|
329
|
+
kind: "removeEnumValue",
|
|
330
|
+
enum: name,
|
|
331
|
+
removed
|
|
332
|
+
});
|
|
326
333
|
}
|
|
327
334
|
}
|
|
328
335
|
function diffEnumsDropPhase(prev, next, changes) {
|
|
@@ -428,7 +435,7 @@ function columnAttrsEqual(a, b) {
|
|
|
428
435
|
function invertChanges(forward) {
|
|
429
436
|
const reversed = [];
|
|
430
437
|
for (const change of forward) reversed.push(invert(change));
|
|
431
|
-
return reversed.
|
|
438
|
+
return reversed.toReversed();
|
|
432
439
|
}
|
|
433
440
|
function invert(change) {
|
|
434
441
|
switch (change.kind) {
|
|
@@ -497,6 +504,7 @@ function invert(change) {
|
|
|
497
504
|
enum: change.enum
|
|
498
505
|
};
|
|
499
506
|
case "addEnumValue": return change;
|
|
507
|
+
case "removeEnumValue": return change;
|
|
500
508
|
}
|
|
501
509
|
}
|
|
502
510
|
/**
|
|
@@ -508,7 +516,8 @@ const AMBIGUOUS_REVERSE_KINDS = new Set([
|
|
|
508
516
|
"dropTable",
|
|
509
517
|
"dropColumn",
|
|
510
518
|
"alterColumn",
|
|
511
|
-
"addEnumValue"
|
|
519
|
+
"addEnumValue",
|
|
520
|
+
"removeEnumValue"
|
|
512
521
|
]);
|
|
513
522
|
function hasAmbiguousReverse(forward) {
|
|
514
523
|
return forward.some((c) => AMBIGUOUS_REVERSE_KINDS.has(c.kind));
|
|
@@ -758,7 +767,7 @@ async function readColumns(client, schema, table) {
|
|
|
758
767
|
}
|
|
759
768
|
function isSerialColumn(r) {
|
|
760
769
|
if (!r.column_default) return false;
|
|
761
|
-
if (
|
|
770
|
+
if (!r.column_default.startsWith("nextval(")) return false;
|
|
762
771
|
return r.udt_name === "int2" || r.udt_name === "int4" || r.udt_name === "int8";
|
|
763
772
|
}
|
|
764
773
|
function serialTypeFor(r) {
|
|
@@ -817,7 +826,7 @@ async function readIndexes(client, schema, table) {
|
|
|
817
826
|
}
|
|
818
827
|
entry.columns.push(r.column_name);
|
|
819
828
|
}
|
|
820
|
-
return [...byIndex.values()].filter((i) => !i._isPrimary).map(({ _isPrimary, ...rest }) => rest).
|
|
829
|
+
return [...byIndex.values()].filter((i) => !i._isPrimary).map(({ _isPrimary, ...rest }) => rest).toSorted((a, b) => a.name.localeCompare(b.name));
|
|
821
830
|
}
|
|
822
831
|
async function readForeignKeys(client, schema, table) {
|
|
823
832
|
const rows = await client.query(`SELECT tc.constraint_name,
|
|
@@ -857,7 +866,7 @@ async function readForeignKeys(client, schema, table) {
|
|
|
857
866
|
fk.columns.push(r.column_name);
|
|
858
867
|
fk.refColumns.push(r.ref_column);
|
|
859
868
|
}
|
|
860
|
-
return [...byName.values()].
|
|
869
|
+
return [...byName.values()].toSorted((a, b) => a.name.localeCompare(b.name));
|
|
861
870
|
}
|
|
862
871
|
function mapFkAction(raw) {
|
|
863
872
|
switch (raw.toUpperCase()) {
|
|
@@ -1000,7 +1009,7 @@ async function maybeCheckDrift(opts) {
|
|
|
1000
1009
|
if (behavior === "ignore") return;
|
|
1001
1010
|
const applied = await opts.adapter.listApplied();
|
|
1002
1011
|
if (applied.length === 0) return;
|
|
1003
|
-
const sorted = [...applied].
|
|
1012
|
+
const sorted = [...applied].toSorted((a, b) => a.batch !== b.batch ? a.batch - b.batch : a.appliedAt.localeCompare(b.appliedAt));
|
|
1004
1013
|
const last = sorted[sorted.length - 1];
|
|
1005
1014
|
let expected;
|
|
1006
1015
|
try {
|
|
@@ -1038,7 +1047,7 @@ async function migrateDown(opts) {
|
|
|
1038
1047
|
return withLock(opts, async () => {
|
|
1039
1048
|
const applied = await opts.adapter.listApplied();
|
|
1040
1049
|
if (applied.length === 0) return { reversed: null };
|
|
1041
|
-
const sorted = [...applied].
|
|
1050
|
+
const sorted = [...applied].toSorted((a, b) => a.batch !== b.batch ? a.batch - b.batch : a.appliedAt.localeCompare(b.appliedAt));
|
|
1042
1051
|
const last = sorted[sorted.length - 1];
|
|
1043
1052
|
await applyReverse(last.id, opts);
|
|
1044
1053
|
return { reversed: last.id };
|
|
@@ -1077,7 +1086,7 @@ async function migrateRollback(opts) {
|
|
|
1077
1086
|
batch: null
|
|
1078
1087
|
};
|
|
1079
1088
|
const lastBatch = Math.max(...applied.map((r) => r.batch));
|
|
1080
|
-
const targets = applied.filter((r) => r.batch === lastBatch).
|
|
1089
|
+
const targets = applied.filter((r) => r.batch === lastBatch).toSorted((a, b) => a.appliedAt.localeCompare(b.appliedAt)).toReversed();
|
|
1081
1090
|
const reversed = [];
|
|
1082
1091
|
for (const row of targets) {
|
|
1083
1092
|
await applyReverse(row.id, opts);
|
|
@@ -1117,12 +1126,18 @@ const kickDbAdapter = defineAdapter({
|
|
|
1117
1126
|
})).filter((s) => s.state === "pending");
|
|
1118
1127
|
if (pending.length > 0) {
|
|
1119
1128
|
if (policy === "fail-if-pending") throw new Error(`kickjs-db: ${pending.length} pending migration(s); run \`kick db migrate latest\` before boot`);
|
|
1120
|
-
if (policy === "apply")
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1129
|
+
if (policy === "apply") {
|
|
1130
|
+
const result = await migrateLatest({
|
|
1131
|
+
adapter: config.migrationAdapter,
|
|
1132
|
+
migrationsDir: config.migrationsDir,
|
|
1133
|
+
requireReviewed: config.requireReviewed,
|
|
1134
|
+
driftCheck: config.driftCheck
|
|
1135
|
+
});
|
|
1136
|
+
if (config.bus) config.bus.emit("db:migration-applied", {
|
|
1137
|
+
applied: result.applied,
|
|
1138
|
+
batch: result.batch
|
|
1139
|
+
});
|
|
1140
|
+
}
|
|
1126
1141
|
}
|
|
1127
1142
|
if (config.token) container.registerFactory(config.token, () => config.migrationAdapter);
|
|
1128
1143
|
},
|
|
@@ -1211,12 +1226,17 @@ function customType(opts) {
|
|
|
1211
1226
|
}
|
|
1212
1227
|
//#endregion
|
|
1213
1228
|
//#region src/client/codec-plugin.ts
|
|
1214
|
-
var
|
|
1215
|
-
constructor(decoders) {
|
|
1229
|
+
var CodecPlugin = class {
|
|
1230
|
+
constructor(encoders, decoders) {
|
|
1231
|
+
this.encoders = encoders;
|
|
1216
1232
|
this.decoders = decoders;
|
|
1217
1233
|
}
|
|
1218
1234
|
transformQuery(args) {
|
|
1219
|
-
return args.node;
|
|
1235
|
+
if (this.encoders.size === 0) return args.node;
|
|
1236
|
+
const node = args.node;
|
|
1237
|
+
if (InsertQueryNode.is(node)) return this.transformInsert(node);
|
|
1238
|
+
if (UpdateQueryNode.is(node)) return this.transformUpdate(node);
|
|
1239
|
+
return node;
|
|
1220
1240
|
}
|
|
1221
1241
|
async transformResult(args) {
|
|
1222
1242
|
if (this.decoders.size === 0) return args.result;
|
|
@@ -1226,6 +1246,80 @@ var CodecResultPlugin = class {
|
|
|
1226
1246
|
rows
|
|
1227
1247
|
};
|
|
1228
1248
|
}
|
|
1249
|
+
transformInsert(node) {
|
|
1250
|
+
const cols = node.columns;
|
|
1251
|
+
const values = node.values;
|
|
1252
|
+
if (!cols || !values) return node;
|
|
1253
|
+
const positional = this.positionalEncoders(cols);
|
|
1254
|
+
if (!positional) return node;
|
|
1255
|
+
if (ValuesNode.is(values)) {
|
|
1256
|
+
const items = values.values.map((item) => this.encodeValuesItem(item, positional));
|
|
1257
|
+
if (!items.some((item, i) => item !== values.values[i])) return node;
|
|
1258
|
+
return InsertQueryNode.cloneWith(node, { values: ValuesNode.create(items) });
|
|
1259
|
+
}
|
|
1260
|
+
return node;
|
|
1261
|
+
}
|
|
1262
|
+
transformUpdate(node) {
|
|
1263
|
+
const updates = node.updates;
|
|
1264
|
+
if (!updates || updates.length === 0) return node;
|
|
1265
|
+
let changed = false;
|
|
1266
|
+
const next = updates.map((u) => {
|
|
1267
|
+
const col = u.column;
|
|
1268
|
+
if (!ColumnNode.is(col)) return u;
|
|
1269
|
+
const encoder = this.encoders.get(col.column.name);
|
|
1270
|
+
if (!encoder) return u;
|
|
1271
|
+
const encoded = this.encodeValueNode(u.value, encoder);
|
|
1272
|
+
if (encoded === u.value) return u;
|
|
1273
|
+
changed = true;
|
|
1274
|
+
return ColumnUpdateNode.create(col, encoded);
|
|
1275
|
+
});
|
|
1276
|
+
if (!changed) return node;
|
|
1277
|
+
return {
|
|
1278
|
+
...node,
|
|
1279
|
+
updates: next
|
|
1280
|
+
};
|
|
1281
|
+
}
|
|
1282
|
+
positionalEncoders(cols) {
|
|
1283
|
+
const out = Array.from({ length: cols.length });
|
|
1284
|
+
let any = false;
|
|
1285
|
+
for (let i = 0; i < cols.length; i++) {
|
|
1286
|
+
const enc = this.encoders.get(cols[i].column.name) ?? null;
|
|
1287
|
+
out[i] = enc;
|
|
1288
|
+
if (enc) any = true;
|
|
1289
|
+
}
|
|
1290
|
+
return any ? out : null;
|
|
1291
|
+
}
|
|
1292
|
+
encodeValuesItem(item, positional) {
|
|
1293
|
+
if (ValueListNode.is(item)) {
|
|
1294
|
+
const next = item.values.map((v, i) => {
|
|
1295
|
+
const enc = positional[i];
|
|
1296
|
+
if (!enc) return v;
|
|
1297
|
+
return this.encodeValueNode(v, enc);
|
|
1298
|
+
});
|
|
1299
|
+
return next.some((v, i) => v !== item.values[i]) ? ValueListNode.create(next) : item;
|
|
1300
|
+
}
|
|
1301
|
+
if (PrimitiveValueListNode.is(item)) {
|
|
1302
|
+
const next = item.values.map((v, i) => {
|
|
1303
|
+
const enc = positional[i];
|
|
1304
|
+
if (!enc) return v;
|
|
1305
|
+
return this.encodePrimitive(v, enc);
|
|
1306
|
+
});
|
|
1307
|
+
return next.some((v, i) => v !== item.values[i]) ? PrimitiveValueListNode.create(next) : item;
|
|
1308
|
+
}
|
|
1309
|
+
return item;
|
|
1310
|
+
}
|
|
1311
|
+
encodeValueNode(node, encoder) {
|
|
1312
|
+
if (!ValueNode.is(node)) return node;
|
|
1313
|
+
const value = node.value;
|
|
1314
|
+
if (value === null || value === void 0) return node;
|
|
1315
|
+
const encoded = encoder(value);
|
|
1316
|
+
if (encoded === value) return node;
|
|
1317
|
+
return ValueNode.create(encoded);
|
|
1318
|
+
}
|
|
1319
|
+
encodePrimitive(value, encoder) {
|
|
1320
|
+
if (value === null || value === void 0) return value;
|
|
1321
|
+
return encoder(value);
|
|
1322
|
+
}
|
|
1229
1323
|
decodeRow(row) {
|
|
1230
1324
|
let mutated = false;
|
|
1231
1325
|
const out = {};
|
|
@@ -1243,27 +1337,141 @@ var CodecResultPlugin = class {
|
|
|
1243
1337
|
/**
|
|
1244
1338
|
* Walk a schema record and collect decoders from every column whose
|
|
1245
1339
|
* builder is a `CustomColumnBuilder` with a `fromDriver` codec set.
|
|
1246
|
-
*
|
|
1247
|
-
* Schema entries that aren't table declarations (e.g. `relations()`
|
|
1248
|
-
* registrations) are skipped. Columns without a fromDriver are
|
|
1249
|
-
* skipped — registering an entry without one would still cost a
|
|
1250
|
-
* Map lookup per row for no payoff.
|
|
1251
1340
|
*/
|
|
1252
1341
|
function buildDecoderMap(schema) {
|
|
1253
|
-
|
|
1254
|
-
|
|
1342
|
+
return collectCodecs(schema, "fromDriver");
|
|
1343
|
+
}
|
|
1344
|
+
/**
|
|
1345
|
+
* Walk a schema record and collect encoders from every column whose
|
|
1346
|
+
* builder is a `CustomColumnBuilder` with a `toDriver` codec set.
|
|
1347
|
+
*/
|
|
1348
|
+
function buildEncoderMap(schema) {
|
|
1349
|
+
return collectCodecs(schema, "toDriver");
|
|
1350
|
+
}
|
|
1351
|
+
function collectCodecs(schema, key) {
|
|
1352
|
+
const out = /* @__PURE__ */ new Map();
|
|
1353
|
+
if (!schema || typeof schema !== "object") return out;
|
|
1255
1354
|
for (const value of Object.values(schema)) {
|
|
1256
1355
|
if (!isTableDecl(value)) continue;
|
|
1257
|
-
for (const [colName, col] of Object.entries(value.__columns)) if (col instanceof CustomColumnBuilder
|
|
1356
|
+
for (const [colName, col] of Object.entries(value.__columns)) if (col instanceof CustomColumnBuilder) {
|
|
1357
|
+
const fn = col[key];
|
|
1358
|
+
if (fn) out.set(colName, fn);
|
|
1359
|
+
}
|
|
1258
1360
|
}
|
|
1259
|
-
return
|
|
1361
|
+
return out;
|
|
1260
1362
|
}
|
|
1261
1363
|
function isTableDecl(value) {
|
|
1262
1364
|
return typeof value === "object" && value !== null && value.__isTable === true;
|
|
1263
1365
|
}
|
|
1264
1366
|
//#endregion
|
|
1367
|
+
//#region src/extend/result-plugin.ts
|
|
1368
|
+
var ResultExtensionPlugin = class {
|
|
1369
|
+
byTable;
|
|
1370
|
+
/**
|
|
1371
|
+
* Map of queryId → table name the query targets. Populated in
|
|
1372
|
+
* transformQuery, consumed in transformResult, deleted after use so
|
|
1373
|
+
* it doesn't leak across long-lived clients.
|
|
1374
|
+
*/
|
|
1375
|
+
pending = /* @__PURE__ */ new Map();
|
|
1376
|
+
constructor(extensions) {
|
|
1377
|
+
this.byTable = /* @__PURE__ */ new Map();
|
|
1378
|
+
for (const [tableName, bag] of Object.entries(extensions)) {
|
|
1379
|
+
if (!bag) continue;
|
|
1380
|
+
const entries = Object.entries(bag);
|
|
1381
|
+
if (entries.length === 0) continue;
|
|
1382
|
+
this.byTable.set(tableName, Object.fromEntries(entries));
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
transformQuery(args) {
|
|
1386
|
+
const { node, queryId } = args;
|
|
1387
|
+
if (!SelectQueryNode.is(node)) return node;
|
|
1388
|
+
const tableName = singleTableTarget(node);
|
|
1389
|
+
if (!tableName) return node;
|
|
1390
|
+
const bag = this.byTable.get(tableName);
|
|
1391
|
+
if (!bag) return node;
|
|
1392
|
+
this.pending.set(queryId, tableName);
|
|
1393
|
+
return injectNeeds(node, bag);
|
|
1394
|
+
}
|
|
1395
|
+
async transformResult(args) {
|
|
1396
|
+
const tableName = this.pending.get(args.queryId);
|
|
1397
|
+
if (!tableName) return args.result;
|
|
1398
|
+
this.pending.delete(args.queryId);
|
|
1399
|
+
const bag = this.byTable.get(tableName);
|
|
1400
|
+
if (!bag) return args.result;
|
|
1401
|
+
const computeds = Object.entries(bag);
|
|
1402
|
+
if (computeds.length === 0) return args.result;
|
|
1403
|
+
const rows = args.result.rows.map((row) => {
|
|
1404
|
+
if (row === null || row === void 0) return row;
|
|
1405
|
+
const base = row;
|
|
1406
|
+
const next = { ...base };
|
|
1407
|
+
for (const [key, ext] of computeds) try {
|
|
1408
|
+
next[key] = ext.compute(base);
|
|
1409
|
+
} catch {
|
|
1410
|
+
next[key] = void 0;
|
|
1411
|
+
}
|
|
1412
|
+
return next;
|
|
1413
|
+
});
|
|
1414
|
+
return {
|
|
1415
|
+
...args.result,
|
|
1416
|
+
rows
|
|
1417
|
+
};
|
|
1418
|
+
}
|
|
1419
|
+
};
|
|
1420
|
+
/**
|
|
1421
|
+
* Detect the single table this select reads from. Returns the table
|
|
1422
|
+
* name when from has exactly one TableNode (or AliasNode wrapping
|
|
1423
|
+
* one); returns null for joins, sub-selects, multi-table selects,
|
|
1424
|
+
* and anything we can't reliably attribute. The plugin only acts on
|
|
1425
|
+
* single-table selects in v1.
|
|
1426
|
+
*/
|
|
1427
|
+
function singleTableTarget(node) {
|
|
1428
|
+
const from = node.from;
|
|
1429
|
+
if (!from || from.froms.length !== 1) return null;
|
|
1430
|
+
const target = unwrapAlias(from.froms[0]);
|
|
1431
|
+
if (!TableNode.is(target)) return null;
|
|
1432
|
+
return target.table.identifier.name;
|
|
1433
|
+
}
|
|
1434
|
+
function unwrapAlias(node) {
|
|
1435
|
+
if (node.kind === "AliasNode") return node.node;
|
|
1436
|
+
return node;
|
|
1437
|
+
}
|
|
1438
|
+
/**
|
|
1439
|
+
* Inject every needs column not already represented in the select
|
|
1440
|
+
* list. SelectAllNode (the `*` wildcard) means "all columns", in
|
|
1441
|
+
* which case there's nothing to add. Specific column references are
|
|
1442
|
+
* deduped by name so a column already selected explicitly stays put
|
|
1443
|
+
* exactly once.
|
|
1444
|
+
*/
|
|
1445
|
+
function injectNeeds(node, bag) {
|
|
1446
|
+
const selections = node.selections ?? [];
|
|
1447
|
+
if (selections.some(isSelectAll)) return node;
|
|
1448
|
+
const have = /* @__PURE__ */ new Set();
|
|
1449
|
+
for (const sel of selections) {
|
|
1450
|
+
const inner = sel.selection;
|
|
1451
|
+
if (ReferenceNode.is(inner) && ColumnNode.is(inner.column)) have.add(inner.column.column.name);
|
|
1452
|
+
else if (ColumnNode.is(inner)) have.add(inner.column.name);
|
|
1453
|
+
}
|
|
1454
|
+
const allNeeded = /* @__PURE__ */ new Set();
|
|
1455
|
+
for (const ext of Object.values(bag)) for (const col of Object.keys(ext.needs)) allNeeded.add(col);
|
|
1456
|
+
const missing = [...allNeeded].filter((c) => !have.has(c));
|
|
1457
|
+
if (missing.length === 0) return node;
|
|
1458
|
+
const additions = missing.map((col) => SelectionNode.create(ReferenceNode.create(ColumnNode.create(col))));
|
|
1459
|
+
return SelectQueryNode.cloneWithSelections(node, additions);
|
|
1460
|
+
}
|
|
1461
|
+
function isSelectAll(node) {
|
|
1462
|
+
const inner = node.selection;
|
|
1463
|
+
if (SelectAllNode.is(inner)) return true;
|
|
1464
|
+
if (ReferenceNode.is(inner) && SelectAllNode.is(inner.column)) return true;
|
|
1465
|
+
return false;
|
|
1466
|
+
}
|
|
1467
|
+
//#endregion
|
|
1265
1468
|
//#region src/extend/apply.ts
|
|
1266
|
-
function applyExtensions(client, ext) {
|
|
1469
|
+
function applyExtensions(client, ctx, ext) {
|
|
1470
|
+
let baseClient = client;
|
|
1471
|
+
if (hasResultExtensions(ext.result)) {
|
|
1472
|
+
const plugin = new ResultExtensionPlugin(ext.result);
|
|
1473
|
+
baseClient = wrap(client.qb.withPlugin(plugin), ctx);
|
|
1474
|
+
}
|
|
1267
1475
|
let proxy;
|
|
1268
1476
|
const modelBag = {};
|
|
1269
1477
|
const model = ext.model ?? {};
|
|
@@ -1274,53 +1482,19 @@ function applyExtensions(client, ext) {
|
|
|
1274
1482
|
for (const [methodName, fn] of Object.entries(methods)) bound[methodName] = (...args) => fn.call(proxy, ...args);
|
|
1275
1483
|
modelBag[tableName] = bound;
|
|
1276
1484
|
}
|
|
1277
|
-
proxy = new Proxy(
|
|
1278
|
-
if (typeof prop === "string" && prop
|
|
1485
|
+
proxy = new Proxy(baseClient, { get(target, prop) {
|
|
1486
|
+
if (typeof prop === "string" && Object.prototype.hasOwnProperty.call(modelBag, prop)) return modelBag[prop];
|
|
1279
1487
|
return target[prop];
|
|
1280
1488
|
} });
|
|
1281
1489
|
return proxy;
|
|
1282
1490
|
}
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
const slowThreshold = opts.slowQueryThresholdMs ?? null;
|
|
1288
|
-
const decoders = buildDecoderMap(opts.schema);
|
|
1289
|
-
const codecPlugin = decoders.size > 0 ? new CodecResultPlugin(decoders) : null;
|
|
1290
|
-
return wrap(new Kysely({
|
|
1291
|
-
dialect: opts.dialect,
|
|
1292
|
-
plugins: codecPlugin ? [codecPlugin] : void 0,
|
|
1293
|
-
log: events ? (event) => {
|
|
1294
|
-
if (event.level === "query") {
|
|
1295
|
-
const durationMs = event.queryDurationMillis;
|
|
1296
|
-
const payload = {
|
|
1297
|
-
sql: event.query.sql,
|
|
1298
|
-
parameters: event.query.parameters,
|
|
1299
|
-
durationMs
|
|
1300
|
-
};
|
|
1301
|
-
events.emit("query", payload);
|
|
1302
|
-
if (slowThreshold != null && durationMs >= slowThreshold) events.emit("slowQuery", {
|
|
1303
|
-
...payload,
|
|
1304
|
-
thresholdMs: slowThreshold
|
|
1305
|
-
});
|
|
1306
|
-
} else if (event.level === "error") events.emit("queryError", {
|
|
1307
|
-
sql: event.query.sql,
|
|
1308
|
-
parameters: event.query.parameters,
|
|
1309
|
-
error: event.error
|
|
1310
|
-
});
|
|
1311
|
-
} : void 0
|
|
1312
|
-
}), {
|
|
1313
|
-
events,
|
|
1314
|
-
dialect: detectDialect(opts.dialect),
|
|
1315
|
-
savepointCounter: { value: 0 }
|
|
1316
|
-
});
|
|
1317
|
-
}
|
|
1318
|
-
function detectDialect(dialect) {
|
|
1319
|
-
const name = dialect.constructor?.name ?? "";
|
|
1320
|
-
if (name.includes("Postgres")) return "postgres";
|
|
1321
|
-
if (name.includes("Mysql") || name.includes("MySql")) return "mysql";
|
|
1322
|
-
return "sqlite";
|
|
1491
|
+
function hasResultExtensions(result) {
|
|
1492
|
+
if (!result || typeof result !== "object") return false;
|
|
1493
|
+
for (const bag of Object.values(result)) if (bag && typeof bag === "object" && Object.keys(bag).length > 0) return true;
|
|
1494
|
+
return false;
|
|
1323
1495
|
}
|
|
1496
|
+
//#endregion
|
|
1497
|
+
//#region src/client/wrap.ts
|
|
1324
1498
|
function wrap(qb, ctx) {
|
|
1325
1499
|
const client = {
|
|
1326
1500
|
qb,
|
|
@@ -1363,7 +1537,7 @@ function wrap(qb, ctx) {
|
|
|
1363
1537
|
return run();
|
|
1364
1538
|
}),
|
|
1365
1539
|
$extends(ext) {
|
|
1366
|
-
return applyExtensions(client, ext);
|
|
1540
|
+
return applyExtensions(client, ctx, ext);
|
|
1367
1541
|
},
|
|
1368
1542
|
async savepoint(fn) {
|
|
1369
1543
|
const name = `sp_${++ctx.savepointCounter.value}`;
|
|
@@ -1384,6 +1558,57 @@ function wrap(qb, ctx) {
|
|
|
1384
1558
|
return client;
|
|
1385
1559
|
}
|
|
1386
1560
|
//#endregion
|
|
1561
|
+
//#region src/client/create.ts
|
|
1562
|
+
function createDbClient(opts) {
|
|
1563
|
+
const events = opts.events || opts.slowQueryThresholdMs != null || opts.bus != null ? new KickDbEventEmitter() : null;
|
|
1564
|
+
const slowThreshold = opts.slowQueryThresholdMs ?? null;
|
|
1565
|
+
const bus = opts.bus ?? null;
|
|
1566
|
+
if (events && bus) {
|
|
1567
|
+
events.on("slowQuery", (payload) => {
|
|
1568
|
+
bus.emit("db:slow-query", payload);
|
|
1569
|
+
});
|
|
1570
|
+
events.on("queryError", (payload) => {
|
|
1571
|
+
bus.emit("db:query-error", payload);
|
|
1572
|
+
});
|
|
1573
|
+
}
|
|
1574
|
+
const decoders = buildDecoderMap(opts.schema);
|
|
1575
|
+
const encoders = buildEncoderMap(opts.schema);
|
|
1576
|
+
const codecPlugin = decoders.size > 0 || encoders.size > 0 ? new CodecPlugin(encoders, decoders) : null;
|
|
1577
|
+
return wrap(new Kysely({
|
|
1578
|
+
dialect: opts.dialect,
|
|
1579
|
+
plugins: codecPlugin ? [codecPlugin] : void 0,
|
|
1580
|
+
log: events ? (event) => {
|
|
1581
|
+
if (event.level === "query") {
|
|
1582
|
+
const durationMs = event.queryDurationMillis;
|
|
1583
|
+
const payload = {
|
|
1584
|
+
sql: event.query.sql,
|
|
1585
|
+
parameters: event.query.parameters,
|
|
1586
|
+
durationMs
|
|
1587
|
+
};
|
|
1588
|
+
events.emit("query", payload);
|
|
1589
|
+
if (slowThreshold != null && durationMs >= slowThreshold) events.emit("slowQuery", {
|
|
1590
|
+
...payload,
|
|
1591
|
+
thresholdMs: slowThreshold
|
|
1592
|
+
});
|
|
1593
|
+
} else if (event.level === "error") events.emit("queryError", {
|
|
1594
|
+
sql: event.query.sql,
|
|
1595
|
+
parameters: event.query.parameters,
|
|
1596
|
+
error: event.error
|
|
1597
|
+
});
|
|
1598
|
+
} : void 0
|
|
1599
|
+
}), {
|
|
1600
|
+
events,
|
|
1601
|
+
dialect: detectDialect(opts.dialect),
|
|
1602
|
+
savepointCounter: { value: 0 }
|
|
1603
|
+
});
|
|
1604
|
+
}
|
|
1605
|
+
function detectDialect(dialect) {
|
|
1606
|
+
const name = dialect.constructor?.name ?? "";
|
|
1607
|
+
if (name.includes("Postgres")) return "postgres";
|
|
1608
|
+
if (name.includes("Mysql") || name.includes("MySql")) return "mysql";
|
|
1609
|
+
return "sqlite";
|
|
1610
|
+
}
|
|
1611
|
+
//#endregion
|
|
1387
1612
|
//#region src/emit/identifiers.ts
|
|
1388
1613
|
function quoteIdent(name) {
|
|
1389
1614
|
return name.split(".").map((part) => "\"" + part.replace(/"/g, "\"\"") + "\"").join(".");
|
|
@@ -1418,7 +1643,76 @@ function emitChange(change) {
|
|
|
1418
1643
|
const before = change.before ? ` BEFORE ${quoteLiteral(change.before)}` : "";
|
|
1419
1644
|
return `ALTER TYPE ${quoteIdent(change.enum)} ADD VALUE ${quoteLiteral(change.value)}${before};`;
|
|
1420
1645
|
}
|
|
1646
|
+
case "removeEnumValue": return emitRemoveEnumValueAdvisory(change.enum, change.removed);
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
/**
|
|
1650
|
+
* PostgreSQL has no `ALTER TYPE … DROP VALUE` — emitting silently
|
|
1651
|
+
* here would drop these values from the schema's intent without
|
|
1652
|
+
* reflecting in the database. Instead we render a multi-line SQL
|
|
1653
|
+
* comment with the manual migration steps the operator must take.
|
|
1654
|
+
*
|
|
1655
|
+
* The migration file still applies cleanly; the comment block makes
|
|
1656
|
+
* the missing operation visible in code review and in the generated
|
|
1657
|
+
* SQL output.
|
|
1658
|
+
*/
|
|
1659
|
+
function emitRemoveEnumValueAdvisory(name, removed) {
|
|
1660
|
+
const safeName = sanitizeForLineComment(quoteIdent(name));
|
|
1661
|
+
return [
|
|
1662
|
+
`-- WARNING: enum ${safeName} dropped value(s): ${removed.map((v) => sanitizeForLineComment(quoteLiteral(v))).join(", ")}.`,
|
|
1663
|
+
`-- PostgreSQL has no ALTER TYPE ... DROP VALUE. To round-trip this`,
|
|
1664
|
+
`-- removal you must:`,
|
|
1665
|
+
`-- 1. Drop or migrate every column whose type is ${safeName} (or any`,
|
|
1666
|
+
`-- composite that references it).`,
|
|
1667
|
+
`-- 2. DROP TYPE ${safeName};`,
|
|
1668
|
+
`-- 3. CREATE TYPE ${safeName} AS ENUM (...) with the new value list.`,
|
|
1669
|
+
`-- 4. Recreate the columns + restore data, mapping any rows that held`,
|
|
1670
|
+
`-- one of the dropped value(s) to a still-valid replacement first.`,
|
|
1671
|
+
`-- This migration emits no SQL for this change — write the steps above`,
|
|
1672
|
+
`-- by hand if the removal is intentional, or restore the value(s) in`,
|
|
1673
|
+
`-- the schema definition to silence this warning.`
|
|
1674
|
+
].join("\n");
|
|
1675
|
+
}
|
|
1676
|
+
/**
|
|
1677
|
+
* Make a value safe to interpolate into a single-line `--` SQL
|
|
1678
|
+
* comment. Identifiers and quoted literals normally don't carry
|
|
1679
|
+
* line breaks, but the user-supplied portion (enum name + values)
|
|
1680
|
+
* can contain anything an adopter passes to `pgEnum()`. A literal
|
|
1681
|
+
* `\n` would terminate the comment early and turn the rest of the
|
|
1682
|
+
* line into executable SQL.
|
|
1683
|
+
*
|
|
1684
|
+
* Scope of the sanitiser:
|
|
1685
|
+
* - Line-break code points (`\r`, `\n`, `U+2028`, `U+2029`) collapse
|
|
1686
|
+
* runs to a single space so the comment stays on one line.
|
|
1687
|
+
* - C0 control bytes excluding tab (0x00-0x08, 0x0B, 0x0C, 0x0E-0x1F)
|
|
1688
|
+
* plus DEL (0x7F) escape to `\x<hh>`.
|
|
1689
|
+
* - Tab (0x09) passes through — visually fine inside a `--` comment.
|
|
1690
|
+
*
|
|
1691
|
+
* Out of scope on purpose: C1 controls (U+0080-U+009F) and other
|
|
1692
|
+
* non-ASCII characters pass through unchanged. Adopters do legitimately
|
|
1693
|
+
* pass UTF-8 enum names + values (`'café'`, `'naïve'`); aggressively
|
|
1694
|
+
* escaping them would degrade the migration file's readability without
|
|
1695
|
+
* adding security — only line terminators can break out of a `--`
|
|
1696
|
+
* comment, and those are handled above.
|
|
1697
|
+
*/
|
|
1698
|
+
function sanitizeForLineComment(value) {
|
|
1699
|
+
let out = "";
|
|
1700
|
+
let prevWasLineBreak = false;
|
|
1701
|
+
for (let i = 0; i < value.length; i++) {
|
|
1702
|
+
const code = value.charCodeAt(i);
|
|
1703
|
+
if (code === 10 || code === 13 || code === 8232 || code === 8233) {
|
|
1704
|
+
if (!prevWasLineBreak) out += " ";
|
|
1705
|
+
prevWasLineBreak = true;
|
|
1706
|
+
continue;
|
|
1707
|
+
}
|
|
1708
|
+
prevWasLineBreak = false;
|
|
1709
|
+
if (code >= 0 && code <= 8 || code === 11 || code === 12 || code >= 14 && code <= 31 || code === 127) {
|
|
1710
|
+
out += `\\x${code.toString(16).padStart(2, "0")}`;
|
|
1711
|
+
continue;
|
|
1712
|
+
}
|
|
1713
|
+
out += value[i];
|
|
1421
1714
|
}
|
|
1715
|
+
return out;
|
|
1422
1716
|
}
|
|
1423
1717
|
function emitAddColumn(table, c) {
|
|
1424
1718
|
return `ALTER TABLE ${quoteIdent(table)} ADD COLUMN ${emitColumnDecl(c)};`;
|
|
@@ -1578,7 +1872,7 @@ async function readLatestSnapshotEntry(migrationsDir) {
|
|
|
1578
1872
|
snapshot: empty,
|
|
1579
1873
|
id: null
|
|
1580
1874
|
};
|
|
1581
|
-
const dirs = (await readdir(migrationsDir)).filter((e) => /^\d{8}_\d{6}_/.test(e)).
|
|
1875
|
+
const dirs = (await readdir(migrationsDir)).filter((e) => /^\d{8}_\d{6}_/.test(e)).toSorted();
|
|
1582
1876
|
if (dirs.length === 0) return {
|
|
1583
1877
|
snapshot: empty,
|
|
1584
1878
|
id: null
|