@nicia-ai/typegraph 0.7.0 → 0.9.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.
- package/dist/backend/postgres/index.cjs +26 -26
- package/dist/backend/postgres/index.js +2 -2
- package/dist/backend/sqlite/index.cjs +12 -12
- package/dist/backend/sqlite/index.d.cts +15 -3
- package/dist/backend/sqlite/index.d.ts +15 -3
- package/dist/backend/sqlite/index.js +2 -2
- package/dist/backend/sqlite/local.cjs +5 -6
- package/dist/backend/sqlite/local.cjs.map +1 -1
- package/dist/backend/sqlite/local.js +2 -3
- package/dist/backend/sqlite/local.js.map +1 -1
- package/dist/{chunk-PDQBCQ34.cjs → chunk-7VITUTRA.cjs} +6 -6
- package/dist/{chunk-PDQBCQ34.cjs.map → chunk-7VITUTRA.cjs.map} +1 -1
- package/dist/{chunk-K5O7TOJO.cjs → chunk-FXZOTO6F.cjs} +56 -48
- package/dist/chunk-FXZOTO6F.cjs.map +1 -0
- package/dist/{chunk-JUZWF5NX.js → chunk-IRFD3MEU.js} +12 -12
- package/dist/chunk-IRFD3MEU.js.map +1 -0
- package/dist/{chunk-2DKSQNPW.js → chunk-KP2HKVXU.js} +45 -37
- package/dist/chunk-KP2HKVXU.js.map +1 -0
- package/dist/{chunk-23NGZHUN.cjs → chunk-MGEVSTDX.cjs} +2 -13
- package/dist/chunk-MGEVSTDX.cjs.map +1 -0
- package/dist/{chunk-BELXZTVK.cjs → chunk-NI2GV74U.cjs} +12 -12
- package/dist/chunk-NI2GV74U.cjs.map +1 -0
- package/dist/{chunk-SH237DWD.js → chunk-PYV4ADC6.js} +3 -3
- package/dist/{chunk-SH237DWD.js.map → chunk-PYV4ADC6.js.map} +1 -1
- package/dist/{chunk-JPO7W262.js → chunk-X3OXNIMH.js} +3 -13
- package/dist/chunk-X3OXNIMH.js.map +1 -0
- package/dist/index.cjs +61 -61
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +4 -4
- package/dist/interchange/index.cjs +6 -6
- package/dist/interchange/index.d.cts +2 -2
- package/dist/interchange/index.d.ts +2 -2
- package/dist/interchange/index.js +1 -1
- package/dist/{manager-Ba2CXGMG.d.ts → manager-BCLhWysp.d.ts} +8 -6
- package/dist/{manager-Cu3JQN0H.d.cts → manager-DGSnJa1v.d.cts} +8 -6
- package/dist/profiler/index.d.cts +2 -2
- package/dist/profiler/index.d.ts +2 -2
- package/dist/schema/index.cjs +21 -21
- package/dist/schema/index.d.cts +2 -2
- package/dist/schema/index.d.ts +2 -2
- package/dist/schema/index.js +3 -3
- package/dist/{store-CL-QMus7.d.cts → store-DgzIgrmn.d.cts} +1 -1
- package/dist/{store-DJpuUOSL.d.ts → store-wqOO3GSy.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-23NGZHUN.cjs.map +0 -1
- package/dist/chunk-2DKSQNPW.js.map +0 -1
- package/dist/chunk-BELXZTVK.cjs.map +0 -1
- package/dist/chunk-JPO7W262.js.map +0 -1
- package/dist/chunk-JUZWF5NX.js.map +0 -1
- package/dist/chunk-K5O7TOJO.cjs.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkMGEVSTDX_cjs = require('./chunk-MGEVSTDX.cjs');
|
|
4
4
|
var chunk44SXEVF4_cjs = require('./chunk-44SXEVF4.cjs');
|
|
5
5
|
var drizzleOrm = require('drizzle-orm');
|
|
6
6
|
|
|
@@ -16,6 +16,10 @@ function getSessionName(db) {
|
|
|
16
16
|
function isD1DatabaseBySessionName(db) {
|
|
17
17
|
return getSessionName(db) === "SQLiteD1Session";
|
|
18
18
|
}
|
|
19
|
+
function isDurableObjectBySessionName(db) {
|
|
20
|
+
const sessionName = getSessionName(db);
|
|
21
|
+
return sessionName === "SQLiteDurableObjectSession";
|
|
22
|
+
}
|
|
19
23
|
function isSyncDatabaseBySessionName(db) {
|
|
20
24
|
const sessionName = getSessionName(db);
|
|
21
25
|
return sessionName === "BetterSQLiteSession" || sessionName === "BunSQLiteSession";
|
|
@@ -38,11 +42,15 @@ function detectSyncProfile(db, profileHints) {
|
|
|
38
42
|
return isSyncDatabaseBySessionName(db);
|
|
39
43
|
}
|
|
40
44
|
}
|
|
41
|
-
function
|
|
42
|
-
if (profileHints.
|
|
43
|
-
return profileHints.
|
|
45
|
+
function detectTransactionMode(db, profileHints, isSync) {
|
|
46
|
+
if (profileHints.transactionMode !== void 0) {
|
|
47
|
+
return profileHints.transactionMode;
|
|
44
48
|
}
|
|
45
|
-
|
|
49
|
+
if (isD1DatabaseBySessionName(db) || isDurableObjectBySessionName(db)) {
|
|
50
|
+
return "none";
|
|
51
|
+
}
|
|
52
|
+
if (isSync) return "sql";
|
|
53
|
+
return "drizzle";
|
|
46
54
|
}
|
|
47
55
|
function resolveSqliteClient(db) {
|
|
48
56
|
const databaseWithClient = db;
|
|
@@ -91,30 +99,27 @@ function createSqliteExecutionAdapter(db, statementCacheMaxOrOptions = {}) {
|
|
|
91
99
|
const options = typeof statementCacheMaxOrOptions === "number" ? { statementCacheMax: statementCacheMaxOrOptions } : statementCacheMaxOrOptions;
|
|
92
100
|
const statementCacheMax = options.statementCacheMax ?? DEFAULT_PREPARED_STATEMENT_CACHE_MAX;
|
|
93
101
|
const profileHints = options.profileHints ?? {};
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
sqliteClient: resolveSqliteClient(db)
|
|
98
|
-
};
|
|
99
|
-
const supportsCompiledExecution = profileBase.isSync && !profileBase.isD1 && profileBase.sqliteClient !== void 0;
|
|
102
|
+
const isSync = detectSyncProfile(db, profileHints);
|
|
103
|
+
const sqliteClient = isSync ? resolveSqliteClient(db) : void 0;
|
|
104
|
+
const transactionMode = detectTransactionMode(db, profileHints, isSync);
|
|
100
105
|
const profile = {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
106
|
+
isSync,
|
|
107
|
+
supportsCompiledExecution: sqliteClient !== void 0,
|
|
108
|
+
transactionMode
|
|
104
109
|
};
|
|
105
|
-
const compile = (query) =>
|
|
106
|
-
if (
|
|
110
|
+
const compile = (query) => chunkMGEVSTDX_cjs.compileQueryWithDialect(db, query, "SQLite");
|
|
111
|
+
if (sqliteClient !== void 0) {
|
|
107
112
|
let executeCompiled2 = function(compiledQuery) {
|
|
108
113
|
const preparedStatement = getOrCreatePreparedStatement(
|
|
109
114
|
statementCache,
|
|
110
|
-
|
|
115
|
+
client,
|
|
111
116
|
compiledQuery.sql,
|
|
112
117
|
statementCacheMax
|
|
113
118
|
);
|
|
114
119
|
const rows = preparedStatement.all(...compiledQuery.params);
|
|
115
120
|
return Promise.resolve(rows);
|
|
116
121
|
};
|
|
117
|
-
const
|
|
122
|
+
const client = sqliteClient;
|
|
118
123
|
const statementCache = /* @__PURE__ */ new Map();
|
|
119
124
|
return {
|
|
120
125
|
clearStatementCache() {
|
|
@@ -128,7 +133,7 @@ function createSqliteExecutionAdapter(db, statementCacheMaxOrOptions = {}) {
|
|
|
128
133
|
executeCompiled: executeCompiled2,
|
|
129
134
|
prepare(sqlText) {
|
|
130
135
|
return createPreparedStatementExecutor(
|
|
131
|
-
|
|
136
|
+
client,
|
|
132
137
|
statementCache,
|
|
133
138
|
sqlText,
|
|
134
139
|
statementCacheMax
|
|
@@ -168,10 +173,10 @@ var SQLITE_GET_EDGES_ID_CHUNK_SIZE = Math.max(
|
|
|
168
173
|
1,
|
|
169
174
|
SQLITE_MAX_BIND_PARAMETERS - 1
|
|
170
175
|
);
|
|
171
|
-
var toNodeRow =
|
|
172
|
-
var toEdgeRow =
|
|
173
|
-
var toUniqueRow =
|
|
174
|
-
var toSchemaVersionRow =
|
|
176
|
+
var toNodeRow = chunkMGEVSTDX_cjs.createNodeRowMapper(chunkMGEVSTDX_cjs.SQLITE_ROW_MAPPER_CONFIG);
|
|
177
|
+
var toEdgeRow = chunkMGEVSTDX_cjs.createEdgeRowMapper(chunkMGEVSTDX_cjs.SQLITE_ROW_MAPPER_CONFIG);
|
|
178
|
+
var toUniqueRow = chunkMGEVSTDX_cjs.createUniqueRowMapper(chunkMGEVSTDX_cjs.SQLITE_ROW_MAPPER_CONFIG);
|
|
179
|
+
var toSchemaVersionRow = chunkMGEVSTDX_cjs.createSchemaVersionRowMapper(chunkMGEVSTDX_cjs.SQLITE_ROW_MAPPER_CONFIG);
|
|
175
180
|
function createSerializedExecutionQueue() {
|
|
176
181
|
let tail = Promise.resolve();
|
|
177
182
|
return {
|
|
@@ -217,7 +222,7 @@ function createSqliteOperationBackend(options) {
|
|
|
217
222
|
if (result instanceof Promise) await result;
|
|
218
223
|
});
|
|
219
224
|
}
|
|
220
|
-
const commonBackend =
|
|
225
|
+
const commonBackend = chunkMGEVSTDX_cjs.createCommonOperationBackend({
|
|
221
226
|
batchConfig: {
|
|
222
227
|
edgeInsertBatchSize: SQLITE_EDGE_INSERT_BATCH_SIZE,
|
|
223
228
|
getEdgesChunkSize: SQLITE_GET_EDGES_ID_CHUNK_SIZE,
|
|
@@ -229,7 +234,7 @@ function createSqliteOperationBackend(options) {
|
|
|
229
234
|
execGet,
|
|
230
235
|
execRun
|
|
231
236
|
},
|
|
232
|
-
nowIso:
|
|
237
|
+
nowIso: chunkMGEVSTDX_cjs.nowIso,
|
|
233
238
|
operationStrategy,
|
|
234
239
|
rowMappers: {
|
|
235
240
|
toEdgeRow,
|
|
@@ -265,14 +270,14 @@ function createSqliteOperationBackend(options) {
|
|
|
265
270
|
...params.indexParams?.efConstruction === void 0 ? {} : { hnswEfConstruction: params.indexParams.efConstruction },
|
|
266
271
|
...params.indexParams?.lists === void 0 ? {} : { ivfflatLists: params.indexParams.lists }
|
|
267
272
|
};
|
|
268
|
-
const result =
|
|
273
|
+
const result = chunkMGEVSTDX_cjs.createSqliteVectorIndex(indexOptions);
|
|
269
274
|
if (!result.success) {
|
|
270
275
|
throw new Error(result.message ?? "Failed to create SQLite vector index");
|
|
271
276
|
}
|
|
272
277
|
return Promise.resolve();
|
|
273
278
|
},
|
|
274
279
|
dropVectorIndex(params) {
|
|
275
|
-
const result =
|
|
280
|
+
const result = chunkMGEVSTDX_cjs.dropSqliteVectorIndex(
|
|
276
281
|
params.graphId,
|
|
277
282
|
params.nodeKind,
|
|
278
283
|
params.fieldPath
|
|
@@ -296,17 +301,17 @@ function createSqliteOperationBackend(options) {
|
|
|
296
301
|
return operationBackend;
|
|
297
302
|
}
|
|
298
303
|
function createSqliteBackend(db, options = {}) {
|
|
299
|
-
const tables2 = options.tables ??
|
|
304
|
+
const tables2 = options.tables ?? chunkMGEVSTDX_cjs.tables;
|
|
300
305
|
const profileHints = options.executionProfile ?? {};
|
|
301
306
|
const executionAdapter = createSqliteExecutionAdapter(db, { profileHints });
|
|
302
|
-
const {
|
|
303
|
-
const capabilities =
|
|
307
|
+
const { isSync, transactionMode } = executionAdapter.profile;
|
|
308
|
+
const capabilities = transactionMode === "none" ? { ...chunkMGEVSTDX_cjs.SQLITE_CAPABILITIES, transactions: false } : chunkMGEVSTDX_cjs.SQLITE_CAPABILITIES;
|
|
304
309
|
const tableNames = {
|
|
305
310
|
nodes: drizzleOrm.getTableName(tables2.nodes),
|
|
306
311
|
edges: drizzleOrm.getTableName(tables2.edges),
|
|
307
312
|
embeddings: drizzleOrm.getTableName(tables2.embeddings)
|
|
308
313
|
};
|
|
309
|
-
const operationStrategy =
|
|
314
|
+
const operationStrategy = chunkMGEVSTDX_cjs.createSqliteOperationStrategy(tables2);
|
|
310
315
|
const serializedQueue = isSync ? createSerializedExecutionQueue() : void 0;
|
|
311
316
|
const operations = createSqliteOperationBackend({
|
|
312
317
|
capabilities,
|
|
@@ -324,24 +329,24 @@ function createSqliteBackend(db, options = {}) {
|
|
|
324
329
|
});
|
|
325
330
|
},
|
|
326
331
|
async transaction(fn, _options) {
|
|
327
|
-
if (
|
|
332
|
+
if (transactionMode === "none") {
|
|
328
333
|
throw new chunk44SXEVF4_cjs.ConfigurationError(
|
|
329
|
-
"
|
|
334
|
+
"This SQLite backend does not support atomic transactions. Operations within a transaction are not rolled back on failure. Use backend.capabilities.transactions to check for transaction support, or use individual operations with manual error handling.",
|
|
330
335
|
{
|
|
331
|
-
backend: "
|
|
336
|
+
backend: "sqlite",
|
|
332
337
|
capability: "transactions",
|
|
333
338
|
supportsTransactions: false
|
|
334
339
|
}
|
|
335
340
|
);
|
|
336
341
|
}
|
|
337
|
-
if (
|
|
342
|
+
if (transactionMode === "sql") {
|
|
338
343
|
return runWithSerializedQueue(serializedQueue, async () => {
|
|
339
344
|
const txBackend = createTransactionBackend({
|
|
340
345
|
capabilities,
|
|
341
346
|
db,
|
|
342
347
|
executionAdapter,
|
|
343
348
|
operationStrategy,
|
|
344
|
-
profileHints: {
|
|
349
|
+
profileHints: { isSync: true },
|
|
345
350
|
tableNames
|
|
346
351
|
});
|
|
347
352
|
db.run(drizzleOrm.sql`BEGIN`);
|
|
@@ -355,16 +360,19 @@ function createSqliteBackend(db, options = {}) {
|
|
|
355
360
|
}
|
|
356
361
|
});
|
|
357
362
|
}
|
|
358
|
-
return
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
363
|
+
return runWithSerializedQueue(
|
|
364
|
+
serializedQueue,
|
|
365
|
+
async () => db.transaction(async (tx) => {
|
|
366
|
+
const txBackend = createTransactionBackend({
|
|
367
|
+
capabilities,
|
|
368
|
+
db: tx,
|
|
369
|
+
operationStrategy,
|
|
370
|
+
profileHints: { isSync },
|
|
371
|
+
tableNames
|
|
372
|
+
});
|
|
373
|
+
return fn(txBackend);
|
|
374
|
+
})
|
|
375
|
+
);
|
|
368
376
|
},
|
|
369
377
|
async close() {
|
|
370
378
|
}
|
|
@@ -385,5 +393,5 @@ function createTransactionBackend(options) {
|
|
|
385
393
|
}
|
|
386
394
|
|
|
387
395
|
exports.createSqliteBackend = createSqliteBackend;
|
|
388
|
-
//# sourceMappingURL=chunk-
|
|
389
|
-
//# sourceMappingURL=chunk-
|
|
396
|
+
//# sourceMappingURL=chunk-FXZOTO6F.cjs.map
|
|
397
|
+
//# sourceMappingURL=chunk-FXZOTO6F.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/backend/drizzle/execution/sqlite-execution.ts","../src/backend/drizzle/sqlite.ts"],"names":["sql","compileQueryWithDialect","executeCompiled","createNodeRowMapper","SQLITE_ROW_MAPPER_CONFIG","createEdgeRowMapper","createUniqueRowMapper","createSchemaVersionRowMapper","createCommonOperationBackend","nowIso","createSqliteVectorIndex","dropSqliteVectorIndex","tables","SQLITE_CAPABILITIES","getTableName","createSqliteOperationStrategy","ConfigurationError"],"mappings":";;;;;;AAUA,IAAM,oCAAA,GAAuC,GAAA;AAgE7C,SAAS,eAAe,EAAA,EAA2C;AACjE,EAAA,MAAM,mBAAA,GAAsB,EAAA;AAC5B,EAAA,MAAM,kBAAA,GAAqB,mBAAA,CAAoB,OAAA,EAAS,WAAA,EAAa,IAAA;AACrE,EAAA,IAAI,uBAAuB,MAAA,EAAW;AACpC,IAAA,OAAO,kBAAA;AAAA,EACT;AAEA,EAAA,OAAO,mBAAA,CAAoB,CAAA,EAAG,OAAA,EAAS,WAAA,EAAa,IAAA;AACtD;AAEA,SAAS,0BAA0B,EAAA,EAAgC;AACjE,EAAA,OAAO,cAAA,CAAe,EAAE,CAAA,KAAM,iBAAA;AAChC;AAEA,SAAS,6BAA6B,EAAA,EAAgC;AACpE,EAAA,MAAM,WAAA,GAAc,eAAe,EAAE,CAAA;AACrC,EAAA,OAAO,WAAA,KAAgB,4BAAA;AACzB;AAEA,SAAS,4BAA4B,EAAA,EAAgC;AACnE,EAAA,MAAM,WAAA,GAAc,eAAe,EAAE,CAAA;AACrC,EAAA,OACE,WAAA,KAAgB,yBAAyB,WAAA,KAAgB,kBAAA;AAE7D;AAEA,SAAS,iBAAA,CACP,IACA,YAAA,EACS;AACT,EAAA,IAAI,YAAA,C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,KAAA;AAAA,UACR;AAAA,QACF,CAAC,CAAA;AAAA,MACH;AAGA,MAAA,OAAO,sBAAA;AAAA,QAAuB,eAAA;AAAA,QAAiB,YAC7C,EAAA,CAAG,WAAA,CAAY,OAAO,EAAA,KAAO;AAC3B,UAAA,MAAM,YAAY,wBAAA,CAAyB;AAAA,YACzC,YAAA;AAAA,YACA,EAAA,EAAI,EAAA;AAAA,YACJ,iBAAA;AAAA,YACA,YAAA,EAAc,EAAE,MAAA,EAAO;AAAA,YACvB;AAAA,WACD,CAAA;AACD,UAAA,OAAO,GAAG,SAAS,CAAA;AAAA,QACrB,CAAC;AAAA,OACH;AAAA,IACF,CAAA;AAAA,IAEA,MAAM,KAAA,GAAuB;AAAA,IAG7B;AAAA,GACF;AAEA,EAAA,OAAO,OAAA;AACT;AAEA,SAAS,yBACP,OAAA,EACoB;AACpB,EAAA,MAAM,kBAAA,GACJ,OAAA,CAAQ,gBAAA,IACR,4BAAA,CAA6B,QAAQ,EAAA,EAAI;AAAA,IACvC,cAAc,OAAA,CAAQ;AAAA,GACvB,CAAA;AAEH,EAAA,OAAO,4BAAA,CAA6B;AAAA,IAClC,cAAc,OAAA,CAAQ,YAAA;AAAA,IACtB,IAAI,OAAA,CAAQ,EAAA;AAAA,IACZ,gBAAA,EAAkB,kBAAA;AAAA,IAClB,mBAAmB,OAAA,CAAQ,iBAAA;AAAA,IAC3B,YAAY,OAAA,CAAQ;AAAA,GACrB,CAAA;AACH","file":"chunk-FXZOTO6F.cjs","sourcesContent":["import { type SQL, sql } from \"drizzle-orm\";\nimport { type BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\nimport {\n type CompiledSqlQuery,\n compileQueryWithDialect,\n type PreparedSqlStatement,\n type SqlExecutionAdapter,\n} from \"./types\";\n\nconst DEFAULT_PREPARED_STATEMENT_CACHE_MAX = 256;\n\ntype PreparedAllStatement = Readonly<{\n all: (...params: readonly unknown[]) => readonly unknown[];\n}>;\n\ntype SqliteClientWithPrepare = Readonly<{\n prepare: (sqlText: string) => PreparedAllStatement;\n}>;\n\ntype SqliteClientCarrier = Readonly<{\n $client?: SqliteClientWithPrepare;\n}>;\n\ntype SessionLike = Readonly<{\n constructor?: Readonly<{\n name?: string;\n }>;\n}>;\n\ntype DatabaseWithSession = Readonly<{\n _?: Readonly<{\n session?: SessionLike;\n }>;\n session?: SessionLike;\n}>;\n\n/**\n * Controls how the backend manages SQLite transactions.\n *\n * - `\"sql\"`: TypeGraph issues BEGIN / COMMIT / ROLLBACK SQL directly.\n * Default for sync drivers (better-sqlite3, bun:sqlite).\n * - `\"drizzle\"`: Delegates to Drizzle's `db.transaction()` method.\n * Default for async drivers (libsql, sql.js).\n * - `\"none\"`: Transactions disabled.\n * Default for Cloudflare D1 and Durable Objects.\n */\nexport type SqliteTransactionMode = \"sql\" | \"drizzle\" | \"none\";\n\nexport type SqliteExecutionProfileHints = Readonly<{\n isSync?: boolean;\n transactionMode?: SqliteTransactionMode;\n}>;\n\ntype SqliteExecutionAdapterOptions = Readonly<{\n profileHints?: SqliteExecutionProfileHints;\n statementCacheMax?: number;\n}>;\n\nexport type AnySqliteDatabase = BaseSQLiteDatabase<\"sync\" | \"async\", unknown>;\n\nexport type SqliteExecutionProfile = Readonly<{\n isSync: boolean;\n supportsCompiledExecution: boolean;\n transactionMode: SqliteTransactionMode;\n}>;\n\nexport type SqliteExecutionAdapter = Readonly<\n SqlExecutionAdapter & {\n clearStatementCache: () => void;\n profile: SqliteExecutionProfile;\n }\n>;\n\nfunction getSessionName(db: AnySqliteDatabase): string | undefined {\n const databaseWithSession = db as DatabaseWithSession;\n const primarySessionName = databaseWithSession.session?.constructor?.name;\n if (primarySessionName !== undefined) {\n return primarySessionName;\n }\n\n return databaseWithSession._?.session?.constructor?.name;\n}\n\nfunction isD1DatabaseBySessionName(db: AnySqliteDatabase): boolean {\n return getSessionName(db) === \"SQLiteD1Session\";\n}\n\nfunction isDurableObjectBySessionName(db: AnySqliteDatabase): boolean {\n const sessionName = getSessionName(db);\n return sessionName === \"SQLiteDurableObjectSession\";\n}\n\nfunction isSyncDatabaseBySessionName(db: AnySqliteDatabase): boolean {\n const sessionName = getSessionName(db);\n return (\n sessionName === \"BetterSQLiteSession\" || sessionName === \"BunSQLiteSession\"\n );\n}\n\nfunction detectSyncProfile(\n db: AnySqliteDatabase,\n profileHints: SqliteExecutionProfileHints,\n): boolean {\n if (profileHints.isSync !== undefined) {\n return profileHints.isSync;\n }\n\n const sessionName = getSessionName(db);\n if (sessionName === \"BetterSQLiteSession\" || sessionName === \"BunSQLiteSession\") {\n return true;\n }\n if (sessionName === \"SQLiteD1Session\") {\n return false;\n }\n\n try {\n const probeResult = db.get(sql`SELECT 1 AS __typegraph_sync_probe__`);\n return !(probeResult instanceof Promise);\n } catch {\n return isSyncDatabaseBySessionName(db);\n }\n}\n\nfunction detectTransactionMode(\n db: AnySqliteDatabase,\n profileHints: SqliteExecutionProfileHints,\n isSync: boolean,\n): SqliteTransactionMode {\n if (profileHints.transactionMode !== undefined) {\n return profileHints.transactionMode;\n }\n // D1 and Durable Object SQLite do not support raw BEGIN/COMMIT SQL\n // through Drizzle's db.run(). Default to \"none\" because async\n // transaction callbacks are not reliably supported across sync\n // Drizzle drivers. Users can opt in to \"drizzle\" mode explicitly if\n // their runtime's db.transaction() handles async callbacks.\n if (isD1DatabaseBySessionName(db) || isDurableObjectBySessionName(db)) {\n return \"none\";\n }\n if (isSync) return \"sql\";\n return \"drizzle\";\n}\n\nfunction resolveSqliteClient(\n db: AnySqliteDatabase,\n): SqliteClientWithPrepare | undefined {\n const databaseWithClient = db as SqliteClientCarrier;\n const sqliteClient = databaseWithClient.$client;\n if (sqliteClient?.prepare === undefined) {\n return undefined;\n }\n return sqliteClient;\n}\n\nfunction getOrCreatePreparedStatement(\n cache: Map<string, PreparedAllStatement>,\n sqliteClient: SqliteClientWithPrepare,\n sqlText: string,\n cacheMax: number,\n): PreparedAllStatement {\n const cachedStatement = cache.get(sqlText);\n if (cachedStatement !== undefined) {\n // Promote to most-recently-used position for LRU eviction\n cache.delete(sqlText);\n cache.set(sqlText, cachedStatement);\n return cachedStatement;\n }\n\n const preparedStatement = sqliteClient.prepare(sqlText);\n cache.set(sqlText, preparedStatement);\n\n if (cache.size > cacheMax) {\n const oldestSqlText = cache.keys().next().value;\n if (typeof oldestSqlText === \"string\") {\n cache.delete(oldestSqlText);\n }\n }\n\n return preparedStatement;\n}\n\nasync function executeDrizzleQuery<TRow>(\n db: AnySqliteDatabase,\n query: SQL,\n): Promise<readonly TRow[]> {\n const rows = db.all(query);\n return (rows instanceof Promise ? await rows : rows) as readonly TRow[];\n}\n\nfunction createPreparedStatementExecutor(\n sqliteClient: SqliteClientWithPrepare,\n cache: Map<string, PreparedAllStatement>,\n sqlText: string,\n cacheMax: number,\n): PreparedSqlStatement {\n return {\n execute<TRow>(params: readonly unknown[]): Promise<readonly TRow[]> {\n const preparedStatement = getOrCreatePreparedStatement(\n cache,\n sqliteClient,\n sqlText,\n cacheMax,\n );\n const rows = preparedStatement.all(...params);\n return Promise.resolve(rows as readonly TRow[]);\n },\n };\n}\n\nexport function createSqliteExecutionAdapter(\n db: AnySqliteDatabase,\n statementCacheMaxOrOptions: number | SqliteExecutionAdapterOptions = {},\n): SqliteExecutionAdapter {\n const options: SqliteExecutionAdapterOptions =\n typeof statementCacheMaxOrOptions === \"number\"\n ? { statementCacheMax: statementCacheMaxOrOptions }\n : statementCacheMaxOrOptions;\n const statementCacheMax =\n options.statementCacheMax ?? DEFAULT_PREPARED_STATEMENT_CACHE_MAX;\n const profileHints = options.profileHints ?? {};\n\n const isSync = detectSyncProfile(db, profileHints);\n const sqliteClient = isSync ? resolveSqliteClient(db) : undefined;\n const transactionMode = detectTransactionMode(db, profileHints, isSync);\n\n const profile: SqliteExecutionProfile = {\n isSync,\n supportsCompiledExecution: sqliteClient !== undefined,\n transactionMode,\n };\n\n const compile = (query: SQL): CompiledSqlQuery =>\n compileQueryWithDialect(db, query, \"SQLite\");\n\n if (sqliteClient !== undefined) {\n const client = sqliteClient;\n const statementCache = new Map<string, PreparedAllStatement>();\n\n function executeCompiled<TRow>(\n compiledQuery: CompiledSqlQuery,\n ): Promise<readonly TRow[]> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n client,\n compiledQuery.sql,\n statementCacheMax,\n );\n const rows = preparedStatement.all(...compiledQuery.params);\n return Promise.resolve(rows as readonly TRow[]);\n }\n\n return {\n clearStatementCache() {\n statementCache.clear();\n },\n compile,\n execute<TRow>(query: SQL): Promise<readonly TRow[]> {\n const compiledQuery = compile(query);\n return executeCompiled<TRow>(compiledQuery);\n },\n executeCompiled,\n prepare(sqlText: string): PreparedSqlStatement {\n return createPreparedStatementExecutor(\n client,\n statementCache,\n sqlText,\n statementCacheMax,\n );\n },\n profile,\n };\n }\n\n return {\n clearStatementCache() {\n // No-op: no statement cache in async/D1 mode\n },\n compile,\n execute<TRow>(query: SQL): Promise<readonly TRow[]> {\n return executeDrizzleQuery<TRow>(db, query);\n },\n profile,\n };\n}\n","/**\n * SQLite backend adapter for TypeGraph.\n *\n * Works with any Drizzle SQLite database instance:\n * - better-sqlite3\n * - libsql / Turso\n * - Cloudflare D1\n * - bun:sqlite\n * - sql.js\n *\n * @example\n * ```typescript\n * import { drizzle } from \"drizzle-orm/better-sqlite3\";\n * import Database from \"better-sqlite3\";\n * import { createSqliteBackend, tables } from \"@nicia-ai/typegraph/sqlite\";\n *\n * const sqlite = new Database(\"app.db\");\n * const db = drizzle(sqlite);\n * const backend = createSqliteBackend(db, { tables });\n * ```\n */\nimport { getTableName, type SQL, sql } from \"drizzle-orm\";\n\nimport { ConfigurationError } from \"../../errors\";\nimport type { SqlTableNames } from \"../../query/compiler/schema\";\nimport {\n type CreateVectorIndexParams,\n type DropVectorIndexParams,\n type GraphBackend,\n SQLITE_CAPABILITIES,\n type TransactionBackend,\n type TransactionOptions,\n} from \"../types\";\nimport {\n type AnySqliteDatabase,\n createSqliteExecutionAdapter,\n type SqliteExecutionAdapter,\n type SqliteExecutionProfileHints,\n} from \"./execution/sqlite-execution\";\nexport type { SqliteTransactionMode } from \"./execution/sqlite-execution\";\nimport { createCommonOperationBackend } from \"./operation-backend-core\";\nimport { createSqliteOperationStrategy } from \"./operations/strategy\";\nimport {\n createEdgeRowMapper,\n createNodeRowMapper,\n createSchemaVersionRowMapper,\n createUniqueRowMapper,\n nowIso,\n SQLITE_ROW_MAPPER_CONFIG,\n} from \"./row-mappers\";\nimport { type SqliteTables, tables as defaultTables } from \"./schema/sqlite\";\nimport {\n createSqliteVectorIndex,\n dropSqliteVectorIndex,\n type VectorIndexOptions,\n} from \"./vector-index\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Options for creating a SQLite backend.\n */\nexport type SqliteBackendOptions = Readonly<{\n /**\n * Custom table definitions. Use createSqliteTables() to customize table names.\n * Defaults to standard TypeGraph table names.\n */\n tables?: SqliteTables;\n /**\n * Optional execution profile hints used to avoid runtime driver reflection.\n * Set `transactionMode: \"none\"` for drivers that do not support transactions\n * (e.g. Cloudflare D1, Durable Objects).\n */\n executionProfile?: SqliteExecutionProfileHints;\n}>;\n\nconst SQLITE_MAX_BIND_PARAMETERS = 999;\nconst NODE_INSERT_PARAM_COUNT = 9;\nconst EDGE_INSERT_PARAM_COUNT = 12;\nconst SQLITE_NODE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(SQLITE_MAX_BIND_PARAMETERS / NODE_INSERT_PARAM_COUNT),\n);\nconst SQLITE_EDGE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(SQLITE_MAX_BIND_PARAMETERS / EDGE_INSERT_PARAM_COUNT),\n);\nconst SQLITE_GET_NODES_ID_CHUNK_SIZE = Math.max(\n 1,\n SQLITE_MAX_BIND_PARAMETERS - 2,\n);\nconst SQLITE_GET_EDGES_ID_CHUNK_SIZE = Math.max(\n 1,\n SQLITE_MAX_BIND_PARAMETERS - 1,\n);\n\ntype SerializedExecutionQueue = Readonly<{\n runExclusive: <T>(task: () => Promise<T>) => Promise<T>;\n}>;\n\n// ============================================================\n// Utilities\n// ============================================================\n\nconst toNodeRow = createNodeRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toEdgeRow = createEdgeRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toUniqueRow = createUniqueRowMapper(SQLITE_ROW_MAPPER_CONFIG);\nconst toSchemaVersionRow = createSchemaVersionRowMapper(SQLITE_ROW_MAPPER_CONFIG);\n\nfunction createSerializedExecutionQueue(): SerializedExecutionQueue {\n let tail: Promise<unknown> = Promise.resolve();\n\n return {\n async runExclusive<T>(task: () => Promise<T>): Promise<T> {\n const runTask = async (): Promise<T> => task();\n const result = tail.then(runTask, runTask);\n tail = result.then(\n () => 0,\n () => 0,\n );\n return result;\n },\n };\n}\n\nasync function runWithSerializedQueue<T>(\n queue: SerializedExecutionQueue | undefined,\n task: () => Promise<T>,\n): Promise<T> {\n if (queue === undefined) return task();\n return queue.runExclusive(task);\n}\n\n// ============================================================\n// Backend Factory\n// ============================================================\n\n/**\n * Creates a TypeGraph backend for SQLite databases.\n *\n * Works with any Drizzle SQLite instance regardless of the underlying driver.\n *\n * @param db - A Drizzle SQLite database instance\n * @param options - Backend configuration\n * @returns A GraphBackend implementation\n */\ntype CreateSqliteOperationBackendOptions = Readonly<{\n capabilities: GraphBackend[\"capabilities\"];\n db: AnySqliteDatabase;\n executionAdapter: SqliteExecutionAdapter;\n operationStrategy: ReturnType<typeof createSqliteOperationStrategy>;\n serializedQueue?: SerializedExecutionQueue;\n tableNames: SqlTableNames;\n}>;\n\ntype CreateSqliteTransactionBackendOptions = Readonly<{\n capabilities: GraphBackend[\"capabilities\"];\n db: AnySqliteDatabase;\n executionAdapter?: SqliteExecutionAdapter;\n operationStrategy: ReturnType<typeof createSqliteOperationStrategy>;\n profileHints: SqliteExecutionProfileHints;\n tableNames: SqlTableNames;\n}>;\n\nfunction createSqliteOperationBackend(\n options: CreateSqliteOperationBackendOptions,\n): TransactionBackend {\n const {\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n serializedQueue,\n tableNames,\n } = options;\n\n async function execGet<T>(query: SQL): Promise<T | undefined> {\n return runWithSerializedQueue(serializedQueue, async () => {\n const result = db.get(query);\n return (result instanceof Promise ? await result : result) as T | undefined;\n });\n }\n\n async function execAll<T>(query: SQL): Promise<T[]> {\n return runWithSerializedQueue(serializedQueue, async () => {\n const result = db.all(query);\n return (result instanceof Promise ? await result : result) as T[];\n });\n }\n\n async function execRun(query: SQL): Promise<void> {\n await runWithSerializedQueue(serializedQueue, async () => {\n const result = db.run(query);\n if (result instanceof Promise) await result;\n });\n }\n\n const commonBackend = createCommonOperationBackend({\n batchConfig: {\n edgeInsertBatchSize: SQLITE_EDGE_INSERT_BATCH_SIZE,\n getEdgesChunkSize: SQLITE_GET_EDGES_ID_CHUNK_SIZE,\n getNodesChunkSize: SQLITE_GET_NODES_ID_CHUNK_SIZE,\n nodeInsertBatchSize: SQLITE_NODE_INSERT_BATCH_SIZE,\n },\n execution: {\n execAll,\n execGet,\n execRun,\n },\n nowIso,\n operationStrategy,\n rowMappers: {\n toEdgeRow,\n toNodeRow,\n toSchemaVersionRow,\n toUniqueRow,\n },\n });\n\n const executeCompiled = executionAdapter.executeCompiled;\n const executeRawMethod: Pick<TransactionBackend, \"executeRaw\"> =\n executeCompiled === undefined ?\n {}\n : {\n executeRaw<T>(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executeCompiled<T>({ params, sql: sqlText }),\n );\n },\n };\n\n const operationBackend: TransactionBackend = {\n ...commonBackend,\n ...executeRawMethod,\n capabilities,\n dialect: \"sqlite\",\n tableNames,\n\n createVectorIndex(params: CreateVectorIndexParams): Promise<void> {\n const indexOptions: VectorIndexOptions = {\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n fieldPath: params.fieldPath,\n dimensions: params.dimensions,\n indexType: params.indexType,\n metric: params.metric,\n ...(params.indexParams?.m === undefined\n ? {}\n : { hnswM: params.indexParams.m }),\n ...(params.indexParams?.efConstruction === undefined\n ? {}\n : { hnswEfConstruction: params.indexParams.efConstruction }),\n ...(params.indexParams?.lists === undefined\n ? {}\n : { ivfflatLists: params.indexParams.lists }),\n };\n\n const result = createSqliteVectorIndex(indexOptions);\n\n if (!result.success) {\n throw new Error(result.message ?? \"Failed to create SQLite vector index\");\n }\n return Promise.resolve();\n },\n\n dropVectorIndex(params: DropVectorIndexParams): Promise<void> {\n const result = dropSqliteVectorIndex(\n params.graphId,\n params.nodeKind,\n params.fieldPath,\n );\n if (!result.success) {\n throw new Error(result.message ?? \"Failed to drop SQLite vector index\");\n }\n return Promise.resolve();\n },\n\n // === Query Execution ===\n\n async execute<T>(query: SQL): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executionAdapter.execute<T>(query),\n );\n },\n\n compileSql(query: SQL): Readonly<{ sql: string; params: readonly unknown[] }> {\n return executionAdapter.compile(query);\n },\n };\n\n return operationBackend;\n}\n\nexport function createSqliteBackend(\n db: AnySqliteDatabase,\n options: SqliteBackendOptions = {},\n): GraphBackend {\n const tables = options.tables ?? defaultTables;\n const profileHints = options.executionProfile ?? {};\n const executionAdapter = createSqliteExecutionAdapter(db, { profileHints });\n const { isSync, transactionMode } = executionAdapter.profile;\n const capabilities =\n transactionMode === \"none\"\n ? { ...SQLITE_CAPABILITIES, transactions: false }\n : SQLITE_CAPABILITIES;\n\n const tableNames: SqlTableNames = {\n nodes: getTableName(tables.nodes),\n edges: getTableName(tables.edges),\n embeddings: getTableName(tables.embeddings),\n };\n const operationStrategy = createSqliteOperationStrategy(tables);\n const serializedQueue = isSync ? createSerializedExecutionQueue() : undefined;\n const operations = createSqliteOperationBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n tableNames,\n ...(serializedQueue === undefined ? {} : { serializedQueue }),\n });\n\n const backend: GraphBackend = {\n ...operations,\n\n async setActiveSchema(graphId: string, version: number): Promise<void> {\n await backend.transaction(async (txBackend) => {\n await txBackend.setActiveSchema(graphId, version);\n });\n },\n\n async transaction<T>(\n fn: (tx: TransactionBackend) => Promise<T>,\n _options?: TransactionOptions,\n ): Promise<T> {\n if (transactionMode === \"none\") {\n throw new ConfigurationError(\n \"This SQLite backend does not support atomic transactions. \" +\n \"Operations within a transaction are not rolled back on failure. \" +\n \"Use backend.capabilities.transactions to check for transaction support, \" +\n \"or use individual operations with manual error handling.\",\n {\n backend: \"sqlite\",\n capability: \"transactions\",\n supportsTransactions: false,\n },\n );\n }\n\n if (transactionMode === \"sql\") {\n return runWithSerializedQueue(serializedQueue, async () => {\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n profileHints: { isSync: true },\n tableNames,\n });\n db.run(sql`BEGIN`);\n\n try {\n const result = await fn(txBackend);\n db.run(sql`COMMIT`);\n return result;\n } catch (error) {\n db.run(sql`ROLLBACK`);\n throw error;\n }\n });\n }\n\n // transactionMode === \"drizzle\"\n return runWithSerializedQueue(serializedQueue, async () =>\n db.transaction(async (tx) => {\n const txBackend = createTransactionBackend({\n capabilities,\n db: tx as AnySqliteDatabase,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n });\n return fn(txBackend);\n }) as Promise<T>,\n );\n },\n\n async close(): Promise<void> {\n // Drizzle doesn't expose a close method\n // Users manage connection lifecycle themselves\n },\n };\n\n return backend;\n}\n\nfunction createTransactionBackend(\n options: CreateSqliteTransactionBackendOptions,\n): TransactionBackend {\n const txExecutionAdapter =\n options.executionAdapter ??\n createSqliteExecutionAdapter(options.db, {\n profileHints: options.profileHints,\n });\n\n return createSqliteOperationBackend({\n capabilities: options.capabilities,\n db: options.db,\n executionAdapter: txExecutionAdapter,\n operationStrategy: options.operationStrategy,\n tableNames: options.tableNames,\n });\n}\n\n// Re-export schema utilities\nexport type { SqliteTableNames,SqliteTables } from \"./schema/sqlite\";\nexport { createSqliteTables, tables } from \"./schema/sqlite\";\n"]}
|
|
@@ -49,23 +49,22 @@ function validateConstraintNarrowing(name, edgeType, registration) {
|
|
|
49
49
|
}
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
|
-
function normalizeEdgeEntry(name, entry) {
|
|
53
|
-
if (
|
|
54
|
-
|
|
55
|
-
type: entry,
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
};
|
|
52
|
+
function normalizeEdgeEntry(name, entry, allNodeTypes) {
|
|
53
|
+
if (isEdgeType(entry)) {
|
|
54
|
+
if (isEdgeTypeWithEndpoints(entry)) {
|
|
55
|
+
return { type: entry, from: entry.from, to: entry.to };
|
|
56
|
+
}
|
|
57
|
+
return { type: entry, from: allNodeTypes, to: allNodeTypes };
|
|
59
58
|
}
|
|
60
59
|
if (isEdgeTypeWithEndpoints(entry.type)) {
|
|
61
60
|
validateConstraintNarrowing(name, entry.type, entry);
|
|
62
61
|
}
|
|
63
62
|
return entry;
|
|
64
63
|
}
|
|
65
|
-
function normalizeEdges(edges) {
|
|
64
|
+
function normalizeEdges(edges, allNodeTypes) {
|
|
66
65
|
const result = {};
|
|
67
66
|
for (const [name, entry] of Object.entries(edges)) {
|
|
68
|
-
result[name] = normalizeEdgeEntry(name, entry);
|
|
67
|
+
result[name] = normalizeEdgeEntry(name, entry, allNodeTypes);
|
|
69
68
|
}
|
|
70
69
|
return result;
|
|
71
70
|
}
|
|
@@ -74,7 +73,8 @@ function defineGraph(config) {
|
|
|
74
73
|
onNodeDelete: config.defaults?.onNodeDelete ?? "restrict",
|
|
75
74
|
temporalMode: config.defaults?.temporalMode ?? "current"
|
|
76
75
|
};
|
|
77
|
-
const
|
|
76
|
+
const allNodeTypes = Object.values(config.nodes).map((reg) => reg.type);
|
|
77
|
+
const normalizedEdges = normalizeEdges(config.edges, allNodeTypes);
|
|
78
78
|
return Object.freeze({
|
|
79
79
|
[GRAPH_DEF_BRAND]: true,
|
|
80
80
|
id: config.id,
|
|
@@ -131,5 +131,5 @@ function nowIso() {
|
|
|
131
131
|
}
|
|
132
132
|
|
|
133
133
|
export { EDGE_TYPE_BRAND, NODE_TYPE_BRAND, defineGraph, getEdgeKinds, getNodeKinds, isEdgeType, isEdgeTypeWithEndpoints, isGraphDef, isNodeType, nowIso, validateOptionalIsoDate };
|
|
134
|
-
//# sourceMappingURL=chunk-
|
|
135
|
-
//# sourceMappingURL=chunk-
|
|
134
|
+
//# sourceMappingURL=chunk-IRFD3MEU.js.map
|
|
135
|
+
//# sourceMappingURL=chunk-IRFD3MEU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/types.ts","../src/core/define-graph.ts","../src/utils/date.ts"],"names":[],"mappings":";;;AAOO,IAAM,eAAA,GAAkB;AAGxB,IAAM,eAAA,GAAkB;AA0PxB,SAAS,WAAW,KAAA,EAAmC;AAC5D,EAAA,OACE,OAAO,UAAU,QAAA,IACjB,KAAA,KAAU,QACV,eAAA,IAAmB,KAAA,IAClB,KAAA,CAAkC,eAAe,CAAA,KAAM,IAAA;AAE5D;AAKO,SAAS,WAAW,KAAA,EAAsC;AAC/D,EAAA,OACE,OAAO,UAAU,QAAA,IACjB,KAAA,KAAU,QACV,eAAA,IAAmB,KAAA,IAClB,KAAA,CAAkC,eAAe,CAAA,KAAM,IAAA;AAE5D;AAMO,SAAS,wBACd,KAAA,EACgC;AAChC,EAAA,OACE,WAAW,KAAK,CAAA,IAChB,MAAM,OAAA,CAAQ,KAAA,CAAM,IAAI,CAAA,IACxB,KAAA,CAAM,KAAK,MAAA,GAAS,CAAA,IACpB,MAAM,OAAA,CAAQ,KAAA,CAAM,EAAE,CAAA,IACtB,KAAA,CAAM,GAAG,MAAA,GAAS,CAAA;AAEtB;;;ACnRA,IAAM,eAAA,GAAkB,YAAA;AA2CxB,SAAS,2BAAA,CACP,IAAA,EACA,QAAA,EACA,YAAA,EACM;AACN,EAAA,MAAM,gBAAA,GAAmB,IAAI,GAAA,CAAI,QAAA,CAAS,IAAA,CAAK,IAAI,CAAC,CAAA,KAAM,CAAA,CAAE,IAAI,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;AAAA,YACE,IAAA,EAAM,SAAA;AAAA,YACN,OAAA,EAAS,+EAA+E,KAAK,CAAA,CAAA;AAAA;AAC/F;AACF,OACF;AAAA,MACA;AAAA,QACE,UAAA,EAAY,CAAA,iEAAA;AAAA;AACd,KACF;AAAA,EACF;AACA,EAAA,OAAO,KAAA;AACT;AAMO,SAAS,uBAAA,CACd,OACA,SAAA,EACoB;AACpB,EAAA,IAAI,KAAA,KAAU,QAAW,OAAO,MAAA;AAChC,EAAA,OAAO,eAAA,CAAgB,OAAO,SAAS,CAAA;AACzC;AAuBO,SAAS,MAAA,GAAiB;AAC/B,EAAA,OAAA,iBAAO,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAChC","file":"chunk-IRFD3MEU.js","sourcesContent":["import { type z } from \"zod\";\n\n// ============================================================\n// Brand Keys for Nominal Typing\n// ============================================================\n\n/** Brand key for NodeType */\nexport const NODE_TYPE_BRAND = \"__nodeType\" as const;\n\n/** Brand key for EdgeType */\nexport const EDGE_TYPE_BRAND = \"__edgeType\" as const;\n\n/** Brand symbol for NodeId */\ndeclare const __nodeId: unique symbol;\n\n/** Brand symbol for EdgeId */\ndeclare const __edgeId: unique symbol;\n\n// ============================================================\n// Node Type\n// ============================================================\n\n/**\n * A node type definition.\n *\n * Created via `defineNode()`. Represents a type of node in the graph\n * with an associated Zod schema for properties.\n */\nexport type NodeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n [NODE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n}>;\n\n/**\n * Branded node ID type.\n *\n * Prevents mixing IDs from different node types at compile time.\n */\nexport type NodeId<N extends NodeType> = string &\n Readonly<{\n [__nodeId]: N;\n }>;\n\n/**\n * Infer the props type from a NodeType.\n */\nexport type NodeProps<N extends NodeType> = z.infer<N[\"schema\"]>;\n\n// ============================================================\n// Edge Type\n// ============================================================\n\n/**\n * An edge type definition.\n *\n * Created via `defineEdge()`. Represents a type of edge in the graph\n * with an optional Zod schema for properties.\n *\n * Optionally includes `from` and `to` arrays that define the allowed\n * source and target node types (domain and range constraints).\n */\nexport type EdgeType<\n K extends string = string,\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n From extends readonly NodeType[] | undefined = undefined,\n To extends readonly NodeType[] | undefined = undefined,\n> = Readonly<{\n [EDGE_TYPE_BRAND]: true;\n kind: K;\n schema: S;\n description: string | undefined;\n from: From;\n to: To;\n}>;\n\n/**\n * Base edge type for use in constraints - accepts any from/to configuration.\n */\nexport type AnyEdgeType = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[] | undefined,\n readonly NodeType[] | undefined\n>;\n\n/**\n * An edge type that has both from and to constraints defined.\n * Can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport type EdgeTypeWithEndpoints = EdgeType<\n string,\n z.ZodObject<z.ZodRawShape>,\n readonly NodeType[],\n readonly NodeType[]\n>;\n\n/**\n * Branded edge ID type.\n *\n * Prevents mixing IDs from different edge types at compile time.\n */\nexport type EdgeId<E extends AnyEdgeType = AnyEdgeType> = string &\n Readonly<{\n [__edgeId]: E;\n }>;\n\n/**\n * Infer the props type from an EdgeType.\n */\nexport type EdgeProps<E extends AnyEdgeType> = z.infer<E[\"schema\"]>;\n\n// ============================================================\n// Configuration Types\n// ============================================================\n\n/**\n * Delete behaviors for nodes.\n */\nexport type DeleteBehavior = \"restrict\" | \"cascade\" | \"disconnect\";\n\n/**\n * Edge cardinality constraints.\n */\nexport type Cardinality =\n | \"many\" // No constraint (default)\n | \"one\" // At most one edge of this kind from any source node\n | \"unique\" // At most one edge of this kind between any (source, target) pair\n | \"oneActive\"; // At most one edge with valid_to IS NULL from any source\n\n/**\n * Endpoint existence modes for edge validation.\n */\nexport type EndpointExistence =\n | \"notDeleted\" // Endpoint deleted_at IS NULL (default)\n | \"currentlyValid\" // Endpoint not deleted AND temporally valid\n | \"ever\"; // Endpoint exists in any state\n\n/**\n * Temporal query modes.\n */\nexport type TemporalMode =\n | \"current\" // Valid now AND not deleted\n | \"asOf\" // Valid at specific date AND not deleted\n | \"includeEnded\" // All validity periods AND not deleted\n | \"includeTombstones\"; // Everything including soft-deleted\n\n/**\n * Uniqueness constraint scope.\n */\nexport type UniquenessScope =\n | \"kind\" // Unique within this exact kind only\n | \"kindWithSubClasses\"; // Unique across this kind and all subclasses\n\n/**\n * Collation for uniqueness constraints.\n */\nexport type Collation = \"binary\" | \"caseInsensitive\";\n\n// ============================================================\n// Uniqueness Constraint\n// ============================================================\n\n/**\n * Uniqueness constraint definition.\n */\nexport type UniqueConstraint<\n S extends z.ZodObject<z.ZodRawShape> = z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n name: string;\n fields: readonly (keyof z.infer<S> & string)[];\n where?: (\n props: UniqueConstraintPredicateBuilder<S>,\n ) => UniqueConstraintPredicate;\n scope: UniquenessScope;\n collation: Collation;\n}>;\n\n/**\n * Predicate builder for uniqueness constraint where clause.\n * Uses -? to make all fields required in the builder, even if optional in the schema.\n */\nexport type UniqueConstraintPredicateBuilder<\n S extends z.ZodObject<z.ZodRawShape>,\n> = Readonly<{\n [K in keyof z.infer<S>]-?: UniqueConstraintField;\n}>;\n\n/**\n * Field operations for uniqueness constraint predicates.\n */\ntype UniqueConstraintField = Readonly<{\n isNull: () => UniqueConstraintPredicate;\n isNotNull: () => UniqueConstraintPredicate;\n}>;\n\n/**\n * A uniqueness constraint predicate (internal representation).\n */\nexport type UniqueConstraintPredicate = Readonly<{\n __type: \"unique_predicate\";\n field: string;\n op: \"isNull\" | \"isNotNull\";\n}>;\n\n// ============================================================\n// Node Registration\n// ============================================================\n\n/**\n * Node registration in a graph definition.\n */\nexport type NodeRegistration<N extends NodeType = NodeType> = Readonly<{\n type: N;\n unique?: readonly UniqueConstraint<N[\"schema\"]>[];\n onDelete?: DeleteBehavior;\n}>;\n\n// ============================================================\n// Edge Registration\n// ============================================================\n\n/**\n * Edge registration in a graph definition.\n */\nexport type EdgeRegistration<\n E extends AnyEdgeType = AnyEdgeType,\n FromTypes extends NodeType = NodeType,\n ToTypes extends NodeType = NodeType,\n> = Readonly<{\n type: E;\n from: readonly FromTypes[];\n to: readonly ToTypes[];\n cardinality?: Cardinality;\n endpointExistence?: EndpointExistence;\n}>;\n\n// ============================================================\n// Graph Defaults\n// ============================================================\n\n/**\n * Default settings for a graph.\n */\nexport type GraphDefaults = Readonly<{\n onNodeDelete?: DeleteBehavior;\n temporalMode?: TemporalMode;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Checks if a value is a NodeType.\n */\nexport function isNodeType(value: unknown): value is NodeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n NODE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[NODE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType.\n */\nexport function isEdgeType(value: unknown): value is AnyEdgeType {\n return (\n typeof value === \"object\" &&\n value !== null &&\n EDGE_TYPE_BRAND in value &&\n (value as Record<string, unknown>)[EDGE_TYPE_BRAND] === true\n );\n}\n\n/**\n * Checks if a value is an EdgeType with both from and to constraints defined.\n * Such edges can be used directly in defineGraph without an EdgeRegistration wrapper.\n */\nexport function isEdgeTypeWithEndpoints(\n value: unknown,\n): value is EdgeTypeWithEndpoints {\n return (\n isEdgeType(value) &&\n Array.isArray(value.from) &&\n value.from.length > 0 &&\n Array.isArray(value.to) &&\n value.to.length > 0\n );\n}\n","import { ConfigurationError } from \"../errors/index\";\nimport { type OntologyRelation } from \"../ontology/types\";\nimport {\n type AnyEdgeType,\n type DeleteBehavior,\n type EdgeRegistration,\n type EdgeTypeWithEndpoints,\n type GraphDefaults,\n isEdgeType,\n isEdgeTypeWithEndpoints,\n type NodeRegistration,\n type NodeType,\n type TemporalMode,\n} from \"./types\";\n\n// ============================================================\n// Graph Definition Brand Symbol\n// ============================================================\n\n/** Brand key for GraphDef */\nconst GRAPH_DEF_BRAND = \"__graphDef\" as const;\n\n// ============================================================\n// Edge Entry Types\n// ============================================================\n\n/**\n * An edge entry in the graph definition.\n * Can be:\n * - EdgeType directly (constrained or unconstrained)\n * - EdgeRegistration object (always works, can override/narrow defaults)\n */\ntype EdgeEntry = EdgeRegistration | AnyEdgeType;\n\n/**\n * Normalized edge map type - all entries become EdgeRegistration.\n * For bare EdgeTypes, constrained endpoints are extracted from the type;\n * unconstrained edges fall back to all node types in the graph.\n */\ntype NormalizedEdges<\n TNodes extends Record<string, NodeRegistration>,\n TEdges extends Record<string, EdgeEntry>,\n> = {\n [K in keyof TEdges]: TEdges[K] extends EdgeRegistration ? TEdges[K]\n : TEdges[K] extends AnyEdgeType ?\n EdgeRegistration<\n TEdges[K],\n TEdges[K][\"from\"] extends readonly (infer N extends NodeType)[] ? N\n : TNodes[keyof TNodes][\"type\"],\n TEdges[K][\"to\"] extends readonly (infer N extends NodeType)[] ? N\n : TNodes[keyof TNodes][\"type\"]\n >\n : never;\n};\n\n// ============================================================\n// Edge Normalization Functions\n// ============================================================\n\n/**\n * Validates that an EdgeRegistration's constraints don't widen beyond\n * the edge type's built-in domain/range constraints.\n */\nfunction validateConstraintNarrowing(\n name: string,\n edgeType: EdgeTypeWithEndpoints,\n registration: EdgeRegistration,\n): void {\n const builtInFromNames = new Set(edgeType.from.map((n) => n.kind));\n for (const fromNode of registration.from) {\n if (!builtInFromNames.has(fromNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'from' kind \"${fromNode.kind}\" ` +\n `not in edge's built-in domain: [${[...builtInFromNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidFrom: fromNode.kind,\n allowedFrom: [...builtInFromNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n\n const builtInToNames = new Set(edgeType.to.map((n) => n.kind));\n for (const toNode of registration.to) {\n if (!builtInToNames.has(toNode.kind)) {\n throw new ConfigurationError(\n `Edge \"${name}\" registration has 'to' kind \"${toNode.kind}\" ` +\n `not in edge's built-in range: [${[...builtInToNames].join(\", \")}]`,\n {\n edgeName: name,\n invalidTo: toNode.kind,\n allowedTo: [...builtInToNames],\n },\n {\n suggestion: `Edge registration can only narrow, not widen, the edge type's built-in constraints.`,\n },\n );\n }\n }\n}\n\n/**\n * Normalizes a single edge entry to EdgeRegistration.\n */\nfunction normalizeEdgeEntry(\n name: string,\n entry: EdgeEntry,\n allNodeTypes: readonly NodeType[],\n): EdgeRegistration {\n if (isEdgeType(entry)) {\n if (isEdgeTypeWithEndpoints(entry)) {\n // EdgeType with from/to — convert to EdgeRegistration\n return { type: entry, from: entry.from, to: entry.to };\n }\n // Unconstrained EdgeType — allow any→any\n return { type: entry, from: allNodeTypes, to: allNodeTypes };\n }\n\n // Already EdgeRegistration — validate narrowing if edge has built-in constraints\n if (isEdgeTypeWithEndpoints(entry.type)) {\n validateConstraintNarrowing(name, entry.type, entry);\n }\n\n return entry;\n}\n\n/**\n * Normalizes all edge entries to EdgeRegistration.\n */\nfunction normalizeEdges(\n edges: Record<string, EdgeEntry>,\n allNodeTypes: readonly NodeType[],\n): Record<string, EdgeRegistration> {\n const result: Record<string, EdgeRegistration> = {};\n for (const [name, entry] of Object.entries(edges)) {\n result[name] = normalizeEdgeEntry(name, entry, allNodeTypes);\n }\n return result;\n}\n\n// ============================================================\n// Graph Definition Configuration\n// ============================================================\n\n/**\n * Configuration for defineGraph.\n */\ntype GraphDefConfig<\n TNodes extends Record<string, NodeRegistration>,\n TEdges extends Record<string, EdgeEntry>,\n TOntology extends readonly OntologyRelation[],\n> = Readonly<{\n /** Unique identifier for this graph */\n id: string;\n /** Node registrations */\n nodes: TNodes;\n /** Edge registrations or EdgeTypes with built-in domain/range */\n edges: TEdges;\n /** Ontology relations */\n ontology?: TOntology;\n /** Graph-wide defaults */\n defaults?: GraphDefaults;\n}>;\n\n// ============================================================\n// Graph Definition Type\n// ============================================================\n\n/**\n * A graph definition.\n *\n * This is a compile-time artifact that describes the structure of a graph.\n * Use `createStore()` to create a runtime store from this definition.\n */\nexport type GraphDef<\n TNodes extends Record<string, NodeRegistration> = Record<\n string,\n NodeRegistration\n >,\n TEdges extends Record<string, EdgeRegistration> = Record<\n string,\n EdgeRegistration\n >,\n TOntology extends readonly OntologyRelation[] = readonly OntologyRelation[],\n> = Readonly<{\n [GRAPH_DEF_BRAND]: true;\n id: string;\n nodes: TNodes;\n edges: TEdges;\n ontology: TOntology;\n defaults: Readonly<{\n onNodeDelete: DeleteBehavior;\n temporalMode: TemporalMode;\n }>;\n}>;\n\n// ============================================================\n// Type Helpers\n// ============================================================\n\n/**\n * Extract node kind names from a GraphDef.\n */\nexport type NodeKinds<G extends GraphDef> = keyof G[\"nodes\"] & string;\n\n/**\n * Extract edge kind names from a GraphDef.\n */\nexport type EdgeKinds<G extends GraphDef> = keyof G[\"edges\"] & string;\n\n/**\n * Get a NodeType from a GraphDef by kind name.\n */\nexport type GetNodeType<\n G extends GraphDef,\n K extends NodeKinds<G>,\n> = G[\"nodes\"][K][\"type\"];\n\n/**\n * Get an EdgeType from a GraphDef by kind name.\n */\nexport type GetEdgeType<\n G extends GraphDef,\n K extends EdgeKinds<G>,\n> = G[\"edges\"][K][\"type\"];\n\n/**\n * Get all NodeTypes from a GraphDef.\n */\nexport type AllNodeTypes<G extends GraphDef> = {\n [K in NodeKinds<G>]: G[\"nodes\"][K][\"type\"];\n}[NodeKinds<G>];\n\n/**\n * Get all EdgeTypes from a GraphDef.\n */\nexport type AllEdgeTypes<G extends GraphDef> = {\n [K in EdgeKinds<G>]: G[\"edges\"][K][\"type\"];\n}[EdgeKinds<G>];\n\n// ============================================================\n// Define Graph Function\n// ============================================================\n\n/**\n * Creates a graph definition.\n *\n * @example\n * ```typescript\n * const graph = defineGraph({\n * id: \"my_graph\",\n * nodes: {\n * Person: { type: Person },\n * Company: { type: Company },\n * },\n * edges: {\n * // Traditional EdgeRegistration syntax\n * worksAt: {\n * type: worksAt,\n * from: [Person],\n * to: [Company],\n * cardinality: \"many\",\n * },\n * // Or use EdgeType directly if it has from/to defined\n * knows, // EdgeType with built-in domain/range\n * },\n * ontology: [\n * subClassOf(Company, Organization),\n * disjointWith(Person, Organization),\n * ],\n * defaults: {\n * onNodeDelete: \"restrict\",\n * temporalMode: \"current\",\n * },\n * });\n * ```\n */\nexport function defineGraph<\n const TNodes extends Record<string, NodeRegistration<NodeType>>,\n const TEdges extends Record<string, EdgeEntry>,\n const TOntology extends readonly OntologyRelation[],\n>(\n config: GraphDefConfig<TNodes, TEdges, TOntology>,\n): GraphDef<TNodes, NormalizedEdges<TNodes, TEdges>, TOntology> {\n const defaults = {\n onNodeDelete: config.defaults?.onNodeDelete ?? \"restrict\",\n temporalMode: config.defaults?.temporalMode ?? \"current\",\n } as const;\n\n const allNodeTypes = Object.values(config.nodes).map((reg) => reg.type);\n const normalizedEdges = normalizeEdges(config.edges, allNodeTypes);\n\n return Object.freeze({\n [GRAPH_DEF_BRAND]: true as const,\n id: config.id,\n nodes: config.nodes,\n edges: normalizedEdges,\n ontology: config.ontology ?? ([] as unknown as TOntology),\n defaults,\n }) as GraphDef<TNodes, NormalizedEdges<TNodes, TEdges>, TOntology>;\n}\n\n// ============================================================\n// Graph Definition Utilities\n// ============================================================\n\n/**\n * Checks if a value is a GraphDef.\n */\nexport function isGraphDef(value: unknown): value is GraphDef {\n return (\n typeof value === \"object\" &&\n value !== null &&\n GRAPH_DEF_BRAND in value &&\n (value as Record<string, unknown>)[GRAPH_DEF_BRAND] === true\n );\n}\n\n/**\n * Gets all node kind names from a GraphDef.\n */\nexport function getNodeKinds<G extends GraphDef>(\n graph: G,\n): readonly (keyof G[\"nodes\"] & string)[] {\n return Object.keys(graph.nodes) as (keyof G[\"nodes\"] & string)[];\n}\n\n/**\n * Gets all edge kind names from a GraphDef.\n */\nexport function getEdgeKinds<G extends GraphDef>(\n graph: G,\n): readonly (keyof G[\"edges\"] & string)[] {\n return Object.keys(graph.edges) as (keyof G[\"edges\"] & string)[];\n}\n","/**\n * Date encoding utilities for consistent storage.\n *\n * Contract: All dates are stored as ISO 8601 strings in UTC.\n * - Always includes milliseconds\n * - Always UTC (Z suffix)\n * - Sorts correctly as strings\n */\n\nimport { ValidationError } from \"../errors\";\n\n/**\n * ISO 8601 datetime pattern.\n * Matches formats like:\n * - 2024-01-15T10:30:00.000Z\n * - 2024-01-15T10:30:00Z\n * - 2024-01-15T10:30:00.123Z\n */\nconst ISO_DATE_PATTERN = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,3})?Z$/;\n\n/**\n * Checks if a string is a valid ISO 8601 datetime.\n *\n * @param value - String to validate\n * @returns True if valid ISO 8601 datetime\n */\nexport function isValidIsoDate(value: string): boolean {\n if (!ISO_DATE_PATTERN.test(value)) {\n return false;\n }\n // Also check that Date parsing produces a valid date\n const date = new Date(value);\n return !Number.isNaN(date.getTime());\n}\n\n/**\n * Validates that a string is a valid ISO 8601 datetime.\n * Throws ValidationError if invalid.\n *\n * @param value - String to validate\n * @param fieldName - Name of field for error message\n * @returns The validated string\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function validateIsoDate(value: string, fieldName: string): string {\n if (!isValidIsoDate(value)) {\n throw new ValidationError(\n `Invalid ISO 8601 datetime for \"${fieldName}\": \"${value}\". ` +\n `Expected format: YYYY-MM-DDTHH:mm:ss.sssZ`,\n {\n issues: [\n {\n path: fieldName,\n message: `Invalid ISO 8601 datetime format. Expected: YYYY-MM-DDTHH:mm:ss.sssZ, got: \"${value}\"`,\n },\n ],\n },\n {\n suggestion: `Use a valid ISO 8601 UTC datetime like \"2024-01-15T10:30:00.000Z\"`,\n },\n );\n }\n return value;\n}\n\n/**\n * Validates an optional ISO date string.\n * Returns undefined if value is undefined, otherwise validates.\n */\nexport function validateOptionalIsoDate(\n value: string | undefined,\n fieldName: string,\n): string | undefined {\n if (value === undefined) return undefined;\n return validateIsoDate(value, fieldName);\n}\n\n/**\n * Encodes a Date to an ISO 8601 string for storage.\n */\nexport function encodeDate(date: Date): string {\n return date.toISOString();\n}\n\n/**\n * Decodes an ISO 8601 string to a Date.\n * Validates the string format first.\n *\n * @throws ValidationError if not a valid ISO datetime\n */\nexport function decodeDate(isoString: string): Date {\n validateIsoDate(isoString, \"date\");\n return new Date(isoString);\n}\n\n/**\n * Returns the current timestamp as an ISO string.\n */\nexport function nowIso(): string {\n return new Date().toISOString();\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createNodeRowMapper, SQLITE_ROW_MAPPER_CONFIG, createEdgeRowMapper, createUniqueRowMapper, createSchemaVersionRowMapper, tables, createSqliteOperationStrategy, createCommonOperationBackend, nowIso,
|
|
1
|
+
import { createNodeRowMapper, SQLITE_ROW_MAPPER_CONFIG, createEdgeRowMapper, createUniqueRowMapper, createSchemaVersionRowMapper, tables, SQLITE_CAPABILITIES, createSqliteOperationStrategy, createCommonOperationBackend, nowIso, compileQueryWithDialect, dropSqliteVectorIndex, createSqliteVectorIndex } from './chunk-X3OXNIMH.js';
|
|
2
2
|
import { ConfigurationError } from './chunk-SJ2QMDXY.js';
|
|
3
3
|
import { getTableName, sql } from 'drizzle-orm';
|
|
4
4
|
|
|
@@ -14,6 +14,10 @@ function getSessionName(db) {
|
|
|
14
14
|
function isD1DatabaseBySessionName(db) {
|
|
15
15
|
return getSessionName(db) === "SQLiteD1Session";
|
|
16
16
|
}
|
|
17
|
+
function isDurableObjectBySessionName(db) {
|
|
18
|
+
const sessionName = getSessionName(db);
|
|
19
|
+
return sessionName === "SQLiteDurableObjectSession";
|
|
20
|
+
}
|
|
17
21
|
function isSyncDatabaseBySessionName(db) {
|
|
18
22
|
const sessionName = getSessionName(db);
|
|
19
23
|
return sessionName === "BetterSQLiteSession" || sessionName === "BunSQLiteSession";
|
|
@@ -36,11 +40,15 @@ function detectSyncProfile(db, profileHints) {
|
|
|
36
40
|
return isSyncDatabaseBySessionName(db);
|
|
37
41
|
}
|
|
38
42
|
}
|
|
39
|
-
function
|
|
40
|
-
if (profileHints.
|
|
41
|
-
return profileHints.
|
|
43
|
+
function detectTransactionMode(db, profileHints, isSync) {
|
|
44
|
+
if (profileHints.transactionMode !== void 0) {
|
|
45
|
+
return profileHints.transactionMode;
|
|
42
46
|
}
|
|
43
|
-
|
|
47
|
+
if (isD1DatabaseBySessionName(db) || isDurableObjectBySessionName(db)) {
|
|
48
|
+
return "none";
|
|
49
|
+
}
|
|
50
|
+
if (isSync) return "sql";
|
|
51
|
+
return "drizzle";
|
|
44
52
|
}
|
|
45
53
|
function resolveSqliteClient(db) {
|
|
46
54
|
const databaseWithClient = db;
|
|
@@ -89,30 +97,27 @@ function createSqliteExecutionAdapter(db, statementCacheMaxOrOptions = {}) {
|
|
|
89
97
|
const options = typeof statementCacheMaxOrOptions === "number" ? { statementCacheMax: statementCacheMaxOrOptions } : statementCacheMaxOrOptions;
|
|
90
98
|
const statementCacheMax = options.statementCacheMax ?? DEFAULT_PREPARED_STATEMENT_CACHE_MAX;
|
|
91
99
|
const profileHints = options.profileHints ?? {};
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
sqliteClient: resolveSqliteClient(db)
|
|
96
|
-
};
|
|
97
|
-
const supportsCompiledExecution = profileBase.isSync && !profileBase.isD1 && profileBase.sqliteClient !== void 0;
|
|
100
|
+
const isSync = detectSyncProfile(db, profileHints);
|
|
101
|
+
const sqliteClient = isSync ? resolveSqliteClient(db) : void 0;
|
|
102
|
+
const transactionMode = detectTransactionMode(db, profileHints, isSync);
|
|
98
103
|
const profile = {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
104
|
+
isSync,
|
|
105
|
+
supportsCompiledExecution: sqliteClient !== void 0,
|
|
106
|
+
transactionMode
|
|
102
107
|
};
|
|
103
108
|
const compile = (query) => compileQueryWithDialect(db, query, "SQLite");
|
|
104
|
-
if (
|
|
109
|
+
if (sqliteClient !== void 0) {
|
|
105
110
|
let executeCompiled2 = function(compiledQuery) {
|
|
106
111
|
const preparedStatement = getOrCreatePreparedStatement(
|
|
107
112
|
statementCache,
|
|
108
|
-
|
|
113
|
+
client,
|
|
109
114
|
compiledQuery.sql,
|
|
110
115
|
statementCacheMax
|
|
111
116
|
);
|
|
112
117
|
const rows = preparedStatement.all(...compiledQuery.params);
|
|
113
118
|
return Promise.resolve(rows);
|
|
114
119
|
};
|
|
115
|
-
const
|
|
120
|
+
const client = sqliteClient;
|
|
116
121
|
const statementCache = /* @__PURE__ */ new Map();
|
|
117
122
|
return {
|
|
118
123
|
clearStatementCache() {
|
|
@@ -126,7 +131,7 @@ function createSqliteExecutionAdapter(db, statementCacheMaxOrOptions = {}) {
|
|
|
126
131
|
executeCompiled: executeCompiled2,
|
|
127
132
|
prepare(sqlText) {
|
|
128
133
|
return createPreparedStatementExecutor(
|
|
129
|
-
|
|
134
|
+
client,
|
|
130
135
|
statementCache,
|
|
131
136
|
sqlText,
|
|
132
137
|
statementCacheMax
|
|
@@ -297,8 +302,8 @@ function createSqliteBackend(db, options = {}) {
|
|
|
297
302
|
const tables2 = options.tables ?? tables;
|
|
298
303
|
const profileHints = options.executionProfile ?? {};
|
|
299
304
|
const executionAdapter = createSqliteExecutionAdapter(db, { profileHints });
|
|
300
|
-
const {
|
|
301
|
-
const capabilities =
|
|
305
|
+
const { isSync, transactionMode } = executionAdapter.profile;
|
|
306
|
+
const capabilities = transactionMode === "none" ? { ...SQLITE_CAPABILITIES, transactions: false } : SQLITE_CAPABILITIES;
|
|
302
307
|
const tableNames = {
|
|
303
308
|
nodes: getTableName(tables2.nodes),
|
|
304
309
|
edges: getTableName(tables2.edges),
|
|
@@ -322,24 +327,24 @@ function createSqliteBackend(db, options = {}) {
|
|
|
322
327
|
});
|
|
323
328
|
},
|
|
324
329
|
async transaction(fn, _options) {
|
|
325
|
-
if (
|
|
330
|
+
if (transactionMode === "none") {
|
|
326
331
|
throw new ConfigurationError(
|
|
327
|
-
"
|
|
332
|
+
"This SQLite backend does not support atomic transactions. Operations within a transaction are not rolled back on failure. Use backend.capabilities.transactions to check for transaction support, or use individual operations with manual error handling.",
|
|
328
333
|
{
|
|
329
|
-
backend: "
|
|
334
|
+
backend: "sqlite",
|
|
330
335
|
capability: "transactions",
|
|
331
336
|
supportsTransactions: false
|
|
332
337
|
}
|
|
333
338
|
);
|
|
334
339
|
}
|
|
335
|
-
if (
|
|
340
|
+
if (transactionMode === "sql") {
|
|
336
341
|
return runWithSerializedQueue(serializedQueue, async () => {
|
|
337
342
|
const txBackend = createTransactionBackend({
|
|
338
343
|
capabilities,
|
|
339
344
|
db,
|
|
340
345
|
executionAdapter,
|
|
341
346
|
operationStrategy,
|
|
342
|
-
profileHints: {
|
|
347
|
+
profileHints: { isSync: true },
|
|
343
348
|
tableNames
|
|
344
349
|
});
|
|
345
350
|
db.run(sql`BEGIN`);
|
|
@@ -353,16 +358,19 @@ function createSqliteBackend(db, options = {}) {
|
|
|
353
358
|
}
|
|
354
359
|
});
|
|
355
360
|
}
|
|
356
|
-
return
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
361
|
+
return runWithSerializedQueue(
|
|
362
|
+
serializedQueue,
|
|
363
|
+
async () => db.transaction(async (tx) => {
|
|
364
|
+
const txBackend = createTransactionBackend({
|
|
365
|
+
capabilities,
|
|
366
|
+
db: tx,
|
|
367
|
+
operationStrategy,
|
|
368
|
+
profileHints: { isSync },
|
|
369
|
+
tableNames
|
|
370
|
+
});
|
|
371
|
+
return fn(txBackend);
|
|
372
|
+
})
|
|
373
|
+
);
|
|
366
374
|
},
|
|
367
375
|
async close() {
|
|
368
376
|
}
|
|
@@ -383,5 +391,5 @@ function createTransactionBackend(options) {
|
|
|
383
391
|
}
|
|
384
392
|
|
|
385
393
|
export { createSqliteBackend };
|
|
386
|
-
//# sourceMappingURL=chunk-
|
|
387
|
-
//# sourceMappingURL=chunk-
|
|
394
|
+
//# sourceMappingURL=chunk-KP2HKVXU.js.map
|
|
395
|
+
//# sourceMappingURL=chunk-KP2HKVXU.js.map
|