@nicia-ai/typegraph 0.5.0 → 0.6.0

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.
Files changed (110) hide show
  1. package/README.md +2 -2
  2. package/dist/{ast-CXFx6bF6.d.ts → ast-CG87Zr6p.d.ts} +2 -2
  3. package/dist/{ast-D-3bOanX.d.cts → ast-Cq9qrnNP.d.cts} +2 -2
  4. package/dist/backend/postgres/index.cjs +295 -23
  5. package/dist/backend/postgres/index.cjs.map +1 -1
  6. package/dist/backend/postgres/index.d.cts +33 -10
  7. package/dist/backend/postgres/index.d.ts +33 -10
  8. package/dist/backend/postgres/index.js +285 -5
  9. package/dist/backend/postgres/index.js.map +1 -1
  10. package/dist/backend/sqlite/index.cjs +21 -90
  11. package/dist/backend/sqlite/index.cjs.map +1 -1
  12. package/dist/backend/sqlite/index.d.cts +22 -58
  13. package/dist/backend/sqlite/index.d.ts +22 -58
  14. package/dist/backend/sqlite/index.js +3 -78
  15. package/dist/backend/sqlite/index.js.map +1 -1
  16. package/dist/backend/sqlite/local.cjs +83 -0
  17. package/dist/backend/sqlite/local.cjs.map +1 -0
  18. package/dist/backend/sqlite/local.d.cts +66 -0
  19. package/dist/backend/sqlite/local.d.ts +66 -0
  20. package/dist/backend/sqlite/local.js +77 -0
  21. package/dist/backend/sqlite/local.js.map +1 -0
  22. package/dist/chunk-23NGZHUN.cjs +2132 -0
  23. package/dist/chunk-23NGZHUN.cjs.map +1 -0
  24. package/dist/{chunk-4MTYE6CF.js → chunk-2DKSQNPW.js} +3 -4
  25. package/dist/chunk-2DKSQNPW.js.map +1 -0
  26. package/dist/chunk-JPO7W262.js +2093 -0
  27. package/dist/chunk-JPO7W262.js.map +1 -0
  28. package/dist/{chunk-KPU6TLUV.cjs → chunk-K5O7TOJO.cjs} +15 -16
  29. package/dist/chunk-K5O7TOJO.cjs.map +1 -0
  30. package/dist/{backend/drizzle/schema/postgres.d.ts → ddl-Bcyb4DW1.d.cts} +17 -17
  31. package/dist/{backend/drizzle/schema/postgres.d.cts → ddl-D7DQx8w8.d.ts} +17 -17
  32. package/dist/{index-DyrR_d-H.d.ts → index-QTnQwakS.d.cts} +1 -1
  33. package/dist/{index-DyrR_d-H.d.cts → index-QTnQwakS.d.ts} +1 -1
  34. package/dist/index.d.cts +11 -12
  35. package/dist/index.d.ts +11 -12
  36. package/dist/indexes/index.d.cts +5 -6
  37. package/dist/indexes/index.d.ts +5 -6
  38. package/dist/interchange/index.d.cts +5 -6
  39. package/dist/interchange/index.d.ts +5 -6
  40. package/dist/{manager-DiPf-0GG.d.cts → manager-BImRiYwz.d.cts} +3 -3
  41. package/dist/{manager-DXC7CqKG.d.ts → manager-DGQ9UF18.d.ts} +3 -3
  42. package/dist/profiler/index.d.cts +7 -8
  43. package/dist/profiler/index.d.ts +7 -8
  44. package/dist/schema/index.d.cts +6 -7
  45. package/dist/schema/index.d.ts +6 -7
  46. package/dist/{backend/drizzle/schema/sqlite.d.ts → sqlite-CSJ-fgIm.d.ts} +2 -25
  47. package/dist/{backend/drizzle/schema/sqlite.d.cts → sqlite-FWGZLwDd.d.cts} +2 -25
  48. package/dist/{store-DODIWZxC.d.ts → store-CscQUG-S.d.ts} +5 -6
  49. package/dist/{store-nDW3GOFb.d.cts → store-DNv1yd3n.d.cts} +5 -6
  50. package/dist/{types-DHRsi6j9.d.cts → types-BbMn2Ycv.d.cts} +2 -2
  51. package/dist/{types-ZT5mlism.d.ts → types-C2rhqkg7.d.ts} +2 -2
  52. package/dist/{types-DpIoePMI.d.ts → types-D5ggX07j.d.ts} +2 -3
  53. package/dist/{types-BL1GyVku.d.cts → types-DEMAqkA1.d.cts} +1 -1
  54. package/dist/{types-DCGa53O2.d.ts → types-DJZoHy5R.d.ts} +1 -1
  55. package/dist/{types-DTJEu_-h.d.ts → types-DolHw9pJ.d.cts} +14 -1
  56. package/dist/{types-DTJEu_-h.d.cts → types-DolHw9pJ.d.ts} +14 -1
  57. package/dist/{types-WX8V9dqn.d.cts → types-SVDEKnU6.d.cts} +2 -3
  58. package/package.json +6 -46
  59. package/dist/backend/drizzle/index.cjs +0 -40
  60. package/dist/backend/drizzle/index.cjs.map +0 -1
  61. package/dist/backend/drizzle/index.d.cts +0 -13
  62. package/dist/backend/drizzle/index.d.ts +0 -13
  63. package/dist/backend/drizzle/index.js +0 -11
  64. package/dist/backend/drizzle/index.js.map +0 -1
  65. package/dist/backend/drizzle/postgres.cjs +0 -26
  66. package/dist/backend/drizzle/postgres.cjs.map +0 -1
  67. package/dist/backend/drizzle/postgres.d.cts +0 -35
  68. package/dist/backend/drizzle/postgres.d.ts +0 -35
  69. package/dist/backend/drizzle/postgres.js +0 -9
  70. package/dist/backend/drizzle/postgres.js.map +0 -1
  71. package/dist/backend/drizzle/schema/postgres.cjs +0 -39
  72. package/dist/backend/drizzle/schema/postgres.cjs.map +0 -1
  73. package/dist/backend/drizzle/schema/postgres.js +0 -6
  74. package/dist/backend/drizzle/schema/postgres.js.map +0 -1
  75. package/dist/backend/drizzle/schema/sqlite.cjs +0 -39
  76. package/dist/backend/drizzle/schema/sqlite.cjs.map +0 -1
  77. package/dist/backend/drizzle/schema/sqlite.js +0 -6
  78. package/dist/backend/drizzle/schema/sqlite.js.map +0 -1
  79. package/dist/backend/drizzle/sqlite.cjs +0 -26
  80. package/dist/backend/drizzle/sqlite.cjs.map +0 -1
  81. package/dist/backend/drizzle/sqlite.d.cts +0 -35
  82. package/dist/backend/drizzle/sqlite.d.ts +0 -35
  83. package/dist/backend/drizzle/sqlite.js +0 -9
  84. package/dist/backend/drizzle/sqlite.js.map +0 -1
  85. package/dist/chunk-3PURVEA4.js +0 -193
  86. package/dist/chunk-3PURVEA4.js.map +0 -1
  87. package/dist/chunk-4MTYE6CF.js.map +0 -1
  88. package/dist/chunk-6HFWKZU5.js +0 -1506
  89. package/dist/chunk-6HFWKZU5.js.map +0 -1
  90. package/dist/chunk-ENXM4W4M.cjs +0 -289
  91. package/dist/chunk-ENXM4W4M.cjs.map +0 -1
  92. package/dist/chunk-KKFJJYCP.js +0 -287
  93. package/dist/chunk-KKFJJYCP.js.map +0 -1
  94. package/dist/chunk-KPU6TLUV.cjs.map +0 -1
  95. package/dist/chunk-NU2XNMVI.cjs +0 -201
  96. package/dist/chunk-NU2XNMVI.cjs.map +0 -1
  97. package/dist/chunk-OGGLFYFA.js +0 -177
  98. package/dist/chunk-OGGLFYFA.js.map +0 -1
  99. package/dist/chunk-PW5BSBZV.cjs +0 -1527
  100. package/dist/chunk-PW5BSBZV.cjs.map +0 -1
  101. package/dist/chunk-SMLIWLS7.js +0 -236
  102. package/dist/chunk-SMLIWLS7.js.map +0 -1
  103. package/dist/chunk-UYMT4LO2.cjs +0 -241
  104. package/dist/chunk-UYMT4LO2.cjs.map +0 -1
  105. package/dist/chunk-XZL6MCZJ.cjs +0 -185
  106. package/dist/chunk-XZL6MCZJ.cjs.map +0 -1
  107. package/dist/test-helpers-CIq1Hhj1.d.ts +0 -26
  108. package/dist/test-helpers-DPRFVky4.d.cts +0 -26
  109. package/dist/types-BRzHlhKC.d.cts +0 -14
  110. package/dist/types-BRzHlhKC.d.ts +0 -14
@@ -1,1527 +0,0 @@
1
- 'use strict';
2
-
3
- var chunk44SXEVF4_cjs = require('./chunk-44SXEVF4.cjs');
4
- var drizzleOrm = require('drizzle-orm');
5
-
6
- // src/backend/types.ts
7
- var SQLITE_CAPABILITIES = {
8
- jsonb: false,
9
- // SQLite uses TEXT with json functions
10
- partialIndexes: true,
11
- // SQLite supports WHERE in CREATE INDEX
12
- ginIndexes: false,
13
- // SQLite doesn't have GIN
14
- cte: true,
15
- // SQLite supports WITH
16
- returning: true,
17
- // SQLite 3.35+ supports RETURNING
18
- transactions: true
19
- // SQLite supports transactions
20
- };
21
- var POSTGRES_CAPABILITIES = {
22
- jsonb: true,
23
- // PostgreSQL has native JSONB
24
- partialIndexes: true,
25
- ginIndexes: true,
26
- cte: true,
27
- returning: true,
28
- transactions: true
29
- // PostgreSQL supports transactions
30
- };
31
- var D1_CAPABILITIES = {
32
- jsonb: false,
33
- // D1 uses TEXT with json functions
34
- partialIndexes: true,
35
- ginIndexes: false,
36
- cte: true,
37
- returning: true,
38
- transactions: false
39
- // D1 does NOT support atomic transactions
40
- };
41
-
42
- // src/backend/drizzle/row-mappers.ts
43
- function requireTimestamp(value, field) {
44
- if (value === void 0) {
45
- throw new chunk44SXEVF4_cjs.DatabaseOperationError(
46
- `Expected non-null ${field} timestamp`,
47
- { operation: "select", entity: "row" }
48
- );
49
- }
50
- return value;
51
- }
52
- function nowIso() {
53
- return (/* @__PURE__ */ new Date()).toISOString();
54
- }
55
- function nullToUndefined(value) {
56
- return value ?? void 0;
57
- }
58
- function formatPostgresTimestamp(value) {
59
- if (value === null || value === void 0) return void 0;
60
- if (value instanceof Date) return value.toISOString();
61
- if (typeof value === "string") {
62
- if (value.includes("T")) return value;
63
- const date = new Date(value);
64
- if (!Number.isNaN(date.getTime())) return date.toISOString();
65
- return value;
66
- }
67
- return void 0;
68
- }
69
- function normalizeJsonColumn(value) {
70
- return typeof value === "string" ? value : JSON.stringify(value ?? {});
71
- }
72
- var SQLITE_ROW_MAPPER_CONFIG = {
73
- formatTimestamp: (value) => nullToUndefined(value),
74
- normalizeJson: (value) => value
75
- };
76
- var POSTGRES_ROW_MAPPER_CONFIG = {
77
- formatTimestamp: formatPostgresTimestamp,
78
- normalizeJson: normalizeJsonColumn
79
- };
80
- function createNodeRowMapper(config) {
81
- return (row) => ({
82
- graph_id: row.graph_id,
83
- kind: row.kind,
84
- id: row.id,
85
- props: config.normalizeJson(row.props),
86
- version: row.version,
87
- valid_from: nullToUndefined(config.formatTimestamp(row.valid_from)),
88
- valid_to: nullToUndefined(config.formatTimestamp(row.valid_to)),
89
- created_at: requireTimestamp(config.formatTimestamp(row.created_at), "created_at"),
90
- updated_at: requireTimestamp(config.formatTimestamp(row.updated_at), "updated_at"),
91
- deleted_at: nullToUndefined(config.formatTimestamp(row.deleted_at))
92
- });
93
- }
94
- function createEdgeRowMapper(config) {
95
- return (row) => ({
96
- graph_id: row.graph_id,
97
- id: row.id,
98
- kind: row.kind,
99
- from_kind: row.from_kind,
100
- from_id: row.from_id,
101
- to_kind: row.to_kind,
102
- to_id: row.to_id,
103
- props: config.normalizeJson(row.props),
104
- valid_from: nullToUndefined(config.formatTimestamp(row.valid_from)),
105
- valid_to: nullToUndefined(config.formatTimestamp(row.valid_to)),
106
- created_at: requireTimestamp(config.formatTimestamp(row.created_at), "created_at"),
107
- updated_at: requireTimestamp(config.formatTimestamp(row.updated_at), "updated_at"),
108
- deleted_at: nullToUndefined(config.formatTimestamp(row.deleted_at))
109
- });
110
- }
111
- function createUniqueRowMapper(config) {
112
- return (row) => ({
113
- graph_id: row.graph_id,
114
- node_kind: row.node_kind,
115
- constraint_name: row.constraint_name,
116
- key: row.key,
117
- node_id: row.node_id,
118
- concrete_kind: row.concrete_kind,
119
- deleted_at: nullToUndefined(config.formatTimestamp(row.deleted_at))
120
- });
121
- }
122
- function createSchemaVersionRowMapper(config) {
123
- return (row) => {
124
- const isActiveValue = row.is_active;
125
- const isActive = isActiveValue === true || isActiveValue === 1 || isActiveValue === "1";
126
- return {
127
- graph_id: row.graph_id,
128
- version: row.version,
129
- schema_hash: row.schema_hash,
130
- schema_doc: config.normalizeJson(row.schema_doc),
131
- created_at: requireTimestamp(config.formatTimestamp(row.created_at), "created_at"),
132
- is_active: isActive
133
- };
134
- };
135
- }
136
-
137
- // src/backend/drizzle/operation-backend-core.ts
138
- function chunkArray(values, size) {
139
- if (values.length <= size) {
140
- return [values];
141
- }
142
- const chunks = [];
143
- for (let index = 0; index < values.length; index += size) {
144
- chunks.push(values.slice(index, index + size));
145
- }
146
- return chunks;
147
- }
148
- function createCommonOperationBackend(options) {
149
- const { batchConfig, execution, operationStrategy, rowMappers } = options;
150
- const nowIso2 = options.nowIso ?? nowIso;
151
- return {
152
- async insertNode(params) {
153
- const timestamp = nowIso2();
154
- const query = operationStrategy.buildInsertNode(params, timestamp);
155
- const row = await execution.execGet(query);
156
- if (!row) throw new chunk44SXEVF4_cjs.DatabaseOperationError("Insert node failed: no row returned", { operation: "insert", entity: "node" });
157
- return rowMappers.toNodeRow(row);
158
- },
159
- async insertNodeNoReturn(params) {
160
- const timestamp = nowIso2();
161
- const query = operationStrategy.buildInsertNodeNoReturn(params, timestamp);
162
- await execution.execRun(query);
163
- },
164
- async insertNodesBatch(params) {
165
- if (params.length === 0) {
166
- return;
167
- }
168
- const timestamp = nowIso2();
169
- for (const chunk of chunkArray(params, batchConfig.nodeInsertBatchSize)) {
170
- const query = operationStrategy.buildInsertNodesBatch(chunk, timestamp);
171
- await execution.execRun(query);
172
- }
173
- },
174
- async insertNodesBatchReturning(params) {
175
- if (params.length === 0) {
176
- return [];
177
- }
178
- const timestamp = nowIso2();
179
- const allRows = [];
180
- for (const chunk of chunkArray(params, batchConfig.nodeInsertBatchSize)) {
181
- const query = operationStrategy.buildInsertNodesBatchReturning(chunk, timestamp);
182
- const rows = await execution.execAll(query);
183
- allRows.push(...rows.map((row) => rowMappers.toNodeRow(row)));
184
- }
185
- return allRows;
186
- },
187
- async getNode(graphId, kind, id) {
188
- const query = operationStrategy.buildGetNode(graphId, kind, id);
189
- const row = await execution.execGet(query);
190
- return row ? rowMappers.toNodeRow(row) : void 0;
191
- },
192
- async getNodes(graphId, kind, ids) {
193
- if (ids.length === 0) return [];
194
- const allRows = [];
195
- for (const chunk of chunkArray(ids, batchConfig.getNodesChunkSize)) {
196
- const query = operationStrategy.buildGetNodes(graphId, kind, chunk);
197
- const rows = await execution.execAll(query);
198
- allRows.push(...rows.map((row) => rowMappers.toNodeRow(row)));
199
- }
200
- return allRows;
201
- },
202
- async updateNode(params) {
203
- const timestamp = nowIso2();
204
- const query = operationStrategy.buildUpdateNode(params, timestamp);
205
- const row = await execution.execGet(query);
206
- if (!row) throw new chunk44SXEVF4_cjs.DatabaseOperationError("Update node failed: no row returned", { operation: "update", entity: "node" });
207
- return rowMappers.toNodeRow(row);
208
- },
209
- async deleteNode(params) {
210
- const timestamp = nowIso2();
211
- const query = operationStrategy.buildDeleteNode(params, timestamp);
212
- await execution.execRun(query);
213
- },
214
- // IMPORTANT: This cascade is not atomic. Callers must ensure this runs
215
- // within a transaction to prevent partial deletion on intermediate failure.
216
- async hardDeleteNode(params) {
217
- const deleteUniquesQuery = operationStrategy.buildHardDeleteUniquesByNode(
218
- params.graphId,
219
- params.id
220
- );
221
- await execution.execRun(deleteUniquesQuery);
222
- const deleteEmbeddingsQuery = operationStrategy.buildHardDeleteEmbeddingsByNode(
223
- params.graphId,
224
- params.kind,
225
- params.id
226
- );
227
- await execution.execRun(deleteEmbeddingsQuery);
228
- const deleteEdgesQuery = operationStrategy.buildHardDeleteEdgesByNode(
229
- params.graphId,
230
- params.kind,
231
- params.id
232
- );
233
- await execution.execRun(deleteEdgesQuery);
234
- const query = operationStrategy.buildHardDeleteNode(params);
235
- await execution.execRun(query);
236
- },
237
- async insertEdge(params) {
238
- const timestamp = nowIso2();
239
- const query = operationStrategy.buildInsertEdge(params, timestamp);
240
- const row = await execution.execGet(query);
241
- if (!row) throw new chunk44SXEVF4_cjs.DatabaseOperationError("Insert edge failed: no row returned", { operation: "insert", entity: "edge" });
242
- return rowMappers.toEdgeRow(row);
243
- },
244
- async insertEdgeNoReturn(params) {
245
- const timestamp = nowIso2();
246
- const query = operationStrategy.buildInsertEdgeNoReturn(params, timestamp);
247
- await execution.execRun(query);
248
- },
249
- async insertEdgesBatch(params) {
250
- if (params.length === 0) {
251
- return;
252
- }
253
- const timestamp = nowIso2();
254
- for (const chunk of chunkArray(params, batchConfig.edgeInsertBatchSize)) {
255
- const query = operationStrategy.buildInsertEdgesBatch(chunk, timestamp);
256
- await execution.execRun(query);
257
- }
258
- },
259
- async insertEdgesBatchReturning(params) {
260
- if (params.length === 0) {
261
- return [];
262
- }
263
- const timestamp = nowIso2();
264
- const allRows = [];
265
- for (const chunk of chunkArray(params, batchConfig.edgeInsertBatchSize)) {
266
- const query = operationStrategy.buildInsertEdgesBatchReturning(chunk, timestamp);
267
- const rows = await execution.execAll(query);
268
- allRows.push(...rows.map((row) => rowMappers.toEdgeRow(row)));
269
- }
270
- return allRows;
271
- },
272
- async getEdge(graphId, id) {
273
- const query = operationStrategy.buildGetEdge(graphId, id);
274
- const row = await execution.execGet(query);
275
- return row ? rowMappers.toEdgeRow(row) : void 0;
276
- },
277
- async getEdges(graphId, ids) {
278
- if (ids.length === 0) return [];
279
- const allRows = [];
280
- for (const chunk of chunkArray(ids, batchConfig.getEdgesChunkSize)) {
281
- const query = operationStrategy.buildGetEdges(graphId, chunk);
282
- const rows = await execution.execAll(query);
283
- allRows.push(...rows.map((row) => rowMappers.toEdgeRow(row)));
284
- }
285
- return allRows;
286
- },
287
- async updateEdge(params) {
288
- const timestamp = nowIso2();
289
- const query = operationStrategy.buildUpdateEdge(params, timestamp);
290
- const row = await execution.execGet(query);
291
- if (!row) throw new chunk44SXEVF4_cjs.DatabaseOperationError("Update edge failed: no row returned", { operation: "update", entity: "edge" });
292
- return rowMappers.toEdgeRow(row);
293
- },
294
- async deleteEdge(params) {
295
- const timestamp = nowIso2();
296
- const query = operationStrategy.buildDeleteEdge(params, timestamp);
297
- await execution.execRun(query);
298
- },
299
- async hardDeleteEdge(params) {
300
- const query = operationStrategy.buildHardDeleteEdge(params);
301
- await execution.execRun(query);
302
- },
303
- async countEdgesFrom(params) {
304
- const query = operationStrategy.buildCountEdgesFrom(params);
305
- const row = await execution.execGet(query);
306
- return Number(row?.count ?? 0);
307
- },
308
- async edgeExistsBetween(params) {
309
- const query = operationStrategy.buildEdgeExistsBetween(params);
310
- const row = await execution.execGet(query);
311
- return row !== void 0;
312
- },
313
- async findEdgesConnectedTo(params) {
314
- const query = operationStrategy.buildFindEdgesConnectedTo(params);
315
- const rows = await execution.execAll(query);
316
- return rows.map((row) => rowMappers.toEdgeRow(row));
317
- },
318
- async findNodesByKind(params) {
319
- const query = operationStrategy.buildFindNodesByKind(params);
320
- const rows = await execution.execAll(query);
321
- return rows.map((row) => rowMappers.toNodeRow(row));
322
- },
323
- async countNodesByKind(params) {
324
- const query = operationStrategy.buildCountNodesByKind(params);
325
- const row = await execution.execGet(query);
326
- return Number(row?.count ?? 0);
327
- },
328
- async findEdgesByKind(params) {
329
- const query = operationStrategy.buildFindEdgesByKind(params);
330
- const rows = await execution.execAll(query);
331
- return rows.map((row) => rowMappers.toEdgeRow(row));
332
- },
333
- async countEdgesByKind(params) {
334
- const query = operationStrategy.buildCountEdgesByKind(params);
335
- const row = await execution.execGet(query);
336
- return Number(row?.count ?? 0);
337
- },
338
- async insertUnique(params) {
339
- const query = operationStrategy.buildInsertUnique(params);
340
- const result = await execution.execGet(query);
341
- if (result && result.node_id !== params.nodeId) {
342
- throw new chunk44SXEVF4_cjs.UniquenessError({
343
- constraintName: params.constraintName,
344
- kind: params.nodeKind,
345
- existingId: result.node_id,
346
- newId: params.nodeId,
347
- fields: []
348
- });
349
- }
350
- },
351
- async deleteUnique(params) {
352
- const timestamp = nowIso2();
353
- const query = operationStrategy.buildDeleteUnique(params, timestamp);
354
- await execution.execRun(query);
355
- },
356
- async checkUnique(params) {
357
- const query = operationStrategy.buildCheckUnique(params);
358
- const row = await execution.execGet(query);
359
- return row ? rowMappers.toUniqueRow(row) : void 0;
360
- },
361
- async checkUniqueBatch(params) {
362
- if (params.keys.length === 0) return [];
363
- const query = operationStrategy.buildCheckUniqueBatch(params);
364
- const rows = await execution.execAll(query);
365
- return rows.map((row) => rowMappers.toUniqueRow(row));
366
- },
367
- async getActiveSchema(graphId) {
368
- const query = operationStrategy.buildGetActiveSchema(graphId);
369
- const row = await execution.execGet(query);
370
- return row ? rowMappers.toSchemaVersionRow(row) : void 0;
371
- },
372
- async insertSchema(params) {
373
- const timestamp = nowIso2();
374
- const query = operationStrategy.buildInsertSchema(params, timestamp);
375
- const row = await execution.execGet(query);
376
- if (!row) throw new chunk44SXEVF4_cjs.DatabaseOperationError("Insert schema failed: no row returned", { operation: "insert", entity: "schema" });
377
- return rowMappers.toSchemaVersionRow(row);
378
- },
379
- async getSchemaVersion(graphId, version) {
380
- const query = operationStrategy.buildGetSchemaVersion(graphId, version);
381
- const row = await execution.execGet(query);
382
- return row ? rowMappers.toSchemaVersionRow(row) : void 0;
383
- },
384
- async setActiveSchema(graphId, version) {
385
- const queries = operationStrategy.buildSetActiveSchema(graphId, version);
386
- await execution.execRun(queries.deactivateAll);
387
- await execution.execRun(queries.activateVersion);
388
- },
389
- async clearGraph(graphId) {
390
- const statements = operationStrategy.buildClearGraph(graphId);
391
- for (const statement of statements) {
392
- await execution.execRun(statement);
393
- }
394
- }
395
- };
396
- }
397
- function buildClearGraph(tables, graphId) {
398
- return [
399
- drizzleOrm.sql`DELETE FROM ${tables.embeddings} WHERE ${tables.embeddings.graphId} = ${graphId}`,
400
- drizzleOrm.sql`DELETE FROM ${tables.uniques} WHERE ${tables.uniques.graphId} = ${graphId}`,
401
- drizzleOrm.sql`DELETE FROM ${tables.edges} WHERE ${tables.edges.graphId} = ${graphId}`,
402
- drizzleOrm.sql`DELETE FROM ${tables.nodes} WHERE ${tables.nodes.graphId} = ${graphId}`,
403
- drizzleOrm.sql`DELETE FROM ${tables.schemaVersions} WHERE ${tables.schemaVersions.graphId} = ${graphId}`
404
- ];
405
- }
406
- function buildTemporalConditions(table, params) {
407
- const conditions = [];
408
- const mode = params.temporalMode;
409
- if (mode === "includeTombstones") return conditions;
410
- if (params.excludeDeleted !== false) {
411
- conditions.push(drizzleOrm.sql`${table.deletedAt} IS NULL`);
412
- }
413
- if (mode === "current" || mode === "asOf") {
414
- const asOf = params.asOf;
415
- conditions.push(
416
- drizzleOrm.sql`(${table.validFrom} IS NULL OR ${table.validFrom} <= ${asOf})`,
417
- drizzleOrm.sql`(${table.validTo} IS NULL OR ${table.validTo} > ${asOf})`
418
- );
419
- }
420
- return conditions;
421
- }
422
- function buildFindNodesByKind(tables, params) {
423
- const { nodes } = tables;
424
- const conditions = [
425
- drizzleOrm.sql`${nodes.graphId} = ${params.graphId}`,
426
- drizzleOrm.sql`${nodes.kind} = ${params.kind}`,
427
- ...buildTemporalConditions(nodes, params)
428
- ];
429
- const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
430
- if (params.limit !== void 0 && params.offset !== void 0) {
431
- return drizzleOrm.sql`
432
- SELECT * FROM ${nodes}
433
- WHERE ${whereClause}
434
- ORDER BY ${nodes.createdAt} DESC
435
- LIMIT ${params.limit} OFFSET ${params.offset}
436
- `;
437
- }
438
- if (params.limit !== void 0) {
439
- return drizzleOrm.sql`
440
- SELECT * FROM ${nodes}
441
- WHERE ${whereClause}
442
- ORDER BY ${nodes.createdAt} DESC
443
- LIMIT ${params.limit}
444
- `;
445
- }
446
- return drizzleOrm.sql`
447
- SELECT * FROM ${nodes}
448
- WHERE ${whereClause}
449
- ORDER BY ${nodes.createdAt} DESC
450
- `;
451
- }
452
- function buildCountNodesByKind(tables, params) {
453
- const { nodes } = tables;
454
- const conditions = [
455
- drizzleOrm.sql`${nodes.graphId} = ${params.graphId}`,
456
- drizzleOrm.sql`${nodes.kind} = ${params.kind}`,
457
- ...buildTemporalConditions(nodes, params)
458
- ];
459
- const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
460
- return drizzleOrm.sql`
461
- SELECT COUNT(*) as count FROM ${nodes}
462
- WHERE ${whereClause}
463
- `;
464
- }
465
- function buildFindEdgesByKind(tables, params) {
466
- const { edges } = tables;
467
- const conditions = [
468
- drizzleOrm.sql`${edges.graphId} = ${params.graphId}`,
469
- drizzleOrm.sql`${edges.kind} = ${params.kind}`,
470
- ...buildTemporalConditions(edges, params)
471
- ];
472
- if (params.fromKind !== void 0) {
473
- conditions.push(drizzleOrm.sql`${edges.fromKind} = ${params.fromKind}`);
474
- }
475
- if (params.fromId !== void 0) {
476
- conditions.push(drizzleOrm.sql`${edges.fromId} = ${params.fromId}`);
477
- }
478
- if (params.toKind !== void 0) {
479
- conditions.push(drizzleOrm.sql`${edges.toKind} = ${params.toKind}`);
480
- }
481
- if (params.toId !== void 0) {
482
- conditions.push(drizzleOrm.sql`${edges.toId} = ${params.toId}`);
483
- }
484
- const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
485
- if (params.limit !== void 0 && params.offset !== void 0) {
486
- return drizzleOrm.sql`
487
- SELECT * FROM ${edges}
488
- WHERE ${whereClause}
489
- ORDER BY ${edges.createdAt} DESC
490
- LIMIT ${params.limit} OFFSET ${params.offset}
491
- `;
492
- }
493
- if (params.limit !== void 0) {
494
- return drizzleOrm.sql`
495
- SELECT * FROM ${edges}
496
- WHERE ${whereClause}
497
- ORDER BY ${edges.createdAt} DESC
498
- LIMIT ${params.limit}
499
- `;
500
- }
501
- return drizzleOrm.sql`
502
- SELECT * FROM ${edges}
503
- WHERE ${whereClause}
504
- ORDER BY ${edges.createdAt} DESC
505
- `;
506
- }
507
- function buildCountEdgesByKind(tables, params) {
508
- const { edges } = tables;
509
- const conditions = [
510
- drizzleOrm.sql`${edges.graphId} = ${params.graphId}`,
511
- drizzleOrm.sql`${edges.kind} = ${params.kind}`,
512
- ...buildTemporalConditions(edges, params)
513
- ];
514
- if (params.fromKind !== void 0) {
515
- conditions.push(drizzleOrm.sql`${edges.fromKind} = ${params.fromKind}`);
516
- }
517
- if (params.fromId !== void 0) {
518
- conditions.push(drizzleOrm.sql`${edges.fromId} = ${params.fromId}`);
519
- }
520
- if (params.toKind !== void 0) {
521
- conditions.push(drizzleOrm.sql`${edges.toKind} = ${params.toKind}`);
522
- }
523
- if (params.toId !== void 0) {
524
- conditions.push(drizzleOrm.sql`${edges.toId} = ${params.toId}`);
525
- }
526
- const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
527
- return drizzleOrm.sql`
528
- SELECT COUNT(*) as count FROM ${edges}
529
- WHERE ${whereClause}
530
- `;
531
- }
532
- function sqlNull(value) {
533
- return value ?? drizzleOrm.sql.raw("NULL");
534
- }
535
- function quotedColumn(column) {
536
- return drizzleOrm.sql.raw(`"${column.name.replaceAll('"', '""')}"`);
537
- }
538
- function nodeColumnList(nodes) {
539
- return drizzleOrm.sql.raw(`"${nodes.graphId.name}", "${nodes.kind.name}", "${nodes.id.name}", "${nodes.props.name}", "${nodes.version.name}", "${nodes.validFrom.name}", "${nodes.validTo.name}", "${nodes.createdAt.name}", "${nodes.updatedAt.name}"`);
540
- }
541
- function edgeColumnList(edges) {
542
- return drizzleOrm.sql.raw(`"${edges.graphId.name}", "${edges.id.name}", "${edges.kind.name}", "${edges.fromKind.name}", "${edges.fromId.name}", "${edges.toKind.name}", "${edges.toId.name}", "${edges.props.name}", "${edges.validFrom.name}", "${edges.validTo.name}", "${edges.createdAt.name}", "${edges.updatedAt.name}"`);
543
- }
544
-
545
- // src/backend/drizzle/operations/edges.ts
546
- function buildInsertEdge(tables, params, timestamp) {
547
- const { edges } = tables;
548
- const propsJson = JSON.stringify(params.props);
549
- const columns = edgeColumnList(edges);
550
- return drizzleOrm.sql`
551
- INSERT INTO ${edges} (${columns})
552
- VALUES (
553
- ${params.graphId}, ${params.id}, ${params.kind},
554
- ${params.fromKind}, ${params.fromId}, ${params.toKind}, ${params.toId},
555
- ${propsJson}, ${sqlNull(params.validFrom)}, ${sqlNull(params.validTo)},
556
- ${timestamp}, ${timestamp}
557
- )
558
- RETURNING *
559
- `;
560
- }
561
- function buildInsertEdgeNoReturn(tables, params, timestamp) {
562
- const { edges } = tables;
563
- const propsJson = JSON.stringify(params.props);
564
- const columns = edgeColumnList(edges);
565
- return drizzleOrm.sql`
566
- INSERT INTO ${edges} (${columns})
567
- VALUES (
568
- ${params.graphId}, ${params.id}, ${params.kind},
569
- ${params.fromKind}, ${params.fromId}, ${params.toKind}, ${params.toId},
570
- ${propsJson}, ${sqlNull(params.validFrom)}, ${sqlNull(params.validTo)},
571
- ${timestamp}, ${timestamp}
572
- )
573
- `;
574
- }
575
- function buildInsertEdgesBatch(tables, params, timestamp) {
576
- const { edges } = tables;
577
- const columns = edgeColumnList(edges);
578
- const values = params.map((edgeParams) => {
579
- const propsJson = JSON.stringify(edgeParams.props);
580
- return drizzleOrm.sql`(${edgeParams.graphId}, ${edgeParams.id}, ${edgeParams.kind}, ${edgeParams.fromKind}, ${edgeParams.fromId}, ${edgeParams.toKind}, ${edgeParams.toId}, ${propsJson}, ${sqlNull(edgeParams.validFrom)}, ${sqlNull(edgeParams.validTo)}, ${timestamp}, ${timestamp})`;
581
- });
582
- return drizzleOrm.sql`
583
- INSERT INTO ${edges} (${columns})
584
- VALUES ${drizzleOrm.sql.join(values, drizzleOrm.sql`, `)}
585
- `;
586
- }
587
- function buildInsertEdgesBatchReturning(tables, params, timestamp) {
588
- const { edges } = tables;
589
- const columns = edgeColumnList(edges);
590
- const values = params.map((edgeParams) => {
591
- const propsJson = JSON.stringify(edgeParams.props);
592
- return drizzleOrm.sql`(${edgeParams.graphId}, ${edgeParams.id}, ${edgeParams.kind}, ${edgeParams.fromKind}, ${edgeParams.fromId}, ${edgeParams.toKind}, ${edgeParams.toId}, ${propsJson}, ${sqlNull(edgeParams.validFrom)}, ${sqlNull(edgeParams.validTo)}, ${timestamp}, ${timestamp})`;
593
- });
594
- return drizzleOrm.sql`
595
- INSERT INTO ${edges} (${columns})
596
- VALUES ${drizzleOrm.sql.join(values, drizzleOrm.sql`, `)}
597
- RETURNING *
598
- `;
599
- }
600
- function buildGetEdge(tables, graphId, id) {
601
- const { edges } = tables;
602
- return drizzleOrm.sql`
603
- SELECT * FROM ${edges}
604
- WHERE ${edges.graphId} = ${graphId}
605
- AND ${edges.id} = ${id}
606
- `;
607
- }
608
- function buildGetEdges(tables, graphId, ids) {
609
- const { edges } = tables;
610
- const idPlaceholders = drizzleOrm.sql.join(
611
- ids.map((edgeId) => drizzleOrm.sql`${edgeId}`),
612
- drizzleOrm.sql`, `
613
- );
614
- return drizzleOrm.sql`
615
- SELECT * FROM ${edges}
616
- WHERE ${edges.graphId} = ${graphId}
617
- AND ${edges.id} IN (${idPlaceholders})
618
- `;
619
- }
620
- function buildUpdateEdge(tables, params, timestamp) {
621
- const { edges } = tables;
622
- const propsJson = JSON.stringify(params.props);
623
- const setParts = [
624
- drizzleOrm.sql`${quotedColumn(edges.props)} = ${propsJson}`,
625
- drizzleOrm.sql`${quotedColumn(edges.updatedAt)} = ${timestamp}`
626
- ];
627
- if (params.validTo !== void 0) {
628
- setParts.push(drizzleOrm.sql`${quotedColumn(edges.validTo)} = ${params.validTo}`);
629
- }
630
- if (params.clearDeleted) {
631
- setParts.push(drizzleOrm.sql`${quotedColumn(edges.deletedAt)} = NULL`);
632
- }
633
- const setClause = drizzleOrm.sql.join(setParts, drizzleOrm.sql`, `);
634
- if (params.clearDeleted) {
635
- return drizzleOrm.sql`
636
- UPDATE ${edges}
637
- SET ${setClause}
638
- WHERE ${edges.graphId} = ${params.graphId}
639
- AND ${edges.id} = ${params.id}
640
- RETURNING *
641
- `;
642
- }
643
- return drizzleOrm.sql`
644
- UPDATE ${edges}
645
- SET ${setClause}
646
- WHERE ${edges.graphId} = ${params.graphId}
647
- AND ${edges.id} = ${params.id}
648
- AND ${edges.deletedAt} IS NULL
649
- RETURNING *
650
- `;
651
- }
652
- function buildDeleteEdge(tables, params, timestamp) {
653
- const { edges } = tables;
654
- return drizzleOrm.sql`
655
- UPDATE ${edges}
656
- SET ${quotedColumn(edges.deletedAt)} = ${timestamp}
657
- WHERE ${edges.graphId} = ${params.graphId}
658
- AND ${edges.id} = ${params.id}
659
- AND ${edges.deletedAt} IS NULL
660
- `;
661
- }
662
- function buildHardDeleteEdge(tables, params) {
663
- const { edges } = tables;
664
- return drizzleOrm.sql`
665
- DELETE FROM ${edges}
666
- WHERE ${edges.graphId} = ${params.graphId}
667
- AND ${edges.id} = ${params.id}
668
- `;
669
- }
670
- function buildHardDeleteEdgesByNode(tables, graphId, nodeKind, nodeId) {
671
- const { edges } = tables;
672
- return drizzleOrm.sql`
673
- DELETE FROM ${edges}
674
- WHERE ${edges.graphId} = ${graphId}
675
- AND (
676
- (${edges.fromKind} = ${nodeKind} AND ${edges.fromId} = ${nodeId})
677
- OR (${edges.toKind} = ${nodeKind} AND ${edges.toId} = ${nodeId})
678
- )
679
- `;
680
- }
681
- function buildCountEdgesFrom(tables, params) {
682
- const { edges } = tables;
683
- if (params.activeOnly) {
684
- return drizzleOrm.sql`
685
- SELECT COUNT(*) as count FROM ${edges}
686
- WHERE ${edges.graphId} = ${params.graphId}
687
- AND ${edges.kind} = ${params.edgeKind}
688
- AND ${edges.fromKind} = ${params.fromKind}
689
- AND ${edges.fromId} = ${params.fromId}
690
- AND ${edges.deletedAt} IS NULL
691
- AND ${edges.validTo} IS NULL
692
- `;
693
- }
694
- return drizzleOrm.sql`
695
- SELECT COUNT(*) as count FROM ${edges}
696
- WHERE ${edges.graphId} = ${params.graphId}
697
- AND ${edges.kind} = ${params.edgeKind}
698
- AND ${edges.fromKind} = ${params.fromKind}
699
- AND ${edges.fromId} = ${params.fromId}
700
- AND ${edges.deletedAt} IS NULL
701
- `;
702
- }
703
- function buildEdgeExistsBetween(tables, params) {
704
- const { edges } = tables;
705
- return drizzleOrm.sql`
706
- SELECT 1 FROM ${edges}
707
- WHERE ${edges.graphId} = ${params.graphId}
708
- AND ${edges.kind} = ${params.edgeKind}
709
- AND ${edges.fromKind} = ${params.fromKind}
710
- AND ${edges.fromId} = ${params.fromId}
711
- AND ${edges.toKind} = ${params.toKind}
712
- AND ${edges.toId} = ${params.toId}
713
- AND ${edges.deletedAt} IS NULL
714
- LIMIT 1
715
- `;
716
- }
717
- function buildFindEdgesConnectedTo(tables, params) {
718
- const { edges } = tables;
719
- return drizzleOrm.sql`
720
- SELECT * FROM ${edges}
721
- WHERE ${edges.graphId} = ${params.graphId}
722
- AND ${edges.deletedAt} IS NULL
723
- AND ${edges.fromKind} = ${params.nodeKind}
724
- AND ${edges.fromId} = ${params.nodeId}
725
- UNION ALL
726
- SELECT * FROM ${edges}
727
- WHERE ${edges.graphId} = ${params.graphId}
728
- AND ${edges.deletedAt} IS NULL
729
- AND ${edges.toKind} = ${params.nodeKind}
730
- AND ${edges.toId} = ${params.nodeId}
731
- AND NOT (
732
- ${edges.fromKind} = ${params.nodeKind}
733
- AND ${edges.fromId} = ${params.nodeId}
734
- )
735
- `;
736
- }
737
- function buildInsertNode(tables, params, timestamp) {
738
- const { nodes } = tables;
739
- const propsJson = JSON.stringify(params.props);
740
- const columns = nodeColumnList(nodes);
741
- return drizzleOrm.sql`
742
- INSERT INTO ${nodes} (${columns})
743
- VALUES (
744
- ${params.graphId}, ${params.kind}, ${params.id}, ${propsJson},
745
- 1, ${sqlNull(params.validFrom)}, ${sqlNull(params.validTo)},
746
- ${timestamp}, ${timestamp}
747
- )
748
- RETURNING *
749
- `;
750
- }
751
- function buildInsertNodeNoReturn(tables, params, timestamp) {
752
- const { nodes } = tables;
753
- const propsJson = JSON.stringify(params.props);
754
- const columns = nodeColumnList(nodes);
755
- return drizzleOrm.sql`
756
- INSERT INTO ${nodes} (${columns})
757
- VALUES (
758
- ${params.graphId}, ${params.kind}, ${params.id}, ${propsJson},
759
- 1, ${sqlNull(params.validFrom)}, ${sqlNull(params.validTo)},
760
- ${timestamp}, ${timestamp}
761
- )
762
- `;
763
- }
764
- function buildInsertNodesBatch(tables, params, timestamp) {
765
- const { nodes } = tables;
766
- const columns = nodeColumnList(nodes);
767
- const values = params.map((nodeParams) => {
768
- const propsJson = JSON.stringify(nodeParams.props);
769
- return drizzleOrm.sql`(${nodeParams.graphId}, ${nodeParams.kind}, ${nodeParams.id}, ${propsJson}, 1, ${sqlNull(nodeParams.validFrom)}, ${sqlNull(nodeParams.validTo)}, ${timestamp}, ${timestamp})`;
770
- });
771
- return drizzleOrm.sql`
772
- INSERT INTO ${nodes} (${columns})
773
- VALUES ${drizzleOrm.sql.join(values, drizzleOrm.sql`, `)}
774
- `;
775
- }
776
- function buildInsertNodesBatchReturning(tables, params, timestamp) {
777
- const { nodes } = tables;
778
- const columns = nodeColumnList(nodes);
779
- const values = params.map((nodeParams) => {
780
- const propsJson = JSON.stringify(nodeParams.props);
781
- return drizzleOrm.sql`(${nodeParams.graphId}, ${nodeParams.kind}, ${nodeParams.id}, ${propsJson}, 1, ${sqlNull(nodeParams.validFrom)}, ${sqlNull(nodeParams.validTo)}, ${timestamp}, ${timestamp})`;
782
- });
783
- return drizzleOrm.sql`
784
- INSERT INTO ${nodes} (${columns})
785
- VALUES ${drizzleOrm.sql.join(values, drizzleOrm.sql`, `)}
786
- RETURNING *
787
- `;
788
- }
789
- function buildGetNode(tables, graphId, kind, id) {
790
- const { nodes } = tables;
791
- return drizzleOrm.sql`
792
- SELECT * FROM ${nodes}
793
- WHERE ${nodes.graphId} = ${graphId}
794
- AND ${nodes.kind} = ${kind}
795
- AND ${nodes.id} = ${id}
796
- `;
797
- }
798
- function buildGetNodes(tables, graphId, kind, ids) {
799
- const { nodes } = tables;
800
- const idPlaceholders = drizzleOrm.sql.join(
801
- ids.map((nodeId) => drizzleOrm.sql`${nodeId}`),
802
- drizzleOrm.sql`, `
803
- );
804
- return drizzleOrm.sql`
805
- SELECT * FROM ${nodes}
806
- WHERE ${nodes.graphId} = ${graphId}
807
- AND ${nodes.kind} = ${kind}
808
- AND ${nodes.id} IN (${idPlaceholders})
809
- `;
810
- }
811
- function buildUpdateNode(tables, params, timestamp) {
812
- const { nodes } = tables;
813
- const propsJson = JSON.stringify(params.props);
814
- const setParts = [
815
- drizzleOrm.sql`${quotedColumn(nodes.props)} = ${propsJson}`,
816
- drizzleOrm.sql`${quotedColumn(nodes.updatedAt)} = ${timestamp}`
817
- ];
818
- if (params.incrementVersion) {
819
- setParts.push(
820
- drizzleOrm.sql`${quotedColumn(nodes.version)} = ${quotedColumn(nodes.version)} + 1`
821
- );
822
- }
823
- if (params.validTo !== void 0) {
824
- setParts.push(drizzleOrm.sql`${quotedColumn(nodes.validTo)} = ${params.validTo}`);
825
- }
826
- if (params.clearDeleted) {
827
- setParts.push(drizzleOrm.sql`${quotedColumn(nodes.deletedAt)} = NULL`);
828
- }
829
- const setClause = drizzleOrm.sql.join(setParts, drizzleOrm.sql`, `);
830
- if (params.clearDeleted) {
831
- return drizzleOrm.sql`
832
- UPDATE ${nodes}
833
- SET ${setClause}
834
- WHERE ${nodes.graphId} = ${params.graphId}
835
- AND ${nodes.kind} = ${params.kind}
836
- AND ${nodes.id} = ${params.id}
837
- RETURNING *
838
- `;
839
- }
840
- return drizzleOrm.sql`
841
- UPDATE ${nodes}
842
- SET ${setClause}
843
- WHERE ${nodes.graphId} = ${params.graphId}
844
- AND ${nodes.kind} = ${params.kind}
845
- AND ${nodes.id} = ${params.id}
846
- AND ${nodes.deletedAt} IS NULL
847
- RETURNING *
848
- `;
849
- }
850
- function buildDeleteNode(tables, params, timestamp) {
851
- const { nodes } = tables;
852
- return drizzleOrm.sql`
853
- UPDATE ${nodes}
854
- SET ${quotedColumn(nodes.deletedAt)} = ${timestamp}
855
- WHERE ${nodes.graphId} = ${params.graphId}
856
- AND ${nodes.kind} = ${params.kind}
857
- AND ${nodes.id} = ${params.id}
858
- AND ${nodes.deletedAt} IS NULL
859
- `;
860
- }
861
- function buildHardDeleteNode(tables, params) {
862
- const { nodes } = tables;
863
- return drizzleOrm.sql`
864
- DELETE FROM ${nodes}
865
- WHERE ${nodes.graphId} = ${params.graphId}
866
- AND ${nodes.kind} = ${params.kind}
867
- AND ${nodes.id} = ${params.id}
868
- `;
869
- }
870
- function createSchemaDialectStrategy(dialect) {
871
- const trueLiteral = dialect === "sqlite" ? drizzleOrm.sql.raw("1") : drizzleOrm.sql.raw("TRUE");
872
- const falseLiteral = dialect === "sqlite" ? drizzleOrm.sql.raw("0") : drizzleOrm.sql.raw("FALSE");
873
- return {
874
- booleanLiteral(value) {
875
- return value ? trueLiteral : falseLiteral;
876
- }
877
- };
878
- }
879
- var SCHEMA_DIALECT_STRATEGIES = {
880
- postgres: createSchemaDialectStrategy("postgres"),
881
- sqlite: createSchemaDialectStrategy("sqlite")
882
- };
883
- function buildInsertSchema(tables, params, timestamp, dialect = "sqlite") {
884
- const { schemaVersions } = tables;
885
- const strategy = SCHEMA_DIALECT_STRATEGIES[dialect];
886
- const schemaDocumentJson = JSON.stringify(params.schemaDoc);
887
- const isActiveValue = strategy.booleanLiteral(params.isActive);
888
- const columns = drizzleOrm.sql.raw(`"${schemaVersions.graphId.name}", "${schemaVersions.version.name}", "${schemaVersions.schemaHash.name}", "${schemaVersions.schemaDoc.name}", "${schemaVersions.createdAt.name}", "${schemaVersions.isActive.name}"`);
889
- return drizzleOrm.sql`
890
- INSERT INTO ${schemaVersions} (${columns})
891
- VALUES (
892
- ${params.graphId}, ${params.version},
893
- ${params.schemaHash}, ${schemaDocumentJson},
894
- ${timestamp}, ${isActiveValue}
895
- )
896
- RETURNING *
897
- `;
898
- }
899
- function buildGetActiveSchema(tables, graphId, dialect = "sqlite") {
900
- const { schemaVersions } = tables;
901
- const strategy = SCHEMA_DIALECT_STRATEGIES[dialect];
902
- return drizzleOrm.sql`
903
- SELECT * FROM ${schemaVersions}
904
- WHERE ${schemaVersions.graphId} = ${graphId}
905
- AND ${schemaVersions.isActive} = ${strategy.booleanLiteral(true)}
906
- `;
907
- }
908
- function buildGetSchemaVersion(tables, graphId, version) {
909
- const { schemaVersions } = tables;
910
- return drizzleOrm.sql`
911
- SELECT * FROM ${schemaVersions}
912
- WHERE ${schemaVersions.graphId} = ${graphId}
913
- AND ${schemaVersions.version} = ${version}
914
- `;
915
- }
916
- function buildSetActiveSchema(tables, graphId, version, dialect = "sqlite") {
917
- const { schemaVersions } = tables;
918
- const strategy = SCHEMA_DIALECT_STRATEGIES[dialect];
919
- const deactivateAll = drizzleOrm.sql`
920
- UPDATE ${schemaVersions}
921
- SET ${quotedColumn(schemaVersions.isActive)} = ${strategy.booleanLiteral(false)}
922
- WHERE ${schemaVersions.graphId} = ${graphId}
923
- `;
924
- const activateVersion = drizzleOrm.sql`
925
- UPDATE ${schemaVersions}
926
- SET ${quotedColumn(schemaVersions.isActive)} = ${strategy.booleanLiteral(true)}
927
- WHERE ${schemaVersions.graphId} = ${graphId}
928
- AND ${schemaVersions.version} = ${version}
929
- `;
930
- return { deactivateAll, activateVersion };
931
- }
932
- function buildInsertUniqueSqlite(tables, params) {
933
- const { uniques } = tables;
934
- const columns = drizzleOrm.sql.raw(`"${uniques.graphId.name}", "${uniques.nodeKind.name}", "${uniques.constraintName.name}", "${uniques.key.name}", "${uniques.nodeId.name}", "${uniques.concreteKind.name}", "${uniques.deletedAt.name}"`);
935
- const conflictColumns = drizzleOrm.sql.raw(`"${uniques.graphId.name}", "${uniques.nodeKind.name}", "${uniques.constraintName.name}", "${uniques.key.name}"`);
936
- return drizzleOrm.sql`
937
- INSERT INTO ${uniques} (${columns})
938
- VALUES (
939
- ${params.graphId}, ${params.nodeKind}, ${params.constraintName},
940
- ${params.key}, ${params.nodeId}, ${params.concreteKind}, ${drizzleOrm.sql.raw("NULL")}
941
- )
942
- ON CONFLICT (${conflictColumns})
943
- DO UPDATE SET
944
- ${quotedColumn(uniques.nodeId)} = CASE
945
- WHEN ${quotedColumn(uniques.nodeId)} = ${params.nodeId} THEN ${params.nodeId}
946
- WHEN ${quotedColumn(uniques.deletedAt)} IS NOT NULL THEN ${params.nodeId}
947
- ELSE ${quotedColumn(uniques.nodeId)}
948
- END,
949
- ${quotedColumn(uniques.concreteKind)} = CASE
950
- WHEN ${quotedColumn(uniques.nodeId)} = ${params.nodeId} THEN ${params.concreteKind}
951
- WHEN ${quotedColumn(uniques.deletedAt)} IS NOT NULL THEN ${params.concreteKind}
952
- ELSE ${quotedColumn(uniques.concreteKind)}
953
- END,
954
- ${quotedColumn(uniques.deletedAt)} = CASE
955
- WHEN ${quotedColumn(uniques.nodeId)} = ${params.nodeId} THEN NULL
956
- WHEN ${quotedColumn(uniques.deletedAt)} IS NOT NULL THEN NULL
957
- ELSE ${quotedColumn(uniques.deletedAt)}
958
- END
959
- RETURNING ${quotedColumn(uniques.nodeId)} as node_id
960
- `;
961
- }
962
- function buildInsertUniquePostgres(tables, params) {
963
- const { uniques } = tables;
964
- const columns = drizzleOrm.sql.raw(`"${uniques.graphId.name}", "${uniques.nodeKind.name}", "${uniques.constraintName.name}", "${uniques.key.name}", "${uniques.nodeId.name}", "${uniques.concreteKind.name}", "${uniques.deletedAt.name}"`);
965
- const conflictColumns = drizzleOrm.sql.raw(`"${uniques.graphId.name}", "${uniques.nodeKind.name}", "${uniques.constraintName.name}", "${uniques.key.name}"`);
966
- const tableName = drizzleOrm.getTableName(uniques);
967
- const existingColumn = (column) => drizzleOrm.sql.raw(`"${tableName}"."${column.name}"`);
968
- return drizzleOrm.sql`
969
- INSERT INTO ${uniques} (${columns})
970
- VALUES (
971
- ${params.graphId}, ${params.nodeKind}, ${params.constraintName},
972
- ${params.key}, ${params.nodeId}, ${params.concreteKind}, ${drizzleOrm.sql.raw("NULL")}
973
- )
974
- ON CONFLICT (${conflictColumns})
975
- DO UPDATE SET
976
- ${quotedColumn(uniques.nodeId)} = CASE
977
- WHEN ${existingColumn(uniques.nodeId)} = ${params.nodeId} THEN ${params.nodeId}
978
- WHEN ${existingColumn(uniques.deletedAt)} IS NOT NULL THEN ${params.nodeId}
979
- ELSE ${existingColumn(uniques.nodeId)}
980
- END,
981
- ${quotedColumn(uniques.concreteKind)} = CASE
982
- WHEN ${existingColumn(uniques.nodeId)} = ${params.nodeId} THEN ${params.concreteKind}
983
- WHEN ${existingColumn(uniques.deletedAt)} IS NOT NULL THEN ${params.concreteKind}
984
- ELSE ${existingColumn(uniques.concreteKind)}
985
- END,
986
- ${quotedColumn(uniques.deletedAt)} = CASE
987
- WHEN ${existingColumn(uniques.nodeId)} = ${params.nodeId} THEN NULL
988
- WHEN ${existingColumn(uniques.deletedAt)} IS NOT NULL THEN NULL
989
- ELSE ${existingColumn(uniques.deletedAt)}
990
- END
991
- RETURNING ${quotedColumn(uniques.nodeId)} as node_id
992
- `;
993
- }
994
- var UNIQUE_INSERT_BUILDERS = {
995
- postgres: buildInsertUniquePostgres,
996
- sqlite: buildInsertUniqueSqlite
997
- };
998
- function buildInsertUnique(tables, dialect, params) {
999
- const builder = UNIQUE_INSERT_BUILDERS[dialect];
1000
- return builder(tables, params);
1001
- }
1002
- function buildDeleteUnique(tables, params, timestamp) {
1003
- const { uniques } = tables;
1004
- return drizzleOrm.sql`
1005
- UPDATE ${uniques}
1006
- SET ${quotedColumn(uniques.deletedAt)} = ${timestamp}
1007
- WHERE ${uniques.graphId} = ${params.graphId}
1008
- AND ${uniques.nodeKind} = ${params.nodeKind}
1009
- AND ${uniques.constraintName} = ${params.constraintName}
1010
- AND ${uniques.key} = ${params.key}
1011
- AND ${uniques.deletedAt} IS NULL
1012
- `;
1013
- }
1014
- function buildHardDeleteUniquesByNode(tables, graphId, nodeId) {
1015
- const { uniques } = tables;
1016
- return drizzleOrm.sql`
1017
- DELETE FROM ${uniques}
1018
- WHERE ${uniques.graphId} = ${graphId}
1019
- AND ${uniques.nodeId} = ${nodeId}
1020
- `;
1021
- }
1022
- function buildHardDeleteEmbeddingsByNode(tables, graphId, nodeKind, nodeId) {
1023
- const { embeddings } = tables;
1024
- return drizzleOrm.sql`
1025
- DELETE FROM ${embeddings}
1026
- WHERE ${embeddings.graphId} = ${graphId}
1027
- AND ${embeddings.nodeKind} = ${nodeKind}
1028
- AND ${embeddings.nodeId} = ${nodeId}
1029
- `;
1030
- }
1031
- function buildCheckUnique(tables, params) {
1032
- const { uniques } = tables;
1033
- if (params.includeDeleted) {
1034
- return drizzleOrm.sql`
1035
- SELECT * FROM ${uniques}
1036
- WHERE ${uniques.graphId} = ${params.graphId}
1037
- AND ${uniques.nodeKind} = ${params.nodeKind}
1038
- AND ${uniques.constraintName} = ${params.constraintName}
1039
- AND ${uniques.key} = ${params.key}
1040
- `;
1041
- }
1042
- return drizzleOrm.sql`
1043
- SELECT * FROM ${uniques}
1044
- WHERE ${uniques.graphId} = ${params.graphId}
1045
- AND ${uniques.nodeKind} = ${params.nodeKind}
1046
- AND ${uniques.constraintName} = ${params.constraintName}
1047
- AND ${uniques.key} = ${params.key}
1048
- AND ${uniques.deletedAt} IS NULL
1049
- `;
1050
- }
1051
- function buildCheckUniqueBatch(tables, params) {
1052
- const { uniques } = tables;
1053
- const keyPlaceholders = drizzleOrm.sql.join(
1054
- params.keys.map((key) => drizzleOrm.sql`${key}`),
1055
- drizzleOrm.sql`, `
1056
- );
1057
- if (params.includeDeleted) {
1058
- return drizzleOrm.sql`
1059
- SELECT * FROM ${uniques}
1060
- WHERE ${uniques.graphId} = ${params.graphId}
1061
- AND ${uniques.nodeKind} = ${params.nodeKind}
1062
- AND ${uniques.constraintName} = ${params.constraintName}
1063
- AND ${uniques.key} IN (${keyPlaceholders})
1064
- `;
1065
- }
1066
- return drizzleOrm.sql`
1067
- SELECT * FROM ${uniques}
1068
- WHERE ${uniques.graphId} = ${params.graphId}
1069
- AND ${uniques.nodeKind} = ${params.nodeKind}
1070
- AND ${uniques.constraintName} = ${params.constraintName}
1071
- AND ${uniques.key} IN (${keyPlaceholders})
1072
- AND ${uniques.deletedAt} IS NULL
1073
- `;
1074
- }
1075
- function assertFiniteNumberArray(array, name) {
1076
- for (const [index, value] of array.entries()) {
1077
- if (typeof value !== "number" || !Number.isFinite(value)) {
1078
- throw new TypeError(
1079
- `${name}[${index}] must be a finite number, got: ${value}`
1080
- );
1081
- }
1082
- }
1083
- }
1084
- function formatEmbeddingLiteral(embedding) {
1085
- assertFiniteNumberArray(embedding, "embedding");
1086
- return `[${embedding.join(",")}]`;
1087
- }
1088
- function buildUpsertEmbeddingPostgres(tables, params, timestamp) {
1089
- const { embeddings } = tables;
1090
- const embeddingLiteral = formatEmbeddingLiteral(params.embedding);
1091
- const columns = drizzleOrm.sql.raw(
1092
- `"${embeddings.graphId.name}", "${embeddings.nodeKind.name}", "${embeddings.nodeId.name}", "${embeddings.fieldPath.name}", "${embeddings.embedding.name}", "${embeddings.dimensions.name}", "${embeddings.createdAt.name}", "${embeddings.updatedAt.name}"`
1093
- );
1094
- const conflictColumns = drizzleOrm.sql.raw(
1095
- `"${embeddings.graphId.name}", "${embeddings.nodeKind.name}", "${embeddings.nodeId.name}", "${embeddings.fieldPath.name}"`
1096
- );
1097
- const column = (target) => drizzleOrm.sql.raw(`"${target.name}"`);
1098
- return drizzleOrm.sql`
1099
- INSERT INTO ${embeddings} (${columns})
1100
- VALUES (
1101
- ${params.graphId}, ${params.nodeKind}, ${params.nodeId}, ${params.fieldPath},
1102
- ${embeddingLiteral}::vector, ${params.dimensions}, ${timestamp}, ${timestamp}
1103
- )
1104
- ON CONFLICT (${conflictColumns})
1105
- DO UPDATE SET
1106
- ${column(embeddings.embedding)} = ${embeddingLiteral}::vector,
1107
- ${column(embeddings.dimensions)} = ${params.dimensions},
1108
- ${column(embeddings.updatedAt)} = ${timestamp}
1109
- `;
1110
- }
1111
- function buildDeleteEmbedding(tables, params) {
1112
- const { embeddings } = tables;
1113
- return drizzleOrm.sql`
1114
- DELETE FROM ${embeddings}
1115
- WHERE ${embeddings.graphId} = ${params.graphId}
1116
- AND ${embeddings.nodeKind} = ${params.nodeKind}
1117
- AND ${embeddings.nodeId} = ${params.nodeId}
1118
- AND ${embeddings.fieldPath} = ${params.fieldPath}
1119
- `;
1120
- }
1121
- function buildGetEmbedding(tables, graphId, nodeKind, nodeId, fieldPath) {
1122
- const { embeddings } = tables;
1123
- return drizzleOrm.sql`
1124
- SELECT * FROM ${embeddings}
1125
- WHERE ${embeddings.graphId} = ${graphId}
1126
- AND ${embeddings.nodeKind} = ${nodeKind}
1127
- AND ${embeddings.nodeId} = ${nodeId}
1128
- AND ${embeddings.fieldPath} = ${fieldPath}
1129
- `;
1130
- }
1131
- function buildDistanceExpression(embeddingColumn, queryLiteral, metric) {
1132
- const vectorParameter = drizzleOrm.sql`${queryLiteral}::vector`;
1133
- switch (metric) {
1134
- case "cosine": {
1135
- return drizzleOrm.sql`(${embeddingColumn} <=> ${vectorParameter})`;
1136
- }
1137
- case "l2": {
1138
- return drizzleOrm.sql`(${embeddingColumn} <-> ${vectorParameter})`;
1139
- }
1140
- case "inner_product": {
1141
- return drizzleOrm.sql`(${embeddingColumn} <#> ${vectorParameter})`;
1142
- }
1143
- default: {
1144
- const _exhaustive = metric;
1145
- throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);
1146
- }
1147
- }
1148
- }
1149
- function buildVectorSearchScoreExpression(distanceExpression, metric) {
1150
- switch (metric) {
1151
- case "cosine": {
1152
- return drizzleOrm.sql`(1 - (${distanceExpression}))`;
1153
- }
1154
- case "l2":
1155
- case "inner_product": {
1156
- return distanceExpression;
1157
- }
1158
- default: {
1159
- const _exhaustive = metric;
1160
- throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);
1161
- }
1162
- }
1163
- }
1164
- function buildVectorSearchMinScoreCondition(distanceExpression, metric, minScore) {
1165
- switch (metric) {
1166
- case "cosine": {
1167
- const threshold = 1 - minScore;
1168
- return drizzleOrm.sql`${distanceExpression} <= ${threshold}`;
1169
- }
1170
- case "l2": {
1171
- return drizzleOrm.sql`${distanceExpression} <= ${minScore}`;
1172
- }
1173
- case "inner_product": {
1174
- const negativeThreshold = -minScore;
1175
- return drizzleOrm.sql`${distanceExpression} <= ${negativeThreshold}`;
1176
- }
1177
- default: {
1178
- const _exhaustive = metric;
1179
- throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);
1180
- }
1181
- }
1182
- }
1183
- function buildVectorSearchPostgres(tables, params) {
1184
- const { embeddings } = tables;
1185
- const queryLiteral = formatEmbeddingLiteral(params.queryEmbedding);
1186
- if (params.minScore !== void 0 && !Number.isFinite(params.minScore)) {
1187
- throw new TypeError(
1188
- `minScore must be a finite number, got: ${params.minScore}`
1189
- );
1190
- }
1191
- if (!Number.isInteger(params.limit) || params.limit <= 0) {
1192
- throw new Error(`limit must be a positive integer, got: ${params.limit}`);
1193
- }
1194
- const embeddingColumn = drizzleOrm.sql`${embeddings.embedding}`;
1195
- const distanceExpression = buildDistanceExpression(
1196
- embeddingColumn,
1197
- queryLiteral,
1198
- params.metric
1199
- );
1200
- const conditions = [
1201
- drizzleOrm.sql`${embeddings.graphId} = ${params.graphId}`,
1202
- drizzleOrm.sql`${embeddings.nodeKind} = ${params.nodeKind}`,
1203
- drizzleOrm.sql`${embeddings.fieldPath} = ${params.fieldPath}`
1204
- ];
1205
- if (params.minScore !== void 0) {
1206
- conditions.push(
1207
- buildVectorSearchMinScoreCondition(
1208
- distanceExpression,
1209
- params.metric,
1210
- params.minScore
1211
- )
1212
- );
1213
- }
1214
- const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
1215
- const scoreExpression = buildVectorSearchScoreExpression(
1216
- distanceExpression,
1217
- params.metric
1218
- );
1219
- return drizzleOrm.sql`
1220
- SELECT
1221
- ${embeddings.nodeId} as node_id,
1222
- ${scoreExpression} as score
1223
- FROM ${embeddings}
1224
- WHERE ${whereClause}
1225
- ORDER BY ${distanceExpression} ASC
1226
- LIMIT ${params.limit}
1227
- `;
1228
- }
1229
-
1230
- // src/backend/drizzle/operations/strategy.ts
1231
- function bindTableOperationBuilders(tables, builders) {
1232
- const boundEntries = Object.entries(builders).map(([name, builder]) => {
1233
- function boundBuilder(...args) {
1234
- return builder(tables, ...args);
1235
- }
1236
- return [name, boundBuilder];
1237
- });
1238
- return Object.fromEntries(boundEntries);
1239
- }
1240
- var COMMON_TABLE_OPERATION_BUILDERS = {
1241
- buildInsertNode,
1242
- buildInsertNodeNoReturn,
1243
- buildInsertNodesBatch,
1244
- buildInsertNodesBatchReturning,
1245
- buildGetNode,
1246
- buildGetNodes,
1247
- buildUpdateNode,
1248
- buildDeleteNode,
1249
- buildHardDeleteNode,
1250
- buildInsertEdge,
1251
- buildInsertEdgeNoReturn,
1252
- buildInsertEdgesBatch,
1253
- buildInsertEdgesBatchReturning,
1254
- buildGetEdge,
1255
- buildGetEdges,
1256
- buildUpdateEdge,
1257
- buildDeleteEdge,
1258
- buildHardDeleteEdge,
1259
- buildHardDeleteEdgesByNode,
1260
- buildCountEdgesFrom,
1261
- buildEdgeExistsBetween,
1262
- buildFindEdgesConnectedTo,
1263
- buildFindNodesByKind,
1264
- buildCountNodesByKind,
1265
- buildFindEdgesByKind,
1266
- buildCountEdgesByKind,
1267
- buildDeleteUnique,
1268
- buildHardDeleteUniquesByNode,
1269
- buildHardDeleteEmbeddingsByNode,
1270
- buildCheckUnique,
1271
- buildCheckUniqueBatch,
1272
- buildGetSchemaVersion
1273
- };
1274
- function createCommonOperationStrategy(tables, dialect) {
1275
- const tableOperations = bindTableOperationBuilders(
1276
- tables,
1277
- COMMON_TABLE_OPERATION_BUILDERS
1278
- );
1279
- return {
1280
- ...tableOperations,
1281
- buildInsertUnique(params) {
1282
- return buildInsertUnique(tables, dialect, params);
1283
- },
1284
- buildGetActiveSchema(graphId) {
1285
- return buildGetActiveSchema(tables, graphId, dialect);
1286
- },
1287
- buildInsertSchema(params, timestamp) {
1288
- return buildInsertSchema(tables, params, timestamp, dialect);
1289
- },
1290
- buildSetActiveSchema(graphId, version) {
1291
- return buildSetActiveSchema(tables, graphId, version, dialect);
1292
- },
1293
- buildClearGraph(graphId) {
1294
- return buildClearGraph(tables, graphId);
1295
- }
1296
- };
1297
- }
1298
- function createSqliteOperationStrategy(tables) {
1299
- return createCommonOperationStrategy(tables, "sqlite");
1300
- }
1301
- function createPostgresOperationStrategy(tables) {
1302
- const common = createCommonOperationStrategy(tables, "postgres");
1303
- return {
1304
- ...common,
1305
- buildUpsertEmbedding(params, timestamp) {
1306
- return buildUpsertEmbeddingPostgres(tables, params, timestamp);
1307
- },
1308
- buildDeleteEmbedding(params) {
1309
- return buildDeleteEmbedding(tables, params);
1310
- },
1311
- buildGetEmbedding(graphId, nodeKind, nodeId, fieldPath) {
1312
- return buildGetEmbedding(tables, graphId, nodeKind, nodeId, fieldPath);
1313
- },
1314
- buildVectorSearch(params) {
1315
- return buildVectorSearchPostgres(tables, params);
1316
- }
1317
- };
1318
- }
1319
- function assertPositiveInteger(value, name) {
1320
- if (!Number.isInteger(value) || value <= 0) {
1321
- throw new Error(`${name} must be a positive integer, got: ${value}`);
1322
- }
1323
- }
1324
- function assertSafeIdentifier(value, name) {
1325
- if (!/^[a-z0-9_]+$/i.test(value)) {
1326
- throw new Error(
1327
- `${name} must contain only alphanumeric characters and underscores, got: ${value}`
1328
- );
1329
- }
1330
- }
1331
- var MAX_IDENTIFIER_LENGTH = 63;
1332
- function sanitizeIdentifier(s) {
1333
- return s.toLowerCase().replaceAll(/[^a-z0-9_]/g, "_");
1334
- }
1335
- function quoteIdentifier(value) {
1336
- return `"${value.replaceAll('"', '""')}"`;
1337
- }
1338
- function shortHash(input) {
1339
- let h1 = 3735928559;
1340
- let h2 = 1103547991;
1341
- for (let index = 0; index < input.length; index++) {
1342
- const ch = input.codePointAt(index);
1343
- h1 = Math.imul(h1 ^ ch, 2654435761);
1344
- h2 = Math.imul(h2 ^ ch, 1597334677);
1345
- }
1346
- h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
1347
- h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
1348
- const hi = (h2 >>> 0).toString(16).padStart(8, "0");
1349
- const lo = (h1 >>> 0).toString(16).padStart(8, "0");
1350
- return `${hi}${lo}`.slice(0, 8);
1351
- }
1352
- function generateVectorIndexName(graphId, nodeKind, fieldPath, metric = "cosine") {
1353
- const parts = [
1354
- "idx_emb",
1355
- sanitizeIdentifier(graphId),
1356
- sanitizeIdentifier(nodeKind),
1357
- sanitizeIdentifier(fieldPath),
1358
- metric
1359
- ];
1360
- const name = parts.join("_");
1361
- if (name.length <= MAX_IDENTIFIER_LENGTH) {
1362
- return name;
1363
- }
1364
- const hash = shortHash(name);
1365
- const truncated = name.slice(0, MAX_IDENTIFIER_LENGTH - 1 - hash.length);
1366
- return `${truncated}_${hash}`;
1367
- }
1368
- function getOperatorClass(metric) {
1369
- switch (metric) {
1370
- case "cosine": {
1371
- return "vector_cosine_ops";
1372
- }
1373
- case "l2": {
1374
- return "vector_l2_ops";
1375
- }
1376
- case "inner_product": {
1377
- return "vector_ip_ops";
1378
- }
1379
- default: {
1380
- const _exhaustive = metric;
1381
- throw new Error("Unsupported vector metric: " + String(_exhaustive));
1382
- }
1383
- }
1384
- }
1385
- function escapeSqlString(value) {
1386
- const tag = `tg${crypto.randomUUID().replaceAll("-", "").slice(0, 8)}`;
1387
- return `$${tag}$${value}$${tag}$`;
1388
- }
1389
- async function createPostgresVectorIndex(db, options) {
1390
- const {
1391
- graphId,
1392
- nodeKind,
1393
- fieldPath,
1394
- dimensions,
1395
- embeddingsTableName = "typegraph_node_embeddings",
1396
- indexType = "hnsw",
1397
- metric = "cosine",
1398
- hnswM = 16,
1399
- hnswEfConstruction = 64,
1400
- ivfflatLists = 100
1401
- } = options;
1402
- assertPositiveInteger(dimensions, "dimensions");
1403
- assertPositiveInteger(hnswM, "hnswM");
1404
- assertPositiveInteger(hnswEfConstruction, "hnswEfConstruction");
1405
- assertPositiveInteger(ivfflatLists, "ivfflatLists");
1406
- const indexName = generateVectorIndexName(graphId, nodeKind, fieldPath, metric);
1407
- const operatorClass = getOperatorClass(metric);
1408
- const quotedEmbeddingsTableName = quoteIdentifier(embeddingsTableName);
1409
- assertSafeIdentifier(indexName, "indexName");
1410
- const safeGraphId = escapeSqlString(graphId);
1411
- const safeNodeKind = escapeSqlString(nodeKind);
1412
- const safeFieldPath = escapeSqlString(fieldPath);
1413
- let indexSql;
1414
- if (indexType === "hnsw") {
1415
- indexSql = drizzleOrm.sql.raw(`
1416
- CREATE INDEX IF NOT EXISTS ${indexName}
1417
- ON ${quotedEmbeddingsTableName}
1418
- USING hnsw ((embedding::vector(${dimensions})) ${operatorClass})
1419
- WITH (m = ${hnswM}, ef_construction = ${hnswEfConstruction})
1420
- WHERE graph_id = ${safeGraphId}
1421
- AND node_kind = ${safeNodeKind}
1422
- AND field_path = ${safeFieldPath}
1423
- `);
1424
- } else if (indexType === "ivfflat") {
1425
- indexSql = drizzleOrm.sql.raw(`
1426
- CREATE INDEX IF NOT EXISTS ${indexName}
1427
- ON ${quotedEmbeddingsTableName}
1428
- USING ivfflat ((embedding::vector(${dimensions})) ${operatorClass})
1429
- WITH (lists = ${ivfflatLists})
1430
- WHERE graph_id = ${safeGraphId}
1431
- AND node_kind = ${safeNodeKind}
1432
- AND field_path = ${safeFieldPath}
1433
- `);
1434
- } else {
1435
- return {
1436
- indexName,
1437
- success: true,
1438
- message: `Index type "${indexType}" not supported, skipping index creation`
1439
- };
1440
- }
1441
- try {
1442
- await db.execute(indexSql);
1443
- return {
1444
- indexName,
1445
- success: true,
1446
- message: `Created ${indexType.toUpperCase()} index "${indexName}" for ${nodeKind}.${fieldPath}`
1447
- };
1448
- } catch (error) {
1449
- return {
1450
- indexName,
1451
- success: false,
1452
- message: `Failed to create index: ${error instanceof Error ? error.message : String(error)}`
1453
- };
1454
- }
1455
- }
1456
- async function dropPostgresVectorIndex(db, indexName) {
1457
- assertSafeIdentifier(indexName, "indexName");
1458
- try {
1459
- const dropSql = drizzleOrm.sql.raw(`DROP INDEX IF EXISTS ${indexName}`);
1460
- await db.execute(dropSql);
1461
- return {
1462
- indexName,
1463
- success: true,
1464
- message: `Dropped index "${indexName}"`
1465
- };
1466
- } catch (error) {
1467
- return {
1468
- indexName,
1469
- success: false,
1470
- message: `Failed to drop index: ${error instanceof Error ? error.message : String(error)}`
1471
- };
1472
- }
1473
- }
1474
- function createSqliteVectorIndex(_options) {
1475
- const indexName = generateVectorIndexName(
1476
- _options.graphId,
1477
- _options.nodeKind,
1478
- _options.fieldPath,
1479
- _options.metric
1480
- );
1481
- return {
1482
- indexName,
1483
- success: true,
1484
- message: "SQLite/sqlite-vec uses optimized internal indexing, no explicit index needed"
1485
- };
1486
- }
1487
- function dropSqliteVectorIndex(graphId, nodeKind, fieldPath, metric = "cosine") {
1488
- const indexName = generateVectorIndexName(graphId, nodeKind, fieldPath, metric);
1489
- return {
1490
- indexName,
1491
- success: true,
1492
- message: "SQLite/sqlite-vec does not use explicit indexes"
1493
- };
1494
- }
1495
-
1496
- // src/backend/drizzle/execution/types.ts
1497
- function compileQueryWithDialect(db, query, backendName) {
1498
- const databaseWithCompiler = db;
1499
- const compiler = databaseWithCompiler.dialect;
1500
- if (compiler === void 0) {
1501
- throw new Error(`${backendName} backend is missing a SQL compiler`);
1502
- }
1503
- return compiler.sqlToQuery(query);
1504
- }
1505
-
1506
- exports.D1_CAPABILITIES = D1_CAPABILITIES;
1507
- exports.POSTGRES_CAPABILITIES = POSTGRES_CAPABILITIES;
1508
- exports.POSTGRES_ROW_MAPPER_CONFIG = POSTGRES_ROW_MAPPER_CONFIG;
1509
- exports.SQLITE_CAPABILITIES = SQLITE_CAPABILITIES;
1510
- exports.SQLITE_ROW_MAPPER_CONFIG = SQLITE_ROW_MAPPER_CONFIG;
1511
- exports.compileQueryWithDialect = compileQueryWithDialect;
1512
- exports.createCommonOperationBackend = createCommonOperationBackend;
1513
- exports.createEdgeRowMapper = createEdgeRowMapper;
1514
- exports.createNodeRowMapper = createNodeRowMapper;
1515
- exports.createPostgresOperationStrategy = createPostgresOperationStrategy;
1516
- exports.createPostgresVectorIndex = createPostgresVectorIndex;
1517
- exports.createSchemaVersionRowMapper = createSchemaVersionRowMapper;
1518
- exports.createSqliteOperationStrategy = createSqliteOperationStrategy;
1519
- exports.createSqliteVectorIndex = createSqliteVectorIndex;
1520
- exports.createUniqueRowMapper = createUniqueRowMapper;
1521
- exports.dropPostgresVectorIndex = dropPostgresVectorIndex;
1522
- exports.dropSqliteVectorIndex = dropSqliteVectorIndex;
1523
- exports.formatPostgresTimestamp = formatPostgresTimestamp;
1524
- exports.generateVectorIndexName = generateVectorIndexName;
1525
- exports.nowIso = nowIso;
1526
- //# sourceMappingURL=chunk-PW5BSBZV.cjs.map
1527
- //# sourceMappingURL=chunk-PW5BSBZV.cjs.map