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