@nicia-ai/typegraph 0.28.1 → 0.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/backend/postgres/index.cjs +24 -762
- package/dist/backend/postgres/index.cjs.map +1 -1
- package/dist/backend/postgres/index.d.cts +24 -5
- package/dist/backend/postgres/index.d.ts +24 -5
- package/dist/backend/postgres/index.js +11 -753
- package/dist/backend/postgres/index.js.map +1 -1
- package/dist/backend/postgres/pglite.cjs +52 -0
- package/dist/backend/postgres/pglite.cjs.map +1 -0
- package/dist/backend/postgres/pglite.d.cts +116 -0
- package/dist/backend/postgres/pglite.d.ts +116 -0
- package/dist/backend/postgres/pglite.js +50 -0
- package/dist/backend/postgres/pglite.js.map +1 -0
- package/dist/backend/sqlite/index.cjs +23 -27
- package/dist/backend/sqlite/index.d.cts +22 -15
- package/dist/backend/sqlite/index.d.ts +22 -15
- package/dist/backend/sqlite/index.js +10 -10
- package/dist/backend/sqlite/libsql.cjs +18 -14
- package/dist/backend/sqlite/libsql.cjs.map +1 -1
- package/dist/backend/sqlite/libsql.d.cts +3 -3
- package/dist/backend/sqlite/libsql.d.ts +3 -3
- package/dist/backend/sqlite/libsql.js +17 -13
- package/dist/backend/sqlite/libsql.js.map +1 -1
- package/dist/backend/sqlite/local.cjs +19 -17
- package/dist/backend/sqlite/local.cjs.map +1 -1
- package/dist/backend/sqlite/local.d.cts +9 -3
- package/dist/backend/sqlite/local.d.ts +9 -3
- package/dist/backend/sqlite/local.js +17 -15
- package/dist/backend/sqlite/local.js.map +1 -1
- package/dist/chunk-26HWIIVS.cjs +740 -0
- package/dist/chunk-26HWIIVS.cjs.map +1 -0
- package/dist/chunk-2QA5EHEN.js +181 -0
- package/dist/chunk-2QA5EHEN.js.map +1 -0
- package/dist/chunk-3IRMLJEK.js +206 -0
- package/dist/chunk-3IRMLJEK.js.map +1 -0
- package/dist/{chunk-5MTOKWDA.js → chunk-3JLRHQ67.js} +9 -9
- package/dist/{chunk-5MTOKWDA.js.map → chunk-3JLRHQ67.js.map} +1 -1
- package/dist/{chunk-WVQXAFP3.js → chunk-454I6GDF.js} +46 -5
- package/dist/chunk-454I6GDF.js.map +1 -0
- package/dist/{chunk-CTHNVU6K.cjs → chunk-4BXHVEFB.cjs} +16 -16
- package/dist/{chunk-CTHNVU6K.cjs.map → chunk-4BXHVEFB.cjs.map} +1 -1
- package/dist/{chunk-NMOE2ZEU.cjs → chunk-4LBO6KIF.cjs} +139 -128
- package/dist/chunk-4LBO6KIF.cjs.map +1 -0
- package/dist/chunk-633N7DSE.js +258 -0
- package/dist/chunk-633N7DSE.js.map +1 -0
- package/dist/{chunk-WFUN6DCM.cjs → chunk-7JGLPAFV.cjs} +11 -11
- package/dist/chunk-7JGLPAFV.cjs.map +1 -0
- package/dist/{chunk-ZTREJOGB.js → chunk-AI3RNREM.js} +140 -69
- package/dist/chunk-AI3RNREM.js.map +1 -0
- package/dist/{chunk-TSGBRPNE.js → chunk-ENDUY2CD.js} +46 -46
- package/dist/chunk-ENDUY2CD.js.map +1 -0
- package/dist/{chunk-7V335GHG.cjs → chunk-FLRCVI2G.cjs} +12 -2
- package/dist/chunk-FLRCVI2G.cjs.map +1 -0
- package/dist/chunk-FVIGJTS7.js +305 -0
- package/dist/chunk-FVIGJTS7.js.map +1 -0
- package/dist/chunk-FWBVPATK.cjs +208 -0
- package/dist/chunk-FWBVPATK.cjs.map +1 -0
- package/dist/chunk-IE6GN7L3.cjs +319 -0
- package/dist/chunk-IE6GN7L3.cjs.map +1 -0
- package/dist/{chunk-PGU2XKMA.js → chunk-IUIJJYPI.js} +117 -106
- package/dist/chunk-IUIJJYPI.js.map +1 -0
- package/dist/{chunk-E5ROA3MN.js → chunk-IX7RE7CG.js} +3 -3
- package/dist/{chunk-E5ROA3MN.js.map → chunk-IX7RE7CG.js.map} +1 -1
- package/dist/{chunk-YEDQLNVE.cjs → chunk-JIEJCTDS.cjs} +30 -2
- package/dist/chunk-JIEJCTDS.cjs.map +1 -0
- package/dist/{chunk-WZH2MKHW.cjs → chunk-K4N35E7B.cjs} +101 -101
- package/dist/{chunk-WZH2MKHW.cjs.map → chunk-K4N35E7B.cjs.map} +1 -1
- package/dist/{chunk-NZ5PMBTG.js → chunk-K5P5OZXS.js} +12 -3
- package/dist/chunk-K5P5OZXS.js.map +1 -0
- package/dist/chunk-K5VREXMZ.js +738 -0
- package/dist/chunk-K5VREXMZ.js.map +1 -0
- package/dist/chunk-LUHU4T2F.cjs +12 -0
- package/dist/{chunk-4FJVSF3K.cjs.map → chunk-LUHU4T2F.cjs.map} +1 -1
- package/dist/{chunk-O57GYGYK.js → chunk-M6OC455F.js} +32 -18
- package/dist/chunk-M6OC455F.js.map +1 -0
- package/dist/{chunk-OYLF3IC7.js → chunk-MAQJYNJR.js} +4 -4
- package/dist/chunk-MAQJYNJR.js.map +1 -0
- package/dist/{chunk-OOS2RKRH.js → chunk-MXE2U3EX.js} +4 -4
- package/dist/{chunk-OOS2RKRH.js.map → chunk-MXE2U3EX.js.map} +1 -1
- package/dist/{chunk-TKM2WDT4.js → chunk-N2OEOGBB.js} +386 -1093
- package/dist/chunk-N2OEOGBB.js.map +1 -0
- package/dist/{chunk-EJCDOA37.js → chunk-R4JOBEJU.js} +5 -5
- package/dist/{chunk-EJCDOA37.js.map → chunk-R4JOBEJU.js.map} +1 -1
- package/dist/{chunk-FFHW2JEK.cjs → chunk-RP7YITHX.cjs} +32 -17
- package/dist/chunk-RP7YITHX.cjs.map +1 -0
- package/dist/{chunk-PYJOBZR3.cjs → chunk-SGPXKJ4A.cjs} +60 -60
- package/dist/chunk-SGPXKJ4A.cjs.map +1 -0
- package/dist/{chunk-U5ROKVRF.js → chunk-TQOYM4LN.js} +29 -3
- package/dist/chunk-TQOYM4LN.js.map +1 -0
- package/dist/{chunk-PN37HVAV.cjs → chunk-UESTHN47.cjs} +153 -71
- package/dist/chunk-UESTHN47.cjs.map +1 -0
- package/dist/chunk-VFX3LC76.cjs +183 -0
- package/dist/chunk-VFX3LC76.cjs.map +1 -0
- package/dist/chunk-WEMZM7J7.cjs +270 -0
- package/dist/chunk-WEMZM7J7.cjs.map +1 -0
- package/dist/{chunk-NYQFPGYP.cjs → chunk-WFCECD6Q.cjs} +423 -1139
- package/dist/chunk-WFCECD6Q.cjs.map +1 -0
- package/dist/{chunk-EK6RJ373.cjs → chunk-YQGLVWB2.cjs} +7 -7
- package/dist/{chunk-EK6RJ373.cjs.map → chunk-YQGLVWB2.cjs.map} +1 -1
- package/dist/{chunk-X3244EKP.cjs → chunk-ZFWNO3GE.cjs} +48 -4
- package/dist/chunk-ZFWNO3GE.cjs.map +1 -0
- package/dist/ddl-BSFlbGQF.d.cts +38 -0
- package/dist/ddl-EdkIiFVU.d.ts +38 -0
- package/dist/{extension-types-B78CZfA5.d.cts → extension-types-CwHV-Uk4.d.cts} +4 -4
- package/dist/{extension-types-B78CZfA5.d.ts → extension-types-CwHV-Uk4.d.ts} +4 -4
- package/dist/graph-extension/index.cjs +19 -19
- package/dist/graph-extension/index.d.cts +4 -4
- package/dist/graph-extension/index.d.ts +4 -4
- package/dist/graph-extension/index.js +4 -4
- package/dist/{index-CWdBFWbI.d.ts → index-DzeIiMO3.d.ts} +30 -3
- package/dist/{index-Bilw0pYm.d.cts → index-Ln_KHTGA.d.cts} +30 -3
- package/dist/index.cjs +1542 -1011
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +142 -12
- package/dist/index.d.ts +142 -12
- package/dist/index.js +1138 -643
- package/dist/index.js.map +1 -1
- package/dist/indexes/index.cjs +19 -19
- package/dist/indexes/index.d.cts +9 -9
- package/dist/indexes/index.d.ts +9 -9
- package/dist/indexes/index.js +5 -5
- package/dist/interchange/index.cjs +8 -14
- package/dist/interchange/index.cjs.map +1 -1
- package/dist/interchange/index.d.cts +5 -16
- package/dist/interchange/index.d.ts +5 -16
- package/dist/interchange/index.js +3 -9
- package/dist/interchange/index.js.map +1 -1
- package/dist/{manager-ehLTTNq0.d.ts → manager-BbdyNhkv.d.ts} +2 -2
- package/dist/{manager-c1MGaVVR.d.cts → manager-wTDgjoXG.d.cts} +2 -2
- package/dist/{materialize-indexes-DFavFQah.d.ts → materialize-indexes-lkawaDor.d.ts} +1 -1
- package/dist/{materialize-indexes-BQfaAZKA.d.cts → materialize-indexes-oanE3RU0.d.cts} +1 -1
- package/dist/{ddl-0Ooc2dpL.d.ts → postgres-CK2ByP1q.d.cts} +2 -471
- package/dist/{ddl-Dza3kDrI.d.cts → postgres-ymXYC6Rr.d.ts} +2 -471
- package/dist/profiler/index.cjs +10 -10
- package/dist/profiler/index.d.cts +7 -7
- package/dist/profiler/index.d.ts +7 -7
- package/dist/profiler/index.js +3 -3
- package/dist/schema/index.cjs +33 -33
- package/dist/schema/index.d.cts +7 -7
- package/dist/schema/index.d.ts +7 -7
- package/dist/schema/index.js +10 -10
- package/dist/{sqlite-BxZUPbyD.d.ts → sqlite-DxH1lrwD.d.cts} +2 -468
- package/dist/{sqlite-mvpXjEeB.d.cts → sqlite-R8YGOqVQ.d.ts} +2 -468
- package/dist/{store-Ufc1Eoey.d.ts → store--z1Tmk7U.d.cts} +124 -5
- package/dist/{store-D7YEMg2v.d.cts → store-CNKM334w.d.ts} +124 -5
- package/dist/{types-CMQymcwk.d.cts → types-BBiDqJCU.d.ts} +252 -46
- package/dist/{types-B-sJJ4GQ.d.ts → types-CMvxx2kd.d.ts} +2 -2
- package/dist/{types-CmUA9sal.d.cts → types-D5B6Be5c.d.cts} +2 -2
- package/dist/{types-CQ7xXJMP.d.ts → types-dL-clxO3.d.cts} +252 -46
- package/dist/{where-CtrLu1Zf.d.ts → where-CAo6wsBZ.d.ts} +2 -2
- package/dist/{where-5zf15aFZ.d.cts → where-bJjuOCeV.d.cts} +2 -2
- package/package.json +20 -5
- package/dist/chunk-3EUKJEQ3.js +0 -77
- package/dist/chunk-3EUKJEQ3.js.map +0 -1
- package/dist/chunk-4FJVSF3K.cjs +0 -12
- package/dist/chunk-7V335GHG.cjs.map +0 -1
- package/dist/chunk-FFHW2JEK.cjs.map +0 -1
- package/dist/chunk-HTGDWIDE.cjs +0 -89
- package/dist/chunk-HTGDWIDE.cjs.map +0 -1
- package/dist/chunk-LYRUNG6E.cjs +0 -52
- package/dist/chunk-LYRUNG6E.cjs.map +0 -1
- package/dist/chunk-NMOE2ZEU.cjs.map +0 -1
- package/dist/chunk-NYQFPGYP.cjs.map +0 -1
- package/dist/chunk-NZ5PMBTG.js.map +0 -1
- package/dist/chunk-O57GYGYK.js.map +0 -1
- package/dist/chunk-OYLF3IC7.js.map +0 -1
- package/dist/chunk-PCHTTG42.js +0 -47
- package/dist/chunk-PCHTTG42.js.map +0 -1
- package/dist/chunk-PGU2XKMA.js.map +0 -1
- package/dist/chunk-PN37HVAV.cjs.map +0 -1
- package/dist/chunk-PYJOBZR3.cjs.map +0 -1
- package/dist/chunk-TKM2WDT4.js.map +0 -1
- package/dist/chunk-TSGBRPNE.js.map +0 -1
- package/dist/chunk-U5ROKVRF.js.map +0 -1
- package/dist/chunk-WFUN6DCM.cjs.map +0 -1
- package/dist/chunk-WVQXAFP3.js.map +0 -1
- package/dist/chunk-X3244EKP.cjs.map +0 -1
- package/dist/chunk-YEDQLNVE.cjs.map +0 -1
- package/dist/chunk-ZTREJOGB.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/backend/drizzle/execution/postgres-execution.ts","../src/backend/drizzle/postgres.ts"],"names":["getOrCreateLru","sql","compileQueryWithDialect","createNodeRowMapper","POSTGRES_ROW_MAPPER_CONFIG","createEdgeRowMapper","createUniqueRowMapper","createSchemaVersionRowMapper","POSTGRES_CAPABILITIES","buildVectorCapabilities","buildFulltextCapabilities","tables","tsvectorStrategy","pgvectorStrategy","createVectorSlotLatch","getTableName","quoteIdentifier","createPostgresOperationStrategy","ConfigurationError","generatePgCreateTableSQL","and","eq","mapContributionMaterializationRow","POSTGRES_CONTRIBUTION_MAT_TIMESTAMPS","buildContributionInsertValues","buildContributionOnConflictSet","createContributionMaterializer","gateFulltext","generatePostgresDDL","gateFulltextMethods","mapMaterializationRow","POSTGRES_INDEX_MAT_TIMESTAMPS","inArray","buildMaterializationInsertValues","buildMaterializationOnConflictSet","isNull","mapKindRemovalRow","POSTGRES_KIND_REMOVAL_TIMESTAMPS","buildKindRemovalInsertValues","buildKindRemovalOnConflictSet","options","assertAdoptedDialect","PgDatabase","PgTransaction","createCommonOperationBackend","nowIso","vectorSlotFromParams","mapVectorWriteError","assertVectorSearchLimit","assertPgvectorEfSearch","vectorSlotFromCreateIndexParams","coerceNumericScore","vectorSlotFromDropIndexParams","isMissingTableError"],"mappings":";;;;;;;;;;;;AAyEA,SAAS,mBAAA,CACP,OACA,QAAA,EACwE;AACxE,EAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM;AACzC,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,MAAM,SAAA,GAAY,KAAA;AAClB,EAAA,OAAO,OAAO,SAAA,CAAU,QAAQ,CAAA,KAAM,UAAA;AACxC;AAEA,SAAS,iBAAiB,SAAA,EAA+C;AAKvE,EAAA,OAAO,OAAO,SAAA,KAAc,QAAA,IAAY,mBAAA,CAAoB,WAAW,OAAO,CAAA;AAChF;AAEA,SAAS,eAAe,SAAA,EAA+C;AAUrE,EAAA,OACE,OAAO,cAAc,QAAA,IACrB,mBAAA,CAAoB,WAAW,OAAO,CAAA,IACtC,mBAAA,CAAoB,SAAA,EAAW,aAAa,CAAA;AAEhD;AAEA,SAAS,mBAAmB,SAAA,EAAmD;AAM7E,EAAA,OACE,OAAO,cAAc,UAAA,IACrB,mBAAA,CAAoB,WAAW,QAAQ,CAAA,IACvC,mBAAA,CAAoB,SAAA,EAAW,OAAO,CAAA;AAE1C;AAcO,SAAS,iBAAiB,EAAA,EAA4B;AAC3D,EAAA,MAAM,YAAa,EAAA,CAAuB,OAAA;AAC1C,EAAA,OACE,OAAO,SAAA,KAAc,UAAA,IACrB,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{ getOrCreateLru } from \"./lru\";\nimport {\n type CompiledSqlQuery,\n compileQueryWithDialect,\n type PreparedSqlStatement,\n type SqlExecutionAdapter,\n} from \"./types\";\n\n/**\n * Edge-safe: this module is loaded on Cloudflare Workers / Vercel Edge\n * via `@neondatabase/serverless`, so it must not statically import any\n * `node:*` module. Use only platform-neutral primitives.\n */\n\ntype PgQueryResult = Readonly<{\n rows: readonly unknown[];\n}>;\n\n/**\n * The wire-protocol-shaped client the fast path calls. Both the wrapped\n * node-postgres and postgres-js clients normalize to this signature; what\n * differs is whether the underlying driver gets a server-side prepared\n * statement (node-postgres path) or relies on its own internal preparation\n * (postgres-js).\n */\ntype PgQueryClient = Readonly<{\n query: (sqlText: string, params: readonly unknown[]) => Promise<PgQueryResult>;\n}>;\n\n/**\n * Minimal shape of the node-postgres / @neondatabase/serverless client\n * we rely on. Both accept either positional `query(text, values)`\n * (unnamed) or the configuration-object form `query({name, text, values})`\n * which uses a server-side prepared statement keyed by `name`.\n */\ntype NodePgQueryConfig = Readonly<{\n name: string;\n text: string;\n values: readonly unknown[];\n}>;\n\ntype NodePgClient = Readonly<{\n query: ((\n sqlText: string,\n params?: readonly unknown[],\n ) => Promise<PgQueryResult>) &\n ((config: NodePgQueryConfig) => Promise<PgQueryResult>);\n}>;\n\n/**\n * Minimal shape of the postgres-js tagged-template `Sql` client we rely on\n * for the raw fast path. `unsafe(sqlText, params)` is postgres-js's\n * parameterized-raw-SQL entry point and resolves to a row array.\n */\ntype PostgresJsClient = ((...args: readonly unknown[]) => unknown) &\n Readonly<{\n unsafe: (\n sqlText: string,\n params?: readonly unknown[],\n ) => PromiseLike<readonly unknown[]>;\n }>;\n\ntype PgClientCarrier = Readonly<{\n $client?: unknown;\n}>;\n\nexport type AnyPgDatabase = PgDatabase<PgQueryResultHKT, Record<string, unknown>>;\n\nexport type PostgresExecutionAdapter = SqlExecutionAdapter;\n\nfunction hasFunctionProperty<K extends string>(\n value: unknown,\n property: K,\n): value is Readonly<Record<K, (...args: readonly unknown[]) => unknown>> {\n if (value === undefined || value === null) {\n return false;\n }\n const candidate = value as Readonly<Record<K, unknown>>;\n return typeof candidate[property] === \"function\";\n}\n\nfunction isPgNativeClient(candidate: unknown): candidate is NodePgClient {\n // pg `Pool` / `Client` and @neondatabase/serverless `Pool` / `Client`\n // are object instances with a `.query` method. We require non-callable\n // here so we don't accidentally swallow the postgres-js or neon-http\n // tagged-template clients (both callable, both also expose `.query`).\n return typeof candidate === \"object\" && hasFunctionProperty(candidate, \"query\");\n}\n\nfunction isPgliteClient(candidate: unknown): candidate is NodePgClient {\n // PGlite (Postgres-in-WASM) exposes `.query(sql, params, options)` like\n // node-postgres and so also satisfies `isPgNativeClient` — but it does NOT\n // accept the `{name, text, values}` named-statement config form. Passing\n // that object doesn't merely fail the call: it desyncs PGlite's single\n // wire connection, so every subsequent query errors with `08P01`. Detect\n // PGlite structurally via `dumpDataDir` (a PGlite-specific method absent on\n // pg `Pool`/`Client`) so `resolvePgClient` can route it to the unnamed\n // positional wrapper regardless of `prepareStatements`. Duck-typed with no\n // static import, keeping this module dependency-free and edge-safe.\n return (\n typeof candidate === \"object\" &&\n hasFunctionProperty(candidate, \"query\") &&\n hasFunctionProperty(candidate, \"dumpDataDir\")\n );\n}\n\nfunction isPostgresJsClient(candidate: unknown): candidate is PostgresJsClient {\n // postgres-js's tagged-template Sql is callable, has `.unsafe` (raw\n // parameterized executor), and has `.begin` (transaction starter).\n // Neon HTTP is also callable + has `.unsafe`, but that `.unsafe` is a\n // fragment builder rather than a query executor, so we discriminate\n // on `.begin` (postgres-js only).\n return (\n typeof candidate === \"function\" &&\n hasFunctionProperty(candidate, \"unsafe\") &&\n hasFunctionProperty(candidate, \"begin\")\n );\n}\n\n/**\n * @neondatabase/serverless's `neon(url)` HTTP-only tagged-template\n * function. Distinguishing markers vs postgres-js: `.transaction`\n * (an HTTP-batch transaction submitter) instead of `.begin`. Its\n * `.query`/`.unsafe` methods have different signatures from pg's, so\n * the fast path can't drive them safely — Drizzle's neon-http session\n * handles them correctly via the `db.execute` slow path.\n *\n * Exported so the backend factory can auto-disable the `transactions`\n * capability when this driver is detected (HTTP can't hold a session,\n * so multi-statement transactions are not available regardless).\n */\nexport function isNeonHttpClient(db: AnyPgDatabase): boolean {\n const candidate = (db as PgClientCarrier).$client;\n return (\n typeof candidate === \"function\" &&\n hasFunctionProperty(candidate, \"transaction\") &&\n !hasFunctionProperty(candidate, \"begin\")\n );\n}\n\n/**\n * Default cap on the number of distinct SQL strings tracked for\n * server-side prepared statements. Mirrors the SQLite adapter's\n * `DEFAULT_PREPARED_STATEMENT_CACHE_MAX`. High-cardinality SQL text —\n * variable-length IN-list expansions, generated aliases, custom\n * `backend.execute()` calls — would otherwise grow this map (and the\n * matching per-session prepared-statement memory inside PostgreSQL)\n * without bound.\n */\nconst DEFAULT_POSTGRES_STATEMENT_CACHE_MAX = 256;\n\n/**\n * Module-scope cache mapping each unique SQL text to a stable\n * prepared-statement name. PostgreSQL only requires statement names to\n * be unique per session, so a monotonic counter is sufficient — and\n * avoids depending on a hash primitive (`node:crypto` doesn't exist on\n * Cloudflare Workers, Web Crypto's digest is async).\n *\n * The cache is module-scope on purpose: pg `Pool` reuses connections,\n * and the same SQL text needs the same statement name across every\n * adapter that might end up driving the same connection. Without\n * shared naming, two adapters could try to register two different\n * statements under the same name on a recycled connection.\n *\n * Bounded by `cacheMax` per call (LRU eviction). The counter is\n * deliberately independent of the cache size so eviction never\n * recycles a name — a recycled name could collide with a still-cached\n * statement on a long-lived pg connection (\"prepared statement\n * already exists\" error with different text).\n */\nconst STATEMENT_NAME_CACHE = new Map<string, string>();\nlet nextStatementId = 0;\n\nfunction statementNameFor(sqlText: string, cacheMax: number): string {\n return getOrCreateLru(STATEMENT_NAME_CACHE, sqlText, cacheMax, () => {\n const name = `tg_${nextStatementId}`;\n nextStatementId += 1;\n return name;\n });\n}\n\n/**\n * Test-only: reset the module-scope statement-name state. Used to\n * isolate tests that assert on counter values or eviction behavior.\n */\nexport function resetStatementNameCacheForTests(): void {\n STATEMENT_NAME_CACHE.clear();\n nextStatementId = 0;\n}\n\n/**\n * Walks a row and replaces any `Date` instance with its ISO-string\n * equivalent. Used to normalize node-postgres / neon-serverless output\n * when we bypass Drizzle's session: pg's default type parsers return\n * `Date` objects for `timestamptz` / `timestamp` / `date` columns, but\n * TypeGraph's row contract everywhere downstream is \"timestamps come\n * back as ISO strings.\" Drizzle's session installs a per-query type\n * override that does the same thing; this is the dependency-free,\n * edge-safe equivalent.\n *\n * O(columns × rows) — negligible for the row counts TypeGraph queries\n * return (typical: 1–100 rows × 5–30 columns).\n */\nfunction normalizeRow(row: unknown): unknown {\n if (row === null || typeof row !== \"object\") return row;\n let mutated: Record<string, unknown> | undefined;\n for (const key of Object.keys(row)) {\n const value = (row as Record<string, unknown>)[key];\n if (value instanceof Date) {\n mutated ??= { ...(row as Record<string, unknown>) };\n mutated[key] = value.toISOString();\n }\n }\n return mutated ?? row;\n}\n\nfunction normalizeRows(\n rows: readonly unknown[],\n): readonly unknown[] {\n // Single-pass scan; only allocate a new array if any row contained a\n // Date that needed normalizing. Most rows on most queries don't.\n let mutated: unknown[] | undefined;\n for (let index = 0; index < rows.length; index += 1) {\n const original = rows[index];\n const normalized = normalizeRow(original);\n if (normalized !== original) {\n mutated ??= [...rows] as unknown[];\n mutated[index] = normalized;\n }\n }\n return mutated ?? rows;\n}\n\n/**\n * Wraps a node-postgres / neon-serverless client so every call goes\n * through a server-side prepared statement keyed by a stable name. The\n * first call on each connection parses + plans + executes; subsequent\n * calls with the same statement name reuse the cached plan and skip\n * both parse and plan phases. Measurable on multi-CTE TypeGraph\n * queries: 3-hop drops from ~7-12ms (parse + plan + execute every call)\n * to ~0.8ms median (execute only).\n *\n * Returned rows are normalized so that `Date` objects from default pg\n * type parsers become ISO strings, matching the row shape Drizzle's\n * session would produce. Without this, `ctx.<alias>.meta.createdAt`\n * style accessors in the SELECT-result path return Date instances,\n * breaking user code that expects strings.\n */\nfunction wrapNodePgClient(\n client: NodePgClient,\n cacheMax: number,\n): PgQueryClient {\n return {\n async query(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<PgQueryResult> {\n const result = await client.query({\n name: statementNameFor(sqlText, cacheMax),\n text: sqlText,\n values: params,\n });\n return { rows: normalizeRows(result.rows) };\n },\n };\n}\n\n/**\n * Variant that bypasses server-side prepared statements entirely.\n * Required for pgbouncer in transaction-pool mode (named statements\n * registered on one backend connection aren't visible on the next),\n * and useful when memory-sensitive workloads can't afford to keep\n * prepared statements warm across the pool.\n *\n * Same Date→ISO normalization as `wrapNodePgClient` so the row contract\n * downstream stays identical.\n */\nfunction wrapNodePgClientUnnamed(client: NodePgClient): PgQueryClient {\n return {\n async query(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<PgQueryResult> {\n const result = await client.query(sqlText, params);\n return { rows: normalizeRows(result.rows) };\n },\n };\n}\n\nfunction adaptPostgresJsClient(sql: PostgresJsClient): PgQueryClient {\n return {\n async query(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<PgQueryResult> {\n // postgres-js handles its own statement preparation internally\n // (controlled by the `prepare` connection option, default true),\n // so we don't need to name statements here ourselves.\n const rows = await sql.unsafe(sqlText, params);\n return { rows };\n },\n };\n}\n\n/**\n * Resolves a Drizzle-wrapped PostgreSQL client to a uniform `{query}` shape\n * that the fast path can call. Supports:\n *\n * - `drizzle-orm/node-postgres` (pg Pool / Client) — wrapped to use\n * server-side prepared statements with stable counter-derived names\n * keyed by the SQL text (see `statementNameFor`). When\n * `prepareStatements` is `false`, falls back to unnamed\n * `client.query(text, values)` for pgbouncer transaction-pool\n * compatibility.\n * - `drizzle-orm/neon-serverless` (@neondatabase/serverless Pool) —\n * pg-Pool-compatible, takes the same wrapper as node-postgres\n * - `drizzle-orm/postgres-js` (postgres-js tagged-template Sql) — adapted\n * via `.unsafe(sql, params)`. Safe because Drizzle installs transparent\n * parsers on the same client instance at `drizzle()` time, so direct\n * calls and Drizzle-routed calls produce identical row shapes.\n * - `drizzle-orm/pglite` (PGlite, Postgres-in-WASM) — routed to the unnamed\n * wrapper unconditionally. PGlite's `.query` has no named-statement config\n * form (and server-side prepared statements buy nothing for an in-process\n * engine), so `prepareStatements` is ignored for it.\n *\n * Returns `undefined` for `drizzle-orm/neon-http` and any other driver we\n * don't recognize; callers fall back to `db.execute(sql)`, which goes\n * through the Drizzle session and is always correct (just without the\n * server-side prepared-statement perf win).\n */\nfunction resolvePgClient(\n db: AnyPgDatabase,\n prepareStatements: boolean,\n cacheMax: number,\n): PgQueryClient | undefined {\n // Order matters: neon-http and postgres-js are both callable + have\n // `.unsafe`, but neon-http's `.unsafe` is a fragment builder (not a\n // query executor) and its `.query` doesn't accept the {name, text,\n // values} config form. Skip the fast path entirely for neon-http and\n // let Drizzle's session route the call.\n if (isNeonHttpClient(db)) {\n return undefined;\n }\n const client = (db as PgClientCarrier).$client;\n // Must precede `isPgNativeClient`: PGlite matches it too (object with\n // `.query`), but only the unnamed wrapper is safe for it (see\n // `isPgliteClient`).\n if (isPgliteClient(client)) {\n return wrapNodePgClientUnnamed(client);\n }\n if (isPgNativeClient(client)) {\n return prepareStatements\n ? wrapNodePgClient(client, cacheMax)\n : wrapNodePgClientUnnamed(client);\n }\n if (isPostgresJsClient(client)) {\n // postgres-js handles its own preparation internally (controlled\n // by the driver's own `prepare` connection option) — the\n // `prepareStatements` flag here only affects the node-postgres\n // path.\n return adaptPostgresJsClient(client);\n }\n return undefined;\n}\n\n/**\n * Normalizes the result shape of `db.execute(sql)` across drivers.\n *\n * - `drizzle-orm/node-postgres` / `drizzle-orm/neon-serverless` return a\n * pg-style `{ rows, rowCount, ... }` object.\n * - `drizzle-orm/postgres-js` returns the raw postgres-js result, which is\n * a plain array of rows (with extra non-enumerable properties like\n * `count` / `command`).\n *\n * The backend contract is \"a row array.\" Normalize here so every caller\n * downstream can assume the same shape.\n */\nasync function executeDrizzleQuery<TRow>(\n db: AnyPgDatabase,\n query: SQL,\n): Promise<readonly TRow[]> {\n const result = await db.execute(query);\n if (Array.isArray(result)) {\n return result as readonly TRow[];\n }\n return (result as Readonly<{ rows: readonly TRow[] }>).rows;\n}\n\nfunction createPgPreparedStatement(\n pgClient: PgQueryClient,\n sqlText: string,\n): PreparedSqlStatement {\n return {\n async execute<TRow>(params: readonly unknown[]): Promise<readonly TRow[]> {\n const result = await pgClient.query(sqlText, params);\n return result.rows as readonly TRow[];\n },\n };\n}\n\n/**\n * Tuning options for the PostgreSQL execution fast path.\n *\n * Defaults are correct for `drizzle-orm/node-postgres` against a\n * standalone PostgreSQL or session-pooled deployment. Override when:\n *\n * - **Pooling through pgbouncer in transaction-pool mode.** Set\n * `prepareStatements: false`. Named statements registered on one\n * pooled backend connection aren't visible to the next, so the\n * server-side prepared-statement cache must be off.\n * - **High-cardinality SQL text.** If the application emits many\n * distinct compiled SQL strings (variable-length IN-list expansions,\n * custom `backend.execute()` calls, generated aliases), tune\n * `preparedStatementCacheMax` down to bound per-session memory more\n * aggressively, or up if memory is plentiful and you want fewer\n * re-PREPAREs.\n */\nexport type PostgresExecutionAdapterOptions = Readonly<{\n /**\n * When `true` (default), node-postgres / neon-serverless calls go\n * through `client.query({name, text, values})` so PostgreSQL caches\n * the parsed/planned statement per session. Set to `false` to issue\n * unnamed `client.query(text, values)` calls — required for\n * pgbouncer transaction-pool mode.\n */\n prepareStatements?: boolean;\n /**\n * Maximum number of distinct SQL strings tracked for prepared-\n * statement naming. Defaults to `DEFAULT_POSTGRES_STATEMENT_CACHE_MAX`\n * (256). Ignored when `prepareStatements` is `false`.\n */\n preparedStatementCacheMax?: number;\n}>;\n\nexport function createPostgresExecutionAdapter(\n db: AnyPgDatabase,\n options: PostgresExecutionAdapterOptions = {},\n): PostgresExecutionAdapter {\n const prepareStatements = options.prepareStatements ?? true;\n const cacheMax =\n options.preparedStatementCacheMax ?? DEFAULT_POSTGRES_STATEMENT_CACHE_MAX;\n const pgClient = resolvePgClient(db, prepareStatements, cacheMax);\n\n function compile(query: SQL): CompiledSqlQuery {\n return compileQueryWithDialect(db, query, \"PostgreSQL\");\n }\n\n if (pgClient === undefined) {\n return {\n compile,\n async execute<TRow>(query: SQL): Promise<readonly TRow[]> {\n return executeDrizzleQuery<TRow>(db, query);\n },\n };\n }\n\n const pgQueryClient = pgClient;\n\n async function executeCompiled<TRow>(\n compiledQuery: CompiledSqlQuery,\n ): Promise<readonly TRow[]> {\n const result = await pgQueryClient.query(\n compiledQuery.sql,\n compiledQuery.params,\n );\n return result.rows as readonly TRow[];\n }\n\n return {\n compile,\n async execute<TRow>(query: SQL): Promise<readonly TRow[]> {\n // Fast path: compile via Drizzle's dialect, then execute through\n // the wrapped client directly. Bypasses Drizzle's session\n // overhead (logging spans, plan-cache bookkeeping for typed\n // queries we don't use), and on node-postgres this also enables\n // the server-side prepared-statement path because the wrapped\n // client assigns each unique SQL a stable statement name.\n const compiled = compile(query);\n return executeCompiled<TRow>(compiled);\n },\n executeCompiled,\n prepare(sqlText: string): PreparedSqlStatement {\n return createPgPreparedStatement(pgQueryClient, sqlText);\n },\n };\n}\n","/**\n * PostgreSQL backend adapter for TypeGraph.\n *\n * Works with any Drizzle PostgreSQL database instance. Tested against:\n * - `drizzle-orm/node-postgres` (pg Pool / Client)\n * - `drizzle-orm/postgres-js` (postgres-js tagged-template client)\n * - `drizzle-orm/neon-serverless` (@neondatabase/serverless Pool / Client)\n * - `drizzle-orm/neon-http` (@neondatabase/serverless `neon(url)`) —\n * transactions are auto-disabled because HTTP can't hold a session;\n * use `drizzle-orm/neon-serverless` if you need transactional writes.\n *\n * - `drizzle-orm/pglite` (PGlite, Postgres-in-WASM) — the execution\n * fast path detects PGlite and routes it correctly (its `.query` has no\n * named-statement form). For a batteries-included in-process setup, see\n * `createLocalPgliteBackend` in `@nicia-ai/typegraph/postgres/pglite`.\n *\n * Other pg-protocol Drizzle adapters (Vercel Postgres, Supabase via pg)\n * work unchanged because they all expose a compatible `db.execute()` /\n * `db.transaction()` surface.\n *\n * @example\n * ```typescript\n * import { drizzle } from \"drizzle-orm/node-postgres\";\n * import { Pool } from \"pg\";\n * import { createPostgresBackend, tables } from \"@nicia-ai/typegraph/postgres\";\n *\n * const pool = new Pool({ connectionString: process.env.DATABASE_URL });\n * const db = drizzle(pool);\n * const backend = createPostgresBackend(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 { PgDatabase, PgTransaction } from \"drizzle-orm/pg-core\";\n\nimport { ConfigurationError } from \"../../errors\";\nimport type { SqlTableNames } from \"../../query/compiler/schema\";\nimport { quoteIdentifier } from \"../../query/compiler/utils\";\nimport {\n buildFulltextCapabilities,\n type FulltextStrategy,\n tsvectorStrategy,\n} from \"../../query/dialect/fulltext-strategy\";\nimport {\n assertPgvectorEfSearch,\n pgvectorStrategy,\n} from \"../../query/dialect/vector/pgvector-strategy\";\nimport {\n assertVectorSearchLimit,\n buildVectorCapabilities,\n type VectorSlot,\n type VectorStrategy,\n} from \"../../query/dialect/vector-strategy\";\nimport { isMissingTableError } from \"../../utils/sql-errors\";\nimport {\n type AdoptedTransaction,\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 GraphBackend,\n type IndexMaterializationRow,\n type KindRemovalRow,\n POSTGRES_CAPABILITIES,\n type RecordContributionMaterializationParams,\n type RecordIndexMaterializationParams,\n type RecordKindRemovalParams,\n type SchemaVersionRow,\n type SetActiveVersionParams,\n type TransactionBackend,\n type TransactionOptions,\n type UpsertEmbeddingParams,\n type UpsertFulltextBatchParams,\n type UpsertFulltextParams,\n type VectorSearchParams,\n type VectorSearchResult,\n} from \"../types\";\nimport {\n buildContributionInsertValues,\n buildContributionOnConflictSet,\n createContributionMaterializer,\n gateFulltext,\n gateFulltextMethods,\n mapContributionMaterializationRow,\n POSTGRES_CONTRIBUTION_MAT_TIMESTAMPS,\n} from \"./contribution-materializations\";\nimport { generatePgCreateTableSQL, generatePostgresDDL } from \"./ddl\";\nimport {\n type AnyPgDatabase,\n createPostgresExecutionAdapter,\n isNeonHttpClient,\n type PostgresExecutionAdapter,\n type PostgresExecutionAdapterOptions,\n} from \"./execution/postgres-execution\";\nimport {\n buildMaterializationInsertValues,\n buildMaterializationOnConflictSet,\n mapMaterializationRow,\n POSTGRES_INDEX_MAT_TIMESTAMPS,\n} from \"./index-materializations\";\nimport {\n buildKindRemovalInsertValues,\n buildKindRemovalOnConflictSet,\n mapKindRemovalRow,\n POSTGRES_KIND_REMOVAL_TIMESTAMPS,\n} from \"./kind-removals\";\nimport {\n assertAdoptedDialect,\n type CommonOperationBackend,\n createCommonOperationBackend,\n type InternalOperationBackend,\n} from \"./operation-backend-core\";\nimport { createPostgresOperationStrategy } from \"./operations/strategy\";\nimport {\n coerceNumericScore,\n createEdgeRowMapper,\n createNodeRowMapper,\n createSchemaVersionRowMapper,\n createUniqueRowMapper,\n nowIso,\n POSTGRES_ROW_MAPPER_CONFIG,\n} from \"./row-mappers\";\nimport {\n type PostgresTables,\n tables as defaultTables,\n} from \"./schema/postgres\";\nimport {\n createVectorSlotLatch,\n mapVectorWriteError,\n vectorSlotFromCreateIndexParams,\n vectorSlotFromDropIndexParams,\n vectorSlotFromParams,\n type VectorSlotLatch,\n} from \"./vector-runtime\";\n\n// ============================================================\n// Types\n// ============================================================\n\n/**\n * Options for creating a PostgreSQL backend.\n */\nexport type PostgresBackendOptions = Readonly<{\n /**\n * Custom table definitions. Use createPostgresTables() to customize table names.\n * Defaults to standard TypeGraph table names.\n */\n tables?: PostgresTables;\n /**\n * Fulltext strategy override. Defaults to `tsvectorStrategy`\n * (Postgres built-in `tsvector` + GIN). Pass a custom strategy here to\n * swap the entire fulltext stack — DDL, MATCH condition, rank\n * expression, and snippet generation — for alternate Postgres\n * backends like ParadeDB (`pg_search`), pg_trgm similarity, or\n * pgroonga without forking TypeGraph.\n */\n fulltext?: FulltextStrategy;\n /**\n * Vector strategy override. Defaults to `pgvectorStrategy` (pgvector's\n * `vector(N)` columns + HNSW/IVFFlat). The strategy owns per-`(kind,\n * field)` typed storage — DDL, upsert, delete, similarity search, and\n * ANN index lifecycle — and advertises `strategy.capabilities` as\n * `capabilities.vector`. Pass a custom strategy to swap the entire\n * vector stack for an alternate Postgres extension without forking\n * TypeGraph.\n *\n * Pass `false` to disable vector support entirely. The backend then\n * advertises no `capabilities.vector` and omits the embedding/search\n * methods, mirroring a SQLite connection without sqlite-vec. Required\n * for an in-process Postgres (e.g. PGlite) built without the pgvector\n * extension: the default `pgvectorStrategy` assumes `vector(N)` exists,\n * so any embedding write or `CREATE EXTENSION vector` would otherwise\n * hard-fail at runtime.\n */\n vector?: VectorStrategy | false;\n /**\n * Override specific backend capabilities. Useful when the underlying\n * driver doesn't support a feature TypeGraph would otherwise assume —\n * for example, an HTTP-only Postgres driver that can't hold a session\n * across statements would need `{ transactions: false }` so\n * TypeGraph falls through to non-transactional execution paths.\n *\n * `drizzle-orm/neon-http` is auto-detected and has `transactions`\n * disabled without an explicit override; this option exists for\n * other HTTP-style drivers and for tests that need to simulate a\n * capability gap.\n */\n capabilities?: Partial<BackendCapabilities>;\n /**\n * Use server-side prepared statements (named statements cached per\n * pg connection) on the node-postgres / neon-serverless fast path.\n * Defaults to `true`. Set to `false` when pooling through pgbouncer\n * in transaction-pool mode — pgbouncer routes successive statements\n * over different backend connections, and a `name` registered on one\n * is invisible on the next.\n *\n * No effect on `drizzle-orm/postgres-js` (handles preparation\n * internally) or `drizzle-orm/neon-http` (no fast path).\n */\n prepareStatements?: boolean;\n /**\n * Cap on the number of distinct SQL strings tracked for\n * prepared-statement naming. Defaults to 256. The cache is LRU-\n * bounded so high-cardinality SQL text (variable-length IN-lists,\n * generated aliases, `backend.execute()` calls with one-off SQL)\n * doesn't grow unbounded in either the Node process or in\n * PostgreSQL's per-session prepared-statement memory. Worst-case\n * server-side footprint is roughly `cap × pool size` statements\n * across all pooled connections. Ignored when\n * `prepareStatements` is `false`.\n */\n preparedStatementCacheMax?: number;\n}>;\n\nconst POSTGRES_MAX_BIND_PARAMETERS = 65_535;\nconst NODE_INSERT_PARAM_COUNT = 9;\nconst EDGE_INSERT_PARAM_COUNT = 12;\nconst POSTGRES_NODE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(POSTGRES_MAX_BIND_PARAMETERS / NODE_INSERT_PARAM_COUNT),\n);\nconst POSTGRES_EDGE_INSERT_BATCH_SIZE = Math.max(\n 1,\n Math.floor(POSTGRES_MAX_BIND_PARAMETERS / EDGE_INSERT_PARAM_COUNT),\n);\nconst POSTGRES_GET_NODES_ID_CHUNK_SIZE = Math.max(\n 1,\n POSTGRES_MAX_BIND_PARAMETERS - 2,\n);\nconst POSTGRES_GET_EDGES_ID_CHUNK_SIZE = Math.max(\n 1,\n POSTGRES_MAX_BIND_PARAMETERS - 1,\n);\nconst CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT = 3;\nconst POSTGRES_CHECK_UNIQUE_BATCH_CHUNK_SIZE = Math.max(\n 1,\n POSTGRES_MAX_BIND_PARAMETERS - CHECK_UNIQUE_BATCH_FIXED_PARAM_COUNT,\n);\n\n// ============================================================\n// Utilities\n// ============================================================\n\nconst toNodeRow = createNodeRowMapper(POSTGRES_ROW_MAPPER_CONFIG);\nconst toEdgeRow = createEdgeRowMapper(POSTGRES_ROW_MAPPER_CONFIG);\nconst toUniqueRow = createUniqueRowMapper(POSTGRES_ROW_MAPPER_CONFIG);\nconst toSchemaVersionRow = createSchemaVersionRowMapper(\n POSTGRES_ROW_MAPPER_CONFIG,\n);\n\nfunction buildPostgresCapabilities(\n fulltextStrategy: FulltextStrategy,\n vectorStrategy: VectorStrategy | undefined,\n): BackendCapabilities {\n return {\n ...POSTGRES_CAPABILITIES,\n ...(vectorStrategy === undefined ?\n {}\n : { vector: buildVectorCapabilities(vectorStrategy) }),\n fulltext: buildFulltextCapabilities(fulltextStrategy),\n };\n}\n\n// ============================================================\n// Backend Factory\n// ============================================================\n\n/**\n * Creates a TypeGraph backend for PostgreSQL databases.\n *\n * Works with any Drizzle PostgreSQL instance regardless of the underlying driver.\n *\n * @param db - A Drizzle PostgreSQL database instance\n * @param options - Backend configuration\n * @returns A GraphBackend implementation\n */\nexport function createPostgresBackend(\n db: AnyPgDatabase,\n options: PostgresBackendOptions = {},\n): GraphBackend {\n const tables = options.tables ?? defaultTables;\n const fulltextStrategy = options.fulltext ?? tsvectorStrategy;\n // pgvector is compiled into a standalone Postgres server, so it is wired\n // unconditionally by default (overridable for alternate Postgres vector\n // stacks). `vector: false` disables it — required for an in-process\n // Postgres (PGlite) built without the pgvector extension, where the\n // default strategy's `vector(N)` DDL would hard-fail.\n const vectorStrategy =\n options.vector === false ? undefined : (options.vector ?? pgvectorStrategy);\n // One latch per backend instance, shared with every transaction-scoped\n // backend so a slot's per-field table is created at most once per process.\n // Absent when vector support is disabled.\n const vectorSlotLatch =\n vectorStrategy === undefined ? undefined : createVectorSlotLatch();\n const baseCapabilities = buildPostgresCapabilities(\n fulltextStrategy,\n vectorStrategy,\n );\n // HTTP-only drivers (notably `drizzle-orm/neon-http`) can't hold a\n // session across statements, so multi-statement transactions are\n // unavailable regardless of what we declare. Auto-detect and downgrade\n // the capability so callers get correct fallback behavior without\n // having to remember to override it themselves.\n const httpOnlyOverrides = isNeonHttpClient(db) ? { transactions: false } : {};\n const capabilities: BackendCapabilities = {\n ...baseCapabilities,\n ...httpOnlyOverrides,\n ...options.capabilities,\n };\n const adapterOptions: PostgresExecutionAdapterOptions = {\n ...(options.prepareStatements === undefined ?\n {}\n : { prepareStatements: options.prepareStatements }),\n ...(options.preparedStatementCacheMax === undefined ?\n {}\n : { preparedStatementCacheMax: options.preparedStatementCacheMax }),\n };\n const executionAdapter = createPostgresExecutionAdapter(db, adapterOptions);\n const tableNames: SqlTableNames = {\n nodes: getTableName(tables.nodes),\n edges: getTableName(tables.edges),\n fulltext: tables.fulltextTableName,\n uniques: getTableName(tables.uniques),\n };\n // Pre-quote identifiers so refreshStatistics() doesn't rebuild the\n // ANALYZE statement on every call. Per-field vector tables are created\n // lazily and live outside this base set, so they are not ANALYZEd here.\n const analyzeStatement = sql`ANALYZE ${sql.join(\n [\n tableNames.nodes,\n tableNames.edges,\n getTableName(tables.uniques),\n tableNames.fulltext,\n ].map((name) => quoteIdentifier(name)),\n sql`, `,\n )}`;\n const operationStrategy = createPostgresOperationStrategy(\n tables,\n fulltextStrategy,\n );\n const operations = createPostgresOperationBackend({\n db,\n executionAdapter,\n adapterOptions,\n operationStrategy,\n tableNames,\n capabilities,\n fulltextStrategy,\n vectorStrategy,\n vectorSlotLatch,\n });\n\n /**\n * Runs `fn` inside a Postgres transaction, holding an\n * `pg_advisory_xact_lock` keyed on the graph id. The advisory lock\n * serializes all schema commits per-graph: the read-then-write CAS in\n * `commitSchemaVersion` is safe even for the initial-commit case\n * where there is no row yet to `SELECT ... FOR UPDATE`.\n *\n * Refuses on backends that don't support transactions\n * (`drizzle-orm/neon-http`). The orphan-row crash window cannot be\n * eliminated without atomicity, so silent best-effort degradation is\n * worse than a typed error.\n */\n function runSchemaWriteTransaction<T>(\n graphId: string,\n fn: (tx: CommonOperationBackend) => Promise<T>,\n ): Promise<T> {\n if (!capabilities.transactions) {\n throw new ConfigurationError(\n \"commitSchemaVersion and setActiveVersion require atomic transactions, \" +\n \"but this Postgres backend does not provide them. The drizzle-orm/neon-http \" +\n \"driver communicates over HTTP and cannot hold a session across statements; \" +\n \"use drizzle-orm/neon-serverless (websocket) for transactional writes.\",\n {\n backend: \"postgres\",\n capability: \"transactions\",\n supportsTransactions: false,\n },\n );\n }\n\n return db.transaction(async (tx) => {\n // Advisory lock: hashtext($graphId) is collision-tolerant for the\n // size of an active graph set; collisions just serialize unrelated\n // graphs which is harmless. Held until the transaction commits.\n await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${graphId}))`);\n // Advisory lock is held here, so the schema-write-capable\n // InternalOperationBackend is used intentionally (see its type).\n const txBackend = createTransactionBackend({\n db: tx,\n adapterOptions,\n operationStrategy,\n tableNames,\n capabilities,\n fulltextStrategy,\n vectorStrategy,\n vectorSlotLatch,\n });\n return fn(txBackend);\n });\n }\n\n // Durable fulltext materialization (#135): the dialect-specific\n // marker-table primitives. Orchestration (materialize / assert /\n // per-instance cache) lives once in `createContributionMaterializer`.\n const matTable = tables.contributionMaterializations;\n\n async function ensureContributionMaterializationsTableImpl(): Promise<void> {\n await db.execute(sql.raw(generatePgCreateTableSQL(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 POSTGRES_CONTRIBUTION_MAT_TIMESTAMPS.decode,\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 POSTGRES_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 const contributionMaterializer = createContributionMaterializer({\n dialect: \"postgres\",\n fulltextStrategy,\n fulltextTableName: tables.fulltextTableName,\n execDdl: async (statement) => {\n await db.execute(sql.raw(statement));\n },\n ensureMarkerTable: ensureContributionMaterializationsTableImpl,\n getMarker: getContributionMaterializationRow,\n recordMarker: recordContributionMaterializationRow,\n });\n\n // Shared by `transaction()` (TypeGraph opens the tx) and\n // `adoptTransaction()` (#134 — the caller already opened it): bind a\n // tx-scoped backend to the *literal* `tx` client and gate fulltext on\n // the durable marker (a cached SELECT, never DDL).\n function bindTransactionBackend(tx: AnyPgDatabase): TransactionBackend {\n const txBackend = createTransactionBackend({\n db: tx,\n adapterOptions,\n operationStrategy,\n tableNames,\n capabilities,\n fulltextStrategy,\n vectorStrategy,\n vectorSlotLatch,\n });\n return gateFulltext(txBackend, contributionMaterializer.assertInitialized);\n }\n\n const backend: GraphBackend = {\n ...operations,\n\n async bootstrapTables(): Promise<void> {\n const statements = generatePostgresDDL(tables, fulltextStrategy);\n for (const statement of statements) {\n await db.execute(sql.raw(statement));\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` loudly\n // rather than self-healing on a read/write path (#135). Shared\n // verbatim with the tx-scoped gate via `gateFulltextMethods`.\n ...gateFulltextMethods(\n operations,\n contributionMaterializer.assertInitialized,\n ),\n\n async executeDdl(ddl: string): Promise<void> {\n await db.execute(sql.raw(ddl));\n },\n\n async ensureIndexMaterializationsTable(): Promise<void> {\n await db.execute(\n sql.raw(generatePgCreateTableSQL(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, POSTGRES_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, POSTGRES_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 POSTGRES_INDEX_MAT_TIMESTAMPS.encode,\n ),\n )\n .onConflictDoUpdate({\n target: t.indexName,\n set: buildMaterializationOnConflictSet(\n t.materializedAt,\n params.materializedAt,\n ),\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.execute(sql.raw(generatePgCreateTableSQL(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, POSTGRES_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, POSTGRES_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 POSTGRES_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.execute(\n sql.raw(generatePgCreateTableSQL(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 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 // Scoped to TypeGraph-managed tables only — we don't touch\n // unrelated tables in the same database. Without fresh stats\n // after a bulk load the planner can pick a reverse-index scan\n // with a filter (5ms forward traversal instead of 0.5ms) until\n // autovacuum catches up.\n await db.execute(analyzeStatement);\n },\n\n async commitSchemaVersion(\n params: CommitSchemaVersionParams,\n ): Promise<SchemaVersionRow> {\n return runSchemaWriteTransaction(params.graphId, (target) =>\n target.commitSchemaVersion(params),\n );\n },\n\n async setActiveVersion(params: SetActiveVersionParams): Promise<void> {\n await runSchemaWriteTransaction(params.graphId, (target) =>\n target.setActiveVersion(params),\n );\n },\n\n async transaction<T>(\n fn: (tx: TransactionBackend, sql: AdoptedTransaction) => Promise<T>,\n options?: TransactionOptions,\n ): Promise<T> {\n // #134/#135: NO DDL or ensure here. The tx-scoped backend's\n // fulltext-touching methods assert the durable contribution\n // marker (one cached SELECT — never DDL) at point of use, exactly\n // like the non-tx wrappers. A transaction that never touches\n // fulltext never asserts; one that does runs pure DML against an\n // already-materialized table, with the \"no DDL in the business\n // transaction\" guarantee backed by the durable fact.\n const txConfig =\n options?.isolationLevel ?\n {\n isolationLevel: options.isolationLevel.replace(\"_\", \" \") as\n | \"read uncommitted\"\n | \"read committed\"\n | \"repeatable read\"\n | \"serializable\",\n }\n : undefined;\n\n return db.transaction(\n async (tx) => fn(bindTransactionBackend(tx), tx),\n txConfig,\n );\n },\n\n adoptTransaction(externalTx: AdoptedTransaction): TransactionBackend {\n // #134: cross-store atomicity is unsafe without real rollback —\n // the caller's relational write on `externalTx` *would* still\n // commit even though the graph write could not be undone. Refuse\n // loudly rather than silently degrade.\n if (!capabilities.transactions) {\n throw new ConfigurationError(\n \"Cross-store atomicity is unavailable on this Postgres backend: \" +\n \"its driver does not support transactions (drizzle-orm/neon-http, \" +\n \"Cloudflare D1). Adopting an external transaction here would let \" +\n \"the caller's relational write commit with no way to roll back \" +\n \"the graph write. Use a node-postgres or neon-serverless \" +\n \"(Pool/WebSocket) connection for cross-store transactions.\",\n {\n backend: \"postgres\",\n capability: \"transactions\",\n supportsTransactions: false,\n },\n );\n }\n assertAdoptedDialect<AnyPgDatabase>(externalTx, PgDatabase, \"postgres\");\n // The caller owns BEGIN/COMMIT/ROLLBACK via its own\n // `db.transaction(...)`. We adopt the literal `tx` client and run\n // pure DML on it — no transaction is opened or closed here, and no\n // DDL is emitted inside the caller's business transaction.\n return bindTransactionBackend(externalTx);\n },\n\n async close(): Promise<void> {\n // Drizzle doesn't expose a close method\n // Users manage connection lifecycle themselves\n },\n };\n\n return backend;\n}\n\ntype CreatePostgresOperationBackendOptions = Readonly<{\n db: AnyPgDatabase;\n executionAdapter: PostgresExecutionAdapter;\n /**\n * Adapter tuning (prepared-statement cache settings). Used to bind a\n * fresh, equivalently-configured adapter to a transaction client when\n * a per-search `efSearch` override opens its own transaction.\n */\n adapterOptions?: PostgresExecutionAdapterOptions | undefined;\n operationStrategy: ReturnType<typeof createPostgresOperationStrategy>;\n tableNames: SqlTableNames;\n capabilities: BackendCapabilities;\n fulltextStrategy: FulltextStrategy;\n /**\n * Active vector strategy (`pgvectorStrategy` unless overridden), or\n * `undefined` when vector support is disabled (`vector: false`).\n */\n vectorStrategy: VectorStrategy | undefined;\n /**\n * Shared per-`(kind, field)` storage-ensure latch. Paired with\n * `vectorStrategy`: both present, or both `undefined`.\n */\n vectorSlotLatch: VectorSlotLatch | undefined;\n}>;\n\ntype CreatePostgresTransactionBackendOptions = Readonly<{\n db: AnyPgDatabase;\n executionAdapter?: PostgresExecutionAdapter;\n adapterOptions?: PostgresExecutionAdapterOptions;\n operationStrategy: ReturnType<typeof createPostgresOperationStrategy>;\n tableNames: SqlTableNames;\n capabilities: BackendCapabilities;\n fulltextStrategy: FulltextStrategy;\n /** Active vector strategy. See {@link CreatePostgresOperationBackendOptions}. */\n vectorStrategy: VectorStrategy | undefined;\n /** Shared storage-ensure latch. See {@link CreatePostgresOperationBackendOptions}. */\n vectorSlotLatch: VectorSlotLatch | undefined;\n}>;\n\nfunction createPostgresOperationBackend(\n options: CreatePostgresOperationBackendOptions,\n): InternalOperationBackend {\n const {\n db,\n executionAdapter,\n adapterOptions,\n operationStrategy,\n tableNames,\n capabilities,\n fulltextStrategy,\n vectorStrategy,\n vectorSlotLatch,\n } = options;\n\n // Route through the execution adapter so driver-specific result shapes\n // (`{rows}` for node-postgres / neon-serverless; bare array for\n // postgres-js) are normalized in one place.\n async function execAll<T>(query: SQL): Promise<readonly T[]> {\n return executionAdapter.execute<T>(query);\n }\n\n async function execGet<T>(query: SQL): Promise<T | undefined> {\n const rows = await executionAdapter.execute<T>(query);\n return rows[0];\n }\n\n async function execRun(query: SQL): Promise<void> {\n await executionAdapter.execute(query);\n }\n\n type VectorSearchRow = Readonly<{ node_id: string; score: number }>;\n\n // One warning per backend instance when `efSearch` is supplied but the\n // driver can't hold a transaction to scope `SET LOCAL` to.\n let efSearchUnsupportedWarned = false;\n function warnEfSearchUnsupported(): void {\n if (efSearchUnsupportedWarned) return;\n efSearchUnsupportedWarned = true;\n if (typeof console === \"undefined\" || typeof console.warn !== \"function\") {\n return;\n }\n console.warn(\n \"[typegraph] efSearch (hnsw.ef_search override) was ignored: this \" +\n \"Postgres backend has transactions disabled (e.g. drizzle-orm/neon-http), \" +\n \"and SET LOCAL needs a transaction to scope the override. Use a \" +\n \"transactional driver (node-postgres / neon-serverless / postgres-js) \" +\n \"to apply efSearch.\",\n );\n }\n\n /**\n * Runs the vector SELECT, applying `hnsw.ef_search` transaction-locally\n * when requested. `SET LOCAL` only takes effect inside an explicit\n * transaction — issued in autocommit it rolls off with the statement\n * and the next pooled query (notably under transaction-mode pgbouncer)\n * sees the session default again. So when `efSearch` is set we bundle\n * `BEGIN; SET LOCAL …; SELECT …; COMMIT;` onto one connection. When\n * absent we take the unchanged single-statement fast path and open no\n * transaction.\n */\n async function runVectorSearch(\n efSearch: number | undefined,\n query: SQL,\n ): Promise<readonly VectorSearchRow[]> {\n if (efSearch === undefined) {\n return execAll<VectorSearchRow>(query);\n }\n if (!capabilities.transactions) {\n warnEfSearchUnsupported();\n return execAll<VectorSearchRow>(query);\n }\n // `SET` cannot be parameterized; `efSearch` is validated as an\n // integer in 1..MAX_HNSW_EF_SEARCH before we get here, so inlining\n // it is injection-safe.\n const setEfSearch = sql.raw(`SET LOCAL hnsw.ef_search = ${efSearch}`);\n if (db instanceof PgTransaction) {\n // Already inside the caller's transaction (low-level\n // backend.transaction / adoptTransaction). `executionAdapter` is\n // bound to this tx client, but SET LOCAL persists to the end of the\n // caller's transaction — leaking the override into their later\n // vector searches and breaking the per-search contract. Snapshot\n // the current frontier, apply the override, then restore it once\n // the SELECT has materialized so the override stays scoped to this\n // one search.\n const [setting] = await execAll<{ ef_search: string }>(\n sql`SELECT current_setting('hnsw.ef_search') AS ef_search`,\n );\n await execRun(setEfSearch);\n const rows = await execAll<VectorSearchRow>(query);\n // Restore only on success: a failed SELECT aborts the caller's\n // transaction, so its rollback discards the SET LOCAL anyway and a\n // restore here would just fail against the aborted tx, masking the\n // real error. `set_config(_, _, true)` is the parameterizable form\n // of SET LOCAL.\n if (setting !== undefined) {\n await execRun(\n sql`SELECT set_config('hnsw.ef_search', ${setting.ef_search}, true)`,\n );\n }\n return rows;\n }\n return db.transaction(async (tx) => {\n // Bind an equivalently-configured adapter to the tx client so the\n // SELECT keeps the server-side prepared-statement fast path and the\n // driver result-shape normalization, rather than a bespoke execute.\n const txAdapter = createPostgresExecutionAdapter(tx, adapterOptions);\n await txAdapter.execute(setEfSearch);\n return txAdapter.execute<VectorSearchRow>(query);\n });\n }\n\n // Runs the strategy's per-field DDL on this backend's connection (the tx\n // client for a transaction-scoped backend) so a slot's table exists\n // before the first write/search hits it.\n async function ensureVectorSlotStorage(slot: VectorSlot): Promise<void> {\n if (vectorStrategy === undefined || vectorSlotLatch === undefined) return;\n await vectorSlotLatch.ensure(vectorStrategy, slot, async (statement) => {\n await execRun(sql.raw(statement));\n });\n }\n\n const commonBackend = createCommonOperationBackend({\n batchConfig: {\n checkUniqueBatchChunkSize: POSTGRES_CHECK_UNIQUE_BATCH_CHUNK_SIZE,\n edgeInsertBatchSize: POSTGRES_EDGE_INSERT_BATCH_SIZE,\n getEdgesChunkSize: POSTGRES_GET_EDGES_ID_CHUNK_SIZE,\n getNodesChunkSize: POSTGRES_GET_NODES_ID_CHUNK_SIZE,\n nodeInsertBatchSize: POSTGRES_NODE_INSERT_BATCH_SIZE,\n },\n execution: {\n execAll,\n execGet,\n execRun,\n },\n nowIso,\n operationStrategy,\n rowMappers: {\n toEdgeRow,\n toNodeRow,\n toSchemaVersionRow,\n toUniqueRow,\n },\n });\n\n const executeCompiled = executionAdapter.executeCompiled;\n const executeRawMethod: Pick<TransactionBackend, \"executeRaw\"> =\n executeCompiled === undefined ?\n {}\n : {\n async executeRaw<T>(\n sqlText: string,\n params: readonly unknown[],\n ): Promise<readonly T[]> {\n return executeCompiled<T>({ params, sql: sqlText });\n },\n };\n\n // Embedding write/search methods are present only when a vector strategy\n // is wired. With `vector: false` (e.g. PGlite without pgvector) they are\n // omitted, so `capabilities.vector` is absent and the store never routes\n // embedding work here — mirroring a SQLite connection without sqlite-vec.\n const vectorEmbeddingMethods =\n vectorStrategy === undefined ?\n {}\n : {\n async upsertEmbedding(params: UpsertEmbeddingParams): Promise<void> {\n const slot = vectorSlotFromParams(params);\n await ensureVectorSlotStorage(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\n async deleteEmbedding(params: DeleteEmbeddingParams): Promise<void> {\n // Ensure the per-field table exists 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), and on Postgres a\n // DELETE against a missing relation INSIDE a transaction aborts the\n // whole transaction — swallowing the JS error can't un-abort it.\n // The idempotent ensure makes the DELETE target an existing\n // (possibly empty) table, so it's always a clean no-op.\n const slot = vectorSlotFromParams(params);\n await ensureVectorSlotStorage(slot);\n const statements = vectorStrategy.buildDelete(slot, params);\n for (const statement of statements) {\n await execRun(statement);\n }\n },\n\n async vectorSearch(\n params: VectorSearchParams,\n ): Promise<readonly VectorSearchResult[]> {\n assertVectorSearchLimit(params.limit);\n // Validate `efSearch` against pgvector's `hnsw.ef_search` ceiling\n // before `runVectorSearch` inlines it into `SET LOCAL`.\n assertPgvectorEfSearch(params.efSearch);\n const slot = vectorSlotFromParams(params);\n await ensureVectorSlotStorage(slot);\n const query = vectorStrategy.buildSearch(slot, params);\n let rows: readonly { node_id: string; score: number }[];\n try {\n rows = await runVectorSearch(params.efSearch, 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 };\n\n const operationBackend: InternalOperationBackend = {\n ...commonBackend,\n ...executeRawMethod,\n ...vectorEmbeddingMethods,\n capabilities,\n fulltextStrategy,\n ...(vectorStrategy === undefined ? {} : { vectorStrategy }),\n dialect: \"postgres\",\n tableNames,\n\n // === Vector Index Operations ===\n\n async createVectorIndex(params: CreateVectorIndexParams): Promise<void> {\n if (vectorStrategy === undefined) return;\n const slot = vectorSlotFromCreateIndexParams(params);\n // Ensure the per-field table exists first (idempotent), then create its\n // ANN index. pgvector's `ownedTables` builds the table only — the HNSW/\n // IVFFlat index is created here (and only here) so it picks up the\n // declared `m`/`ef_construction`/`lists` from `slot.indexParams` rather\n // than defaults.\n await ensureVectorSlotStorage(slot);\n // Honor the `concurrent` flag materializeIndexes passes on Postgres so the\n // ANN build doesn't take a write-blocking lock on a live table. execRun is\n // autocommit, which CONCURRENTLY requires.\n const indexStatement = vectorStrategy.buildCreateIndex?.(slot, {\n concurrent: params.concurrent === true,\n });\n if (indexStatement !== undefined) {\n await execRun(indexStatement);\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 const statements = operationStrategy.buildUpsertFulltextBatch(\n params,\n timestamp,\n );\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async deleteFulltextBatch(\n params: DeleteFulltextBatchParams,\n ): Promise<void> {\n if (params.nodeIds.length === 0) return;\n const statements = operationStrategy.buildDeleteFulltextBatch(params);\n for (const stmt of statements) {\n await execRun(stmt);\n }\n },\n\n async fulltextSearch(\n params: FulltextSearchParams,\n ): Promise<readonly FulltextSearchResult[]> {\n const query = operationStrategy.buildFulltextSearch(params);\n // pg returns `numeric` as a string to preserve precision; coerce at the\n // backend boundary so FulltextSearchResult.score is always `number`.\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 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; treat a missing relation as already-dropped.\n if (!isMissingTableError(error)) throw error;\n }\n },\n\n // === Query Execution ===\n\n async execute<T>(query: SQL): Promise<readonly T[]> {\n return executionAdapter.execute<T>(query);\n },\n\n compileSql(\n query: SQL,\n ): Readonly<{ sql: string; params: readonly unknown[] }> {\n return executionAdapter.compile(query);\n },\n };\n\n return operationBackend;\n}\n\nfunction createTransactionBackend(\n options: CreatePostgresTransactionBackendOptions,\n): InternalOperationBackend {\n const txExecutionAdapter =\n options.executionAdapter ??\n createPostgresExecutionAdapter(options.db, options.adapterOptions);\n\n // A transaction-scoped backend gets its OWN per-field ensure-latch, never\n // the outer process-global one: a `CREATE TABLE/INDEX` that runs inside the\n // caller's transaction and then rolls back must not leave the shared latch\n // marking the slot \"ensured\" (which would skip the re-CREATE and make every\n // later write fail with \"relation does not exist\"). The fresh latch is\n // discarded with the transaction, so the next write re-ensures idempotently.\n // No latch when vector support is disabled (`vector: false`).\n return createPostgresOperationBackend({\n db: options.db,\n executionAdapter: txExecutionAdapter,\n adapterOptions: options.adapterOptions,\n operationStrategy: options.operationStrategy,\n tableNames: options.tableNames,\n capabilities: options.capabilities,\n fulltextStrategy: options.fulltextStrategy,\n vectorStrategy: options.vectorStrategy,\n vectorSlotLatch:\n options.vectorStrategy === undefined ? undefined : createVectorSlotLatch(),\n });\n}\n\n// Re-export schema utilities\nexport type { PostgresTableNames, PostgresTables } from \"./schema/postgres\";\nexport { createPostgresTables, tables } from \"./schema/postgres\";\n"]}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { quoteIdentifier, quotedTableName, vectorScoreExpression, vectorMinScoreCondition, VECTOR_CONTRIBUTION_PREFIX, vectorPhysicalName, assertFiniteEmbedding } from './chunk-AI3RNREM.js';
|
|
2
|
+
import { sql } from 'drizzle-orm';
|
|
3
|
+
|
|
4
|
+
var TABLE_PREFIX = "tg_vec";
|
|
5
|
+
var SQLITE_VEC_MAX_DIMENSIONS = 8e3;
|
|
6
|
+
var SQLITE_VEC_CAPABILITIES = {
|
|
7
|
+
supported: true,
|
|
8
|
+
metrics: ["cosine", "l2"],
|
|
9
|
+
// vec0 always indexes inline, so the portable ANN intent ("hnsw", the
|
|
10
|
+
// `embedding()` default) is honored by real KNN; "none" stays brute-force.
|
|
11
|
+
// Both map to the same vec0 table — only `buildSearch` differs.
|
|
12
|
+
indexTypes: ["hnsw", "none"],
|
|
13
|
+
maxDimensions: SQLITE_VEC_MAX_DIMENSIONS
|
|
14
|
+
};
|
|
15
|
+
function usesAnnIndex(slot) {
|
|
16
|
+
return slot.indexType === "hnsw";
|
|
17
|
+
}
|
|
18
|
+
function sqliteVecMetricToken(metric) {
|
|
19
|
+
switch (metric) {
|
|
20
|
+
case "cosine": {
|
|
21
|
+
return "cosine";
|
|
22
|
+
}
|
|
23
|
+
case "l2": {
|
|
24
|
+
return "l2";
|
|
25
|
+
}
|
|
26
|
+
case "inner_product": {
|
|
27
|
+
throw new Error(
|
|
28
|
+
"sqlite-vec does not support inner_product. Use 'cosine' or 'l2'."
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
default: {
|
|
32
|
+
const _exhaustive = metric;
|
|
33
|
+
throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function vecF32Literal(embedding, name) {
|
|
38
|
+
assertFiniteEmbedding(embedding, name);
|
|
39
|
+
return sql`vec_f32(${JSON.stringify(embedding)})`;
|
|
40
|
+
}
|
|
41
|
+
function distanceExpression(embeddingColumn, queryEmbedding, metric) {
|
|
42
|
+
const query = vecF32Literal(queryEmbedding, "queryEmbedding");
|
|
43
|
+
switch (metric) {
|
|
44
|
+
case "cosine": {
|
|
45
|
+
return sql`vec_distance_cosine(${embeddingColumn}, ${query})`;
|
|
46
|
+
}
|
|
47
|
+
case "l2": {
|
|
48
|
+
return sql`vec_distance_l2(${embeddingColumn}, ${query})`;
|
|
49
|
+
}
|
|
50
|
+
case "inner_product": {
|
|
51
|
+
throw new Error(
|
|
52
|
+
"sqlite-vec does not support inner_product. Use 'cosine' or 'l2'."
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
default: {
|
|
56
|
+
const _exhaustive = metric;
|
|
57
|
+
throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
var sqliteVecStrategy = {
|
|
62
|
+
name: "sqlite-vec",
|
|
63
|
+
capabilities: SQLITE_VEC_CAPABILITIES,
|
|
64
|
+
tableName(graphId, nodeKind, fieldPath) {
|
|
65
|
+
return vectorPhysicalName(TABLE_PREFIX, graphId, nodeKind, fieldPath);
|
|
66
|
+
},
|
|
67
|
+
ownedTables(slot) {
|
|
68
|
+
const table = this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath);
|
|
69
|
+
const name = quoteIdentifier(table);
|
|
70
|
+
const metric = sqliteVecMetricToken(slot.metric);
|
|
71
|
+
return [
|
|
72
|
+
{
|
|
73
|
+
logicalName: `${VECTOR_CONTRIBUTION_PREFIX}:${slot.nodeKind}.${slot.fieldPath}`,
|
|
74
|
+
owner: "sqlite-vec",
|
|
75
|
+
tableName: table,
|
|
76
|
+
createDdl: [
|
|
77
|
+
`CREATE VIRTUAL TABLE IF NOT EXISTS ${name} USING vec0(
|
|
78
|
+
node_id TEXT PRIMARY KEY,
|
|
79
|
+
graph_id TEXT PARTITION KEY,
|
|
80
|
+
+created_at TEXT,
|
|
81
|
+
+updated_at TEXT,
|
|
82
|
+
embedding float[${slot.dimensions}] distance_metric=${metric}
|
|
83
|
+
);`
|
|
84
|
+
],
|
|
85
|
+
runtimeEnsure: true
|
|
86
|
+
}
|
|
87
|
+
];
|
|
88
|
+
},
|
|
89
|
+
buildUpsert(slot, params, timestamp) {
|
|
90
|
+
const table = quotedTableName(
|
|
91
|
+
this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath)
|
|
92
|
+
);
|
|
93
|
+
const value = vecF32Literal(params.embedding, "embedding");
|
|
94
|
+
return [
|
|
95
|
+
sql`
|
|
96
|
+
DELETE FROM ${table}
|
|
97
|
+
WHERE "node_id" = ${params.nodeId} AND "graph_id" = ${params.graphId}
|
|
98
|
+
`,
|
|
99
|
+
sql`
|
|
100
|
+
INSERT INTO ${table} ("node_id", "graph_id", "created_at", "updated_at", "embedding")
|
|
101
|
+
VALUES (${params.nodeId}, ${params.graphId}, ${timestamp}, ${timestamp}, ${value})
|
|
102
|
+
`
|
|
103
|
+
];
|
|
104
|
+
},
|
|
105
|
+
buildDelete(slot, params) {
|
|
106
|
+
const table = quotedTableName(
|
|
107
|
+
this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath)
|
|
108
|
+
);
|
|
109
|
+
return [
|
|
110
|
+
sql`
|
|
111
|
+
DELETE FROM ${table}
|
|
112
|
+
WHERE "node_id" = ${params.nodeId} AND "graph_id" = ${params.graphId}
|
|
113
|
+
`
|
|
114
|
+
];
|
|
115
|
+
},
|
|
116
|
+
buildSearch(slot, params) {
|
|
117
|
+
const table = quotedTableName(
|
|
118
|
+
this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath)
|
|
119
|
+
);
|
|
120
|
+
const embeddingColumn = sql`${table}."embedding"`;
|
|
121
|
+
const distance = distanceExpression(
|
|
122
|
+
embeddingColumn,
|
|
123
|
+
params.queryEmbedding,
|
|
124
|
+
params.metric
|
|
125
|
+
);
|
|
126
|
+
const score = vectorScoreExpression(distance, params.metric);
|
|
127
|
+
if (usesAnnIndex(slot)) {
|
|
128
|
+
const query = vecF32Literal(params.queryEmbedding, "queryEmbedding");
|
|
129
|
+
const conditions2 = [
|
|
130
|
+
sql`${table}."embedding" MATCH ${query}`,
|
|
131
|
+
sql`k = ${params.limit}`,
|
|
132
|
+
sql`${table}."graph_id" = ${params.graphId}`
|
|
133
|
+
];
|
|
134
|
+
if (params.minScore !== void 0) {
|
|
135
|
+
conditions2.push(
|
|
136
|
+
vectorMinScoreCondition(distance, params.metric, params.minScore)
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
return sql`
|
|
140
|
+
SELECT ${table}."node_id" AS node_id, ${score} AS score
|
|
141
|
+
FROM ${table}
|
|
142
|
+
WHERE ${sql.join(conditions2, sql` AND `)}
|
|
143
|
+
ORDER BY distance ASC
|
|
144
|
+
`;
|
|
145
|
+
}
|
|
146
|
+
const conditions = [sql`${table}."graph_id" = ${params.graphId}`];
|
|
147
|
+
if (params.minScore !== void 0) {
|
|
148
|
+
conditions.push(
|
|
149
|
+
vectorMinScoreCondition(distance, params.metric, params.minScore)
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
return sql`
|
|
153
|
+
SELECT ${table}."node_id" AS node_id, ${score} AS score
|
|
154
|
+
FROM ${table}
|
|
155
|
+
WHERE ${sql.join(conditions, sql` AND `)}
|
|
156
|
+
ORDER BY ${distance} ASC
|
|
157
|
+
LIMIT ${params.limit}
|
|
158
|
+
`;
|
|
159
|
+
},
|
|
160
|
+
distanceExpression(embeddingColumn, queryEmbedding, metric) {
|
|
161
|
+
return distanceExpression(embeddingColumn, queryEmbedding, metric);
|
|
162
|
+
},
|
|
163
|
+
// vec0 indexes inline (the virtual table is the index), so there is no
|
|
164
|
+
// standalone ANN index to create or drop — both return undefined.
|
|
165
|
+
buildCreateIndex() {
|
|
166
|
+
return void 0;
|
|
167
|
+
},
|
|
168
|
+
buildDropIndex() {
|
|
169
|
+
return void 0;
|
|
170
|
+
},
|
|
171
|
+
buildDropStorage(slot) {
|
|
172
|
+
const table = quoteIdentifier(
|
|
173
|
+
this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath)
|
|
174
|
+
);
|
|
175
|
+
return [`DROP TABLE IF EXISTS ${table}`];
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
export { sqliteVecStrategy };
|
|
180
|
+
//# sourceMappingURL=chunk-2QA5EHEN.js.map
|
|
181
|
+
//# sourceMappingURL=chunk-2QA5EHEN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/query/dialect/vector/sqlite-vec-strategy.ts"],"names":["conditions"],"mappings":";;;AA6EA,IAAM,YAAA,GAAe,QAAA;AAOrB,IAAM,yBAAA,GAA4B,GAAA;AAElC,IAAM,uBAAA,GAA8C;AAAA,EAClD,SAAA,EAAW,IAAA;AAAA,EACX,OAAA,EAAS,CAAC,QAAA,EAAU,IAAI,CAAA;AAAA;AAAA;AAAA;AAAA,EAIxB,UAAA,EAAY,CAAC,MAAA,EAAQ,MAAM,CAAA;AAAA,EAC3B,aAAA,EAAe;AACjB,CAAA;AAGA,SAAS,aAAa,IAAA,EAA2B;AAC/C,EAAA,OAAO,KAAK,SAAA,KAAc,MAAA;AAC5B;AAGA,SAAS,qBAAqB,MAAA,EAA8B;AAC1D,EAAA,QAAQ,MAAA;AAAQ,IACd,KAAK,QAAA,EAAU;AACb,MAAA,OAAO,QAAA;AAAA,IACT;AAAA,IACA,KAAK,IAAA,EAAM;AACT,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,IACA,KAAK,eAAA,EAAiB;AACpB,MAAA,MAAM,IAAI,KAAA;AAAA,QACR;AA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EAAgB,MAAM,CAAA;AAAA,EACnE,CAAA;AAAA;AAAA;AAAA,EAIA,gBAAA,GAAoC;AAClC,IAAA,OAAO,MAAA;AAAA,EACT,CAAA;AAAA,EAEA,cAAA,GAAkC;AAChC,IAAA,OAAO,MAAA;AAAA,EACT,CAAA;AAAA,EAEA,iBAAiB,IAAA,EAAyB;AACxC,IAAA,MAAM,KAAA,GAAQ,eAAA;AAAA,MACZ,KAAK,SAAA,CAAU,IAAA,CAAK,SAAS,IAAA,CAAK,QAAA,EAAU,KAAK,SAAS;AAAA,KAC5D;AAEA,IAAA,OAAO,CAAC,CAAA,qBAAA,EAAwB,KAAK,CAAA,CAAE,CAAA;AAAA,EACzC;AACF","file":"chunk-2QA5EHEN.js","sourcesContent":["/**\n * sqlite-vec strategy — real `vec0` KNN for local SQLite.\n *\n * This upgrades `createLocalSqliteBackend` (better-sqlite3 + the sqlite-vec\n * extension) from the legacy brute-force-on-a-shared-table model to genuine\n * approximate-nearest-neighbor search on per-`(nodeKind, fieldPath)` storage.\n *\n * ## Storage choice: a `vec0` virtual table per field\n *\n * Each slot is backed by its own `vec0` virtual table:\n *\n * ```sql\n * CREATE VIRTUAL TABLE tg_vec_<kind>_<field> USING vec0(\n * node_id TEXT PRIMARY KEY,\n * graph_id TEXT PARTITION KEY,\n * +created_at TEXT,\n * +updated_at TEXT,\n * embedding float[<N>] distance_metric=<cosine|l2>\n * );\n * ```\n *\n * Verified against the installed `sqlite-vec` `v0.1.9`:\n *\n * - **vec0 over a plain `vec_f32` BLOB column.** The shipped option (a) — a\n * `vec0` virtual table — is chosen over option (b) — a regular table whose\n * `vec_f32` BLOB column is brute-forced — because vec0 is the *only* form\n * that gives local SQLite a real ANN index (today's code only ever\n * brute-forces). vec0 indexes inline (the virtual table *is* the index), so\n * there is no separate `CREATE INDEX` step.\n * - **KNN with partition-correct filtering.** `WHERE embedding MATCH vec_f32(q)\n * AND k = ? AND graph_id = ?` returns the nearest `k`, ordered by `distance`,\n * scoped to one graph — a near vector in another `graph_id` partition does\n * not leak. This is strictly better than libSQL's table-global `vector_top_k`\n * (which over-fetches for multi-graph correctness): vec0's `PARTITION KEY`\n * makes the per-graph KNN exact.\n * - **One table serves both read paths.** The same `embedding` column answers\n * the compiler's brute-force `distanceExpression` (`vec_distance_cosine` /\n * `vec_distance_l2` over the column, `ORDER BY … LIMIT`, no `MATCH`), so the\n * `.where(field.similarTo(...))` CTE path needs no second structure.\n * - **`k` and `LIMIT` are mutually exclusive** in a vec0 `MATCH` query, so the\n * ANN path uses `k = <limit>` with no `LIMIT`, and the brute-force path uses\n * `LIMIT <limit>` with no `MATCH`.\n * - **No `ON CONFLICT` / `INSERT OR REPLACE`** on a vec0 primary key, so upsert\n * is `DELETE` + `INSERT` (atomic under the caller's outer transaction),\n * mirroring the FTS5 strategy.\n *\n * Metric support is `cosine` + `l2` (no `inner_product` — sqlite-vec has no\n * `vec_distance_ip`), advertised as data on `capabilities`. The table's\n * `distance_metric` is fixed at creation from the slot's metric, alongside its\n * fixed dimension `N`.\n *\n * The libSQL and pgvector siblings implement the same `VectorStrategy`\n * contract for their engines.\n */\nimport { type SQL, sql } from \"drizzle-orm\";\n\nimport { quotedTableName } from \"../../../backend/drizzle/operations/shared\";\nimport { type StrategyTableContribution } from \"../../../backend/table-contribution\";\nimport {\n type DeleteEmbeddingParams,\n type UpsertEmbeddingParams,\n type VectorCapabilities,\n type VectorMetric,\n type VectorSearchParams,\n} from \"../../../backend/types\";\nimport {\n assertFiniteEmbedding,\n quoteIdentifier,\n VECTOR_CONTRIBUTION_PREFIX,\n vectorMinScoreCondition,\n vectorPhysicalName,\n vectorScoreExpression,\n type VectorSlot,\n type VectorStrategy,\n} from \"../vector-strategy\";\n\n/** Physical-name prefix for the per-field `vec0` virtual table. */\nconst TABLE_PREFIX = \"tg_vec\";\n\n/**\n * sqlite-vec stores each dimension as a 32-bit float; `float[N]` accepts\n * large `N`, but we advertise the same conservative ceiling the legacy\n * SQLite path used so capability discovery is stable across the swap.\n */\nconst SQLITE_VEC_MAX_DIMENSIONS = 8000;\n\nconst SQLITE_VEC_CAPABILITIES: VectorCapabilities = {\n supported: true,\n metrics: [\"cosine\", \"l2\"],\n // vec0 always indexes inline, so the portable ANN intent (\"hnsw\", the\n // `embedding()` default) is honored by real KNN; \"none\" stays brute-force.\n // Both map to the same vec0 table — only `buildSearch` differs.\n indexTypes: [\"hnsw\", \"none\"],\n maxDimensions: SQLITE_VEC_MAX_DIMENSIONS,\n};\n\n/** Whether a slot's declared index type maps to vec0's `MATCH … k =` KNN. */\nfunction usesAnnIndex(slot: VectorSlot): boolean {\n return slot.indexType === \"hnsw\";\n}\n\n/** vec0 `distance_metric` token accepted in the virtual-table definition. */\nfunction sqliteVecMetricToken(metric: VectorMetric): string {\n switch (metric) {\n case \"cosine\": {\n return \"cosine\";\n }\n case \"l2\": {\n return \"l2\";\n }\n case \"inner_product\": {\n throw new Error(\n \"sqlite-vec does not support inner_product. Use 'cosine' or 'l2'.\",\n );\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);\n }\n }\n}\n\n/**\n * Formats an embedding as the bound JSON argument to `vec_f32(...)`. The\n * value rides as a parameter (not interpolated) — `vec_f32` parses the JSON\n * array into the packed float blob. Finiteness is validated first so a\n * NaN/Infinity names its index before JSON.stringify masks it as `null`.\n */\nfunction vecF32Literal(embedding: readonly number[], name: string): SQL {\n assertFiniteEmbedding(embedding, name);\n return sql`vec_f32(${JSON.stringify(embedding)})`;\n}\n\nfunction distanceExpression(\n embeddingColumn: SQL,\n queryEmbedding: readonly number[],\n metric: VectorMetric,\n): SQL {\n const query = vecF32Literal(queryEmbedding, \"queryEmbedding\");\n switch (metric) {\n case \"cosine\": {\n return sql`vec_distance_cosine(${embeddingColumn}, ${query})`;\n }\n case \"l2\": {\n return sql`vec_distance_l2(${embeddingColumn}, ${query})`;\n }\n case \"inner_product\": {\n throw new Error(\n \"sqlite-vec does not support inner_product. Use 'cosine' or 'l2'.\",\n );\n }\n default: {\n const _exhaustive: never = metric;\n throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);\n }\n }\n}\n\nexport const sqliteVecStrategy: VectorStrategy = {\n name: \"sqlite-vec\",\n capabilities: SQLITE_VEC_CAPABILITIES,\n\n tableName(graphId, nodeKind, fieldPath) {\n return vectorPhysicalName(TABLE_PREFIX, graphId, nodeKind, fieldPath);\n },\n\n ownedTables(slot): readonly StrategyTableContribution[] {\n const table = this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath);\n const name = quoteIdentifier(table);\n const metric = sqliteVecMetricToken(slot.metric);\n\n // vec0 virtual tables cannot be modeled as a Drizzle table, so this is a\n // raw-ddl contribution — emitted verbatim and invisible to drizzle-kit.\n // `graph_id` is a PARTITION KEY so per-graph KNN is exact; `created_at` /\n // `updated_at` are auxiliary (`+`) columns (stored, not filtered on). The\n // virtual table *is* the index — no separate CREATE INDEX is emitted.\n return [\n {\n logicalName: `${VECTOR_CONTRIBUTION_PREFIX}:${slot.nodeKind}.${slot.fieldPath}`,\n owner: \"sqlite-vec\",\n tableName: table,\n createDdl: [\n `CREATE VIRTUAL TABLE IF NOT EXISTS ${name} USING vec0(\n node_id TEXT PRIMARY KEY,\n graph_id TEXT PARTITION KEY,\n +created_at TEXT,\n +updated_at TEXT,\n embedding float[${slot.dimensions}] distance_metric=${metric}\n);`,\n ],\n runtimeEnsure: true,\n },\n ];\n },\n\n buildUpsert(slot, params: UpsertEmbeddingParams, timestamp): readonly SQL[] {\n const table = quotedTableName(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n const value = vecF32Literal(params.embedding, \"embedding\");\n // vec0 rejects ON CONFLICT / INSERT OR REPLACE on its primary key —\n // emulate upsert with DELETE + INSERT, atomic under the caller's\n // outer transaction (mirrors the FTS5 fulltext strategy).\n return [\n sql`\n DELETE FROM ${table}\n WHERE \"node_id\" = ${params.nodeId} AND \"graph_id\" = ${params.graphId}\n `,\n sql`\n INSERT INTO ${table} (\"node_id\", \"graph_id\", \"created_at\", \"updated_at\", \"embedding\")\n VALUES (${params.nodeId}, ${params.graphId}, ${timestamp}, ${timestamp}, ${value})\n `,\n ];\n },\n\n buildDelete(slot, params: DeleteEmbeddingParams): readonly SQL[] {\n const table = quotedTableName(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n return [\n sql`\n DELETE FROM ${table}\n WHERE \"node_id\" = ${params.nodeId} AND \"graph_id\" = ${params.graphId}\n `,\n ];\n },\n\n buildSearch(slot, params: VectorSearchParams): SQL {\n const table = quotedTableName(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n const embeddingColumn = sql`${table}.\"embedding\"`;\n const distance = distanceExpression(\n embeddingColumn,\n params.queryEmbedding,\n params.metric,\n );\n const score = vectorScoreExpression(distance, params.metric);\n\n if (usesAnnIndex(slot)) {\n // vec0 KNN. `k` and `LIMIT` are mutually exclusive in a MATCH query, so\n // bound `k = limit` and omit LIMIT. `graph_id` filters by the partition\n // key (exact, no recall loss). Order by vec0's own `distance` column —\n // the recomputed `distance` expression is reused only for score/minScore\n // so the math matches the brute-force path and the shared helpers.\n const query = vecF32Literal(params.queryEmbedding, \"queryEmbedding\");\n const conditions: SQL[] = [\n sql`${table}.\"embedding\" MATCH ${query}`,\n sql`k = ${params.limit}`,\n sql`${table}.\"graph_id\" = ${params.graphId}`,\n ];\n if (params.minScore !== undefined) {\n conditions.push(\n vectorMinScoreCondition(distance, params.metric, params.minScore),\n );\n }\n return sql`\n SELECT ${table}.\"node_id\" AS node_id, ${score} AS score\n FROM ${table}\n WHERE ${sql.join(conditions, sql` AND `)}\n ORDER BY distance ASC\n `;\n }\n\n // Brute-force scan: no MATCH, so LIMIT is allowed (and required).\n const conditions: SQL[] = [sql`${table}.\"graph_id\" = ${params.graphId}`];\n if (params.minScore !== undefined) {\n conditions.push(\n vectorMinScoreCondition(distance, params.metric, params.minScore),\n );\n }\n return sql`\n SELECT ${table}.\"node_id\" AS node_id, ${score} AS score\n FROM ${table}\n WHERE ${sql.join(conditions, sql` AND `)}\n ORDER BY ${distance} ASC\n LIMIT ${params.limit}\n `;\n },\n\n distanceExpression(embeddingColumn, queryEmbedding, metric) {\n return distanceExpression(embeddingColumn, queryEmbedding, metric);\n },\n\n // vec0 indexes inline (the virtual table is the index), so there is no\n // standalone ANN index to create or drop — both return undefined.\n buildCreateIndex(): SQL | undefined {\n return undefined;\n },\n\n buildDropIndex(): SQL | undefined {\n return undefined;\n },\n\n buildDropStorage(slot): readonly string[] {\n const table = quoteIdentifier(\n this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),\n );\n // Dropping the vec0 virtual table removes its backing shadow tables too.\n return [`DROP TABLE IF EXISTS ${table}`];\n },\n};\n"]}
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { quoteIdentifier, quotedTableName, vectorScoreExpression, vectorMinScoreCondition, VECTOR_CONTRIBUTION_PREFIX, vectorPhysicalName, assertFiniteEmbedding } from './chunk-AI3RNREM.js';
|
|
2
|
+
import { sql } from 'drizzle-orm';
|
|
3
|
+
|
|
4
|
+
var TABLE_PREFIX = "tg_vec";
|
|
5
|
+
var INDEX_PREFIX = "tg_vecidx";
|
|
6
|
+
var LIBSQL_MAX_DIMENSIONS = 65536;
|
|
7
|
+
var LIBSQL_CAPABILITIES = {
|
|
8
|
+
supported: true,
|
|
9
|
+
metrics: ["cosine", "l2"],
|
|
10
|
+
// "hnsw" = portable ANN intent, realized as DiskANN. "none" = brute-force.
|
|
11
|
+
indexTypes: ["hnsw", "none"],
|
|
12
|
+
maxDimensions: LIBSQL_MAX_DIMENSIONS
|
|
13
|
+
};
|
|
14
|
+
function usesAnnIndex(slot) {
|
|
15
|
+
return slot.indexType === "hnsw";
|
|
16
|
+
}
|
|
17
|
+
function libsqlMetricToken(metric) {
|
|
18
|
+
switch (metric) {
|
|
19
|
+
case "cosine": {
|
|
20
|
+
return "cosine";
|
|
21
|
+
}
|
|
22
|
+
case "l2": {
|
|
23
|
+
return "l2";
|
|
24
|
+
}
|
|
25
|
+
case "inner_product": {
|
|
26
|
+
throw new Error(
|
|
27
|
+
"libSQL vector search does not support inner_product. Use 'cosine' or 'l2'."
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
default: {
|
|
31
|
+
const _exhaustive = metric;
|
|
32
|
+
throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function vector32Literal(embedding, name) {
|
|
37
|
+
assertFiniteEmbedding(embedding, name);
|
|
38
|
+
return sql`vector32(${`[${embedding.join(",")}]`})`;
|
|
39
|
+
}
|
|
40
|
+
function distanceExpression(embeddingColumn, queryEmbedding, metric) {
|
|
41
|
+
const query = vector32Literal(queryEmbedding, "queryEmbedding");
|
|
42
|
+
switch (metric) {
|
|
43
|
+
case "cosine": {
|
|
44
|
+
return sql`vector_distance_cos(${embeddingColumn}, ${query})`;
|
|
45
|
+
}
|
|
46
|
+
case "l2": {
|
|
47
|
+
return sql`vector_distance_l2(${embeddingColumn}, ${query})`;
|
|
48
|
+
}
|
|
49
|
+
case "inner_product": {
|
|
50
|
+
throw new Error(
|
|
51
|
+
"libSQL vector search does not support inner_product. Use 'cosine' or 'l2'."
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
default: {
|
|
55
|
+
const _exhaustive = metric;
|
|
56
|
+
throw new Error(`Unsupported vector metric: ${String(_exhaustive)}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
var libsqlVectorStrategy = {
|
|
61
|
+
name: "libsql-native",
|
|
62
|
+
capabilities: LIBSQL_CAPABILITIES,
|
|
63
|
+
tableName(graphId, nodeKind, fieldPath) {
|
|
64
|
+
return vectorPhysicalName(TABLE_PREFIX, graphId, nodeKind, fieldPath);
|
|
65
|
+
},
|
|
66
|
+
ownedTables(slot) {
|
|
67
|
+
const table = this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath);
|
|
68
|
+
const name = quoteIdentifier(table);
|
|
69
|
+
const createDdl = [
|
|
70
|
+
`CREATE TABLE IF NOT EXISTS ${name} (
|
|
71
|
+
"graph_id" TEXT NOT NULL,
|
|
72
|
+
"node_id" TEXT NOT NULL,
|
|
73
|
+
"embedding" F32_BLOB(${slot.dimensions}) NOT NULL,
|
|
74
|
+
"created_at" TEXT NOT NULL,
|
|
75
|
+
"updated_at" TEXT NOT NULL,
|
|
76
|
+
PRIMARY KEY ("graph_id", "node_id")
|
|
77
|
+
);`
|
|
78
|
+
];
|
|
79
|
+
if (usesAnnIndex(slot)) {
|
|
80
|
+
createDdl.push(libsqlVectorIndexDdl(table, slot));
|
|
81
|
+
}
|
|
82
|
+
return [
|
|
83
|
+
{
|
|
84
|
+
logicalName: `${VECTOR_CONTRIBUTION_PREFIX}:${slot.nodeKind}.${slot.fieldPath}`,
|
|
85
|
+
owner: "libsql-native",
|
|
86
|
+
tableName: table,
|
|
87
|
+
createDdl,
|
|
88
|
+
runtimeEnsure: true
|
|
89
|
+
}
|
|
90
|
+
];
|
|
91
|
+
},
|
|
92
|
+
buildUpsert(slot, params, timestamp) {
|
|
93
|
+
const table = quotedTableName(
|
|
94
|
+
this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath)
|
|
95
|
+
);
|
|
96
|
+
const value = vector32Literal(params.embedding, "embedding");
|
|
97
|
+
return [
|
|
98
|
+
sql`
|
|
99
|
+
INSERT INTO ${table} ("graph_id", "node_id", "embedding", "created_at", "updated_at")
|
|
100
|
+
VALUES (${params.graphId}, ${params.nodeId}, ${value}, ${timestamp}, ${timestamp})
|
|
101
|
+
ON CONFLICT ("graph_id", "node_id")
|
|
102
|
+
DO UPDATE SET "embedding" = ${value}, "updated_at" = ${timestamp}
|
|
103
|
+
`
|
|
104
|
+
];
|
|
105
|
+
},
|
|
106
|
+
buildDelete(slot, params) {
|
|
107
|
+
const table = quotedTableName(
|
|
108
|
+
this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath)
|
|
109
|
+
);
|
|
110
|
+
return [
|
|
111
|
+
sql`
|
|
112
|
+
DELETE FROM ${table}
|
|
113
|
+
WHERE "graph_id" = ${params.graphId} AND "node_id" = ${params.nodeId}
|
|
114
|
+
`
|
|
115
|
+
];
|
|
116
|
+
},
|
|
117
|
+
buildSearch(slot, params) {
|
|
118
|
+
const table = this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath);
|
|
119
|
+
const quoted = quotedTableName(table);
|
|
120
|
+
const embeddingColumn = sql`${quoted}."embedding"`;
|
|
121
|
+
const distance = distanceExpression(
|
|
122
|
+
embeddingColumn,
|
|
123
|
+
params.queryEmbedding,
|
|
124
|
+
params.metric
|
|
125
|
+
);
|
|
126
|
+
const score = vectorScoreExpression(distance, params.metric);
|
|
127
|
+
if (usesAnnIndex(slot)) {
|
|
128
|
+
const indexName = libsqlIndexName(slot);
|
|
129
|
+
const query = vector32Literal(params.queryEmbedding, "queryEmbedding");
|
|
130
|
+
const conditions2 = [sql`${quoted}."graph_id" = ${params.graphId}`];
|
|
131
|
+
if (params.minScore !== void 0) {
|
|
132
|
+
conditions2.push(
|
|
133
|
+
vectorMinScoreCondition(distance, params.metric, params.minScore)
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
return sql`
|
|
137
|
+
SELECT ${quoted}."node_id" AS node_id, ${score} AS score
|
|
138
|
+
FROM vector_top_k(${indexName}, ${query}, ${params.limit})
|
|
139
|
+
JOIN ${quoted} ON ${quoted}.rowid = id
|
|
140
|
+
WHERE ${sql.join(conditions2, sql` AND `)}
|
|
141
|
+
ORDER BY ${distance} ASC
|
|
142
|
+
LIMIT ${params.limit}
|
|
143
|
+
`;
|
|
144
|
+
}
|
|
145
|
+
const conditions = [sql`${quoted}."graph_id" = ${params.graphId}`];
|
|
146
|
+
if (params.minScore !== void 0) {
|
|
147
|
+
conditions.push(
|
|
148
|
+
vectorMinScoreCondition(distance, params.metric, params.minScore)
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
return sql`
|
|
152
|
+
SELECT ${quoted}."node_id" AS node_id, ${score} AS score
|
|
153
|
+
FROM ${quoted}
|
|
154
|
+
WHERE ${sql.join(conditions, sql` AND `)}
|
|
155
|
+
ORDER BY ${distance} ASC
|
|
156
|
+
LIMIT ${params.limit}
|
|
157
|
+
`;
|
|
158
|
+
},
|
|
159
|
+
distanceExpression(embeddingColumn, queryEmbedding, metric) {
|
|
160
|
+
return distanceExpression(embeddingColumn, queryEmbedding, metric);
|
|
161
|
+
},
|
|
162
|
+
buildCreateIndex(slot) {
|
|
163
|
+
if (!usesAnnIndex(slot)) return void 0;
|
|
164
|
+
return sql.raw(
|
|
165
|
+
libsqlVectorIndexDdl(
|
|
166
|
+
this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath),
|
|
167
|
+
slot
|
|
168
|
+
)
|
|
169
|
+
);
|
|
170
|
+
},
|
|
171
|
+
buildDropIndex(slot) {
|
|
172
|
+
if (!usesAnnIndex(slot)) return void 0;
|
|
173
|
+
const indexName = libsqlIndexName(slot);
|
|
174
|
+
return sql.raw(`DROP INDEX IF EXISTS ${quoteIdentifier(indexName)}`);
|
|
175
|
+
},
|
|
176
|
+
buildDropStorage(slot) {
|
|
177
|
+
const table = quoteIdentifier(
|
|
178
|
+
this.tableName(slot.graphId, slot.nodeKind, slot.fieldPath)
|
|
179
|
+
);
|
|
180
|
+
const statements = [];
|
|
181
|
+
if (usesAnnIndex(slot)) {
|
|
182
|
+
statements.push(
|
|
183
|
+
`DROP INDEX IF EXISTS ${quoteIdentifier(libsqlIndexName(slot))}`
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
statements.push(`DROP TABLE IF EXISTS ${table}`);
|
|
187
|
+
return statements;
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
function libsqlIndexName(slot) {
|
|
191
|
+
return vectorPhysicalName(
|
|
192
|
+
INDEX_PREFIX,
|
|
193
|
+
slot.graphId,
|
|
194
|
+
slot.nodeKind,
|
|
195
|
+
slot.fieldPath
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
function libsqlVectorIndexDdl(table, slot) {
|
|
199
|
+
const indexName = quoteIdentifier(libsqlIndexName(slot));
|
|
200
|
+
const metric = libsqlMetricToken(slot.metric);
|
|
201
|
+
return `CREATE INDEX IF NOT EXISTS ${indexName} ON ${quoteIdentifier(table)}(libsql_vector_idx("embedding", 'metric=${metric}'));`;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export { libsqlVectorStrategy };
|
|
205
|
+
//# sourceMappingURL=chunk-3IRMLJEK.js.map
|
|
206
|
+
//# sourceMappingURL=chunk-3IRMLJEK.js.map
|