@nicia-ai/typegraph 0.38.0 → 0.39.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 (95) hide show
  1. package/dist/backend/postgres/index.cjs +16 -16
  2. package/dist/backend/postgres/index.js +3 -3
  3. package/dist/backend/postgres/pglite-store.cjs +11 -11
  4. package/dist/backend/postgres/pglite-store.d.cts +1 -1
  5. package/dist/backend/postgres/pglite-store.d.ts +1 -1
  6. package/dist/backend/postgres/pglite-store.js +8 -8
  7. package/dist/backend/postgres/pglite.cjs +5 -5
  8. package/dist/backend/postgres/pglite.js +4 -4
  9. package/dist/backend/sqlite/index.cjs +6 -6
  10. package/dist/backend/sqlite/index.js +3 -3
  11. package/dist/backend/sqlite/libsql.cjs +5 -5
  12. package/dist/backend/sqlite/libsql.js +3 -3
  13. package/dist/backend/sqlite/local-store.cjs +11 -11
  14. package/dist/backend/sqlite/local-store.d.cts +1 -1
  15. package/dist/backend/sqlite/local-store.d.ts +1 -1
  16. package/dist/backend/sqlite/local-store.js +9 -9
  17. package/dist/backend/sqlite/local.cjs +6 -6
  18. package/dist/backend/sqlite/local.js +4 -4
  19. package/dist/{chunk-UPXDVI3T.js → chunk-3SK4SVTW.js} +3 -3
  20. package/dist/{chunk-UPXDVI3T.js.map → chunk-3SK4SVTW.js.map} +1 -1
  21. package/dist/{chunk-NU23DUSJ.cjs → chunk-3YFDFOYB.cjs} +7 -7
  22. package/dist/{chunk-NU23DUSJ.cjs.map → chunk-3YFDFOYB.cjs.map} +1 -1
  23. package/dist/{chunk-NWYCOFEZ.cjs → chunk-5ELKD2FQ.cjs} +4 -4
  24. package/dist/chunk-5ELKD2FQ.cjs.map +1 -0
  25. package/dist/{chunk-2SL7OGPR.cjs → chunk-6SRLCSAV.cjs} +478 -338
  26. package/dist/chunk-6SRLCSAV.cjs.map +1 -0
  27. package/dist/{chunk-A2FGSWMQ.js → chunk-CBK2IVI2.js} +167 -27
  28. package/dist/chunk-CBK2IVI2.js.map +1 -0
  29. package/dist/{chunk-TE5ZA4VX.js → chunk-DOKUXLFH.js} +14 -10
  30. package/dist/chunk-DOKUXLFH.js.map +1 -0
  31. package/dist/{chunk-KCLZHYPU.cjs → chunk-E2Q7SP2K.cjs} +52 -52
  32. package/dist/{chunk-KCLZHYPU.cjs.map → chunk-E2Q7SP2K.cjs.map} +1 -1
  33. package/dist/{chunk-YLINFV7Z.cjs → chunk-GKQU44SQ.cjs} +67 -63
  34. package/dist/chunk-GKQU44SQ.cjs.map +1 -0
  35. package/dist/{chunk-O5H62ZWJ.cjs → chunk-HP6LWBLB.cjs} +14 -2
  36. package/dist/chunk-HP6LWBLB.cjs.map +1 -0
  37. package/dist/{chunk-7VLCN3JB.cjs → chunk-HTQOBY75.cjs} +59 -59
  38. package/dist/{chunk-7VLCN3JB.cjs.map → chunk-HTQOBY75.cjs.map} +1 -1
  39. package/dist/{chunk-RQPRCEIO.js → chunk-IFDXG2YJ.js} +3 -3
  40. package/dist/chunk-IFDXG2YJ.js.map +1 -0
  41. package/dist/{chunk-YJDSPA5E.js → chunk-IFRPHG7O.js} +4 -4
  42. package/dist/{chunk-YJDSPA5E.js.map → chunk-IFRPHG7O.js.map} +1 -1
  43. package/dist/{chunk-LZ3TVJY4.cjs → chunk-JD2YC62H.cjs} +17 -17
  44. package/dist/{chunk-LZ3TVJY4.cjs.map → chunk-JD2YC62H.cjs.map} +1 -1
  45. package/dist/{chunk-XD6X7O5R.js → chunk-KAFXPB2L.js} +4 -4
  46. package/dist/{chunk-XD6X7O5R.js.map → chunk-KAFXPB2L.js.map} +1 -1
  47. package/dist/{chunk-ZHX4KEM7.cjs → chunk-KIZSHRUI.cjs} +7 -7
  48. package/dist/{chunk-ZHX4KEM7.cjs.map → chunk-KIZSHRUI.cjs.map} +1 -1
  49. package/dist/{chunk-G32AO634.js → chunk-KXFUQNF2.js} +3 -3
  50. package/dist/{chunk-G32AO634.js.map → chunk-KXFUQNF2.js.map} +1 -1
  51. package/dist/{chunk-E6YZRKMM.js → chunk-NQBYTLPW.js} +4 -4
  52. package/dist/{chunk-E6YZRKMM.js.map → chunk-NQBYTLPW.js.map} +1 -1
  53. package/dist/{chunk-VBH7ZXSZ.js → chunk-SU7VQOJ3.js} +3 -3
  54. package/dist/{chunk-VBH7ZXSZ.js.map → chunk-SU7VQOJ3.js.map} +1 -1
  55. package/dist/{chunk-KFLXWVUJ.js → chunk-UUIBACKJ.js} +14 -3
  56. package/dist/chunk-UUIBACKJ.js.map +1 -0
  57. package/dist/{chunk-CQC6VBAF.cjs → chunk-VXAFOF6Z.cjs} +5 -5
  58. package/dist/{chunk-CQC6VBAF.cjs.map → chunk-VXAFOF6Z.cjs.map} +1 -1
  59. package/dist/{chunk-XFY73JWD.cjs → chunk-Y6UA55YS.cjs} +5 -5
  60. package/dist/{chunk-XFY73JWD.cjs.map → chunk-Y6UA55YS.cjs.map} +1 -1
  61. package/dist/{chunk-6G5CQ6JX.js → chunk-YPUNPG2T.js} +4 -4
  62. package/dist/{chunk-6G5CQ6JX.js.map → chunk-YPUNPG2T.js.map} +1 -1
  63. package/dist/graph-merge/index.cjs +30 -32
  64. package/dist/graph-merge/index.cjs.map +1 -1
  65. package/dist/graph-merge/index.d.cts +10 -5
  66. package/dist/graph-merge/index.d.ts +10 -5
  67. package/dist/graph-merge/index.js +9 -11
  68. package/dist/graph-merge/index.js.map +1 -1
  69. package/dist/index.cjs +68 -68
  70. package/dist/index.d.cts +2 -2
  71. package/dist/index.d.ts +2 -2
  72. package/dist/index.js +5 -5
  73. package/dist/interchange/index.cjs +23 -23
  74. package/dist/interchange/index.d.cts +1 -1
  75. package/dist/interchange/index.d.ts +1 -1
  76. package/dist/interchange/index.js +4 -4
  77. package/dist/profiler/index.d.cts +1 -1
  78. package/dist/profiler/index.d.ts +1 -1
  79. package/dist/provenance/index.cjs +11 -11
  80. package/dist/provenance/index.d.cts +1 -1
  81. package/dist/provenance/index.d.ts +1 -1
  82. package/dist/provenance/index.js +2 -2
  83. package/dist/schema/index.cjs +22 -22
  84. package/dist/schema/index.js +3 -3
  85. package/dist/{store-view-BoHqdHjB.d.cts → store-view-BJd6Vwpt.d.cts} +39 -17
  86. package/dist/{store-view-Ctq-3OHy.d.ts → store-view-CLIhwMMX.d.ts} +39 -17
  87. package/package.json +1 -1
  88. package/dist/chunk-2SL7OGPR.cjs.map +0 -1
  89. package/dist/chunk-A2FGSWMQ.js.map +0 -1
  90. package/dist/chunk-KFLXWVUJ.js.map +0 -1
  91. package/dist/chunk-NWYCOFEZ.cjs.map +0 -1
  92. package/dist/chunk-O5H62ZWJ.cjs.map +0 -1
  93. package/dist/chunk-RQPRCEIO.js.map +0 -1
  94. package/dist/chunk-TE5ZA4VX.js.map +0 -1
  95. package/dist/chunk-YLINFV7Z.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/backend/drizzle/execution/sqlite-execution.ts","../src/backend/drizzle/sqlite.ts"],"names":["sql","DURABLE_OBJECT_MAX_BIND_PARAMETERS","D1_MAX_BIND_PARAMETERS","SQLITE_MAX_BIND_PARAMETERS","MODERN_SQLITE_MAX_BIND_PARAMETERS","getOrCreateLru","compileQueryWithDialect","executeCompiled","executeCompiledRun","executePreparedRunBatch","isSqlFragment","toDrizzleSql","EMBEDDING_UPSERT_PARAM_COUNT","createNodeRowMapper","SQLITE_ROW_MAPPER_CONFIG","createEdgeRowMapper","createUniqueRowMapper","createSchemaVersionRowMapper","ConfigurationError","BackendDisposedError","SQLITE_CAPABILITIES","buildFulltextCapabilities","buildVectorCapabilities","rows","createCommonOperationBackend","nowIso","vectorSlotFromParams","mapVectorWriteError","chunk","assertVectorSearchLimit","buildLiveNodeCandidates","mapHybridSearchRow","vectorSlotFromCreateIndexParams","vectorSlotFromDropIndexParams","isMissingTableError","coerceNumericScore","tables","fts5Strategy","normalizeGraphAnalyticsCapabilities","getTableName","createSqliteOperationStrategy","generateSqliteCreateTableSQL","and","eq","mapContributionMaterializationRow","SQLITE_CONTRIBUTION_MAT_TIMESTAMPS","buildContributionInsertValues","buildContributionOnConflictSet","createContributionMaterializer","gateFulltext","assertTrustedImportDatabaseEmpty","suspendSqliteSecondaryIndexes","createSqliteTrustedImportSession","restoreSecondaryIndexes","analyzeImportedTables","generateSqliteDDL","gateFulltextMethods","mapMaterializationRow","SQLITE_INDEX_MAT_TIMESTAMPS","inArray","buildMaterializationInsertValues","buildMaterializationOnConflictSet","isNull","mapKindRemovalRow","SQLITE_KIND_REMOVAL_TIMESTAMPS","buildKindRemovalInsertValues","buildKindRemovalOnConflictSet","isSqliteNotAuthorizedError","options","INTERNAL_TEMPORARY_WRITES","assertAdoptedDialect","BaseSQLiteDatabase"],"mappings":";;;;;;;;;;;;;;;AAoBA,IAAM,oCAAA,GAAuC,GAAA;AA8H7C,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;AAIrC,EAAA,OACE,WAAA,KAAgB,qBAChB,WAAA,KAAgB,4BAAA;AAEpB;AAEA,SAAS,6BACP,KAAA,EACqC;AACrC,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,MAAM,OAAO,KAAA;AACxD,EAAA,MAAM,SAAA,GAAY,KAAA;AAClB,EAAA,MAAM,MAAA,GAAS,UAAU,KAAK,CAAA;AAC9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A,CAAQ,iBAAA;AAAA,IAC3B,YAAY,OAAA,CAAQ,UAAA;AAAA,IACpB,kBAAkB,OAAA,CAAQ,gBAAA;AAAA,IAC1B,gBAAgB,OAAA,CAAQ,cAAA;AAAA,IACxB,0BAA0B,OAAA,CAAQ;AAAA,GACnC,CAAA;AACH","file":"chunk-GKQU44SQ.cjs","sourcesContent":["import { type SQL as DrizzleSql, sql } from \"drizzle-orm\";\nimport { type BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\nimport { isSqlFragment } from \"../../../query/sql-fragment\";\nimport {\n D1_MAX_BIND_PARAMETERS,\n DURABLE_OBJECT_MAX_BIND_PARAMETERS,\n MODERN_SQLITE_MAX_BIND_PARAMETERS,\n SQLITE_MAX_BIND_PARAMETERS,\n} from \"../../types\";\nimport { getOrCreateLru } from \"./lru\";\nimport {\n type CompiledSqlQuery,\n compileQueryWithDialect,\n type ExecutableSql,\n type PreparedSqlStatement,\n type SqlExecutionAdapter,\n toDrizzleSql,\n} from \"./types\";\n\nconst DEFAULT_PREPARED_STATEMENT_CACHE_MAX = 256;\n\ntype PreparedAllStatement = Readonly<{\n all: (...params: readonly unknown[]) => readonly unknown[];\n /**\n * Executes a statement that returns no rows. better-sqlite3 and\n * bun:sqlite both expose it; better-sqlite3 additionally REQUIRES it for\n * non-reader statements (`all()` on those throws).\n */\n run?: (...params: readonly unknown[]) => unknown;\n /**\n * better-sqlite3's \"does this statement return rows\" flag. bun:sqlite\n * has no equivalent; `undefined` is treated as non-reader on the run\n * path (bun's `run()` accepts any statement).\n */\n reader?: boolean;\n}>;\n\ntype SqliteClientWithPrepare = Readonly<{\n prepare: (sqlText: string) => PreparedAllStatement;\n}>;\n\ntype SqliteClientCarrier = Readonly<{ $client?: unknown }>;\n\ntype DurableObjectSqlApi = Readonly<{\n exec: (...args: readonly unknown[]) => unknown;\n}>;\n\n/**\n * Runtime shape of the Durable Object storage client exposed as\n * `drizzle(ctx.storage).$client`. Structural because Drizzle does not export\n * this client type and constructor names are not stable under bundling.\n */\nexport type DurableObjectStorageClient = Readonly<{\n sql: DurableObjectSqlApi;\n transaction: <Result>(run: () => Promise<Result>) => Promise<Result>;\n transactionSync: <Result>(run: () => Result) => Result;\n}>;\n\ntype SqliteHostedPlatform = \"d1\" | \"durable-object\";\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 on\n * the connection. Default for sync drivers (better-sqlite3,\n * bun:sqlite); also selected by `createLibsqlBackend` for\n * local `@libsql/client` connections (`file:` / `:memory:`),\n * whose `client.transaction()` permanently abandons the\n * current connection — fatal for an in-memory database.\n * - `\"drizzle\"`: Delegates to Drizzle's `db.transaction()` method.\n * Default for async drivers (remote libsql/Turso, sql.js).\n * - `\"do-sqlite\"`: Delegates to the Cloudflare Durable Objects async\n * storage transaction runner (`db.$client.transaction`,\n * i.e. `ctx.storage.transaction(async ...)`). Drizzle's\n * own `db.transaction()` on DO is\n * `ctx.storage.transactionSync` and cannot span `await`,\n * so it is deliberately not used. Auto-detected for\n * `drizzle(ctx.storage)` (#140).\n * - `\"none\"`: Transactions disabled. Default for Cloudflare D1\n * (`D1Database.batch` is transactional but not an\n * interactive runner — tracked separately).\n */\nexport type SqliteTransactionMode = \"sql\" | \"drizzle\" | \"none\" | \"do-sqlite\";\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 /** Hosted runtime detected independently of caller-supplied hints. */\n hostedPlatform?: SqliteHostedPlatform;\n /** Platform ceiling that capability overrides may lower but never raise. */\n hardMaxBindParameters?: number;\n isSync: boolean;\n /**\n * Detected per-statement bound-parameter ceiling for this connection:\n * Cloudflare's documented D1 / Durable Objects cap, the probed\n * `SQLITE_MAX_VARIABLE_NUMBER` on synchronous drivers, or the conservative\n * 999 floor when the limit cannot be probed (async/remote drivers).\n */\n maxBindParameters: number;\n supportsCompiledExecution: boolean;\n transactionMode: SqliteTransactionMode;\n}>;\n\nexport type SqliteExecutionAdapter = Readonly<\n SqlExecutionAdapter & {\n clearStatementCache: () => void;\n profile: SqliteExecutionProfile;\n /**\n * Executes a compiled statement that returns no rows through the\n * prepared-statement cache. Present only on synchronous drivers with a\n * preparable client — the CRUD write path falls back to drizzle's\n * `db.run()` when absent.\n */\n executeCompiledRun?: (compiledQuery: CompiledSqlQuery) => Promise<void>;\n /** Rebinds one cached non-reader statement for every parameter row. */\n executePreparedRunBatch?: (\n sqlText: string,\n params: readonly (readonly unknown[])[],\n ) => Promise<void>;\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 // drizzle-orm/durable-sqlite's session class is `SQLiteDOSession`\n // (verified drizzle 0.45.x). `SQLiteDurableObjectSession` is kept as\n // a defensive alias against future drizzle renames.\n return (\n sessionName === \"SQLiteDOSession\" ||\n sessionName === \"SQLiteDurableObjectSession\"\n );\n}\n\nfunction isDurableObjectStorageClient(\n value: unknown,\n): value is DurableObjectStorageClient {\n if (typeof value !== \"object\" || value === null) return false;\n const candidate = value as Record<string, unknown>;\n const sqlApi = candidate[\"sql\"];\n return (\n typeof candidate[\"transaction\"] === \"function\" &&\n typeof candidate[\"transactionSync\"] === \"function\" &&\n typeof sqlApi === \"object\" &&\n sqlApi !== null &&\n typeof (sqlApi as Record<string, unknown>)[\"exec\"] === \"function\"\n );\n}\n\n/**\n * Returns the real Durable Object storage client when the Drizzle connection\n * exposes its distinctive async + sync transaction runners and SQL API.\n * Requiring the full shape avoids mistaking better-sqlite3's transaction\n * wrapper factory for the Durable Object async runner.\n */\nexport function getDurableObjectStorageClient(\n db: AnySqliteDatabase,\n): DurableObjectStorageClient | undefined {\n const client = (db as SqliteClientCarrier).$client;\n return isDurableObjectStorageClient(client) ? client : undefined;\n}\n\nfunction detectHostedPlatform(\n db: AnySqliteDatabase,\n): SqliteHostedPlatform | undefined {\n if (\n getDurableObjectStorageClient(db) !== undefined ||\n isDurableObjectBySessionName(db)\n ) {\n return \"durable-object\";\n }\n if (isD1DatabaseBySessionName(db)) return \"d1\";\n return undefined;\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 hostedPlatform: SqliteHostedPlatform | undefined,\n): boolean {\n if (hostedPlatform === \"durable-object\") return true;\n if (hostedPlatform === \"d1\") return false;\n if (profileHints.isSync !== undefined) {\n return profileHints.isSync;\n }\n\n const sessionName = getSessionName(db);\n if (\n sessionName === \"BetterSQLiteSession\" ||\n sessionName === \"BunSQLiteSession\"\n ) {\n return true;\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 profileHints: SqliteExecutionProfileHints,\n isSync: boolean,\n hostedPlatform: SqliteHostedPlatform | undefined,\n): SqliteTransactionMode {\n // Hosted platform identity is authoritative. A stale hint must not disable\n // Durable Object rollback or opt D1 into unsupported interactive writes.\n if (hostedPlatform === \"durable-object\") return \"do-sqlite\";\n if (hostedPlatform === \"d1\") return \"none\";\n if (profileHints.transactionMode !== undefined) {\n return profileHints.transactionMode;\n }\n // Neither D1 nor Durable Object SQLite supports raw BEGIN/COMMIT SQL\n // through Drizzle's db.run(), and Drizzle's own db.transaction() on\n // Durable Objects is `ctx.storage.transactionSync` (cannot span an\n // await). Durable Objects expose an async storage transaction runner\n // (`ctx.storage.transaction(async ...)`, surfaced by Drizzle as\n // `db.$client.transaction`) — route those through \"do-sqlite\" (#140).\n // D1 has no equivalent interactive runner (only batch); it stays\n // \"none\" pending a separate batch-mode investigation.\n if (isSync) return \"sql\";\n return \"drizzle\";\n}\n\n// SQLITE_MAX_VARIABLE_NUMBER's compiled-in default rose from 999 to 32,766\n// in SQLite 3.32.0. Builds that override the default list it in\n// `PRAGMA compile_options`; builds that keep it do not, so the version\n// decides the fallback.\nconst MAX_VARIABLE_NUMBER_COMPILE_OPTION = /^MAX_VARIABLE_NUMBER=(\\d+)$/;\nconst FIRST_MODERN_BIND_LIMIT_MAJOR = 3;\nconst FIRST_MODERN_BIND_LIMIT_MINOR = 32;\n\nfunction parseCompiledMaxVariableNumber(\n rows: readonly unknown[],\n): number | undefined {\n for (const row of rows) {\n if (typeof row !== \"object\" || row === null) continue;\n const option = (row as Record<string, unknown>)[\"compile_options\"];\n if (typeof option !== \"string\") continue;\n const match = MAX_VARIABLE_NUMBER_COMPILE_OPTION.exec(option);\n if (match !== null) return Number(match[1]);\n }\n return undefined;\n}\n\nfunction hasModernBindLimitByVersion(rows: readonly unknown[]): boolean {\n const first = rows[0];\n if (typeof first !== \"object\" || first === null) return false;\n const version = (first as Record<string, unknown>)[\"version\"];\n if (typeof version !== \"string\") return false;\n const [major = 0, minor = 0] = version.split(\".\").map(Number);\n if (!Number.isFinite(major) || !Number.isFinite(minor)) return false;\n return (\n major > FIRST_MODERN_BIND_LIMIT_MAJOR ||\n (major === FIRST_MODERN_BIND_LIMIT_MAJOR &&\n minor >= FIRST_MODERN_BIND_LIMIT_MINOR)\n );\n}\n\n/**\n * Resolves the connection's per-statement bound-parameter ceiling. Batch\n * chunk math derives from this value, so too high breaks batched writes at\n * runtime and too low wastes round trips (999 vs 32,766 is ~33× more\n * chunks per bulk insert).\n */\nfunction detectHardMaxBindParameters(\n transactionMode: SqliteTransactionMode,\n hostedPlatform: SqliteHostedPlatform | undefined,\n): number | undefined {\n if (hostedPlatform === \"durable-object\" || transactionMode === \"do-sqlite\") {\n return DURABLE_OBJECT_MAX_BIND_PARAMETERS;\n }\n if (hostedPlatform === \"d1\") return D1_MAX_BIND_PARAMETERS;\n return undefined;\n}\n\nfunction detectMaxBindParameters(\n sqliteClient: SqliteClientWithPrepare | undefined,\n hardMaxBindParameters: number | undefined,\n): number {\n if (hardMaxBindParameters !== undefined) return hardMaxBindParameters;\n if (sqliteClient === undefined) return SQLITE_MAX_BIND_PARAMETERS;\n try {\n const compiled = parseCompiledMaxVariableNumber(\n sqliteClient.prepare(\"PRAGMA compile_options\").all(),\n );\n if (compiled !== undefined) return compiled;\n const isModern = hasModernBindLimitByVersion(\n sqliteClient.prepare(\"SELECT sqlite_version() AS version\").all(),\n );\n return isModern ?\n MODERN_SQLITE_MAX_BIND_PARAMETERS\n : SQLITE_MAX_BIND_PARAMETERS;\n } catch {\n // A client that can't answer the probes keeps the conservative floor.\n return SQLITE_MAX_BIND_PARAMETERS;\n }\n}\n\nfunction resolveSqliteClient(\n db: AnySqliteDatabase,\n): SqliteClientWithPrepare | undefined {\n const sqliteClient = (db as SqliteClientCarrier).$client;\n if (typeof sqliteClient !== \"object\" || sqliteClient === null) return;\n const candidate = sqliteClient as Record<string, unknown>;\n if (typeof candidate[\"prepare\"] !== \"function\") return;\n return sqliteClient as SqliteClientWithPrepare;\n}\n\nfunction getOrCreatePreparedStatement(\n cache: Map<string, PreparedAllStatement>,\n sqliteClient: SqliteClientWithPrepare,\n sqlText: string,\n cacheMax: number,\n): PreparedAllStatement {\n return getOrCreateLru(cache, sqlText, cacheMax, () =>\n sqliteClient.prepare(sqlText),\n );\n}\n\n// Uses unconditional `await` because Drizzle returns SQLiteRaw thenables\n// that fail `instanceof Promise` checks (drizzle-team/drizzle-orm#2275).\nasync function executeDrizzleQuery<TRow>(\n db: AnySqliteDatabase,\n query: DrizzleSql,\n): Promise<readonly TRow[]> {\n return await db.all(query);\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 hostedPlatform = detectHostedPlatform(db);\n const isSync = detectSyncProfile(db, profileHints, hostedPlatform);\n const sqliteClient = isSync ? resolveSqliteClient(db) : undefined;\n const transactionMode = detectTransactionMode(\n profileHints,\n isSync,\n hostedPlatform,\n );\n const hardMaxBindParameters = detectHardMaxBindParameters(\n transactionMode,\n hostedPlatform,\n );\n const maxBindParameters = detectMaxBindParameters(\n sqliteClient,\n hardMaxBindParameters,\n );\n\n const profile: SqliteExecutionProfile = {\n ...(hostedPlatform === undefined ? {} : { hostedPlatform }),\n ...(hardMaxBindParameters === undefined ? {} : { hardMaxBindParameters }),\n isSync,\n maxBindParameters,\n supportsCompiledExecution: sqliteClient !== undefined,\n transactionMode,\n };\n\n const compile = (query: ExecutableSql): 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 function executeCompiledRun(\n compiledQuery: CompiledSqlQuery,\n ): Promise<void> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n client,\n compiledQuery.sql,\n statementCacheMax,\n );\n // better-sqlite3 rejects run() on reader statements and all() on\n // non-reader statements, so pick by the statement's own flag; a\n // client without run() (or without the reader flag but returning\n // rows) drains through all() and discards.\n if (\n preparedStatement.run === undefined ||\n preparedStatement.reader === true\n ) {\n preparedStatement.all(...compiledQuery.params);\n } else {\n preparedStatement.run(...compiledQuery.params);\n }\n return Promise.resolve();\n }\n\n function executePreparedRunBatch(\n sqlText: string,\n parameterRows: readonly (readonly unknown[])[],\n ): Promise<void> {\n const preparedStatement = getOrCreatePreparedStatement(\n statementCache,\n client,\n sqlText,\n statementCacheMax,\n );\n if (preparedStatement.run === undefined) {\n throw new Error(\n \"Trusted SQLite import requires a prepared statement run() method.\",\n );\n }\n for (const params of parameterRows) {\n preparedStatement.run(...params);\n }\n return Promise.resolve();\n }\n\n return {\n clearStatementCache() {\n statementCache.clear();\n },\n compile,\n execute<TRow>(query: ExecutableSql): Promise<readonly TRow[]> {\n const compiledQuery = compile(query);\n return executeCompiled<TRow>(compiledQuery);\n },\n executeCompiled,\n executeCompiledRun,\n executePreparedRunBatch,\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: ExecutableSql): Promise<readonly TRow[]> {\n return executeDrizzleQuery<TRow>(\n db,\n isSqlFragment(query) ? toDrizzleSql(query, \"sqlite\") : query,\n );\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/adapters/drizzle/sqlite\";\n *\n * const sqlite = new Database(\"app.db\");\n * const db = drizzle(sqlite);\n * const backend = createSqliteBackend(db, { tables });\n * ```\n */\nimport {\n and,\n eq,\n getTableName,\n inArray,\n isNull,\n type SQL,\n sql,\n} from \"drizzle-orm\";\nimport { BaseSQLiteDatabase } from \"drizzle-orm/sqlite-core\";\n\nimport { BackendDisposedError, ConfigurationError } from \"../../errors\";\nimport type { ResolvedSqlTableNames } from \"../../query/compiler/schema\";\nimport {\n buildFulltextCapabilities,\n fts5Strategy,\n type FulltextStrategy,\n} from \"../../query/dialect/fulltext-strategy\";\nimport {\n assertVectorSearchLimit,\n buildVectorCapabilities,\n type VectorSlot,\n type VectorStrategy,\n} from \"../../query/dialect/vector-strategy\";\nimport {\n isSqlFragment,\n sql as portableSql,\n type SqlFragment,\n} from \"../../query/sql-fragment\";\nimport { type CompiledRowsSql } from \"../../query/sql-intent\";\nimport { chunk as chunkArray } from \"../../utils/array\";\nimport {\n isMissingTableError,\n isSqliteNotAuthorizedError,\n} from \"../../utils/sql-errors\";\nimport { buildLiveNodeCandidates } from \"../live-node-candidates\";\nimport {\n type AdapterBackend,\n type BackendCapabilities,\n type CommitSchemaVersionParams,\n type ContributionMaterializationIdentity,\n type ContributionMaterializationRow,\n type CreateVectorIndexParams,\n type DeleteEmbeddingParams,\n type DeleteFulltextBatchParams,\n type DeleteFulltextParams,\n type DropVectorIndexParams,\n type FulltextSearchParams,\n type FulltextSearchResult,\n type GraphAnalyticsCapabilities,\n type GraphBackend,\n type HybridSearchParams,\n type HybridSearchRow,\n type IndexMaterializationRow,\n INTERNAL_TEMPORARY_WRITES,\n type InternalTransactionOptions,\n type KindRemovalRow,\n normalizeGraphAnalyticsCapabilities,\n type RecordContributionMaterializationParams,\n type RecordIndexMaterializationParams,\n type RecordKindRemovalParams,\n type SchemaVersionRow,\n type SetActiveVersionParams,\n SQLITE_CAPABILITIES,\n SQLITE_MAX_BIND_PARAMETERS,\n type TransactionBackend,\n type TrustedImportSession,\n type UpsertEmbeddingBatchParams,\n type UpsertEmbeddingParams,\n type UpsertFulltextBatchParams,\n type UpsertFulltextParams,\n type VectorSearchParams,\n type VectorSearchResult,\n} from \"../types\";\nimport {\n type AnySqliteDatabase,\n createSqliteExecutionAdapter,\n getDurableObjectStorageClient,\n type SqliteExecutionAdapter,\n type SqliteExecutionProfile,\n type SqliteExecutionProfileHints,\n} from \"./execution/sqlite-execution\";\nimport { type ExecutableSql, toDrizzleSql } from \"./execution/types\";\nimport {\n EMBEDDING_UPSERT_PARAM_COUNT,\n mapVectorWriteError,\n vectorSlotFromCreateIndexParams,\n vectorSlotFromDropIndexParams,\n vectorSlotFromParams,\n} from \"./vector-runtime\";\nexport type { SqliteTransactionMode } from \"./execution/sqlite-execution\";\nimport {\n coerceNumericScore,\n createEdgeRowMapper,\n createNodeRowMapper,\n createSchemaVersionRowMapper,\n createUniqueRowMapper,\n nowIso,\n SQLITE_ROW_MAPPER_CONFIG,\n} from \"../row-mappers\";\nimport {\n buildContributionInsertValues,\n buildContributionOnConflictSet,\n type ContributionMaterializer,\n createContributionMaterializer,\n gateFulltext,\n gateFulltextMethods,\n mapContributionMaterializationRow,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS,\n} from \"./contribution-materializations\";\nimport { generateSqliteCreateTableSQL, generateSqliteDDL } from \"./ddl\";\nimport {\n buildMaterializationInsertValues,\n buildMaterializationOnConflictSet,\n mapMaterializationRow,\n SQLITE_INDEX_MAT_TIMESTAMPS,\n} from \"./index-materializations\";\nimport {\n buildKindRemovalInsertValues,\n buildKindRemovalOnConflictSet,\n mapKindRemovalRow,\n SQLITE_KIND_REMOVAL_TIMESTAMPS,\n} from \"./kind-removals\";\nimport {\n assertAdoptedDialect,\n type CommonOperationBackend,\n createCommonOperationBackend,\n type InternalOperationBackend,\n} from \"./operation-backend-core\";\nimport { mapHybridSearchRow } from \"./operations/hybrid\";\nimport { createSqliteOperationStrategy } from \"./operations/strategy\";\nimport { type SqliteTables, tables as defaultTables } from \"./schema/sqlite\";\nimport {\n analyzeImportedTables,\n assertTrustedImportDatabaseEmpty,\n createSqliteTrustedImportSession,\n restoreSecondaryIndexes,\n suspendSqliteSecondaryIndexes,\n} from \"./trusted-import\";\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 without transactions (e.g.\n * Cloudflare D1). Durable Objects (`drizzle(ctx.storage)`) auto-detect\n * `transactionMode: \"do-sqlite\"` and do not need a hint. Hosted platform\n * identity is authoritative when it conflicts with a stale hint.\n */\n executionProfile?: SqliteExecutionProfileHints;\n /**\n * Fulltext strategy override. Defaults to `fts5Strategy` (SQLite's\n * built-in FTS5 virtual table). Most users should leave this alone.\n */\n fulltext?: FulltextStrategy;\n /**\n * Vector strategy override. When present, the backend owns per-`(kind,\n * field)` typed storage through this strategy (DDL, upsert, delete,\n * similarity search, ANN index lifecycle) and advertises\n * `strategy.capabilities` as `capabilities.vector`. `createLibsqlBackend`\n * passes `libsqlVectorStrategy` unconditionally; `createLocalSqliteBackend`\n * passes `sqliteVecStrategy` when the extension loads. When absent the\n * backend exposes no vector capability and embedding values pass through\n * writes without being indexed — matching existing behavior for SQLite\n * connections without a vector extension.\n */\n vector?: VectorStrategy;\n /**\n * Override specific backend capabilities. Useful for custom SQLite builds\n * or tests that need to simulate an engine-level capability gap. Overrides\n * may lower, but cannot raise, a hosted platform's hard parameter ceiling.\n */\n capabilities?: Partial<BackendCapabilities>;\n}>;\n\nconst NODE_INSERT_PARAM_COUNT = 9;\nconst EDGE_INSERT_PARAM_COUNT = 12;\nconst GET_NODES_FIXED_PARAM_COUNT = 2;\nconst GET_EDGES_FIXED_PARAM_COUNT = 1;\nconst CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT = 3;\nconst FULLTEXT_UPSERT_PARAM_COUNT = 6;\nconst FULLTEXT_DELETE_FIXED_PARAM_COUNT = 2;\nconst UNIQUE_INSERT_PARAM_COUNT = 6;\n\n/**\n * `PRAGMA analysis_limit` value `refreshStatistics()` sets before running\n * `ANALYZE`. Unlike Postgres (whose `ANALYZE` always examines a bounded\n * sample sized off `default_statistics_target`), SQLite's `ANALYZE`\n * defaults to a full table/index scan — O(table size) per call. A caller\n * streaming a bulk load through repeated `bulkInsert()` calls (the only\n * practical pattern for a multi-million-row load) re-triggers\n * `refreshStatistics()` on every batch once that batch's row count crosses\n * `AUTO_REFRESH_STATISTICS_ROW_THRESHOLD`; without this bound, per-call\n * cost grows with total table size, integrating to O(n²) total load time.\n * 1000 is SQLite's own documented suggestion for large databases.\n */\nexport const SQLITE_ANALYZE_ROW_LIMIT = 1000;\n\n/**\n * Batch chunk sizes for the SQLite operation backend, derived from the\n * connection's bound-parameter budget. Keys mirror the operation backend's\n * `batchConfig`.\n */\nexport type SqliteBatchChunkSizes = Readonly<{\n checkUniqueBatchChunkSize: number;\n edgeInsertBatchSize: number;\n /** Rows per embedding batch upsert (5 binds per row). */\n embeddingUpsertBatchSize: number;\n /** Rows per fulltext batch upsert (6 binds per row on FTS5). */\n fulltextUpsertBatchSize: number;\n /** Node ids per fulltext batch delete (2 fixed binds + one per id). */\n fulltextDeleteChunkSize: number;\n getEdgesChunkSize: number;\n getNodesChunkSize: number;\n nodeInsertBatchSize: number;\n uniqueInsertBatchSize: number;\n}>;\n\n/**\n * Derives batch chunk sizes from a per-statement bound-parameter budget.\n * The budget varies by driver — better-sqlite3 compiles in 32,766, D1 caps\n * at ~100, undetectable async drivers keep the 999 floor — so chunk math is\n * computed per backend instance rather than fixed at module scope.\n */\nexport function computeSqliteBatchChunkSizes(\n maxBindParameters: number,\n): SqliteBatchChunkSizes {\n return {\n checkUniqueBatchChunkSize: Math.max(\n 1,\n maxBindParameters - CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT,\n ),\n embeddingUpsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / EMBEDDING_UPSERT_PARAM_COUNT),\n ),\n fulltextUpsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / FULLTEXT_UPSERT_PARAM_COUNT),\n ),\n fulltextDeleteChunkSize: Math.max(\n 1,\n maxBindParameters - FULLTEXT_DELETE_FIXED_PARAM_COUNT,\n ),\n edgeInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / EDGE_INSERT_PARAM_COUNT),\n ),\n getEdgesChunkSize: Math.max(\n 1,\n maxBindParameters - GET_EDGES_FIXED_PARAM_COUNT,\n ),\n getNodesChunkSize: Math.max(\n 1,\n maxBindParameters - GET_NODES_FIXED_PARAM_COUNT,\n ),\n nodeInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / NODE_INSERT_PARAM_COUNT),\n ),\n uniqueInsertBatchSize: Math.max(\n 1,\n Math.floor(maxBindParameters / UNIQUE_INSERT_PARAM_COUNT),\n ),\n };\n}\n\ntype SerializedExecutionQueue = Readonly<{\n dispose: () => void;\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(\n SQLITE_ROW_MAPPER_CONFIG,\n);\n\n/** A shared promise that never settles — used to absorb post-dispose work. */\nconst PENDING_FOREVER: Promise<never> = new Promise<never>(noop);\n\nfunction pendingForever<T>(): Promise<T> {\n return PENDING_FOREVER;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nfunction noop(): void {}\n\n/**\n * Tracks which serialized queue (if any) the current async execution is\n * running a task for, so a re-entrant submission — a root-backend operation\n * awaited from inside a transaction already occupying the same queue — can be\n * rejected with a typed error instead of deadlocking (the enclosing task holds\n * the queue slot until it completes, so the inner operation can never run).\n *\n * AsyncLocalStorage is loaded lazily and optionally: it is available on Node\n * and on Cloudflare workers with the `nodejs_als` compatibility flag, and a\n * runtime without it simply skips the detection (the queue behaves as before).\n */\ntype QueueTaskContext = Readonly<{\n getStore: () => unknown;\n run: <T>(store: object, callback: () => T) => T;\n}>;\n\nlet queueTaskContext: QueueTaskContext | undefined;\n\nasync function loadQueueTaskContext(): Promise<void> {\n try {\n const asyncHooks = await import(\"node:async_hooks\");\n queueTaskContext = new asyncHooks.AsyncLocalStorage<object>();\n } catch {\n // AsyncLocalStorage unavailable on this runtime: re-entrant submissions\n // stay undetected, matching the queue's previous behavior.\n }\n}\n\n// eslint-disable-next-line unicorn/prefer-top-level-await -- the dual CJS/ESM build cannot use top-level await\nvoid loadQueueTaskContext();\n\nfunction rejectReentrantQueueSubmission(): Promise<never> {\n return Promise.reject(\n new ConfigurationError(\n \"This operation was awaited from inside a transaction running on the \" +\n \"same SQLite backend and would deadlock: the transaction holds the \" +\n \"backend's serialized execution slot until it completes, so the \" +\n \"operation could never run.\",\n { backend: \"sqlite\", capability: \"concurrentRootAccess\" },\n {\n suggestion:\n \"Inside a store.transaction callback, use the transaction-scoped \" +\n \"context (tx.nodes / tx.edges / tx.backend) instead of the root \" +\n \"store or backend, or move the operation outside the transaction.\",\n },\n ),\n );\n}\n\nfunction createSerializedExecutionQueue(): SerializedExecutionQueue {\n let tail: Promise<unknown> = Promise.resolve();\n let disposed = false;\n // Unique per queue: a task running on THIS queue must not submit back to it,\n // but may freely submit to a different backend's queue.\n const taskMarker: object = {};\n\n function isDisposed(): boolean {\n return disposed;\n }\n\n return {\n dispose() {\n disposed = true;\n },\n\n runExclusive<T>(task: () => Promise<T>): Promise<T> {\n if (isDisposed()) return Promise.reject(new BackendDisposedError());\n if (queueTaskContext?.getStore() === taskMarker) {\n return rejectReentrantQueueSubmission();\n }\n\n // When disposed, runTask returns a never-settling promise so that no\n // rejection propagates through the 7+ async wrappers between this\n // queue and the store-level caller. A rejection here would become an\n // unhandled rejection if the caller abandoned the promise during\n // teardown — and JavaScript offers no way to `.catch()` a rejection\n // at the bottom of a chain without every async wrapper above it also\n // creating an independently-unhandled rejected promise.\n //\n // The tradeoff: an active caller whose operation was queued before\n // dispose() will see a permanently-pending promise rather than a\n // BackendDisposedError. Post-dispose submissions (the check above)\n // still reject immediately since the caller actively holds that\n // promise.\n const runTask = async (): Promise<T> => {\n if (isDisposed()) return pendingForever<T>();\n try {\n const context = queueTaskContext;\n return context === undefined ?\n await task()\n : await context.run(taskMarker, () => task());\n } catch (error) {\n if (isDisposed()) return pendingForever<T>();\n throw error;\n }\n };\n const result = tail.then(runTask, runTask);\n tail = result.then(\n () => 0,\n () => 0,\n );\n return result;\n },\n };\n}\n\nfunction 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/** Every SQLite \"atomic transactions unavailable\" refusal shares this shape. */\nfunction throwSqliteTransactionsDisabled(message: string): never {\n throw new ConfigurationError(message, {\n backend: \"sqlite\",\n capability: \"transactions\",\n supportsTransactions: false,\n });\n}\n\nfunction buildSqliteCapabilities(\n options: Readonly<{\n fulltextStrategy: FulltextStrategy;\n vectorStrategy: VectorStrategy | undefined;\n transactionMode: SqliteExecutionAdapter[\"profile\"][\"transactionMode\"];\n maxBindParameters: number;\n }>,\n): BackendCapabilities {\n const base =\n options.transactionMode === \"none\" ?\n {\n ...SQLITE_CAPABILITIES,\n transactions: false,\n graphAnalytics: {\n ...(SQLITE_CAPABILITIES.graphAnalytics ?? {\n mathFunctions: false,\n }),\n supported: false,\n },\n }\n : SQLITE_CAPABILITIES;\n return {\n ...base,\n maxBindParameters: options.maxBindParameters,\n fulltext: buildFulltextCapabilities(options.fulltextStrategy),\n ...(options.vectorStrategy === undefined ?\n {}\n : { vector: buildVectorCapabilities(options.vectorStrategy) }),\n };\n}\n\nfunction resolveMaxBindParametersCapability(\n profile: SqliteExecutionProfile,\n override: number | undefined,\n): number {\n const requested = override ?? profile.maxBindParameters;\n return profile.hardMaxBindParameters === undefined ?\n requested\n : Math.min(requested, profile.hardMaxBindParameters);\n}\n\nfunction resolveSqliteGraphAnalyticsCapabilities(\n profile: SqliteExecutionProfile,\n override: GraphAnalyticsCapabilities | undefined,\n): GraphAnalyticsCapabilities {\n const requested = override ??\n SQLITE_CAPABILITIES.graphAnalytics ?? {\n supported: false,\n mathFunctions: false,\n };\n if (\n profile.transactionMode !== \"do-sqlite\" &&\n profile.transactionMode !== \"none\"\n ) {\n return requested;\n }\n return { ...requested, supported: false };\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: ResolvedSqlTableNames;\n fulltextStrategy: FulltextStrategy;\n /**\n * Active vector strategy, or `undefined` when the connection has no\n * vector extension. When present, the backend exposes upsertEmbedding /\n * deleteEmbedding / vectorSearch / createVectorIndex / dropVectorIndex,\n * all routed through this strategy's per-`(kind, field)` storage.\n */\n vectorStrategy?: VectorStrategy | undefined;\n /**\n * Shared durable-marker materializer. The vector methods assert a\n * slot's marker (SELECT, never DDL) on the hot path and `createVectorIndex`\n * ensures it (privileged) — replacing the old in-process ensure-latch.\n * Shared across the outer backend and every transaction-scoped backend\n * so a slot's marker is resolved at most once per process.\n */\n contributionMaterializer: ContributionMaterializer;\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: ResolvedSqlTableNames;\n fulltextStrategy: FulltextStrategy;\n /** Active vector strategy. See {@link CreateSqliteOperationBackendOptions}. */\n vectorStrategy?: VectorStrategy | undefined;\n /** Shared durable-marker materializer. See {@link CreateSqliteOperationBackendOptions}. */\n contributionMaterializer: ContributionMaterializer;\n}>;\n\nfunction createSqliteOperationBackend(\n options: CreateSqliteOperationBackendOptions,\n): InternalOperationBackend {\n const {\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n serializedQueue,\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n } = options;\n\n // CRUD statements route through the execution adapter's compiled path on\n // synchronous drivers so a repeated operation shape re-binds parameters\n // against a cached prepared statement instead of re-preparing through\n // drizzle's session on every call. Async drivers (remote libsql, D1)\n // have no statement cache and keep the drizzle fallback.\n const compiledExecute = executionAdapter.executeCompiled;\n const compiledRun = executionAdapter.executeCompiledRun;\n\n function execGet<T>(query: ExecutableSql): Promise<T | undefined> {\n // Fallback uses db.all()[0], not db.get(): drizzle-team/drizzle-orm#1049\n // — db.get() crashes with the libsql driver when no rows match\n // (normalizeRow receives undefined).\n //\n // The fallback branches use `await` unconditionally rather than\n // `instanceof Promise` because Drizzle returns SQLiteRaw thenables\n // that are NOT Promise instances (drizzle-team/drizzle-orm#2275).\n return runWithSerializedQueue(serializedQueue, async () => {\n if (compiledExecute === undefined) {\n const rows = await executionAdapter.execute<T>(query);\n return rows[0];\n }\n const rows = await compiledExecute<T>(executionAdapter.compile(query));\n return rows[0];\n });\n }\n\n function execAll<T>(query: ExecutableSql): Promise<T[]> {\n return runWithSerializedQueue(serializedQueue, async () => {\n if (compiledExecute === undefined) {\n return [...(await executionAdapter.execute<T>(query))];\n }\n return [...(await compiledExecute<T>(executionAdapter.compile(query)))];\n });\n }\n\n function execRun(query: ExecutableSql): Promise<void> {\n return runWithSerializedQueue(serializedQueue, async () => {\n if (compiledRun === undefined) {\n await db.run(\n isSqlFragment(query) ? toDrizzleSql(query, \"sqlite\") : query,\n );\n return;\n }\n await compiledRun(executionAdapter.compile(query));\n });\n }\n\n const batchConfig = computeSqliteBatchChunkSizes(\n capabilities.maxBindParameters ?? SQLITE_MAX_BIND_PARAMETERS,\n );\n const commonBackend = createCommonOperationBackend({\n batchConfig,\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 vectorEmbeddingMethods =\n vectorStrategy === undefined ?\n {}\n : {\n async upsertEmbedding(params: UpsertEmbeddingParams): Promise<void> {\n const slot = vectorSlotFromParams(params);\n // Assert the slot's durable marker (SELECT, cached) — never DDL.\n // The per-field table is provisioned by the privileged migrator\n // (`createStoreWithSchema` → `materializeVectorContributions`).\n await contributionMaterializer.assertVectorSlot(slot);\n const statements = vectorStrategy.buildUpsert(slot, params, nowIso());\n try {\n for (const statement of statements) {\n await execRun(statement);\n }\n } catch (error) {\n throw mapVectorWriteError(error, params);\n }\n },\n async upsertEmbeddingBatch(\n params: UpsertEmbeddingBatchParams,\n ): Promise<void> {\n if (params.rows.length === 0) return;\n const slot = vectorSlotFromParams(params);\n // Same SELECT-only marker assert as the single-row path — never DDL.\n await contributionMaterializer.assertVectorSlot(slot);\n // Last-write-wins dedupe: a multi-row upsert cannot affect one\n // row twice.\n const rowsById = new Map(\n params.rows.map((row) => [row.nodeId, row] as const),\n );\n const rows = [...rowsById.values()];\n const timestamp = nowIso();\n try {\n for (const chunk of chunkArray(\n rows,\n batchConfig.embeddingUpsertBatchSize,\n )) {\n const statements =\n vectorStrategy.buildUpsertBatch === undefined ?\n chunk.flatMap((row) =>\n vectorStrategy.buildUpsert(\n slot,\n {\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n nodeId: row.nodeId,\n fieldPath: params.fieldPath,\n embedding: row.embedding,\n dimensions: params.dimensions,\n metric: params.metric,\n indexType: params.indexType,\n },\n timestamp,\n ),\n )\n : vectorStrategy.buildUpsertBatch(\n slot,\n { ...params, rows: chunk },\n timestamp,\n );\n for (const statement of statements) {\n await execRun(statement);\n }\n }\n } catch (error) {\n throw mapVectorWriteError(error, params);\n }\n },\n async deleteEmbedding(params: DeleteEmbeddingParams): Promise<void> {\n // Assert the slot's durable marker before deleting. A delete can\n // run before any embedding was ever written for the field (e.g. a\n // node hard-deleted having never carried one); the per-field table\n // was provisioned at boot, so the DELETE is a clean no-op against\n // an existing (possibly empty) table, matching the Postgres path\n // (where a DELETE on a missing relation would abort an enclosing\n // transaction). SELECT-only assert, never DDL.\n const slot = vectorSlotFromParams(params);\n await contributionMaterializer.assertVectorSlot(slot);\n const statements = vectorStrategy.buildDelete(slot, params);\n for (const statement of statements) {\n await execRun(statement);\n }\n },\n async vectorSearch(\n params: VectorSearchParams,\n ): Promise<readonly VectorSearchResult[]> {\n assertVectorSearchLimit(params.limit);\n // Deliberately NOT marker-gated: search is read-only (no DDL\n // hazard to gate), and its params carry the caller's runtime\n // metric override, which legitimately diverges from the\n // provisioned shape on strategies that bake the metric into the\n // DDL (sqlite-vec). An unprovisioned slot surfaces the engine's\n // missing-relation error — the same contract as a query-builder\n // `similarTo()` predicate; `createVerifiedStore` catches both at\n // attach.\n const slot = vectorSlotFromParams(params);\n const query = vectorStrategy.buildSearch(\n slot,\n params,\n // Store-compiled candidates (predicates + subclass + currency)\n // take precedence; the live-node default covers direct backend use.\n params.candidates ??\n buildLiveNodeCandidates(\n tableNames.nodes,\n params.graphId,\n params.nodeKind,\n nowIso(),\n ),\n );\n let rows: readonly { node_id: string; score: number }[];\n try {\n rows = await execAll<{ node_id: string; score: number }>(query);\n } catch (error) {\n // A query vector whose dimension no longer matches the stored\n // column surfaces the same typed error as the write path.\n throw mapVectorWriteError(error, params);\n }\n return rows.map((row) => ({\n nodeId: row.node_id,\n score: row.score,\n }));\n },\n // Single-statement hybrid needs ROW_NUMBER(); a capability profile\n // that disables window functions keeps the store's multi-statement\n // fallback by simply not exposing the member.\n ...(capabilities.windowFunctions ?\n {\n async hybridSearch(\n params: HybridSearchParams,\n ): Promise<readonly HybridSearchRow[]> {\n assertVectorSearchLimit(params.limit);\n // Source depths get the same boundary validation the\n // fallback path applies (vectorSearch validates its limit;\n // the fulltext depth is validated inside\n // buildFulltextSearch).\n assertVectorSearchLimit(params.vector.k);\n const slot = vectorSlotFromParams({\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n fieldPath: params.vector.fieldPath,\n dimensions: params.vector.dimensions,\n metric: params.vector.metric,\n indexType: params.vector.indexType,\n });\n // Read-only, not marker-gated — see vectorSearch above.\n const candidates =\n params.candidates ??\n buildLiveNodeCandidates(\n tableNames.nodes,\n params.graphId,\n params.nodeKind,\n nowIso(),\n );\n const vectorParams: VectorSearchParams = {\n graphId: params.graphId,\n nodeKind: params.nodeKind,\n fieldPath: params.vector.fieldPath,\n queryEmbedding: params.vector.queryEmbedding,\n metric: params.vector.metric,\n dimensions: params.vector.dimensions,\n indexType: params.vector.indexType,\n limit: params.vector.k,\n ...(params.vector.minScore === undefined ?\n {}\n : { minScore: params.vector.minScore }),\n };\n // The vector leg references the statement's shared\n // tg_hybrid_cand CTE; the actual candidates SQL is emitted\n // once by buildHybridSearch.\n const vectorSql = vectorStrategy.buildSearch(\n slot,\n vectorParams,\n portableSql.raw(\"SELECT node_id FROM tg_hybrid_cand\"),\n );\n const statement = operationStrategy.buildHybridSearch(\n { ...params, candidates },\n toDrizzleSql(vectorSql, \"sqlite\"),\n params.vector.metric === \"cosine\",\n );\n let raw: readonly Record<string, unknown>[];\n try {\n raw = await execAll<Record<string, unknown>>(statement);\n } catch (error) {\n throw mapVectorWriteError(error, vectorParams);\n }\n return raw.map((row) => mapHybridSearchRow(row, toNodeRow));\n },\n }\n : {}),\n };\n\n const operationBackend: InternalOperationBackend = {\n ...commonBackend,\n ...executeRawMethod,\n ...vectorEmbeddingMethods,\n capabilities,\n dialect: \"sqlite\",\n tableNames,\n fulltextStrategy,\n ...(vectorStrategy === undefined ? {} : { vectorStrategy }),\n\n async createVectorIndex(params: CreateVectorIndexParams): Promise<void> {\n if (vectorStrategy === undefined) return;\n const slot = vectorSlotFromCreateIndexParams(params);\n // Ensure the per-field table + its durable marker first (privileged,\n // idempotent), then create its ANN index. `ownedTables` already folds\n // the index DDL in, so the explicit `buildCreateIndex` step is\n // belt-and-suspenders for slots whose index intent changed after the\n // table was first materialized.\n await contributionMaterializer.ensureVectorSlot(slot);\n const indexStatement = vectorStrategy.buildCreateIndex?.(slot);\n if (indexStatement !== undefined) {\n await execRun(indexStatement);\n }\n },\n\n async dropVectorIndex(params: DropVectorIndexParams): Promise<void> {\n if (vectorStrategy === undefined) return;\n const slot = vectorSlotFromDropIndexParams(params);\n const dropStatement = vectorStrategy.buildDropIndex?.(slot);\n if (dropStatement === undefined) return;\n try {\n await execRun(dropStatement);\n } catch (error) {\n // The per-field table (and thus its index) may never have been\n // materialized; DROP INDEX IF EXISTS against a missing table errors\n // on some drivers, so treat that as already-dropped.\n if (!isMissingTableError(error)) throw error;\n }\n },\n\n // === Fulltext Operations ===\n\n async upsertFulltext(params: UpsertFulltextParams): Promise<void> {\n const timestamp = nowIso();\n const statements = operationStrategy.buildUpsertFulltext(\n params,\n timestamp,\n );\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async deleteFulltext(params: DeleteFulltextParams): Promise<void> {\n const statements = operationStrategy.buildDeleteFulltext(params);\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async upsertFulltextBatch(\n params: UpsertFulltextBatchParams,\n ): Promise<void> {\n if (params.rows.length === 0) return;\n const timestamp = nowIso();\n // The strategy emits ONE statement over every row it is given, so\n // the bind budget is enforced here — same contract as node/edge\n // batch inserts.\n for (const rows of chunkArray(\n params.rows,\n batchConfig.fulltextUpsertBatchSize,\n )) {\n const statements = operationStrategy.buildUpsertFulltextBatch(\n { ...params, rows },\n timestamp,\n );\n for (const stmt of statements) {\n await execRun(stmt);\n }\n }\n },\n\n async deleteFulltextBatch(\n params: DeleteFulltextBatchParams,\n ): Promise<void> {\n if (params.nodeIds.length === 0) return;\n for (const nodeIds of chunkArray(\n params.nodeIds,\n batchConfig.fulltextDeleteChunkSize,\n )) {\n const statements = operationStrategy.buildDeleteFulltextBatch({\n ...params,\n nodeIds,\n });\n for (const stmt of statements) {\n await execRun(stmt);\n }\n }\n },\n\n async fulltextSearch(\n params: FulltextSearchParams,\n ): Promise<readonly FulltextSearchResult[]> {\n const query = operationStrategy.buildFulltextSearch(params);\n const rows = await execAll<{\n node_id: string;\n score: number | string;\n snippet: string | null;\n }>(query);\n return rows.map((row, index) => ({\n nodeId: row.node_id,\n score: coerceNumericScore(row.score),\n rank: index + 1,\n ...(row.snippet === null ? {} : { snippet: row.snippet }),\n }));\n },\n\n // === Query Execution ===\n\n async execute<T>(query: CompiledRowsSql): Promise<readonly T[]> {\n return runWithSerializedQueue(serializedQueue, async () =>\n executionAdapter.execute<T>(query),\n );\n },\n\n compileSql(\n query: SqlFragment,\n ): 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): AdapterBackend<AnySqliteDatabase> {\n const tables = options.tables ?? defaultTables;\n const fulltextStrategy = options.fulltext ?? fts5Strategy;\n const profileHints = options.executionProfile ?? {};\n const executionAdapter = createSqliteExecutionAdapter(db, { profileHints });\n const { isSync, transactionMode } = executionAdapter.profile;\n // The active vector strategy gates upsertEmbedding / deleteEmbedding /\n // vectorSearch and supplies the per-`(kind, field)` storage. Passed by\n // the caller that knows the connection's vector capability\n // (`createLibsqlBackend` always; `createLocalSqliteBackend` when the\n // extension loads); absent for plain SQLite drivers with no extension.\n const vectorStrategy = options.vector;\n const capabilityOverrides = options.capabilities ?? {};\n const capabilities = normalizeGraphAnalyticsCapabilities({\n ...buildSqliteCapabilities({\n fulltextStrategy,\n vectorStrategy,\n transactionMode,\n maxBindParameters: executionAdapter.profile.maxBindParameters,\n }),\n ...capabilityOverrides,\n maxBindParameters: resolveMaxBindParametersCapability(\n executionAdapter.profile,\n capabilityOverrides.maxBindParameters,\n ),\n graphAnalytics: resolveSqliteGraphAnalyticsCapabilities(\n executionAdapter.profile,\n capabilityOverrides.graphAnalytics,\n ),\n });\n\n const tableNames: ResolvedSqlTableNames = {\n nodes: getTableName(tables.nodes),\n edges: getTableName(tables.edges),\n recordedNodes: getTableName(tables.recordedNodes),\n recordedEdges: getTableName(tables.recordedEdges),\n recordedClock: getTableName(tables.recordedClock),\n revisionOrigins: getTableName(tables.revisionOrigins),\n fulltext: tables.fulltextTableName,\n uniques: getTableName(tables.uniques),\n };\n // refreshStatistics() scopes ANALYZE to these — matching the Postgres\n // backend, which never touches unrelated tables sharing the database.\n // The recorded relations are ANALYZEd separately under a missing-table\n // guard: a schema created before recorded-time history landed\n // (bring-your-own-connection, no DDL re-run) has no recorded_* tables.\n const coreAnalyzeTables = [\n tableNames.nodes,\n tableNames.edges,\n tableNames.uniques,\n tableNames.fulltext,\n ];\n const recordedAnalyzeTables = [\n tableNames.recordedNodes,\n tableNames.recordedEdges,\n tableNames.recordedClock,\n ] as const;\n const operationStrategy = createSqliteOperationStrategy(\n tables,\n fulltextStrategy,\n );\n // Serialize top-level operations per backend on every transaction-capable\n // mode (\"sql\", \"drizzle\", \"do-sqlite\"). SQLite is single-writer, and two\n // concurrent `transaction()` calls on one connection open overlapping BEGINs\n // and collide with SQLITE_BUSY; the queue makes each top-level operation —\n // including a whole transaction — run to completion before the next starts.\n // A transaction's inner reads/writes run on the tx-scoped backend, which\n // does not carry the queue (see CreateSqliteTransactionBackendOptions);\n // awaiting a ROOT-backend operation from inside the transaction callback\n // would deadlock, so the queue rejects such re-entrant submissions with a\n // typed error (see rejectReentrantQueueSubmission). `none` drivers (D1 /\n // neon-http) have no transactions and manage their own concurrency, so they\n // stay unqueued.\n const serializedQueue =\n transactionMode === \"none\" ? undefined : createSerializedExecutionQueue();\n\n // Durable fulltext + vector materialization (#135): the dialect-specific\n // marker-table primitives. Orchestration (materialize / assert /\n // per-instance cache) lives once in `createContributionMaterializer`,\n // shared by the outer backend and every transaction-scoped backend so a\n // slot's marker is resolved at most once per process. Built before\n // `operations` so the operation backend's vector methods can assert/\n // ensure through it instead of issuing DDL on the hot path.\n const matTable = tables.contributionMaterializations;\n\n async function ensureContributionMaterializationsTableImpl(): Promise<void> {\n await db.run(sql.raw(generateSqliteCreateTableSQL(matTable)));\n }\n\n async function getContributionMaterializationRow(\n identity: ContributionMaterializationIdentity,\n ): Promise<ContributionMaterializationRow | undefined> {\n const rows = await db\n .select()\n .from(matTable)\n .where(\n and(\n eq(matTable.graphId, identity.graphId),\n eq(matTable.logicalName, identity.logicalName),\n eq(matTable.owner, identity.owner),\n eq(matTable.tableName, identity.tableName),\n ),\n );\n const row = rows[0];\n if (row === undefined) return undefined;\n return mapContributionMaterializationRow(\n row,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS.decode,\n );\n }\n\n async function getContributionMaterializationRows(\n graphId: string,\n ): Promise<readonly ContributionMaterializationRow[]> {\n const rows = await db\n .select()\n .from(matTable)\n .where(eq(matTable.graphId, graphId));\n return rows.map((row) =>\n mapContributionMaterializationRow(\n row,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS.decode,\n ),\n );\n }\n\n async function recordContributionMaterializationRow(\n params: RecordContributionMaterializationParams,\n ): Promise<void> {\n await db\n .insert(matTable)\n .values(\n buildContributionInsertValues(\n params,\n SQLITE_CONTRIBUTION_MAT_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: [\n matTable.graphId,\n matTable.logicalName,\n matTable.owner,\n matTable.tableName,\n ],\n set: buildContributionOnConflictSet(\n matTable.materializedAt,\n params.materializedAt,\n ),\n });\n }\n\n async function deleteContributionMaterializationRow(\n identity: ContributionMaterializationIdentity,\n ): Promise<void> {\n await db\n .delete(matTable)\n .where(\n and(\n eq(matTable.graphId, identity.graphId),\n eq(matTable.logicalName, identity.logicalName),\n eq(matTable.owner, identity.owner),\n eq(matTable.tableName, identity.tableName),\n ),\n );\n }\n\n const contributionMaterializer = createContributionMaterializer({\n dialect: \"sqlite\",\n fulltextStrategy,\n fulltextTableName: tables.fulltextTableName,\n vectorStrategy,\n execDdl: async (statement) => {\n await db.run(sql.raw(statement));\n },\n ensureMarkerTable: ensureContributionMaterializationsTableImpl,\n getMarkers: getContributionMaterializationRows,\n recordMarker: recordContributionMaterializationRow,\n deleteMarker: deleteContributionMaterializationRow,\n });\n\n const operations = createSqliteOperationBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n ...(serializedQueue === undefined ? {} : { serializedQueue }),\n });\n\n /**\n * #140: the `transactionMode: \"do-sqlite\"` primitive. Cloudflare\n * Durable Objects expose an async storage transaction runner —\n * `ctx.storage.transaction(async () => ...)`, surfaced by Drizzle as\n * `db.$client.transaction` — that rolls back SQL writes across\n * `await`. There is no Drizzle tx handle on DO: the storage\n * transaction is ambient on the object, so callers bind the *outer*\n * `db` (as the \"sql\" path binds the outer connection). Drizzle's own\n * `db.transaction()` here is `ctx.storage.transactionSync` and cannot\n * span an await, so it is deliberately not used. Shared by\n * `transaction()` (business writes) and `runSchemaWriteTransaction()`\n * (schema-version commits — data only, never DDL: the #135 invariant\n * holds because `bootstrapTables` runs outside any transaction).\n */\n function runDoSqliteStorageTransaction<T>(run: () => Promise<T>): Promise<T> {\n const storage = getDurableObjectStorageClient(db);\n if (storage === undefined) {\n throwSqliteTransactionsDisabled(\n \"transactionMode 'do-sqlite' requires a Drizzle Durable Objects \" +\n \"database (drizzle(ctx.storage)) whose `$client` exposes the SQL, \" +\n \"transactionSync, and async transaction runners.\",\n );\n }\n return runWithSerializedQueue(serializedQueue, () =>\n storage.transaction(run),\n );\n }\n\n /**\n * Executes a transaction-frame statement (BEGIN IMMEDIATE / COMMIT /\n * ROLLBACK) through the prepared-statement cache when the driver has one.\n * These are the hottest statements on the per-write path (every single\n * write is its own transaction). Local libsql also uses \"sql\" transaction\n * mode but is async (no compiled path) and keeps the drizzle fallback.\n */\n async function runFrameStatement(query: SQL): Promise<void> {\n const compiledRun = executionAdapter.executeCompiledRun;\n if (compiledRun === undefined) {\n await db.run(query);\n return;\n }\n await compiledRun(executionAdapter.compile(query));\n }\n\n /**\n * Runs `fn` inside a SQLite write transaction (BEGIN IMMEDIATE) so that\n * the read-then-write inside `commitSchemaVersion` / `setActiveVersion`\n * is serialized against concurrent writers — a deferred BEGIN would let\n * two transactions race past the CAS read and one would later fail\n * with SQLITE_BUSY instead of producing a clean StaleVersionError.\n *\n * Refuses on `transactionMode: \"none\"`. The orphan-row crash window\n * cannot be eliminated without atomicity.\n */\n function runSchemaWriteTransaction<T>(\n fn: (tx: CommonOperationBackend) => Promise<T>,\n ): Promise<T> {\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\n \"commitSchemaVersion and setActiveVersion require atomic transactions, \" +\n \"but this SQLite backend has transactions disabled. Configure a \" +\n \"driver that supports transactions (better-sqlite3, libsql, \" +\n \"bun:sqlite) to use schema commits.\",\n );\n }\n\n if (transactionMode === \"sql\") {\n return runWithSerializedQueue(serializedQueue, async () => {\n // Write-lock is held here, so the schema-write-capable\n // InternalOperationBackend is used intentionally (see its type).\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n await runFrameStatement(sql`BEGIN IMMEDIATE`);\n try {\n const result = await fn(txBackend);\n await runFrameStatement(sql`COMMIT`);\n return result;\n } catch (error) {\n await runFrameStatement(sql`ROLLBACK`);\n throw error;\n }\n });\n }\n\n if (transactionMode === \"do-sqlite\") {\n // No interactive lock-mode control on the DO storage runner; the\n // serialized queue (always present — DO is sync) provides the\n // single-writer ordering that \"immediate\" gives the other paths.\n // Raw txBackend (no `gateFulltext`, unlike the business\n // `transaction()` do-sqlite branch): schema-version commits are\n // data-only and never touch fulltext (#135), matching the \"sql\"\n // and \"drizzle\" schema-write branches.\n return runDoSqliteStorageTransaction(async () => {\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n return fn(txBackend);\n });\n }\n\n // transactionMode === \"drizzle\". Drizzle's sqlite-core transaction\n // accepts a `behavior` option that maps to BEGIN / BEGIN IMMEDIATE /\n // BEGIN EXCLUSIVE; \"immediate\" is what we need to acquire a reserved\n // write lock at the start of the transaction.\n return runWithSerializedQueue(\n serializedQueue,\n async () =>\n db.transaction(\n async (tx) => {\n const txBackend = createTransactionBackend({\n capabilities,\n db: tx,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n return fn(txBackend);\n },\n { behavior: \"immediate\" },\n ) as Promise<T>,\n );\n }\n\n // Shared by the \"drizzle\" branch of `transaction()` (TypeGraph opens\n // the tx) and `adoptTransaction()` (#134 — the caller already opened\n // it): bind a tx-scoped backend to the *literal* `tx` client and gate\n // fulltext on the durable marker (a cached SELECT, never DDL).\n function bindTransactionBackend(tx: AnySqliteDatabase): TransactionBackend {\n const txBackend = createTransactionBackend({\n capabilities,\n db: tx,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n return gateFulltext(txBackend, contributionMaterializer.assertInitialized);\n }\n\n const backend: AdapterBackend<AnySqliteDatabase> = {\n ...operations,\n\n ...((\n isSync &&\n transactionMode === \"sql\" &&\n executionAdapter.executePreparedRunBatch !== undefined\n ) ?\n {\n async trustedImport<T>(\n fn: (session: TrustedImportSession) => Promise<T>,\n ): Promise<T> {\n return backend.transaction(async (tx) => {\n await assertTrustedImportDatabaseEmpty(tx, tableNames);\n const indexDefinitions = await suspendSqliteSecondaryIndexes(\n tx,\n tableNames,\n );\n const result = await fn(\n createSqliteTrustedImportSession(executionAdapter, tableNames),\n );\n await restoreSecondaryIndexes(tx, indexDefinitions);\n await analyzeImportedTables(tx, tableNames);\n return result;\n });\n },\n }\n : {}),\n\n async bootstrapTables(): Promise<void> {\n const statements = generateSqliteDDL(tables, fulltextStrategy);\n for (const statement of statements) {\n await db.run(sql.raw(statement));\n }\n },\n\n async ensureRevisionOriginsTable(): Promise<void> {\n await db.run(\n sql.raw(generateSqliteCreateTableSQL(tables.revisionOrigins)),\n );\n },\n\n // Every fulltext-touching method asserts the durable marker instead\n // of lazily emitting DDL. Steady state performs zero ensure; an\n // uninitialized database throws `StoreNotInitializedError` rather\n // than self-healing (#135). Shared verbatim with the tx-scoped gate\n // via `gateFulltextMethods`.\n ...gateFulltextMethods(\n operations,\n contributionMaterializer.assertInitialized,\n ),\n\n async executeDdl(ddl: string): Promise<void> {\n await db.run(sql.raw(ddl));\n },\n\n async ensureIndexMaterializationsTable(): Promise<void> {\n await db.run(\n sql.raw(generateSqliteCreateTableSQL(tables.indexMaterializations)),\n );\n },\n\n async getIndexMaterialization(\n indexName: string,\n ): Promise<IndexMaterializationRow | undefined> {\n const t = tables.indexMaterializations;\n const rows = await db.select().from(t).where(eq(t.indexName, indexName));\n const row = rows[0];\n if (row === undefined) return undefined;\n return mapMaterializationRow(row, SQLITE_INDEX_MAT_TIMESTAMPS.decode);\n },\n\n async getIndexMaterializations(\n statusKeys: readonly string[],\n ): Promise<readonly IndexMaterializationRow[]> {\n if (statusKeys.length === 0) return [];\n const t = tables.indexMaterializations;\n const rows = await db\n .select()\n .from(t)\n .where(inArray(t.indexName, [...statusKeys]));\n return rows.map((row) =>\n mapMaterializationRow(row, SQLITE_INDEX_MAT_TIMESTAMPS.decode),\n );\n },\n\n async recordIndexMaterialization(\n params: RecordIndexMaterializationParams,\n ): Promise<void> {\n const t = tables.indexMaterializations;\n await db\n .insert(t)\n .values(\n buildMaterializationInsertValues(\n params,\n SQLITE_INDEX_MAT_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: t.indexName,\n set: buildMaterializationOnConflictSet(params.materializedAt),\n });\n },\n\n async ensureContributionMaterializationsTable(): Promise<void> {\n await ensureContributionMaterializationsTableImpl();\n },\n\n async getContributionMaterialization(\n identity: ContributionMaterializationIdentity,\n ): Promise<ContributionMaterializationRow | undefined> {\n return getContributionMaterializationRow(identity);\n },\n\n async recordContributionMaterialization(\n params: RecordContributionMaterializationParams,\n ): Promise<void> {\n await recordContributionMaterializationRow(params);\n },\n\n async assertRuntimeContributionsInitialized(\n graphId: string,\n ): Promise<void> {\n await contributionMaterializer.assertInitialized(graphId);\n },\n\n async ensureKindRemovalsTable(): Promise<void> {\n await db.run(sql.raw(generateSqliteCreateTableSQL(tables.kindRemovals)));\n },\n\n async getPendingKindRemovals(\n graphId: string,\n ): Promise<readonly KindRemovalRow[]> {\n const t = tables.kindRemovals;\n const rows = await db\n .select()\n .from(t)\n .where(and(eq(t.graphId, graphId), isNull(t.removedAt)));\n return rows.map((row) =>\n mapKindRemovalRow(row, SQLITE_KIND_REMOVAL_TIMESTAMPS.decode),\n );\n },\n\n async getAllKindRemovals(\n graphId: string,\n ): Promise<readonly KindRemovalRow[]> {\n const t = tables.kindRemovals;\n const rows = await db.select().from(t).where(eq(t.graphId, graphId));\n return rows.map((row) =>\n mapKindRemovalRow(row, SQLITE_KIND_REMOVAL_TIMESTAMPS.decode),\n );\n },\n\n async recordKindRemoval(params: RecordKindRemovalParams): Promise<void> {\n const t = tables.kindRemovals;\n await db\n .insert(t)\n .values(\n buildKindRemovalInsertValues(\n params,\n SQLITE_KIND_REMOVAL_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: [t.graphId, t.kindName, t.entity, t.schemaVersion],\n set: buildKindRemovalOnConflictSet(t.removedAt, params.removedAt),\n });\n },\n\n async ensureReconciliationMarkersTable(): Promise<void> {\n await db.run(\n sql.raw(generateSqliteCreateTableSQL(tables.reconciliationMarkers)),\n );\n },\n\n async ensureRuntimeContributions(graphId: string): Promise<void> {\n await contributionMaterializer.ensureRuntimeContributions(graphId);\n },\n\n /**\n * Superseded by `ensureRuntimeContributions(graphId)` (#129).\n * Retained as a thin back-compat wrapper for callers predating\n * #129; #135 routed it through the durable-marker writer.\n */\n async ensureFulltextTable(graphId: string): Promise<void> {\n await contributionMaterializer.ensureRuntimeContributions(graphId);\n },\n\n // Vector counterparts of the runtime-contribution methods. Present\n // only when a vector strategy is wired (omitted on a plain SQLite\n // connection with no vector extension), mirroring the embedding/\n // search methods.\n ...(vectorStrategy === undefined ?\n {}\n : {\n async ensureVectorSlotContribution(\n slot: VectorSlot,\n options_?: Readonly<{ force?: boolean; onDrift?: \"throw\" | \"skip\" }>,\n ): Promise<void> {\n await contributionMaterializer.ensureVectorSlot(slot, options_);\n },\n\n async ensureVectorSlotContributions(\n slots: readonly VectorSlot[],\n options_?: Readonly<{ force?: boolean; onDrift?: \"throw\" | \"skip\" }>,\n ): Promise<void> {\n await contributionMaterializer.ensureVectorSlots(slots, options_);\n },\n\n async assertVectorSlotInitialized(slot: VectorSlot): Promise<void> {\n await contributionMaterializer.assertVectorSlot(slot);\n },\n\n async assertVectorSlotsInitialized(\n slots: readonly VectorSlot[],\n ): Promise<void> {\n await contributionMaterializer.assertVectorSlots(slots);\n },\n\n async deleteVectorSlotContribution(slot: VectorSlot): Promise<void> {\n await contributionMaterializer.dropVectorSlot(slot);\n },\n }),\n\n async getReconciliationMarker(\n graphId: string,\n ): Promise<number | undefined> {\n const t = tables.reconciliationMarkers;\n const rows = await db.select().from(t).where(eq(t.graphId, graphId));\n return rows[0]?.reconciledToVersion;\n },\n\n async setReconciliationMarker(\n graphId: string,\n version: number,\n ): Promise<void> {\n const t = tables.reconciliationMarkers;\n await db\n .insert(t)\n .values({ graphId, reconciledToVersion: version })\n .onConflictDoUpdate({\n target: t.graphId,\n set: { reconciledToVersion: version },\n });\n },\n\n async refreshStatistics(): Promise<void> {\n // `ANALYZE` populates `sqlite_stat1`. With no stat table, the\n // planner falls back to heuristics that, at least for FTS5\n // virtual-table queries and multi-column index selection, can be\n // an order of magnitude slower. Running it explicitly makes the\n // planner data-driven.\n //\n // Scoped to TypeGraph-managed tables only (matching the Postgres\n // backend) — a bare `ANALYZE` touches every table in the database\n // file, including unrelated ones sharing it. Bounded by\n // `analysis_limit` (see its doc comment) so cost stays roughly\n // constant per call regardless of table size — the value is a\n // fixed internal constant, not user input, so inlining it via\n // `sql.raw` is safe; SQLite's `PRAGMA` does not accept bound\n // parameters for its value.\n try {\n await db.run(\n toDrizzleSql(\n portableSql`PRAGMA analysis_limit = ${portableSql.raw(String(SQLITE_ANALYZE_ROW_LIMIT))}`,\n \"sqlite\",\n ),\n );\n } catch (error) {\n // Cloudflare D1 and Durable Object SQLite reject this performance-only\n // tuning PRAGMA through their authorizer. Continue with scoped ANALYZE,\n // which workerd permits, but keep every unexpected failure loud.\n if (!isSqliteNotAuthorizedError(error)) throw error;\n }\n for (const tableName of coreAnalyzeTables) {\n await db.run(\n toDrizzleSql(\n portableSql`ANALYZE ${portableSql.identifier(tableName)}`,\n \"sqlite\",\n ),\n );\n }\n // The recorded relations may be absent on a schema created before\n // recorded-time history landed (bring-your-own-connection, no DDL\n // re-run); ANALYZE on a missing table errors, so skip those.\n for (const tableName of recordedAnalyzeTables) {\n try {\n await db.run(\n toDrizzleSql(\n portableSql`ANALYZE ${portableSql.identifier(tableName)}`,\n \"sqlite\",\n ),\n );\n } catch (error) {\n if (!isMissingTableError(error)) throw error;\n }\n }\n },\n\n async commitSchemaVersion(\n params: CommitSchemaVersionParams,\n ): Promise<SchemaVersionRow> {\n return runSchemaWriteTransaction((target) =>\n target.commitSchemaVersion(params),\n );\n },\n\n async setActiveVersion(params: SetActiveVersionParams): Promise<void> {\n await runSchemaWriteTransaction((target) =>\n target.setActiveVersion(params),\n );\n },\n\n async transaction<T>(\n fn: (tx: TransactionBackend) => Promise<T>,\n options?: InternalTransactionOptions,\n ): Promise<T> {\n return backend.transactionWithNative((tx) => fn(tx), options);\n },\n\n async transactionWithNative<T>(\n fn: (tx: TransactionBackend, sql: AnySqliteDatabase) => Promise<T>,\n options?: InternalTransactionOptions,\n ): Promise<T> {\n const temporaryWrites =\n options?.temporaryWrites === INTERNAL_TEMPORARY_WRITES;\n if (temporaryWrites && options.accessMode !== \"read_only\") {\n throw new ConfigurationError(\n \"Temporary-write transactions must be semantically read-only.\",\n { dialect: \"sqlite\" },\n );\n }\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\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 }\n\n // #134/#135: NO DDL or ensure here. The tx-scoped backend\n // exposes raw fulltext methods without self-ensure wrappers; the\n // single gate is `Store.transaction()`, which asserts the durable\n // contribution marker (one cached SELECT) before this method is\n // reached. The caller's BEGIN never carries CREATE statements.\n if (transactionMode === \"sql\") {\n return runWithSerializedQueue(serializedQueue, async () => {\n // Not `bindTransactionBackend(...)`: this path frames the tx\n // with manual BEGIN/COMMIT on the *outer* `db`, so it must\n // reuse that connection's already-built `executionAdapter`\n // rather than synthesize a fresh one for a distinct handle.\n // Serves sync drivers AND local libsql connections: both keep\n // one stable connection, where raw BEGIN/COMMIT composes and\n // Drizzle's `db.transaction()` (which for libsql abandons the\n // client's connection — fatal for `:memory:`) must be avoided.\n const txBackend = createTransactionBackend({\n capabilities,\n db,\n executionAdapter,\n operationStrategy,\n profileHints: { isSync },\n tableNames,\n fulltextStrategy,\n vectorStrategy,\n contributionMaterializer,\n });\n // Read-only multi-statement operations need one snapshot but must not\n // reserve SQLite's single writer slot. Business transactions retain\n // BEGIN IMMEDIATE so read-then-write cannot lose a lock-upgrade race.\n await runFrameStatement(\n options?.accessMode === \"read_only\" || temporaryWrites ?\n sql`BEGIN`\n : sql`BEGIN IMMEDIATE`,\n );\n\n try {\n const result = await fn(\n gateFulltext(\n txBackend,\n contributionMaterializer.assertInitialized,\n ),\n db,\n );\n await runFrameStatement(sql`COMMIT`);\n return result;\n } catch (error) {\n await runFrameStatement(sql`ROLLBACK`);\n throw error;\n }\n });\n }\n\n if (transactionMode === \"do-sqlite\") {\n return runDoSqliteStorageTransaction(async () =>\n fn(bindTransactionBackend(db), db),\n );\n }\n\n // transactionMode === \"drizzle\". Read-only work uses a deferred snapshot;\n // business transactions retain BEGIN IMMEDIATE for safe lock upgrades.\n return runWithSerializedQueue(\n serializedQueue,\n async () =>\n db.transaction(async (tx) => fn(bindTransactionBackend(tx), tx), {\n behavior:\n options?.accessMode === \"read_only\" || temporaryWrites ?\n \"deferred\"\n : \"immediate\",\n }) as Promise<T>,\n );\n },\n\n adoptTransaction(externalTx: AnySqliteDatabase): TransactionBackend {\n // #134: parity with Postgres. Cross-store atomicity needs real\n // rollback; on a \"none\" driver the caller's relational write\n // would commit with no way to undo the graph write. Refuse\n // loudly rather than silently degrade.\n if (transactionMode === \"none\") {\n throwSqliteTransactionsDisabled(\n \"Cross-store atomicity is unavailable on this SQLite backend: \" +\n \"transactions are disabled (transactionMode: 'none'). Adopting \" +\n \"an external transaction here would let the caller's relational \" +\n \"write commit with no way to roll back the graph write. \" +\n \"Configure a driver that supports transactions (better-sqlite3, \" +\n \"libsql, bun:sqlite).\",\n );\n }\n assertAdoptedDialect<AnySqliteDatabase>(\n externalTx,\n BaseSQLiteDatabase,\n \"sqlite\",\n );\n // serializedQueue is deliberately NOT applied to an adopted tx: a\n // sync better-sqlite3 driver runs the adopted statements on the\n // caller's stack, so wrapping a caller-driven tx in our queue\n // could deadlock against the caller's outer `db.transaction(...)`.\n return bindTransactionBackend(externalTx);\n },\n\n close(): Promise<void> {\n serializedQueue?.dispose();\n return Promise.resolve();\n },\n };\n\n return backend;\n}\n\nfunction createTransactionBackend(\n options: CreateSqliteTransactionBackendOptions,\n): InternalOperationBackend {\n const txExecutionAdapter =\n options.executionAdapter ??\n createSqliteExecutionAdapter(options.db, {\n profileHints: options.profileHints,\n });\n\n // The transaction-scoped backend shares the outer backend's\n // contribution materializer: the per-field vector table is provisioned\n // (DDL) only by the privileged outer backend, so a tx-scoped vector op\n // only ASSERTS the durable marker (SELECT, never DDL) and can't poison\n // anything on rollback. The shared per-instance cache means a slot\n // confirmed once stays a pure `Set.has` inside every later transaction.\n return createSqliteOperationBackend({\n capabilities: options.capabilities,\n db: options.db,\n executionAdapter: txExecutionAdapter,\n operationStrategy: options.operationStrategy,\n tableNames: options.tableNames,\n fulltextStrategy: options.fulltextStrategy,\n vectorStrategy: options.vectorStrategy,\n contributionMaterializer: options.contributionMaterializer,\n });\n}\n\n// Re-export schema utilities\nexport type { SqliteTableNames, SqliteTables } from \"./schema/sqlite\";\nexport { createSqliteTables, tables } from \"./schema/sqlite\";\n"]}
@@ -5,6 +5,7 @@ var chunkSAFZ6JTI_cjs = require('./chunk-SAFZ6JTI.cjs');
5
5
  // src/utils/sql-errors.ts
6
6
  var SQLITE_MISSING_TABLE_PATTERN = "no such table";
7
7
  var SQLITE_GENERIC_ERROR_CODE = "SQLITE_ERROR";
8
+ var SQLITE_NOT_AUTHORIZED_CODE = "SQLITE_AUTH";
8
9
  var DRIZZLE_QUERY_ERROR_PREFIX = "Failed query:";
9
10
  var POSTGRES_UNDEFINED_RELATION_PATTERN = /\b(?:relation|table)\s+"[^"]+"\s+does not exist\b/i;
10
11
  var POSTGRES_UNDEFINED_TABLE_CODE = "42P01";
@@ -75,6 +76,16 @@ function isMissingTableError(error) {
75
76
  }
76
77
  return false;
77
78
  }
79
+ function isSqliteNotAuthorizedError(error) {
80
+ for (const link of errorChain(error)) {
81
+ if (sqliteErrorCode(link) === SQLITE_NOT_AUTHORIZED_CODE) return true;
82
+ const message = messageProperty(link);
83
+ if (message?.includes(SQLITE_NOT_AUTHORIZED_CODE) === true && message.toLowerCase().includes("not authorized")) {
84
+ return true;
85
+ }
86
+ }
87
+ return false;
88
+ }
78
89
  function historyMissingRecordedRelationsError(details, cause) {
79
90
  return new chunkSAFZ6JTI_cjs.ConfigurationError(
80
91
  "history: true requires the recorded-time relations to exist, but a recorded relation is missing.",
@@ -113,7 +124,8 @@ function parseDimensionMismatch(error) {
113
124
 
114
125
  exports.isInsufficientResourcesError = isInsufficientResourcesError;
115
126
  exports.isMissingTableError = isMissingTableError;
127
+ exports.isSqliteNotAuthorizedError = isSqliteNotAuthorizedError;
116
128
  exports.parseDimensionMismatch = parseDimensionMismatch;
117
129
  exports.withRecordedRelationsPrecondition = withRecordedRelationsPrecondition;
118
- //# sourceMappingURL=chunk-O5H62ZWJ.cjs.map
119
- //# sourceMappingURL=chunk-O5H62ZWJ.cjs.map
130
+ //# sourceMappingURL=chunk-HP6LWBLB.cjs.map
131
+ //# sourceMappingURL=chunk-HP6LWBLB.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils/sql-errors.ts"],"names":["ConfigurationError"],"mappings":";;;;;AAuBA,IAAM,4BAAA,GAA+B,eAAA;AACrC,IAAM,yBAAA,GAA4B,cAAA;AAClC,IAAM,0BAAA,GAA6B,aAAA;AACnC,IAAM,0BAAA,GAA6B,eAAA;AACnC,IAAM,mCAAA,GACJ,oDAAA;AASF,IAAM,6BAAA,GAAgC,OAAA;AAiBtC,UAAU,WAAW,KAAA,EAAgD;AACnE,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAa;AAC9B,EAAA,IAAI,OAAA,GAAmB,KAAA;AACvB,EAAA,OAAO,OAAA,KAAY,UAAa,OAAA,KAAY,IAAA,IAAQ,CAAC,IAAA,CAAK,GAAA,CAAI,OAAO,CAAA,EAAG;AACtE,IAAA,IAAA,CAAK,IAAI,OAAO,CAAA;AAChB,IAAA,MAAM,OAAA;AACN,IAAA,OAAA,GACE,gBAAgB,OAAO,CAAA,GAAI,QAAQ,GAAA,CAAI,OAAA,EAAS,OAAO,CAAA,GAAI,MAAA;AAAA,EAC/D;AACF;AAEA,SAAS,gBAAgB,KAAA,EAAiC;AACxD,EAAA,OACG,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA,IAAS,OAAO,KAAA,KAAU,UAAA;AAEtE;AAMA,SAAS,yBAAyB,IAAA,EAAwB;AACxD,EAAA,OACE,gBAAgB,IAAI,CAAA,IACpB,QAAQ,GAAA,CAAI,IAAA,EAAM,MAAM,CAAA,KAAM,6BAAA;AAElC;AAEA,SAAS,gBAAgB,IAAA,EAAmC;AAC1D,EAA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M,CAAC,CAAC;AAAA,OAC9D;AAAA,IACF;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-HP6LWBLB.cjs","sourcesContent":["/**\n * Cross-dialect detection of \"this relation does not exist yet\" errors.\n *\n * Shared so the schema bootstrap (`loadActiveSchemaWithBootstrap`) and\n * the durable contribution-materialization gate (#135) agree on what a\n * missing-table failure looks like, and — critically — so neither one\n * swallows a genuine system fault (connection/permission/driver error)\n * as a benign \"not bootstrapped yet\".\n *\n * Detection walks the error's `cause` chain because Drizzle (>= the\n * `DrizzleQueryError` era, drizzle-orm ≥ 0.36) wraps every failure from a\n * query-builder call (`db.select()`, `db.insert()`, …): the wrapper's\n * `.message` becomes the failed query text and the real driver error —\n * which carries both the missing-relation text and the SQLSTATE — is\n * preserved on `.cause`. node-postgres / postgres-js nest the pg error\n * one link deep; better-sqlite3 throws it unwrapped; raw `client.query()`\n * fast paths surface it directly. Walking the chain makes the check\n * wrapper- and driver-agnostic instead of only matching the outermost\n * `.message`, which on Postgres is just the SQL string.\n */\n\nimport { ConfigurationError } from \"../errors\";\n\nconst SQLITE_MISSING_TABLE_PATTERN = \"no such table\";\nconst SQLITE_GENERIC_ERROR_CODE = \"SQLITE_ERROR\";\nconst SQLITE_NOT_AUTHORIZED_CODE = \"SQLITE_AUTH\";\nconst DRIZZLE_QUERY_ERROR_PREFIX = \"Failed query:\";\nconst POSTGRES_UNDEFINED_RELATION_PATTERN =\n /\\b(?:relation|table)\\s+\"[^\"]+\"\\s+does not exist\\b/i;\n\n/**\n * SQLSTATE for PostgreSQL `undefined_table`. Preferred over the\n * human-readable message: it is locale-independent (the \"... does not\n * exist\" text is translated under a non-English `lc_messages`) and is\n * preserved on the underlying driver error even when Drizzle overwrites\n * `.message` with the query text.\n */\nconst POSTGRES_UNDEFINED_TABLE_CODE = \"42P01\";\n\n/**\n * Yields an error and each error reachable by following `.cause`,\n * outermost first. `seen` guards the pathological cyclic-cause case so a\n * self-referential chain can't spin forever.\n *\n * The walk intentionally follows `.cause` through *non-`Error`* links, not just\n * `Error` instances: postgres-js surfaces its driver error as a plain object\n * (message + SQLSTATE `code`) on a Drizzle wrapper's `.cause`, so stopping at\n * the first non-`Error` link would miss it (see the postgres-js test). A plain\n * object is classified by its locale-independent SQLSTATE alone\n * ({@link isPostgresUndefinedTable}); the looser SQLite message substring is\n * consulted only for `Error` instances and raw strings\n * ({@link missingTableMessage}), so an unrelated object in a cause chain that\n * merely mentions one of those phrases is not mistaken for a missing table.\n */\nfunction* errorChain(error: unknown): Generator<unknown, void, void> {\n const seen = new Set<unknown>();\n let current: unknown = error;\n while (current !== undefined && current !== null && !seen.has(current)) {\n seen.add(current);\n yield current;\n current =\n canReadProperty(current) ? Reflect.get(current, \"cause\") : undefined;\n }\n}\n\nfunction canReadProperty(value: unknown): value is object {\n return (\n (typeof value === \"object\" && value !== null) || typeof value === \"function\"\n );\n}\n\n/**\n * Whether a single chain link is a PostgreSQL `undefined_table` failure,\n * identified by its SQLSTATE rather than a message substring.\n */\nfunction isPostgresUndefinedTable(link: unknown): boolean {\n return (\n canReadProperty(link) &&\n Reflect.get(link, \"code\") === POSTGRES_UNDEFINED_TABLE_CODE\n );\n}\n\nfunction messageProperty(link: unknown): string | undefined {\n if (typeof link === \"string\") return link;\n if (link instanceof Error) return link.message;\n const message =\n canReadProperty(link) ?\n (Reflect.get(link, \"message\") as unknown)\n : undefined;\n return typeof message === \"string\" ? message : undefined;\n}\n\nfunction errorMessage(link: unknown): string {\n return messageProperty(link) ?? String(link);\n}\n\n/**\n * The message a SQLite missing-table substring match may be tested against — but\n * only for `Error` instances and raw `string` links, never an arbitrary plain\n * object.\n *\n * Generic \"does not exist\" is deliberately not substring-matched: PostgreSQL uses\n * that phrase for undefined columns, functions, types, and relations. PostgreSQL\n * missing tables are classified by SQLSTATE 42P01 when available, or by the\n * narrower driver-message shape `relation/table \"...\" does not exist` when a\n * bring-your-own driver omits SQLSTATE. SQLite does not expose a portable\n * SQLSTATE here, so the narrow \"no such table\" engine message is still accepted.\n */\nfunction missingTableMessage(link: unknown): string | undefined {\n return typeof link === \"string\" || link instanceof Error ?\n messageProperty(link)\n : undefined;\n}\n\nfunction sqliteErrorCode(link: unknown): unknown {\n if (!canReadProperty(link)) return undefined;\n return Reflect.get(link, \"code\");\n}\n\n/**\n * Cloudflare D1 / Durable Objects may surface a missing-table failure as the\n * generic SQLite code with no detail. Accept the bare marker, but do not\n * substring-match detailed `SQLITE_ERROR: ...` failures: those include syntax\n * errors and bind-limit faults that must stay loud.\n */\nfunction isBareSqliteErrorMarker(link: unknown): boolean {\n const message = messageProperty(link);\n if (message === SQLITE_GENERIC_ERROR_CODE) return true;\n if (sqliteErrorCode(link) !== SQLITE_GENERIC_ERROR_CODE) return false;\n return (\n message === undefined ||\n message === SQLITE_GENERIC_ERROR_CODE ||\n message.includes(SQLITE_MISSING_TABLE_PATTERN)\n );\n}\n\nfunction isPostgresUndefinedRelationMessage(link: unknown): boolean {\n const message = errorMessage(link);\n if (message.startsWith(DRIZZLE_QUERY_ERROR_PREFIX)) return false;\n return POSTGRES_UNDEFINED_RELATION_PATTERN.test(message);\n}\n\n/**\n * Whether any link in the cause chain is a PostgreSQL \"insufficient\n * resources\" failure (SQLSTATE class 53: disk_full, out_of_memory,\n * configuration_limit_exceeded, ...). Parallel index builds surface\n * shared-memory exhaustion this way (53100 from dsm_impl_posix on hosts\n * with a small /dev/shm); callers retry such work with parallelism\n * disabled. Identified by the locale-independent 5-character SQLSTATE\n * prefix only — never by message text.\n */\nexport function isInsufficientResourcesError(error: unknown): boolean {\n for (const link of errorChain(error)) {\n if (!canReadProperty(link)) continue;\n const code: unknown = Reflect.get(link, \"code\");\n if (typeof code === \"string\" && code.length === 5 && code.startsWith(\"53\"))\n return true;\n }\n return false;\n}\n\nexport function isMissingTableError(error: unknown): boolean {\n // SQLSTATE 42P01 is locale-independent and structural, so it is honored on\n // *every* link — including a plain driver-error object reached only by walking\n // through a non-`Error` `.cause` (postgres-js).\n //\n // The SQLite message substring is honored only while every prior link in the\n // chain was an `Error` (or the top-level string) — the reach of the\n // pre-broadening walk, which stopped at the first non-`Error` `.cause`.\n let everyPriorLinkWasError = true;\n for (const link of errorChain(error)) {\n if (isPostgresUndefinedTable(link)) return true;\n if (isPostgresUndefinedRelationMessage(link)) return true;\n if (isBareSqliteErrorMarker(link)) return true;\n if (everyPriorLinkWasError) {\n const message = missingTableMessage(link);\n if (message?.includes(SQLITE_MISSING_TABLE_PATTERN) === true) {\n return true;\n }\n }\n if (!(link instanceof Error)) everyPriorLinkWasError = false;\n }\n return false;\n}\n\n/**\n * Whether SQLite rejected a statement through its authorizer. Cloudflare D1\n * and Durable Objects surface this as `not authorized: SQLITE_AUTH`, usually on\n * a Drizzle wrapper's `.cause`; native drivers may instead expose\n * `code: \"SQLITE_AUTH\"`. Both shapes are structural enough to distinguish from\n * an unrelated permission or connection failure.\n */\nexport function isSqliteNotAuthorizedError(error: unknown): boolean {\n for (const link of errorChain(error)) {\n if (sqliteErrorCode(link) === SQLITE_NOT_AUTHORIZED_CODE) return true;\n const message = messageProperty(link);\n if (\n message?.includes(SQLITE_NOT_AUTHORIZED_CODE) === true &&\n message.toLowerCase().includes(\"not authorized\")\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction historyMissingRecordedRelationsError(\n details: Record<string, unknown>,\n cause: unknown,\n): ConfigurationError {\n return new ConfigurationError(\n \"history: true requires the recorded-time relations to exist, but a recorded relation is missing.\",\n details,\n {\n cause,\n suggestion:\n \"Create the recorded-time relations (typegraph_recorded_nodes, typegraph_recorded_edges, typegraph_recorded_clock) — e.g. re-run the generated migration SQL — on this database before enabling history capture.\",\n },\n );\n}\n\n/**\n * Converts missing recorded-relation failures into the actionable precondition\n * error used by construction-time history checks. Capture paths use this after\n * the live write has already succeeded inside the same transaction; recorded\n * read paths use it when query/schema swapping reaches a recorded table that\n * has not been materialized yet.\n */\nexport async function withRecordedRelationsPrecondition<T>(\n promise: Promise<T>,\n details: Record<string, unknown>,\n): Promise<T> {\n try {\n return await promise;\n } catch (error) {\n if (!isMissingTableError(error)) throw error;\n throw historyMissingRecordedRelationsError(\n { ...details, code: \"RECORDED_RELATIONS_MISSING\" },\n error,\n );\n }\n}\n\n/**\n * Engine \"vector dimension mismatch\" message shapes. pgvector:\n * `expected 384 dimensions, not 512`; libSQL / sqlite-vec surface a similar\n * `expected N … got/not M`. The first capture is the dimension the *stored*\n * column expects; the optional second is the dimension that was *attempted*.\n */\nconst DIMENSION_MISMATCH_PATTERN =\n /expected (\\d+) dimensions(?:[,\\s]+(?:not|got|but got|but)\\s*(\\d+))?/i;\n\n/**\n * Parses an engine vector-dimension-mismatch error into `{ expected, actual }`\n * by walking the `.cause` chain (drivers wrap the real error). `expected` is\n * the stored column's dimension; `actual` (when the message includes it) is the\n * attempted vector's dimension. Returns `undefined` for unrelated errors.\n */\nexport function parseDimensionMismatch(\n error: unknown,\n): { expected: number; actual: number | undefined } | undefined {\n for (const link of errorChain(error)) {\n const message = errorMessage(link);\n const match = DIMENSION_MISMATCH_PATTERN.exec(message);\n if (match) {\n return {\n expected: Number(match[1]),\n actual: match[2] === undefined ? undefined : Number(match[2]),\n };\n }\n }\n return undefined;\n}\n"]}