@nicia-ai/typegraph 0.4.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 (114) 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-ZO2FRJ2U.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-NYDXJGA3.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.cts → index-QTnQwakS.d.cts} +1 -1
  33. package/dist/{index-DyrR_d-H.d.ts → index-QTnQwakS.d.ts} +1 -1
  34. package/dist/index.cjs +238 -1
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +11 -12
  37. package/dist/index.d.ts +11 -12
  38. package/dist/index.js +238 -1
  39. package/dist/index.js.map +1 -1
  40. package/dist/indexes/index.d.cts +5 -6
  41. package/dist/indexes/index.d.ts +5 -6
  42. package/dist/interchange/index.d.cts +5 -6
  43. package/dist/interchange/index.d.ts +5 -6
  44. package/dist/{manager-0NysX4s6.d.cts → manager-BImRiYwz.d.cts} +3 -3
  45. package/dist/{manager-DFKe7ql3.d.ts → manager-DGQ9UF18.d.ts} +3 -3
  46. package/dist/profiler/index.d.cts +7 -8
  47. package/dist/profiler/index.d.ts +7 -8
  48. package/dist/schema/index.d.cts +6 -7
  49. package/dist/schema/index.d.ts +6 -7
  50. package/dist/{backend/drizzle/schema/sqlite.d.ts → sqlite-CSJ-fgIm.d.ts} +2 -25
  51. package/dist/{backend/drizzle/schema/sqlite.d.cts → sqlite-FWGZLwDd.d.cts} +2 -25
  52. package/dist/{store-SiovWEYA.d.ts → store-CscQUG-S.d.ts} +57 -6
  53. package/dist/{store-DhoA5uRc.d.cts → store-DNv1yd3n.d.cts} +57 -6
  54. package/dist/{types-DHRsi6j9.d.cts → types-BbMn2Ycv.d.cts} +2 -2
  55. package/dist/{types-ZT5mlism.d.ts → types-C2rhqkg7.d.ts} +2 -2
  56. package/dist/{types-6EKrWTs9.d.ts → types-D5ggX07j.d.ts} +7 -3
  57. package/dist/{types-BL1GyVku.d.cts → types-DEMAqkA1.d.cts} +1 -1
  58. package/dist/{types-DCGa53O2.d.ts → types-DJZoHy5R.d.ts} +1 -1
  59. package/dist/{types-DTJEu_-h.d.ts → types-DolHw9pJ.d.cts} +14 -1
  60. package/dist/{types-DTJEu_-h.d.cts → types-DolHw9pJ.d.ts} +14 -1
  61. package/dist/{types-BUy-pHKH.d.cts → types-SVDEKnU6.d.cts} +7 -3
  62. package/package.json +6 -46
  63. package/dist/backend/drizzle/index.cjs +0 -40
  64. package/dist/backend/drizzle/index.cjs.map +0 -1
  65. package/dist/backend/drizzle/index.d.cts +0 -13
  66. package/dist/backend/drizzle/index.d.ts +0 -13
  67. package/dist/backend/drizzle/index.js +0 -11
  68. package/dist/backend/drizzle/index.js.map +0 -1
  69. package/dist/backend/drizzle/postgres.cjs +0 -26
  70. package/dist/backend/drizzle/postgres.cjs.map +0 -1
  71. package/dist/backend/drizzle/postgres.d.cts +0 -35
  72. package/dist/backend/drizzle/postgres.d.ts +0 -35
  73. package/dist/backend/drizzle/postgres.js +0 -9
  74. package/dist/backend/drizzle/postgres.js.map +0 -1
  75. package/dist/backend/drizzle/schema/postgres.cjs +0 -39
  76. package/dist/backend/drizzle/schema/postgres.cjs.map +0 -1
  77. package/dist/backend/drizzle/schema/postgres.js +0 -6
  78. package/dist/backend/drizzle/schema/postgres.js.map +0 -1
  79. package/dist/backend/drizzle/schema/sqlite.cjs +0 -39
  80. package/dist/backend/drizzle/schema/sqlite.cjs.map +0 -1
  81. package/dist/backend/drizzle/schema/sqlite.js +0 -6
  82. package/dist/backend/drizzle/schema/sqlite.js.map +0 -1
  83. package/dist/backend/drizzle/sqlite.cjs +0 -26
  84. package/dist/backend/drizzle/sqlite.cjs.map +0 -1
  85. package/dist/backend/drizzle/sqlite.d.cts +0 -35
  86. package/dist/backend/drizzle/sqlite.d.ts +0 -35
  87. package/dist/backend/drizzle/sqlite.js +0 -9
  88. package/dist/backend/drizzle/sqlite.js.map +0 -1
  89. package/dist/chunk-3PURVEA4.js +0 -193
  90. package/dist/chunk-3PURVEA4.js.map +0 -1
  91. package/dist/chunk-7RVSDXT3.cjs +0 -1509
  92. package/dist/chunk-7RVSDXT3.cjs.map +0 -1
  93. package/dist/chunk-LUARLSYT.cjs +0 -289
  94. package/dist/chunk-LUARLSYT.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-NYDXJGA3.cjs.map +0 -1
  98. package/dist/chunk-OGGLFYFA.js +0 -177
  99. package/dist/chunk-OGGLFYFA.js.map +0 -1
  100. package/dist/chunk-Q6PXIKRQ.js +0 -287
  101. package/dist/chunk-Q6PXIKRQ.js.map +0 -1
  102. package/dist/chunk-SMLIWLS7.js +0 -236
  103. package/dist/chunk-SMLIWLS7.js.map +0 -1
  104. package/dist/chunk-UYMT4LO2.cjs +0 -241
  105. package/dist/chunk-UYMT4LO2.cjs.map +0 -1
  106. package/dist/chunk-XZL6MCZJ.cjs +0 -185
  107. package/dist/chunk-XZL6MCZJ.cjs.map +0 -1
  108. package/dist/chunk-ZO2FRJ2U.js.map +0 -1
  109. package/dist/chunk-ZQGOBVXZ.js +0 -1488
  110. package/dist/chunk-ZQGOBVXZ.js.map +0 -1
  111. package/dist/test-helpers-CIq1Hhj1.d.ts +0 -26
  112. package/dist/test-helpers-DPRFVky4.d.cts +0 -26
  113. package/dist/types-BRzHlhKC.d.cts +0 -14
  114. package/dist/types-BRzHlhKC.d.ts +0 -14
@@ -1,1509 +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
- };
390
- }
391
- function buildTemporalConditions(table, params) {
392
- const conditions = [];
393
- const mode = params.temporalMode;
394
- if (mode === "includeTombstones") return conditions;
395
- if (params.excludeDeleted !== false) {
396
- conditions.push(drizzleOrm.sql`${table.deletedAt} IS NULL`);
397
- }
398
- if (mode === "current" || mode === "asOf") {
399
- const asOf = params.asOf;
400
- conditions.push(
401
- drizzleOrm.sql`(${table.validFrom} IS NULL OR ${table.validFrom} <= ${asOf})`,
402
- drizzleOrm.sql`(${table.validTo} IS NULL OR ${table.validTo} > ${asOf})`
403
- );
404
- }
405
- return conditions;
406
- }
407
- function buildFindNodesByKind(tables, params) {
408
- const { nodes } = tables;
409
- const conditions = [
410
- drizzleOrm.sql`${nodes.graphId} = ${params.graphId}`,
411
- drizzleOrm.sql`${nodes.kind} = ${params.kind}`,
412
- ...buildTemporalConditions(nodes, params)
413
- ];
414
- const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
415
- if (params.limit !== void 0 && params.offset !== void 0) {
416
- return drizzleOrm.sql`
417
- SELECT * FROM ${nodes}
418
- WHERE ${whereClause}
419
- ORDER BY ${nodes.createdAt} DESC
420
- LIMIT ${params.limit} OFFSET ${params.offset}
421
- `;
422
- }
423
- if (params.limit !== void 0) {
424
- return drizzleOrm.sql`
425
- SELECT * FROM ${nodes}
426
- WHERE ${whereClause}
427
- ORDER BY ${nodes.createdAt} DESC
428
- LIMIT ${params.limit}
429
- `;
430
- }
431
- return drizzleOrm.sql`
432
- SELECT * FROM ${nodes}
433
- WHERE ${whereClause}
434
- ORDER BY ${nodes.createdAt} DESC
435
- `;
436
- }
437
- function buildCountNodesByKind(tables, params) {
438
- const { nodes } = tables;
439
- const conditions = [
440
- drizzleOrm.sql`${nodes.graphId} = ${params.graphId}`,
441
- drizzleOrm.sql`${nodes.kind} = ${params.kind}`,
442
- ...buildTemporalConditions(nodes, params)
443
- ];
444
- const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
445
- return drizzleOrm.sql`
446
- SELECT COUNT(*) as count FROM ${nodes}
447
- WHERE ${whereClause}
448
- `;
449
- }
450
- function buildFindEdgesByKind(tables, params) {
451
- const { edges } = tables;
452
- const conditions = [
453
- drizzleOrm.sql`${edges.graphId} = ${params.graphId}`,
454
- drizzleOrm.sql`${edges.kind} = ${params.kind}`,
455
- ...buildTemporalConditions(edges, params)
456
- ];
457
- if (params.fromKind !== void 0) {
458
- conditions.push(drizzleOrm.sql`${edges.fromKind} = ${params.fromKind}`);
459
- }
460
- if (params.fromId !== void 0) {
461
- conditions.push(drizzleOrm.sql`${edges.fromId} = ${params.fromId}`);
462
- }
463
- if (params.toKind !== void 0) {
464
- conditions.push(drizzleOrm.sql`${edges.toKind} = ${params.toKind}`);
465
- }
466
- if (params.toId !== void 0) {
467
- conditions.push(drizzleOrm.sql`${edges.toId} = ${params.toId}`);
468
- }
469
- const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
470
- if (params.limit !== void 0 && params.offset !== void 0) {
471
- return drizzleOrm.sql`
472
- SELECT * FROM ${edges}
473
- WHERE ${whereClause}
474
- ORDER BY ${edges.createdAt} DESC
475
- LIMIT ${params.limit} OFFSET ${params.offset}
476
- `;
477
- }
478
- if (params.limit !== void 0) {
479
- return drizzleOrm.sql`
480
- SELECT * FROM ${edges}
481
- WHERE ${whereClause}
482
- ORDER BY ${edges.createdAt} DESC
483
- LIMIT ${params.limit}
484
- `;
485
- }
486
- return drizzleOrm.sql`
487
- SELECT * FROM ${edges}
488
- WHERE ${whereClause}
489
- ORDER BY ${edges.createdAt} DESC
490
- `;
491
- }
492
- function buildCountEdgesByKind(tables, params) {
493
- const { edges } = tables;
494
- const conditions = [
495
- drizzleOrm.sql`${edges.graphId} = ${params.graphId}`,
496
- drizzleOrm.sql`${edges.kind} = ${params.kind}`,
497
- ...buildTemporalConditions(edges, params)
498
- ];
499
- if (params.fromKind !== void 0) {
500
- conditions.push(drizzleOrm.sql`${edges.fromKind} = ${params.fromKind}`);
501
- }
502
- if (params.fromId !== void 0) {
503
- conditions.push(drizzleOrm.sql`${edges.fromId} = ${params.fromId}`);
504
- }
505
- if (params.toKind !== void 0) {
506
- conditions.push(drizzleOrm.sql`${edges.toKind} = ${params.toKind}`);
507
- }
508
- if (params.toId !== void 0) {
509
- conditions.push(drizzleOrm.sql`${edges.toId} = ${params.toId}`);
510
- }
511
- const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
512
- return drizzleOrm.sql`
513
- SELECT COUNT(*) as count FROM ${edges}
514
- WHERE ${whereClause}
515
- `;
516
- }
517
- function sqlNull(value) {
518
- return value ?? drizzleOrm.sql.raw("NULL");
519
- }
520
- function quotedColumn(column) {
521
- return drizzleOrm.sql.raw(`"${column.name.replaceAll('"', '""')}"`);
522
- }
523
- function nodeColumnList(nodes) {
524
- 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}"`);
525
- }
526
- function edgeColumnList(edges) {
527
- 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}"`);
528
- }
529
-
530
- // src/backend/drizzle/operations/edges.ts
531
- function buildInsertEdge(tables, params, timestamp) {
532
- const { edges } = tables;
533
- const propsJson = JSON.stringify(params.props);
534
- const columns = edgeColumnList(edges);
535
- return drizzleOrm.sql`
536
- INSERT INTO ${edges} (${columns})
537
- VALUES (
538
- ${params.graphId}, ${params.id}, ${params.kind},
539
- ${params.fromKind}, ${params.fromId}, ${params.toKind}, ${params.toId},
540
- ${propsJson}, ${sqlNull(params.validFrom)}, ${sqlNull(params.validTo)},
541
- ${timestamp}, ${timestamp}
542
- )
543
- RETURNING *
544
- `;
545
- }
546
- function buildInsertEdgeNoReturn(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
- `;
559
- }
560
- function buildInsertEdgesBatch(tables, params, timestamp) {
561
- const { edges } = tables;
562
- const columns = edgeColumnList(edges);
563
- const values = params.map((edgeParams) => {
564
- const propsJson = JSON.stringify(edgeParams.props);
565
- 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})`;
566
- });
567
- return drizzleOrm.sql`
568
- INSERT INTO ${edges} (${columns})
569
- VALUES ${drizzleOrm.sql.join(values, drizzleOrm.sql`, `)}
570
- `;
571
- }
572
- function buildInsertEdgesBatchReturning(tables, params, timestamp) {
573
- const { edges } = tables;
574
- const columns = edgeColumnList(edges);
575
- const values = params.map((edgeParams) => {
576
- const propsJson = JSON.stringify(edgeParams.props);
577
- 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})`;
578
- });
579
- return drizzleOrm.sql`
580
- INSERT INTO ${edges} (${columns})
581
- VALUES ${drizzleOrm.sql.join(values, drizzleOrm.sql`, `)}
582
- RETURNING *
583
- `;
584
- }
585
- function buildGetEdge(tables, graphId, id) {
586
- const { edges } = tables;
587
- return drizzleOrm.sql`
588
- SELECT * FROM ${edges}
589
- WHERE ${edges.graphId} = ${graphId}
590
- AND ${edges.id} = ${id}
591
- `;
592
- }
593
- function buildGetEdges(tables, graphId, ids) {
594
- const { edges } = tables;
595
- const idPlaceholders = drizzleOrm.sql.join(
596
- ids.map((edgeId) => drizzleOrm.sql`${edgeId}`),
597
- drizzleOrm.sql`, `
598
- );
599
- return drizzleOrm.sql`
600
- SELECT * FROM ${edges}
601
- WHERE ${edges.graphId} = ${graphId}
602
- AND ${edges.id} IN (${idPlaceholders})
603
- `;
604
- }
605
- function buildUpdateEdge(tables, params, timestamp) {
606
- const { edges } = tables;
607
- const propsJson = JSON.stringify(params.props);
608
- const setParts = [
609
- drizzleOrm.sql`${quotedColumn(edges.props)} = ${propsJson}`,
610
- drizzleOrm.sql`${quotedColumn(edges.updatedAt)} = ${timestamp}`
611
- ];
612
- if (params.validTo !== void 0) {
613
- setParts.push(drizzleOrm.sql`${quotedColumn(edges.validTo)} = ${params.validTo}`);
614
- }
615
- if (params.clearDeleted) {
616
- setParts.push(drizzleOrm.sql`${quotedColumn(edges.deletedAt)} = NULL`);
617
- }
618
- const setClause = drizzleOrm.sql.join(setParts, drizzleOrm.sql`, `);
619
- if (params.clearDeleted) {
620
- return drizzleOrm.sql`
621
- UPDATE ${edges}
622
- SET ${setClause}
623
- WHERE ${edges.graphId} = ${params.graphId}
624
- AND ${edges.id} = ${params.id}
625
- RETURNING *
626
- `;
627
- }
628
- return drizzleOrm.sql`
629
- UPDATE ${edges}
630
- SET ${setClause}
631
- WHERE ${edges.graphId} = ${params.graphId}
632
- AND ${edges.id} = ${params.id}
633
- AND ${edges.deletedAt} IS NULL
634
- RETURNING *
635
- `;
636
- }
637
- function buildDeleteEdge(tables, params, timestamp) {
638
- const { edges } = tables;
639
- return drizzleOrm.sql`
640
- UPDATE ${edges}
641
- SET ${quotedColumn(edges.deletedAt)} = ${timestamp}
642
- WHERE ${edges.graphId} = ${params.graphId}
643
- AND ${edges.id} = ${params.id}
644
- AND ${edges.deletedAt} IS NULL
645
- `;
646
- }
647
- function buildHardDeleteEdge(tables, params) {
648
- const { edges } = tables;
649
- return drizzleOrm.sql`
650
- DELETE FROM ${edges}
651
- WHERE ${edges.graphId} = ${params.graphId}
652
- AND ${edges.id} = ${params.id}
653
- `;
654
- }
655
- function buildHardDeleteEdgesByNode(tables, graphId, nodeKind, nodeId) {
656
- const { edges } = tables;
657
- return drizzleOrm.sql`
658
- DELETE FROM ${edges}
659
- WHERE ${edges.graphId} = ${graphId}
660
- AND (
661
- (${edges.fromKind} = ${nodeKind} AND ${edges.fromId} = ${nodeId})
662
- OR (${edges.toKind} = ${nodeKind} AND ${edges.toId} = ${nodeId})
663
- )
664
- `;
665
- }
666
- function buildCountEdgesFrom(tables, params) {
667
- const { edges } = tables;
668
- if (params.activeOnly) {
669
- return drizzleOrm.sql`
670
- SELECT COUNT(*) as count FROM ${edges}
671
- WHERE ${edges.graphId} = ${params.graphId}
672
- AND ${edges.kind} = ${params.edgeKind}
673
- AND ${edges.fromKind} = ${params.fromKind}
674
- AND ${edges.fromId} = ${params.fromId}
675
- AND ${edges.deletedAt} IS NULL
676
- AND ${edges.validTo} IS NULL
677
- `;
678
- }
679
- return drizzleOrm.sql`
680
- SELECT COUNT(*) as count FROM ${edges}
681
- WHERE ${edges.graphId} = ${params.graphId}
682
- AND ${edges.kind} = ${params.edgeKind}
683
- AND ${edges.fromKind} = ${params.fromKind}
684
- AND ${edges.fromId} = ${params.fromId}
685
- AND ${edges.deletedAt} IS NULL
686
- `;
687
- }
688
- function buildEdgeExistsBetween(tables, params) {
689
- const { edges } = tables;
690
- return drizzleOrm.sql`
691
- SELECT 1 FROM ${edges}
692
- WHERE ${edges.graphId} = ${params.graphId}
693
- AND ${edges.kind} = ${params.edgeKind}
694
- AND ${edges.fromKind} = ${params.fromKind}
695
- AND ${edges.fromId} = ${params.fromId}
696
- AND ${edges.toKind} = ${params.toKind}
697
- AND ${edges.toId} = ${params.toId}
698
- AND ${edges.deletedAt} IS NULL
699
- LIMIT 1
700
- `;
701
- }
702
- function buildFindEdgesConnectedTo(tables, params) {
703
- const { edges } = tables;
704
- return drizzleOrm.sql`
705
- SELECT * FROM ${edges}
706
- WHERE ${edges.graphId} = ${params.graphId}
707
- AND ${edges.deletedAt} IS NULL
708
- AND ${edges.fromKind} = ${params.nodeKind}
709
- AND ${edges.fromId} = ${params.nodeId}
710
- UNION ALL
711
- SELECT * FROM ${edges}
712
- WHERE ${edges.graphId} = ${params.graphId}
713
- AND ${edges.deletedAt} IS NULL
714
- AND ${edges.toKind} = ${params.nodeKind}
715
- AND ${edges.toId} = ${params.nodeId}
716
- AND NOT (
717
- ${edges.fromKind} = ${params.nodeKind}
718
- AND ${edges.fromId} = ${params.nodeId}
719
- )
720
- `;
721
- }
722
- function buildInsertNode(tables, params, timestamp) {
723
- const { nodes } = tables;
724
- const propsJson = JSON.stringify(params.props);
725
- const columns = nodeColumnList(nodes);
726
- return drizzleOrm.sql`
727
- INSERT INTO ${nodes} (${columns})
728
- VALUES (
729
- ${params.graphId}, ${params.kind}, ${params.id}, ${propsJson},
730
- 1, ${sqlNull(params.validFrom)}, ${sqlNull(params.validTo)},
731
- ${timestamp}, ${timestamp}
732
- )
733
- RETURNING *
734
- `;
735
- }
736
- function buildInsertNodeNoReturn(tables, params, timestamp) {
737
- const { nodes } = tables;
738
- const propsJson = JSON.stringify(params.props);
739
- const columns = nodeColumnList(nodes);
740
- return drizzleOrm.sql`
741
- INSERT INTO ${nodes} (${columns})
742
- VALUES (
743
- ${params.graphId}, ${params.kind}, ${params.id}, ${propsJson},
744
- 1, ${sqlNull(params.validFrom)}, ${sqlNull(params.validTo)},
745
- ${timestamp}, ${timestamp}
746
- )
747
- `;
748
- }
749
- function buildInsertNodesBatch(tables, params, timestamp) {
750
- const { nodes } = tables;
751
- const columns = nodeColumnList(nodes);
752
- const values = params.map((nodeParams) => {
753
- const propsJson = JSON.stringify(nodeParams.props);
754
- return drizzleOrm.sql`(${nodeParams.graphId}, ${nodeParams.kind}, ${nodeParams.id}, ${propsJson}, 1, ${sqlNull(nodeParams.validFrom)}, ${sqlNull(nodeParams.validTo)}, ${timestamp}, ${timestamp})`;
755
- });
756
- return drizzleOrm.sql`
757
- INSERT INTO ${nodes} (${columns})
758
- VALUES ${drizzleOrm.sql.join(values, drizzleOrm.sql`, `)}
759
- `;
760
- }
761
- function buildInsertNodesBatchReturning(tables, params, timestamp) {
762
- const { nodes } = tables;
763
- const columns = nodeColumnList(nodes);
764
- const values = params.map((nodeParams) => {
765
- const propsJson = JSON.stringify(nodeParams.props);
766
- return drizzleOrm.sql`(${nodeParams.graphId}, ${nodeParams.kind}, ${nodeParams.id}, ${propsJson}, 1, ${sqlNull(nodeParams.validFrom)}, ${sqlNull(nodeParams.validTo)}, ${timestamp}, ${timestamp})`;
767
- });
768
- return drizzleOrm.sql`
769
- INSERT INTO ${nodes} (${columns})
770
- VALUES ${drizzleOrm.sql.join(values, drizzleOrm.sql`, `)}
771
- RETURNING *
772
- `;
773
- }
774
- function buildGetNode(tables, graphId, kind, id) {
775
- const { nodes } = tables;
776
- return drizzleOrm.sql`
777
- SELECT * FROM ${nodes}
778
- WHERE ${nodes.graphId} = ${graphId}
779
- AND ${nodes.kind} = ${kind}
780
- AND ${nodes.id} = ${id}
781
- `;
782
- }
783
- function buildGetNodes(tables, graphId, kind, ids) {
784
- const { nodes } = tables;
785
- const idPlaceholders = drizzleOrm.sql.join(
786
- ids.map((nodeId) => drizzleOrm.sql`${nodeId}`),
787
- drizzleOrm.sql`, `
788
- );
789
- return drizzleOrm.sql`
790
- SELECT * FROM ${nodes}
791
- WHERE ${nodes.graphId} = ${graphId}
792
- AND ${nodes.kind} = ${kind}
793
- AND ${nodes.id} IN (${idPlaceholders})
794
- `;
795
- }
796
- function buildUpdateNode(tables, params, timestamp) {
797
- const { nodes } = tables;
798
- const propsJson = JSON.stringify(params.props);
799
- const setParts = [
800
- drizzleOrm.sql`${quotedColumn(nodes.props)} = ${propsJson}`,
801
- drizzleOrm.sql`${quotedColumn(nodes.updatedAt)} = ${timestamp}`
802
- ];
803
- if (params.incrementVersion) {
804
- setParts.push(
805
- drizzleOrm.sql`${quotedColumn(nodes.version)} = ${quotedColumn(nodes.version)} + 1`
806
- );
807
- }
808
- if (params.validTo !== void 0) {
809
- setParts.push(drizzleOrm.sql`${quotedColumn(nodes.validTo)} = ${params.validTo}`);
810
- }
811
- if (params.clearDeleted) {
812
- setParts.push(drizzleOrm.sql`${quotedColumn(nodes.deletedAt)} = NULL`);
813
- }
814
- const setClause = drizzleOrm.sql.join(setParts, drizzleOrm.sql`, `);
815
- if (params.clearDeleted) {
816
- return drizzleOrm.sql`
817
- UPDATE ${nodes}
818
- SET ${setClause}
819
- WHERE ${nodes.graphId} = ${params.graphId}
820
- AND ${nodes.kind} = ${params.kind}
821
- AND ${nodes.id} = ${params.id}
822
- RETURNING *
823
- `;
824
- }
825
- return drizzleOrm.sql`
826
- UPDATE ${nodes}
827
- SET ${setClause}
828
- WHERE ${nodes.graphId} = ${params.graphId}
829
- AND ${nodes.kind} = ${params.kind}
830
- AND ${nodes.id} = ${params.id}
831
- AND ${nodes.deletedAt} IS NULL
832
- RETURNING *
833
- `;
834
- }
835
- function buildDeleteNode(tables, params, timestamp) {
836
- const { nodes } = tables;
837
- return drizzleOrm.sql`
838
- UPDATE ${nodes}
839
- SET ${quotedColumn(nodes.deletedAt)} = ${timestamp}
840
- WHERE ${nodes.graphId} = ${params.graphId}
841
- AND ${nodes.kind} = ${params.kind}
842
- AND ${nodes.id} = ${params.id}
843
- AND ${nodes.deletedAt} IS NULL
844
- `;
845
- }
846
- function buildHardDeleteNode(tables, params) {
847
- const { nodes } = tables;
848
- return drizzleOrm.sql`
849
- DELETE FROM ${nodes}
850
- WHERE ${nodes.graphId} = ${params.graphId}
851
- AND ${nodes.kind} = ${params.kind}
852
- AND ${nodes.id} = ${params.id}
853
- `;
854
- }
855
- function createSchemaDialectStrategy(dialect) {
856
- const trueLiteral = dialect === "sqlite" ? drizzleOrm.sql.raw("1") : drizzleOrm.sql.raw("TRUE");
857
- const falseLiteral = dialect === "sqlite" ? drizzleOrm.sql.raw("0") : drizzleOrm.sql.raw("FALSE");
858
- return {
859
- booleanLiteral(value) {
860
- return value ? trueLiteral : falseLiteral;
861
- }
862
- };
863
- }
864
- var SCHEMA_DIALECT_STRATEGIES = {
865
- postgres: createSchemaDialectStrategy("postgres"),
866
- sqlite: createSchemaDialectStrategy("sqlite")
867
- };
868
- function buildInsertSchema(tables, params, timestamp, dialect = "sqlite") {
869
- const { schemaVersions } = tables;
870
- const strategy = SCHEMA_DIALECT_STRATEGIES[dialect];
871
- const schemaDocumentJson = JSON.stringify(params.schemaDoc);
872
- const isActiveValue = strategy.booleanLiteral(params.isActive);
873
- const columns = drizzleOrm.sql.raw(`"${schemaVersions.graphId.name}", "${schemaVersions.version.name}", "${schemaVersions.schemaHash.name}", "${schemaVersions.schemaDoc.name}", "${schemaVersions.createdAt.name}", "${schemaVersions.isActive.name}"`);
874
- return drizzleOrm.sql`
875
- INSERT INTO ${schemaVersions} (${columns})
876
- VALUES (
877
- ${params.graphId}, ${params.version},
878
- ${params.schemaHash}, ${schemaDocumentJson},
879
- ${timestamp}, ${isActiveValue}
880
- )
881
- RETURNING *
882
- `;
883
- }
884
- function buildGetActiveSchema(tables, graphId, dialect = "sqlite") {
885
- const { schemaVersions } = tables;
886
- const strategy = SCHEMA_DIALECT_STRATEGIES[dialect];
887
- return drizzleOrm.sql`
888
- SELECT * FROM ${schemaVersions}
889
- WHERE ${schemaVersions.graphId} = ${graphId}
890
- AND ${schemaVersions.isActive} = ${strategy.booleanLiteral(true)}
891
- `;
892
- }
893
- function buildGetSchemaVersion(tables, graphId, version) {
894
- const { schemaVersions } = tables;
895
- return drizzleOrm.sql`
896
- SELECT * FROM ${schemaVersions}
897
- WHERE ${schemaVersions.graphId} = ${graphId}
898
- AND ${schemaVersions.version} = ${version}
899
- `;
900
- }
901
- function buildSetActiveSchema(tables, graphId, version, dialect = "sqlite") {
902
- const { schemaVersions } = tables;
903
- const strategy = SCHEMA_DIALECT_STRATEGIES[dialect];
904
- const deactivateAll = drizzleOrm.sql`
905
- UPDATE ${schemaVersions}
906
- SET ${quotedColumn(schemaVersions.isActive)} = ${strategy.booleanLiteral(false)}
907
- WHERE ${schemaVersions.graphId} = ${graphId}
908
- `;
909
- const activateVersion = drizzleOrm.sql`
910
- UPDATE ${schemaVersions}
911
- SET ${quotedColumn(schemaVersions.isActive)} = ${strategy.booleanLiteral(true)}
912
- WHERE ${schemaVersions.graphId} = ${graphId}
913
- AND ${schemaVersions.version} = ${version}
914
- `;
915
- return { deactivateAll, activateVersion };
916
- }
917
- function buildInsertUniqueSqlite(tables, params) {
918
- const { uniques } = tables;
919
- 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}"`);
920
- const conflictColumns = drizzleOrm.sql.raw(`"${uniques.graphId.name}", "${uniques.nodeKind.name}", "${uniques.constraintName.name}", "${uniques.key.name}"`);
921
- return drizzleOrm.sql`
922
- INSERT INTO ${uniques} (${columns})
923
- VALUES (
924
- ${params.graphId}, ${params.nodeKind}, ${params.constraintName},
925
- ${params.key}, ${params.nodeId}, ${params.concreteKind}, ${drizzleOrm.sql.raw("NULL")}
926
- )
927
- ON CONFLICT (${conflictColumns})
928
- DO UPDATE SET
929
- ${quotedColumn(uniques.nodeId)} = CASE
930
- WHEN ${quotedColumn(uniques.nodeId)} = ${params.nodeId} THEN ${params.nodeId}
931
- WHEN ${quotedColumn(uniques.deletedAt)} IS NOT NULL THEN ${params.nodeId}
932
- ELSE ${quotedColumn(uniques.nodeId)}
933
- END,
934
- ${quotedColumn(uniques.concreteKind)} = CASE
935
- WHEN ${quotedColumn(uniques.nodeId)} = ${params.nodeId} THEN ${params.concreteKind}
936
- WHEN ${quotedColumn(uniques.deletedAt)} IS NOT NULL THEN ${params.concreteKind}
937
- ELSE ${quotedColumn(uniques.concreteKind)}
938
- END,
939
- ${quotedColumn(uniques.deletedAt)} = CASE
940
- WHEN ${quotedColumn(uniques.nodeId)} = ${params.nodeId} THEN NULL
941
- WHEN ${quotedColumn(uniques.deletedAt)} IS NOT NULL THEN NULL
942
- ELSE ${quotedColumn(uniques.deletedAt)}
943
- END
944
- RETURNING ${quotedColumn(uniques.nodeId)} as node_id
945
- `;
946
- }
947
- function buildInsertUniquePostgres(tables, params) {
948
- const { uniques } = tables;
949
- 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}"`);
950
- const conflictColumns = drizzleOrm.sql.raw(`"${uniques.graphId.name}", "${uniques.nodeKind.name}", "${uniques.constraintName.name}", "${uniques.key.name}"`);
951
- const tableName = drizzleOrm.getTableName(uniques);
952
- const existingColumn = (column) => drizzleOrm.sql.raw(`"${tableName}"."${column.name}"`);
953
- return drizzleOrm.sql`
954
- INSERT INTO ${uniques} (${columns})
955
- VALUES (
956
- ${params.graphId}, ${params.nodeKind}, ${params.constraintName},
957
- ${params.key}, ${params.nodeId}, ${params.concreteKind}, ${drizzleOrm.sql.raw("NULL")}
958
- )
959
- ON CONFLICT (${conflictColumns})
960
- DO UPDATE SET
961
- ${quotedColumn(uniques.nodeId)} = CASE
962
- WHEN ${existingColumn(uniques.nodeId)} = ${params.nodeId} THEN ${params.nodeId}
963
- WHEN ${existingColumn(uniques.deletedAt)} IS NOT NULL THEN ${params.nodeId}
964
- ELSE ${existingColumn(uniques.nodeId)}
965
- END,
966
- ${quotedColumn(uniques.concreteKind)} = CASE
967
- WHEN ${existingColumn(uniques.nodeId)} = ${params.nodeId} THEN ${params.concreteKind}
968
- WHEN ${existingColumn(uniques.deletedAt)} IS NOT NULL THEN ${params.concreteKind}
969
- ELSE ${existingColumn(uniques.concreteKind)}
970
- END,
971
- ${quotedColumn(uniques.deletedAt)} = CASE
972
- WHEN ${existingColumn(uniques.nodeId)} = ${params.nodeId} THEN NULL
973
- WHEN ${existingColumn(uniques.deletedAt)} IS NOT NULL THEN NULL
974
- ELSE ${existingColumn(uniques.deletedAt)}
975
- END
976
- RETURNING ${quotedColumn(uniques.nodeId)} as node_id
977
- `;
978
- }
979
- var UNIQUE_INSERT_BUILDERS = {
980
- postgres: buildInsertUniquePostgres,
981
- sqlite: buildInsertUniqueSqlite
982
- };
983
- function buildInsertUnique(tables, dialect, params) {
984
- const builder = UNIQUE_INSERT_BUILDERS[dialect];
985
- return builder(tables, params);
986
- }
987
- function buildDeleteUnique(tables, params, timestamp) {
988
- const { uniques } = tables;
989
- return drizzleOrm.sql`
990
- UPDATE ${uniques}
991
- SET ${quotedColumn(uniques.deletedAt)} = ${timestamp}
992
- WHERE ${uniques.graphId} = ${params.graphId}
993
- AND ${uniques.nodeKind} = ${params.nodeKind}
994
- AND ${uniques.constraintName} = ${params.constraintName}
995
- AND ${uniques.key} = ${params.key}
996
- AND ${uniques.deletedAt} IS NULL
997
- `;
998
- }
999
- function buildHardDeleteUniquesByNode(tables, graphId, nodeId) {
1000
- const { uniques } = tables;
1001
- return drizzleOrm.sql`
1002
- DELETE FROM ${uniques}
1003
- WHERE ${uniques.graphId} = ${graphId}
1004
- AND ${uniques.nodeId} = ${nodeId}
1005
- `;
1006
- }
1007
- function buildHardDeleteEmbeddingsByNode(tables, graphId, nodeKind, nodeId) {
1008
- const { embeddings } = tables;
1009
- return drizzleOrm.sql`
1010
- DELETE FROM ${embeddings}
1011
- WHERE ${embeddings.graphId} = ${graphId}
1012
- AND ${embeddings.nodeKind} = ${nodeKind}
1013
- AND ${embeddings.nodeId} = ${nodeId}
1014
- `;
1015
- }
1016
- function buildCheckUnique(tables, params) {
1017
- const { uniques } = tables;
1018
- if (params.includeDeleted) {
1019
- return drizzleOrm.sql`
1020
- SELECT * FROM ${uniques}
1021
- WHERE ${uniques.graphId} = ${params.graphId}
1022
- AND ${uniques.nodeKind} = ${params.nodeKind}
1023
- AND ${uniques.constraintName} = ${params.constraintName}
1024
- AND ${uniques.key} = ${params.key}
1025
- `;
1026
- }
1027
- return drizzleOrm.sql`
1028
- SELECT * FROM ${uniques}
1029
- WHERE ${uniques.graphId} = ${params.graphId}
1030
- AND ${uniques.nodeKind} = ${params.nodeKind}
1031
- AND ${uniques.constraintName} = ${params.constraintName}
1032
- AND ${uniques.key} = ${params.key}
1033
- AND ${uniques.deletedAt} IS NULL
1034
- `;
1035
- }
1036
- function buildCheckUniqueBatch(tables, params) {
1037
- const { uniques } = tables;
1038
- const keyPlaceholders = drizzleOrm.sql.join(
1039
- params.keys.map((key) => drizzleOrm.sql`${key}`),
1040
- drizzleOrm.sql`, `
1041
- );
1042
- if (params.includeDeleted) {
1043
- return drizzleOrm.sql`
1044
- SELECT * FROM ${uniques}
1045
- WHERE ${uniques.graphId} = ${params.graphId}
1046
- AND ${uniques.nodeKind} = ${params.nodeKind}
1047
- AND ${uniques.constraintName} = ${params.constraintName}
1048
- AND ${uniques.key} IN (${keyPlaceholders})
1049
- `;
1050
- }
1051
- return drizzleOrm.sql`
1052
- SELECT * FROM ${uniques}
1053
- WHERE ${uniques.graphId} = ${params.graphId}
1054
- AND ${uniques.nodeKind} = ${params.nodeKind}
1055
- AND ${uniques.constraintName} = ${params.constraintName}
1056
- AND ${uniques.key} IN (${keyPlaceholders})
1057
- AND ${uniques.deletedAt} IS NULL
1058
- `;
1059
- }
1060
- function assertFiniteNumberArray(array, name) {
1061
- for (const [index, value] of array.entries()) {
1062
- if (typeof value !== "number" || !Number.isFinite(value)) {
1063
- throw new TypeError(
1064
- `${name}[${index}] must be a finite number, got: ${value}`
1065
- );
1066
- }
1067
- }
1068
- }
1069
- function formatEmbeddingLiteral(embedding) {
1070
- assertFiniteNumberArray(embedding, "embedding");
1071
- return `[${embedding.join(",")}]`;
1072
- }
1073
- function buildUpsertEmbeddingPostgres(tables, params, timestamp) {
1074
- const { embeddings } = tables;
1075
- const embeddingLiteral = formatEmbeddingLiteral(params.embedding);
1076
- const columns = drizzleOrm.sql.raw(
1077
- `"${embeddings.graphId.name}", "${embeddings.nodeKind.name}", "${embeddings.nodeId.name}", "${embeddings.fieldPath.name}", "${embeddings.embedding.name}", "${embeddings.dimensions.name}", "${embeddings.createdAt.name}", "${embeddings.updatedAt.name}"`
1078
- );
1079
- const conflictColumns = drizzleOrm.sql.raw(
1080
- `"${embeddings.graphId.name}", "${embeddings.nodeKind.name}", "${embeddings.nodeId.name}", "${embeddings.fieldPath.name}"`
1081
- );
1082
- const column = (target) => drizzleOrm.sql.raw(`"${target.name}"`);
1083
- return drizzleOrm.sql`
1084
- INSERT INTO ${embeddings} (${columns})
1085
- VALUES (
1086
- ${params.graphId}, ${params.nodeKind}, ${params.nodeId}, ${params.fieldPath},
1087
- ${embeddingLiteral}::vector, ${params.dimensions}, ${timestamp}, ${timestamp}
1088
- )
1089
- ON CONFLICT (${conflictColumns})
1090
- DO UPDATE SET
1091
- ${column(embeddings.embedding)} = ${embeddingLiteral}::vector,
1092
- ${column(embeddings.dimensions)} = ${params.dimensions},
1093
- ${column(embeddings.updatedAt)} = ${timestamp}
1094
- `;
1095
- }
1096
- function buildDeleteEmbedding(tables, params) {
1097
- const { embeddings } = tables;
1098
- return drizzleOrm.sql`
1099
- DELETE FROM ${embeddings}
1100
- WHERE ${embeddings.graphId} = ${params.graphId}
1101
- AND ${embeddings.nodeKind} = ${params.nodeKind}
1102
- AND ${embeddings.nodeId} = ${params.nodeId}
1103
- AND ${embeddings.fieldPath} = ${params.fieldPath}
1104
- `;
1105
- }
1106
- function buildGetEmbedding(tables, graphId, nodeKind, nodeId, fieldPath) {
1107
- const { embeddings } = tables;
1108
- return drizzleOrm.sql`
1109
- SELECT * FROM ${embeddings}
1110
- WHERE ${embeddings.graphId} = ${graphId}
1111
- AND ${embeddings.nodeKind} = ${nodeKind}
1112
- AND ${embeddings.nodeId} = ${nodeId}
1113
- AND ${embeddings.fieldPath} = ${fieldPath}
1114
- `;
1115
- }
1116
- function buildDistanceExpression(embeddingColumn, queryLiteral, metric) {
1117
- const vectorParameter = drizzleOrm.sql`${queryLiteral}::vector`;
1118
- switch (metric) {
1119
- case "cosine": {
1120
- return drizzleOrm.sql`(${embeddingColumn} <=> ${vectorParameter})`;
1121
- }
1122
- case "l2": {
1123
- return drizzleOrm.sql`(${embeddingColumn} <-> ${vectorParameter})`;
1124
- }
1125
- case "inner_product": {
1126
- return drizzleOrm.sql`(${embeddingColumn} <#> ${vectorParameter})`;
1127
- }
1128
- default: {
1129
- const _exhaustive = metric;
1130
- throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);
1131
- }
1132
- }
1133
- }
1134
- function buildVectorSearchScoreExpression(distanceExpression, metric) {
1135
- switch (metric) {
1136
- case "cosine": {
1137
- return drizzleOrm.sql`(1 - (${distanceExpression}))`;
1138
- }
1139
- case "l2":
1140
- case "inner_product": {
1141
- return distanceExpression;
1142
- }
1143
- default: {
1144
- const _exhaustive = metric;
1145
- throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);
1146
- }
1147
- }
1148
- }
1149
- function buildVectorSearchMinScoreCondition(distanceExpression, metric, minScore) {
1150
- switch (metric) {
1151
- case "cosine": {
1152
- const threshold = 1 - minScore;
1153
- return drizzleOrm.sql`${distanceExpression} <= ${threshold}`;
1154
- }
1155
- case "l2": {
1156
- return drizzleOrm.sql`${distanceExpression} <= ${minScore}`;
1157
- }
1158
- case "inner_product": {
1159
- const negativeThreshold = -minScore;
1160
- return drizzleOrm.sql`${distanceExpression} <= ${negativeThreshold}`;
1161
- }
1162
- default: {
1163
- const _exhaustive = metric;
1164
- throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);
1165
- }
1166
- }
1167
- }
1168
- function buildVectorSearchPostgres(tables, params) {
1169
- const { embeddings } = tables;
1170
- const queryLiteral = formatEmbeddingLiteral(params.queryEmbedding);
1171
- if (params.minScore !== void 0 && !Number.isFinite(params.minScore)) {
1172
- throw new TypeError(
1173
- `minScore must be a finite number, got: ${params.minScore}`
1174
- );
1175
- }
1176
- if (!Number.isInteger(params.limit) || params.limit <= 0) {
1177
- throw new Error(`limit must be a positive integer, got: ${params.limit}`);
1178
- }
1179
- const embeddingColumn = drizzleOrm.sql`${embeddings.embedding}`;
1180
- const distanceExpression = buildDistanceExpression(
1181
- embeddingColumn,
1182
- queryLiteral,
1183
- params.metric
1184
- );
1185
- const conditions = [
1186
- drizzleOrm.sql`${embeddings.graphId} = ${params.graphId}`,
1187
- drizzleOrm.sql`${embeddings.nodeKind} = ${params.nodeKind}`,
1188
- drizzleOrm.sql`${embeddings.fieldPath} = ${params.fieldPath}`
1189
- ];
1190
- if (params.minScore !== void 0) {
1191
- conditions.push(
1192
- buildVectorSearchMinScoreCondition(
1193
- distanceExpression,
1194
- params.metric,
1195
- params.minScore
1196
- )
1197
- );
1198
- }
1199
- const whereClause = drizzleOrm.sql.join(conditions, drizzleOrm.sql` AND `);
1200
- const scoreExpression = buildVectorSearchScoreExpression(
1201
- distanceExpression,
1202
- params.metric
1203
- );
1204
- return drizzleOrm.sql`
1205
- SELECT
1206
- ${embeddings.nodeId} as node_id,
1207
- ${scoreExpression} as score
1208
- FROM ${embeddings}
1209
- WHERE ${whereClause}
1210
- ORDER BY ${distanceExpression} ASC
1211
- LIMIT ${params.limit}
1212
- `;
1213
- }
1214
-
1215
- // src/backend/drizzle/operations/strategy.ts
1216
- function bindTableOperationBuilders(tables, builders) {
1217
- const boundEntries = Object.entries(builders).map(([name, builder]) => {
1218
- function boundBuilder(...args) {
1219
- return builder(tables, ...args);
1220
- }
1221
- return [name, boundBuilder];
1222
- });
1223
- return Object.fromEntries(boundEntries);
1224
- }
1225
- var COMMON_TABLE_OPERATION_BUILDERS = {
1226
- buildInsertNode,
1227
- buildInsertNodeNoReturn,
1228
- buildInsertNodesBatch,
1229
- buildInsertNodesBatchReturning,
1230
- buildGetNode,
1231
- buildGetNodes,
1232
- buildUpdateNode,
1233
- buildDeleteNode,
1234
- buildHardDeleteNode,
1235
- buildInsertEdge,
1236
- buildInsertEdgeNoReturn,
1237
- buildInsertEdgesBatch,
1238
- buildInsertEdgesBatchReturning,
1239
- buildGetEdge,
1240
- buildGetEdges,
1241
- buildUpdateEdge,
1242
- buildDeleteEdge,
1243
- buildHardDeleteEdge,
1244
- buildHardDeleteEdgesByNode,
1245
- buildCountEdgesFrom,
1246
- buildEdgeExistsBetween,
1247
- buildFindEdgesConnectedTo,
1248
- buildFindNodesByKind,
1249
- buildCountNodesByKind,
1250
- buildFindEdgesByKind,
1251
- buildCountEdgesByKind,
1252
- buildDeleteUnique,
1253
- buildHardDeleteUniquesByNode,
1254
- buildHardDeleteEmbeddingsByNode,
1255
- buildCheckUnique,
1256
- buildCheckUniqueBatch,
1257
- buildGetSchemaVersion
1258
- };
1259
- function createCommonOperationStrategy(tables, dialect) {
1260
- const tableOperations = bindTableOperationBuilders(
1261
- tables,
1262
- COMMON_TABLE_OPERATION_BUILDERS
1263
- );
1264
- return {
1265
- ...tableOperations,
1266
- buildInsertUnique(params) {
1267
- return buildInsertUnique(tables, dialect, params);
1268
- },
1269
- buildGetActiveSchema(graphId) {
1270
- return buildGetActiveSchema(tables, graphId, dialect);
1271
- },
1272
- buildInsertSchema(params, timestamp) {
1273
- return buildInsertSchema(tables, params, timestamp, dialect);
1274
- },
1275
- buildSetActiveSchema(graphId, version) {
1276
- return buildSetActiveSchema(tables, graphId, version, dialect);
1277
- }
1278
- };
1279
- }
1280
- function createSqliteOperationStrategy(tables) {
1281
- return createCommonOperationStrategy(tables, "sqlite");
1282
- }
1283
- function createPostgresOperationStrategy(tables) {
1284
- const common = createCommonOperationStrategy(tables, "postgres");
1285
- return {
1286
- ...common,
1287
- buildUpsertEmbedding(params, timestamp) {
1288
- return buildUpsertEmbeddingPostgres(tables, params, timestamp);
1289
- },
1290
- buildDeleteEmbedding(params) {
1291
- return buildDeleteEmbedding(tables, params);
1292
- },
1293
- buildGetEmbedding(graphId, nodeKind, nodeId, fieldPath) {
1294
- return buildGetEmbedding(tables, graphId, nodeKind, nodeId, fieldPath);
1295
- },
1296
- buildVectorSearch(params) {
1297
- return buildVectorSearchPostgres(tables, params);
1298
- }
1299
- };
1300
- }
1301
- function assertPositiveInteger(value, name) {
1302
- if (!Number.isInteger(value) || value <= 0) {
1303
- throw new Error(`${name} must be a positive integer, got: ${value}`);
1304
- }
1305
- }
1306
- function assertSafeIdentifier(value, name) {
1307
- if (!/^[a-z0-9_]+$/i.test(value)) {
1308
- throw new Error(
1309
- `${name} must contain only alphanumeric characters and underscores, got: ${value}`
1310
- );
1311
- }
1312
- }
1313
- var MAX_IDENTIFIER_LENGTH = 63;
1314
- function sanitizeIdentifier(s) {
1315
- return s.toLowerCase().replaceAll(/[^a-z0-9_]/g, "_");
1316
- }
1317
- function quoteIdentifier(value) {
1318
- return `"${value.replaceAll('"', '""')}"`;
1319
- }
1320
- function shortHash(input) {
1321
- let h1 = 3735928559;
1322
- let h2 = 1103547991;
1323
- for (let index = 0; index < input.length; index++) {
1324
- const ch = input.codePointAt(index);
1325
- h1 = Math.imul(h1 ^ ch, 2654435761);
1326
- h2 = Math.imul(h2 ^ ch, 1597334677);
1327
- }
1328
- h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
1329
- h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
1330
- const hi = (h2 >>> 0).toString(16).padStart(8, "0");
1331
- const lo = (h1 >>> 0).toString(16).padStart(8, "0");
1332
- return `${hi}${lo}`.slice(0, 8);
1333
- }
1334
- function generateVectorIndexName(graphId, nodeKind, fieldPath, metric = "cosine") {
1335
- const parts = [
1336
- "idx_emb",
1337
- sanitizeIdentifier(graphId),
1338
- sanitizeIdentifier(nodeKind),
1339
- sanitizeIdentifier(fieldPath),
1340
- metric
1341
- ];
1342
- const name = parts.join("_");
1343
- if (name.length <= MAX_IDENTIFIER_LENGTH) {
1344
- return name;
1345
- }
1346
- const hash = shortHash(name);
1347
- const truncated = name.slice(0, MAX_IDENTIFIER_LENGTH - 1 - hash.length);
1348
- return `${truncated}_${hash}`;
1349
- }
1350
- function getOperatorClass(metric) {
1351
- switch (metric) {
1352
- case "cosine": {
1353
- return "vector_cosine_ops";
1354
- }
1355
- case "l2": {
1356
- return "vector_l2_ops";
1357
- }
1358
- case "inner_product": {
1359
- return "vector_ip_ops";
1360
- }
1361
- default: {
1362
- const _exhaustive = metric;
1363
- throw new Error("Unsupported vector metric: " + String(_exhaustive));
1364
- }
1365
- }
1366
- }
1367
- function escapeSqlString(value) {
1368
- const tag = `tg${crypto.randomUUID().replaceAll("-", "").slice(0, 8)}`;
1369
- return `$${tag}$${value}$${tag}$`;
1370
- }
1371
- async function createPostgresVectorIndex(db, options) {
1372
- const {
1373
- graphId,
1374
- nodeKind,
1375
- fieldPath,
1376
- dimensions,
1377
- embeddingsTableName = "typegraph_node_embeddings",
1378
- indexType = "hnsw",
1379
- metric = "cosine",
1380
- hnswM = 16,
1381
- hnswEfConstruction = 64,
1382
- ivfflatLists = 100
1383
- } = options;
1384
- assertPositiveInteger(dimensions, "dimensions");
1385
- assertPositiveInteger(hnswM, "hnswM");
1386
- assertPositiveInteger(hnswEfConstruction, "hnswEfConstruction");
1387
- assertPositiveInteger(ivfflatLists, "ivfflatLists");
1388
- const indexName = generateVectorIndexName(graphId, nodeKind, fieldPath, metric);
1389
- const operatorClass = getOperatorClass(metric);
1390
- const quotedEmbeddingsTableName = quoteIdentifier(embeddingsTableName);
1391
- assertSafeIdentifier(indexName, "indexName");
1392
- const safeGraphId = escapeSqlString(graphId);
1393
- const safeNodeKind = escapeSqlString(nodeKind);
1394
- const safeFieldPath = escapeSqlString(fieldPath);
1395
- let indexSql;
1396
- if (indexType === "hnsw") {
1397
- indexSql = drizzleOrm.sql.raw(`
1398
- CREATE INDEX IF NOT EXISTS ${indexName}
1399
- ON ${quotedEmbeddingsTableName}
1400
- USING hnsw ((embedding::vector(${dimensions})) ${operatorClass})
1401
- WITH (m = ${hnswM}, ef_construction = ${hnswEfConstruction})
1402
- WHERE graph_id = ${safeGraphId}
1403
- AND node_kind = ${safeNodeKind}
1404
- AND field_path = ${safeFieldPath}
1405
- `);
1406
- } else if (indexType === "ivfflat") {
1407
- indexSql = drizzleOrm.sql.raw(`
1408
- CREATE INDEX IF NOT EXISTS ${indexName}
1409
- ON ${quotedEmbeddingsTableName}
1410
- USING ivfflat ((embedding::vector(${dimensions})) ${operatorClass})
1411
- WITH (lists = ${ivfflatLists})
1412
- WHERE graph_id = ${safeGraphId}
1413
- AND node_kind = ${safeNodeKind}
1414
- AND field_path = ${safeFieldPath}
1415
- `);
1416
- } else {
1417
- return {
1418
- indexName,
1419
- success: true,
1420
- message: `Index type "${indexType}" not supported, skipping index creation`
1421
- };
1422
- }
1423
- try {
1424
- await db.execute(indexSql);
1425
- return {
1426
- indexName,
1427
- success: true,
1428
- message: `Created ${indexType.toUpperCase()} index "${indexName}" for ${nodeKind}.${fieldPath}`
1429
- };
1430
- } catch (error) {
1431
- return {
1432
- indexName,
1433
- success: false,
1434
- message: `Failed to create index: ${error instanceof Error ? error.message : String(error)}`
1435
- };
1436
- }
1437
- }
1438
- async function dropPostgresVectorIndex(db, indexName) {
1439
- assertSafeIdentifier(indexName, "indexName");
1440
- try {
1441
- const dropSql = drizzleOrm.sql.raw(`DROP INDEX IF EXISTS ${indexName}`);
1442
- await db.execute(dropSql);
1443
- return {
1444
- indexName,
1445
- success: true,
1446
- message: `Dropped index "${indexName}"`
1447
- };
1448
- } catch (error) {
1449
- return {
1450
- indexName,
1451
- success: false,
1452
- message: `Failed to drop index: ${error instanceof Error ? error.message : String(error)}`
1453
- };
1454
- }
1455
- }
1456
- function createSqliteVectorIndex(_options) {
1457
- const indexName = generateVectorIndexName(
1458
- _options.graphId,
1459
- _options.nodeKind,
1460
- _options.fieldPath,
1461
- _options.metric
1462
- );
1463
- return {
1464
- indexName,
1465
- success: true,
1466
- message: "SQLite/sqlite-vec uses optimized internal indexing, no explicit index needed"
1467
- };
1468
- }
1469
- function dropSqliteVectorIndex(graphId, nodeKind, fieldPath, metric = "cosine") {
1470
- const indexName = generateVectorIndexName(graphId, nodeKind, fieldPath, metric);
1471
- return {
1472
- indexName,
1473
- success: true,
1474
- message: "SQLite/sqlite-vec does not use explicit indexes"
1475
- };
1476
- }
1477
-
1478
- // src/backend/drizzle/execution/types.ts
1479
- function compileQueryWithDialect(db, query, backendName) {
1480
- const databaseWithCompiler = db;
1481
- const compiler = databaseWithCompiler.dialect;
1482
- if (compiler === void 0) {
1483
- throw new Error(`${backendName} backend is missing a SQL compiler`);
1484
- }
1485
- return compiler.sqlToQuery(query);
1486
- }
1487
-
1488
- exports.D1_CAPABILITIES = D1_CAPABILITIES;
1489
- exports.POSTGRES_CAPABILITIES = POSTGRES_CAPABILITIES;
1490
- exports.POSTGRES_ROW_MAPPER_CONFIG = POSTGRES_ROW_MAPPER_CONFIG;
1491
- exports.SQLITE_CAPABILITIES = SQLITE_CAPABILITIES;
1492
- exports.SQLITE_ROW_MAPPER_CONFIG = SQLITE_ROW_MAPPER_CONFIG;
1493
- exports.compileQueryWithDialect = compileQueryWithDialect;
1494
- exports.createCommonOperationBackend = createCommonOperationBackend;
1495
- exports.createEdgeRowMapper = createEdgeRowMapper;
1496
- exports.createNodeRowMapper = createNodeRowMapper;
1497
- exports.createPostgresOperationStrategy = createPostgresOperationStrategy;
1498
- exports.createPostgresVectorIndex = createPostgresVectorIndex;
1499
- exports.createSchemaVersionRowMapper = createSchemaVersionRowMapper;
1500
- exports.createSqliteOperationStrategy = createSqliteOperationStrategy;
1501
- exports.createSqliteVectorIndex = createSqliteVectorIndex;
1502
- exports.createUniqueRowMapper = createUniqueRowMapper;
1503
- exports.dropPostgresVectorIndex = dropPostgresVectorIndex;
1504
- exports.dropSqliteVectorIndex = dropSqliteVectorIndex;
1505
- exports.formatPostgresTimestamp = formatPostgresTimestamp;
1506
- exports.generateVectorIndexName = generateVectorIndexName;
1507
- exports.nowIso = nowIso;
1508
- //# sourceMappingURL=chunk-7RVSDXT3.cjs.map
1509
- //# sourceMappingURL=chunk-7RVSDXT3.cjs.map