symmetria 3.3.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/better-auth.js +2 -2
  2. package/dist/better-auth.js.map +1 -1
  3. package/dist/bun.d.ts +2 -2
  4. package/dist/bun.js +1 -1
  5. package/dist/cohere.d.ts +1 -1
  6. package/dist/cohere.js +1 -1
  7. package/dist/{compile-ZwOWiPod.js → compile-D2gkALSH.js} +34 -14
  8. package/dist/compile-D2gkALSH.js.map +1 -0
  9. package/dist/{core-Dww__AzP.js → core-BwSS9Xl7.js} +119 -29
  10. package/dist/core-BwSS9Xl7.js.map +1 -0
  11. package/dist/driver.d.ts +3 -3
  12. package/dist/driver.js +1 -1
  13. package/dist/{errors-DNyJuu6e.js → errors-D7nAgODm.js} +10 -6
  14. package/dist/errors-D7nAgODm.js.map +1 -0
  15. package/dist/google.d.ts +1 -1
  16. package/dist/google.js +1 -1
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.js +264 -69
  19. package/dist/index.js.map +1 -1
  20. package/dist/{inspection-CMwwt5mS.js → inspection-CHgBTNQ_.js} +4 -4
  21. package/dist/{inspection-CMwwt5mS.js.map → inspection-CHgBTNQ_.js.map} +1 -1
  22. package/dist/internal.d.ts +1 -1
  23. package/dist/internal.js +4 -4
  24. package/dist/jina.d.ts +1 -1
  25. package/dist/jina.js +1 -1
  26. package/dist/mistral.d.ts +1 -1
  27. package/dist/mistral.js +1 -1
  28. package/dist/ollama.d.ts +1 -1
  29. package/dist/ollama.js +1 -1
  30. package/dist/openai.d.ts +1 -1
  31. package/dist/openai.js +1 -1
  32. package/dist/opentelemetry.d.ts +6 -2
  33. package/dist/opentelemetry.js +118 -13
  34. package/dist/opentelemetry.js.map +1 -1
  35. package/dist/{pg-mrOCZi9Z.js → pg-CFLpqlwI.js} +29 -12
  36. package/dist/pg-CFLpqlwI.js.map +1 -0
  37. package/dist/{pg-BR0PaxkR.d.ts → pg-D8_XgXPl.d.ts} +3 -3
  38. package/dist/pg.d.ts +3 -3
  39. package/dist/pg.js +1 -1
  40. package/dist/{pool-DpIlCXfo.d.ts → pool-B4Nw4D9X.d.ts} +2 -2
  41. package/dist/{pool-FCcF1emD.js → pool-IYDUq-NI.js} +30 -7
  42. package/dist/{pool-FCcF1emD.js.map → pool-IYDUq-NI.js.map} +1 -1
  43. package/dist/{profiling-Ca4rPFVy.js → profiling-DJryCjEd.js} +5 -4
  44. package/dist/profiling-DJryCjEd.js.map +1 -0
  45. package/dist/{search-uCUvhR3s.js → search-ks_yELtx.js} +7 -9
  46. package/dist/{search-uCUvhR3s.js.map → search-ks_yELtx.js.map} +1 -1
  47. package/dist/{search-DFEDMdX8.js → search-nBrRcObb.js} +3 -3
  48. package/dist/{search-DFEDMdX8.js.map → search-nBrRcObb.js.map} +1 -1
  49. package/dist/search.d.ts +1 -1
  50. package/dist/search.js +1 -1
  51. package/dist/{table-B89jb16u.js → table-DVhvRFZJ.js} +4 -4
  52. package/dist/{table-B89jb16u.js.map → table-DVhvRFZJ.js.map} +1 -1
  53. package/dist/{types-ojhCorK7.js → types-DGEtOzjC.js} +48 -5
  54. package/dist/types-DGEtOzjC.js.map +1 -0
  55. package/dist/{types-TJDae-ar.d.ts → types-DNIqcZA4.d.ts} +34 -5
  56. package/dist/{values-JeB3Fwkt.js → values-qxAv9Duz.js} +2 -2
  57. package/dist/{values-JeB3Fwkt.js.map → values-qxAv9Duz.js.map} +1 -1
  58. package/dist/vector.d.ts +1 -1
  59. package/dist/vector.js +2 -2
  60. package/dist/voyage.d.ts +1 -1
  61. package/dist/voyage.js +1 -1
  62. package/package.json +1 -1
  63. package/dist/compile-ZwOWiPod.js.map +0 -1
  64. package/dist/core-Dww__AzP.js.map +0 -1
  65. package/dist/errors-DNyJuu6e.js.map +0 -1
  66. package/dist/pg-mrOCZi9Z.js.map +0 -1
  67. package/dist/profiling-Ca4rPFVy.js.map +0 -1
  68. package/dist/types-ojhCorK7.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { u as and, v as not, x as or } from "./core-Dww__AzP.js";
1
+ import { u as and, v as not, x as or } from "./core-BwSS9Xl7.js";
2
2
  import { createAdapterFactory } from "better-auth/adapters";
3
3
  //#region src/entries/better-auth.ts
4
4
  const escapeLike = (value) => String(value).replace(/[\\%_]/g, (character) => `\\${character}`);
@@ -32,7 +32,7 @@ const COLUMN_TYPES = {
32
32
  string: "text",
33
33
  boolean: "bool",
34
34
  date: "timestamptz",
35
- json: "jsonb",
35
+ json: "jsonb()",
36
36
  "string[]": "text.array",
37
37
  "number[]": "int.array"
38
38
  };
@@ -1 +1 @@
1
- {"version":3,"file":"better-auth.js","names":[],"sources":["../src/entries/better-auth.ts"],"sourcesContent":["/**\n * `symmetria/better-auth`: a better-auth database adapter over a Symmetria\n * database: `betterAuth({ database: symmetriaAdapter(db) })`. The auth tables\n * are tables of your schema, keyed and named the way better-auth names its\n * models and fields (`user.emailVerified`), so they are migrated, related and\n * queried like the rest; `npx auth generate` writes them.\n */\nimport type { BetterAuthOptions } from \"better-auth\";\nimport {\n createAdapterFactory,\n type CleanedWhere,\n type DBAdapterDebugLogOption,\n} from \"better-auth/adapters\";\nimport { and, not, or } from \"../query/expressions\";\n\nexport type SymmetriaAdapterOptions = {\n /** Tables are keyed in the plural (`users`, `sessions`). */\n readonly usePlural?: boolean;\n readonly debugLogs?: DBAdapterDebugLogOption;\n};\n\n// better-auth names tables and fields at run time, so the adapter reaches\n// them by key and leaves the typed API to the application.\ntype Loose = any;\ntype Tables = Record<\n string,\n {\n modelName: string;\n fields: Record<string, Field>;\n indexes?: readonly {\n fields: readonly string[];\n unique?: boolean | undefined;\n }[];\n }\n>;\ntype Field = {\n type: string | readonly string[];\n required?: boolean | undefined;\n unique?: boolean | undefined;\n index?: boolean | undefined;\n bigint?: boolean | undefined;\n fieldName?: string | undefined;\n defaultValue?: unknown;\n references?:\n | { model: string; field: string; onDelete?: string | undefined }\n | undefined;\n};\n\nconst escapeLike = (value: unknown): string =>\n String(value).replace(/[\\\\%_]/g, (character) => `\\\\${character}`);\n\nconst predicate = (row: Loose, clause: CleanedWhere) => {\n const column = row[clause.field];\n\n if (!column) {\n throw new Error(\n `symmetria: better-auth asked for field \"${clause.field}\", which the table does not have`,\n );\n }\n\n const insensitive =\n clause.mode === \"insensitive\" && typeof clause.value === \"string\";\n const pattern = (text: string) =>\n insensitive ? column.ilike(text) : column.like(text);\n\n switch (clause.operator) {\n case \"ne\":\n return insensitive\n ? not(column.ilike(escapeLike(clause.value)))\n : column.isNot(clause.value);\n case \"in\":\n return column.in(clause.value);\n case \"not_in\":\n return column.notIn(clause.value);\n case \"gt\":\n return column.above(clause.value);\n case \"gte\":\n return column.atLeast(clause.value);\n case \"lt\":\n return column.below(clause.value);\n case \"lte\":\n return column.atMost(clause.value);\n case \"contains\":\n return pattern(`%${escapeLike(clause.value)}%`);\n case \"starts_with\":\n return pattern(`${escapeLike(clause.value)}%`);\n case \"ends_with\":\n return pattern(`%${escapeLike(clause.value)}`);\n default:\n return insensitive\n ? column.ilike(escapeLike(clause.value))\n : column.is(clause.value);\n }\n};\n\n/** better-auth's flat clause list: every AND clause, and at least one of the OR clauses. */\nconst filter = (where: readonly CleanedWhere[] | undefined) => (row: Loose) => {\n const clauses = where ?? [];\n const all = clauses\n .filter((clause) => clause.connector !== \"OR\")\n .map((clause) => predicate(row, clause));\n const any = clauses\n .filter((clause) => clause.connector === \"OR\")\n .map((clause) => predicate(row, clause));\n\n return and(...all, any.length > 0 ? or(...any) : undefined);\n};\n\nconst COLUMN_TYPES: Readonly<Record<string, string>> = {\n string: \"text\",\n boolean: \"bool\",\n date: \"timestamptz\",\n json: \"jsonb\",\n \"string[]\": \"text.array\",\n \"number[]\": \"int.array\",\n};\n\nconst snakeCase = (name: string): string =>\n name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);\n\n/**\n * The auth tables as a Symmetria schema module, for `npx auth generate`.\n * Tables come out in an order where each one follows the tables it\n * references; spread `authTables` into `schema({ ... })`.\n */\nexport const authSchemaSource = (tables: Tables): string => {\n const builders = new Set<string>([\"table\", \"text\"]);\n const models = Object.values(tables);\n const nameOf = (model: string): string =>\n tables[model]?.modelName ??\n models.find((entry) => entry.modelName === model)?.modelName ??\n model;\n const ordered: typeof models = [];\n const pending = [...models];\n\n // References first; a cycle keeps the order better-auth gave.\n while (pending.length) {\n const next =\n pending.find((entry) =>\n Object.values(entry.fields).every(\n (field) =>\n !field.references ||\n nameOf(field.references.model) === entry.modelName ||\n ordered.some(\n (done) => done.modelName === nameOf(field.references!.model),\n ),\n ),\n ) ?? pending[0]!;\n\n ordered.push(next);\n pending.splice(pending.indexOf(next), 1);\n }\n\n const declarations = ordered.map((entry) => {\n const targets = Object.values(entry.fields).flatMap((field) =>\n field.references ? [nameOf(field.references.model)] : [],\n );\n const lines = Object.entries(entry.fields).map(([key, field]) => {\n const named =\n field.fieldName &&\n field.fieldName !== key &&\n field.fieldName !== snakeCase(key)\n ? `.named(${JSON.stringify(field.fieldName)})`\n : \"\";\n const reference = field.references;\n\n if (reference && reference.field === \"id\" && key.endsWith(\"Id\")) {\n const target = nameOf(reference.model);\n // better-auth's own migrations cascade when a reference names no action.\n const action =\n reference.onDelete === undefined || reference.onDelete === \"cascade\"\n ? \"cascade\"\n : reference.onDelete === \"set null\"\n ? \"setNull\"\n : undefined;\n const relation = key.slice(0, -2);\n const self = target === entry.modelName;\n\n // Two keys to one table need names for their reverse sides.\n if (targets.filter((name) => name === target).length > 1 || self) {\n if (self) {\n builders.add(\"self\");\n }\n\n return ` ${relation}: ${self ? \"self\" : target}${field.required === false || action === \"setNull\" ? \".nullable\" : \"\"}${field.unique ? \".unique\" : \".index\"}${action ? `.onDelete.${action}` : \"\"}.inverse(${JSON.stringify(`${entry.modelName}By${relation[0]!.toUpperCase()}${relation.slice(1)}`)}),`;\n }\n\n const claim =\n field.required === false || action === \"setNull\" ? \"maybe\" : \"one\";\n\n builders.add(claim);\n\n return ` ${relation}: ${claim}(${target})${action ? `.${action}` : \"\"}${field.unique ? \".unique\" : \"\"},`;\n }\n\n let type: string;\n\n if (Array.isArray(field.type)) {\n builders.add(\"oneOf\");\n type = `oneOf(${field.type.map((value) => JSON.stringify(value)).join(\", \")})`;\n } else if (field.type === \"number\") {\n type = field.bigint ? \"bigint\" : \"int\";\n } else {\n type = COLUMN_TYPES[field.type as string] ?? \"text\";\n }\n\n builders.add(type.split(/[.(]/)[0]!);\n\n const fallback = field.defaultValue;\n const literal =\n typeof fallback === \"string\" ||\n typeof fallback === \"number\" ||\n typeof fallback === \"boolean\"\n ? `.default(${field.bigint ? `${fallback}n` : JSON.stringify(fallback)})`\n : \"\";\n\n return ` ${key}: ${type}${named}${field.required === false ? \".nullable\" : \"\"}${field.unique ? \".unique\" : \"\"}${field.index && !field.unique ? \".index\" : \"\"}${literal},`;\n });\n const indexes = (entry.indexes ?? []).filter(\n (definition) => definition.fields.length > 1,\n );\n\n if (indexes.length) {\n builders.add(\"index\");\n }\n\n return [\n `export const ${entry.modelName} = table({`,\n \" id: text,\",\n ...lines,\n indexes.length\n ? `}).indexes((${entry.modelName}) => ({\\n${indexes\n .map(\n (definition) =>\n ` ${definition.fields.join(\"_\").replace(/_(\\w)/g, (_match, letter: string) => letter.toUpperCase())}: index(${definition.fields.map((name) => `${entry.modelName}.${name}`).join(\", \")})${definition.unique ? \".unique\" : \"\"},`,\n )\n .join(\"\\n\")}\\n}));`\n : \"});\",\n ].join(\"\\n\");\n });\n\n return [\n \"// Written by `auth generate` through symmetria/better-auth.\",\n \"// Spread `authTables` into your schema: schema({ ...authTables, posts, … }).\",\n `import { ${[...builders].sort().join(\", \")} } from \"symmetria\";`,\n \"\",\n declarations.join(\"\\n\\n\"),\n \"\",\n `export const authTables = { ${ordered.map((entry) => entry.modelName).join(\", \")} };`,\n \"\",\n ].join(\"\\n\");\n};\n\n/**\n * `betterAuth({ database: symmetriaAdapter(db) })`. `db` is the database (or a\n * `$scope()` of it) whose schema holds the auth tables; better-auth's own\n * transactions run inside `db.$transaction`.\n */\nexport const symmetriaAdapter = (\n db: object,\n options: SymmetriaAdapterOptions = {},\n) => {\n // What better-auth hands the adapter, kept for the adapters built around a transaction.\n let authOptions: BetterAuthOptions | undefined;\n\n const build = (connection: Loose): ReturnType<typeof createAdapterFactory> =>\n createAdapterFactory({\n config: {\n adapterId: \"symmetria\",\n adapterName: \"Symmetria\",\n usePlural: options.usePlural ?? false,\n debugLogs: options.debugLogs ?? false,\n supportsDates: true,\n supportsBooleans: true,\n supportsJSON: true,\n supportsArrays: true,\n transaction: (callback) =>\n connection.$transaction((transaction: Loose) =>\n callback(build(transaction)(authOptions ?? {}) as never),\n ),\n },\n adapter: () => {\n const table = (model: string) => {\n const handle = connection[model];\n\n if (!handle) {\n throw new Error(\n `symmetria: better-auth uses a table \"${model}\" that the schema does not have; run \\`npx auth generate\\` and add it`,\n );\n }\n\n return handle;\n };\n // An UPDATE or DELETE without a filter is refused unless spelled\n // out; better-auth means every row when it sends none.\n const filtered = (\n mutation: Loose,\n where: readonly CleanedWhere[] | undefined,\n ) => (where?.length ? mutation.where(filter(where)) : mutation.all());\n\n return {\n create: ({ model, data }) => table(model).insert(data).returning(),\n\n findOne: ({ model, where }) =>\n table(model)({ where: filter(where), limit: 1 }).first(),\n\n findMany: ({ model, where, limit, offset, sortBy }) =>\n table(model)({\n where: filter(where),\n limit,\n offset,\n orderBy: sortBy\n ? { [sortBy.field]: sortBy.direction }\n : undefined,\n }),\n\n count: ({ model, where }) =>\n table(model)({ where: filter(where) }).count(),\n\n update: async ({ model, where, update }) => {\n const [row] = await filtered(\n table(model).update(update),\n where,\n ).returning();\n\n return row ?? null;\n },\n\n updateMany: async ({ model, where, update }) =>\n (await filtered(table(model).update(update), where)).affectedRows,\n\n delete: async ({ model, where }) => {\n await filtered(table(model).delete(), where);\n },\n\n deleteMany: async ({ model, where }) =>\n (await filtered(table(model).delete(), where)).affectedRows,\n\n // One row at most: the DELETE by key decides which of two\n // concurrent callers gets it.\n consumeOne: async ({ model, where }) => {\n const found = await table(model)({\n where: filter(where),\n limit: 1,\n }).first();\n\n if (!found) {\n return null;\n }\n\n const [row] = await table(model)\n .byId(found.id)\n .delete()\n .returning();\n\n return row ?? null;\n },\n\n incrementOne: async ({ model, where, increment, set }) => {\n const [row] = await filtered(\n table(model).update((current: Loose) => ({\n ...set,\n ...Object.fromEntries(\n Object.entries(increment).map(([field, delta]) => [\n field,\n current[field].plus(delta),\n ]),\n ),\n })),\n where,\n ).returning();\n\n return row ?? null;\n },\n\n createSchema: async ({ tables, file }) => ({\n code: authSchemaSource(tables as Tables),\n path: file ?? \"./auth-schema.ts\",\n overwrite: true,\n }),\n };\n },\n });\n\n const adapter = build(db);\n\n return (betterAuthOptions: BetterAuthOptions) => {\n authOptions = betterAuthOptions;\n\n return adapter(betterAuthOptions);\n };\n};\n"],"mappings":";;;AAgDA,MAAM,cAAc,UAClB,OAAO,KAAK,CAAC,CAAC,QAAQ,YAAY,cAAc,KAAK,WAAW;AAElE,MAAM,aAAa,KAAY,WAAyB;CACtD,MAAM,SAAS,IAAI,OAAO;CAE1B,IAAI,CAAC,QACH,MAAM,IAAI,MACR,2CAA2C,OAAO,MAAM,iCAC1D;CAGF,MAAM,cACJ,OAAO,SAAS,iBAAiB,OAAO,OAAO,UAAU;CAC3D,MAAM,WAAW,SACf,cAAc,OAAO,MAAM,IAAI,IAAI,OAAO,KAAK,IAAI;CAErD,QAAQ,OAAO,UAAf;EACE,KAAK,MACH,OAAO,cACH,IAAI,OAAO,MAAM,WAAW,OAAO,KAAK,CAAC,CAAC,IAC1C,OAAO,MAAM,OAAO,KAAK;EAC/B,KAAK,MACH,OAAO,OAAO,GAAG,OAAO,KAAK;EAC/B,KAAK,UACH,OAAO,OAAO,MAAM,OAAO,KAAK;EAClC,KAAK,MACH,OAAO,OAAO,MAAM,OAAO,KAAK;EAClC,KAAK,OACH,OAAO,OAAO,QAAQ,OAAO,KAAK;EACpC,KAAK,MACH,O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;MACvC,GAAG;MACH,GAAG,OAAO,YACR,OAAO,QAAQ,SAAS,CAAC,CAAC,KAAK,CAAC,OAAO,WAAW,CAChD,OACA,QAAQ,MAAM,CAAC,KAAK,KAAK,CAC3B,CAAC,CACH;KACF,EAAE,GACF,KACF,CAAC,CAAC,UAAU;KAEZ,OAAO,OAAO;IAChB;IAEA,cAAc,OAAO,EAAE,QAAQ,YAAY;KACzC,MAAM,iBAAiB,MAAgB;KACvC,MAAM,QAAQ;KACd,WAAW;IACb;GACF;EACF;CACF,CAAC;CAEH,MAAM,UAAU,MAAM,EAAE;CAExB,QAAQ,sBAAyC;EAC/C,cAAc;EAEd,OAAO,QAAQ,iBAAiB;CAClC;AACF"}
1
+ {"version":3,"file":"better-auth.js","names":[],"sources":["../src/entries/better-auth.ts"],"sourcesContent":["/**\n * `symmetria/better-auth`: a better-auth database adapter over a Symmetria\n * database: `betterAuth({ database: symmetriaAdapter(db) })`. The auth tables\n * are tables of your schema, keyed and named the way better-auth names its\n * models and fields (`user.emailVerified`), so they are migrated, related and\n * queried like the rest; `npx auth generate` writes them.\n */\nimport type { BetterAuthOptions } from \"better-auth\";\nimport {\n createAdapterFactory,\n type CleanedWhere,\n type DBAdapterDebugLogOption,\n} from \"better-auth/adapters\";\nimport { and, not, or } from \"../query/expressions\";\n\nexport type SymmetriaAdapterOptions = {\n /** Tables are keyed in the plural (`users`, `sessions`). */\n readonly usePlural?: boolean;\n readonly debugLogs?: DBAdapterDebugLogOption;\n};\n\n// better-auth names tables and fields at run time, so the adapter reaches\n// them by key and leaves the typed API to the application.\ntype Loose = any;\ntype Tables = Record<\n string,\n {\n modelName: string;\n fields: Record<string, Field>;\n indexes?: readonly {\n fields: readonly string[];\n unique?: boolean | undefined;\n }[];\n }\n>;\ntype Field = {\n type: string | readonly string[];\n required?: boolean | undefined;\n unique?: boolean | undefined;\n index?: boolean | undefined;\n bigint?: boolean | undefined;\n fieldName?: string | undefined;\n defaultValue?: unknown;\n references?:\n | { model: string; field: string; onDelete?: string | undefined }\n | undefined;\n};\n\nconst escapeLike = (value: unknown): string =>\n String(value).replace(/[\\\\%_]/g, (character) => `\\\\${character}`);\n\nconst predicate = (row: Loose, clause: CleanedWhere) => {\n const column = row[clause.field];\n\n if (!column) {\n throw new Error(\n `symmetria: better-auth asked for field \"${clause.field}\", which the table does not have`,\n );\n }\n\n const insensitive =\n clause.mode === \"insensitive\" && typeof clause.value === \"string\";\n const pattern = (text: string) =>\n insensitive ? column.ilike(text) : column.like(text);\n\n switch (clause.operator) {\n case \"ne\":\n return insensitive\n ? not(column.ilike(escapeLike(clause.value)))\n : column.isNot(clause.value);\n case \"in\":\n return column.in(clause.value);\n case \"not_in\":\n return column.notIn(clause.value);\n case \"gt\":\n return column.above(clause.value);\n case \"gte\":\n return column.atLeast(clause.value);\n case \"lt\":\n return column.below(clause.value);\n case \"lte\":\n return column.atMost(clause.value);\n case \"contains\":\n return pattern(`%${escapeLike(clause.value)}%`);\n case \"starts_with\":\n return pattern(`${escapeLike(clause.value)}%`);\n case \"ends_with\":\n return pattern(`%${escapeLike(clause.value)}`);\n default:\n return insensitive\n ? column.ilike(escapeLike(clause.value))\n : column.is(clause.value);\n }\n};\n\n/** better-auth's flat clause list: every AND clause, and at least one of the OR clauses. */\nconst filter = (where: readonly CleanedWhere[] | undefined) => (row: Loose) => {\n const clauses = where ?? [];\n const all = clauses\n .filter((clause) => clause.connector !== \"OR\")\n .map((clause) => predicate(row, clause));\n const any = clauses\n .filter((clause) => clause.connector === \"OR\")\n .map((clause) => predicate(row, clause));\n\n return and(...all, any.length > 0 ? or(...any) : undefined);\n};\n\nconst COLUMN_TYPES: Readonly<Record<string, string>> = {\n string: \"text\",\n boolean: \"bool\",\n date: \"timestamptz\",\n json: \"jsonb()\",\n \"string[]\": \"text.array\",\n \"number[]\": \"int.array\",\n};\n\nconst snakeCase = (name: string): string =>\n name.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);\n\n/**\n * The auth tables as a Symmetria schema module, for `npx auth generate`.\n * Tables come out in an order where each one follows the tables it\n * references; spread `authTables` into `schema({ ... })`.\n */\nexport const authSchemaSource = (tables: Tables): string => {\n const builders = new Set<string>([\"table\", \"text\"]);\n const models = Object.values(tables);\n const nameOf = (model: string): string =>\n tables[model]?.modelName ??\n models.find((entry) => entry.modelName === model)?.modelName ??\n model;\n const ordered: typeof models = [];\n const pending = [...models];\n\n // References first; a cycle keeps the order better-auth gave.\n while (pending.length) {\n const next =\n pending.find((entry) =>\n Object.values(entry.fields).every(\n (field) =>\n !field.references ||\n nameOf(field.references.model) === entry.modelName ||\n ordered.some(\n (done) => done.modelName === nameOf(field.references!.model),\n ),\n ),\n ) ?? pending[0]!;\n\n ordered.push(next);\n pending.splice(pending.indexOf(next), 1);\n }\n\n const declarations = ordered.map((entry) => {\n const targets = Object.values(entry.fields).flatMap((field) =>\n field.references ? [nameOf(field.references.model)] : [],\n );\n const lines = Object.entries(entry.fields).map(([key, field]) => {\n const named =\n field.fieldName &&\n field.fieldName !== key &&\n field.fieldName !== snakeCase(key)\n ? `.named(${JSON.stringify(field.fieldName)})`\n : \"\";\n const reference = field.references;\n\n if (reference && reference.field === \"id\" && key.endsWith(\"Id\")) {\n const target = nameOf(reference.model);\n // better-auth's own migrations cascade when a reference names no action.\n const action =\n reference.onDelete === undefined || reference.onDelete === \"cascade\"\n ? \"cascade\"\n : reference.onDelete === \"set null\"\n ? \"setNull\"\n : undefined;\n const relation = key.slice(0, -2);\n const self = target === entry.modelName;\n\n // Two keys to one table need names for their reverse sides.\n if (targets.filter((name) => name === target).length > 1 || self) {\n if (self) {\n builders.add(\"self\");\n }\n\n return ` ${relation}: ${self ? \"self\" : target}${field.required === false || action === \"setNull\" ? \".nullable\" : \"\"}${field.unique ? \".unique\" : \".index\"}${action ? `.onDelete.${action}` : \"\"}.inverse(${JSON.stringify(`${entry.modelName}By${relation[0]!.toUpperCase()}${relation.slice(1)}`)}),`;\n }\n\n const claim =\n field.required === false || action === \"setNull\" ? \"maybe\" : \"one\";\n\n builders.add(claim);\n\n return ` ${relation}: ${claim}(${target})${action ? `.${action}` : \"\"}${field.unique ? \".unique\" : \"\"},`;\n }\n\n let type: string;\n\n if (Array.isArray(field.type)) {\n builders.add(\"oneOf\");\n type = `oneOf(${field.type.map((value) => JSON.stringify(value)).join(\", \")})`;\n } else if (field.type === \"number\") {\n type = field.bigint ? \"bigint\" : \"int\";\n } else {\n type = COLUMN_TYPES[field.type as string] ?? \"text\";\n }\n\n builders.add(type.split(/[.(]/)[0]!);\n\n const fallback = field.defaultValue;\n const literal =\n typeof fallback === \"string\" ||\n typeof fallback === \"number\" ||\n typeof fallback === \"boolean\"\n ? `.default(${field.bigint ? `${fallback}n` : JSON.stringify(fallback)})`\n : \"\";\n\n return ` ${key}: ${type}${named}${field.required === false ? \".nullable\" : \"\"}${field.unique ? \".unique\" : \"\"}${field.index && !field.unique ? \".index\" : \"\"}${literal},`;\n });\n const indexes = (entry.indexes ?? []).filter(\n (definition) => definition.fields.length > 1,\n );\n\n if (indexes.length) {\n builders.add(\"index\");\n }\n\n return [\n `export const ${entry.modelName} = table({`,\n \" id: text,\",\n ...lines,\n indexes.length\n ? `}).indexes((${entry.modelName}) => ({\\n${indexes\n .map(\n (definition) =>\n ` ${definition.fields.join(\"_\").replace(/_(\\w)/g, (_match, letter: string) => letter.toUpperCase())}: index(${definition.fields.map((name) => `${entry.modelName}.${name}`).join(\", \")})${definition.unique ? \".unique\" : \"\"},`,\n )\n .join(\"\\n\")}\\n}));`\n : \"});\",\n ].join(\"\\n\");\n });\n\n return [\n \"// Written by `auth generate` through symmetria/better-auth.\",\n \"// Spread `authTables` into your schema: schema({ ...authTables, posts, … }).\",\n `import { ${[...builders].sort().join(\", \")} } from \"symmetria\";`,\n \"\",\n declarations.join(\"\\n\\n\"),\n \"\",\n `export const authTables = { ${ordered.map((entry) => entry.modelName).join(\", \")} };`,\n \"\",\n ].join(\"\\n\");\n};\n\n/**\n * `betterAuth({ database: symmetriaAdapter(db) })`. `db` is the database (or a\n * `$scope()` of it) whose schema holds the auth tables; better-auth's own\n * transactions run inside `db.$transaction`.\n */\nexport const symmetriaAdapter = (\n db: object,\n options: SymmetriaAdapterOptions = {},\n) => {\n // What better-auth hands the adapter, kept for the adapters built around a transaction.\n let authOptions: BetterAuthOptions | undefined;\n\n const build = (connection: Loose): ReturnType<typeof createAdapterFactory> =>\n createAdapterFactory({\n config: {\n adapterId: \"symmetria\",\n adapterName: \"Symmetria\",\n usePlural: options.usePlural ?? false,\n debugLogs: options.debugLogs ?? false,\n supportsDates: true,\n supportsBooleans: true,\n supportsJSON: true,\n supportsArrays: true,\n transaction: (callback) =>\n connection.$transaction((transaction: Loose) =>\n callback(build(transaction)(authOptions ?? {}) as never),\n ),\n },\n adapter: () => {\n const table = (model: string) => {\n const handle = connection[model];\n\n if (!handle) {\n throw new Error(\n `symmetria: better-auth uses a table \"${model}\" that the schema does not have; run \\`npx auth generate\\` and add it`,\n );\n }\n\n return handle;\n };\n // An UPDATE or DELETE without a filter is refused unless spelled\n // out; better-auth means every row when it sends none.\n const filtered = (\n mutation: Loose,\n where: readonly CleanedWhere[] | undefined,\n ) => (where?.length ? mutation.where(filter(where)) : mutation.all());\n\n return {\n create: ({ model, data }) => table(model).insert(data).returning(),\n\n findOne: ({ model, where }) =>\n table(model)({ where: filter(where), limit: 1 }).first(),\n\n findMany: ({ model, where, limit, offset, sortBy }) =>\n table(model)({\n where: filter(where),\n limit,\n offset,\n orderBy: sortBy\n ? { [sortBy.field]: sortBy.direction }\n : undefined,\n }),\n\n count: ({ model, where }) =>\n table(model)({ where: filter(where) }).count(),\n\n update: async ({ model, where, update }) => {\n const [row] = await filtered(\n table(model).update(update),\n where,\n ).returning();\n\n return row ?? null;\n },\n\n updateMany: async ({ model, where, update }) =>\n (await filtered(table(model).update(update), where)).affectedRows,\n\n delete: async ({ model, where }) => {\n await filtered(table(model).delete(), where);\n },\n\n deleteMany: async ({ model, where }) =>\n (await filtered(table(model).delete(), where)).affectedRows,\n\n // One row at most: the DELETE by key decides which of two\n // concurrent callers gets it.\n consumeOne: async ({ model, where }) => {\n const found = await table(model)({\n where: filter(where),\n limit: 1,\n }).first();\n\n if (!found) {\n return null;\n }\n\n const [row] = await table(model)\n .byId(found.id)\n .delete()\n .returning();\n\n return row ?? null;\n },\n\n incrementOne: async ({ model, where, increment, set }) => {\n const [row] = await filtered(\n table(model).update((current: Loose) => ({\n ...set,\n ...Object.fromEntries(\n Object.entries(increment).map(([field, delta]) => [\n field,\n current[field].plus(delta),\n ]),\n ),\n })),\n where,\n ).returning();\n\n return row ?? null;\n },\n\n createSchema: async ({ tables, file }) => ({\n code: authSchemaSource(tables as Tables),\n path: file ?? \"./auth-schema.ts\",\n overwrite: true,\n }),\n };\n },\n });\n\n const adapter = build(db);\n\n return (betterAuthOptions: BetterAuthOptions) => {\n authOptions = betterAuthOptions;\n\n return adapter(betterAuthOptions);\n };\n};\n"],"mappings":";;;AAgDA,MAAM,cAAc,UAClB,OAAO,KAAK,CAAC,CAAC,QAAQ,YAAY,cAAc,KAAK,WAAW;AAElE,MAAM,aAAa,KAAY,WAAyB;CACtD,MAAM,SAAS,IAAI,OAAO;CAE1B,IAAI,CAAC,QACH,MAAM,IAAI,MACR,2CAA2C,OAAO,MAAM,iCAC1D;CAGF,MAAM,cACJ,OAAO,SAAS,iBAAiB,OAAO,OAAO,UAAU;CAC3D,MAAM,WAAW,SACf,cAAc,OAAO,MAAM,IAAI,IAAI,OAAO,KAAK,IAAI;CAErD,QAAQ,OAAO,UAAf;EACE,KAAK,MACH,OAAO,cACH,IAAI,OAAO,MAAM,WAAW,OAAO,KAAK,CAAC,CAAC,IAC1C,OAAO,MAAM,OAAO,KAAK;EAC/B,KAAK,MACH,OAAO,OAAO,GAAG,OAAO,KAAK;EAC/B,KAAK,UACH,OAAO,OAAO,MAAM,OAAO,KAAK;EAClC,KAAK,MACH,OAAO,OAAO,MAAM,OAAO,KAAK;EAClC,KAAK,OACH,OAAO,OAAO,QA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AM,KAAK,CAAC,CAAC,QAAQ,aAAoB;MACvC,GAAG;MACH,GAAG,OAAO,YACR,OAAO,QAAQ,SAAS,CAAC,CAAC,KAAK,CAAC,OAAO,WAAW,CAChD,OACA,QAAQ,MAAM,CAAC,KAAK,KAAK,CAC3B,CAAC,CACH;KACF,EAAE,GACF,KACF,CAAC,CAAC,UAAU;KAEZ,OAAO,OAAO;IAChB;IAEA,cAAc,OAAO,EAAE,QAAQ,YAAY;KACzC,MAAM,iBAAiB,MAAgB;KACvC,MAAM,QAAQ;KACd,WAAW;IACb;GACF;EACF;CACF,CAAC;CAEH,MAAM,UAAU,MAAM,EAAE;CAExB,QAAQ,sBAAyC;EAC/C,cAAc;EAEd,OAAO,QAAQ,iBAAiB;CAClC;AACF"}
package/dist/bun.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { c as SessionDriver, dt as BindableSchema, l as TransactionDriver, nt as QueryProfiler, pt as SCHEMA_BIND, r as Driver } from "./types-TJDae-ar.js";
2
- import { t as PostgresDriver } from "./pool-DpIlCXfo.js";
1
+ import { c as SessionDriver, dt as BindableSchema, l as TransactionDriver, nt as QueryProfiler, pt as SCHEMA_BIND, r as Driver } from "./types-DNIqcZA4.js";
2
+ import { t as PostgresDriver } from "./pool-B4Nw4D9X.js";
3
3
  import { SQL } from "bun";
4
4
  //#region src/driver/bun.d.ts
5
5
  type PostgresOptions = Omit<SQL.PostgresOrMySQLOptions, "adapter" | "bigint"> & {
package/dist/bun.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as SCHEMA_BIND } from "./binding-CD-0xNaB.js";
2
- import { n as postgresParameters, t as createPostgresDriver } from "./pool-FCcF1emD.js";
2
+ import { n as postgresParameters, t as createPostgresDriver } from "./pool-IYDUq-NI.js";
3
3
  import { SQL } from "bun";
4
4
  //#region src/driver/bun.ts
5
5
  /**
package/dist/cohere.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { K as EmbeddingModel, cn as SelectedColumn, q as MeaningSearch } from "./types-TJDae-ar.js";
1
+ import { K as EmbeddingModel, cn as SelectedColumn, q as MeaningSearch } from "./types-DNIqcZA4.js";
2
2
  //#region src/entries/cohere.d.ts
3
3
  export type CohereOptions = {
4
4
  readonly apiKey?: string;
package/dist/cohere.js CHANGED
@@ -1,4 +1,4 @@
1
- import { r as embedder } from "./search-DFEDMdX8.js";
1
+ import { r as embedder } from "./search-nBrRcObb.js";
2
2
  import { i as postJson, r as inBatches, t as apiKey } from "./http-o1fpnTNy.js";
3
3
  //#region src/entries/cohere.ts
4
4
  /**
@@ -1,10 +1,10 @@
1
- import { E as throwDataErrors, c as mergeBindings, f as bigintCodec, l as normalizeResult, m as cloneParameter, s as containsBinding, t as DEFAULT_VALUE, u as numberedAlias, v as createRowDecoder, x as numericCodec } from "./types-ojhCorK7.js";
2
- import { F as containsNode, N as expressionSqlType, P as childNodes } from "./core-Dww__AzP.js";
3
- import { o as scopeViolationText } from "./errors-DNyJuu6e.js";
4
- import { G as createCompilation, J as renderContext, K as parameter, W as aliasSql, q as quoteIdentifier } from "./table-B89jb16u.js";
1
+ import { D as throwDataErrors, S as numericCodec, c as containsBinding, d as numberedAlias, h as cloneParameter, l as mergeBindings, n as DEFAULT_VALUE, p as bigintCodec, u as normalizeResult, y as createRowDecoder } from "./types-DGEtOzjC.js";
2
+ import { F as containsNode, N as expressionSqlType, P as childNodes } from "./core-BwSS9Xl7.js";
3
+ import { o as scopeViolationText } from "./errors-D7nAgODm.js";
4
+ import { G as createCompilation, J as renderContext, K as parameter, W as aliasSql, q as quoteIdentifier } from "./table-DVhvRFZJ.js";
5
5
  import { t as freeze } from "./freeze-D2-KMR2m.js";
6
- import { a as unconstrained, i as postgresRenderer, n as executorProfiling } from "./profiling-Ca4rPFVy.js";
7
- import { a as tsquerySql, n as searchRankSql, o as tsvectorSql, r as searchVectorSql, t as searchHeadlineSql } from "./search-uCUvhR3s.js";
6
+ import { a as unconstrained, i as postgresRenderer, n as executorProfiling } from "./profiling-DJryCjEd.js";
7
+ import { i as searchVectorSql, n as searchHeadlineSql, o as tsquerySql, r as searchRankSql, s as tsvectorSql, t as headlineOptionsText } from "./search-ks_yELtx.js";
8
8
  import { isDeepStrictEqual } from "node:util";
9
9
  //#region src/query/plan/batching.ts
10
10
  const batchCollectors = /* @__PURE__ */ new WeakMap();
@@ -186,7 +186,12 @@ const renderValue = (compilation, node, bindings, jsonOutput) => {
186
186
  ...node.normalization === void 0 ? {} : { normalization: node.normalization },
187
187
  coverDensity: !!node.coverDensity
188
188
  });
189
- case "searchHeadline": return searchHeadlineSql(node.language, valueSql(compilation, node.value, bindings), tsquerySql(valueSql(compilation, node.query, bindings), node.language, node.mode), node.options);
189
+ case "searchHeadline": {
190
+ const value = valueSql(compilation, node.value, bindings);
191
+ const query = tsquerySql(valueSql(compilation, node.query, bindings), node.language, node.mode);
192
+ const options = headlineOptionsText(node.options);
193
+ return searchHeadlineSql(node.language, value, query, options === void 0 ? void 0 : parameter(compilation, options));
194
+ }
190
195
  case "tsvector": return tsvectorSql(node.parts.map((part) => ({
191
196
  value: valueSql(compilation, part.value, bindings),
192
197
  ...part.weight ? { weight: part.weight } : {},
@@ -272,11 +277,13 @@ const predicateSql = (compilation, description, bindings) => {
272
277
  const comparison = `${left} ${operator} ${right}`;
273
278
  if (!nullable || description.right.kind !== "placeholder") return comparison;
274
279
  const type = sqlTypeOf(description.left);
275
- if (type === "enum") return `${left} ${operator === "<>" ? "IS DISTINCT FROM" : "IS NOT DISTINCT FROM"} ${right}`;
280
+ const isNull = description.nullCheck ? predicateSql(compilation, description.nullCheck, bindings) : `${left} IS NULL`;
281
+ const whenNull = operator === "<>" ? `NOT (${isNull})` : isNull;
282
+ if (type === "enum") return `(${comparison} OR (${right} IS NULL AND ${whenNull}))`;
276
283
  return `(CASE WHEN ${renderer.cast(right, {
277
284
  kind: "typed",
278
285
  type: type === "derived" ? description.right.sqlType : type
279
- })} IS NULL THEN ${left} IS ${operator === "<>" ? "NOT " : ""}NULL ELSE ${comparison} END)`;
286
+ })} IS NULL THEN ${whenNull} ELSE ${comparison} END)`;
280
287
  }
281
288
  case "between": {
282
289
  const operand = (node) => operandSql(compilation, node, bindings);
@@ -646,7 +653,7 @@ const sharedAggregates = (query) => {
646
653
  /** Subqueries evaluated once per outer row: nested collections, aggregates, EXISTS. */
647
654
  const containsCorrelatedSubquery = (node) => containsNode(node, (candidate) => candidate.kind === "subquery" || candidate.kind === "rowCount" || candidate.kind === "jsonRows");
648
655
  /** Raw SQL may hide windows, aggregates or volatile ordering; keep its scope intact. */
649
- const blocksRootPagination = (node) => containsNode(node, (candidate) => candidate.kind === "window" || candidate.kind === "relativeWindow" || candidate.kind === "aggregate" || candidate.kind === "raw");
656
+ const blocksRootPagination = (node) => containsNode(node, (candidate) => candidate.kind === "window" || candidate.kind === "relativeWindow" || candidate.kind === "aggregate" || candidate.kind === "raw" && !candidate.composed);
650
657
  /**
651
658
  * A paginated SELECT whose projection runs correlated subqueries can restrict
652
659
  * its root rows first, so PostgreSQL evaluates those subqueries only for the
@@ -699,7 +706,8 @@ const DISTANCES = /* @__PURE__ */ new Set([
699
706
  * filters only afterwards, so a filtered or a long LIMIT would come up short
700
707
  * without an error. For this statement the index returns as many rows as are
701
708
  * asked for (1000 is its ceiling) and, from pgvector 0.8, keeps scanning until
702
- * enough rows pass the filters. `set_config(…, true)` lasts for the
709
+ * enough rows pass the filters, with as much memory as that takes (up to
710
+ * pgvector's limit of 1000 × work_mem). `set_config(…, true)` lasts for the
703
711
  * transaction, which outside `$transaction()` is this one statement.
704
712
  */
705
713
  const nearestScanSql = (query, relaxed) => {
@@ -712,6 +720,7 @@ const nearestScanSql = (query, relaxed) => {
712
720
  ...rows > 40 ? [setting("hnsw.ef_search", `greatest(current_setting('hnsw.ef_search')::integer, ${Math.min(rows, 1e3)})::text`)] : [],
713
721
  setting("hnsw.iterative_scan", "'strict_order'"),
714
722
  setting("hnsw.max_scan_tuples", "'2147483647'"),
723
+ setting("hnsw.scan_mem_multiplier", "'1000'"),
715
724
  ...relaxed ? [setting("ivfflat.iterative_scan", "'relaxed_order'")] : []
716
725
  ].join(" || ")}) IS NOT NULL`;
717
726
  };
@@ -725,7 +734,7 @@ const nearestScanSql = (query, relaxed) => {
725
734
  const ordersThroughIvfflat = (query) => {
726
735
  const node = query.ordering[0]?.expression.node;
727
736
  const column = node?.kind === "binary" && node.left.kind === "column" ? node.left.description : void 0;
728
- return !!column && !query.locking && !query.distinct && !query.grouping.length && (column.binding.table.indexes ?? []).some((definition) => definition.method === "ivfflat" && definition.keys[0]?.startsWith(quoteIdentifier(column.column.sqlName)));
737
+ return !!column && !query.distinct && !query.grouping.length && (column.binding.table.indexes ?? []).some((definition) => definition.method === "ivfflat" && definition.keys[0]?.startsWith(quoteIdentifier(column.column.sqlName)));
729
738
  };
730
739
  const carriedLists = /* @__PURE__ */ new WeakMap();
731
740
  /** Every column of the root under its own name, for a page taken before its nested rows. */
@@ -749,6 +758,17 @@ const renderSelect = (compilation, query, outerBindings, jsonValues, jsonOutput)
749
758
  ...Object.fromEntries(query.joins.map((join) => [join.binding.alias, join.binding])),
750
759
  ...query.bindings
751
760
  }) : query.bindings;
761
+ if (jsonValues && query.distinct && query.ordering.length && query.selection.some((expression) => jsonPrecisionSql(compilation, expression, "") !== "")) {
762
+ const fields = query.ordering.map((ordering) => query.selection.find((expression) => sameExpression(expression.node, ordering.expression.node)));
763
+ if (fields.every(Boolean)) {
764
+ const field = (name) => `"__symmetria_distinct".${quoteIdentifier(name)}`;
765
+ return [
766
+ `SELECT ${query.selection.map((expression) => `${jsonPrecisionSql(compilation, expression, field(expression.outputName))} AS ${quoteIdentifier(expression.outputName)}`).join(", ")}`,
767
+ `FROM (${renderSelect(compilation, query, outerBindings, false, false)}) AS "__symmetria_distinct"`,
768
+ `ORDER BY ${query.ordering.map((ordering, position) => `${field(fields[position].outputName)} ${ordering.direction}${ordering.nulls ? ` NULLS ${ordering.nulls}` : ""}`).join(", ")}`
769
+ ].join("\n");
770
+ }
771
+ }
752
772
  const repeatsText = !!query.grouping.length || query.distinct;
753
773
  const ordersBySelected = !repeatsText && !compilation.shapeOnly && query.ordering.some(({ expression }) => expression.node.kind !== "column" && query.selection.some((selected) => sameExpression(selected.node, expression.node)));
754
774
  if (repeatsText || ordersBySelected) (compilation.expressionCaches ??= /* @__PURE__ */ new Map()).set(bindings, []);
@@ -901,7 +921,7 @@ const columnArrays = (query, columns) => {
901
921
  }
902
922
  const base = ARRAY_TYPES.exec(column.sqlType)?.[1];
903
923
  if (!base) {
904
- const empty = /^(jsonb|json|real|vector)(?:\(\d+\))?$/.exec(column.sqlType)?.[1];
924
+ const empty = /^(jsonb|json|real|vector|halfvec)(?:\(\d+\))?$/.exec(column.sqlType)?.[1];
905
925
  if (!empty) return;
906
926
  arrays.push({
907
927
  values,
@@ -1242,4 +1262,4 @@ const rowDecoder = (plan) => {
1242
1262
  //#endregion
1243
1263
  export { currentScopes as a, rowDecoder as c, compileTemplate as i, queryOccurrence as l, compileQuery as n, executeCompiled as o, compileShape as r, executePlan as s, compilePlan as t, batchCollectors as u };
1244
1264
 
1245
- //# sourceMappingURL=compile-ZwOWiPod.js.map
1265
+ //# sourceMappingURL=compile-D2gkALSH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile-D2gkALSH.js","names":[],"sources":["../src/query/plan/batching.ts","../src/query/plan/equivalence.ts","../src/query/compile/values.ts","../src/query/compile/predicates.ts","../src/query/plan/occurrence.ts","../src/query/expressions/aggregates.ts","../src/query/compile/select.ts","../src/query/compile/mutations.ts","../src/query/compile/cte.ts","../src/query/compile/index.ts"],"sourcesContent":["/**\n * Where an open `$batch()` collects its reads. Kept apart from the batch\n * itself so the compiler entry can look an executor up without importing it.\n */\nimport type { ExecutionResult, QueryExecutor, SelectPlan } from \"./types\";\n\nexport type BatchCollector = {\n /** The read's result once the batch has run, or undefined when it cannot join the batch. */\n readonly add: (plan: SelectPlan) => Promise<ExecutionResult> | undefined;\n};\n\nexport const batchCollectors = new WeakMap<QueryExecutor, BatchCollector>();\n","import { isDeepStrictEqual } from \"node:util\";\nimport type { PredicateDescription, ValueNode } from \"../expressions\";\nimport type { SelectPlan, TableBinding } from \"./types\";\n\nconst sameParameter = (first: unknown, second: unknown): boolean => {\n if (!isDeepStrictEqual(first, second)) {\n return false;\n }\n\n if (first === null || typeof first !== \"object\") {\n return true;\n }\n\n // Drivers can expose object-key order as text, including inside array parameters.\n const representation = (_key: string, value: unknown): unknown =>\n typeof value === \"bigint\" ? String(value) : value;\n\n try {\n return (\n JSON.stringify(first, representation) ===\n JSON.stringify(second, representation)\n );\n } catch {\n return false;\n }\n};\n\n/** Bindings and parameter codecs are identities, even when their shapes match. */\nexport const sameExpression = (\n left: ValueNode | readonly PredicateDescription[],\n right: ValueNode | readonly PredicateDescription[],\n bindings?: ReadonlyMap<TableBinding, TableBinding>,\n): boolean => {\n const equivalent = (\n first: unknown,\n second: unknown,\n field?: string,\n correspondence = bindings,\n ): boolean => {\n if (first === second) {\n return true;\n }\n\n if (field === \"binding\" || field === \"root\" || field === \"from\") {\n return correspondence?.get(first as TableBinding) === second;\n }\n\n if (field === \"scope\" || field === \"codec\") {\n return false;\n }\n\n if (\n !first ||\n !second ||\n typeof first !== \"object\" ||\n typeof second !== \"object\"\n ) {\n return false;\n }\n\n // Parameter contents are application data, even when they resemble AST nodes.\n if (\"kind\" in first && first.kind === \"parameter\") {\n const parameter = first as Extract<ValueNode, { kind: \"parameter\" }>;\n const other = second as Partial<typeof parameter>;\n\n return (\n other.kind === \"parameter\" &&\n parameter.cast === other.cast &&\n parameter.sqlType === other.sqlType &&\n sameParameter(parameter.value, other.value)\n );\n }\n\n if (\n \"kind\" in first &&\n first.kind === \"select\" &&\n \"kind\" in second &&\n second.kind === \"select\"\n ) {\n const firstQuery = first as SelectPlan;\n const secondQuery = second as SelectPlan;\n const aliases = Object.keys(firstQuery.bindings);\n const localBindings = new Map(correspondence);\n\n if (aliases.length !== Object.keys(secondQuery.bindings).length) {\n return false;\n }\n\n for (const alias of aliases) {\n const firstBinding = firstQuery.bindings[alias]!;\n const secondBinding = secondQuery.bindings[alias];\n\n if (\n !secondBinding ||\n firstBinding.table !== secondBinding.table ||\n firstBinding.alias !== secondBinding.alias ||\n firstBinding.derived !== secondBinding.derived ||\n firstBinding.cte !== secondBinding.cte ||\n firstBinding.cteReference !== secondBinding.cteReference\n ) {\n return false;\n }\n\n localBindings.set(firstBinding, secondBinding);\n }\n\n return (\n Object.keys(firstQuery).length === Object.keys(secondQuery).length &&\n Object.keys(firstQuery).every(\n (name) =>\n Object.hasOwn(secondQuery, name) &&\n (name === \"bindings\" ||\n equivalent(\n firstQuery[name as keyof SelectPlan],\n secondQuery[name as keyof SelectPlan],\n name,\n localBindings,\n )),\n )\n );\n }\n\n const fields = Object.keys(first);\n\n return (\n fields.length === Object.keys(second).length &&\n fields.every(\n (name) =>\n Object.hasOwn(second, name) &&\n equivalent(\n (first as Record<string, unknown>)[name],\n (second as Record<string, unknown>)[name],\n name,\n correspondence,\n ),\n )\n );\n };\n\n return equivalent(left, right);\n};\n","/**\n * Renders value expressions, operands, orderings and projections to SQL with the right codecs and casts.\n */\nimport { bigintCodec, numericCodec, cloneParameter } from \"../codecs\";\nimport { expressionSqlType } from \"../plan/metadata\";\nimport { sameExpression } from \"../plan/equivalence\";\nimport { containsNode } from \"../plan/traverse\";\nimport type {\n ExpressionDescription,\n ValueNode,\n WindowBoundary,\n} from \"../expressions\";\nimport { containsBinding, type OrderingDescription } from \"../plan/types\";\nimport {\n aliasSql,\n parameter,\n quoteIdentifier,\n renderContext,\n type Bindings,\n type Compilation,\n} from \"./state\";\nimport {\n searchHeadlineSql,\n headlineOptionsText,\n searchRankSql,\n searchVectorSql,\n tsquerySql,\n tsvectorSql,\n} from \"./postgres/search\";\n\n/** bigint and numeric values travel as text inside JSON to keep their precision. */\nexport const jsonPrecisionSql = (\n compilation: Compilation,\n expression: ExpressionDescription,\n value: string,\n): string => {\n const sqlType = expressionSqlType(expression);\n const array =\n sqlType.endsWith(\"[]\") || expression.codec?.parameterCast?.endsWith(\"[]\");\n const codec = array ? expression.codec?.element : expression.codec;\n const scalarType = array ? sqlType.slice(0, -2) : sqlType;\n\n if (\n codec !== bigintCodec &&\n codec !== numericCodec &&\n scalarType !== \"bigint\" &&\n !scalarType.startsWith(\"numeric\")\n ) {\n // Polymorphic JSON constructors cannot infer a bare placeholder's type.\n if (\n (expression.node.kind === \"placeholder\" ||\n expression.node.kind === \"parameter\") &&\n sqlType !== \"derived\"\n ) {\n return compilation.renderer.cast(value, {\n kind: \"typed\",\n type: sqlType === \"enum\" ? \"text\" : sqlType,\n });\n }\n\n return value;\n }\n\n // Preserve the array shape and NULL elements while stringifying each number.\n return compilation.renderer.cast(value, { kind: \"text\", array: !!array });\n};\n\nconst BARE_PARAMETER = /^\\(*\\$\\d+\\)*$/;\n\nconst buildsJson = (node: ValueNode): boolean =>\n node.kind === \"jsonObject\" || node.kind === \"jsonRows\";\n\nexport const valueSql = (\n compilation: Compilation,\n node: ValueNode,\n bindings: Bindings,\n jsonOutput = false,\n): string => {\n const aggregate =\n node.kind === \"subquery\"\n ? compilation.aggregateReferences?.get(bindings)?.get(node)\n : undefined;\n\n if (aggregate) {\n return aggregate;\n }\n\n const cache =\n node.kind !== \"column\" &&\n node.kind !== \"parameter\" &&\n node.kind !== \"placeholder\"\n ? compilation.expressionCaches?.get(bindings)\n : undefined;\n // Only JSON builders render differently as the statement's own output.\n const existing = cache?.find(\n (entry) =>\n sameExpression(entry.node, node) &&\n (entry.jsonOutput === jsonOutput ||\n (!compilation.shapeOnly && !containsNode(node, buildsJson))),\n );\n\n if (existing) {\n return existing.sql;\n }\n\n const sql = renderValue(compilation, node, bindings, jsonOutput);\n\n // A bare `$1` takes its type from where it stands, so two clauses that\n // shared one could give it two types; each keeps a parameter of its own.\n if (cache && !BARE_PARAMETER.test(sql)) {\n cache.push({ node, sql, jsonOutput });\n }\n\n return sql;\n};\n\n/** Raw SQL is opaque: parenthesize it wherever an operator could bind into it. */\nexport const operandSql = (\n compilation: Compilation,\n node: ValueNode,\n bindings: Bindings,\n): string => {\n const sql = valueSql(compilation, node, bindings);\n\n return node.kind === \"raw\" ? `(${sql})` : sql;\n};\n\n/** One ORDER BY key with its direction and optional NULLS position. */\nexport const orderingSql = (\n compilation: Compilation,\n ordering: OrderingDescription,\n bindings: Bindings,\n): string => {\n const node = ordering.expression.node;\n const sql = valueSql(compilation, node, bindings);\n const nulls = ordering.nulls;\n\n return `${sql} ${ordering.direction}${nulls ? ` NULLS ${nulls}` : \"\"}`;\n};\n\n/** The document side of a full-text match; multi-part documents are parenthesized before `@@`. */\nexport const searchVector = (\n compilation: Compilation,\n node: ValueNode,\n bindings: Bindings,\n language: string,\n): string => {\n const rendered = searchVectorSql(\n valueSql(compilation, node, bindings),\n language,\n expressionSqlType({ node, outputName: \"value\" }) === \"tsvector\",\n );\n\n return node.kind === \"tsvector\" && node.parts.length > 1\n ? `(${rendered})`\n : rendered;\n};\n\n/**\n * An aggregate call, rendered with its argument now and completed with a\n * window's OVER clause, if any, right after the call. MIN and MAX of a type\n * without them take the first element of the aggregated one-element arrays,\n * which order by the type's comparison, skipping NULL and JSON null.\n */\nconst aggregateSql = (\n compilation: Compilation,\n node: Extract<ValueNode, { kind: \"aggregate\" }>,\n bindings: Bindings,\n): ((over?: string) => string) => {\n const value = node.value ? valueSql(compilation, node.value, bindings) : \"*\";\n\n return (over = \"\") => {\n if (node.element) {\n const present =\n node.element === \"json\"\n ? `${value} <> 'null'::jsonb`\n : `${value} IS NOT NULL`;\n\n return `(${node.name}(ARRAY[${value}]) FILTER (WHERE ${present})${over})[1]`;\n }\n\n const aggregate = `${node.name}(${value})${over}`;\n\n return node.numeric\n ? compilation.renderer.cast(aggregate, { kind: \"numeric\" })\n : aggregate;\n };\n};\n\nconst renderValue = (\n compilation: Compilation,\n node: ValueNode,\n bindings: Bindings,\n jsonOutput: boolean,\n): string => {\n const { renderer } = compilation;\n\n switch (node.kind) {\n case \"placeholder\": {\n if (!compilation.placeholder) {\n throw new Error(\n `symmetria: bind parameter \"${node.name}\" with prepare()`,\n );\n }\n\n const bound = parameter(compilation, compilation.placeholder(node));\n\n return node.codec?.parameterCast\n ? renderer.cast(bound, {\n kind: \"parameter\",\n type: node.codec.parameterCast,\n })\n : bound;\n }\n case \"column\": {\n const { binding, column } = node.description;\n\n if (!containsBinding(bindings, binding)) {\n throw new Error(\n `symmetria: column \"${binding.alias}.${column.name}\" belongs to another query scope; use a distinct alias for correlated queries`,\n );\n }\n\n return `${aliasSql(compilation, binding)}.${quoteIdentifier(column.sqlName)}`;\n }\n case \"jsonPath\":\n return renderer.jsonPath(\n valueSql(compilation, node.value, bindings),\n node.path,\n { scalarType: node.scalarType },\n renderContext(compilation, bindings),\n );\n case \"arrayIndex\":\n return renderer.arrayIndex(\n valueSql(compilation, node.value, bindings),\n node.position,\n renderContext(compilation, bindings),\n );\n case \"jsonObject\":\n return renderer.jsonObject(\n node.selection.map((expression) => ({\n key: expression.outputName,\n value: jsonPrecisionSql(\n compilation,\n expression,\n valueSql(compilation, expression.node, bindings, jsonOutput),\n ),\n })),\n jsonOutput,\n );\n case \"parameter\": {\n const bound = parameter(compilation, cloneParameter(node.value));\n\n return node.cast\n ? renderer.cast(bound, { kind: \"parameter\", type: node.cast })\n : bound;\n }\n case \"raw\":\n return node.parts\n .map((part) =>\n typeof part === \"string\"\n ? part\n : operandSql(compilation, part, bindings),\n )\n .join(\"\");\n case \"binary\":\n return `(${operandSql(compilation, node.left, bindings)} ${node.operator} ${operandSql(compilation, node.right, bindings)})`;\n case \"aggregate\":\n return aggregateSql(compilation, node, bindings)();\n case \"case\":\n return `(CASE ${valueSql(compilation, node.value, bindings)} ${node.branches.map((branch) => `WHEN ${valueSql(compilation, branch.when, bindings)} THEN ${valueSql(compilation, branch.then, bindings)}`).join(\" \")} END)`;\n case \"coalesce\":\n return `COALESCE(${node.values.map((value) => valueSql(compilation, value, bindings)).join(\", \")})`;\n case \"tuple\":\n return `(${node.values.map((value) => valueSql(compilation, value, bindings)).join(\", \")})`;\n case \"relativeWindow\":\n return `${node.name.toUpperCase()}(${[node.value, node.offset, ...(node.fallback ? [node.fallback] : [])].map((value) => valueSql(compilation, value, bindings)).join(\", \")})`;\n case \"window\": {\n // The expression renders first, so its parameters precede the frame's.\n const aggregate =\n node.expression.kind === \"aggregate\"\n ? aggregateSql(compilation, node.expression, bindings)\n : undefined;\n const expressionSQL = aggregate\n ? \"\"\n : valueSql(compilation, node.expression, bindings);\n const fragments: string[] = [];\n\n if (node.partitionBy.length) {\n fragments.push(\n `PARTITION BY ${node.partitionBy.map((value) => valueSql(compilation, value, bindings)).join(\", \")}`,\n );\n }\n\n if (node.orderBy.length) {\n fragments.push(\n `ORDER BY ${node.orderBy.map((ordering) => orderingSql(compilation, ordering, bindings)).join(\", \")}`,\n );\n }\n\n if (node.rows) {\n const boundary = (value: WindowBoundary) =>\n typeof value === \"string\"\n ? value.toUpperCase()\n : \"preceding\" in value\n ? `${parameter(compilation, value.preceding)} PRECEDING`\n : `${parameter(compilation, value.following)} FOLLOWING`;\n\n fragments.push(\n `ROWS BETWEEN ${boundary(node.rows[0])} AND ${boundary(node.rows[1])}`,\n );\n }\n\n const suffix = ` OVER (${fragments.join(\" \")})`;\n\n // OVER follows the aggregate call, inside its numeric cast or element access.\n return aggregate ? aggregate(suffix) : `${expressionSQL}${suffix}`;\n }\n case \"subquery\":\n return `(${compilation.selectSql(node.query, bindings)})`;\n case \"searchRank\":\n return searchRankSql(\n searchVector(compilation, node.value, bindings, node.language),\n tsquerySql(\n valueSql(compilation, node.query, bindings),\n node.language,\n node.mode,\n ),\n {\n ...(node.weights ? { weights: node.weights } : {}),\n ...(node.normalization === undefined\n ? {}\n : { normalization: node.normalization }),\n coverDensity: !!node.coverDensity,\n },\n );\n case \"searchHeadline\": {\n const value = valueSql(compilation, node.value, bindings);\n const query = tsquerySql(\n valueSql(compilation, node.query, bindings),\n node.language,\n node.mode,\n );\n const options = headlineOptionsText(node.options);\n\n return searchHeadlineSql(\n node.language,\n value,\n query,\n options === undefined ? undefined : parameter(compilation, options),\n );\n }\n case \"tsvector\":\n return tsvectorSql(\n node.parts.map((part) => ({\n value: valueSql(compilation, part.value, bindings),\n ...(part.weight ? { weight: part.weight } : {}),\n isVector:\n expressionSqlType({ node: part.value, outputName: \"value\" }) ===\n \"tsvector\",\n })),\n node.language,\n );\n case \"arrayLength\":\n return renderer.arrayLength(\n valueSql(compilation, node.value, bindings),\n !!node.json,\n );\n case \"rowCount\":\n return `(SELECT COUNT(*) FROM (${compilation.selectSql(node.query, bindings)}) AS \"__symmetria_count\")`;\n case \"jsonRows\":\n return renderer.jsonRows(\n compilation.selectSql(node.query, bindings, true, jsonOutput),\n node.many,\n jsonOutput,\n );\n }\n};\n\nexport const projectionSql = (\n compilation: Compilation,\n selection: readonly ExpressionDescription[],\n bindings: Bindings,\n jsonValues = false,\n jsonOutput = false,\n): string =>\n selection\n .map((expression) => {\n const value = valueSql(\n compilation,\n expression.node,\n bindings,\n jsonOutput,\n );\n const node = expression.node;\n const projected = jsonValues\n ? jsonPrecisionSql(compilation, expression, value)\n : node.kind === \"placeholder\" &&\n !node.codec?.parameterCast &&\n node.sqlType !== \"derived\"\n ? compilation.renderer.cast(value, {\n kind: \"typed\",\n type: node.sqlType === \"enum\" ? \"text\" : node.sqlType,\n })\n : value;\n\n return `${projected} AS ${quoteIdentifier(expression.outputName)}`;\n })\n .join(\", \");\n","/**\n * Renders predicate nodes (comparisons, IN lists, JSON checks, subqueries) to SQL.\n */\nimport { expressionSqlType } from \"../plan/metadata\";\nimport { tsquerySql } from \"./postgres/search\";\nimport type {\n PredicateDescription,\n ScopePredicate,\n ValueNode,\n} from \"../expressions\";\nimport type { SelectPlan } from \"../plan/types\";\nimport {\n parameter,\n renderContext,\n type Bindings,\n type Compilation,\n} from \"./state\";\nimport { jsonPrecisionSql, operandSql, searchVector, valueSql } from \"./values\";\n\nconst sqlTypeOf = (node: ValueNode): string =>\n expressionSqlType({ node, outputName: \"value\" });\n\n/** Lists longer than this bind as a single PostgreSQL array parameter. */\nconst LARGE_LIST_THRESHOLD = 1000;\n\nconst largeListType = (\n description: Extract<PredicateDescription, { kind: \"membership\" }>,\n): string | undefined => {\n if (\n !Array.isArray(description.values) ||\n description.values.length <= LARGE_LIST_THRESHOLD ||\n !description.values.every(\n (value: ValueNode) => value.kind === \"parameter\" && !value.cast,\n )\n ) {\n return undefined;\n }\n\n const type = sqlTypeOf(description.value);\n\n return /^(?:smallint|integer|bigint|text|uuid|boolean|timestamptz|date|(?:numeric|varchar|character varying)(?:\\(\\d+(?:,\\s*\\d+)?\\))?)$/.test(\n type,\n )\n ? type\n : undefined;\n};\n\n/** Stands for a $scope() filter in a shape-only compilation; never executed. */\nconst SCOPE_MARKER = \"<$scope>\";\n\n/**\n * A $scope() filter renders like any predicate, and the compilation records\n * where it landed: its SQL, parameter range, bindings and aliases, so each\n * execution can render the callback's current result in its place. Expression\n * caches stay out of it, so no other clause reuses its parameters.\n */\nconst scopeSql = (\n compilation: Compilation,\n description: ScopePredicate,\n bindings: Bindings,\n): string => {\n if (compilation.shapeOnly) {\n return SCOPE_MARKER;\n }\n\n const current =\n compilation.scopeValues?.get(description) ?? description.predicate;\n const caches = compilation.expressionCaches;\n const aliases = new Map(compilation.aliasNames);\n const start = compilation.parameters.length;\n compilation.expressionCaches = undefined;\n\n try {\n const sql = predicateSql(compilation, current, bindings);\n (compilation.scopes ??= []).push({\n description,\n bindings,\n aliases,\n start,\n end: compilation.parameters.length,\n sql,\n });\n\n return sql;\n } finally {\n compilation.expressionCaches = caches;\n }\n};\n\nexport const predicateSql = (\n compilation: Compilation,\n description: PredicateDescription,\n bindings: Bindings,\n): string => {\n const { renderer } = compilation;\n\n switch (description.kind) {\n case \"group\":\n if (!description.predicates.length) {\n return description.operator === \"AND\" ? \"TRUE\" : \"FALSE\";\n }\n\n return `(${description.predicates.map((child) => predicateSql(compilation, child, bindings)).join(` ${description.operator} `)})`;\n case \"scope\":\n return scopeSql(compilation, description, bindings);\n case \"not\":\n return `NOT (${predicateSql(compilation, description.predicate, bindings)})`;\n case \"notTrue\":\n return `(${predicateSql(compilation, description.predicate, bindings)}) IS NOT TRUE`;\n case \"nullCheck\":\n return `${operandSql(compilation, description.value, bindings)} IS ${description.negated ? \"NOT \" : \"\"}NULL`;\n case \"comparison\": {\n const { operator } = description;\n const nullable =\n description.nullableParameter &&\n description.right.kind === \"placeholder\";\n const left = operandSql(compilation, description.left, bindings);\n const right = operandSql(compilation, description.right, bindings);\n const comparison = `${left} ${operator} ${right}`;\n\n if (!nullable || description.right.kind !== \"placeholder\") {\n return comparison;\n }\n\n const type = sqlTypeOf(description.left);\n const isNull = description.nullCheck\n ? predicateSql(compilation, description.nullCheck, bindings)\n : `${left} IS NULL`;\n const whenNull = operator === \"<>\" ? `NOT (${isNull})` : isNull;\n\n // An enum type's name is not known here to cast the parameter; the\n // comparison comes first, so PostgreSQL takes the type from it. As in\n // the CASE form, a NULL row never matches a value under = or <>.\n if (type === \"enum\") {\n return `(${comparison} OR (${right} IS NULL AND ${whenNull}))`;\n }\n\n const checked = renderer.cast(right, {\n kind: \"typed\",\n type: type === \"derived\" ? description.right.sqlType : type,\n });\n\n return `(CASE WHEN ${checked} IS NULL THEN ${whenNull} ELSE ${comparison} END)`;\n }\n case \"between\": {\n const operand = (node: ValueNode) =>\n operandSql(compilation, node, bindings);\n\n return `${operand(description.value)} BETWEEN ${operand(description.lower)} AND ${operand(description.upper)}`;\n }\n case \"has\": {\n if (description.json) {\n const value = operandSql(compilation, description.value, bindings);\n const element = operandSql(compilation, description.element, bindings);\n const expression = { node: description.element, outputName: \"value\" };\n\n return renderer.jsonHas(\n value,\n element,\n {\n overlap: !!description.overlap,\n encoded:\n description.element.kind === \"parameter\" ||\n description.element.kind === \"placeholder\",\n elementArray: expressionSqlType(expression).endsWith(\"[]\"),\n operand: jsonPrecisionSql(compilation, expression, element),\n },\n renderContext(compilation, bindings),\n );\n }\n\n const element = operandSql(compilation, description.element, bindings);\n const value = operandSql(compilation, description.value, bindings);\n\n return renderer.arrayHas(value, element);\n }\n case \"search\":\n return renderer.search(\n searchVector(\n compilation,\n description.value,\n bindings,\n description.language,\n ),\n tsquerySql(\n valueSql(compilation, description.query, bindings),\n description.language,\n description.mode,\n ),\n );\n case \"exists\":\n return `${description.negated ? \"NOT \" : \"\"}EXISTS (${compilation.selectSql(description.query, bindings)})`;\n case \"membership\": {\n if (Array.isArray(description.values) && !description.values.length) {\n return description.negated ? \"TRUE\" : \"FALSE\";\n }\n\n const left = operandSql(compilation, description.value, bindings);\n const arrayType = largeListType(description);\n\n if (arrayType) {\n const values = (description.values as readonly ValueNode[]).map(\n (value) => (value as Extract<ValueNode, { kind: \"parameter\" }>).value,\n );\n\n return `${left} ${description.negated ? \"<> ALL\" : \"= ANY\"}(${renderer.cast(parameter(compilation, values), { kind: \"typed\", type: `${arrayType}[]` })})`;\n }\n\n const operand = Array.isArray(description.values)\n ? description.values\n .map((value) => operandSql(compilation, value, bindings))\n .join(\", \")\n : compilation.selectSql(description.values as SelectPlan, bindings);\n\n return `${left} ${description.negated ? \"NOT \" : \"\"}IN (${operand})`;\n }\n }\n};\n","import { freeze } from \"./freeze\";\nimport type {\n ExpressionDescription,\n PredicateDescription,\n ValueNode,\n} from \"../expressions\";\nimport type { OrderingDescription, SelectPlan, TableBinding } from \"./types\";\n\nconst remap = <Value>(\n values: readonly Value[],\n visit: (value: Value) => Value,\n): readonly Value[] => (values.length ? freeze(values.map(visit)) : values);\n\n/** Rewrites plans and expressions onto other bindings; anything not listed stays as it is. */\nconst rebinder = (replacements: ReadonlyMap<TableBinding, TableBinding>) => {\n const derivedBindings = new Map<TableBinding, TableBinding>();\n\n const binding = (original: TableBinding): TableBinding => {\n if (!original.derived) {\n return replacements.get(original) ?? original;\n }\n\n const existing = derivedBindings.get(original);\n\n if (existing) {\n return existing;\n }\n\n const rebound = freeze({\n ...original,\n derived: query(original.derived),\n ...(original.projection\n ? {\n projection: freeze(\n Object.fromEntries(\n Object.entries(original.projection).map(([name, selected]) => [\n name,\n expression(selected),\n ]),\n ),\n ),\n }\n : {}),\n });\n derivedBindings.set(original, rebound);\n\n return rebound;\n };\n\n const expression = (\n original: ExpressionDescription,\n ): ExpressionDescription => {\n const node = value(original.node);\n\n return node === original.node ? original : freeze({ ...original, node });\n };\n\n const ordering = (original: OrderingDescription): OrderingDescription =>\n freeze({ ...original, expression: expression(original.expression) });\n\n const value = (original: ValueNode): ValueNode => {\n switch (original.kind) {\n case \"column\": {\n const rebound = binding(original.description.binding);\n\n if (rebound === original.description.binding) {\n return original;\n }\n\n return freeze({\n ...original,\n description: freeze({\n ...original.description,\n binding: rebound,\n }),\n });\n }\n case \"parameter\":\n case \"placeholder\":\n return original;\n case \"raw\":\n return freeze({\n ...original,\n parts: freeze(\n original.parts.map((part) =>\n typeof part === \"string\" ? part : value(part),\n ),\n ),\n });\n case \"binary\":\n return freeze({\n ...original,\n left: value(original.left),\n right: value(original.right),\n });\n case \"aggregate\":\n return original.value\n ? freeze({ ...original, value: value(original.value) })\n : original;\n case \"case\":\n return freeze({\n ...original,\n value: value(original.value),\n branches: freeze(\n original.branches.map((branch) =>\n freeze({\n when: value(branch.when),\n then: value(branch.then),\n }),\n ),\n ),\n });\n case \"coalesce\":\n case \"tuple\":\n return freeze({\n ...original,\n values: freeze(original.values.map(value)),\n });\n case \"relativeWindow\":\n return freeze({\n ...original,\n value: value(original.value),\n offset: value(original.offset),\n ...(original.fallback ? { fallback: value(original.fallback) } : {}),\n });\n case \"window\":\n return freeze({\n ...original,\n expression: value(original.expression),\n partitionBy: freeze(original.partitionBy.map(value)),\n orderBy: freeze(original.orderBy.map(ordering)),\n });\n case \"subquery\":\n case \"rowCount\":\n case \"jsonRows\":\n return freeze({ ...original, query: query(original.query) });\n case \"jsonObject\":\n return freeze({\n ...original,\n selection: freeze(original.selection.map(expression)),\n });\n case \"jsonPath\":\n case \"arrayLength\":\n case \"arrayIndex\":\n return freeze({ ...original, value: value(original.value) });\n case \"searchRank\":\n case \"searchHeadline\":\n return freeze({\n ...original,\n value: value(original.value),\n query: value(original.query),\n });\n case \"tsvector\":\n return freeze({\n ...original,\n parts: freeze(\n original.parts.map((part) =>\n freeze({ ...part, value: value(part.value) }),\n ),\n ),\n });\n }\n };\n\n const predicate = (original: PredicateDescription): PredicateDescription => {\n switch (original.kind) {\n case \"comparison\":\n return freeze({\n ...original,\n left: value(original.left),\n right: value(original.right),\n });\n case \"search\":\n return freeze({\n ...original,\n value: value(original.value),\n query: value(original.query),\n });\n case \"has\":\n return freeze({\n ...original,\n value: value(original.value),\n element: value(original.element),\n });\n case \"nullCheck\":\n return freeze({ ...original, value: value(original.value) });\n case \"group\":\n return freeze({\n ...original,\n predicates: freeze(original.predicates.map(predicate)),\n });\n case \"not\":\n case \"notTrue\":\n return freeze({\n ...original,\n predicate: predicate(original.predicate),\n });\n case \"membership\":\n return freeze({\n ...original,\n value: value(original.value),\n values: Array.isArray(original.values)\n ? freeze(original.values.map(value))\n : query(original.values as SelectPlan),\n });\n case \"between\":\n return freeze({\n ...original,\n value: value(original.value),\n lower: value(original.lower),\n upper: value(original.upper),\n });\n case \"exists\":\n return freeze({ ...original, query: query(original.query) });\n case \"scope\":\n // The callback runs again against the new occurrence at execution.\n return freeze({\n ...original,\n binding: binding(original.binding),\n predicate: predicate(original.predicate),\n });\n }\n };\n\n const query = (original: SelectPlan): SelectPlan =>\n freeze({\n ...original,\n root: binding(original.root),\n bindings: freeze(\n Object.fromEntries(\n Object.entries(original.bindings).map(([name, original]) => [\n name,\n binding(original),\n ]),\n ),\n ),\n joins: remap(original.joins, (join) =>\n freeze({\n ...join,\n binding: binding(join.binding),\n ...(join.condition ? { condition: predicate(join.condition) } : {}),\n ...(join.relation\n ? {\n relation: freeze({\n ...join.relation,\n from: binding(join.relation.from),\n }),\n }\n : {}),\n }),\n ),\n selection: remap(original.selection, expression),\n predicates: remap(original.predicates, predicate),\n grouping: remap(original.grouping, expression),\n having: remap(original.having, predicate),\n ordering: remap(original.ordering, ordering),\n });\n\n return { query, expression };\n};\n\n/** Give a reusable query new local sources, retaining its correlated ancestors. */\nexport const queryOccurrence = (source: SelectPlan): SelectPlan =>\n rebinder(\n new Map<TableBinding, TableBinding>(\n [source.root, ...source.joins.map((join) => join.binding)].map(\n (binding) => [binding, freeze({ ...binding })],\n ),\n ),\n ).query(source);\n\n/** An expression read from other bindings, such as one query's root in place of another's. */\nexport const reboundExpression = (\n expression: ExpressionDescription,\n replacements: ReadonlyMap<TableBinding, TableBinding>,\n): ExpressionDescription => rebinder(replacements).expression(expression);\n","/**\n * Plan analysis for aggregates: shared aggregate detection, correlated-subquery checks and root-first pagination.\n */\nimport type { ExpressionDescription, PredicateDescription, ValueNode } from \".\";\nimport { freeze } from \"../plan/freeze\";\nimport { reboundExpression } from \"../plan/occurrence\";\nimport type { SelectPlan } from \"../plan/types\";\nimport { sameExpression } from \"../plan/equivalence\";\nimport { containsNode } from \"../plan/traverse\";\n\ntype AggregateQuery = Extract<ValueNode, { kind: \"subquery\" }>;\n\n/**\n * Aggregates over one relation with one filter: `orders.count()` and\n * `orders.sum.total` read the same rows, so one subquery computes both.\n */\nexport type SharedAggregate = {\n /** The subquery with every distinct aggregate of the group selected. */\n readonly query: SelectPlan;\n /** Each replaced node and the column of `query` it reads. */\n readonly references: ReadonlyMap<ValueNode, string>;\n};\n\nexport type SharedAggregates = {\n /** Joined before WHERE: a filter reads them, or no LIMIT trims the rows. */\n readonly inner: readonly SharedAggregate[];\n /** Joined to the page a root-first pagination has already cut. */\n readonly outer: readonly SharedAggregate[];\n};\n\ntype AggregateGroup = {\n first: AggregateQuery;\n columns: { expression: ExpressionDescription; name: string }[];\n references: Map<ValueNode, string>;\n filtered: boolean;\n};\n\nconst NONE: SharedAggregates = Object.freeze({ inner: [], outer: [] });\n\nconst atomicValue = (node: ValueNode): boolean =>\n node.kind === \"column\" ||\n node.kind === \"parameter\" ||\n node.kind === \"placeholder\";\n\n/** Only deterministic, single-row aggregates can be shared across query clauses. */\nconst shareable = (node: AggregateQuery): boolean => {\n const query = node.query;\n\n if (\n query.root.derived ||\n query.root.cte ||\n query.root.cteReference ||\n query.joins.length ||\n query.grouping.length ||\n query.having.length ||\n query.ordering.length ||\n query.limit !== undefined ||\n query.offset !== undefined ||\n query.locking ||\n query.distinct ||\n query.selection.length !== 1 ||\n query.selection[0]!.node.kind !== \"aggregate\"\n ) {\n return false;\n }\n\n const deterministic = (value: unknown): boolean => {\n if (!value || typeof value !== \"object\") {\n return true;\n }\n\n if (\n \"kind\" in value &&\n [\"column\", \"parameter\", \"placeholder\"].includes(String(value.kind))\n ) {\n return true;\n }\n\n if (\"kind\" in value && value.kind === \"jsonPath\") {\n return deterministic(\n (value as Extract<ValueNode, { kind: \"jsonPath\" }>).value,\n );\n }\n\n if (\"kind\" in value && value.kind === \"scope\") {\n return deterministic(\n (value as Extract<PredicateDescription, { kind: \"scope\" }>).predicate,\n );\n }\n\n if (\n \"kind\" in value &&\n [\n \"raw\",\n \"window\",\n \"relativeWindow\",\n \"subquery\",\n \"rowCount\",\n \"jsonRows\",\n \"exists\",\n ].includes(String(value.kind))\n ) {\n return false;\n }\n\n return Object.values(value).every(deterministic);\n };\n\n return (\n deterministic(query.selection[0]!.node) && deterministic(query.predicates)\n );\n};\n\nconst subquery = (node: ValueNode): boolean => node.kind === \"subquery\";\n\nexport const sharedAggregates = (query: SelectPlan): SharedAggregates => {\n if (\n query.rootless ||\n query.joins.length ||\n query.grouping.length ||\n query.having.length ||\n query.distinct ||\n query.locking\n ) {\n return NONE;\n }\n\n // Most queries stop here: sharing needs two aggregates, or one that a filter repeats.\n const filters = !query.predicates.every(\n (predicate) =>\n predicate.kind === \"scope\" ||\n (predicate.kind === \"comparison\" &&\n atomicValue(predicate.left) &&\n atomicValue(predicate.right)),\n );\n\n if (\n !filters &&\n query.selection.reduce(\n (count, expression) =>\n count + (containsNode(expression.node, subquery) ? 1 : 0),\n 0,\n ) +\n (query.ordering.some((ordering) =>\n containsNode(ordering.expression.node, subquery),\n )\n ? 1\n : 0) <\n 2\n ) {\n return NONE;\n }\n\n const groups: AggregateGroup[] = [];\n\n const visit = (value: unknown, filtered: boolean): void => {\n if (!value || typeof value !== \"object\") {\n return;\n }\n\n if (Array.isArray(value)) {\n for (const child of value) {\n visit(child, filtered);\n }\n\n return;\n }\n\n if (\"kind\" in value) {\n const node = value as ValueNode | PredicateDescription;\n\n if (node.kind === \"comparison\" || node.kind === \"binary\") {\n visit(node.left, filtered);\n visit(node.right, filtered);\n\n return;\n }\n\n if (node.kind === \"jsonPath\") {\n visit(node.value, filtered);\n\n return;\n }\n\n if (node.kind === \"subquery\") {\n if (!shareable(node)) {\n return;\n }\n\n let group = groups.find(({ first }) => {\n const one = first.query;\n const other = node.query;\n\n return (\n one.root.table === other.root.table &&\n sameExpression(\n one.predicates,\n other.predicates,\n new Map([[one.root, other.root]]),\n )\n );\n });\n\n if (!group) {\n group = { first: node, columns: [], references: new Map(), filtered };\n groups.push(group);\n }\n\n // Read from the group's own source, so equal aggregates compare equal.\n const expression =\n group.first === node\n ? node.query.selection[0]!\n : reboundExpression(\n node.query.selection[0]!,\n new Map([[node.query.root, group.first.query.root]]),\n );\n let column = group.columns.find((existing) =>\n sameExpression(existing.expression.node, expression.node),\n );\n\n if (!column) {\n const taken = group.columns.some(\n (existing) => existing.name === expression.outputName,\n );\n\n column = {\n expression,\n name: taken\n ? `${expression.outputName}_${group.columns.length}`\n : expression.outputName,\n };\n group.columns.push(column);\n }\n\n group.references.set(node, column.name);\n group.filtered ||= filtered;\n\n return;\n }\n\n // $scope() filters are re-rendered per execution, so nothing inside\n // them may be shared with another clause.\n if (\n [\n \"column\",\n \"parameter\",\n \"placeholder\",\n \"rowCount\",\n \"jsonRows\",\n \"exists\",\n \"raw\",\n \"scope\",\n ].includes(node.kind)\n ) {\n return;\n }\n\n if (node.kind === \"membership\") {\n visit(node.value, filtered);\n\n if (Array.isArray(node.values)) {\n visit(node.values, filtered);\n }\n\n return;\n }\n }\n\n for (const [field, child] of Object.entries(value)) {\n if (field !== \"codec\") {\n visit(child, filtered);\n }\n }\n };\n\n visit(query.predicates, true);\n visit(query.selection, false);\n visit(query.ordering, false);\n\n const repeated = groups.filter((group) => group.references.size > 1);\n\n if (!repeated.length) {\n return NONE;\n }\n\n const shared = (group: AggregateGroup): SharedAggregate => ({\n query: freeze({\n ...group.first.query,\n selection: freeze(\n group.columns.map(({ expression, name }) =>\n freeze({ ...expression, outputName: name }),\n ),\n ),\n }),\n references: group.references,\n });\n\n // Without LIMIT every row is returned, so each of its aggregates runs anyway.\n if (query.limit === undefined && query.offset === undefined) {\n return { inner: repeated.map(shared), outer: [] };\n }\n\n const filtered = repeated.filter((group) => group.filtered);\n\n // A filter needs its aggregate before LIMIT, for every candidate row.\n if (filtered.length) {\n return { inner: filtered.map(shared), outer: [] };\n }\n\n // Otherwise only the rows of the page may pay for a subquery.\n return paginatesRootFirst(query)\n ? { inner: [], outer: repeated.map(shared) }\n : NONE;\n};\n\n/** Subqueries evaluated once per outer row: nested collections, aggregates, EXISTS. */\nconst containsCorrelatedSubquery = (node: ValueNode): boolean =>\n containsNode(\n node,\n (candidate) =>\n candidate.kind === \"subquery\" ||\n candidate.kind === \"rowCount\" ||\n candidate.kind === \"jsonRows\",\n );\n\n/** Raw SQL may hide windows, aggregates or volatile ordering; keep its scope intact. */\nconst blocksRootPagination = (node: ValueNode): boolean =>\n containsNode(\n node,\n (candidate) =>\n candidate.kind === \"window\" ||\n candidate.kind === \"relativeWindow\" ||\n candidate.kind === \"aggregate\" ||\n (candidate.kind === \"raw\" && !candidate.composed),\n );\n\n/**\n * A paginated SELECT whose projection runs correlated subqueries can restrict\n * its root rows first, so PostgreSQL evaluates those subqueries only for the\n * rows that survive LIMIT/OFFSET instead of for every scanned row.\n */\nexport const paginatesRootFirst = (query: SelectPlan): boolean =>\n (query.limit !== undefined || query.offset !== undefined) &&\n !query.distinct &&\n !query.grouping.length &&\n !query.having.length &&\n !query.locking &&\n !query.joins.length &&\n query.selection.some((expression) =>\n containsCorrelatedSubquery(expression.node),\n ) &&\n !query.selection.some((expression) =>\n blocksRootPagination(expression.node),\n ) &&\n !query.ordering.some(\n (ordering) =>\n blocksRootPagination(ordering.expression.node) ||\n containsCorrelatedSubquery(ordering.expression.node),\n );\n","/**\n * Renders SELECT plans: FROM/JOIN clauses, nested JSON projections, pagination and locking.\n */\nimport {\n paginatesRootFirst,\n sharedAggregates,\n type SharedAggregates,\n} from \"../expressions/aggregates\";\nimport type { ValueNode } from \"../expressions\";\nimport { sameExpression } from \"../plan/equivalence\";\nimport {\n containsBinding,\n mergeBindings,\n numberedAlias,\n type SelectPlan,\n type TableBinding,\n} from \"../plan/types\";\nimport {\n aliasSql,\n quoteIdentifier,\n type Bindings,\n type Compilation,\n} from \"./state\";\nimport {\n jsonPrecisionSql,\n orderingSql,\n projectionSql,\n valueSql,\n} from \"./values\";\nimport { predicateSql } from \"./predicates\";\n\nexport const tableSql = (\n compilation: Compilation,\n binding: TableBinding,\n ancestors: Bindings = {},\n): string => {\n if (\n binding.cte &&\n compilation.commonTables.get(binding.cte.name) !== binding.cte\n ) {\n throw new Error(\n `symmetria: internal error, CTE \"${binding.cte.name}\" was not collected before rendering`,\n );\n }\n\n return `${binding.derived ? `(${selectSql(compilation, binding.derived, ancestors)})` : quoteIdentifier(binding.cteReference?.name ?? binding.table.sqlName)} AS ${aliasSql(compilation, binding)}`;\n};\n\nexport const selectSql = (\n compilation: Compilation,\n query: SelectPlan,\n outerBindings: Bindings,\n jsonValues = false,\n jsonOutput = false,\n): string => {\n // A data error found while building this query or one it embeds.\n if (query.failure) {\n throw query.failure.error;\n }\n\n if (\n !query.joins.length &&\n !Object.keys(outerBindings).length &&\n !compilation.aliasNames.has(query.root)\n ) {\n return renderSelect(\n compilation,\n query,\n outerBindings,\n jsonValues,\n jsonOutput,\n );\n }\n\n const occupied = new Set(\n Object.values(outerBindings).map(\n (binding) => compilation.aliasNames.get(binding) ?? binding.alias,\n ),\n );\n const previousAliases = new Map<TableBinding, string | undefined>();\n\n try {\n for (const binding of [\n query.root,\n ...query.joins.map((join) => join.binding),\n ]) {\n if (containsBinding(outerBindings, binding)) {\n if (\n compilation.plan.kind !== \"select\" &&\n binding === compilation.plan.root\n ) {\n continue;\n }\n\n throw new Error(\n \"symmetria: nested queries require a distinct source occurrence\",\n );\n }\n\n previousAliases.set(binding, compilation.aliasNames.get(binding));\n let alias = binding.alias;\n let ordinal = 2;\n\n while (occupied.has(alias)) {\n alias = numberedAlias(binding.alias, ordinal++);\n }\n\n occupied.add(alias);\n compilation.aliasNames.set(binding, alias);\n }\n\n return renderSelect(\n compilation,\n query,\n outerBindings,\n jsonValues,\n jsonOutput,\n );\n } finally {\n for (const [binding, alias] of previousAliases) {\n if (alias === undefined) {\n compilation.aliasNames.delete(binding);\n } else {\n compilation.aliasNames.set(binding, alias);\n }\n }\n }\n};\n\nconst DISTANCES = new Set([\"<->\", \"<=>\", \"<#>\", \"<+>\"]);\n\n/**\n * A condition for \"the nearest N rows\": true, and it reads no column, so\n * PostgreSQL evaluates it once, before the scan it guards. pgvector's HNSW\n * index hands back `hnsw.ef_search` rows (40 unless set) and meets the other\n * filters only afterwards, so a filtered or a long LIMIT would come up short\n * without an error. For this statement the index returns as many rows as are\n * asked for (1000 is its ceiling) and, from pgvector 0.8, keeps scanning until\n * enough rows pass the filters, with as much memory as that takes (up to\n * pgvector's limit of 1000 × work_mem). `set_config(…, true)` lasts for the\n * transaction, which outside `$transaction()` is this one statement.\n */\nconst nearestScanSql = (\n query: SelectPlan,\n relaxed: boolean,\n): string | undefined => {\n const first = query.ordering[0];\n const node = first?.expression.node;\n\n if (\n query.limit === undefined ||\n first?.direction !== \"ASC\" ||\n node?.kind !== \"binary\" ||\n !DISTANCES.has(node.operator)\n ) {\n return undefined;\n }\n\n const rows =\n typeof query.limit === \"number\"\n ? query.limit + (typeof query.offset === \"number\" ? query.offset : 0)\n : 0;\n const setting = (name: string, value: string) =>\n `CASE WHEN current_setting('${name}', true) IS NULL THEN '' ELSE set_config('${name}', ${value}, true) END`;\n\n return `(SELECT ${[\n ...(rows > 40\n ? [\n setting(\n \"hnsw.ef_search\",\n `greatest(current_setting('hnsw.ef_search')::integer, ${Math.min(rows, 1000)})::text`,\n ),\n ]\n : []),\n setting(\"hnsw.iterative_scan\", \"'strict_order'\"),\n setting(\"hnsw.max_scan_tuples\", \"'2147483647'\"),\n // The scan also stops at work_mem × this multiplier (1 unless set):\n // about 23,000 index tuples at 4MB, after which rows that pass the\n // filters further away were lost without an error.\n setting(\"hnsw.scan_mem_multiplier\", \"'1000'\"),\n ...(relaxed ? [setting(\"ivfflat.iterative_scan\", \"'relaxed_order'\")] : []),\n ].join(\" || \")}) IS NOT NULL`;\n};\n\n/**\n * Whether the schema declares an IVFFlat index on the column the query takes\n * its nearest rows by. Such an index reads the lists nearest to the question\n * and stops, so a filter can leave it short of rows; it can read on (pgvector\n * 0.8), but then returns rows only roughly in order. The statement lets it,\n * and sorts the rows it returned once more, exactly.\n */\nconst ordersThroughIvfflat = (query: SelectPlan): boolean => {\n const node = query.ordering[0]?.expression.node;\n const column =\n node?.kind === \"binary\" && node.left.kind === \"column\"\n ? node.left.description\n : undefined;\n\n // A row lock stays on the inner statement, which may lock rows in a\n // subquery; the outer one only sorts them again.\n return (\n !!column &&\n !query.distinct &&\n !query.grouping.length &&\n (column.binding.table.indexes ?? []).some(\n (definition) =>\n definition.method === \"ivfflat\" &&\n definition.keys[0]?.startsWith(quoteIdentifier(column.column.sqlName)),\n )\n );\n};\n\nconst carriedLists = new WeakMap<TableBinding[\"table\"], Map<string, string>>();\n\n/** Every column of the root under its own name, for a page taken before its nested rows. */\nconst carriedColumns = (root: TableBinding, alias: string): string => {\n let lists = carriedLists.get(root.table);\n\n if (!lists) {\n carriedLists.set(root.table, (lists = new Map()));\n }\n\n let list = lists.get(alias);\n\n if (list === undefined) {\n list = root.table.columns\n .map(\n (column) =>\n `${alias}.${quoteIdentifier(column.sqlName)} AS ${quoteIdentifier(column.sqlName)}`,\n )\n .join(\", \");\n\n // A table is read under a handful of aliases; generated ones stay bounded.\n if (lists.size < 64) {\n lists.set(alias, list);\n }\n }\n\n return list;\n};\n\nconst NO_SHARED_AGGREGATES: SharedAggregates = { inner: [], outer: [] };\n\nconst renderSelect = (\n compilation: Compilation,\n query: SelectPlan,\n outerBindings: Bindings,\n jsonValues: boolean,\n jsonOutput: boolean,\n): string => {\n if (!query.selection.length) {\n throw new Error(\n \"symmetria: select fields in a shape before compiling or executing a query\",\n );\n }\n\n const bindings =\n query.joins.length || Object.keys(outerBindings).length\n ? mergeBindings(outerBindings, {\n ...Object.fromEntries(\n query.joins.map((join) => [join.binding.alias, join.binding]),\n ),\n ...query.bindings,\n })\n : query.bindings;\n\n // In JSON, bigint and numeric values travel as text; a DISTINCT query\n // ordered by such a value would then order by an expression its select\n // list does not have. It runs as it would at the top level, and the text\n // casts and the order are applied around it.\n if (\n jsonValues &&\n query.distinct &&\n query.ordering.length &&\n query.selection.some(\n (expression) => jsonPrecisionSql(compilation, expression, \"\") !== \"\",\n )\n ) {\n const fields = query.ordering.map((ordering) =>\n query.selection.find((expression) =>\n sameExpression(expression.node, ordering.expression.node),\n ),\n );\n\n if (fields.every(Boolean)) {\n const field = (name: string) =>\n `\"__symmetria_distinct\".${quoteIdentifier(name)}`;\n\n return [\n `SELECT ${query.selection\n .map(\n (expression) =>\n `${jsonPrecisionSql(compilation, expression, field(expression.outputName))} AS ${quoteIdentifier(expression.outputName)}`,\n )\n .join(\", \")}`,\n `FROM (${renderSelect(compilation, query, outerBindings, false, false)}) AS \"__symmetria_distinct\"`,\n `ORDER BY ${query.ordering\n .map(\n (ordering, position) =>\n `${field(fields[position]!.outputName)} ${ordering.direction}${ordering.nulls ? ` NULLS ${ordering.nulls}` : \"\"}`,\n )\n .join(\", \")}`,\n ].join(\"\\n\");\n }\n }\n\n // A grouped or distinct query must repeat an expression as the same text.\n // An ordering by a selected field repeats it too: with the same text and\n // parameters PostgreSQL computes the expression once, not once per clause.\n const repeatsText = !!query.grouping.length || query.distinct;\n // A shape identifies the query across releases (page cursors), so it is\n // rendered plainly, without the rewrites that only make a statement faster.\n const ordersBySelected =\n !repeatsText &&\n !compilation.shapeOnly &&\n query.ordering.some(\n ({ expression }) =>\n expression.node.kind !== \"column\" &&\n query.selection.some((selected) =>\n sameExpression(selected.node, expression.node),\n ),\n );\n\n if (repeatsText || ordersBySelected) {\n (compilation.expressionCaches ??= new Map()).set(bindings, []);\n }\n\n const aggregates = compilation.shapeOnly\n ? NO_SHARED_AGGREGATES\n : sharedAggregates(query);\n const shared = {\n inner: [] as { alias: string; query: SelectPlan }[],\n outer: [] as { alias: string; query: SelectPlan }[],\n };\n const lateral = (placement: \"inner\" | \"outer\") =>\n shared[placement].map(\n ({ alias, query: aggregate }) =>\n `LEFT JOIN LATERAL (${selectSql(compilation, aggregate, bindings)}) AS ${quoteIdentifier(alias)} ON TRUE`,\n );\n\n if (aggregates.inner.length || aggregates.outer.length) {\n const sharedReferences = new Map<ValueNode, string>();\n const occupied = new Set(\n Object.values(bindings).map(\n (binding) => compilation.aliasNames.get(binding) ?? binding.alias,\n ),\n );\n let position = 0;\n\n for (const placement of [\"inner\", \"outer\"] as const) {\n for (const group of aggregates[placement]) {\n let alias = `__symmetria_shared_${position++}`;\n\n while (occupied.has(alias)) {\n alias += \"_\";\n }\n\n occupied.add(alias);\n\n for (const [node, column] of group.references) {\n sharedReferences.set(\n node,\n `${quoteIdentifier(alias)}.${quoteIdentifier(column)}`,\n );\n }\n\n shared[placement].push({ alias, query: group.query });\n }\n }\n\n (compilation.aggregateReferences ??= new Map()).set(\n bindings,\n sharedReferences,\n );\n }\n\n const terminalJSON =\n jsonOutput &&\n !query.distinct &&\n !query.grouping.length &&\n !query.having.length &&\n !query.ordering.some(\n (ordering) =>\n ordering.expression.node.kind === \"jsonRows\" ||\n ordering.expression.node.kind === \"jsonObject\",\n );\n\n const projection = `SELECT ${query.distinct ? \"DISTINCT \" : \"\"}${projectionSql(compilation, query.selection, bindings, jsonValues, terminalJSON)}`;\n if (query.rootless) {\n return projection;\n }\n\n const source = `FROM ${tableSql(compilation, query.root, outerBindings)}`;\n const fragments: string[] = [];\n\n if (query.joins.length) {\n let joinedBindings: Bindings = mergeBindings(outerBindings, {\n [query.root.alias]: query.root,\n });\n\n for (const join of query.joins) {\n joinedBindings = mergeBindings(joinedBindings, {\n [join.binding.alias]: join.binding,\n });\n fragments.push(\n `${join.kind} JOIN ${tableSql(compilation, join.binding)}${join.condition ? ` ON ${predicateSql(compilation, join.condition, joinedBindings)}` : \"\"}`,\n );\n }\n }\n\n fragments.push(...lateral(\"inner\"));\n\n const relaxed = !compilation.shapeOnly && ordersThroughIvfflat(query);\n const nearest = compilation.shapeOnly\n ? undefined\n : nearestScanSql(query, relaxed);\n\n if (query.predicates.length || nearest) {\n fragments.push(\n `WHERE ${[...(nearest ? [nearest] : []), ...query.predicates.map((description) => predicateSql(compilation, description, bindings))].join(\" AND \")}`,\n );\n }\n\n if (query.grouping.length) {\n fragments.push(\n `GROUP BY ${query.grouping.map((expression) => valueSql(compilation, expression.node, bindings)).join(\", \")}`,\n );\n }\n\n if (query.having.length) {\n fragments.push(\n `HAVING ${query.having.map((description) => predicateSql(compilation, description, bindings)).join(\" AND \")}`,\n );\n }\n\n const orderBy = query.ordering.length\n ? `ORDER BY ${query.ordering.map((ordering) => orderingSql(compilation, ordering, bindings)).join(\", \")}`\n : undefined;\n const body = fragments.splice(0);\n\n if (orderBy) {\n fragments.push(orderBy);\n }\n\n const count = (value: number | ValueNode | undefined) =>\n value === undefined\n ? undefined\n : typeof value === \"number\"\n ? String(value)\n : valueSql(compilation, value, bindings);\n\n fragments.push(\n ...compilation.renderer.limitOffset(\n count(query.limit),\n count(query.offset),\n ),\n );\n\n if (query.locking) {\n // PostgreSQL cannot lock the nullable side of an outer join and refuses a\n // lock that names no tables there. A relation path adds such a JOIN by\n // itself (`post.editor.name`), so the lock then names the tables it can\n // reach: the root and the inner-joined ones.\n const outer = query.joins.some((join) => join.kind === \"LEFT\");\n const reachable =\n !query.locking.of &&\n outer &&\n query.joins.every((join) => join.kind !== \"RIGHT\" && join.kind !== \"FULL\")\n ? [\n query.root,\n ...query.joins\n .filter(\n (join) =>\n join.kind !== \"LEFT\" &&\n !join.binding.cte &&\n !join.binding.cteReference,\n )\n .map((join) => join.binding),\n ].map((binding) => aliasSql(compilation, binding))\n : undefined;\n const lock = compilation.renderer.rowLock({\n mode: query.locking.mode,\n of:\n reachable ??\n query.locking.of?.map((alias) =>\n aliasSql(compilation, query.bindings[alias]!),\n ),\n noWait: !!query.locking.noWait,\n skipLocked: !!query.locking.skipLocked,\n });\n\n fragments.push(lock);\n }\n\n if (aggregates.inner.length || !paginatesRootFirst(query)) {\n if (!nearest || !relaxed) {\n return [projection, source, ...body, ...fragments].join(\"\\n\");\n }\n\n // The ordering keys travel as extra columns. PostgreSQL trusts the inner\n // ORDER BY, so the first key is sorted as `key + 0`, an order it has to\n // establish itself.\n const keys = query.ordering.map(\n (ordering, position) =>\n `${valueSql(compilation, ordering.expression.node, bindings)} AS ${quoteIdentifier(`__symmetria_order_${position}`)}`,\n );\n const inner = [\n `${projection}, ${keys.join(\", \")}`,\n source,\n ...body,\n ...fragments,\n ].join(\"\\n\");\n\n return [\n `SELECT ${query.selection.map((expression) => quoteIdentifier(expression.outputName)).join(\", \")}`,\n `FROM (${inner}) AS \"__symmetria_nearest\"`,\n `ORDER BY ${query.ordering\n .map(\n (ordering, position) =>\n `${quoteIdentifier(`__symmetria_order_${position}`)}${position ? \"\" : \" + 0\"} ${ordering.direction}${ordering.nulls ? ` NULLS ${ordering.nulls}` : \"\"}`,\n )\n .join(\", \")}`,\n ].join(\"\\n\");\n }\n\n const carried = carriedColumns(query.root, aliasSql(compilation, query.root));\n const inner = [`SELECT ${carried}`, source, ...body, ...fragments].join(\"\\n\");\n\n return [\n projection,\n `FROM (${inner}) AS ${aliasSql(compilation, query.root)}`,\n ...lateral(\"outer\"),\n ...(orderBy ? [orderBy] : []),\n ].join(\"\\n\");\n};\n","/**\n * Renders INSERT, UPDATE and DELETE plans to SQL, including the scope checks\n * of a scoped database's writes.\n */\nimport { scopeViolationText } from \"../../driver/errors\";\nimport type { PredicateDescription, ValueNode } from \"../expressions\";\nimport { DEFAULT_VALUE, type MutationPlan } from \"../plan/types\";\nimport {\n aliasSql,\n parameter,\n quoteIdentifier,\n type Bindings,\n type Compilation,\n} from \"./state\";\nimport { projectionSql, valueSql } from \"./values\";\nimport { predicateSql } from \"./predicates\";\nimport { tableSql } from \"./select\";\nimport { unconstrained } from \"./postgres/render\";\n\n/**\n * TRUE (or the `passing` condition) when the row satisfies the scope;\n * otherwise casting the violation text to boolean fails and aborts the whole\n * statement, so nothing is written, and PostgreSQL's error\n * (`invalid input syntax for type boolean: \"SYMMETRIA_OUT_OF_SCOPE:insert:posts:16384\"`)\n * names the check and the table. The failing branch reads the row's tableoid,\n * which keeps PostgreSQL from evaluating it while planning, even when the\n * scope is a constant.\n */\nconst scopeCheckSql = (\n compilation: Compilation,\n query: MutationPlan,\n checks: readonly PredicateDescription[],\n failure: \"insert\" | \"update\" | \"conflict\",\n passing?: () => string,\n): string => {\n const scope = checks\n .map((description) =>\n predicateSql(compilation, description, query.bindings),\n )\n .join(\" AND \");\n const text = scopeViolationText(failure, query.root.table.name);\n\n return `CASE WHEN ${scope} THEN ${passing ? passing() : \"TRUE\"} ELSE ('${text.replaceAll(\"'\", \"''\")}' || ${aliasSql(compilation, query.root)}.tableoid)::boolean END`;\n};\n\n/** From this many rows on, a plain multi-row INSERT sends one array per column. */\nconst ARRAY_INSERT_THRESHOLD = 100;\n\n/** Text an array insert carries at most; UTF-8 and quoting can triple it on the wire. */\nconst ARRAY_INSERT_CHARACTERS = 128 * 1024 * 1024;\n\n/** Column types whose values bind as they are; the array is cast to the type without its length or scale, which assignment then applies. */\nconst ARRAY_TYPES =\n /^(smallint|integer|bigint|text|uuid|boolean|date|double precision|timestamptz|timestamp|numeric|varchar|character varying)(?:\\(\\d+(?:,\\s*\\d+)?\\))?$/;\n\n/**\n * The rows of a bulk INSERT as one array per column, when every row carries\n * the same columns as plain values of types PostgreSQL reads from an array\n * literal exactly as from a parameter. Anything else (a DEFAULT, an SQL\n * expression, a prepared parameter, an enum, an array column) keeps VALUES.\n */\nconst columnArrays = (\n query: MutationPlan,\n columns: readonly MutationPlan[\"root\"][\"table\"][\"columns\"][number][],\n): { values: unknown[]; type: string }[] | undefined => {\n if (query.values.length < ARRAY_INSERT_THRESHOLD) {\n return undefined;\n }\n\n const arrays: { values: unknown[]; type: string }[] = [];\n let characters = 0;\n\n for (const column of columns) {\n const values: unknown[] = [];\n let cast: string | undefined;\n let typed = false;\n\n for (const row of query.values) {\n const value = row[column.name];\n\n if (\n value === undefined ||\n value === DEFAULT_VALUE ||\n value.kind !== \"parameter\" ||\n Array.isArray(value.value)\n ) {\n return undefined;\n }\n\n // NULL is NULL under any cast; the other values must agree on theirs.\n if (value.value !== null) {\n if (typed && value.cast !== cast) {\n return undefined;\n }\n\n cast = value.cast;\n typed = true;\n }\n\n if (typeof value.value === \"string\") {\n characters += value.value.length;\n }\n\n values.push(value.value);\n }\n\n // One array is one protocol message, which PostgreSQL caps at 1 GB;\n // row by row the same values are sent in pieces.\n if (characters > ARRAY_INSERT_CHARACTERS) {\n return undefined;\n }\n\n if (cast) {\n // A value bound as `$1::text::jsonb` is an element of `text[]::jsonb[]`.\n if (cast.endsWith(\"]\")) {\n return undefined;\n }\n\n arrays.push({ values, type: `text[]::${unconstrained(cast)}[]` });\n continue;\n }\n\n const base = ARRAY_TYPES.exec(column.sqlType)?.[1];\n\n if (!base) {\n // These bind with a cast, which a column of nothing but NULL never shows.\n const empty = /^(jsonb|json|real|vector|halfvec)(?:\\(\\d+\\))?$/.exec(\n column.sqlType,\n )?.[1];\n\n if (!empty) {\n return undefined;\n }\n\n arrays.push({ values, type: `text[]::${empty}[]` });\n continue;\n }\n\n arrays.push({\n values,\n type: `${base === \"varchar\" || base === \"character varying\" ? \"text\" : base}[]`,\n });\n }\n\n return arrays;\n};\n\nexport const mutationSql = (\n compilation: Compilation,\n query: MutationPlan,\n): string => {\n // A data error found while building, such as a value a codec rejects.\n if (query.failure) {\n throw query.failure.error;\n }\n\n const fragments: string[] = [];\n\n const assignments = (\n values: Readonly<Record<string, ValueNode | typeof DEFAULT_VALUE>>,\n bindings = query.bindings,\n ): string =>\n Object.entries(values)\n .map(([name, value]) => {\n const column = query.root.table.columns.find(\n (candidate) => candidate.name === name,\n )!;\n\n return `${quoteIdentifier(column.sqlName)} = ${value === DEFAULT_VALUE ? \"DEFAULT\" : valueSql(compilation, value, bindings)}`;\n })\n .join(\", \");\n\n if (query.kind === \"insert\") {\n if (!query.values.length) {\n throw new Error(\n \"symmetria: insert([]) has no SQL; executing it is a no-op\",\n );\n }\n\n const names = query.root.table.columns.filter((column) =>\n query.values.some((values) => column.name in values),\n );\n\n fragments.push(`INSERT INTO ${tableSql(compilation, query.root)}`);\n\n if (!names.length && query.values.length === 1) {\n fragments.push(\"DEFAULT VALUES\");\n } else {\n const columns = names.length\n ? names\n : query.root.table.columns.slice(0, 1);\n\n if (!columns.length) {\n throw new Error(\n \"symmetria: cannot bulk insert into a table without columns\",\n );\n }\n\n const arrays = columnArrays(query, columns);\n\n fragments.push(\n arrays\n ? // One array per column: the statement's text and its parameter\n // count no longer grow with the number of rows.\n `(${columns.map((column) => quoteIdentifier(column.sqlName)).join(\", \")}) SELECT * FROM unnest(${arrays\n .map(\n ({ values, type }) =>\n `${parameter(compilation, values)}::${type}`,\n )\n .join(\", \")})`\n : `(${columns.map((column) => quoteIdentifier(column.sqlName)).join(\", \")}) VALUES ${query.values\n .map(\n (values) =>\n `(${columns\n .map((column) => {\n const value = values[column.name];\n\n return value === undefined || value === DEFAULT_VALUE\n ? \"DEFAULT\"\n : valueSql(compilation, value, query.bindings);\n })\n .join(\", \")})`,\n )\n .join(\", \")}`,\n );\n }\n\n if (query.conflict) {\n const target = query.conflict.columns.length\n ? ` (${query.conflict.columns.map((column) => quoteIdentifier(column.sqlName)).join(\", \")})`\n : \"\";\n\n if (query.conflict.action === \"nothing\") {\n fragments.push(`ON CONFLICT${target} DO NOTHING`);\n } else {\n const { condition } = query.conflict;\n const conflictBindings: Bindings = {\n ...query.bindings,\n ...(query.conflict.excluded\n ? { excluded: query.conflict.excluded }\n : {}),\n };\n\n fragments.push(\n `ON CONFLICT${target} DO UPDATE SET ${assignments(query.conflict.values, conflictBindings)}`,\n );\n\n // A conflict with a row outside the scope fails the statement; one\n // inside it whose condition is false is skipped, as without a scope.\n if (query.checks) {\n fragments.push(\n `WHERE ${scopeCheckSql(\n compilation,\n query,\n query.checks,\n \"conflict\",\n condition &&\n (() => predicateSql(compilation, condition, conflictBindings)),\n )}`,\n );\n } else if (condition) {\n fragments.push(\n `WHERE ${predicateSql(compilation, condition, conflictBindings)}`,\n );\n }\n }\n }\n } else {\n // A $scope() bounds the write but does not choose its rows: every row of\n // a tenant still takes all().\n if (\n !query.predicates.some((predicate) => predicate.kind !== \"scope\") &&\n !query.unrestricted\n ) {\n throw new Error(\n `symmetria: ${query.kind}() on \"${query.root.table.name}\" has no where(); call .all() to ${query.kind === \"update\" ? \"update\" : \"delete\"} every row`,\n );\n }\n\n fragments.push(\n query.kind === \"update\"\n ? `UPDATE ${tableSql(compilation, query.root)} SET ${assignments(query.values[0]!)}`\n : `DELETE FROM ${tableSql(compilation, query.root)}`,\n );\n }\n\n if (query.predicates.length) {\n fragments.push(\n `WHERE ${query.predicates.map((description) => predicateSql(compilation, description, query.bindings)).join(\" AND \")}`,\n );\n }\n\n // Every row the statement writes, with its final values, must satisfy the scope.\n const check = query.checks\n ? `${scopeCheckSql(compilation, query, query.checks, query.kind === \"update\" ? \"update\" : \"insert\")} AS \"__symmetria_scope\"`\n : undefined;\n\n if (query.selection.length) {\n fragments.push(\n `RETURNING ${projectionSql(compilation, query.selection, query.bindings, false, true)}${check ? `, ${check}` : \"\"}`,\n );\n } else if (check) {\n fragments.push(`RETURNING ${check}`);\n }\n\n return fragments.join(\"\\n\");\n};\n","import type { PredicateDescription, ValueNode } from \"../expressions\";\nimport {\n DEFAULT_VALUE,\n type MutationPlan,\n type SelectPlan,\n type TableBinding,\n} from \"../plan/types\";\nimport { quoteIdentifier, type Compilation } from \"./state\";\nimport { selectSql } from \"./select\";\nimport { childNodes } from \"../plan/traverse\";\n\n/**\n * Collects common table expressions before rendering, visiting the plan in the\n * order the renderer emits text, so `commonTables` keeps the dependency\n * post-order that WITH requires and every CTE body is rendered exactly once.\n */\nexport const collectCommonTables = (compilation: Compilation): void => {\n const { plan, commonTables, visiting, references } = compilation;\n // SQL names of the real tables the statement reads or writes.\n const tables = new Set<string>();\n\n const walkValue = (node: ValueNode): void => {\n if (\n node.kind === \"subquery\" ||\n node.kind === \"rowCount\" ||\n node.kind === \"jsonRows\"\n ) {\n walkSelect(node.query);\n\n return;\n }\n\n childNodes(node).forEach(walkValue);\n };\n\n const walkPredicate = (description: PredicateDescription): void => {\n switch (description.kind) {\n case \"group\":\n description.predicates.forEach(walkPredicate);\n\n return;\n case \"not\":\n case \"notTrue\":\n walkPredicate(description.predicate);\n\n return;\n case \"scope\":\n // A shape-only compilation renders a marker instead of the filter.\n if (compilation.shapeOnly) {\n return;\n }\n\n walkPredicate(\n compilation.scopeValues?.get(description) ?? description.predicate,\n );\n\n return;\n case \"nullCheck\":\n walkValue(description.value);\n\n return;\n case \"comparison\":\n walkValue(description.left);\n walkValue(description.right);\n\n return;\n case \"between\":\n walkValue(description.value);\n walkValue(description.lower);\n walkValue(description.upper);\n\n return;\n case \"has\":\n if (!description.json) {\n walkValue(description.element);\n walkValue(description.value);\n } else {\n walkValue(description.value);\n walkValue(description.element);\n }\n\n return;\n case \"search\":\n walkValue(description.value);\n walkValue(description.query);\n\n return;\n case \"exists\":\n walkSelect(description.query);\n\n return;\n case \"membership\":\n if (Array.isArray(description.values) && !description.values.length) {\n return;\n }\n\n walkValue(description.value);\n\n if (Array.isArray(description.values)) {\n description.values.forEach(walkValue);\n } else {\n walkSelect(description.values as SelectPlan);\n }\n\n return;\n }\n };\n\n const walkBinding = (binding: TableBinding): void => {\n if (binding.cteReference) {\n references.set(binding.cteReference.identity, binding.cteReference.name);\n } else if (!binding.derived) {\n tables.add(binding.table.sqlName);\n }\n\n if (binding.cte) {\n const definition = binding.cte;\n const existing = commonTables.get(definition.name);\n\n if (existing && existing.identity !== definition.identity) {\n throw new Error(`symmetria: duplicate CTE name \"${definition.name}\"`);\n }\n\n if (!existing) {\n if (visiting.has(definition.identity)) {\n throw new Error(\"symmetria: cyclic CTE dependency; use recursive()\");\n }\n\n visiting.add(definition.identity);\n walkSelect(definition.query);\n\n if (definition.recursive) {\n walkSelect(definition.recursive);\n }\n\n visiting.delete(definition.identity);\n commonTables.set(definition.name, definition);\n }\n }\n\n if (binding.derived) {\n walkSelect(binding.derived);\n }\n };\n\n const walkSelect = (query: SelectPlan): void => {\n if (!query.selection.length) {\n throw new Error(\n \"symmetria: select fields in a shape before compiling or executing a query\",\n );\n }\n\n query.selection.forEach((expression) => walkValue(expression.node));\n walkBinding(query.root);\n\n for (const join of query.joins) {\n walkBinding(join.binding);\n\n if (join.condition) {\n walkPredicate(join.condition);\n }\n }\n\n query.predicates.forEach(walkPredicate);\n query.grouping.forEach((expression) => walkValue(expression.node));\n query.having.forEach(walkPredicate);\n query.ordering.forEach((ordering) => walkValue(ordering.expression.node));\n };\n\n const walkMutation = (query: MutationPlan): void => {\n walkBinding(query.root);\n\n const walkAssignments = (\n values: Readonly<Record<string, ValueNode | typeof DEFAULT_VALUE>>,\n ) => {\n for (const value of Object.values(values)) {\n if (value !== DEFAULT_VALUE) {\n walkValue(value);\n }\n }\n };\n\n if (query.kind === \"insert\") {\n if (!query.atomicValues) {\n for (const column of query.root.table.columns) {\n for (const values of query.values) {\n const value = values[column.name];\n\n if (value !== undefined && value !== DEFAULT_VALUE) {\n walkValue(value);\n }\n }\n }\n }\n\n if (query.conflict?.action === \"update\") {\n walkAssignments(query.conflict.values);\n\n // The `doUpdate(values, { where })` condition, rendered after SET.\n if (query.conflict.condition) {\n walkPredicate(query.conflict.condition);\n }\n }\n } else if (query.kind === \"update\") {\n walkAssignments(query.values[0]!);\n }\n\n query.predicates.forEach(walkPredicate);\n query.checks?.forEach(walkPredicate);\n query.selection.forEach((expression) => walkValue(expression.node));\n };\n\n if (plan.kind === \"select\") {\n walkSelect(plan);\n } else {\n walkMutation(plan);\n }\n\n for (const [identity, name] of references) {\n if (commonTables.get(name)?.identity !== identity) {\n throw new Error(\n `symmetria: recursive reference \"${name}\" escaped its CTE`,\n );\n }\n }\n\n // WITH names shadow tables everywhere in the statement.\n for (const name of commonTables.keys()) {\n if (tables.has(name)) {\n throw new Error(\n `symmetria: CTE \"${name}\" has the SQL name of a table in this statement and would hide it; choose another CTE name`,\n );\n }\n }\n};\n\n/** Renders `WITH …` for the collected CTEs; their parameters are numbered first. */\nexport const withClause = (compilation: Compilation): string => {\n const definitions = [...compilation.commonTables.values()];\n const rendered = definitions.map((definition) => {\n const anchor = selectSql(compilation, definition.query, {});\n const body = definition.recursive\n ? compilation.renderer.recursiveUnion(\n anchor,\n selectSql(compilation, definition.recursive, {}),\n { unionAll: !!definition.unionAll },\n )\n : anchor;\n\n return `${quoteIdentifier(definition.name)} AS ${definition.materialized === undefined ? \"\" : definition.materialized ? \"MATERIALIZED \" : \"NOT MATERIALIZED \"}(${body})`;\n });\n\n return `WITH ${definitions.some((definition) => definition.recursive) ? \"RECURSIVE \" : \"\"}${rendered.join(\",\\n\")}\\n`;\n};\n","/**\n * SQL compiler entry: turns a query plan into a compiled query (SQL, parameters, decoder) and executes it on a driver.\n */\nimport { createRowDecoder, cloneParameter } from \"../codecs\";\nimport { throwDataErrors } from \"../codecs/deferred\";\nimport { executorProfiling } from \"../../observability/profiling\";\nimport { postgresRenderer } from \"./postgres/render\";\nimport { batchCollectors } from \"../plan/batching\";\nimport type {\n PlaceholderNode,\n PredicateDescription,\n ScopePredicate,\n} from \"../expressions\";\nimport {\n normalizeResult,\n type CompiledQuery,\n type ExecutionResult,\n type MutationPlan,\n type QueryExecutor,\n type SelectPlan,\n} from \"../plan/types\";\nimport { createCompilation, quoteIdentifier, type ScopeSlot } from \"./state\";\nimport { predicateSql } from \"./predicates\";\nimport { selectSql } from \"./select\";\nimport { mutationSql } from \"./mutations\";\nimport { collectCommonTables, withClause } from \"./cte\";\n\nexport { quoteIdentifier };\n\n/** A compiled plan and where its $scope() filters landed; never handed to callers. */\nexport type CompiledStatement = CompiledQuery & {\n readonly scopes: readonly ScopeSlot[] | undefined;\n};\n\ntype Placeholder = (node: PlaceholderNode) => unknown;\n\nconst compileStatement = (\n plan: SelectPlan | MutationPlan,\n placeholder?: Placeholder,\n scopeValues?: ReadonlyMap<ScopePredicate, PredicateDescription>,\n shapeOnly = false,\n): CompiledStatement => {\n const compilation = createCompilation(\n plan,\n postgresRenderer,\n placeholder,\n (query, outerBindings, jsonValues, jsonOutput) =>\n selectSql(compilation, query, outerBindings, jsonValues, jsonOutput),\n scopeValues,\n shapeOnly,\n );\n\n collectCommonTables(compilation);\n\n const prologue = compilation.commonTables.size ? withClause(compilation) : \"\";\n const statement = `${prologue}${\n compilation.plan.kind === \"select\"\n ? selectSql(compilation, compilation.plan, {}, false, true)\n : mutationSql(compilation, compilation.plan)\n }`;\n\n return {\n sql: statement,\n parameters: compilation.parameters,\n scopes: compilation.scopes,\n };\n};\n\n/** One $scope() result rendered where its slot sits, or undefined when it cannot be. */\nconst renderScope = (\n plan: SelectPlan | MutationPlan,\n slot: ScopeSlot,\n predicate: PredicateDescription,\n values: ReadonlyMap<ScopePredicate, PredicateDescription>,\n placeholder?: Placeholder,\n): CompiledQuery | undefined => {\n // The current values reach filters nested in this one, such as a scoped\n // query built earlier and used inside another $scope() callback.\n const compilation = createCompilation(\n plan,\n postgresRenderer,\n placeholder,\n (query, outerBindings, jsonValues, jsonOutput) =>\n selectSql(compilation, query, outerBindings, jsonValues, jsonOutput),\n values,\n );\n\n // Numbering continues from the slot, so equal SQL means equal parameter positions.\n compilation.parameters.length = slot.start;\n\n for (const [binding, alias] of slot.aliases) {\n compilation.aliasNames.set(binding, alias);\n }\n\n try {\n return {\n sql: predicateSql(compilation, predicate, slot.bindings),\n parameters: compilation.parameters.slice(slot.start),\n };\n } catch {\n // Such as a CTE inside the filter: the full recompilation below handles it.\n return undefined;\n }\n};\n\n/**\n * `$scope()` callbacks may read a changing value (the current tenant), so a\n * compiled or prepared statement never reuses their values from build time:\n * every execution runs each callback again and binds its current values in\n * place. When a callback now produces different SQL, such as a longer IN list,\n * the statement is compiled again with the current results.\n */\nexport const currentScopes = (\n plan: SelectPlan | MutationPlan,\n statement: CompiledStatement,\n parameters: unknown[],\n placeholder?: Placeholder,\n): CompiledQuery => {\n const values = new Map<ScopePredicate, PredicateDescription>();\n\n for (const slot of statement.scopes!) {\n const { description } = slot;\n\n if (!values.has(description)) {\n // A value the callback's codecs reject fails this execution.\n values.set(\n description,\n throwDataErrors(() => description.evaluate(description.binding)),\n );\n }\n }\n\n // Slots are recorded in rendering order; splice from the end so earlier\n // positions stay valid even if a nested filter is recorded before its parent.\n const slots = [...statement.scopes!].sort((a, b) => b.start - a.start);\n\n for (const slot of slots) {\n const rendered = renderScope(\n plan,\n slot,\n values.get(slot.description)!,\n values,\n placeholder,\n );\n\n if (!rendered || rendered.sql !== slot.sql) {\n const recompiled = compileStatement(plan, placeholder, values);\n\n return { sql: recompiled.sql, parameters: recompiled.parameters };\n }\n\n parameters.splice(\n slot.start,\n slot.end - slot.start,\n ...rendered.parameters,\n );\n }\n\n return { sql: statement.sql, parameters };\n};\n\n/** A plan compiled now, with the current values of its $scope() filters. */\nexport const compileQuery = (\n plan: SelectPlan | MutationPlan,\n placeholder?: Placeholder,\n): CompiledQuery => {\n const statement = compileStatement(plan, placeholder);\n\n return statement.scopes\n ? currentScopes(plan, statement, statement.parameters.slice(), placeholder)\n : { sql: statement.sql, parameters: statement.parameters };\n};\n\n/** A plan compiled once with placeholders; bind it with currentScopes() per execution. */\nexport const compileTemplate = (\n plan: SelectPlan | MutationPlan,\n placeholder: Placeholder,\n): CompiledStatement => compileStatement(plan, placeholder);\n\n/**\n * What a plan asks for, apart from its $scope() filters: the SQL with a marker\n * where each filter sits, and the parameters outside them. It is the same\n * whatever the callbacks return now or returned when the query was built, so\n * it can identify the query (a page cursor's fingerprint); it cannot run.\n */\nexport const compileShape = (\n plan: SelectPlan | MutationPlan,\n): CompiledQuery => {\n const statement = compileStatement(plan, undefined, undefined, true);\n\n return { sql: statement.sql, parameters: statement.parameters };\n};\n\ntype CachedCompilation = CompiledStatement & {\n /** Object-backed parameters must be re-cloned for every caller. */\n readonly objects: boolean;\n};\n\nconst compiledPlans = new WeakMap<\n SelectPlan | MutationPlan,\n CachedCompilation\n>();\n\n/**\n * Plans are frozen, so their SQL is compiled once; every call still receives a\n * detached parameters array, with $scope() values current at the call.\n */\nexport const compilePlan = (plan: SelectPlan | MutationPlan): CompiledQuery => {\n let cached = compiledPlans.get(plan);\n\n if (!cached) {\n const compiled = compileStatement(plan);\n\n cached = {\n ...compiled,\n objects: compiled.parameters.some(\n (value) => value !== null && typeof value === \"object\",\n ),\n };\n\n compiledPlans.set(plan, cached);\n }\n\n const parameters = cached.objects\n ? cached.parameters.map(cloneParameter)\n : cached.parameters.slice();\n\n return cached.scopes\n ? currentScopes(plan, cached, parameters)\n : { sql: cached.sql, parameters };\n};\n\n/** Compiles and runs a plan; a compilation error, such as a deferred data error, rejects. */\nexport const executePlan = (\n plan: SelectPlan | MutationPlan,\n executor?: QueryExecutor,\n): Promise<ExecutionResult> => {\n // Inside an open $batch(), a read waits for the batch's single statement.\n const batched =\n executor && plan.kind === \"select\"\n ? batchCollectors.get(executor)?.add(plan)\n : undefined;\n\n if (batched) {\n return batched;\n }\n\n const profile = executorProfiling(executor);\n const started = profile ? performance.now() : 0;\n let compiled: CompiledQuery;\n\n try {\n compiled = compilePlan(plan);\n } catch (error) {\n return Promise.reject(error);\n }\n\n return executeCompiled(\n plan,\n compiled,\n executor,\n profile ? performance.now() - started : 0,\n );\n};\n\nexport const executeCompiled = async (\n plan: SelectPlan | MutationPlan,\n compiled: CompiledQuery,\n executor?: QueryExecutor,\n compileMs = 0,\n): Promise<ExecutionResult> => {\n if (!executor) {\n throw new Error(\n \"symmetria: configure a query executor or driver before calling execute()\",\n );\n }\n\n const profile = executorProfiling(executor);\n let decodeMs = 0;\n\n try {\n const result = normalizeResult(await executor(compiled));\n const started = profile ? performance.now() : 0;\n const rows = result.rows.map(rowDecoder(plan));\n decodeMs = profile ? performance.now() - started : 0;\n\n return {\n rows,\n affectedRows: result.affectedRows,\n };\n } finally {\n profile?.annotate(compiled, { kind: plan.kind, compileMs, decodeMs });\n }\n};\n\nconst rowDecoders = new WeakMap<\n SelectPlan | MutationPlan,\n ReturnType<typeof createRowDecoder>\n>();\n\n/** The cached row decoder of a plan, shared by execute() and stream(). */\nexport const rowDecoder = (\n plan: SelectPlan | MutationPlan,\n): ReturnType<typeof createRowDecoder> => {\n let decode = rowDecoders.get(plan);\n\n if (!decode) {\n decode = createRowDecoder(plan.selection);\n rowDecoders.set(plan, decode);\n }\n\n return decode;\n};\n"],"mappings":";;;;;;;;;AAWA,MAAa,kCAAkB,IAAI,QAAuC;;;ACP1E,MAAM,iBAAiB,OAAgB,WAA6B;CAClE,IAAI,CAAC,kBAAkB,OAAO,MAAM,GAClC,OAAO;CAGT,IAAI,UAAU,QAAQ,OAAO,UAAU,UACrC,OAAO;CAIT,MAAM,kBAAkB,MAAc,UACpC,OAAO,UAAU,WAAW,OAAO,KAAK,IAAI;CAE9C,IAAI;EACF,OACE,KAAK,UAAU,OAAO,cAAc,MACpC,KAAK,UAAU,QAAQ,cAAc;CAEzC,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,MAAa,kBACX,MACA,OACA,aACY;CACZ,MAAM,cACJ,OACA,QACA,OACA,iBAAiB,aACL;EACZ,IAAI,UAAU,QACZ,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