@vantreeseba/drizzle-graphql 15.0.0 → 15.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +100 -66
- package/dist/index.cjs +112 -22
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -3
- package/dist/index.d.ts +19 -3
- package/dist/index.js +112 -22
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["GraphQLError","GraphQLScalarType","Kind","GraphQLEnumType","GraphQLObjectType","GraphQLFloat","GraphQLInputObjectType","is","PgDate","PgDateString","MySqlDate","MySqlDateString","MySqlTimestampString","MySqlDateTimeString","PgTimestampString","SQLiteTimestamp","PgTimestamp","MySqlTimestamp","MySqlDateTime","GraphQLList","GraphQLNonNull","extractExtendedColumnType","GraphQLBoolean","GraphQLDateTime","GraphQLInt","GraphQLJSON","PgUUID","GraphQLUUID","GraphQLString","PgInteger","PgSerial","MySqlInt","MySqlSerial","SQLiteInteger","GraphQLScalarType","getColumns","GraphQLJSON","GraphQLList","GraphQLNonNull","GraphQLUUID","GraphQLBoolean","GraphQLEnumType","GraphQLInt","GraphQLFloat","GraphQLInputObjectType","GraphQLString","GraphQLDateTime","extractExtendedColumnType","getColumns","is","One","notIlike","ilike","sql","and","arrayOverlaps","arrayContains","not","or","is","Column","getColumns","getColumns","GraphQLInputObjectType","GraphQLNonNull","getColumns","eq","and","getColumns","eq","and","aliasedTable","getTableAsAliasSQL","relationsFilterToSQL","not","is","One","or","GraphQLEnumType","getColumns","extractExtendedColumnType","isNotNull","isNull","eq","ne","or","is","SQL","and","GraphQLInt","GraphQLString","GraphQLList","GraphQLNonNull","GraphQLEnumType","GraphQLEnumType","GraphQLList","GraphQLNonNull","GraphQLInputObjectType","getColumns","sql","asc","desc","is","One","aliasedTable","relationsFilterToSQL","getTableAsAliasSQL","sql","getColumns","and","getColumns","isNotNull","gt","lt","or","isNull","and","eq","getColumns","asc","getColumns","sql","asc","eq","inArray","or","and","GraphQLNonNull","GraphQLEnumType","GraphQLInputObjectType","GraphQLNonNull","GraphQLInt","GraphQLBoolean","Kind","getArgumentValues","GraphQLInt","GraphQLFloat","GraphQLList","GraphQLInputObjectType","GraphQLNonNull","getColumns","sql","getColumns","is","One","and","inArray","sql","GraphQLBoolean","GraphQLInputObjectType","GraphQLNonNull","getColumns","getColumns","sql","gt","lte","and","inArray","GraphQLString","is","One","GraphQLInputObjectType","GraphQLList","GraphQLNonNull","GraphQLObjectType","is","One","GraphQLNonNull","GraphQLList","GraphQLInt","GraphQLString","GraphQLInputObjectType","is","Table","getColumns","count","GraphQLList","GraphQLObjectType","extractExtendedColumnType","GraphQLNonNull","GraphQLInt","GraphQLFloat","getColumns","and","inArray","GraphQLInputObjectType","getColumns","is","One","GraphQLInputObjectType","GraphQLList","GraphQLNonNull","GraphQLBoolean","eq","and","inArray","is","GraphQLNonNull","GraphQLList","One","GraphQLNonNull","GraphQLList","generateUpdateMany","getTableConfig","mysqlTableConfig","MySqlTable","generateSchemaData","GraphQLObjectType","GraphQLBoolean","GraphQLInt","GraphQLNonNull","GraphQLList","GraphQLNonNull","GraphQLList","GraphQLInt","GraphQLNonNull","GraphQLList","getTableConfig","pgTableConfig","generateUpdateMany","PgTable","generateSchemaData","sqliteTableConfig","SQLiteTable","mysqlTableConfig","pgTableConfig","sqliteTableConfig","is","MySqlAsyncDatabase","PgAsyncDatabase","SQLiteAsyncDatabase","Table","is","MySqlAsyncDatabase","generateMySQL","PgAsyncDatabase","generatePG","SQLiteAsyncDatabase","generateSQLite","GraphQLObjectType","GraphQLSchema"],"sources":["../src/util/builders/common/errors.ts","../src/util/scalars/index.ts","../src/util/case-ops/index.ts","../src/util/type-converter/index.ts","../src/util/builders/common/type-names.ts","../src/util/builders/common/column-filters.ts","../src/util/data-mappers/index.ts","../src/util/builders/common/filters.ts","../src/util/builders/common/relations.ts","../src/util/builders/common/exclusions.ts","../src/util/builders/common/naming.ts","../src/util/builders/common/unique-keys.ts","../src/util/builders/common/relation-filters.ts","../src/util/builders/common/policies.ts","../src/util/builders/common/args.ts","../src/util/builders/common/column-enums.ts","../src/util/builders/common/conflict.ts","../src/util/builders/common/order-by.ts","../src/util/builders/common/cursor.ts","../src/util/builders/common/keys.ts","../src/util/builders/common/distinct.ts","../src/util/builders/common/docs.ts","../src/util/builders/common/executor.ts","../src/util/builders/common/input-order.ts","../src/util/builders/common/limits.ts","../src/util/parse-resolve-info.ts","../src/util/builders/field-updates.ts","../src/util/builders/common/rqb-config.ts","../src/util/builders/common/selected-columns.ts","../src/util/builders/common/relation-params.ts","../src/util/builders/common/select-runtime.ts","../src/util/builders/common/transactions.ts","../src/util/builders/common/write-hooks.ts","../src/util/builders/common/write-scaffold.ts","../src/util/builders/common/mutation-helpers.ts","../src/util/batch-loader/index.ts","../src/util/extensions.ts","../src/util/builders/common/relation-resolvers.ts","../src/util/builders/common/resolver-names.ts","../src/util/builders/common/root-fields.ts","../src/util/builders/common/table-inputs.ts","../src/util/builders/common/table-types.ts","../src/util/features.ts","../src/util/build-config.ts","../src/util/builders/aggregates.ts","../src/util/builders/nested-writes.ts","../src/util/builders/errors.ts","../src/util/builders/select.ts","../src/util/builders/build-context.ts","../src/util/builders/mysql.ts","../src/util/builders/write-resolvers.ts","../src/util/builders/schema-data.ts","../src/util/builders/update-many.ts","../src/util/builders/pg.ts","../src/util/builders/sqlite.ts","../src/util/selection.ts","../src/index.ts"],"sourcesContent":["// The `onError` boundary: what a resolver's throw is turned into, the default mapper, and the\n// plumbing that lets a caller replace it.\n\nimport { type ASTNode, GraphQLError } from 'graphql';\nimport type { DrizzleFieldOperation } from '../../extensions.ts';\n\n/**\n * The classification of an error drizzle-graphql raised itself, published as\n * `extensions.code`. A consumer maps these onto its own vocabulary; the prose is written for\n * a client to read and may be reworded in any release, so it is not something to match on.\n */\nexport type DrizzleErrorCode =\n /** A `Single` write's `where` matched more than one row, so nothing was written. */\n | 'DRIZZLE_MULTI_ROW_MATCH'\n /** A write that refuses to run unbounded was given no `where`, or one matching every row. */\n | 'DRIZZLE_WHERE_REQUIRED'\n /** The requested `limit` is above the maximum the field's limit policy allows. */\n | 'DRIZZLE_LIMIT_EXCEEDED'\n /** A write's `values` / `set` carried nothing to write. */\n | 'DRIZZLE_NO_VALUES'\n /** An insert reported no row back, so there is nothing to return or attach. */\n | 'DRIZZLE_NO_ROW_RETURNED'\n /** The driver reported no row count for a returnless write. */\n | 'DRIZZLE_ROW_COUNT_UNAVAILABLE'\n /** A nested write was passed to a field that cannot run one. */\n | 'DRIZZLE_NESTED_WRITES_UNSUPPORTED'\n /** A nested `create` / `connect` / `disconnect` / `set` operand was not usable. */\n | 'DRIZZLE_NESTED_WRITE_INVALID'\n /** A `groupBy` named no column, or one that cannot be grouped by. */\n | 'DRIZZLE_INVALID_GROUP_BY'\n /** An `after` cursor did not decode, or was issued for a different ordering. */\n | 'DRIZZLE_INVALID_CURSOR'\n /** A `where` key was not a filter of the table, or a relation was used as one. */\n | 'DRIZZLE_INVALID_FILTER'\n /** A column's update operations input held none, or more than one. */\n | 'DRIZZLE_INVALID_UPDATE_OPERATION'\n /** A configured `scope` hook returned something that is not a predicate. */\n | 'DRIZZLE_INVALID_SCOPE'\n /** An `orderBy` named something that cannot be ordered by in this query. */\n | 'DRIZZLE_INVALID_ORDER_BY'\n /** `distinct` was asked for where it cannot be applied. */\n | 'DRIZZLE_INVALID_DISTINCT'\n /** An `onConflict` named a target or update column the upsert cannot use. */\n | 'DRIZZLE_INVALID_ON_CONFLICT'\n /** A written value could not be converted to what its column stores. */\n | 'DRIZZLE_INVALID_INPUT_VALUE'\n /** An update's `set` gave a column that cannot hold null an explicit null. */\n | 'DRIZZLE_NOT_NULL'\n /** A write's input named a key that is not a column of the table. */\n | 'DRIZZLE_UNKNOWN_COLUMN'\n /** A stored value could not be represented by the scalar that transports it. */\n | 'DRIZZLE_UNREPRESENTABLE_VALUE'\n /** The request's shared mutation transaction was rolled back, so this field never ran. */\n | 'DRIZZLE_TRANSACTION_ABORTED';\n\n/**\n * What an error was about, published as `extensions.drizzle` beside the code — the runtime\n * half of the `extensions.drizzle` markers a generated field carries.\n *\n * `field` is the **generated** field name, which is why it is data rather than prose: a build\n * that republishes these fields under other names (`RenameRootFields`, a stitched gateway, a\n * hand-written façade) would otherwise be telling a client about a field it has never heard\n * of. The name the client asked for is already in the error's `path`.\n */\nexport type DrizzleErrorContext = {\n /** The Drizzle schema key of the table the field reads or writes. */\n table?: string;\n operation?: DrizzleFieldOperation;\n /** The generated field's own name, pre-rename. */\n field?: string;\n /** For a relation field: the relation's name. */\n relation?: string;\n};\n\n/**\n * A `GraphQLError` carrying its context as data. The message says what went wrong, in prose\n * meant for a client; `extensions.code` classifies it and `extensions.drizzle` says which\n * table, operation and generated field it came from.\n */\nexport const drizzleError = (\n message: string,\n {\n code,\n nodes,\n ...context\n }: DrizzleErrorContext & {\n code: DrizzleErrorCode;\n /** The AST the error is about, where the throw site has one — it becomes the `locations`. */\n nodes?: ASTNode | readonly ASTNode[];\n },\n): GraphQLError =>\n new GraphQLError(message, {\n nodes,\n extensions: Object.keys(context).length ? { code, drizzle: context } : { code },\n });\n\n/**\n * Attaches `extensions.drizzle` to one of this library's own errors on its way out of a\n * resolver, so that the deep helpers — filter compilation, ordering, cursors, conflict\n * planning — can raise a coded error without every one of them being handed the field it was\n * called from. Anything else (a driver error, a `GraphQLError` a hook raised) passes through\n * untouched, and context a throw site already supplied wins over the field's.\n */\nexport const withErrorContext = (error: unknown, context: DrizzleErrorContext): unknown => {\n if (!(error instanceof GraphQLError)) {\n return error;\n }\n const { code, drizzle } = (error.extensions ?? {}) as { code?: unknown; drizzle?: DrizzleErrorContext };\n if (typeof code !== 'string' || !code.startsWith('DRIZZLE_')) {\n return error;\n }\n return new GraphQLError(error.message, {\n nodes: error.nodes,\n source: error.source,\n positions: error.positions,\n path: error.path,\n originalError: error.originalError,\n extensions: { ...error.extensions, drizzle: { ...context, ...drizzle } },\n });\n};\n\n/**\n * Normalizes whatever a driver threw into a `GraphQLError`. Errors drizzle-graphql raised\n * itself pass straight through; anything else keeps the thrown value on `originalError`,\n * which is how {@link defaultErrorMapper} later tells the two apart.\n */\nexport const toGraphQLError = (e: unknown): unknown => {\n if (e instanceof GraphQLError) {\n return e;\n }\n return e instanceof Error ? new GraphQLError(e.message, { originalError: e }) : e;\n};\n\n/**\n * Default for `config.onError`: keeps drizzle-graphql's own errors, which are written for\n * the client, and replaces driver/database errors with a generic message. Their text names\n * tables, columns, constraints and offending values, none of which belongs in a response.\n * The original is preserved on `originalError` for server-side logging.\n */\nexport const defaultErrorMapper = (error: unknown): unknown => {\n if (error instanceof GraphQLError && !error.originalError) {\n return error;\n }\n\n return new GraphQLError('Internal server error', {\n originalError:\n error instanceof GraphQLError ? (error.originalError ?? error) : error instanceof Error ? error : null,\n extensions: { code: 'INTERNAL_SERVER_ERROR' },\n });\n};\n\n/**\n * Wraps every resolver reachable from a generated entity set so that its errors pass through\n * `mapError` first. Done here rather than at each `throw` site so that the hook also covers\n * relation field resolvers and anything that throws outside a builder's own try/catch.\n */\nexport const applyErrorMapper = (\n entities: {\n queries: Record<string, { resolve?: (...args: any[]) => any }>;\n mutations: Record<string, { resolve?: (...args: any[]) => any }>;\n types: Record<string, { getFields?: () => Record<string, { resolve?: (...args: any[]) => any }> }>;\n fieldResolvers?: Record<string, Record<string, (...args: any[]) => any>>;\n },\n mapError: (error: unknown) => unknown,\n): void => {\n const wrap =\n (resolve: (...args: any[]) => any) =>\n (...args: any[]) => {\n try {\n const result = resolve(...args);\n if (result && typeof result.then === 'function') {\n return result.then(undefined, (e: unknown) => {\n throw mapError(e);\n });\n }\n return result;\n } catch (e) {\n throw mapError(e);\n }\n };\n\n for (const field of [...Object.values(entities.queries), ...Object.values(entities.mutations)]) {\n if (field?.resolve) {\n field.resolve = wrap(field.resolve);\n }\n }\n\n // Relation and aggregate fields live on the object types, not in the query/mutation maps.\n for (const type of Object.values(entities.types)) {\n if (typeof type?.getFields !== 'function') {\n continue;\n }\n for (const field of Object.values(type.getFields())) {\n if (field?.resolve) {\n field.resolve = wrap(field.resolve);\n }\n }\n }\n\n // Standalone relation resolvers, handed out for use in hand-written schemas.\n for (const tableResolvers of Object.values(entities.fieldResolvers ?? {})) {\n for (const [relationName, resolve] of Object.entries(tableResolvers)) {\n tableResolvers[relationName] = wrap(resolve);\n }\n }\n};\n","import { GraphQLScalarType, Kind } from 'graphql';\nimport { GraphQLDateTime, GraphQLJSON, GraphQLUUID } from 'graphql-scalars';\nimport { type DrizzleErrorCode, drizzleError } from '../builders/common/errors.ts';\n\n// Both scalars below coerce the same way in both directions, so each helper is built once per\n// direction with the code that direction reports: a rejected argument is the client's value to\n// fix, while a rejected column value is the stored data's. graphql-js wraps a `parseValue`\n// throw when it coerces variables, but the wrapper inherits the original's `extensions`, so\n// the code survives that trip.\nconst INVALID_INPUT: DrizzleErrorCode = 'DRIZZLE_INVALID_INPUT_VALUE';\nconst UNREPRESENTABLE: DrizzleErrorCode = 'DRIZZLE_UNREPRESENTABLE_VALUE';\n\nconst decimalString =\n (code: DrizzleErrorCode) =>\n (value: unknown): string => {\n if (typeof value === 'bigint') {\n return value.toString();\n }\n\n if (typeof value === 'number') {\n if (!Number.isInteger(value)) {\n throw drizzleError(`BigInt cannot represent non-integer value: ${value}`, { code });\n }\n if (!Number.isSafeInteger(value)) {\n throw drizzleError(\n `BigInt cannot represent the number ${value} without precision loss — pass it as a string instead`,\n { code },\n );\n }\n return String(value);\n }\n\n if (typeof value === 'string') {\n if (!/^-?\\d+$/.test(value)) {\n throw drizzleError(`BigInt cannot represent non-integer value: \"${value}\"`, { code });\n }\n return value;\n }\n\n throw drizzleError(`BigInt cannot represent value: ${JSON.stringify(value)}`, { code });\n };\n\nconst parseDecimal = decimalString(INVALID_INPUT);\n\n/**\n * A 64-bit integer. Always transported as a decimal string, in both directions, so no value\n * is ever silently rounded by JSON's double-precision numbers. `graphql-scalars`' own\n * `GraphQLBigInt` is deliberately not used: it emits numbers for safe integers and strings\n * for everything else, so a client cannot know which it will get.\n */\nexport const GraphQLBigIntString = new GraphQLScalarType<string, string>({\n name: 'BigInt',\n description:\n 'A 64-bit integer, transported as a decimal string so that values beyond ' +\n \"JavaScript's safe integer range survive the round-trip intact.\",\n serialize: decimalString(UNREPRESENTABLE),\n parseValue: parseDecimal,\n parseLiteral: (ast) => {\n if (ast.kind !== Kind.STRING && ast.kind !== Kind.INT) {\n throw drizzleError(`BigInt cannot represent a ${ast.kind}`, { code: INVALID_INPUT, nodes: ast });\n }\n return parseDecimal(ast.value);\n },\n});\n\n// Optional sign, digits with an optional fractional part (or a bare fractional part),\n// and an optional exponent. Deliberately excludes 'NaN', 'Infinity', and empty strings,\n// even though some databases would accept them.\nconst numericStringPattern = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$/;\n\nconst numericString =\n (code: DrizzleErrorCode) =>\n (value: unknown): string => {\n if (typeof value === 'bigint') {\n return value.toString();\n }\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw drizzleError(`Decimal cannot represent non-finite value: ${value}`, { code });\n }\n return String(value);\n }\n\n if (typeof value === 'string') {\n if (!numericStringPattern.test(value)) {\n throw drizzleError(`Decimal cannot represent non-numeric value: \"${value}\"`, { code });\n }\n return value;\n }\n\n throw drizzleError(`Decimal cannot represent value: ${JSON.stringify(value)}`, { code });\n };\n\nconst parseNumeric = numericString(INVALID_INPUT);\n\n/**\n * An arbitrary-precision decimal (`numeric` / `decimal` columns). Always transported as a\n * numeric string, in both directions, so no value is ever silently rounded by JSON's\n * double-precision numbers. Accepts numeric literals and numeric strings on input; rejects\n * non-numeric strings (including 'NaN' and 'Infinity').\n */\nexport const GraphQLDecimalString = new GraphQLScalarType<string, string>({\n name: 'Decimal',\n description:\n 'An arbitrary-precision decimal, transported as a numeric string so that values ' +\n \"beyond JavaScript's double-precision range survive the round-trip intact.\",\n serialize: numericString(UNREPRESENTABLE),\n parseValue: parseNumeric,\n parseLiteral: (ast) => {\n if (ast.kind !== Kind.STRING && ast.kind !== Kind.INT && ast.kind !== Kind.FLOAT) {\n throw drizzleError(`Decimal cannot represent a ${ast.kind}`, { code: INVALID_INPUT, nodes: ast });\n }\n return parseNumeric(ast.value);\n },\n});\n\n// RFC 3339 `full-date`: four-digit year, two-digit month and day, nothing else — no time, no\n// offset. The shape alone admits `2026-13-45`, so `isCalendarDate` checks the ranges too.\nconst fullDatePattern = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\nconst daysInMonth = (year: number, month: number): number => {\n if (month === 2) {\n const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n return leap ? 29 : 28;\n }\n return [4, 6, 9, 11].includes(month) ? 30 : 31;\n};\n\n/** Whether `value` is a `YYYY-MM-DD` string naming a day that exists on the calendar. */\nexport const isCalendarDate = (value: string): boolean => {\n const match = fullDatePattern.exec(value);\n if (!match) {\n return false;\n }\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n return month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth(year, month);\n};\n\n/**\n * A JS `Date` as the calendar day it stands for. Read in UTC, because that is how drivers\n * build one from a `date` column: `new Date('2026-09-15')` is UTC midnight, so the local\n * getters would name the previous day anywhere west of Greenwich.\n */\nexport const dateToCalendarDate = (value: Date): string | undefined => {\n if (Number.isNaN(value.getTime())) {\n return undefined;\n }\n const year = value.getUTCFullYear();\n if (year < 0 || year > 9999) {\n return undefined;\n }\n const month = String(value.getUTCMonth() + 1).padStart(2, '0');\n const day = String(value.getUTCDate()).padStart(2, '0');\n return `${String(year).padStart(4, '0')}-${month}-${day}`;\n};\n\nconst calendarDate =\n (code: DrizzleErrorCode, acceptDate: boolean) =>\n (value: unknown): string => {\n if (typeof value === 'string') {\n if (!isCalendarDate(value)) {\n throw drizzleError(`Date cannot represent \"${value}\": expected a calendar date as YYYY-MM-DD`, { code });\n }\n return value;\n }\n\n if (acceptDate && value instanceof Date) {\n const formatted = dateToCalendarDate(value);\n if (formatted === undefined) {\n throw drizzleError('Date cannot represent an invalid or out-of-range Date', { code });\n }\n return formatted;\n }\n\n throw drizzleError(`Date cannot represent value: ${JSON.stringify(value)}: expected a YYYY-MM-DD string`, {\n code,\n });\n };\n\nconst parseCalendarDate = calendarDate(INVALID_INPUT, false);\n\n/**\n * A calendar day — `date` columns, whichever `mode` drizzle reads them in. Always transported\n * as an RFC 3339 `full-date` string (`YYYY-MM-DD`), in both directions: it has no time and no\n * offset, so there is nothing for a client's timezone to shift. `graphql-scalars`' own\n * `GraphQLDate` is deliberately not used: its `parseValue` returns a JS `Date`, so the same\n * scalar would be a string on the way out and an instant on the way in.\n *\n * Input accepts only a `YYYY-MM-DD` string naming a real day (`2026-02-30` and datetime\n * strings are rejected) and hands it on unchanged. Output also accepts a JS `Date`, read as\n * the UTC day it encodes.\n */\nexport const GraphQLDate = new GraphQLScalarType<string, string>({\n name: 'Date',\n description: 'A calendar date with no time or offset, transported as an RFC 3339 full-date string (YYYY-MM-DD).',\n specifiedByURL: 'https://datatracker.ietf.org/doc/html/rfc3339#section-5.6',\n serialize: calendarDate(UNREPRESENTABLE, true),\n parseValue: parseCalendarDate,\n parseLiteral: (ast) => {\n if (ast.kind !== Kind.STRING) {\n throw drizzleError(`Date cannot represent a ${ast.kind}`, { code: INVALID_INPUT, nodes: ast });\n }\n return parseCalendarDate(ast.value);\n },\n});\n\nexport { GraphQLDateTime, GraphQLJSON, GraphQLUUID };\n","import pluralize from 'pluralize';\n\nexport const uncapitalize = <T extends string>(input: T) =>\n (input?.length\n ? `${input[0]!.toLocaleLowerCase()}${input.length > 1 ? input.slice(1, input.length) : ''}`\n : input) as Uncapitalize<T>;\n\nexport const capitalize = <T extends string>(input: T) =>\n (input?.length\n ? `${input[0]!.toLocaleUpperCase()}${input.length > 1 ? input.slice(1, input.length) : ''}`\n : input) as Capitalize<T>;\n\nexport const singularize = <T extends string>(input: T) => pluralize.singular(input);\n\nexport const cleanTableName = <T extends string>(input: T) => singularize(uncapitalize(input));\n\nexport const tableNameToModel = <T extends string>(input: T) => singularize(capitalize(input));\n\n// (input.length\n// ? `${input[-]!.toLocaleUpperCase()}${input.length > 1 ? input.slice(1, input.length) : \"\"}`\n// : input) as Capitalize<T>;\n\n/**\n * `inProgress` / `in-progress` / `in progress` / `InProgress` → `IN_PROGRESS`; `HTTPError` →\n * `HTTP_ERROR`. Words are split at non-alphanumeric runs and at lower→upper and\n * acronym→word boundaries, then upper-cased and joined with `_`.\n *\n * The preset behind `enumValueNameMapper: 'constant'`.\n */\nexport const constantCase = (input: string): string =>\n input\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean)\n .map((part) => part.toUpperCase())\n .join('_');\n\n/**\n * The `typeNameMapper` preset behind `typeNameMapper: 'singularize'`.\n *\n * Derives the singular and plural forms of a table key with the library's own `pluralize`,\n * which is what nearly every consumer with plural table keys (`export const tasks =\n * pgTable('tasks', …)`) was writing by hand — and adding `pluralize` to their own\n * dependencies to write.\n *\n * `tasks` becomes type `Task`, queries `tasks` / `task`, mutations `createTasks` /\n * `createTask`. A key that is already singular is pluralized for the list side, so `task`\n * yields the same names, and a capitalized key (`Tasks`) yields them too — the field forms\n * are uncapitalized so the generated names follow GraphQL's camelCase convention whatever\n * the schema key looks like. The type name is capitalized by the generator either way.\n */\nexport const singularizeMapper = (tableName: string): { singular: string; plural: string } => ({\n singular: uncapitalize(pluralize.singular(tableName)),\n plural: uncapitalize(pluralize.plural(tableName)),\n});\n","import type { Column, Table } from 'drizzle-orm';\nimport { extractExtendedColumnType, getColumns, is } from 'drizzle-orm';\nimport {\n MySqlDate,\n MySqlDateString,\n MySqlDateTime,\n MySqlDateTimeString,\n MySqlInt,\n MySqlSerial,\n MySqlTimestamp,\n MySqlTimestampString,\n} from 'drizzle-orm/mysql-core';\nimport { PgDate, PgDateString, PgInteger, PgSerial, PgTimestamp, PgTimestampString, PgUUID } from 'drizzle-orm/pg-core';\nimport { SQLiteInteger, SQLiteTimestamp } from 'drizzle-orm/sqlite-core';\nimport {\n GraphQLBoolean,\n GraphQLEnumType,\n GraphQLFloat,\n GraphQLInputObjectType,\n type GraphQLInputType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n type GraphQLOutputType,\n GraphQLScalarType,\n GraphQLString,\n} from 'graphql';\nimport { capitalize, constantCase } from '../case-ops/index.ts';\nimport {\n GraphQLBigIntString,\n GraphQLDate,\n GraphQLDateTime,\n GraphQLDecimalString,\n GraphQLJSON,\n GraphQLUUID,\n} from '../scalars/index.ts';\nimport type {\n ColumnTypeMapper,\n ConvertedColumn,\n EnumNameMapper,\n EnumValueNameMapper,\n NullableConvertedColumnType,\n ScalarOverride,\n ScalarOverridesConfig,\n} from './types.ts';\n\nconst allowedNameChars = /^[a-zA-Z0-9_]+$/;\n\n/** drizzle's `number` constraints whose values always fit a GraphQL `Int` (32-bit signed). */\nconst smallIntegerConstraints = new Set<string>([\n 'int8',\n 'uint8',\n 'int16',\n 'uint16',\n 'int24',\n 'uint24',\n 'int32',\n 'year',\n]);\n\n/** A GraphQL `Name` that is also allowed as an enum value — the spec reserves the three literals. */\nconst validEnumValueName = (name: string): boolean =>\n /^[_a-zA-Z][_a-zA-Z0-9]*$/.test(name) && name !== 'true' && name !== 'false' && name !== 'null';\n\n/**\n * The enum type a column was declared with, when it is a *named* one — `pgEnum('status', …)`\n * shared by however many tables reference it. An inline value list (`text({ enum: [...] })`,\n * `mysqlEnum('role', [...])`) has no such object: the values belong to that one column.\n */\nconst declaredEnum = (column: Column): { enumName: string; schema: string | undefined } | undefined => {\n const declared = (column as any).enum as { enumName?: unknown; schema?: unknown } | undefined;\n return typeof declared?.enumName === 'string'\n ? { enumName: declared.enumName, schema: typeof declared.schema === 'string' ? declared.schema : undefined }\n : undefined;\n};\n\n/** `user_status` / `user-status` / `user status` → `UserStatus`; an already-PascalCase name is left alone. */\nconst pascalize = (input: string): string =>\n input\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean)\n .map((part) => capitalize(part))\n .join('');\n\n/**\n * Identity of the values a GraphQL enum was built from, so a name claimed twice can be told\n * apart from the same enum reached twice.\n */\nconst enumValuesKey = (values: readonly string[]): string => JSON.stringify(values);\n\n/**\n * Identity of the GraphQL names those values were given. Kept apart from {@link enumValuesKey}\n * because `enumValueNameMapper` sees the column, so two columns reaching one type can name its\n * values differently — and only one set of names can win.\n */\nconst enumValueNamesKey = (names: readonly string[]): string => JSON.stringify(names);\n\n/**\n * Every GraphQL enum name this build has handed out. Two columns that resolve to the same\n * name share one type — that is how the columns of one `pgEnum` end up on a single type —\n * so the values are kept alongside it to tell a genuine collision from a re-use.\n */\nlet enumNamesInUse = new Map<string, { type: GraphQLEnumType; valuesKey: string; namesKey: string }>();\nlet enumNameMapper: EnumNameMapper | undefined;\nlet enumValueNameMapper: EnumValueNameMapper | undefined;\n\n/** The value-name presets, by the string a config passes for them. */\nconst enumValueNamePresets: Record<string, EnumValueNameMapper> = {\n constant: ({ value }) => constantCase(value),\n};\n\n/**\n * Resets the enum registry for a fresh schema build and installs that build's\n * `enumNameMapper` and `enumValueNameMapper`. Called once per `generateSchemaData`, alongside\n * {@link registerScalarOverrides} — without the reset a second build would reuse the first\n * build's enum types, and so its naming decisions.\n */\nexport const registerEnumConfig = (config: {\n enumNameMapper?: EnumNameMapper;\n enumValueNameMapper?: 'constant' | EnumValueNameMapper;\n}): void => {\n enumNameMapper = config.enumNameMapper;\n const valueMapper = config.enumValueNameMapper;\n if (typeof valueMapper === 'string') {\n const preset = enumValueNamePresets[valueMapper];\n if (!preset) {\n throw new Error(\n `Drizzle-GraphQL Error: Unknown enumValueNameMapper preset '${valueMapper}'. The only preset is 'constant'; pass a function for anything else.`,\n );\n }\n enumValueNameMapper = preset;\n } else {\n enumValueNameMapper = valueMapper;\n }\n enumNamesInUse = new Map();\n};\n\n/**\n * The GraphQL enum for a column's value list.\n *\n * The name decides the sharing: a column declared with a named `pgEnum` is named for the\n * enum, so every column declared with that same `pgEnum` lands on one GraphQL type — the\n * database column is literally the same type, and a client variable typed `StatusEnum!`\n * should be passable to any of them. A column with an inline value list is named for the\n * table and column instead, and so keeps a type of its own; its values are not shared with\n * anything.\n *\n * `enumNameMapper` is consulted for every column and overrides that name either way, which\n * makes it both the way to unify inline enums that were declared separately but mean the\n * same thing, and the way to split apart columns of one `pgEnum` that should not share.\n * Sending two *different* value lists to one name is a build-time error rather than an\n * invalid schema.\n */\nconst generateEnumCached = (column: Column, columnName: string, tableName: string): GraphQLEnumType => {\n const declared = declaredEnum(column);\n const values = column.enumValues!;\n const name =\n enumNameMapper?.({\n enumName: declared?.enumName,\n schema: declared?.schema,\n tableName,\n columnName,\n values,\n }) ?? (declared ? `${pascalize(declared.enumName)}Enum` : `${capitalize(tableName)}${capitalize(columnName)}Enum`);\n\n const valueNames = values.map((value, index) => {\n const mapped = enumValueNameMapper?.({\n enumName: declared?.enumName,\n schema: declared?.schema,\n tableName,\n columnName,\n values,\n value,\n index,\n typeName: name,\n });\n if (mapped === undefined) {\n return allowedNameChars.test(value) ? value : `Option${index}`;\n }\n if (!validEnumValueName(mapped)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.enumValueNameMapper named value '${value}' of enum '${name}' (on '${tableName}.${columnName}') '${mapped}', which is not a valid GraphQL enum value name. A name must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ and not be true, false or null.`,\n );\n }\n return mapped;\n });\n\n const seen = new Map<string, string>();\n values.forEach((value, index) => {\n const valueName = valueNames[index]!;\n const earlier = seen.get(valueName);\n if (earlier !== undefined) {\n throw new Error(\n `Drizzle-GraphQL Error: Values '${earlier}' and '${value}' of enum '${name}' (on '${tableName}.${columnName}') both map to the GraphQL value name '${valueName}'. Give one of them a different name via config.enumValueNameMapper.`,\n );\n }\n seen.set(valueName, value);\n });\n\n const valuesKey = enumValuesKey(values);\n const namesKey = enumValueNamesKey(valueNames);\n const claimed = enumNamesInUse.get(name);\n if (claimed) {\n if (claimed.valuesKey !== valuesKey) {\n throw new Error(\n `Drizzle-GraphQL Error: Two different enums both map to the GraphQL type name '${name}' (most recently '${tableName}.${columnName}'). Give one of them a different name via config.enumNameMapper.`,\n );\n }\n if (claimed.namesKey !== namesKey) {\n const before = claimed.type\n .getValues()\n .map((v) => v.name)\n .join(', ');\n throw new Error(\n `Drizzle-GraphQL Error: Columns sharing the GraphQL enum '${name}' name its values differently ('${tableName}.${columnName}' gives ${valueNames.join(', ')}; an earlier column gave ${before}). config.enumValueNameMapper must name a shared enum's values the same way for every column, or config.enumNameMapper must give the columns separate types.`,\n );\n }\n return claimed.type;\n }\n\n const gqlEnum = new GraphQLEnumType({\n name,\n values: Object.fromEntries(\n values.map((e, index) => [\n valueNames[index]!,\n {\n value: e,\n description: `Value: ${e}`,\n },\n ]),\n ),\n });\n\n enumNamesInUse.set(name, { type: gqlEnum, valuesKey, namesKey });\n\n return gqlEnum;\n};\n\nconst geoXyType = new GraphQLObjectType({\n name: 'PgGeometryObject',\n fields: {\n x: { type: GraphQLFloat },\n y: { type: GraphQLFloat },\n },\n});\n\nconst geoXyInputType = new GraphQLInputObjectType({\n name: 'PgGeometryObjectInput',\n fields: {\n x: { type: GraphQLFloat },\n y: { type: GraphQLFloat },\n },\n});\n\n/**\n * Whether the column holds a calendar day with no time component — a SQL `date`, in either of\n * the modes drizzle reads one in (`'date'` → a JS `Date`, `'string'` → `YYYY-MM-DD`). Every\n * position a column's type appears in — output, create/update input, filter operands,\n * aggregates and group keys — gives such a column the `Date` scalar, whichever mode it uses:\n * the mode is how the server holds the value, not what the value is. SQLite has no date-only\n * column type (its integer timestamps are instants — see {@link isDateTimeColumn}), so only\n * Postgres and MySQL appear here.\n */\nexport const isDateOnlyColumn = (column: Column): boolean =>\n is(column, PgDate) || is(column, PgDateString) || is(column, MySqlDate) || is(column, MySqlDateString);\n\n/**\n * Whether the column is a MySQL `timestamp` / `datetime` read in drizzle's `'string'` mode. The\n * driver hands such a column back as MySQL's own `YYYY-MM-DD HH:MM:SS[.fraction]` text, with no\n * offset, and expects that form on write, so the data mappers translate between it and the ISO\n * 8601 instant the `DateTime` scalar carries. The text is read as UTC, the way drizzle's own\n * `'date'`-mode codecs for these columns read it.\n */\nexport const isMySqlDateTimeStringColumn = (column: Column): boolean =>\n is(column, MySqlTimestampString) || is(column, MySqlDateTimeString);\n\n/**\n * Whether the column is a Postgres `timestamp` read in drizzle's `'string'` mode. The driver hands\n * such a column back as Postgres's own text — `YYYY-MM-DD HH:MM:SS[.fraction]`, followed by an\n * offset (`+00`, `-06`, `+05:30`) for `timestamptz` — so the data mappers translate between it\n * and the ISO 8601 instant the `DateTime` scalar carries. Text without an offset (`timestamp`\n * without time zone) is read as UTC, the way drizzle's own `'date'`-mode codec reads it.\n */\nexport const isPgTimestampStringColumn = (column: Column): boolean => is(column, PgTimestampString);\n\n/**\n * Whether the column is a SQLite `integer({ mode: 'timestamp' | 'timestamp_ms' })`. Both modes\n * are one drizzle class, told apart by `mode`: the stored integer counts seconds or milliseconds\n * since the Unix epoch. drizzle converts a JS `Date` to that integer on write (`'timestamp'`\n * floors to the whole second) and back on read, but a value read through a path that skips the\n * column's decoder arrives as the bare integer, which {@link sqliteTimestampToDate} reads.\n */\nexport const isSQLiteTimestampColumn = (column: Column): boolean => is(column, SQLiteTimestamp);\n\n/**\n * A SQLite timestamp column's stored integer as the instant it names, using the column's own\n * unit (seconds for `'timestamp'`, milliseconds for `'timestamp_ms'`).\n */\nexport const sqliteTimestampToDate = (column: Column, value: number): Date =>\n new Date((column as any).mode === 'timestamp' ? value * 1000 : value);\n\n/**\n * Whether the column holds an instant — a Postgres `timestamp`, a MySQL `timestamp` /\n * `datetime`, in either drizzle mode, or a SQLite integer timestamp in either unit. Every position\n * such a column appears in gives it the `DateTime` scalar and the `DateTimeFilter`, whichever\n * mode it uses, for the same reason as {@link isDateOnlyColumn}.\n */\nexport const isDateTimeColumn = (column: Column): boolean =>\n is(column, PgTimestamp) ||\n isPgTimestampStringColumn(column) ||\n is(column, MySqlTimestamp) ||\n is(column, MySqlDateTime) ||\n isMySqlDateTimeStringColumn(column) ||\n isSQLiteTimestampColumn(column);\n\nconst columnToGraphQLCore = (\n column: Column,\n columnName: string,\n tableName: string,\n isInput: boolean,\n): ConvertedColumn<boolean> => {\n // drizzle-orm v1 models `.array()` columns as their base column plus a `dimensions` count\n // (e.g. text().array() keeps columnType=PgText with dimensions=1), so the element type is\n // whatever the base column maps to. PgVector/PgGeometry report dimensions of 0 and keep\n // their dedicated handling below.\n const dimensions = (column as any).dimensions as number | undefined;\n if (dimensions !== undefined && dimensions > 0) {\n const inner = columnBaseToGraphQLCore(column, columnName, tableName, isInput);\n const innerLabel = inner.typeLabel ?? (inner.type as GraphQLScalarType).name;\n\n let type: ConvertedColumn<boolean>['type'] = inner.type;\n let typeLabel = innerLabel;\n for (let i = 0; i < dimensions; i++) {\n type = new GraphQLList(new GraphQLNonNull(type as GraphQLScalarType));\n typeLabel = `Array<${typeLabel}>`;\n }\n\n return { type, typeLabel };\n }\n\n return columnBaseToGraphQLCore(column, columnName, tableName, isInput);\n};\n\nconst columnBaseToGraphQLCore = (\n column: Column,\n columnName: string,\n tableName: string,\n isInput: boolean,\n): ConvertedColumn<boolean> => {\n const { type: baseType, constraint } = extractExtendedColumnType(column);\n switch (baseType) {\n case 'boolean':\n return { type: GraphQLBoolean, typeLabel: 'Boolean' };\n case 'object':\n if (isDateOnlyColumn(column)) {\n return { type: GraphQLDate, typeLabel: 'Date' };\n }\n if (isDateTimeColumn(column)) {\n return { type: GraphQLDateTime, typeLabel: 'DateTime' };\n }\n return column.columnType === 'PgGeometryObject'\n ? {\n type: isInput ? geoXyInputType : geoXyType,\n typeLabel: 'Geometry points XY',\n }\n : column.columnType === 'PgBytea'\n ? {\n type: new GraphQLList(new GraphQLNonNull(GraphQLInt)),\n typeLabel: 'Buffer',\n }\n : { type: GraphQLJSON, typeLabel: 'JSON' };\n case 'string':\n if (column.enumValues?.length) {\n return { type: generateEnumCached(column, columnName, tableName) };\n }\n\n // numeric/decimal columns (pg numeric, mysql decimal, sqlite numeric) transport as\n // strings, but they are numbers — give them the named Decimal scalar so the SDL says\n // so and non-numeric input is rejected. Array-typed numeric columns (dimensions > 0)\n // keep their existing mapping.\n if (constraint === 'numeric' && !(column as any).dimensions) {\n return { type: GraphQLDecimalString, typeLabel: 'Decimal' };\n }\n\n if (isDateTimeColumn(column)) {\n return { type: GraphQLDateTime, typeLabel: 'DateTime' };\n }\n if (column instanceof PgUUID) {\n return { type: GraphQLUUID, typeLabel: 'UUID' };\n }\n if (isDateOnlyColumn(column)) {\n return { type: GraphQLDate, typeLabel: 'Date' };\n }\n\n return { type: GraphQLString, typeLabel: 'String' };\n case 'bigint':\n return { type: GraphQLBigIntString, typeLabel: 'BigInt' };\n case 'number': {\n // Every integer kind that fits GraphQL's 32-bit signed Int: smallint / tinyint /\n // mediumint / smallserial and MySQL `year` report these constraints in drizzle v1, and\n // used to fall through to Float. Wider kinds (int53, uint32, uint53) are matched only\n // through the column classes below, as before.\n return (constraint !== undefined && smallIntegerConstraints.has(constraint)) ||\n is(column, PgInteger) ||\n is(column, PgSerial) ||\n is(column, MySqlInt) ||\n is(column, MySqlSerial) ||\n is(column, SQLiteInteger)\n ? { type: GraphQLInt, typeLabel: 'Integer' }\n : { type: GraphQLFloat, typeLabel: 'Float' };\n }\n case 'array': {\n if (column.columnType === 'PgVector') {\n return {\n type: new GraphQLList(new GraphQLNonNull(GraphQLFloat)),\n typeLabel: 'Array<Float>',\n };\n }\n\n if (column.columnType === 'PgGeometry') {\n return {\n type: new GraphQLList(new GraphQLNonNull(GraphQLFloat)),\n typeLabel: 'Tuple<[Float, Float]>',\n };\n }\n\n const innerType = columnToGraphQLCore(\n (column as unknown as { baseColumn: Column }).baseColumn,\n columnName,\n tableName,\n isInput,\n );\n\n return {\n type: new GraphQLList(new GraphQLNonNull(innerType.type as GraphQLScalarType)),\n typeLabel: `Array<${innerType.typeLabel}>`,\n };\n }\n default:\n throw new Error(`Drizzle-GraphQL Error: Type ${column.dataType} is not implemented!`);\n }\n};\n\n/**\n * Per-column scalar overrides, resolved at build time from `BuildSchemaConfig.scalars` /\n * `BuildSchemaConfig.mapColumnType` and consulted by every column→GraphQL type decision\n * (select fields, insert/update inputs, filter operands, aggregate min/max) as well as by\n * the runtime data mappers, which must not re-coerce a value an override scalar owns.\n *\n * Keyed weakly by the column object itself so the registry never outlives the schema.\n * `registerScalarOverrides` runs on every build and clears entries for columns that no\n * longer have an override; when two live schemas are built from the same table objects\n * with different scalar configs, the most recent build wins for runtime value mapping.\n */\nconst columnScalarOverrides = new WeakMap<Column, { output?: GraphQLScalarType; input?: GraphQLScalarType }>();\n\n/** The scalar overriding this column in the given direction, if one was registered. */\nexport const getColumnScalarOverride = (column: Column, isInput: boolean): GraphQLScalarType | undefined => {\n const override = columnScalarOverrides.get(column);\n return override ? (isInput ? override.input : override.output) : undefined;\n};\n\nconst normalizeScalarOverride = (\n override: ScalarOverride,\n tableName: string,\n columnName: string,\n): { output?: GraphQLScalarType; input?: GraphQLScalarType } => {\n const pair =\n override instanceof GraphQLScalarType\n ? { output: override, input: override }\n : { output: override.output, input: override.input };\n\n for (const scalar of [pair.output, pair.input]) {\n if (scalar !== undefined && !(scalar instanceof GraphQLScalarType)) {\n throw new Error(\n `Drizzle-GraphQL Error: Scalar override for column '${tableName}.${columnName}' must be a GraphQLScalarType!`,\n );\n }\n }\n\n return pair;\n};\n\n/**\n * Resolves the scalar-override config against every column of the given tables and stores\n * the result in the override registry. Called once per schema build, before any types are\n * generated — and always, even with no config, so a rebuild clears overrides left behind\n * by a previous build against the same table objects.\n *\n * The declarative `scalars` map wins over `mapColumnType`; a mapper returning `undefined`\n * leaves the column on built-in detection.\n */\nexport const registerScalarOverrides = (\n tables: Record<string, Table>,\n config: { scalars?: ScalarOverridesConfig; mapColumnType?: ColumnTypeMapper },\n): void => {\n for (const [tableName, table] of Object.entries(tables)) {\n for (const [columnName, column] of Object.entries(getColumns(table))) {\n const declared = config.scalars?.[tableName]?.[columnName];\n\n let resolved: { output?: GraphQLScalarType; input?: GraphQLScalarType } | undefined;\n if (declared !== undefined) {\n resolved = normalizeScalarOverride(declared, tableName, columnName);\n } else if (config.mapColumnType) {\n // Built-in detection throws for column types it has no mapping for; the mapper is\n // exactly the tool to type such columns, so a failed default becomes `undefined`\n // rather than an error.\n let defaultType: GraphQLOutputType | undefined;\n let defaultInputType: GraphQLInputType | undefined;\n try {\n defaultType = columnToGraphQLCore(column, columnName, tableName, false).type as GraphQLOutputType;\n } catch {}\n try {\n defaultInputType = columnToGraphQLCore(column, columnName, tableName, true).type as GraphQLInputType;\n } catch {}\n\n const mapped = config.mapColumnType(column, { tableName, columnName, defaultType, defaultInputType });\n if (mapped !== undefined) {\n resolved = normalizeScalarOverride(mapped, tableName, columnName);\n }\n }\n\n if (resolved && (resolved.output !== undefined || resolved.input !== undefined)) {\n columnScalarOverrides.set(column, resolved);\n } else {\n columnScalarOverrides.delete(column);\n }\n }\n }\n};\n\nexport const drizzleColumnToGraphQLType = <TColumn extends Column, TIsInput extends boolean = false>(\n column: TColumn,\n columnName: string,\n tableName: string,\n forceNullable = false,\n defaultIsNullable = false,\n isInput: TIsInput = false as TIsInput,\n): ConvertedColumn<TIsInput> => {\n const override = getColumnScalarOverride(column, isInput);\n // An override replaces built-in detection entirely, so the label is the scalar's own name:\n // nothing downstream should treat an overridden column as the type it would have had.\n const typeDesc: ConvertedColumn<boolean> = override\n ? { type: override, typeLabel: override.name }\n : columnToGraphQLCore(column, columnName, tableName, isInput);\n\n if (forceNullable) {\n return typeDesc as ConvertedColumn<TIsInput>;\n }\n if (column.notNull && !(defaultIsNullable && (column.hasDefault || column.defaultFn))) {\n return {\n // Neither branch above wraps, so this is the only wrapper the column ever gets; the cast\n // narrows the declared union to the nullable half graphql 17's constructor accepts.\n type: new GraphQLNonNull(typeDesc.type as NullableConvertedColumnType<boolean>),\n typeLabel: typeDesc.typeLabel,\n } as ConvertedColumn<TIsInput>;\n }\n\n return typeDesc as ConvertedColumn<TIsInput>;\n};\n","// Every name the build gives a generated type, in one place.\n//\n// `typeNameMapper` names a table's object type and its root fields. It does not reach the\n// types generated *around* that table — the filter, the write inputs, the order-by, the\n// aggregate family — which are derived from that name by a fixed rule. A build that stitches\n// its schema next to a second generator over the same tables collides on exactly those\n// derived names, and had no hook to say otherwise.\n//\n// Both levers here answer that. `derivedTypeNameMapper` is asked for every type the build\n// creates and may decline, so a single kind can be renamed and nothing else moves;\n// `typeNamePrefix` / `typeNameSuffix` wrap every name the mapper did not answer for, which is\n// the one-line way to make a whole subschema collision-free.\n\nimport type { GraphQLNamedType } from 'graphql';\n\n/**\n * What a generated type is, so a name mapper can answer for one kind without matching on the\n * spelling of the default name.\n *\n * - `object` — a table's row type, the one `typeNameMapper` already names\n * - `filter` / `listRelationFilter` — `<Type>Filters` and the `some`/`none`/`every` wrapper\n * - `orderBy` — `<Type>OrderBy`\n * - `createInput` / `updateInput` / `updateManyInput` / `nestedWriteInput` / `fieldUpdateInput`\n * — the write inputs\n * - `aggregate` — `<Type>Aggregate` and its per-operation children (`operation` names which)\n * - `having` / `groupBy` / `groupKeys` — the group-by family\n * - `onConflict` — the upsert's conflict input\n * - `uniqueKey` — a compound unique constraint's key input\n * - `columnEnum` — an enum naming a table's columns (`distinct`, conflict target, …)\n * - `columnFilter` — a shared per-scalar filter (`StringFilter`, `IntFilter`, …), not per table\n * - `shared` — everything else the build creates once (`OrderNulls`, `DeletedFilter`, …)\n */\nexport type GeneratedTypeKind =\n | 'object'\n | 'filter'\n | 'listRelationFilter'\n | 'orderBy'\n | 'createInput'\n | 'updateInput'\n | 'updateManyInput'\n | 'nestedWriteInput'\n | 'fieldUpdateInput'\n | 'aggregate'\n | 'having'\n | 'groupBy'\n | 'groupKeys'\n | 'onConflict'\n | 'uniqueKey'\n | 'columnEnum'\n | 'columnFilter'\n | 'shared';\n\n/** What a name mapper is told about the type it is being asked to name. */\nexport interface GeneratedTypeInfo {\n /** Which kind of generated type this is. */\n kind: GeneratedTypeKind;\n /** The name the library would use, before any prefix or suffix. */\n defaultName: string;\n /** The table key the type belongs to, where it belongs to one. */\n table?: string;\n /**\n * The narrower thing the type is for, where the kind alone does not say: the aggregate\n * operation (`sum`, `avg`, …), the relation a nested-write input is for, the scalar a\n * column filter covers, the columns of a unique key.\n */\n operation?: string;\n}\n\n/**\n * Renames a generated type. Return `undefined` — or the same name — to keep the default,\n * which is what an unlisted kind should do; anything returned is used verbatim, without the\n * build's prefix or suffix.\n */\nexport type DerivedTypeNameMapper = (info: GeneratedTypeInfo) => string | undefined;\n\n/** The build's resolved naming rule, asked at every type construction. */\nexport type TypeNameResolver = (info: GeneratedTypeInfo) => string;\n\n/** The naming knobs `resolveGeneratedTypeNames` reads off the build config. */\nexport interface GeneratedTypeNameConfig {\n derivedTypeNameMapper?: DerivedTypeNameMapper;\n typeNamePrefix?: string;\n typeNameSuffix?: string;\n}\n\n/**\n * The build's naming rule: the mapper's answer where it has one, otherwise the default name\n * wrapped in the build's prefix and suffix.\n *\n * A build that configures neither gets the identity function, so the fast path costs a\n * property read and today's schemas are byte-for-byte unchanged.\n */\nexport const resolveGeneratedTypeNames = (config: GeneratedTypeNameConfig | undefined): TypeNameResolver => {\n const mapper = config?.derivedTypeNameMapper;\n const prefix = config?.typeNamePrefix ?? '';\n const suffix = config?.typeNameSuffix ?? '';\n\n if (!mapper && !prefix && !suffix) {\n return (info) => info.defaultName;\n }\n\n return (info) => {\n const mapped = mapper?.(info);\n // Verbatim: the caller named this type explicitly, so wrapping it would be overruling\n // the more specific of the two knobs with the blunter one.\n return mapped || `${prefix}${info.defaultName}${suffix}`;\n };\n};\n\n// Types the build creates once rather than per table — `OrderNulls`, `StringFilter` and the\n// like — used to be module-level constants, shared by every build in the process. They still\n// are, but keyed by the name they resolved to: two builds that name a type the same way share\n// one instance exactly as before, and a build that renames it gets its own.\nconst sharedTypeCache = new Map<string, GraphQLNamedType>();\n\n/**\n * A build-wide shared type, built once per name it is known by.\n *\n * @param build receives the resolved name — the type must be constructed with it, not with\n * the default the caller passed in\n */\nexport const sharedType = <T extends GraphQLNamedType>(\n typeName: TypeNameResolver,\n info: GeneratedTypeInfo,\n build: (name: string) => T,\n): T => {\n const name = typeName(info);\n const cached = sharedTypeCache.get(name);\n if (cached) {\n return cached as T;\n }\n const built = build(name);\n sharedTypeCache.set(name, built);\n return built;\n};\n","// The filter input types, generated per column *shape* rather than per (table, column) pair —\n// the local modification `../common.ts` describes. Which descriptor a column gets is decided by\n// its data type, its dialect, and any scalar override the caller configured.\n\nimport type { Column } from 'drizzle-orm';\nimport { extractExtendedColumnType } from 'drizzle-orm';\nimport {\n GraphQLBoolean,\n GraphQLEnumType,\n GraphQLFloat,\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n type GraphQLScalarType,\n GraphQLString,\n} from 'graphql';\nimport {\n GraphQLBigIntString,\n GraphQLDate,\n GraphQLDateTime,\n GraphQLDecimalString,\n GraphQLJSON,\n GraphQLUUID,\n} from '../../scalars/index.ts';\nimport { drizzleColumnToGraphQLType, getColumnScalarOverride, isDateTimeColumn } from '../../type-converter/index.ts';\nimport type { ConvertedColumn, NullableConvertedColumnType } from '../../type-converter/types.ts';\nimport type { TypeCacheCtx } from './type-cache.ts';\nimport { sharedType, type TypeNameResolver } from './type-names.ts';\n\n/** The dialect a column belongs to, inferred from its drizzle columnType string (e.g. 'PgJsonb'). */\nexport const columnDialect = (column: Column): 'pg' | 'mysql' | 'sqlite' | undefined => {\n const ct: string = (column as any).columnType ?? '';\n if (ct.startsWith('Pg')) {\n return 'pg';\n }\n if (ct.startsWith('MySql')) {\n return 'mysql';\n }\n if (ct.startsWith('SQLite')) {\n return 'sqlite';\n }\n return undefined;\n};\n\n/**\n * Whether the column stores JSON.\n *\n * Decided on drizzle's `dataType`, its semantic marker, rather than on `columnType`, which\n * names the implementing class. drizzle-orm v1 uses compound dataType strings (`\"object\n * json\"` for every json/jsonb column across the three dialects), hence the inclusion test.\n *\n * `PgGeometryObject` is excluded explicitly. That is currently redundant — it reports\n * `\"object geometry\"` — but it is stored as json, has its own object type in the generated\n * schema, and must not be reclassified if drizzle ever spells its dataType differently.\n *\n * One predicate for two callers that must agree: the filter builder, whose `path` and\n * `contains` operators mean structural JSON containment rather than the string operators,\n * and the data mappers, which transport a JSON value as-is instead of remapping it. They\n * previously had a copy each, asking different questions of the column.\n */\nexport const isJsonColumn = (column: Column): boolean =>\n ((column as any).dataType ?? '').includes('json') && (column as any).columnType !== 'PgGeometryObject';\n\n/** How a column's generic filter input should be shaped, alongside the cache key to store it under. */\ninterface GenericFilterDescriptor {\n name: string;\n kind: 'scalar' | 'json' | 'array';\n /**\n * True for an enum column. Enum filter types are named after the enum, so they cannot be\n * recognised by name the way the built-in filters below are — but they want the same lean\n * operator set as `Boolean`: a closed set of members has nothing to pattern-match and no\n * order beyond the accident of how the column was declared.\n */\n isEnum?: boolean;\n}\n\n/**\n * Maps a Drizzle column to the generic filter type to use.\n *\n * Selection is keyed on the column's data type, never its name: a text column named\n * `userId` gets the full String filter (string operators included), while a uuid column\n * gets the lean Id filter whatever it is called.\n * - \"JSON\" → json/jsonb columns (eq/ne + containment, no scalar comparison ops)\n * - `${Element}Array` → array columns, keyed per element type (IntArray, FloatArray,\n * StringArray, …) so arrays with different element types never share\n * one filter input; membership operators instead of scalar comparisons\n * - \"Id\" → uuid-typed columns (no string pattern operators)\n * - \"Boolean\" → boolean columns (equality and membership only — no ordering, no patterns)\n * - \"BigInt\" → bigint columns (BigInt-scalar-typed operators, no string pattern operators)\n * - \"Decimal\" → numeric/decimal columns (Decimal-scalar-typed operators, no string pattern operators)\n * - the enum GraphQL type name → enum columns (still unique per enum; equality and\n * membership only, like Boolean)\n * - \"Date\" → date columns, either mode (ordering kept, no string pattern operators)\n * - \"DateTime\" → timestamp columns (ordering kept, no string pattern operators)\n * - \"Int\" → integer/serial columns (no string pattern operators)\n * - \"Float\" → real/double columns (no string pattern operators)\n * - \"String\" → all other text/varchar columns\n */\nconst resolveGenericFilterDescriptor = (\n column: Column,\n columnGraphQLType: ReturnType<typeof drizzleColumnToGraphQLType>,\n): GenericFilterDescriptor => {\n // JSON / JSONB columns — structural values with their own operator set.\n if (columnGraphQLType.type === GraphQLJSON) {\n return { name: 'JSON', kind: 'json' };\n }\n // Array columns — keyed per element type so an int[] and a text[] column never share\n // one cached filter input.\n if (columnGraphQLType.type instanceof GraphQLList) {\n let element = columnGraphQLType.type.ofType;\n if (element instanceof GraphQLNonNull) {\n element = element.ofType;\n }\n return { name: `${element.name}Array`, kind: 'array' };\n }\n // Opaque uuid keys — keyed on the column type, not on an `id`/`*Id` naming convention.\n if (columnGraphQLType.type === GraphQLUUID) {\n return { name: 'Id', kind: 'scalar' };\n }\n // Boolean scalar\n if (columnGraphQLType.type === GraphQLBoolean) {\n return { name: 'Boolean', kind: 'scalar' };\n }\n // Enum type — keep unique per enum since values differ\n if (columnGraphQLType.type instanceof GraphQLEnumType) {\n return { name: columnGraphQLType.type.name, kind: 'scalar', isEnum: true };\n }\n // Named numeric-string scalars — give them their own filters so the operators\n // are typed with the scalar (and validated by it) instead of a shared StringFilter.\n if (columnGraphQLType.type === GraphQLBigIntString) {\n return { name: 'BigInt', kind: 'scalar' };\n }\n if (columnGraphQLType.type === GraphQLDecimalString) {\n return { name: 'Decimal', kind: 'scalar' };\n }\n // Calendar-date columns, in either drizzle mode — the type converter gives them the `Date`\n // scalar, so the operands are `Date` too and a datetime string is rejected in a filter\n // exactly as it is in a write.\n if (columnGraphQLType.type === GraphQLDate) {\n return { name: 'Date', kind: 'scalar' };\n }\n // Timestamp / datetime columns, in either drizzle mode.\n if (isDateTimeColumn(column)) {\n return { name: 'DateTime', kind: 'scalar' };\n }\n // Numeric scalars — distinct names so an int/float column never shares (and never\n // mistypes) the StringFilter, and integer ids keep a filter without string operators.\n // (BigInt/Decimal columns are handled above via their named scalars.)\n if (columnGraphQLType.type === GraphQLInt) {\n return { name: 'Int', kind: 'scalar' };\n }\n if (columnGraphQLType.type === GraphQLFloat) {\n return { name: 'Float', kind: 'scalar' };\n }\n // Default: plain text/varchar\n return { name: 'String', kind: 'scalar' };\n};\n\n/**\n * Filter fields for a json/jsonb column. `eq`/`ne` compare the whole document (jsonb equality\n * on Postgres, driver-level comparison elsewhere); `contains` is structural containment —\n * Postgres `@>` / MySQL `JSON_CONTAINS`. SQLite stores json as text and has no containment\n * operator, so `contains` is omitted there (same precedent as dialect-specific ops like ilike).\n */\nconst jsonFilterFields = (column: Column, colType: ConvertedColumn<true>['type'], typeName: TypeNameResolver) => {\n const dialect = columnDialect(column);\n return {\n eq: { type: colType, description: 'JSON equality on the whole value' },\n ne: { type: colType, description: 'JSON inequality on the whole value' },\n ...(dialect === 'pg' || dialect === 'mysql'\n ? {\n contains: {\n type: colType,\n description: 'Value structurally contains this JSON (Postgres `@>` / MySQL JSON_CONTAINS)',\n },\n }\n : {}),\n path: {\n type: new GraphQLList(new GraphQLNonNull(jsonPathFilterType(typeName))),\n description:\n 'Compares the value at one path inside the document. Several entries are ANDed; a single object may be passed without the list brackets.',\n },\n isNull: { type: GraphQLBoolean },\n isNotNull: { type: GraphQLBoolean },\n };\n};\n\n/**\n * How the value at a JSON path is read before it is compared. Left unset, the operand\n * decides: a GraphQL number compares numerically, a boolean as a boolean, anything else as\n * text. Set it when the operand's type does not match the document's — comparing a numeric\n * field against a `String` variable, say.\n */\nconst jsonPathCastType = (typeName: TypeNameResolver): GraphQLEnumType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'JSONPathCast' },\n (name) =>\n new GraphQLEnumType({\n name,\n description: 'How to read the value at a JSON path before comparing it',\n values: {\n TEXT: { value: 'text', description: 'Compare as text (lexicographic ordering)' },\n NUMBER: { value: 'number', description: 'Compare as a number; a non-numeric value never matches' },\n BOOLEAN: { value: 'boolean', description: 'Compare as a boolean' },\n },\n }),\n );\n\n/**\n * One predicate on the value at a path inside a json/jsonb column. `path` walks the document\n * key by key (an all-digits element indexes an array), and the remaining operators compare\n * whatever sits there. Operands are `JSON` so a single input type serves string, number and\n * boolean fields; see {@link jsonPathCast} for how the comparison type is chosen.\n *\n * Note that `contains` here is substring matching on the extracted value — unlike `contains`\n * on the column itself, which is structural JSON containment. A path names a scalar, so the\n * string reading is the useful one.\n */\nconst jsonPathFilterType = (typeName: TypeNameResolver): GraphQLInputObjectType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'JSONPathFilter' },\n (name) =>\n new GraphQLInputObjectType({\n name,\n fields: {\n path: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLString))),\n description:\n 'Keys to walk from the document root, e.g. `[\"profile\", \"level\"]`. An all-digits key indexes an array.',\n },\n as: { type: jsonPathCastType(typeName), description: 'Overrides how the value is read before comparing' },\n eq: { type: GraphQLJSON, description: 'Equal to' },\n ne: { type: GraphQLJSON, description: 'Not equal to' },\n lt: { type: GraphQLJSON, description: 'Less than' },\n lte: { type: GraphQLJSON, description: 'Less than or equal to' },\n gt: { type: GraphQLJSON, description: 'Greater than' },\n gte: { type: GraphQLJSON, description: 'Greater than or equal to' },\n startsWith: {\n type: GraphQLString,\n description: 'Extracted value starts with this string. `%`, `_` and `\\\\` are matched literally.',\n },\n endsWith: {\n type: GraphQLString,\n description: 'Extracted value ends with this string. `%`, `_` and `\\\\` are matched literally.',\n },\n contains: {\n type: GraphQLString,\n description: 'Extracted value contains this string. `%`, `_` and `\\\\` are matched literally.',\n },\n iStartsWith: { type: GraphQLString, description: 'Case-insensitive `startsWith`.' },\n iEndsWith: { type: GraphQLString, description: 'Case-insensitive `endsWith`.' },\n iContains: { type: GraphQLString, description: 'Case-insensitive `contains`.' },\n isNull: {\n type: GraphQLBoolean,\n description: 'When true, matches rows where the path is missing or holds JSON null',\n },\n isNotNull: { type: GraphQLBoolean, description: 'When true, matches rows where the path holds a value' },\n },\n }),\n );\n\n/**\n * `inArray` / `notInArray` take a list of candidate values and compile to SQL `IN` /\n * `NOT IN`. Their descriptions are fixed rather than derived from the column: what the\n * operator does is the same everywhere, and the operand type already says what goes in it.\n */\nconst IN_ARRAY_DESCRIPTION = 'Matches any one of these values (SQL `IN`)';\nconst NOT_IN_ARRAY_DESCRIPTION = 'Matches none of these values (SQL `NOT IN`)';\n\n/**\n * Filter fields for an array column (Postgres-only in drizzle). Membership operators replace\n * the scalar comparison and string pattern sets: `has` checks a single element (`@>` with a\n * one-element array), `hasSome` is overlap (`&&`), `hasEvery` is containment (`@>`), `isEmpty`\n * matches arrays with no elements. `eq`/`ne` still compare the whole array, and\n * `inArray`/`notInArray` still match the whole array against a list of candidate arrays\n * (SQL `IN`, typed `[[Element!]!]`).\n */\nconst arrayFilterFields = (colType: GraphQLList<any>, colArr: GraphQLList<any>) => {\n let element = colType.ofType;\n if (element instanceof GraphQLNonNull) {\n element = element.ofType;\n }\n const elementList = new GraphQLList(new GraphQLNonNull(element));\n\n return {\n eq: { type: colType, description: 'The whole array equals this array' },\n ne: { type: colType, description: 'The whole array differs from this array' },\n has: { type: element, description: 'Array contains this element' },\n hasSome: { type: elementList, description: 'Array contains at least one of these elements (overlap, `&&`)' },\n hasEvery: { type: elementList, description: 'Array contains every one of these elements (containment, `@>`)' },\n isEmpty: { type: GraphQLBoolean, description: 'When true, matches arrays with no elements' },\n inArray: { type: colArr, description: IN_ARRAY_DESCRIPTION },\n notInArray: { type: colArr, description: NOT_IN_ARRAY_DESCRIPTION },\n isNull: { type: GraphQLBoolean },\n isNotNull: { type: GraphQLBoolean },\n };\n};\n\n/**\n * Filters whose fields omit the string pattern operators (like/notLike/ilike/notIlike/\n * startsWith/contains/… and the `insensitive` flag that modifies them): they are nonsensical\n * on opaque uuids, booleans and enum members, invalid SQL on numeric columns, and on a\n * timestamp they match whatever the session happens to render the value as rather than\n * anything in the query. Keyed on the generic filter name (i.e. on column type) — a\n * string-typed column keeps the string operators whatever it is called. Enum filters are\n * named after their enum and are recognised by `isEnum` instead.\n */\nconst FILTERS_WITHOUT_STRING_OPS = new Set(['Id', 'Int', 'Float', 'BigInt', 'Decimal', 'Boolean', 'Date', 'DateTime']);\n\n/**\n * Filters that additionally omit the ordering operators (lt/lte/gt/gte). Ordering two\n * booleans is `eq` spelled as a puzzle (`gt: false` is `eq: true`), and ordering enum members\n * compares their declaration order — an artefact of how the column was written rather than a\n * fact about the domain. Timestamps and the numerics keep them: ranges are the point of\n * having them. Enum filters are recognised by `isEnum`, as above.\n */\nconst FILTERS_WITHOUT_ORDERING_OPS = new Set(['Boolean']);\n\n/**\n * Scalars the built-in detection itself can produce. A scalar override to one of these\n * shares the built-in filter type for that scalar, so its shape must stay exactly what a\n * natural column of the scalar gets — whichever column builds the cached type first.\n * Any other override scalar gets its own filter type named after the scalar.\n */\nconst BUILTIN_FILTER_SCALARS = new Set<GraphQLScalarType>([\n GraphQLString,\n GraphQLInt,\n GraphQLFloat,\n GraphQLBoolean,\n GraphQLBigIntString,\n GraphQLDecimalString,\n GraphQLUUID,\n GraphQLJSON,\n GraphQLDate,\n GraphQLDateTime,\n]);\n\n/**\n * Filter descriptor for a scalar-overridden column. Overrides to the library's own\n * structural scalars keep the corresponding built-in descriptor (JSON keeps the\n * json-shaped filter, UUID the Id filter), so they share the name-keyed cache with\n * natural columns safely in either build order; every other scalar — the remaining\n * built-ins and all custom scalars — gets a scalar-shaped filter named after it\n * (BigIntFilter, MoneyFilter, …).\n */\nconst resolveOverrideFilterDescriptor = (scalar: GraphQLScalarType): GenericFilterDescriptor => {\n if (scalar === GraphQLJSON) {\n return { name: 'JSON', kind: 'json' };\n }\n if (scalar === GraphQLUUID) {\n return { name: 'Id', kind: 'scalar' };\n }\n return { name: scalar.name, kind: 'scalar' };\n};\n\nexport const generateColumnFilterValues = (\n column: Column,\n tableName: string,\n columnName: string,\n cacheCtx: TypeCacheCtx,\n): GraphQLInputObjectType => {\n const columnGraphQLType = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, true);\n\n // A scalar-overridden column gets its filter built from the override scalar, which\n // `columnGraphQLType` above already resolved to. An override to one of the library's own\n // scalars shares the built-in filter for that scalar (same descriptor a natural column of\n // that scalar gets); any other scalar gets its own scalar-shaped filter type named after it\n // (e.g. MoneyFilter). The cache stays keyed by name, so all columns overridden with the\n // same scalar share one filter type.\n const inputOverride = getColumnScalarOverride(column, true);\n\n const {\n name: genericName,\n kind,\n isEnum,\n } = inputOverride\n ? resolveOverrideFilterDescriptor(inputOverride)\n : resolveGenericFilterDescriptor(column, columnGraphQLType);\n const cached = cacheCtx.genericFilterCache.get(genericName);\n if (cached) {\n return cached;\n }\n\n // Built with `forceNullable`, so the value is never a `GraphQLNonNull` — only the union is\n // wide enough to say so, and graphql 17's branded constructor cares.\n const colType = columnGraphQLType.type as NullableConvertedColumnType<true>;\n const colArr = new GraphQLList(new GraphQLNonNull(colType));\n\n // Which operators a column type gets is decided by the column type, never by the column\n // name. A filter shared with the built-ins keeps that name-keyed rule even for an\n // overridden column, so the shared type's shape never depends on which column built it\n // first. A custom override scalar's own filter carries the pattern operators only when a\n // pattern match is valid SQL on the underlying database column: string-typed, and not\n // numeric/decimal (those transport as strings but reject LIKE). Ordering operators are\n // dropped only for the built-in shapes where they are meaningless — a custom scalar says\n // nothing about whether its column is orderable, so it keeps them.\n const customOverrideFilter = inputOverride !== undefined && !BUILTIN_FILTER_SCALARS.has(inputOverride);\n const underlying = extractExtendedColumnType(column);\n const omitStringOps = customOverrideFilter\n ? underlying.type !== 'string' || underlying.constraint === 'numeric'\n : isEnum || FILTERS_WITHOUT_STRING_OPS.has(genericName);\n const omitOrderingOps = !customOverrideFilter && (isEnum || FILTERS_WITHOUT_ORDERING_OPS.has(genericName));\n\n const baseFields =\n kind === 'json'\n ? jsonFilterFields(column, colType, cacheCtx.typeName)\n : kind === 'array'\n ? arrayFilterFields(colType as GraphQLList<any>, colArr)\n : {\n eq: { type: colType, description: 'Equal to' },\n ne: { type: colType, description: 'Not equal to' },\n ...(omitOrderingOps\n ? {}\n : {\n lt: { type: colType, description: 'Less than' },\n lte: { type: colType, description: 'Less than or equal to' },\n gt: { type: colType, description: 'Greater than' },\n gte: { type: colType, description: 'Greater than or equal to' },\n }),\n ...(omitStringOps\n ? {}\n : {\n like: { type: GraphQLString },\n notLike: { type: GraphQLString },\n ilike: { type: GraphQLString },\n notIlike: { type: GraphQLString },\n startsWith: {\n type: GraphQLString,\n description:\n 'Matches values starting with the given string. `%`, `_` and `\\\\` are matched literally.',\n },\n endsWith: {\n type: GraphQLString,\n description:\n 'Matches values ending with the given string. `%`, `_` and `\\\\` are matched literally.',\n },\n contains: {\n type: GraphQLString,\n description: 'Matches values containing the given string. `%`, `_` and `\\\\` are matched literally.',\n },\n iStartsWith: {\n type: GraphQLString,\n description: 'Case-insensitive `startsWith`.',\n },\n iEndsWith: {\n type: GraphQLString,\n description: 'Case-insensitive `endsWith`.',\n },\n iContains: {\n type: GraphQLString,\n description: 'Case-insensitive `contains`.',\n },\n insensitive: {\n type: GraphQLBoolean,\n description:\n 'When true, every comparison operator in this object matches case-insensitively — `eq`, `ne`, the ordering operators, `inArray`/`notInArray` and the pattern operators all compare `lower(column)` against `lower(operand)`. Applies only to the operators beside it; a nested `AND`/`OR`/`NOT` branch sets its own.',\n },\n }),\n inArray: { type: colArr, description: IN_ARRAY_DESCRIPTION },\n notInArray: { type: colArr, description: NOT_IN_ARRAY_DESCRIPTION },\n isNull: { type: GraphQLBoolean, description: 'When true, matches rows where the column is NULL' },\n isNotNull: { type: GraphQLBoolean, description: 'When true, matches rows where the column is not NULL' },\n };\n\n // The boolean branches are recursive — each branch is this filter type itself — so the\n // fields are thunked and reference the type being constructed.\n const mainType: GraphQLInputObjectType = new GraphQLInputObjectType({\n name: cacheCtx.typeName({ kind: 'columnFilter', defaultName: `${genericName}Filter`, operation: genericName }),\n fields: () => ({\n ...baseFields,\n OR: {\n type: new GraphQLList(new GraphQLNonNull(mainType)),\n description: 'At least one branch matches; ANDed with any sibling operators',\n },\n AND: {\n type: new GraphQLList(new GraphQLNonNull(mainType)),\n description: 'Every branch matches',\n },\n NOT: {\n type: mainType,\n description: 'Negates the nested operators',\n },\n }),\n });\n\n cacheCtx.genericFilterCache.set(genericName, mainType);\n return mainType;\n};\n","import { type Column, getColumns, is, One, type Table } from 'drizzle-orm';\nimport { isJsonColumn } from '../builders/common/column-filters.ts';\nimport { drizzleError } from '../builders/common/errors.ts';\nimport type { TableNamedRelations } from '../builders/index.ts';\nimport { dateToCalendarDate, isCalendarDate } from '../scalars/index.ts';\nimport {\n getColumnScalarOverride,\n isDateOnlyColumn,\n isDateTimeColumn,\n isMySqlDateTimeStringColumn,\n isPgTimestampStringColumn,\n isSQLiteTimestampColumn,\n sqliteTimestampToDate,\n} from '../type-converter/index.ts';\n\n/**\n * MySQL's own text form for a `timestamp` / `datetime`: `YYYY-MM-DD HH:MM:SS`, an optional\n * fraction, and no offset. mysql2 returns it for a `'string'`-mode column, and it is what such a\n * column expects on write.\n */\nconst MYSQL_DATETIME_TEXT = /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?)$/;\n\n/**\n * MySQL datetime text, read as UTC, as the ISO 8601 instant the `DateTime` scalar carries.\n * UTC because that is how drizzle's own `'date'`-mode codecs read the same text, so a column's\n * two modes agree on the instant. Anything else (a zero date, a value already carrying an\n * offset) is returned unchanged for the scalar to accept or reject.\n */\nconst mySqlDateTimeTextToIso = (value: string): string => {\n const match = MYSQL_DATETIME_TEXT.exec(value);\n return match ? `${match[1]}T${match[2]}Z` : value;\n};\n\n/**\n * A JS `Date` as offset-less `YYYY-MM-DD HH:MM:SS.mmm` text in UTC: what a MySQL `'string'`-mode\n * column and a Postgres `timestamp` (without time zone) `'string'`-mode column are written with.\n */\nconst dateToUtcWallText = (value: Date): string => value.toISOString().slice(0, -1).replace('T', ' ');\n\n/**\n * Postgres's text form for a `timestamp` / `timestamptz` (the `ISO` `DateStyle`, the default):\n * `YYYY-MM-DD HH:MM:SS`, an optional fraction, and — for `timestamptz` only — the session zone's\n * offset as `±HH`, `±HH:MM` or, for historical local mean time, `±HH:MM:SS`.\n */\nconst PG_TIMESTAMP_TEXT =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(\\.\\d+)?(?:([+-])(\\d{2})(?::?(\\d{2}))?(?::?(\\d{2}))?)?$/;\n\n/**\n * Postgres timestamp text as the RFC 3339 UTC instant (`…Z`) the `DateTime` scalar accepts.\n *\n * - With an offset (`timestamptz`), the instant is shifted to UTC. The offset can carry seconds,\n * which RFC 3339 cannot express, so it is applied here rather than rewritten.\n * - Without one (`timestamp`), the wall time is read as UTC: that is what drizzle's `'date'`-mode\n * codec does (`new Date(text + '+0000')`) and what the input side writes, so a column's two\n * modes agree on the instant.\n * - The fraction is kept digit for digit. The scalar itself carries milliseconds, so microseconds\n * are truncated on the wire, never rounded into the next second.\n *\n * Anything else (`infinity`, a `BC` date, a five-digit year) is returned unchanged for the scalar\n * to reject.\n */\nexport const pgTimestampTextToIso = (value: string): string => {\n const match = PG_TIMESTAMP_TEXT.exec(value);\n if (!match) {\n return value;\n }\n const [, date, time, fraction = '', sign, hours, minutes = '0', seconds = '0'] = match;\n if (!sign) {\n return `${date}T${time}${fraction}Z`;\n }\n\n const wallMs = Date.parse(`${date}T${time}Z`);\n if (Number.isNaN(wallMs)) {\n return value;\n }\n const offsetSeconds = (sign === '-' ? -1 : 1) * (Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds));\n const utc = new Date(wallMs - offsetSeconds * 1000).toISOString();\n // `toISOString` only stays `YYYY-MM-DDTHH:MM:SS.mmmZ` inside years 0000–9999.\n return utc.length === 24 ? `${utc.slice(0, 19)}${fraction}Z` : value;\n};\n\nexport const remapToGraphQLCore = (\n key: string,\n value: any,\n tableName: string,\n // Relation keys have no column; the guard below is what handles them.\n column: Column | undefined,\n relationMap?: Record<string, Record<string, TableNamedRelations>>,\n): any => {\n // Check for relation fields BEFORE the column check.\n // Relation fields don't have corresponding table columns.\n if (Array.isArray(value)) {\n const relations = relationMap?.[tableName];\n if (relations?.[key]) {\n const rel = relations[key]!;\n return remapToGraphQLArrayOutput(\n value,\n rel.targetTableName,\n (rel.relation as any)?.targetTable ?? (rel.relation as any)?.referencedTable,\n relationMap,\n );\n }\n }\n\n if (typeof value === 'object' && value !== null) {\n const relations = relationMap?.[tableName];\n if (relations?.[key]) {\n const rel = relations[key]!;\n const remapped = remapToGraphQLSingleOutput(\n value,\n rel.targetTableName,\n (rel.relation as any)?.targetTable ?? (rel.relation as any)?.referencedTable,\n relationMap,\n );\n return remapped;\n }\n }\n\n // For non-relation fields, require a column definition.\n if (!column) {\n return value;\n }\n\n // Columns whose output type is a scalar override hand the driver's raw value straight to\n // that scalar — serialization is wholly the scalar's job, and converting here first would\n // double-convert.\n if (getColumnScalarOverride(column, false)) {\n return value;\n }\n\n // JSON columns are carried by the `JSON` scalar, which transports the parsed value as-is.\n // This has to come before the array/object branches below, which would otherwise walk into\n // the value and remap its contents as if they were column values.\n if (isJsonColumn(column)) {\n return value;\n }\n\n // A `date` column read in drizzle's `'date'` mode arrives as a JS `Date` at UTC midnight;\n // the `Date` scalar transports the day it names, not the instant. An unrepresentable value\n // is left for the scalar to reject rather than silently reformatted.\n if (value instanceof Date && isDateOnlyColumn(column)) {\n return dateToCalendarDate(value) ?? value;\n }\n\n // A SQLite integer timestamp arrives as a `Date`: drizzle decodes it on every path the library\n // reads through, aggregates included (`min`/`max` are `mapWith(column)`). A row that skipped the\n // column's decoder (a hand-built one, say) holds the stored integer instead, in the column's own\n // unit — read it as that unit here, because the `DateTime` scalar reads any number as\n // milliseconds.\n if (typeof value === 'number' && isSQLiteTimestampColumn(column)) {\n const instant = sqliteTimestampToDate(column, value);\n return Number.isNaN(instant.getTime()) ? value : instant.toISOString();\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n // A MySQL `timestamp` / `datetime` read in `'string'` mode arrives as MySQL's offset-less text,\n // which the `DateTime` scalar does not accept; it names a UTC instant (see\n // `mySqlDateTimeTextToIso`).\n if (typeof value === 'string' && isMySqlDateTimeStringColumn(column)) {\n return mySqlDateTimeTextToIso(value);\n }\n\n // A Postgres `timestamp` read in `'string'` mode arrives as Postgres's own text, which the\n // `DateTime` scalar does not accept either (see `pgTimestampTextToIso`).\n if (typeof value === 'string' && isPgTimestampStringColumn(column)) {\n return pgTimestampTextToIso(value);\n }\n\n if (value instanceof Buffer) {\n return Array.from(value);\n }\n\n if (typeof value === 'bigint') {\n return value.toString();\n }\n\n if (Array.isArray(value)) {\n if (column.columnType === 'PgGeometry' || column.columnType === 'PgVector') {\n return value;\n }\n\n return value.map((arrVal) => remapToGraphQLCore(key, arrVal, tableName, column, relationMap));\n }\n\n if (typeof value === 'object' && value !== null) {\n if (column.columnType === 'PgGeometryObject') {\n return value;\n }\n\n return JSON.stringify(value);\n }\n\n return value;\n};\n\nexport const remapToGraphQLSingleOutput = (\n queryOutput: Record<string, any>,\n tableName: string,\n table: Table,\n relationMap?: Record<string, Record<string, TableNamedRelations>>,\n) => {\n const columns = getColumns(table);\n\n for (const [key, value] of Object.entries(queryOutput)) {\n if (value === undefined || value === null) {\n // Preserve an explicitly-null TO-ONE relation field (eager-loaded with no related\n // row) as null, so the relation's field resolver returns null directly instead of\n // re-querying it through the batch loader. Only to-one relations are nullable; a\n // to-many relation is a non-null list, so a null there must fall through to deletion\n // (the field resolver then resolves it to []) rather than be emitted as null.\n const relEntry = value === null ? relationMap?.[tableName]?.[key] : undefined;\n if (relEntry && is(relEntry.relation, One)) {\n queryOutput[key] = null;\n continue;\n }\n delete queryOutput[key];\n continue;\n }\n\n const column = columns[key];\n\n // SQLite blob(bigint) returns 0n for null DB values — treat as absent when nullable.\n if (value === 0n && column && (column as any).columnType === 'SQLiteBigInt' && !(column as any).notNull) {\n delete queryOutput[key];\n continue;\n }\n\n queryOutput[key] = remapToGraphQLCore(key, value, tableName, column, relationMap);\n }\n\n return queryOutput;\n};\n\nexport const remapToGraphQLArrayOutput = (\n queryOutput: Record<string, any>[],\n tableName: string,\n table: Table,\n relationMap?: Record<string, Record<string, TableNamedRelations>>,\n) => {\n for (const entry of queryOutput) {\n remapToGraphQLSingleOutput(entry, tableName, table, relationMap);\n }\n\n return queryOutput;\n};\n\nexport const remapFromGraphQLCore = (value: any, column: Column, columnName: string): any => {\n // `null` is SQL NULL whatever the column's type, so there is nothing to coerce — and the\n // coercing branches below would get it wrong rather than fail: `new Date(null)` is the\n // epoch, not an invalid date, and `BigInt(null)` throws. Whether the column may hold a\n // null is the caller's question (see `remapFromGraphQLSingleInput`), not this function's.\n if (value === null) {\n return null;\n }\n\n // Columns whose input type is a scalar override receive exactly what that scalar's\n // parseValue/parseLiteral produced — coercion is the scalar's job, so the value goes to\n // the driver untouched. Only the null-prototype normalization still applies (it undoes a\n // graphql-js artifact, not a coercion — see the default case below).\n if (getColumnScalarOverride(column, true)) {\n if (typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === null) {\n return Object.assign({}, value);\n }\n return value;\n }\n\n // drizzle-orm v1 uses compound dataType strings (e.g. \"object date\", \"bigint int64\").\n // We must check inclusion rather than equality to handle these cases.\n const dataType: string = (column as any).dataType ?? '';\n\n // Timestamp/datetime columns: Postgres and MySQL `timestamp`, MySQL `datetime` (either mode),\n // and SQLite's integer timestamps. Pure DATE columns are handled below.\n //\n // A SQLite integer timestamp takes the `Date`, which drizzle's `mapToDriverValue` turns into\n // the stored integer: milliseconds for `'timestamp_ms'`, and for `'timestamp'` whole seconds,\n // floored — `…T10:00:00.999Z` is stored, and read back, as `…T10:00:00Z`. Filter operands go\n // through here and the same encoder, so they are floored exactly as a write would be: `eq`\n // matches the row that input would have written.\n const columnType: string = (column as any).columnType ?? '';\n if (isDateTimeColumn(column)) {\n const isMySql = columnType.startsWith('MySql');\n const isPgString = isPgTimestampStringColumn(column);\n // MySQL / Postgres text with no offset is read as UTC, as on output — `new Date()` would read\n // it in the server's local zone. The `DateTime` scalar never produces it; an `entities` caller\n // might.\n const toIso = isMySql ? mySqlDateTimeTextToIso : isPgString ? pgTimestampTextToIso : undefined;\n const formatted = new Date(toIso && typeof value === 'string' ? toIso(value) : value);\n if (Number.isNaN(formatted.getTime())) {\n throw drizzleError(`Field '${columnName}' is not a valid date!`, { code: 'DRIZZLE_INVALID_INPUT_VALUE' });\n }\n\n // A `'string'`-mode MySQL column takes MySQL's own text, written in UTC. A `'date'`-mode\n // column takes the `Date`; drizzle's `mapToDriverValue` formats it with `toISOString`, so it\n // is written in UTC too rather than in mysql2's local-time formatting.\n //\n // A `'string'`-mode Postgres column takes a string, in the form its type reads without\n // ambiguity: `timestamptz` the ISO instant (`…Z`); `timestamp` the UTC wall time with no\n // offset, because Postgres silently drops an offset written to a `timestamp` column.\n if (isPgString) {\n return (column as any).withTimezone ? formatted.toISOString() : dateToUtcWallText(formatted);\n }\n return isMySqlDateTimeStringColumn(column) ? dateToUtcWallText(formatted) : formatted;\n }\n\n // Date-only columns, either drizzle mode. The `Date` scalar has already checked the value is\n // a `YYYY-MM-DD` calendar day, and that string is what goes to the driver for both modes:\n // drizzle passes a string through to a `'date'`-mode column untouched, and a string is the\n // one form that cannot be shifted by a timezone (mysql2 formats a JS `Date` in local time).\n // The check is repeated here because not every caller is the scalar — `entities` resolvers\n // can be called with hand-built args — and a JS `Date` from such a caller is read as the UTC\n // day it encodes, the same way the output side reads one.\n if (isDateOnlyColumn(column)) {\n // `date().array()` keeps the date column type with a `dimensions` count, so an array here\n // is a list of days, checked element by element.\n if (Array.isArray(value)) {\n return value.map((element) => remapFromGraphQLCore(element, column, columnName));\n }\n const day = value instanceof Date ? dateToCalendarDate(value) : value;\n if (typeof day !== 'string' || !isCalendarDate(day)) {\n throw drizzleError(`Field '${columnName}' is not a valid date! Expected a calendar date as YYYY-MM-DD.`, {\n code: 'DRIZZLE_INVALID_INPUT_VALUE',\n });\n }\n\n return day;\n }\n\n // BigInt columns (SQLite: \"bigint int64\", others: \"bigint\").\n if (dataType.includes('bigint')) {\n try {\n return BigInt(value);\n } catch {\n throw drizzleError(`Field '${columnName}' is not a BigInt!`, { code: 'DRIZZLE_INVALID_INPUT_VALUE' });\n }\n }\n\n // JSON columns (SQLite: \"object json\", PG: \"json\"). The `JSON` scalar has already parsed\n // the literal, so the value goes to the driver untouched — parsing it again here would\n // wrongly reject a JSON value that happens to be a string, like `\"hello\"`.\n // PgGeometryObject is already handled by the switch case below.\n if (dataType.includes('json') && (column as any).columnType !== 'PgGeometryObject') {\n return value;\n }\n\n switch (dataType) {\n case 'date': {\n const formatted = new Date(value);\n if (Number.isNaN(formatted.getTime())) {\n throw drizzleError(`Field '${columnName}' is not a valid date!`, { code: 'DRIZZLE_INVALID_INPUT_VALUE' });\n }\n\n return formatted;\n }\n\n case 'buffer': {\n if (!Array.isArray(value)) {\n throw drizzleError(`Field '${columnName}' is not an array!`, { code: 'DRIZZLE_INVALID_INPUT_VALUE' });\n }\n\n return Buffer.from(value);\n }\n\n case 'json': {\n if (column.columnType === 'PgGeometryObject') {\n return value;\n }\n\n try {\n return JSON.parse(value);\n } catch (e) {\n throw drizzleError(\n `Invalid JSON in field '${columnName}':\\n${e instanceof Error ? e.message : 'Unknown error'}`,\n {\n code: 'DRIZZLE_INVALID_INPUT_VALUE',\n },\n );\n }\n }\n\n case 'array': {\n if (!Array.isArray(value)) {\n throw drizzleError(`Field '${columnName}' is not an array!`, { code: 'DRIZZLE_INVALID_INPUT_VALUE' });\n }\n\n if (column.columnType === 'PgGeometry' && value.length !== 2) {\n throw drizzleError(\n `Invalid float tuple in field '${columnName}': expected array with length of 2, received ${value.length}`,\n { code: 'DRIZZLE_INVALID_INPUT_VALUE' },\n );\n }\n\n return value;\n }\n\n case 'bigint': {\n try {\n return BigInt(value);\n } catch (_error) {\n throw drizzleError(`Field '${columnName}' is not a BigInt!`, { code: 'DRIZZLE_INVALID_INPUT_VALUE' });\n }\n }\n\n default: {\n // graphql-js coerces input object types using Object.create(null), producing\n // null-prototype objects. Drizzle's internal is() check accesses\n // Object.getPrototypeOf(value).constructor and throws for null-prototype objects.\n // Convert to a plain object so drizzle can process it safely.\n if (typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === null) {\n return Object.assign({}, value);\n }\n return value;\n }\n }\n};\n\n/**\n * Which write an input is being remapped for. It decides one thing only: what an explicit\n * `null` means for a `notNull` column — see {@link remapFromGraphQLSingleInput}.\n */\nexport type RemapInputOperation = 'insert' | 'update';\n\nexport const remapFromGraphQLSingleInput = (\n queryInput: Record<string, any>,\n table: Table,\n operation: RemapInputOperation = 'insert',\n) => {\n const columns = getColumns(table);\n\n for (const [key, value] of Object.entries(queryInput)) {\n if (value === undefined) {\n delete queryInput[key];\n } else {\n const column = columns[key];\n if (!column) {\n throw drizzleError(`Unknown column: ${key}`, { code: 'DRIZZLE_UNKNOWN_COLUMN' });\n }\n\n // An explicit `null` for a column that cannot hold one reads differently on each side\n // of a write, because the generated input types mean different things by nullability.\n //\n // On INSERT a `notNull` column's field is only nullable when the database or drizzle\n // can fill it in — `defaultIsNullable` is passed for the create input, so the field is\n // non-null unless the column has a default, or a nested `create` supplies it. So the\n // only nulls that reach here are ones the schema itself offered as \"I am not supplying\n // this\", and dropping the key is what lets the default apply. That contract is pinned\n // by `upsert-null-key.test.ts` and `not-null-writes.test.ts`.\n //\n // On UPDATE every field is nullable — the update input forces it, whatever the column\n // — so nullability says nothing, and there is no default to fall back to. `null` can\n // only mean \"write null\", which this column cannot hold. Dropping it used to report\n // either a wrong success (the rest of the `set` landed, this column silently kept its\n // old value) or a misleading `DRIZZLE_NO_VALUES` when it was the only field.\n if (value === null && column.notNull) {\n if (operation === 'update') {\n throw drizzleError(`Column '${key}' cannot be set to null.`, { code: 'DRIZZLE_NOT_NULL' });\n }\n delete queryInput[key];\n continue;\n }\n\n queryInput[key] = remapFromGraphQLCore(value, column, key);\n }\n }\n\n return queryInput;\n};\n\nexport const remapFromGraphQLArrayInput = (\n queryInput: Record<string, any>[],\n table: Table,\n operation: RemapInputOperation = 'insert',\n) => {\n for (const entry of queryInput) {\n remapFromGraphQLSingleInput(entry, table, operation);\n }\n\n return queryInput;\n};\n","// Compiling one column's filter operators into SQL, including the LIKE escaping and the\n// JSON-path machinery the JSON operators are built on.\n\nimport type { Column } from 'drizzle-orm';\nimport {\n and,\n arrayContains,\n arrayOverlaps,\n eq,\n gt,\n gte,\n ilike,\n inArray,\n isNotNull,\n isNull,\n like,\n lt,\n lte,\n ne,\n not,\n notIlike,\n notInArray,\n notLike,\n or,\n type SQL,\n sql,\n} from 'drizzle-orm';\nimport { remapFromGraphQLCore } from '../../data-mappers/index.ts';\nimport type { FilterColumnOperators, FilterColumnOperatorsCore } from '../types.ts';\nimport { columnDialect, isJsonColumn } from './column-filters.ts';\nimport { drizzleError } from './errors.ts';\n\n/**\n * Escape character pinned via `ESCAPE` on every generated safe-LIKE predicate. Bound as a\n * query parameter (never spliced into the SQL text), so no dialect-specific string-literal\n * escaping rules apply to it.\n */\nconst LIKE_ESCAPE_CHAR = '\\\\';\n\n/**\n * Escapes the LIKE wildcards (`%`, `_`) and the escape character itself (`\\`) in a literal\n * search term, so the term only ever matches literally inside a LIKE pattern.\n */\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (char) => `\\\\${char}`);\n\n/**\n * The injection-safe string operators: the caller passes a literal search term, the library\n * builds the LIKE pattern with the term's `%` / `_` / `\\` escaped and the `ESCAPE` clause pinned.\n * The `i`-prefixed variants match case-insensitively.\n */\nconst safeLikeOps: Record<string, { buildPattern: (value: string) => string; insensitive: boolean }> = {\n startsWith: { buildPattern: (value) => `${escapeLikeValue(value)}%`, insensitive: false },\n endsWith: { buildPattern: (value) => `%${escapeLikeValue(value)}`, insensitive: false },\n contains: { buildPattern: (value) => `%${escapeLikeValue(value)}%`, insensitive: false },\n iStartsWith: { buildPattern: (value) => `${escapeLikeValue(value)}%`, insensitive: true },\n iEndsWith: { buildPattern: (value) => `%${escapeLikeValue(value)}`, insensitive: true },\n iContains: { buildPattern: (value) => `%${escapeLikeValue(value)}%`, insensitive: true },\n};\n\n/**\n * `LIKE <pattern> ESCAPE '\\'` for a safe string operator. Case-insensitive variants use\n * Postgres's native `ILIKE`; MySQL and SQLite have no `ILIKE`, so they compare `lower()`\n * on both sides instead (mirroring how the raw `ilike` operator is Postgres-only).\n */\nconst safeLikeCondition = (column: Column, pattern: string, insensitive: boolean): SQL => {\n if (!insensitive) {\n return sql`${column} like ${pattern} escape ${LIKE_ESCAPE_CHAR}`;\n }\n\n const isPg = (((column as any).columnType ?? '') as string).startsWith('Pg');\n return isPg\n ? sql`${column} ilike ${pattern} escape ${LIKE_ESCAPE_CHAR}`\n : sql`lower(${column}) like ${pattern.toLowerCase()} escape ${LIKE_ESCAPE_CHAR}`;\n};\n\n/**\n * The case-insensitive form of the raw `like` / `notLike` operators, whose operand is a\n * caller-written pattern rather than a literal. Postgres has `ILIKE`; the other two dialects\n * compare `lower()` on both sides, exactly as {@link safeLikeCondition} does.\n */\nconst insensitiveLike = (column: Column, pattern: string, negated: boolean): SQL => {\n if (columnDialect(column) === 'pg') {\n return negated ? notIlike(column, pattern) : ilike(column, pattern);\n }\n return negated ? sql`lower(${column}) not like lower(${pattern})` : sql`lower(${column}) like lower(${pattern})`;\n};\n\n/**\n * SQL spelling of each comparison operator, for the case-insensitive forms that have to be\n * written out rather than built by drizzle's `eq`/`ne`/`lt`/… helpers.\n */\nconst COMPARISON_SQL: Record<string, string> = { eq: '=', ne: '<>', lt: '<', lte: '<=', gt: '>', gte: '>=' };\n\n/**\n * `insensitive: true` folds case out of every comparison beside it by comparing\n * `lower(column)` against `lower(operand)`. Lowercasing both sides in SQL — rather than the\n * operand in JS — keeps the comparison under one collation, and `lower(column)` is an\n * expression a matching index can serve, which `ilike '%…%'` never can. It is the same\n * `lower()` the case-insensitive LIKE operators already fall back to on the dialects without\n * a native `ILIKE`, so it adds no dialect surface.\n */\nconst lowerComparison = (column: Column, operatorName: string, value: unknown): SQL =>\n sql`lower(${column}) ${sql.raw(COMPARISON_SQL[operatorName]!)} lower(${value})`;\n\n/** `lower(column) IN (lower($1), …)` / `NOT IN` — the case-insensitive `inArray`/`notInArray`. */\nconst lowerMembership = (column: Column, values: unknown[], negated: boolean): SQL => {\n const lowered = sql.join(\n values.map((value) => sql`lower(${value})`),\n sql`, `,\n );\n return negated ? sql`lower(${column}) not in (${lowered})` : sql`lower(${column}) in (${lowered})`;\n};\n\n/**\n * Structural JSON containment for the `contains` operator on json/jsonb columns.\n * The value is serialized and bound as a parameter (never interpolated into the SQL text):\n * - Postgres: `col @> $1::jsonb` (a plain `json` column is cast through jsonb — `json` has\n * no containment operator of its own)\n * - MySQL: `JSON_CONTAINS(col, ?)`\n * SQLite has no containment operator, so the filter input never exposes `contains` there;\n * reaching this with an unsupported dialect is a programming error surfaced as a GraphQLError.\n */\nconst jsonContains = (column: Column, columnName: string, value: any): SQL => {\n const serialized = JSON.stringify(value);\n\n switch (columnDialect(column)) {\n case 'pg':\n return (column as any).columnType === 'PgJson'\n ? sql`${column}::jsonb @> ${serialized}::jsonb`\n : sql`${column} @> ${serialized}::jsonb`;\n case 'mysql':\n return sql`json_contains(${column}, ${serialized})`;\n default:\n throw drizzleError(`WHERE ${columnName}: Operator 'contains' is not supported for this dialect!`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n};\n\n/**\n * Constant predicates, used where an operator's operand list is empty and the answer is\n * therefore known without touching the column. Written as `1 = 0` / `1 = 1` rather than the\n * `FALSE` / `TRUE` keywords so they compile identically on all three dialects. Built fresh\n * per call because a `SQL` object is spliced into whatever query consumes it.\n */\nconst sqlFalse = (): SQL => sql`1 = 0`;\nconst sqlTrue = (): SQL => sql`1 = 1`;\n\n/**\n * A MySQL / SQLite JSON path expression for the given key walk. Bound as a query parameter,\n * never spliced into the SQL text; an all-digits key becomes an array index, and quotes and\n * backslashes inside a key are escaped so a key can never end the path segment early.\n */\nconst jsonPathString = (path: string[]): string =>\n `$${path.map((part) => (/^\\d+$/.test(part) ? `[${part}]` : `.\"${part.replace(/([\"\\\\])/g, '\\\\$1')}\"`)).join('')}`;\n\n/**\n * Matches the text forms a database will accept as a number. Used to guard both numeric casts —\n * Postgres has no TRY_CAST and errors outright on a bad `::numeric`, while MySQL quietly casts\n * a non-numeric string to 0; neither is what a non-matching row should do.\n */\nconst NUMERIC_TEXT_PATTERN = '^\\\\s*-?(\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)([eE][-+]?\\\\d+)?\\\\s*$';\n\n/**\n * The value at a JSON path, as the expressions a comparison can be built on: read as text,\n * read as a number, and read as the dialect spells a boolean. Each dialect extracts\n * differently, and each needs its own guard so a value of the wrong shape answers \"no match\"\n * rather than erroring or comparing by some unrelated rule:\n *\n * - **Postgres** — `#>>` with a bound `text[]` path, which works on `json` and `jsonb` alike.\n * `::numeric` on a non-numeric string is a hard error, so the numeric read is guarded by a\n * pattern test.\n * - **MySQL** — `JSON_UNQUOTE(JSON_EXTRACT(col, ?))`, so a JSON string arrives without its\n * quotes. Unquoting a JSON *null* would otherwise yield the string `'null'`, so it is mapped\n * back to SQL NULL first. `CAST` quietly turns a non-numeric string into 0, hence the same\n * pattern guard.\n * - **SQLite** — `json_extract` returns the value in SQLite's own type, so the reads cast\n * explicitly: without that, SQLite's cross-type ordering puts every string above every\n * number and `'admin' > 0` would be true.\n */\nconst jsonPathExprs = (\n column: Column,\n path: string[],\n): { text: SQL; number: SQL; boolean: SQL; encodeBoolean: (value: boolean) => string | number } => {\n switch (columnDialect(column)) {\n case 'pg': {\n const pathArray = sql`array[${sql.join(\n path.map((part) => sql`${part}`),\n sql`, `,\n )}]::text[]`;\n const text = sql`(${column} #>> ${pathArray})`;\n return {\n text,\n number: sql`(case when ${text} ~ ${NUMERIC_TEXT_PATTERN} then ${text}::numeric end)`,\n boolean: text,\n encodeBoolean: (value) => String(value),\n };\n }\n case 'mysql': {\n const extracted = sql`json_extract(${column}, ${jsonPathString(path)})`;\n const text = sql`(case when json_type(${extracted}) = 'NULL' then null else json_unquote(${extracted}) end)`;\n return {\n text,\n number: sql`(case when ${text} regexp ${NUMERIC_TEXT_PATTERN} then cast(${text} as decimal(65, 30)) end)`,\n boolean: text,\n encodeBoolean: (value) => String(value),\n };\n }\n default: {\n const extracted = sql`json_extract(${column}, ${jsonPathString(path)})`;\n return {\n text: sql`cast(${extracted} as text)`,\n number: sql`(case when typeof(${extracted}) in ('integer', 'real') then ${extracted} end)`,\n // SQLite has no boolean type: a JSON `true` comes back as the integer 1.\n boolean: extracted,\n encodeBoolean: (value) => (value ? 1 : 0),\n };\n }\n }\n};\n\n/** Comparison operators available inside a JSON path filter, as their SQL spelling. */\nconst JSON_PATH_COMPARISONS: Record<string, string> = {\n eq: '=',\n ne: '<>',\n lt: '<',\n lte: '<=',\n gt: '>',\n gte: '>=',\n};\n\n/**\n * How the value at a path is read when the filter does not say: a GraphQL number compares\n * numerically, a boolean as a boolean, everything else as text.\n */\nconst inferJsonPathCast = (value: unknown): 'text' | 'number' | 'boolean' =>\n typeof value === 'number' ? 'number' : typeof value === 'boolean' ? 'boolean' : 'text';\n\n/**\n * Compiles one entry of a column's `path` filter: `as` (or the operand's own type) picks\n * which of {@link jsonPathExprs}' reads the comparison is built on, and the operand is bound\n * in the shape that read expects.\n */\nconst jsonPathCondition = (column: Column, columnName: string, filter: Record<string, any>): SQL | undefined => {\n const { path, as: castOverride, ...operators } = filter;\n const locator = `${columnName}.path`;\n\n if (!Array.isArray(path) || !path.length) {\n throw drizzleError(`WHERE ${locator}: 'path' must name at least one key`, { code: 'DRIZZLE_INVALID_FILTER' });\n }\n\n const exprs = jsonPathExprs(column, path);\n const variants: SQL[] = [];\n\n for (const [operatorName, operatorValue] of Object.entries(operators)) {\n if (operatorValue === null || operatorValue === undefined) {\n continue;\n }\n\n if (operatorName === 'isNull' || operatorName === 'isNotNull') {\n if (operatorValue === false) {\n continue;\n }\n variants.push(operatorName === 'isNull' ? sql`${exprs.text} is null` : sql`${exprs.text} is not null`);\n continue;\n }\n\n if (operatorName in safeLikeOps) {\n const { buildPattern, insensitive } = safeLikeOps[operatorName]!;\n if (typeof operatorValue !== 'string') {\n throw drizzleError(`WHERE ${locator}: operator '${operatorName}' takes a string`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n // The extracted value is an expression, not a column, so the case-insensitive form\n // always goes through `lower()` rather than Postgres's ILIKE.\n variants.push(safeLikeCondition(exprs.text as any, buildPattern(operatorValue), insensitive));\n continue;\n }\n\n const comparison = JSON_PATH_COMPARISONS[operatorName];\n if (!comparison) {\n throw drizzleError(`WHERE ${locator}: Unknown operator: ${operatorName}`, { code: 'DRIZZLE_INVALID_FILTER' });\n }\n\n const cast = castOverride ?? inferJsonPathCast(operatorValue);\n if (cast === 'number') {\n const numeric = Number(operatorValue);\n if (Number.isNaN(numeric)) {\n throw drizzleError(\n `WHERE ${locator}: operator '${operatorName}' compares as a number, so its value must be one`,\n { code: 'DRIZZLE_INVALID_FILTER' },\n );\n }\n variants.push(sql`${exprs.number} ${sql.raw(comparison)} ${numeric}`);\n } else if (cast === 'boolean') {\n const truthy = operatorValue === true || operatorValue === 'true';\n variants.push(sql`${exprs.boolean} ${sql.raw(comparison)} ${exprs.encodeBoolean(truthy)}`);\n } else {\n variants.push(sql`${exprs.text} ${sql.raw(comparison)} ${String(operatorValue)}`);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n\n// The operator dispatch tables. Constant, and hoisted out of `extractFiltersColumn` — which\n// recurses once per AND/OR/NOT branch of every filter of every request — so they are built\n// once per process rather than five objects per call.\nconst singleValueOps: Record<string, (...args: any[]) => SQL> = { eq, ne, gt, gte, lt, lte };\nconst stringValueOps: Record<string, (...args: any[]) => SQL> = { like, notLike, ilike, notIlike };\nconst arrayValueOps: Record<string, (...args: any[]) => SQL> = { inArray, notInArray };\n/** Membership operators for array columns: element list → SQL. Empty lists are rejected below. */\nconst arrayMembershipOps: Record<string, (...args: any[]) => SQL> = {\n hasSome: arrayOverlaps,\n hasEvery: arrayContains,\n};\nconst nullableOps: Record<string, (...args: any[]) => SQL> = { isNull, isNotNull };\n\nexport const extractFiltersColumn = <TColumn extends Column>(\n column: TColumn,\n columnName: string,\n operators: FilterColumnOperators<TColumn>,\n): SQL | undefined => {\n // Boolean branches compose with sibling operators: siblings and the AND list are ANDed\n // together, NOT negates its whole branch, and the OR group is ANDed with the rest.\n const { OR, AND, NOT, insensitive, ...restOperators } = operators;\n\n // `insensitive` is a modifier, not a predicate: it changes how the operators beside it\n // compile and contributes no condition of its own. It applies to this object only —\n // a nested AND/OR/NOT branch is a separate object and sets its own.\n const foldCase = insensitive === true;\n\n const entries = Object.entries(restOperators as FilterColumnOperatorsCore<TColumn>);\n\n const variants = [] as SQL[];\n for (const [operatorName, operatorValue] of entries) {\n if (operatorValue === null || operatorValue === false) {\n continue;\n }\n\n if (operatorName in singleValueOps) {\n const singleValue = remapFromGraphQLCore(operatorValue, column, columnName);\n variants.push(\n foldCase\n ? lowerComparison(column, operatorName, singleValue)\n : singleValueOps[operatorName]!(column, singleValue),\n );\n } else if (operatorName in stringValueOps) {\n // Under `insensitive`, `like`/`notLike` compile the same way their `i` counterparts\n // do; `ilike`/`notIlike` are already case-insensitive and are left alone.\n const insensitivePattern = foldCase && (operatorName === 'like' || operatorName === 'notLike');\n variants.push(\n insensitivePattern\n ? insensitiveLike(column, operatorValue as string, operatorName === 'notLike')\n : stringValueOps[operatorName]!(column, operatorValue as string),\n );\n } else if (operatorName === 'path' && isJsonColumn(column)) {\n // Several path predicates on one column are ANDed, matching how sibling operators\n // already combine. GraphQL coerces a lone object into a one-element list.\n for (const pathFilter of operatorValue as Record<string, any>[]) {\n const extracted = jsonPathCondition(column, columnName, pathFilter);\n if (extracted) {\n variants.push(extracted);\n }\n }\n } else if (operatorName === 'contains' && isJsonColumn(column)) {\n // `contains` is JSON containment on json/jsonb columns; on string columns it is the\n // safe substring operator handled by safeLikeOps below.\n variants.push(jsonContains(column, columnName, operatorValue));\n } else if (operatorName in safeLikeOps) {\n const { buildPattern, insensitive: alwaysInsensitive } = safeLikeOps[operatorName]!;\n variants.push(safeLikeCondition(column, buildPattern(operatorValue as string), alwaysInsensitive || foldCase));\n } else if (operatorName in arrayValueOps) {\n // An empty candidate list is a well-formed question with a known answer — nothing is\n // `IN ()`, everything is `NOT IN ()` — so it resolves to a constant predicate rather\n // than an error. SQL has no empty-list literal, hence the constant rather than `IN ()`.\n if (!(operatorValue as any[]).length) {\n variants.push(operatorName === 'inArray' ? sqlFalse() : sqlTrue());\n continue;\n }\n const arrayValue = (operatorValue as any[]).map((val) => remapFromGraphQLCore(val, column, columnName));\n variants.push(\n foldCase\n ? lowerMembership(column, arrayValue, operatorName === 'notInArray')\n : arrayValueOps[operatorName]!(column, arrayValue),\n );\n } else if (operatorName === 'has') {\n // Single-element membership: containment with a one-element array (`col @> ARRAY[value]`).\n variants.push(arrayContains(column, [operatorValue]));\n } else if (operatorName in arrayMembershipOps) {\n // Same reasoning as inArray/notInArray: overlapping with no elements is never true,\n // and every array contains all zero of them.\n if (!(operatorValue as any[]).length) {\n variants.push(operatorName === 'hasSome' ? sqlFalse() : sqlTrue());\n continue;\n }\n variants.push(arrayMembershipOps[operatorName]!(column, operatorValue as any[]));\n } else if (operatorName === 'isEmpty') {\n variants.push(sql`cardinality(${column}) = 0`);\n } else if (operatorName in nullableOps) {\n variants.push(nullableOps[operatorName]!(column));\n } else {\n // An unrecognized operator must throw rather than be dropped: when the generated\n // schema is stitched/merged with another schema, foreign operators (e.g. `equals`,\n // `contains`, `mode`) can pass input validation, and silently dropping them could\n // turn a constrained where into an unbounded one.\n throw drizzleError(`WHERE ${columnName}: Unknown operator: ${operatorName}`, { code: 'DRIZZLE_INVALID_FILTER' });\n }\n }\n\n if (AND?.length) {\n for (const variant of AND) {\n const extracted = extractFiltersColumn(column, columnName, variant);\n if (extracted) {\n variants.push(extracted);\n }\n }\n }\n\n if (NOT) {\n const extracted = extractFiltersColumn(column, columnName, NOT);\n // `not()` is typed `SQL | undefined` from drizzle-orm rc.5 on, `SQL` before it.\n const negated = extracted ? not(extracted) : undefined;\n if (negated) {\n variants.push(negated);\n }\n }\n\n if (OR?.length) {\n const orVariants = [] as SQL[];\n for (const variant of OR) {\n const extracted = extractFiltersColumn(column, columnName, variant);\n if (extracted) {\n orVariants.push(extracted);\n }\n }\n\n if (orVariants.length) {\n variants.push(orVariants.length > 1 ? or(...orVariants)! : orVariants[0]!);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n","// The named-relation map the builders work from, derived from drizzle-orm v1's relational\n// config, plus the factory signatures the dialect builders implement.\n\nimport type { Relation, Table } from 'drizzle-orm';\nimport { Column, getColumns, is } from 'drizzle-orm';\nimport type { GraphQLFieldResolver, GraphQLObjectType } from 'graphql';\nimport type { TableNamedRelations } from '../types.ts';\n\n/**\n * Shape of the relational config from drizzle-orm v1 db._.relations.\n * Each entry has { table, name, relations }.\n */\ninterface TableRelationalConfig {\n table: Table;\n name: string;\n relations: Record<string, Relation<string>>;\n}\nexport type TablesRelationalConfig = Record<string, TableRelationalConfig>;\n\n/**\n * Flatten drizzle-orm v1 TablesRelationalConfig into the canonical\n * Record<tableName, Record<relName, TableNamedRelations>> shape used\n * throughout common.ts. Both pg.ts and sqlite.ts call this before\n * passing the relation map to any shared function.\n */\nexport const buildNamedRelations = (\n relations: TablesRelationalConfig,\n tableEntries: [string, Table][],\n): Record<string, Record<string, TableNamedRelations>> => {\n const namedRelations: Record<string, Record<string, TableNamedRelations>> = {};\n\n for (const [relTableName, relConfig] of Object.entries(relations)) {\n if (!relConfig?.relations) {\n continue;\n }\n\n const namedConfig: Record<string, TableNamedRelations> = {};\n\n for (const [innerRelName, innerRelValue] of Object.entries(relConfig.relations)) {\n // drizzle-orm v1 uses `targetTable` (not `referencedTable`)\n // and provides `targetTableName` directly.\n const targetTable = (innerRelValue as any).targetTable ?? (innerRelValue as any).referencedTable;\n const directTargetName = (innerRelValue as any).targetTableName as string | undefined;\n\n let targetTableName: string | undefined;\n\n if (directTargetName) {\n // v1: use the direct name to find the schema key\n const targetEntry = tableEntries.find(([key]) => key === directTargetName);\n targetTableName = targetEntry?.[0];\n } else if (targetTable) {\n // fallback: match by object reference\n const targetEntry = tableEntries.find(([, tableValue]) => tableValue === targetTable);\n targetTableName = targetEntry?.[0];\n }\n\n if (!targetTableName) {\n continue;\n }\n\n namedConfig[innerRelName] = {\n relation: innerRelValue,\n targetTableName,\n };\n }\n\n if (Object.keys(namedConfig).length > 0) {\n namedRelations[relTableName] = namedConfig;\n }\n }\n\n return namedRelations;\n};\n\n/**\n * Records each relation's target-table primary-key property names on the relation entry,\n * so the pagination paths (the window-function batch loader and the eager `with:` orderBy\n * default) can fall back to a deterministic PK order without re-deriving it per request.\n *\n * Composite primary keys are only visible through the dialect's getTableConfig, so the\n * dialect builder passes a `resolvePkNames` that threads the composite column names in.\n * Mutates the relation entries in place (they are shared with the pruned eager map and\n * the resolver factory, so attaching once covers every consumer).\n */\nexport const attachTargetPrimaryKeys = (\n namedRelations: Record<string, Record<string, TableNamedRelations>>,\n tables: Record<string, Table>,\n resolvePkNames: (table: Table) => string[],\n): void => {\n const cache = new Map<string, readonly string[]>();\n for (const rels of Object.values(namedRelations)) {\n for (const relEntry of Object.values(rels)) {\n const { targetTableName } = relEntry;\n let pk = cache.get(targetTableName);\n if (!pk) {\n const targetTable = tables[targetTableName];\n pk = targetTable ? resolvePkNames(targetTable) : [];\n cache.set(targetTableName, pk);\n }\n relEntry.targetPkNames = pk;\n }\n }\n};\n\n/**\n * The table column behind one entry of a relation's `sourceColumns`, `targetColumns` or\n * `through` lists.\n *\n * drizzle-orm rc.4 stores the table's own Column objects in `sourceColumns` / `targetColumns`\n * and a `RelationsBuilderColumn` descriptor (`{ _: { column, key, tableName } }`) in `through`.\n * The rc.5 snapshots store the descriptor in all of them. Both shapes are accepted here, told\n * apart structurally rather than by importing a class one of those versions does not export.\n * Anything else yields `undefined`, which callers treat as \"join columns not readable\".\n */\nexport const unwrapRelationColumn = (entry: unknown): Column | undefined => {\n if (is(entry, Column)) {\n return entry;\n }\n const inner = (entry as any)?._?.column;\n return is(inner, Column) ? inner : undefined;\n};\n\n/**\n * A relation's `sourceColumns` or `targetColumns` as table columns, via\n * {@link unwrapRelationColumn}. `undefined` when the list is missing, empty, or has an entry\n * that is not a column in either known shape.\n */\nexport const relationColumns = (relation: unknown, side: 'source' | 'target'): Column[] | undefined => {\n const entries: unknown[] | undefined = (relation as any)?.[side === 'source' ? 'sourceColumns' : 'targetColumns'];\n if (!entries?.length) {\n return undefined;\n }\n const columns: Column[] = [];\n for (const entry of entries) {\n const column = unwrapRelationColumn(entry);\n if (!column) {\n return undefined;\n }\n columns.push(column);\n }\n return columns;\n};\n\n/**\n * drizzle-orm's \"no filter\" sentinel. rc.5 snapshots export it as `EmptyFilter` and use it as\n * the default `relation.where`; rc.4 has no such export and leaves `where` undefined. It is a\n * registered symbol, so it can be compared against without importing anything.\n */\nconst EMPTY_FILTER = Symbol.for('drizzle:EmptyFilter');\n\n/**\n * The relation's own declared `where` filter, or `undefined` when it has none. rc.4 leaves\n * `where` undefined in that case; rc.5 snapshots set it to the `EmptyFilter` sentinel, which is\n * truthy and must not be read as a filter.\n */\nexport const relationOwnWhere = (relation: unknown): Record<string, unknown> | undefined => {\n const where = (relation as any)?.where;\n return where == null || where === EMPTY_FILTER ? undefined : where;\n};\n\n/**\n * Whether the relation's `where` was inherited from its reverse relation, and so is written\n * against the parent table rather than the target. rc.4 calls this flag `isReversed`; rc.5\n * snapshots renamed it to `isFilterReversed`. Both are set in the same place with the same\n * meaning (true only for a relation declared without `from`/`to` and without its own `where`).\n */\nexport const isRelationFilterReversed = (relation: unknown): boolean =>\n !!((relation as any)?.isFilterReversed ?? (relation as any)?.isReversed);\n\n/**\n * Warns, at build time, that a field was left out because the relation's join columns could\n * not be matched to its tables. Omitting it silently is how a drizzle-orm change in the shape\n * of relation columns (issue #179) went unnoticed. A relation that declares no join columns\n * is not reported: there is nothing that failed to match.\n */\nexport const warnUnresolvedJoin = (\n relEntry: TableNamedRelations,\n tableName: string,\n relationName: string,\n omitted: string,\n): void => {\n const rel = (relEntry as any).relation ?? relEntry;\n if (!rel?.sourceColumns?.length || !rel?.targetColumns?.length) {\n return;\n }\n console.warn(\n `Drizzle-GraphQL Warning: relation '${tableName}.${relationName}' declares join columns that could not be matched to columns of '${tableName}' and '${relEntry.targetTableName}', so ${omitted} is not generated. The installed drizzle-orm probably stores relation columns in a shape this version of drizzle-graphql does not recognize.`,\n );\n};\n\n/**\n * Extracts the join column info from a drizzle-orm v1 Relation object.\n * Returns the JS property name of the local column on the parent table and the\n * Column object for the foreign column on the target table, or undefined if the\n * relation internals are not accessible.\n */\nexport const extractRelationJoinColumns = (\n relEntry: TableNamedRelations,\n parentTable: Table,\n targetTable: Table,\n): { localColPropName: string; foreignCol: Column; foreignColPropName: string } | undefined => {\n const rel = (relEntry as any).relation ?? relEntry;\n const sourceCol = relationColumns(rel, 'source')?.[0];\n const targetCol = relationColumns(rel, 'target')?.[0];\n\n if (!sourceCol || !targetCol) {\n return undefined;\n }\n\n const parentCols = getColumns(parentTable);\n const localColPropName = Object.entries(parentCols).find(([, c]) => c === sourceCol)?.[0];\n\n const targetCols = getColumns(targetTable);\n const foreignColPropName = Object.entries(targetCols).find(([, c]) => c === targetCol)?.[0];\n\n if (!localColPropName || !foreignColPropName) {\n return undefined;\n }\n\n return { localColPropName, foreignCol: targetCol, foreignColPropName };\n};\n\nexport type RelationResolverFactory = (params: {\n tableName: string;\n relationName: string;\n relEntry: TableNamedRelations;\n isOne: boolean;\n}) => GraphQLFieldResolver<any, any> | undefined;\n\n/**\n * Builds the `${relationName}Aggregate` field for a to-many relation. Implemented in\n * `aggregates.ts` and injected here so the aggregate code can depend on this module\n * without the two importing each other.\n */\nexport type RelationAggregateFactory = (params: {\n tableName: string;\n relationName: string;\n relEntry: TableNamedRelations;\n}) => { type: GraphQLObjectType; resolve: GraphQLFieldResolver<any, any> } | undefined;\n\n/**\n * Whether a to-one relation can back a relation orderBy hop. `.through()` (junction)\n * relations are excluded — the ordering subquery only joins the direct target, never the\n * junction table. (Relation *filters* do support `.through()` — this guard is orderBy-only.)\n */\nexport const isFilterableRelation = (relation: Relation<string>): boolean => !(relation as any).through;\n","// The `exclude` config. Which columns a table hides, and the cache key that keeps two tables\n// excluding different columns from sharing a generated type.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { getColumns } from 'drizzle-orm';\n\n/**\n * Columns this build keeps out of the generated schema, keyed by the table object.\n *\n * A registry rather than a threaded parameter because the sites that decide schema shape —\n * the object type, every input, the filter, `orderBy`, the aggregates, the column enums —\n * are spread across four files and reach a table with no config in hand. Runtime code keeps\n * calling `getColumns` directly: a primary key that a client cannot name is still the key a\n * cursor is built from, and hiding it there would break pagination rather than secure it.\n *\n * {@link registerColumnExclusions} runs on every build, including with no config, so a\n * second build against the same table objects never inherits the first build's exclusions.\n */\nconst excludedColumnRegistry = new WeakMap<object, Set<string>>();\n\n/** Installs this build's column exclusions and clears any left by a previous build. */\nexport const registerColumnExclusions = (\n tables: Record<string, Table>,\n exclude?: { columns?: Record<string, string[]> },\n): void => {\n for (const [tableName, table] of Object.entries(tables)) {\n const hidden = exclude?.columns?.[tableName];\n if (hidden?.length) {\n excludedColumnRegistry.set(table, new Set(hidden));\n } else {\n excludedColumnRegistry.delete(table);\n }\n }\n};\n\n/** Whether any column of this table was excluded from the schema. */\nexport const hasExcludedColumns = (table: Table): boolean => excludedColumnRegistry.has(table);\n\n/**\n * A stable string naming this build's exclusions for `table`, empty when it has none. Used to\n * key the caches that hold generated types: two builds of the same table objects with\n * different exclusions must not share an entry, but *within* one build every call site has to\n * get the same instance back or the schema ends up with two types of the same name.\n */\nexport const excludedColumnsKey = (table: Table): string => {\n const hidden = excludedColumnRegistry.get(table);\n return hidden ? [...hidden].sort().join(',') : '';\n};\n\n/**\n * The columns of `table` that this build exposes — every column unless some were excluded.\n * Use this anywhere the result decides what the *schema* contains; use `getColumns` where it\n * decides what SQL to write.\n */\nexport const visibleColumns = (table: Table): Record<string, Column> => {\n const columns = getColumns(table);\n const hidden = excludedColumnRegistry.get(table);\n if (!hidden) {\n return columns;\n }\n return Object.fromEntries(Object.entries(columns).filter(([columnName]) => !hidden.has(columnName)));\n};\n","// Table key to GraphQL type name, through the caller's `typeNameMapper`.\n\nimport { capitalize } from '../../case-ops/index.ts';\nimport type { TypeNameResolver } from './type-names.ts';\n\n/** Optional mapper from table key to singular/plural name pair. Return undefined to use default naming for a table. */\nexport type TypeNameMapper = (tableName: string) => { singular: string; plural: string } | undefined;\n\n/** Produce the GraphQL object type name for a table, using the mapper if provided. */\nexport const resolveTypeName = (name: string, typeNameMapper?: TypeNameMapper): string => {\n const mapped = typeNameMapper?.(name);\n return mapped ? capitalize(mapped.singular) : capitalize(name);\n};\n\n/**\n * The name a table's object type actually carries in the built schema — {@link resolveTypeName}\n * put through the build's naming rule. Resolvers read selections out of\n * `fieldsByTypeName`, which is keyed by the real type name, so anything that walks a\n * selection tree has to ask for the name this way rather than assuming the default.\n */\nexport const resolveObjectTypeName = (\n name: string,\n typeNameMapper?: TypeNameMapper,\n resolveName?: TypeNameResolver,\n): string => applyObjectTypeName(resolveTypeName(name, typeNameMapper), name, resolveName);\n\n/** {@link resolveObjectTypeName} for a caller that already holds the table's default type name. */\nexport const applyObjectTypeName = (defaultName: string, tableName: string, resolveName?: TypeNameResolver): string =>\n resolveName ? resolveName({ kind: 'object', defaultName, table: tableName }) : defaultName;\n","// A table's compound unique constraints as `where` fields: the input a lookup by natural key\n// is spelled with, and the SQL it compiles to.\n//\n// The library already knows every unique constraint — `onConflict`'s `target` is validated\n// against them — but only on the write side. A read by a two-column natural key had to be\n// spelled as two ordinary filters, which reads as a partial filter that happens to return one\n// row, and stays valid when half of it goes missing. A key field says the same thing in one\n// place, with every member required.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { and, eq, getColumns, type SQL } from 'drizzle-orm';\nimport { GraphQLInputObjectType, GraphQLNonNull } from 'graphql';\nimport { capitalize } from '../../case-ops/index.ts';\nimport { remapFromGraphQLCore } from '../../data-mappers/index.ts';\nimport { drizzleColumnToGraphQLType } from '../../type-converter/index.ts';\nimport type { ConvertedInputColumn, NullableConvertedColumnType } from '../../type-converter/types.ts';\nimport { drizzleError } from './errors.ts';\nimport { visibleColumns } from './exclusions.ts';\nimport type { TypeNameMapper } from './naming.ts';\nimport { resolveTypeName } from './naming.ts';\nimport type { TypeCacheCtx } from './type-cache.ts';\n\n/** A table's unique-key `where` fields: field name → the constraint's member property names. */\nexport type UniqueKeyMap = Record<string, readonly string[]>;\n\n/** The field a constraint is offered under: its member property names, in declaration order. */\nexport const uniqueKeyFieldName = (members: readonly string[]): string => members.join('_');\n\n/**\n * Which of a table's unique constraints get a `where` field.\n *\n * Single-column constraints are left out — `eq` on the column already says \"the row with this\n * key\", and a wrapper around one value would only be a second way to spell it. A set whose\n * field name is taken by a column or a relation is left out too: the existing field keeps the\n * name, exactly as a relation yields to a same-named column.\n *\n * @param taken names already claimed on the table's filter input (columns, then relations)\n */\nexport const buildUniqueKeyMap = (sets: readonly string[][], taken: ReadonlySet<string>): UniqueKeyMap => {\n const map: Record<string, readonly string[]> = {};\n for (const set of sets) {\n if (set.length < 2) {\n continue;\n }\n const fieldName = uniqueKeyFieldName(set);\n if (taken.has(fieldName) || fieldName in map) {\n continue;\n }\n map[fieldName] = set;\n }\n return map;\n};\n\n/**\n * The `where` fields for a table's compound unique constraints, one input type per constraint.\n *\n * Every member is non-null, which is the whole point: a half-supplied key is a query-validation\n * error rather than a filter that quietly matches more rows than the caller meant it to.\n */\nexport const generateUniqueKeyFilterFields = (\n table: Table,\n tableName: string,\n uniqueKeys: UniqueKeyMap,\n typeNameMapper: TypeNameMapper | undefined,\n cacheCtx: TypeCacheCtx,\n): Record<string, ConvertedInputColumn> => {\n const columns = visibleColumns(table) as Record<string, Column>;\n const typeName = resolveTypeName(tableName, typeNameMapper);\n const fields: Record<string, ConvertedInputColumn> = {};\n\n for (const [fieldName, members] of Object.entries(uniqueKeys)) {\n fields[fieldName] = {\n type: new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'uniqueKey',\n defaultName: `${typeName}${members.map((member) => capitalize(member)).join('')}Key`,\n table: tableName,\n operation: fieldName,\n }),\n description: `The unique constraint on ${members.join(' + ')} of ${typeName}. Every field is required — a half-supplied key is an error, not a broader filter.`,\n fields: Object.fromEntries(\n members.map((member) => [\n member,\n {\n // `forceNullable` is on, so the conversion never returns an already-wrapped type;\n // the cast is only to narrow the union graphql 17 refuses to wrap.\n type: new GraphQLNonNull(\n drizzleColumnToGraphQLType(columns[member]!, member, tableName, true, false, true)\n .type as NullableConvertedColumnType<true>,\n ),\n },\n ]),\n ),\n }),\n description: `The one ${typeName} row holding this ${members.join(' + ')} key. ANDed with any sibling filters.`,\n } as ConvertedInputColumn;\n }\n\n return fields;\n};\n\n/**\n * Compiles a unique-key field into the equality on each member column. Identical to the\n * filters it replaces — the guarantee is in the input type, not in the SQL.\n */\nexport const extractUniqueKeyFilter = (\n table: Table,\n tableName: string,\n fieldName: string,\n members: readonly string[],\n value: Record<string, any>,\n): SQL | undefined => {\n const columns = getColumns(table) as Record<string, Column>;\n const conditions: SQL[] = [];\n\n for (const member of members) {\n const column = columns[member];\n const supplied = value?.[member];\n // Unreachable through the generated input, whose members are all non-null. Reachable when\n // the same-named input arrives from a stitched schema that spells the key differently, and\n // a key missing a column is not the key.\n if (!column || supplied === undefined || supplied === null) {\n throw drizzleError(`WHERE ${tableName}: ${fieldName} is missing ${member}, so it does not name a row.`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n conditions.push(eq(column, remapFromGraphQLCore(supplied, column, member)));\n }\n\n return conditions.length > 1 ? and(...conditions) : conditions[0];\n};\n","// Relation keys inside a `where`: the correlated EXISTS subquery each `some` / `none` / `every`\n// compiles to, and `extractFilters`, which dispatches a whole filter object across columns,\n// boolean groups and relations.\n\nimport type { Column, Relation, Table } from 'drizzle-orm';\nimport {\n aliasedTable,\n and,\n eq,\n getColumns,\n getTableAsAliasSQL,\n is,\n not,\n One,\n or,\n relationsFilterToSQL,\n type SQL,\n sql,\n} from 'drizzle-orm';\nimport type { FilterColumnOperatorsCore, Filters, TableNamedRelations } from '../types.ts';\nimport { drizzleError } from './errors.ts';\nimport { extractFiltersColumn } from './filters.ts';\nimport { isRelationFilterReversed, relationColumns, relationOwnWhere, unwrapRelationColumn } from './relations.ts';\nimport type { UniqueKeyMap } from './unique-keys.ts';\nimport { extractUniqueKeyFilter } from './unique-keys.ts';\n\n/**\n * Everything `extractFilters` needs to turn a relation key in a `where` argument into a\n * correlated subquery. Omitted by callers that don't generate relation filters, in which case\n * relation keys can't appear in the input to begin with.\n */\nexport interface RelationFilterContext {\n /** Every table in the schema, keyed by its schema key. */\n tables: Record<string, Table>;\n /** Relations keyed by table schema key, then relation name. */\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n /**\n * Schema key of the table being filtered. Not always the same as the `tableName` label\n * used in error messages (relation `where` callbacks pass the relation name there).\n */\n tableKey: string;\n /** Shared counter making every subquery alias unique within one extraction. */\n aliases?: { n: number };\n /**\n * The compound-unique-key `where` fields of each table, keyed by table schema key. Only\n * populated when `features.uniqueKeyFilters` generated them — a key field the build did not\n * generate is an unknown filter key like any other.\n */\n uniqueKeys?: Record<string, UniqueKeyMap>;\n}\n\n/**\n * The build-scoped half of {@link RelationFilterContext}. Created once per generated schema and\n * handed to every resolver, which adds the table it is filtering.\n */\nexport type RelationFilterBase = Pick<RelationFilterContext, 'tables' | 'relationMap' | 'uniqueKeys'>;\n\n/**\n * The narrowed contexts already handed out, keyed by the build-scoped base and then by\n * table. The base is created once per `buildSchema` and the result depends on nothing else,\n * so every call for one table produces the same value — a `WeakMap` on the base keeps them\n * for exactly as long as that build is reachable.\n */\nconst narrowedCtxCache = new WeakMap<RelationFilterBase, Map<string, RelationFilterContext>>();\n\n/**\n * Narrows the build-scoped relation filter context to the table a resolver is filtering.\n *\n * Cached rather than rebuilt: the base carries the build's whole `tables` and `relationMap`,\n * and the spread copied both on every call — three per parent row in the lazy relation\n * resolver, one per parent row in the relation aggregate, and up to four per select, several\n * of them inside callbacks drizzle invokes lazily.\n *\n * The one field written after the fact is `aliases`, the counter that keeps subquery aliases\n * apart ({@link extractRelationFilter}). Sharing it is what makes the caching safe rather\n * than a hazard: the counter now spans the process instead of restarting per extraction, and\n * aliases only ever have to be unique *within* one statement, which a number that never\n * repeats gives more surely than one that restarts.\n */\nexport const relationFilterCtx = (\n base: RelationFilterBase | undefined,\n tableKey: string,\n): RelationFilterContext | undefined => {\n if (!base) {\n return undefined;\n }\n\n let byTable = narrowedCtxCache.get(base);\n if (!byTable) {\n byTable = new Map();\n narrowedCtxCache.set(base, byTable);\n }\n\n let ctx = byTable.get(tableKey);\n if (!ctx) {\n ctx = { ...base, tableKey };\n byTable.set(tableKey, ctx);\n }\n\n return ctx;\n};\n\n/** The three ways a to-many relation can be required to match, plus the to-one shorthand. */\ntype RelationMatchMode = 'some' | 'none' | 'every';\n\n/**\n * Correlates the parent row with the aliased target table using the relation's own join\n * columns. Columns are matched by SQL name rather than object identity so this also works when\n * the parent is an aliased proxy (as it is inside a relational `with:` where callback).\n */\nexport const buildRelationJoinCondition = (\n parentTable: Table,\n relation: Relation<string>,\n aliasedTarget: Table,\n relationName: string,\n): SQL | undefined => {\n const sourceColumns = relationColumns(relation, 'source');\n const targetColumns = relationColumns(relation, 'target');\n\n if (!sourceColumns?.length || sourceColumns.length !== targetColumns?.length) {\n throw drizzleError(`WHERE ${relationName}: Relation cannot be used as a filter`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n\n const parentColumns = Object.values(getColumns(parentTable));\n const targetColumnsByName = Object.values(getColumns(aliasedTarget));\n\n const conditions: SQL[] = [];\n for (let i = 0; i < sourceColumns.length; i++) {\n const localColumn = parentColumns.find((c) => c.name === sourceColumns[i]!.name);\n const foreignColumn = targetColumnsByName.find((c) => c.name === targetColumns[i]!.name);\n\n if (!localColumn || !foreignColumn) {\n throw drizzleError(`WHERE ${relationName}: Relation cannot be used as a filter`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n\n conditions.push(eq(localColumn, foreignColumn));\n }\n\n return conditions.length > 1 ? and(...conditions) : conditions[0];\n};\n\n/**\n * Resolves one side of a `.through()` junction pair to the corresponding column on the\n * aliased junction table. Drizzle stores the junction column as a RelationsBuilderColumn\n * (`_.column` is the Column, `_.key` its property name), so look up by property name first\n * and fall back to matching by SQL name.\n */\nconst resolveJunctionColumn = (aliasedThrough: Table, junctionRef: any, relationName: string): Column => {\n const throughColumns = getColumns(aliasedThrough);\n\n const key: string | undefined = junctionRef?._?.key;\n const byKey = key ? throughColumns[key] : undefined;\n if (byKey) {\n return byKey;\n }\n\n const columnName: string | undefined = unwrapRelationColumn(junctionRef)?.name;\n const byName = columnName ? Object.values(throughColumns).find((c) => c.name === columnName) : undefined;\n if (!byName) {\n throw drizzleError(`WHERE ${relationName}: Relation cannot be used as a filter`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n\n return byName;\n};\n\n/**\n * Join conditions for a `.through()` (many-to-many) relation, split into the two legs of the\n * junction: `correlation` ties the parent row to the aliased junction table on the relation's\n * source keys, `junctionJoin` ties the aliased junction table to the aliased target on the\n * target keys. Column matching mirrors {@link buildRelationJoinCondition} — by SQL name on the\n * parent/target so aliased proxies work — while junction columns come from the relation's own\n * `through` metadata.\n */\nconst buildThroughJoinConditions = (\n parentTable: Table,\n relation: Relation<string>,\n aliasedThrough: Table,\n aliasedTarget: Table,\n relationName: string,\n): { correlation: SQL | undefined; junctionJoin: SQL | undefined } => {\n const sourceColumns = relationColumns(relation, 'source');\n const targetColumns = relationColumns(relation, 'target');\n const through = (relation as any).through as { source: any[]; target: any[] } | undefined;\n\n if (\n !sourceColumns?.length ||\n !targetColumns?.length ||\n through?.source.length !== sourceColumns.length ||\n through.target.length !== targetColumns.length\n ) {\n throw drizzleError(`WHERE ${relationName}: Relation cannot be used as a filter`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n\n const parentColumns = Object.values(getColumns(parentTable));\n const targetTableColumns = Object.values(getColumns(aliasedTarget));\n\n const correlationConditions: SQL[] = [];\n for (let i = 0; i < sourceColumns.length; i++) {\n const localColumn = parentColumns.find((c) => c.name === sourceColumns[i]!.name);\n if (!localColumn) {\n throw drizzleError(`WHERE ${relationName}: Relation cannot be used as a filter`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n correlationConditions.push(eq(localColumn, resolveJunctionColumn(aliasedThrough, through.source[i], relationName)));\n }\n\n const junctionJoinConditions: SQL[] = [];\n for (let i = 0; i < targetColumns.length; i++) {\n const foreignColumn = targetTableColumns.find((c) => c.name === targetColumns[i]!.name);\n if (!foreignColumn) {\n throw drizzleError(`WHERE ${relationName}: Relation cannot be used as a filter`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n junctionJoinConditions.push(\n eq(resolveJunctionColumn(aliasedThrough, through.target[i], relationName), foreignColumn),\n );\n }\n\n return {\n correlation: correlationConditions.length > 1 ? and(...correlationConditions) : correlationConditions[0],\n junctionJoin: junctionJoinConditions.length > 1 ? and(...junctionJoinConditions) : junctionJoinConditions[0],\n };\n};\n\n/**\n * Builds one `[NOT] EXISTS (SELECT 1 FROM target alias WHERE …)` for a relation filter.\n * A `.through()` (many-to-many) relation adds an `INNER JOIN` on the aliased junction table\n * inside the subquery, correlated to the parent on the relation's source keys.\n *\n * `some` / the to-one shorthand match when a related row satisfies the inner filters, `none`\n * when none does, and `every` is expressed as \"no related row fails the inner filters\".\n * Because `every` negates the inner condition, a related row whose compared column is NULL\n * counts as matching (SQL three-valued logic) — the same caveat Prisma carries.\n */\nconst buildRelationExists = (\n parentTable: Table,\n relationName: string,\n relEntry: TableNamedRelations,\n innerFilters: Filters<Table> | undefined,\n mode: RelationMatchMode,\n ctx: RelationFilterContext,\n): SQL | undefined => {\n const { targetTableName } = relEntry;\n const targetTable = ctx.tables[targetTableName];\n const relation = ((relEntry as any).relation ?? relEntry) as Relation<string>;\n\n if (!targetTable) {\n throw drizzleError(`WHERE ${relationName}: Relation cannot be used as a filter`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n\n ctx.aliases ??= { n: 0 };\n const aliases = ctx.aliases;\n const aliasedTarget = aliasedTable(targetTable, `dgql_rel_${aliases.n++}`);\n\n // A `.through()` relation reaches the target via a junction table: the subquery joins the\n // aliased junction to the aliased target and correlates the junction to the parent, so\n // `some` / `none` / `every` compile exactly like the direct case with a longer FROM clause.\n const throughTable = (relation as any).throughTable as Table | undefined;\n let fromClause: SQL;\n let joinCondition: SQL | undefined;\n if (throughTable) {\n const aliasedThrough = aliasedTable(throughTable, `dgql_rel_${aliases.n++}`);\n const { correlation, junctionJoin } = buildThroughJoinConditions(\n parentTable,\n relation,\n aliasedThrough,\n aliasedTarget,\n relationName,\n );\n fromClause = sql`${getTableAsAliasSQL(aliasedTarget)} inner join ${getTableAsAliasSQL(aliasedThrough)} on ${junctionJoin}`;\n joinCondition = correlation;\n } else {\n fromClause = getTableAsAliasSQL(aliasedTarget);\n joinCondition = buildRelationJoinCondition(parentTable, relation, aliasedTarget, relationName);\n }\n\n // A relation declared with its own `where` only ever exposes the rows it selects, so the\n // subquery has to honour it too — otherwise a filter could match a row the relation hides.\n const ownWhere = relationOwnWhere(relation);\n const relationWhere = ownWhere\n ? relationsFilterToSQL(isRelationFilterReversed(relation) ? parentTable : aliasedTarget, ownWhere as any)\n : undefined;\n\n const inner = innerFilters\n ? extractFilters(aliasedTarget, targetTableName, innerFilters, { ...ctx, tableKey: targetTableName, aliases })\n : undefined;\n\n if (mode === 'every') {\n // \"every related row matches\" with no inner condition is vacuously true.\n if (!inner) {\n return undefined;\n }\n\n return sql`not exists (select 1 from ${fromClause} where ${and(joinCondition, relationWhere, not(inner))})`;\n }\n\n const condition = and(joinCondition, relationWhere, inner);\n\n return mode === 'none'\n ? sql`not exists (select 1 from ${fromClause} where ${condition})`\n : sql`exists (select 1 from ${fromClause} where ${condition})`;\n};\n\n/**\n * Handles one relation key in a `where` argument. To-one relations take the target's filters\n * inline; to-many relations take any combination of `some` / `none` / `every`, ANDed together.\n */\nconst extractRelationFilter = (\n parentTable: Table,\n relationName: string,\n relEntry: TableNamedRelations,\n value: Record<string, any>,\n ctx: RelationFilterContext,\n): SQL | undefined => {\n const relation = ((relEntry as any).relation ?? relEntry) as Relation<string>;\n\n if (is(relation, One)) {\n return buildRelationExists(parentTable, relationName, relEntry, value, 'some', ctx);\n }\n\n const relationMatchModes: readonly RelationMatchMode[] = ['some', 'none', 'every'];\n\n const variants: SQL[] = [];\n for (const [mode, inner] of Object.entries(value)) {\n if (inner === undefined || inner === null) {\n continue;\n }\n\n // Unknown keys inside the some/none/every wrapper must throw rather than be dropped —\n // a stitched schema can contribute foreign keys here too, and dropping them all would\n // silently turn the relation filter into no filter at all.\n if (!relationMatchModes.includes(mode as RelationMatchMode)) {\n throw drizzleError(`WHERE ${relationName}: Unknown relation filter key: ${mode}`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n\n const extracted = buildRelationExists(parentTable, relationName, relEntry, inner, mode as RelationMatchMode, ctx);\n if (extracted) {\n variants.push(extracted);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n\nexport const extractFilters = <TTable extends Table>(\n table: TTable,\n tableName: string,\n filters: Filters<TTable>,\n relationCtx?: RelationFilterContext,\n): SQL | undefined => {\n // Boolean branches compose with sibling fields: siblings and the AND list are ANDed\n // together, NOT negates its whole branch, and the OR group is ANDed with the rest —\n // `{ a: …, OR: [{ b: … }, { c: … }] }` reads as `a AND (b OR c)`. Every branch is the\n // filter type itself, so the tree nests arbitrarily.\n const { OR, AND, NOT, ...fieldFilters } = filters;\n\n // `Omit`-ing the boolean keys off a generic `Filters<TTable>` leaves a type the checker\n // can no longer relate to `FiltersCore<TTable>`. Each key is dispatched on its own below\n // — as a column or as a relation — so the entries are typed for that dispatch instead.\n const entries = Object.entries(fieldFilters) as [string, FilterColumnOperatorsCore<any> | undefined][];\n\n const columns = getColumns(table);\n const relations = relationCtx?.relationMap[relationCtx.tableKey];\n\n const variants = [] as SQL[];\n for (const [fieldName, operators] of entries) {\n if (operators === null || operators === undefined) {\n continue;\n }\n\n const column = columns[fieldName];\n // Resolved in the order the fields were generated in: a column keeps its name, then a\n // relation, and a unique-key field only exists where neither claimed it.\n const uniqueKey = column ? undefined : relationCtx?.uniqueKeys?.[relationCtx.tableKey]?.[fieldName];\n\n // A key that is none of the three must throw rather than be dropped: when the generated\n // schema is stitched/merged with another schema, same-named inputs can contribute foreign\n // keys that pass input validation, and a where that loses all of its keys silently becomes\n // an unbounded select/update/delete.\n if (!column && !uniqueKey && !(relations?.[fieldName] && relationCtx)) {\n throw drizzleError(`WHERE ${tableName}: Unknown filter key: ${fieldName}`, { code: 'DRIZZLE_INVALID_FILTER' });\n }\n\n const extracted = column\n ? extractFiltersColumn(column, fieldName, operators)\n : uniqueKey\n ? extractUniqueKeyFilter(table, tableName, fieldName, uniqueKey, operators as any)\n : extractRelationFilter(table, fieldName, relations![fieldName]!, operators as any, relationCtx!);\n\n if (extracted) {\n variants.push(extracted);\n }\n }\n\n if (AND?.length) {\n for (const variant of AND) {\n const extracted = extractFilters(table, tableName, variant, relationCtx);\n if (extracted) {\n variants.push(extracted);\n }\n }\n }\n\n if (NOT) {\n const extracted = extractFilters(table, tableName, NOT, relationCtx);\n // `not()` is typed `SQL | undefined` from drizzle-orm rc.5 on, `SQL` before it.\n const negated = extracted ? not(extracted) : undefined;\n if (negated) {\n variants.push(negated);\n }\n }\n\n if (OR?.length) {\n const orVariants = [] as SQL[];\n for (const variant of OR) {\n const extracted = extractFilters(table, tableName, variant, relationCtx);\n if (extracted) {\n orVariants.push(extracted);\n }\n }\n\n if (orVariants.length) {\n variants.push(orVariants.length > 1 ? or(...orVariants)! : orVariants[0]!);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Row-level scoping\n// ─────────────────────────────────────────────────────────────────────────────\n","// Row-level policy: `scope`, `softDelete` and `contextValues`, each resolved per table and\n// bound into the shape the resolvers apply at request time.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { and, eq, extractExtendedColumnType, getColumns, is, isNotNull, isNull, ne, or, SQL } from 'drizzle-orm';\nimport { GraphQLEnumType } from 'graphql';\nimport { drizzleError } from './errors.ts';\nimport type { DefaultOrderByFor } from './limits.ts';\nimport type { RelationFilterBase } from './relation-filters.ts';\nimport { extractFilters, relationFilterCtx } from './relation-filters.ts';\nimport { sharedType, type TypeNameResolver } from './type-names.ts';\nimport type { WriteHookFor } from './write-hooks.ts';\n\n/**\n * A table's row-level scope: the predicate every generated read, update and delete on that\n * table is narrowed by. See `BuildSchemaConfig.scope`.\n *\n * `table` is the table the predicate must be built against. On the relational-query path\n * drizzle hands its callbacks an *aliased* proxy (`d0`, `d1`, …), so a predicate built from\n * the imported schema table would reference a name that isn't in the query — always build\n * from the argument. Returning a filter object instead (the same shape as the field's\n * `where`) sidesteps aliasing entirely, and is the only form that can reach through a\n * relation — which is what ownership through a join table needs.\n */\ntype ScopeHook<TContext = any> = (context: TContext, table: any) => SQL | Record<string, any> | undefined | null;\n\n/** Build-time lookup: the scope configured for a table, if any. */\nexport type ScopeFor = (tableName: string) => ScopeHook | undefined;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Soft delete\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** What a read over a soft-deleting table does with rows that are marked deleted. */\nexport type DeletedMode = 'EXCLUDE' | 'INCLUDE' | 'ONLY';\n\n/**\n * One table's soft-delete convention, resolved against the real column at build time.\n *\n * `marker` picks the shape of the predicate. When the config names a constant that means\n * deleted, the predicate compares against it (`isDeleted = true`); otherwise the column marks\n * a row deleted by holding a value at all (`deletedAt IS NOT NULL`), the common timestamp\n * form. A NOT NULL column has no \"absent\" state, so it must have a marker; a nullable one\n * takes the NULL-means-alive reading only when no marker was configured.\n */\nexport type SoftDeleteInfo = {\n /** Property name of the column on the drizzle table — also the key on an aliased proxy. */\n columnName: string;\n column: Column;\n nullable: boolean;\n /** Evaluated per delete, so a timestamp form stamps the moment of the delete. */\n writeDeleted: () => any;\n /** Written by the restore mutation. */\n writeRestored: any;\n /**\n * The constant that means \"this row is deleted\", when the config named one. Required on a\n * NOT NULL column; optional on a nullable one, which otherwise reads NULL as alive.\n */\n marker?: any;\n /**\n * Which reads hide marked rows by default — `'all'` (the table's own fields and every\n * relation pointing at it) or `'root'` (its own fields only). See\n * {@link relationDeletedDefault}.\n */\n scope: 'root' | 'all';\n /**\n * Whether the delete mutations take a `hard` argument that issues a real `DELETE`. Off\n * unless the table opts in, so the generated schema says which tables can be purged.\n */\n hardDelete: boolean;\n};\n\n/** Build-time lookup: the soft-delete convention of a table, if it declares one. */\nexport type SoftDeleteFor = (tableName: string) => SoftDeleteInfo | undefined;\n\n/**\n * The enum behind the `deleted` argument on every read over a soft-deleting table. Built once\n * per name it resolves to — it carries no per-build state beyond that name, so every build\n * that names it the same way shares one instance.\n */\nexport const deletedFilterEnumType = (typeName: TypeNameResolver): GraphQLEnumType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'DeletedFilter' },\n (name) =>\n new GraphQLEnumType({\n name,\n description: 'Which rows a read over a soft-deleting table returns.',\n values: {\n EXCLUDE: { value: 'EXCLUDE', description: 'Only rows that are not marked deleted. The default.' },\n INCLUDE: { value: 'INCLUDE', description: 'Marked and unmarked rows alike.' },\n ONLY: { value: 'ONLY', description: 'Only rows that are marked deleted — a trash view.' },\n },\n }),\n );\n\n/**\n * Resolves one table's `softDelete` declaration against the real column, at build time, so a\n * renamed column fails the build instead of quietly making every row visible again.\n */\nexport const resolveSoftDeleteInfo = (\n table: Table,\n tableName: string,\n declaration:\n | string\n | {\n column: string;\n deletedValue?: any;\n restoredValue?: any;\n scope?: 'root' | 'all';\n hardDelete?: boolean;\n },\n): SoftDeleteInfo => {\n const config = typeof declaration === 'string' ? { column: declaration } : declaration;\n const columnName = config?.column;\n if (typeof columnName !== 'string' || !columnName) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName} must be a column name or an object with a 'column' property.`,\n );\n }\n const column = getColumns(table)[columnName];\n if (!column) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete names '${tableName}.${columnName}', which is not a column of that table.`,\n );\n }\n const nullable = !column.notNull;\n // drizzle-orm v1 reports compound dataType strings (\"object date\", \"number int32\"), so the\n // shape of the column has to come from the extended type rather than a string compare.\n const { type: baseType, constraint } = extractExtendedColumnType(column);\n const hasDeleted = 'deletedValue' in (config as object) && config.deletedValue !== undefined;\n // The default depends on what the column can hold: a timestamp records when, a flag records\n // whether. Both are the shapes the convention actually takes in the wild.\n const writeDeleted: () => any = hasDeleted\n ? typeof config.deletedValue === 'function'\n ? (config.deletedValue as () => any)\n : () => config.deletedValue\n : constraint === 'date' && baseType === 'object'\n ? () => new Date()\n : baseType === 'string'\n ? () => new Date().toISOString()\n : baseType === 'number'\n ? () => Date.now()\n : baseType === 'bigint'\n ? () => BigInt(Date.now())\n : () => true;\n\n let marker: any;\n if (hasDeleted && typeof config.deletedValue !== 'function') {\n // A configured constant is what reads compare against, whether or not the column is\n // nullable: a nullable boolean defaulting to `false` (the shape a marker column added to\n // an existing table without a backfill takes) means deleted by holding `true`, not by\n // holding anything at all.\n marker = config.deletedValue;\n } else if (!nullable) {\n // A non-nullable column has no \"absent\" state, so the predicate has to compare against a\n // constant — which a function cannot supply, and which the boolean form supplies for free.\n if (!hasDeleted && baseType === 'boolean') {\n marker = true;\n } else {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName} marks a NOT NULL column ('${columnName}'), so 'deletedValue' must be a constant that means deleted — not a function, and not omitted for a non-boolean column.`,\n );\n }\n }\n\n const hasRestored = 'restoredValue' in (config as object);\n const writeRestored = hasRestored\n ? config.restoredValue\n : nullable\n ? null\n : baseType === 'boolean'\n ? false\n : undefined;\n if (!nullable && writeRestored === undefined) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName} marks a NOT NULL column ('${columnName}'), so 'restoredValue' must say what restoring writes back.`,\n );\n }\n\n const scope = config.scope ?? 'all';\n if (scope !== 'root' && scope !== 'all') {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName}.scope must be 'root' or 'all', not ${JSON.stringify(scope)}.`,\n );\n }\n\n const hardDelete = config.hardDelete ?? false;\n if (typeof hardDelete !== 'boolean') {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName}.hardDelete must be a boolean, not ${JSON.stringify(hardDelete)}.`,\n );\n }\n\n return { columnName, column, nullable, writeDeleted, writeRestored, marker, scope, hardDelete };\n};\n\n/**\n * The `deleted` mode a *relation* field reads its target with when the request does not pass\n * one. Root fields always default to `EXCLUDE`; a relation field is the case a soft delete\n * cannot answer for on its own, because the row it hides belongs to a different query than\n * the one that marked it.\n *\n * - `scope: 'root'` reads relations with `INCLUDE`: the row is retired, not erased, so the\n * historical rows that reference it keep rendering it.\n * - `scope: 'all'` keeps hiding it — except through a *required* to-one relation, where a\n * hidden row can only surface as \"Cannot return null for non-nullable field\" and take the\n * whole parent down with it. There is no usable result to protect there, so the row is\n * included rather than the parent lost.\n *\n * Returns `undefined` when the target declares no soft delete, so an unconfigured build\n * passes exactly the mode it did before.\n */\nexport const relationDeletedDefault = (\n softDelete: SoftDeleteFor | undefined,\n targetTableName: string,\n requiredToOne: boolean,\n): DeletedMode | undefined => {\n const info = softDelete?.(targetTableName);\n if (!info) {\n return undefined;\n }\n return info.scope === 'root' || requiredToOne ? 'INCLUDE' : 'EXCLUDE';\n};\n\n/**\n * The predicate that selects the rows a `deleted` mode asks for: nothing for `INCLUDE`, the\n * marked rows for `ONLY`, the unmarked ones for `EXCLUDE`. Built against the table it is\n * handed, which on the relational path is drizzle's aliased proxy rather than the schema\n * table — the same rule a scope hook follows.\n */\nexport const softDeletePredicate = (info: SoftDeleteInfo, table: Table, mode: DeletedMode): SQL | undefined => {\n if (mode === 'INCLUDE') {\n return undefined;\n }\n const column = ((table as any)?.[info.columnName] ?? info.column) as Column;\n if (info.marker === undefined) {\n return mode === 'ONLY' ? isNotNull(column) : isNull(column);\n }\n if (!info.nullable) {\n return mode === 'ONLY' ? eq(column, info.marker) : ne(column, info.marker);\n }\n // A nullable column with a marker: NULL is neither the marker nor a match for `<>`, so the\n // exclude side has to name it explicitly or every un-backfilled row would drop out.\n return mode === 'ONLY' ? eq(column, info.marker) : or(ne(column, info.marker), isNull(column))!;\n};\n\n/**\n * The row policies of one request, bound to its context: the table's scope and its\n * soft-delete convention, which both narrow the same `where`. `has` answers \"does this table\n * restrict anything at all\", cheaply and without evaluating a hook; `on` compiles the\n * predicate against a given table.\n */\nexport type ScopeResolver = {\n has: (tableName: string, mode?: DeletedMode) => boolean;\n on: (tableName: string, table: Table, mode?: DeletedMode) => SQL | undefined;\n /**\n * The mode a relation field reading `tableName` defaults to — see\n * {@link relationDeletedDefault}. Carried here because the eager (`with:`) path has the\n * resolver but not the build-time soft-delete lookup.\n */\n relationDefault: (tableName: string, requiredToOne: boolean) => DeletedMode | undefined;\n};\n\n/**\n * Binds the configured row policies to one request's GraphQL context. Returns `undefined`\n * when neither a scope nor a soft-delete column is configured, so every call site skips the\n * machinery with a single check and an unconfigured build generates exactly the SQL it did\n * before.\n */\nexport const resolveScope = (\n policies: TablePolicies | undefined,\n context: any,\n filterCtx?: RelationFilterBase,\n): ScopeResolver | undefined => {\n const scopes = policies?.scope;\n const softDelete = policies?.softDelete;\n if (!scopes && !softDelete) {\n return undefined;\n }\n return {\n has: (tableName, mode) => !!scopes?.(tableName) || (!!softDelete?.(tableName) && (mode ?? 'EXCLUDE') !== 'INCLUDE'),\n relationDefault: (tableName, requiredToOne) => relationDeletedDefault(softDelete, tableName, requiredToOne),\n on: (tableName, table, mode) => {\n // Order is fixed: the soft-delete predicate first, the scope after it, both ANDed. They\n // commute, but a fixed order keeps the generated SQL stable between requests.\n const marked = softDelete?.(tableName);\n const deleted = marked ? softDeletePredicate(marked, table, mode ?? 'EXCLUDE') : undefined;\n const hook = scopes?.(tableName);\n if (!hook) {\n return deleted;\n }\n const predicate = hook(context, table);\n if (predicate === undefined || predicate === null) {\n return deleted;\n }\n if (is(predicate, SQL)) {\n return and(deleted, predicate as SQL);\n }\n if (typeof predicate !== 'object') {\n throw drizzleError(\n `Drizzle-GraphQL Error: the scope for '${tableName}' returned a ${typeof predicate}. A scope returns a filter object, a Drizzle SQL expression, or undefined.`,\n { code: 'DRIZZLE_INVALID_SCOPE' },\n );\n }\n // A filter object is compiled the same way the field's own `where` is, against the\n // table it was handed — which is what keeps it correct under RQB aliasing.\n return and(deleted, extractFilters(table, tableName, predicate as any, relationFilterCtx(filterCtx, tableName)));\n },\n };\n};\n\n/**\n * `condition AND <the row policies of tableName>` — the single way a scope or a soft-delete\n * predicate is ever combined with a caller-supplied filter, so a `where` can only ever narrow\n * them, never widen them. `mode` is the read's `deleted` argument, and defaults to hiding\n * marked rows; a write passes nothing and so never touches one.\n */\nexport const withScope = (\n scope: ScopeResolver | undefined,\n tableName: string,\n table: Table,\n condition: SQL | undefined,\n mode?: DeletedMode,\n): SQL | undefined => {\n const predicate = scope?.on(tableName, table, mode);\n return predicate ? and(condition, predicate) : condition;\n};\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Context-derived column values\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Produces one column's value from the GraphQL context. See `BuildSchemaConfig.contextValues`. */\nexport type ContextValueHook<TContext = any> = (context: TContext) => any;\n\n/** Build-time lookup: the context-derived columns of a table, keyed by column property name. */\nexport type ContextValuesFor = (tableName: string) => Record<string, ContextValueHook> | undefined;\n\n/**\n * The two request-time policies a generated resolver applies, passed to the dialect\n * generators as one value so a table's read scope and its server-owned columns travel\n * together. Both stay `undefined` when nothing is configured, and every call site checks\n * before doing any work — an unconfigured build generates exactly the SQL it did before.\n */\nexport type TablePolicies = {\n /** See `BuildSchemaConfig.scope`. */\n scope?: ScopeFor;\n /** See `BuildSchemaConfig.contextValues`. */\n contextValues?: ContextValuesFor;\n /** See `BuildSchemaConfig.softDelete`. */\n softDelete?: SoftDeleteFor;\n /** See `BuildSchemaConfig.onWrite`. */\n onWrite?: WriteHookFor;\n /** See `BuildSchemaConfig.defaults`. */\n defaultOrderBy?: DefaultOrderByFor;\n};\n\n/**\n * {@link TablePolicies} with the scope already bound to the build's relation context, which\n * is what a dialect generator is handed: `scope(context)` is all a resolver needs to compile\n * a predicate, and it stays `undefined` when nothing is scoped.\n */\nexport type ResolverPolicies = {\n scope?: (context: any) => ScopeResolver | undefined;\n contextValues?: ContextValuesFor;\n softDelete?: SoftDeleteFor;\n onWrite?: WriteHookFor;\n defaultOrderBy?: DefaultOrderByFor;\n};\n\n/** Binds a build's {@link TablePolicies} to its relation context, once, at schema-build time. */\nexport const bindPolicies = (\n policies: TablePolicies | undefined,\n filterCtx: RelationFilterBase | undefined,\n): ResolverPolicies | undefined =>\n policies?.scope || policies?.contextValues || policies?.softDelete || policies?.onWrite || policies?.defaultOrderBy\n ? {\n scope:\n policies.scope || policies.softDelete\n ? (context: any) => resolveScope(policies, context, filterCtx)\n : undefined,\n contextValues: policies.contextValues,\n softDelete: policies.softDelete,\n onWrite: policies.onWrite,\n defaultOrderBy: policies.defaultOrderBy,\n }\n : undefined;\n\n/**\n * Merges a table's context-derived values into one row's insert values. The hooks run per\n * row — a value may depend on the row's own contents through the closure the caller built —\n * and they overwrite whatever was there: the columns are not in the create input, so nothing\n * legitimate can be lost, but a stitched-in input could still carry the key and the server's\n * value has to win.\n */\nexport const applyContextValues = (\n values: Record<string, any>,\n hooks: Record<string, ContextValueHook> | undefined,\n context: any,\n): Record<string, any> => {\n if (!hooks) {\n return values;\n }\n for (const [columnName, hook] of Object.entries(hooks)) {\n values[columnName] = hook(context);\n }\n return values;\n};\n\n/** {@link applyContextValues} over a batch — every row in an insert gets its own evaluation. */\nexport const applyContextValuesAll = (\n rows: Record<string, any>[],\n hooks: Record<string, ContextValueHook> | undefined,\n context: any,\n): Record<string, any>[] => {\n if (!hooks) {\n return rows;\n }\n for (const row of rows) {\n applyContextValues(row, hooks, context);\n }\n return rows;\n};\n\n/**\n * Drops context-derived columns from an update's `set`. They are not in the update input\n * either, so this only matters when the key arrives some other way — and reassigning one is\n * exactly the ownership transfer the feature exists to prevent.\n */\nexport const stripContextValues = (\n values: Record<string, any>,\n hooks: Record<string, ContextValueHook> | undefined,\n): Record<string, any> => {\n if (!hooks) {\n return values;\n }\n for (const columnName of Object.keys(hooks)) {\n delete values[columnName];\n }\n return values;\n};\n","// The argument maps the generated read fields take: the shared filter/order/paging set,\n// and the `deleted` argument a soft-deleting table adds.\n\nimport {\n type GraphQLEnumType,\n type GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLString,\n} from 'graphql';\nimport type { SoftDeleteFor } from './policies.ts';\nimport { deletedFilterEnumType } from './policies.ts';\nimport type { GeneratedTypeInfo, TypeNameResolver } from './type-names.ts';\n\n/** GraphQL argument map for a list/array select field. */\n/**\n * The `deleted` argument, emitted only on reads over a table that declares a soft-delete\n * column — a schema with no soft delete anywhere keeps exactly the arguments it had.\n */\nexport const deletedArg = (\n softDelete: SoftDeleteFor | undefined,\n tableName: string,\n resolveName?: TypeNameResolver,\n): Record<string, { type: any; description: string }> =>\n softDelete?.(tableName)\n ? {\n deleted: {\n type: deletedFilterEnumType(resolveName ?? ((info: GeneratedTypeInfo) => info.defaultName)),\n description: 'Whether rows marked deleted are returned. Defaults to EXCLUDE.',\n },\n }\n : {};\n\nexport const selectArrayArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n distinctEnum?: GraphQLEnumType,\n softDelete?: SoftDeleteFor,\n tableName?: string,\n resolveName?: TypeNameResolver,\n): Record<string, { type: any; description?: string }> => ({\n offset: { type: GraphQLInt },\n limit: { type: GraphQLInt },\n orderBy: { type: orderArgs },\n where: { type: filterArgs },\n after: {\n type: GraphQLString,\n description:\n \"Keyset pagination: only return rows strictly after this cursor (a row's `cursor` field from a previous page, under the same orderBy).\",\n },\n ...(distinctEnum ? { distinct: { type: new GraphQLList(new GraphQLNonNull(distinctEnum)) } } : {}),\n ...deletedArg(softDelete, tableName!, resolveName),\n});\n\n/** GraphQL argument map for a single-row select field (no `limit`). */\nexport const selectSingleArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n softDelete?: SoftDeleteFor,\n tableName?: string,\n resolveName?: TypeNameResolver,\n): Record<string, { type: any }> => ({\n offset: { type: GraphQLInt },\n orderBy: { type: orderArgs },\n where: { type: filterArgs },\n ...deletedArg(softDelete, tableName!, resolveName),\n});\n","// GraphQL enums naming a table's columns — the operand type for `distinctOn` and for any\n// argument that has to name a column rather than carry a value.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { GraphQLEnumType } from 'graphql';\nimport { excludedColumnsKey, visibleColumns } from './exclusions.ts';\nimport type { TypeNameResolver } from './type-names.ts';\n\n/** Alias of the row-number helper column in the `distinct` pass. Namespaced against real columns. */\nexport const DISTINCT_RN = '__drizzle_graphql_distinct_rn';\n\nconst columnEnumCache = new WeakMap<object, Map<string, GraphQLEnumType>>();\n\n/**\n * An enum of a table's column property names, under `enumName`. Cached per (table, enum name,\n * exclusions), like the order/filter inputs, so repeated builds reuse one instance and two\n * enums over the same table never collide.\n *\n * Returns `undefined` when no column qualifies — the caller then omits the argument or\n * input field the enum would have typed, rather than emitting an empty enum, which is\n * invalid GraphQL.\n */\nexport const generateColumnEnum = (\n table: Table,\n enumName: string,\n description: string,\n predicate: (column: Column, columnName: string) => boolean = () => true,\n): GraphQLEnumType | undefined => {\n // The exclusions are part of the key, not a reason to skip the cache: a table's enum is\n // asked for from more than one place in a build (a list query's `distinct` argument and the\n // same argument on a to-many relation field pointing at it), and handing those two call\n // sites separate instances would put two types of the same name in one schema.\n const cacheKey = `${enumName}\\u0000${excludedColumnsKey(table)}`;\n let tableCache = columnEnumCache.get(table);\n const cached = tableCache?.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const columnNames = Object.entries(visibleColumns(table))\n .filter(([columnName, column]) => predicate(column as Column, columnName))\n .map(([columnName]) => columnName);\n if (!columnNames.length) {\n return undefined;\n }\n\n const enumType = new GraphQLEnumType({\n name: enumName,\n description,\n values: Object.fromEntries(columnNames.map((columnName) => [columnName, { value: columnName }])),\n });\n\n if (!tableCache) {\n tableCache = new Map();\n columnEnumCache.set(table, tableCache);\n }\n tableCache.set(cacheKey, enumType);\n return enumType;\n};\n\n/**\n * `${typeName}DistinctColumn` — the enum of columns a list query may be made distinct on.\n *\n * @param resolveName the build's naming rule, where the caller has one; the default name is\n * used as-is when it does not, which is what a consumer calling this directly gets.\n */\nexport const generateDistinctEnum = (\n table: Table,\n typeName: string,\n resolveName?: TypeNameResolver,\n tableKey?: string,\n): GraphQLEnumType | undefined => {\n const defaultName = `${typeName}DistinctColumn`;\n return generateColumnEnum(\n table,\n resolveName?.({ kind: 'columnEnum', defaultName, table: tableKey, operation: 'distinct' }) ?? defaultName,\n `Columns of ${typeName} that a query can be made distinct on`,\n );\n};\n\n// ── upsert / conflict handling ────────────────────────────────────────────────\n","// The `onConflict` argument: the input type it is generated from, and the plan a resolver\n// compiles one into before handing it to the dialect's upsert.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { getColumns, type SQL, sql } from 'drizzle-orm';\nimport { GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull } from 'graphql';\nimport { generateColumnEnum } from './column-enums.ts';\nimport { drizzleError } from './errors.ts';\nimport type { TypeCacheCtx } from './type-cache.ts';\nimport { sharedType, type TypeNameResolver } from './type-names.ts';\n\n/** Shared by every table's `${typeName}OnConflict` input, so it is created once per name. */\nexport const conflictActionEnumType = (typeName: TypeNameResolver): GraphQLEnumType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'ConflictAction' },\n (name) =>\n new GraphQLEnumType({\n name,\n description: 'What an upsert does when a row with the same unique key already exists',\n values: {\n UPDATE: { value: 'UPDATE', description: 'Overwrite the conflicting row with the supplied values' },\n NOTHING: { value: 'NOTHING', description: 'Keep the existing row and insert nothing' },\n },\n }),\n );\n\n/**\n * The `${typeName}OnConflict` input that types an upsert's `onConflict` argument.\n *\n * `target` and `where` only exist when the dialect can express them: MySQL's\n * `ON DUPLICATE KEY UPDATE` fires on any unique key and takes no predicate, so offering\n * either there would mean silently ignoring it.\n *\n * Returns `undefined` when the table has nothing to conflict on (`withTarget` dialects\n * only) — the caller then generates no upsert mutations for that table at all, rather than\n * an operation whose every call is a database error.\n */\nexport const generateOnConflictInput = (params: {\n table: Table;\n tableName: string;\n typeName: string;\n uniqueSets: string[][];\n tableFilters: GraphQLInputObjectType;\n withTarget: boolean;\n cacheCtx: TypeCacheCtx;\n}): GraphQLInputObjectType | undefined => {\n const { table, tableName, typeName, uniqueSets, tableFilters, withTarget, cacheCtx } = params;\n const resolveName = cacheCtx.typeName;\n\n const updateEnum = generateColumnEnum(\n table,\n resolveName({\n kind: 'columnEnum',\n defaultName: `${typeName}UpdateColumn`,\n table: tableName,\n operation: 'conflictUpdate',\n }),\n `Columns of ${typeName} that an upsert can overwrite`,\n );\n if (!updateEnum) {\n return undefined;\n }\n\n const fields: Record<string, any> = {\n action: {\n type: conflictActionEnumType(resolveName),\n defaultValue: 'UPDATE',\n description: 'Whether a conflicting row is overwritten or left alone. Defaults to UPDATE.',\n },\n update: {\n type: new GraphQLList(new GraphQLNonNull(updateEnum)),\n description:\n 'Columns to overwrite on conflict. Defaults to every column the request supplied, minus the conflict target. Columns the request did not supply cannot be listed here — there would be no value to write.',\n },\n };\n\n if (withTarget) {\n const uniqueColumns = new Set(uniqueSets.flat());\n const targetEnum = generateColumnEnum(\n table,\n resolveName({\n kind: 'columnEnum',\n defaultName: `${typeName}ConflictTarget`,\n table: tableName,\n operation: 'conflictTarget',\n }),\n `Columns of ${typeName} that carry a unique constraint, and so can be conflicted on`,\n (_column, columnName) => uniqueColumns.has(columnName),\n );\n if (!targetEnum) {\n return undefined;\n }\n\n fields['target'] = {\n type: new GraphQLList(new GraphQLNonNull(targetEnum)),\n description:\n 'The unique column set a conflict is detected on. Must match one of the table’s unique constraints exactly. Defaults to the primary key.',\n };\n fields['where'] = {\n type: tableFilters,\n description: 'Only overwrite conflicting rows that match this filter. Others are left alone.',\n };\n }\n\n return new GraphQLInputObjectType({\n name: resolveName({ kind: 'onConflict', defaultName: `${typeName}OnConflict`, table: tableName }),\n description: `Conflict handling for an upsert of ${typeName}`,\n fields,\n });\n};\n\n/** The `onConflict` argument as it arrives from GraphQL. */\nexport type OnConflictArg = {\n action?: 'UPDATE' | 'NOTHING';\n target?: string[];\n update?: string[];\n where?: any;\n};\n\n/** What a dialect needs to turn an insert into an upsert. */\nexport type ConflictPlan = {\n action: 'UPDATE' | 'NOTHING';\n /** Columns to conflict on, or `undefined` on dialects that take no conflict target. */\n target: Column[] | undefined;\n /** `column -> value to write`, in Drizzle's `set` shape. Empty when the action is NOTHING. */\n set: Record<string, SQL>;\n setWhere: SQL | undefined;\n};\n\n/**\n * Turns the request's `onConflict` argument and the rows it is inserting into the clause a\n * dialect should attach.\n *\n * `excludedRef` names the row that failed to insert in the dialect's own terms\n * (`excluded.col` on PostgreSQL and SQLite, `values(col)` on MySQL), which is what makes a\n * batch upsert update each row with its own values instead of the last row's.\n *\n * An UPDATE with nothing left to write degrades to NOTHING: `DO UPDATE SET` with an empty\n * body is not valid SQL, and doing nothing is what the request asked for anyway.\n */\nexport const resolveConflictPlan = (params: {\n table: Table;\n values: Record<string, any>[];\n onConflict: OnConflictArg | undefined;\n pkNames: readonly string[];\n uniqueSets: string[][];\n excludedRef: (columnName: string) => SQL;\n withTarget: boolean;\n buildWhere?: (where: any) => SQL | undefined;\n}): ConflictPlan => {\n const { table, values, onConflict, pkNames, uniqueSets, excludedRef, withTarget, buildWhere } = params;\n const columns = getColumns(table) as Record<string, Column>;\n\n let target: Column[] | undefined;\n if (withTarget) {\n const targetNames = onConflict?.target?.length ? onConflict.target : [...pkNames];\n if (!targetNames.length) {\n throw drizzleError(\n 'Unable to upsert: no conflict target was given and this table has no primary key. Pass onConflict.target.',\n { code: 'DRIZZLE_INVALID_ON_CONFLICT' },\n );\n }\n // A target that is not itself a unique constraint is a database error, and a confusing\n // one (\"there is no unique or exclusion constraint matching the ON CONFLICT\n // specification\"), so reject it here where we can say which sets are valid.\n const requested = [...targetNames].sort().join(',');\n if (!uniqueSets.some((set) => [...set].sort().join(',') === requested)) {\n throw drizzleError(\n `Unable to upsert: [${targetNames.join(', ')}] is not a unique constraint on this table. Valid conflict targets: ${uniqueSets\n .map((set) => `[${set.join(', ')}]`)\n .join(', ')}.`,\n { code: 'DRIZZLE_INVALID_ON_CONFLICT' },\n );\n }\n target = targetNames.map((name) => columns[name]!);\n }\n\n if ((onConflict?.action ?? 'UPDATE') === 'NOTHING') {\n return { action: 'NOTHING', target, set: {}, setWhere: undefined };\n }\n\n // Only columns the request actually supplied have a value to copy over; anything else\n // would write the column's default (usually null) onto the row that already exists.\n const supplied = new Set(values.flatMap((row) => Object.keys(row)));\n const targetNames = new Set(withTarget ? (onConflict?.target?.length ? onConflict.target : pkNames) : []);\n\n let updateNames: string[];\n if (onConflict?.update?.length) {\n const unsupplied = onConflict.update.filter((name) => !supplied.has(name));\n if (unsupplied.length) {\n throw drizzleError(\n `Unable to upsert: onConflict.update lists ${unsupplied.join(', ')}, which the values do not supply.`,\n { code: 'DRIZZLE_INVALID_ON_CONFLICT' },\n );\n }\n updateNames = onConflict.update;\n } else {\n updateNames = [...supplied].filter((name) => !targetNames.has(name));\n }\n\n if (!updateNames.length) {\n return { action: 'NOTHING', target, set: {}, setWhere: undefined };\n }\n\n const set = Object.fromEntries(updateNames.map((name) => [name, excludedRef(columns[name]!.name)]));\n const setWhere = onConflict?.where && buildWhere ? buildWhere(onConflict.where) : undefined;\n\n return { action: 'UPDATE', target, set, setWhere };\n};\n\n/** `excluded.<column>` — PostgreSQL and SQLite name the rejected row this way. */\nexport const excludedColumnRef = (columnName: string): SQL => sql`excluded.${sql.identifier(columnName)}`;\n\n/** `values(<column>)` — MySQL's equivalent inside ON DUPLICATE KEY UPDATE. */\nexport const mysqlValuesColumnRef = (columnName: string): SQL => sql`values(${sql.identifier(columnName)})`;\n","// Compiling an `orderBy` argument into ORDER BY expressions — including ordering by a to-one\n// relation's columns, which compiles to a correlated scalar subquery.\n\nimport type { Column, Relation, Table } from 'drizzle-orm';\nimport {\n aliasedTable,\n and,\n asc,\n desc,\n getColumns,\n getTableAsAliasSQL,\n is,\n One,\n relationsFilterToSQL,\n type SQL,\n sql,\n} from 'drizzle-orm';\nimport { remapFromGraphQLCore } from '../../data-mappers/index.ts';\nimport type { OrderByArgs, TableNamedRelations } from '../types.ts';\nimport { drizzleError } from './errors.ts';\nimport type { RelationFilterContext } from './relation-filters.ts';\nimport { buildRelationJoinCondition } from './relation-filters.ts';\nimport { isFilterableRelation, isRelationFilterReversed, relationOwnWhere } from './relations.ts';\n\n/** How NULLs are placed relative to non-NULL values in an ordered column. */\nexport type OrderNullsOption = 'first' | 'last';\n\n/**\n * Column name / direction / nulls triples from an `orderBy` argument, highest priority\n * first. Split out of `extractOrderBy` so the same ordering can be rebuilt against a\n * subquery's fields, where there is no `Table` to read columns from. Because there is no\n * table, ordering through a relation cannot be compiled here — a relation-shaped entry\n * (an object without a `direction`) is rejected with a clear error instead of being\n * silently dropped.\n */\nexport const orderByEntries = (\n orderArgs: Record<string, any>,\n): [string, 'asc' | 'desc', OrderNullsOption | undefined][] =>\n Object.entries(orderArgs)\n // Filtered before the sort: an unset key contributes no entry, so sorting it is work\n // thrown away — and `sort` is stable, so dropping first leaves the same relative order\n // among equal priorities.\n .filter(([, config]) => config)\n .sort((a, b) => (b[1]?.priority ?? 0) - (a[1]?.priority ?? 0))\n .map(([column, config]) => {\n if (typeof config === 'object' && config.direction === undefined) {\n throw drizzleError(`ORDER BY ${column}: ordering through a relation is not supported in this query`, {\n code: 'DRIZZLE_INVALID_ORDER_BY',\n });\n }\n // Same reason as above: the sort key is not a value of the row, so it cannot be\n // rebuilt against a subquery's fields or encoded into a cursor.\n if (config.matchFilterOrder) {\n throw drizzleError(`ORDER BY ${column}: 'matchFilterOrder' is not supported in this query`, {\n code: 'DRIZZLE_INVALID_ORDER_BY',\n });\n }\n return [column, config.direction, config.nulls ?? undefined];\n });\n\n/**\n * The ORDER BY expression(s) for one ordered value. Without a `nulls` option this is the\n * plain `asc`/`desc` of the expression. With one:\n * - PostgreSQL and SQLite (3.30+) support `NULLS FIRST` / `NULLS LAST` natively, so the\n * clause is emitted as-is.\n * - MySQL has no such clause, so it is emulated with an extra `<expr> IS NULL` sort key\n * ahead of the expression itself (`IS NULL DESC` puts nulls first, `ASC` puts them\n * last). The same GraphQL surface is kept on all three dialects.\n *\n * `dialectColumn` is the real table column the expression derives from — used only to\n * detect the dialect (its `columnType` is prefixed `Pg` / `MySql` / `SQLite`), so `expr`\n * may be the column itself, a subquery field, or a correlated subquery.\n */\nexport const orderExpressions = (\n expr: Column | SQL | SQL.Aliased | any,\n direction: 'asc' | 'desc',\n nulls: OrderNullsOption | undefined,\n dialectColumn: Column,\n): SQL[] => {\n const directed = direction === 'asc' ? asc(expr) : desc(expr);\n\n if (!nulls) {\n return [directed];\n }\n\n const isMySql = (((dialectColumn as any).columnType as string) ?? '').startsWith('MySql');\n if (isMySql) {\n const nullsKey = nulls === 'first' ? desc(sql`(${expr} is null)`) : asc(sql`(${expr} is null)`);\n return [nullsKey, directed];\n }\n\n return [nulls === 'first' ? sql`${directed} nulls first` : sql`${directed} nulls last`];\n};\n\n/**\n * One ordering term, flattened out of a (possibly relation-nested) `orderBy` argument.\n * `expression` is what the ORDER BY sorts on — the column itself, or a correlated\n * subquery reaching it through one or more to-one relations. `column` is the leaf table\n * column, kept for dialect detection.\n */\ninterface FlatOrderEntry {\n expression: Column | SQL;\n column: Column;\n direction: 'asc' | 'desc';\n nulls: OrderNullsOption | undefined;\n priority: number;\n}\n\n/**\n * The chain of aliased to-one hops a relation-ordered column is reached through. Rendered\n * as a single correlated scalar subquery: every hop's target sits in the FROM list and\n * its join condition (plus the relation's own `where`, when it declares one) in the WHERE.\n */\ninterface RelationOrderChain {\n fromParts: SQL[];\n conditions: SQL[];\n /** The aliased target of the last hop — the table the next hop or leaf column resolves from. */\n table: Table;\n}\n\n/** Extends the chain (or starts one from `parentTable`) with one to-one hop. */\nconst extendRelationOrderChain = (\n parentTable: Table,\n relationName: string,\n relEntry: TableNamedRelations,\n ctx: RelationFilterContext,\n chain: RelationOrderChain | undefined,\n): RelationOrderChain => {\n const targetTable = ctx.tables[relEntry.targetTableName];\n const relation = ((relEntry as any).relation ?? relEntry) as Relation<string>;\n\n if (!targetTable || !is(relation, One) || !isFilterableRelation(relation)) {\n throw drizzleError(`ORDER BY ${relationName}: Relation cannot be used for ordering`, {\n code: 'DRIZZLE_INVALID_ORDER_BY',\n });\n }\n\n ctx.aliases ??= { n: 0 };\n const aliasedTarget = aliasedTable(targetTable, `dgql_ord_${ctx.aliases.n++}`);\n\n const joinCondition = buildRelationJoinCondition(parentTable, relation, aliasedTarget, relationName);\n // A relation declared with its own `where` only ever exposes the rows it selects, so the\n // ordering subquery has to honour it too — mirroring the relation-filter subqueries.\n const ownWhere = relationOwnWhere(relation);\n const relationWhere = ownWhere\n ? relationsFilterToSQL(isRelationFilterReversed(relation) ? parentTable : aliasedTarget, ownWhere as any)\n : undefined;\n\n return {\n fromParts: [...(chain?.fromParts ?? []), getTableAsAliasSQL(aliasedTarget)],\n conditions: [\n ...(chain?.conditions ?? []),\n ...(joinCondition ? [joinCondition] : []),\n ...(relationWhere ? [relationWhere] : []),\n ],\n table: aliasedTarget,\n };\n};\n\n/**\n * The sort key behind `matchFilterOrder`: the column's position in the `inArray` list that\n * the same request's `where` gives it, as a `CASE` ladder over that list.\n *\n * A ladder rather than a dialect array function (`array_position` on Postgres, `FIELD()` on\n * MySQL, neither on SQLite) because it is the one form all three share, and because every\n * list value stays a bound parameter — encoded by the column, as `eq` would, so a value whose\n * driver form differs from its JS one (a SQLite integer timestamp's `Date`) is bound as stored.\n * The branch indices are library-generated integers, so they are written into the SQL text — a\n * bound parameter there would leave Postgres unable to infer the CASE result type. Values\n * outside the list sort after every listed one.\n */\nconst filterOrderExpression = (column: Column, columnName: string, whereArgs: Record<string, any> | undefined): SQL => {\n const values = whereArgs?.[columnName]?.inArray as unknown;\n if (!Array.isArray(values)) {\n throw drizzleError(\n `ORDER BY ${columnName}: 'matchFilterOrder' needs an 'inArray' filter on the same column in this query's 'where'`,\n { code: 'DRIZZLE_INVALID_ORDER_BY' },\n );\n }\n if (!values.length) {\n // An empty `inArray` matches no rows at all, so every row would sort the same anyway;\n // a constant keeps the expression valid without a ladder that has no branches.\n return sql`0`;\n }\n\n const branches = values.map(\n (value, index) =>\n sql`when ${column} = ${sql.param(remapFromGraphQLCore(value, column, columnName), column)} then ${sql.raw(String(index))}`,\n );\n return sql`case ${sql.join(branches, sql` `)} else ${sql.raw(String(values.length))} end`;\n};\n\n/**\n * Flattens one level of an `orderBy` argument into `out`. A column key becomes an entry\n * directly (wrapped in a correlated subquery when reached through a relation chain); a\n * to-one relation key recurses with the chain extended by that hop. Priorities live in one\n * global space, so a relation's column can interleave with the parent's own columns.\n */\nconst collectOrderEntries = (\n table: Table,\n tableKey: string,\n orderArgs: Record<string, any>,\n ctx: RelationFilterContext | undefined,\n chain: RelationOrderChain | undefined,\n out: FlatOrderEntry[],\n whereArgs: Record<string, any> | undefined,\n): void => {\n const columns = getColumns(table);\n const relations = ctx?.relationMap[tableKey];\n\n for (const [key, config] of Object.entries(orderArgs)) {\n if (config === null || config === undefined) {\n continue;\n }\n\n const column = columns[key];\n if (column) {\n if (config.matchFilterOrder && chain) {\n throw drizzleError(`ORDER BY ${key}: 'matchFilterOrder' is not supported through a relation`, {\n code: 'DRIZZLE_INVALID_ORDER_BY',\n });\n }\n out.push({\n expression: config.matchFilterOrder\n ? filterOrderExpression(column, key, whereArgs)\n : chain\n ? sql`(select ${column} from ${sql.join(chain.fromParts, sql`, `)} where ${and(...chain.conditions)})`\n : column,\n column,\n direction: config.direction,\n nulls: config.nulls ?? undefined,\n priority: config.priority ?? 0,\n });\n continue;\n }\n\n const relEntry = relations?.[key];\n if (!relEntry || !ctx) {\n throw drizzleError(`ORDER BY ${key}: Unknown column or relation`, { code: 'DRIZZLE_INVALID_ORDER_BY' });\n }\n\n const nextChain = extendRelationOrderChain(chain?.table ?? table, key, relEntry, ctx, chain);\n collectOrderEntries(nextChain.table, relEntry.targetTableName, config, ctx, nextChain, out, undefined);\n }\n};\n\n/**\n * Compiles an `orderBy` argument into ORDER BY expressions, highest priority first.\n *\n * A key naming one of the table's columns orders by that column. A key naming a to-one\n * relation takes the target table's own OrderBy input and orders by the related row's\n * column(s), compiled as a correlated scalar subquery — reusing the aliased-join machinery\n * the relation filters are built on — so it works identically on all three dialects and\n * inside the relational query builder's aliased CTEs. Priorities share one global space\n * across relation boundaries. Each entry may also carry `nulls: first | last`\n * (see {@link orderExpressions} for how MySQL emulates it).\n *\n * An entry may instead set `matchFilterOrder`, which sorts by the column's position in the\n * `inArray` list the same request's `where` gives it — `whereArgs` is that `where`.\n *\n * `ctx` supplies the tables and relation map that relation ordering needs; callers whose\n * inputs cannot contain relation keys may omit it.\n */\nexport const extractOrderBy = <TTable extends Table, TArgs extends OrderByArgs<any> = OrderByArgs<TTable>>(\n table: TTable,\n orderArgs: TArgs,\n ctx?: RelationFilterContext,\n whereArgs?: Record<string, any>,\n): SQL[] => {\n const entries: FlatOrderEntry[] = [];\n collectOrderEntries(table, ctx?.tableKey ?? '', orderArgs, ctx, undefined, entries, whereArgs);\n\n return entries\n .sort((a, b) => b.priority - a.priority)\n .flatMap((entry) => orderExpressions(entry.expression, entry.direction, entry.nulls, entry.column));\n};\n","// Keyset pagination. The `cursor` field, the ordering entries a cursor encodes, the encode and\n// decode pair, and the predicate that resumes a query from one.\n\nimport type { Table } from 'drizzle-orm';\nimport { and, eq, getColumns, gt, isNotNull, isNull, lt, or, type SQL, sql } from 'drizzle-orm';\nimport type { ResolveTree } from '../../parse-resolve-info.ts';\nimport { drizzleError } from './errors.ts';\nimport type { OrderNullsOption } from './order-by.ts';\nimport { orderByEntries, orderExpressions } from './order-by.ts';\n\n/** Name of the field on generated select types that exposes a row's opaque pagination cursor. */\nexport const CURSOR_FIELD_NAME = 'cursor';\n\n/**\n * Property the list resolvers stash each row's computed cursor under. Namespaced so it can't\n * collide with a real column; the `cursor` field's resolver reads it back off the row.\n */\nconst ROW_CURSOR_PROP = '__drizzle_graphql_cursor';\n\n/**\n * Where a dialect's default sort places NULLs relative to non-NULL values:\n * - `nulls-largest` — PostgreSQL: NULLs sort as the largest values (last in ASC, first in DESC).\n * - `nulls-smallest` — MySQL and SQLite: NULLs sort as the smallest values (first in ASC, last\n * in DESC).\n * The keyset predicate has to agree with the dialect's ORDER BY, so each builder passes its own.\n */\nexport type NullOrdering = 'nulls-largest' | 'nulls-smallest';\n\n/**\n * One key of the total order a cursor is defined over: column property name + direction,\n * plus the request's `nulls: first | last` override when it carries one (absent/null means\n * the dialect's native NULL placement).\n */\nexport type CursorOrderEntry = [string, 'asc' | 'desc', (OrderNullsOption | null)?];\n\n/**\n * Whether an `orderBy` argument orders through a to-one relation (a nested object entry\n * rather than a direction). A cursor encodes the row's own ordering-tuple values, and a\n * related row's value is not part of the row, so cursor pagination refuses these orderings —\n * `after` raises an error and the `cursor` field resolves to null, while the ordering itself\n * still applies.\n */\nexport const orderByHasRelationEntry = (orderBy: Record<string, any> | undefined): boolean =>\n !!orderBy &&\n Object.values(orderBy).some((config) => config && typeof config === 'object' && config.direction === undefined);\n\n/**\n * Why the given `orderBy` cannot back a cursor, as the message to raise — or `undefined`\n * when it can. Both cases sort on something that is not a value of the row: a related row's\n * column, or a position in the request's own `inArray` list. `after` raises the message and\n * the `cursor` field resolves to null, while the ordering itself still applies.\n */\nexport const orderByCursorObstacle = (orderBy: Record<string, any> | undefined): string | undefined => {\n if (orderByHasRelationEntry(orderBy)) {\n return \"'after' cannot be combined with an orderBy that orders through a relation — a related row's value cannot be encoded into a cursor.\";\n }\n if (\n orderBy &&\n Object.values(orderBy).some((config) => config && typeof config === 'object' && config.matchFilterOrder)\n ) {\n return \"'after' cannot be combined with 'matchFilterOrder' — a row's position in the request's own filter list is not a value of the row, so it cannot be encoded into a cursor.\";\n }\n return undefined;\n};\n\n/**\n * The total order a list query's rows follow when cursor pagination is in play: the request's\n * `orderBy` entries (highest priority first), then the primary key ascending as a tiebreak —\n * skipping PK columns the `orderBy` already names, so no key appears twice.\n */\nexport const cursorOrderingEntries = (\n orderBy: Record<string, any> | undefined,\n pkNames: readonly string[],\n): CursorOrderEntry[] => {\n const entries: CursorOrderEntry[] = orderBy ? orderByEntries(orderBy) : [];\n const seen = new Set(entries.map(([column]) => column));\n for (const pk of pkNames) {\n if (!seen.has(pk)) {\n entries.push([pk, 'asc']);\n }\n }\n return entries;\n};\n\n/**\n * ORDER BY expressions realizing a cursor's total order on `table` (which may be the aliased\n * RQB proxy) — each key's direction plus its `nulls` override, exactly the order the keyset\n * predicate in {@link buildCursorCondition} compares against.\n */\nexport const cursorOrderExprs = (table: Table, entries: CursorOrderEntry[]): SQL[] => {\n const cols = getColumns(table);\n return entries.flatMap(([column, direction, nulls]) =>\n orderExpressions(cols[column]!, direction, nulls ?? undefined, cols[column]!),\n );\n};\n\n/**\n * Serializes one ordering-tuple value into a JSON-safe shape. Dates and bigints don't survive\n * JSON.stringify losslessly (bigint throws, Date turns into an untagged string), so they are\n * tagged; decimals already arrive from the driver as strings, which are lossless as-is.\n */\nconst encodeCursorValue = (value: any): any => {\n if (value instanceof Date) {\n return { $type: 'date', value: value.toISOString() };\n }\n if (typeof value === 'bigint') {\n return { $type: 'bigint', value: value.toString() };\n }\n return value;\n};\n\nconst decodeCursorValue = (value: any): any => {\n if (value && typeof value === 'object' && typeof value.$type === 'string') {\n if (value.$type === 'date') {\n return new Date(value.value);\n }\n if (value.$type === 'bigint') {\n return BigInt(value.value);\n }\n }\n return value;\n};\n\n/**\n * Encodes a row's position in the given total order as an opaque cursor: base64url of a JSON\n * payload holding the ordering spec (`o`) and the row's values for it (`v`). The spec rides\n * along so a later request can verify the cursor was issued for the same ordering it is using.\n */\nexport const encodeCursor = (entries: CursorOrderEntry[], row: Record<string, any>): string =>\n cursorEncoder(entries)(row);\n\n/**\n * `encodeCursor` bound to one ordering, for encoding a whole page.\n *\n * The ordering spec is the same for every row of a page, so it is serialized once here and\n * spliced into each row's payload rather than re-serialized per row. The bytes are identical\n * to what building the payload object and stringifying it produces — same keys, same order —\n * so cursors stay interchangeable with ones issued before this was split out.\n */\nconst cursorEncoder = (entries: CursorOrderEntry[]): ((row: Record<string, any>) => string) => {\n const spec = JSON.stringify(entries);\n const columns = entries.map(([column]) => column);\n\n return (row) => {\n const values = JSON.stringify(columns.map((column) => encodeCursorValue(row[column] ?? null)));\n return Buffer.from(`{\"o\":${spec},\"v\":${values}}`, 'utf8').toString('base64url');\n };\n};\n\n/**\n * Decodes an `after` cursor and validates it against the ordering the current request pages\n * over. A cursor issued under a different `orderBy` would combine one ordering's predicate\n * with another's sort — silently wrong pages — so a mismatch is an error, as is anything that\n * doesn't decode to the expected payload shape.\n */\nexport const decodeCursor = (after: string, entries: CursorOrderEntry[]): any[] => {\n let payload: any;\n try {\n payload = JSON.parse(Buffer.from(after, 'base64url').toString('utf8'));\n } catch (_e) {\n throw drizzleError('Invalid cursor: unable to decode it. Pass a cursor returned by a previous page.', {\n code: 'DRIZZLE_INVALID_CURSOR',\n });\n }\n\n if (\n !payload ||\n typeof payload !== 'object' ||\n !Array.isArray(payload.o) ||\n !Array.isArray(payload.v) ||\n payload.o.length !== payload.v.length\n ) {\n throw drizzleError('Invalid cursor: malformed payload. Pass a cursor returned by a previous page.', {\n code: 'DRIZZLE_INVALID_CURSOR',\n });\n }\n\n const matchesOrdering =\n payload.o.length === entries.length &&\n payload.o.every(\n (entry: any, i: number) =>\n Array.isArray(entry) &&\n entry[0] === entries[i]![0] &&\n entry[1] === entries[i]![1] &&\n // The nulls override changes where NULLs sort, so it is part of the ordering identity.\n // JSON round-trips undefined as null — compare the normalized forms.\n (entry[2] ?? null) === (entries[i]![2] ?? null),\n );\n if (!matchesOrdering) {\n throw drizzleError(\n \"Invalid cursor: it was issued for a different ordering. Pass the same orderBy the cursor's page used.\",\n { code: 'DRIZZLE_INVALID_CURSOR' },\n );\n }\n\n return payload.v.map(decodeCursorValue);\n};\n\n/**\n * The keyset predicate selecting rows strictly after the cursor position in the given total\n * order — the expanded lexicographic form\n * `after(k0) OR (k0 = v0 AND after(k1)) OR (k0 = v0 AND k1 = v1 AND after(k2)) …`,\n * built with and/or/gt/lt/eq rather than SQL row-value syntax, which cannot express mixed\n * asc/desc directions and mishandles NULLs.\n *\n * NULL handling follows each key's `nulls: first | last` override when present, and otherwise\n * the dialect's default sort position (see {@link NullOrdering}): where NULLs sort last for a\n * key, \"after a non-NULL value\" includes the NULL rows and nothing sorts after a NULL one;\n * where NULLs sort first, \"after NULL\" is every non-NULL row.\n * `table` may be the aliased RQB proxy.\n */\nexport const buildCursorCondition = (\n table: Table,\n entries: CursorOrderEntry[],\n values: any[],\n nullOrdering: NullOrdering,\n): SQL => {\n const cols = getColumns(table);\n const disjuncts: SQL[] = [];\n const equalities: SQL[] = [];\n\n entries.forEach(([column, direction, nulls], i) => {\n const col = cols[column];\n if (!col) {\n throw drizzleError(`Invalid cursor: unknown column '${column}'.`, { code: 'DRIZZLE_INVALID_CURSOR' });\n }\n\n const value = values[i];\n const nullsSortLast =\n nulls != null ? nulls === 'last' : (direction === 'asc') === (nullOrdering === 'nulls-largest');\n\n let strictlyAfter: SQL | undefined;\n if (value === null || value === undefined) {\n // Nothing sorts after NULL when NULLs are last; every non-NULL row does when first.\n strictlyAfter = nullsSortLast ? undefined : isNotNull(col);\n } else {\n const comparison = direction === 'asc' ? gt(col, value) : lt(col, value);\n strictlyAfter = nullsSortLast ? or(comparison, isNull(col)) : comparison;\n }\n\n if (strictlyAfter) {\n disjuncts.push(equalities.length ? and(...equalities, strictlyAfter)! : strictlyAfter);\n }\n equalities.push(value === null || value === undefined ? isNull(col) : eq(col, value));\n });\n\n if (!disjuncts.length) {\n // Every key's strict term was impossible (e.g. a NULLs-last cursor position of all NULLs) —\n // nothing sorts after this cursor.\n return sql`1 = 0`;\n }\n\n return disjuncts.length > 1 ? or(...disjuncts)! : disjuncts[0]!;\n};\n\n/**\n * Whether the selection asks for the `cursor` meta field. A real column named `cursor` keeps\n * the field for itself, so the meta field only exists (and is only computed) when the table\n * has no such column.\n */\nexport const isCursorFieldSelected = (tree: Record<string, ResolveTree> | undefined, table: Table): boolean => {\n if (!tree) {\n return false;\n }\n if (getColumns(table)[CURSOR_FIELD_NAME]) {\n return false;\n }\n return Object.values(tree).some((field) => field.name === CURSOR_FIELD_NAME);\n};\n\n/**\n * Whether a field's own selection set asks for the `cursor` meta field, read straight off the\n * AST. The relation resolvers need this per parent row on the batch path, where parsing a\n * full resolve tree each time would cost far more than the one-level walk the question needs;\n * fragment spreads are followed, and a real column named `cursor` keeps the field for itself\n * exactly as in {@link isCursorFieldSelected}.\n */\nexport const selectsCursorField = (info: any, table: Table): boolean => {\n if (getColumns(table)[CURSOR_FIELD_NAME]) {\n return false;\n }\n\n const visited = new Set<string>();\n const walk = (selections: any[]): boolean =>\n selections.some((selection) => {\n if (selection.kind === 'Field') {\n return selection.name.value === CURSOR_FIELD_NAME;\n }\n if (selection.kind === 'InlineFragment') {\n return walk(selection.selectionSet.selections);\n }\n const name = selection.name?.value;\n if (!name || visited.has(name)) {\n return false;\n }\n visited.add(name);\n const fragment = info.fragments?.[name];\n return fragment ? walk(fragment.selectionSet.selections) : false;\n });\n\n return (info.fieldNodes ?? []).some((node: any) => !!node.selectionSet && walk(node.selectionSet.selections));\n};\n\n/**\n * Computes and attaches each row's opaque cursor (under a namespaced property the `cursor`\n * field's resolver reads). Must run on the raw driver rows, before output remapping rewrites\n * dates and bigints into their transport forms.\n */\nexport const attachRowCursors = (rows: Record<string, any>[], entries: CursorOrderEntry[]): void => {\n const encode = cursorEncoder(entries);\n for (const row of rows) {\n row[ROW_CURSOR_PROP] = encode(row);\n }\n};\n\n/** Resolver for the `cursor` meta field: reads the value a list resolver attached, if any. */\nexport const rowCursorResolver = (source: any): string | null => source?.[ROW_CURSOR_PROP] ?? null;\n","// Primary keys and unique column sets, read off a table however its dialect stores them.\n\nimport type { Table } from 'drizzle-orm';\nimport { asc, getColumns } from 'drizzle-orm';\nimport { visibleColumns } from './exclusions.ts';\n\n/**\n * Returns the property names of a table's primary key column(s).\n *\n * drizzle-orm marks inline `.primaryKey()` columns with `column.primary === true`,\n * but table-level composite keys (`primaryKey({ columns })`) leave `column.primary`\n * false on each member — those are only visible via the per-dialect `getTableConfig`.\n * Dialect builders pass the composite members' DB column names in via\n * `compositePkColumnNames`; we map them back to property names here.\n *\n * Resolution order: inline PK columns → composite PK columns → empty. We deliberately\n * do NOT guess a column named `id`: if no real primary key is declared, returning empty\n * lets callers fall back to the batch loader rather than re-keying on a possibly\n * non-unique column.\n */\nexport const getPrimaryKeyPropNames = (table: Table, compositePkColumnNames?: readonly string[]): string[] => {\n const cols = getColumns(table);\n const entries = Object.entries(cols);\n\n // Inline single `.primaryKey()` columns.\n const inlinePks = entries.filter(([, c]) => (c as any).primary).map(([k]) => k);\n if (inlinePks.length) {\n return inlinePks;\n }\n\n // Composite primary key (DB column names supplied by the dialect builder).\n if (compositePkColumnNames?.length) {\n const wanted = new Set(compositePkColumnNames);\n const fromComposite = entries.filter(([, c]) => wanted.has((c as any).name)).map(([k]) => k);\n if (fromComposite.length) {\n return fromComposite;\n }\n }\n\n // No declared primary key — let the caller fall back to the batch loader.\n return [];\n};\n\n/**\n * Ensures a selected-columns map (SQL format: prop name → Column) includes the table's\n * primary-key columns. Mutation resolvers pass their RETURNING columns through this so\n * the eager-loader can re-key rows by PK even when the client didn't select it. Mutates\n * and returns the same map.\n */\nexport const withPrimaryKeyColumns = <T extends Record<string, any>>(\n columns: T,\n table: Table,\n pkNames: readonly string[],\n): T => {\n const allCols = getColumns(table);\n for (const pk of pkNames) {\n if (!(pk in columns) && allCols[pk]) {\n (columns as any)[pk] = allCols[pk];\n }\n }\n return columns;\n};\n\n/**\n * Wraps a dialect's `getTableConfig` in a per-table cache.\n *\n * The dialect implementations are not lookups: each call re-runs the table's\n * `extraConfigBuilder` and rebuilds every index, check, unique constraint, primary key and\n * foreign key it declares. Nothing about a table changes after it is defined, so the result\n * is the same every time — but a build asks for it many times per table (primary-key names,\n * unique column sets, conflict targets, one per relation that keys off the target's PK), and\n * an overriding resolver asks again at request time.\n *\n * The cache is a `WeakMap` on the table object, so it costs nothing once the table is gone.\n * Bind it once per dialect module, at module scope, so the cache outlives a single\n * `buildSchema` call.\n */\nexport const memoizeTableConfig = <TTable extends Table, TConfig>(\n getTableConfig: (table: TTable) => TConfig,\n): ((table: TTable) => TConfig) => {\n const cache = new WeakMap<TTable, TConfig>();\n return (table: TTable): TConfig => {\n let config = cache.get(table);\n if (config === undefined) {\n config = getTableConfig(table);\n cache.set(table, config);\n }\n return config;\n };\n};\n\n/**\n * Resolves a table's primary-key property names using a dialect's `getTableConfig` to\n * surface table-level composite keys (whose member columns aren't flagged `.primary`).\n * Each dialect builder binds this with its own getTableConfig and reuses the binding for\n * both relation pagination and mutation re-fetch keying.\n */\nexport const getPrimaryKeyPropNamesFromConfig = <TTable extends Table>(\n table: TTable,\n getTableConfig: (table: TTable) => { primaryKeys: { columns: { name: string }[] }[] },\n): string[] => {\n const compositePkColumnNames = getTableConfig(table).primaryKeys.flatMap((pk) => pk.columns.map((c) => c.name));\n return getPrimaryKeyPropNames(table, compositePkColumnNames);\n};\n\n/**\n * Ascending order expressions for a table's primary key — the deterministic tiebreak for\n * paginated relations. Shared by the window-function batch path and the eager `with:`\n * orderBy default so both order identically. `table` may be the aliased RQB proxy.\n */\nexport const primaryKeyOrderExprs = (table: Table, pkNames: readonly string[]): any[] => {\n const cols = getColumns(table);\n return pkNames\n .map((n) => cols[n])\n .filter(Boolean)\n .map((col) => asc(col!));\n};\n\n// ── cursor (keyset) pagination ───────────────────────────────────────────────\n\n/**\n * Every set of columns that uniquely identifies a row of `table`: the primary key first,\n * then each unique constraint and unique index, then each column declared `.unique()`\n * inline. Sets are property names (what GraphQL inputs use), not database column names.\n *\n * `getTableConfig` is the dialect's own — the three dialects expose the same\n * `{ primaryKeys, uniqueConstraints, indexes }` shape but from different modules, so the\n * caller passes theirs in, as `getPrimaryKeyPropNamesFromConfig` does.\n *\n * Index entries whose columns are SQL expressions rather than plain columns are skipped:\n * an expression index is a valid conflict target in the database but cannot be named by a\n * column enum. Deduplicated, order-insensitive — a column that is both the primary key and\n * a unique constraint yields one set.\n */\nexport const getUniqueColumnSets = <TTable extends Table>(\n table: TTable,\n getTableConfig: (table: TTable) => {\n primaryKeys: { columns: { name: string }[] }[];\n uniqueConstraints?: { columns: { name: string }[] }[];\n indexes?: { config: { unique?: boolean; columns: any[] } }[];\n },\n): string[][] => {\n const cols = visibleColumns(table);\n const propNameByColumnName = new Map(Object.entries(cols).map(([propName, col]) => [(col as any).name, propName]));\n // A set is usable only if every one of its columns maps back to a property on the table.\n const toPropNames = (columnNames: (string | undefined)[]): string[] | undefined => {\n const propNames: string[] = [];\n for (const columnName of columnNames) {\n const propName = columnName === undefined ? undefined : propNameByColumnName.get(columnName);\n if (!propName) {\n return undefined;\n }\n propNames.push(propName);\n }\n return propNames.length ? propNames : undefined;\n };\n\n const config = getTableConfig(table);\n const candidates: (string[] | undefined)[] = [\n // Inline `.primaryKey()` columns, then table-level `primaryKey({ columns })`.\n Object.entries(cols)\n .filter(([, col]) => (col as any).primary)\n .map(([propName]) => propName),\n ...config.primaryKeys.map((pk) => toPropNames(pk.columns.map((c) => c.name))),\n ...(config.uniqueConstraints ?? []).map((uc) => toPropNames(uc.columns.map((c) => c.name))),\n ...(config.indexes ?? [])\n .filter((index) => index.config.unique)\n .map((index) => toPropNames(index.config.columns.map((c) => (c as any)?.name))),\n ...Object.entries(cols)\n .filter(([, col]) => (col as any).isUnique)\n .map(([propName]) => [propName]),\n ];\n\n const seen = new Set<string>();\n const sets: string[][] = [];\n for (const set of candidates) {\n if (!set?.length) {\n continue;\n }\n const key = [...set].sort().join(',');\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n sets.push(set);\n }\n return sets;\n};\n","// `distinctOn` for the dialects with no native support: the window-function key query the\n// resolver runs first, and the primary-key restriction it feeds into the real select.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { and, asc, eq, getColumns, inArray, or, type SQL, sql } from 'drizzle-orm';\nimport { DISTINCT_RN } from './column-enums.ts';\nimport { drizzleError } from './errors.ts';\nimport { primaryKeyOrderExprs } from './keys.ts';\nimport { orderByEntries, orderExpressions } from './order-by.ts';\n\n/**\n * Keeps the first row of each distinct combination of the requested columns, following the\n * query's own ordering, then applies `limit`/`offset` to what survives — and returns the\n * surviving rows' primary key values in that order.\n *\n * The relational query builder has no `distinct` support, so this runs as its own\n * `row_number() over (partition by … order by …)` pass and the main query is narrowed to the\n * keys it returns. `orderExprs` is the full ordering (the request's `orderBy` plus the primary\n * key tiebreak); the caller applies the same ordering to the main query, so the two agree.\n *\n * `partitionBy` prepends extra columns to the window's partition. A to-many relation field\n * uses it to pass the foreign key, which makes the pass distinct *within each parent* rather\n * than across the whole batch — the same meaning `distinct` has on a root list.\n */\nexport const selectDistinctKeys = async (params: {\n db: any;\n table: Table;\n tableName: string;\n distinct: string[];\n pkNames: readonly string[];\n where: SQL | undefined;\n orderBy: Record<string, any> | undefined;\n limit?: number;\n offset?: number;\n partitionBy?: Column[];\n}): Promise<Record<string, any>[]> => {\n const { db, table, tableName, distinct, pkNames, where, orderBy, limit, offset, partitionBy } = params;\n const cols = getColumns(table);\n\n if (!pkNames.length) {\n throw drizzleError(`Table ${tableName} has no primary key, so 'distinct' cannot be applied to it.`, {\n code: 'DRIZZLE_INVALID_DISTINCT',\n });\n }\n\n const requestedCols = distinct.map((name) => cols[name]).filter(Boolean);\n if (!requestedCols.length) {\n throw drizzleError(`No known columns were given to 'distinct' on ${tableName}.`, {\n code: 'DRIZZLE_INVALID_DISTINCT',\n });\n }\n const partitionCols = [...(partitionBy ?? []), ...requestedCols];\n\n const orderEntries = orderBy ? orderByEntries(orderBy) : [];\n // Both orderings must agree, so build each from the same entries — once against the table\n // (inside the window) and once against the subquery's fields (for the outer row order).\n const windowOrder = [\n ...orderEntries.flatMap(([column, direction, nulls]) =>\n orderExpressions(cols[column]!, direction, nulls, cols[column]!),\n ),\n ...primaryKeyOrderExprs(table, pkNames),\n ];\n\n const rowNumber = sql`row_number() over (partition by ${sql.join(partitionCols, sql`, `)} order by ${sql.join(\n windowOrder,\n sql`, `,\n )})`.as(DISTINCT_RN);\n\n const sub = db\n .select({ ...cols, [DISTINCT_RN]: rowNumber })\n .from(table)\n .where(where)\n .as('__dgql_distinct');\n\n const outerOrder = [\n ...orderEntries.flatMap(([column, direction, nulls]) =>\n orderExpressions(sub[column], direction, nulls, cols[column]!),\n ),\n ...pkNames.filter((name) => sub[name]).map((name) => asc(sub[name])),\n ];\n\n let query = db\n .select(Object.fromEntries(pkNames.map((name) => [name, sub[name]])))\n .from(sub)\n .where(eq(sub[DISTINCT_RN], 1))\n .orderBy(...outerOrder);\n\n if (offset) {\n query = query.offset(offset);\n }\n if (limit != null) {\n query = query.limit(limit);\n }\n\n return await query;\n};\n\n/**\n * Condition matching exactly the rows identified by `keys` — an `IN (…)` for a single-column\n * primary key, an `OR` of per-row equality for a composite one. `table` may be the aliased\n * RQB proxy.\n */\nexport const primaryKeyRestriction = (table: Table, pkNames: readonly string[], keys: Record<string, any>[]): SQL => {\n const cols = getColumns(table);\n\n if (pkNames.length === 1) {\n const name = pkNames[0]!;\n return inArray(\n cols[name]!,\n keys.map((key) => key[name]),\n );\n }\n\n return or(...keys.map((key) => and(...pkNames.map((name) => eq(cols[name]!, key[name])))))!;\n};\n","// The descriptions generated fields and inputs carry, assembled from the Drizzle schema and\n// whatever the caller passed in `docs`.\n\nimport type { Column } from 'drizzle-orm';\nimport { GraphQLNonNull } from 'graphql';\nimport type { SchemaDocs } from '../../type-converter/types.ts';\n\n/**\n * The `description` / `deprecationReason` a column field should carry, from the build's\n * documentation hooks. Both are omitted rather than set to `undefined` so a field config\n * built by spreading this stays identical to one built without it.\n */\nexport const columnDocs = (\n docs: SchemaDocs,\n column: Column,\n tableName: string,\n columnName: string,\n): { description?: string; deprecationReason?: string } => {\n const description = docs.describeColumn?.(column, { tableName, columnName });\n const deprecationReason = docs.deprecateColumn?.(column, { tableName, columnName });\n return {\n ...(description !== undefined ? { description } : {}),\n ...(deprecationReason !== undefined ? { deprecationReason } : {}),\n };\n};\n\n/**\n * A required input field cannot be deprecated — graphql-js rejects the schema outright, since\n * a client has no way to stop sending it. `deprecateColumn` is written against the column, not\n * against each generated input, so drop the reason where it cannot apply rather than making\n * the caller predict which inputs made the column non-null.\n */\nexport const inputFieldDocs = (\n docs: SchemaDocs,\n column: Column,\n tableName: string,\n columnName: string,\n fieldType: unknown,\n): { description?: string; deprecationReason?: string } => {\n const resolved = columnDocs(docs, column, tableName, columnName);\n if (resolved.deprecationReason !== undefined && fieldType instanceof GraphQLNonNull) {\n const { deprecationReason: _dropped, ...rest } = resolved;\n return rest;\n }\n return resolved;\n};\n","// `drizzleExecutorKey` — the context slot a caller can park a transaction (or any other\n// executor) in — and the lookups every generated resolver does through it.\n\n/**\n * Key on the GraphQL context object under which a caller can place a Drizzle transaction\n * (or any other executor: a pooled connection, a logging proxy). Every generated resolver\n * reads it at resolve time and runs its statements there instead of on the database the\n * schema was built from, which is what lets several mutations in one request share a\n * transaction and lets a query see that transaction's uncommitted rows:\n *\n * ```ts\n * await db.transaction(async (tx) => {\n * await graphql({ schema, source, contextValue: { [drizzleExecutorKey]: tx } });\n * });\n * ```\n *\n * Registered with `Symbol.for` so the ESM and CJS builds of this package agree on it when\n * both end up loaded in one process.\n */\nexport const drizzleExecutorKey: unique symbol = Symbol.for('drizzle-graphql:executor') as any;\n\n/**\n * The executor a resolver should run on: the request's transaction when the context\n * carries one, otherwise the database the schema was built from.\n */\nexport const resolveExecutor = <T>(db: T, context: any): T => {\n if (context && typeof context === 'object') {\n const executor = context[drizzleExecutorKey];\n if (executor) {\n return executor as T;\n }\n }\n return db;\n};\n\n/**\n * This request's executor together with the relational query builder to select through.\n *\n * `buildTimeQueryBase` decides whether the table supports the relational query builder at\n * all — a table with no relations has none, and the caller falls back to a plain select.\n * The executor only decides which connection the query runs on, so a transaction that is\n * missing `query` (or a table absent from its schema) keeps the build-time builder.\n */\nexport const resolveQueryExecutor = (\n db: any,\n context: any,\n tableName: string,\n buildTimeQueryBase: any,\n): { executor: any; queryBase: any } => {\n const executor = resolveExecutor(db, context);\n return {\n executor,\n queryBase: buildTimeQueryBase ? (executor?.query?.[tableName] ?? buildTimeQueryBase) : buildTimeQueryBase,\n };\n};\n","// The two shared input types every generated OrderBy is assembled from: `orderNulls` and\n// `innerOrder`. Both are built once per name they resolve to, so a build that renames its\n// types gets its own pair and every other build keeps sharing one.\n\nimport { GraphQLBoolean, GraphQLEnumType, GraphQLInputObjectType, GraphQLInt, GraphQLNonNull } from 'graphql';\nimport { sharedType, type TypeNameResolver } from './type-names.ts';\n\n/**\n * Where NULL values sort relative to non-NULL values. Compiled to native\n * `NULLS FIRST` / `NULLS LAST` on PostgreSQL and SQLite (3.30+); MySQL has no such\n * clause, so there it is emulated with an extra `<expr> IS NULL` sort key ahead of\n * the column itself.\n */\nexport const orderNullsType = (typeName: TypeNameResolver): GraphQLEnumType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'OrderNulls' },\n (name) =>\n new GraphQLEnumType({\n name,\n description: 'Where NULL values sort relative to non-NULL values',\n values: {\n first: {\n value: 'first',\n description: 'NULL values sort before all non-NULL values',\n },\n last: {\n value: 'last',\n description: 'NULL values sort after all non-NULL values',\n },\n },\n }),\n );\n\nconst orderDirectionType = (typeName: TypeNameResolver): GraphQLEnumType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'OrderDirection' },\n (name) =>\n new GraphQLEnumType({\n name,\n description: 'Order by direction',\n values: {\n asc: {\n value: 'asc',\n description: 'Ascending order',\n },\n desc: {\n value: 'desc',\n description: 'Descending order',\n },\n },\n }),\n );\n\nexport const innerOrderType = (typeName: TypeNameResolver): GraphQLInputObjectType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'InnerOrder' },\n (name) =>\n new GraphQLInputObjectType({\n name,\n fields: {\n direction: {\n type: new GraphQLNonNull(orderDirectionType(typeName)),\n },\n priority: {\n type: new GraphQLNonNull(GraphQLInt),\n description: 'Priority of current field',\n },\n nulls: {\n type: orderNullsType(typeName),\n description:\n \"Where NULL values sort. Defaults to the database's own rule (PostgreSQL: last on asc, first on desc; MySQL/SQLite: first on asc, last on desc)\",\n },\n matchFilterOrder: {\n type: GraphQLBoolean,\n description:\n \"Sort by this column's position in the `inArray` list the same request's `where` gives it, rather than by the column's own value — `direction: asc` keeps the list's order, `desc` reverses it. Requires an `inArray` filter on the same column at the top level of `where`, and cannot be combined with `after` or `distinct`.\",\n },\n },\n }),\n );\n","// The `limits`, `defaults` and `complexity` configs resolved per table, plus the estimator\n// functions the generated fields publish on `extensions.complexity`.\n\nimport { type DrizzleErrorContext, drizzleError } from './errors.ts';\n\n/** The shape `graphql-query-complexity`'s `fieldExtensionsEstimator` hands to a field's hint. */\ntype ComplexityEstimatorArgs = { args: Record<string, any>; childComplexity: number };\n\n/** A field's cost hint, published as `extensions.complexity` on the generated field config. */\nexport type ComplexityEstimator = (options: ComplexityEstimatorArgs) => number;\n\n/** {@link BuildSchemaConfig.complexity} with its defaults filled in. */\nexport type ResolvedComplexityOptions = {\n /** Rows a list field is assumed to return when the query passes no `limit`. */\n defaultListSize: number;\n /** Flat cost charged for an aggregate field, on top of the fields selected inside it. */\n aggregateCost: number;\n};\n\n/** {@link BuildSchemaConfig.limits} resolved for one table. `undefined` means no policy. */\nexport type ResolvedLimitPolicy = {\n defaultLimit: number | undefined;\n maxLimit: number | undefined;\n clampToMax: boolean;\n};\n\n/**\n * Looks up the limit policy for a table by its Drizzle schema key. Built once per schema by\n * `buildSchema`; `undefined` for a table the caller left unbounded.\n */\nexport type LimitPolicyFor = (tableName: string) => ResolvedLimitPolicy | undefined;\n\n/**\n * {@link BuildSchemaConfig.defaults} resolved for one table: the `orderBy` a read falls back\n * to when the request passes none, already in the shape the generated argument has.\n * `undefined` means the table declares no default and keeps whatever order the database\n * returns.\n */\nexport type DefaultOrderByFor = (tableName: string) => Record<string, any> | undefined;\n\n/**\n * Substitutes a table's default ordering for an absent `orderBy`.\n *\n * Applied where the arguments are first read, so everything downstream — the cursor tuple, a\n * `distinct` pass, the plain-select fallback — sees one effective ordering and cannot\n * disagree about it. Only a missing argument is replaced: `orderBy: {}` is a request for no\n * ordering, and stays one.\n */\nexport const withDefaultOrderBy = <T extends { orderBy?: any }>(\n args: T,\n tableName: string,\n defaults: DefaultOrderByFor | undefined,\n): T => {\n if (!defaults || args?.orderBy != null) {\n return args;\n }\n const fallback = defaults(tableName);\n return fallback ? { ...args, orderBy: fallback } : args;\n};\n\n/**\n * The `limit` a query actually runs with, given the policy for the table it reads.\n *\n * A request that passes no `limit` falls back to `defaultLimit`, or to `maxLimit` when only\n * that is configured — an absent limit means every row, which is above any maximum. A limit\n * the client did ask for is rejected when it exceeds `maxLimit`, since silently truncating a\n * page tells a paginating client it has reached the end when it has not; `clampToMax` opts\n * into the truncation instead. A limit the *policy* supplied is capped rather than rejected —\n * a misconfigured `defaultLimit` above `maxLimit` is the operator's problem, not something to\n * fail a client's query over.\n */\nexport const applyLimitPolicy = (\n limit: number | null | undefined,\n policy: ResolvedLimitPolicy | undefined,\n /**\n * Only a relation field passes this: its limit is applied while the *parent's* resolver is\n * building the eager query, so there is no relation-shaped catch to attach the context at.\n */\n errorCtx?: DrizzleErrorContext,\n): number | undefined => {\n if (!policy) {\n return limit ?? undefined;\n }\n const { defaultLimit, maxLimit, clampToMax } = policy;\n\n if (limit == null) {\n const fallback = defaultLimit ?? maxLimit;\n if (fallback === undefined) {\n return undefined;\n }\n return maxLimit === undefined ? fallback : Math.min(fallback, maxLimit);\n }\n\n if (maxLimit !== undefined && limit > maxLimit) {\n if (clampToMax) {\n return maxLimit;\n }\n throw drizzleError(`'limit' of ${limit} exceeds the maximum of ${maxLimit}.`, {\n code: 'DRIZZLE_LIMIT_EXCEEDED',\n ...errorCtx,\n });\n }\n return limit;\n};\n\n/** Merges a per-table override over the global policy, or `undefined` when neither bounds anything. */\nexport const resolveLimitPolicy = (\n global: { defaultLimit?: number; maxLimit?: number; clampToMax?: boolean } | undefined,\n table: { defaultLimit?: number; maxLimit?: number; clampToMax?: boolean } | undefined,\n): ResolvedLimitPolicy | undefined => {\n const defaultLimit = table?.defaultLimit ?? global?.defaultLimit;\n const maxLimit = table?.maxLimit ?? global?.maxLimit;\n if (defaultLimit === undefined && maxLimit === undefined) {\n return undefined;\n }\n return { defaultLimit, maxLimit, clampToMax: table?.clampToMax ?? global?.clampToMax ?? false };\n};\n\n/**\n * A paginated field costs its page size times whatever one row of it costs, so `users(limit: 100)\n * { posts(limit: 10) { id } }` is charged for the thousand rows it can return rather than the two\n * fields it mentions. `childComplexity` floors at 1 so a row is never free.\n *\n * The page size is the *effective* one: a request without `limit` is priced at the policy's\n * `defaultLimit` rather than the estimator's guess, and no request is priced above `maxLimit`,\n * so the cost a query is charged matches the rows it can actually pull.\n */\nexport const listFieldComplexity =\n (options: ResolvedComplexityOptions, policy?: ResolvedLimitPolicy): ComplexityEstimator =>\n ({ args, childComplexity }) => {\n const limit = args['limit'];\n const requested = typeof limit === 'number' && limit > 0 ? limit : undefined;\n let rows = requested ?? policy?.defaultLimit ?? options.defaultListSize;\n if (policy?.maxLimit !== undefined) {\n rows = Math.min(rows, policy.maxLimit);\n }\n return rows * Math.max(childComplexity, 1);\n };\n\n/**\n * An aggregate returns a single row but reads however many match, so its cost tracks the scan\n * rather than the response.\n */\nexport const aggregateFieldComplexity =\n (options: ResolvedComplexityOptions): ComplexityEstimator =>\n ({ childComplexity }) =>\n options.aggregateCost + childComplexity;\n","// A resolver's `info` carries the query AST, not the selection: reading which fields were\n// actually asked for means walking `fieldNodes`, resolving fragments against `info.fragments`,\n// honouring `@include` / `@skip`, and coercing each field's arguments. Every generated\n// resolver in this library needs that walk before it can decide which columns to SELECT and\n// which relations to join, so it happens on every request.\n//\n// This is an in-repo replacement for `graphql-parse-resolve-info`, which used to be a required\n// peer dependency. That package is CommonJS, so it reaches graphql through `require`, and it\n// decides whether a field has sub-selections with `instanceof` against whatever that `require`\n// returned. graphql 17 ships several builds of itself out of one package — a `development`\n// export condition routes to a whole second copy under `__dev__/`, with `.js`/`.mjs` behind the\n// format conditions — so any loader that resolves the CommonJS graph differently from the ESM\n// one hands it a different instance than the one that built the schema. The `instanceof` then\n// answers \"not composite\", the walk returns `fieldsByTypeName: {}` instead of throwing, and\n// every resolver downstream reads a selection of nothing. Upstream is dead (4.14.1, unchanged\n// since 2025-04-27) and its own peer range stops at 16, so npm refuses the install as well.\n//\n// The replacement keeps the `ResolveTree` shape byte-for-byte so nothing downstream moves, and\n// answers the \"is this composite / what are its fields\" questions structurally instead of by\n// `instanceof`, so it cannot silently disagree with the graphql copy that is executing the\n// query. Argument coercion is still graphql's own `getArgumentValues` — spec-correct handling\n// of variables, defaults, enums, input objects and list/non-null wrapping is not worth\n// re-deriving, and passing `info.variableValues` straight through works under both majors\n// (graphql 16 hands resolvers a plain map, graphql 17 a `{ sources, coerced }` record, and each\n// major's `getArgumentValues` expects its own).\n\nimport type { DirectiveNode, GraphQLResolveInfo, NamedTypeNode, SelectionNode, ValueNode } from 'graphql';\nimport { getArgumentValues, Kind } from 'graphql';\n\n/**\n * The selections made against one concrete type, keyed by the *response key* — the field's\n * alias when it has one, otherwise its name. A selection spanning an abstract type has one\n * entry per type condition it was written against (the interface or union itself included,\n * when fields were selected directly on it).\n */\nexport interface FieldsByTypeName {\n [typeName: string]: {\n [responseKey: string]: ResolveTree;\n };\n}\n\n/** One selected field: what was asked for, under what alias, with which arguments. */\nexport interface ResolveTree {\n /** The field name as declared in the schema. */\n name: string;\n /** The response key — the alias when the selection carried one, otherwise `name`. */\n alias: string;\n /** The field's arguments, coerced by graphql's own `getArgumentValues`. */\n args: {\n [argName: string]: unknown;\n };\n /** The field's own sub-selections, keyed by the type they were written against. */\n fieldsByTypeName: FieldsByTypeName;\n}\n\n/** Options accepted by {@link parseResolveInfo}. */\nexport interface ParseResolveInfoOptions {\n /**\n * Whether to descend into sub-selections and fragments. Defaults to `true`; `false` reads\n * only the root field's own name, alias and arguments.\n */\n deep?: boolean;\n}\n\n/**\n * A GraphQL type as this module needs to see it. Deliberately structural: the type objects on\n * `info` come from whichever copy of graphql is executing the query, which is not necessarily\n * the copy this module imported, so `instanceof` is not a question that can be asked here.\n */\ntype TypeLike = {\n name?: string;\n ofType?: TypeLike;\n getFields?: () => Record<string, { type?: TypeLike }>;\n getTypes?: () => unknown[];\n};\n\n/** Unwraps `[T]!`-style wrappers down to the named type. `getNamedType` without the realm tie. */\nconst namedTypeOf = (type: TypeLike | undefined): TypeLike | undefined => {\n let current = type;\n while (current?.ofType) {\n current = current.ofType;\n }\n return current;\n};\n\n/**\n * Whether a field's named output type has sub-selections. Object types and interfaces expose\n * `getFields`, unions expose `getTypes`; scalars and enums expose neither. Input object types\n * also expose `getFields`, but an input type can never be a field's output type, so there is\n * nothing here for that to collide with.\n */\nconst isCompositeLike = (type: TypeLike | undefined): boolean =>\n !!type && (typeof type.getFields === 'function' || typeof type.getTypes === 'function');\n\n/**\n * The fields declared on a type, or `undefined` when it has none to declare. A union is the\n * case that matters: it has no fields of its own, so a selection directly against one resolves\n * to nothing and is dropped — only the inline fragments underneath contribute.\n */\nconst fieldsOf = (type: TypeLike | undefined): Record<string, { type?: TypeLike }> | undefined =>\n typeof type?.getFields === 'function' ? type.getFields() : undefined;\n\n/**\n * The runtime variable values, in the plain-map form the directive check wants. graphql 17\n * wraps them in `{ sources, coerced }`; graphql 16 hands over the map itself.\n */\nconst coercedVariables = (info: GraphQLResolveInfo): Record<string, unknown> => {\n const values = info.variableValues as unknown;\n if (values && typeof values === 'object' && 'coerced' in (values as Record<string, unknown>)) {\n return ((values as { coerced?: Record<string, unknown> }).coerced ?? {}) as Record<string, unknown>;\n }\n return (values ?? {}) as Record<string, unknown>;\n};\n\n/** The value of a `@skip` / `@include` `if:` argument — a literal or a variable reference. */\nconst directiveIfValue = (info: GraphQLResolveInfo, value: ValueNode): unknown => {\n if (value.kind === Kind.VARIABLE) {\n return coercedVariables(info)[value.name.value];\n }\n if (value.kind === Kind.BOOLEAN) {\n return value.value;\n }\n return undefined;\n};\n\n/**\n * Whether `@skip` / `@include` on this selection exclude it. Applies to fields, fragment\n * spreads and inline fragments alike, which is where graphql puts them.\n */\nconst isExcluded = (\n info: GraphQLResolveInfo,\n node: { readonly directives?: ReadonlyArray<DirectiveNode> },\n): boolean => {\n for (const directive of node.directives ?? []) {\n const directiveName = directive.name.value;\n if (directiveName !== 'skip' && directiveName !== 'include') {\n continue;\n }\n const ifArgument = directive.arguments?.find((argument) => argument.name.value === 'if');\n if (!ifArgument) {\n continue;\n }\n const value = directiveIfValue(info, ifArgument.value);\n if (directiveName === 'skip' ? !!value : !value) {\n return true;\n }\n }\n return false;\n};\n\n/** The type a fragment's `on Type` condition names, looked up in the executing schema. */\nconst typeFromCondition = (info: GraphQLResolveInfo, condition: NamedTypeNode): TypeLike | undefined =>\n info.schema.getType(condition.name.value) as TypeLike | undefined;\n\n/**\n * Introspection meta-fields are not schema fields and never reach the database. `__typename` is\n * the one that turns up in practice; `__id` is excluded from the rule because a schema is free\n * to declare a field by that name.\n */\nconst isMetaField = (name: string): boolean => name.startsWith('__') && name !== '__id';\n\n/**\n * Merges one selection set into `tree`, which is a `fieldsByTypeName` map — the caller owns the\n * level, this owns the entries under `parentType`'s name.\n *\n * `activeFragments` is the set of fragment names on the current spread path. A document that\n * passed validation cannot contain a fragment cycle, but this parser also runs on trees a\n * caller assembled by hand, and an unbounded walk would hang rather than fail.\n */\nconst collectSelections = (\n selections: ReadonlyArray<SelectionNode>,\n info: GraphQLResolveInfo,\n tree: FieldsByTypeName,\n parentType: TypeLike | undefined,\n deep: boolean,\n activeFragments: Set<string>,\n): FieldsByTypeName => {\n const parentTypeName = parentType?.name;\n if (!parentTypeName) {\n return tree;\n }\n // Seeded even when nothing under it survives, so a consumer can tell \"selected nothing on\n // this type\" from \"never reached this type\" — the shape `graphql-parse-resolve-info` produced.\n let fields = tree[parentTypeName];\n if (!fields) {\n fields = {};\n tree[parentTypeName] = fields;\n }\n // Loop-invariant: the parent type is the same for every selection in this set, and this\n // walk runs on every resolve of every request.\n const parentFields = fieldsOf(parentType);\n\n for (const selection of selections) {\n if (isExcluded(info, selection)) {\n continue;\n }\n\n if (selection.kind === Kind.FIELD) {\n const name = selection.name.value;\n if (isMetaField(name)) {\n continue;\n }\n\n const fieldDef = parentFields?.[name];\n // A field the parent type does not declare: either a union's own selection set, which\n // carries nothing but meta-fields, or a document that never passed validation.\n if (!fieldDef) {\n continue;\n }\n\n const fieldType = namedTypeOf(fieldDef.type);\n if (!fieldType) {\n continue;\n }\n const composite = isCompositeLike(fieldType);\n\n const alias = selection.alias?.value || name;\n let node = fields[alias];\n if (!node) {\n node = {\n name,\n alias,\n // Spread out of the null-prototype object graphql returns, so downstream code can\n // treat it as an ordinary record. The casts are on the installed major's own\n // signature: graphql 17 brands its field type and takes a `{ sources, coerced }`\n // variables record where 16 takes a plain map, and `info` carries whichever shape\n // that major's executor produced.\n args: {\n ...getArgumentValues(\n fieldDef as unknown as Parameters<typeof getArgumentValues>[0],\n selection,\n info.variableValues as unknown as Parameters<typeof getArgumentValues>[2],\n ),\n },\n fieldsByTypeName: composite && fieldType.name ? { [fieldType.name]: {} } : {},\n };\n fields[alias] = node;\n }\n\n // Two selections of the same response key merge, exactly as execution merges them: the\n // first one's arguments stand (validation requires them to be identical) and both\n // sub-selections are collected into the one node.\n if (selection.selectionSet && deep && composite) {\n collectSelections(\n selection.selectionSet.selections,\n info,\n node.fieldsByTypeName,\n fieldType,\n deep,\n activeFragments,\n );\n }\n continue;\n }\n\n if (!deep) {\n continue;\n }\n\n if (selection.kind === Kind.FRAGMENT_SPREAD) {\n const fragmentName = selection.name.value;\n const fragment = info.fragments?.[fragmentName];\n if (!fragment) {\n throw new Error(\n `Drizzle-GraphQL Error: unknown fragment '${fragmentName}' — it is spread in the query but not defined in the document.`,\n );\n }\n if (activeFragments.has(fragmentName)) {\n continue;\n }\n\n const fragmentType = fragment.typeCondition ? typeFromCondition(info, fragment.typeCondition) : parentType;\n if (!isCompositeLike(fragmentType)) {\n continue;\n }\n\n activeFragments.add(fragmentName);\n try {\n // Spread into the *caller's* level, not a nested one: a fragment contributes its fields\n // to the selection it was spread into, keyed by its own type condition.\n collectSelections(fragment.selectionSet.selections, info, tree, fragmentType, deep, activeFragments);\n } finally {\n activeFragments.delete(fragmentName);\n }\n continue;\n }\n\n if (selection.kind === Kind.INLINE_FRAGMENT) {\n const fragmentType = selection.typeCondition ? typeFromCondition(info, selection.typeCondition) : parentType;\n if (!isCompositeLike(fragmentType)) {\n continue;\n }\n collectSelections(selection.selectionSet.selections, info, tree, fragmentType, deep, activeFragments);\n }\n }\n\n return tree;\n};\n\n/** The first key of an object, without materializing the whole key array to discard it. */\nconst firstKey = (object: Record<string, unknown>): string | undefined => {\n for (const key in object) {\n return key;\n }\n return undefined;\n};\n\n/**\n * Reads the selection under a resolver's own field out of its `info`, as a tree of\n * {@link ResolveTree} nodes.\n *\n * ```ts\n * const parsed = parseResolveInfo(info, { deep: true })!;\n * const selected = parsed.fieldsByTypeName['Users']; // keyed by response key\n * ```\n *\n * Returns `undefined` when the resolver's field produced no node at all, which in practice\n * means `info` carried no field nodes.\n */\nexport const parseResolveInfo = (\n info: GraphQLResolveInfo,\n options: ParseResolveInfoOptions = {},\n): ResolveTree | undefined => {\n const fieldNodes = info.fieldNodes;\n if (!fieldNodes) {\n throw new Error(\n 'Drizzle-GraphQL Error: resolve info carries no fieldNodes, so no selection could be read from it.',\n );\n }\n\n const tree = collectSelections(\n fieldNodes,\n info,\n {},\n info.parentType as unknown as TypeLike,\n options.deep ?? true,\n new Set(),\n );\n\n // Every field node handed to one resolver shares one response key under one parent type, so\n // the tree has exactly one entry at each of its two top levels — which is the node wanted.\n const typeKey = firstKey(tree);\n const fields = typeKey === undefined ? undefined : tree[typeKey];\n const fieldKey = fields && firstKey(fields);\n return fieldKey === undefined ? undefined : fields?.[fieldKey];\n};\n","/**\n * Atomic column operations on the update `set` (`features.fieldUpdateOperations`).\n *\n * Without them `Update<Table>Input` is set-only, so \"increment the view count\" is a read\n * followed by a write of the value the read returned — two round trips, and a lost update\n * whenever two clients read the same number. The operation happens in the database instead:\n * `set: { views: { increment: 1 } }` compiles to `SET views = views + 1`.\n *\n * The build side turns a qualifying column's update-input field into an operations input;\n * the runtime side splits a `set` back into plain column values and SQL expressions, which\n * drizzle's `.set()` accepts side by side.\n */\nimport type { Column, SQL, Table } from 'drizzle-orm';\nimport { getColumns, sql } from 'drizzle-orm';\nimport {\n GraphQLFloat,\n GraphQLInputObjectType,\n type GraphQLInputType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n type GraphQLScalarType,\n} from 'graphql';\nimport { remapFromGraphQLCore, remapFromGraphQLSingleInput } from '../data-mappers/index.ts';\nimport { GraphQLBigIntString, GraphQLDecimalString } from '../scalars/index.ts';\nimport { drizzleColumnToGraphQLType, getColumnScalarOverride } from '../type-converter/index.ts';\nimport { drizzleError } from './common/errors.ts';\nimport type { TypeNameResolver } from './common/type-names.ts';\n\n/** What a column's update-input field offers: arithmetic, list append, or nothing. */\nexport type FieldUpdateKind = 'numeric' | 'list' | 'none';\n\n/**\n * The scalars arithmetic is offered on. Decimal and BigInt transport as strings but are\n * numbers in the database, so `views: { increment: \"1\" }` is as meaningful there as on an\n * `Int`. Identity rather than name: a column an override owns is excluded before this is\n * consulted, so these are always the built-ins.\n */\nconst NUMERIC_SCALARS = new Set<GraphQLInputType>([\n GraphQLInt,\n GraphQLFloat,\n GraphQLBigIntString,\n GraphQLDecimalString,\n]);\n\n/**\n * Column types that convert to a GraphQL list without being a list *in the database* —\n * a bytea reads as `[Int]`, a vector and a geometry point as `[Float]` — so appending to\n * them is not the operation `push` means.\n */\nconst NON_LIST_ARRAY_COLUMNS = new Set(['PgVector', 'PgGeometry', 'PgBytea']);\n\nconst kindCache = new WeakMap<Column, FieldUpdateKind>();\n\n/**\n * Whether a column takes an operations input, and which one.\n *\n * A column owned by a scalar override is always `'none'`: the override decides what the\n * column accepts, and wrapping it would overrule that. Everything else is decided by the\n * GraphQL type the column already converts to, so the operations follow the same\n * scalar-mapping rules as the rest of the schema.\n */\nexport const fieldUpdateKind = (column: Column, columnName: string, tableName: string): FieldUpdateKind => {\n const cached = kindCache.get(column);\n if (cached) {\n return cached;\n }\n\n let kind: FieldUpdateKind = 'none';\n if (!getColumnScalarOverride(column, true)) {\n const { type } = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, true);\n if (NUMERIC_SCALARS.has(type)) {\n kind = 'numeric';\n } else if (type instanceof GraphQLList && !NON_LIST_ARRAY_COLUMNS.has((column as any).columnType)) {\n kind = 'list';\n }\n }\n\n kindCache.set(column, kind);\n return kind;\n};\n\n/** `${Scalar}FieldUpdate` / `${Scalar}ListFieldUpdate`, shared by every column of that type. */\nconst inputCache = new Map<string, GraphQLInputObjectType>();\n\nconst namedFieldUpdateInput = (\n name: string,\n fields: () => Record<string, { type: GraphQLInputType; description: string }>,\n description: string,\n): GraphQLInputObjectType => {\n const cached = inputCache.get(name);\n if (cached) {\n return cached;\n }\n const input = new GraphQLInputObjectType({ name, description, fields: fields() });\n inputCache.set(name, input);\n return input;\n};\n\n/**\n * The operations input replacing a column's plain field on the update input, or `undefined`\n * when the column keeps its plain type.\n *\n * The type is named for the scalar, not the column, so every `Int` column in the schema\n * shares one `IntFieldUpdate` — the operations are the same wherever they appear.\n */\nexport const fieldUpdateInputType = (\n column: Column,\n columnName: string,\n tableName: string,\n resolveName?: TypeNameResolver,\n): GraphQLInputObjectType | undefined => {\n const kind = fieldUpdateKind(column, columnName, tableName);\n if (kind === 'none') {\n return undefined;\n }\n // Named for the scalar rather than the column, so the naming rule is asked without a table:\n // one instance covers every column of that type across the schema.\n const nameOf = (defaultName: string) =>\n resolveName?.({ kind: 'fieldUpdateInput', defaultName, operation: kind }) ?? defaultName;\n\n const { type } = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, true);\n\n if (kind === 'numeric') {\n const scalar = type as GraphQLScalarType;\n return namedFieldUpdateInput(\n nameOf(`${scalar.name}FieldUpdate`),\n () => ({\n set: { type: scalar, description: 'Replace the current value with this one' },\n increment: { type: scalar, description: 'Add this to the current value (SQL `column + value`)' },\n decrement: { type: scalar, description: 'Subtract this from the current value (SQL `column - value`)' },\n multiply: { type: scalar, description: 'Multiply the current value by this (SQL `column * value`)' },\n divide: {\n type: scalar,\n description: 'Divide the current value by this (SQL `column / value`), rounding as the database does',\n },\n }),\n `An update to a ${scalar.name} column: exactly one of these operations`,\n );\n }\n\n // The element type carries the list's own non-null wrapper, so `push` and `set` accept\n // exactly what the plain field accepted.\n const list = type as GraphQLList<GraphQLInputType>;\n const element = list.ofType;\n const elementName = element instanceof GraphQLNonNull ? String(element.ofType) : String(element);\n return namedFieldUpdateInput(\n nameOf(`${elementName}ListFieldUpdate`),\n () => ({\n set: { type: list, description: 'Replace the current array with this one' },\n push: { type: list, description: 'Append these elements to the current array' },\n }),\n `An update to a ${elementName} array column: exactly one of these operations`,\n );\n};\n\n/** The operation keys, in the order they are reported when a caller passes several. */\nconst OPERATIONS = ['set', 'increment', 'decrement', 'multiply', 'divide', 'push'] as const;\n\n/**\n * The single operation an operations input carries. graphql-js has no `@oneOf` on the\n * version range this library supports, so \"exactly one\" is enforced here rather than by the\n * type — and a caller who passes none has written `{}`, which would otherwise update\n * nothing while looking like it updated something.\n */\nconst singleOperation = (value: Record<string, any>, columnName: string): [string, any] => {\n const given = OPERATIONS.filter((operation) => value[operation] !== undefined);\n if (given.length === 1) {\n return [given[0]!, value[given[0]!]];\n }\n throw drizzleError(\n given.length\n ? `Field '${columnName}' takes exactly one update operation, but ${given.length} were given (${given.join(', ')}).`\n : `Field '${columnName}' was given no update operation. Pass exactly one of ${OPERATIONS.join(', ')}.`,\n { code: 'DRIZZLE_INVALID_UPDATE_OPERATION' },\n );\n};\n\n/** An update `set` split into values drizzle assigns directly and ones it assigns from SQL. */\nexport type SplitUpdateValues = {\n /** Column values still to go through `remapFromGraphQLSingleInput`. */\n columns: Record<string, any>;\n /** Column-relative expressions, already driver-ready, to merge into the same `.set()`. */\n expressions: Record<string, SQL>;\n};\n\n/**\n * Splits an update `set` into plain values and column-relative SQL expressions.\n *\n * Only columns the build side gave an operations input to are read as operations, so a JSON\n * column that happens to hold `{ increment: 1 }` is still just a value. `set` is the\n * explicit spelling of a plain assignment and stays on the plain side, where the usual\n * input remapping applies to it.\n */\nexport const splitFieldUpdateOperations = (\n values: Record<string, any>,\n table: Table,\n tableName: string,\n): SplitUpdateValues => {\n const cols = getColumns(table);\n const columns: Record<string, any> = {};\n const expressions: Record<string, SQL> = {};\n\n for (const [columnName, value] of Object.entries(values)) {\n const column = cols[columnName];\n // An unknown key is left for the remapper, whose error names it.\n if (!column || value === null || value === undefined) {\n columns[columnName] = value;\n continue;\n }\n\n // The operations arrive as an input object; a plain value is a plain assignment. That\n // is what makes this safe to run whether or not `features.fieldUpdateOperations` is on —\n // with it off, a numeric or list column's field is typed as the scalar or the list, so\n // graphql-js has already ruled out the object shape by the time the value gets here.\n const isOperations = typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date);\n if (!isOperations || fieldUpdateKind(column as Column, columnName, tableName) === 'none') {\n columns[columnName] = value;\n continue;\n }\n\n const [operation, operand] = singleOperation(value, columnName);\n if (operation === 'set') {\n columns[columnName] = operand;\n continue;\n }\n\n const param = sql.param(remapFromGraphQLCore(operand, column as Column, columnName), column);\n expressions[columnName] =\n operation === 'increment'\n ? sql`${column} + ${param}`\n : operation === 'decrement'\n ? sql`${column} - ${param}`\n : operation === 'multiply'\n ? sql`${column} * ${param}`\n : operation === 'divide'\n ? sql`${column} / ${param}`\n : // `push`: array concatenation, which is the only dialect-specific operation\n // here — and arrays are a PostgreSQL column type to begin with.\n sql`${column} || ${param}`;\n }\n\n return { columns, expressions };\n};\n\n/**\n * Remaps an update `set` into the values drizzle's `.set()` takes: plain columns through the\n * usual input remapping, column-relative operations as SQL expressions alongside them.\n *\n * Safe to call on every update path regardless of `features.fieldUpdateOperations` — see the\n * shape check in {@link splitFieldUpdateOperations}.\n *\n * This is the single funnel every update goes through — the plural and `Single` mutations,\n * `updateMany`, the `Count` mutations and the MySQL builder's own — which is why it is the\n * one place that has to tell the remapper it is serving an update rather than an insert.\n */\nexport const remapUpdateInput = (values: Record<string, any>, table: Table, tableName: string): Record<string, any> => {\n const { columns, expressions } = splitFieldUpdateOperations(values, table, tableName);\n const remapped = remapFromGraphQLSingleInput(columns, table, 'update');\n return Object.keys(expressions).length ? { ...remapped, ...expressions } : remapped;\n};\n","// Shaping of the config objects handed to drizzle's relational query builder\n// (`findMany` / `findFirst` and each entry of a `with:` tree).\n\n/**\n * A copy of a relational query config with every key whose value is `undefined` left out.\n *\n * drizzle-orm rc.5 snapshots test `\"where\" in params` rather than its value, and throw\n * `Unexpected 'undefined' in filter value` for `{ where: undefined }`; rc.4 read the value and\n * treated both the same. The library builds its configs with conditional keys\n * (`where: cond ? … : undefined`), so every config goes through here before it reaches drizzle.\n * Only `where` is checked that way today, but leaving out every undefined key costs nothing\n * and keeps the next key that gets the same treatment from breaking queries.\n *\n * Shallow on purpose: nested `with:` entries are built (and passed through here) one level at\n * a time, and the values of the other keys are drizzle's own (column maps, callbacks, RAW).\n */\nexport const omitUndefinedKeys = <T extends Record<string, unknown>>(config: T): T => {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(config)) {\n if (value !== undefined) {\n out[key] = value;\n }\n }\n return out as T;\n};\n","// Reading the requested columns off a parsed selection tree, in both shapes the builders need —\n// the relational query builder's `columns` map, and a SQL select list.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { getColumns } from 'drizzle-orm';\nimport type { ResolveTree } from '../../parse-resolve-info.ts';\nimport type { SelectedColumnsRaw, SelectedSQLColumns, TableNamedRelations } from '../types.ts';\nimport { extractRelationJoinColumns } from './relations.ts';\n\nconst rqbCrashTypes = ['SQLiteBigInt', 'SQLiteBlobJson', 'SQLiteBlobBuffer'];\n\n/**\n * Everything needed to work out which extra columns a selection implies. Passed to the column\n * extractors so a requested `<relation>Aggregate` field can pull in the join column it resolves\n * from, which the client has no reason to have selected itself.\n */\nexport interface SelectionCtx {\n tableName: string;\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n tables: Record<string, Table>;\n /**\n * Every relation on the table, including those `relationMap` omits because they are not\n * eager-loaded. A lazily-resolved relation still correlates on a join column, so the\n * column extractors need to see it even when the eager map doesn't.\n */\n allRelations?: Record<string, Record<string, TableNamedRelations>>;\n}\n\nconst AGGREGATE_FIELD_SUFFIX = 'Aggregate';\n\n/**\n * Property names of the join columns that this selection's relation fields correlate on.\n * Without them the parent row reaches the relation resolver with no key: an aggregate counts\n * 0 and a relation list comes back empty.\n *\n * Needed by every relation field that resolves through its own resolver rather than the\n * parent's `with:` clause — `<relation>Aggregate` fields, which are always lazy; relations\n * excluded by `eagerLoadRelations`; and relations dropped from `with:` because they were\n * selected more than once under different aliases. Forcing the column for *any* selected\n * relation covers all three without the extractor having to predict which path will run: the\n * cost is one extra column (usually the primary key) in the parent SELECT, and GraphQL only\n * returns the fields the query asked for, so it never reaches the response.\n */\nconst relationJoinColumns = (\n tree: Record<string, ResolveTree>,\n table: Table,\n selectionCtx: SelectionCtx | undefined,\n): string[] => {\n if (!selectionCtx) {\n return [];\n }\n const relations =\n (selectionCtx.allRelations ?? selectionCtx.relationMap)[selectionCtx.tableName] ??\n selectionCtx.relationMap[selectionCtx.tableName];\n if (!relations) {\n return [];\n }\n\n const tableColumns = getColumns(table);\n const needed: string[] = [];\n\n for (const fieldData of Object.values(tree)) {\n // A column that happens to be named like a relation is a column.\n if (tableColumns[fieldData.name]) {\n continue;\n }\n\n const relEntry = fieldData.name.endsWith(AGGREGATE_FIELD_SUFFIX)\n ? relations[fieldData.name.slice(0, -AGGREGATE_FIELD_SUFFIX.length)]\n : relations[fieldData.name];\n const targetTable = relEntry ? selectionCtx.tables[relEntry.targetTableName] : undefined;\n if (!relEntry || !targetTable) {\n continue;\n }\n\n const joinCols = extractRelationJoinColumns(relEntry, table, targetTable);\n if (joinCols) {\n needed.push(joinCols.localColPropName);\n }\n }\n\n return needed;\n};\n\n/**\n * The column the extractors fall back to when a selection names none of its own — a query that\n * asked only for `__typename`, or only for relation fields. The relational query builder still\n * needs at least one column, and some SQLite column types crash it when they are the only one\n * selected, so a column of any other type is preferred and the first column is the last resort.\n */\nconst fallbackColumnName = (tableColumns: Record<string, Column>): string => {\n const columnKeys = Object.entries(tableColumns);\n return columnKeys.find(([, column]) => !rqbCrashTypes.includes(column.columnType))?.[0] ?? columnKeys[0]![0];\n};\n\n/**\n * Property names of the columns a selection reads: the ones it names itself, plus the join\n * columns its relation fields correlate on, plus the fallback when that leaves nothing.\n */\nconst selectedColumnNames = (\n tree: Record<string, ResolveTree>,\n table: Table,\n selectionCtx: SelectionCtx | undefined,\n): string[] => {\n const tableColumns = getColumns(table);\n const names: string[] = [];\n\n for (const fieldData of Object.values(tree)) {\n if (!tableColumns[fieldData.name]) {\n continue;\n }\n\n names.push(fieldData.name);\n }\n\n names.push(...relationJoinColumns(tree, table, selectionCtx));\n\n if (!names.length) {\n names.push(fallbackColumnName(tableColumns));\n }\n\n return names;\n};\n\n/** The requested columns as the relational query builder's `columns` map. */\nexport const extractSelectedColumnsFromTree = (\n tree: Record<string, ResolveTree>,\n table: Table,\n selectionCtx?: SelectionCtx,\n): Record<string, true> => {\n const selectedColumns: SelectedColumnsRaw = selectedColumnNames(tree, table, selectionCtx).map((columnName) => [\n columnName,\n true,\n ]);\n\n return Object.fromEntries(selectedColumns);\n};\n\n/**\n * The same columns as a SQL select list.\n *\n * Can't automatically determine column type on type level\n * Since drizzle table types extend eachother\n */\nexport const extractSelectedColumnsFromTreeSQLFormat = <TColType extends Column = Column>(\n tree: Record<string, ResolveTree>,\n table: Table,\n selectionCtx?: SelectionCtx,\n): Record<string, TColType> => {\n const tableColumns = getColumns(table);\n const selectedColumns: SelectedSQLColumns = selectedColumnNames(tree, table, selectionCtx).map((columnName) => [\n columnName,\n tableColumns[columnName]!,\n ]);\n\n return Object.fromEntries(selectedColumns) as Record<string, TColType>;\n};\n","// Turning a parsed selection tree into the relational query builder's `with:` clause, and\n// pruning the relations that opted out of eager loading.\n\nimport type { Table } from 'drizzle-orm';\nimport { is, One } from 'drizzle-orm';\nimport type { ResolveTree } from '../../parse-resolve-info.ts';\nimport type { ProcessedTableSelectArgs, TableNamedRelations, TableSelectArgs } from '../types.ts';\nimport { isCursorFieldSelected } from './cursor.ts';\nimport { primaryKeyOrderExprs } from './keys.ts';\nimport type { DefaultOrderByFor, LimitPolicyFor } from './limits.ts';\nimport { applyLimitPolicy, withDefaultOrderBy } from './limits.ts';\nimport type { TypeNameMapper } from './naming.ts';\nimport { resolveObjectTypeName } from './naming.ts';\nimport { extractOrderBy } from './order-by.ts';\nimport type { DeletedMode, ScopeResolver } from './policies.ts';\nimport { withScope } from './policies.ts';\nimport type { RelationFilterBase } from './relation-filters.ts';\nimport { extractFilters, relationFilterCtx } from './relation-filters.ts';\nimport { omitUndefinedKeys } from './rqb-config.ts';\nimport { extractSelectedColumnsFromTree } from './selected-columns.ts';\nimport type { TypeNameResolver } from './type-names.ts';\n\n/**\n * The build-wide policy the walk carries down unchanged. Grouped rather than passed\n * positionally because the recursion below re-passes every one of them as it descends, and\n * five of the six are object-or-undefined — a positional list of those is a silent hazard\n * (a caller that means \"no limits, no scope\" writes three bare `undefined`s in a row).\n */\nexport interface RelationParamsOptions {\n typeNameMapper?: TypeNameMapper;\n filterCtx?: RelationFilterBase;\n limits?: LimitPolicyFor;\n scope?: ScopeResolver;\n defaultOrderBy?: DefaultOrderByFor;\n resolveName?: TypeNameResolver;\n}\n\nexport const extractRelationsParams = (\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n tables: Record<string, Table>,\n tableName: string,\n info: ResolveTree | undefined,\n typeName: string,\n options: RelationParamsOptions = {},\n): Record<string, Partial<ProcessedTableSelectArgs>> | undefined => {\n const { typeNameMapper, filterCtx, limits, scope, defaultOrderBy, resolveName } = options;\n if (!info) {\n return undefined;\n }\n\n const relationsForTable = relationMap[tableName];\n if (!relationsForTable) {\n return undefined;\n }\n\n const baseField = info.fieldsByTypeName[typeName];\n if (!baseField) {\n return undefined;\n }\n\n // The parsed tree keys its entries by response key — the alias — so a relation is found by\n // the `name` its selections carry, not by the key they sit under. Grouped once here rather\n // than searched per relation: the loop below runs over every relation the table declares,\n // selected or not, and used to walk the whole selection set three times for each of them.\n const selectionsByName = new Map<string, ResolveTree[]>();\n for (const selection of Object.values(baseField) as ResolveTree[]) {\n const selections = selectionsByName.get(selection.name);\n if (selections) {\n selections.push(selection);\n } else {\n selectionsByName.set(selection.name, [selection]);\n }\n }\n\n const args: Record<string, Partial<ProcessedTableSelectArgs>> = {};\n\n for (const [relName, relEntry] of Object.entries(relationsForTable)) {\n const { targetTableName, targetPkNames } = relEntry;\n // The relation field resolves to the target table's own type, e.g. \"Posts\" not \"UsersPostsRelation\".\n const relTypeName = resolveObjectTypeName(targetTableName, typeNameMapper, resolveName);\n const selections = selectionsByName.get(relName);\n if (!selections) {\n continue;\n }\n const field = selections[0]!;\n\n // The `with:` clause is keyed by relation name, so one relation selected twice under\n // different aliases has no eager representation: the first selection's args and column\n // set would win, and both aliases would then read the same pre-fetched array off the\n // parent — wrong rows for the loser, and missing columns it selected. Drizzle's RQB\n // cannot fetch one relation twice under two keys, so there is no eager fix. Leave the\n // relation out of `with:` and let every alias resolve through the field resolver's\n // batch loader, which keys its loader by the serialized args and so is per-alias\n // correct (and still batched across parents).\n if (selections.length > 1) {\n continue;\n }\n const relFieldSelection = field.fieldsByTypeName[relTypeName];\n\n // Guard: if the relation type is not in fieldsByTypeName, this field is\n // either an aliased scalar column (not an actual relation) or the relation\n // was not selected in the query. Skip it in both cases.\n if (!relFieldSelection) {\n continue;\n }\n\n // `after`, `distinct` and the `cursor` field are the relation-level half of the root\n // list's keyset and distinct machinery, and drizzle's `with:` clause can express none of\n // them: keyset needs a predicate over the request's own total order, distinct needs a\n // window pass, and a cursor has to be computed from the raw row. As with an aliased\n // relation above, the fix is to leave the relation out of the eager clause — the field\n // resolver's batch loader implements all three, still in one query per relation.\n const eagerArgs = field.args as Partial<TableSelectArgs> | undefined;\n if (\n !is((relEntry as any).relation ?? relEntry, One) &&\n (eagerArgs?.after != null ||\n !!(eagerArgs?.distinct as string[] | undefined)?.length ||\n isCursorFieldSelected(relFieldSelection, tables[targetTableName]!))\n ) {\n continue;\n }\n\n const columns = extractSelectedColumnsFromTree(relFieldSelection, tables[targetTableName]!, {\n tableName: targetTableName,\n relationMap,\n tables,\n allRelations: filterCtx?.relationMap,\n });\n\n const thisRecord: Partial<ProcessedTableSelectArgs> = {};\n thisRecord.columns = columns;\n\n // The eager path reads its arguments off the AST rather than through the relation field's\n // resolver, so the target's default ordering has to be substituted here too — otherwise\n // an eagerly loaded relation would come back in a different order from a lazily loaded one.\n const relationArgs: Partial<TableSelectArgs> | undefined = is(relEntry.relation, One)\n ? field.args\n : withDefaultOrderBy(field.args ?? {}, targetTableName, defaultOrderBy);\n\n const offset = relationArgs?.offset ?? undefined;\n // The eager path reads its arguments off the AST rather than through the relation field's\n // resolver, so the policy has to be applied here too — otherwise an eagerly loaded\n // relation would be the one way around it. A to-one relation takes no `limit` and is a\n // single row by definition, so it is left alone.\n const limit = is(relEntry.relation, One)\n ? (relationArgs?.limit ?? undefined)\n : applyLimitPolicy(relationArgs?.limit, limits?.(targetTableName), {\n table: targetTableName,\n operation: 'relation',\n relation: relName,\n });\n\n // drizzle-orm v1 RQB calls both `where` and `orderBy` callbacks with an\n // aliased table proxy (e.g. d0, d1). Pass the proxy through so column\n // references in the generated SQL match the CTE alias rather than the\n // original unaliased table name.\n const relWhere = relationArgs?.where;\n // A relation field's soft-delete default is the target's, not the root default — a\n // required to-one relation, and a table declared `scope: 'root'`, both read INCLUDE.\n const relDeleted =\n ((relationArgs as any)?.deleted as DeletedMode | undefined) ??\n scope?.relationDefault(\n targetTableName,\n is(relEntry.relation, One) && (relEntry.relation as any).optional === false,\n );\n // The eager path is the one read that never passes through the relation field's own\n // resolver, so the target's scope has to be applied here as well — otherwise selecting a\n // relation would be the way around it.\n thisRecord.where =\n relWhere || scope?.has(targetTableName, relDeleted)\n ? {\n RAW: (aliasedTable: Table) =>\n withScope(\n scope,\n targetTableName,\n aliasedTable,\n relWhere\n ? extractFilters(aliasedTable, relName, relWhere, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n relDeleted,\n ),\n }\n : undefined;\n // When a relation is paginated (limit/offset) but unordered, default to the target's\n // primary key so the per-parent slice is deterministic. Drizzle's RQB calls orderBy\n // with the aliased table proxy, so resolve the PK columns from it. targetPkNames is\n // resolved at build time and includes composite keys.\n const hasPagination = offset != null || limit != null;\n const pkNames = targetPkNames ?? [];\n thisRecord.orderBy = relationArgs?.orderBy\n ? (aliasedTable: Table) =>\n extractOrderBy(aliasedTable, relationArgs.orderBy!, relationFilterCtx(filterCtx, targetTableName), relWhere)\n : hasPagination && pkNames.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined;\n thisRecord.offset = offset;\n thisRecord.limit = limit;\n\n const relWith = extractRelationsParams(relationMap, tables, targetTableName, field, relTypeName, options);\n thisRecord.with = relWith;\n\n args[relName] = omitUndefinedKeys(thisRecord);\n }\n\n return args;\n};\n\n/**\n * Returns a copy of `relationMap` containing only the relations that should be eagerly\n * pre-fetched (per the `shouldEagerLoad` predicate). Pass the result wherever a query or\n * mutation resolver builds its `with:` clause; pass the full map to type generation so\n * opted-out relations still get a (lazily-resolved) field. Relations excluded here are\n * never added to `with:`, so they don't overfetch — they resolve through their field\n * resolver instead (or a resolver you override, e.g. via `@graphql-tools/schema`).\n */\nexport const pruneNonEagerRelations = (\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n shouldEagerLoad: (tableName: string, relationName: string) => boolean,\n): Record<string, Record<string, TableNamedRelations>> => {\n const out: Record<string, Record<string, TableNamedRelations>> = {};\n for (const [tableName, rels] of Object.entries(relationMap)) {\n out[tableName] = Object.fromEntries(\n Object.entries(rels).filter(([relationName]) => shouldEagerLoad(tableName, relationName)),\n );\n }\n return out;\n};\n","// The read path at resolve time: running a relational select with everything the arguments\n// asked for, and eager-loading relations onto the rows a mutation returns.\n\nimport type { Table } from 'drizzle-orm';\nimport { and, inArray, type SQL, sql } from 'drizzle-orm';\nimport { remapToGraphQLArrayOutput, remapToGraphQLSingleOutput } from '../../data-mappers/index.ts';\nimport type { ResolveTree } from '../../parse-resolve-info.ts';\nimport type { ProcessedTableSelectArgs, TableNamedRelations } from '../types.ts';\nimport type { CursorOrderEntry, NullOrdering } from './cursor.ts';\nimport {\n attachRowCursors,\n buildCursorCondition,\n cursorOrderExprs,\n cursorOrderingEntries,\n decodeCursor,\n isCursorFieldSelected,\n orderByCursorObstacle,\n} from './cursor.ts';\nimport { primaryKeyRestriction, selectDistinctKeys } from './distinct.ts';\nimport { drizzleError } from './errors.ts';\nimport { primaryKeyOrderExprs } from './keys.ts';\nimport type { DefaultOrderByFor, LimitPolicyFor } from './limits.ts';\nimport type { TypeNameMapper } from './naming.ts';\nimport { extractOrderBy } from './order-by.ts';\nimport type { DeletedMode, ScopeResolver } from './policies.ts';\nimport { withScope } from './policies.ts';\nimport type { RelationFilterBase } from './relation-filters.ts';\nimport { extractFilters, relationFilterCtx } from './relation-filters.ts';\nimport { extractRelationsParams } from './relation-params.ts';\nimport { omitUndefinedKeys } from './rqb-config.ts';\nimport { extractSelectedColumnsFromTree } from './selected-columns.ts';\nimport type { TypeNameResolver } from './type-names.ts';\n\n/**\n * Runs the relational-query-builder select shared by every dialect's `generateSelect*`\n * resolver: selected columns + offset/limit + aliased orderBy/where callbacks + the eager\n * `with:` relation params, then remaps the result. `single` switches between\n * findFirst/findMany (and the single path omits `limit`). The PG fallback for tables\n * without RQB support stays in pg.ts; this covers the common RQB path for all three.\n */\nexport const runRelationalSelect = async (opts: {\n queryBase: any;\n tables: Record<string, Table>;\n tableName: string;\n table: Table;\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n typeName: string;\n typeNameMapper: TypeNameMapper | undefined;\n parsedInfo: ResolveTree;\n offset?: number;\n limit?: number;\n orderBy?: any;\n where?: any;\n single: boolean;\n filterCtx?: RelationFilterBase;\n pkNames?: readonly string[];\n db?: any;\n distinct?: string[];\n after?: string;\n nullOrdering?: NullOrdering;\n limits?: LimitPolicyFor;\n scope?: ScopeResolver;\n defaultOrderBy?: DefaultOrderByFor;\n deleted?: DeletedMode;\n /** The build's type-naming rule, so a relation's target type is looked up under its real name. */\n resolveName?: TypeNameResolver;\n}): Promise<any> => {\n const {\n queryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n offset,\n orderBy,\n where,\n single,\n filterCtx,\n pkNames,\n after,\n scope,\n deleted,\n } = opts;\n const distinct = opts.distinct?.length ? opts.distinct : undefined;\n\n // ── keyset (cursor) pagination ──\n // Active when the request passes `after` or selects the `cursor` meta field. The cursor is\n // defined over a total order — the request's orderBy plus the primary-key tiebreak — so both\n // need the PK; a table without one gets an error for `after` and null cursors otherwise.\n const cursorSelected = !single && isCursorFieldSelected(parsedInfo.fieldsByTypeName[typeName], table);\n let cursorEntries: CursorOrderEntry[] | undefined;\n if (!single && (after != null || cursorSelected)) {\n if (after != null && distinct) {\n throw drizzleError(\"'after' cannot be combined with 'distinct'.\", { code: 'DRIZZLE_INVALID_CURSOR' });\n }\n const cursorObstacle = orderByCursorObstacle(orderBy);\n if (cursorObstacle) {\n if (after != null) {\n throw drizzleError(cursorObstacle, { code: 'DRIZZLE_INVALID_CURSOR' });\n }\n // `cursor` was selected under an ordering a cursor cannot express — the field resolves\n // to null and the ordering itself still applies.\n } else if (!pkNames?.length) {\n if (after != null) {\n throw drizzleError(`Table ${tableName} has no primary key, so cursor pagination cannot be used on it.`, {\n code: 'DRIZZLE_INVALID_CURSOR',\n });\n }\n // `cursor` was selected but no total order exists — the field resolves to null.\n } else {\n cursorEntries = cursorOrderingEntries(orderBy, pkNames);\n }\n }\n const cursorValues = after != null && cursorEntries ? decodeCursor(after, cursorEntries) : undefined;\n // Taking a slice of an unordered result lets the database return any rows it likes, so\n // `limit`/`offset` pages can overlap or skip rows between requests, and a single query\n // can return a different row each time. Default to the primary key whenever the query is\n // narrowed to a subset, mirroring the relation-level default in extractRelationsParams.\n const needsDefaultOrder = single || offset != null || opts.limit != null;\n\n // `distinct` runs as its own pass — the relational query builder cannot express it — and\n // the main query is then narrowed to the primary keys it picked, with the same ordering\n // and without re-applying limit/offset.\n let distinctKeys: Record<string, any>[] | undefined;\n if (distinct) {\n distinctKeys = await selectDistinctKeys({\n db: opts.db,\n table,\n tableName,\n distinct,\n pkNames: pkNames ?? [],\n where: withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n deleted,\n ),\n orderBy,\n limit: single ? 1 : opts.limit,\n offset,\n });\n\n if (!distinctKeys.length) {\n return single ? undefined : [];\n }\n }\n\n const params: any = {\n columns: extractSelectedColumnsFromTree(parsedInfo.fieldsByTypeName[typeName]!, table, {\n tableName,\n relationMap,\n tables,\n allRelations: filterCtx?.relationMap,\n }),\n offset: distinctKeys ? undefined : offset,\n // drizzle-orm v1 RQB calls orderBy/where with the aliased table proxy — use it\n // directly so column refs match the CTE alias.\n orderBy: distinctKeys\n ? (aliasedTable: Table) => [\n ...(orderBy ? extractOrderBy(aliasedTable, orderBy, relationFilterCtx(filterCtx, tableName), where) : []),\n ...primaryKeyOrderExprs(aliasedTable, pkNames!),\n ]\n : cursorEntries\n ? // Cursor pagination needs a total order: the request's orderBy plus the PK tiebreak,\n // exactly the ordering the cursor encodes and the keyset predicate compares against.\n (aliasedTable: Table) => cursorOrderExprs(aliasedTable, cursorEntries!)\n : orderBy\n ? (aliasedTable: Table) =>\n extractOrderBy(aliasedTable, orderBy, relationFilterCtx(filterCtx, tableName), where)\n : needsDefaultOrder && pkNames?.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined,\n where: distinctKeys\n ? // The distinct pass already ran inside the scope, so the keys it picked are in it.\n { RAW: (aliasedTable: Table) => primaryKeyRestriction(aliasedTable, pkNames!, distinctKeys!) }\n : where || cursorValues || scope?.has(tableName, deleted)\n ? {\n RAW: (aliasedTable: Table) =>\n withScope(\n scope,\n tableName,\n aliasedTable,\n and(\n where\n ? extractFilters(aliasedTable, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n cursorValues\n ? buildCursorCondition(\n aliasedTable,\n cursorEntries!,\n cursorValues,\n opts.nullOrdering ?? 'nulls-smallest',\n )\n : undefined,\n ),\n deleted,\n ),\n }\n : undefined,\n with: relationMap[tableName]\n ? extractRelationsParams(relationMap, tables, tableName, parsedInfo, typeName, {\n typeNameMapper,\n filterCtx,\n limits: opts.limits,\n scope,\n defaultOrderBy: opts.defaultOrderBy,\n resolveName: opts.resolveName,\n })\n : undefined,\n };\n\n if (single) {\n const result = await queryBase.findFirst(omitUndefinedKeys(params));\n return result ? remapToGraphQLSingleOutput(result, tableName, table, relationMap) : undefined;\n }\n\n // Computing each row's cursor needs the whole ordering tuple, which the client has no\n // reason to have selected — force those columns into the fetch (GraphQL only returns\n // the fields the query asked for, so extra properties never leak into the response).\n if (cursorEntries && cursorSelected) {\n for (const [column] of cursorEntries) {\n params.columns[column] = true;\n }\n }\n\n params.limit = distinctKeys ? undefined : opts.limit;\n const result = await queryBase.findMany(omitUndefinedKeys(params));\n if (cursorEntries && cursorSelected) {\n // On the raw rows, before remapping rewrites dates/bigints into transport forms.\n attachRowCursors(result, cursorEntries);\n }\n return remapToGraphQLArrayOutput(result, tableName, table, relationMap);\n};\n\n/**\n * After a mutation, re-fetch the mutated rows through the relational query builder so the\n * selected relations are eagerly loaded in a single query, then merge those relations onto\n * the `.returning()` rows — making the per-field BatchLoader fallback unnecessary.\n *\n * `withParams` is the pre-computed relation selection (from extractRelationsParams); the\n * caller only invokes this when relations are actually selected, so it also gates whether\n * the PK was forced into RETURNING.\n *\n * Falls back to the original `.returning()` rows (relations then resolve via the\n * field-level BatchLoader) when the table has no RQB support, no primary key columns can be\n * determined, or the re-fetch fails. Supports single- and multi-column primary keys.\n */\nexport const eagerLoadMutationRelations = async (\n db: any,\n tableName: string,\n rows: any[],\n pkNames: readonly string[],\n withParams: Record<string, Partial<ProcessedTableSelectArgs>> | undefined,\n): Promise<any[]> => {\n if (!rows.length || !pkNames.length || !withParams || !Object.keys(withParams).length) {\n return rows;\n }\n\n const queryBase = db.query?.[tableName];\n if (!queryBase) {\n return rows;\n }\n\n // Only rows that carry every PK value can be re-keyed. Callers force the PK into\n // RETURNING, but if a value is still missing for some rows, eager-load just those that\n // are keyable and leave the rest untouched (their relations resolve lazily) rather than\n // bailing the whole batch.\n const keyableRows = rows.filter((row) => pkNames.every((n) => row[n] != null));\n if (!keyableRows.length) {\n return rows;\n }\n\n // Re-fetch ONLY the primary key + relations: the scalar columns are already present\n // on `rows` from RETURNING, so re-selecting them would transfer them a second time\n // (and would lose them on the fallback path). We merge the fetched relations back in.\n const pkColumns: Record<string, true> = {};\n for (const pk of pkNames) {\n pkColumns[pk] = true;\n }\n const relationNames = Object.keys(withParams);\n\n // Normalize bigint PK values to strings: JSON.stringify throws on bigint, and a\n // bigint and its string form never collide within a single column's values.\n const keyOf = (row: any) =>\n JSON.stringify(pkNames.map((n) => (typeof row[n] === 'bigint' ? row[n].toString() : row[n])));\n\n let whereRaw: (aliased: any) => SQL | undefined;\n if (pkNames.length === 1) {\n const pkName = pkNames[0]!;\n const ids = keyableRows.map((r) => r[pkName]);\n // drizzle-orm v1 RQB calls the where callback with the aliased table proxy;\n // reference the PK through it so the column ref matches the CTE alias.\n whereRaw = (aliased: any) => inArray(aliased[pkName], ids);\n } else {\n // Composite PK: use a row-value IN — `(a, b) IN ((..), (..))` — so the database can\n // plan it as a set membership test, instead of an OR of N per-row AND-tuples that\n // blows up for large bulk mutations.\n whereRaw = (aliased: any) => {\n const lhs = sql.join(\n pkNames.map((n) => sql`${aliased[n]}`),\n sql`, `,\n );\n const tuples = sql.join(\n keyableRows.map(\n (row) =>\n sql`(${sql.join(\n pkNames.map((n) => sql`${row[n]}`),\n sql`, `,\n )})`,\n ),\n sql`, `,\n );\n return sql`(${lhs}) in (${tuples})`;\n };\n }\n\n let enriched: any[];\n try {\n enriched = await queryBase.findMany({\n columns: pkColumns,\n where: { RAW: whereRaw },\n with: withParams,\n });\n } catch (err) {\n // The write has already committed; a re-fetch failure (e.g. an RQB-incompatible\n // column or relation) must not turn a successful mutation into an error. Fall back\n // to the raw rows — relations then resolve lazily via the batch loader — but surface\n // the cause so a genuine misconfiguration isn't silently hidden.\n console.warn(\n `[drizzle-graphql] eager-loading relations for a \"${tableName}\" mutation failed; ` +\n 'falling back to lazy resolution.',\n err,\n );\n return rows;\n }\n\n // Merge the fetched relations onto the RETURNING rows in place, preserving order. A row\n // the re-fetch didn't return (e.g. deleted concurrently) keeps its scalar columns and\n // its relations resolve lazily, so the result never reports fewer rows than were mutated.\n const byKey = new Map(enriched.map((e) => [keyOf(e), e]));\n for (const row of rows) {\n const match = byKey.get(keyOf(row));\n if (!match) {\n continue;\n }\n for (const rel of relationNames) {\n row[rel] = match[rel];\n }\n }\n return rows;\n};\n","// =============================================================================\n// Automatic per-request transactions for multi-mutation documents\n// (`BuildSchemaConfig.transactions: 'auto'`).\n//\n// GraphQL executes root mutation fields serially, but each one is a separate\n// resolver call on whatever server hosts the schema — the library never sees\n// the request as a whole. So the FIRST mutation resolver of a request inspects\n// `info.operation`: when the document selects more than one root mutation\n// field, it opens `db.transaction()` once, parks the transaction on a\n// per-request state object (WeakMap keyed by the context object), and every\n// later mutation resolver of the same request runs on that transaction. The\n// transaction callback awaits a latch; the last field to complete resolves it\n// (COMMIT) and the first failure rejects it (ROLLBACK).\n// =============================================================================\n\nimport type { GraphQLError } from 'graphql';\nimport { drizzleError } from './errors.ts';\nimport { drizzleExecutorKey, resolveExecutor } from './executor.ts';\n\n/** How long a shared transaction may sit idle between resolver calls before it is rolled back. */\nexport const DEFAULT_TRANSACTION_TIMEOUT_MS = 30_000;\n\n/**\n * One per built schema (when `transactions: 'auto'` is on). `fieldNames` is filled by the\n * dialect generator once every mutation field name is known, so a request-time count can\n * tell library mutations apart from consumer-added ones.\n */\nexport type MutationTxCtx = {\n timeoutMs: number;\n fieldNames: Set<string>;\n states: WeakMap<object, RequestTxState>;\n};\n\nexport const createMutationTxCtx = (options: { timeoutMs: number } | undefined): MutationTxCtx | undefined =>\n options ? { timeoutMs: options.timeoutMs, fieldNames: new Set(), states: new WeakMap() } : undefined;\n\ntype SharedTxState = {\n kind: 'shared';\n /** Distinct root mutation response keys the document will execute. */\n expected: number;\n completed: number;\n /** First failure; set once, before the latch is rejected. */\n failure: unknown;\n aborted: boolean;\n /** True once the underlying `db.transaction()` promise has settled (committed or rolled back). */\n done: boolean;\n /** Resolves with the transaction once BEGIN succeeded; rejects if it never will. */\n ready: Promise<any>;\n /** The `db.transaction()` promise itself — rejects when the transaction rolls back. */\n settled: Promise<unknown>;\n release: () => void;\n abort: (e: unknown) => void;\n /** Pause the inactivity timer while a resolver is actively working. */\n suspendTimer: () => void;\n /** (Re)arm the inactivity timer while waiting for the next resolver call. */\n bumpTimer: () => void;\n};\n\ntype RequestTxState = { kind: 'passthrough' } | SharedTxState;\n\nconst includedByDirectives = (node: { directives?: readonly any[] }, variables: any): boolean => {\n for (const directive of node.directives ?? []) {\n const name = directive.name.value;\n if (name !== 'skip' && name !== 'include') {\n continue;\n }\n const ifArg = directive.arguments?.find((arg: any) => arg.name.value === 'if');\n let value: unknown;\n if (ifArg?.value.kind === 'BooleanValue') {\n value = ifArg.value.value;\n } else if (ifArg?.value.kind === 'Variable') {\n value = variables?.[ifArg.value.name.value];\n }\n if (name === 'skip' && value === true) {\n return false;\n }\n if (name === 'include' && value !== true) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Collects the response keys of every root mutation field the executor will run, expanding\n * fragments and honoring `@skip` / `@include`. Distinct response keys (alias ?? name) are\n * counted, matching graphql-js field collection, so a field selected twice under one key is\n * still one resolver call. Returns `false` when the document selects a root mutation field\n * this build did not generate — its completion cannot be tracked, so the caller must not\n * open a transaction it might never be able to close.\n */\nconst collectRootMutationKeys = (\n selectionSet: any,\n fragments: any,\n variables: any,\n known: ReadonlySet<string>,\n keys: Set<string>,\n visitedFragments: Set<string>,\n): boolean => {\n for (const selection of selectionSet.selections) {\n if (!includedByDirectives(selection, variables)) {\n continue;\n }\n if (selection.kind === 'Field') {\n const name = selection.name.value;\n if (name === '__typename') {\n continue;\n }\n if (!known.has(name)) {\n return false;\n }\n keys.add(selection.alias?.value ?? name);\n } else if (selection.kind === 'InlineFragment') {\n if (!collectRootMutationKeys(selection.selectionSet, fragments, variables, known, keys, visitedFragments)) {\n return false;\n }\n } else if (selection.kind === 'FragmentSpread') {\n const fragmentName = selection.name.value;\n if (visitedFragments.has(fragmentName)) {\n continue;\n }\n visitedFragments.add(fragmentName);\n const fragment = fragments?.[fragmentName];\n if (!fragment) {\n return false;\n }\n if (!collectRootMutationKeys(fragment.selectionSet, fragments, variables, known, keys, visitedFragments)) {\n return false;\n }\n }\n }\n return true;\n};\n\nconst abortedBatchError = (): GraphQLError =>\n drizzleError(\n 'Drizzle-GraphQL Error: Mutation was not executed because an earlier mutation in the same request failed and the shared transaction was rolled back.',\n { code: 'DRIZZLE_TRANSACTION_ABORTED' },\n );\n\n/** Opens the request-wide transaction and wires up latch, inactivity timer and cleanup. */\nconst openSharedTx = (\n db: any,\n context: any,\n txCtx: MutationTxCtx,\n stateKey: object,\n expected: number,\n): SharedTxState => {\n let release!: () => void;\n let rejectLatch!: (e: unknown) => void;\n const latch = new Promise<void>((resolve, reject) => {\n release = resolve;\n rejectLatch = reject;\n });\n\n let readyResolve!: (tx: any) => void;\n let readyReject!: (e: unknown) => void;\n const ready = new Promise<any>((resolve, reject) => {\n readyResolve = resolve;\n readyReject = reject;\n });\n // Nobody may be awaiting `ready` when BEGIN fails — keep that from surfacing as an\n // unhandled rejection; each resolver still observes it through its own `await`.\n ready.catch(() => {});\n\n const canStash = context !== null && typeof context === 'object' && !Object.isFrozen(context);\n\n const settled: Promise<unknown> = db.transaction(async (tx: any) => {\n if (canStash) {\n // Publish our transaction under the caller-facing key so nested resolvers (lazy\n // relation fields, relation aggregates) selected under a mutation read through it\n // and see its uncommitted rows — the same wrapper a caller-supplied transaction uses.\n context[drizzleExecutorKey] = tx;\n }\n readyResolve(tx);\n // Held open across resolver calls: the last mutation field to complete resolves the\n // latch (COMMIT); the first failure — or the inactivity timeout — rejects it (ROLLBACK).\n await latch;\n });\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const clearTimer = () => {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const state: SharedTxState = {\n kind: 'shared',\n expected,\n completed: 0,\n failure: undefined,\n aborted: false,\n done: false,\n ready,\n settled,\n release,\n abort: (e: unknown) => {\n if (!state.aborted) {\n state.aborted = true;\n state.failure = e;\n }\n rejectLatch(e);\n },\n suspendTimer: clearTimer,\n bumpTimer: () => {\n clearTimer();\n if (state.done) {\n return;\n }\n timer = setTimeout(() => {\n // The host never called the remaining resolvers (e.g. a non-null completion error\n // outside our resolvers aborted serial execution). Roll back rather than leak.\n state.abort(\n drizzleError(\n `Drizzle-GraphQL Error: Shared mutation transaction timed out after ${txCtx.timeoutMs}ms waiting for the remaining mutation fields; rolling back.`,\n { code: 'DRIZZLE_TRANSACTION_ABORTED' },\n ),\n );\n }, txCtx.timeoutMs);\n (timer as any).unref?.();\n },\n };\n\n const cleanup = () => {\n state.done = true;\n clearTimer();\n if (canStash) {\n delete context[drizzleExecutorKey];\n }\n // A committed state left in the map would poison a reused context object; an aborted\n // one must stay so late-arriving fields of THIS request keep failing fast.\n if (!state.aborted) {\n txCtx.states.delete(stateKey);\n }\n };\n settled.then(cleanup, (e) => {\n cleanup();\n // BEGIN itself may have failed (driver without transaction support) — unblock waiters.\n readyReject(e);\n });\n\n state.bumpTimer();\n return state;\n};\n\nconst runOnSharedTx = async <T>(state: SharedTxState, body: (executor: any) => Promise<T>): Promise<T> => {\n if (state.aborted) {\n // Fail fast: never run a later field against a transaction that already rolled back.\n await (state.settled as Promise<unknown>).catch(() => {});\n throw abortedBatchError();\n }\n state.suspendTimer();\n const tx = await state.ready;\n try {\n if (state.aborted) {\n throw abortedBatchError();\n }\n const result = await body(tx);\n state.completed += 1;\n if (state.completed >= state.expected) {\n state.release();\n // COMMIT before this (final) field resolves, so the data is durable — and a commit\n // failure surfaces as this field's error.\n await state.settled;\n } else {\n state.bumpTimer();\n }\n return result;\n } catch (e) {\n state.abort(e);\n // Wait for the ROLLBACK to finish before surfacing, so the caller never observes a\n // response produced while the transaction is still being unwound.\n await (state.settled as Promise<unknown>).catch(() => {});\n throw e;\n }\n};\n\n/**\n * Executor selection for every generated mutation resolver. Runs `body` with:\n *\n * - the caller-supplied executor, when the context carries one under\n * {@link drizzleExecutorKey} — the library never nests a transaction inside it;\n * - the build-time `db`, when auto-transactions are off, the document has at most one root\n * mutation field, or it selects a mutation field this build did not generate (a consumer\n * extension whose completion cannot be tracked);\n * - otherwise, the request's shared transaction, opened on the first mutation resolver call\n * and committed when the last one completes / rolled back when any fails.\n */\nexport const runMutation = async <T>(\n db: any,\n context: any,\n info: any,\n txCtx: MutationTxCtx | undefined,\n body: (executor: any) => Promise<T>,\n /**\n * Opens a transaction for a field that would otherwise have run straight on `db`. Set when\n * the field carries an `onWrite` hook, whose whole purpose is to write atomically with the\n * mutation — a hook that ran outside a transaction could not roll anything back.\n */\n forceTx?: boolean,\n): Promise<T> => {\n const contextIsObject = context !== null && (typeof context === 'object' || typeof context === 'function');\n // Check our own request state FIRST: once the shared transaction is stashed on the\n // context it is indistinguishable from a caller-supplied one, but its completion still\n // has to be accounted here.\n const stateKey: object = contextIsObject ? context : info.operation;\n let state = txCtx?.states.get(stateKey);\n\n if (!state) {\n if (contextIsObject && context[drizzleExecutorKey]) {\n // The caller already runs this request on its own transaction/executor — use it as-is.\n return body(context[drizzleExecutorKey]);\n }\n if (!txCtx || info.operation.operation !== 'mutation') {\n return forceTx ? db.transaction((tx: any) => body(tx)) : body(db);\n }\n const keys = new Set<string>();\n const allKnown = collectRootMutationKeys(\n info.operation.selectionSet,\n info.fragments,\n info.variableValues,\n txCtx.fieldNames,\n keys,\n new Set(),\n );\n state =\n !allKnown || keys.size <= 1 ? { kind: 'passthrough' } : openSharedTx(db, context, txCtx, stateKey, keys.size);\n txCtx.states.set(stateKey, state);\n }\n\n if (state.kind === 'passthrough') {\n const executor = resolveExecutor(db, context);\n return forceTx && executor === db ? db.transaction((tx: any) => body(tx)) : body(executor);\n }\n return runOnSharedTx(state, body);\n};\n","// Write hooks (`BuildSchemaConfig.onWrite`): the payload a hook is handed, and running one\n// around the statement it is attached to.\n\nimport type { Column } from 'drizzle-orm';\nimport type { TablePolicies } from './policies.ts';\n\n/** The write a hook is attached to. `restore` only exists for a soft-deleting table. */\nexport type WriteOperation = 'insert' | 'update' | 'updateMany' | 'upsert' | 'delete' | 'restore';\n\n/** Which input of a relation field a nested write came from. */\nexport type NestedWriteOp = 'create' | 'connect' | 'disconnect' | 'set';\n\n/**\n * Where a nested write came from: set on the payload of a hook that fires for a row a nested\n * `create` / `connect` / `disconnect` / `set` wrote, and absent at the mutation field's own\n * table. See {@link WriteHookPayload.nested}.\n */\nexport type NestedWriteOrigin = {\n /** Drizzle schema key of the table whose input carried the relation field. */\n parentTable: string;\n /** The relation field the write went through, as named on the parent table. */\n relation: string;\n /** The relation field's input that produced this statement. */\n op: NestedWriteOp;\n};\n\n/** What a write hook is handed. See {@link BuildSchemaConfig.onWrite}. */\nexport type WriteHookPayload = {\n /** Drizzle schema key of the table being written. */\n table: string;\n /**\n * What happened to `table`. A nested write reports what its statement did to *that* table:\n * `insert` for a nested `create`, `update` for a `connect` / `disconnect` / `set` that\n * changes the foreign key on the target, and `insert` / `delete` on the junction table for\n * a many-to-many link / unlink.\n */\n operation: WriteOperation;\n /** `'before'` runs ahead of the statement, `'after'` once it has returned. */\n position: 'before' | 'after';\n /**\n * Whether the field writes a single row (`createUsersSingle`) or a list. For a nested\n * write, whether the relation it went through is a to-one.\n */\n single: boolean;\n /**\n * The field's GraphQL arguments, exactly as the resolver received them — for a nested\n * write, the arguments of the root mutation field it is part of.\n */\n args: any;\n /**\n * Set when the rows were written by a nested write under another table's mutation, and\n * `undefined` for the mutation field's own table. A hook that only cares about root writes\n * skips the rest with `if (payload.nested) return;`.\n */\n nested?: NestedWriteOrigin;\n /**\n * The rows the write produced, as the database returned them — before the output mapper,\n * so values are database-shaped. Empty at the `before` position, and on MySQL, whose\n * mutations return no rows.\n *\n * Each row holds the columns the client's selection asked for (plus any key a relation or\n * nested write needed), **and** every column the hook names in `columns`. A column the\n * client did not select and the hook did not name is absent. The count mutations select\n * nothing, so there a row holds the named columns, or the primary key when none are named.\n *\n * A nested write has no selection of its own, so its rows hold the table's primary key and\n * the join column(s) the write changed, plus the hook's `columns`.\n */\n rows: any[];\n context: any;\n info: any;\n /** The executor the mutation itself ran on. Throwing from the hook rolls it back. */\n tx: any;\n};\n\nexport type WriteHook = (payload: WriteHookPayload) => void | Promise<void>;\nexport type WriteHookPositions = {\n before?: WriteHook;\n after?: WriteHook;\n /**\n * Columns the `after` hook's `rows` always carry, whatever the client selected: a list of\n * column keys (the table object's property names, as `rows` is keyed), or `'all'` for\n * every column of the table. They are added to the statement's `RETURNING` and taken back\n * off before the result is mapped, so the client's response is unchanged.\n *\n * An unknown column fails the build, and so does `columns` without an `after` hook. On a\n * top-level (every-table) registration a named column must exist on every table.\n */\n columns?: readonly string[] | 'all';\n};\nexport type WriteHooks = WriteHook | WriteHookPositions;\n\n/**\n * Resolved, per-field hooks: `undefined` when the table registered none. `columns` is the\n * hook's `columns` resolved against the table, or `undefined` when it named none.\n */\nexport type ResolvedWriteHooks = { before?: WriteHook; after?: WriteHook; columns?: Record<string, Column> };\n\n/** Build-time lookup of a table's hooks, installed on {@link TablePolicies}. */\nexport type WriteHookFor = (tableName: string, operation: WriteOperation) => ResolvedWriteHooks | undefined;\n\n/**\n * Normalizes the two registration shapes: a bare function is the `after` hook — the position\n * that has rows, and the one the common audit/outbox case wants — while `{ before, after }`\n * names them explicitly.\n */\nexport const normalizeWriteHooks = (\n hooks: WriteHooks | undefined | null,\n tableColumns: Record<string, Column>,\n where: string,\n): ResolvedWriteHooks | undefined => {\n if (!hooks) {\n return undefined;\n }\n if (typeof hooks === 'function') {\n return { after: hooks };\n }\n const resolved: ResolvedWriteHooks = { before: hooks.before, after: hooks.after };\n if (hooks.columns !== undefined) {\n resolved.columns = resolveHookColumns(hooks.columns, !!hooks.after, tableColumns, where);\n }\n return resolved.before || resolved.after ? resolved : undefined;\n};\n\n/**\n * Resolves a hook's `columns` against the table it runs on. `where` names the registration\n * (`config.onWrite.posts`) and, for a top-level one, the table, so the error says which.\n */\nconst resolveHookColumns = (\n spec: readonly string[] | 'all',\n hasAfter: boolean,\n tableColumns: Record<string, Column>,\n where: string,\n): Record<string, Column> => {\n // Only the `after` hook is handed rows, so naming columns for a `before` hook alone is a\n // config that asks for something nothing will ever receive.\n if (!hasAfter) {\n throw new Error(`Drizzle-GraphQL Error: ${where}.columns only applies to an 'after' hook, and none is registered.`);\n }\n if (spec === 'all') {\n return { ...tableColumns };\n }\n if (!Array.isArray(spec)) {\n throw new Error(`Drizzle-GraphQL Error: ${where}.columns must be an array of column names or 'all'.`);\n }\n const resolved: Record<string, Column> = {};\n for (const name of spec) {\n const column =\n typeof name === 'string' && Object.keys(tableColumns).includes(name) ? tableColumns[name] : undefined;\n if (!column) {\n throw new Error(\n `Drizzle-GraphQL Error: ${where}.columns names '${String(name)}', which is not a column of that table.`,\n );\n }\n resolved[name] = column;\n }\n return resolved;\n};\n\n/**\n * Adds a hook's `columns` to a RETURNING column map, and reports which keys it added — the\n * ones the client never asked for, which have to come back off before the rows are mapped.\n * Returns the map untouched, and no keys, when the hook named none or the selection already\n * covers them.\n */\nexport const withHookColumns = <T extends Record<string, Column>>(\n hooks: ResolvedWriteHooks | undefined,\n columns: T,\n): { returning: T; added: string[] | undefined } => {\n const hookColumns = hooks?.columns;\n if (!hookColumns) {\n return { returning: columns, added: undefined };\n }\n const selected = new Set(Object.keys(columns));\n const added = Object.keys(hookColumns).filter((key) => !selected.has(key));\n if (!added.length) {\n return { returning: columns, added: undefined };\n }\n const returning: Record<string, Column> = { ...columns };\n for (const key of added) {\n returning[key] = hookColumns[key]!;\n }\n return { returning: returning as T, added };\n};\n\n/**\n * The rows with the hook-only keys taken off, as fresh objects: the hook was handed the\n * originals and may still hold them, so they are not mutated under it.\n */\nexport const omitHookColumns = <T extends Record<string, any>>(rows: T[], added: string[] | undefined): T[] => {\n if (!added) {\n return rows;\n }\n return rows.map((row) => {\n const copy: Record<string, any> = { ...row };\n for (const key of added) {\n delete copy[key];\n }\n return copy as T;\n });\n};\n\n/**\n * Invokes one position of a field's hooks. Returns `undefined` rather than a resolved promise\n * when nothing is registered, so the awaiting call site costs nothing on an unhooked build.\n */\nexport const runWriteHook = (\n hooks: ResolvedWriteHooks | undefined,\n position: 'before' | 'after',\n payload: Omit<WriteHookPayload, 'position' | 'rows'> & { rows?: any[] },\n): Promise<void> | undefined => {\n const hook = position === 'before' ? hooks?.before : hooks?.after;\n if (!hook) {\n return undefined;\n }\n return Promise.resolve(hook({ ...payload, position, rows: payload.rows ?? [] }));\n};\n","// The scaffolding every generated mutation resolver shares, whatever the dialect or the\n// operation: look up the table's write hooks, run the statement inside the request's\n// transaction, emit the hooks around it, and tag anything that escapes with the field it\n// came from.\n//\n// This was written out by hand at twelve call sites — six in the MySQL builder, five in the\n// shared pg/SQLite write resolvers, one in the shared `updateMany` — and every one of them\n// spelled the same hook payload, the same `runMutation` wrapper and the same catch clause.\n// What actually differs between a MySQL insert and a PostgreSQL one is the statement in the\n// middle: MySQL has no RETURNING clause, so it writes and reports `{ isSuccess }`, while the\n// others select their rows back on the way out. That difference lives in the body below,\n// which is exactly the shape a caller passes in.\n\nimport type { Column } from 'drizzle-orm';\nimport type { GraphQLFieldConfigArgumentMap } from 'graphql';\nimport type { CreatedResolver } from '../types.ts';\nimport { type DrizzleErrorContext, toGraphQLError, withErrorContext } from './errors.ts';\nimport type { ResolverPolicies } from './policies.ts';\nimport { type MutationTxCtx, runMutation } from './transactions.ts';\nimport { omitHookColumns, runWriteHook, type WriteOperation, withHookColumns } from './write-hooks.ts';\n\n/**\n * The table's `onWrite` hooks, bound to this field and this request. A body calls `before()`\n * ahead of its statement and `after(rows)` once the statement has returned; both are no-ops\n * when the table registered no hook.\n */\nexport type WriteHookEmitter = {\n before: () => Promise<void> | undefined;\n /** @param rows the rows the write produced, or `[]` where the dialect returns none. */\n after: (rows?: any[]) => Promise<void> | undefined;\n /**\n * The RETURNING column map the statement should use: the selection's `columns` plus the\n * ones the `after` hook named. Returns `columns` itself when the hook named none.\n */\n returning: <T extends Record<string, Column>>(columns: T) => T;\n /**\n * The rows to map for the client: the statement's rows with the hook-only columns that\n * {@link WriteHookEmitter.returning} added taken back off. Call it after `after(rows)`.\n */\n output: <T extends Record<string, any>>(rows: T[]) => T[];\n};\n\n/** The statement a mutation field runs, and whatever it resolves to. */\nexport type WriteBody<TArgs> = (\n params: {\n /** The transaction (or bare `db`) the write must run on. */\n executor: any;\n args: TArgs;\n context: any;\n info: any;\n } & WriteHookEmitter,\n) => Promise<any>;\n\nexport type WriteResolverSpec<TArgs> = {\n db: any;\n tableName: string;\n operation: WriteOperation;\n /** Whether the field writes one row or a list — reported to the hooks, nothing else. */\n single: boolean;\n fieldName: string;\n /** The field's GraphQL arguments, passed through untouched. */\n args: GraphQLFieldConfigArgumentMap;\n txCtx?: MutationTxCtx;\n policies?: ResolverPolicies;\n run: WriteBody<TArgs>;\n};\n\n/**\n * Wraps one mutation body in the scaffolding above and returns the field it becomes.\n *\n * A field carrying a hook is forced into a transaction even when it would have run straight\n * on `db`: a hook exists to write atomically with the mutation, and one that ran outside the\n * transaction could not roll anything back.\n */\nexport const writeResolver = <TArgs = any>({\n db,\n tableName,\n operation,\n single,\n fieldName,\n args: queryArgs,\n txCtx,\n policies,\n run,\n}: WriteResolverSpec<TArgs>): CreatedResolver => {\n const hooks = policies?.onWrite?.(tableName, operation);\n const errorCtx: DrizzleErrorContext = { table: tableName, operation, field: fieldName };\n\n return {\n name: fieldName,\n resolver: async (_source, args: TArgs, context, info) => {\n try {\n return await runMutation(\n db,\n context,\n info,\n txCtx,\n (executor) => {\n const payload = { table: tableName, operation, single, args, context, info, tx: executor };\n // Per request: which keys `returning` added is a function of this request's selection.\n let added: string[] | undefined;\n return run({\n executor,\n args,\n context,\n info,\n before: () => runWriteHook(hooks, 'before', payload),\n after: (rows) => runWriteHook(hooks, 'after', { ...payload, rows: rows ?? [] }),\n returning: (columns) => {\n const withHook = withHookColumns(hooks, columns);\n added = withHook.added;\n return withHook.returning;\n },\n output: (rows) => omitHookColumns(rows, added),\n });\n },\n !!hooks,\n );\n } catch (e) {\n throw withErrorContext(toGraphQLError(e), errorCtx);\n }\n },\n args: queryArgs,\n };\n};\n","// Pieces the generated mutations share: the relation columns a write has to prepare, the batch\n// update's input type, the filters a write requires, and the write-count return type.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { getColumns, type SQL, sql } from 'drizzle-orm';\nimport type { GraphQLFieldConfigArgumentMap } from 'graphql';\nimport { GraphQLBoolean, GraphQLInputObjectType, GraphQLNonNull } from 'graphql';\nimport { capitalize } from '../../case-ops/index.ts';\nimport type { ResolveTree } from '../../parse-resolve-info.ts';\nimport { parseResolveInfo } from '../../parse-resolve-info.ts';\nimport { remapUpdateInput } from '../field-updates.ts';\n// Type-only: the nested-write module imports this one at runtime, so the dependency has to\n// stay one-directional. The implementation is injected by the dialect builder.\nimport type { NestedWriteRuntime } from '../nested-writes.ts';\nimport type { CreatedResolver, Filters, ProcessedTableSelectArgs, TableNamedRelations } from '../types.ts';\nimport { drizzleError } from './errors.ts';\nimport { withPrimaryKeyColumns } from './keys.ts';\nimport type { DefaultOrderByFor, LimitPolicyFor } from './limits.ts';\nimport type { TypeNameMapper } from './naming.ts';\nimport { resolveObjectTypeName } from './naming.ts';\nimport type { DeletedMode, ResolverPolicies, ScopeResolver } from './policies.ts';\nimport { stripContextValues, withScope } from './policies.ts';\nimport type { RelationFilterBase, RelationFilterContext } from './relation-filters.ts';\nimport { extractFilters, relationFilterCtx } from './relation-filters.ts';\nimport { extractRelationsParams } from './relation-params.ts';\nimport { eagerLoadMutationRelations } from './select-runtime.ts';\nimport { extractSelectedColumnsFromTreeSQLFormat } from './selected-columns.ts';\nimport type { MutationTxCtx } from './transactions.ts';\nimport type { TypeCacheCtx } from './type-cache.ts';\nimport type { TypeNameResolver } from './type-names.ts';\nimport { writeResolver } from './write-scaffold.ts';\n\n/**\n * The `hard` argument on the delete mutations of a soft-deleting table that opted into\n * `hardDelete`. One config shared by every such field — argument configs carry no per-field\n * state — and generated nowhere else, so the schema says which tables can be purged.\n */\nexport const hardDeleteArg = {\n type: GraphQLBoolean,\n defaultValue: false,\n description:\n 'Remove the matched rows instead of marking them deleted. Reads at `INCLUDE`, so it reaches rows that are already marked; a `scope` still confines what it can reach.',\n} as const;\n\n/**\n * Computes the RETURNING columns and relation selection for a mutation resolver: extracts\n * the selected scalar columns, determines whether any relations were selected, and only\n * then forces the primary key into the column set (so the post-mutation eager-load can\n * re-key rows). Returns everything the resolver needs to decide whether to eager-load.\n */\nexport interface PrepareMutationRelationColumnsParams {\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n tables: Record<string, Table>;\n tableName: string;\n typeName: string;\n typeNameMapper: TypeNameMapper | undefined;\n table: Table;\n pkNames: readonly string[];\n parsedInfo: ResolveTree;\n limits?: LimitPolicyFor;\n scope?: ScopeResolver;\n defaultOrderBy?: DefaultOrderByFor;\n /** The build's type-naming rule — the selection tree is keyed by the name it produced. */\n resolveName?: TypeNameResolver;\n}\n\nexport const prepareMutationRelationColumns = (\n params: PrepareMutationRelationColumnsParams,\n): {\n columns: Record<string, Column>;\n hasRelations: boolean;\n withParams: Record<string, Partial<ProcessedTableSelectArgs>> | undefined;\n} => {\n const { relationMap, tables, tableName, typeNameMapper, table, pkNames, parsedInfo, resolveName } = params;\n const typeName = resolveObjectTypeName(tableName, typeNameMapper, resolveName);\n const withParams = relationMap[tableName]\n ? extractRelationsParams(relationMap, tables, tableName, parsedInfo, typeName, {\n typeNameMapper,\n limits: params.limits,\n scope: params.scope,\n defaultOrderBy: params.defaultOrderBy,\n resolveName,\n })\n : undefined;\n const hasRelations = !!(withParams && Object.keys(withParams).length);\n const baseColumns = extractSelectedColumnsFromTreeSQLFormat(parsedInfo.fieldsByTypeName[typeName]!, table, {\n tableName,\n relationMap,\n tables,\n });\n const columns = hasRelations ? withPrimaryKeyColumns(baseColumns, table, pkNames) : baseColumns;\n return { columns, hasRelations, withParams };\n};\n\n/**\n * The prologue every write resolver runs: parse the resolve info, then work out the columns\n * to return and the relations to eager-load from it. `parsedInfo` comes back too — the delete\n * resolver reads its own columns off the tree rather than taking the prepared set.\n */\nexport const mutationSelection = (\n info: any,\n params: Omit<PrepareMutationRelationColumnsParams, 'parsedInfo'>,\n): {\n parsedInfo: ResolveTree;\n columns: Record<string, Column>;\n hasRelations: boolean;\n withParams: Record<string, Partial<ProcessedTableSelectArgs>> | undefined;\n} => {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n return { parsedInfo, ...prepareMutationRelationColumns({ ...params, parsedInfo }) };\n};\n\n/**\n * The `where` a write runs under: the caller's filters — required when the mutation refuses to\n * run unbounded — with the row scope ANDed on last, so a supplied filter can only narrow the\n * scope and never widen it. An out-of-scope row is simply not matched.\n *\n * `deleted` states which soft-delete mode the match reads at, for the writes that need one:\n * `restore` sees only marked rows, a hard delete has to see them too.\n */\nexport const scopedWhere = <TTable extends Table>(params: {\n scope: ScopeResolver | undefined;\n tableName: string;\n table: TTable;\n where: Filters<TTable> | undefined;\n relationCtx?: RelationFilterContext;\n /** The single-row writes always require a `where`; the plural ones do under `requireWhere`. */\n required?: boolean;\n deleted?: DeletedMode;\n}): SQL | undefined => {\n const { scope, tableName, table, where, relationCtx, required, deleted } = params;\n return withScope(\n scope,\n tableName,\n table,\n required\n ? extractRequiredFilters(table, tableName, where, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined,\n deleted,\n );\n};\n\n/**\n * The epilogue: the written rows with their selected relations attached, or the rows as they\n * came back when the selection asked for no relation at all.\n */\nexport const withEagerRelations = (\n executor: any,\n tableName: string,\n rows: any[],\n pkNames: readonly string[],\n withParams: Record<string, Partial<ProcessedTableSelectArgs>> | undefined,\n hasRelations: boolean,\n): Promise<any[]> | any[] =>\n hasRelations ? eagerLoadMutationRelations(executor, tableName, rows, pkNames, withParams) : rows;\n\n/**\n * The per-entry input of `update<Table>Many`: `{ where, set }`, reusing the table's\n * update `set` input and filter input. Shared by all three dialect builders.\n */\nexport const generateUpdateManyInput = (params: {\n tableName: string;\n typeName: string;\n updatePrefix: string;\n updateInput: GraphQLInputObjectType;\n tableFilters: GraphQLInputObjectType;\n cacheCtx: TypeCacheCtx;\n}): GraphQLInputObjectType => {\n const { tableName, typeName, updatePrefix, updateInput, tableFilters, cacheCtx } = params;\n return new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'updateManyInput',\n defaultName: `${capitalize(updatePrefix)}${typeName}ManyInput`,\n table: tableName,\n }),\n description: `One entry of a batch update of ${typeName}: the rows \\`where\\` matches get this entry's \\`set\\` applied.`,\n fields: {\n where: {\n type: tableFilters,\n description: 'Rows this entry updates. An omitted filter updates every row.',\n },\n set: {\n type: new GraphQLNonNull(updateInput),\n },\n },\n });\n};\n\n/**\n * Extracts a `where` argument that a mutation refuses to run without: missing, or present\n * but matching every row (e.g. `where: {}` or filters that all collapse to nothing), both\n * throw instead of becoming an unbounded write. Used by the `Single` write variants always\n * and by the plural update/delete mutations when `features.requireWhere` is on.\n */\nexport const extractRequiredFilters = <TTable extends Table>(\n table: TTable,\n tableName: string,\n where: Filters<TTable> | undefined,\n relationCtx?: RelationFilterContext,\n): SQL => {\n const filters = where ? extractFilters(table, tableName, where, relationCtx) : undefined;\n if (!filters) {\n throw drizzleError(\n \"A 'where' argument with at least one filter is required — this mutation does not run unbounded.\",\n { code: 'DRIZZLE_WHERE_REQUIRED' },\n );\n }\n return filters;\n};\n\n/**\n * How many rows a returnless write reported affecting. The three dialects' drivers each\n * spell it differently — `rowCount` (node-postgres, Neon), `affectedRows` (PGlite, and MySQL\n * on its result header), `count` (postgres.js), `rowsAffected` (libsql), `changes`\n * (better-sqlite3) — and none of them is reachable through a common drizzle type, so the\n * shape is probed rather than declared.\n *\n * Only the result object itself is read, plus `affectedRows` one level in, since MySQL\n * returns `[header, fields]`. A row of the table is never inspected, so a table with a\n * column named `count` cannot be mistaken for a count.\n */\nexport const rowsAffected = (result: any): number => {\n const asNumber = (value: unknown): number | undefined =>\n typeof value === 'number' ? value : typeof value === 'bigint' ? Number(value) : undefined;\n\n if (result && typeof result === 'object') {\n for (const key of ['rowCount', 'affectedRows', 'rowsAffected', 'changes', 'count']) {\n const value = asNumber((result as any)[key]);\n if (value !== undefined) {\n return value;\n }\n }\n const header = Array.isArray(result) ? result[0] : undefined;\n const affected = header && typeof header === 'object' ? asNumber(header.affectedRows) : undefined;\n if (affected !== undefined) {\n return affected;\n }\n }\n\n throw drizzleError('The driver did not report how many rows the write affected.', {\n code: 'DRIZZLE_ROW_COUNT_UNAVAILABLE',\n });\n};\n\n/**\n * Guard for the `Single` write variants: throws before anything is written when `where`\n * matches more than one row, so a multi-row update/delete never executes. Probed with a\n * `LIMIT 2` select rather than a count so the check stays cheap on large matches.\n */\nexport const assertSingleMatch = async (executor: any, table: Table, filters: SQL): Promise<void> => {\n const matched = await executor.select({ found: sql`1` }).from(table).where(filters).limit(2);\n if (matched.length > 1) {\n throw drizzleError(\"'where' matched more than one row — nothing was written!\", {\n code: 'DRIZZLE_MULTI_ROW_MATCH',\n });\n }\n};\n\n/**\n * `update<Tables>Count` / `delete<Tables>Count` — the plural write without the payload\n * (`features.countMutations`).\n *\n * The plural `update` and `delete` always `RETURNING *`, which is the wrong shape for\n * \"archive everything older than a year\": the caller pays to ship rows it does not want, and\n * on a large match that cost is the whole mutation. These return `Int!` instead — how many\n * rows the write touched.\n *\n * Leaving the payload off changes nothing else: the write obeys every rule of the plural\n * mutation it mirrors, through the same {@link writeResolver} scaffolding.\n *\n * - `scope` (and the soft-delete marker) is ANDed into the `where`, so only rows the plural\n * write could reach are counted and written.\n * - On a soft-deleting table the delete is the marking `UPDATE`, not a `DELETE`, and rows that\n * are already marked are not matched; the update skips marked rows too. `hard: true` exists\n * exactly where the plural delete takes it.\n * - Context-derived columns are stripped from the update's `set`, as the plural update does.\n * - `onWrite` hooks run `before` and `after`, inside a transaction. The `after` hook is handed\n * rows, so a table with one pays for a `RETURNING` — of the columns the hook names in\n * `columns`, or of the primary key when it names none (the whole row on a table without a\n * key) — and the count is the number of rows returned. Every other write, and every write on\n * MySQL (no `RETURNING`; its hooks see `rows: []` as on every MySQL mutation), skips the\n * `RETURNING` and reads the count off the driver's result via {@link rowsAffected}.\n */\nexport const generateWriteCount = ({\n db,\n tableName,\n table,\n kind,\n setArgs,\n filterArgs,\n fieldName,\n requireWhere,\n filterCtx,\n txCtx,\n nested,\n policies,\n pkNames = [],\n returnsRows,\n}: {\n db: any;\n tableName: string;\n table: Table;\n kind: 'update' | 'delete';\n /** The update `set` input; omitted for the delete variant, which has nothing to set. */\n setArgs?: GraphQLInputObjectType;\n filterArgs: GraphQLInputObjectType;\n fieldName: string;\n requireWhere: boolean;\n filterCtx?: RelationFilterBase;\n txCtx?: MutationTxCtx;\n nested?: NestedWriteRuntime;\n policies?: ResolverPolicies;\n /** The table's primary-key property names: what an `after` hook that named no columns gets. */\n pkNames?: readonly string[];\n /** Whether the dialect has `RETURNING` (false on MySQL), which an `after` hook's rows need. */\n returnsRows: boolean;\n}): CreatedResolver => {\n const softDelete = kind === 'delete' ? policies?.softDelete?.(tableName) : undefined;\n // The plural delete's rule: only a soft-deleting table that opted in can purge.\n const canHardDelete = softDelete?.hardDelete === true;\n const queryArgs = {\n ...(setArgs ? { set: { type: new GraphQLNonNull(setArgs) } } : {}),\n where: {\n type: requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n ...(canHardDelete ? { hard: hardDeleteArg } : {}),\n } as GraphQLFieldConfigArgumentMap;\n\n // Only an `after` hook is handed rows, so only a table with one gives up the returnless write.\n const readsRows = returnsRows && !!policies?.onWrite?.(tableName, kind)?.after;\n // What the `after` hook's rows carry when it named no `columns`: the key, which identifies\n // each written row without shipping the rest of it — or the whole row when there is no key.\n const allColumns = getColumns(table) as Record<string, Column>;\n const keyColumns: Record<string, Column> = pkNames.length\n ? Object.fromEntries(pkNames.map((name) => [name, allColumns[name]!]))\n : allColumns;\n\n return writeResolver<{ where?: Filters<Table>; set?: Record<string, any>; hard?: boolean }>({\n db,\n tableName,\n operation: kind,\n single: false,\n fieldName,\n txCtx,\n policies,\n args: queryArgs,\n run: async ({ executor, args, context, before, after, returning }) => {\n const { where, set } = args;\n // `canHardDelete` decides whether the argument exists; this decides what it does, so a\n // stitched-in `hard: true` on a table that never opted in stays a soft delete.\n const hard = canHardDelete && args.hard === true;\n const scope = policies?.scope?.(context);\n await before();\n\n let query: any;\n if (kind === 'delete') {\n query =\n softDelete && !hard\n ? executor.update(table).set({ [softDelete.columnName]: softDelete.writeDeleted() })\n : executor.delete(table);\n } else {\n // Nested writes need the parent rows they attach to, which is exactly what this\n // mutation exists not to fetch — so they are refused rather than silently dropped.\n const entry = nested?.enabled(tableName) ? nested.split(tableName, set!) : undefined;\n if (entry && nested!.hasOps(entry.ops)) {\n throw drizzleError(\n 'This mutation does not support nested writes — use the one that returns the rows instead.',\n { code: 'DRIZZLE_NESTED_WRITES_UNSUPPORTED' },\n );\n }\n // A context-derived column is the server's to set, so an update never reassigns one.\n const values = stripContextValues(\n remapUpdateInput(entry ? entry.columns : set!, table, tableName),\n policies?.contextValues?.(tableName),\n );\n if (!Object.keys(values).length) {\n throw drizzleError('Unable to update with no values specified!', {\n code: 'DRIZZLE_NO_VALUES',\n });\n }\n query = executor.update(table).set(values);\n }\n\n // The scope — and on a soft-deleting table the not-yet-marked predicate — is ANDed on\n // last, so a caller's `where` can only narrow what the write reaches.\n const filters = scopedWhere({\n scope,\n tableName,\n table,\n where,\n relationCtx: relationFilterCtx(filterCtx, tableName),\n required: requireWhere,\n // A hard delete reads at INCLUDE, so it reaches the rows that are already marked.\n deleted: hard ? 'INCLUDE' : undefined,\n });\n if (filters) {\n query = query.where(filters);\n }\n\n if (!readsRows) {\n const result = await query;\n await after();\n return rowsAffected(result);\n }\n\n // The client selected nothing, so the rows hold only what the hook asked for.\n const named = returning({});\n const rows = (await query.returning(Object.keys(named).length ? named : keyColumns)) as any[];\n await after(rows);\n return rows.length;\n },\n });\n};\n","const DRIZZLE_LOADERS_KEY = Symbol('drizzle-graphql-loaders');\nconst DRIZZLE_REQUEST_CACHE_KEY = Symbol('drizzle-graphql-request-cache');\n\ntype BatchFn<K, V> = (keys: readonly K[]) => Promise<readonly V[]>;\n\nclass BatchLoader<K, V> {\n private batch: Array<{ key: K; resolve: (v: V) => void; reject: (e: unknown) => void }> = [];\n private scheduled = false;\n\n constructor(private readonly batchFn: BatchFn<K, V>) {}\n\n load(key: K): Promise<V> {\n return new Promise<V>((resolve, reject) => {\n this.batch.push({ key, resolve, reject });\n if (!this.scheduled) {\n this.scheduled = true;\n Promise.resolve().then(() => this.dispatch());\n }\n });\n }\n\n private async dispatch(): Promise<void> {\n const current = this.batch.splice(0);\n this.scheduled = false;\n try {\n const results = await this.batchFn(current.map(({ key }) => key));\n for (let i = 0; i < current.length; i++) {\n current[i]!.resolve(results[i] as V);\n }\n } catch (err) {\n for (const { reject } of current) {\n reject(err);\n }\n }\n }\n}\n\n/**\n * Returns a BatchLoader keyed by `key` on the GraphQL context object.\n * Loaders are stored under a Symbol so they never collide with consumer properties.\n * If context is absent or not an object, a fresh (unbatched) loader is returned.\n */\nexport const getOrCreateLoader = <K, V>(context: any, key: string, batchFn: BatchFn<K, V>): BatchLoader<K, V> => {\n if (!context || typeof context !== 'object') {\n return new BatchLoader<K, V>(batchFn);\n }\n if (!context[DRIZZLE_LOADERS_KEY]) {\n context[DRIZZLE_LOADERS_KEY] = new Map<string, BatchLoader<any, any>>();\n }\n const loaders = context[DRIZZLE_LOADERS_KEY] as Map<string, BatchLoader<any, any>>;\n if (!loaders.has(key)) {\n loaders.set(key, new BatchLoader<K, V>(batchFn));\n }\n return loaders.get(key) as BatchLoader<K, V>;\n};\n\n/**\n * Memoizes a value that a resolver derives from its own field — its args and its selection —\n * for the length of one request. Resolvers run once per parent row, so anything derived only\n * from the field is otherwise recomputed for every row of a batch.\n *\n * The cache lives on the context (weakly keyed by the AST node the value is derived from, so a\n * document cached across requests never carries values between them) and `key` separates fields\n * that share a node: one fragment selection can resolve for more than one parent type. Without a\n * context object there is nowhere request-scoped to cache, so the value is simply computed.\n *\n * `compute` must not read the parent row.\n */\nexport const getOrCreateRequestValue = <T>(\n context: any,\n node: object | undefined,\n key: string,\n compute: () => T,\n): T => {\n if (!context || typeof context !== 'object' || !node || typeof node !== 'object') {\n return compute();\n }\n if (!context[DRIZZLE_REQUEST_CACHE_KEY]) {\n context[DRIZZLE_REQUEST_CACHE_KEY] = new WeakMap<object, Map<string, unknown>>();\n }\n const cache = context[DRIZZLE_REQUEST_CACHE_KEY] as WeakMap<object, Map<string, unknown>>;\n let entries = cache.get(node);\n if (!entries) {\n entries = new Map<string, unknown>();\n cache.set(node, entries);\n }\n if (entries.has(key)) {\n return entries.get(key) as T;\n }\n const value = compute();\n entries.set(key, value);\n return value;\n};\n","/**\n * The identity a generated field publishes about itself, under `extensions.drizzle`.\n *\n * Every field this library generates carries one, so a wrapper — `graphql-middleware`,\n * envelop, `graphql-shield`, an audit log, a cache invalidator — can ask the schema what a\n * field is instead of reverse-engineering its name. Names are configurable (`prefixes`,\n * `suffixes`, `typeNameMapper`), so name parsing is ambiguous by construction; this is not.\n *\n * This shape is stable API: fields are only ever added to it, never removed or repurposed.\n */\n\n/** What family of field this is. */\nexport type DrizzleFieldKind = 'query' | 'mutation' | 'relation' | 'aggregate' | 'type';\n\n/**\n * What the field does. Arity is carried separately by `single`, so `select` covers both\n * the list query and its `…Single` sibling rather than being spelled twice.\n */\nexport type DrizzleFieldOperation =\n | 'select'\n | 'insert'\n | 'update'\n | 'updateMany'\n | 'upsert'\n | 'delete'\n | 'restore'\n | 'aggregate'\n | 'groupBy'\n | 'relation'\n | 'relationAggregate';\n\n/** The argument holding the rows a field is about, when it has one. */\nexport type DrizzleTargetArg = 'where' | 'values' | 'updates';\n\n/** `extensions.drizzle` on a generated field. */\nexport type DrizzleFieldExtension = {\n /** The Drizzle schema key of the table the field reads or writes. */\n table: string;\n kind: Exclude<DrizzleFieldKind, 'type'>;\n operation: DrizzleFieldOperation;\n /** Whether the field resolves to one row (or one aggregate) rather than a list. */\n single: boolean;\n /**\n * Which argument names the rows: `where` for select/update/delete/aggregate, `values`\n * for insert and upsert, `updates` for the batch update's per-entry `{ where, set }`.\n * Absent when the field takes no such argument.\n */\n targetArg?: DrizzleTargetArg;\n /**\n * Primary-key property names of `table`, in schema order. Empty when the table declares\n * no primary key. Carried here so {@link identifyRows} works from the field alone.\n */\n primaryKey: readonly string[];\n /**\n * For `operation: 'delete'` on a soft-deleting table that opted into `hardDelete`: the\n * field takes a `hard` argument that issues a real `DELETE` rather than writing the marker.\n * Absent everywhere else, so a wrapper can gate purging without parsing arguments.\n */\n hardDelete?: boolean;\n /**\n * `true` on the count mutations (`update<Table>Count` / `delete<Table>Count`,\n * `features.countMutations`): the field writes like its plural `update` / `delete` sibling\n * — same `operation`, same rows — but resolves to how many rows it wrote (`Int!`) rather\n * than to the rows. Absent everywhere else.\n */\n count?: boolean;\n /** For `kind: 'relation'` and `operation: 'relationAggregate'`: the relation's name. */\n relation?: string;\n /** For `kind: 'relation'` and `operation: 'relationAggregate'`: the table it hangs off. */\n parentTable?: string;\n};\n\n/** `extensions.drizzle` on a generated object type. */\nexport type DrizzleTypeExtension = {\n /** The Drizzle schema key this type was generated from. */\n table: string;\n kind: 'type';\n /** Primary-key property names of `table`, in schema order. Empty when there is none. */\n primaryKey: readonly string[];\n};\n\nexport type DrizzleExtension = DrizzleFieldExtension | DrizzleTypeExtension;\n\n/** Anything carrying GraphQL `extensions` — a field config, a field, or a named type. */\ntype WithExtensions = { extensions?: { drizzle?: unknown } | null } | null | undefined;\n\n/**\n * Reads the `drizzle` extension off a field or type, typed. Returns `undefined` for\n * anything this library did not generate, which is the check a wrapper wants before it\n * treats a field as one of ours.\n */\nexport const drizzleExtension = (target: WithExtensions): DrizzleExtension | undefined => {\n const value = target?.extensions?.drizzle;\n return value && typeof value === 'object' ? (value as DrizzleExtension) : undefined;\n};\n\n/** Narrows to the field form — object types carry `kind: 'type'` and no operation. */\nexport const isDrizzleFieldExtension = (value: DrizzleExtension | undefined): value is DrizzleFieldExtension =>\n !!value && value.kind !== 'type';\n\n/**\n * Builds the extension for one table's fields. Dialect builders make one per table so each\n * call site only states what differs.\n */\nexport const tableFieldExtensions =\n (table: string, primaryKey: readonly string[]) =>\n (meta: Omit<DrizzleFieldExtension, 'table' | 'primaryKey'>): DrizzleFieldExtension => ({\n table,\n primaryKey,\n ...meta,\n });\n\n/**\n * One table's bound extension builder — what {@link tableFieldExtensions} returns. Named so\n * the shared build helpers can take one without restating the signature.\n */\nexport type TableFieldExtensionFactory = ReturnType<typeof tableFieldExtensions>;\n\n/**\n * The parts of a mutation's identity that differ between mutations. Dialect builders that\n * assign every mutation in one loop pair each generated mutation with one of these.\n */\nexport type DrizzleMutationMeta = Pick<\n DrizzleFieldExtension,\n 'operation' | 'single' | 'targetArg' | 'hardDelete' | 'count'\n>;\n\n/** Builds the extension a generated object type carries. */\nexport const tableTypeExtension = (table: string, primaryKey: readonly string[]): DrizzleTypeExtension => ({\n table,\n kind: 'type',\n primaryKey,\n});\n\n/**\n * Builds the extension a relation field carries. `table` is the relation's *target* — the\n * table the field resolves rows of — while `parentTable` is the type the field hangs off,\n * so a wrapper can tell `Users.posts` from `Customers.posts`.\n */\nexport const relationFieldExtension = (params: {\n targetTable: string;\n parentTable: string;\n relation: string;\n single: boolean;\n primaryKey: readonly string[];\n aggregate?: boolean;\n}): DrizzleFieldExtension => ({\n table: params.targetTable,\n kind: params.aggregate ? 'aggregate' : 'relation',\n operation: params.aggregate ? 'relationAggregate' : 'relation',\n // An aggregate over a to-many relation still resolves to a single aggregate object.\n single: params.aggregate ? true : params.single,\n targetArg: 'where',\n primaryKey: params.primaryKey,\n relation: params.relation,\n parentTable: params.parentTable,\n});\n\n/** The rows a field's arguments name. */\nexport type IdentifiedRows = {\n /** The Drizzle schema key of the table being read or written. */\n table: string;\n /** Primary-key property names, in schema order. */\n primaryKey: readonly string[];\n /** One entry per identified row: the primary-key values, keyed by property name. */\n rows: Record<string, unknown>[];\n /**\n * Whether `rows` is exactly the set the operation affects.\n *\n * `false` means the arguments do not pin the rows down — an insert whose key the\n * database generates, a `where` that filters on something other than the primary key,\n * a plural update with no filter at all, or a table with no primary key. `rows` is then\n * a best-effort subset-free superset: every entry in it is a row the key values name,\n * but other filters may narrow the real set further, and it may be empty.\n */\n complete: boolean;\n};\n\n/** Pulls the primary-key values out of one `values` entry; `undefined` if any are missing. */\nconst keyFromValues = (entry: unknown, primaryKey: readonly string[]): Record<string, unknown> | undefined => {\n if (!entry || typeof entry !== 'object') {\n return undefined;\n }\n const row: Record<string, unknown> = {};\n for (const column of primaryKey) {\n const value = (entry as Record<string, unknown>)[column];\n if (value === undefined || value === null) {\n return undefined;\n }\n row[column] = value;\n }\n return row;\n};\n\n/**\n * Pulls primary-key values out of a filter argument.\n *\n * Only top-level equality counts: `{ id: { eq } }` names one row, `{ id: { inArray } }`\n * names a list, and a composite key needs `eq` on every one of its columns. A boolean\n * group (`OR` / `AND` / `NOT`) or any other operator on a key column means the filter is\n * not a key lookup, and the rows are reported as not identified.\n */\nconst keysFromWhere = (\n where: unknown,\n primaryKey: readonly string[],\n): { rows: Record<string, unknown>[]; complete: boolean } => {\n const none = { rows: [], complete: false };\n if (!where || typeof where !== 'object' || Array.isArray(where)) {\n return none;\n }\n const filters = where as { OR?: unknown; AND?: unknown; NOT?: unknown; [column: string]: any };\n if (filters.OR || filters.AND || filters.NOT) {\n return none;\n }\n\n // A composite key is only pinned by an equality on each of its columns — one column\n // carrying a list would describe a rectangle of key tuples, not the rows written.\n if (primaryKey.length > 1) {\n const row: Record<string, unknown> = {};\n for (const column of primaryKey) {\n const operators = filters[column];\n if (!operators || typeof operators !== 'object' || operators.eq === undefined) {\n return none;\n }\n row[column] = operators.eq;\n }\n // Filters beyond the key can only narrow further, so the key alone is not the answer.\n return { rows: [row], complete: Object.keys(filters).length === primaryKey.length };\n }\n\n const column = primaryKey[0];\n if (!column) {\n return none;\n }\n const operators = filters[column];\n if (!operators || typeof operators !== 'object') {\n return none;\n }\n\n const exact = Object.keys(filters).length === 1 && Object.keys(operators).length === 1;\n if (operators.eq !== undefined) {\n return { rows: [{ [column]: operators.eq }], complete: exact };\n }\n if (Array.isArray(operators.inArray)) {\n return { rows: operators.inArray.map((value: unknown) => ({ [column]: value })), complete: exact };\n }\n return none;\n};\n\n/**\n * The rows a generated field's arguments are about, as primary-key values.\n *\n * The row identity of a mutation lives in a different argument for every operation —\n * `where` for update and delete, `values` for insert and upsert, a per-entry `where` inside\n * `updates` for the batch update — and each of those has both a one-row and a many-row\n * spelling. This reads whichever one applies:\n *\n * ```ts\n * const field = info.parentType.getFields()[info.fieldName];\n * const target = identifyRows(field, args);\n * if (target?.complete) await invalidate(target.table, target.rows);\n * ```\n *\n * Returns `undefined` for a field this library did not generate, or an object type. Check\n * `complete` before treating `rows` as the affected set — see {@link IdentifiedRows}.\n */\nexport const identifyRows = (\n field: WithExtensions,\n args: Record<string, unknown> | undefined,\n): IdentifiedRows | undefined => {\n const meta = drizzleExtension(field);\n if (!isDrizzleFieldExtension(meta)) {\n return undefined;\n }\n\n const { table, primaryKey, targetArg } = meta;\n const empty: IdentifiedRows = { table, primaryKey, rows: [], complete: false };\n if (!primaryKey.length || !targetArg) {\n return empty;\n }\n\n const target = args?.[targetArg];\n\n if (targetArg === 'values') {\n // Both spellings of insert/upsert land here: the single variant takes one object.\n const entries = Array.isArray(target) ? target : target === undefined ? [] : [target];\n const rows = entries.map((entry) => keyFromValues(entry, primaryKey));\n return {\n table,\n primaryKey,\n rows: rows.filter((row): row is Record<string, unknown> => !!row),\n // A row whose key the database generates is not identifiable before the write.\n complete: entries.length > 0 && rows.every(Boolean),\n };\n }\n\n if (targetArg === 'updates') {\n if (!Array.isArray(target)) {\n return empty;\n }\n const perEntry = target.map((entry) =>\n keysFromWhere((entry as { where?: unknown } | undefined)?.where, primaryKey),\n );\n return {\n table,\n primaryKey,\n rows: perEntry.flatMap((entry) => entry.rows),\n complete: target.length > 0 && perEntry.every((entry) => entry.complete),\n };\n }\n\n return { table, primaryKey, ...keysFromWhere(target, primaryKey) };\n};\n","// The field resolver every relation gets. It returns what the parent already fetched when the\n// eager path ran, and otherwise batches all sibling calls in the same execution tick into one\n// IN-clause query.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { and, getColumns, gt, inArray, lte, type SQL, sql } from 'drizzle-orm';\nimport { getOrCreateLoader, getOrCreateRequestValue } from '../../batch-loader/index.ts';\nimport { remapToGraphQLArrayOutput } from '../../data-mappers/index.ts';\nimport { relationFieldExtension } from '../../extensions.ts';\nimport type { ResolveTree } from '../../parse-resolve-info.ts';\nimport { parseResolveInfo } from '../../parse-resolve-info.ts';\nimport type { TableNamedRelations } from '../types.ts';\nimport type { CursorOrderEntry, NullOrdering } from './cursor.ts';\nimport {\n attachRowCursors,\n buildCursorCondition,\n cursorOrderExprs,\n cursorOrderingEntries,\n decodeCursor,\n orderByHasRelationEntry,\n selectsCursorField,\n} from './cursor.ts';\nimport { primaryKeyRestriction, selectDistinctKeys } from './distinct.ts';\nimport { type DrizzleErrorContext, drizzleError, toGraphQLError, withErrorContext } from './errors.ts';\nimport { resolveExecutor } from './executor.ts';\nimport { primaryKeyOrderExprs } from './keys.ts';\nimport type { LimitPolicyFor } from './limits.ts';\nimport { applyLimitPolicy, withDefaultOrderBy } from './limits.ts';\nimport { extractOrderBy } from './order-by.ts';\nimport type { TablePolicies } from './policies.ts';\nimport { relationDeletedDefault, resolveScope, withScope } from './policies.ts';\nimport type { RelationFilterBase, RelationFilterContext } from './relation-filters.ts';\nimport { extractFilters, relationFilterCtx } from './relation-filters.ts';\nimport type { RelationResolverFactory } from './relations.ts';\nimport { extractRelationJoinColumns } from './relations.ts';\nimport { extractSelectedColumnsFromTreeSQLFormat } from './selected-columns.ts';\n\n/**\n * Fetches a to-many relation with per-parent limit/offset for ALL parents in a\n * single query, using a window function (ROW_NUMBER() OVER (PARTITION BY fk ...)).\n *\n * This replaces the previous per-parent fallback that issued one query per parent\n * (true N+1) whenever pagination args were present. Each parent gets its own\n * limit/offset window while the database is hit exactly once for the whole batch.\n *\n * Window functions require PostgreSQL, MySQL >= 8.0, or SQLite >= 3.25.\n * Returns raw rows (NOT remapped); the caller groups + remaps them.\n */\nconst batchedPaginatedRelationQuery = async (\n db: any,\n targetTable: Table,\n foreignCol: Column,\n whereCondition: SQL | undefined,\n orderByArg: any,\n limit: number | null,\n offset: number | null,\n pkNames: readonly string[],\n columns: Record<string, Column> | undefined,\n orderCtx?: RelationFilterContext,\n whereArgs?: Record<string, any>,\n): Promise<any[]> => {\n const cols = columns ?? getColumns(targetTable);\n\n // Always tiebreak the window by the target's primary key so per-parent limit/offset\n // slices are deterministic even when the client supplies no (or a non-unique) orderBy.\n // pkNames is resolved at build time and includes composite keys.\n const orderExprs = [\n ...(orderByArg ? extractOrderBy(targetTable, orderByArg, orderCtx, whereArgs) : []),\n ...primaryKeyOrderExprs(targetTable, pkNames),\n ];\n const orderClause = orderExprs.length ? sql` order by ${sql.join(orderExprs, sql`, `)}` : sql``;\n // Namespaced alias so it can't collide with a real column on the target table.\n const RN = '__drizzle_graphql_rn';\n const rowNumber = sql`row_number() over (partition by ${foreignCol}${orderClause})`.as(RN);\n\n // Subquery: every target column plus a per-partition row number.\n const sub = db\n .select({ ...cols, [RN]: rowNumber })\n .from(targetTable)\n .where(whereCondition)\n .as('__paginated');\n\n // Outer: keep only the rows that fall inside each parent's window.\n const lower = offset ?? 0;\n const windowConds: any[] = [gt(sub[RN], lower)];\n if (limit != null) {\n windowConds.push(lte(sub[RN], lower + limit));\n }\n\n const rows: any[] = await db\n .select()\n .from(sub)\n .where(and(...windowConds))\n .orderBy(sub[RN]);\n\n // Strip the helper column so it doesn't leak into remapping/output.\n for (const row of rows) {\n delete row[RN];\n }\n return rows;\n};\n\n/**\n * Creates a RelationResolverFactory that generates field-level resolvers for each relation.\n * Each resolver:\n * 1. Returns pre-fetched data if the parent resolver already included it (eager path, zero cost).\n * 2. When limit/offset args are present, falls back to a direct per-item query.\n * 3. Otherwise batches all sibling resolver calls within the same GraphQL execution tick\n * into a single IN-clause query, eliminating N+1 database round-trips.\n *\n * `nullOrdering` is the dialect's native `ORDER BY` placement for `NULL` — the keyset\n * predicate behind a relation's `after` argument has to match it, or rows with a `NULL` in an\n * ordered column would be skipped instead of paged through. It has no sensible default, so\n * each dialect builder states it: `'nulls-largest'` for PostgreSQL, `'nulls-smallest'` for\n * MySQL and SQLite.\n */\nexport const createRelationResolverFactory =\n (\n db: any,\n tables: Record<string, Table>,\n nullOrdering: NullOrdering,\n filterCtx?: RelationFilterBase,\n limits?: LimitPolicyFor,\n policies?: TablePolicies,\n ): RelationResolverFactory =>\n ({ tableName, relationName, relEntry, isOne }) => {\n const parentTable = tables[tableName];\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n\n if (!parentTable || !targetTable) {\n return undefined;\n }\n\n const joinCols = extractRelationJoinColumns(relEntry, parentTable, targetTable);\n if (!joinCols) {\n return undefined;\n }\n\n const { localColPropName, foreignCol, foreignColPropName } = joinCols;\n // The mode this field reads its target with when the request passes no `deleted` — see\n // `relationDeletedDefault`. Required to-one relations and `scope: 'root'` tables read\n // marked rows; everything else keeps hiding them.\n const defaultDeleted = relationDeletedDefault(\n policies?.softDelete,\n targetTableName,\n isOne && (relEntry.relation as any)?.optional === false,\n );\n // A relation field is bounded by the policy of the table it reads, not the parent's.\n const limitPolicy = isOne ? undefined : limits?.(targetTableName);\n // Resolved at build time (composite keys included) — used to tiebreak paginated batches.\n const targetPkNames = relEntry.targetPkNames ?? [];\n const errorCtx: DrizzleErrorContext = { table: targetTableName, operation: 'relation', relation: relationName };\n\n /**\n * The columns one batch reads: the ones the selection names, plus the ones the batch needs\n * whatever the client asked for — the key it groups the rows by, and the ordering columns a\n * row cursor is encoded from. Nested relation fields contribute their own join column\n * through the selection context, the same way the root select path narrows.\n *\n * `undefined` means \"every column\", which is what a resolver with no readable resolve info\n * has to fall back to.\n */\n const selectedColumns = (info: any, cursorEntries: CursorOrderEntry[] | undefined) => {\n const parsed = info ? (parseResolveInfo(info) as ResolveTree | undefined) : undefined;\n if (!parsed) {\n return undefined;\n }\n // A relation field returns one object type, but merging every entry costs nothing and\n // keeps this honest if the target is ever reached through an abstract type.\n const tree: Record<string, ResolveTree> = Object.assign({}, ...Object.values(parsed.fieldsByTypeName));\n\n const columns = extractSelectedColumnsFromTreeSQLFormat(tree, targetTable, {\n tableName: targetTableName,\n relationMap: filterCtx?.relationMap ?? {},\n tables,\n allRelations: filterCtx?.relationMap,\n });\n\n const targetColumns = getColumns(targetTable);\n columns[foreignColPropName] = foreignCol;\n for (const [columnName] of cursorEntries ?? []) {\n const column = targetColumns[columnName];\n if (column) {\n columns[columnName] = column;\n }\n }\n return columns;\n };\n\n const resolve = async (parent: any, args: any, context: any, info: any) => {\n // Eager path: the parent resolver pre-fetched this relation via Drizzle's `with`.\n if (parent[relationName] !== undefined) {\n return parent[relationName];\n }\n\n const localValue = parent[localColPropName];\n if (localValue == null) {\n return isOne ? null : [];\n }\n\n const { where: whereArg, limit: requestedLimit, offset, after, deleted } = (args ?? {}) as any;\n\n // Everything below is derived from this field alone — its args and its selection — so it is\n // identical for every parent row the batch fetches. Resolvers run once per parent row, so it\n // is computed once per field per request and reused, rather than re-reading the selection and\n // re-stringifying the loader key N times.\n const { orderByArg, limit, distinct, cursorEntries, cursorValues, columns, loaderKey } = getOrCreateRequestValue(\n context,\n info?.fieldNodes?.[0],\n `relation:${tableName}::${relationName}`,\n () => {\n // A relation field falls back to the *target* table's default ordering, since that is\n // the table it reads. A to-one relation is a single row and takes no ordering at all.\n const orderByArg = isOne\n ? (args as any)?.orderBy\n : withDefaultOrderBy(args ?? {}, targetTableName, policies?.defaultOrderBy).orderBy;\n const limit = applyLimitPolicy(requestedLimit, limitPolicy, errorCtx);\n const distinct = ((args ?? {}) as any).distinct?.length ? ((args ?? {}) as any).distinct : undefined;\n\n // ── keyset (cursor) pagination ──\n // The same rules the root list follows, over the related rows of one parent: the cursor\n // is defined over the request's orderBy plus the target's primary-key tiebreak, and the\n // keyset predicate is a plain condition on the target's own columns — so it filters each\n // parent's rows independently even though the batch fetches them all at once.\n const cursorSelected = !isOne && !!info && selectsCursorField(info, targetTable);\n let cursorEntries: CursorOrderEntry[] | undefined;\n if (!isOne && (after != null || cursorSelected)) {\n if (after != null && distinct) {\n throw drizzleError(\"'after' cannot be combined with 'distinct'.\", { code: 'DRIZZLE_INVALID_CURSOR' });\n }\n if (orderByHasRelationEntry(orderByArg)) {\n if (after != null) {\n throw drizzleError(\n \"'after' cannot be combined with an orderBy that orders through a relation — a related row's value cannot be encoded into a cursor.\",\n { code: 'DRIZZLE_INVALID_CURSOR' },\n );\n }\n // `cursor` was selected under a relation ordering — the field resolves to null.\n } else if (!targetPkNames.length) {\n if (after != null) {\n throw drizzleError(\n `Table ${targetTableName} has no primary key, so cursor pagination cannot be used on it.`,\n { code: 'DRIZZLE_INVALID_CURSOR' },\n );\n }\n // `cursor` was selected but no total order exists — the field resolves to null.\n } else {\n cursorEntries = cursorOrderingEntries(orderByArg, targetPkNames);\n }\n }\n const cursorValues = after != null && cursorEntries ? decodeCursor(after, cursorEntries) : undefined;\n\n const columns = selectedColumns(info, cursorEntries);\n\n // Batch path: collect all sibling calls in this tick and execute one query.\n // Pagination args are part of the loader key so siblings sharing identical\n // args batch together; per-parent limit/offset is applied inside the batch\n // via a window function rather than bailing to a per-parent query (N+1).\n // `cursorEntries` joins the key because it changes the ordering, not just the filter.\n // The column list joins it too: one batch runs one SELECT, so two aliases of the same\n // relation asking for different columns need a batch each.\n const argsKey = JSON.stringify({\n where: whereArg ?? null,\n orderBy: orderByArg ?? null,\n limit: limit ?? null,\n offset: offset ?? null,\n deleted: deleted ?? defaultDeleted ?? null,\n after: after ?? null,\n distinct: distinct ?? null,\n cursor: cursorEntries ? 1 : 0,\n columns: columns ? Object.keys(columns).sort() : null,\n });\n\n return {\n orderByArg,\n limit,\n distinct,\n cursorEntries,\n cursorValues,\n columns,\n loaderKey: `${tableName}::${relationName}::${argsKey}`,\n };\n },\n );\n\n const loader = getOrCreateLoader(context, loaderKey, async (parentIds: readonly any[]) => {\n // Loaders are cached per context, so every call batched here shares this request's\n // executor — the transaction on the context, when there is one.\n const executor = resolveExecutor(db, context);\n const uniqueIds = [...new Set(parentIds)];\n // Loaders are keyed per context too, so the scope resolved here is this request's.\n const scope = resolveScope(policies, context, filterCtx);\n let whereCondition = withScope(\n scope,\n targetTableName,\n targetTable,\n and(\n inArray(foreignCol, uniqueIds),\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n cursorValues ? buildCursorCondition(targetTable, cursorEntries!, cursorValues, nullOrdering) : undefined,\n ),\n deleted ?? defaultDeleted,\n );\n\n if (distinct) {\n // Partitioned by the foreign key as well as the requested columns, so \"one row per\n // distinct value\" means one per parent — `users { posts(distinct: [status]) }` gives\n // each user one post per status, not one post per status across all users. The pass\n // runs first and the batch query is then narrowed to the keys it picked, exactly as\n // the root list does.\n const keys = await selectDistinctKeys({\n db: executor,\n table: targetTable,\n tableName: targetTableName,\n distinct,\n pkNames: targetPkNames,\n where: whereCondition,\n orderBy: orderByArg,\n partitionBy: [foreignCol],\n });\n if (!keys.length) {\n return parentIds.map(() => (isOne ? null : []));\n }\n whereCondition = and(whereCondition, primaryKeyRestriction(targetTable, targetPkNames, keys));\n }\n\n let rows: any[];\n if (limit != null || offset != null) {\n // Per-parent pagination across the whole batch in one query. Its window ordering is\n // the request's orderBy plus the primary key, which is the cursor's total order too,\n // so a cursor page and a limit/offset page agree on row order.\n rows = await batchedPaginatedRelationQuery(\n executor,\n targetTable,\n foreignCol,\n whereCondition,\n orderByArg,\n limit ?? null,\n offset ?? null,\n targetPkNames,\n columns,\n relationFilterCtx(filterCtx, targetTableName),\n whereArg,\n );\n } else {\n // Use plain db.select() so column refs are never aliased — avoids drizzle-orm v1\n // RQB aliasing requirements that would require referencing via aliasedTable proxy.\n let q = (columns ? executor.select(columns) : executor.select())\n .from(targetTable)\n .where(whereCondition) as any;\n const orderExprs = cursorEntries\n ? cursorOrderExprs(targetTable, cursorEntries)\n : orderByArg\n ? extractOrderBy(targetTable, orderByArg, relationFilterCtx(filterCtx, targetTableName), whereArg)\n : [];\n if (orderExprs.length) {\n q = q.orderBy(...orderExprs);\n }\n rows = await q;\n }\n\n // Before remapping, which rewrites dates and bigints into their transport forms.\n if (cursorEntries) {\n attachRowCursors(rows, cursorEntries);\n }\n\n // Group by FK value before remapping (remapping may delete null fields).\n if (isOne) {\n const byKey = new Map(rows.map((row: any) => [String(row[foreignColPropName]), row]));\n remapToGraphQLArrayOutput(rows, targetTableName, targetTable);\n return parentIds.map((id) => byKey.get(String(id)) ?? null);\n }\n\n const grouped = new Map<string, any[]>(uniqueIds.map((id) => [String(id), []]));\n for (const row of rows) {\n grouped.get(String(row[foreignColPropName]))?.push(row);\n }\n remapToGraphQLArrayOutput(rows, targetTableName, targetTable);\n return parentIds.map((id) => grouped.get(String(id)) ?? []);\n });\n\n return loader.load(localValue);\n };\n\n // The context goes on here rather than at each throw: everything this resolver leans on —\n // filter compilation, ordering, the cursor — raises coded errors that know nothing about\n // which relation field called them.\n return async (parent, args, context, info) => {\n try {\n return await resolve(parent, args, context, info);\n } catch (e) {\n throw withErrorContext(toGraphQLError(e), errorCtx);\n }\n };\n };\n\n/**\n * The `extensions.drizzle` block for one relation field. The relation entry already carries\n * the target table's primary key (resolved at build time for pagination), so the field can\n * publish it without the dialect's key resolver being reachable from here.\n */\nexport const relationExtensionFor = (\n relEntry: TableNamedRelations,\n parentTable: string,\n relationName: string,\n isOne: boolean,\n aggregate?: boolean,\n) =>\n relationFieldExtension({\n targetTable: relEntry.targetTableName,\n parentTable,\n relation: relationName,\n single: isOne,\n primaryKey: relEntry.targetPkNames ?? [],\n aggregate,\n });\n","// The field names one table's generated resolvers get, after prefixes, suffixes and the\n// type-name mapper have been applied.\n\nimport { capitalize, uncapitalize } from '../../case-ops/index.ts';\nimport type { TypeNameMapper } from './naming.ts';\n\n/** The query and mutation field names one table generates. */\nexport type ResolverFieldNames = {\n typeName: string;\n listFieldName: string;\n singleFieldName: string;\n aggregateFieldName: string;\n groupByFieldName: string;\n createArrayFieldName: string;\n createSingleFieldName: string;\n upsertArrayFieldName: string;\n upsertSingleFieldName: string;\n updateFieldName: string;\n updateManyFieldName: string;\n updateSingleFieldName: string;\n updateCountFieldName: string;\n deleteFieldName: string;\n deleteSingleFieldName: string;\n restoreFieldName: string;\n restoreSingleFieldName: string;\n deleteCountFieldName: string;\n};\n\n/**\n * Derives the generated query/mutation field names for a table from the naming config\n * (typeNameMapper + prefixes/suffixes). Shared by all three dialect builders.\n */\nexport const computeResolverFieldNames = (\n tableName: string,\n typeNameMapper: TypeNameMapper | undefined,\n prefixes: { insert: string; update: string; delete: string; upsert?: string; restore?: string },\n suffixes: { list: string; single: string },\n): ResolverFieldNames => {\n const mapped = typeNameMapper?.(tableName);\n const typeName = mapped ? capitalize(mapped.singular) : capitalize(tableName);\n const listFieldName = (mapped?.plural ?? uncapitalize(tableName)) + suffixes.list;\n const singleFieldName = mapped?.singular ?? uncapitalize(tableName) + suffixes.single;\n const aggregateFieldName = `${mapped?.plural ?? uncapitalize(tableName)}Aggregate`;\n const groupByFieldName = `${mapped?.plural ?? uncapitalize(tableName)}GroupBy`;\n const pluralNoun = mapped ? capitalize(mapped.plural) : capitalize(tableName);\n const singularNoun = mapped ? capitalize(mapped.singular) : capitalize(tableName);\n // The write mutations take the same two suffixes the queries do, and in the same places:\n // `list` on the form that operates on a set of rows, `single` on the one that operates on\n // one. They used to take only `single`, so a build that renamed the list side got\n // `usersAll` on the query and a bare `createUsers` next to it — and, worse, a\n // `{ list: 'All', single: '' }` build silently lost the array insert, because both insert\n // mutations resolved to `createUsers` and the second registration overwrote the first.\n const createArrayFieldName = `${prefixes.insert}${pluralNoun}${suffixes.list}`;\n const createSingleFieldName = mapped\n ? `${prefixes.insert}${capitalize(mapped.singular)}`\n : `${prefixes.insert}${capitalize(tableName)}${suffixes.single}`;\n const upsertPrefix = prefixes.upsert ?? 'upsert';\n const upsertArrayFieldName = `${upsertPrefix}${pluralNoun}${suffixes.list}`;\n const upsertSingleFieldName = mapped\n ? `${upsertPrefix}${capitalize(mapped.singular)}`\n : `${upsertPrefix}${capitalize(tableName)}${suffixes.single}`;\n const restorePrefix = prefixes.restore ?? 'restore';\n // update/delete/restore are named the way create and upsert are: the plural noun on the\n // form that operates on a set of rows, the singular noun on the one that operates on one.\n // They used to put the *singular* noun on the list form — they filter rather than\n // enumerate — which read as a single-row operation and was not one (`deleteUser(where:)`\n // deleting every match), and which left the one-row variant no name but `Single` even\n // under a mapper whose singular/plural pair had already separated every other operation.\n const updateFieldName = `${prefixes.update}${pluralNoun}${suffixes.list}`;\n // The batch variant is plural like the array insert/upsert, with an explicit `Many`\n // suffix so it never collides with the single-set update.\n const updateManyFieldName = `${prefixes.update}${pluralNoun}Many`;\n const deleteFieldName = `${prefixes.delete}${pluralNoun}${suffixes.list}`;\n // The soft-delete counterpart, named the same way so `deleteUsers` / `restoreUsers` and\n // `deleteUser` / `restoreUser` read as pairs however the prefixes and suffixes are set.\n const restoreFieldName = `${restorePrefix}${pluralNoun}${suffixes.list}`;\n // With a mapper the singular noun is separation enough, exactly as it is for the single\n // query and the single insert, so those take no suffix at all. Without one both nouns are\n // the table key and `suffixes.single` is what separates the pair — the same string the\n // single query is separated by, so a build where it cannot separate them has already\n // failed on the queries (or, with no mapper at all, on the suffix check in `buildSchema`)\n // before reaching here. These used to carry a 'Single' fallback for that case; it was\n // unreachable once the list forms above stopped taking the singular noun.\n const singleWrite = (prefix: string) =>\n mapped ? `${prefix}${singularNoun}` : `${prefix}${singularNoun}${suffixes.single}`;\n const updateSingleFieldName = singleWrite(prefixes.update);\n const deleteSingleFieldName = singleWrite(prefixes.delete);\n const restoreSingleFieldName = singleWrite(restorePrefix);\n // The count variants are the plural write under another name, so they take the plural\n // noun the plural writes take. Their explicit `Count` is the disambiguator, so they take\n // no configured suffix.\n const updateCountFieldName = `${prefixes.update}${pluralNoun}Count`;\n const deleteCountFieldName = `${prefixes.delete}${pluralNoun}Count`;\n return {\n typeName,\n listFieldName,\n singleFieldName,\n aggregateFieldName,\n groupByFieldName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n updateManyFieldName,\n updateSingleFieldName,\n updateCountFieldName,\n deleteFieldName,\n deleteSingleFieldName,\n restoreFieldName,\n restoreSingleFieldName,\n deleteCountFieldName,\n };\n};\n","// Registration of the generated root fields, with the collision check that the naming\n// config cannot do for itself.\n\nimport type { GraphQLFieldConfig } from 'graphql';\n\n/**\n * Registers one generated root field, refusing to overwrite a name already taken.\n *\n * A generated name is the table name run through `typeNameMapper`, a prefix and a suffix,\n * and the pluralization each operation applies — so whether two operations collide is a\n * property of the finished names, not of any one piece of the config. `buildSchema` checks\n * what it can up front (identical list and single suffixes with no mapper), but that check\n * compares the suffix *strings*, which cannot see a collision the rest of the naming rules\n * produce: `{ list: 'All', single: '' }` used to give both insert mutations the name\n * `createUsers`, and the array insert simply disappeared from the schema.\n *\n * Assigning into the record silently kept the last registration. Throwing here means a\n * naming config that cannot work says so at build time, naming the field it lost.\n */\nexport const defineRootField = (\n fields: Record<string, GraphQLFieldConfig<any, any>>,\n kind: 'query' | 'mutation',\n name: string,\n config: GraphQLFieldConfig<any, any>,\n): void => {\n if (Object.getOwnPropertyDescriptor(fields, name) !== undefined) {\n throw new Error(\n `Drizzle-GraphQL Error: two generated ${kind} fields are both named '${name}'. Generated names come from the table name plus config.prefixes, config.suffixes and config.typeNameMapper — some combination of those gives two operations the same name. Adjust one of them so each operation gets its own.`,\n );\n }\n\n fields[name] = config;\n};\n","// The per-table input types — Filters, OrderBy, and the select field map — each cached so a\n// schema builds one of them per table no matter how many fields reference it.\n\nimport type { Table } from 'drizzle-orm';\nimport { is, One } from 'drizzle-orm';\nimport { GraphQLInputObjectType, GraphQLList, GraphQLNonNull, GraphQLString } from 'graphql';\nimport { drizzleColumnToGraphQLType } from '../../type-converter/index.ts';\nimport type { ConvertedColumn, ConvertedInputColumn } from '../../type-converter/types.ts';\nimport type { TableNamedRelations } from '../types.ts';\nimport { generateColumnFilterValues } from './column-filters.ts';\nimport { CURSOR_FIELD_NAME, rowCursorResolver } from './cursor.ts';\nimport { columnDocs } from './docs.ts';\nimport { hasExcludedColumns, visibleColumns } from './exclusions.ts';\nimport { innerOrderType } from './input-order.ts';\nimport type { TypeNameMapper } from './naming.ts';\nimport { resolveTypeName } from './naming.ts';\nimport { isFilterableRelation } from './relations.ts';\nimport type { TypeCacheCtx } from './type-cache.ts';\nimport { generateUniqueKeyFilterFields } from './unique-keys.ts';\n\n// Keyed by the `InnerOrder` instance as well as the table: the type's name follows the\n// build's naming rule, and the cache outlives a build, so two builds that name it differently\n// must not share one field map.\nconst orderMap = new WeakMap<object, Map<GraphQLInputObjectType, Record<string, ConvertedInputColumn>>>();\nconst generateTableOrderCached = (table: Table, innerOrder: GraphQLInputObjectType) => {\n // The cache outlives a build, so a table whose columns this build hides must not read from\n // it (a previous build may have cached the full set) or write to it (a later unfiltered\n // build would inherit the holes).\n const cacheable = !hasExcludedColumns(table);\n const cached = cacheable ? orderMap.get(table)?.get(innerOrder) : undefined;\n if (cached) {\n return cached;\n }\n\n let remapped = {};\n try {\n const columns = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n remapped = Object.fromEntries(\n columnEntries.map(([columnName, _columnDescription]) => [columnName, { type: innerOrder }]),\n );\n\n if (cacheable) {\n let byInnerOrder = orderMap.get(table);\n if (!byInnerOrder) {\n byInnerOrder = new Map();\n orderMap.set(table, byInnerOrder);\n }\n byInnerOrder.set(innerOrder, remapped);\n }\n } catch (_err) {}\n return remapped;\n};\n\nconst generateTableFilterValuesCached = (table: Table, tableName: string, cacheCtx: TypeCacheCtx) => {\n if (cacheCtx.filterFieldCache.has(table)) {\n return cacheCtx.filterFieldCache.get(table)!;\n }\n\n const columns = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n const remapped = Object.fromEntries(\n columnEntries.map(([columnName, column]) => [\n columnName,\n {\n type: generateColumnFilterValues(column, tableName, columnName, cacheCtx),\n // A filter field is the same column, so it carries the same documentation. Deprecation\n // is not propagated: filtering on a deprecated column is how a caller finds the rows\n // that still use it.\n ...(cacheCtx.docs.describeColumn\n ? { description: cacheCtx.docs.describeColumn(column, { tableName, columnName }) }\n : {}),\n },\n ]),\n );\n\n cacheCtx.filterFieldCache.set(table, remapped);\n\n return remapped;\n};\n\nexport const generateTableSelectTypeFieldsCached = (\n table: Table,\n tableName: string,\n cacheCtx: TypeCacheCtx,\n): Record<string, ConvertedColumn> => {\n if (cacheCtx.selectFieldCache.has(table)) {\n return cacheCtx.selectFieldCache.get(table)!;\n }\n\n const columns = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n const remapped = Object.fromEntries(\n columnEntries.map(([columnName, column]) => [\n columnName,\n {\n ...drizzleColumnToGraphQLType(column, columnName, tableName),\n ...columnDocs(cacheCtx.docs, column, tableName, columnName),\n },\n ]),\n );\n\n // Opaque keyset-pagination cursor. Only populated on rows returned by a list query; a real\n // column named `cursor` keeps the field for itself instead.\n if (!remapped[CURSOR_FIELD_NAME]) {\n remapped[CURSOR_FIELD_NAME] = {\n type: GraphQLString,\n description:\n \"Opaque cursor of this row's position in the query's ordering. Pass it as `after` to resume from here. Only set on rows returned by a list query.\",\n resolve: rowCursorResolver,\n } as ConvertedColumn;\n }\n\n cacheCtx.selectFieldCache.set(table, remapped);\n\n return remapped;\n};\n\n/**\n * Order fields for a table's to-one relations: each takes the target table's own OrderBy\n * input, so a list can be sorted by a related row's column (compiled as a correlated\n * subquery in the ORDER BY — see `extractOrderBy`). To-many relations are left out: \"order\n * a parent by its many children\" has no single defined value to sort on. A relation whose\n * name collides with a column is skipped — the column keeps the field.\n */\nconst generateRelationOrderFields = (\n tableName: string,\n cacheCtx: TypeCacheCtx,\n typeNameMapper: TypeNameMapper | undefined,\n columnFields: Record<string, ConvertedInputColumn>,\n relationMap?: Record<string, Record<string, TableNamedRelations>>,\n tables?: Record<string, Table>,\n): Record<string, { type: GraphQLInputObjectType; description?: string }> => {\n const relations = relationMap?.[tableName];\n if (!relations || !tables) {\n return {};\n }\n\n const fields: Record<string, { type: GraphQLInputObjectType; description?: string }> = {};\n\n for (const [relationName, relEntry] of Object.entries(relations)) {\n if (relationName in columnFields) {\n continue;\n }\n\n const targetTable = tables[relEntry.targetTableName];\n const relation = (relEntry as any).relation ?? relEntry;\n if (!targetTable || !is(relation, One) || !isFilterableRelation(relation)) {\n continue;\n }\n\n fields[relationName] = {\n type: generateTableOrderTypeCached(\n targetTable,\n relEntry.targetTableName,\n typeNameMapper,\n cacheCtx,\n relationMap,\n tables,\n ),\n description: `Order by columns of the related ${relationName} row`,\n };\n }\n\n return fields;\n};\n\nexport const generateTableOrderTypeCached = (\n table: Table,\n tableName: string,\n typeNameMapper: TypeNameMapper | undefined,\n cacheCtx: TypeCacheCtx,\n relationMap?: Record<string, Record<string, TableNamedRelations>>,\n tables?: Record<string, Table>,\n) => {\n if (cacheCtx.orderTypeCache.has(table)) {\n return cacheCtx.orderTypeCache.get(table)!;\n }\n\n // Fields are thunked so that relation order fields, which reference other tables' order\n // inputs (and eventually this one again), are only resolved after this type is cached.\n const order = new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'orderBy',\n defaultName: `${resolveTypeName(tableName, typeNameMapper)}OrderBy`,\n table: tableName,\n }),\n fields: () => {\n const orderColumns = generateTableOrderCached(table, innerOrderType(cacheCtx.typeName));\n return {\n ...orderColumns,\n ...generateRelationOrderFields(tableName, cacheCtx, typeNameMapper, orderColumns, relationMap, tables),\n };\n },\n });\n\n cacheCtx.orderTypeCache.set(table, order);\n\n return order;\n};\n\n/**\n * `${Target}ListRelationFilter` — the Prisma-style some/every/none wrapper for a to-many\n * relation. Shared by every table that points at the same target, and built through a thunk\n * so mutually-referencing tables (Users.posts ⇄ Posts.author) don't recurse forever.\n */\nconst generateListRelationFilterCached = (\n targetTable: Table,\n targetTableName: string,\n cacheCtx: TypeCacheCtx,\n typeNameMapper: TypeNameMapper | undefined,\n relationMap: Record<string, Record<string, TableNamedRelations>> | undefined,\n tables: Record<string, Table> | undefined,\n): GraphQLInputObjectType => {\n const cached = cacheCtx.listRelationFilterCache.get(targetTableName);\n if (cached) {\n return cached;\n }\n\n const listFilter = new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'listRelationFilter',\n defaultName: `${resolveTypeName(targetTableName, typeNameMapper)}ListRelationFilter`,\n table: targetTableName,\n }),\n fields: () => {\n const targetFilters = generateTableFilterTypeCached(\n targetTable,\n targetTableName,\n cacheCtx,\n typeNameMapper,\n relationMap,\n tables,\n );\n\n return {\n some: { type: targetFilters, description: 'At least one related row matches' },\n none: { type: targetFilters, description: 'No related row matches' },\n every: { type: targetFilters, description: 'Every related row matches' },\n };\n },\n });\n\n cacheCtx.listRelationFilterCache.set(targetTableName, listFilter);\n\n return listFilter;\n};\n\n/**\n * Filter fields for a table's relations: a to-one relation takes the target's own filter input\n * directly, a to-many relation takes the some/every/none wrapper. A relation whose name collides\n * with a column name is skipped — the column keeps the field.\n */\nconst generateRelationFilterFields = (\n tableName: string,\n cacheCtx: TypeCacheCtx,\n typeNameMapper: TypeNameMapper | undefined,\n columnFields: Record<string, ConvertedInputColumn>,\n relationMap?: Record<string, Record<string, TableNamedRelations>>,\n tables?: Record<string, Table>,\n): Record<string, { type: GraphQLInputObjectType; description?: string }> => {\n const relations = relationMap?.[tableName];\n if (!relations || !tables) {\n return {};\n }\n\n const fields: Record<string, { type: GraphQLInputObjectType; description?: string }> = {};\n\n for (const [relationName, relEntry] of Object.entries(relations)) {\n if (relationName in columnFields) {\n continue;\n }\n\n const targetTable = tables[relEntry.targetTableName];\n const relation = (relEntry as any).relation ?? relEntry;\n if (!targetTable) {\n continue;\n }\n\n fields[relationName] = is(relation, One)\n ? {\n type: generateTableFilterTypeCached(\n targetTable,\n relEntry.targetTableName,\n cacheCtx,\n typeNameMapper,\n relationMap,\n tables,\n ),\n description: `Matches rows whose ${relationName} matches these filters`,\n }\n : {\n type: generateListRelationFilterCached(\n targetTable,\n relEntry.targetTableName,\n cacheCtx,\n typeNameMapper,\n relationMap,\n tables,\n ),\n };\n }\n\n return fields;\n};\n\nexport const generateTableFilterTypeCached = (\n table: Table,\n tableName: string,\n cacheCtx: TypeCacheCtx,\n typeNameMapper?: TypeNameMapper,\n relationMap?: Record<string, Record<string, TableNamedRelations>>,\n tables?: Record<string, Table>,\n) => {\n if (cacheCtx.filterTypeCache.has(table)) {\n return cacheCtx.filterTypeCache.get(table)!;\n }\n\n // Fields are thunked so that relation filters, which reference other tables' filter inputs\n // (and eventually this one again), are only resolved after this type is in the cache.\n const buildFields = () => {\n const filterColumns = generateTableFilterValuesCached(table, tableName, cacheCtx);\n const uniqueKeys = cacheCtx.uniqueKeysOf?.(tableName);\n return {\n ...filterColumns,\n ...generateRelationFilterFields(tableName, cacheCtx, typeNameMapper, filterColumns, relationMap, tables),\n // Last, and already filtered against both — a key field only exists under a name no\n // column and no relation claimed.\n ...(uniqueKeys ? generateUniqueKeyFilterFields(table, tableName, uniqueKeys, typeNameMapper, cacheCtx) : {}),\n };\n };\n\n // The boolean branches (OR / AND / NOT) are recursive — each branch is this filter type\n // itself — so the thunk references the type being constructed. Siblings and branches\n // compose: sibling fields are implicitly ANDed with the OR / AND / NOT groups.\n const filters: GraphQLInputObjectType = new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'filter',\n defaultName: `${resolveTypeName(tableName, typeNameMapper)}Filters`,\n table: tableName,\n }),\n fields: () => ({\n ...buildFields(),\n OR: {\n type: new GraphQLList(new GraphQLNonNull(filters)),\n description: 'At least one branch matches; ANDed with any sibling fields',\n },\n AND: {\n type: new GraphQLList(new GraphQLNonNull(filters)),\n description: 'Every branch matches',\n },\n NOT: {\n type: filters,\n description: 'Negates the nested filters',\n },\n }),\n });\n\n cacheCtx.filterTypeCache.set(table, filters);\n\n return filters;\n};\n","// The per-table object types and the fields on them, including relation fields and the type a\n// mutation returns.\n\nimport type { Table } from 'drizzle-orm';\nimport { is, One } from 'drizzle-orm';\nimport {\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n GraphQLString,\n} from 'graphql';\nimport { capitalize } from '../../case-ops/index.ts';\nimport { tableTypeExtension } from '../../extensions.ts';\nimport { drizzleColumnToGraphQLType } from '../../type-converter/index.ts';\nimport type { ConvertedRelationColumnWithArgs } from '../../type-converter/types.ts';\nimport { fieldUpdateInputType } from '../field-updates.ts';\n// Type-only: the nested-write module imports this one at runtime, so the dependency has to\n// stay one-directional. The implementation is injected by the dialect builder.\nimport type { NestedWriteTypes } from '../nested-writes.ts';\nimport type { GeneratedTableTypes, GeneratedTableTypesOutputs, SelectData, TableNamedRelations } from '../types.ts';\nimport { deletedArg } from './args.ts';\nimport { generateDistinctEnum } from './column-enums.ts';\nimport { inputFieldDocs } from './docs.ts';\nimport { visibleColumns } from './exclusions.ts';\nimport { aggregateFieldComplexity, listFieldComplexity } from './limits.ts';\nimport type { TypeNameMapper } from './naming.ts';\nimport { resolveTypeName } from './naming.ts';\nimport { relationExtensionFor } from './relation-resolvers.ts';\nimport type { RelationAggregateFactory, RelationResolverFactory } from './relations.ts';\nimport {\n generateTableFilterTypeCached,\n generateTableOrderTypeCached,\n generateTableSelectTypeFieldsCached,\n} from './table-inputs.ts';\nimport type { TypeCacheCtx } from './type-cache.ts';\n\n/**\n * Build the select fields for a table.\n * Creates:\n * - Main select type: ${capitalize(tableName)} (e.g. Users)\n * - Relation fields reference the target table's own type directly (e.g. posts: [Posts!]!)\n * rather than creating intermediate relation types.\n *\n * The function is called recursively for relation targets.\n * Cycle detection: usedTables tracks tables currently being processed in the call stack.\n * When we see a table already in usedTables, we stop recursing (no relation fields for that type).\n */\nconst generateSelectFields = <TWithOrder extends boolean>(\n tables: Record<string, Table>,\n tableName: string,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n fromTableName: string,\n fromRelationName: string,\n withOrder: TWithOrder,\n relationsDepthLimit: number | undefined,\n cacheCtx: TypeCacheCtx,\n typeNameMapper: TypeNameMapper | undefined,\n usedTables: Set<string> = new Set(),\n resolverFactory?: RelationResolverFactory,\n currentDepth: number = 0,\n relationAggregateFactory?: RelationAggregateFactory,\n): SelectData<TWithOrder> => {\n const table = tables[tableName]!;\n const order = withOrder\n ? generateTableOrderTypeCached(table, tableName, typeNameMapper, cacheCtx, relationMap, tables)\n : undefined;\n const filters = generateTableFilterTypeCached(table, tableName, cacheCtx, typeNameMapper, relationMap, tables);\n const tableFields = generateTableSelectTypeFieldsCached(table, tableName, cacheCtx);\n\n const relationsForTable = relationMap[tableName];\n const relationEntries: [string, TableNamedRelations][] = relationsForTable ? Object.entries(relationsForTable) : [];\n\n // Depth limit: stop generating relation fields once we reach the configured maximum.\n // relationsDepthLimit: 0 → no relation fields on any type.\n // relationsDepthLimit: N → each table's own root call (depth 0) generates its relations,\n // but traversals beyond depth N stop, which prevents unbounded recursive generation.\n if (relationsDepthLimit !== undefined && currentDepth >= relationsDepthLimit) {\n return {\n order,\n filters,\n tableFields,\n relationFields: {},\n } as SelectData<TWithOrder>;\n }\n\n // If this table is already being processed (cycle), stop recursing.\n // Return just the base fields with no relation fields.\n if (usedTables.has(tableName)) {\n return {\n order,\n filters,\n tableFields,\n relationFields: {},\n } as SelectData<TWithOrder>;\n }\n\n // For the root call (fromTableName === '' && fromRelationName === ''), this builds the\n // main ${capitalize(tableName)}SelectItem type.\n // For recursive calls, this builds the relation type.\n const isRootCall = fromTableName === '' && fromRelationName === '';\n\n // If the root type has already been fully built (not just pre-registered as a shell), return early.\n if (isRootCall && cacheCtx.fullyBuiltTables.has(tableName)) {\n return {\n order,\n filters,\n tableFields,\n relationFields: {},\n } as SelectData<TWithOrder>;\n }\n\n // Obtain or create the mutable relation-fields container for this table.\n // The container is a plain object whose `fields` property the GraphQLObjectType thunk reads.\n // Pre-registering it here (before recursion) allows sibling relation traversals to reference\n // the same single GraphQLObjectType instance even when it hasn't been fully built yet.\n let container = cacheCtx.relationFieldContainers.get(tableName);\n if (!container) {\n container = { fields: {} };\n cacheCtx.relationFieldContainers.set(tableName, container);\n }\n\n if (isRootCall && !cacheCtx.objectTypeCache.has(tableName)) {\n const typeName = cacheCtx.typeName({\n kind: 'object',\n defaultName: resolveTypeName(tableName, typeNameMapper),\n table: tableName,\n });\n // Pre-register shell with thunk BEFORE recursing to break circular refs.\n // The thunk reads container.fields, which will be populated after recursion completes.\n const shell = new GraphQLObjectType({\n name: typeName,\n description: cacheCtx.docs.describeTable?.(tableName),\n fields: () => ({ ...tableFields, ...container!.fields }),\n extensions: { drizzle: tableTypeExtension(tableName, cacheCtx.primaryKeyOf?.(tableName) ?? []) },\n });\n cacheCtx.objectTypeCache.set(tableName, shell);\n }\n\n // Build relation fields — recurse into each related table.\n // Mark this table as in-progress before recursing to detect cycles.\n if (relationEntries.length > 0) {\n const rawRelationFields: [string, ConvertedRelationColumnWithArgs][] = [];\n\n // Mark this table as currently being processed.\n const nextUsedTables = new Set(usedTables);\n nextUsedTables.add(tableName);\n\n for (const [relationName, relEntry] of relationEntries) {\n const { targetTableName } = relEntry;\n const relation = (relEntry as any).relation ?? relEntry;\n const isOne = is(relation, One);\n\n // Always recurse to get the target table's filters/order (needed for args).\n // The usedTables check inside the recursive call prevents actual infinite recursion.\n const relSelectData = generateSelectFields(\n tables,\n targetTableName,\n relationMap,\n tableName, // fromTableName for the relation type\n relationName, // fromRelationName for the relation type\n !isOne,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n nextUsedTables,\n resolverFactory,\n currentDepth + 1,\n relationAggregateFactory,\n );\n\n // Use the target table's own GraphQL type directly instead of creating an intermediate relation type.\n // Ensure exactly one GraphQLObjectType instance exists for the target table.\n // If the root call for the target table has already run (or pre-registered a shell),\n // reuse that instance so the schema never contains duplicate type names.\n let relType = cacheCtx.objectTypeCache.get(targetTableName);\n if (!relType) {\n // The target table hasn't been processed yet. Pre-register a shell so that:\n // (a) this relation field has a concrete type reference, and\n // (b) when the target table's root call eventually runs, it reuses this same object.\n const targetTable = tables[targetTableName]!;\n const targetTableFields = generateTableSelectTypeFieldsCached(targetTable, targetTableName, cacheCtx);\n // Get or create a container for the target table's relation fields.\n let targetContainer = cacheCtx.relationFieldContainers.get(targetTableName);\n if (!targetContainer) {\n targetContainer = { fields: {} };\n cacheCtx.relationFieldContainers.set(targetTableName, targetContainer);\n }\n const capturedTargetContainer = targetContainer;\n // The thunk reads capturedTargetContainer.fields so that when the target table's root\n // call populates the container, the shell automatically includes those relation fields.\n relType = new GraphQLObjectType({\n name: cacheCtx.typeName({\n kind: 'object',\n defaultName: resolveTypeName(targetTableName, typeNameMapper),\n table: targetTableName,\n }),\n description: cacheCtx.docs.describeTable?.(targetTableName),\n fields: () => ({ ...targetTableFields, ...capturedTargetContainer.fields }),\n extensions: {\n drizzle: tableTypeExtension(targetTableName, cacheCtx.primaryKeyOf?.(targetTableName) ?? []),\n },\n });\n cacheCtx.objectTypeCache.set(targetTableName, relType);\n }\n\n const resolve = resolverFactory?.({ tableName, relationName, relEntry: relEntry as TableNamedRelations, isOne });\n const relationDescription = cacheCtx.docs.describeRelation?.(tableName, relationName);\n const relationDocs = relationDescription !== undefined ? { description: relationDescription } : {};\n\n if (isOne) {\n // Honor the relation's declared optionality: `r.one.Target({ ..., optional: false })`\n // asserts the related row always exists (a NOT NULL foreign key), so the field is\n // emitted as `Target!`. The default (`optional: true` / omitted) stays nullable.\n // Column nullability alone is NOT used to infer this — a notNull `from` column does\n // not guarantee a related row exists when the FK constraint lives on the other side\n // (e.g. `Users.customer` joins the notNull `Users.id` to `Customers.userId`).\n const isRequired = (relation as One<any, any>).optional === false;\n rawRelationFields.push([\n relationName,\n {\n type: isRequired ? new GraphQLNonNull(relType) : relType,\n args: {\n where: { type: relSelectData.filters },\n ...deletedArg(cacheCtx.softDeleteOf, targetTableName, cacheCtx.typeName),\n },\n resolve,\n ...relationDocs,\n extensions: { drizzle: relationExtensionFor(relEntry, tableName, relationName, true) },\n },\n ]);\n continue;\n }\n\n // A to-many relation field is a list of the target table, so it takes the same\n // pagination surface a root list of that table does. `after` and `distinct` are the\n // two drizzle's `with:` clause cannot express, so a request that passes either drops\n // the relation out of the eager fetch and resolves it through the batch loader, which\n // implements both — see extractRelationsParams.\n const targetDistinctEnum = cacheCtx.featureOf(targetTableName).distinct\n ? generateDistinctEnum(\n tables[targetTableName]!,\n resolveTypeName(targetTableName, typeNameMapper),\n cacheCtx.typeName,\n targetTableName,\n )\n : undefined;\n\n rawRelationFields.push([\n relationName,\n {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(relType))),\n args: {\n where: { type: relSelectData.filters },\n orderBy: { type: relSelectData.order! },\n offset: { type: GraphQLInt },\n limit: { type: GraphQLInt },\n ...deletedArg(cacheCtx.softDeleteOf, targetTableName, cacheCtx.typeName),\n after: {\n type: GraphQLString,\n description:\n \"Keyset pagination: only return related rows strictly after this cursor (a row's `cursor` field from a previous page of this relation, under the same orderBy).\",\n },\n ...(targetDistinctEnum\n ? { distinct: { type: new GraphQLList(new GraphQLNonNull(targetDistinctEnum)) } }\n : {}),\n },\n resolve,\n ...relationDocs,\n extensions: {\n drizzle: relationExtensionFor(relEntry, tableName, relationName, false),\n ...(cacheCtx.complexity\n ? { complexity: listFieldComplexity(cacheCtx.complexity, cacheCtx.limits?.(targetTableName)) }\n : {}),\n },\n },\n ]);\n\n // Aggregate over the related rows without fetching them: `user { postsAggregate { count } }`.\n // Skipped when the name would shadow a column or another relation.\n const aggregateFieldName = `${relationName}Aggregate`;\n if (!tableFields[aggregateFieldName] && !relationsForTable?.[aggregateFieldName]) {\n const relationAggregate = relationAggregateFactory?.({\n tableName,\n relationName,\n relEntry: relEntry as TableNamedRelations,\n });\n\n if (relationAggregate) {\n rawRelationFields.push([\n aggregateFieldName,\n {\n type: new GraphQLNonNull(relationAggregate.type),\n args: {\n where: { type: relSelectData.filters },\n ...deletedArg(cacheCtx.softDeleteOf, targetTableName, cacheCtx.typeName),\n },\n resolve: relationAggregate.resolve,\n extensions: {\n drizzle: relationExtensionFor(relEntry, tableName, relationName, isOne, true),\n ...(cacheCtx.complexity ? { complexity: aggregateFieldComplexity(cacheCtx.complexity) } : {}),\n },\n } as unknown as ConvertedRelationColumnWithArgs,\n ]);\n }\n }\n }\n\n const builtRelationFields = Object.fromEntries(rawRelationFields);\n\n // Only the root call should populate the container — non-root calls are temporary traversals\n // to collect filters/order for args and should not overwrite the canonical relation fields.\n if (isRootCall) {\n // Populate the container so that the thunk on the GraphQLObjectType shell (whether it was\n // created here or pre-registered by another table's relation traversal) picks up the fields.\n container.fields = builtRelationFields;\n cacheCtx.fullyBuiltTables.add(tableName);\n }\n\n return {\n order,\n filters,\n tableFields,\n relationFields: builtRelationFields,\n } as SelectData<TWithOrder>;\n }\n\n // No relation entries — mark as fully built if root call.\n if (isRootCall) {\n cacheCtx.fullyBuiltTables.add(tableName);\n }\n\n return {\n order,\n filters,\n tableFields,\n relationFields: {},\n } as SelectData<TWithOrder>;\n};\n\nexport const generateTableTypes = <WithReturning extends boolean>(\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n withReturning: WithReturning,\n relationsDepthLimit: number | undefined,\n cacheCtx: TypeCacheCtx,\n typeNameMapper: TypeNameMapper | undefined = undefined,\n insertPrefix: string = 'create',\n updatePrefix: string = 'update',\n resolverFactory?: RelationResolverFactory,\n relationAggregateFactory?: RelationAggregateFactory,\n nestedWrites?: NestedWriteTypes,\n): GeneratedTableTypes<WithReturning> => {\n const { tableFields, relationFields, filters, order } = generateSelectFields(\n tables,\n tableName,\n relationMap,\n '', // root call: no fromTableName\n '', // root call: no fromRelationName\n true,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n new Set(),\n resolverFactory,\n 0,\n relationAggregateFactory,\n );\n\n const table = tables[tableName]!;\n const columns = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n // A column whose value comes from the request context is not part of any write input: the\n // client cannot supply one on create, and cannot reassign one on update. It stays an\n // ordinary column everywhere else — the output type, the filters, the ordering.\n const contextColumns = cacheCtx.contextValuesOf?.(tableName);\n // Same for the column that marks a row deleted: `delete` and `restore` own it, and a client\n // that could write it through an ordinary create or update could delete or undelete a row\n // without going through either.\n const markerColumn = cacheCtx.softDeleteOf?.(tableName)?.columnName;\n const writableEntries =\n contextColumns || markerColumn\n ? columnEntries.filter(\n ([columnName]) => !(contextColumns && columnName in contextColumns) && columnName !== markerColumn,\n )\n : columnEntries;\n\n // A column a nested write can supply (`author: { create: … }` fills in `authorId`) cannot\n // stay required on the create input, or the two ways of setting it would be mutually\n // exclusive at the type level.\n const relaxedColumns = nestedWrites?.relaxedColumns(tableName);\n\n const insertFields = Object.fromEntries(\n writableEntries.map(([columnName, column]) => {\n const converted = drizzleColumnToGraphQLType(\n column,\n columnName,\n tableName,\n !!relaxedColumns?.has(columnName),\n true,\n true,\n );\n return [\n columnName,\n { ...converted, ...inputFieldDocs(cacheCtx.docs, column, tableName, columnName, converted.type) },\n ];\n }),\n );\n\n const updateFields = Object.fromEntries(\n writableEntries.map(([columnName, column]) => {\n const converted = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, true);\n // A numeric or array column takes an operations input instead of the bare scalar, so\n // it can be changed relative to its current value rather than only replaced.\n const operations = cacheCtx.featureOf(tableName).fieldUpdateOperations\n ? fieldUpdateInputType(column, columnName, tableName, cacheCtx.typeName)\n : undefined;\n const field = operations ? { ...converted, type: operations } : converted;\n return [columnName, { ...field, ...inputFieldDocs(cacheCtx.docs, column, tableName, columnName, field.type) }];\n }),\n );\n\n const typeName = resolveTypeName(tableName, typeNameMapper);\n\n // Insert/update input types: ${capitalize(insertPrefix)}${resolveTypeName(tableName)}Input / ${capitalize(updatePrefix)}${resolveTypeName(tableName)}Input\n // With nested writes on, the fields are thunked: a relation field's operand is the target\n // table's filter input, which does not exist yet while this table is being generated.\n const insertInput = new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'createInput',\n defaultName: `${capitalize(insertPrefix)}${typeName}Input`,\n table: tableName,\n }),\n fields: nestedWrites\n ? () => ({ ...insertFields, ...nestedWrites.createFields(tableName, typeName) })\n : insertFields,\n });\n\n const updateInput = new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'updateInput',\n defaultName: `${capitalize(updatePrefix)}${typeName}Input`,\n table: tableName,\n }),\n fields: nestedWrites\n ? () => ({ ...updateFields, ...nestedWrites.updateFields(tableName, typeName) })\n : updateFields,\n });\n\n // Select type: ${resolveTypeName(tableName)} (with relation fields)\n // Reuse the cached shell created in generateSelectFields.\n const selectSingleOutput =\n cacheCtx.objectTypeCache.get(tableName) ??\n new GraphQLObjectType({\n name: cacheCtx.typeName({\n kind: 'object',\n defaultName: resolveTypeName(tableName, typeNameMapper),\n table: tableName,\n }),\n description: cacheCtx.docs.describeTable?.(tableName),\n fields: { ...tableFields, ...relationFields },\n extensions: { drizzle: tableTypeExtension(tableName, cacheCtx.primaryKeyOf?.(tableName) ?? []) },\n });\n\n const selectArrOutput = new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(selectSingleOutput)));\n\n // Mutation return type: ${capitalize(tableName)}Item (table columns only, no relations)\n // const singleTableItemOutput = withReturning\n // ? new GraphQLObjectType({\n // name: `${capitalize(tableName)}`,\n // // name: `${capitalize(tableName)}Item`,\n // fields: tableFields,\n // })\n // : undefined;\n\n const arrTableItemOutput = withReturning\n ? // ? new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(singleTableItemOutput!)))\n new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(selectSingleOutput!)))\n : undefined;\n\n const inputs = {\n insertInput,\n updateInput,\n tableOrder: order,\n tableFilters: filters,\n };\n\n const outputs = (\n withReturning\n ? {\n selectSingleOutput,\n selectArrOutput,\n singleTableItemOutput: selectSingleOutput!,\n // singleTableItemOutput: singleTableItemOutput!,\n arrTableItemOutput: arrTableItemOutput!,\n }\n : {\n selectSingleOutput,\n selectArrOutput,\n }\n ) as GeneratedTableTypesOutputs<WithReturning>;\n\n return {\n inputs,\n outputs,\n };\n};\n","import type { SchemaFeatures } from '../types.ts';\nimport type { TableFeatures } from './builders/types.ts';\n\n/**\n * What a table generates when the config says nothing. Everything is on except the opt-in\n * features, so a build with no `features` block generates what it always did.\n */\nexport const featureDefaults: TableFeatures = {\n aggregates: true,\n groupBy: true,\n relationAggregates: true,\n distinct: true,\n insert: true,\n update: true,\n updateMany: true,\n delete: true,\n upsert: false,\n fieldUpdateOperations: false,\n countMutations: false,\n requireWhere: false,\n uniqueKeyFilters: false,\n};\n\n/**\n * Turns `BuildSchemaConfig.features` — booleans, per-table predicates, or nothing at all —\n * into a lookup the generators can ask about one table. Memoized, so a predicate is run once\n * per table however many places consult it.\n */\nexport const resolveTableFeatures = (features: SchemaFeatures | undefined): ((tableName: string) => TableFeatures) => {\n const cache = new Map<string, TableFeatures>();\n const names = Object.keys(featureDefaults) as (keyof TableFeatures)[];\n return (tableName: string): TableFeatures => {\n let resolved = cache.get(tableName);\n if (!resolved) {\n resolved = {} as TableFeatures;\n for (const name of names) {\n const configured = features?.[name];\n // A predicate answering with something other than a boolean is answering \"yes\" for\n // anything truthy, matching how the flags read everywhere else.\n resolved[name] =\n configured === undefined\n ? featureDefaults[name]\n : typeof configured === 'function'\n ? !!configured(tableName)\n : !!configured;\n }\n cache.set(tableName, resolved);\n }\n return resolved;\n };\n};\n","// =============================================================================\n// `BuildSchemaConfig` -> `SchemaGeneratorOptions`.\n//\n// Everything `buildSchema` decides before it knows which dialect it is talking\n// to: defaults filled in, per-table configuration resolved against the real\n// schema (so a renamed table or column fails the build rather than silently\n// doing nothing), contradictory feature flags warned about, and the whole lot\n// normalized into the single options object the three dialect generators take.\n// =============================================================================\n\nimport { getColumns, is, Table } from 'drizzle-orm';\nimport type { BuildSchemaConfig, TableLimitPolicy } from '../types.ts';\nimport {\n DEFAULT_TRANSACTION_TIMEOUT_MS,\n type DefaultOrderByFor,\n type LimitPolicyFor,\n normalizeWriteHooks,\n type ResolvedLimitPolicy,\n type ResolvedWriteHooks,\n resolveGeneratedTypeNames,\n resolveLimitPolicy,\n resolveSoftDeleteInfo,\n type SoftDeleteInfo,\n type TablePolicies,\n type WriteHookFor,\n type WriteHookPositions,\n type WriteHooks,\n} from './builders/common.ts';\nimport type { SchemaGeneratorOptions } from './builders/types.ts';\nimport { singularizeMapper } from './case-ops/index.ts';\nimport { resolveTableFeatures } from './features.ts';\n\n/**\n * Resolves a caller's `BuildSchemaConfig` against the Drizzle schema it will be applied to.\n *\n * Throws on configuration that names a table or column the schema does not have, and warns on\n * feature flags whose combination generates something other than what it appears to ask for.\n *\n * @param config the caller's config, or `undefined` for an all-defaults build\n * @param schema the Drizzle schema map `buildSchema` resolved from the database instance\n */\nexport const resolveBuildConfig = (\n config: BuildSchemaConfig | undefined,\n schema: Record<string, unknown>,\n): SchemaGeneratorOptions => {\n const prefixes = {\n insert: config?.prefixes?.insert ?? 'create',\n delete: config?.prefixes?.delete ?? 'delete',\n update: config?.prefixes?.update ?? 'update',\n upsert: config?.prefixes?.upsert ?? 'upsert',\n restore: config?.prefixes?.restore ?? 'restore',\n };\n\n const suffixes = {\n list: config?.suffixes?.list ?? '',\n single: config?.suffixes?.single ?? 'Single',\n };\n\n // `'singularize'` is the one shipped preset; anything else is the caller's own function.\n const typeNameMapper = config?.typeNameMapper === 'singularize' ? singularizeMapper : config?.typeNameMapper;\n\n // The naming rule for every generated type. Validated here rather than left to graphql-js,\n // whose complaint names the finished type and not the affix that produced it.\n const affix = (value: string | undefined, key: 'typeNamePrefix' | 'typeNameSuffix', pattern: RegExp) => {\n if (value !== undefined && !pattern.test(value)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.${key} must be a valid GraphQL name fragment (letters, digits and underscores${key === 'typeNamePrefix' ? ', not starting with a digit' : ''}), got '${value}'.`,\n );\n }\n return value;\n };\n const typeName = resolveGeneratedTypeNames({\n derivedTypeNameMapper: config?.derivedTypeNameMapper,\n typeNamePrefix: affix(config?.typeNamePrefix, 'typeNamePrefix', /^[_A-Za-z][_0-9A-Za-z]*$/),\n typeNameSuffix: affix(config?.typeNameSuffix, 'typeNameSuffix', /^[_0-9A-Za-z]+$/),\n });\n\n // Table keys this build generates for — what a per-table feature predicate is asked about.\n // Excluded tables are dropped up front so no predicate is ever consulted for a table that\n // generates nothing.\n const tableKeys = Object.entries(schema as Record<string, unknown>)\n .filter(([, value]) => is(value, Table))\n .map(([key]) => key);\n const excludedTableNames = new Set(config?.exclude?.tables ?? []);\n const featureTables = tableKeys.filter((key) => !excludedTableNames.has(key));\n\n // Resolved the same way the generators resolve it, so the implication warnings below\n // describe exactly what gets generated.\n const forTable = resolveTableFeatures(config?.features);\n\n // Cost hints are inert without a complexity rule installed, so they are generated unless the\n // caller opts out.\n const complexityConfig = config?.complexity ?? true;\n const complexity =\n complexityConfig === false\n ? undefined\n : {\n defaultListSize: (complexityConfig === true ? undefined : complexityConfig.defaultListSize) ?? 10,\n aggregateCost: (complexityConfig === true ? undefined : complexityConfig.aggregateCost) ?? 10,\n };\n\n // Off unless asked for: opening transactions the caller did not wire up themselves is a\n // behavior change (and some drivers, e.g. neon-http, cannot open one at all).\n const transactionsOpt = config?.transactions;\n const transactions =\n transactionsOpt === undefined || transactionsOpt === 'none'\n ? undefined\n : {\n timeoutMs:\n (transactionsOpt === 'auto' ? undefined : transactionsOpt.timeoutMs) ?? DEFAULT_TRANSACTION_TIMEOUT_MS,\n };\n\n // A limit policy is only built when the caller configured one; otherwise `limits` stays\n // undefined and every list keeps its unbounded behavior. Policies are resolved once per\n // table and memoized, since the lookup runs on every relation field build and every list\n // resolve.\n const limitsConfig = config?.limits;\n if (limitsConfig) {\n const check = (policy: TableLimitPolicy, where: string) => {\n for (const key of ['defaultLimit', 'maxLimit'] as const) {\n const value = policy[key];\n if (value === undefined) {\n continue;\n }\n if (!Number.isInteger(value) || value < 1) {\n throw new Error(`Drizzle-GraphQL Error: config.limits${where}.${key} must be a positive integer.`);\n }\n }\n };\n check(limitsConfig, '');\n for (const [tableName, policy] of Object.entries(limitsConfig.tables ?? {})) {\n check(policy, `.tables.${tableName}`);\n }\n }\n const limitPolicyCache = new Map<string, ResolvedLimitPolicy | undefined>();\n const limits: LimitPolicyFor | undefined = limitsConfig\n ? (tableName: string) => {\n if (limitPolicyCache.has(tableName)) {\n return limitPolicyCache.get(tableName);\n }\n const resolved = resolveLimitPolicy(limitsConfig, limitsConfig.tables?.[tableName]);\n limitPolicyCache.set(tableName, resolved);\n return resolved;\n }\n : undefined;\n\n // Per-table defaults are resolved against the real schema at build time, so a renamed table\n // or column fails the build rather than silently ordering by nothing. The normalized form is\n // the same shape the generated `orderBy` argument has, so every read path can substitute it\n // without knowing where it came from.\n const defaultsConfig = config?.defaults;\n const defaultOrderByByTable = new Map<string, Record<string, any>>();\n if (defaultsConfig) {\n const defaultsTableNames = new Set(tableKeys);\n for (const [tableName, tableDefaults] of Object.entries(defaultsConfig)) {\n if (!defaultsTableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.defaults names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n const orderBy = tableDefaults?.orderBy;\n if (!orderBy || !Object.keys(orderBy).length) {\n continue;\n }\n const columns = getColumns(schema[tableName] as Table);\n const normalized: Record<string, any> = {};\n for (const [columnName, entry] of Object.entries(orderBy)) {\n if (!columns[columnName]) {\n throw new Error(\n `Drizzle-GraphQL Error: config.defaults.${tableName}.orderBy names '${columnName}', which is not a column of '${tableName}'.`,\n );\n }\n const direction = typeof entry === 'string' ? entry : entry?.direction;\n if (direction !== 'asc' && direction !== 'desc') {\n throw new Error(\n `Drizzle-GraphQL Error: config.defaults.${tableName}.orderBy.${columnName} must be 'asc', 'desc', or { direction, priority? }.`,\n );\n }\n const priority = typeof entry === 'string' ? undefined : entry?.priority;\n if (priority !== undefined && !Number.isInteger(priority)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.defaults.${tableName}.orderBy.${columnName}.priority must be an integer.`,\n );\n }\n normalized[columnName] = priority === undefined ? { direction } : { direction, priority };\n }\n defaultOrderByByTable.set(tableName, normalized);\n }\n }\n const defaultOrderBy: DefaultOrderByFor | undefined = defaultOrderByByTable.size\n ? (tableName: string) => defaultOrderByByTable.get(tableName)\n : undefined;\n\n // A row scope and the context-derived columns are resolved against the real schema for the\n // same reason exclusions are: a renamed table or column must fail the build, not silently\n // stop scoping. Both stay undefined unless configured, so an unconfigured build emits the\n // same SQL it always did.\n const scopeConfig = config?.scope;\n const contextValuesConfig = config?.contextValues;\n if (scopeConfig || contextValuesConfig) {\n const tableNames = new Set(tableKeys);\n for (const [tableName, hook] of Object.entries(scopeConfig ?? {})) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.scope names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n if (typeof hook !== 'function') {\n throw new Error(`Drizzle-GraphQL Error: config.scope.${tableName} must be a function.`);\n }\n }\n for (const [tableName, columnHooks] of Object.entries(contextValuesConfig ?? {})) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.contextValues names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n const columns = getColumns(schema[tableName] as Table);\n for (const [columnName, hook] of Object.entries(columnHooks)) {\n if (!columns[columnName]) {\n throw new Error(\n `Drizzle-GraphQL Error: config.contextValues names '${tableName}.${columnName}', which is not a column of that table.`,\n );\n }\n if (typeof hook !== 'function') {\n throw new Error(`Drizzle-GraphQL Error: config.contextValues.${tableName}.${columnName} must be a function.`);\n }\n }\n }\n }\n // Soft delete is resolved against the real columns here, once, so a renamed column or a\n // NOT NULL column with no restore value fails the build rather than silently making every\n // row visible again at runtime.\n const softDeleteConfig = config?.softDelete;\n const softDeleteInfos = new Map<string, SoftDeleteInfo>();\n if (softDeleteConfig) {\n if (typeof softDeleteConfig === 'function') {\n for (const tableName of tableKeys) {\n const declaration = softDeleteConfig(schema[tableName] as Table, tableName);\n if (declaration) {\n softDeleteInfos.set(tableName, resolveSoftDeleteInfo(schema[tableName] as Table, tableName, declaration));\n }\n }\n } else {\n const tableNames = new Set(tableKeys);\n for (const [tableName, declaration] of Object.entries(softDeleteConfig)) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n softDeleteInfos.set(tableName, resolveSoftDeleteInfo(schema[tableName] as Table, tableName, declaration));\n }\n }\n }\n\n // Write hooks are resolved the same way: a table name that matches nothing fails the build,\n // and the two registration shapes collapse into one per-table lookup here rather than in\n // every resolver.\n const onWriteConfig = config?.onWrite;\n const writeHooks = new Map<string, ResolvedWriteHooks | undefined>();\n if (onWriteConfig) {\n // A bare function, or an object naming the positions, applies to every table; anything\n // else is a table map. `before`/`after` are reserved as position names for that reason.\n const isGlobal =\n typeof onWriteConfig === 'function' ||\n typeof (onWriteConfig as WriteHookPositions).before === 'function' ||\n typeof (onWriteConfig as WriteHookPositions).after === 'function';\n if (isGlobal) {\n // Resolved per table rather than once, because a hook's `columns` resolve to that\n // table's own column objects — and a named column every table must actually have.\n for (const tableName of featureTables) {\n writeHooks.set(\n tableName,\n normalizeWriteHooks(\n onWriteConfig as WriteHooks,\n getColumns(schema[tableName] as Table),\n `config.onWrite (on table '${tableName}')`,\n ),\n );\n }\n } else {\n const tableNames = new Set(tableKeys);\n for (const [tableName, hooks] of Object.entries(onWriteConfig as Record<string, WriteHooks>)) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.onWrite names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n if (typeof hooks !== 'function' && typeof hooks !== 'object') {\n throw new Error(\n `Drizzle-GraphQL Error: config.onWrite.${tableName} must be a function or an object with 'before' and/or 'after'.`,\n );\n }\n writeHooks.set(\n tableName,\n normalizeWriteHooks(hooks, getColumns(schema[tableName] as Table), `config.onWrite.${tableName}`),\n );\n }\n }\n }\n const onWrite: WriteHookFor | undefined = writeHooks.size\n ? (tableName: string) => writeHooks.get(tableName)\n : undefined;\n\n const policies: TablePolicies | undefined =\n scopeConfig || contextValuesConfig || softDeleteInfos.size || onWrite || defaultOrderBy\n ? {\n scope: scopeConfig ? (tableName: string) => scopeConfig[tableName] : undefined,\n contextValues: contextValuesConfig ? (tableName: string) => contextValuesConfig[tableName] : undefined,\n softDelete: softDeleteInfos.size ? (tableName: string) => softDeleteInfos.get(tableName) : undefined,\n onWrite,\n defaultOrderBy,\n }\n : undefined;\n\n // Exclusions are resolved against the real schema so a renamed table or column fails the\n // build instead of quietly un-hiding itself — the failure mode that matters when this config\n // is what keeps a secret out of the API.\n const exclude = config?.exclude;\n if (exclude) {\n const tableNames = new Set(tableKeys);\n const excludedTables = excludedTableNames;\n for (const tableName of excludedTables) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.exclude.tables names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n }\n if (excludedTables.size >= tableNames.size) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.exclude.tables excludes every table in the schema, leaving nothing to generate.',\n );\n }\n for (const [tableName, columnNames] of Object.entries(exclude.columns ?? {})) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.exclude.columns names table '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n // An excluded table has no columns left to hide; listing them too is redundant, not wrong.\n if (excludedTables.has(tableName)) {\n continue;\n }\n const columns = getColumns(schema[tableName] as Table);\n for (const columnName of columnNames) {\n const column = columns[columnName];\n if (!column) {\n throw new Error(\n `Drizzle-GraphQL Error: config.exclude.columns names '${tableName}.${columnName}', which is not a column of that table.`,\n );\n }\n // Hiding a column every insert must supply leaves the table readable but unwritable.\n // That is a reasonable thing to configure deliberately, so it warns rather than throws.\n if (column.notNull && !column.hasDefault && !column.defaultFn) {\n console.warn(\n `Drizzle-GraphQL Warning: excluded column '${tableName}.${columnName}' is NOT NULL with no default, so generated inserts for '${tableName}' can never succeed.`,\n );\n }\n }\n }\n }\n\n // Some operations are built out of others: an upsert writes through the insert and update\n // paths, a batch update reuses the update input, a grouped result reuses the aggregate\n // output types. The generator knows those implications; a table whose flags contradict them\n // is told at build time rather than leaving the consumer to notice a second write path (or a\n // missing operation) later. These warn rather than throw — the resulting schema is coherent,\n // it just isn't what the config appears to ask for.\n const featureConflicts = new Map<string, string[]>();\n const noteConflict = (message: string, tableName: string) => {\n const tables = featureConflicts.get(message);\n if (tables) {\n tables.push(tableName);\n } else {\n featureConflicts.set(message, [tableName]);\n }\n };\n for (const tableName of featureTables) {\n const tableFeatures = forTable(tableName);\n if (tableFeatures.upsert) {\n const missing = [!tableFeatures.insert ? 'insert' : undefined, !tableFeatures.update ? 'update' : undefined]\n .filter(Boolean)\n .join(' and ');\n if (missing) {\n noteConflict(\n `upsert is on while ${missing} is off, so the upsert mutations are a second write path past the operation you turned off`,\n tableName,\n );\n }\n }\n // Nested writes are not a conflict: a nested input whose write the target table turns off\n // is left out of the schema, and the build notes which (see `gateNestedWritePlans`).\n // Only flagged when the caller actually asked for the dependent feature: both default to\n // on, so turning off the operation they build on is the normal way to remove them.\n if (config?.features?.updateMany !== undefined && tableFeatures.updateMany && !tableFeatures.update) {\n noteConflict('updateMany is on while update is off, so no batch update is generated', tableName);\n }\n if (config?.features?.groupBy !== undefined && tableFeatures.groupBy && !tableFeatures.aggregates) {\n noteConflict('groupBy is on while aggregates is off, so no grouped query is generated', tableName);\n }\n // The count mutations mirror the plural write they count, so they need at least one of the\n // two to be generated at all.\n if (tableFeatures.countMutations && !tableFeatures.update && !tableFeatures.delete) {\n noteConflict(\n 'countMutations is on while update and delete are both off, so no count mutation is generated',\n tableName,\n );\n }\n }\n for (const [message, tables] of featureConflicts) {\n const listed =\n tables.length > 5 ? `${tables.slice(0, 5).join(', ')} and ${tables.length - 5} more` : tables.join(', ');\n console.warn(`Drizzle-GraphQL Warning: config.features — ${message} (${listed}).`);\n }\n\n // Normalize eagerLoadRelations (boolean | predicate | undefined) into a predicate.\n const eagerOpt = config?.eagerLoadRelations;\n const shouldEagerLoad: (tableName: string, relationName: string) => boolean =\n eagerOpt === undefined || eagerOpt === true ? () => true : eagerOpt === false ? () => false : eagerOpt;\n\n // When a typeNameMapper is provided, the mapper's singular/plural forms disambiguate the\n // list and single fields even if the suffixes are identical (e.g. both '').\n // Only enforce the suffix-collision check when no mapper is active.\n if (!typeNameMapper && suffixes.list === suffixes.single) {\n throw new Error(\n 'Drizzle-GraphQL Error: List and single query suffixes cannot be the same. This would create conflicting GraphQL field names.',\n );\n }\n\n if (typeof config?.relationsDepthLimit === 'number') {\n if (config.relationsDepthLimit < 0) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.relationsDepthLimit is supposed to be nonnegative integer or undefined!',\n );\n }\n if (config.relationsDepthLimit !== ~~config.relationsDepthLimit) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.relationsDepthLimit is supposed to be nonnegative integer or undefined!',\n );\n }\n }\n\n const generatorOptions: SchemaGeneratorOptions = {\n relationsDepthLimit: config?.relationsDepthLimit,\n prefixes,\n suffixes,\n conflictDoNothing: config?.conflictDoNothing ?? false,\n typeNameMapper,\n typeName,\n shouldEagerLoad,\n features: config?.features ?? {},\n complexity,\n scalars: config?.scalars,\n mapColumnType: config?.mapColumnType,\n enumNameMapper: config?.enumNameMapper,\n enumValueNameMapper: config?.enumValueNameMapper,\n transactions,\n limits,\n policies,\n exclude,\n docs: {\n describeColumn: config?.describeColumn,\n describeTable: config?.describeTable,\n describeRelation: config?.describeRelation,\n deprecateColumn: config?.deprecateColumn,\n },\n };\n\n return generatorOptions;\n};\n","import {\n and,\n avg,\n type Column,\n count,\n countDistinct,\n eq,\n extractExtendedColumnType,\n getColumns,\n gt,\n gte,\n inArray,\n lt,\n lte,\n max,\n min,\n ne,\n sum,\n type Table,\n} from 'drizzle-orm';\nimport {\n type GraphQLEnumType,\n GraphQLFloat,\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport { getOrCreateLoader, getOrCreateRequestValue } from '../batch-loader/index.ts';\nimport { capitalize } from '../case-ops/index.ts';\nimport { remapToGraphQLCore } from '../data-mappers/index.ts';\nimport type { ResolveTree } from '../parse-resolve-info.ts';\nimport { parseResolveInfo } from '../parse-resolve-info.ts';\nimport { drizzleColumnToGraphQLType } from '../type-converter/index.ts';\nimport type { ConvertedColumn } from '../type-converter/types.ts';\nimport {\n columnDocs,\n type DeletedMode,\n type DrizzleErrorContext,\n deletedArg,\n drizzleError,\n extractFilters,\n extractRelationJoinColumns,\n type GeneratedTypeInfo,\n generateColumnEnum,\n type RelationAggregateFactory,\n type RelationFilterBase,\n relationDeletedDefault,\n relationFilterCtx,\n resolveExecutor,\n resolveScope,\n resolveTypeName,\n sharedType,\n type TablePolicies,\n type TypeCacheCtx,\n type TypeNameMapper,\n type TypeNameResolver,\n toGraphQLError,\n visibleColumns,\n warnUnresolvedJoin,\n withErrorContext,\n withScope,\n} from './common.ts';\nimport type { CreatedResolver, Filters } from './types.ts';\n\n/** Operations that aggregate over a set of column values. `count` is handled separately (whole rows). */\nconst AGGREGATE_OPS = ['avg', 'sum', 'min', 'max', 'countNonNull', 'countDistinct'] as const;\ntype AggregateOp = (typeof AGGREGATE_OPS)[number];\n\n/** Ops whose result is a row count: never null, and returned as `Int!` rather than the column's type. */\nconst COUNT_OPS = new Set<AggregateOp>(['countNonNull', 'countDistinct']);\n\nconst OP_FNS: Record<AggregateOp, (col: Column) => any> = {\n avg,\n sum,\n min,\n max,\n countNonNull: count,\n countDistinct,\n};\n\n/** Separator for flat select aliases (`avg__price`) — reassembled into nested output by the resolver. */\nconst SEP = '__';\n\ninterface AggregateColumnSets {\n /** Columns avg/sum apply to: plain Int/Float scalars. */\n numeric: Record<string, Column>;\n /** Columns min/max apply to: anything with a total ordering the DB supports (numbers, strings, dates, enums). */\n orderable: Record<string, { column: Column; converted: ConvertedColumn }>;\n /** Every column — `count(col)` is valid whatever the type. */\n all: Record<string, Column>;\n}\n\n/**\n * Classifies a table's columns for aggregation. avg/sum only make sense on numeric scalars;\n * min/max work on any orderable scalar (numbers, strings, bigints, dates, enums). Booleans,\n * arrays (including array-typed number columns), JSON, buffers, and object-shaped columns\n * (e.g. geometry) are excluded entirely.\n */\n/**\n * Cache for {@link classifyAggregateColumns}. Keyed on the table object, then on the name it\n * was classified under — the name only reaches `drizzleColumnToGraphQLType` for enum naming,\n * but a table registered under two names would name its enums differently, so it is part of\n * the key rather than assumed irrelevant.\n *\n * The entries hold this build's GraphQL types and this build's column exclusions, so the\n * cache lives exactly as long as a build: {@link resetAggregateColumnCache} runs at the start\n * of every one, alongside the other per-build registries. Kept across builds it would hand a\n * second build the first build's enum instances, which is a schema with two types of one name.\n */\nlet aggregateColumnSetsCache = new WeakMap<Table, Map<string, AggregateColumnSets>>();\n\n/** Drops the classifications cached for the previous build. Called once per `generateSchemaData`. */\nexport const resetAggregateColumnCache = (): void => {\n aggregateColumnSetsCache = new WeakMap();\n};\n\nconst classifyAggregateColumns = (table: Table, tableName: string): AggregateColumnSets => {\n // Called from every aggregate/group-by generator for the same table — five times per table\n // at build time, plus twice per to-many relation — and each call re-converts every column.\n let byName = aggregateColumnSetsCache.get(table);\n if (!byName) {\n byName = new Map();\n aggregateColumnSetsCache.set(table, byName);\n }\n const cached = byName.get(tableName);\n if (cached) {\n return cached;\n }\n\n const numeric: AggregateColumnSets['numeric'] = {};\n const orderable: AggregateColumnSets['orderable'] = {};\n const all: AggregateColumnSets['all'] = {};\n\n for (const [columnName, column] of Object.entries(visibleColumns(table))) {\n all[columnName] = column;\n const converted = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, false);\n const gqlType = converted.type;\n\n // Anything that isn't a plain scalar in the generated schema (arrays, geometry objects)\n // has no meaningful min/max. This also catches array-typed number columns, which keep\n // their scalar drizzle dataType but convert to a GraphQL list.\n if (gqlType instanceof GraphQLList || gqlType instanceof GraphQLObjectType) {\n continue;\n }\n\n // Classify on the drizzle data type rather than the GraphQL one: date columns convert to\n // different GraphQL scalars per dialect, but are orderable everywhere.\n const { type: dataType, constraint } = extractExtendedColumnType(column);\n if (dataType === 'boolean' || dataType === 'array' || dataType === 'custom') {\n continue;\n }\n if (dataType === 'object' && constraint !== 'date') {\n continue;\n }\n\n orderable[columnName] = { column, converted };\n if (dataType === 'number') {\n numeric[columnName] = column;\n }\n }\n\n const sets = { numeric, orderable, all };\n byName.set(tableName, sets);\n\n return sets;\n};\n\n/**\n * Builds the `${typeName}Aggregate` output type for a table:\n * - `count: Int!` — number of matching rows\n * - `avg` / `sum` — per numeric column, always nullable Float (SQL returns NULL on empty sets,\n * and avg/sum of integers overflow Int / produce decimals)\n * - `min` / `max` — per orderable column, the column's own (nullable) scalar type\n * - `countNonNull` — per column, `Int!`: how many matching rows have a non-null value there\n * - `countDistinct` — per orderable column, `Int!`: how many distinct non-null values there are\n * Each wrapper is omitted when no column qualifies for it.\n */\nexport const generateAggregateTypes = (\n table: Table,\n tableName: string,\n typeName: string,\n cacheCtx?: TypeCacheCtx,\n): GraphQLObjectType => {\n const cached = cacheCtx?.aggregateTypeCache.get(tableName);\n if (cached) {\n return cached;\n }\n\n const { numeric, orderable, all } = classifyAggregateColumns(table, tableName);\n const nameOf = (op: string) =>\n cacheCtx?.typeName({\n kind: 'aggregate',\n defaultName: `${typeName}${capitalize(op)}Aggregate`,\n table: tableName,\n operation: op,\n }) ?? `${typeName}${capitalize(op)}Aggregate`;\n\n const fields: Record<string, { type: any }> = {\n count: { type: new GraphQLNonNull(GraphQLInt) },\n };\n\n if (Object.keys(numeric).length) {\n for (const op of ['avg', 'sum'] as const) {\n fields[op] = {\n type: new GraphQLObjectType({\n name: nameOf(op),\n fields: Object.fromEntries(Object.keys(numeric).map((columnName) => [columnName, { type: GraphQLFloat }])),\n }),\n };\n }\n }\n\n if (Object.keys(orderable).length) {\n for (const op of ['min', 'max'] as const) {\n fields[op] = {\n type: new GraphQLObjectType({\n name: nameOf(op),\n fields: Object.fromEntries(\n Object.entries(orderable).map(([columnName, { column, converted }]) => [\n columnName,\n { type: converted.type, ...columnDocs(cacheCtx?.docs ?? {}, column, tableName, columnName) },\n ]),\n ),\n }),\n };\n }\n }\n\n // `count(col)` works on any column type; `count(distinct col)` needs an equality operator,\n // which is the same requirement min/max have, so it reuses the orderable set.\n const countSets: Record<string, Record<string, unknown>> = { countNonNull: all, countDistinct: orderable };\n for (const [op, columns] of Object.entries(countSets)) {\n const columnNames = Object.keys(columns);\n if (!columnNames.length) {\n continue;\n }\n fields[op] = {\n type: new GraphQLObjectType({\n name: nameOf(op),\n fields: Object.fromEntries(\n columnNames.map((columnName) => [columnName, { type: new GraphQLNonNull(GraphQLInt) }]),\n ),\n }),\n };\n }\n\n const aggregateType = new GraphQLObjectType({\n name:\n cacheCtx?.typeName({ kind: 'aggregate', defaultName: `${typeName}Aggregate`, table: tableName }) ??\n `${typeName}Aggregate`,\n fields,\n });\n\n cacheCtx?.aggregateTypeCache.set(tableName, aggregateType);\n\n return aggregateType;\n};\n\n/** Parses a driver-level date/time string (`2024-04-02 06:44:41.785`, `2024-04-02`) as UTC. */\nconst parseDriverDateTime = (raw: string): Date => {\n let v = raw.includes(' ') ? raw.replace(' ', 'T') : raw;\n if (!v.includes('T')) {\n v = `${v}T00:00:00`;\n }\n if (!/(?:[Zz]|[+-]\\d{2}(?::?\\d{2})?)$/.test(v)) {\n v = `${v}Z`;\n }\n const parsed = new Date(v);\n return Number.isNaN(parsed.getTime()) ? new Date(raw) : parsed;\n};\n\n/** What the client asked for, plus the drizzle select map that computes it. */\ninterface AggregateRequest {\n count: boolean;\n ops: Record<AggregateOp, string[]>;\n selection: Record<string, any>;\n}\n\n/** Everything about a table that aggregating over it needs, resolved once at build time. */\ninterface AggregateTarget {\n tableName: string;\n typeName: string;\n /** The name the `${Table}Aggregate` object type actually carries, which keys the resolve tree. */\n aggregateTypeName: string;\n /** The same for each per-op sub-type, e.g. `${Table}AvgAggregate`. */\n opTypeName: (op: AggregateOp) => string;\n columns: Record<string, Column>;\n /** Columns whose GraphQL output is DateTime — their min/max may need string→Date coercion. */\n dateTimeColumns: Set<string>;\n}\n\nconst aggregateTarget = (\n table: Table,\n tableName: string,\n typeName: string,\n resolveName?: TypeNameResolver,\n): AggregateTarget => {\n const { orderable } = classifyAggregateColumns(table, tableName);\n // Named exactly the way `generateAggregateTypes` names them, so the resolver reads the\n // selection tree under the key the schema actually published.\n return {\n tableName,\n typeName,\n aggregateTypeName:\n resolveName?.({ kind: 'aggregate', defaultName: `${typeName}Aggregate`, table: tableName }) ??\n `${typeName}Aggregate`,\n opTypeName: (op) =>\n resolveName?.({\n kind: 'aggregate',\n defaultName: `${typeName}${capitalize(op)}Aggregate`,\n table: tableName,\n operation: op,\n }) ?? `${typeName}${capitalize(op)}Aggregate`,\n columns: getColumns(table),\n dateTimeColumns: new Set(\n Object.entries(orderable)\n .filter(([, { converted }]) => converted.typeLabel === 'DateTime')\n .map(([columnName]) => columnName),\n ),\n };\n};\n\n/**\n * Reads the requested count/avg/sum/min/max selections off the resolve tree and turns them\n * into one drizzle select expression per (op, column) pair. An empty `selection` means the\n * client asked for nothing runnable (`__typename` only, or empty sub-selections).\n */\nconst parseAggregateRequest = (\n info: any,\n target: AggregateTarget,\n rootTypeName = target.aggregateTypeName,\n): AggregateRequest => {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const selectionTree = parsedInfo.fieldsByTypeName[rootTypeName] ?? {};\n\n const request: AggregateRequest = {\n count: false,\n ops: { avg: [], sum: [], min: [], max: [], countNonNull: [], countDistinct: [] },\n selection: {},\n };\n\n // Keys are aliases; `field.name` is the real field. Duplicate selections of the same\n // field under different aliases collapse into one SQL expression — graphql-js resolves\n // every alias from the same result property.\n for (const field of Object.values(selectionTree) as ResolveTree[]) {\n if (field.name === 'count') {\n request.count = true;\n request.selection['count'] = count();\n continue;\n }\n\n if (!AGGREGATE_OPS.includes(field.name as AggregateOp)) {\n continue;\n }\n const op = field.name as AggregateOp;\n const subTree = field.fieldsByTypeName[target.opTypeName(op)];\n if (!subTree) {\n continue;\n }\n\n for (const subField of Object.values(subTree) as ResolveTree[]) {\n const columnName = subField.name;\n const column = target.columns[columnName];\n if (!column || request.ops[op].includes(columnName)) {\n continue;\n }\n request.ops[op].push(columnName);\n request.selection[`${op}${SEP}${columnName}`] = OP_FNS[op](column);\n }\n }\n\n return request;\n};\n\n/** Reassembles a flat aggregate row (`avg__price`) into the nested GraphQL shape. */\nconst assembleAggregateRow = (row: Record<string, any>, request: AggregateRequest, target: AggregateTarget) => {\n const result: Record<string, any> = {};\n\n if (request.count) {\n // drizzle's count() maps to number already; guard for drivers returning strings.\n result['count'] = row['count'] == null ? 0 : Number(row['count']);\n }\n\n for (const op of AGGREGATE_OPS) {\n if (!request.ops[op].length) {\n continue;\n }\n const opResult: Record<string, any> = {};\n for (const columnName of request.ops[op]) {\n const value = row[`${op}${SEP}${columnName}`];\n if (COUNT_OPS.has(op)) {\n // A count is never null: an empty set counts to 0, and a missing group means no rows.\n opResult[columnName] = value == null ? 0 : Number(value);\n } else if (value == null) {\n opResult[columnName] = null;\n } else if (op === 'avg' || op === 'sum') {\n // Drivers return numeric/decimal aggregates as strings — coerce to Float.\n opResult[columnName] = Number(value);\n } else {\n // min/max keep the column's own type — drizzle already ran the column's decoder over\n // the value (`min`/`max` are `mapWith(column)`), so all that's left is coercing a\n // leftover raw date string (PG decodes timestamps in driver-level codecs, which raw\n // select expressions bypass) and remapping for GraphQL output.\n // Present by construction: a name only reaches `request.ops` after the same lookup\n // succeeded in `buildAggregateRequest`.\n const column = target.columns[columnName]!;\n const decoded =\n typeof value === 'string' && target.dateTimeColumns.has(columnName) ? parseDriverDateTime(value) : value;\n opResult[columnName] = remapToGraphQLCore(columnName, decoded, target.tableName, column);\n }\n }\n result[op] = opResult;\n }\n\n return result;\n};\n\n/**\n * Creates the resolver for a table's aggregate query field. Reads the requested\n * count/avg/sum/min/max selections from the resolve tree, runs them all as a single\n * `SELECT` with one aggregate expression per requested (op, column) pair, and\n * reassembles the flat row into the nested GraphQL shape.\n *\n * Shared by all three dialects — it only relies on `db.select().from().where()`.\n */\nexport const generateAggregate = (\n db: any,\n tableName: string,\n table: Table,\n typeName: string,\n fieldName: string,\n filterArgs: GraphQLInputObjectType,\n filterCtx?: RelationFilterBase,\n policies?: TablePolicies,\n resolveName?: TypeNameResolver,\n): CreatedResolver => {\n const target = aggregateTarget(table, tableName, typeName, resolveName);\n const errorCtx: DrizzleErrorContext = { table: tableName, operation: 'aggregate', field: fieldName };\n\n const queryArgs = {\n where: { type: filterArgs },\n ...deletedArg(policies?.softDelete, tableName, resolveName),\n };\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table>; deleted?: DeletedMode }, context, info) => {\n try {\n const request = parseAggregateRequest(info, target);\n if (!Object.keys(request.selection).length) {\n return {};\n }\n\n let query = resolveExecutor(db, context).select(request.selection).from(table);\n const where = withScope(\n resolveScope(policies, context, filterCtx),\n tableName,\n table,\n args.where\n ? extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n args.deleted,\n );\n if (where) {\n query = query.where(where);\n }\n const rows = await query;\n\n return assembleAggregateRow(rows[0] ?? {}, request, target);\n } catch (e) {\n throw withErrorContext(toGraphQLError(e), errorCtx);\n }\n },\n args: queryArgs,\n };\n};\n\n/** Alias the grouping key is selected under. Prefixed so it can't collide with `${op}__${column}`. */\nconst GROUP_KEY = '__dgql_group_key';\n\n/**\n * Builds the `${relationName}Aggregate` field that hangs off a parent type for each to-many\n * relation — `user { postsAggregate { count } }`.\n *\n * Resolution is batched the same way relation fields are: every parent row in the current tick\n * that asked for the same relation with the same arguments is served by one\n * `SELECT fk, <aggregates> ... WHERE fk IN (...) GROUP BY fk`, so a list of N parents costs one\n * extra query rather than N. Parents with no matching related rows get `count: 0` and `null`\n * for every other aggregate.\n */\nexport const createRelationAggregateFactory = (\n db: any,\n tables: Record<string, Table>,\n cacheCtx: TypeCacheCtx,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n policies?: TablePolicies,\n): RelationAggregateFactory => {\n // The factory can be asked for the same relation more than once in a build; warn once.\n const warned = new Set<string>();\n return ({ tableName, relationName, relEntry }) => {\n const parentTable = tables[tableName];\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n\n if (!parentTable || !targetTable) {\n return undefined;\n }\n\n const joinCols = extractRelationJoinColumns(relEntry, parentTable, targetTable);\n if (!joinCols) {\n const key = `${tableName}.${relationName}`;\n if (!warned.has(key)) {\n warned.add(key);\n warnUnresolvedJoin(relEntry, tableName, relationName, `its '${relationName}Aggregate' field`);\n }\n return undefined;\n }\n const { localColPropName, foreignCol } = joinCols;\n // An aggregate over a relation counts the rows the relation itself returns, so it takes\n // the same soft-delete default — a `scope: 'root'` target is not hidden here either.\n const defaultDeleted = relationDeletedDefault(policies?.softDelete, targetTableName, false);\n\n const targetTypeName = resolveTypeName(targetTableName, typeNameMapper);\n const type = generateAggregateTypes(targetTable, targetTableName, targetTypeName, cacheCtx);\n const target = aggregateTarget(targetTable, targetTableName, targetTypeName, cacheCtx.typeName);\n const errorCtx: DrizzleErrorContext = {\n table: targetTableName,\n operation: 'relationAggregate',\n relation: relationName,\n };\n\n const resolve = async (\n parent: any,\n args: { where?: Filters<Table>; deleted?: DeletedMode },\n context: any,\n info: any,\n ) => {\n try {\n // This resolver runs once per parent row, and the resolve-info walk and the loader key\n // depend on the field alone, not on the row — so they are derived once per field per\n // request and reused by every sibling the batch serves.\n const { request, loaderKey } = getOrCreateRequestValue(\n context,\n info?.fieldNodes?.[0],\n `aggregate:${tableName}::${relationName}`,\n () => {\n const request = parseAggregateRequest(info, target);\n // Siblings only share a batch when they'd run the same query: same filters, same aggregates.\n const argsKey = JSON.stringify({\n where: args?.where ?? null,\n deleted: args?.deleted ?? defaultDeleted ?? null,\n selection: Object.keys(request.selection).sort(),\n });\n return { request, loaderKey: `${tableName}::${relationName}::aggregate::${argsKey}` };\n },\n );\n if (!Object.keys(request.selection).length) {\n return {};\n }\n\n const localValue = parent[localColPropName];\n // No key to correlate on — the relation is empty by definition.\n if (localValue == null) {\n return assembleAggregateRow({}, request, target);\n }\n\n const whereArg = args?.where;\n const deleted = args?.deleted;\n\n const loader = getOrCreateLoader(context, loaderKey, async (parentIds: readonly any[]) => {\n // Loaders are cached per context, so the whole batch shares this request's executor.\n const executor = resolveExecutor(db, context);\n const uniqueIds = [...new Set(parentIds)];\n // An aggregate over a relation counts the same rows the relation itself returns,\n // so it is narrowed by the target table's scope too.\n const whereCondition = withScope(\n resolveScope(policies, context, filterCtx),\n targetTableName,\n targetTable,\n and(\n inArray(foreignCol, uniqueIds),\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n ),\n deleted ?? defaultDeleted,\n );\n\n const rows: any[] = await executor\n .select({ [GROUP_KEY]: foreignCol, ...request.selection })\n .from(targetTable)\n .where(whereCondition)\n .groupBy(foreignCol);\n\n const byKey = new Map(rows.map((row) => [row[GROUP_KEY], row]));\n\n // A parent with no matching rows produces no group — hand back an empty row so it\n // assembles to count 0 / null aggregates rather than dropping the field.\n return parentIds.map((id) => byKey.get(id) ?? {});\n });\n\n return assembleAggregateRow(await loader.load(localValue), request, target);\n } catch (e) {\n throw withErrorContext(toGraphQLError(e), errorCtx);\n }\n };\n\n return { type, resolve };\n };\n};\n\n// ── group by ──────────────────────────────────────────────────────────────────\n\n/** Alias prefix for grouped columns, kept clear of the `${op}__${column}` aggregate aliases. */\nconst GROUP_COL = `group${SEP}`;\n\n/** Comparison operators a `having` clause can apply to an aggregated value. */\nconst HAVING_OPS = { eq, ne, gt, gte, lt, lte } as const;\n\n/**\n * Columns a query can group on. Grouping needs an equality operator, which is the same\n * requirement min/max has, plus booleans — orderable excludes them because a min/max over\n * true/false says nothing, but `GROUP BY isConfirmed` is perfectly ordinary.\n */\nconst groupableColumns = (\n table: Table,\n tableName: string,\n): Record<string, { column: Column; converted: ConvertedColumn }> => {\n const { orderable } = classifyAggregateColumns(table, tableName);\n const groupable: Record<string, { column: Column; converted: ConvertedColumn }> = { ...orderable };\n\n for (const [columnName, column] of Object.entries(visibleColumns(table))) {\n if (groupable[columnName]) {\n continue;\n }\n const { type: dataType } = extractExtendedColumnType(column);\n if (dataType !== 'boolean') {\n continue;\n }\n groupable[columnName] = {\n column,\n converted: drizzleColumnToGraphQLType(column, columnName, tableName, true, false, false),\n };\n }\n\n return groupable;\n};\n\n/** The `${typeName}GroupByColumn` enum listing what a group-by query can group on. */\nexport const generateGroupByEnum = (\n table: Table,\n tableName: string,\n typeName: string,\n cacheCtx?: TypeCacheCtx,\n): GraphQLEnumType | undefined => {\n const groupable = groupableColumns(table, tableName);\n const defaultName = `${typeName}GroupByColumn`;\n\n return generateColumnEnum(\n table,\n cacheCtx?.typeName({ kind: 'columnEnum', defaultName, table: tableName, operation: 'groupBy' }) ?? defaultName,\n `Columns of ${typeName} that a query can group by`,\n (_column, columnName) => Boolean(groupable[columnName]),\n );\n};\n\n/** Shared by every `having` clause, so it is created once per name rather than per table. */\nexport const aggregateNumberFilterType = (typeName: TypeNameResolver): GraphQLInputObjectType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'AggregateNumberFilter' },\n (name) =>\n new GraphQLInputObjectType({\n name,\n description: 'Compares an aggregated value. Several operators in one filter are ANDed together.',\n fields: Object.fromEntries(Object.keys(HAVING_OPS).map((op) => [op, { type: GraphQLFloat }])),\n }),\n );\n\n/**\n * The `${typeName}Having` input: one entry per aggregate the group-by query can filter on.\n * Several entries are ANDed together, as are several operators within one entry.\n *\n * `min`/`max` are limited to numeric columns here even though the output type computes them\n * for every orderable column — the comparison is numeric, so a min over a text column has\n * nothing to compare against.\n */\nexport const generateHavingInput = (\n table: Table,\n tableName: string,\n typeName: string,\n cacheCtx?: TypeCacheCtx,\n): GraphQLInputObjectType => {\n const { numeric, orderable, all } = classifyAggregateColumns(table, tableName);\n const resolveName = cacheCtx?.typeName ?? ((info: GeneratedTypeInfo) => info.defaultName);\n const numberFilter = aggregateNumberFilterType(resolveName);\n\n const fields: Record<string, { type: any; description?: string }> = {\n count: { type: numberFilter, description: 'Filters groups by how many rows they contain' },\n };\n\n const opColumns: Record<string, Record<string, unknown>> = {\n avg: numeric,\n sum: numeric,\n min: numeric,\n max: numeric,\n countNonNull: all,\n countDistinct: orderable,\n };\n\n for (const [op, columns] of Object.entries(opColumns)) {\n const columnNames = Object.keys(columns);\n if (!columnNames.length) {\n continue;\n }\n fields[op] = {\n type: new GraphQLInputObjectType({\n name: resolveName({\n kind: 'having',\n defaultName: `${typeName}${capitalize(op)}Having`,\n table: tableName,\n operation: op,\n }),\n fields: Object.fromEntries(columnNames.map((columnName) => [columnName, { type: numberFilter }])),\n }),\n };\n }\n\n return new GraphQLInputObjectType({\n name: resolveName({ kind: 'having', defaultName: `${typeName}Having`, table: tableName }),\n description: `Filters ${typeName} groups by their aggregated values`,\n fields,\n });\n};\n\n/**\n * The `${typeName}GroupBy` output type: the grouped columns under `group`, alongside the same\n * aggregate fields the `${typeName}Aggregate` type carries — the wrapper types are the very\n * same instances, so the schema holds one `${typeName}AvgAggregate` however it is reached.\n *\n * The keys are nested rather than spread across the top level so a column called `count`,\n * `avg` or `min` cannot collide with the aggregate it sits next to.\n */\nexport const generateGroupByType = (\n table: Table,\n tableName: string,\n typeName: string,\n cacheCtx?: TypeCacheCtx,\n): GraphQLObjectType | undefined => {\n const groupable = groupableColumns(table, tableName);\n if (!Object.keys(groupable).length) {\n return undefined;\n }\n\n const keysType = new GraphQLObjectType({\n name:\n cacheCtx?.typeName({ kind: 'groupKeys', defaultName: `${typeName}GroupKeys`, table: tableName }) ??\n `${typeName}GroupKeys`,\n description: `The grouped column values of one ${typeName} group. A column the query did not group by is null.`,\n fields: Object.fromEntries(\n Object.entries(groupable).map(([columnName, { column, converted }]) => [\n columnName,\n { type: converted.type, ...columnDocs(cacheCtx?.docs ?? {}, column, tableName, columnName) },\n ]),\n ),\n });\n\n const aggregateType = generateAggregateTypes(table, tableName, typeName, cacheCtx);\n const aggregateFields = Object.fromEntries(\n Object.values(aggregateType.getFields()).map((field) => [\n field.name,\n { type: field.type, description: field.description ?? undefined },\n ]),\n );\n\n return new GraphQLObjectType({\n name:\n cacheCtx?.typeName({ kind: 'groupBy', defaultName: `${typeName}GroupBy`, table: tableName }) ??\n `${typeName}GroupBy`,\n fields: { group: { type: new GraphQLNonNull(keysType) }, ...aggregateFields },\n });\n};\n\n/** Turns one `${typeName}Having` entry into SQL conditions over the matching aggregate expression. */\nconst havingComparisons = (expression: any, filter: Record<string, any>): any[] =>\n Object.entries(filter)\n .filter(([op, value]) => value != null && op in HAVING_OPS)\n .map(([op, value]) => HAVING_OPS[op as keyof typeof HAVING_OPS](expression, value));\n\nconst buildHavingCondition = (having: Record<string, any> | undefined, columns: Record<string, Column>) => {\n if (!having) {\n return undefined;\n }\n\n const conditions: any[] = [];\n\n for (const [key, value] of Object.entries(having)) {\n if (value == null) {\n continue;\n }\n if (key === 'count') {\n conditions.push(...havingComparisons(count(), value));\n continue;\n }\n if (!AGGREGATE_OPS.includes(key as AggregateOp)) {\n continue;\n }\n for (const [columnName, filter] of Object.entries(value as Record<string, any>)) {\n const column = columns[columnName];\n if (!column || filter == null) {\n continue;\n }\n conditions.push(...havingComparisons(OP_FNS[key as AggregateOp](column), filter));\n }\n }\n\n return conditions.length ? and(...conditions) : undefined;\n};\n\n/**\n * Creates the resolver for a table's `<plural>GroupBy` query: the same aggregates the\n * `<plural>Aggregate` query computes, but one row per distinct combination of the requested\n * columns, optionally filtered on the aggregated values with `having`.\n *\n * Shared by all three dialects — `SELECT <keys>, <aggregates> FROM t WHERE … GROUP BY <keys>\n * HAVING …` is the same everywhere.\n */\nexport const generateGroupBy = (\n db: any,\n tableName: string,\n table: Table,\n typeName: string,\n fieldName: string,\n filterArgs: GraphQLInputObjectType,\n groupByEnum: GraphQLEnumType,\n havingInput: GraphQLInputObjectType,\n filterCtx?: RelationFilterBase,\n policies?: TablePolicies,\n resolveName?: TypeNameResolver,\n): CreatedResolver => {\n const target = aggregateTarget(table, tableName, typeName, resolveName);\n const groupable = groupableColumns(table, tableName);\n const columns = getColumns(table);\n const rootTypeName =\n resolveName?.({ kind: 'groupBy', defaultName: `${typeName}GroupBy`, table: tableName }) ?? `${typeName}GroupBy`;\n const errorCtx: DrizzleErrorContext = { table: tableName, operation: 'groupBy', field: fieldName };\n\n const queryArgs = {\n groupBy: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByEnum))),\n description: 'Columns to group by. One result row per distinct combination of their values.',\n },\n where: { type: filterArgs, description: 'Filters the rows before they are grouped.' },\n having: { type: havingInput, description: 'Filters the groups after they are aggregated.' },\n ...deletedArg(policies?.softDelete, tableName, resolveName),\n };\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { groupBy?: string[]; where?: Filters<Table>; having?: Record<string, any>; deleted?: DeletedMode },\n context,\n info,\n ) => {\n try {\n const requestedKeys = [...new Set(args.groupBy ?? [])];\n if (!requestedKeys.length) {\n throw drizzleError('At least one column to group by is required!', {\n code: 'DRIZZLE_INVALID_GROUP_BY',\n });\n }\n\n const keyColumns = requestedKeys.map((columnName) => {\n const groupableColumn = groupable[columnName];\n if (!groupableColumn) {\n throw drizzleError(`Cannot group ${typeName} by ${columnName}!`, {\n code: 'DRIZZLE_INVALID_GROUP_BY',\n });\n }\n return [columnName, groupableColumn.column] as const;\n });\n\n const request = parseAggregateRequest(info, target, rootTypeName);\n const selection = {\n ...Object.fromEntries(keyColumns.map(([columnName, column]) => [`${GROUP_COL}${columnName}`, column])),\n ...request.selection,\n };\n\n let query = resolveExecutor(db, context).select(selection).from(table);\n const where = withScope(\n resolveScope(policies, context, filterCtx),\n tableName,\n table,\n args.where\n ? extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n args.deleted,\n );\n if (where) {\n query = query.where(where);\n }\n query = query.groupBy(...keyColumns.map(([, column]) => column));\n\n const havingCondition = buildHavingCondition(args.having, columns);\n if (havingCondition) {\n query = query.having(havingCondition);\n }\n\n const rows: any[] = await query;\n\n return rows.map((row) => {\n const group: Record<string, any> = {};\n for (const [columnName, column] of keyColumns) {\n const value = row[`${GROUP_COL}${columnName}`];\n const decoded =\n typeof value === 'string' && target.dateTimeColumns.has(columnName) ? parseDriverDateTime(value) : value;\n group[columnName] = value == null ? null : remapToGraphQLCore(columnName, decoded, tableName, column);\n }\n\n return { group, ...assembleAggregateRow(row, request, target) };\n });\n } catch (e) {\n throw withErrorContext(toGraphQLError(e), errorCtx);\n }\n },\n args: queryArgs,\n };\n};\n","// =============================================================================\n// Nested writes — `create` / `connect` / `disconnect` / `set` on the relation\n// fields of a table's create and update inputs.\n//\n// A nested write is always several statements (the parent row plus one per\n// relation operation), so every resolver that runs one opens a transaction —\n// a savepoint when the request already carries one. What a relation can offer\n// is decided here, at build time, from which side of the relation stores the\n// foreign key and whether that column is nullable, so the schema never advertises\n// an operation whose every call would be a database error.\n// =============================================================================\nimport { and, type Column, eq, getColumns, inArray, is, One, type Table } from 'drizzle-orm';\nimport { GraphQLBoolean, GraphQLInputObjectType, type GraphQLInputType, GraphQLList, GraphQLNonNull } from 'graphql';\nimport { capitalize } from '../case-ops/index.ts';\nimport { remapFromGraphQLSingleInput } from '../data-mappers/index.ts';\nimport { drizzleColumnToGraphQLType } from '../type-converter/index.ts';\nimport { drizzleError } from './common/errors.ts';\nimport {\n type NestedWriteOp,\n type ResolvedWriteHooks,\n runWriteHook,\n type WriteHookPayload,\n withHookColumns,\n} from './common/write-hooks.ts';\nimport {\n applyContextValues,\n type ContextValuesFor,\n extractFilters,\n type RelationFilterBase,\n relationFilterCtx,\n resolveScope,\n resolveTypeName,\n type ScopeResolver,\n type TablePolicies,\n type TypeCacheCtx,\n type TypeNameMapper,\n unwrapRelationColumn,\n visibleColumns,\n warnUnresolvedJoin,\n withScope,\n} from './common.ts';\nimport type { TableFeatures, TableNamedRelations } from './types.ts';\n\nconst ALL_OPS: readonly NestedWriteOp[] = ['create', 'connect', 'disconnect', 'set'];\n\n/**\n * How one relation can be written through, resolved once at build time.\n *\n * `fkSide` is the whole point: a relation is stored as a value in exactly one of the two\n * tables, and which one decides both what operations make sense and in what order the\n * statements have to run. When the child holds it (`Authors.posts` — `posts.author_id`),\n * the parent has to exist first and the children are attached afterwards. When the parent\n * holds it (`Posts.author` — `posts.author_id` again, seen from the other end), the target\n * row has to exist first so its key can go into the parent's own INSERT.\n */\nexport type NestedRelationPlan = {\n relationName: string;\n targetTableName: string;\n targetTable: Table;\n /** Property name of the join column on the table the input belongs to. */\n localColPropName: string;\n /** Property name of the join column on the relation's target table. */\n foreignColPropName: string;\n foreignCol: Column;\n localCol: Column;\n isOne: boolean;\n /** Which table stores the value that has to change for a row to be attached or detached. */\n fkSide: 'child' | 'parent';\n /** Whether the foreign key is nullable, and so whether a row can be detached at all. */\n canDetach: boolean;\n /** Set when the relation goes through a junction table, which is then what gets written. */\n through?: NestedThroughPlan;\n /**\n * The target's primary-key columns and the join column, keyed by property name — what a\n * nested statement on the target returns to that table's `onWrite` hook when it has one.\n */\n targetKeyColumns: Record<string, Column>;\n /**\n * The relation field's inputs the relation's shape allows (no `create` through a junction,\n * no `disconnect` / `set` on a NOT NULL key), narrowed by {@link gateNestedWritePlans} to\n * the ones whose write the table it lands on has turned on.\n */\n allowed: Set<NestedWriteOp>;\n};\n\n/**\n * The junction table of a `.through()` relation, and the two of its columns this relation\n * joins on. A many-to-many is attached and detached by inserting and deleting junction rows,\n * so neither the parent row nor the target row is written at all.\n */\nexport type NestedThroughPlan = {\n table: Table;\n /** The junction's Drizzle schema key — what its `features` and `onWrite` are keyed by. */\n tableName: string | undefined;\n /** Property name of the junction column holding the parent's key. */\n sourceColPropName: string;\n /** Property name of the junction column holding the target's key. */\n targetColPropName: string;\n sourceCol: Column;\n targetCol: Column;\n};\n\n/** Every writable relation of every table: table name → relation name → plan. */\nexport type NestedWritePlans = Record<string, Record<string, NestedRelationPlan>>;\n\n/** The nested operations of one mutation input, keyed by relation name. */\nexport type NestedOps = Record<string, Record<string, any>>;\n\n/**\n * Whether a column can be left out of an INSERT — either the database fills it in or it\n * accepts NULL.\n */\nconst isOptionalOnInsert = (column: Column): boolean =>\n !column.notNull || !!column.hasDefault || !!(column as any).defaultFn;\n\n/** The property name a column is stored under on its table, matched by identity. */\nconst propNameOf = (table: Table, column: Column | undefined): string | undefined => {\n if (!column) {\n return undefined;\n }\n for (const [propName, candidate] of Object.entries(getColumns(table))) {\n if (candidate === column) {\n return propName;\n }\n }\n return undefined;\n};\n\n/**\n * A `.through()` relation's plan: the junction table plus the two columns it joins on.\n *\n * Nothing about the parent or the target row changes when a many-to-many link is made or\n * broken — only junction rows are inserted and deleted — so `canDetach` is unconditional\n * here, and there is no nullable-foreign-key question to ask.\n *\n * Left unplanned, and so absent from the inputs: a to-one `.through()`, whose \"exactly one\n * row\" guarantee lives in the junction's constraints rather than in the relation; a relation\n * joining on more than one column per side; and a junction carrying a further NOT NULL column\n * with no default, which no `connect` operand could supply a value for.\n *\n * `onUnresolved` is called when the relation's columns are of a supported shape but cannot be\n * matched to the three tables — a drizzle-orm mismatch rather than an unsupported relation.\n */\nconst buildThroughPlan = (\n relationName: string,\n relation: any,\n table: Table,\n targetTableName: string,\n targetTable: Table,\n tableNameOf: (table: Table) => string | undefined,\n onUnresolved: () => void,\n): NestedRelationPlan | undefined => {\n if (is(relation, One)) {\n return undefined;\n }\n\n const junction = relation.throughTable as Table | undefined;\n const sourceEntries = relation.through?.source;\n const targetEntries = relation.through?.target;\n if (!junction || sourceEntries?.length !== 1 || targetEntries?.length !== 1) {\n return undefined;\n }\n if (relation.sourceColumns?.length !== 1 || relation.targetColumns?.length !== 1) {\n return undefined;\n }\n\n // Drizzle normalizes the two ends before it stores them, so `source` is the parent's side\n // even on the relation declared from the other table. Each column is looked up on the table\n // it is supposed to belong to, which is also the check that the normalization held.\n const localCol = unwrapRelationColumn(relation.sourceColumns[0]);\n const foreignCol = unwrapRelationColumn(relation.targetColumns[0]);\n const localColPropName = propNameOf(table, localCol);\n const foreignColPropName = propNameOf(targetTable, foreignCol);\n const sourceColPropName = propNameOf(junction, unwrapRelationColumn(sourceEntries[0]));\n const targetColPropName = propNameOf(junction, unwrapRelationColumn(targetEntries[0]));\n if (\n !localCol ||\n !foreignCol ||\n !localColPropName ||\n !foreignColPropName ||\n !sourceColPropName ||\n !targetColPropName\n ) {\n onUnresolved();\n return undefined;\n }\n\n const junctionColumns = getColumns(junction);\n const sourceCol = junctionColumns[sourceColPropName] as Column;\n const targetCol = junctionColumns[targetColPropName] as Column;\n const unsuppliable = Object.entries(junctionColumns).some(\n ([propName, column]) =>\n propName !== sourceColPropName && propName !== targetColPropName && !isOptionalOnInsert(column as Column),\n );\n if (unsuppliable) {\n return undefined;\n }\n\n return {\n relationName,\n targetTableName,\n targetTable,\n localColPropName,\n foreignColPropName,\n foreignCol,\n localCol,\n isOne: false,\n // The link is written after the parent row exists, exactly like a child-side foreign key.\n fkSide: 'child',\n canDetach: true,\n through: {\n table: junction,\n tableName: tableNameOf(junction),\n sourceColPropName,\n targetColPropName,\n sourceCol,\n targetCol,\n },\n targetKeyColumns: { [foreignColPropName]: foreignCol },\n allowed: new Set(['connect', 'disconnect', 'set']),\n };\n};\n\n/**\n * Which relations of which tables can be written through.\n *\n * A `.through()` (many-to-many) relation is planned too, but as a junction-table write\n * rather than a foreign-key one — see {@link buildThroughPlan}.\n *\n * Skipped, and so absent from the generated inputs rather than failing at runtime:\n * relations whose join columns cannot be read off the drizzle relation; and relations where\n * neither join column is unique, which leaves no way to tell which side stores the key.\n */\nexport const buildNestedWritePlans = (\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n resolveUniqueSets: (table: Table) => string[][],\n resolvePrimaryKeys: (table: Table) => string[],\n extractJoinColumns: (\n relEntry: TableNamedRelations,\n parentTable: Table,\n targetTable: Table,\n ) => { localColPropName: string; foreignCol: Column; foreignColPropName: string } | undefined,\n /**\n * The schema key of any table in the Drizzle schema, excluded ones included — a junction\n * table is written without being a relation target, so it is looked up here.\n */\n tableNameOf: (table: Table) => string | undefined = () => undefined,\n): NestedWritePlans => {\n const uniqueCache = new Map<string, Set<string>>();\n // Only single-column unique keys matter here: a relation joins on one column, so a\n // composite key says nothing about whether that column identifies a row on its own.\n const singleColumnUniques = (tableName: string, table: Table): Set<string> => {\n let cached = uniqueCache.get(tableName);\n if (!cached) {\n cached = new Set(\n resolveUniqueSets(table)\n .filter((set) => set.length === 1)\n .map((set) => set[0]!),\n );\n uniqueCache.set(tableName, cached);\n }\n return cached;\n };\n\n const pkCache = new Map<string, string | undefined>();\n // Only a single-column primary key identifies a row by one join column, which is the only\n // shape a relation can be written through.\n const singleColumnPk = (tableName: string, table: Table): string | undefined => {\n if (!pkCache.has(tableName)) {\n const pk = resolvePrimaryKeys(table);\n pkCache.set(tableName, pk.length === 1 ? pk[0] : undefined);\n }\n return pkCache.get(tableName);\n };\n\n const plans: NestedWritePlans = {};\n\n for (const [tableName, relations] of Object.entries(relationMap)) {\n const table = tables[tableName];\n if (!table) {\n continue;\n }\n\n const tablePlans: Record<string, NestedRelationPlan> = {};\n\n for (const [relationName, relEntry] of Object.entries(relations)) {\n const relation = (relEntry as any).relation;\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n if (!targetTable) {\n continue;\n }\n\n const omitted = `the '${relationName}' field of its nested-write create and update inputs`;\n if ((relation as any).through) {\n const throughPlan = buildThroughPlan(\n relationName,\n relation,\n table,\n targetTableName,\n targetTable,\n tableNameOf,\n () => warnUnresolvedJoin(relEntry, tableName, relationName, omitted),\n );\n if (throughPlan) {\n tablePlans[relationName] = throughPlan;\n }\n continue;\n }\n\n const joinColumns = extractJoinColumns(relEntry, table, targetTable);\n if (!joinColumns) {\n warnUnresolvedJoin(relEntry, tableName, relationName, omitted);\n continue;\n }\n const { localColPropName, foreignCol, foreignColPropName } = joinColumns;\n const localCol = getColumns(table)[localColPropName] as Column | undefined;\n if (!localCol) {\n continue;\n }\n\n const isOne = is(relation, One);\n const localIsPk = singleColumnPk(tableName, table) === localColPropName;\n const foreignIsPk = singleColumnPk(targetTableName, targetTable) === foreignColPropName;\n const localIsUnique = singleColumnUniques(tableName, table).has(localColPropName);\n const foreignIsUnique = singleColumnUniques(targetTableName, targetTable).has(foreignColPropName);\n\n // Which of the two columns actually holds the reference. A to-many is always the\n // child's — one parent column cannot point at many rows. For a to-one, the side that\n // joins on its own primary key is the one being pointed *at*, so the reference lives on\n // the other side; a unique constraint is the fallback signal when neither is a key.\n // A relation whose join column identifies a row on neither side is left out entirely:\n // there would be no way to say which row an operation meant.\n let fkSide: 'child' | 'parent';\n if (!isOne) {\n fkSide = 'child';\n } else if (foreignIsPk && !localIsPk) {\n fkSide = 'parent';\n } else if (localIsPk) {\n fkSide = 'child';\n } else if (foreignIsUnique) {\n fkSide = 'parent';\n } else if (localIsUnique) {\n fkSide = 'child';\n } else {\n continue;\n }\n\n const fkColumn = fkSide === 'child' ? foreignCol : localCol;\n const targetColumns = getColumns(targetTable);\n const targetKeyColumns: Record<string, Column> = Object.fromEntries(\n resolvePrimaryKeys(targetTable)\n .filter((name) => targetColumns[name])\n .map((name) => [name, targetColumns[name] as Column]),\n );\n targetKeyColumns[foreignColPropName] = foreignCol;\n\n tablePlans[relationName] = {\n relationName,\n targetTableName,\n targetTable,\n localColPropName,\n foreignColPropName,\n foreignCol,\n localCol,\n isOne,\n fkSide,\n canDetach: !fkColumn.notNull,\n targetKeyColumns,\n // `set` replaces a to-many's whole set, and `disconnect` / `set` need a key that can\n // be nulled. Whether the input is the update one, and whether `connect` has a filter\n // to select with, is decided where the input types are built.\n allowed: new Set<NestedWriteOp>(\n !fkColumn.notNull ? (isOne ? ['create', 'connect', 'disconnect'] : ALL_OPS) : ['create', 'connect'],\n ),\n };\n }\n\n if (Object.keys(tablePlans).length) {\n plans[tableName] = tablePlans;\n }\n }\n\n return plans;\n};\n\n/** The writes one relation-field input performs, as `[table, operation]` pairs. */\ntype RequiredWrite = { tableName: string | undefined; feature: 'insert' | 'update' | 'delete' };\n\n/**\n * Which of the target's (or junction's) write features each input of a relation needs. A\n * parent-side `connect` / `disconnect` only rewrites the parent's own column, so it needs\n * nothing of the target; a child-side one moves the target's foreign key, which is an update\n * of the target. A to-one child-side `create` also detaches the row attached before it, when\n * the key is nullable.\n */\nconst requiredWrites = (plan: NestedRelationPlan, op: NestedWriteOp): RequiredWrite[] => {\n if (plan.through) {\n const junction = plan.through.tableName;\n if (op === 'connect') {\n return [{ tableName: junction, feature: 'insert' }];\n }\n if (op === 'disconnect') {\n return [{ tableName: junction, feature: 'delete' }];\n }\n if (op === 'set') {\n return [\n { tableName: junction, feature: 'delete' },\n { tableName: junction, feature: 'insert' },\n ];\n }\n return [];\n }\n const target = plan.targetTableName;\n if (op === 'create') {\n const detaches = plan.fkSide === 'child' && plan.isOne && plan.canDetach;\n return detaches\n ? [\n { tableName: target, feature: 'insert' },\n { tableName: target, feature: 'update' },\n ]\n : [{ tableName: target, feature: 'insert' }];\n }\n return plan.fkSide === 'child' ? [{ tableName: target, feature: 'update' }] : [];\n};\n\n/**\n * Narrows every plan's `allowed` inputs to the ones whose writes the table they land on\n * permits: its `features.insert` / `update` / `delete`, and for a junction table that it is\n * not excluded. A plan left with nothing is dropped, so its relation field is not generated.\n *\n * Returns one line per input taken out, for the build note.\n */\nexport const gateNestedWritePlans = (\n plans: NestedWritePlans,\n featureOf: (tableName: string) => TableFeatures,\n isExcluded: (tableName: string) => boolean,\n): string[] => {\n const omitted: string[] = [];\n for (const [tableName, tablePlans] of Object.entries(plans)) {\n for (const [relationName, plan] of Object.entries(tablePlans)) {\n for (const op of [...plan.allowed]) {\n const blocked = requiredWrites(plan, op).filter(\n ({ tableName: target, feature }) =>\n target !== undefined && (isExcluded(target) || !featureOf(target)[feature]),\n );\n if (blocked.length) {\n plan.allowed.delete(op);\n const reasons = blocked.map(({ tableName: target, feature }) =>\n isExcluded(target!) ? `${target} is excluded` : `${target}.${feature} is off`,\n );\n omitted.push(`${tableName}.${relationName}.${op} (${[...new Set(reasons)].join(', ')})`);\n }\n }\n if (!plan.allowed.size) {\n delete tablePlans[relationName];\n }\n }\n if (!Object.keys(tablePlans).length) {\n delete plans[tableName];\n }\n }\n return omitted;\n};\n\n// ── input types ──────────────────────────────────────────────────────────────\n\n/**\n * The extra input fields nested writes add to a table's create and update inputs, plus the\n * columns whose NOT NULL requirement the create input has to relax.\n */\nexport type NestedWriteTypes = {\n /** Relation fields for `Create<Table>Input`, empty when the table has no writable relation. */\n createFields: (\n tableName: string,\n typeName: string,\n ) => Record<string, { type: GraphQLInputType; description: string }>;\n /** Relation fields for `Update<Table>Input`. */\n updateFields: (\n tableName: string,\n typeName: string,\n ) => Record<string, { type: GraphQLInputType; description: string }>;\n /**\n * Columns a relation on the same input can fill in, which therefore cannot stay required:\n * `authorId` is NOT NULL, but `author: { create: … }` supplies it.\n */\n relaxedColumns: (tableName: string) => ReadonlySet<string>;\n};\n\nconst NO_COLUMNS: ReadonlySet<string> = new Set();\n\n/**\n * Builds the nested-write input types for a schema.\n *\n * Every field map is produced lazily, from inside the enclosing input type's own thunk: the\n * operand of `connect` is the target table's `Filters` input, which does not exist yet while\n * the first table's types are being generated.\n */\nexport const createNestedWriteTypes = (params: {\n plans: NestedWritePlans;\n cacheCtx: TypeCacheCtx;\n typeNameMapper: TypeNameMapper | undefined;\n}): NestedWriteTypes => {\n const { plans, cacheCtx, typeNameMapper } = params;\n const wrapperCache = new Map<string, GraphQLInputObjectType>();\n const payloadCache = new Map<string, GraphQLInputObjectType>();\n\n /**\n * `<Type><Relation>NestedCreatePayloadInput` — the row a nested `create` inserts. Built from\n * the target's columns rather than from its create input: the join column this relation\n * fills in is left out (setting it by hand could point the new row somewhere other than its\n * parent), and the nesting stops here, so the type carries no relation fields of its own.\n *\n * The name shares the wrapper's `<Type><Relation>Nested…` segment rather than reading\n * `Create<Type><Relation>Input`, which lands in the same namespace as a table's own create\n * input: `item.type` spells `CreateItemTypeInput`, and so does a sibling table named\n * `itemType`. Two types of that name is a schema that cannot be built at all, and\n * `nestedWrites` is a whole-schema flag, so one such pair made it unusable.\n */\n const payloadType = (tableName: string, typeName: string, plan: NestedRelationPlan): GraphQLInputObjectType => {\n const key = `${tableName}.${plan.relationName}`;\n const cached = payloadCache.get(key);\n if (cached) {\n return cached;\n }\n\n const omitted = plan.fkSide === 'child' ? plan.foreignColPropName : undefined;\n // Same rule as the table's own create input: a column the server fills in from context\n // is not something a nested `create` may supply either.\n const contextColumns = cacheCtx.contextValuesOf?.(plan.targetTableName);\n const fields = Object.fromEntries(\n Object.entries(visibleColumns(plan.targetTable))\n .filter(([columnName]) => columnName !== omitted && !contextColumns?.[columnName])\n .map(([columnName, column]) => [\n columnName,\n drizzleColumnToGraphQLType(column as Column, columnName, plan.targetTableName, false, true, true),\n ]),\n );\n\n const type = new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'nestedWriteInput',\n defaultName: `${typeName}${capitalize(plan.relationName)}NestedCreatePayloadInput`,\n table: tableName,\n operation: plan.relationName,\n }),\n description:\n omitted === undefined\n ? `A new ${resolveTypeName(plan.targetTableName, typeNameMapper)} row for ${typeName}.${plan.relationName}`\n : `A new ${resolveTypeName(plan.targetTableName, typeNameMapper)} row for ${typeName}.${plan.relationName}. \\`${omitted}\\` is set from the ${typeName} row this is written with.`,\n fields,\n });\n payloadCache.set(key, type);\n return type;\n };\n\n /** The target's `Filters` input, which every `connect` / `disconnect` / `set` selects with. */\n const targetFilters = (plan: NestedRelationPlan): GraphQLInputObjectType | undefined =>\n cacheCtx.filterTypeCache.get(plan.targetTable);\n\n const listOf = (type: GraphQLInputObjectType) => new GraphQLList(new GraphQLNonNull(type));\n\n /**\n * `<Type><Relation>NestedCreateInput` / `<Type><Relation>NestedUpdateInput` — the operations\n * offered on one relation. The create variant has no `disconnect` or `set`: a row that does\n * not exist yet has nothing attached to detach or replace.\n *\n * A many-to-many relation offers no `create`: inserting a row *and* linking it is two\n * writes to two tables, and the link half is what the relation field is for. Its\n * `disconnect` and `set` do not depend on nullability, since breaking a link deletes a\n * junction row rather than nulling a column that might be NOT NULL.\n *\n * Each input is also subject to `plan.allowed` — the table it writes has to have that\n * write turned on (see {@link gateNestedWritePlans}).\n */\n const wrapperType = (\n tableName: string,\n typeName: string,\n plan: NestedRelationPlan,\n forUpdate: boolean,\n ): GraphQLInputObjectType | undefined => {\n const key = `${tableName}.${plan.relationName}.${forUpdate ? 'update' : 'create'}`;\n const cached = wrapperCache.get(key);\n if (cached) {\n return cached;\n }\n\n const filters = targetFilters(plan);\n const targetTypeName = resolveTypeName(plan.targetTableName, typeNameMapper);\n const fields: Record<string, { type: GraphQLInputType; description: string }> = {};\n\n const offers = (op: NestedWriteOp) => plan.allowed.has(op);\n\n if (plan.through) {\n // Without a `Filters` input there is no way to name the rows to link, and `create` is\n // not offered here.\n if (filters && offers('connect')) {\n fields['connect'] = {\n type: listOf(filters),\n description: `Link every existing ${targetTypeName} row these match. Already-linked rows are left alone.`,\n };\n }\n if (filters && forUpdate && offers('disconnect')) {\n fields['disconnect'] = {\n type: listOf(filters),\n description: `Unlink every linked ${targetTypeName} row these match, leaving the rows in place`,\n };\n }\n if (filters && forUpdate && offers('set')) {\n fields['set'] = {\n type: listOf(filters),\n description: `Replace the whole set: unlink everything linked, then link every ${targetTypeName} row these match. \\`set: []\\` clears the relation. Applied before \\`disconnect\\` and \\`connect\\`.`,\n };\n }\n } else if (plan.isOne) {\n if (offers('create')) {\n fields['create'] = {\n type: payloadType(tableName, typeName, plan),\n description: `Insert a ${targetTypeName} row and attach it`,\n };\n }\n if (filters && offers('connect')) {\n fields['connect'] = {\n type: filters,\n description: `Attach the existing ${targetTypeName} row this matches. Must match exactly one row.`,\n };\n }\n if (forUpdate && offers('disconnect')) {\n fields['disconnect'] = {\n type: GraphQLBoolean,\n description: `Detach the currently attached ${targetTypeName} row, leaving it in place`,\n };\n }\n } else {\n if (offers('create')) {\n fields['create'] = {\n type: listOf(payloadType(tableName, typeName, plan)),\n description: `Insert these ${targetTypeName} rows and attach them`,\n };\n }\n if (filters && offers('connect')) {\n fields['connect'] = {\n type: listOf(filters),\n description: `Attach every existing ${targetTypeName} row these match`,\n };\n }\n if (filters && forUpdate && offers('disconnect')) {\n fields['disconnect'] = {\n type: listOf(filters),\n description: `Detach every attached ${targetTypeName} row these match, leaving the rows in place`,\n };\n }\n if (filters && forUpdate && offers('set')) {\n fields['set'] = {\n type: listOf(filters),\n description: `Replace the whole set: detach everything attached, then attach every ${targetTypeName} row these match. Applied before \\`disconnect\\`, \\`connect\\` and \\`create\\`.`,\n };\n }\n }\n\n // The target's (or junction's) features can leave a relation with nothing on it, and a\n // GraphQL input object needs at least one field — so the relation is left out instead.\n if (!Object.keys(fields).length) {\n return undefined;\n }\n\n const type = new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'nestedWriteInput',\n defaultName: `${typeName}${capitalize(plan.relationName)}Nested${forUpdate ? 'Update' : 'Create'}Input`,\n table: tableName,\n operation: plan.relationName,\n }),\n description: `Writes through ${typeName}.${plan.relationName}`,\n fields,\n });\n wrapperCache.set(key, type);\n return type;\n };\n\n const relationFields = (tableName: string, typeName: string, forUpdate: boolean) => {\n const tablePlans = plans[tableName];\n if (!tablePlans) {\n return {};\n }\n return Object.fromEntries(\n Object.values(tablePlans).flatMap((plan) => {\n const wrapper = wrapperType(tableName, typeName, plan, forUpdate);\n return wrapper\n ? [[plan.relationName, { type: wrapper, description: `Writes through ${typeName}.${plan.relationName}` }]]\n : [];\n }),\n );\n };\n\n return {\n createFields: (tableName, typeName) => relationFields(tableName, typeName, false),\n updateFields: (tableName, typeName) => relationFields(tableName, typeName, true),\n relaxedColumns: (tableName) => {\n const tablePlans = plans[tableName];\n if (!tablePlans) {\n return NO_COLUMNS;\n }\n const relaxed = new Set<string>();\n for (const plan of Object.values(tablePlans)) {\n // Only a parent-side relation writes a column of *this* table, and only a column that\n // is otherwise required needs relaxing.\n if (\n plan.fkSide === 'parent' &&\n (plan.allowed.has('create') || plan.allowed.has('connect')) &&\n !isOptionalOnInsert(plan.localCol)\n ) {\n relaxed.add(plan.localColPropName);\n }\n }\n return relaxed.size ? relaxed : NO_COLUMNS;\n },\n };\n};\n\n// ── runtime ──────────────────────────────────────────────────────────────────\n\n/**\n * The request a nested write runs for. `context` drives the scope and the context values;\n * all three are what the target table's `onWrite` hooks are handed alongside the rows.\n */\nexport type NestedWriteRequest = { context?: any; args?: any; info?: any };\n\n/** What the resolvers call into. Created once per build, next to the plans it closes over. */\nexport type NestedWriteRuntime = {\n /** Whether the table has any writable relation at all — the cheap check on the hot path. */\n enabled: (tableName: string) => boolean;\n /** Splits one mutation input into plain column values and the nested operations. */\n split: (tableName: string, values: Record<string, any>) => { columns: Record<string, any>; ops: NestedOps };\n /** Whether a split produced anything to do. */\n hasOps: (ops: NestedOps) => boolean;\n /**\n * Adds the join columns the child-side operations will need to a RETURNING column map, so\n * the parent rows come back with the key their children are attached by.\n */\n withJoinColumns: <T extends Record<string, Column>>(tableName: string, ops: NestedOps, columns: T, table: Table) => T;\n /**\n * Runs the operations that have to happen *before* the parent row is written, and returns\n * the parent column values they produced.\n */\n applyParentSide: (\n executor: any,\n tableName: string,\n ops: NestedOps,\n request?: NestedWriteRequest,\n ) => Promise<Record<string, any>>;\n /** Runs the operations that attach to a parent row, once that row exists. */\n applyChildSide: (\n executor: any,\n tableName: string,\n ops: NestedOps,\n parentRows: Record<string, any>[],\n request?: NestedWriteRequest,\n ) => Promise<void>;\n};\n\n/**\n * The union of the relation names a batch of entries writes through — enough to decide which\n * join columns the whole batch's RETURNING clause needs, without inspecting each row's write.\n */\nexport const mergedOps = (entries: { ops: NestedOps }[]): NestedOps =>\n Object.assign({}, ...entries.map((entry) => entry.ops));\n\nconst asArray = (value: any): any[] => (Array.isArray(value) ? value : value === undefined ? [] : [value]);\n\nconst supplied = (value: any) => value !== undefined && value !== null;\n\n/** The write a nested statement performs on the table it lands on. */\ntype NestedOperation = 'insert' | 'update' | 'delete';\n\n/**\n * One `onWrite` call for a nested write: every statement one relation-field input runs\n * against one table with one operation, within one call of the runtime. Their rows are\n * collected and handed to `after` together, the way a root field's hook sees its whole\n * statement's rows at once.\n */\ntype HookStep = {\n tableName: string;\n operation: NestedOperation;\n op: NestedWriteOp;\n hooks: ResolvedWriteHooks;\n /** The keys the write touches plus the hook's `columns` — what each statement returns. */\n returning: Record<string, Column>;\n rows: any[];\n};\n\n/**\n * The hook calls one relation field makes. Every step is registered before the field's first\n * statement, so each `before` runs ahead of all of them and each `after` once the last has\n * returned. A table without hooks registers nothing, and its statements run exactly as they\n * did before hooks reached nested writes — no RETURNING clause is added.\n */\nconst createHookSteps = (\n onWrite: TablePolicies['onWrite'],\n executor: any,\n request: NestedWriteRequest | undefined,\n parentTable: string,\n plan: NestedRelationPlan,\n) => {\n const steps = new Map<string, HookStep>();\n const keyOf = (op: NestedWriteOp, operation: NestedOperation) => `${op}:${operation}`;\n\n const payload = (step: HookStep): Omit<WriteHookPayload, 'position' | 'rows'> => ({\n table: step.tableName,\n operation: step.operation,\n single: plan.isOne,\n args: request?.args,\n context: request?.context,\n info: request?.info,\n tx: executor,\n nested: { parentTable, relation: plan.relationName, op: step.op },\n });\n\n return {\n /** Registers the hook call for `op`'s `operation` statements, if that table has hooks. */\n add: (op: NestedWriteOp, operation: NestedOperation) => {\n const through = plan.through;\n const tableName = through ? through.tableName : plan.targetTableName;\n const hooks = tableName ? onWrite?.(tableName, operation) : undefined;\n if (!tableName || !hooks || steps.has(keyOf(op, operation))) {\n return;\n }\n const keyColumns: Record<string, Column> = through\n ? { [through.sourceColPropName]: through.sourceCol, [through.targetColPropName]: through.targetCol }\n : { ...plan.targetKeyColumns };\n steps.set(keyOf(op, operation), {\n tableName,\n operation,\n op,\n hooks,\n returning: withHookColumns(hooks, keyColumns).returning,\n rows: [],\n });\n },\n get: (op: NestedWriteOp, operation: NestedOperation) => steps.get(keyOf(op, operation)),\n /** Runs one statement, returning its rows to the step it belongs to when there is one. */\n run: async (query: any, op: NestedWriteOp, operation: NestedOperation) => {\n const step = steps.get(keyOf(op, operation));\n if (!step) {\n await query;\n return;\n }\n step.rows.push(...((await query.returning(step.returning)) as any[]));\n },\n before: async () => {\n for (const step of steps.values()) {\n await runWriteHook(step.hooks, 'before', payload(step));\n }\n },\n after: async () => {\n for (const step of steps.values()) {\n await runWriteHook(step.hooks, 'after', { ...payload(step), rows: step.rows });\n }\n },\n };\n};\n\ntype HookSteps = ReturnType<typeof createHookSteps>;\n\n/**\n * Registers the hook calls a child-side relation field will make, in the order its\n * statements run, so the `before` hooks fire in that order too. Mirrors the branches of\n * `applyChildSide` and `applyThroughOps` exactly: a step registered for an input that runs no\n * statement would fire with no rows, and one missing would miss them.\n */\nconst registerChildSteps = (steps: HookSteps, plan: NestedRelationPlan, op: Record<string, any>) => {\n if (plan.through) {\n if (supplied(op['set'])) {\n steps.add('set', 'delete');\n steps.add('set', 'insert');\n }\n if (supplied(op['disconnect'])) {\n steps.add('disconnect', 'delete');\n }\n if (supplied(op['connect'])) {\n steps.add('connect', 'insert');\n }\n return;\n }\n if (op['set'] !== undefined) {\n steps.add('set', 'update');\n }\n if (op['disconnect'] !== undefined && (!plan.isOne || op['disconnect'] === true)) {\n steps.add('disconnect', 'update');\n }\n const attachedBy = attachingOp(op);\n if (plan.isOne && attachedBy && plan.canDetach && op['set'] === undefined) {\n steps.add(attachedBy, 'update');\n }\n if (op['connect'] !== undefined) {\n steps.add('connect', 'update');\n }\n if (op['create'] !== undefined) {\n steps.add('create', 'insert');\n }\n};\n\n/** The input that attaches a row to a to-one, which detaches whatever was attached before. */\nconst attachingOp = (op: Record<string, any>): NestedWriteOp | undefined =>\n op['connect'] !== undefined ? 'connect' : op['create'] !== undefined ? 'create' : undefined;\n\nexport const createNestedWriteRuntime = (params: {\n plans: NestedWritePlans;\n filterCtx: RelationFilterBase | undefined;\n policies?: TablePolicies;\n contextValues?: ContextValuesFor;\n}): NestedWriteRuntime => {\n const { plans, filterCtx, policies, contextValues } = params;\n const onWrite = policies?.onWrite;\n\n /**\n * A `connect` / `disconnect` / `set` operand compiled to SQL. An operand that compiles to\n * nothing is rejected: `connect: {}` would otherwise attach every row in the table.\n */\n const conditionOf = (\n plan: NestedRelationPlan,\n filter: Record<string, any>,\n operation: string,\n scope: ScopeResolver | undefined,\n ) => {\n const condition = extractFilters(\n plan.targetTable,\n plan.targetTableName,\n filter,\n relationFilterCtx(filterCtx, plan.targetTableName),\n );\n if (!condition) {\n throw drizzleError(\n `Drizzle-GraphQL Error: '${operation}' on '${plan.relationName}' needs a filter that selects rows — it was given one that matches everything.`,\n { code: 'DRIZZLE_NESTED_WRITE_INVALID' },\n );\n }\n // The filter selects rows to attach or detach, so it is a write against the target\n // table and is narrowed by its scope: `connect` cannot reach a row the caller cannot\n // see, and out-of-scope rows are not detached.\n return withScope(scope, plan.targetTableName, plan.targetTable, condition)!;\n };\n\n const assertSingleOperation = (plan: NestedRelationPlan, op: Record<string, any>) => {\n const given = ['create', 'connect', 'disconnect'].filter((key) => supplied(op[key]));\n if (given.length > 1) {\n throw drizzleError(\n `Drizzle-GraphQL Error: '${plan.relationName}' takes one of ${given.join(', ')} at a time — it holds a single row.`,\n { code: 'DRIZZLE_NESTED_WRITE_INVALID' },\n );\n }\n };\n\n /** The values the junction stores for the target rows one operand selects. */\n const selectedTargetKeys = async (\n executor: any,\n plan: NestedRelationPlan,\n filter: Record<string, any>,\n operation: string,\n scope: ScopeResolver | undefined,\n ): Promise<any[]> => {\n // Only the key the junction stores is read back, so the projection asks for that column\n // alone — a wide target row is never dragged across the wire to pick one value off it.\n const rows = await executor\n .select({ [plan.foreignColPropName]: plan.foreignCol })\n .from(plan.targetTable)\n .where(conditionOf(plan, filter, operation, scope));\n return rows\n .map((row: any) => row[plan.foreignColPropName])\n .filter((value: any) => value !== undefined && value !== null);\n };\n\n /**\n * The link half of a many-to-many write: junction rows are inserted and deleted, and both\n * the parent row and the target rows are left exactly as they are.\n *\n * `connect` reads the parent's existing links first and inserts only the missing ones, so\n * re-connecting a linked row is a no-op on every dialect rather than a unique-constraint\n * error on some of them — the read and the write share the surrounding transaction, so no\n * other writer can slip a duplicate in between them.\n */\n const applyThroughOps = async (\n executor: any,\n plan: NestedRelationPlan,\n key: any,\n op: Record<string, any>,\n scope: ScopeResolver | undefined,\n steps: HookSteps,\n ) => {\n const through = plan.through!;\n\n const link = async (operands: any[], operation: 'connect' | 'set') => {\n const existing = new Set(\n (\n await executor\n .select({ [through.targetColPropName]: through.targetCol })\n .from(through.table)\n .where(eq(through.sourceCol, key))\n ).map((row: any) => row[through.targetColPropName]),\n );\n const rows: Record<string, any>[] = [];\n for (const filter of operands) {\n for (const targetKey of await selectedTargetKeys(executor, plan, filter, operation, scope)) {\n if (!existing.has(targetKey)) {\n existing.add(targetKey);\n rows.push({ [through.sourceColPropName]: key, [through.targetColPropName]: targetKey });\n }\n }\n }\n if (rows.length) {\n await steps.run(executor.insert(through.table).values(rows), operation, 'insert');\n }\n };\n\n // Replace-the-set first, so a `set` alongside a `connect` reads as \"these rows, plus that\n // one\". `set: []` unlinks everything and links nothing back, which is how the relation is\n // cleared.\n if (supplied(op['set'])) {\n await steps.run(executor.delete(through.table).where(eq(through.sourceCol, key)), 'set', 'delete');\n await link(asArray(op['set']), 'set');\n }\n\n if (supplied(op['disconnect'])) {\n for (const filter of asArray(op['disconnect'])) {\n const targetKeys = await selectedTargetKeys(executor, plan, filter, 'disconnect', scope);\n if (targetKeys.length) {\n await steps.run(\n executor\n .delete(through.table)\n .where(and(eq(through.sourceCol, key), inArray(through.targetCol, targetKeys))),\n 'disconnect',\n 'delete',\n );\n }\n }\n }\n\n if (supplied(op['connect'])) {\n await link(asArray(op['connect']), 'connect');\n }\n };\n\n const detachAll = (\n executor: any,\n plan: NestedRelationPlan,\n key: any,\n scope: ScopeResolver | undefined,\n steps: HookSteps,\n op: NestedWriteOp,\n ) =>\n steps.run(\n executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: null })\n .where(withScope(scope, plan.targetTableName, plan.targetTable, eq(plan.foreignCol, key))),\n op,\n 'update',\n );\n\n return {\n enabled: (tableName) => !!plans[tableName],\n\n split: (tableName, values) => {\n const tablePlans = plans[tableName];\n if (!tablePlans) {\n return { columns: values, ops: {} };\n }\n const columns: Record<string, any> = {};\n const ops: NestedOps = {};\n for (const [key, value] of Object.entries(values)) {\n if (tablePlans[key] && value !== undefined && value !== null) {\n ops[key] = value;\n } else if (!tablePlans[key]) {\n columns[key] = value;\n }\n }\n return { columns, ops };\n },\n\n hasOps: (ops) => Object.keys(ops).length > 0,\n\n withJoinColumns: (tableName, ops, columns, table) => {\n const tablePlans = plans[tableName];\n if (!tablePlans) {\n return columns;\n }\n const allColumns = getColumns(table);\n for (const relationName of Object.keys(ops)) {\n const plan = tablePlans[relationName];\n if (plan?.fkSide === 'child' && !(plan.localColPropName in columns) && allColumns[plan.localColPropName]) {\n (columns as any)[plan.localColPropName] = allColumns[plan.localColPropName];\n }\n }\n return columns;\n },\n\n applyParentSide: async (executor, tableName, ops, request) => {\n const tablePlans = plans[tableName];\n const patch: Record<string, any> = {};\n if (!tablePlans) {\n return patch;\n }\n const context = request?.context;\n const scope = resolveScope(policies, context, filterCtx);\n\n for (const [relationName, op] of Object.entries(ops)) {\n const plan = tablePlans[relationName];\n if (plan?.fkSide !== 'parent') {\n continue;\n }\n assertSingleOperation(plan, op);\n\n if (op['create'] !== undefined) {\n // The only parent-side input that writes the target: `connect` and `disconnect`\n // change the parent's own column, which the parent's own hooks already cover.\n const steps = createHookSteps(onWrite, executor, request, tableName, plan);\n steps.add('create', 'insert');\n await steps.before();\n const values = applyContextValues(\n remapFromGraphQLSingleInput({ ...op['create'] }, plan.targetTable),\n contextValues?.(plan.targetTableName),\n context,\n );\n // The hook's RETURNING always includes the join column, which the patch reads.\n const step = steps.get('create', 'insert');\n const inserted = await executor\n .insert(plan.targetTable)\n .values(values)\n .returning(step ? step.returning : { [plan.foreignColPropName]: plan.foreignCol });\n step?.rows.push(...inserted);\n const created = inserted[0];\n if (!created) {\n throw drizzleError(\n `Drizzle-GraphQL Error: 'create' on '${relationName}' inserted no row, so there is nothing to attach.`,\n { code: 'DRIZZLE_NESTED_WRITE_INVALID' },\n );\n }\n await steps.after();\n patch[plan.localColPropName] = created[plan.foreignColPropName];\n } else if (op['connect'] !== undefined) {\n // `rows.length` drives the match check and is unaffected by the projection, so the\n // read asks only for the key that ends up on the parent's patch.\n const rows = await executor\n .select({ [plan.foreignColPropName]: plan.foreignCol })\n .from(plan.targetTable)\n .where(conditionOf(plan, op['connect'], 'connect', scope));\n if (rows.length !== 1) {\n throw drizzleError(\n `Drizzle-GraphQL Error: 'connect' on '${relationName}' matched ${rows.length} rows — it attaches a single row, so its filter must match exactly one.`,\n { code: 'DRIZZLE_NESTED_WRITE_INVALID' },\n );\n }\n patch[plan.localColPropName] = rows[0][plan.foreignColPropName];\n } else if (op['disconnect'] === true) {\n patch[plan.localColPropName] = null;\n }\n }\n\n return patch;\n },\n\n applyChildSide: async (executor, tableName, ops, parentRows, request) => {\n const tablePlans = plans[tableName];\n if (!tablePlans) {\n return;\n }\n const context = request?.context;\n const scope = resolveScope(policies, context, filterCtx);\n\n for (const [relationName, op] of Object.entries(ops)) {\n const plan = tablePlans[relationName];\n if (plan?.fkSide !== 'child') {\n continue;\n }\n if (plan.isOne) {\n assertSingleOperation(plan, op);\n }\n\n // One hook call per input and operation for the whole batch of parent rows: an update\n // matching several rows writes each one's children, and the hook sees them together.\n const steps = createHookSteps(onWrite, executor, request, tableName, plan);\n registerChildSteps(steps, plan, op);\n await steps.before();\n\n for (const parentRow of parentRows) {\n const key = parentRow?.[plan.localColPropName];\n if (key === undefined || key === null) {\n throw drizzleError(\n `Drizzle-GraphQL Error: cannot write through '${relationName}': the ${tableName} row has no '${plan.localColPropName}' value to attach to.`,\n { code: 'DRIZZLE_NESTED_WRITE_INVALID' },\n );\n }\n\n if (plan.through) {\n await applyThroughOps(executor, plan, key, op, scope, steps);\n continue;\n }\n\n // Replace-the-set first, so a `set` alongside a `create` reads as \"these rows, plus\n // this new one\" rather than dropping the row it just inserted.\n if (op['set'] !== undefined) {\n await detachAll(executor, plan, key, scope, steps, 'set');\n for (const filter of asArray(op['set'])) {\n await steps.run(\n executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: key })\n .where(conditionOf(plan, filter, 'set', scope)),\n 'set',\n 'update',\n );\n }\n }\n\n if (op['disconnect'] !== undefined) {\n if (plan.isOne) {\n if (op['disconnect'] === true) {\n await detachAll(executor, plan, key, scope, steps, 'disconnect');\n }\n } else {\n for (const filter of asArray(op['disconnect'])) {\n await steps.run(\n executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: null })\n .where(and(eq(plan.foreignCol, key), conditionOf(plan, filter, 'disconnect', scope))),\n 'disconnect',\n 'update',\n );\n }\n }\n }\n\n // A to-one relation holds one row, so attaching a new one detaches whatever was\n // there — otherwise both rows point at this parent and the relation is ambiguous.\n const attachedBy = attachingOp(op);\n if (plan.isOne && attachedBy && plan.canDetach && op['set'] === undefined) {\n await detachAll(executor, plan, key, scope, steps, attachedBy);\n }\n\n if (op['connect'] !== undefined) {\n for (const filter of asArray(op['connect'])) {\n await steps.run(\n executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: key })\n .where(conditionOf(plan, filter, 'connect', scope)),\n 'connect',\n 'update',\n );\n }\n }\n\n if (op['create'] !== undefined) {\n const rows = asArray(op['create']).map((row) => ({\n ...applyContextValues(\n remapFromGraphQLSingleInput({ ...row }, plan.targetTable),\n contextValues?.(plan.targetTableName),\n context,\n ),\n [plan.foreignColPropName]: key,\n }));\n if (rows.length) {\n await steps.run(executor.insert(plan.targetTable).values(rows), 'create', 'insert');\n }\n }\n }\n\n await steps.after();\n }\n },\n };\n};\n\n/**\n * Runs one parent write per input entry, with that entry's nested operations around it, all\n * inside a single transaction — a savepoint when the caller already runs on one, so a failing\n * entry rolls the whole batch back.\n *\n * That transaction is also the `tx` the target tables' `onWrite` hooks run on. Every nested\n * write opens it, so a hook on a nested target has the whole tree to roll back even when the\n * root field carries no hook of its own and was not forced into a transaction for one.\n *\n * Entries are written one at a time rather than as a single multi-row statement: a nested\n * operation attaches to the row its own entry produced, so the two have to stay correlated.\n * The batch path is untouched when no entry carries a nested operation.\n */\nexport const writeWithNestedOps = async (params: {\n executor: any;\n runtime: NestedWriteRuntime;\n tableName: string;\n entries: { columns: Record<string, any>; ops: NestedOps }[];\n remapValues: (columns: Record<string, any>) => Record<string, any>;\n write: (executor: any, values: Record<string, any>) => Promise<Record<string, any>[]>;\n request?: NestedWriteRequest;\n}): Promise<Record<string, any>[]> => {\n const { executor, runtime, tableName, entries, remapValues, write, request } = params;\n\n return executor.transaction(async (tx: any) => {\n const rows: Record<string, any>[] = [];\n for (const entry of entries) {\n const patch = await runtime.applyParentSide(tx, tableName, entry.ops, request);\n const written = await write(tx, { ...remapValues(entry.columns), ...patch });\n await runtime.applyChildSide(tx, tableName, entry.ops, written, request);\n rows.push(...written);\n }\n return rows;\n });\n};\n\n/**\n * The update counterpart: one `set` whose nested operations apply to every row the `where`\n * matched. Resolves the parent-side operations into the values first, writes once, then\n * attaches to each row that came back.\n */\nexport const updateWithNestedOps = async (params: {\n executor: any;\n runtime: NestedWriteRuntime;\n tableName: string;\n columns: Record<string, any>;\n ops: NestedOps;\n remapValues: (columns: Record<string, any>) => Record<string, any>;\n write: (executor: any, values: Record<string, any>) => Promise<Record<string, any>[]>;\n request?: NestedWriteRequest;\n}): Promise<Record<string, any>[]> => {\n const { executor, runtime, tableName, columns, ops, remapValues, write, request } = params;\n\n return executor.transaction(async (tx: any) => {\n const patch = await runtime.applyParentSide(tx, tableName, ops, request);\n const rows = await write(tx, { ...remapValues(columns), ...patch });\n await runtime.applyChildSide(tx, tableName, ops, rows, request);\n return rows;\n });\n};\n","/**\n * A table the drizzle instance has no relational query builder for.\n *\n * Both the generated schema and `db.query` are keyed by the relations config, so under\n * drizzle-orm v1 the two agree by construction and this should never fire — a table left out\n * of the relations config is simply never generated for. It stays as a guard because the\n * alternative is a `TypeError` on `undefined` deep inside a resolver, and because earlier v1\n * release candidates *could* disagree: they took the schema as a separate constructor\n * argument, so a table passed there but left out of `buildRelations`/`defineRelations` was\n * generated for and then had nothing to read through.\n */\nexport const missingQueryBuilderError = (tableName: string): Error =>\n new Error(\n `Drizzle-GraphQL Error: Table '${tableName}' has no query builder on the drizzle instance, so there is nothing for its resolvers to read through. Include it in the relations you pass to buildRelations/defineRelations, or drop it from the generated schema with config.exclude.tables.`,\n );\n","// =============================================================================\n// The read side of a table's root fields: `<table>` and `<table>Single`.\n//\n// All three dialects generate these identically. Everything dialect-specific\n// about a relational read lives below this layer — `runRelationalSelect` takes\n// the NULL ordering as a parameter, and the primary-key lookup is passed in —\n// so a dialect supplies two values and gets both resolvers.\n// =============================================================================\n\nimport type { Table } from 'drizzle-orm';\nimport type { RelationalQueryBuilder } from 'drizzle-orm/mysql-core/query-builders/query';\nimport type { GraphQLInputObjectType } from 'graphql';\nimport {\n applyLimitPolicy,\n type DrizzleErrorContext,\n generateDistinctEnum,\n type LimitPolicyFor,\n type NullOrdering,\n type RelationFilterBase,\n type ResolverPolicies,\n resolveObjectTypeName,\n resolveQueryExecutor,\n runRelationalSelect,\n selectArrayArgs,\n selectSingleArgs,\n type TypeNameMapper,\n type TypeNameResolver,\n toGraphQLError,\n withDefaultOrderBy,\n withErrorContext,\n} from '../builders/common.ts';\nimport type { ResolveTree } from '../parse-resolve-info.ts';\nimport { parseResolveInfo } from '../parse-resolve-info.ts';\nimport { missingQueryBuilderError } from './errors.ts';\nimport type { CreatedResolver, TableNamedRelations, TableSelectArgs } from './types.ts';\n\n/** `<table>` — the list field. */\nexport type SelectArrayGenerator = (\n db: any,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n distinctEnabled?: boolean,\n limits?: LimitPolicyFor,\n policies?: ResolverPolicies,\n /** The build's type-naming rule, which names the `distinct` enum. */\n resolveName?: TypeNameResolver,\n) => CreatedResolver;\n\n/** `<table>Single` — the same read, capped at one row. */\nexport type SelectSingleGenerator = (\n db: any,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n limits?: LimitPolicyFor,\n policies?: ResolverPolicies,\n /** The build's type-naming rule, which names the `deleted` argument's enum. */\n resolveName?: TypeNameResolver,\n) => CreatedResolver;\n\n/** The table's entry in `db.query`, which is what a relational read runs through. */\nconst queryBaseFor = (db: any, tableName: string): RelationalQueryBuilder<any, any, any> => {\n const queryBase = db.query[tableName] as RelationalQueryBuilder<any, any, any> | undefined;\n if (!queryBase) {\n throw missingQueryBuilderError(tableName);\n }\n return queryBase;\n};\n\n/**\n * Builds a dialect's two select generators.\n *\n * @param primaryKeyPropNames the dialect's composite-aware primary-key lookup\n * @param nullOrdering how the dialect's `ORDER BY` sorts NULLs, which keyset pagination has\n * to agree with\n */\nexport const createSelectGenerators = (\n primaryKeyPropNames: (table: any) => string[],\n nullOrdering: NullOrdering,\n): { generateSelectArray: SelectArrayGenerator; generateSelectSingle: SelectSingleGenerator } => {\n const generateSelectArray: SelectArrayGenerator = (\n db,\n tableName,\n tables,\n relationMap,\n orderArgs,\n filterArgs,\n fieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n distinctEnabled = true,\n limits,\n policies,\n resolveName,\n ): CreatedResolver => {\n const queryBase = queryBaseFor(db, tableName);\n\n const table = tables[tableName]!;\n const limitPolicy = limits?.(tableName);\n const pkNames = primaryKeyPropNames(table);\n const errorCtx: DrizzleErrorContext = { table: tableName, operation: 'select', field: fieldName };\n const queryArgs = selectArrayArgs(\n orderArgs,\n filterArgs,\n distinctEnabled ? generateDistinctEnum(table, typeName, resolveName, tableName) : undefined,\n policies?.softDelete,\n tableName,\n resolveName,\n );\n // The name the object type actually carries — what `fieldsByTypeName` is keyed by.\n const objectTypeName = resolveObjectTypeName(tableName, typeNameMapper, resolveName);\n\n return {\n name: fieldName,\n resolver: async (_source: any, rawArgs: Partial<TableSelectArgs>, context: any, info: any) => {\n // An omitted `orderBy` falls back to the table's configured default ordering here,\n // before anything reads the arguments — the cursor tuple and a `distinct` pass both\n // have to agree on one effective ordering.\n const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName: objectTypeName,\n typeNameMapper,\n resolveName,\n parsedInfo,\n ...args,\n limit: applyLimitPolicy(args.limit, limitPolicy),\n single: false,\n filterCtx,\n limits,\n defaultOrderBy: policies?.defaultOrderBy,\n pkNames,\n db: executor,\n scope: policies?.scope?.(context),\n nullOrdering,\n });\n } catch (e) {\n throw withErrorContext(toGraphQLError(e), errorCtx);\n }\n },\n args: queryArgs,\n };\n };\n\n const generateSelectSingle: SelectSingleGenerator = (\n db,\n tableName,\n tables,\n relationMap,\n orderArgs,\n filterArgs,\n fieldName,\n // The list field's only use for the default type name is naming its `distinct` enum,\n // and a single-row read has no `distinct` argument. The slot stays so the two\n // generators keep one positional shape at the call site in `build-context.ts`.\n _typeName,\n typeNameMapper,\n filterCtx,\n limits,\n policies,\n resolveName,\n ): CreatedResolver => {\n const queryBase = queryBaseFor(db, tableName);\n\n const queryArgs = selectSingleArgs(orderArgs, filterArgs, policies?.softDelete, tableName, resolveName);\n const objectTypeName = resolveObjectTypeName(tableName, typeNameMapper, resolveName);\n\n const table = tables[tableName]!;\n const pkNames = primaryKeyPropNames(table);\n const errorCtx: DrizzleErrorContext = { table: tableName, operation: 'select', field: fieldName };\n\n return {\n name: fieldName,\n resolver: async (_source: any, rawArgs: Partial<TableSelectArgs>, context: any, info: any) => {\n // Same as the list field: the effective ordering is resolved before anything reads it.\n const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName: objectTypeName,\n typeNameMapper,\n resolveName,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n limits,\n defaultOrderBy: policies?.defaultOrderBy,\n pkNames,\n db: executor,\n scope: policies?.scope?.(context),\n });\n } catch (e) {\n throw withErrorContext(toGraphQLError(e), errorCtx);\n }\n },\n args: queryArgs,\n };\n };\n\n return { generateSelectArray, generateSelectSingle };\n};\n","// =============================================================================\n// The part of a schema build that has nothing to do with the dialect.\n//\n// Every builder starts the same way: find the tables, resolve the feature flags,\n// flatten the relation graph, register the per-build scalar/enum/exclusion state,\n// assemble the filter context and the type cache, and generate each table's types.\n// Every builder ends the same way too, and the read half in between — the two\n// select fields, the aggregate field and the group-by field — is identical down to\n// the argument lists.\n//\n// The per-table loop is shared as well: `forEachTable` works out what every dialect\n// needs per table, calls the dialect back for the mutations it generated, and then\n// registers those and the inputs and outputs they reference. What a dialect still\n// owns is the mutation half itself — PostgreSQL and SQLite return the rows they\n// wrote, MySQL cannot, so its mutation fields, return types and resolvers differ\n// throughout.\n//\n// Keeping this shared is not just deduplication. A feature added to the prelude\n// used to reach two of the three dialects — `uniqueKeyFilters` (#90) shipped as a\n// flag MySQL accepted and never acted on, because MySQL carried its own copy.\n// =============================================================================\n\nimport { is, One, type Table } from 'drizzle-orm';\nimport type { GraphQLFieldConfig, GraphQLInputObjectType, GraphQLObjectType, GraphQLOutputType } from 'graphql';\nimport { GraphQLList, GraphQLNonNull } from 'graphql';\nimport {\n aggregateFieldComplexity,\n attachTargetPrimaryKeys,\n bindPolicies,\n buildNamedRelations,\n buildUniqueKeyMap,\n computeResolverFieldNames,\n createMutationTxCtx,\n createRelationResolverFactory,\n defineRootField,\n extractRelationJoinColumns,\n generateTableTypes,\n getUniqueColumnSets,\n type LimitPolicyFor,\n listFieldComplexity,\n type MutationTxCtx,\n type NullOrdering,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n type ResolverFieldNames,\n type ResolverPolicies,\n registerColumnExclusions,\n type SoftDeleteInfo,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n type UniqueKeyMap,\n visibleColumns,\n} from '../builders/common.ts';\nimport { type DrizzleMutationMeta, type TableFieldExtensionFactory, tableFieldExtensions } from '../extensions.ts';\nimport { resolveTableFeatures } from '../features.ts';\nimport { registerEnumConfig, registerScalarOverrides } from '../type-converter/index.ts';\nimport {\n createRelationAggregateFactory,\n generateAggregate,\n generateAggregateTypes,\n generateGroupBy,\n generateGroupByEnum,\n generateGroupByType,\n generateHavingInput,\n resetAggregateColumnCache,\n} from './aggregates.ts';\nimport {\n buildNestedWritePlans,\n createNestedWriteRuntime,\n createNestedWriteTypes,\n gateNestedWritePlans,\n type NestedWriteRuntime,\n type NestedWriteTypes,\n} from './nested-writes.ts';\nimport { createSelectGenerators } from './select.ts';\nimport type {\n CreatedResolver,\n GeneratedTableTypes,\n GeneratedTableTypesOutputs,\n SchemaGeneratorOptions,\n TableFeatures,\n TableNamedRelations,\n} from './types.ts';\n\n/** What {@link createSchemaBuilder} cannot work out for itself. */\nexport type SchemaBuildAdapter<WithReturning extends boolean = boolean> = {\n /** The dialect's table class, used with `is()` to pick tables out of the schema module. */\n tableClass: any;\n /**\n * The dialect's `getTableConfig`. The three dialects expose the same\n * `{ primaryKeys, uniqueConstraints, indexes }` shape from different modules.\n */\n getTableConfig: (table: any) => any;\n /** Primary-key property names, composite-aware — built on the dialect's `getTableConfig`. */\n primaryKeyPropNames: (table: any) => string[];\n /** How the dialect's `ORDER BY` sorts NULLs, which relation pagination has to match. */\n nullOrdering: NullOrdering;\n /**\n * Whether a write can return the rows it wrote. `false` on MySQL, which has no `RETURNING`\n * clause — its table types carry no `${Table}Item` outputs because no mutation returns one.\n */\n returnsRows: WithReturning;\n /**\n * Dialect-specific validation of the database handle against the requested options, run\n * once the tables are known but before anything is generated. SQLite uses it to reject\n * features a synchronous driver cannot support; MySQL to reject nested writes.\n */\n preflight?: (db: any, options: SchemaGeneratorOptions) => void;\n};\n\n/**\n * Everything a build accumulates before its root fields exist, handed to the dialect so it\n * can generate its mutation half against the same tables, caches and policies the shared\n * half used.\n */\nexport type SchemaBuildContext<WithReturning extends boolean = boolean> = {\n db: any;\n /** The schema module as given, including whatever is not a table. */\n schema: Record<string, unknown>;\n options: SchemaGeneratorOptions;\n /** The tables this build covers — excluded ones already dropped. */\n tables: Record<string, Table>;\n tableEntries: [string, Table][];\n /** This table's feature flags, with any per-table predicate already run. */\n featureOf: (tableName: string) => TableFeatures;\n /** Whether any table in the build wants a feature — i.e. whether to build shared machinery. */\n anyTable: (feature: keyof TableFeatures) => boolean;\n /** The full relation graph, used by type generation. */\n namedRelations: Record<string, Record<string, TableNamedRelations>>;\n /** The relations to eager-load via `with:`, used by the resolvers. */\n eagerRelations: Record<string, Record<string, TableNamedRelations>>;\n filterCtx: RelationFilterBase;\n /** The build's policies as configured, before binding. */\n tablePolicies: SchemaGeneratorOptions['policies'];\n policies: ResolverPolicies | undefined;\n softDeleteOf: NonNullable<SchemaGeneratorOptions['policies']>['softDelete'];\n resolverFactory: RelationResolverFactory;\n cacheCtx: TypeCacheCtx;\n nestedRuntime: NestedWriteRuntime | undefined;\n nestedTypes: NestedWriteTypes | undefined;\n /** Undefined unless `transactions: 'auto'`; its field-name set is filled by `finalizeBuild`. */\n mutationTxCtx: MutationTxCtx | undefined;\n gqlSchemaTypes: Record<string, GeneratedTableTypes<WithReturning>>;\n // A plain map rather than graphql's `ThunkObjMap`, which is a union with a thunk and so\n // cannot be indexed through a property. Still assignable wherever a thunk map is wanted.\n queries: Record<string, GraphQLFieldConfig<any, any>>;\n mutations: Record<string, GraphQLFieldConfig<any, any>>;\n inputs: Record<string, GraphQLInputObjectType>;\n outputs: Record<string, GraphQLObjectType>;\n limits: LimitPolicyFor | undefined;\n typeNameMapper: TypeNameMapper | undefined;\n};\n\n/**\n * One generated mutation, ready to be hung off the mutation root: what the field returns,\n * and what it says about itself. A dialect's per-table callback answers with a list of these\n * rather than registering fields itself, so the registration — and the collision check in\n * {@link defineRootField} — happens in one place for all three dialects.\n */\nexport type MutationRegistration = {\n /** Undefined when this table's features left the mutation ungenerated. */\n generated: CreatedResolver | undefined;\n type: GraphQLOutputType;\n /**\n * The identity published on `extensions.drizzle`. The count mutations carry their plural\n * sibling's operation plus `count: true`, so a wrapper gating writes on `operation` cannot\n * be bypassed by swapping in the count variant.\n */\n meta?: DrizzleMutationMeta;\n description?: string;\n};\n\n/** What a dialect's per-table callback hands back for {@link forEachTable} to register. */\nexport type TableMutations = {\n /** In registration order, which is the order the fields appear in the schema. */\n mutations: MutationRegistration[];\n /**\n * The two inputs whose presence is decided by the mutation half rather than by a feature\n * flag, and which the shared loop needs in order to know whether to publish them.\n */\n onConflictInput?: GraphQLInputObjectType;\n updateManyInput?: GraphQLInputObjectType;\n};\n\n/** The per-table values {@link forEachTable} has already worked out, handed to the dialect. */\nexport type TableBuild<WithReturning extends boolean = boolean> = {\n tableName: string;\n table: Table;\n /** This table's feature flags, with any per-table predicate already run. */\n tableFeatures: TableFeatures;\n /** Builds what a field of this table publishes under `extensions.drizzle`. */\n drizzleMeta: TableFieldExtensionFactory;\n /** The generated field names, from the naming config. */\n names: ResolverFieldNames;\n types: GeneratedTableTypes<WithReturning>;\n /** Set when the table marks rows deleted instead of removing them. */\n softDeleteInfo: SoftDeleteInfo | undefined;\n};\n\n/**\n * Binds a dialect and returns the shared halves of its build.\n *\n * Called once per dialect module at import time, so the select generators — which close over\n * the dialect's primary-key lookup and NULL ordering — are built once rather than per\n * `buildSchema`.\n */\nexport const createSchemaBuilder = <WithReturning extends boolean>(adapter: SchemaBuildAdapter<WithReturning>) => {\n const primaryKeyPropNames = adapter.primaryKeyPropNames;\n const uniqueColumnSets = (table: Table): string[][] => getUniqueColumnSets(table, adapter.getTableConfig);\n const { generateSelectArray, generateSelectSingle } = createSelectGenerators(\n primaryKeyPropNames,\n adapter.nullOrdering,\n );\n\n /** Everything up to and including each table's generated types. */\n const prepareBuild = (\n db: any,\n schema: Record<string, unknown>,\n relations: TablesRelationalConfig,\n options: SchemaGeneratorOptions,\n ): SchemaBuildContext<WithReturning> => {\n const { relationsDepthLimit, prefixes, typeNameMapper, shouldEagerLoad, features, complexity, limits } = options;\n const schemaEntries = Object.entries(schema);\n // Excluded tables are dropped here, before anything reads `tableEntries` — which also makes\n // `buildNamedRelations` skip every relation pointing at one, since it resolves targets\n // through this list.\n const excludedTables = new Set(options.exclude?.tables ?? []);\n const tableEntries = schemaEntries.filter(\n ([key, value]) => is(value, adapter.tableClass) && !excludedTables.has(key),\n ) as [string, Table][];\n const tables = Object.fromEntries(tableEntries) as Record<string, Table>;\n\n // A feature flag may be a per-table predicate, so every flag is resolved against the table\n // it applies to. `anyTable` answers the build-wide question — whether machinery shared\n // across tables is worth constructing at all.\n const featureOf = resolveTableFeatures(features);\n const anyTable = (feature: keyof TableFeatures) => tableEntries.some(([name]) => featureOf(name)[feature]);\n\n if (!tableEntries.length) {\n throw new Error(\n \"Drizzle-GraphQL Error: No tables detected in Drizzle-ORM's database instance. Did you forget to pass schema to drizzle constructor?\",\n );\n }\n\n // Resolve scalar overrides into the type-converter's registry before any type generation —\n // every subsequent column→GraphQL type decision and runtime value remap consults it.\n registerScalarOverrides(tables, options);\n // Same lifecycle: the enum registry is per-build, so a second build never reuses the first\n // build's enum types (and with them its naming decisions).\n registerEnumConfig(options);\n // And the same for column exclusions: a per-build registry read by every site that decides\n // what the schema contains, reset here so a rebuild never inherits the previous build's.\n registerColumnExclusions(tables, options.exclude);\n // Column classifications for the aggregates are cached across the tables of one build, and\n // hold that build's types and exclusions — so they are dropped here for the same reason.\n resetAggregateColumnCache();\n\n // Flatten drizzle-orm v1 TablesRelationalConfig into the canonical shape\n // used throughout common.ts: Record<tableName, Record<relName, TableNamedRelations>>\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Relations *into* an excluded table are already gone (their target no longer resolves);\n // relations *out of* one have no type left to hang a field on.\n for (const excluded of excludedTables) {\n delete namedRelations[excluded];\n }\n // Record each relation target's primary key (composite-aware) so paginated relations\n // default to a deterministic PK order. Must run before pruning / type generation, which\n // share these entry objects.\n attachTargetPrimaryKeys(namedRelations, tables, (table) => primaryKeyPropNames(table));\n // Relations to eager-load via `with:`. Query/mutation resolvers use this pruned map so\n // opted-out relations never overfetch; type generation keeps the full map so their\n // fields still exist and resolve lazily.\n const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);\n\n // A `where` field per compound unique constraint, for the tables that asked for one. Built\n // once and shared by the input types and the resolvers: the fields a request may spell and\n // the fields a resolver understands are the same map, so neither can drift from the other.\n const uniqueKeys: Record<string, UniqueKeyMap> = {};\n for (const [tableName, table] of tableEntries) {\n if (!featureOf(tableName).uniqueKeyFilters) {\n continue;\n }\n // Whatever the filter input already offers under a name keeps it — columns are added\n // first, then relations, and a key field last.\n const taken = new Set([...Object.keys(visibleColumns(table)), ...Object.keys(namedRelations[tableName] ?? {})]);\n const map = buildUniqueKeyMap(uniqueColumnSets(table), taken);\n if (Object.keys(map).length) {\n uniqueKeys[tableName] = map;\n }\n }\n\n const filterCtx: RelationFilterBase = { tables, relationMap: namedRelations, uniqueKeys };\n\n // The row scope compiled against this build's relation graph, plus the columns whose value\n // the server supplies. Both stay undefined unless configured.\n const tablePolicies = options.policies;\n const contextValuesOf = tablePolicies?.contextValues;\n const softDeleteOf = tablePolicies?.softDelete;\n const policies = bindPolicies(tablePolicies, filterCtx);\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(\n db,\n tables,\n adapter.nullOrdering,\n filterCtx,\n limits,\n tablePolicies,\n );\n\n // Fresh cache per build — prevents type name collisions when buildSchema() is called\n // multiple times.\n const cacheCtx: TypeCacheCtx = {\n typeName: options.typeName ?? ((info) => info.defaultName),\n genericFilterCache: new Map(),\n objectTypeCache: new Map(),\n relationFieldContainers: new Map(),\n fullyBuiltTables: new Set(),\n relationTypeCache: new Map(),\n selectFieldCache: new WeakMap(),\n filterFieldCache: new WeakMap(),\n orderTypeCache: new WeakMap(),\n filterTypeCache: new WeakMap(),\n listRelationFilterCache: new Map(),\n aggregateTypeCache: new Map(),\n complexity,\n limits,\n docs: options.docs ?? {},\n primaryKeyOf: (name) => (tables[name] ? primaryKeyPropNames(tables[name] as Table) : []),\n contextValuesOf,\n softDeleteOf,\n featureOf,\n uniqueKeysOf: (tableName) => uniqueKeys[tableName],\n };\n\n adapter.preflight?.(db, options);\n\n // Nested writes: the plans decide which relations are writable at all, the types add their\n // fields to the create/update inputs, and the runtime executes them. All three are left\n // undefined when the feature is off, so the inputs and the resolvers stay as they were.\n const nestedPlans = features.nestedWrites\n ? buildNestedWritePlans(\n tables,\n namedRelations,\n (target) => uniqueColumnSets(target as Table),\n (target) => primaryKeyPropNames(target as Table),\n extractRelationJoinColumns,\n // A junction is written without being a relation target, so it is named from the\n // whole schema — excluded tables included, which the gate below then refuses.\n (junction) => schemaEntries.find(([, value]) => value === junction)?.[0],\n )\n : undefined;\n // A nested write is a write to the target (or junction) table, so it obeys that table's\n // features: an input whose write is turned off there is left out of the schema.\n if (nestedPlans) {\n const omitted = gateNestedWritePlans(nestedPlans, featureOf, (tableName) => excludedTables.has(tableName));\n if (omitted.length) {\n const listed =\n omitted.length > 5 ? `${omitted.slice(0, 5).join(', ')} and ${omitted.length - 5} more` : omitted.join(', ');\n console.warn(\n `Drizzle-GraphQL Warning: config.features — nestedWrites leaves out the nested inputs whose table has that write turned off: ${listed}.`,\n );\n }\n }\n const nestedTypes = nestedPlans\n ? createNestedWriteTypes({ plans: nestedPlans, cacheCtx, typeNameMapper })\n : undefined;\n const nestedRuntime = nestedPlans\n ? createNestedWriteRuntime({\n plans: nestedPlans,\n filterCtx,\n policies: tablePolicies,\n contextValues: contextValuesOf,\n })\n : undefined;\n\n // Built when at least one table wants relation aggregates; a table that has them off is\n // handed `undefined` below, so `generateTableTypes` emits no `${relation}Aggregate` fields\n // on its object type.\n const relationAggregateFactory: RelationAggregateFactory | undefined = anyTable('relationAggregates')\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx, tablePolicies)\n : undefined;\n\n const gqlSchemaTypes = Object.fromEntries(\n Object.entries(tables).map(([tableName, _table]) => [\n tableName,\n generateTableTypes(\n tableName,\n tables,\n namedRelations,\n adapter.returnsRows,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n prefixes.insert,\n prefixes.update,\n resolverFactory,\n featureOf(tableName).relationAggregates ? relationAggregateFactory : undefined,\n nestedTypes,\n ),\n ]),\n ) as Record<string, GeneratedTableTypes<WithReturning>>;\n\n return {\n db,\n schema,\n options,\n tables,\n tableEntries,\n featureOf,\n anyTable,\n namedRelations,\n eagerRelations,\n filterCtx,\n tablePolicies,\n policies,\n softDeleteOf,\n resolverFactory,\n cacheCtx,\n nestedRuntime,\n nestedTypes,\n // Shared per-request transaction machinery for multi-mutation documents; undefined\n // unless `transactions: 'auto'`. Its field-name set is filled once all mutations exist.\n mutationTxCtx: createMutationTxCtx(options.transactions),\n gqlSchemaTypes,\n queries: {},\n mutations: {},\n inputs: {},\n outputs: {},\n limits,\n typeNameMapper,\n };\n };\n\n /**\n * The table's read fields — both selects, the aggregate and the group-by — generated and\n * hung off the query root. Identical for every dialect: a read returns rows everywhere.\n *\n * The types it built are returned rather than registered, because where they land in the\n * schema's type map is the caller's business — MySQL has no `${Table}Item` output to\n * interleave them with, and the printed order of the two schemas should not drift.\n */\n const addReadFields = (\n ctx: SchemaBuildContext<WithReturning>,\n tableName: string,\n names: ResolverFieldNames,\n tableTypes: GeneratedTableTypes<WithReturning>,\n drizzleMeta: TableFieldExtensionFactory,\n ) => {\n const { db, tables, cacheCtx, filterCtx, eagerRelations, policies, tablePolicies, limits, typeNameMapper } = ctx;\n const { complexity } = ctx.options;\n const table = tables[tableName] as Table;\n const tableFeatures = ctx.featureOf(tableName);\n const { tableFilters, tableOrder } = tableTypes.inputs;\n const { selectSingleOutput, selectArrOutput } = tableTypes.outputs;\n const { typeName, listFieldName, singleFieldName, aggregateFieldName, groupByFieldName } = names;\n\n const selectArrGenerated = generateSelectArray(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n listFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n tableFeatures.distinct,\n limits,\n policies,\n cacheCtx.typeName,\n );\n const selectSingleGenerated = generateSelectSingle(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n singleFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n limits,\n policies,\n cacheCtx.typeName,\n );\n\n const aggregateType = tableFeatures.aggregates\n ? generateAggregateTypes(table, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = tableFeatures.aggregates\n ? generateAggregate(\n db,\n tableName,\n table,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n tablePolicies,\n cacheCtx.typeName,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n tableFeatures.aggregates && tableFeatures.groupBy\n ? generateGroupByType(table, tableName, typeName, cacheCtx)\n : undefined;\n const groupByEnum = groupByType ? generateGroupByEnum(table, tableName, typeName, cacheCtx) : undefined;\n const havingInput = groupByEnum ? generateHavingInput(table, tableName, typeName, cacheCtx) : undefined;\n const groupByGenerated =\n groupByType && groupByEnum && havingInput\n ? generateGroupBy(\n db,\n tableName,\n table,\n typeName,\n groupByFieldName,\n tableFilters,\n groupByEnum,\n havingInput,\n filterCtx,\n tablePolicies,\n cacheCtx.typeName,\n )\n : undefined;\n\n defineRootField(ctx.queries, 'query', selectArrGenerated.name, {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: listFieldComplexity(complexity, limits?.(tableName)) } : {}),\n },\n });\n defineRootField(ctx.queries, 'query', selectSingleGenerated.name, {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: true, targetArg: 'where' }),\n },\n });\n if (aggregateGenerated && aggregateType) {\n defineRootField(ctx.queries, 'query', aggregateGenerated.name, {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'aggregate', single: true, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n });\n }\n if (groupByGenerated && groupByType) {\n defineRootField(ctx.queries, 'query', groupByGenerated.name, {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'groupBy', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n });\n }\n\n return { aggregateType, groupByType, havingInput };\n };\n\n /**\n * The per-table loop, run once for every table the build covers.\n *\n * The dialect's callback receives the values the loop has already worked out — the feature\n * flags, the extension factory, the field names, the table's generated types and its\n * soft-delete config — and answers with the mutations it generated. Registering them, and\n * registering the inputs and outputs those mutations reference, happens here: both sides\n * did it identically, down to the `description` strings on the count mutations, so a gate\n * changed on one side and forgotten on the other used to be a silent dialect divergence.\n *\n * What stays in the dialect is what genuinely differs — which generators run, what each\n * mutation returns, and (on MySQL) that a write cannot report the rows it touched.\n */\n const forEachTable = (\n ctx: SchemaBuildContext<WithReturning>,\n perTable: (build: TableBuild<WithReturning>) => TableMutations,\n ): void => {\n const { schema, featureOf, softDeleteOf, typeNameMapper, gqlSchemaTypes, mutations, inputs, outputs } = ctx;\n const { prefixes, suffixes } = ctx.options;\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n // Everything this table generates, with any per-table predicate already run.\n const tableFeatures = featureOf(tableName);\n // What every field this table generates publishes about itself under `extensions.drizzle`,\n // so a wrapper can read a field's identity instead of parsing its configurable name.\n const drizzleMeta = tableFieldExtensions(tableName, primaryKeyPropNames(schema[tableName] as Table));\n // Compute field names using the mapper logic\n const names = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\n // A table that marks rows deleted instead of removing them also gets the mutation that\n // reverses it — clearing the column through an ordinary update is not possible, since the\n // column is not in the update input and a marked row is invisible to a `where` anyway.\n const softDeleteInfo = softDeleteOf?.(tableName);\n\n // Both selects, the aggregate and the group-by: generated and hung off the query root\n // by the shared builder, since a read is a read on every dialect.\n const readTypes = addReadFields(ctx, tableName, names, tableTypes, drizzleMeta);\n\n const built = perTable({\n tableName,\n table: schema[tableName] as Table,\n tableFeatures,\n drizzleMeta,\n names,\n types: tableTypes,\n softDeleteInfo,\n });\n\n for (const { generated, type, meta, description } of built.mutations) {\n if (generated) {\n defineRootField(mutations, 'mutation', generated.name, {\n type,\n args: generated.args,\n resolve: generated.resolver,\n ...(meta ? { extensions: { drizzle: drizzleMeta({ kind: 'mutation', ...meta }) } } : {}),\n ...(description ? { description } : {}),\n });\n }\n }\n\n const { insertInput, updateInput, tableFilters, tableOrder } = tableTypes.inputs;\n // The insert/update inputs are still built (they type the mutations that survive) but\n // only reach the schema's type map when a mutation actually references them.\n const activeInputs = [\n // The insert input types the upsert mutations too, so either feature keeps it.\n ...(tableFeatures.insert || built.onConflictInput ? [insertInput] : []),\n ...(built.onConflictInput ? [built.onConflictInput] : []),\n ...(tableFeatures.update ? [updateInput] : []),\n ...(built.updateManyInput ? [built.updateManyInput] : []),\n tableFilters,\n tableOrder,\n ];\n activeInputs.forEach((e) => {\n inputs[e.name] = e;\n });\n const { selectSingleOutput } = tableTypes.outputs;\n outputs[selectSingleOutput.name] = selectSingleOutput;\n if (adapter.returnsRows) {\n // Only a dialect with RETURNING has a `${Table}Item` type — its mutations answer with\n // one, where MySQL's answer with the build's shared `MutationReturn`.\n const { singleTableItemOutput } = tableTypes.outputs as GeneratedTableTypesOutputs<true>;\n outputs[singleTableItemOutput.name] = singleTableItemOutput;\n }\n const { aggregateType, groupByType, havingInput } = readTypes;\n if (aggregateType) {\n outputs[aggregateType.name] = aggregateType;\n }\n if (groupByType && havingInput) {\n outputs[groupByType.name] = groupByType;\n inputs[havingInput.name] = havingInput;\n }\n }\n };\n\n /** The relation field resolvers and the transaction roster, once every root field exists. */\n const finalizeBuild = (ctx: SchemaBuildContext<WithReturning>): any => {\n // Every generated mutation name is now known — the first mutation resolver of a request\n // uses this set to count the document's root mutation fields (and to leave documents\n // containing consumer-added mutations alone).\n if (ctx.mutationTxCtx) {\n for (const name of Object.keys(ctx.mutations)) {\n ctx.mutationTxCtx.fieldNames.add(name);\n }\n }\n\n const fieldResolvers: Record<string, Record<string, any>> = {};\n for (const [tableName, tableRelations] of Object.entries(ctx.namedRelations)) {\n const relResolvers: Record<string, any> = {};\n for (const [relName, relEntry] of Object.entries(tableRelations)) {\n const isOne = is((relEntry as any).relation ?? relEntry, One);\n const resolver = ctx.resolverFactory({ tableName, relationName: relName, relEntry, isOne });\n if (resolver) {\n relResolvers[relName] = resolver;\n }\n }\n if (Object.keys(relResolvers).length > 0) {\n fieldResolvers[tableName] = relResolvers;\n }\n }\n\n return {\n queries: ctx.queries,\n mutations: ctx.mutations,\n inputs: ctx.inputs,\n types: ctx.outputs,\n fieldResolvers,\n };\n };\n\n return { primaryKeyPropNames, uniqueColumnSets, prepareBuild, forEachTable, finalizeBuild };\n};\n","import type { Table } from 'drizzle-orm';\nimport { type MySqlAsyncDatabase, MySqlTable, getTableConfig as mysqlTableConfig } from 'drizzle-orm/mysql-core';\nimport {\n GraphQLBoolean,\n type GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n applyContextValues,\n applyContextValuesAll,\n assertSingleMatch,\n drizzleError,\n extractFilters,\n generateOnConflictInput,\n generateUpdateManyInput,\n generateWriteCount,\n getPrimaryKeyPropNamesFromConfig,\n hardDeleteArg,\n type MutationTxCtx,\n memoizeTableConfig,\n mysqlValuesColumnRef,\n type OnConflictArg,\n type RelationFilterBase,\n type ResolverPolicies,\n relationFilterCtx,\n resolveConflictPlan,\n scopedWhere,\n stripContextValues,\n type TablesRelationalConfig,\n type WriteOperation,\n withScope,\n writeResolver,\n} from '../builders/common.ts';\nimport { remapFromGraphQLArrayInput, remapFromGraphQLSingleInput } from '../data-mappers/index.ts';\nimport type { DrizzleMutationMeta } from '../extensions.ts';\nimport { createSchemaBuilder, type MutationRegistration } from './build-context.ts';\nimport { remapUpdateInput } from './field-updates.ts';\nimport type { CreatedResolver, Filters, SchemaGeneratorOptions } from './types.ts';\n\n// Every MySQL mutation answers `{ isSuccess: true }`: with no RETURNING clause there is\n// nothing else the statement can report.\nconst isSuccess = { isSuccess: true };\n\nconst generateInsertArray = (\n db: MySqlAsyncDatabase<any, any>,\n tableName: string,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n txCtx?: MutationTxCtx,\n policies?: ResolverPolicies,\n): CreatedResolver =>\n writeResolver<{ values: Record<string, any>[] }>({\n db,\n tableName,\n operation: 'insert',\n single: false,\n fieldName,\n txCtx,\n policies,\n args: {\n values: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(baseType))),\n },\n },\n run: async ({ executor, args, context, before, after }) => {\n const input = applyContextValuesAll(\n remapFromGraphQLArrayInput(args.values, table),\n policies?.contextValues?.(tableName),\n context,\n );\n if (!input.length) {\n throw drizzleError('No values were provided!', { code: 'DRIZZLE_NO_VALUES' });\n }\n await before();\n\n await executor.insert(table).values(input);\n\n await after();\n return isSuccess;\n },\n });\n\nconst generateInsertSingle = (\n db: MySqlAsyncDatabase<any, any>,\n tableName: string,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n txCtx?: MutationTxCtx,\n policies?: ResolverPolicies,\n): CreatedResolver =>\n writeResolver<{ values: Record<string, any> }>({\n db,\n tableName,\n operation: 'insert',\n single: true,\n fieldName,\n txCtx,\n policies,\n args: {\n values: {\n type: new GraphQLNonNull(baseType),\n },\n },\n run: async ({ executor, args, context, before, after }) => {\n await before();\n const input = applyContextValues(\n remapFromGraphQLSingleInput(args.values, table),\n policies?.contextValues?.(tableName),\n context,\n );\n\n await executor.insert(table).values(input);\n\n await after();\n return isSuccess;\n },\n });\n\nconst generateUpsert = (\n db: MySqlAsyncDatabase<any, any>,\n tableName: string,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n onConflictType: GraphQLInputObjectType,\n fieldName: string,\n single: boolean,\n txCtx?: MutationTxCtx,\n policies?: ResolverPolicies,\n): CreatedResolver => {\n const pkNames = mysqlPrimaryKeyPropNames(table);\n\n return writeResolver<{ values: Record<string, any> | Record<string, any>[]; onConflict?: OnConflictArg }>({\n db,\n tableName,\n operation: 'upsert',\n single,\n fieldName,\n txCtx,\n policies,\n args: {\n values: {\n type: single ? new GraphQLNonNull(baseType) : new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(baseType))),\n },\n onConflict: {\n type: onConflictType,\n description: 'How a conflicting row is resolved. Defaults to overwriting it.',\n },\n },\n run: async ({ executor, args, context, before, after }) => {\n const input = applyContextValuesAll(\n single\n ? [remapFromGraphQLSingleInput(args.values as Record<string, any>, table)]\n : remapFromGraphQLArrayInput(args.values as Record<string, any>[], table),\n policies?.contextValues?.(tableName),\n context,\n );\n if (!input.length) {\n throw drizzleError('No values were provided!', { code: 'DRIZZLE_NO_VALUES' });\n }\n await before();\n\n // MySQL's ON DUPLICATE KEY UPDATE fires on whichever unique key was violated, so\n // there is no target to resolve and no predicate to attach.\n const plan = resolveConflictPlan({\n table,\n values: input,\n onConflict: args.onConflict,\n pkNames,\n uniqueSets: [],\n excludedRef: mysqlValuesColumnRef,\n withTarget: false,\n });\n\n if (plan.action === 'NOTHING') {\n // INSERT IGNORE is the closest MySQL gets to DO NOTHING.\n await executor.insert(table).ignore().values(input);\n } else {\n await executor.insert(table).values(input).onDuplicateKeyUpdate({ set: plan.set });\n }\n\n await after();\n return isSuccess;\n },\n });\n};\n\nconst generateUpdate = (\n db: MySqlAsyncDatabase<any, any>,\n tableName: string,\n table: MySqlTable,\n setArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n single: boolean,\n requireWhere: boolean,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n policies?: ResolverPolicies,\n): CreatedResolver =>\n writeResolver<{ where?: Filters<Table>; set: Record<string, any> }>({\n db,\n tableName,\n operation: 'update',\n single,\n fieldName,\n txCtx,\n policies,\n args: {\n set: {\n type: new GraphQLNonNull(setArgs),\n },\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n },\n run: async ({ executor, args, context, before, after }) => {\n const { where, set } = args;\n const scope = policies?.scope?.(context);\n\n // A context-derived column is the server's to set, so an update never reassigns\n // one — that is what stops a row being handed to another owner.\n const input = stripContextValues(remapUpdateInput(set, table, tableName), policies?.contextValues?.(tableName));\n if (!Object.keys(input).length) {\n throw drizzleError('Unable to update with no values specified!', { code: 'DRIZZLE_NO_VALUES' });\n }\n await before();\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // The scope is ANDed on last, so a caller-supplied `where` can only narrow it.\n const filters = scopedWhere({\n scope,\n tableName,\n table,\n where,\n relationCtx,\n required: single || requireWhere,\n });\n\n if (single) {\n await assertSingleMatch(executor, table, filters!);\n }\n\n let query = executor.update(table).set(input);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n await query;\n\n await after();\n return isSuccess;\n },\n });\n\n/**\n * `update<Table>Many` — batch update with a per-entry `set` and `where`.\n *\n * The entries run as one UPDATE statement each, in input order, inside a single\n * transaction (a savepoint when the request context already carries one), so a failing\n * entry rolls the whole batch back and a row matched by several entries sees them applied\n * in order. MySQL has no RETURNING, so — like every other MySQL mutation — the result is\n * `{ isSuccess: true }` rather than the updated rows.\n */\nconst generateUpdateMany = (\n db: MySqlAsyncDatabase<any, any>,\n tableName: string,\n table: MySqlTable,\n updateManyInput: GraphQLInputObjectType,\n fieldName: string,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n policies?: ResolverPolicies,\n): CreatedResolver =>\n writeResolver<{ updates: { where?: Filters<Table>; set: Record<string, any> }[] }>({\n db,\n tableName,\n operation: 'updateMany',\n single: false,\n fieldName,\n txCtx,\n policies,\n args: {\n updates: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(updateManyInput))),\n },\n },\n run: async ({ executor, args, context, before, after }) => {\n const { updates } = args;\n if (!updates.length) {\n throw drizzleError('No updates were provided!', { code: 'DRIZZLE_NO_VALUES' });\n }\n await before();\n const scope = policies?.scope?.(context);\n const contextColumns = policies?.contextValues?.(tableName);\n\n // Remap and validate every entry before the transaction opens, so a malformed\n // entry rejects the request instead of rolling back mid-batch.\n const entries = updates.map(({ where, set }) => {\n const input = stripContextValues(remapUpdateInput(set, table, tableName), contextColumns);\n if (!Object.keys(input).length) {\n throw drizzleError('Unable to update with no values specified!', { code: 'DRIZZLE_NO_VALUES' });\n }\n return {\n set: input,\n filters: withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n ),\n };\n });\n\n // On a caller-supplied transaction — or the shared multi-mutation transaction\n // opened by `runMutation` — this opens a savepoint, so the batch stays atomic\n // without breaking the outer transaction.\n await executor.transaction(async (tx: any) => {\n for (const entry of entries) {\n let query = tx.update(table).set(entry.set);\n if (entry.filters) {\n query = query.where(entry.filters) as any;\n }\n await query;\n }\n });\n\n await after();\n return isSuccess;\n },\n });\n\n/**\n * `delete<Table>` and, for a table that declares a soft-delete column, `restore<Table>`.\n * MySQL's writes return no rows either way, so both answer `{ isSuccess: true }` — the\n * difference from the other dialects is only what the payload can say, not what runs.\n *\n * A table that opted into `hardDelete` also takes `hard: true`, which issues the real\n * `DELETE` instead of writing the marker, reading at `INCLUDE` so it reaches marked rows.\n */\nconst generateDelete = (\n db: MySqlAsyncDatabase<any, any>,\n tableName: string,\n table: MySqlTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n single: boolean,\n requireWhere: boolean,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n policies?: ResolverPolicies,\n restore: boolean = false,\n): CreatedResolver => {\n const softDelete = policies?.softDelete?.(tableName);\n const operation: WriteOperation = restore ? 'restore' : 'delete';\n // Only a soft-deleting table that opted in gets the argument, so the schema itself says\n // which tables can be purged — and `restore` never takes one, having nothing to remove.\n const canHardDelete = !restore && softDelete?.hardDelete === true;\n\n return writeResolver<{ where?: Filters<Table>; hard?: boolean }>({\n db,\n tableName,\n operation,\n single,\n fieldName,\n txCtx,\n policies,\n args: {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n ...(canHardDelete ? { hard: hardDeleteArg } : {}),\n },\n run: async ({ executor, args, context, before, after }) => {\n await before();\n const { where } = args;\n // `canHardDelete` decides whether the argument exists; this decides what it does,\n // so a stitched-in `hard: true` on a table that never opted in stays a soft delete.\n const hard = canHardDelete && args.hard === true;\n const scope = policies?.scope?.(context);\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // Same rule as update: the scope is ANDed on last, so a delete can only ever reach\n // rows inside it — an out-of-scope row is not matched rather than being refused.\n // A soft-deleting table adds the marker predicate the same way: `delete` only sees\n // rows that are not already marked, `restore` only sees the ones that are.\n const filters = scopedWhere({\n scope,\n tableName,\n table,\n where,\n relationCtx,\n required: single || requireWhere,\n // A hard delete reads at INCLUDE: the rows it mostly exists to remove are the\n // ones already marked, which the default EXCLUDE could not reach at all.\n deleted: restore ? 'ONLY' : hard ? 'INCLUDE' : undefined,\n });\n\n if (single) {\n await assertSingleMatch(executor, table, filters!);\n }\n\n let query =\n softDelete && !hard\n ? executor\n .update(table)\n .set({ [softDelete.columnName]: restore ? softDelete.writeRestored : softDelete.writeDeleted() })\n : executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n await query;\n\n await after();\n return isSuccess;\n },\n });\n};\n\n/** The dialect's table config, cached per table — see {@link memoizeTableConfig}. */\nconst getTableConfig = memoizeTableConfig(mysqlTableConfig);\n\n/** Primary-key property names for a MySQL table, including table-level composite keys. */\nconst mysqlPrimaryKeyPropNames = (table: MySqlTable): string[] =>\n getPrimaryKeyPropNamesFromConfig(table, getTableConfig);\n\n// MySQL sorts NULLs as the smallest values (first in ASC), and its writes return no rows.\nconst { prepareBuild, forEachTable, finalizeBuild } = createSchemaBuilder({\n tableClass: MySqlTable,\n getTableConfig,\n primaryKeyPropNames: mysqlPrimaryKeyPropNames,\n nullOrdering: 'nulls-smallest',\n returnsRows: false,\n // A nested write reads the key of the row it just wrote back out of the statement that\n // wrote it, which MySQL has no RETURNING clause for.\n preflight: (_db, options) => {\n if (options.features.nestedWrites) {\n throw new Error(\n 'Drizzle-GraphQL Error: features.nestedWrites is not supported on MySQL — a nested write needs the parent row it just inserted returned to it, and MySQL has no RETURNING clause.',\n );\n }\n },\n});\n\nexport const generateSchemaData = <\n TDrizzleInstance extends MySqlAsyncDatabase<any, any>,\n TSchema extends Record<string, Table | unknown>,\n>(\n db: TDrizzleInstance,\n schema: TSchema,\n relations: TablesRelationalConfig,\n options: SchemaGeneratorOptions,\n): GeneratedEntities<TDrizzleInstance, TSchema> => {\n const { prefixes } = options;\n\n // Table discovery, the relation graph, the per-build registries, the filter context, the\n // type cache and every table's types — all of it dialect-independent, so all of it lives\n // in `build-context.ts` and is shared with the PostgreSQL/SQLite builder.\n const ctx = prepareBuild(db, schema as Record<string, unknown>, relations, options);\n const { anyTable, filterCtx, policies, cacheCtx, mutationTxCtx, outputs } = ctx;\n\n // MySQL cannot return the rows a write touched, so every mutation reports only whether it\n // succeeded — one shared type for the whole build.\n const mutationReturnType = new GraphQLObjectType({\n name: cacheCtx.typeName({ kind: 'shared', defaultName: 'MutationReturn' }),\n fields: {\n isSuccess: {\n type: new GraphQLNonNull(GraphQLBoolean),\n },\n },\n });\n // Every MySQL mutation returns it, so it only belongs in the type map when at least one\n // mutation is generated.\n if ((['insert', 'upsert', 'update', 'delete'] as const).some((feature) => anyTable(feature))) {\n outputs['MutationReturn'] = mutationReturnType;\n }\n\n forEachTable(ctx, ({ tableName, tableFeatures, names, types, softDeleteInfo }) => {\n const { insertInput, updateInput, tableFilters } = types.inputs;\n const {\n typeName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n updateManyFieldName,\n updateSingleFieldName,\n updateCountFieldName,\n deleteFieldName,\n deleteSingleFieldName,\n restoreFieldName,\n restoreSingleFieldName,\n deleteCountFieldName,\n } = names;\n\n const insertArrGenerated = tableFeatures.insert\n ? generateInsertArray(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n createArrayFieldName,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const insertSingleGenerated = tableFeatures.insert\n ? generateInsertSingle(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n createSingleFieldName,\n mutationTxCtx,\n policies,\n )\n : undefined;\n // MySQL detects a conflict on any unique key, so unlike PostgreSQL and SQLite every\n // table can be upserted — there is no target to validate.\n const onConflictInput = tableFeatures.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as MySqlTable,\n tableName,\n typeName,\n uniqueSets: [],\n tableFilters,\n withTarget: false,\n cacheCtx,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n onConflictInput,\n upsertArrayFieldName,\n false,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const upsertSingleGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n onConflictInput,\n upsertSingleFieldName,\n true,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const updateGenerated = tableFeatures.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateFieldName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const updateSingleGenerated = tableFeatures.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n tableFeatures.update && tableFeatures.updateMany\n ? generateUpdateManyInput({\n tableName,\n typeName,\n updatePrefix: prefixes.update,\n updateInput,\n tableFilters,\n cacheCtx,\n })\n : undefined;\n const updateManyGenerated = updateManyInput\n ? generateUpdateMany(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateManyInput,\n updateManyFieldName,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const deleteGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteFieldName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const deleteSingleGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteSingleFieldName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const restoreGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n restoreFieldName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n const restoreSingleGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n restoreSingleFieldName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n // The count variants are the plural write with its payload left off, so each follows the\n // same feature switch — and the same scope, soft-delete, context-value and hook rules —\n // as the write it mirrors. No RETURNING here, so an `after` hook sees `rows: []`, exactly\n // as it does on the plural MySQL write.\n const updateCountGenerated =\n tableFeatures.update && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as MySqlTable,\n kind: 'update',\n setArgs: updateInput,\n filterArgs: tableFilters,\n fieldName: updateCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n policies,\n returnsRows: false,\n })\n : undefined;\n const deleteCountGenerated =\n tableFeatures.delete && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as MySqlTable,\n kind: 'delete',\n filterArgs: tableFilters,\n fieldName: deleteCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n policies,\n returnsRows: false,\n })\n : undefined;\n // Each mutation is paired with the identity it publishes on `extensions.drizzle`, so a\n // consumer can tell an insert from an upsert without unpicking the configured prefixes —\n // and, for a delete, whether the field can purge rather than mark. Every row-touching\n // mutation shares one return type here, since MySQL answers with `isSuccess` rather than\n // with rows; the count pair is the exception, returning `Int!` and marked `count: true`.\n const hardDeleteMeta = softDeleteInfo?.hardDelete ? ({ hardDelete: true } as const) : {};\n const withMeta = (generated: CreatedResolver | undefined, meta: DrizzleMutationMeta): MutationRegistration => ({\n generated,\n type: mutationReturnType,\n meta,\n });\n const generatedMutations: MutationRegistration[] = [\n withMeta(insertArrGenerated, { operation: 'insert', single: false, targetArg: 'values' }),\n withMeta(insertSingleGenerated, { operation: 'insert', single: true, targetArg: 'values' }),\n withMeta(upsertArrGenerated, { operation: 'upsert', single: false, targetArg: 'values' }),\n withMeta(upsertSingleGenerated, { operation: 'upsert', single: true, targetArg: 'values' }),\n withMeta(updateGenerated, { operation: 'update', single: false, targetArg: 'where' }),\n withMeta(updateManyGenerated, { operation: 'updateMany', single: false, targetArg: 'updates' }),\n withMeta(updateSingleGenerated, { operation: 'update', single: true, targetArg: 'where' }),\n withMeta(deleteGenerated, { operation: 'delete', single: false, targetArg: 'where', ...hardDeleteMeta }),\n withMeta(deleteSingleGenerated, { operation: 'delete', single: true, targetArg: 'where', ...hardDeleteMeta }),\n withMeta(restoreGenerated, { operation: 'restore', single: false, targetArg: 'where' }),\n withMeta(restoreSingleGenerated, { operation: 'restore', single: true, targetArg: 'where' }),\n {\n generated: updateCountGenerated,\n type: new GraphQLNonNull(GraphQLInt),\n meta: { operation: 'update', single: false, targetArg: 'where', count: true },\n description:\n 'How many rows the update touched. The rows themselves are not read back, which is the point of this mutation.',\n },\n {\n generated: deleteCountGenerated,\n type: new GraphQLNonNull(GraphQLInt),\n meta: { operation: 'delete', single: false, targetArg: 'where', count: true, ...hardDeleteMeta },\n description:\n 'How many rows the delete removed — or, on a soft-deleting table, marked deleted. The rows themselves are not read back, which is the point of this mutation.',\n },\n ];\n\n return { mutations: generatedMutations, onConflictInput, updateManyInput };\n });\n\n return finalizeBuild(ctx);\n};\n","// The five write resolvers PostgreSQL and SQLite generate identically.\n//\n// Both dialects insert/upsert/update/delete through the same drizzle-orm surface, so these\n// bodies were duplicated verbatim between pg.ts and sqlite.ts. The only differences were the\n// dialect spellings of `db` and `table` and how primary-key prop names are derived — the\n// first two collapse into the union/base types below, the third is the factory's parameter.\n// MySQL is NOT built from here: it has no RETURNING clause, so where these bodies read their\n// rows back out of the statement, MySQL's report `{ isSuccess }` — a genuinely different\n// shape, not a spelling difference. What all three dialects do share is the scaffolding\n// around the statement (hooks, transaction, error context), which lives in\n// `common/write-scaffold.ts` and wraps every body below.\n\nimport type { Table } from 'drizzle-orm';\nimport type { PgAsyncDatabase } from 'drizzle-orm/pg-core';\nimport type { SQLiteAsyncDatabase } from 'drizzle-orm/sqlite-core';\nimport { type GraphQLFieldConfigArgumentMap, type GraphQLInputObjectType, GraphQLList, GraphQLNonNull } from 'graphql';\nimport {\n remapFromGraphQLArrayInput,\n remapFromGraphQLSingleInput,\n remapToGraphQLArrayOutput,\n remapToGraphQLSingleOutput,\n} from '../data-mappers/index.ts';\nimport type { ResolveTree } from '../parse-resolve-info.ts';\nimport { parseResolveInfo } from '../parse-resolve-info.ts';\nimport {\n applyContextValues,\n applyContextValuesAll,\n applyObjectTypeName,\n assertSingleMatch,\n drizzleError,\n excludedColumnRef,\n extractFilters,\n extractSelectedColumnsFromTreeSQLFormat,\n hardDeleteArg,\n type LimitPolicyFor,\n type MutationTxCtx,\n mutationSelection,\n type OnConflictArg,\n type RelationFilterBase,\n type ResolverPolicies,\n relationFilterCtx,\n resolveConflictPlan,\n type SelectionCtx,\n scopedWhere,\n stripContextValues,\n type TypeNameMapper,\n type TypeNameResolver,\n type WriteOperation,\n withEagerRelations,\n withScope,\n writeResolver,\n} from './common.ts';\nimport { remapUpdateInput } from './field-updates.ts';\nimport { mergedOps, type NestedWriteRuntime, updateWithNestedOps, writeWithNestedOps } from './nested-writes.ts';\nimport type { CreatedResolver, Filters, TableNamedRelations } from './types.ts';\n\n/** Every database handle these resolvers can run on. `runMutation` takes `any`, so this is purely a call-site guard. */\nexport type WriteDatabase = PgAsyncDatabase<any, any> | SQLiteAsyncDatabase<any, any, any>;\n\n/**\n * The dialect's build-time primary-key lookup (`getTableConfig`-based, so it cannot be shared).\n * Typed on `any` because `PgTable` and `SQLiteTable` are unrelated subtypes of `Table`, and a\n * parameter of the base type would not accept either dialect's narrower function.\n */\n/**\n * What a write generator gets from the build rather than from the table. Every field is the\n * same for every table in one `buildSchema` call, so the call sites assemble it once and pass\n * it along unchanged — leaving each call to name only what actually varies per table.\n */\nexport interface WriteBuildOptions {\n db: WriteDatabase;\n /** Every table in the build — the relation columns a selection can reach live here. */\n tables: Record<string, Table>;\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n typeNameMapper?: TypeNameMapper;\n filterCtx?: RelationFilterBase;\n txCtx?: MutationTxCtx;\n nested?: NestedWriteRuntime;\n limits?: LimitPolicyFor;\n policies?: ResolverPolicies;\n /** The build's type-naming rule — the resolve tree is keyed by the names it produced. */\n resolveName?: TypeNameResolver;\n}\n\n/** The half of a write generator's options that changes from table to table. */\ninterface WriteTableOptions {\n tableName: string;\n table: Table;\n /** The mutation field's name, already run through the build's naming rules. */\n fieldName: string;\n typeName: string;\n /** One row in, one row out — as opposed to the list-shaped variant of the same mutation. */\n single: boolean;\n}\n\nexport interface InsertOptions extends WriteTableOptions {\n /** The table's create input, shared by both insert shapes and by the upsert. */\n baseType: GraphQLInputObjectType;\n /** Conflicting rows are skipped rather than failing the statement. */\n conflictDoNothing?: boolean;\n}\n\nexport interface UpsertOptions extends WriteTableOptions {\n baseType: GraphQLInputObjectType;\n onConflictType: GraphQLInputObjectType;\n uniqueSets: string[][];\n}\n\nexport interface UpdateOptions extends WriteTableOptions {\n setArgs: GraphQLInputObjectType;\n filterArgs: GraphQLInputObjectType;\n /** The table refuses an unfiltered write, so `where` is required even on the list shape. */\n requireWhere: boolean;\n}\n\nexport interface DeleteOptions extends WriteTableOptions {\n filterArgs: GraphQLInputObjectType;\n requireWhere: boolean;\n /** Builds `restore<Table>` — the same resolver reading and writing the other way. */\n restore?: boolean;\n selectionCtx?: SelectionCtx;\n}\n\nexport type PrimaryKeyPropNames = (table: any) => string[];\n\n/**\n * Binds the five resolvers to one dialect. Call once per dialect module and destructure the\n * result, so the generator call sites read exactly as they did when the functions were local.\n */\nexport const buildWriteResolvers = (primaryKeyPropNames: PrimaryKeyPropNames) => {\n /**\n * `insert<Table>` / `insert<Table>Single` — one generator for both shapes, the way\n * {@link generateUpsert} handles its pair. `single` decides the argument type, whether the\n * result is remapped as a row or a list, and whether an empty return is an error; the write\n * itself is the same multi-row statement either way, with the single variant supplying a\n * one-element list.\n */\n const generateInsert = (build: WriteBuildOptions, opts: InsertOptions): CreatedResolver => {\n const { db, tables, relationMap, typeNameMapper, txCtx, nested, limits, policies, resolveName } = build;\n const { tableName, table, baseType, fieldName, typeName, single, conflictDoNothing = false } = opts;\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: single ? new GraphQLNonNull(baseType) : new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(baseType))),\n },\n };\n\n // Primary-key prop names are constant per table — derive them once at build time\n // rather than re-running getTableConfig on every mutation request.\n const pkNames = primaryKeyPropNames(table);\n\n return writeResolver<{ values: Record<string, any> | Record<string, any>[] }>({\n db,\n tableName,\n operation: 'insert',\n single,\n fieldName,\n txCtx,\n policies,\n args: queryArgs,\n run: async ({ executor, args, context, info, before, after, returning: withHookReturning, output }) => {\n const supplied = single ? [args.values as Record<string, any>] : (args.values as Record<string, any>[]);\n if (!supplied.length) {\n throw drizzleError('No values were provided!', { code: 'DRIZZLE_NO_VALUES' });\n }\n await before();\n\n // Split each row's relation fields off its columns. Only when something is actually\n // nested does the write leave the single multi-row statement below.\n const entries = nested?.enabled(tableName)\n ? supplied.map((values) => nested.split(tableName, values))\n : undefined;\n const nestedEntries = entries?.some((entry) => nested!.hasOps(entry.ops)) ? entries : undefined;\n const contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntries\n ? []\n : applyContextValuesAll(\n remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table),\n contextColumns,\n context,\n );\n\n const { columns, hasRelations, withParams } = mutationSelection(info, {\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n resolveName,\n table,\n pkNames,\n limits,\n scope,\n defaultOrderBy: policies?.defaultOrderBy,\n });\n\n const returning = withHookReturning(\n nestedEntries ? nested!.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table) : columns,\n );\n\n const runInsert = async (target: any, values: Record<string, any>[]) => {\n let query = target.insert(table).values(values).returning(returning);\n if (conflictDoNothing) {\n query = query.onConflictDoNothing() as any;\n }\n return (await query) as Record<string, any>[];\n };\n\n const written = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: (tx, values) => runInsert(tx, [values]),\n request: { context, args, info },\n })\n : await runInsert(executor, input);\n\n await after(written);\n const result = output(written);\n\n if (single && !result[0]) {\n // Only reachable under `conflictDoNothing`, which is why the field is nullable\n // there and non-null everywhere else.\n if (!conflictDoNothing) {\n throw drizzleError('The insert returned no row.', { code: 'DRIZZLE_NO_ROW_RETURNED' });\n }\n return undefined;\n }\n\n const enriched = await withEagerRelations(executor, tableName, result, pkNames, withParams, hasRelations);\n\n return single\n ? remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap)\n : remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n },\n });\n };\n\n /**\n * `upsert<Table>` / `upsert<Table>Single` — an insert that resolves a unique-key conflict\n * the way the request's `onConflict` argument asks, rather than failing.\n *\n * Shares the insert input: an upsert supplies a whole row, same as a create.\n */\n const generateUpsert = (build: WriteBuildOptions, opts: UpsertOptions): CreatedResolver => {\n const { db, tables, relationMap, typeNameMapper, filterCtx, txCtx, nested, limits, policies, resolveName } = build;\n const { tableName, table, baseType, onConflictType, uniqueSets, fieldName, typeName, single } = opts;\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: single ? new GraphQLNonNull(baseType) : new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(baseType))),\n },\n onConflict: {\n type: onConflictType,\n description: 'How a conflicting row is resolved. Defaults to overwriting it on the primary key.',\n },\n };\n\n const pkNames = primaryKeyPropNames(table);\n\n return writeResolver<{ values: Record<string, any> | Record<string, any>[]; onConflict?: OnConflictArg }>({\n db,\n tableName,\n operation: 'upsert',\n single,\n fieldName,\n txCtx,\n policies,\n args: queryArgs,\n run: async ({ executor, args, context, info, before, after, returning: withHookReturning, output }) => {\n const supplied = single ? [args.values as Record<string, any>] : (args.values as Record<string, any>[]);\n if (!supplied.length) {\n throw drizzleError('No values were provided!', { code: 'DRIZZLE_NO_VALUES' });\n }\n await before();\n\n const entries = nested?.enabled(tableName)\n ? supplied.map((values) => nested.split(tableName, values))\n : undefined;\n const nestedEntries = entries?.some((entry) => nested!.hasOps(entry.ops)) ? entries : undefined;\n const contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntries\n ? []\n : applyContextValuesAll(\n remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table),\n contextColumns,\n context,\n );\n\n const { columns, hasRelations, withParams } = mutationSelection(info, {\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n resolveName,\n table,\n pkNames,\n limits,\n scope,\n defaultOrderBy: policies?.defaultOrderBy,\n });\n\n const returning = withHookReturning(\n nestedEntries ? nested!.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table) : columns,\n );\n\n // The conflict plan reads the columns the write actually supplies, so a nested write\n // — whose rows go in one at a time, each already carrying whatever its parent-side\n // operations produced — resolves its plan per row rather than once for the batch.\n const runUpsert = async (target: any, values: Record<string, any>[]) => {\n const plan = resolveConflictPlan({\n table,\n values,\n onConflict: args.onConflict,\n pkNames,\n uniqueSets,\n excludedRef: excludedColumnRef,\n withTarget: true,\n buildWhere: (where) => extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)),\n });\n\n let query = target.insert(table).values(values).returning(returning);\n // On conflict the statement updates a row that already exists, so the scope applies\n // to it exactly as it would to `update<Table>`: a conflicting row the caller cannot\n // see is left alone rather than taken over.\n const setWhere = withScope(scope, tableName, table, plan.setWhere);\n query =\n plan.action === 'NOTHING'\n ? (query.onConflictDoNothing(plan.target ? { target: plan.target } : undefined) as any)\n : (query.onConflictDoUpdate({ target: plan.target!, set: plan.set, setWhere }) as any);\n\n return (await query) as Record<string, any>[];\n };\n\n const written = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: (tx, values) => runUpsert(tx, [values]),\n request: { context, args, info },\n })\n : await runUpsert(executor, input);\n\n await after(written);\n const result = output(written);\n\n if (single && !result[0]) {\n return undefined;\n }\n\n const enriched = await withEagerRelations(executor, tableName, result, pkNames, withParams, hasRelations);\n\n return single\n ? remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap)\n : remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n },\n });\n };\n\n const generateUpdate = (build: WriteBuildOptions, opts: UpdateOptions): CreatedResolver => {\n const { db, tables, relationMap, typeNameMapper, filterCtx, txCtx, nested, limits, policies, resolveName } = build;\n const { tableName, table, setArgs, filterArgs, fieldName, typeName, single, requireWhere } = opts;\n const queryArgs = {\n set: {\n type: new GraphQLNonNull(setArgs),\n },\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n // Derived once at build time — PK prop names don't change per request.\n const pkNames = primaryKeyPropNames(table);\n\n return writeResolver<{ where?: Filters<Table>; set: Record<string, any> }>({\n db,\n tableName,\n operation: 'update',\n single,\n fieldName,\n txCtx,\n policies,\n args: queryArgs,\n run: async ({ executor, args, context, info, before, after, returning: withHookReturning, output }) => {\n const { where, set } = args;\n const scope = policies?.scope?.(context);\n await before();\n\n const { columns, hasRelations, withParams } = mutationSelection(info, {\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n resolveName,\n table,\n pkNames,\n limits,\n scope,\n defaultOrderBy: policies?.defaultOrderBy,\n });\n\n const entry = nested?.enabled(tableName) ? nested.split(tableName, set) : undefined;\n const nestedOps = entry && nested!.hasOps(entry.ops) ? entry.ops : undefined;\n // A context-derived column is the server's to set, so an update never reassigns\n // one — that is what stops a row being handed to another owner.\n const input = stripContextValues(\n remapUpdateInput(entry ? entry.columns : set, table, tableName),\n policies?.contextValues?.(tableName),\n );\n // A `set` that carries only nested operations is a legitimate update — of the\n // relation rather than of the row — so it is only empty when neither is present.\n if (!Object.keys(input).length && !nestedOps) {\n throw drizzleError('Unable to update with no values specified!', { code: 'DRIZZLE_NO_VALUES' });\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // The scope is ANDed on last, so a caller-supplied `where` can only narrow it.\n const filters = scopedWhere({\n scope,\n tableName,\n table,\n where,\n relationCtx,\n required: single || requireWhere,\n });\n\n if (single) {\n await assertSingleMatch(executor, table, filters!);\n }\n\n const returning = withHookReturning(\n nestedOps ? nested!.withJoinColumns(tableName, nestedOps, { ...columns }, table) : columns,\n );\n\n const runUpdate = async (target: any, values: Record<string, any>) => {\n // Nothing to write to the row itself: the operations attach to whatever the\n // `where` matched, so the rows are read rather than rewritten.\n const writes = Object.keys(values).length > 0;\n let query = writes ? target.update(table).set(values) : target.select(returning).from(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n return (await (writes ? (query.returning(returning) as any) : query)) as Record<string, any>[];\n };\n\n const written = nestedOps\n ? await updateWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n columns: input,\n ops: nestedOps,\n remapValues: (values) => values,\n write: runUpdate,\n request: { context, args, info },\n })\n : await runUpdate(executor, input);\n\n await after(written);\n const result = output(written);\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw drizzleError(\"'where' matched more than one row!\", { code: 'DRIZZLE_MULTI_ROW_MATCH' });\n }\n\n if (single && !result[0]) {\n return undefined;\n }\n\n const enriched = await withEagerRelations(executor, tableName, result, pkNames, withParams, hasRelations);\n\n return single\n ? remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap)\n : remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n },\n });\n };\n\n /**\n * `delete<Table>` and, for a table that declares a soft-delete column, `restore<Table>`.\n *\n * A soft-deleting table normally issues no `DELETE`: both mutations are an `UPDATE` of the\n * marker column, and the rows they return are the rows as they now stand. `restore` is the\n * same resolver reading the other way — it matches only marked rows (`deleted: ONLY`) and\n * writes the restored value.\n *\n * A table that opted into `hardDelete` also takes `hard: true`, which issues the real\n * `DELETE` — emptying the trash, reclaiming a unique key. It reads at `INCLUDE`, since the\n * rows it mostly exists to remove are the ones already marked; a `scope` still confines it.\n */\n const generateDelete = (build: WriteBuildOptions, opts: DeleteOptions): CreatedResolver => {\n const { db, filterCtx, txCtx, policies, resolveName } = build;\n const { tableName, table, filterArgs, fieldName, typeName, single, requireWhere, selectionCtx } = opts;\n const restore = opts.restore ?? false;\n const softDelete = policies?.softDelete?.(tableName);\n const operation: WriteOperation = restore ? 'restore' : 'delete';\n // Only a soft-deleting table that opted in gets the argument, so the schema itself says\n // which tables can be purged — and `restore` never takes one, having nothing to remove.\n const canHardDelete = !restore && softDelete?.hardDelete === true;\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n ...(canHardDelete ? { hard: hardDeleteArg } : {}),\n } as GraphQLFieldConfigArgumentMap;\n\n return writeResolver<{ where?: Filters<Table>; hard?: boolean }>({\n db,\n tableName,\n operation,\n single,\n fieldName,\n txCtx,\n policies,\n args: queryArgs,\n run: async ({ executor, args, context, info, before, after, returning: withHookReturning, output }) => {\n const { where } = args;\n // `canHardDelete` decides whether the argument exists; this decides what it does,\n // so a stitched-in `hard: true` on a table that never opted in stays a soft delete.\n const hard = canHardDelete && args.hard === true;\n const scope = policies?.scope?.(context);\n await before();\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const columns = extractSelectedColumnsFromTreeSQLFormat(\n parsedInfo.fieldsByTypeName[applyObjectTypeName(typeName, tableName, resolveName)]!,\n table,\n selectionCtx,\n );\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // Same rule as update: the scope is ANDed on last, so a delete can only ever reach\n // rows inside it — an out-of-scope row is not matched rather than being refused.\n // A soft-deleting table adds the marker predicate the same way: `delete` only sees\n // rows that are not already marked, `restore` only sees the ones that are.\n const filters = scopedWhere({\n scope,\n tableName,\n table,\n where,\n relationCtx,\n required: single || requireWhere,\n // A hard delete reads at INCLUDE: the rows it mostly exists to remove are the\n // ones already marked, which the default EXCLUDE could not reach at all.\n deleted: restore ? 'ONLY' : hard ? 'INCLUDE' : undefined,\n });\n\n if (single) {\n await assertSingleMatch(executor, table, filters!);\n }\n\n let query =\n softDelete && !hard\n ? executor.update(table).set({\n [softDelete.columnName]: restore ? softDelete.writeRestored : softDelete.writeDeleted(),\n })\n : executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n query = query.returning(withHookReturning(columns)) as any;\n\n const written = await query;\n\n await after(written);\n const result = output(written);\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw drizzleError(\"'where' matched more than one row!\", { code: 'DRIZZLE_MULTI_ROW_MATCH' });\n }\n\n if (single) {\n return result[0] ? remapToGraphQLSingleOutput(result[0], tableName, table) : undefined;\n }\n\n return remapToGraphQLArrayOutput(result, tableName, table);\n },\n });\n };\n return { generateInsert, generateUpsert, generateUpdate, generateDelete };\n};\n","// =============================================================================\n// `generateSchemaData` for the two dialects whose writes return the rows they\n// wrote — PostgreSQL and SQLite. They build a schema identically, so this module\n// holds it once and a dialect supplies only what it genuinely owns, through\n// {@link DialectSchemaAdapter}.\n//\n// The parts that are not even dialect-specific — everything up to each table's\n// types, the read fields, the per-table loop and the relation resolvers at the end\n// — live in `build-context.ts`, which MySQL shares. What remains here is the\n// mutation half, handed back to `forEachTable` for registration: MySQL has no\n// RETURNING clause, so its mutation fields, return types and resolvers differ\n// throughout.\n// =============================================================================\n\nimport type { Table } from 'drizzle-orm';\nimport type { GraphQLInputObjectType } from 'graphql';\nimport { GraphQLInt, GraphQLList, GraphQLNonNull } from 'graphql';\nimport {\n generateOnConflictInput,\n generateUpdateManyInput,\n generateWriteCount,\n getUniqueColumnSets,\n type TablesRelationalConfig,\n} from '../builders/common.ts';\nimport { createSchemaBuilder, type MutationRegistration, type SchemaBuildAdapter } from './build-context.ts';\nimport type { CreatedResolver, SchemaGeneratorOptions } from './types.ts';\nimport { buildWriteResolvers, type WriteBuildOptions } from './write-resolvers.ts';\n\n/** The per-table half of {@link UpdateManyGenerator}'s options; the rest comes from the build. */\nexport interface UpdateManyOptions {\n tableName: string;\n table: any;\n updateManyInput: GraphQLInputObjectType;\n fieldName: string;\n typeName: string;\n}\n\n/** `update<Table>Many` — batch update, whose statement loop is dialect-specific. */\nexport type UpdateManyGenerator = (build: WriteBuildOptions, opts: UpdateManyOptions) => CreatedResolver;\n\n/**\n * Everything {@link createSchemaDataGenerator} cannot decide for itself: the shared build's\n * adapter, plus the one generator whose statement loop is dialect-specific. Both dialects on\n * this path return the rows they write, so it is fixed to `true`.\n */\nexport type DialectSchemaAdapter = SchemaBuildAdapter<true> & {\n generateUpdateMany: UpdateManyGenerator;\n};\n\n/**\n * Binds an adapter and returns the dialect's `generateSchemaData` implementation.\n *\n * Called once per dialect module at import time, so the write resolvers — which close\n * over the dialect's primary-key lookup — are built once rather than per `buildSchema`.\n */\nexport const createSchemaDataGenerator = (adapter: DialectSchemaAdapter) => {\n const primaryKeyPropNames = adapter.primaryKeyPropNames;\n const uniqueColumnSets = (table: Table): string[][] => getUniqueColumnSets(table, adapter.getTableConfig);\n const { generateInsert, generateUpsert, generateUpdate, generateDelete } = buildWriteResolvers(primaryKeyPropNames);\n // The three stretches of a build that have nothing to do with the dialect: everything up to\n // each table's types, the read fields in the middle, and the relation resolvers at the end.\n const { prepareBuild, forEachTable, finalizeBuild } = createSchemaBuilder(adapter);\n\n return (\n db: any,\n schema: Record<string, unknown>,\n relations: TablesRelationalConfig,\n options: SchemaGeneratorOptions,\n ): any => {\n const { prefixes, conflictDoNothing, typeNameMapper, limits } = options;\n\n // Table discovery, the relation graph, the per-build registries, the filter context, the\n // type cache and every table's types — all of it dialect-independent, so all of it lives\n // in `build-context.ts` and is shared with the MySQL builder.\n const ctx = prepareBuild(db, schema, relations, options);\n const { tables, eagerRelations, filterCtx, policies, namedRelations, cacheCtx, nestedRuntime, mutationTxCtx } = ctx;\n\n // Everything a write generator takes from the build rather than from the table. The same\n // object serves every table below, so each call names only what varies per table.\n const writeBuild: WriteBuildOptions = {\n db,\n tables,\n relationMap: eagerRelations,\n typeNameMapper,\n filterCtx,\n txCtx: mutationTxCtx,\n nested: nestedRuntime,\n limits,\n policies,\n resolveName: cacheCtx.typeName,\n };\n\n forEachTable(ctx, ({ tableName, tableFeatures, names, types, softDeleteInfo }) => {\n const { insertInput, updateInput, tableFilters } = types.inputs;\n const { singleTableItemOutput, arrTableItemOutput } = types.outputs;\n const {\n typeName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n updateManyFieldName,\n updateSingleFieldName,\n updateCountFieldName,\n deleteFieldName,\n deleteSingleFieldName,\n restoreFieldName,\n restoreSingleFieldName,\n deleteCountFieldName,\n } = names;\n\n const insertArrGenerated = tableFeatures.insert\n ? generateInsert(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n baseType: insertInput,\n fieldName: createArrayFieldName,\n typeName,\n single: false,\n conflictDoNothing,\n })\n : undefined;\n const insertSingleGenerated = tableFeatures.insert\n ? generateInsert(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n baseType: insertInput,\n fieldName: createSingleFieldName,\n typeName,\n single: true,\n conflictDoNothing,\n })\n : undefined;\n // An upsert needs something to conflict on, so a table with no primary key and no\n // unique constraint gets no upsert mutations rather than ones that always fail.\n const uniqueSets = tableFeatures.upsert ? uniqueColumnSets(schema[tableName] as Table) : [];\n const onConflictInput = tableFeatures.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as Table,\n tableName,\n typeName,\n uniqueSets,\n tableFilters,\n withTarget: true,\n cacheCtx,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n baseType: insertInput,\n onConflictType: onConflictInput,\n uniqueSets,\n fieldName: upsertArrayFieldName,\n typeName,\n single: false,\n })\n : undefined;\n const upsertSingleGenerated = onConflictInput\n ? generateUpsert(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n baseType: insertInput,\n onConflictType: onConflictInput,\n uniqueSets,\n fieldName: upsertSingleFieldName,\n typeName,\n single: true,\n })\n : undefined;\n const updateGenerated = tableFeatures.update\n ? generateUpdate(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n setArgs: updateInput,\n filterArgs: tableFilters,\n fieldName: updateFieldName,\n typeName,\n single: false,\n requireWhere: tableFeatures.requireWhere,\n })\n : undefined;\n const updateSingleGenerated = tableFeatures.update\n ? generateUpdate(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n setArgs: updateInput,\n filterArgs: tableFilters,\n fieldName: updateSingleFieldName,\n typeName,\n single: true,\n requireWhere: tableFeatures.requireWhere,\n })\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n tableFeatures.update && tableFeatures.updateMany\n ? generateUpdateManyInput({\n tableName,\n typeName,\n updatePrefix: prefixes.update,\n updateInput,\n tableFilters,\n cacheCtx,\n })\n : undefined;\n const updateManyGenerated = updateManyInput\n ? adapter.generateUpdateMany(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n updateManyInput,\n fieldName: updateManyFieldName,\n typeName,\n })\n : undefined;\n const deleteGenerated = tableFeatures.delete\n ? generateDelete(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n filterArgs: tableFilters,\n fieldName: deleteFieldName,\n typeName,\n single: false,\n requireWhere: tableFeatures.requireWhere,\n restore: false,\n selectionCtx: { tableName, relationMap: namedRelations, tables },\n })\n : undefined;\n const deleteSingleGenerated = tableFeatures.delete\n ? generateDelete(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n filterArgs: tableFilters,\n fieldName: deleteSingleFieldName,\n typeName,\n single: true,\n requireWhere: tableFeatures.requireWhere,\n restore: false,\n selectionCtx: { tableName, relationMap: namedRelations, tables },\n })\n : undefined;\n const restoreGenerated = softDeleteInfo\n ? generateDelete(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n filterArgs: tableFilters,\n fieldName: restoreFieldName,\n typeName,\n single: false,\n requireWhere: tableFeatures.requireWhere,\n restore: true,\n selectionCtx: { tableName, relationMap: namedRelations, tables },\n })\n : undefined;\n const restoreSingleGenerated = softDeleteInfo\n ? generateDelete(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n filterArgs: tableFilters,\n fieldName: restoreSingleFieldName,\n typeName,\n single: true,\n requireWhere: tableFeatures.requireWhere,\n restore: true,\n selectionCtx: { tableName, relationMap: namedRelations, tables },\n })\n : undefined;\n // The count variants are the plural write with its payload left off, so each follows the\n // same feature switch — and the same scope, soft-delete, context-value and hook rules —\n // as the write it mirrors.\n const updateCountGenerated =\n tableFeatures.update && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as Table,\n kind: 'update',\n setArgs: updateInput,\n filterArgs: tableFilters,\n fieldName: updateCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n nested: nestedRuntime,\n policies,\n pkNames: primaryKeyPropNames(schema[tableName] as Table),\n returnsRows: true,\n })\n : undefined;\n const deleteCountGenerated =\n tableFeatures.delete && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as Table,\n kind: 'delete',\n filterArgs: tableFilters,\n fieldName: deleteCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n policies,\n pkNames: primaryKeyPropNames(schema[tableName] as Table),\n returnsRows: true,\n })\n : undefined;\n // Each mutation is paired with the type it returns and the identity it publishes on\n // `extensions.drizzle`, so a consumer can tell an insert from an upsert without unpicking\n // the configured prefixes — and, for a delete, whether the field can purge rather than\n // mark. The count pair publishes its plural sibling's identity plus `count: true`, so a\n // wrapper gating on `operation` sees it as the write it is.\n const hardDeleteMeta = softDeleteInfo?.hardDelete ? ({ hardDelete: true } as const) : {};\n const generatedMutations: MutationRegistration[] = [\n {\n generated: insertArrGenerated,\n type: arrTableItemOutput,\n meta: { operation: 'insert', single: false, targetArg: 'values' },\n },\n {\n generated: insertSingleGenerated,\n // An insert either returns the row it inserted or throws — the one path to `null` is\n // `conflictDoNothing` swallowing the insert, so the field is nullable only there.\n type: conflictDoNothing ? singleTableItemOutput : new GraphQLNonNull(singleTableItemOutput),\n meta: { operation: 'insert', single: true, targetArg: 'values' },\n },\n {\n generated: upsertArrGenerated,\n type: arrTableItemOutput,\n meta: { operation: 'upsert', single: false, targetArg: 'values' },\n },\n {\n generated: upsertSingleGenerated,\n type: singleTableItemOutput,\n meta: { operation: 'upsert', single: true, targetArg: 'values' },\n },\n {\n generated: updateGenerated,\n type: arrTableItemOutput,\n meta: { operation: 'update', single: false, targetArg: 'where' },\n },\n {\n generated: updateManyGenerated,\n type: new GraphQLNonNull(new GraphQLList(singleTableItemOutput)),\n meta: { operation: 'updateMany', single: false, targetArg: 'updates' },\n // The nullable element is deliberate, and the reason this mutation's return type\n // differs from every sibling's: the result is aligned with the input, one slot per\n // entry, so an entry that matched nothing has to be able to say so.\n description:\n \"Each entry's updated rows, in entry order. An entry whose `where` matched no rows contributes `null` in its slot; an entry that matched several contributes each of its rows.\",\n },\n {\n generated: updateSingleGenerated,\n type: singleTableItemOutput,\n meta: { operation: 'update', single: true, targetArg: 'where' },\n },\n {\n generated: deleteGenerated,\n type: arrTableItemOutput,\n meta: { operation: 'delete', single: false, targetArg: 'where', ...hardDeleteMeta },\n },\n {\n generated: deleteSingleGenerated,\n type: singleTableItemOutput,\n meta: { operation: 'delete', single: true, targetArg: 'where', ...hardDeleteMeta },\n },\n {\n generated: restoreGenerated,\n type: arrTableItemOutput,\n meta: { operation: 'restore', single: false, targetArg: 'where' },\n },\n {\n generated: restoreSingleGenerated,\n type: singleTableItemOutput,\n meta: { operation: 'restore', single: true, targetArg: 'where' },\n },\n {\n generated: updateCountGenerated,\n type: new GraphQLNonNull(GraphQLInt),\n meta: { operation: 'update', single: false, targetArg: 'where', count: true },\n description:\n 'How many rows the update touched. The rows themselves are not read back, which is the point of this mutation.',\n },\n {\n generated: deleteCountGenerated,\n type: new GraphQLNonNull(GraphQLInt),\n meta: { operation: 'delete', single: false, targetArg: 'where', count: true, ...hardDeleteMeta },\n description:\n 'How many rows the delete removed — or, on a soft-deleting table, marked deleted. The rows themselves are not read back, which is the point of this mutation.',\n },\n ];\n\n return { mutations: generatedMutations, onConflictInput, updateManyInput };\n });\n\n return finalizeBuild(ctx);\n };\n};\n","// =============================================================================\n// The dialect-independent half of `update<Table>Many`.\n//\n// PostgreSQL and SQLite build this resolver identically right up to the point\n// where the entries actually execute — argument parsing, the per-entry remap\n// and validation, the nested-write split, the write hooks, relation\n// enrichment and the per-entry output slots are all the same. The two dialects\n// differ only in HOW the batch runs inside its transaction, which is what\n// {@link UpdateManyBatchRunner} abstracts.\n// =============================================================================\n\nimport type { Table } from 'drizzle-orm';\nimport type { GraphQLFieldConfigArgumentMap } from 'graphql';\nimport { GraphQLList, GraphQLNonNull } from 'graphql';\nimport {\n drizzleError,\n extractFilters,\n mutationSelection,\n relationFilterCtx,\n stripContextValues,\n withEagerRelations,\n withScope,\n writeResolver,\n} from '../builders/common.ts';\nimport { remapToGraphQLSingleOutput } from '../data-mappers/index.ts';\nimport { remapUpdateInput } from './field-updates.ts';\nimport { mergedOps, type NestedWriteRequest, type NestedWriteRuntime } from './nested-writes.ts';\nimport type { UpdateManyGenerator, UpdateManyOptions } from './schema-data.ts';\nimport type { CreatedResolver, Filters } from './types.ts';\nimport type { WriteBuildOptions } from './write-resolvers.ts';\n\n/** One entry of the `updates` argument, already remapped and validated. */\nexport type UpdateManyEntry = {\n /** Column values to write, context-supplied columns stripped. */\n set: Record<string, any>;\n /** Nested-write operations, or `undefined` when the entry writes columns only. */\n ops: Record<string, any> | undefined;\n /** The entry's `where`, already combined with the row scope. */\n filters: any;\n};\n\n/** Everything a batch runner needs; assembled by the shared resolver before the batch opens. */\nexport type UpdateManyBatchCtx = {\n /** The executor the mutation runs on — `db`, a caller's transaction, or the shared one. */\n executor: any;\n entries: UpdateManyEntry[];\n table: any;\n /** The columns each statement returns, join columns included when nested writes are on. */\n returning: Record<string, any>;\n /** True when at least one entry carries nested-write operations. */\n anyNested: boolean;\n nested: NestedWriteRuntime | undefined;\n tableName: string;\n /** The request the nested writes run for — its context, and what their hooks are handed. */\n request: NestedWriteRequest;\n};\n\n/** Runs the entries and returns each one's rows, in entry order. */\nexport type UpdateManyBatchRunner = (ctx: UpdateManyBatchCtx) => Promise<Record<string, any>[][]>;\n\n/**\n * The batch runner for a dialect whose driver is always asynchronous: one UPDATE per entry,\n * awaited in input order, inside a single transaction. On a caller-supplied transaction — or\n * the shared multi-mutation transaction opened by `runMutation` — this opens a savepoint, so\n * the batch stays atomic without breaking the outer transaction.\n */\nexport const runUpdateManyBatch: UpdateManyBatchRunner = ({\n executor,\n entries,\n table,\n returning,\n nested,\n tableName,\n request,\n}) =>\n executor.transaction(async (tx: any) => {\n const results: Record<string, any>[][] = [];\n for (const entry of entries) {\n const values = entry.ops\n ? { ...entry.set, ...(await nested!.applyParentSide(tx, tableName, entry.ops, request)) }\n : entry.set;\n\n // Same as the single update: an entry with no column values reads the rows its\n // `where` matched so the nested operations have something to attach to.\n const writes = Object.keys(values).length > 0;\n let query = writes ? tx.update(table).set(values) : tx.select(returning).from(table);\n if (entry.filters) {\n query = query.where(entry.filters) as any;\n }\n const rows = (await (writes ? (query.returning(returning) as any) : query)) as Record<string, any>[];\n\n if (entry.ops) {\n await nested!.applyChildSide(tx, tableName, entry.ops, rows, request);\n }\n results.push(rows);\n }\n return results;\n });\n\n/**\n * Builds a dialect's `update<Table>Many` generator.\n *\n * `update<Table>Many` is a batch update with a per-entry `set` and `where`. The entries run\n * as one UPDATE statement each, in input order, inside a single transaction (a savepoint when\n * the request context already carries one), so a failing entry rolls the whole batch back and\n * a row matched by several entries sees them applied in order. The result lists each entry's\n * updated rows in entry order, with `null` standing in for an entry whose `where` matched no\n * rows, so the common one-row-per-entry case stays aligned with the input.\n *\n * @param primaryKeyPropNames the dialect's composite-aware primary-key lookup\n * @param runBatch how the entries execute; defaults to {@link runUpdateManyBatch}\n */\nexport const createUpdateManyGenerator = (\n primaryKeyPropNames: (table: any) => string[],\n runBatch: UpdateManyBatchRunner = runUpdateManyBatch,\n): UpdateManyGenerator => {\n return (build: WriteBuildOptions, opts: UpdateManyOptions): CreatedResolver => {\n const { db, tables, relationMap, typeNameMapper, filterCtx, txCtx, nested, limits, policies, resolveName } = build;\n const { tableName, table, updateManyInput, fieldName, typeName } = opts;\n const queryArgs = {\n updates: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(updateManyInput))),\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n // Derived once at build time — PK prop names don't change per request.\n const pkNames = primaryKeyPropNames(table);\n\n return writeResolver<{ updates: { where?: Filters<Table>; set: Record<string, any> }[] }>({\n db,\n tableName,\n operation: 'updateMany',\n single: false,\n fieldName,\n txCtx,\n policies,\n args: queryArgs,\n run: async ({\n executor,\n args,\n context,\n info,\n before,\n after,\n returning: withHookReturning,\n output: withoutHookColumns,\n }) => {\n const { updates } = args;\n if (!updates.length) {\n throw drizzleError('No updates were provided!', { code: 'DRIZZLE_NO_VALUES' });\n }\n await before();\n const scope = policies?.scope?.(context);\n const contextColumns = policies?.contextValues?.(tableName);\n\n const { columns, hasRelations, withParams } = mutationSelection(info, {\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n resolveName,\n table,\n pkNames,\n limits,\n scope,\n defaultOrderBy: policies?.defaultOrderBy,\n });\n\n // Remap and validate every entry before the transaction opens, so a malformed\n // entry rejects the request instead of rolling back mid-batch.\n const entries: UpdateManyEntry[] = updates.map(({ where, set }) => {\n const split = nested?.enabled(tableName) ? nested.split(tableName, set) : undefined;\n const ops = split && nested!.hasOps(split.ops) ? split.ops : undefined;\n const input = stripContextValues(\n remapUpdateInput(split ? split.columns : set, table, tableName),\n contextColumns,\n );\n // An entry that only writes through a relation still has work to do.\n if (!Object.keys(input).length && !ops) {\n throw drizzleError('Unable to update with no values specified!', { code: 'DRIZZLE_NO_VALUES' });\n }\n return {\n set: input,\n ops,\n filters: withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n ),\n };\n });\n\n const anyNested = entries.some((entry) => entry.ops);\n const returning = withHookReturning(\n anyNested\n ? nested!.withJoinColumns(\n tableName,\n mergedOps(entries.map((entry) => ({ ops: entry.ops ?? {} }))),\n { ...columns },\n table,\n )\n : columns,\n );\n\n const perEntry = await runBatch({\n executor,\n entries,\n table,\n returning,\n anyNested,\n nested,\n tableName,\n request: { context, args, info },\n });\n\n const written = perEntry.flat();\n await after(written);\n const flatRows = withoutHookColumns(written);\n\n const enriched = await withEagerRelations(executor, tableName, flatRows, pkNames, withParams, hasRelations);\n\n // Rebuild the per-entry slots: a no-match entry contributes `null`, a multi-match\n // entry contributes each of its rows.\n const output: (Record<string, any> | null)[] = [];\n let offset = 0;\n for (const rows of perEntry) {\n if (!rows.length) {\n output.push(null);\n continue;\n }\n for (let i = 0; i < rows.length; i++) {\n output.push(remapToGraphQLSingleOutput(enriched[offset + i], tableName, table, relationMap));\n }\n offset += rows.length;\n }\n return output;\n },\n });\n };\n};\n","import type { Table } from 'drizzle-orm';\nimport { type PgAsyncDatabase, PgTable, getTableConfig as pgTableConfig } from 'drizzle-orm/pg-core';\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n getPrimaryKeyPropNamesFromConfig,\n memoizeTableConfig,\n type TablesRelationalConfig,\n} from '../builders/common.ts';\nimport { createSchemaDataGenerator } from './schema-data.ts';\nimport type { SchemaGeneratorOptions } from './types.ts';\nimport { createUpdateManyGenerator } from './update-many.ts';\n\n/** The dialect's table config, cached per table — see {@link memoizeTableConfig}. */\nconst getTableConfig = memoizeTableConfig(pgTableConfig);\n\n/** Primary-key property names for a PG table, including table-level composite keys. */\nconst pgPrimaryKeyPropNames = (table: PgTable): string[] => getPrimaryKeyPropNamesFromConfig(table, getTableConfig);\n\nconst generateUpdateMany = createUpdateManyGenerator(pgPrimaryKeyPropNames);\n\nconst pgSchemaData = createSchemaDataGenerator({\n tableClass: PgTable,\n getTableConfig,\n primaryKeyPropNames: pgPrimaryKeyPropNames,\n // PostgreSQL sorts NULLs as the largest values (last in ASC).\n nullOrdering: 'nulls-largest',\n // Writes come back with their rows, so the table types carry the `${Table}Item` outputs.\n returnsRows: true,\n generateUpdateMany,\n});\n\nexport const generateSchemaData = <\n TDrizzleInstance extends PgAsyncDatabase<any, any>,\n TSchema extends Record<string, Table | unknown>,\n>(\n db: TDrizzleInstance,\n schema: TSchema,\n relations: TablesRelationalConfig,\n options: SchemaGeneratorOptions,\n): GeneratedEntities<TDrizzleInstance, TSchema> => pgSchemaData(db, schema, relations, options);\n","import type { Table } from 'drizzle-orm';\nimport { type SQLiteAsyncDatabase, SQLiteTable, getTableConfig as sqliteTableConfig } from 'drizzle-orm/sqlite-core';\n\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n getPrimaryKeyPropNamesFromConfig,\n memoizeTableConfig,\n type TablesRelationalConfig,\n} from '../builders/common.ts';\nimport { createSchemaDataGenerator } from './schema-data.ts';\nimport type { SchemaGeneratorOptions } from './types.ts';\nimport { createUpdateManyGenerator, type UpdateManyBatchRunner, type UpdateManyEntry } from './update-many.ts';\n\n/** The dialect's table config, cached per table — see {@link memoizeTableConfig}. */\nconst getTableConfig = memoizeTableConfig(sqliteTableConfig);\n\n/** Primary-key property names for a SQLite table, including table-level composite keys. */\nconst sqlitePrimaryKeyPropNames = (table: SQLiteTable): string[] =>\n getPrimaryKeyPropNamesFromConfig(table, getTableConfig);\n\n/**\n * SQLite's batch runner. A synchronous driver (better-sqlite3) commits the moment its\n * transaction callback returns, so that callback must not be async — an awaited statement\n * would run after the COMMIT. The driver kind is probed from the first statement's result\n * rather than declared, so the same resolver serves both driver families.\n */\nconst runSqliteUpdateManyBatch: UpdateManyBatchRunner = ({\n executor,\n entries,\n table,\n returning,\n anyNested,\n nested,\n tableName,\n request,\n}) => {\n const runEntry = (tx: any, entry: UpdateManyEntry) => {\n let query = tx.update(table).set(entry.set);\n if (entry.filters) {\n query = query.where(entry.filters);\n }\n // `.all()` instead of awaiting the thenable: a sync driver executes it immediately,\n // which is the only way the statement still runs inside the native transaction below.\n return query.returning(returning).all();\n };\n\n // Nested writes need statements interleaved with awaited reads, which only an async driver\n // can do inside a transaction — `features.nestedWrites` rejects a sync driver at build\n // time, so this path is always on one.\n const runNestedEntry = async (tx: any, entry: UpdateManyEntry) => {\n const values = entry.ops\n ? { ...entry.set, ...(await nested!.applyParentSide(tx, tableName, entry.ops, request)) }\n : entry.set;\n\n // Same as the single update: an entry with no column values reads the rows its `where`\n // matched so the nested operations have something to attach to.\n const writes = Object.keys(values).length > 0;\n let query = writes ? tx.update(table).set(values) : tx.select(returning).from(table);\n if (entry.filters) {\n query = query.where(entry.filters);\n }\n const rows = (await (writes ? query.returning(returning) : query)) as Record<string, any>[];\n\n if (entry.ops) {\n await nested!.applyChildSide(tx, tableName, entry.ops, rows, request);\n }\n return rows;\n };\n\n // On a caller-supplied transaction — or the shared multi-mutation transaction opened by\n // `runMutation` — this opens a savepoint, so the batch stays atomic without breaking the\n // outer transaction.\n return executor.transaction((tx: any) => {\n if (anyNested) {\n return (async () => {\n const results: Record<string, any>[][] = [];\n for (const entry of entries) {\n results.push(await runNestedEntry(tx, entry));\n }\n return results;\n })();\n }\n\n const first = runEntry(tx, entries[0]!);\n if (typeof (first as any)?.then === 'function') {\n // Async driver: await sequentially so the entries apply in input order.\n return (async () => {\n const results: Record<string, any>[][] = [await first];\n for (let i = 1; i < entries.length; i++) {\n results.push(await runEntry(tx, entries[i]!));\n }\n return results;\n })();\n }\n const results: Record<string, any>[][] = [first];\n for (let i = 1; i < entries.length; i++) {\n results.push(runEntry(tx, entries[i]!));\n }\n return results;\n });\n};\n\nconst generateUpdateMany = createUpdateManyGenerator(sqlitePrimaryKeyPropNames, runSqliteUpdateManyBatch);\n\nconst sqliteSchemaData = createSchemaDataGenerator({\n tableClass: SQLiteTable,\n getTableConfig,\n primaryKeyPropNames: sqlitePrimaryKeyPropNames,\n // SQLite sorts NULLs as the smallest values (first in ASC).\n nullOrdering: 'nulls-smallest',\n // Writes come back with their rows, so the table types carry the `${Table}Item` outputs.\n returnsRows: true,\n // A synchronous driver (e.g. better-sqlite3) commits the moment its transaction callback\n // returns, so it can neither interleave awaited statements inside one transaction nor hold\n // one open across resolver calls — which is what both of these features require.\n preflight: (db, options) => {\n if (options.features.nestedWrites && (db as any).resultKind === 'sync') {\n throw new Error(\n 'Drizzle-GraphQL Error: features.nestedWrites requires an asynchronous SQLite driver (e.g. libsql). Synchronous drivers cannot run the multi-statement transaction a nested write needs.',\n );\n }\n if (options.transactions && (db as any).resultKind === 'sync') {\n throw new Error(\n \"Drizzle-GraphQL Error: transactions: 'auto' requires an asynchronous SQLite driver (e.g. libsql). Synchronous drivers cannot hold a transaction open across resolvers.\",\n );\n }\n },\n generateUpdateMany,\n});\n\nexport const generateSchemaData = <\n TDrizzleInstance extends SQLiteAsyncDatabase<any, any, any>,\n TSchema extends Record<string, Table | unknown>,\n>(\n db: TDrizzleInstance,\n schema: TSchema,\n relations: TablesRelationalConfig,\n options: SchemaGeneratorOptions,\n): GeneratedEntities<TDrizzleInstance, TSchema> => sqliteSchemaData(db, schema, relations, options);\n","import { is, Table } from 'drizzle-orm';\nimport { MySqlAsyncDatabase, getTableConfig as mysqlTableConfig } from 'drizzle-orm/mysql-core';\nimport { PgAsyncDatabase, getTableConfig as pgTableConfig } from 'drizzle-orm/pg-core';\nimport { SQLiteAsyncDatabase, getTableConfig as sqliteTableConfig } from 'drizzle-orm/sqlite-core';\nimport type { GraphQLResolveInfo } from 'graphql';\nimport type { AnyDrizzleDB } from '../types.ts';\nimport {\n attachTargetPrimaryKeys,\n buildNamedRelations,\n type DerivedTypeNameMapper,\n extractRelationsParams,\n getPrimaryKeyPropNamesFromConfig,\n memoizeTableConfig,\n type RelationFilterBase,\n resolveGeneratedTypeNames,\n resolveObjectTypeName,\n runRelationalSelect,\n type TypeNameMapper,\n type TypeNameResolver,\n} from './builders/common.ts';\nimport type { TableNamedRelations } from './builders/types.ts';\nimport { parseResolveInfo, type ResolveTree } from './parse-resolve-info.ts';\n\n/**\n * Everything the translation needs about a drizzle instance: the tables it holds, the\n * relation graph in this library's canonical shape, and the filter context that lets a\n * nested `where` reach a relation's target table. Derived once per instance — the same\n * derivation `buildSchema` does — and cached, since an overriding resolver calls this on\n * every request.\n */\ntype SelectionContext = {\n tables: Record<string, Table>;\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n filterCtx: RelationFilterBase;\n primaryKeyOf: (tableName: string) => readonly string[];\n};\n\nconst contextCache = new WeakMap<object, SelectionContext>();\n\ntype TableConfigLookup = (table: Table) => { primaryKeys: { columns: { name: string }[] }[] };\n\n// Cached per table, and bound at module scope so the cache is shared with every selection\n// this process translates — the same memoization each dialect builder applies.\nconst getMySqlTableConfig = memoizeTableConfig(mysqlTableConfig as unknown as TableConfigLookup);\nconst getPgTableConfig = memoizeTableConfig(pgTableConfig as unknown as TableConfigLookup);\nconst getSQLiteTableConfig = memoizeTableConfig(sqliteTableConfig as unknown as TableConfigLookup);\n\n/** The dialect's `getTableConfig`, which is the only place a composite primary key shows up. */\nconst tableConfigFor = (db: AnyDrizzleDB<any>): TableConfigLookup => {\n if (is(db, MySqlAsyncDatabase)) {\n return getMySqlTableConfig;\n }\n if (is(db, PgAsyncDatabase)) {\n return getPgTableConfig;\n }\n if (is(db, SQLiteAsyncDatabase)) {\n return getSQLiteTableConfig;\n }\n throw new Error('Drizzle-GraphQL Error: unsupported database instance — expected a PostgreSQL, MySQL or SQLite one.');\n};\n\nconst contextFor = (db: AnyDrizzleDB<any>): SelectionContext => {\n const cached = contextCache.get(db as object);\n if (cached) {\n return cached;\n }\n\n const relations = (db as any)._.relations ?? {};\n // Same reconstruction `buildSchema` does: the relations config is the only table map a v1\n // handle carries, and each of its entries carries its table.\n const schema = Object.fromEntries(\n Object.entries(relations as Record<string, any>)\n .filter(([, config]) => config?.table != null)\n .map(([key, config]) => [key, config.table]),\n );\n\n const tableEntries = Object.entries(schema as Record<string, unknown>).filter(([, value]) => is(value, Table)) as [\n string,\n Table,\n ][];\n if (!tableEntries.length) {\n throw new Error(\n 'Drizzle-GraphQL Error: Schema not found in drizzle instance. Pass relations (from buildRelations/defineRelations) to the drizzle constructor so drizzle-graphql can read your tables.',\n );\n }\n\n const tables = Object.fromEntries(tableEntries);\n const getTableConfig = tableConfigFor(db);\n const primaryKeyCache = new Map<string, readonly string[]>();\n const primaryKeyOf = (tableName: string): readonly string[] => {\n let pk = primaryKeyCache.get(tableName);\n if (!pk) {\n const table = tables[tableName];\n pk = table ? getPrimaryKeyPropNamesFromConfig(table, getTableConfig) : [];\n primaryKeyCache.set(tableName, pk);\n }\n return pk;\n };\n\n const relationMap = buildNamedRelations(relations, tableEntries);\n // Paginated relations fall back to a primary-key order, which is resolved once per target\n // and hung off the relation entry — exactly as the generated schema does it.\n attachTargetPrimaryKeys(relationMap, tables, (table) => [...primaryKeyOf(tableNameOf(tables, table))]);\n\n const context: SelectionContext = {\n tables,\n relationMap,\n filterCtx: { tables, relationMap },\n primaryKeyOf,\n };\n contextCache.set(db as object, context);\n return context;\n};\n\n/** Reverse lookup for `attachTargetPrimaryKeys`, which hands back the table, not its key. */\nconst tableNameOf = (tables: Record<string, Table>, table: Table): string =>\n Object.keys(tables).find((name) => tables[name] === table) ?? '';\n\n/** Options shared by {@link selectionToWith} and {@link resolveSelection}. */\nexport type SelectionOptions = {\n /** The drizzle instance the schema was built from. */\n db: AnyDrizzleDB<any>;\n /** The Drizzle schema key of the table the selection is rooted at. */\n table: string;\n /**\n * The `typeNameMapper` the schema was built with, when one was configured. The translation\n * matches selections against GraphQL type names, so a build that renames its types has to\n * pass the same mapper here or nothing will match.\n */\n typeNameMapper?: TypeNameMapper;\n /**\n * The `derivedTypeNameMapper` / `typeNamePrefix` / `typeNameSuffix` the schema was built\n * with, when any were configured. Same reason as `typeNameMapper`: the translation matches\n * selections against the names the build actually published.\n */\n derivedTypeNameMapper?: DerivedTypeNameMapper;\n typeNamePrefix?: string;\n typeNameSuffix?: string;\n};\n\n/** The build's naming rule, reassembled from the three options a caller passes back. */\nconst namingRuleOf = (options: SelectionOptions): TypeNameResolver =>\n resolveGeneratedTypeNames({\n derivedTypeNameMapper: options.derivedTypeNameMapper,\n typeNamePrefix: options.typeNamePrefix,\n typeNameSuffix: options.typeNameSuffix,\n });\n\n/**\n * Reads the parsed selection tree out of a resolver's `info`, resolving fragments and\n * inline fragments. Accepts an already-parsed tree so a caller that has one (or is chaining\n * these helpers) does not pay for the walk twice.\n */\nconst parseInfo = (info: GraphQLResolveInfo | ResolveTree): ResolveTree | undefined => {\n if ('fieldsByTypeName' in info) {\n return info as ResolveTree;\n }\n return parseResolveInfo(info, { deep: true }) as ResolveTree | undefined;\n};\n\n/**\n * Translates a GraphQL selection set into the relational query builder's `with` tree — the\n * same translation the generated resolvers use for their own queries.\n *\n * A resolver that replaces a generated one has to return a row shaped like the type it\n * replaced, and the field resolvers underneath only fill in relations the parent did not\n * already provide. Reproducing that by hand means resolving fragments against\n * `info.fragments`, intersecting selection names against the relations config (so scalars\n * and consumer-added fields drop out instead of becoming invalid `with` keys), following\n * aliases, compiling each relation's `where` / `orderBy` / `limit` / `offset` arguments into\n * its nested entry, and leaving `<relation>Aggregate` selections out — they are not `with`\n * entries at all. This does all of it.\n *\n * ```ts\n * const withTree = selectionToWith(info, { db, table: 'Users' });\n * const row = await tx.query.Users.findFirst({ where: { id: { eq } }, with: withTree });\n * ```\n *\n * Returns `undefined` when the selection asks for no relations, which is the value the\n * query builder wants for \"no `with` clause\".\n */\nexport const selectionToWith = (\n info: GraphQLResolveInfo | ResolveTree,\n options: SelectionOptions,\n): Record<string, any> | undefined => {\n const { db, table, typeNameMapper } = options;\n const resolveName = namingRuleOf(options);\n const { tables, relationMap, filterCtx } = contextFor(db);\n if (!tables[table]) {\n throw new Error(`Drizzle-GraphQL Error: '${table}' is not a table in the Drizzle schema.`);\n }\n if (!relationMap[table]) {\n return undefined;\n }\n\n const parsed = parseInfo(info);\n const params = extractRelationsParams(\n relationMap,\n tables,\n table,\n parsed,\n resolveObjectTypeName(table, typeNameMapper, resolveName),\n { typeNameMapper, filterCtx, resolveName },\n );\n // A selection with no relations in it gets no `with` clause at all, rather than an empty\n // object the query builder would have to be asked to ignore.\n return params && Object.keys(params).length ? params : undefined;\n};\n\n/** Options for {@link resolveSelection} — the selection options plus the read itself. */\nexport type ResolveSelectionOptions = SelectionOptions & {\n /**\n * The transaction (or other drizzle executor) to read on. Defaults to `db`, so an override\n * that has opened its own transaction passes it here to see its own uncommitted writes.\n */\n executor?: any;\n /** Whether to return one row or a list. A single read ignores `limit`. */\n single?: boolean;\n /** The generated `where` argument, in the schema's filter DSL — compiled the same way. */\n where?: any;\n /** The generated `orderBy` argument. */\n orderBy?: any;\n limit?: number;\n offset?: number;\n /** The generated `after` cursor argument, for keyset pagination. */\n after?: string;\n};\n\n/**\n * Runs the read a generated select resolver would have run, against whichever executor is\n * given — the whole body, not just the `with` tree: selected columns, relation arguments,\n * eager loading, cursor pagination, and the transport remapping of the result.\n *\n * This is what an override usually wants after it has done its own work:\n *\n * ```ts\n * const rows = await resolveSelection(info, { db, table: 'Users', where, executor: tx });\n * ```\n *\n * Relation arguments and aggregate fields keep behaving as they do in the generated schema,\n * because it is the generated schema's own code path.\n */\nexport const resolveSelection = async (\n info: GraphQLResolveInfo | ResolveTree,\n options: ResolveSelectionOptions,\n): Promise<any> => {\n const {\n db,\n table: tableName,\n typeNameMapper,\n executor,\n single = false,\n where,\n orderBy,\n limit,\n offset,\n after,\n } = options;\n const resolveName = namingRuleOf(options);\n const { tables, relationMap, filterCtx, primaryKeyOf } = contextFor(db);\n const table = tables[tableName];\n if (!table) {\n throw new Error(`Drizzle-GraphQL Error: '${tableName}' is not a table in the Drizzle schema.`);\n }\n\n const parsedInfo = parseInfo(info);\n if (!parsedInfo) {\n throw new Error('Drizzle-GraphQL Error: resolveSelection could not read a selection set from the resolve info.');\n }\n\n const source = executor ?? db;\n const queryBase = (source as any).query?.[tableName];\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: the executor passed to resolveSelection has no relational query builder for '${tableName}'.`,\n );\n }\n\n return runRelationalSelect({\n queryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName: resolveObjectTypeName(tableName, typeNameMapper, resolveName),\n typeNameMapper,\n resolveName,\n parsedInfo,\n single,\n where,\n orderBy,\n limit,\n offset,\n after,\n filterCtx,\n pkNames: primaryKeyOf(tableName),\n db: source,\n });\n};\n","import { is } from 'drizzle-orm';\nimport { MySqlAsyncDatabase } from 'drizzle-orm/mysql-core';\nimport { PgAsyncDatabase } from 'drizzle-orm/pg-core';\nimport { SQLiteAsyncDatabase } from 'drizzle-orm/sqlite-core';\nimport {\n type GraphQLFieldConfig,\n type GraphQLInputObjectType,\n GraphQLObjectType,\n GraphQLSchema,\n type GraphQLSchemaConfig,\n} from 'graphql';\nimport type { AnyDrizzleDB, BuildSchemaConfig, GeneratedData, NamingOf } from './types.ts';\nimport { resolveBuildConfig } from './util/build-config.ts';\nimport { applyErrorMapper, defaultErrorMapper } from './util/builders/common.ts';\nimport { generateMySQL, generatePG, generateSQLite } from './util/builders/index.ts';\n\nexport type {\n AggregateResolver,\n AnyDrizzleDB,\n BuildSchemaConfig,\n ComplexityConfig,\n ContextValuesConfig,\n DefaultOrderByEntry,\n DefaultsConfig,\n DeleteResolver,\n DeleteSingleResolver,\n DerivedTypeNameMapper,\n ExtractRelations,\n ExtractTableByName,\n ExtractTableRelations,\n ExtractTables,\n FeatureSwitch,\n GeneratedData,\n GeneratedEntities,\n GeneratedInputs,\n GeneratedOutputs,\n GeneratedTypeInfo,\n GeneratedTypeKind,\n InsertArrResolver,\n InsertResolver,\n LimitsConfig,\n MutationReturnlessResult,\n MutationsCore,\n NamingOf,\n NestedWriteOp,\n NestedWriteOrigin,\n OnWriteConfig,\n QueriesCore,\n RowScope,\n RowScopeFilter,\n SchemaExclusions,\n SchemaFeatures,\n ScopeConfig,\n SelectResolver,\n SelectSingleResolver,\n SoftDeleteColumn,\n SoftDeleteConfig,\n TableDefaults,\n TableLimitPolicy,\n TypeNameMapper,\n UpdateManyArgs,\n UpdateManyEntry,\n UpdateManyResolver,\n UpdateResolver,\n UpdateSingleResolver,\n UpsertArgs,\n UpsertArrResolver,\n UpsertConflictArgs,\n UpsertResolver,\n WriteHook,\n WriteHookPayload,\n WriteHookPositions,\n WriteHooks,\n WriteOperation,\n} from './types.ts';\nexport type { DrizzleErrorCode, DrizzleErrorContext, RelationResolverFactory } from './util/builders/common.ts';\nexport {\n createRelationResolverFactory,\n defaultErrorMapper,\n drizzleError,\n drizzleExecutorKey,\n extractFilters,\n extractOrderBy,\n extractRelationJoinColumns,\n} from './util/builders/common.ts';\nexport type { TableNamedRelations } from './util/builders/types.ts';\nexport { singularizeMapper } from './util/case-ops/index.ts';\nexport type {\n DrizzleExtension,\n DrizzleFieldExtension,\n DrizzleFieldKind,\n DrizzleFieldOperation,\n DrizzleTargetArg,\n DrizzleTypeExtension,\n IdentifiedRows,\n} from './util/extensions.ts';\nexport { drizzleExtension, identifyRows, isDrizzleFieldExtension } from './util/extensions.ts';\nexport type { FieldsByTypeName, ParseResolveInfoOptions, ResolveTree } from './util/parse-resolve-info.ts';\nexport { parseResolveInfo } from './util/parse-resolve-info.ts';\nexport {\n GraphQLBigIntString,\n GraphQLDate,\n GraphQLDateTime,\n GraphQLDecimalString,\n GraphQLJSON,\n GraphQLUUID,\n} from './util/scalars/index.ts';\nexport type { ResolveSelectionOptions, SelectionOptions } from './util/selection.ts';\nexport { resolveSelection, selectionToWith } from './util/selection.ts';\nexport type {\n ColumnDeprecator,\n ColumnDescriber,\n ColumnDocInfo,\n ColumnTypeMapper,\n ColumnTypeMapperInfo,\n EnumNameInfo,\n EnumNameMapper,\n EnumValueNameInfo,\n EnumValueNameMapper,\n RelationDescriber,\n ScalarOverride,\n ScalarOverridesConfig,\n SchemaDocs,\n TableDescriber,\n} from './util/type-converter/types.ts';\nexport type { Pluralize, Singularize, TypeNaming } from './util/type-naming.ts';\n\ntype ObjMap<T> = Record<string, T>;\n\nexport const buildSchema = <TDbClient extends AnyDrizzleDB<any>, TConfig extends BuildSchemaConfig = BuildSchemaConfig>(\n db: TDbClient,\n config?: TConfig,\n): GeneratedData<TDbClient, NamingOf<TConfig>> => {\n const relations = db._.relations;\n // The relations config is the only table map a v1 handle carries: `_.fullSchema` is gone\n // from all three dialects, and the constructor's separate `schema` argument no longer\n // reaches the handle at all. Each entry carries its own table, so the map is rebuilt from\n // there — a table left out of the relations config is simply not part of the schema.\n const schema = Object.fromEntries(\n Object.entries(relations as Record<string, any>)\n .filter(([, config]) => config?.table != null)\n .map(([key, config]) => [key, config.table]),\n );\n\n if (!Object.keys(schema).length) {\n throw new Error(\n 'Drizzle-GraphQL Error: Schema not found in drizzle instance. Pass relations (from buildRelations/defineRelations) to the drizzle constructor so drizzle-graphql can detect your tables.',\n );\n }\n\n const generatorOptions = resolveBuildConfig(config, schema as Record<string, unknown>);\n\n let generatorOutput;\n if (is(db, MySqlAsyncDatabase)) {\n generatorOutput = generateMySQL(db, schema, relations, generatorOptions);\n } else if (is(db, PgAsyncDatabase)) {\n generatorOutput = generatePG(db, schema, relations, generatorOptions);\n } else if (is(db, SQLiteAsyncDatabase)) {\n generatorOutput = generateSQLite(db, schema, relations, generatorOptions);\n } else {\n throw new Error('Drizzle-GraphQL Error: Unknown database instance type');\n }\n\n // Wrap resolvers before the schema is assembled, so the generated schema and the returned\n // entities share the same handling.\n const onError = config?.onError;\n applyErrorMapper(\n generatorOutput as any,\n onError ? (error) => onError(error) ?? defaultErrorMapper(error) : defaultErrorMapper,\n );\n\n const { queries, mutations, inputs, types } = generatorOutput;\n\n const graphQLSchemaConfig: GraphQLSchemaConfig = {\n types: [...Object.values(inputs), ...Object.values(types)] as (GraphQLInputObjectType | GraphQLObjectType)[],\n query: new GraphQLObjectType({\n name: 'Query',\n fields: queries as ObjMap<GraphQLFieldConfig<any, any, any>>,\n }),\n };\n\n // An empty Mutation type is invalid GraphQL, so turning off every mutation feature\n // omits the type the same way `mutations: false` does.\n if (config?.mutations !== false && Object.keys(mutations).length) {\n const mutation = new GraphQLObjectType({\n name: 'Mutation',\n fields: mutations as ObjMap<GraphQLFieldConfig<any, any, any>>,\n });\n\n graphQLSchemaConfig.mutation = mutation;\n }\n\n const outputSchema = new GraphQLSchema(graphQLSchemaConfig);\n\n // The three dialect generators are typed on their own dialect's database, so their union\n // does not structurally match `GeneratedEntities<TDbClient>` for a still-generic TDbClient.\n // The runtime branch above is what guarantees the right one was built.\n return {\n schema: outputSchema,\n entities: generatorOutput as unknown as GeneratedData<TDbClient, NamingOf<TConfig>>['entities'],\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+EA,MAAa,gBACX,SACA,EACE,MACA,OACA,GAAG,cAOL,IAAIA,QAAAA,aAAa,SAAS;CACxB;CACA,YAAY,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS;EAAE;EAAM,SAAS;CAAQ,IAAI,EAAE,KAAK;AAChF,CAAC;;;;;;;;AASH,MAAa,oBAAoB,OAAgB,YAA0C;CACzF,IAAI,EAAE,iBAAiBA,Q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,kBAAkB,cAAc,SAClC,eACE,IACA,WACA,OAAO,YACP,aACA,cACA,iBACA,OACA,cAAc,cACd,WACA,eACA,QACF,IACA,KAAA;EACJ,MAAM,wBAAwB,cAAc,SACxC,eACE,IACA,WACA,OAAO,YACP,aACA,cACA,uBACA,MACA,cAAc,cACd,WACA,eACA,QACF,IACA,KAAA;EAEJ,MAAM,kBACJ,cAAc,UAAU,cAAc,aAClC,wBAAwB;GACtB;GACA;GACA,cAAc,SAAS;GACvB;GACA;GACA;EACF,CAAC,IACD,KAAA;EACN,MAAM,sBAAsB,kBACxBN,qBACE,IACA,WACA,OAAO,YACP,iBACA,qBACA,WACA,eACA,QACF,IACA,KAAA;EACJ,MAAM,kBAAkB,cAAc,SAClC,eACE,IACA,WACA,OAAO,YACP,cACA,iBACA,OACA,cAAc,cACd,WACA,eACA,QACF,IACA,KAAA;EACJ,MAAM,wBAAwB,cAAc,SACxC,eACE,IACA,WACA,OAAO,YACP,cACA,uBACA,MACA,cAAc,cACd,WACA,eACA,QACF,IACA,KAAA;EACJ,MAAM,mBAAmB,iBACrB,eACE,IACA,WACA,OAAO,YACP,cACA,kBACA,OACA,cAAc,cACd,WACA,eACA,UACA,IACF,IACA,KAAA;EACJ,MAAM,yBAAyB,iBAC3B,eACE,IACA,WACA,OAAO,YACP,cACA,wBACA,MACA,cAAc,cACd,WACA,eACA,UACA,IACF,IACA,KAAA;EAKJ,MAAM,uBACJ,cAAc,UAAU,cAAc,iBAClC,mBAAmB;GACjB;GACA;GACA,OAAO,OAAO;GACd,MAAM;GACN,SAAS;GACT,YAAY;GACZ,WAAW;GACX,cAAc,cAAc;GAC5B;GACA,OAAO;GACP;GACA,aAAa;EACf,CAAC,IACD,KAAA;EACN,MAAM,uBACJ,cAAc,UAAU,cAAc,iBAClC,mBAAmB;GACjB;GACA;GACA,OAAO,OAAO;GACd,MAAM;GACN,YAAY;GACZ,WAAW;GACX,cAAc,cAAc;GAC5B;GACA,OAAO;GACP;GACA,aAAa;EACf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AAO,KAAK,CAAC,CAC/C;CAEA,IAAI,CAAC,OAAO,KAAK,MAAM,CAAC,CAAC,QACvB,MAAM,IAAI,MACR,yLACF;CAGF,MAAM,mBAAmB,mBAAmB,QAAQ,MAAiC;CAErF,IAAI;CACJ,KAAA,GAAIC,YAAAA,GAAAA,CAAG,IAAIC,uBAAAA,kBAAkB,GAC3B,kBAAkBC,qBAAc,IAAI,QAAQ,WAAW,gBAAgB;MAClE,KAAA,GAAIF,YAAAA,GAAAA,CAAG,IAAIG,oBAAAA,eAAe,GAC/B,kBAAkBC,qBAAW,IAAI,QAAQ,WAAW,gBAAgB;MAC/D,KAAA,GAAIJ,YAAAA,GAAAA,CAAG,IAAIK,wBAAAA,mBAAmB,GACnC,kBAAkBC,mBAAe,IAAI,QAAQ,WAAW,gBAAgB;MAExE,MAAM,IAAI,MAAM,uDAAuD;CAKzE,MAAM,UAAU,QAAQ;CACxB,iBACE,iBACA,WAAW,UAAU,QAAQ,KAAK,KAAK,mBAAmB,KAAK,IAAI,kBACrE;CAEA,MAAM,EAAE,SAAS,WAAW,QAAQ,UAAU;CAE9C,MAAM,sBAA2C;EAC/C,OAAO,CAAC,GAAG,OAAO,OAAO,MAAM,GAAG,GAAG,OAAO,OAAO,KAAK,CAAC;EACzD,OAAO,IAAIC,QAAAA,kBAAkB;GAC3B,MAAM;GACN,QAAQ;EACV,CAAC;CACH;CAIA,IAAI,QAAQ,cAAc,SAAS,OAAO,KAAK,SAAS,CAAC,CAAC,QAMxD,oBAAoB,WAAW,IALVA,QAAAA,kBAAkB;EACrC,MAAM;EACN,QAAQ;CACV,CAEsC;CAQxC,OAAO;EACL,QAAQ,IANeC,QAAAA,cAAc,mBAMlB;EACnB,UAAU;CACZ;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["GraphQLError","GraphQLScalarType","Kind","GraphQLEnumType","GraphQLObjectType","GraphQLFloat","GraphQLInputObjectType","is","PgDate","PgDateString","MySqlDate","MySqlDateString","MySqlTimestampString","MySqlDateTimeString","PgTimestampString","SQLiteTimestamp","PgTimestamp","MySqlTimestamp","MySqlDateTime","GraphQLList","GraphQLNonNull","extractExtendedColumnType","GraphQLBoolean","GraphQLDateTime","GraphQLInt","GraphQLJSON","PgUUID","GraphQLUUID","GraphQLString","PgInteger","PgSerial","MySqlInt","MySqlSerial","SQLiteInteger","GraphQLScalarType","getColumns","GraphQLJSON","GraphQLList","GraphQLNonNull","GraphQLUUID","GraphQLBoolean","GraphQLEnumType","GraphQLInt","GraphQLFloat","GraphQLInputObjectType","GraphQLString","GraphQLDateTime","extractExtendedColumnType","getColumns","is","One","notIlike","ilike","sql","and","arrayOverlaps","arrayContains","not","or","is","Column","getColumns","relationsFilterToSQL","getColumns","GraphQLInputObjectType","GraphQLNonNull","getColumns","eq","and","getColumns","eq","and","aliasedTable","getTableAsAliasSQL","relationsFilterToSQL","not","is","One","or","GraphQLEnumType","getColumns","extractExtendedColumnType","isNotNull","isNull","eq","ne","or","is","SQL","and","GraphQLInt","GraphQLString","GraphQLList","GraphQLNonNull","GraphQLEnumType","GraphQLEnumType","GraphQLList","GraphQLNonNull","GraphQLInputObjectType","getColumns","sql","asc","desc","is","One","aliasedTable","relationsFilterToSQL","getTableAsAliasSQL","sql","getColumns","and","getColumns","isNotNull","gt","lt","or","isNull","and","eq","getColumns","asc","getColumns","sql","asc","eq","inArray","or","and","GraphQLNonNull","GraphQLEnumType","GraphQLInputObjectType","GraphQLNonNull","GraphQLInt","GraphQLBoolean","Kind","getArgumentValues","GraphQLInt","GraphQLFloat","GraphQLList","GraphQLInputObjectType","GraphQLNonNull","getColumns","sql","getColumns","is","One","and","inArray","sql","GraphQLBoolean","GraphQLInputObjectType","GraphQLNonNull","getColumns","getColumns","sql","gt","lte","and","eq","inArray","or","GraphQLString","is","One","GraphQLInputObjectType","GraphQLList","GraphQLNonNull","GraphQLObjectType","is","One","GraphQLNonNull","GraphQLList","GraphQLInt","GraphQLString","GraphQLInputObjectType","is","Table","getColumns","count","GraphQLList","GraphQLObjectType","extractExtendedColumnType","GraphQLNonNull","GraphQLInt","GraphQLFloat","getColumns","and","inArray","eq","GraphQLInputObjectType","getColumns","is","One","GraphQLInputObjectType","GraphQLList","GraphQLNonNull","GraphQLBoolean","eq","and","inArray","is","GraphQLNonNull","GraphQLList","One","GraphQLNonNull","GraphQLList","generateUpdateMany","getTableConfig","mysqlTableConfig","MySqlTable","generateSchemaData","GraphQLObjectType","GraphQLBoolean","GraphQLInt","GraphQLNonNull","GraphQLList","GraphQLNonNull","GraphQLList","GraphQLInt","GraphQLNonNull","GraphQLList","getTableConfig","pgTableConfig","generateUpdateMany","PgTable","generateSchemaData","sqliteTableConfig","SQLiteTable","mysqlTableConfig","pgTableConfig","sqliteTableConfig","is","MySqlAsyncDatabase","PgAsyncDatabase","SQLiteAsyncDatabase","Table","is","MySqlAsyncDatabase","generateMySQL","PgAsyncDatabase","generatePG","SQLiteAsyncDatabase","generateSQLite","GraphQLObjectType","GraphQLSchema"],"sources":["../src/util/builders/common/errors.ts","../src/util/scalars/index.ts","../src/util/case-ops/index.ts","../src/util/type-converter/index.ts","../src/util/builders/common/type-names.ts","../src/util/builders/common/column-filters.ts","../src/util/data-mappers/index.ts","../src/util/builders/common/filters.ts","../src/util/builders/common/relations.ts","../src/util/builders/common/exclusions.ts","../src/util/builders/common/naming.ts","../src/util/builders/common/unique-keys.ts","../src/util/builders/common/relation-filters.ts","../src/util/builders/common/policies.ts","../src/util/builders/common/args.ts","../src/util/builders/common/column-enums.ts","../src/util/builders/common/conflict.ts","../src/util/builders/common/order-by.ts","../src/util/builders/common/cursor.ts","../src/util/builders/common/keys.ts","../src/util/builders/common/distinct.ts","../src/util/builders/common/docs.ts","../src/util/builders/common/executor.ts","../src/util/builders/common/input-order.ts","../src/util/builders/common/limits.ts","../src/util/parse-resolve-info.ts","../src/util/builders/field-updates.ts","../src/util/builders/common/rqb-config.ts","../src/util/builders/common/selected-columns.ts","../src/util/builders/common/relation-params.ts","../src/util/builders/common/select-runtime.ts","../src/util/builders/common/transactions.ts","../src/util/builders/common/write-hooks.ts","../src/util/builders/common/write-scaffold.ts","../src/util/builders/common/mutation-helpers.ts","../src/util/batch-loader/index.ts","../src/util/extensions.ts","../src/util/builders/common/relation-resolvers.ts","../src/util/builders/common/resolver-names.ts","../src/util/builders/common/root-fields.ts","../src/util/builders/common/table-inputs.ts","../src/util/builders/common/table-types.ts","../src/util/features.ts","../src/util/build-config.ts","../src/util/builders/aggregates.ts","../src/util/builders/nested-writes.ts","../src/util/builders/errors.ts","../src/util/builders/select.ts","../src/util/builders/build-context.ts","../src/util/builders/mysql.ts","../src/util/builders/write-resolvers.ts","../src/util/builders/schema-data.ts","../src/util/builders/update-many.ts","../src/util/builders/pg.ts","../src/util/builders/sqlite.ts","../src/util/selection.ts","../src/index.ts"],"sourcesContent":["// The `onError` boundary: what a resolver's throw is turned into, the default mapper, and the\n// plumbing that lets a caller replace it.\n\nimport { type ASTNode, GraphQLError } from 'graphql';\nimport type { DrizzleFieldOperation } from '../../extensions.ts';\n\n/**\n * The classification of an error drizzle-graphql raised itself, published as\n * `extensions.code`. A consumer maps these onto its own vocabulary; the prose is written for\n * a client to read and may be reworded in any release, so it is not something to match on.\n */\nexport type DrizzleErrorCode =\n /** A `Single` write's `where` matched more than one row, so nothing was written. */\n | 'DRIZZLE_MULTI_ROW_MATCH'\n /** A write that refuses to run unbounded was given no `where`, or one matching every row. */\n | 'DRIZZLE_WHERE_REQUIRED'\n /** The requested `limit` is above the maximum the field's limit policy allows. */\n | 'DRIZZLE_LIMIT_EXCEEDED'\n /** A write's `values` / `set` carried nothing to write. */\n | 'DRIZZLE_NO_VALUES'\n /** An insert reported no row back, so there is nothing to return or attach. */\n | 'DRIZZLE_NO_ROW_RETURNED'\n /** The driver reported no row count for a returnless write. */\n | 'DRIZZLE_ROW_COUNT_UNAVAILABLE'\n /** A nested write was passed to a field that cannot run one. */\n | 'DRIZZLE_NESTED_WRITES_UNSUPPORTED'\n /** A nested `create` / `connect` / `disconnect` / `set` operand was not usable. */\n | 'DRIZZLE_NESTED_WRITE_INVALID'\n /** A `groupBy` named no column, or one that cannot be grouped by. */\n | 'DRIZZLE_INVALID_GROUP_BY'\n /** An `after` cursor did not decode, or was issued for a different ordering. */\n | 'DRIZZLE_INVALID_CURSOR'\n /** A `where` key was not a filter of the table, or a relation was used as one. */\n | 'DRIZZLE_INVALID_FILTER'\n /** A column's update operations input held none, or more than one. */\n | 'DRIZZLE_INVALID_UPDATE_OPERATION'\n /** A configured `scope` hook returned something that is not a predicate. */\n | 'DRIZZLE_INVALID_SCOPE'\n /** An `orderBy` named something that cannot be ordered by in this query. */\n | 'DRIZZLE_INVALID_ORDER_BY'\n /** `distinct` was asked for where it cannot be applied. */\n | 'DRIZZLE_INVALID_DISTINCT'\n /** An `onConflict` named a target or update column the upsert cannot use. */\n | 'DRIZZLE_INVALID_ON_CONFLICT'\n /** A written value could not be converted to what its column stores. */\n | 'DRIZZLE_INVALID_INPUT_VALUE'\n /** An update's `set` gave a column that cannot hold null an explicit null. */\n | 'DRIZZLE_NOT_NULL'\n /** A write's input named a key that is not a column of the table. */\n | 'DRIZZLE_UNKNOWN_COLUMN'\n /** A stored value could not be represented by the scalar that transports it. */\n | 'DRIZZLE_UNREPRESENTABLE_VALUE'\n /** The request's shared mutation transaction was rolled back, so this field never ran. */\n | 'DRIZZLE_TRANSACTION_ABORTED'\n /** A relation was read on a path it cannot be loaded through (see the message). */\n | 'DRIZZLE_UNSUPPORTED_RELATION';\n\n/**\n * What an error was about, published as `extensions.drizzle` beside the code — the runtime\n * half of the `extensions.drizzle` markers a generated field carries.\n *\n * `field` is the **generated** field name, which is why it is data rather than prose: a build\n * that republishes these fields under other names (`RenameRootFields`, a stitched gateway, a\n * hand-written façade) would otherwise be telling a client about a field it has never heard\n * of. The name the client asked for is already in the error's `path`.\n */\nexport type DrizzleErrorContext = {\n /** The Drizzle schema key of the table the field reads or writes. */\n table?: string;\n operation?: DrizzleFieldOperation;\n /** The generated field's own name, pre-rename. */\n field?: string;\n /** For a relation field: the relation's name. */\n relation?: string;\n};\n\n/**\n * A `GraphQLError` carrying its context as data. The message says what went wrong, in prose\n * meant for a client; `extensions.code` classifies it and `extensions.drizzle` says which\n * table, operation and generated field it came from.\n */\nexport const drizzleError = (\n message: string,\n {\n code,\n nodes,\n ...context\n }: DrizzleErrorContext & {\n code: DrizzleErrorCode;\n /** The AST the error is about, where the throw site has one — it becomes the `locations`. */\n nodes?: ASTNode | readonly ASTNode[];\n },\n): GraphQLError =>\n new GraphQLError(message, {\n nodes,\n extensions: Object.keys(context).length ? { code, drizzle: context } : { code },\n });\n\n/**\n * Attaches `extensions.drizzle` to one of this library's own errors on its way out of a\n * resolver, so that the deep helpers — filter compilation, ordering, cursors, conflict\n * planning — can raise a coded error without every one of them being handed the field it was\n * called from. Anything else (a driver error, a `GraphQLError` a hook raised) passes through\n * untouched, and context a throw site already supplied wins over the field's.\n */\nexport const withErrorContext = (error: unknown, context: DrizzleErrorContext): unknown => {\n if (!(error instanceof GraphQLError)) {\n return error;\n }\n const { code, drizzle } = (error.extensions ?? {}) as { code?: unknown; drizzle?: DrizzleErrorContext };\n if (typeof code !== 'string' || !code.startsWith('DRIZZLE_')) {\n return error;\n }\n return new GraphQLError(error.message, {\n nodes: error.nodes,\n source: error.source,\n positions: error.positions,\n path: error.path,\n originalError: error.originalError,\n extensions: { ...error.extensions, drizzle: { ...context, ...drizzle } },\n });\n};\n\n/**\n * Normalizes whatever a driver threw into a `GraphQLError`. Errors drizzle-graphql raised\n * itself pass straight through; anything else keeps the thrown value on `originalError`,\n * which is how {@link defaultErrorMapper} later tells the two apart.\n */\nexport const toGraphQLError = (e: unknown): unknown => {\n if (e instanceof GraphQLError) {\n return e;\n }\n return e instanceof Error ? new GraphQLError(e.message, { originalError: e }) : e;\n};\n\n/**\n * Default for `config.onError`: keeps drizzle-graphql's own errors, which are written for\n * the client, and replaces driver/database errors with a generic message. Their text names\n * tables, columns, constraints and offending values, none of which belongs in a response.\n * The original is preserved on `originalError` for server-side logging.\n */\nexport const defaultErrorMapper = (error: unknown): unknown => {\n if (error instanceof GraphQLError && !error.originalError) {\n return error;\n }\n\n return new GraphQLError('Internal server error', {\n originalError:\n error instanceof GraphQLError ? (error.originalError ?? error) : error instanceof Error ? error : null,\n extensions: { code: 'INTERNAL_SERVER_ERROR' },\n });\n};\n\n/**\n * Wraps every resolver reachable from a generated entity set so that its errors pass through\n * `mapError` first. Done here rather than at each `throw` site so that the hook also covers\n * relation field resolvers and anything that throws outside a builder's own try/catch.\n */\nexport const applyErrorMapper = (\n entities: {\n queries: Record<string, { resolve?: (...args: any[]) => any }>;\n mutations: Record<string, { resolve?: (...args: any[]) => any }>;\n types: Record<string, { getFields?: () => Record<string, { resolve?: (...args: any[]) => any }> }>;\n fieldResolvers?: Record<string, Record<string, (...args: any[]) => any>>;\n },\n mapError: (error: unknown) => unknown,\n): void => {\n const wrap =\n (resolve: (...args: any[]) => any) =>\n (...args: any[]) => {\n try {\n const result = resolve(...args);\n if (result && typeof result.then === 'function') {\n return result.then(undefined, (e: unknown) => {\n throw mapError(e);\n });\n }\n return result;\n } catch (e) {\n throw mapError(e);\n }\n };\n\n for (const field of [...Object.values(entities.queries), ...Object.values(entities.mutations)]) {\n if (field?.resolve) {\n field.resolve = wrap(field.resolve);\n }\n }\n\n // Relation and aggregate fields live on the object types, not in the query/mutation maps.\n for (const type of Object.values(entities.types)) {\n if (typeof type?.getFields !== 'function') {\n continue;\n }\n for (const field of Object.values(type.getFields())) {\n if (field?.resolve) {\n field.resolve = wrap(field.resolve);\n }\n }\n }\n\n // Standalone relation resolvers, handed out for use in hand-written schemas.\n for (const tableResolvers of Object.values(entities.fieldResolvers ?? {})) {\n for (const [relationName, resolve] of Object.entries(tableResolvers)) {\n tableResolvers[relationName] = wrap(resolve);\n }\n }\n};\n","import { GraphQLScalarType, Kind } from 'graphql';\nimport { GraphQLDateTime, GraphQLJSON, GraphQLUUID } from 'graphql-scalars';\nimport { type DrizzleErrorCode, drizzleError } from '../builders/common/errors.ts';\n\n// Both scalars below coerce the same way in both directions, so each helper is built once per\n// direction with the code that direction reports: a rejected argument is the client's value to\n// fix, while a rejected column value is the stored data's. graphql-js wraps a `parseValue`\n// throw when it coerces variables, but the wrapper inherits the original's `extensions`, so\n// the code survives that trip.\nconst INVALID_INPUT: DrizzleErrorCode = 'DRIZZLE_INVALID_INPUT_VALUE';\nconst UNREPRESENTABLE: DrizzleErrorCode = 'DRIZZLE_UNREPRESENTABLE_VALUE';\n\nconst decimalString =\n (code: DrizzleErrorCode) =>\n (value: unknown): string => {\n if (typeof value === 'bigint') {\n return value.toString();\n }\n\n if (typeof value === 'number') {\n if (!Number.isInteger(value)) {\n throw drizzleError(`BigInt cannot represent non-integer value: ${value}`, { code });\n }\n if (!Number.isSafeInteger(value)) {\n throw drizzleError(\n `BigInt cannot represent the number ${value} without precision loss — pass it as a string instead`,\n { code },\n );\n }\n return String(value);\n }\n\n if (typeof value === 'string') {\n if (!/^-?\\d+$/.test(value)) {\n throw drizzleError(`BigInt cannot represent non-integer value: \"${value}\"`, { code });\n }\n return value;\n }\n\n throw drizzleError(`BigInt cannot represent value: ${JSON.stringify(value)}`, { code });\n };\n\nconst parseDecimal = decimalString(INVALID_INPUT);\n\n/**\n * A 64-bit integer. Always transported as a decimal string, in both directions, so no value\n * is ever silently rounded by JSON's double-precision numbers. `graphql-scalars`' own\n * `GraphQLBigInt` is deliberately not used: it emits numbers for safe integers and strings\n * for everything else, so a client cannot know which it will get.\n */\nexport const GraphQLBigIntString = new GraphQLScalarType<string, string>({\n name: 'BigInt',\n description:\n 'A 64-bit integer, transported as a decimal string so that values beyond ' +\n \"JavaScript's safe integer range survive the round-trip intact.\",\n serialize: decimalString(UNREPRESENTABLE),\n parseValue: parseDecimal,\n parseLiteral: (ast) => {\n if (ast.kind !== Kind.STRING && ast.kind !== Kind.INT) {\n throw drizzleError(`BigInt cannot represent a ${ast.kind}`, { code: INVALID_INPUT, nodes: ast });\n }\n return parseDecimal(ast.value);\n },\n});\n\n// Optional sign, digits with an optional fractional part (or a bare fractional part),\n// and an optional exponent. Deliberately excludes 'NaN', 'Infinity', and empty strings,\n// even though some databases would accept them.\nconst numericStringPattern = /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$/;\n\nconst numericString =\n (code: DrizzleErrorCode) =>\n (value: unknown): string => {\n if (typeof value === 'bigint') {\n return value.toString();\n }\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw drizzleError(`Decimal cannot represent non-finite value: ${value}`, { code });\n }\n return String(value);\n }\n\n if (typeof value === 'string') {\n if (!numericStringPattern.test(value)) {\n throw drizzleError(`Decimal cannot represent non-numeric value: \"${value}\"`, { code });\n }\n return value;\n }\n\n throw drizzleError(`Decimal cannot represent value: ${JSON.stringify(value)}`, { code });\n };\n\nconst parseNumeric = numericString(INVALID_INPUT);\n\n/**\n * An arbitrary-precision decimal (`numeric` / `decimal` columns). Always transported as a\n * numeric string, in both directions, so no value is ever silently rounded by JSON's\n * double-precision numbers. Accepts numeric literals and numeric strings on input; rejects\n * non-numeric strings (including 'NaN' and 'Infinity').\n */\nexport const GraphQLDecimalString = new GraphQLScalarType<string, string>({\n name: 'Decimal',\n description:\n 'An arbitrary-precision decimal, transported as a numeric string so that values ' +\n \"beyond JavaScript's double-precision range survive the round-trip intact.\",\n serialize: numericString(UNREPRESENTABLE),\n parseValue: parseNumeric,\n parseLiteral: (ast) => {\n if (ast.kind !== Kind.STRING && ast.kind !== Kind.INT && ast.kind !== Kind.FLOAT) {\n throw drizzleError(`Decimal cannot represent a ${ast.kind}`, { code: INVALID_INPUT, nodes: ast });\n }\n return parseNumeric(ast.value);\n },\n});\n\n// RFC 3339 `full-date`: four-digit year, two-digit month and day, nothing else — no time, no\n// offset. The shape alone admits `2026-13-45`, so `isCalendarDate` checks the ranges too.\nconst fullDatePattern = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\nconst daysInMonth = (year: number, month: number): number => {\n if (month === 2) {\n const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n return leap ? 29 : 28;\n }\n return [4, 6, 9, 11].includes(month) ? 30 : 31;\n};\n\n/** Whether `value` is a `YYYY-MM-DD` string naming a day that exists on the calendar. */\nexport const isCalendarDate = (value: string): boolean => {\n const match = fullDatePattern.exec(value);\n if (!match) {\n return false;\n }\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n return month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth(year, month);\n};\n\n/**\n * A JS `Date` as the calendar day it stands for. Read in UTC, because that is how drivers\n * build one from a `date` column: `new Date('2026-09-15')` is UTC midnight, so the local\n * getters would name the previous day anywhere west of Greenwich.\n */\nexport const dateToCalendarDate = (value: Date): string | undefined => {\n if (Number.isNaN(value.getTime())) {\n return undefined;\n }\n const year = value.getUTCFullYear();\n if (year < 0 || year > 9999) {\n return undefined;\n }\n const month = String(value.getUTCMonth() + 1).padStart(2, '0');\n const day = String(value.getUTCDate()).padStart(2, '0');\n return `${String(year).padStart(4, '0')}-${month}-${day}`;\n};\n\nconst calendarDate =\n (code: DrizzleErrorCode, acceptDate: boolean) =>\n (value: unknown): string => {\n if (typeof value === 'string') {\n if (!isCalendarDate(value)) {\n throw drizzleError(`Date cannot represent \"${value}\": expected a calendar date as YYYY-MM-DD`, { code });\n }\n return value;\n }\n\n if (acceptDate && value instanceof Date) {\n const formatted = dateToCalendarDate(value);\n if (formatted === undefined) {\n throw drizzleError('Date cannot represent an invalid or out-of-range Date', { code });\n }\n return formatted;\n }\n\n throw drizzleError(`Date cannot represent value: ${JSON.stringify(value)}: expected a YYYY-MM-DD string`, {\n code,\n });\n };\n\nconst parseCalendarDate = calendarDate(INVALID_INPUT, false);\n\n/**\n * A calendar day — `date` columns, whichever `mode` drizzle reads them in. Always transported\n * as an RFC 3339 `full-date` string (`YYYY-MM-DD`), in both directions: it has no time and no\n * offset, so there is nothing for a client's timezone to shift. `graphql-scalars`' own\n * `GraphQLDate` is deliberately not used: its `parseValue` returns a JS `Date`, so the same\n * scalar would be a string on the way out and an instant on the way in.\n *\n * Input accepts only a `YYYY-MM-DD` string naming a real day (`2026-02-30` and datetime\n * strings are rejected) and hands it on unchanged. Output also accepts a JS `Date`, read as\n * the UTC day it encodes.\n */\nexport const GraphQLDate = new GraphQLScalarType<string, string>({\n name: 'Date',\n description: 'A calendar date with no time or offset, transported as an RFC 3339 full-date string (YYYY-MM-DD).',\n specifiedByURL: 'https://datatracker.ietf.org/doc/html/rfc3339#section-5.6',\n serialize: calendarDate(UNREPRESENTABLE, true),\n parseValue: parseCalendarDate,\n parseLiteral: (ast) => {\n if (ast.kind !== Kind.STRING) {\n throw drizzleError(`Date cannot represent a ${ast.kind}`, { code: INVALID_INPUT, nodes: ast });\n }\n return parseCalendarDate(ast.value);\n },\n});\n\nexport { GraphQLDateTime, GraphQLJSON, GraphQLUUID };\n","import pluralize from 'pluralize';\n\nexport const uncapitalize = <T extends string>(input: T) =>\n (input?.length\n ? `${input[0]!.toLocaleLowerCase()}${input.length > 1 ? input.slice(1, input.length) : ''}`\n : input) as Uncapitalize<T>;\n\nexport const capitalize = <T extends string>(input: T) =>\n (input?.length\n ? `${input[0]!.toLocaleUpperCase()}${input.length > 1 ? input.slice(1, input.length) : ''}`\n : input) as Capitalize<T>;\n\nexport const singularize = <T extends string>(input: T) => pluralize.singular(input);\n\nexport const cleanTableName = <T extends string>(input: T) => singularize(uncapitalize(input));\n\nexport const tableNameToModel = <T extends string>(input: T) => singularize(capitalize(input));\n\n// (input.length\n// ? `${input[-]!.toLocaleUpperCase()}${input.length > 1 ? input.slice(1, input.length) : \"\"}`\n// : input) as Capitalize<T>;\n\n/**\n * `inProgress` / `in-progress` / `in progress` / `InProgress` → `IN_PROGRESS`; `HTTPError` →\n * `HTTP_ERROR`. Words are split at non-alphanumeric runs and at lower→upper and\n * acronym→word boundaries, then upper-cased and joined with `_`.\n *\n * The preset behind `enumValueNameMapper: 'constant'`.\n */\nexport const constantCase = (input: string): string =>\n input\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean)\n .map((part) => part.toUpperCase())\n .join('_');\n\n/**\n * The `typeNameMapper` preset behind `typeNameMapper: 'singularize'`.\n *\n * Derives the singular and plural forms of a table key with the library's own `pluralize`,\n * which is what nearly every consumer with plural table keys (`export const tasks =\n * pgTable('tasks', …)`) was writing by hand — and adding `pluralize` to their own\n * dependencies to write.\n *\n * `tasks` becomes type `Task`, queries `tasks` / `task`, mutations `createTasks` /\n * `createTask`. A key that is already singular is pluralized for the list side, so `task`\n * yields the same names, and a capitalized key (`Tasks`) yields them too — the field forms\n * are uncapitalized so the generated names follow GraphQL's camelCase convention whatever\n * the schema key looks like. The type name is capitalized by the generator either way.\n */\nexport const singularizeMapper = (tableName: string): { singular: string; plural: string } => ({\n singular: uncapitalize(pluralize.singular(tableName)),\n plural: uncapitalize(pluralize.plural(tableName)),\n});\n","import type { Column, Table } from 'drizzle-orm';\nimport { extractExtendedColumnType, getColumns, is } from 'drizzle-orm';\nimport {\n MySqlDate,\n MySqlDateString,\n MySqlDateTime,\n MySqlDateTimeString,\n MySqlInt,\n MySqlSerial,\n MySqlTimestamp,\n MySqlTimestampString,\n} from 'drizzle-orm/mysql-core';\nimport { PgDate, PgDateString, PgInteger, PgSerial, PgTimestamp, PgTimestampString, PgUUID } from 'drizzle-orm/pg-core';\nimport { SQLiteInteger, SQLiteTimestamp } from 'drizzle-orm/sqlite-core';\nimport {\n GraphQLBoolean,\n GraphQLEnumType,\n GraphQLFloat,\n GraphQLInputObjectType,\n type GraphQLInputType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n type GraphQLOutputType,\n GraphQLScalarType,\n GraphQLString,\n} from 'graphql';\nimport { capitalize, constantCase } from '../case-ops/index.ts';\nimport {\n GraphQLBigIntString,\n GraphQLDate,\n GraphQLDateTime,\n GraphQLDecimalString,\n GraphQLJSON,\n GraphQLUUID,\n} from '../scalars/index.ts';\nimport type {\n ColumnTypeMapper,\n ConvertedColumn,\n EnumNameMapper,\n EnumValueNameMapper,\n NullableConvertedColumnType,\n ScalarOverride,\n ScalarOverridesConfig,\n} from './types.ts';\n\nconst allowedNameChars = /^[a-zA-Z0-9_]+$/;\n\n/** drizzle's `number` constraints whose values always fit a GraphQL `Int` (32-bit signed). */\nconst smallIntegerConstraints = new Set<string>([\n 'int8',\n 'uint8',\n 'int16',\n 'uint16',\n 'int24',\n 'uint24',\n 'int32',\n 'year',\n]);\n\n/** A GraphQL `Name` that is also allowed as an enum value — the spec reserves the three literals. */\nconst validEnumValueName = (name: string): boolean =>\n /^[_a-zA-Z][_a-zA-Z0-9]*$/.test(name) && name !== 'true' && name !== 'false' && name !== 'null';\n\n/**\n * The enum type a column was declared with, when it is a *named* one — `pgEnum('status', …)`\n * shared by however many tables reference it. An inline value list (`text({ enum: [...] })`,\n * `mysqlEnum('role', [...])`) has no such object: the values belong to that one column.\n */\nconst declaredEnum = (column: Column): { enumName: string; schema: string | undefined } | undefined => {\n const declared = (column as any).enum as { enumName?: unknown; schema?: unknown } | undefined;\n return typeof declared?.enumName === 'string'\n ? { enumName: declared.enumName, schema: typeof declared.schema === 'string' ? declared.schema : undefined }\n : undefined;\n};\n\n/** `user_status` / `user-status` / `user status` → `UserStatus`; an already-PascalCase name is left alone. */\nconst pascalize = (input: string): string =>\n input\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean)\n .map((part) => capitalize(part))\n .join('');\n\n/**\n * Identity of the values a GraphQL enum was built from, so a name claimed twice can be told\n * apart from the same enum reached twice.\n */\nconst enumValuesKey = (values: readonly string[]): string => JSON.stringify(values);\n\n/**\n * Identity of the GraphQL names those values were given. Kept apart from {@link enumValuesKey}\n * because `enumValueNameMapper` sees the column, so two columns reaching one type can name its\n * values differently — and only one set of names can win.\n */\nconst enumValueNamesKey = (names: readonly string[]): string => JSON.stringify(names);\n\n/**\n * Every GraphQL enum name this build has handed out. Two columns that resolve to the same\n * name share one type — that is how the columns of one `pgEnum` end up on a single type —\n * so the values are kept alongside it to tell a genuine collision from a re-use.\n */\nlet enumNamesInUse = new Map<string, { type: GraphQLEnumType; valuesKey: string; namesKey: string }>();\nlet enumNameMapper: EnumNameMapper | undefined;\nlet enumValueNameMapper: EnumValueNameMapper | undefined;\n\n/** The value-name presets, by the string a config passes for them. */\nconst enumValueNamePresets: Record<string, EnumValueNameMapper> = {\n constant: ({ value }) => constantCase(value),\n};\n\n/**\n * Resets the enum registry for a fresh schema build and installs that build's\n * `enumNameMapper` and `enumValueNameMapper`. Called once per `generateSchemaData`, alongside\n * {@link registerScalarOverrides} — without the reset a second build would reuse the first\n * build's enum types, and so its naming decisions.\n */\nexport const registerEnumConfig = (config: {\n enumNameMapper?: EnumNameMapper;\n enumValueNameMapper?: 'constant' | EnumValueNameMapper;\n}): void => {\n enumNameMapper = config.enumNameMapper;\n const valueMapper = config.enumValueNameMapper;\n if (typeof valueMapper === 'string') {\n const preset = enumValueNamePresets[valueMapper];\n if (!preset) {\n throw new Error(\n `Drizzle-GraphQL Error: Unknown enumValueNameMapper preset '${valueMapper}'. The only preset is 'constant'; pass a function for anything else.`,\n );\n }\n enumValueNameMapper = preset;\n } else {\n enumValueNameMapper = valueMapper;\n }\n enumNamesInUse = new Map();\n};\n\n/**\n * The GraphQL enum for a column's value list.\n *\n * The name decides the sharing: a column declared with a named `pgEnum` is named for the\n * enum, so every column declared with that same `pgEnum` lands on one GraphQL type — the\n * database column is literally the same type, and a client variable typed `StatusEnum!`\n * should be passable to any of them. A column with an inline value list is named for the\n * table and column instead, and so keeps a type of its own; its values are not shared with\n * anything.\n *\n * `enumNameMapper` is consulted for every column and overrides that name either way, which\n * makes it both the way to unify inline enums that were declared separately but mean the\n * same thing, and the way to split apart columns of one `pgEnum` that should not share.\n * Sending two *different* value lists to one name is a build-time error rather than an\n * invalid schema.\n */\nconst generateEnumCached = (column: Column, columnName: string, tableName: string): GraphQLEnumType => {\n const declared = declaredEnum(column);\n const values = column.enumValues!;\n const name =\n enumNameMapper?.({\n enumName: declared?.enumName,\n schema: declared?.schema,\n tableName,\n columnName,\n values,\n }) ?? (declared ? `${pascalize(declared.enumName)}Enum` : `${capitalize(tableName)}${capitalize(columnName)}Enum`);\n\n const valueNames = values.map((value, index) => {\n const mapped = enumValueNameMapper?.({\n enumName: declared?.enumName,\n schema: declared?.schema,\n tableName,\n columnName,\n values,\n value,\n index,\n typeName: name,\n });\n if (mapped === undefined) {\n return allowedNameChars.test(value) ? value : `Option${index}`;\n }\n if (!validEnumValueName(mapped)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.enumValueNameMapper named value '${value}' of enum '${name}' (on '${tableName}.${columnName}') '${mapped}', which is not a valid GraphQL enum value name. A name must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ and not be true, false or null.`,\n );\n }\n return mapped;\n });\n\n const seen = new Map<string, string>();\n values.forEach((value, index) => {\n const valueName = valueNames[index]!;\n const earlier = seen.get(valueName);\n if (earlier !== undefined) {\n throw new Error(\n `Drizzle-GraphQL Error: Values '${earlier}' and '${value}' of enum '${name}' (on '${tableName}.${columnName}') both map to the GraphQL value name '${valueName}'. Give one of them a different name via config.enumValueNameMapper.`,\n );\n }\n seen.set(valueName, value);\n });\n\n const valuesKey = enumValuesKey(values);\n const namesKey = enumValueNamesKey(valueNames);\n const claimed = enumNamesInUse.get(name);\n if (claimed) {\n if (claimed.valuesKey !== valuesKey) {\n throw new Error(\n `Drizzle-GraphQL Error: Two different enums both map to the GraphQL type name '${name}' (most recently '${tableName}.${columnName}'). Give one of them a different name via config.enumNameMapper.`,\n );\n }\n if (claimed.namesKey !== namesKey) {\n const before = claimed.type\n .getValues()\n .map((v) => v.name)\n .join(', ');\n throw new Error(\n `Drizzle-GraphQL Error: Columns sharing the GraphQL enum '${name}' name its values differently ('${tableName}.${columnName}' gives ${valueNames.join(', ')}; an earlier column gave ${before}). config.enumValueNameMapper must name a shared enum's values the same way for every column, or config.enumNameMapper must give the columns separate types.`,\n );\n }\n return claimed.type;\n }\n\n const gqlEnum = new GraphQLEnumType({\n name,\n values: Object.fromEntries(\n values.map((e, index) => [\n valueNames[index]!,\n {\n value: e,\n description: `Value: ${e}`,\n },\n ]),\n ),\n });\n\n enumNamesInUse.set(name, { type: gqlEnum, valuesKey, namesKey });\n\n return gqlEnum;\n};\n\nconst geoXyType = new GraphQLObjectType({\n name: 'PgGeometryObject',\n fields: {\n x: { type: GraphQLFloat },\n y: { type: GraphQLFloat },\n },\n});\n\nconst geoXyInputType = new GraphQLInputObjectType({\n name: 'PgGeometryObjectInput',\n fields: {\n x: { type: GraphQLFloat },\n y: { type: GraphQLFloat },\n },\n});\n\n/**\n * Whether the column holds a calendar day with no time component — a SQL `date`, in either of\n * the modes drizzle reads one in (`'date'` → a JS `Date`, `'string'` → `YYYY-MM-DD`). Every\n * position a column's type appears in — output, create/update input, filter operands,\n * aggregates and group keys — gives such a column the `Date` scalar, whichever mode it uses:\n * the mode is how the server holds the value, not what the value is. SQLite has no date-only\n * column type (its integer timestamps are instants — see {@link isDateTimeColumn}), so only\n * Postgres and MySQL appear here.\n */\nexport const isDateOnlyColumn = (column: Column): boolean =>\n is(column, PgDate) || is(column, PgDateString) || is(column, MySqlDate) || is(column, MySqlDateString);\n\n/**\n * Whether the column is a MySQL `timestamp` / `datetime` read in drizzle's `'string'` mode. The\n * driver hands such a column back as MySQL's own `YYYY-MM-DD HH:MM:SS[.fraction]` text, with no\n * offset, and expects that form on write, so the data mappers translate between it and the ISO\n * 8601 instant the `DateTime` scalar carries. The text is read as UTC, the way drizzle's own\n * `'date'`-mode codecs for these columns read it.\n */\nexport const isMySqlDateTimeStringColumn = (column: Column): boolean =>\n is(column, MySqlTimestampString) || is(column, MySqlDateTimeString);\n\n/**\n * Whether the column is a Postgres `timestamp` read in drizzle's `'string'` mode. The driver hands\n * such a column back as Postgres's own text — `YYYY-MM-DD HH:MM:SS[.fraction]`, followed by an\n * offset (`+00`, `-06`, `+05:30`) for `timestamptz` — so the data mappers translate between it\n * and the ISO 8601 instant the `DateTime` scalar carries. Text without an offset (`timestamp`\n * without time zone) is read as UTC, the way drizzle's own `'date'`-mode codec reads it.\n */\nexport const isPgTimestampStringColumn = (column: Column): boolean => is(column, PgTimestampString);\n\n/**\n * Whether the column is a SQLite `integer({ mode: 'timestamp' | 'timestamp_ms' })`. Both modes\n * are one drizzle class, told apart by `mode`: the stored integer counts seconds or milliseconds\n * since the Unix epoch. drizzle converts a JS `Date` to that integer on write (`'timestamp'`\n * floors to the whole second) and back on read, but a value read through a path that skips the\n * column's decoder arrives as the bare integer, which {@link sqliteTimestampToDate} reads.\n */\nexport const isSQLiteTimestampColumn = (column: Column): boolean => is(column, SQLiteTimestamp);\n\n/**\n * A SQLite timestamp column's stored integer as the instant it names, using the column's own\n * unit (seconds for `'timestamp'`, milliseconds for `'timestamp_ms'`).\n */\nexport const sqliteTimestampToDate = (column: Column, value: number): Date =>\n new Date((column as any).mode === 'timestamp' ? value * 1000 : value);\n\n/**\n * Whether the column holds an instant — a Postgres `timestamp`, a MySQL `timestamp` /\n * `datetime`, in either drizzle mode, or a SQLite integer timestamp in either unit. Every position\n * such a column appears in gives it the `DateTime` scalar and the `DateTimeFilter`, whichever\n * mode it uses, for the same reason as {@link isDateOnlyColumn}.\n */\nexport const isDateTimeColumn = (column: Column): boolean =>\n is(column, PgTimestamp) ||\n isPgTimestampStringColumn(column) ||\n is(column, MySqlTimestamp) ||\n is(column, MySqlDateTime) ||\n isMySqlDateTimeStringColumn(column) ||\n isSQLiteTimestampColumn(column);\n\nconst columnToGraphQLCore = (\n column: Column,\n columnName: string,\n tableName: string,\n isInput: boolean,\n): ConvertedColumn<boolean> => {\n // drizzle-orm v1 models `.array()` columns as their base column plus a `dimensions` count\n // (e.g. text().array() keeps columnType=PgText with dimensions=1), so the element type is\n // whatever the base column maps to. PgVector/PgGeometry report dimensions of 0 and keep\n // their dedicated handling below.\n const dimensions = (column as any).dimensions as number | undefined;\n if (dimensions !== undefined && dimensions > 0) {\n const inner = columnBaseToGraphQLCore(column, columnName, tableName, isInput);\n const innerLabel = inner.typeLabel ?? (inner.type as GraphQLScalarType).name;\n\n let type: ConvertedColumn<boolean>['type'] = inner.type;\n let typeLabel = innerLabel;\n for (let i = 0; i < dimensions; i++) {\n type = new GraphQLList(new GraphQLNonNull(type as GraphQLScalarType));\n typeLabel = `Array<${typeLabel}>`;\n }\n\n return { type, typeLabel };\n }\n\n return columnBaseToGraphQLCore(column, columnName, tableName, isInput);\n};\n\nconst columnBaseToGraphQLCore = (\n column: Column,\n columnName: string,\n tableName: string,\n isInput: boolean,\n): ConvertedColumn<boolean> => {\n const { type: baseType, constraint } = extractExtendedColumnType(column);\n switch (baseType) {\n case 'boolean':\n return { type: GraphQLBoolean, typeLabel: 'Boolean' };\n case 'object':\n if (isDateOnlyColumn(column)) {\n return { type: GraphQLDate, typeLabel: 'Date' };\n }\n if (isDateTimeColumn(column)) {\n return { type: GraphQLDateTime, typeLabel: 'DateTime' };\n }\n return column.columnType === 'PgGeometryObject'\n ? {\n type: isInput ? geoXyInputType : geoXyType,\n typeLabel: 'Geometry points XY',\n }\n : column.columnType === 'PgBytea'\n ? {\n type: new GraphQLList(new GraphQLNonNull(GraphQLInt)),\n typeLabel: 'Buffer',\n }\n : { type: GraphQLJSON, typeLabel: 'JSON' };\n case 'string':\n if (column.enumValues?.length) {\n return { type: generateEnumCached(column, columnName, tableName) };\n }\n\n // numeric/decimal columns (pg numeric, mysql decimal, sqlite numeric) transport as\n // strings, but they are numbers — give them the named Decimal scalar so the SDL says\n // so and non-numeric input is rejected. Array-typed numeric columns (dimensions > 0)\n // keep their existing mapping.\n if (constraint === 'numeric' && !(column as any).dimensions) {\n return { type: GraphQLDecimalString, typeLabel: 'Decimal' };\n }\n\n if (isDateTimeColumn(column)) {\n return { type: GraphQLDateTime, typeLabel: 'DateTime' };\n }\n if (column instanceof PgUUID) {\n return { type: GraphQLUUID, typeLabel: 'UUID' };\n }\n if (isDateOnlyColumn(column)) {\n return { type: GraphQLDate, typeLabel: 'Date' };\n }\n\n return { type: GraphQLString, typeLabel: 'String' };\n case 'bigint':\n return { type: GraphQLBigIntString, typeLabel: 'BigInt' };\n case 'number': {\n // Every integer kind that fits GraphQL's 32-bit signed Int: smallint / tinyint /\n // mediumint / smallserial and MySQL `year` report these constraints in drizzle v1, and\n // used to fall through to Float. Wider kinds (int53, uint32, uint53) are matched only\n // through the column classes below, as before.\n return (constraint !== undefined && smallIntegerConstraints.has(constraint)) ||\n is(column, PgInteger) ||\n is(column, PgSerial) ||\n is(column, MySqlInt) ||\n is(column, MySqlSerial) ||\n is(column, SQLiteInteger)\n ? { type: GraphQLInt, typeLabel: 'Integer' }\n : { type: GraphQLFloat, typeLabel: 'Float' };\n }\n case 'array': {\n if (column.columnType === 'PgVector') {\n return {\n type: new GraphQLList(new GraphQLNonNull(GraphQLFloat)),\n typeLabel: 'Array<Float>',\n };\n }\n\n if (column.columnType === 'PgGeometry') {\n return {\n type: new GraphQLList(new GraphQLNonNull(GraphQLFloat)),\n typeLabel: 'Tuple<[Float, Float]>',\n };\n }\n\n const innerType = columnToGraphQLCore(\n (column as unknown as { baseColumn: Column }).baseColumn,\n columnName,\n tableName,\n isInput,\n );\n\n return {\n type: new GraphQLList(new GraphQLNonNull(innerType.type as GraphQLScalarType)),\n typeLabel: `Array<${innerType.typeLabel}>`,\n };\n }\n default:\n throw new Error(`Drizzle-GraphQL Error: Type ${column.dataType} is not implemented!`);\n }\n};\n\n/**\n * Per-column scalar overrides, resolved at build time from `BuildSchemaConfig.scalars` /\n * `BuildSchemaConfig.mapColumnType` and consulted by every column→GraphQL type decision\n * (select fields, insert/update inputs, filter operands, aggregate min/max) as well as by\n * the runtime data mappers, which must not re-coerce a value an override scalar owns.\n *\n * Keyed weakly by the column object itself so the registry never outlives the schema.\n * `registerScalarOverrides` runs on every build and clears entries for columns that no\n * longer have an override; when two live schemas are built from the same table objects\n * with different scalar configs, the most recent build wins for runtime value mapping.\n */\nconst columnScalarOverrides = new WeakMap<Column, { output?: GraphQLScalarType; input?: GraphQLScalarType }>();\n\n/** The scalar overriding this column in the given direction, if one was registered. */\nexport const getColumnScalarOverride = (column: Column, isInput: boolean): GraphQLScalarType | undefined => {\n const override = columnScalarOverrides.get(column);\n return override ? (isInput ? override.input : override.output) : undefined;\n};\n\nconst normalizeScalarOverride = (\n override: ScalarOverride,\n tableName: string,\n columnName: string,\n): { output?: GraphQLScalarType; input?: GraphQLScalarType } => {\n const pair =\n override instanceof GraphQLScalarType\n ? { output: override, input: override }\n : { output: override.output, input: override.input };\n\n for (const scalar of [pair.output, pair.input]) {\n if (scalar !== undefined && !(scalar instanceof GraphQLScalarType)) {\n throw new Error(\n `Drizzle-GraphQL Error: Scalar override for column '${tableName}.${columnName}' must be a GraphQLScalarType!`,\n );\n }\n }\n\n return pair;\n};\n\n/**\n * Resolves the scalar-override config against every column of the given tables and stores\n * the result in the override registry. Called once per schema build, before any types are\n * generated — and always, even with no config, so a rebuild clears overrides left behind\n * by a previous build against the same table objects.\n *\n * The declarative `scalars` map wins over `mapColumnType`; a mapper returning `undefined`\n * leaves the column on built-in detection.\n */\nexport const registerScalarOverrides = (\n tables: Record<string, Table>,\n config: { scalars?: ScalarOverridesConfig; mapColumnType?: ColumnTypeMapper },\n): void => {\n for (const [tableName, table] of Object.entries(tables)) {\n for (const [columnName, column] of Object.entries(getColumns(table))) {\n const declared = config.scalars?.[tableName]?.[columnName];\n\n let resolved: { output?: GraphQLScalarType; input?: GraphQLScalarType } | undefined;\n if (declared !== undefined) {\n resolved = normalizeScalarOverride(declared, tableName, columnName);\n } else if (config.mapColumnType) {\n // Built-in detection throws for column types it has no mapping for; the mapper is\n // exactly the tool to type such columns, so a failed default becomes `undefined`\n // rather than an error.\n let defaultType: GraphQLOutputType | undefined;\n let defaultInputType: GraphQLInputType | undefined;\n try {\n defaultType = columnToGraphQLCore(column, columnName, tableName, false).type as GraphQLOutputType;\n } catch {}\n try {\n defaultInputType = columnToGraphQLCore(column, columnName, tableName, true).type as GraphQLInputType;\n } catch {}\n\n const mapped = config.mapColumnType(column, { tableName, columnName, defaultType, defaultInputType });\n if (mapped !== undefined) {\n resolved = normalizeScalarOverride(mapped, tableName, columnName);\n }\n }\n\n if (resolved && (resolved.output !== undefined || resolved.input !== undefined)) {\n columnScalarOverrides.set(column, resolved);\n } else {\n columnScalarOverrides.delete(column);\n }\n }\n }\n};\n\nexport const drizzleColumnToGraphQLType = <TColumn extends Column, TIsInput extends boolean = false>(\n column: TColumn,\n columnName: string,\n tableName: string,\n forceNullable = false,\n defaultIsNullable = false,\n isInput: TIsInput = false as TIsInput,\n): ConvertedColumn<TIsInput> => {\n const override = getColumnScalarOverride(column, isInput);\n // An override replaces built-in detection entirely, so the label is the scalar's own name:\n // nothing downstream should treat an overridden column as the type it would have had.\n const typeDesc: ConvertedColumn<boolean> = override\n ? { type: override, typeLabel: override.name }\n : columnToGraphQLCore(column, columnName, tableName, isInput);\n\n if (forceNullable) {\n return typeDesc as ConvertedColumn<TIsInput>;\n }\n if (column.notNull && !(defaultIsNullable && (column.hasDefault || column.defaultFn))) {\n return {\n // Neither branch above wraps, so this is the only wrapper the column ever gets; the cast\n // narrows the declared union to the nullable half graphql 17's constructor accepts.\n type: new GraphQLNonNull(typeDesc.type as NullableConvertedColumnType<boolean>),\n typeLabel: typeDesc.typeLabel,\n } as ConvertedColumn<TIsInput>;\n }\n\n return typeDesc as ConvertedColumn<TIsInput>;\n};\n","// Every name the build gives a generated type, in one place.\n//\n// `typeNameMapper` names a table's object type and its root fields. It does not reach the\n// types generated *around* that table — the filter, the write inputs, the order-by, the\n// aggregate family — which are derived from that name by a fixed rule. A build that stitches\n// its schema next to a second generator over the same tables collides on exactly those\n// derived names, and had no hook to say otherwise.\n//\n// Both levers here answer that. `derivedTypeNameMapper` is asked for every type the build\n// creates and may decline, so a single kind can be renamed and nothing else moves;\n// `typeNamePrefix` / `typeNameSuffix` wrap every name the mapper did not answer for, which is\n// the one-line way to make a whole subschema collision-free.\n\nimport type { GraphQLNamedType } from 'graphql';\n\n/**\n * What a generated type is, so a name mapper can answer for one kind without matching on the\n * spelling of the default name.\n *\n * - `object` — a table's row type, the one `typeNameMapper` already names\n * - `filter` / `listRelationFilter` — `<Type>Filters` and the `some`/`none`/`every` wrapper\n * - `orderBy` — `<Type>OrderBy`\n * - `createInput` / `updateInput` / `updateManyInput` / `nestedWriteInput` / `fieldUpdateInput`\n * — the write inputs\n * - `aggregate` — `<Type>Aggregate` and its per-operation children (`operation` names which)\n * - `having` / `groupBy` / `groupKeys` — the group-by family\n * - `onConflict` — the upsert's conflict input\n * - `uniqueKey` — a compound unique constraint's key input\n * - `columnEnum` — an enum naming a table's columns (`distinct`, conflict target, …)\n * - `columnFilter` — a shared per-scalar filter (`StringFilter`, `IntFilter`, …), not per table\n * - `shared` — everything else the build creates once (`OrderNulls`, `DeletedFilter`, …)\n */\nexport type GeneratedTypeKind =\n | 'object'\n | 'filter'\n | 'listRelationFilter'\n | 'orderBy'\n | 'createInput'\n | 'updateInput'\n | 'updateManyInput'\n | 'nestedWriteInput'\n | 'fieldUpdateInput'\n | 'aggregate'\n | 'having'\n | 'groupBy'\n | 'groupKeys'\n | 'onConflict'\n | 'uniqueKey'\n | 'columnEnum'\n | 'columnFilter'\n | 'shared';\n\n/** What a name mapper is told about the type it is being asked to name. */\nexport interface GeneratedTypeInfo {\n /** Which kind of generated type this is. */\n kind: GeneratedTypeKind;\n /** The name the library would use, before any prefix or suffix. */\n defaultName: string;\n /** The table key the type belongs to, where it belongs to one. */\n table?: string;\n /**\n * The narrower thing the type is for, where the kind alone does not say: the aggregate\n * operation (`sum`, `avg`, …), the relation a nested-write input is for, the scalar a\n * column filter covers, the columns of a unique key.\n */\n operation?: string;\n}\n\n/**\n * Renames a generated type. Return `undefined` — or the same name — to keep the default,\n * which is what an unlisted kind should do; anything returned is used verbatim, without the\n * build's prefix or suffix.\n */\nexport type DerivedTypeNameMapper = (info: GeneratedTypeInfo) => string | undefined;\n\n/** The build's resolved naming rule, asked at every type construction. */\nexport type TypeNameResolver = (info: GeneratedTypeInfo) => string;\n\n/** The naming knobs `resolveGeneratedTypeNames` reads off the build config. */\nexport interface GeneratedTypeNameConfig {\n derivedTypeNameMapper?: DerivedTypeNameMapper;\n typeNamePrefix?: string;\n typeNameSuffix?: string;\n}\n\n/**\n * The build's naming rule: the mapper's answer where it has one, otherwise the default name\n * wrapped in the build's prefix and suffix.\n *\n * A build that configures neither gets the identity function, so the fast path costs a\n * property read and today's schemas are byte-for-byte unchanged.\n */\nexport const resolveGeneratedTypeNames = (config: GeneratedTypeNameConfig | undefined): TypeNameResolver => {\n const mapper = config?.derivedTypeNameMapper;\n const prefix = config?.typeNamePrefix ?? '';\n const suffix = config?.typeNameSuffix ?? '';\n\n if (!mapper && !prefix && !suffix) {\n return (info) => info.defaultName;\n }\n\n return (info) => {\n const mapped = mapper?.(info);\n // Verbatim: the caller named this type explicitly, so wrapping it would be overruling\n // the more specific of the two knobs with the blunter one.\n return mapped || `${prefix}${info.defaultName}${suffix}`;\n };\n};\n\n// Types the build creates once rather than per table — `OrderNulls`, `StringFilter` and the\n// like — used to be module-level constants, shared by every build in the process. They still\n// are, but keyed by the name they resolved to: two builds that name a type the same way share\n// one instance exactly as before, and a build that renames it gets its own.\nconst sharedTypeCache = new Map<string, GraphQLNamedType>();\n\n/**\n * A build-wide shared type, built once per name it is known by.\n *\n * @param build receives the resolved name — the type must be constructed with it, not with\n * the default the caller passed in\n */\nexport const sharedType = <T extends GraphQLNamedType>(\n typeName: TypeNameResolver,\n info: GeneratedTypeInfo,\n build: (name: string) => T,\n): T => {\n const name = typeName(info);\n const cached = sharedTypeCache.get(name);\n if (cached) {\n return cached as T;\n }\n const built = build(name);\n sharedTypeCache.set(name, built);\n return built;\n};\n","// The filter input types, generated per column *shape* rather than per (table, column) pair —\n// the local modification `../common.ts` describes. Which descriptor a column gets is decided by\n// its data type, its dialect, and any scalar override the caller configured.\n\nimport type { Column } from 'drizzle-orm';\nimport { extractExtendedColumnType } from 'drizzle-orm';\nimport {\n GraphQLBoolean,\n GraphQLEnumType,\n GraphQLFloat,\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n type GraphQLScalarType,\n GraphQLString,\n} from 'graphql';\nimport {\n GraphQLBigIntString,\n GraphQLDate,\n GraphQLDateTime,\n GraphQLDecimalString,\n GraphQLJSON,\n GraphQLUUID,\n} from '../../scalars/index.ts';\nimport { drizzleColumnToGraphQLType, getColumnScalarOverride, isDateTimeColumn } from '../../type-converter/index.ts';\nimport type { ConvertedColumn, NullableConvertedColumnType } from '../../type-converter/types.ts';\nimport type { TypeCacheCtx } from './type-cache.ts';\nimport { sharedType, type TypeNameResolver } from './type-names.ts';\n\n/** The dialect a column belongs to, inferred from its drizzle columnType string (e.g. 'PgJsonb'). */\nexport const columnDialect = (column: Column): 'pg' | 'mysql' | 'sqlite' | undefined => {\n const ct: string = (column as any).columnType ?? '';\n if (ct.startsWith('Pg')) {\n return 'pg';\n }\n if (ct.startsWith('MySql')) {\n return 'mysql';\n }\n if (ct.startsWith('SQLite')) {\n return 'sqlite';\n }\n return undefined;\n};\n\n/**\n * Whether the column stores JSON.\n *\n * Decided on drizzle's `dataType`, its semantic marker, rather than on `columnType`, which\n * names the implementing class. drizzle-orm v1 uses compound dataType strings (`\"object\n * json\"` for every json/jsonb column across the three dialects), hence the inclusion test.\n *\n * `PgGeometryObject` is excluded explicitly. That is currently redundant — it reports\n * `\"object geometry\"` — but it is stored as json, has its own object type in the generated\n * schema, and must not be reclassified if drizzle ever spells its dataType differently.\n *\n * One predicate for two callers that must agree: the filter builder, whose `path` and\n * `contains` operators mean structural JSON containment rather than the string operators,\n * and the data mappers, which transport a JSON value as-is instead of remapping it. They\n * previously had a copy each, asking different questions of the column.\n */\nexport const isJsonColumn = (column: Column): boolean =>\n ((column as any).dataType ?? '').includes('json') && (column as any).columnType !== 'PgGeometryObject';\n\n/** How a column's generic filter input should be shaped, alongside the cache key to store it under. */\ninterface GenericFilterDescriptor {\n name: string;\n kind: 'scalar' | 'json' | 'array';\n /**\n * True for an enum column. Enum filter types are named after the enum, so they cannot be\n * recognised by name the way the built-in filters below are — but they want the same lean\n * operator set as `Boolean`: a closed set of members has nothing to pattern-match and no\n * order beyond the accident of how the column was declared.\n */\n isEnum?: boolean;\n}\n\n/**\n * Maps a Drizzle column to the generic filter type to use.\n *\n * Selection is keyed on the column's data type, never its name: a text column named\n * `userId` gets the full String filter (string operators included), while a uuid column\n * gets the lean Id filter whatever it is called.\n * - \"JSON\" → json/jsonb columns (eq/ne + containment, no scalar comparison ops)\n * - `${Element}Array` → array columns, keyed per element type (IntArray, FloatArray,\n * StringArray, …) so arrays with different element types never share\n * one filter input; membership operators instead of scalar comparisons\n * - \"Id\" → uuid-typed columns (no string pattern operators)\n * - \"Boolean\" → boolean columns (equality and membership only — no ordering, no patterns)\n * - \"BigInt\" → bigint columns (BigInt-scalar-typed operators, no string pattern operators)\n * - \"Decimal\" → numeric/decimal columns (Decimal-scalar-typed operators, no string pattern operators)\n * - the enum GraphQL type name → enum columns (still unique per enum; equality and\n * membership only, like Boolean)\n * - \"Date\" → date columns, either mode (ordering kept, no string pattern operators)\n * - \"DateTime\" → timestamp columns (ordering kept, no string pattern operators)\n * - \"Int\" → integer/serial columns (no string pattern operators)\n * - \"Float\" → real/double columns (no string pattern operators)\n * - \"String\" → all other text/varchar columns\n */\nconst resolveGenericFilterDescriptor = (\n column: Column,\n columnGraphQLType: ReturnType<typeof drizzleColumnToGraphQLType>,\n): GenericFilterDescriptor => {\n // JSON / JSONB columns — structural values with their own operator set.\n if (columnGraphQLType.type === GraphQLJSON) {\n return { name: 'JSON', kind: 'json' };\n }\n // Array columns — keyed per element type so an int[] and a text[] column never share\n // one cached filter input.\n if (columnGraphQLType.type instanceof GraphQLList) {\n let element = columnGraphQLType.type.ofType;\n if (element instanceof GraphQLNonNull) {\n element = element.ofType;\n }\n return { name: `${element.name}Array`, kind: 'array' };\n }\n // Opaque uuid keys — keyed on the column type, not on an `id`/`*Id` naming convention.\n if (columnGraphQLType.type === GraphQLUUID) {\n return { name: 'Id', kind: 'scalar' };\n }\n // Boolean scalar\n if (columnGraphQLType.type === GraphQLBoolean) {\n return { name: 'Boolean', kind: 'scalar' };\n }\n // Enum type — keep unique per enum since values differ\n if (columnGraphQLType.type instanceof GraphQLEnumType) {\n return { name: columnGraphQLType.type.name, kind: 'scalar', isEnum: true };\n }\n // Named numeric-string scalars — give them their own filters so the operators\n // are typed with the scalar (and validated by it) instead of a shared StringFilter.\n if (columnGraphQLType.type === GraphQLBigIntString) {\n return { name: 'BigInt', kind: 'scalar' };\n }\n if (columnGraphQLType.type === GraphQLDecimalString) {\n return { name: 'Decimal', kind: 'scalar' };\n }\n // Calendar-date columns, in either drizzle mode — the type converter gives them the `Date`\n // scalar, so the operands are `Date` too and a datetime string is rejected in a filter\n // exactly as it is in a write.\n if (columnGraphQLType.type === GraphQLDate) {\n return { name: 'Date', kind: 'scalar' };\n }\n // Timestamp / datetime columns, in either drizzle mode.\n if (isDateTimeColumn(column)) {\n return { name: 'DateTime', kind: 'scalar' };\n }\n // Numeric scalars — distinct names so an int/float column never shares (and never\n // mistypes) the StringFilter, and integer ids keep a filter without string operators.\n // (BigInt/Decimal columns are handled above via their named scalars.)\n if (columnGraphQLType.type === GraphQLInt) {\n return { name: 'Int', kind: 'scalar' };\n }\n if (columnGraphQLType.type === GraphQLFloat) {\n return { name: 'Float', kind: 'scalar' };\n }\n // Default: plain text/varchar\n return { name: 'String', kind: 'scalar' };\n};\n\n/**\n * Filter fields for a json/jsonb column. `eq`/`ne` compare the whole document (jsonb equality\n * on Postgres, driver-level comparison elsewhere); `contains` is structural containment —\n * Postgres `@>` / MySQL `JSON_CONTAINS`. SQLite stores json as text and has no containment\n * operator, so `contains` is omitted there (same precedent as dialect-specific ops like ilike).\n */\nconst jsonFilterFields = (column: Column, colType: ConvertedColumn<true>['type'], typeName: TypeNameResolver) => {\n const dialect = columnDialect(column);\n return {\n eq: { type: colType, description: 'JSON equality on the whole value' },\n ne: { type: colType, description: 'JSON inequality on the whole value' },\n ...(dialect === 'pg' || dialect === 'mysql'\n ? {\n contains: {\n type: colType,\n description: 'Value structurally contains this JSON (Postgres `@>` / MySQL JSON_CONTAINS)',\n },\n }\n : {}),\n path: {\n type: new GraphQLList(new GraphQLNonNull(jsonPathFilterType(typeName))),\n description:\n 'Compares the value at one path inside the document. Several entries are ANDed; a single object may be passed without the list brackets.',\n },\n isNull: { type: GraphQLBoolean },\n isNotNull: { type: GraphQLBoolean },\n };\n};\n\n/**\n * How the value at a JSON path is read before it is compared. Left unset, the operand\n * decides: a GraphQL number compares numerically, a boolean as a boolean, anything else as\n * text. Set it when the operand's type does not match the document's — comparing a numeric\n * field against a `String` variable, say.\n */\nconst jsonPathCastType = (typeName: TypeNameResolver): GraphQLEnumType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'JSONPathCast' },\n (name) =>\n new GraphQLEnumType({\n name,\n description: 'How to read the value at a JSON path before comparing it',\n values: {\n TEXT: { value: 'text', description: 'Compare as text (lexicographic ordering)' },\n NUMBER: { value: 'number', description: 'Compare as a number; a non-numeric value never matches' },\n BOOLEAN: { value: 'boolean', description: 'Compare as a boolean' },\n },\n }),\n );\n\n/**\n * One predicate on the value at a path inside a json/jsonb column. `path` walks the document\n * key by key (an all-digits element indexes an array), and the remaining operators compare\n * whatever sits there. Operands are `JSON` so a single input type serves string, number and\n * boolean fields; see {@link jsonPathCast} for how the comparison type is chosen.\n *\n * Note that `contains` here is substring matching on the extracted value — unlike `contains`\n * on the column itself, which is structural JSON containment. A path names a scalar, so the\n * string reading is the useful one.\n */\nconst jsonPathFilterType = (typeName: TypeNameResolver): GraphQLInputObjectType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'JSONPathFilter' },\n (name) =>\n new GraphQLInputObjectType({\n name,\n fields: {\n path: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLString))),\n description:\n 'Keys to walk from the document root, e.g. `[\"profile\", \"level\"]`. An all-digits key indexes an array.',\n },\n as: { type: jsonPathCastType(typeName), description: 'Overrides how the value is read before comparing' },\n eq: { type: GraphQLJSON, description: 'Equal to' },\n ne: { type: GraphQLJSON, description: 'Not equal to' },\n lt: { type: GraphQLJSON, description: 'Less than' },\n lte: { type: GraphQLJSON, description: 'Less than or equal to' },\n gt: { type: GraphQLJSON, description: 'Greater than' },\n gte: { type: GraphQLJSON, description: 'Greater than or equal to' },\n startsWith: {\n type: GraphQLString,\n description: 'Extracted value starts with this string. `%`, `_` and `\\\\` are matched literally.',\n },\n endsWith: {\n type: GraphQLString,\n description: 'Extracted value ends with this string. `%`, `_` and `\\\\` are matched literally.',\n },\n contains: {\n type: GraphQLString,\n description: 'Extracted value contains this string. `%`, `_` and `\\\\` are matched literally.',\n },\n iStartsWith: { type: GraphQLString, description: 'Case-insensitive `startsWith`.' },\n iEndsWith: { type: GraphQLString, description: 'Case-insensitive `endsWith`.' },\n iContains: { type: GraphQLString, description: 'Case-insensitive `contains`.' },\n isNull: {\n type: GraphQLBoolean,\n description: 'When true, matches rows where the path is missing or holds JSON null',\n },\n isNotNull: { type: GraphQLBoolean, description: 'When true, matches rows where the path holds a value' },\n },\n }),\n );\n\n/**\n * `inArray` / `notInArray` take a list of candidate values and compile to SQL `IN` /\n * `NOT IN`. Their descriptions are fixed rather than derived from the column: what the\n * operator does is the same everywhere, and the operand type already says what goes in it.\n */\nconst IN_ARRAY_DESCRIPTION = 'Matches any one of these values (SQL `IN`)';\nconst NOT_IN_ARRAY_DESCRIPTION = 'Matches none of these values (SQL `NOT IN`)';\n\n/**\n * Filter fields for an array column (Postgres-only in drizzle). Membership operators replace\n * the scalar comparison and string pattern sets: `has` checks a single element (`@>` with a\n * one-element array), `hasSome` is overlap (`&&`), `hasEvery` is containment (`@>`), `isEmpty`\n * matches arrays with no elements. `eq`/`ne` still compare the whole array, and\n * `inArray`/`notInArray` still match the whole array against a list of candidate arrays\n * (SQL `IN`, typed `[[Element!]!]`).\n */\nconst arrayFilterFields = (colType: GraphQLList<any>, colArr: GraphQLList<any>) => {\n let element = colType.ofType;\n if (element instanceof GraphQLNonNull) {\n element = element.ofType;\n }\n const elementList = new GraphQLList(new GraphQLNonNull(element));\n\n return {\n eq: { type: colType, description: 'The whole array equals this array' },\n ne: { type: colType, description: 'The whole array differs from this array' },\n has: { type: element, description: 'Array contains this element' },\n hasSome: { type: elementList, description: 'Array contains at least one of these elements (overlap, `&&`)' },\n hasEvery: { type: elementList, description: 'Array contains every one of these elements (containment, `@>`)' },\n isEmpty: { type: GraphQLBoolean, description: 'When true, matches arrays with no elements' },\n inArray: { type: colArr, description: IN_ARRAY_DESCRIPTION },\n notInArray: { type: colArr, description: NOT_IN_ARRAY_DESCRIPTION },\n isNull: { type: GraphQLBoolean },\n isNotNull: { type: GraphQLBoolean },\n };\n};\n\n/**\n * Filters whose fields omit the string pattern operators (like/notLike/ilike/notIlike/\n * startsWith/contains/… and the `insensitive` flag that modifies them): they are nonsensical\n * on opaque uuids, booleans and enum members, invalid SQL on numeric columns, and on a\n * timestamp they match whatever the session happens to render the value as rather than\n * anything in the query. Keyed on the generic filter name (i.e. on column type) — a\n * string-typed column keeps the string operators whatever it is called. Enum filters are\n * named after their enum and are recognised by `isEnum` instead.\n */\nconst FILTERS_WITHOUT_STRING_OPS = new Set(['Id', 'Int', 'Float', 'BigInt', 'Decimal', 'Boolean', 'Date', 'DateTime']);\n\n/**\n * Filters that additionally omit the ordering operators (lt/lte/gt/gte). Ordering two\n * booleans is `eq` spelled as a puzzle (`gt: false` is `eq: true`), and ordering enum members\n * compares their declaration order — an artefact of how the column was written rather than a\n * fact about the domain. Timestamps and the numerics keep them: ranges are the point of\n * having them. Enum filters are recognised by `isEnum`, as above.\n */\nconst FILTERS_WITHOUT_ORDERING_OPS = new Set(['Boolean']);\n\n/**\n * Scalars the built-in detection itself can produce. A scalar override to one of these\n * shares the built-in filter type for that scalar, so its shape must stay exactly what a\n * natural column of the scalar gets — whichever column builds the cached type first.\n * Any other override scalar gets its own filter type named after the scalar.\n */\nconst BUILTIN_FILTER_SCALARS = new Set<GraphQLScalarType>([\n GraphQLString,\n GraphQLInt,\n GraphQLFloat,\n GraphQLBoolean,\n GraphQLBigIntString,\n GraphQLDecimalString,\n GraphQLUUID,\n GraphQLJSON,\n GraphQLDate,\n GraphQLDateTime,\n]);\n\n/**\n * Filter descriptor for a scalar-overridden column. Overrides to the library's own\n * structural scalars keep the corresponding built-in descriptor (JSON keeps the\n * json-shaped filter, UUID the Id filter), so they share the name-keyed cache with\n * natural columns safely in either build order; every other scalar — the remaining\n * built-ins and all custom scalars — gets a scalar-shaped filter named after it\n * (BigIntFilter, MoneyFilter, …).\n */\nconst resolveOverrideFilterDescriptor = (scalar: GraphQLScalarType): GenericFilterDescriptor => {\n if (scalar === GraphQLJSON) {\n return { name: 'JSON', kind: 'json' };\n }\n if (scalar === GraphQLUUID) {\n return { name: 'Id', kind: 'scalar' };\n }\n return { name: scalar.name, kind: 'scalar' };\n};\n\nexport const generateColumnFilterValues = (\n column: Column,\n tableName: string,\n columnName: string,\n cacheCtx: TypeCacheCtx,\n): GraphQLInputObjectType => {\n const columnGraphQLType = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, true);\n\n // A scalar-overridden column gets its filter built from the override scalar, which\n // `columnGraphQLType` above already resolved to. An override to one of the library's own\n // scalars shares the built-in filter for that scalar (same descriptor a natural column of\n // that scalar gets); any other scalar gets its own scalar-shaped filter type named after it\n // (e.g. MoneyFilter). The cache stays keyed by name, so all columns overridden with the\n // same scalar share one filter type.\n const inputOverride = getColumnScalarOverride(column, true);\n\n const {\n name: genericName,\n kind,\n isEnum,\n } = inputOverride\n ? resolveOverrideFilterDescriptor(inputOverride)\n : resolveGenericFilterDescriptor(column, columnGraphQLType);\n const cached = cacheCtx.genericFilterCache.get(genericName);\n if (cached) {\n return cached;\n }\n\n // Built with `forceNullable`, so the value is never a `GraphQLNonNull` — only the union is\n // wide enough to say so, and graphql 17's branded constructor cares.\n const colType = columnGraphQLType.type as NullableConvertedColumnType<true>;\n const colArr = new GraphQLList(new GraphQLNonNull(colType));\n\n // Which operators a column type gets is decided by the column type, never by the column\n // name. A filter shared with the built-ins keeps that name-keyed rule even for an\n // overridden column, so the shared type's shape never depends on which column built it\n // first. A custom override scalar's own filter carries the pattern operators only when a\n // pattern match is valid SQL on the underlying database column: string-typed, and not\n // numeric/decimal (those transport as strings but reject LIKE). Ordering operators are\n // dropped only for the built-in shapes where they are meaningless — a custom scalar says\n // nothing about whether its column is orderable, so it keeps them.\n const customOverrideFilter = inputOverride !== undefined && !BUILTIN_FILTER_SCALARS.has(inputOverride);\n const underlying = extractExtendedColumnType(column);\n const omitStringOps = customOverrideFilter\n ? underlying.type !== 'string' || underlying.constraint === 'numeric'\n : isEnum || FILTERS_WITHOUT_STRING_OPS.has(genericName);\n const omitOrderingOps = !customOverrideFilter && (isEnum || FILTERS_WITHOUT_ORDERING_OPS.has(genericName));\n\n const baseFields =\n kind === 'json'\n ? jsonFilterFields(column, colType, cacheCtx.typeName)\n : kind === 'array'\n ? arrayFilterFields(colType as GraphQLList<any>, colArr)\n : {\n eq: { type: colType, description: 'Equal to' },\n ne: { type: colType, description: 'Not equal to' },\n ...(omitOrderingOps\n ? {}\n : {\n lt: { type: colType, description: 'Less than' },\n lte: { type: colType, description: 'Less than or equal to' },\n gt: { type: colType, description: 'Greater than' },\n gte: { type: colType, description: 'Greater than or equal to' },\n }),\n ...(omitStringOps\n ? {}\n : {\n like: { type: GraphQLString },\n notLike: { type: GraphQLString },\n ilike: { type: GraphQLString },\n notIlike: { type: GraphQLString },\n startsWith: {\n type: GraphQLString,\n description:\n 'Matches values starting with the given string. `%`, `_` and `\\\\` are matched literally.',\n },\n endsWith: {\n type: GraphQLString,\n description:\n 'Matches values ending with the given string. `%`, `_` and `\\\\` are matched literally.',\n },\n contains: {\n type: GraphQLString,\n description: 'Matches values containing the given string. `%`, `_` and `\\\\` are matched literally.',\n },\n iStartsWith: {\n type: GraphQLString,\n description: 'Case-insensitive `startsWith`.',\n },\n iEndsWith: {\n type: GraphQLString,\n description: 'Case-insensitive `endsWith`.',\n },\n iContains: {\n type: GraphQLString,\n description: 'Case-insensitive `contains`.',\n },\n insensitive: {\n type: GraphQLBoolean,\n description:\n 'When true, every comparison operator in this object matches case-insensitively — `eq`, `ne`, the ordering operators, `inArray`/`notInArray` and the pattern operators all compare `lower(column)` against `lower(operand)`. Applies only to the operators beside it; a nested `AND`/`OR`/`NOT` branch sets its own.',\n },\n }),\n inArray: { type: colArr, description: IN_ARRAY_DESCRIPTION },\n notInArray: { type: colArr, description: NOT_IN_ARRAY_DESCRIPTION },\n isNull: { type: GraphQLBoolean, description: 'When true, matches rows where the column is NULL' },\n isNotNull: { type: GraphQLBoolean, description: 'When true, matches rows where the column is not NULL' },\n };\n\n // The boolean branches are recursive — each branch is this filter type itself — so the\n // fields are thunked and reference the type being constructed.\n const mainType: GraphQLInputObjectType = new GraphQLInputObjectType({\n name: cacheCtx.typeName({ kind: 'columnFilter', defaultName: `${genericName}Filter`, operation: genericName }),\n fields: () => ({\n ...baseFields,\n OR: {\n type: new GraphQLList(new GraphQLNonNull(mainType)),\n description: 'At least one branch matches; ANDed with any sibling operators',\n },\n AND: {\n type: new GraphQLList(new GraphQLNonNull(mainType)),\n description: 'Every branch matches',\n },\n NOT: {\n type: mainType,\n description: 'Negates the nested operators',\n },\n }),\n });\n\n cacheCtx.genericFilterCache.set(genericName, mainType);\n return mainType;\n};\n","import { type Column, getColumns, is, One, type Table } from 'drizzle-orm';\nimport { isJsonColumn } from '../builders/common/column-filters.ts';\nimport { drizzleError } from '../builders/common/errors.ts';\nimport type { TableNamedRelations } from '../builders/index.ts';\nimport { dateToCalendarDate, isCalendarDate } from '../scalars/index.ts';\nimport {\n getColumnScalarOverride,\n isDateOnlyColumn,\n isDateTimeColumn,\n isMySqlDateTimeStringColumn,\n isPgTimestampStringColumn,\n isSQLiteTimestampColumn,\n sqliteTimestampToDate,\n} from '../type-converter/index.ts';\n\n/**\n * MySQL's own text form for a `timestamp` / `datetime`: `YYYY-MM-DD HH:MM:SS`, an optional\n * fraction, and no offset. mysql2 returns it for a `'string'`-mode column, and it is what such a\n * column expects on write.\n */\nconst MYSQL_DATETIME_TEXT = /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?)$/;\n\n/**\n * MySQL datetime text, read as UTC, as the ISO 8601 instant the `DateTime` scalar carries.\n * UTC because that is how drizzle's own `'date'`-mode codecs read the same text, so a column's\n * two modes agree on the instant. Anything else (a zero date, a value already carrying an\n * offset) is returned unchanged for the scalar to accept or reject.\n */\nconst mySqlDateTimeTextToIso = (value: string): string => {\n const match = MYSQL_DATETIME_TEXT.exec(value);\n return match ? `${match[1]}T${match[2]}Z` : value;\n};\n\n/**\n * A JS `Date` as offset-less `YYYY-MM-DD HH:MM:SS.mmm` text in UTC: what a MySQL `'string'`-mode\n * column and a Postgres `timestamp` (without time zone) `'string'`-mode column are written with.\n */\nconst dateToUtcWallText = (value: Date): string => value.toISOString().slice(0, -1).replace('T', ' ');\n\n/**\n * Postgres's text form for a `timestamp` / `timestamptz` (the `ISO` `DateStyle`, the default):\n * `YYYY-MM-DD HH:MM:SS`, an optional fraction, and — for `timestamptz` only — the session zone's\n * offset as `±HH`, `±HH:MM` or, for historical local mean time, `±HH:MM:SS`.\n */\nconst PG_TIMESTAMP_TEXT =\n /^(\\d{4}-\\d{2}-\\d{2})[ T](\\d{2}:\\d{2}:\\d{2})(\\.\\d+)?(?:([+-])(\\d{2})(?::?(\\d{2}))?(?::?(\\d{2}))?)?$/;\n\n/**\n * Postgres timestamp text as the RFC 3339 UTC instant (`…Z`) the `DateTime` scalar accepts.\n *\n * - With an offset (`timestamptz`), the instant is shifted to UTC. The offset can carry seconds,\n * which RFC 3339 cannot express, so it is applied here rather than rewritten.\n * - Without one (`timestamp`), the wall time is read as UTC: that is what drizzle's `'date'`-mode\n * codec does (`new Date(text + '+0000')`) and what the input side writes, so a column's two\n * modes agree on the instant.\n * - The fraction is kept digit for digit. The scalar itself carries milliseconds, so microseconds\n * are truncated on the wire, never rounded into the next second.\n *\n * Anything else (`infinity`, a `BC` date, a five-digit year) is returned unchanged for the scalar\n * to reject.\n */\nexport const pgTimestampTextToIso = (value: string): string => {\n const match = PG_TIMESTAMP_TEXT.exec(value);\n if (!match) {\n return value;\n }\n const [, date, time, fraction = '', sign, hours, minutes = '0', seconds = '0'] = match;\n if (!sign) {\n return `${date}T${time}${fraction}Z`;\n }\n\n const wallMs = Date.parse(`${date}T${time}Z`);\n if (Number.isNaN(wallMs)) {\n return value;\n }\n const offsetSeconds = (sign === '-' ? -1 : 1) * (Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds));\n const utc = new Date(wallMs - offsetSeconds * 1000).toISOString();\n // `toISOString` only stays `YYYY-MM-DDTHH:MM:SS.mmmZ` inside years 0000–9999.\n return utc.length === 24 ? `${utc.slice(0, 19)}${fraction}Z` : value;\n};\n\nexport const remapToGraphQLCore = (\n key: string,\n value: any,\n tableName: string,\n // Relation keys have no column; the guard below is what handles them.\n column: Column | undefined,\n relationMap?: Record<string, Record<string, TableNamedRelations>>,\n): any => {\n // Check for relation fields BEFORE the column check.\n // Relation fields don't have corresponding table columns.\n if (Array.isArray(value)) {\n const relations = relationMap?.[tableName];\n if (relations?.[key]) {\n const rel = relations[key]!;\n return remapToGraphQLArrayOutput(\n value,\n rel.targetTableName,\n (rel.relation as any)?.targetTable ?? (rel.relation as any)?.referencedTable,\n relationMap,\n );\n }\n }\n\n if (typeof value === 'object' && value !== null) {\n const relations = relationMap?.[tableName];\n if (relations?.[key]) {\n const rel = relations[key]!;\n const remapped = remapToGraphQLSingleOutput(\n value,\n rel.targetTableName,\n (rel.relation as any)?.targetTable ?? (rel.relation as any)?.referencedTable,\n relationMap,\n );\n return remapped;\n }\n }\n\n // For non-relation fields, require a column definition.\n if (!column) {\n return value;\n }\n\n // Columns whose output type is a scalar override hand the driver's raw value straight to\n // that scalar — serialization is wholly the scalar's job, and converting here first would\n // double-convert.\n if (getColumnScalarOverride(column, false)) {\n return value;\n }\n\n // JSON columns are carried by the `JSON` scalar, which transports the parsed value as-is.\n // This has to come before the array/object branches below, which would otherwise walk into\n // the value and remap its contents as if they were column values.\n if (isJsonColumn(column)) {\n return value;\n }\n\n // A `date` column read in drizzle's `'date'` mode arrives as a JS `Date` at UTC midnight;\n // the `Date` scalar transports the day it names, not the instant. An unrepresentable value\n // is left for the scalar to reject rather than silently reformatted.\n if (value instanceof Date && isDateOnlyColumn(column)) {\n return dateToCalendarDate(value) ?? value;\n }\n\n // A SQLite integer timestamp arrives as a `Date`: drizzle decodes it on every path the library\n // reads through, aggregates included (`min`/`max` are `mapWith(column)`). A row that skipped the\n // column's decoder (a hand-built one, say) holds the stored integer instead, in the column's own\n // unit — read it as that unit here, because the `DateTime` scalar reads any number as\n // milliseconds.\n if (typeof value === 'number' && isSQLiteTimestampColumn(column)) {\n const instant = sqliteTimestampToDate(column, value);\n return Number.isNaN(instant.getTime()) ? value : instant.toISOString();\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n // A MySQL `timestamp` / `datetime` read in `'string'` mode arrives as MySQL's offset-less text,\n // which the `DateTime` scalar does not accept; it names a UTC instant (see\n // `mySqlDateTimeTextToIso`).\n if (typeof value === 'string' && isMySqlDateTimeStringColumn(column)) {\n return mySqlDateTimeTextToIso(value);\n }\n\n // A Postgres `timestamp` read in `'string'` mode arrives as Postgres's own text, which the\n // `DateTime` scalar does not accept either (see `pgTimestampTextToIso`).\n if (typeof value === 'string' && isPgTimestampStringColumn(column)) {\n return pgTimestampTextToIso(value);\n }\n\n if (value instanceof Buffer) {\n return Array.from(value);\n }\n\n if (typeof value === 'bigint') {\n return value.toString();\n }\n\n if (Array.isArray(value)) {\n if (column.columnType === 'PgGeometry' || column.columnType === 'PgVector') {\n return value;\n }\n\n return value.map((arrVal) => remapToGraphQLCore(key, arrVal, tableName, column, relationMap));\n }\n\n if (typeof value === 'object' && value !== null) {\n if (column.columnType === 'PgGeometryObject') {\n return value;\n }\n\n return JSON.stringify(value);\n }\n\n return value;\n};\n\nexport const remapToGraphQLSingleOutput = (\n queryOutput: Record<string, any>,\n tableName: string,\n table: Table,\n relationMap?: Record<string, Record<string, TableNamedRelations>>,\n) => {\n const columns = getColumns(table);\n\n for (const [key, value] of Object.entries(queryOutput)) {\n if (value === undefined || value === null) {\n // Preserve an explicitly-null TO-ONE relation field (eager-loaded with no related\n // row) as null, so the relation's field resolver returns null directly instead of\n // re-querying it through the batch loader. Only to-one relations are nullable; a\n // to-many relation is a non-null list, so a null there must fall through to deletion\n // (the field resolver then resolves it to []) rather than be emitted as null.\n const relEntry = value === null ? relationMap?.[tableName]?.[key] : undefined;\n if (relEntry && is(relEntry.relation, One)) {\n queryOutput[key] = null;\n continue;\n }\n delete queryOutput[key];\n continue;\n }\n\n const column = columns[key];\n\n // SQLite blob(bigint) returns 0n for null DB values — treat as absent when nullable.\n if (value === 0n && column && (column as any).columnType === 'SQLiteBigInt' && !(column as any).notNull) {\n delete queryOutput[key];\n continue;\n }\n\n queryOutput[key] = remapToGraphQLCore(key, value, tableName, column, relationMap);\n }\n\n return queryOutput;\n};\n\nexport const remapToGraphQLArrayOutput = (\n queryOutput: Record<string, any>[],\n tableName: string,\n table: Table,\n relationMap?: Record<string, Record<string, TableNamedRelations>>,\n) => {\n for (const entry of queryOutput) {\n remapToGraphQLSingleOutput(entry, tableName, table, relationMap);\n }\n\n return queryOutput;\n};\n\nexport const remapFromGraphQLCore = (value: any, column: Column, columnName: string): any => {\n // `null` is SQL NULL whatever the column's type, so there is nothing to coerce — and the\n // coercing branches below would get it wrong rather than fail: `new Date(null)` is the\n // epoch, not an invalid date, and `BigInt(null)` throws. Whether the column may hold a\n // null is the caller's question (see `remapFromGraphQLSingleInput`), not this function's.\n if (value === null) {\n return null;\n }\n\n // Columns whose input type is a scalar override receive exactly what that scalar's\n // parseValue/parseLiteral produced — coercion is the scalar's job, so the value goes to\n // the driver untouched. Only the null-prototype normalization still applies (it undoes a\n // graphql-js artifact, not a coercion — see the default case below).\n if (getColumnScalarOverride(column, true)) {\n if (typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === null) {\n return Object.assign({}, value);\n }\n return value;\n }\n\n // drizzle-orm v1 uses compound dataType strings (e.g. \"object date\", \"bigint int64\").\n // We must check inclusion rather than equality to handle these cases.\n const dataType: string = (column as any).dataType ?? '';\n\n // Timestamp/datetime columns: Postgres and MySQL `timestamp`, MySQL `datetime` (either mode),\n // and SQLite's integer timestamps. Pure DATE columns are handled below.\n //\n // A SQLite integer timestamp takes the `Date`, which drizzle's `mapToDriverValue` turns into\n // the stored integer: milliseconds for `'timestamp_ms'`, and for `'timestamp'` whole seconds,\n // floored — `…T10:00:00.999Z` is stored, and read back, as `…T10:00:00Z`. Filter operands go\n // through here and the same encoder, so they are floored exactly as a write would be: `eq`\n // matches the row that input would have written.\n const columnType: string = (column as any).columnType ?? '';\n if (isDateTimeColumn(column)) {\n const isMySql = columnType.startsWith('MySql');\n const isPgString = isPgTimestampStringColumn(column);\n // MySQL / Postgres text with no offset is read as UTC, as on output — `new Date()` would read\n // it in the server's local zone. The `DateTime` scalar never produces it; an `entities` caller\n // might.\n const toIso = isMySql ? mySqlDateTimeTextToIso : isPgString ? pgTimestampTextToIso : undefined;\n const formatted = new Date(toIso && typeof value === 'string' ? toIso(value) : value);\n if (Number.isNaN(formatted.getTime())) {\n throw drizzleError(`Field '${columnName}' is not a valid date!`, { code: 'DRIZZLE_INVALID_INPUT_VALUE' });\n }\n\n // A `'string'`-mode MySQL column takes MySQL's own text, written in UTC. A `'date'`-mode\n // column takes the `Date`; drizzle's `mapToDriverValue` formats it with `toISOString`, so it\n // is written in UTC too rather than in mysql2's local-time formatting.\n //\n // A `'string'`-mode Postgres column takes a string, in the form its type reads without\n // ambiguity: `timestamptz` the ISO instant (`…Z`); `timestamp` the UTC wall time with no\n // offset, because Postgres silently drops an offset written to a `timestamp` column.\n if (isPgString) {\n return (column as any).withTimezone ? formatted.toISOString() : dateToUtcWallText(formatted);\n }\n return isMySqlDateTimeStringColumn(column) ? dateToUtcWallText(formatted) : formatted;\n }\n\n // Date-only columns, either drizzle mode. The `Date` scalar has already checked the value is\n // a `YYYY-MM-DD` calendar day, and that string is what goes to the driver for both modes:\n // drizzle passes a string through to a `'date'`-mode column untouched, and a string is the\n // one form that cannot be shifted by a timezone (mysql2 formats a JS `Date` in local time).\n // The check is repeated here because not every caller is the scalar — `entities` resolvers\n // can be called with hand-built args — and a JS `Date` from such a caller is read as the UTC\n // day it encodes, the same way the output side reads one.\n if (isDateOnlyColumn(column)) {\n // `date().array()` keeps the date column type with a `dimensions` count, so an array here\n // is a list of days, checked element by element.\n if (Array.isArray(value)) {\n return value.map((element) => remapFromGraphQLCore(element, column, columnName));\n }\n const day = value instanceof Date ? dateToCalendarDate(value) : value;\n if (typeof day !== 'string' || !isCalendarDate(day)) {\n throw drizzleError(`Field '${columnName}' is not a valid date! Expected a calendar date as YYYY-MM-DD.`, {\n code: 'DRIZZLE_INVALID_INPUT_VALUE',\n });\n }\n\n return day;\n }\n\n // BigInt columns (SQLite: \"bigint int64\", others: \"bigint\").\n if (dataType.includes('bigint')) {\n try {\n return BigInt(value);\n } catch {\n throw drizzleError(`Field '${columnName}' is not a BigInt!`, { code: 'DRIZZLE_INVALID_INPUT_VALUE' });\n }\n }\n\n // JSON columns (SQLite: \"object json\", PG: \"json\"). The `JSON` scalar has already parsed\n // the literal, so the value goes to the driver untouched — parsing it again here would\n // wrongly reject a JSON value that happens to be a string, like `\"hello\"`.\n // PgGeometryObject is already handled by the switch case below.\n if (dataType.includes('json') && (column as any).columnType !== 'PgGeometryObject') {\n return value;\n }\n\n switch (dataType) {\n case 'date': {\n const formatted = new Date(value);\n if (Number.isNaN(formatted.getTime())) {\n throw drizzleError(`Field '${columnName}' is not a valid date!`, { code: 'DRIZZLE_INVALID_INPUT_VALUE' });\n }\n\n return formatted;\n }\n\n case 'buffer': {\n if (!Array.isArray(value)) {\n throw drizzleError(`Field '${columnName}' is not an array!`, { code: 'DRIZZLE_INVALID_INPUT_VALUE' });\n }\n\n return Buffer.from(value);\n }\n\n case 'json': {\n if (column.columnType === 'PgGeometryObject') {\n return value;\n }\n\n try {\n return JSON.parse(value);\n } catch (e) {\n throw drizzleError(\n `Invalid JSON in field '${columnName}':\\n${e instanceof Error ? e.message : 'Unknown error'}`,\n {\n code: 'DRIZZLE_INVALID_INPUT_VALUE',\n },\n );\n }\n }\n\n case 'array': {\n if (!Array.isArray(value)) {\n throw drizzleError(`Field '${columnName}' is not an array!`, { code: 'DRIZZLE_INVALID_INPUT_VALUE' });\n }\n\n if (column.columnType === 'PgGeometry' && value.length !== 2) {\n throw drizzleError(\n `Invalid float tuple in field '${columnName}': expected array with length of 2, received ${value.length}`,\n { code: 'DRIZZLE_INVALID_INPUT_VALUE' },\n );\n }\n\n return value;\n }\n\n case 'bigint': {\n try {\n return BigInt(value);\n } catch (_error) {\n throw drizzleError(`Field '${columnName}' is not a BigInt!`, { code: 'DRIZZLE_INVALID_INPUT_VALUE' });\n }\n }\n\n default: {\n // graphql-js coerces input object types using Object.create(null), producing\n // null-prototype objects. Drizzle's internal is() check accesses\n // Object.getPrototypeOf(value).constructor and throws for null-prototype objects.\n // Convert to a plain object so drizzle can process it safely.\n if (typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === null) {\n return Object.assign({}, value);\n }\n return value;\n }\n }\n};\n\n/**\n * Which write an input is being remapped for. It decides one thing only: what an explicit\n * `null` means for a `notNull` column — see {@link remapFromGraphQLSingleInput}.\n */\nexport type RemapInputOperation = 'insert' | 'update';\n\nexport const remapFromGraphQLSingleInput = (\n queryInput: Record<string, any>,\n table: Table,\n operation: RemapInputOperation = 'insert',\n) => {\n const columns = getColumns(table);\n\n for (const [key, value] of Object.entries(queryInput)) {\n if (value === undefined) {\n delete queryInput[key];\n } else {\n const column = columns[key];\n if (!column) {\n throw drizzleError(`Unknown column: ${key}`, { code: 'DRIZZLE_UNKNOWN_COLUMN' });\n }\n\n // An explicit `null` for a column that cannot hold one reads differently on each side\n // of a write, because the generated input types mean different things by nullability.\n //\n // On INSERT a `notNull` column's field is only nullable when the database or drizzle\n // can fill it in — `defaultIsNullable` is passed for the create input, so the field is\n // non-null unless the column has a default, or a nested `create` supplies it. So the\n // only nulls that reach here are ones the schema itself offered as \"I am not supplying\n // this\", and dropping the key is what lets the default apply. That contract is pinned\n // by `upsert-null-key.test.ts` and `not-null-writes.test.ts`.\n //\n // On UPDATE every field is nullable — the update input forces it, whatever the column\n // — so nullability says nothing, and there is no default to fall back to. `null` can\n // only mean \"write null\", which this column cannot hold. Dropping it used to report\n // either a wrong success (the rest of the `set` landed, this column silently kept its\n // old value) or a misleading `DRIZZLE_NO_VALUES` when it was the only field.\n if (value === null && column.notNull) {\n if (operation === 'update') {\n throw drizzleError(`Column '${key}' cannot be set to null.`, { code: 'DRIZZLE_NOT_NULL' });\n }\n delete queryInput[key];\n continue;\n }\n\n queryInput[key] = remapFromGraphQLCore(value, column, key);\n }\n }\n\n return queryInput;\n};\n\nexport const remapFromGraphQLArrayInput = (\n queryInput: Record<string, any>[],\n table: Table,\n operation: RemapInputOperation = 'insert',\n) => {\n for (const entry of queryInput) {\n remapFromGraphQLSingleInput(entry, table, operation);\n }\n\n return queryInput;\n};\n","// Compiling one column's filter operators into SQL, including the LIKE escaping and the\n// JSON-path machinery the JSON operators are built on.\n\nimport type { Column } from 'drizzle-orm';\nimport {\n and,\n arrayContains,\n arrayOverlaps,\n eq,\n gt,\n gte,\n ilike,\n inArray,\n isNotNull,\n isNull,\n like,\n lt,\n lte,\n ne,\n not,\n notIlike,\n notInArray,\n notLike,\n or,\n type SQL,\n sql,\n} from 'drizzle-orm';\nimport { remapFromGraphQLCore } from '../../data-mappers/index.ts';\nimport type { FilterColumnOperators, FilterColumnOperatorsCore } from '../types.ts';\nimport { columnDialect, isJsonColumn } from './column-filters.ts';\nimport { drizzleError } from './errors.ts';\n\n/**\n * Escape character pinned via `ESCAPE` on every generated safe-LIKE predicate. Bound as a\n * query parameter (never spliced into the SQL text), so no dialect-specific string-literal\n * escaping rules apply to it.\n */\nconst LIKE_ESCAPE_CHAR = '\\\\';\n\n/**\n * Escapes the LIKE wildcards (`%`, `_`) and the escape character itself (`\\`) in a literal\n * search term, so the term only ever matches literally inside a LIKE pattern.\n */\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (char) => `\\\\${char}`);\n\n/**\n * The injection-safe string operators: the caller passes a literal search term, the library\n * builds the LIKE pattern with the term's `%` / `_` / `\\` escaped and the `ESCAPE` clause pinned.\n * The `i`-prefixed variants match case-insensitively.\n */\nconst safeLikeOps: Record<string, { buildPattern: (value: string) => string; insensitive: boolean }> = {\n startsWith: { buildPattern: (value) => `${escapeLikeValue(value)}%`, insensitive: false },\n endsWith: { buildPattern: (value) => `%${escapeLikeValue(value)}`, insensitive: false },\n contains: { buildPattern: (value) => `%${escapeLikeValue(value)}%`, insensitive: false },\n iStartsWith: { buildPattern: (value) => `${escapeLikeValue(value)}%`, insensitive: true },\n iEndsWith: { buildPattern: (value) => `%${escapeLikeValue(value)}`, insensitive: true },\n iContains: { buildPattern: (value) => `%${escapeLikeValue(value)}%`, insensitive: true },\n};\n\n/**\n * `LIKE <pattern> ESCAPE '\\'` for a safe string operator. Case-insensitive variants use\n * Postgres's native `ILIKE`; MySQL and SQLite have no `ILIKE`, so they compare `lower()`\n * on both sides instead (mirroring how the raw `ilike` operator is Postgres-only).\n */\nconst safeLikeCondition = (column: Column, pattern: string, insensitive: boolean): SQL => {\n if (!insensitive) {\n return sql`${column} like ${pattern} escape ${LIKE_ESCAPE_CHAR}`;\n }\n\n const isPg = (((column as any).columnType ?? '') as string).startsWith('Pg');\n return isPg\n ? sql`${column} ilike ${pattern} escape ${LIKE_ESCAPE_CHAR}`\n : sql`lower(${column}) like ${pattern.toLowerCase()} escape ${LIKE_ESCAPE_CHAR}`;\n};\n\n/**\n * The case-insensitive form of the raw `like` / `notLike` operators, whose operand is a\n * caller-written pattern rather than a literal. Postgres has `ILIKE`; the other two dialects\n * compare `lower()` on both sides, exactly as {@link safeLikeCondition} does.\n */\nconst insensitiveLike = (column: Column, pattern: string, negated: boolean): SQL => {\n if (columnDialect(column) === 'pg') {\n return negated ? notIlike(column, pattern) : ilike(column, pattern);\n }\n return negated ? sql`lower(${column}) not like lower(${pattern})` : sql`lower(${column}) like lower(${pattern})`;\n};\n\n/**\n * SQL spelling of each comparison operator, for the case-insensitive forms that have to be\n * written out rather than built by drizzle's `eq`/`ne`/`lt`/… helpers.\n */\nconst COMPARISON_SQL: Record<string, string> = { eq: '=', ne: '<>', lt: '<', lte: '<=', gt: '>', gte: '>=' };\n\n/**\n * `insensitive: true` folds case out of every comparison beside it by comparing\n * `lower(column)` against `lower(operand)`. Lowercasing both sides in SQL — rather than the\n * operand in JS — keeps the comparison under one collation, and `lower(column)` is an\n * expression a matching index can serve, which `ilike '%…%'` never can. It is the same\n * `lower()` the case-insensitive LIKE operators already fall back to on the dialects without\n * a native `ILIKE`, so it adds no dialect surface.\n */\nconst lowerComparison = (column: Column, operatorName: string, value: unknown): SQL =>\n sql`lower(${column}) ${sql.raw(COMPARISON_SQL[operatorName]!)} lower(${value})`;\n\n/** `lower(column) IN (lower($1), …)` / `NOT IN` — the case-insensitive `inArray`/`notInArray`. */\nconst lowerMembership = (column: Column, values: unknown[], negated: boolean): SQL => {\n const lowered = sql.join(\n values.map((value) => sql`lower(${value})`),\n sql`, `,\n );\n return negated ? sql`lower(${column}) not in (${lowered})` : sql`lower(${column}) in (${lowered})`;\n};\n\n/**\n * Structural JSON containment for the `contains` operator on json/jsonb columns.\n * The value is serialized and bound as a parameter (never interpolated into the SQL text):\n * - Postgres: `col @> $1::jsonb` (a plain `json` column is cast through jsonb — `json` has\n * no containment operator of its own)\n * - MySQL: `JSON_CONTAINS(col, ?)`\n * SQLite has no containment operator, so the filter input never exposes `contains` there;\n * reaching this with an unsupported dialect is a programming error surfaced as a GraphQLError.\n */\nconst jsonContains = (column: Column, columnName: string, value: any): SQL => {\n const serialized = JSON.stringify(value);\n\n switch (columnDialect(column)) {\n case 'pg':\n return (column as any).columnType === 'PgJson'\n ? sql`${column}::jsonb @> ${serialized}::jsonb`\n : sql`${column} @> ${serialized}::jsonb`;\n case 'mysql':\n return sql`json_contains(${column}, ${serialized})`;\n default:\n throw drizzleError(`WHERE ${columnName}: Operator 'contains' is not supported for this dialect!`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n};\n\n/**\n * Constant predicates, used where an operator's operand list is empty and the answer is\n * therefore known without touching the column. Written as `1 = 0` / `1 = 1` rather than the\n * `FALSE` / `TRUE` keywords so they compile identically on all three dialects. Built fresh\n * per call because a `SQL` object is spliced into whatever query consumes it.\n */\nconst sqlFalse = (): SQL => sql`1 = 0`;\nconst sqlTrue = (): SQL => sql`1 = 1`;\n\n/**\n * A MySQL / SQLite JSON path expression for the given key walk. Bound as a query parameter,\n * never spliced into the SQL text; an all-digits key becomes an array index, and quotes and\n * backslashes inside a key are escaped so a key can never end the path segment early.\n */\nconst jsonPathString = (path: string[]): string =>\n `$${path.map((part) => (/^\\d+$/.test(part) ? `[${part}]` : `.\"${part.replace(/([\"\\\\])/g, '\\\\$1')}\"`)).join('')}`;\n\n/**\n * Matches the text forms a database will accept as a number. Used to guard both numeric casts —\n * Postgres has no TRY_CAST and errors outright on a bad `::numeric`, while MySQL quietly casts\n * a non-numeric string to 0; neither is what a non-matching row should do.\n */\nconst NUMERIC_TEXT_PATTERN = '^\\\\s*-?(\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)([eE][-+]?\\\\d+)?\\\\s*$';\n\n/**\n * The value at a JSON path, as the expressions a comparison can be built on: read as text,\n * read as a number, and read as the dialect spells a boolean. Each dialect extracts\n * differently, and each needs its own guard so a value of the wrong shape answers \"no match\"\n * rather than erroring or comparing by some unrelated rule:\n *\n * - **Postgres** — `#>>` with a bound `text[]` path, which works on `json` and `jsonb` alike.\n * `::numeric` on a non-numeric string is a hard error, so the numeric read is guarded by a\n * pattern test.\n * - **MySQL** — `JSON_UNQUOTE(JSON_EXTRACT(col, ?))`, so a JSON string arrives without its\n * quotes. Unquoting a JSON *null* would otherwise yield the string `'null'`, so it is mapped\n * back to SQL NULL first. `CAST` quietly turns a non-numeric string into 0, hence the same\n * pattern guard.\n * - **SQLite** — `json_extract` returns the value in SQLite's own type, so the reads cast\n * explicitly: without that, SQLite's cross-type ordering puts every string above every\n * number and `'admin' > 0` would be true.\n */\nconst jsonPathExprs = (\n column: Column,\n path: string[],\n): { text: SQL; number: SQL; boolean: SQL; encodeBoolean: (value: boolean) => string | number } => {\n switch (columnDialect(column)) {\n case 'pg': {\n const pathArray = sql`array[${sql.join(\n path.map((part) => sql`${part}`),\n sql`, `,\n )}]::text[]`;\n const text = sql`(${column} #>> ${pathArray})`;\n return {\n text,\n number: sql`(case when ${text} ~ ${NUMERIC_TEXT_PATTERN} then ${text}::numeric end)`,\n boolean: text,\n encodeBoolean: (value) => String(value),\n };\n }\n case 'mysql': {\n const extracted = sql`json_extract(${column}, ${jsonPathString(path)})`;\n const text = sql`(case when json_type(${extracted}) = 'NULL' then null else json_unquote(${extracted}) end)`;\n return {\n text,\n number: sql`(case when ${text} regexp ${NUMERIC_TEXT_PATTERN} then cast(${text} as decimal(65, 30)) end)`,\n boolean: text,\n encodeBoolean: (value) => String(value),\n };\n }\n default: {\n const extracted = sql`json_extract(${column}, ${jsonPathString(path)})`;\n return {\n text: sql`cast(${extracted} as text)`,\n number: sql`(case when typeof(${extracted}) in ('integer', 'real') then ${extracted} end)`,\n // SQLite has no boolean type: a JSON `true` comes back as the integer 1.\n boolean: extracted,\n encodeBoolean: (value) => (value ? 1 : 0),\n };\n }\n }\n};\n\n/** Comparison operators available inside a JSON path filter, as their SQL spelling. */\nconst JSON_PATH_COMPARISONS: Record<string, string> = {\n eq: '=',\n ne: '<>',\n lt: '<',\n lte: '<=',\n gt: '>',\n gte: '>=',\n};\n\n/**\n * How the value at a path is read when the filter does not say: a GraphQL number compares\n * numerically, a boolean as a boolean, everything else as text.\n */\nconst inferJsonPathCast = (value: unknown): 'text' | 'number' | 'boolean' =>\n typeof value === 'number' ? 'number' : typeof value === 'boolean' ? 'boolean' : 'text';\n\n/**\n * Compiles one entry of a column's `path` filter: `as` (or the operand's own type) picks\n * which of {@link jsonPathExprs}' reads the comparison is built on, and the operand is bound\n * in the shape that read expects.\n */\nconst jsonPathCondition = (column: Column, columnName: string, filter: Record<string, any>): SQL | undefined => {\n const { path, as: castOverride, ...operators } = filter;\n const locator = `${columnName}.path`;\n\n if (!Array.isArray(path) || !path.length) {\n throw drizzleError(`WHERE ${locator}: 'path' must name at least one key`, { code: 'DRIZZLE_INVALID_FILTER' });\n }\n\n const exprs = jsonPathExprs(column, path);\n const variants: SQL[] = [];\n\n for (const [operatorName, operatorValue] of Object.entries(operators)) {\n if (operatorValue === null || operatorValue === undefined) {\n continue;\n }\n\n if (operatorName === 'isNull' || operatorName === 'isNotNull') {\n if (operatorValue === false) {\n continue;\n }\n variants.push(operatorName === 'isNull' ? sql`${exprs.text} is null` : sql`${exprs.text} is not null`);\n continue;\n }\n\n if (operatorName in safeLikeOps) {\n const { buildPattern, insensitive } = safeLikeOps[operatorName]!;\n if (typeof operatorValue !== 'string') {\n throw drizzleError(`WHERE ${locator}: operator '${operatorName}' takes a string`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n // The extracted value is an expression, not a column, so the case-insensitive form\n // always goes through `lower()` rather than Postgres's ILIKE.\n variants.push(safeLikeCondition(exprs.text as any, buildPattern(operatorValue), insensitive));\n continue;\n }\n\n const comparison = JSON_PATH_COMPARISONS[operatorName];\n if (!comparison) {\n throw drizzleError(`WHERE ${locator}: Unknown operator: ${operatorName}`, { code: 'DRIZZLE_INVALID_FILTER' });\n }\n\n const cast = castOverride ?? inferJsonPathCast(operatorValue);\n if (cast === 'number') {\n const numeric = Number(operatorValue);\n if (Number.isNaN(numeric)) {\n throw drizzleError(\n `WHERE ${locator}: operator '${operatorName}' compares as a number, so its value must be one`,\n { code: 'DRIZZLE_INVALID_FILTER' },\n );\n }\n variants.push(sql`${exprs.number} ${sql.raw(comparison)} ${numeric}`);\n } else if (cast === 'boolean') {\n const truthy = operatorValue === true || operatorValue === 'true';\n variants.push(sql`${exprs.boolean} ${sql.raw(comparison)} ${exprs.encodeBoolean(truthy)}`);\n } else {\n variants.push(sql`${exprs.text} ${sql.raw(comparison)} ${String(operatorValue)}`);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n\n// The operator dispatch tables. Constant, and hoisted out of `extractFiltersColumn` — which\n// recurses once per AND/OR/NOT branch of every filter of every request — so they are built\n// once per process rather than five objects per call.\nconst singleValueOps: Record<string, (...args: any[]) => SQL> = { eq, ne, gt, gte, lt, lte };\nconst stringValueOps: Record<string, (...args: any[]) => SQL> = { like, notLike, ilike, notIlike };\nconst arrayValueOps: Record<string, (...args: any[]) => SQL> = { inArray, notInArray };\n/** Membership operators for array columns: element list → SQL. Empty lists are rejected below. */\nconst arrayMembershipOps: Record<string, (...args: any[]) => SQL> = {\n hasSome: arrayOverlaps,\n hasEvery: arrayContains,\n};\nconst nullableOps: Record<string, (...args: any[]) => SQL> = { isNull, isNotNull };\n\nexport const extractFiltersColumn = <TColumn extends Column>(\n column: TColumn,\n columnName: string,\n operators: FilterColumnOperators<TColumn>,\n): SQL | undefined => {\n // Boolean branches compose with sibling operators: siblings and the AND list are ANDed\n // together, NOT negates its whole branch, and the OR group is ANDed with the rest.\n const { OR, AND, NOT, insensitive, ...restOperators } = operators;\n\n // `insensitive` is a modifier, not a predicate: it changes how the operators beside it\n // compile and contributes no condition of its own. It applies to this object only —\n // a nested AND/OR/NOT branch is a separate object and sets its own.\n const foldCase = insensitive === true;\n\n const entries = Object.entries(restOperators as FilterColumnOperatorsCore<TColumn>);\n\n const variants = [] as SQL[];\n for (const [operatorName, operatorValue] of entries) {\n if (operatorValue === null || operatorValue === false) {\n continue;\n }\n\n if (operatorName in singleValueOps) {\n const singleValue = remapFromGraphQLCore(operatorValue, column, columnName);\n variants.push(\n foldCase\n ? lowerComparison(column, operatorName, singleValue)\n : singleValueOps[operatorName]!(column, singleValue),\n );\n } else if (operatorName in stringValueOps) {\n // Under `insensitive`, `like`/`notLike` compile the same way their `i` counterparts\n // do; `ilike`/`notIlike` are already case-insensitive and are left alone.\n const insensitivePattern = foldCase && (operatorName === 'like' || operatorName === 'notLike');\n variants.push(\n insensitivePattern\n ? insensitiveLike(column, operatorValue as string, operatorName === 'notLike')\n : stringValueOps[operatorName]!(column, operatorValue as string),\n );\n } else if (operatorName === 'path' && isJsonColumn(column)) {\n // Several path predicates on one column are ANDed, matching how sibling operators\n // already combine. GraphQL coerces a lone object into a one-element list.\n for (const pathFilter of operatorValue as Record<string, any>[]) {\n const extracted = jsonPathCondition(column, columnName, pathFilter);\n if (extracted) {\n variants.push(extracted);\n }\n }\n } else if (operatorName === 'contains' && isJsonColumn(column)) {\n // `contains` is JSON containment on json/jsonb columns; on string columns it is the\n // safe substring operator handled by safeLikeOps below.\n variants.push(jsonContains(column, columnName, operatorValue));\n } else if (operatorName in safeLikeOps) {\n const { buildPattern, insensitive: alwaysInsensitive } = safeLikeOps[operatorName]!;\n variants.push(safeLikeCondition(column, buildPattern(operatorValue as string), alwaysInsensitive || foldCase));\n } else if (operatorName in arrayValueOps) {\n // An empty candidate list is a well-formed question with a known answer — nothing is\n // `IN ()`, everything is `NOT IN ()` — so it resolves to a constant predicate rather\n // than an error. SQL has no empty-list literal, hence the constant rather than `IN ()`.\n if (!(operatorValue as any[]).length) {\n variants.push(operatorName === 'inArray' ? sqlFalse() : sqlTrue());\n continue;\n }\n const arrayValue = (operatorValue as any[]).map((val) => remapFromGraphQLCore(val, column, columnName));\n variants.push(\n foldCase\n ? lowerMembership(column, arrayValue, operatorName === 'notInArray')\n : arrayValueOps[operatorName]!(column, arrayValue),\n );\n } else if (operatorName === 'has') {\n // Single-element membership: containment with a one-element array (`col @> ARRAY[value]`).\n variants.push(arrayContains(column, [operatorValue]));\n } else if (operatorName in arrayMembershipOps) {\n // Same reasoning as inArray/notInArray: overlapping with no elements is never true,\n // and every array contains all zero of them.\n if (!(operatorValue as any[]).length) {\n variants.push(operatorName === 'hasSome' ? sqlFalse() : sqlTrue());\n continue;\n }\n variants.push(arrayMembershipOps[operatorName]!(column, operatorValue as any[]));\n } else if (operatorName === 'isEmpty') {\n variants.push(sql`cardinality(${column}) = 0`);\n } else if (operatorName in nullableOps) {\n variants.push(nullableOps[operatorName]!(column));\n } else {\n // An unrecognized operator must throw rather than be dropped: when the generated\n // schema is stitched/merged with another schema, foreign operators (e.g. `equals`,\n // `contains`, `mode`) can pass input validation, and silently dropping them could\n // turn a constrained where into an unbounded one.\n throw drizzleError(`WHERE ${columnName}: Unknown operator: ${operatorName}`, { code: 'DRIZZLE_INVALID_FILTER' });\n }\n }\n\n if (AND?.length) {\n for (const variant of AND) {\n const extracted = extractFiltersColumn(column, columnName, variant);\n if (extracted) {\n variants.push(extracted);\n }\n }\n }\n\n if (NOT) {\n const extracted = extractFiltersColumn(column, columnName, NOT);\n // `not()` is typed `SQL | undefined` from drizzle-orm rc.5 on, `SQL` before it.\n const negated = extracted ? not(extracted) : undefined;\n if (negated) {\n variants.push(negated);\n }\n }\n\n if (OR?.length) {\n const orVariants = [] as SQL[];\n for (const variant of OR) {\n const extracted = extractFiltersColumn(column, columnName, variant);\n if (extracted) {\n orVariants.push(extracted);\n }\n }\n\n if (orVariants.length) {\n variants.push(orVariants.length > 1 ? or(...orVariants)! : orVariants[0]!);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n","// The named-relation map the builders work from, derived from drizzle-orm v1's relational\n// config, plus the factory signatures the dialect builders implement.\n\nimport type { Relation, SQL, Table } from 'drizzle-orm';\nimport { Column, getColumns, is, relationsFilterToSQL, sql } from 'drizzle-orm';\nimport type { GraphQLFieldResolver, GraphQLObjectType } from 'graphql';\nimport type { TableNamedRelations } from '../types.ts';\n\n/**\n * Shape of the relational config from drizzle-orm v1 db._.relations.\n * Each entry has { table, name, relations }.\n */\ninterface TableRelationalConfig {\n table: Table;\n name: string;\n relations: Record<string, Relation<string>>;\n}\nexport type TablesRelationalConfig = Record<string, TableRelationalConfig>;\n\n/**\n * Flatten drizzle-orm v1 TablesRelationalConfig into the canonical\n * Record<tableName, Record<relName, TableNamedRelations>> shape used\n * throughout common.ts. Both pg.ts and sqlite.ts call this before\n * passing the relation map to any shared function.\n */\nexport const buildNamedRelations = (\n relations: TablesRelationalConfig,\n tableEntries: [string, Table][],\n): Record<string, Record<string, TableNamedRelations>> => {\n const namedRelations: Record<string, Record<string, TableNamedRelations>> = {};\n\n for (const [relTableName, relConfig] of Object.entries(relations)) {\n if (!relConfig?.relations) {\n continue;\n }\n\n const namedConfig: Record<string, TableNamedRelations> = {};\n\n for (const [innerRelName, innerRelValue] of Object.entries(relConfig.relations)) {\n // drizzle-orm v1 uses `targetTable` (not `referencedTable`)\n // and provides `targetTableName` directly.\n const targetTable = (innerRelValue as any).targetTable ?? (innerRelValue as any).referencedTable;\n const directTargetName = (innerRelValue as any).targetTableName as string | undefined;\n\n let targetTableName: string | undefined;\n\n if (directTargetName) {\n // v1: use the direct name to find the schema key\n const targetEntry = tableEntries.find(([key]) => key === directTargetName);\n targetTableName = targetEntry?.[0];\n } else if (targetTable) {\n // fallback: match by object reference\n const targetEntry = tableEntries.find(([, tableValue]) => tableValue === targetTable);\n targetTableName = targetEntry?.[0];\n }\n\n if (!targetTableName) {\n continue;\n }\n\n namedConfig[innerRelName] = {\n relation: innerRelValue,\n targetTableName,\n };\n }\n\n if (Object.keys(namedConfig).length > 0) {\n namedRelations[relTableName] = namedConfig;\n }\n }\n\n return namedRelations;\n};\n\n/**\n * Records each relation's target-table primary-key property names on the relation entry,\n * so the pagination paths (the window-function batch loader and the eager `with:` orderBy\n * default) can fall back to a deterministic PK order without re-deriving it per request.\n *\n * Composite primary keys are only visible through the dialect's getTableConfig, so the\n * dialect builder passes a `resolvePkNames` that threads the composite column names in.\n * Mutates the relation entries in place (they are shared with the pruned eager map and\n * the resolver factory, so attaching once covers every consumer).\n */\nexport const attachTargetPrimaryKeys = (\n namedRelations: Record<string, Record<string, TableNamedRelations>>,\n tables: Record<string, Table>,\n resolvePkNames: (table: Table) => string[],\n): void => {\n const cache = new Map<string, readonly string[]>();\n for (const rels of Object.values(namedRelations)) {\n for (const relEntry of Object.values(rels)) {\n const { targetTableName } = relEntry;\n let pk = cache.get(targetTableName);\n if (!pk) {\n const targetTable = tables[targetTableName];\n pk = targetTable ? resolvePkNames(targetTable) : [];\n cache.set(targetTableName, pk);\n }\n relEntry.targetPkNames = pk;\n }\n }\n};\n\n/**\n * The table column behind one entry of a relation's `sourceColumns`, `targetColumns` or\n * `through` lists.\n *\n * drizzle-orm rc.4 stores the table's own Column objects in `sourceColumns` / `targetColumns`\n * and a `RelationsBuilderColumn` descriptor (`{ _: { column, key, tableName } }`) in `through`.\n * The rc.5 snapshots store the descriptor in all of them. Both shapes are accepted here, told\n * apart structurally rather than by importing a class one of those versions does not export.\n * Anything else yields `undefined`, which callers treat as \"join columns not readable\".\n */\nexport const unwrapRelationColumn = (entry: unknown): Column | undefined => {\n if (is(entry, Column)) {\n return entry;\n }\n const inner = (entry as any)?._?.column;\n return is(inner, Column) ? inner : undefined;\n};\n\n/**\n * A relation's `sourceColumns` or `targetColumns` as table columns, via\n * {@link unwrapRelationColumn}. `undefined` when the list is missing, empty, or has an entry\n * that is not a column in either known shape.\n */\nexport const relationColumns = (relation: unknown, side: 'source' | 'target'): Column[] | undefined => {\n const entries: unknown[] | undefined = (relation as any)?.[side === 'source' ? 'sourceColumns' : 'targetColumns'];\n if (!entries?.length) {\n return undefined;\n }\n const columns: Column[] = [];\n for (const entry of entries) {\n const column = unwrapRelationColumn(entry);\n if (!column) {\n return undefined;\n }\n columns.push(column);\n }\n return columns;\n};\n\n/**\n * drizzle-orm's \"no filter\" sentinel. rc.5 snapshots export it as `EmptyFilter` and use it as\n * the default `relation.where`; rc.4 has no such export and leaves `where` undefined. It is a\n * registered symbol, so it can be compared against without importing anything.\n */\nconst EMPTY_FILTER = Symbol.for('drizzle:EmptyFilter');\n\n/**\n * The relation's own declared `where` filter, or `undefined` when it has none. rc.4 leaves\n * `where` undefined in that case; rc.5 snapshots set it to the `EmptyFilter` sentinel, which is\n * truthy and must not be read as a filter.\n */\nexport const relationOwnWhere = (relation: unknown): Record<string, unknown> | undefined => {\n const where = (relation as any)?.where;\n return where == null || where === EMPTY_FILTER ? undefined : where;\n};\n\n/**\n * Whether the relation's `where` was inherited from its reverse relation, and so is written\n * against the parent table rather than the target. rc.4 calls this flag `isReversed`; rc.5\n * snapshots renamed it to `isFilterReversed`. Both are set in the same place with the same\n * meaning (true only for a relation declared without `from`/`to` and without its own `where`).\n */\nexport const isRelationFilterReversed = (relation: unknown): boolean =>\n !!((relation as any)?.isFilterReversed ?? (relation as any)?.isReversed);\n\n/**\n * Warns, at build time, that a field was left out because the relation's join columns could\n * not be matched to its tables. Omitting it silently is how a drizzle-orm change in the shape\n * of relation columns (issue #179) went unnoticed. A relation that declares no join columns\n * is not reported: there is nothing that failed to match.\n */\nexport const warnUnresolvedJoin = (\n relEntry: TableNamedRelations,\n tableName: string,\n relationName: string,\n omitted: string,\n): void => {\n const rel = (relEntry as any).relation ?? relEntry;\n if (!rel?.sourceColumns?.length || !rel?.targetColumns?.length) {\n return;\n }\n console.warn(\n `Drizzle-GraphQL Warning: relation '${tableName}.${relationName}' declares join columns that could not be matched to columns of '${tableName}' and '${relEntry.targetTableName}', so ${omitted} is not generated. The installed drizzle-orm probably stores relation columns in a shape this version of drizzle-graphql does not recognize.`,\n );\n};\n\n/**\n * Extracts the join column info from a drizzle-orm v1 Relation object.\n * Returns the JS property name of the local column on the parent table and the\n * Column object for the foreign column on the target table, or undefined if the\n * relation internals are not accessible.\n */\nexport const extractRelationJoinColumns = (\n relEntry: TableNamedRelations,\n parentTable: Table,\n targetTable: Table,\n): { localColPropName: string; foreignCol: Column; foreignColPropName: string } | undefined => {\n const rel = (relEntry as any).relation ?? relEntry;\n const sourceCol = relationColumns(rel, 'source')?.[0];\n const targetCol = relationColumns(rel, 'target')?.[0];\n\n if (!sourceCol || !targetCol) {\n return undefined;\n }\n\n const parentCols = getColumns(parentTable);\n const localColPropName = Object.entries(parentCols).find(([, c]) => c === sourceCol)?.[0];\n\n const targetCols = getColumns(targetTable);\n const foreignColPropName = Object.entries(targetCols).find(([, c]) => c === targetCol)?.[0];\n\n if (!localColPropName || !foreignColPropName) {\n return undefined;\n }\n\n return { localColPropName, foreignCol: targetCol, foreignColPropName };\n};\n\n/**\n * The junction table and its two columns for a `.through()` (many-to-many) relation:\n * `sourceCol` holds the parent's key, `targetCol` the target's. `undefined` for a relation\n * with no junction; `null` for one whose junction cannot be used here — more than one column\n * on either side, or columns that are not on the junction table.\n */\nexport const extractJunctionColumns = (\n relEntry: TableNamedRelations,\n): { table: Table; sourceCol: Column; targetCol: Column } | null | undefined => {\n const rel = (relEntry as any).relation ?? relEntry;\n const junction = rel?.throughTable as Table | undefined;\n if (!junction) {\n return undefined;\n }\n const sourceEntries: unknown[] | undefined = rel.through?.source;\n const targetEntries: unknown[] | undefined = rel.through?.target;\n if (sourceEntries?.length !== 1 || targetEntries?.length !== 1) {\n return null;\n }\n const junctionCols = Object.values(getColumns(junction));\n const sourceCol = unwrapRelationColumn(sourceEntries[0]);\n const targetCol = unwrapRelationColumn(targetEntries[0]);\n if (!sourceCol || !targetCol || !junctionCols.includes(sourceCol) || !junctionCols.includes(targetCol)) {\n return null;\n }\n return { table: junction, sourceCol, targetCol };\n};\n\n/**\n * The relation's own declared `where` as a condition on a query that reads the target table,\n * or `undefined` when it has none. The eager path gets this from drizzle's `with:`; the batched\n * field resolver and `<relation>Aggregate` read the target table directly, so they have to add\n * it themselves or they return rows the relation hides.\n *\n * A reversed filter (inherited from the relation on the other side) is written against the\n * parent table, so it is applied as \"the row's parent key belongs to a parent that passes it\".\n * `parentKeyCol` is the parent's join column and `groupCol` the column in the query that holds\n * the parent key for each row — the target's foreign key, or the junction's source column.\n */\nexport const relationOwnCondition = (\n relEntry: TableNamedRelations,\n parentTable: Table,\n targetTable: Table,\n parentKeyCol: Column,\n groupCol: Column,\n): SQL | undefined => {\n const rel = (relEntry as any).relation ?? relEntry;\n const ownWhere = relationOwnWhere(rel);\n if (!ownWhere) {\n return undefined;\n }\n if (!isRelationFilterReversed(rel)) {\n return relationsFilterToSQL(targetTable, ownWhere as any);\n }\n const parentFilter = relationsFilterToSQL(parentTable, ownWhere as any);\n return sql`${groupCol} in (select ${parentKeyCol} from ${parentTable} where ${parentFilter})`;\n};\n\nexport type RelationResolverFactory = (params: {\n tableName: string;\n relationName: string;\n relEntry: TableNamedRelations;\n isOne: boolean;\n}) => GraphQLFieldResolver<any, any> | undefined;\n\n/**\n * Builds the `${relationName}Aggregate` field for a to-many relation. Implemented in\n * `aggregates.ts` and injected here so the aggregate code can depend on this module\n * without the two importing each other.\n */\nexport type RelationAggregateFactory = (params: {\n tableName: string;\n relationName: string;\n relEntry: TableNamedRelations;\n}) => { type: GraphQLObjectType; resolve: GraphQLFieldResolver<any, any> } | undefined;\n\n/**\n * Whether a to-one relation can back a relation orderBy hop. `.through()` (junction)\n * relations are excluded — the ordering subquery only joins the direct target, never the\n * junction table. (Relation *filters* do support `.through()` — this guard is orderBy-only.)\n */\nexport const isFilterableRelation = (relation: Relation<string>): boolean => !(relation as any).through;\n","// The `exclude` config. Which columns a table hides, and the cache key that keeps two tables\n// excluding different columns from sharing a generated type.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { getColumns } from 'drizzle-orm';\n\n/**\n * Columns this build keeps out of the generated schema, keyed by the table object.\n *\n * A registry rather than a threaded parameter because the sites that decide schema shape —\n * the object type, every input, the filter, `orderBy`, the aggregates, the column enums —\n * are spread across four files and reach a table with no config in hand. Runtime code keeps\n * calling `getColumns` directly: a primary key that a client cannot name is still the key a\n * cursor is built from, and hiding it there would break pagination rather than secure it.\n *\n * {@link registerColumnExclusions} runs on every build, including with no config, so a\n * second build against the same table objects never inherits the first build's exclusions.\n */\nconst excludedColumnRegistry = new WeakMap<object, Set<string>>();\n\n/** Installs this build's column exclusions and clears any left by a previous build. */\nexport const registerColumnExclusions = (\n tables: Record<string, Table>,\n exclude?: { columns?: Record<string, string[]> },\n): void => {\n for (const [tableName, table] of Object.entries(tables)) {\n const hidden = exclude?.columns?.[tableName];\n if (hidden?.length) {\n excludedColumnRegistry.set(table, new Set(hidden));\n } else {\n excludedColumnRegistry.delete(table);\n }\n }\n};\n\n/** Whether any column of this table was excluded from the schema. */\nexport const hasExcludedColumns = (table: Table): boolean => excludedColumnRegistry.has(table);\n\n/**\n * A stable string naming this build's exclusions for `table`, empty when it has none. Used to\n * key the caches that hold generated types: two builds of the same table objects with\n * different exclusions must not share an entry, but *within* one build every call site has to\n * get the same instance back or the schema ends up with two types of the same name.\n */\nexport const excludedColumnsKey = (table: Table): string => {\n const hidden = excludedColumnRegistry.get(table);\n return hidden ? [...hidden].sort().join(',') : '';\n};\n\n/**\n * The columns of `table` that this build exposes — every column unless some were excluded.\n * Use this anywhere the result decides what the *schema* contains; use `getColumns` where it\n * decides what SQL to write.\n */\nexport const visibleColumns = (table: Table): Record<string, Column> => {\n const columns = getColumns(table);\n const hidden = excludedColumnRegistry.get(table);\n if (!hidden) {\n return columns;\n }\n return Object.fromEntries(Object.entries(columns).filter(([columnName]) => !hidden.has(columnName)));\n};\n","// Table key to GraphQL type name, through the caller's `typeNameMapper`.\n\nimport { capitalize } from '../../case-ops/index.ts';\nimport type { TypeNameResolver } from './type-names.ts';\n\n/** Optional mapper from table key to singular/plural name pair. Return undefined to use default naming for a table. */\nexport type TypeNameMapper = (tableName: string) => { singular: string; plural: string } | undefined;\n\n/** Produce the GraphQL object type name for a table, using the mapper if provided. */\nexport const resolveTypeName = (name: string, typeNameMapper?: TypeNameMapper): string => {\n const mapped = typeNameMapper?.(name);\n return mapped ? capitalize(mapped.singular) : capitalize(name);\n};\n\n/**\n * The name a table's object type actually carries in the built schema — {@link resolveTypeName}\n * put through the build's naming rule. Resolvers read selections out of\n * `fieldsByTypeName`, which is keyed by the real type name, so anything that walks a\n * selection tree has to ask for the name this way rather than assuming the default.\n */\nexport const resolveObjectTypeName = (\n name: string,\n typeNameMapper?: TypeNameMapper,\n resolveName?: TypeNameResolver,\n): string => applyObjectTypeName(resolveTypeName(name, typeNameMapper), name, resolveName);\n\n/** {@link resolveObjectTypeName} for a caller that already holds the table's default type name. */\nexport const applyObjectTypeName = (defaultName: string, tableName: string, resolveName?: TypeNameResolver): string =>\n resolveName ? resolveName({ kind: 'object', defaultName, table: tableName }) : defaultName;\n","// A table's compound unique constraints as `where` fields: the input a lookup by natural key\n// is spelled with, and the SQL it compiles to.\n//\n// The library already knows every unique constraint — `onConflict`'s `target` is validated\n// against them — but only on the write side. A read by a two-column natural key had to be\n// spelled as two ordinary filters, which reads as a partial filter that happens to return one\n// row, and stays valid when half of it goes missing. A key field says the same thing in one\n// place, with every member required.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { and, eq, getColumns, type SQL } from 'drizzle-orm';\nimport { GraphQLInputObjectType, GraphQLNonNull } from 'graphql';\nimport { capitalize } from '../../case-ops/index.ts';\nimport { remapFromGraphQLCore } from '../../data-mappers/index.ts';\nimport { drizzleColumnToGraphQLType } from '../../type-converter/index.ts';\nimport type { ConvertedInputColumn, NullableConvertedColumnType } from '../../type-converter/types.ts';\nimport { drizzleError } from './errors.ts';\nimport { visibleColumns } from './exclusions.ts';\nimport type { TypeNameMapper } from './naming.ts';\nimport { resolveTypeName } from './naming.ts';\nimport type { TypeCacheCtx } from './type-cache.ts';\n\n/** A table's unique-key `where` fields: field name → the constraint's member property names. */\nexport type UniqueKeyMap = Record<string, readonly string[]>;\n\n/** The field a constraint is offered under: its member property names, in declaration order. */\nexport const uniqueKeyFieldName = (members: readonly string[]): string => members.join('_');\n\n/**\n * Which of a table's unique constraints get a `where` field.\n *\n * Single-column constraints are left out — `eq` on the column already says \"the row with this\n * key\", and a wrapper around one value would only be a second way to spell it. A set whose\n * field name is taken by a column or a relation is left out too: the existing field keeps the\n * name, exactly as a relation yields to a same-named column.\n *\n * @param taken names already claimed on the table's filter input (columns, then relations)\n */\nexport const buildUniqueKeyMap = (sets: readonly string[][], taken: ReadonlySet<string>): UniqueKeyMap => {\n const map: Record<string, readonly string[]> = {};\n for (const set of sets) {\n if (set.length < 2) {\n continue;\n }\n const fieldName = uniqueKeyFieldName(set);\n if (taken.has(fieldName) || fieldName in map) {\n continue;\n }\n map[fieldName] = set;\n }\n return map;\n};\n\n/**\n * The `where` fields for a table's compound unique constraints, one input type per constraint.\n *\n * Every member is non-null, which is the whole point: a half-supplied key is a query-validation\n * error rather than a filter that quietly matches more rows than the caller meant it to.\n */\nexport const generateUniqueKeyFilterFields = (\n table: Table,\n tableName: string,\n uniqueKeys: UniqueKeyMap,\n typeNameMapper: TypeNameMapper | undefined,\n cacheCtx: TypeCacheCtx,\n): Record<string, ConvertedInputColumn> => {\n const columns = visibleColumns(table) as Record<string, Column>;\n const typeName = resolveTypeName(tableName, typeNameMapper);\n const fields: Record<string, ConvertedInputColumn> = {};\n\n for (const [fieldName, members] of Object.entries(uniqueKeys)) {\n fields[fieldName] = {\n type: new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'uniqueKey',\n defaultName: `${typeName}${members.map((member) => capitalize(member)).join('')}Key`,\n table: tableName,\n operation: fieldName,\n }),\n description: `The unique constraint on ${members.join(' + ')} of ${typeName}. Every field is required — a half-supplied key is an error, not a broader filter.`,\n fields: Object.fromEntries(\n members.map((member) => [\n member,\n {\n // `forceNullable` is on, so the conversion never returns an already-wrapped type;\n // the cast is only to narrow the union graphql 17 refuses to wrap.\n type: new GraphQLNonNull(\n drizzleColumnToGraphQLType(columns[member]!, member, tableName, true, false, true)\n .type as NullableConvertedColumnType<true>,\n ),\n },\n ]),\n ),\n }),\n description: `The one ${typeName} row holding this ${members.join(' + ')} key. ANDed with any sibling filters.`,\n } as ConvertedInputColumn;\n }\n\n return fields;\n};\n\n/**\n * Compiles a unique-key field into the equality on each member column. Identical to the\n * filters it replaces — the guarantee is in the input type, not in the SQL.\n */\nexport const extractUniqueKeyFilter = (\n table: Table,\n tableName: string,\n fieldName: string,\n members: readonly string[],\n value: Record<string, any>,\n): SQL | undefined => {\n const columns = getColumns(table) as Record<string, Column>;\n const conditions: SQL[] = [];\n\n for (const member of members) {\n const column = columns[member];\n const supplied = value?.[member];\n // Unreachable through the generated input, whose members are all non-null. Reachable when\n // the same-named input arrives from a stitched schema that spells the key differently, and\n // a key missing a column is not the key.\n if (!column || supplied === undefined || supplied === null) {\n throw drizzleError(`WHERE ${tableName}: ${fieldName} is missing ${member}, so it does not name a row.`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n conditions.push(eq(column, remapFromGraphQLCore(supplied, column, member)));\n }\n\n return conditions.length > 1 ? and(...conditions) : conditions[0];\n};\n","// Relation keys inside a `where`: the correlated EXISTS subquery each `some` / `none` / `every`\n// compiles to, and `extractFilters`, which dispatches a whole filter object across columns,\n// boolean groups and relations.\n\nimport type { Column, Relation, Table } from 'drizzle-orm';\nimport {\n aliasedTable,\n and,\n eq,\n getColumns,\n getTableAsAliasSQL,\n is,\n not,\n One,\n or,\n relationsFilterToSQL,\n type SQL,\n sql,\n} from 'drizzle-orm';\nimport type { FilterColumnOperatorsCore, Filters, TableNamedRelations } from '../types.ts';\nimport { drizzleError } from './errors.ts';\nimport { extractFiltersColumn } from './filters.ts';\nimport { isRelationFilterReversed, relationColumns, relationOwnWhere, unwrapRelationColumn } from './relations.ts';\nimport type { UniqueKeyMap } from './unique-keys.ts';\nimport { extractUniqueKeyFilter } from './unique-keys.ts';\n\n/**\n * Everything `extractFilters` needs to turn a relation key in a `where` argument into a\n * correlated subquery. Omitted by callers that don't generate relation filters, in which case\n * relation keys can't appear in the input to begin with.\n */\nexport interface RelationFilterContext {\n /** Every table in the schema, keyed by its schema key. */\n tables: Record<string, Table>;\n /** Relations keyed by table schema key, then relation name. */\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n /**\n * Schema key of the table being filtered. Not always the same as the `tableName` label\n * used in error messages (relation `where` callbacks pass the relation name there).\n */\n tableKey: string;\n /** Shared counter making every subquery alias unique within one extraction. */\n aliases?: { n: number };\n /**\n * The compound-unique-key `where` fields of each table, keyed by table schema key. Only\n * populated when `features.uniqueKeyFilters` generated them — a key field the build did not\n * generate is an unknown filter key like any other.\n */\n uniqueKeys?: Record<string, UniqueKeyMap>;\n}\n\n/**\n * The build-scoped half of {@link RelationFilterContext}. Created once per generated schema and\n * handed to every resolver, which adds the table it is filtering.\n */\nexport type RelationFilterBase = Pick<RelationFilterContext, 'tables' | 'relationMap' | 'uniqueKeys'>;\n\n/**\n * The narrowed contexts already handed out, keyed by the build-scoped base and then by\n * table. The base is created once per `buildSchema` and the result depends on nothing else,\n * so every call for one table produces the same value — a `WeakMap` on the base keeps them\n * for exactly as long as that build is reachable.\n */\nconst narrowedCtxCache = new WeakMap<RelationFilterBase, Map<string, RelationFilterContext>>();\n\n/**\n * Narrows the build-scoped relation filter context to the table a resolver is filtering.\n *\n * Cached rather than rebuilt: the base carries the build's whole `tables` and `relationMap`,\n * and the spread copied both on every call — three per parent row in the lazy relation\n * resolver, one per parent row in the relation aggregate, and up to four per select, several\n * of them inside callbacks drizzle invokes lazily.\n *\n * The one field written after the fact is `aliases`, the counter that keeps subquery aliases\n * apart ({@link extractRelationFilter}). Sharing it is what makes the caching safe rather\n * than a hazard: the counter now spans the process instead of restarting per extraction, and\n * aliases only ever have to be unique *within* one statement, which a number that never\n * repeats gives more surely than one that restarts.\n */\nexport const relationFilterCtx = (\n base: RelationFilterBase | undefined,\n tableKey: string,\n): RelationFilterContext | undefined => {\n if (!base) {\n return undefined;\n }\n\n let byTable = narrowedCtxCache.get(base);\n if (!byTable) {\n byTable = new Map();\n narrowedCtxCache.set(base, byTable);\n }\n\n let ctx = byTable.get(tableKey);\n if (!ctx) {\n ctx = { ...base, tableKey };\n byTable.set(tableKey, ctx);\n }\n\n return ctx;\n};\n\n/** The three ways a to-many relation can be required to match, plus the to-one shorthand. */\ntype RelationMatchMode = 'some' | 'none' | 'every';\n\n/**\n * Correlates the parent row with the aliased target table using the relation's own join\n * columns. Columns are matched by SQL name rather than object identity so this also works when\n * the parent is an aliased proxy (as it is inside a relational `with:` where callback).\n */\nexport const buildRelationJoinCondition = (\n parentTable: Table,\n relation: Relation<string>,\n aliasedTarget: Table,\n relationName: string,\n): SQL | undefined => {\n const sourceColumns = relationColumns(relation, 'source');\n const targetColumns = relationColumns(relation, 'target');\n\n if (!sourceColumns?.length || sourceColumns.length !== targetColumns?.length) {\n throw drizzleError(`WHERE ${relationName}: Relation cannot be used as a filter`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n\n const parentColumns = Object.values(getColumns(parentTable));\n const targetColumnsByName = Object.values(getColumns(aliasedTarget));\n\n const conditions: SQL[] = [];\n for (let i = 0; i < sourceColumns.length; i++) {\n const localColumn = parentColumns.find((c) => c.name === sourceColumns[i]!.name);\n const foreignColumn = targetColumnsByName.find((c) => c.name === targetColumns[i]!.name);\n\n if (!localColumn || !foreignColumn) {\n throw drizzleError(`WHERE ${relationName}: Relation cannot be used as a filter`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n\n conditions.push(eq(localColumn, foreignColumn));\n }\n\n return conditions.length > 1 ? and(...conditions) : conditions[0];\n};\n\n/**\n * Resolves one side of a `.through()` junction pair to the corresponding column on the\n * aliased junction table. Drizzle stores the junction column as a RelationsBuilderColumn\n * (`_.column` is the Column, `_.key` its property name), so look up by property name first\n * and fall back to matching by SQL name.\n */\nconst resolveJunctionColumn = (aliasedThrough: Table, junctionRef: any, relationName: string): Column => {\n const throughColumns = getColumns(aliasedThrough);\n\n const key: string | undefined = junctionRef?._?.key;\n const byKey = key ? throughColumns[key] : undefined;\n if (byKey) {\n return byKey;\n }\n\n const columnName: string | undefined = unwrapRelationColumn(junctionRef)?.name;\n const byName = columnName ? Object.values(throughColumns).find((c) => c.name === columnName) : undefined;\n if (!byName) {\n throw drizzleError(`WHERE ${relationName}: Relation cannot be used as a filter`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n\n return byName;\n};\n\n/**\n * Join conditions for a `.through()` (many-to-many) relation, split into the two legs of the\n * junction: `correlation` ties the parent row to the aliased junction table on the relation's\n * source keys, `junctionJoin` ties the aliased junction table to the aliased target on the\n * target keys. Column matching mirrors {@link buildRelationJoinCondition} — by SQL name on the\n * parent/target so aliased proxies work — while junction columns come from the relation's own\n * `through` metadata.\n */\nconst buildThroughJoinConditions = (\n parentTable: Table,\n relation: Relation<string>,\n aliasedThrough: Table,\n aliasedTarget: Table,\n relationName: string,\n): { correlation: SQL | undefined; junctionJoin: SQL | undefined } => {\n const sourceColumns = relationColumns(relation, 'source');\n const targetColumns = relationColumns(relation, 'target');\n const through = (relation as any).through as { source: any[]; target: any[] } | undefined;\n\n if (\n !sourceColumns?.length ||\n !targetColumns?.length ||\n through?.source.length !== sourceColumns.length ||\n through.target.length !== targetColumns.length\n ) {\n throw drizzleError(`WHERE ${relationName}: Relation cannot be used as a filter`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n\n const parentColumns = Object.values(getColumns(parentTable));\n const targetTableColumns = Object.values(getColumns(aliasedTarget));\n\n const correlationConditions: SQL[] = [];\n for (let i = 0; i < sourceColumns.length; i++) {\n const localColumn = parentColumns.find((c) => c.name === sourceColumns[i]!.name);\n if (!localColumn) {\n throw drizzleError(`WHERE ${relationName}: Relation cannot be used as a filter`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n correlationConditions.push(eq(localColumn, resolveJunctionColumn(aliasedThrough, through.source[i], relationName)));\n }\n\n const junctionJoinConditions: SQL[] = [];\n for (let i = 0; i < targetColumns.length; i++) {\n const foreignColumn = targetTableColumns.find((c) => c.name === targetColumns[i]!.name);\n if (!foreignColumn) {\n throw drizzleError(`WHERE ${relationName}: Relation cannot be used as a filter`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n junctionJoinConditions.push(\n eq(resolveJunctionColumn(aliasedThrough, through.target[i], relationName), foreignColumn),\n );\n }\n\n return {\n correlation: correlationConditions.length > 1 ? and(...correlationConditions) : correlationConditions[0],\n junctionJoin: junctionJoinConditions.length > 1 ? and(...junctionJoinConditions) : junctionJoinConditions[0],\n };\n};\n\n/**\n * Builds one `[NOT] EXISTS (SELECT 1 FROM target alias WHERE …)` for a relation filter.\n * A `.through()` (many-to-many) relation adds an `INNER JOIN` on the aliased junction table\n * inside the subquery, correlated to the parent on the relation's source keys.\n *\n * `some` / the to-one shorthand match when a related row satisfies the inner filters, `none`\n * when none does, and `every` is expressed as \"no related row fails the inner filters\".\n * Because `every` negates the inner condition, a related row whose compared column is NULL\n * counts as matching (SQL three-valued logic) — the same caveat Prisma carries.\n */\nconst buildRelationExists = (\n parentTable: Table,\n relationName: string,\n relEntry: TableNamedRelations,\n innerFilters: Filters<Table> | undefined,\n mode: RelationMatchMode,\n ctx: RelationFilterContext,\n): SQL | undefined => {\n const { targetTableName } = relEntry;\n const targetTable = ctx.tables[targetTableName];\n const relation = ((relEntry as any).relation ?? relEntry) as Relation<string>;\n\n if (!targetTable) {\n throw drizzleError(`WHERE ${relationName}: Relation cannot be used as a filter`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n\n ctx.aliases ??= { n: 0 };\n const aliases = ctx.aliases;\n const aliasedTarget = aliasedTable(targetTable, `dgql_rel_${aliases.n++}`);\n\n // A `.through()` relation reaches the target via a junction table: the subquery joins the\n // aliased junction to the aliased target and correlates the junction to the parent, so\n // `some` / `none` / `every` compile exactly like the direct case with a longer FROM clause.\n const throughTable = (relation as any).throughTable as Table | undefined;\n let fromClause: SQL;\n let joinCondition: SQL | undefined;\n if (throughTable) {\n const aliasedThrough = aliasedTable(throughTable, `dgql_rel_${aliases.n++}`);\n const { correlation, junctionJoin } = buildThroughJoinConditions(\n parentTable,\n relation,\n aliasedThrough,\n aliasedTarget,\n relationName,\n );\n fromClause = sql`${getTableAsAliasSQL(aliasedTarget)} inner join ${getTableAsAliasSQL(aliasedThrough)} on ${junctionJoin}`;\n joinCondition = correlation;\n } else {\n fromClause = getTableAsAliasSQL(aliasedTarget);\n joinCondition = buildRelationJoinCondition(parentTable, relation, aliasedTarget, relationName);\n }\n\n // A relation declared with its own `where` only ever exposes the rows it selects, so the\n // subquery has to honour it too — otherwise a filter could match a row the relation hides.\n const ownWhere = relationOwnWhere(relation);\n const relationWhere = ownWhere\n ? relationsFilterToSQL(isRelationFilterReversed(relation) ? parentTable : aliasedTarget, ownWhere as any)\n : undefined;\n\n const inner = innerFilters\n ? extractFilters(aliasedTarget, targetTableName, innerFilters, { ...ctx, tableKey: targetTableName, aliases })\n : undefined;\n\n if (mode === 'every') {\n // \"every related row matches\" with no inner condition is vacuously true.\n if (!inner) {\n return undefined;\n }\n\n return sql`not exists (select 1 from ${fromClause} where ${and(joinCondition, relationWhere, not(inner))})`;\n }\n\n const condition = and(joinCondition, relationWhere, inner);\n\n return mode === 'none'\n ? sql`not exists (select 1 from ${fromClause} where ${condition})`\n : sql`exists (select 1 from ${fromClause} where ${condition})`;\n};\n\n/**\n * Handles one relation key in a `where` argument. To-one relations take the target's filters\n * inline; to-many relations take any combination of `some` / `none` / `every`, ANDed together.\n */\nconst extractRelationFilter = (\n parentTable: Table,\n relationName: string,\n relEntry: TableNamedRelations,\n value: Record<string, any>,\n ctx: RelationFilterContext,\n): SQL | undefined => {\n const relation = ((relEntry as any).relation ?? relEntry) as Relation<string>;\n\n if (is(relation, One)) {\n return buildRelationExists(parentTable, relationName, relEntry, value, 'some', ctx);\n }\n\n const relationMatchModes: readonly RelationMatchMode[] = ['some', 'none', 'every'];\n\n const variants: SQL[] = [];\n for (const [mode, inner] of Object.entries(value)) {\n if (inner === undefined || inner === null) {\n continue;\n }\n\n // Unknown keys inside the some/none/every wrapper must throw rather than be dropped —\n // a stitched schema can contribute foreign keys here too, and dropping them all would\n // silently turn the relation filter into no filter at all.\n if (!relationMatchModes.includes(mode as RelationMatchMode)) {\n throw drizzleError(`WHERE ${relationName}: Unknown relation filter key: ${mode}`, {\n code: 'DRIZZLE_INVALID_FILTER',\n });\n }\n\n const extracted = buildRelationExists(parentTable, relationName, relEntry, inner, mode as RelationMatchMode, ctx);\n if (extracted) {\n variants.push(extracted);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n\nexport const extractFilters = <TTable extends Table>(\n table: TTable,\n tableName: string,\n filters: Filters<TTable>,\n relationCtx?: RelationFilterContext,\n): SQL | undefined => {\n // Boolean branches compose with sibling fields: siblings and the AND list are ANDed\n // together, NOT negates its whole branch, and the OR group is ANDed with the rest —\n // `{ a: …, OR: [{ b: … }, { c: … }] }` reads as `a AND (b OR c)`. Every branch is the\n // filter type itself, so the tree nests arbitrarily.\n const { OR, AND, NOT, ...fieldFilters } = filters;\n\n // `Omit`-ing the boolean keys off a generic `Filters<TTable>` leaves a type the checker\n // can no longer relate to `FiltersCore<TTable>`. Each key is dispatched on its own below\n // — as a column or as a relation — so the entries are typed for that dispatch instead.\n const entries = Object.entries(fieldFilters) as [string, FilterColumnOperatorsCore<any> | undefined][];\n\n const columns = getColumns(table);\n const relations = relationCtx?.relationMap[relationCtx.tableKey];\n\n const variants = [] as SQL[];\n for (const [fieldName, operators] of entries) {\n if (operators === null || operators === undefined) {\n continue;\n }\n\n const column = columns[fieldName];\n // Resolved in the order the fields were generated in: a column keeps its name, then a\n // relation, and a unique-key field only exists where neither claimed it.\n const uniqueKey = column ? undefined : relationCtx?.uniqueKeys?.[relationCtx.tableKey]?.[fieldName];\n\n // A key that is none of the three must throw rather than be dropped: when the generated\n // schema is stitched/merged with another schema, same-named inputs can contribute foreign\n // keys that pass input validation, and a where that loses all of its keys silently becomes\n // an unbounded select/update/delete.\n if (!column && !uniqueKey && !(relations?.[fieldName] && relationCtx)) {\n throw drizzleError(`WHERE ${tableName}: Unknown filter key: ${fieldName}`, { code: 'DRIZZLE_INVALID_FILTER' });\n }\n\n const extracted = column\n ? extractFiltersColumn(column, fieldName, operators)\n : uniqueKey\n ? extractUniqueKeyFilter(table, tableName, fieldName, uniqueKey, operators as any)\n : extractRelationFilter(table, fieldName, relations![fieldName]!, operators as any, relationCtx!);\n\n if (extracted) {\n variants.push(extracted);\n }\n }\n\n if (AND?.length) {\n for (const variant of AND) {\n const extracted = extractFilters(table, tableName, variant, relationCtx);\n if (extracted) {\n variants.push(extracted);\n }\n }\n }\n\n if (NOT) {\n const extracted = extractFilters(table, tableName, NOT, relationCtx);\n // `not()` is typed `SQL | undefined` from drizzle-orm rc.5 on, `SQL` before it.\n const negated = extracted ? not(extracted) : undefined;\n if (negated) {\n variants.push(negated);\n }\n }\n\n if (OR?.length) {\n const orVariants = [] as SQL[];\n for (const variant of OR) {\n const extracted = extractFilters(table, tableName, variant, relationCtx);\n if (extracted) {\n orVariants.push(extracted);\n }\n }\n\n if (orVariants.length) {\n variants.push(orVariants.length > 1 ? or(...orVariants)! : orVariants[0]!);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Row-level scoping\n// ─────────────────────────────────────────────────────────────────────────────\n","// Row-level policy: `scope`, `softDelete` and `contextValues`, each resolved per table and\n// bound into the shape the resolvers apply at request time.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { and, eq, extractExtendedColumnType, getColumns, is, isNotNull, isNull, ne, or, SQL } from 'drizzle-orm';\nimport { GraphQLEnumType } from 'graphql';\nimport { drizzleError } from './errors.ts';\nimport type { DefaultOrderByFor } from './limits.ts';\nimport type { RelationFilterBase } from './relation-filters.ts';\nimport { extractFilters, relationFilterCtx } from './relation-filters.ts';\nimport { sharedType, type TypeNameResolver } from './type-names.ts';\nimport type { WriteHookFor } from './write-hooks.ts';\n\n/**\n * A table's row-level scope: the predicate every generated read, update and delete on that\n * table is narrowed by. See `BuildSchemaConfig.scope`.\n *\n * `table` is the table the predicate must be built against. On the relational-query path\n * drizzle hands its callbacks an *aliased* proxy (`d0`, `d1`, …), so a predicate built from\n * the imported schema table would reference a name that isn't in the query — always build\n * from the argument. Returning a filter object instead (the same shape as the field's\n * `where`) sidesteps aliasing entirely, and is the only form that can reach through a\n * relation — which is what ownership through a join table needs.\n */\ntype ScopeHook<TContext = any> = (context: TContext, table: any) => SQL | Record<string, any> | undefined | null;\n\n/** Build-time lookup: the scope configured for a table, if any. */\nexport type ScopeFor = (tableName: string) => ScopeHook | undefined;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Soft delete\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** What a read over a soft-deleting table does with rows that are marked deleted. */\nexport type DeletedMode = 'EXCLUDE' | 'INCLUDE' | 'ONLY';\n\n/**\n * One table's soft-delete convention, resolved against the real column at build time.\n *\n * `marker` picks the shape of the predicate. When the config names a constant that means\n * deleted, the predicate compares against it (`isDeleted = true`); otherwise the column marks\n * a row deleted by holding a value at all (`deletedAt IS NOT NULL`), the common timestamp\n * form. A NOT NULL column has no \"absent\" state, so it must have a marker; a nullable one\n * takes the NULL-means-alive reading only when no marker was configured.\n */\nexport type SoftDeleteInfo = {\n /** Property name of the column on the drizzle table — also the key on an aliased proxy. */\n columnName: string;\n column: Column;\n nullable: boolean;\n /** Evaluated per delete, so a timestamp form stamps the moment of the delete. */\n writeDeleted: () => any;\n /** Written by the restore mutation. */\n writeRestored: any;\n /**\n * The constant that means \"this row is deleted\", when the config named one. Required on a\n * NOT NULL column; optional on a nullable one, which otherwise reads NULL as alive.\n */\n marker?: any;\n /**\n * Which reads hide marked rows by default — `'all'` (the table's own fields and every\n * relation pointing at it) or `'root'` (its own fields only). See\n * {@link relationDeletedDefault}.\n */\n scope: 'root' | 'all';\n /**\n * Whether the delete mutations take a `hard` argument that issues a real `DELETE`. Off\n * unless the table opts in, so the generated schema says which tables can be purged.\n */\n hardDelete: boolean;\n};\n\n/** Build-time lookup: the soft-delete convention of a table, if it declares one. */\nexport type SoftDeleteFor = (tableName: string) => SoftDeleteInfo | undefined;\n\n/**\n * The enum behind the `deleted` argument on every read over a soft-deleting table. Built once\n * per name it resolves to — it carries no per-build state beyond that name, so every build\n * that names it the same way shares one instance.\n */\nexport const deletedFilterEnumType = (typeName: TypeNameResolver): GraphQLEnumType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'DeletedFilter' },\n (name) =>\n new GraphQLEnumType({\n name,\n description: 'Which rows a read over a soft-deleting table returns.',\n values: {\n EXCLUDE: { value: 'EXCLUDE', description: 'Only rows that are not marked deleted. The default.' },\n INCLUDE: { value: 'INCLUDE', description: 'Marked and unmarked rows alike.' },\n ONLY: { value: 'ONLY', description: 'Only rows that are marked deleted — a trash view.' },\n },\n }),\n );\n\n/**\n * Resolves one table's `softDelete` declaration against the real column, at build time, so a\n * renamed column fails the build instead of quietly making every row visible again.\n */\nexport const resolveSoftDeleteInfo = (\n table: Table,\n tableName: string,\n declaration:\n | string\n | {\n column: string;\n deletedValue?: any;\n restoredValue?: any;\n scope?: 'root' | 'all';\n hardDelete?: boolean;\n },\n): SoftDeleteInfo => {\n const config = typeof declaration === 'string' ? { column: declaration } : declaration;\n const columnName = config?.column;\n if (typeof columnName !== 'string' || !columnName) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName} must be a column name or an object with a 'column' property.`,\n );\n }\n const column = getColumns(table)[columnName];\n if (!column) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete names '${tableName}.${columnName}', which is not a column of that table.`,\n );\n }\n const nullable = !column.notNull;\n // drizzle-orm v1 reports compound dataType strings (\"object date\", \"number int32\"), so the\n // shape of the column has to come from the extended type rather than a string compare.\n const { type: baseType, constraint } = extractExtendedColumnType(column);\n const hasDeleted = 'deletedValue' in (config as object) && config.deletedValue !== undefined;\n // The default depends on what the column can hold: a timestamp records when, a flag records\n // whether. Both are the shapes the convention actually takes in the wild.\n const writeDeleted: () => any = hasDeleted\n ? typeof config.deletedValue === 'function'\n ? (config.deletedValue as () => any)\n : () => config.deletedValue\n : constraint === 'date' && baseType === 'object'\n ? () => new Date()\n : baseType === 'string'\n ? () => new Date().toISOString()\n : baseType === 'number'\n ? () => Date.now()\n : baseType === 'bigint'\n ? () => BigInt(Date.now())\n : () => true;\n\n let marker: any;\n if (hasDeleted && typeof config.deletedValue !== 'function') {\n // A configured constant is what reads compare against, whether or not the column is\n // nullable: a nullable boolean defaulting to `false` (the shape a marker column added to\n // an existing table without a backfill takes) means deleted by holding `true`, not by\n // holding anything at all.\n marker = config.deletedValue;\n } else if (!nullable) {\n // A non-nullable column has no \"absent\" state, so the predicate has to compare against a\n // constant — which a function cannot supply, and which the boolean form supplies for free.\n if (!hasDeleted && baseType === 'boolean') {\n marker = true;\n } else {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName} marks a NOT NULL column ('${columnName}'), so 'deletedValue' must be a constant that means deleted — not a function, and not omitted for a non-boolean column.`,\n );\n }\n }\n\n const hasRestored = 'restoredValue' in (config as object);\n const writeRestored = hasRestored\n ? config.restoredValue\n : nullable\n ? null\n : baseType === 'boolean'\n ? false\n : undefined;\n if (!nullable && writeRestored === undefined) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName} marks a NOT NULL column ('${columnName}'), so 'restoredValue' must say what restoring writes back.`,\n );\n }\n\n const scope = config.scope ?? 'all';\n if (scope !== 'root' && scope !== 'all') {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName}.scope must be 'root' or 'all', not ${JSON.stringify(scope)}.`,\n );\n }\n\n const hardDelete = config.hardDelete ?? false;\n if (typeof hardDelete !== 'boolean') {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName}.hardDelete must be a boolean, not ${JSON.stringify(hardDelete)}.`,\n );\n }\n\n return { columnName, column, nullable, writeDeleted, writeRestored, marker, scope, hardDelete };\n};\n\n/**\n * The `deleted` mode a *relation* field reads its target with when the request does not pass\n * one. Root fields always default to `EXCLUDE`; a relation field is the case a soft delete\n * cannot answer for on its own, because the row it hides belongs to a different query than\n * the one that marked it.\n *\n * - `scope: 'root'` reads relations with `INCLUDE`: the row is retired, not erased, so the\n * historical rows that reference it keep rendering it.\n * - `scope: 'all'` keeps hiding it — except through a *required* to-one relation, where a\n * hidden row can only surface as \"Cannot return null for non-nullable field\" and take the\n * whole parent down with it. There is no usable result to protect there, so the row is\n * included rather than the parent lost.\n *\n * Returns `undefined` when the target declares no soft delete, so an unconfigured build\n * passes exactly the mode it did before.\n */\nexport const relationDeletedDefault = (\n softDelete: SoftDeleteFor | undefined,\n targetTableName: string,\n requiredToOne: boolean,\n): DeletedMode | undefined => {\n const info = softDelete?.(targetTableName);\n if (!info) {\n return undefined;\n }\n return info.scope === 'root' || requiredToOne ? 'INCLUDE' : 'EXCLUDE';\n};\n\n/**\n * The predicate that selects the rows a `deleted` mode asks for: nothing for `INCLUDE`, the\n * marked rows for `ONLY`, the unmarked ones for `EXCLUDE`. Built against the table it is\n * handed, which on the relational path is drizzle's aliased proxy rather than the schema\n * table — the same rule a scope hook follows.\n */\nexport const softDeletePredicate = (info: SoftDeleteInfo, table: Table, mode: DeletedMode): SQL | undefined => {\n if (mode === 'INCLUDE') {\n return undefined;\n }\n const column = ((table as any)?.[info.columnName] ?? info.column) as Column;\n if (info.marker === undefined) {\n return mode === 'ONLY' ? isNotNull(column) : isNull(column);\n }\n if (!info.nullable) {\n return mode === 'ONLY' ? eq(column, info.marker) : ne(column, info.marker);\n }\n // A nullable column with a marker: NULL is neither the marker nor a match for `<>`, so the\n // exclude side has to name it explicitly or every un-backfilled row would drop out.\n return mode === 'ONLY' ? eq(column, info.marker) : or(ne(column, info.marker), isNull(column))!;\n};\n\n/**\n * The row policies of one request, bound to its context: the table's scope and its\n * soft-delete convention, which both narrow the same `where`. `has` answers \"does this table\n * restrict anything at all\", cheaply and without evaluating a hook; `on` compiles the\n * predicate against a given table.\n */\nexport type ScopeResolver = {\n has: (tableName: string, mode?: DeletedMode) => boolean;\n on: (tableName: string, table: Table, mode?: DeletedMode) => SQL | undefined;\n /**\n * The mode a relation field reading `tableName` defaults to — see\n * {@link relationDeletedDefault}. Carried here because the eager (`with:`) path has the\n * resolver but not the build-time soft-delete lookup.\n */\n relationDefault: (tableName: string, requiredToOne: boolean) => DeletedMode | undefined;\n};\n\n/**\n * Binds the configured row policies to one request's GraphQL context. Returns `undefined`\n * when neither a scope nor a soft-delete column is configured, so every call site skips the\n * machinery with a single check and an unconfigured build generates exactly the SQL it did\n * before.\n */\nexport const resolveScope = (\n policies: TablePolicies | undefined,\n context: any,\n filterCtx?: RelationFilterBase,\n): ScopeResolver | undefined => {\n const scopes = policies?.scope;\n const softDelete = policies?.softDelete;\n if (!scopes && !softDelete) {\n return undefined;\n }\n return {\n has: (tableName, mode) => !!scopes?.(tableName) || (!!softDelete?.(tableName) && (mode ?? 'EXCLUDE') !== 'INCLUDE'),\n relationDefault: (tableName, requiredToOne) => relationDeletedDefault(softDelete, tableName, requiredToOne),\n on: (tableName, table, mode) => {\n // Order is fixed: the soft-delete predicate first, the scope after it, both ANDed. They\n // commute, but a fixed order keeps the generated SQL stable between requests.\n const marked = softDelete?.(tableName);\n const deleted = marked ? softDeletePredicate(marked, table, mode ?? 'EXCLUDE') : undefined;\n const hook = scopes?.(tableName);\n if (!hook) {\n return deleted;\n }\n const predicate = hook(context, table);\n if (predicate === undefined || predicate === null) {\n return deleted;\n }\n if (is(predicate, SQL)) {\n return and(deleted, predicate as SQL);\n }\n if (typeof predicate !== 'object') {\n throw drizzleError(\n `Drizzle-GraphQL Error: the scope for '${tableName}' returned a ${typeof predicate}. A scope returns a filter object, a Drizzle SQL expression, or undefined.`,\n { code: 'DRIZZLE_INVALID_SCOPE' },\n );\n }\n // A filter object is compiled the same way the field's own `where` is, against the\n // table it was handed — which is what keeps it correct under RQB aliasing.\n return and(deleted, extractFilters(table, tableName, predicate as any, relationFilterCtx(filterCtx, tableName)));\n },\n };\n};\n\n/**\n * `condition AND <the row policies of tableName>` — the single way a scope or a soft-delete\n * predicate is ever combined with a caller-supplied filter, so a `where` can only ever narrow\n * them, never widen them. `mode` is the read's `deleted` argument, and defaults to hiding\n * marked rows; a write passes nothing and so never touches one.\n */\nexport const withScope = (\n scope: ScopeResolver | undefined,\n tableName: string,\n table: Table,\n condition: SQL | undefined,\n mode?: DeletedMode,\n): SQL | undefined => {\n const predicate = scope?.on(tableName, table, mode);\n return predicate ? and(condition, predicate) : condition;\n};\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Context-derived column values\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Produces one column's value from the GraphQL context. See `BuildSchemaConfig.contextValues`. */\nexport type ContextValueHook<TContext = any> = (context: TContext) => any;\n\n/** Build-time lookup: the context-derived columns of a table, keyed by column property name. */\nexport type ContextValuesFor = (tableName: string) => Record<string, ContextValueHook> | undefined;\n\n/**\n * The two request-time policies a generated resolver applies, passed to the dialect\n * generators as one value so a table's read scope and its server-owned columns travel\n * together. Both stay `undefined` when nothing is configured, and every call site checks\n * before doing any work — an unconfigured build generates exactly the SQL it did before.\n */\nexport type TablePolicies = {\n /** See `BuildSchemaConfig.scope`. */\n scope?: ScopeFor;\n /** See `BuildSchemaConfig.contextValues`. */\n contextValues?: ContextValuesFor;\n /** See `BuildSchemaConfig.softDelete`. */\n softDelete?: SoftDeleteFor;\n /** See `BuildSchemaConfig.onWrite`. */\n onWrite?: WriteHookFor;\n /** See `BuildSchemaConfig.defaults`. */\n defaultOrderBy?: DefaultOrderByFor;\n};\n\n/**\n * {@link TablePolicies} with the scope already bound to the build's relation context, which\n * is what a dialect generator is handed: `scope(context)` is all a resolver needs to compile\n * a predicate, and it stays `undefined` when nothing is scoped.\n */\nexport type ResolverPolicies = {\n scope?: (context: any) => ScopeResolver | undefined;\n contextValues?: ContextValuesFor;\n softDelete?: SoftDeleteFor;\n onWrite?: WriteHookFor;\n defaultOrderBy?: DefaultOrderByFor;\n};\n\n/** Binds a build's {@link TablePolicies} to its relation context, once, at schema-build time. */\nexport const bindPolicies = (\n policies: TablePolicies | undefined,\n filterCtx: RelationFilterBase | undefined,\n): ResolverPolicies | undefined =>\n policies?.scope || policies?.contextValues || policies?.softDelete || policies?.onWrite || policies?.defaultOrderBy\n ? {\n scope:\n policies.scope || policies.softDelete\n ? (context: any) => resolveScope(policies, context, filterCtx)\n : undefined,\n contextValues: policies.contextValues,\n softDelete: policies.softDelete,\n onWrite: policies.onWrite,\n defaultOrderBy: policies.defaultOrderBy,\n }\n : undefined;\n\n/**\n * Merges a table's context-derived values into one row's insert values. The hooks run per\n * row — a value may depend on the row's own contents through the closure the caller built —\n * and they overwrite whatever was there: the columns are not in the create input, so nothing\n * legitimate can be lost, but a stitched-in input could still carry the key and the server's\n * value has to win.\n */\nexport const applyContextValues = (\n values: Record<string, any>,\n hooks: Record<string, ContextValueHook> | undefined,\n context: any,\n): Record<string, any> => {\n if (!hooks) {\n return values;\n }\n for (const [columnName, hook] of Object.entries(hooks)) {\n values[columnName] = hook(context);\n }\n return values;\n};\n\n/** {@link applyContextValues} over a batch — every row in an insert gets its own evaluation. */\nexport const applyContextValuesAll = (\n rows: Record<string, any>[],\n hooks: Record<string, ContextValueHook> | undefined,\n context: any,\n): Record<string, any>[] => {\n if (!hooks) {\n return rows;\n }\n for (const row of rows) {\n applyContextValues(row, hooks, context);\n }\n return rows;\n};\n\n/**\n * Drops context-derived columns from an update's `set`. They are not in the update input\n * either, so this only matters when the key arrives some other way — and reassigning one is\n * exactly the ownership transfer the feature exists to prevent.\n */\nexport const stripContextValues = (\n values: Record<string, any>,\n hooks: Record<string, ContextValueHook> | undefined,\n): Record<string, any> => {\n if (!hooks) {\n return values;\n }\n for (const columnName of Object.keys(hooks)) {\n delete values[columnName];\n }\n return values;\n};\n","// The argument maps the generated read fields take: the shared filter/order/paging set,\n// and the `deleted` argument a soft-deleting table adds.\n\nimport {\n type GraphQLEnumType,\n type GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLString,\n} from 'graphql';\nimport type { SoftDeleteFor } from './policies.ts';\nimport { deletedFilterEnumType } from './policies.ts';\nimport type { GeneratedTypeInfo, TypeNameResolver } from './type-names.ts';\n\n/** GraphQL argument map for a list/array select field. */\n/**\n * The `deleted` argument, emitted only on reads over a table that declares a soft-delete\n * column — a schema with no soft delete anywhere keeps exactly the arguments it had.\n */\nexport const deletedArg = (\n softDelete: SoftDeleteFor | undefined,\n tableName: string,\n resolveName?: TypeNameResolver,\n): Record<string, { type: any; description: string }> =>\n softDelete?.(tableName)\n ? {\n deleted: {\n type: deletedFilterEnumType(resolveName ?? ((info: GeneratedTypeInfo) => info.defaultName)),\n description: 'Whether rows marked deleted are returned. Defaults to EXCLUDE.',\n },\n }\n : {};\n\nexport const selectArrayArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n distinctEnum?: GraphQLEnumType,\n softDelete?: SoftDeleteFor,\n tableName?: string,\n resolveName?: TypeNameResolver,\n): Record<string, { type: any; description?: string }> => ({\n offset: { type: GraphQLInt },\n limit: { type: GraphQLInt },\n orderBy: { type: orderArgs },\n where: { type: filterArgs },\n after: {\n type: GraphQLString,\n description:\n \"Keyset pagination: only return rows strictly after this cursor (a row's `cursor` field from a previous page, under the same orderBy).\",\n },\n ...(distinctEnum ? { distinct: { type: new GraphQLList(new GraphQLNonNull(distinctEnum)) } } : {}),\n ...deletedArg(softDelete, tableName!, resolveName),\n});\n\n/** GraphQL argument map for a single-row select field (no `limit`). */\nexport const selectSingleArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n softDelete?: SoftDeleteFor,\n tableName?: string,\n resolveName?: TypeNameResolver,\n): Record<string, { type: any }> => ({\n offset: { type: GraphQLInt },\n orderBy: { type: orderArgs },\n where: { type: filterArgs },\n ...deletedArg(softDelete, tableName!, resolveName),\n});\n","// GraphQL enums naming a table's columns — the operand type for `distinctOn` and for any\n// argument that has to name a column rather than carry a value.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { GraphQLEnumType } from 'graphql';\nimport { excludedColumnsKey, visibleColumns } from './exclusions.ts';\nimport type { TypeNameResolver } from './type-names.ts';\n\n/** Alias of the row-number helper column in the `distinct` pass. Namespaced against real columns. */\nexport const DISTINCT_RN = '__drizzle_graphql_distinct_rn';\n\nconst columnEnumCache = new WeakMap<object, Map<string, GraphQLEnumType>>();\n\n/**\n * An enum of a table's column property names, under `enumName`. Cached per (table, enum name,\n * exclusions), like the order/filter inputs, so repeated builds reuse one instance and two\n * enums over the same table never collide.\n *\n * Returns `undefined` when no column qualifies — the caller then omits the argument or\n * input field the enum would have typed, rather than emitting an empty enum, which is\n * invalid GraphQL.\n */\nexport const generateColumnEnum = (\n table: Table,\n enumName: string,\n description: string,\n predicate: (column: Column, columnName: string) => boolean = () => true,\n): GraphQLEnumType | undefined => {\n // The exclusions are part of the key, not a reason to skip the cache: a table's enum is\n // asked for from more than one place in a build (a list query's `distinct` argument and the\n // same argument on a to-many relation field pointing at it), and handing those two call\n // sites separate instances would put two types of the same name in one schema.\n const cacheKey = `${enumName}\\u0000${excludedColumnsKey(table)}`;\n let tableCache = columnEnumCache.get(table);\n const cached = tableCache?.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const columnNames = Object.entries(visibleColumns(table))\n .filter(([columnName, column]) => predicate(column as Column, columnName))\n .map(([columnName]) => columnName);\n if (!columnNames.length) {\n return undefined;\n }\n\n const enumType = new GraphQLEnumType({\n name: enumName,\n description,\n values: Object.fromEntries(columnNames.map((columnName) => [columnName, { value: columnName }])),\n });\n\n if (!tableCache) {\n tableCache = new Map();\n columnEnumCache.set(table, tableCache);\n }\n tableCache.set(cacheKey, enumType);\n return enumType;\n};\n\n/**\n * `${typeName}DistinctColumn` — the enum of columns a list query may be made distinct on.\n *\n * @param resolveName the build's naming rule, where the caller has one; the default name is\n * used as-is when it does not, which is what a consumer calling this directly gets.\n */\nexport const generateDistinctEnum = (\n table: Table,\n typeName: string,\n resolveName?: TypeNameResolver,\n tableKey?: string,\n): GraphQLEnumType | undefined => {\n const defaultName = `${typeName}DistinctColumn`;\n return generateColumnEnum(\n table,\n resolveName?.({ kind: 'columnEnum', defaultName, table: tableKey, operation: 'distinct' }) ?? defaultName,\n `Columns of ${typeName} that a query can be made distinct on`,\n );\n};\n\n// ── upsert / conflict handling ────────────────────────────────────────────────\n","// The `onConflict` argument: the input type it is generated from, and the plan a resolver\n// compiles one into before handing it to the dialect's upsert.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { getColumns, type SQL, sql } from 'drizzle-orm';\nimport { GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull } from 'graphql';\nimport { generateColumnEnum } from './column-enums.ts';\nimport { drizzleError } from './errors.ts';\nimport type { TypeCacheCtx } from './type-cache.ts';\nimport { sharedType, type TypeNameResolver } from './type-names.ts';\n\n/** Shared by every table's `${typeName}OnConflict` input, so it is created once per name. */\nexport const conflictActionEnumType = (typeName: TypeNameResolver): GraphQLEnumType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'ConflictAction' },\n (name) =>\n new GraphQLEnumType({\n name,\n description: 'What an upsert does when a row with the same unique key already exists',\n values: {\n UPDATE: { value: 'UPDATE', description: 'Overwrite the conflicting row with the supplied values' },\n NOTHING: { value: 'NOTHING', description: 'Keep the existing row and insert nothing' },\n },\n }),\n );\n\n/**\n * The `${typeName}OnConflict` input that types an upsert's `onConflict` argument.\n *\n * `target` and `where` only exist when the dialect can express them: MySQL's\n * `ON DUPLICATE KEY UPDATE` fires on any unique key and takes no predicate, so offering\n * either there would mean silently ignoring it.\n *\n * Returns `undefined` when the table has nothing to conflict on (`withTarget` dialects\n * only) — the caller then generates no upsert mutations for that table at all, rather than\n * an operation whose every call is a database error.\n */\nexport const generateOnConflictInput = (params: {\n table: Table;\n tableName: string;\n typeName: string;\n uniqueSets: string[][];\n tableFilters: GraphQLInputObjectType;\n withTarget: boolean;\n cacheCtx: TypeCacheCtx;\n}): GraphQLInputObjectType | undefined => {\n const { table, tableName, typeName, uniqueSets, tableFilters, withTarget, cacheCtx } = params;\n const resolveName = cacheCtx.typeName;\n\n const updateEnum = generateColumnEnum(\n table,\n resolveName({\n kind: 'columnEnum',\n defaultName: `${typeName}UpdateColumn`,\n table: tableName,\n operation: 'conflictUpdate',\n }),\n `Columns of ${typeName} that an upsert can overwrite`,\n );\n if (!updateEnum) {\n return undefined;\n }\n\n const fields: Record<string, any> = {\n action: {\n type: conflictActionEnumType(resolveName),\n defaultValue: 'UPDATE',\n description: 'Whether a conflicting row is overwritten or left alone. Defaults to UPDATE.',\n },\n update: {\n type: new GraphQLList(new GraphQLNonNull(updateEnum)),\n description:\n 'Columns to overwrite on conflict. Defaults to every column the request supplied, minus the conflict target. Columns the request did not supply cannot be listed here — there would be no value to write.',\n },\n };\n\n if (withTarget) {\n const uniqueColumns = new Set(uniqueSets.flat());\n const targetEnum = generateColumnEnum(\n table,\n resolveName({\n kind: 'columnEnum',\n defaultName: `${typeName}ConflictTarget`,\n table: tableName,\n operation: 'conflictTarget',\n }),\n `Columns of ${typeName} that carry a unique constraint, and so can be conflicted on`,\n (_column, columnName) => uniqueColumns.has(columnName),\n );\n if (!targetEnum) {\n return undefined;\n }\n\n fields['target'] = {\n type: new GraphQLList(new GraphQLNonNull(targetEnum)),\n description:\n 'The unique column set a conflict is detected on. Must match one of the table’s unique constraints exactly. Defaults to the primary key.',\n };\n fields['where'] = {\n type: tableFilters,\n description: 'Only overwrite conflicting rows that match this filter. Others are left alone.',\n };\n }\n\n return new GraphQLInputObjectType({\n name: resolveName({ kind: 'onConflict', defaultName: `${typeName}OnConflict`, table: tableName }),\n description: `Conflict handling for an upsert of ${typeName}`,\n fields,\n });\n};\n\n/** The `onConflict` argument as it arrives from GraphQL. */\nexport type OnConflictArg = {\n action?: 'UPDATE' | 'NOTHING';\n target?: string[];\n update?: string[];\n where?: any;\n};\n\n/** What a dialect needs to turn an insert into an upsert. */\nexport type ConflictPlan = {\n action: 'UPDATE' | 'NOTHING';\n /** Columns to conflict on, or `undefined` on dialects that take no conflict target. */\n target: Column[] | undefined;\n /** `column -> value to write`, in Drizzle's `set` shape. Empty when the action is NOTHING. */\n set: Record<string, SQL>;\n setWhere: SQL | undefined;\n};\n\n/**\n * Turns the request's `onConflict` argument and the rows it is inserting into the clause a\n * dialect should attach.\n *\n * `excludedRef` names the row that failed to insert in the dialect's own terms\n * (`excluded.col` on PostgreSQL and SQLite, `values(col)` on MySQL), which is what makes a\n * batch upsert update each row with its own values instead of the last row's.\n *\n * An UPDATE with nothing left to write degrades to NOTHING: `DO UPDATE SET` with an empty\n * body is not valid SQL, and doing nothing is what the request asked for anyway.\n */\nexport const resolveConflictPlan = (params: {\n table: Table;\n values: Record<string, any>[];\n onConflict: OnConflictArg | undefined;\n pkNames: readonly string[];\n uniqueSets: string[][];\n excludedRef: (columnName: string) => SQL;\n withTarget: boolean;\n buildWhere?: (where: any) => SQL | undefined;\n}): ConflictPlan => {\n const { table, values, onConflict, pkNames, uniqueSets, excludedRef, withTarget, buildWhere } = params;\n const columns = getColumns(table) as Record<string, Column>;\n\n let target: Column[] | undefined;\n if (withTarget) {\n const targetNames = onConflict?.target?.length ? onConflict.target : [...pkNames];\n if (!targetNames.length) {\n throw drizzleError(\n 'Unable to upsert: no conflict target was given and this table has no primary key. Pass onConflict.target.',\n { code: 'DRIZZLE_INVALID_ON_CONFLICT' },\n );\n }\n // A target that is not itself a unique constraint is a database error, and a confusing\n // one (\"there is no unique or exclusion constraint matching the ON CONFLICT\n // specification\"), so reject it here where we can say which sets are valid.\n const requested = [...targetNames].sort().join(',');\n if (!uniqueSets.some((set) => [...set].sort().join(',') === requested)) {\n throw drizzleError(\n `Unable to upsert: [${targetNames.join(', ')}] is not a unique constraint on this table. Valid conflict targets: ${uniqueSets\n .map((set) => `[${set.join(', ')}]`)\n .join(', ')}.`,\n { code: 'DRIZZLE_INVALID_ON_CONFLICT' },\n );\n }\n target = targetNames.map((name) => columns[name]!);\n }\n\n if ((onConflict?.action ?? 'UPDATE') === 'NOTHING') {\n return { action: 'NOTHING', target, set: {}, setWhere: undefined };\n }\n\n // Only columns the request actually supplied have a value to copy over; anything else\n // would write the column's default (usually null) onto the row that already exists.\n const supplied = new Set(values.flatMap((row) => Object.keys(row)));\n const targetNames = new Set(withTarget ? (onConflict?.target?.length ? onConflict.target : pkNames) : []);\n\n let updateNames: string[];\n if (onConflict?.update?.length) {\n const unsupplied = onConflict.update.filter((name) => !supplied.has(name));\n if (unsupplied.length) {\n throw drizzleError(\n `Unable to upsert: onConflict.update lists ${unsupplied.join(', ')}, which the values do not supply.`,\n { code: 'DRIZZLE_INVALID_ON_CONFLICT' },\n );\n }\n updateNames = onConflict.update;\n } else {\n updateNames = [...supplied].filter((name) => !targetNames.has(name));\n }\n\n if (!updateNames.length) {\n return { action: 'NOTHING', target, set: {}, setWhere: undefined };\n }\n\n const set = Object.fromEntries(updateNames.map((name) => [name, excludedRef(columns[name]!.name)]));\n const setWhere = onConflict?.where && buildWhere ? buildWhere(onConflict.where) : undefined;\n\n return { action: 'UPDATE', target, set, setWhere };\n};\n\n/** `excluded.<column>` — PostgreSQL and SQLite name the rejected row this way. */\nexport const excludedColumnRef = (columnName: string): SQL => sql`excluded.${sql.identifier(columnName)}`;\n\n/** `values(<column>)` — MySQL's equivalent inside ON DUPLICATE KEY UPDATE. */\nexport const mysqlValuesColumnRef = (columnName: string): SQL => sql`values(${sql.identifier(columnName)})`;\n","// Compiling an `orderBy` argument into ORDER BY expressions — including ordering by a to-one\n// relation's columns, which compiles to a correlated scalar subquery.\n\nimport type { Column, Relation, Table } from 'drizzle-orm';\nimport {\n aliasedTable,\n and,\n asc,\n desc,\n getColumns,\n getTableAsAliasSQL,\n is,\n One,\n relationsFilterToSQL,\n type SQL,\n sql,\n} from 'drizzle-orm';\nimport { remapFromGraphQLCore } from '../../data-mappers/index.ts';\nimport type { OrderByArgs, TableNamedRelations } from '../types.ts';\nimport { drizzleError } from './errors.ts';\nimport type { RelationFilterContext } from './relation-filters.ts';\nimport { buildRelationJoinCondition } from './relation-filters.ts';\nimport { isFilterableRelation, isRelationFilterReversed, relationOwnWhere } from './relations.ts';\n\n/** How NULLs are placed relative to non-NULL values in an ordered column. */\nexport type OrderNullsOption = 'first' | 'last';\n\n/**\n * Column name / direction / nulls triples from an `orderBy` argument, highest priority\n * first. Split out of `extractOrderBy` so the same ordering can be rebuilt against a\n * subquery's fields, where there is no `Table` to read columns from. Because there is no\n * table, ordering through a relation cannot be compiled here — a relation-shaped entry\n * (an object without a `direction`) is rejected with a clear error instead of being\n * silently dropped.\n */\nexport const orderByEntries = (\n orderArgs: Record<string, any>,\n): [string, 'asc' | 'desc', OrderNullsOption | undefined][] =>\n Object.entries(orderArgs)\n // Filtered before the sort: an unset key contributes no entry, so sorting it is work\n // thrown away — and `sort` is stable, so dropping first leaves the same relative order\n // among equal priorities.\n .filter(([, config]) => config)\n .sort((a, b) => (b[1]?.priority ?? 0) - (a[1]?.priority ?? 0))\n .map(([column, config]) => {\n if (typeof config === 'object' && config.direction === undefined) {\n throw drizzleError(`ORDER BY ${column}: ordering through a relation is not supported in this query`, {\n code: 'DRIZZLE_INVALID_ORDER_BY',\n });\n }\n // Same reason as above: the sort key is not a value of the row, so it cannot be\n // rebuilt against a subquery's fields or encoded into a cursor.\n if (config.matchFilterOrder) {\n throw drizzleError(`ORDER BY ${column}: 'matchFilterOrder' is not supported in this query`, {\n code: 'DRIZZLE_INVALID_ORDER_BY',\n });\n }\n return [column, config.direction, config.nulls ?? undefined];\n });\n\n/**\n * The ORDER BY expression(s) for one ordered value. Without a `nulls` option this is the\n * plain `asc`/`desc` of the expression. With one:\n * - PostgreSQL and SQLite (3.30+) support `NULLS FIRST` / `NULLS LAST` natively, so the\n * clause is emitted as-is.\n * - MySQL has no such clause, so it is emulated with an extra `<expr> IS NULL` sort key\n * ahead of the expression itself (`IS NULL DESC` puts nulls first, `ASC` puts them\n * last). The same GraphQL surface is kept on all three dialects.\n *\n * `dialectColumn` is the real table column the expression derives from — used only to\n * detect the dialect (its `columnType` is prefixed `Pg` / `MySql` / `SQLite`), so `expr`\n * may be the column itself, a subquery field, or a correlated subquery.\n */\nexport const orderExpressions = (\n expr: Column | SQL | SQL.Aliased | any,\n direction: 'asc' | 'desc',\n nulls: OrderNullsOption | undefined,\n dialectColumn: Column,\n): SQL[] => {\n const directed = direction === 'asc' ? asc(expr) : desc(expr);\n\n if (!nulls) {\n return [directed];\n }\n\n const isMySql = (((dialectColumn as any).columnType as string) ?? '').startsWith('MySql');\n if (isMySql) {\n const nullsKey = nulls === 'first' ? desc(sql`(${expr} is null)`) : asc(sql`(${expr} is null)`);\n return [nullsKey, directed];\n }\n\n return [nulls === 'first' ? sql`${directed} nulls first` : sql`${directed} nulls last`];\n};\n\n/**\n * One ordering term, flattened out of a (possibly relation-nested) `orderBy` argument.\n * `expression` is what the ORDER BY sorts on — the column itself, or a correlated\n * subquery reaching it through one or more to-one relations. `column` is the leaf table\n * column, kept for dialect detection.\n */\ninterface FlatOrderEntry {\n expression: Column | SQL;\n column: Column;\n direction: 'asc' | 'desc';\n nulls: OrderNullsOption | undefined;\n priority: number;\n}\n\n/**\n * The chain of aliased to-one hops a relation-ordered column is reached through. Rendered\n * as a single correlated scalar subquery: every hop's target sits in the FROM list and\n * its join condition (plus the relation's own `where`, when it declares one) in the WHERE.\n */\ninterface RelationOrderChain {\n fromParts: SQL[];\n conditions: SQL[];\n /** The aliased target of the last hop — the table the next hop or leaf column resolves from. */\n table: Table;\n}\n\n/** Extends the chain (or starts one from `parentTable`) with one to-one hop. */\nconst extendRelationOrderChain = (\n parentTable: Table,\n relationName: string,\n relEntry: TableNamedRelations,\n ctx: RelationFilterContext,\n chain: RelationOrderChain | undefined,\n): RelationOrderChain => {\n const targetTable = ctx.tables[relEntry.targetTableName];\n const relation = ((relEntry as any).relation ?? relEntry) as Relation<string>;\n\n if (!targetTable || !is(relation, One) || !isFilterableRelation(relation)) {\n throw drizzleError(`ORDER BY ${relationName}: Relation cannot be used for ordering`, {\n code: 'DRIZZLE_INVALID_ORDER_BY',\n });\n }\n\n ctx.aliases ??= { n: 0 };\n const aliasedTarget = aliasedTable(targetTable, `dgql_ord_${ctx.aliases.n++}`);\n\n const joinCondition = buildRelationJoinCondition(parentTable, relation, aliasedTarget, relationName);\n // A relation declared with its own `where` only ever exposes the rows it selects, so the\n // ordering subquery has to honour it too — mirroring the relation-filter subqueries.\n const ownWhere = relationOwnWhere(relation);\n const relationWhere = ownWhere\n ? relationsFilterToSQL(isRelationFilterReversed(relation) ? parentTable : aliasedTarget, ownWhere as any)\n : undefined;\n\n return {\n fromParts: [...(chain?.fromParts ?? []), getTableAsAliasSQL(aliasedTarget)],\n conditions: [\n ...(chain?.conditions ?? []),\n ...(joinCondition ? [joinCondition] : []),\n ...(relationWhere ? [relationWhere] : []),\n ],\n table: aliasedTarget,\n };\n};\n\n/**\n * The sort key behind `matchFilterOrder`: the column's position in the `inArray` list that\n * the same request's `where` gives it, as a `CASE` ladder over that list.\n *\n * A ladder rather than a dialect array function (`array_position` on Postgres, `FIELD()` on\n * MySQL, neither on SQLite) because it is the one form all three share, and because every\n * list value stays a bound parameter — encoded by the column, as `eq` would, so a value whose\n * driver form differs from its JS one (a SQLite integer timestamp's `Date`) is bound as stored.\n * The branch indices are library-generated integers, so they are written into the SQL text — a\n * bound parameter there would leave Postgres unable to infer the CASE result type. Values\n * outside the list sort after every listed one.\n */\nconst filterOrderExpression = (column: Column, columnName: string, whereArgs: Record<string, any> | undefined): SQL => {\n const values = whereArgs?.[columnName]?.inArray as unknown;\n if (!Array.isArray(values)) {\n throw drizzleError(\n `ORDER BY ${columnName}: 'matchFilterOrder' needs an 'inArray' filter on the same column in this query's 'where'`,\n { code: 'DRIZZLE_INVALID_ORDER_BY' },\n );\n }\n if (!values.length) {\n // An empty `inArray` matches no rows at all, so every row would sort the same anyway;\n // a constant keeps the expression valid without a ladder that has no branches.\n return sql`0`;\n }\n\n const branches = values.map(\n (value, index) =>\n sql`when ${column} = ${sql.param(remapFromGraphQLCore(value, column, columnName), column)} then ${sql.raw(String(index))}`,\n );\n return sql`case ${sql.join(branches, sql` `)} else ${sql.raw(String(values.length))} end`;\n};\n\n/**\n * Flattens one level of an `orderBy` argument into `out`. A column key becomes an entry\n * directly (wrapped in a correlated subquery when reached through a relation chain); a\n * to-one relation key recurses with the chain extended by that hop. Priorities live in one\n * global space, so a relation's column can interleave with the parent's own columns.\n */\nconst collectOrderEntries = (\n table: Table,\n tableKey: string,\n orderArgs: Record<string, any>,\n ctx: RelationFilterContext | undefined,\n chain: RelationOrderChain | undefined,\n out: FlatOrderEntry[],\n whereArgs: Record<string, any> | undefined,\n): void => {\n const columns = getColumns(table);\n const relations = ctx?.relationMap[tableKey];\n\n for (const [key, config] of Object.entries(orderArgs)) {\n if (config === null || config === undefined) {\n continue;\n }\n\n const column = columns[key];\n if (column) {\n if (config.matchFilterOrder && chain) {\n throw drizzleError(`ORDER BY ${key}: 'matchFilterOrder' is not supported through a relation`, {\n code: 'DRIZZLE_INVALID_ORDER_BY',\n });\n }\n out.push({\n expression: config.matchFilterOrder\n ? filterOrderExpression(column, key, whereArgs)\n : chain\n ? sql`(select ${column} from ${sql.join(chain.fromParts, sql`, `)} where ${and(...chain.conditions)})`\n : column,\n column,\n direction: config.direction,\n nulls: config.nulls ?? undefined,\n priority: config.priority ?? 0,\n });\n continue;\n }\n\n const relEntry = relations?.[key];\n if (!relEntry || !ctx) {\n throw drizzleError(`ORDER BY ${key}: Unknown column or relation`, { code: 'DRIZZLE_INVALID_ORDER_BY' });\n }\n\n const nextChain = extendRelationOrderChain(chain?.table ?? table, key, relEntry, ctx, chain);\n collectOrderEntries(nextChain.table, relEntry.targetTableName, config, ctx, nextChain, out, undefined);\n }\n};\n\n/**\n * Compiles an `orderBy` argument into ORDER BY expressions, highest priority first.\n *\n * A key naming one of the table's columns orders by that column. A key naming a to-one\n * relation takes the target table's own OrderBy input and orders by the related row's\n * column(s), compiled as a correlated scalar subquery — reusing the aliased-join machinery\n * the relation filters are built on — so it works identically on all three dialects and\n * inside the relational query builder's aliased CTEs. Priorities share one global space\n * across relation boundaries. Each entry may also carry `nulls: first | last`\n * (see {@link orderExpressions} for how MySQL emulates it).\n *\n * An entry may instead set `matchFilterOrder`, which sorts by the column's position in the\n * `inArray` list the same request's `where` gives it — `whereArgs` is that `where`.\n *\n * `ctx` supplies the tables and relation map that relation ordering needs; callers whose\n * inputs cannot contain relation keys may omit it.\n */\nexport const extractOrderBy = <TTable extends Table, TArgs extends OrderByArgs<any> = OrderByArgs<TTable>>(\n table: TTable,\n orderArgs: TArgs,\n ctx?: RelationFilterContext,\n whereArgs?: Record<string, any>,\n): SQL[] => {\n const entries: FlatOrderEntry[] = [];\n collectOrderEntries(table, ctx?.tableKey ?? '', orderArgs, ctx, undefined, entries, whereArgs);\n\n return entries\n .sort((a, b) => b.priority - a.priority)\n .flatMap((entry) => orderExpressions(entry.expression, entry.direction, entry.nulls, entry.column));\n};\n","// Keyset pagination. The `cursor` field, the ordering entries a cursor encodes, the encode and\n// decode pair, and the predicate that resumes a query from one.\n\nimport type { Table } from 'drizzle-orm';\nimport { and, eq, getColumns, gt, isNotNull, isNull, lt, or, type SQL, sql } from 'drizzle-orm';\nimport type { ResolveTree } from '../../parse-resolve-info.ts';\nimport { drizzleError } from './errors.ts';\nimport type { OrderNullsOption } from './order-by.ts';\nimport { orderByEntries, orderExpressions } from './order-by.ts';\n\n/** Name of the field on generated select types that exposes a row's opaque pagination cursor. */\nexport const CURSOR_FIELD_NAME = 'cursor';\n\n/**\n * Property the list resolvers stash each row's computed cursor under. Namespaced so it can't\n * collide with a real column; the `cursor` field's resolver reads it back off the row.\n */\nconst ROW_CURSOR_PROP = '__drizzle_graphql_cursor';\n\n/**\n * Where a dialect's default sort places NULLs relative to non-NULL values:\n * - `nulls-largest` — PostgreSQL: NULLs sort as the largest values (last in ASC, first in DESC).\n * - `nulls-smallest` — MySQL and SQLite: NULLs sort as the smallest values (first in ASC, last\n * in DESC).\n * The keyset predicate has to agree with the dialect's ORDER BY, so each builder passes its own.\n */\nexport type NullOrdering = 'nulls-largest' | 'nulls-smallest';\n\n/**\n * One key of the total order a cursor is defined over: column property name + direction,\n * plus the request's `nulls: first | last` override when it carries one (absent/null means\n * the dialect's native NULL placement).\n */\nexport type CursorOrderEntry = [string, 'asc' | 'desc', (OrderNullsOption | null)?];\n\n/**\n * Whether an `orderBy` argument orders through a to-one relation (a nested object entry\n * rather than a direction). A cursor encodes the row's own ordering-tuple values, and a\n * related row's value is not part of the row, so cursor pagination refuses these orderings —\n * `after` raises an error and the `cursor` field resolves to null, while the ordering itself\n * still applies.\n */\nexport const orderByHasRelationEntry = (orderBy: Record<string, any> | undefined): boolean =>\n !!orderBy &&\n Object.values(orderBy).some((config) => config && typeof config === 'object' && config.direction === undefined);\n\n/**\n * Why the given `orderBy` cannot back a cursor, as the message to raise — or `undefined`\n * when it can. Both cases sort on something that is not a value of the row: a related row's\n * column, or a position in the request's own `inArray` list. `after` raises the message and\n * the `cursor` field resolves to null, while the ordering itself still applies.\n */\nexport const orderByCursorObstacle = (orderBy: Record<string, any> | undefined): string | undefined => {\n if (orderByHasRelationEntry(orderBy)) {\n return \"'after' cannot be combined with an orderBy that orders through a relation — a related row's value cannot be encoded into a cursor.\";\n }\n if (\n orderBy &&\n Object.values(orderBy).some((config) => config && typeof config === 'object' && config.matchFilterOrder)\n ) {\n return \"'after' cannot be combined with 'matchFilterOrder' — a row's position in the request's own filter list is not a value of the row, so it cannot be encoded into a cursor.\";\n }\n return undefined;\n};\n\n/**\n * The total order a list query's rows follow when cursor pagination is in play: the request's\n * `orderBy` entries (highest priority first), then the primary key ascending as a tiebreak —\n * skipping PK columns the `orderBy` already names, so no key appears twice.\n */\nexport const cursorOrderingEntries = (\n orderBy: Record<string, any> | undefined,\n pkNames: readonly string[],\n): CursorOrderEntry[] => {\n const entries: CursorOrderEntry[] = orderBy ? orderByEntries(orderBy) : [];\n const seen = new Set(entries.map(([column]) => column));\n for (const pk of pkNames) {\n if (!seen.has(pk)) {\n entries.push([pk, 'asc']);\n }\n }\n return entries;\n};\n\n/**\n * ORDER BY expressions realizing a cursor's total order on `table` (which may be the aliased\n * RQB proxy) — each key's direction plus its `nulls` override, exactly the order the keyset\n * predicate in {@link buildCursorCondition} compares against.\n */\nexport const cursorOrderExprs = (table: Table, entries: CursorOrderEntry[]): SQL[] => {\n const cols = getColumns(table);\n return entries.flatMap(([column, direction, nulls]) =>\n orderExpressions(cols[column]!, direction, nulls ?? undefined, cols[column]!),\n );\n};\n\n/**\n * Serializes one ordering-tuple value into a JSON-safe shape. Dates and bigints don't survive\n * JSON.stringify losslessly (bigint throws, Date turns into an untagged string), so they are\n * tagged; decimals already arrive from the driver as strings, which are lossless as-is.\n */\nconst encodeCursorValue = (value: any): any => {\n if (value instanceof Date) {\n return { $type: 'date', value: value.toISOString() };\n }\n if (typeof value === 'bigint') {\n return { $type: 'bigint', value: value.toString() };\n }\n return value;\n};\n\nconst decodeCursorValue = (value: any): any => {\n if (value && typeof value === 'object' && typeof value.$type === 'string') {\n if (value.$type === 'date') {\n return new Date(value.value);\n }\n if (value.$type === 'bigint') {\n return BigInt(value.value);\n }\n }\n return value;\n};\n\n/**\n * Encodes a row's position in the given total order as an opaque cursor: base64url of a JSON\n * payload holding the ordering spec (`o`) and the row's values for it (`v`). The spec rides\n * along so a later request can verify the cursor was issued for the same ordering it is using.\n */\nexport const encodeCursor = (entries: CursorOrderEntry[], row: Record<string, any>): string =>\n cursorEncoder(entries)(row);\n\n/**\n * `encodeCursor` bound to one ordering, for encoding a whole page.\n *\n * The ordering spec is the same for every row of a page, so it is serialized once here and\n * spliced into each row's payload rather than re-serialized per row. The bytes are identical\n * to what building the payload object and stringifying it produces — same keys, same order —\n * so cursors stay interchangeable with ones issued before this was split out.\n */\nconst cursorEncoder = (entries: CursorOrderEntry[]): ((row: Record<string, any>) => string) => {\n const spec = JSON.stringify(entries);\n const columns = entries.map(([column]) => column);\n\n return (row) => {\n const values = JSON.stringify(columns.map((column) => encodeCursorValue(row[column] ?? null)));\n return Buffer.from(`{\"o\":${spec},\"v\":${values}}`, 'utf8').toString('base64url');\n };\n};\n\n/**\n * Decodes an `after` cursor and validates it against the ordering the current request pages\n * over. A cursor issued under a different `orderBy` would combine one ordering's predicate\n * with another's sort — silently wrong pages — so a mismatch is an error, as is anything that\n * doesn't decode to the expected payload shape.\n */\nexport const decodeCursor = (after: string, entries: CursorOrderEntry[]): any[] => {\n let payload: any;\n try {\n payload = JSON.parse(Buffer.from(after, 'base64url').toString('utf8'));\n } catch (_e) {\n throw drizzleError('Invalid cursor: unable to decode it. Pass a cursor returned by a previous page.', {\n code: 'DRIZZLE_INVALID_CURSOR',\n });\n }\n\n if (\n !payload ||\n typeof payload !== 'object' ||\n !Array.isArray(payload.o) ||\n !Array.isArray(payload.v) ||\n payload.o.length !== payload.v.length\n ) {\n throw drizzleError('Invalid cursor: malformed payload. Pass a cursor returned by a previous page.', {\n code: 'DRIZZLE_INVALID_CURSOR',\n });\n }\n\n const matchesOrdering =\n payload.o.length === entries.length &&\n payload.o.every(\n (entry: any, i: number) =>\n Array.isArray(entry) &&\n entry[0] === entries[i]![0] &&\n entry[1] === entries[i]![1] &&\n // The nulls override changes where NULLs sort, so it is part of the ordering identity.\n // JSON round-trips undefined as null — compare the normalized forms.\n (entry[2] ?? null) === (entries[i]![2] ?? null),\n );\n if (!matchesOrdering) {\n throw drizzleError(\n \"Invalid cursor: it was issued for a different ordering. Pass the same orderBy the cursor's page used.\",\n { code: 'DRIZZLE_INVALID_CURSOR' },\n );\n }\n\n return payload.v.map(decodeCursorValue);\n};\n\n/**\n * The keyset predicate selecting rows strictly after the cursor position in the given total\n * order — the expanded lexicographic form\n * `after(k0) OR (k0 = v0 AND after(k1)) OR (k0 = v0 AND k1 = v1 AND after(k2)) …`,\n * built with and/or/gt/lt/eq rather than SQL row-value syntax, which cannot express mixed\n * asc/desc directions and mishandles NULLs.\n *\n * NULL handling follows each key's `nulls: first | last` override when present, and otherwise\n * the dialect's default sort position (see {@link NullOrdering}): where NULLs sort last for a\n * key, \"after a non-NULL value\" includes the NULL rows and nothing sorts after a NULL one;\n * where NULLs sort first, \"after NULL\" is every non-NULL row.\n * `table` may be the aliased RQB proxy.\n */\nexport const buildCursorCondition = (\n table: Table,\n entries: CursorOrderEntry[],\n values: any[],\n nullOrdering: NullOrdering,\n): SQL => {\n const cols = getColumns(table);\n const disjuncts: SQL[] = [];\n const equalities: SQL[] = [];\n\n entries.forEach(([column, direction, nulls], i) => {\n const col = cols[column];\n if (!col) {\n throw drizzleError(`Invalid cursor: unknown column '${column}'.`, { code: 'DRIZZLE_INVALID_CURSOR' });\n }\n\n const value = values[i];\n const nullsSortLast =\n nulls != null ? nulls === 'last' : (direction === 'asc') === (nullOrdering === 'nulls-largest');\n\n let strictlyAfter: SQL | undefined;\n if (value === null || value === undefined) {\n // Nothing sorts after NULL when NULLs are last; every non-NULL row does when first.\n strictlyAfter = nullsSortLast ? undefined : isNotNull(col);\n } else {\n const comparison = direction === 'asc' ? gt(col, value) : lt(col, value);\n strictlyAfter = nullsSortLast ? or(comparison, isNull(col)) : comparison;\n }\n\n if (strictlyAfter) {\n disjuncts.push(equalities.length ? and(...equalities, strictlyAfter)! : strictlyAfter);\n }\n equalities.push(value === null || value === undefined ? isNull(col) : eq(col, value));\n });\n\n if (!disjuncts.length) {\n // Every key's strict term was impossible (e.g. a NULLs-last cursor position of all NULLs) —\n // nothing sorts after this cursor.\n return sql`1 = 0`;\n }\n\n return disjuncts.length > 1 ? or(...disjuncts)! : disjuncts[0]!;\n};\n\n/**\n * Whether the selection asks for the `cursor` meta field. A real column named `cursor` keeps\n * the field for itself, so the meta field only exists (and is only computed) when the table\n * has no such column.\n */\nexport const isCursorFieldSelected = (tree: Record<string, ResolveTree> | undefined, table: Table): boolean => {\n if (!tree) {\n return false;\n }\n if (getColumns(table)[CURSOR_FIELD_NAME]) {\n return false;\n }\n return Object.values(tree).some((field) => field.name === CURSOR_FIELD_NAME);\n};\n\n/**\n * Whether a field's own selection set asks for the `cursor` meta field, read straight off the\n * AST. The relation resolvers need this per parent row on the batch path, where parsing a\n * full resolve tree each time would cost far more than the one-level walk the question needs;\n * fragment spreads are followed, and a real column named `cursor` keeps the field for itself\n * exactly as in {@link isCursorFieldSelected}.\n */\nexport const selectsCursorField = (info: any, table: Table): boolean => {\n if (getColumns(table)[CURSOR_FIELD_NAME]) {\n return false;\n }\n\n const visited = new Set<string>();\n const walk = (selections: any[]): boolean =>\n selections.some((selection) => {\n if (selection.kind === 'Field') {\n return selection.name.value === CURSOR_FIELD_NAME;\n }\n if (selection.kind === 'InlineFragment') {\n return walk(selection.selectionSet.selections);\n }\n const name = selection.name?.value;\n if (!name || visited.has(name)) {\n return false;\n }\n visited.add(name);\n const fragment = info.fragments?.[name];\n return fragment ? walk(fragment.selectionSet.selections) : false;\n });\n\n return (info.fieldNodes ?? []).some((node: any) => !!node.selectionSet && walk(node.selectionSet.selections));\n};\n\n/**\n * Computes and attaches each row's opaque cursor (under a namespaced property the `cursor`\n * field's resolver reads). Must run on the raw driver rows, before output remapping rewrites\n * dates and bigints into their transport forms.\n */\nexport const attachRowCursors = (rows: Record<string, any>[], entries: CursorOrderEntry[]): void => {\n const encode = cursorEncoder(entries);\n for (const row of rows) {\n row[ROW_CURSOR_PROP] = encode(row);\n }\n};\n\n/** Resolver for the `cursor` meta field: reads the value a list resolver attached, if any. */\nexport const rowCursorResolver = (source: any): string | null => source?.[ROW_CURSOR_PROP] ?? null;\n","// Primary keys and unique column sets, read off a table however its dialect stores them.\n\nimport type { Table } from 'drizzle-orm';\nimport { asc, getColumns } from 'drizzle-orm';\nimport { visibleColumns } from './exclusions.ts';\n\n/**\n * Returns the property names of a table's primary key column(s).\n *\n * drizzle-orm marks inline `.primaryKey()` columns with `column.primary === true`,\n * but table-level composite keys (`primaryKey({ columns })`) leave `column.primary`\n * false on each member — those are only visible via the per-dialect `getTableConfig`.\n * Dialect builders pass the composite members' DB column names in via\n * `compositePkColumnNames`; we map them back to property names here.\n *\n * Resolution order: inline PK columns → composite PK columns → empty. We deliberately\n * do NOT guess a column named `id`: if no real primary key is declared, returning empty\n * lets callers fall back to the batch loader rather than re-keying on a possibly\n * non-unique column.\n */\nexport const getPrimaryKeyPropNames = (table: Table, compositePkColumnNames?: readonly string[]): string[] => {\n const cols = getColumns(table);\n const entries = Object.entries(cols);\n\n // Inline single `.primaryKey()` columns.\n const inlinePks = entries.filter(([, c]) => (c as any).primary).map(([k]) => k);\n if (inlinePks.length) {\n return inlinePks;\n }\n\n // Composite primary key (DB column names supplied by the dialect builder).\n if (compositePkColumnNames?.length) {\n const wanted = new Set(compositePkColumnNames);\n const fromComposite = entries.filter(([, c]) => wanted.has((c as any).name)).map(([k]) => k);\n if (fromComposite.length) {\n return fromComposite;\n }\n }\n\n // No declared primary key — let the caller fall back to the batch loader.\n return [];\n};\n\n/**\n * Ensures a selected-columns map (SQL format: prop name → Column) includes the table's\n * primary-key columns. Mutation resolvers pass their RETURNING columns through this so\n * the eager-loader can re-key rows by PK even when the client didn't select it. Mutates\n * and returns the same map.\n */\nexport const withPrimaryKeyColumns = <T extends Record<string, any>>(\n columns: T,\n table: Table,\n pkNames: readonly string[],\n): T => {\n const allCols = getColumns(table);\n for (const pk of pkNames) {\n if (!(pk in columns) && allCols[pk]) {\n (columns as any)[pk] = allCols[pk];\n }\n }\n return columns;\n};\n\n/**\n * Wraps a dialect's `getTableConfig` in a per-table cache.\n *\n * The dialect implementations are not lookups: each call re-runs the table's\n * `extraConfigBuilder` and rebuilds every index, check, unique constraint, primary key and\n * foreign key it declares. Nothing about a table changes after it is defined, so the result\n * is the same every time — but a build asks for it many times per table (primary-key names,\n * unique column sets, conflict targets, one per relation that keys off the target's PK), and\n * an overriding resolver asks again at request time.\n *\n * The cache is a `WeakMap` on the table object, so it costs nothing once the table is gone.\n * Bind it once per dialect module, at module scope, so the cache outlives a single\n * `buildSchema` call.\n */\nexport const memoizeTableConfig = <TTable extends Table, TConfig>(\n getTableConfig: (table: TTable) => TConfig,\n): ((table: TTable) => TConfig) => {\n const cache = new WeakMap<TTable, TConfig>();\n return (table: TTable): TConfig => {\n let config = cache.get(table);\n if (config === undefined) {\n config = getTableConfig(table);\n cache.set(table, config);\n }\n return config;\n };\n};\n\n/**\n * Resolves a table's primary-key property names using a dialect's `getTableConfig` to\n * surface table-level composite keys (whose member columns aren't flagged `.primary`).\n * Each dialect builder binds this with its own getTableConfig and reuses the binding for\n * both relation pagination and mutation re-fetch keying.\n */\nexport const getPrimaryKeyPropNamesFromConfig = <TTable extends Table>(\n table: TTable,\n getTableConfig: (table: TTable) => { primaryKeys: { columns: { name: string }[] }[] },\n): string[] => {\n const compositePkColumnNames = getTableConfig(table).primaryKeys.flatMap((pk) => pk.columns.map((c) => c.name));\n return getPrimaryKeyPropNames(table, compositePkColumnNames);\n};\n\n/**\n * Ascending order expressions for a table's primary key — the deterministic tiebreak for\n * paginated relations. Shared by the window-function batch path and the eager `with:`\n * orderBy default so both order identically. `table` may be the aliased RQB proxy.\n */\nexport const primaryKeyOrderExprs = (table: Table, pkNames: readonly string[]): any[] => {\n const cols = getColumns(table);\n return pkNames\n .map((n) => cols[n])\n .filter(Boolean)\n .map((col) => asc(col!));\n};\n\n// ── cursor (keyset) pagination ───────────────────────────────────────────────\n\n/**\n * Every set of columns that uniquely identifies a row of `table`: the primary key first,\n * then each unique constraint and unique index, then each column declared `.unique()`\n * inline. Sets are property names (what GraphQL inputs use), not database column names.\n *\n * `getTableConfig` is the dialect's own — the three dialects expose the same\n * `{ primaryKeys, uniqueConstraints, indexes }` shape but from different modules, so the\n * caller passes theirs in, as `getPrimaryKeyPropNamesFromConfig` does.\n *\n * Index entries whose columns are SQL expressions rather than plain columns are skipped:\n * an expression index is a valid conflict target in the database but cannot be named by a\n * column enum. Deduplicated, order-insensitive — a column that is both the primary key and\n * a unique constraint yields one set.\n */\nexport const getUniqueColumnSets = <TTable extends Table>(\n table: TTable,\n getTableConfig: (table: TTable) => {\n primaryKeys: { columns: { name: string }[] }[];\n uniqueConstraints?: { columns: { name: string }[] }[];\n indexes?: { config: { unique?: boolean; columns: any[] } }[];\n },\n): string[][] => {\n const cols = visibleColumns(table);\n const propNameByColumnName = new Map(Object.entries(cols).map(([propName, col]) => [(col as any).name, propName]));\n // A set is usable only if every one of its columns maps back to a property on the table.\n const toPropNames = (columnNames: (string | undefined)[]): string[] | undefined => {\n const propNames: string[] = [];\n for (const columnName of columnNames) {\n const propName = columnName === undefined ? undefined : propNameByColumnName.get(columnName);\n if (!propName) {\n return undefined;\n }\n propNames.push(propName);\n }\n return propNames.length ? propNames : undefined;\n };\n\n const config = getTableConfig(table);\n const candidates: (string[] | undefined)[] = [\n // Inline `.primaryKey()` columns, then table-level `primaryKey({ columns })`.\n Object.entries(cols)\n .filter(([, col]) => (col as any).primary)\n .map(([propName]) => propName),\n ...config.primaryKeys.map((pk) => toPropNames(pk.columns.map((c) => c.name))),\n ...(config.uniqueConstraints ?? []).map((uc) => toPropNames(uc.columns.map((c) => c.name))),\n ...(config.indexes ?? [])\n .filter((index) => index.config.unique)\n .map((index) => toPropNames(index.config.columns.map((c) => (c as any)?.name))),\n ...Object.entries(cols)\n .filter(([, col]) => (col as any).isUnique)\n .map(([propName]) => [propName]),\n ];\n\n const seen = new Set<string>();\n const sets: string[][] = [];\n for (const set of candidates) {\n if (!set?.length) {\n continue;\n }\n const key = [...set].sort().join(',');\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n sets.push(set);\n }\n return sets;\n};\n","// `distinctOn` for the dialects with no native support: the window-function key query the\n// resolver runs first, and the primary-key restriction it feeds into the real select.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { and, asc, eq, getColumns, inArray, or, type SQL, sql } from 'drizzle-orm';\nimport { DISTINCT_RN } from './column-enums.ts';\nimport { drizzleError } from './errors.ts';\nimport { primaryKeyOrderExprs } from './keys.ts';\nimport { orderByEntries, orderExpressions } from './order-by.ts';\n\n/**\n * Alias the parent key comes back under when the pass runs through a junction table. See\n * `selectDistinctKeys`' `junction` parameter.\n */\nexport const DISTINCT_PARENT = '__dgql_distinct_parent';\n\n/**\n * Keeps the first row of each distinct combination of the requested columns, following the\n * query's own ordering, then applies `limit`/`offset` to what survives — and returns the\n * surviving rows' primary key values in that order.\n *\n * The relational query builder has no `distinct` support, so this runs as its own\n * `row_number() over (partition by … order by …)` pass and the main query is narrowed to the\n * keys it returns. `orderExprs` is the full ordering (the request's `orderBy` plus the primary\n * key tiebreak); the caller applies the same ordering to the main query, so the two agree.\n *\n * `partitionBy` prepends extra columns to the window's partition. A to-many relation field\n * uses it to pass the foreign key, which makes the pass distinct *within each parent* rather\n * than across the whole batch — the same meaning `distinct` has on a root list.\n *\n * `junction` is for a many-to-many relation: the target is joined to the junction `on` the\n * given condition, and each returned key also carries the parent it was kept for, under\n * {@link DISTINCT_PARENT}. A target row linked to several parents can be kept for one and\n * dropped for another, so a key alone cannot narrow such a batch.\n */\nexport const selectDistinctKeys = async (params: {\n db: any;\n table: Table;\n tableName: string;\n distinct: string[];\n pkNames: readonly string[];\n where: SQL | undefined;\n orderBy: Record<string, any> | undefined;\n limit?: number;\n offset?: number;\n partitionBy?: Column[];\n junction?: { table: Table; on: SQL; parentKey: Column };\n}): Promise<Record<string, any>[]> => {\n const { db, table, tableName, distinct, pkNames, where, orderBy, limit, offset, partitionBy, junction } = params;\n const cols = getColumns(table);\n\n if (!pkNames.length) {\n throw drizzleError(`Table ${tableName} has no primary key, so 'distinct' cannot be applied to it.`, {\n code: 'DRIZZLE_INVALID_DISTINCT',\n });\n }\n\n const requestedCols = distinct.map((name) => cols[name]).filter(Boolean);\n if (!requestedCols.length) {\n throw drizzleError(`No known columns were given to 'distinct' on ${tableName}.`, {\n code: 'DRIZZLE_INVALID_DISTINCT',\n });\n }\n const partitionCols = [...(partitionBy ?? []), ...requestedCols];\n\n const orderEntries = orderBy ? orderByEntries(orderBy) : [];\n // Both orderings must agree, so build each from the same entries — once against the table\n // (inside the window) and once against the subquery's fields (for the outer row order).\n const windowOrder = [\n ...orderEntries.flatMap(([column, direction, nulls]) =>\n orderExpressions(cols[column]!, direction, nulls, cols[column]!),\n ),\n ...primaryKeyOrderExprs(table, pkNames),\n ];\n\n const rowNumber = sql`row_number() over (partition by ${sql.join(partitionCols, sql`, `)} order by ${sql.join(\n windowOrder,\n sql`, `,\n )})`.as(DISTINCT_RN);\n\n const selected = db\n .select({ ...cols, ...(junction ? { [DISTINCT_PARENT]: junction.parentKey } : {}), [DISTINCT_RN]: rowNumber })\n .from(table);\n const sub = (junction ? selected.innerJoin(junction.table, junction.on) : selected)\n .where(where)\n .as('__dgql_distinct');\n\n const outerOrder = [\n ...orderEntries.flatMap(([column, direction, nulls]) =>\n orderExpressions(sub[column], direction, nulls, cols[column]!),\n ),\n ...pkNames.filter((name) => sub[name]).map((name) => asc(sub[name])),\n ];\n\n let query = db\n .select({\n ...Object.fromEntries(pkNames.map((name) => [name, sub[name]])),\n ...(junction ? { [DISTINCT_PARENT]: sub[DISTINCT_PARENT] } : {}),\n })\n .from(sub)\n .where(eq(sub[DISTINCT_RN], 1))\n .orderBy(...outerOrder);\n\n if (offset) {\n query = query.offset(offset);\n }\n if (limit != null) {\n query = query.limit(limit);\n }\n\n return await query;\n};\n\n/**\n * Condition matching exactly the rows identified by `keys` — an `IN (…)` for a single-column\n * primary key, an `OR` of per-row equality for a composite one. `table` may be the aliased\n * RQB proxy.\n */\nexport const primaryKeyRestriction = (table: Table, pkNames: readonly string[], keys: Record<string, any>[]): SQL => {\n const cols = getColumns(table);\n\n if (pkNames.length === 1) {\n const name = pkNames[0]!;\n return inArray(\n cols[name]!,\n keys.map((key) => key[name]),\n );\n }\n\n return or(...keys.map((key) => and(...pkNames.map((name) => eq(cols[name]!, key[name])))))!;\n};\n","// The descriptions generated fields and inputs carry, assembled from the Drizzle schema and\n// whatever the caller passed in `docs`.\n\nimport type { Column } from 'drizzle-orm';\nimport { GraphQLNonNull } from 'graphql';\nimport type { SchemaDocs } from '../../type-converter/types.ts';\n\n/**\n * The `description` / `deprecationReason` a column field should carry, from the build's\n * documentation hooks. Both are omitted rather than set to `undefined` so a field config\n * built by spreading this stays identical to one built without it.\n */\nexport const columnDocs = (\n docs: SchemaDocs,\n column: Column,\n tableName: string,\n columnName: string,\n): { description?: string; deprecationReason?: string } => {\n const description = docs.describeColumn?.(column, { tableName, columnName });\n const deprecationReason = docs.deprecateColumn?.(column, { tableName, columnName });\n return {\n ...(description !== undefined ? { description } : {}),\n ...(deprecationReason !== undefined ? { deprecationReason } : {}),\n };\n};\n\n/**\n * A required input field cannot be deprecated — graphql-js rejects the schema outright, since\n * a client has no way to stop sending it. `deprecateColumn` is written against the column, not\n * against each generated input, so drop the reason where it cannot apply rather than making\n * the caller predict which inputs made the column non-null.\n */\nexport const inputFieldDocs = (\n docs: SchemaDocs,\n column: Column,\n tableName: string,\n columnName: string,\n fieldType: unknown,\n): { description?: string; deprecationReason?: string } => {\n const resolved = columnDocs(docs, column, tableName, columnName);\n if (resolved.deprecationReason !== undefined && fieldType instanceof GraphQLNonNull) {\n const { deprecationReason: _dropped, ...rest } = resolved;\n return rest;\n }\n return resolved;\n};\n","// `drizzleExecutorKey` — the context slot a caller can park a transaction (or any other\n// executor) in — and the lookups every generated resolver does through it.\n\n/**\n * Key on the GraphQL context object under which a caller can place a Drizzle transaction\n * (or any other executor: a pooled connection, a logging proxy). Every generated resolver\n * reads it at resolve time and runs its statements there instead of on the database the\n * schema was built from, which is what lets several mutations in one request share a\n * transaction and lets a query see that transaction's uncommitted rows:\n *\n * ```ts\n * await db.transaction(async (tx) => {\n * await graphql({ schema, source, contextValue: { [drizzleExecutorKey]: tx } });\n * });\n * ```\n *\n * Registered with `Symbol.for` so the ESM and CJS builds of this package agree on it when\n * both end up loaded in one process.\n */\nexport const drizzleExecutorKey: unique symbol = Symbol.for('drizzle-graphql:executor') as any;\n\n/**\n * The executor a resolver should run on: the request's transaction when the context\n * carries one, otherwise the database the schema was built from.\n */\nexport const resolveExecutor = <T>(db: T, context: any): T => {\n if (context && typeof context === 'object') {\n const executor = context[drizzleExecutorKey];\n if (executor) {\n return executor as T;\n }\n }\n return db;\n};\n\n/**\n * This request's executor together with the relational query builder to select through.\n *\n * `buildTimeQueryBase` decides whether the table supports the relational query builder at\n * all — a table with no relations has none, and the caller falls back to a plain select.\n * The executor only decides which connection the query runs on, so a transaction that is\n * missing `query` (or a table absent from its schema) keeps the build-time builder.\n */\nexport const resolveQueryExecutor = (\n db: any,\n context: any,\n tableName: string,\n buildTimeQueryBase: any,\n): { executor: any; queryBase: any } => {\n const executor = resolveExecutor(db, context);\n return {\n executor,\n queryBase: buildTimeQueryBase ? (executor?.query?.[tableName] ?? buildTimeQueryBase) : buildTimeQueryBase,\n };\n};\n","// The two shared input types every generated OrderBy is assembled from: `orderNulls` and\n// `innerOrder`. Both are built once per name they resolve to, so a build that renames its\n// types gets its own pair and every other build keeps sharing one.\n\nimport { GraphQLBoolean, GraphQLEnumType, GraphQLInputObjectType, GraphQLInt, GraphQLNonNull } from 'graphql';\nimport { sharedType, type TypeNameResolver } from './type-names.ts';\n\n/**\n * Where NULL values sort relative to non-NULL values. Compiled to native\n * `NULLS FIRST` / `NULLS LAST` on PostgreSQL and SQLite (3.30+); MySQL has no such\n * clause, so there it is emulated with an extra `<expr> IS NULL` sort key ahead of\n * the column itself.\n */\nexport const orderNullsType = (typeName: TypeNameResolver): GraphQLEnumType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'OrderNulls' },\n (name) =>\n new GraphQLEnumType({\n name,\n description: 'Where NULL values sort relative to non-NULL values',\n values: {\n first: {\n value: 'first',\n description: 'NULL values sort before all non-NULL values',\n },\n last: {\n value: 'last',\n description: 'NULL values sort after all non-NULL values',\n },\n },\n }),\n );\n\nconst orderDirectionType = (typeName: TypeNameResolver): GraphQLEnumType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'OrderDirection' },\n (name) =>\n new GraphQLEnumType({\n name,\n description: 'Order by direction',\n values: {\n asc: {\n value: 'asc',\n description: 'Ascending order',\n },\n desc: {\n value: 'desc',\n description: 'Descending order',\n },\n },\n }),\n );\n\nexport const innerOrderType = (typeName: TypeNameResolver): GraphQLInputObjectType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'InnerOrder' },\n (name) =>\n new GraphQLInputObjectType({\n name,\n fields: {\n direction: {\n type: new GraphQLNonNull(orderDirectionType(typeName)),\n },\n priority: {\n type: new GraphQLNonNull(GraphQLInt),\n description: 'Priority of current field',\n },\n nulls: {\n type: orderNullsType(typeName),\n description:\n \"Where NULL values sort. Defaults to the database's own rule (PostgreSQL: last on asc, first on desc; MySQL/SQLite: first on asc, last on desc)\",\n },\n matchFilterOrder: {\n type: GraphQLBoolean,\n description:\n \"Sort by this column's position in the `inArray` list the same request's `where` gives it, rather than by the column's own value — `direction: asc` keeps the list's order, `desc` reverses it. Requires an `inArray` filter on the same column at the top level of `where`, and cannot be combined with `after` or `distinct`.\",\n },\n },\n }),\n );\n","// The `limits`, `defaults` and `complexity` configs resolved per table, plus the estimator\n// functions the generated fields publish on `extensions.complexity`.\n\nimport { type DrizzleErrorContext, drizzleError } from './errors.ts';\n\n/** The shape `graphql-query-complexity`'s `fieldExtensionsEstimator` hands to a field's hint. */\ntype ComplexityEstimatorArgs = { args: Record<string, any>; childComplexity: number };\n\n/** A field's cost hint, published as `extensions.complexity` on the generated field config. */\nexport type ComplexityEstimator = (options: ComplexityEstimatorArgs) => number;\n\n/** {@link BuildSchemaConfig.complexity} with its defaults filled in. */\nexport type ResolvedComplexityOptions = {\n /** Rows a list field is assumed to return when the query passes no `limit`. */\n defaultListSize: number;\n /** Flat cost charged for an aggregate field, on top of the fields selected inside it. */\n aggregateCost: number;\n};\n\n/** {@link BuildSchemaConfig.limits} resolved for one table. `undefined` means no policy. */\nexport type ResolvedLimitPolicy = {\n defaultLimit: number | undefined;\n maxLimit: number | undefined;\n clampToMax: boolean;\n};\n\n/**\n * Looks up the limit policy for a table by its Drizzle schema key. Built once per schema by\n * `buildSchema`; `undefined` for a table the caller left unbounded.\n */\nexport type LimitPolicyFor = (tableName: string) => ResolvedLimitPolicy | undefined;\n\n/**\n * {@link BuildSchemaConfig.defaults} resolved for one table: the `orderBy` a read falls back\n * to when the request passes none, already in the shape the generated argument has.\n * `undefined` means the table declares no default and keeps whatever order the database\n * returns.\n */\nexport type DefaultOrderByFor = (tableName: string) => Record<string, any> | undefined;\n\n/**\n * Substitutes a table's default ordering for an absent `orderBy`.\n *\n * Applied where the arguments are first read, so everything downstream — the cursor tuple, a\n * `distinct` pass, the plain-select fallback — sees one effective ordering and cannot\n * disagree about it. Only a missing argument is replaced: `orderBy: {}` is a request for no\n * ordering, and stays one.\n */\nexport const withDefaultOrderBy = <T extends { orderBy?: any }>(\n args: T,\n tableName: string,\n defaults: DefaultOrderByFor | undefined,\n): T => {\n if (!defaults || args?.orderBy != null) {\n return args;\n }\n const fallback = defaults(tableName);\n return fallback ? { ...args, orderBy: fallback } : args;\n};\n\n/**\n * The `limit` a query actually runs with, given the policy for the table it reads.\n *\n * A request that passes no `limit` falls back to `defaultLimit`, or to `maxLimit` when only\n * that is configured — an absent limit means every row, which is above any maximum. A limit\n * the client did ask for is rejected when it exceeds `maxLimit`, since silently truncating a\n * page tells a paginating client it has reached the end when it has not; `clampToMax` opts\n * into the truncation instead. A limit the *policy* supplied is capped rather than rejected —\n * a misconfigured `defaultLimit` above `maxLimit` is the operator's problem, not something to\n * fail a client's query over.\n */\nexport const applyLimitPolicy = (\n limit: number | null | undefined,\n policy: ResolvedLimitPolicy | undefined,\n /**\n * Only a relation field passes this: its limit is applied while the *parent's* resolver is\n * building the eager query, so there is no relation-shaped catch to attach the context at.\n */\n errorCtx?: DrizzleErrorContext,\n): number | undefined => {\n if (!policy) {\n return limit ?? undefined;\n }\n const { defaultLimit, maxLimit, clampToMax } = policy;\n\n if (limit == null) {\n const fallback = defaultLimit ?? maxLimit;\n if (fallback === undefined) {\n return undefined;\n }\n return maxLimit === undefined ? fallback : Math.min(fallback, maxLimit);\n }\n\n if (maxLimit !== undefined && limit > maxLimit) {\n if (clampToMax) {\n return maxLimit;\n }\n throw drizzleError(`'limit' of ${limit} exceeds the maximum of ${maxLimit}.`, {\n code: 'DRIZZLE_LIMIT_EXCEEDED',\n ...errorCtx,\n });\n }\n return limit;\n};\n\n/** Merges a per-table override over the global policy, or `undefined` when neither bounds anything. */\nexport const resolveLimitPolicy = (\n global: { defaultLimit?: number; maxLimit?: number; clampToMax?: boolean } | undefined,\n table: { defaultLimit?: number; maxLimit?: number; clampToMax?: boolean } | undefined,\n): ResolvedLimitPolicy | undefined => {\n const defaultLimit = table?.defaultLimit ?? global?.defaultLimit;\n const maxLimit = table?.maxLimit ?? global?.maxLimit;\n if (defaultLimit === undefined && maxLimit === undefined) {\n return undefined;\n }\n return { defaultLimit, maxLimit, clampToMax: table?.clampToMax ?? global?.clampToMax ?? false };\n};\n\n/**\n * A paginated field costs its page size times whatever one row of it costs, so `users(limit: 100)\n * { posts(limit: 10) { id } }` is charged for the thousand rows it can return rather than the two\n * fields it mentions. `childComplexity` floors at 1 so a row is never free.\n *\n * The page size is the *effective* one: a request without `limit` is priced at the policy's\n * `defaultLimit` rather than the estimator's guess, and no request is priced above `maxLimit`,\n * so the cost a query is charged matches the rows it can actually pull.\n */\nexport const listFieldComplexity =\n (options: ResolvedComplexityOptions, policy?: ResolvedLimitPolicy): ComplexityEstimator =>\n ({ args, childComplexity }) => {\n const limit = args['limit'];\n const requested = typeof limit === 'number' && limit > 0 ? limit : undefined;\n let rows = requested ?? policy?.defaultLimit ?? options.defaultListSize;\n if (policy?.maxLimit !== undefined) {\n rows = Math.min(rows, policy.maxLimit);\n }\n return rows * Math.max(childComplexity, 1);\n };\n\n/**\n * An aggregate returns a single row but reads however many match, so its cost tracks the scan\n * rather than the response.\n */\nexport const aggregateFieldComplexity =\n (options: ResolvedComplexityOptions): ComplexityEstimator =>\n ({ childComplexity }) =>\n options.aggregateCost + childComplexity;\n","// A resolver's `info` carries the query AST, not the selection: reading which fields were\n// actually asked for means walking `fieldNodes`, resolving fragments against `info.fragments`,\n// honouring `@include` / `@skip`, and coercing each field's arguments. Every generated\n// resolver in this library needs that walk before it can decide which columns to SELECT and\n// which relations to join, so it happens on every request.\n//\n// This is an in-repo replacement for `graphql-parse-resolve-info`, which used to be a required\n// peer dependency. That package is CommonJS, so it reaches graphql through `require`, and it\n// decides whether a field has sub-selections with `instanceof` against whatever that `require`\n// returned. graphql 17 ships several builds of itself out of one package — a `development`\n// export condition routes to a whole second copy under `__dev__/`, with `.js`/`.mjs` behind the\n// format conditions — so any loader that resolves the CommonJS graph differently from the ESM\n// one hands it a different instance than the one that built the schema. The `instanceof` then\n// answers \"not composite\", the walk returns `fieldsByTypeName: {}` instead of throwing, and\n// every resolver downstream reads a selection of nothing. Upstream is dead (4.14.1, unchanged\n// since 2025-04-27) and its own peer range stops at 16, so npm refuses the install as well.\n//\n// The replacement keeps the `ResolveTree` shape byte-for-byte so nothing downstream moves, and\n// answers the \"is this composite / what are its fields\" questions structurally instead of by\n// `instanceof`, so it cannot silently disagree with the graphql copy that is executing the\n// query. Argument coercion is still graphql's own `getArgumentValues` — spec-correct handling\n// of variables, defaults, enums, input objects and list/non-null wrapping is not worth\n// re-deriving, and passing `info.variableValues` straight through works under both majors\n// (graphql 16 hands resolvers a plain map, graphql 17 a `{ sources, coerced }` record, and each\n// major's `getArgumentValues` expects its own).\n\nimport type { DirectiveNode, GraphQLResolveInfo, NamedTypeNode, SelectionNode, ValueNode } from 'graphql';\nimport { getArgumentValues, Kind } from 'graphql';\n\n/**\n * The selections made against one concrete type, keyed by the *response key* — the field's\n * alias when it has one, otherwise its name. A selection spanning an abstract type has one\n * entry per type condition it was written against (the interface or union itself included,\n * when fields were selected directly on it).\n */\nexport interface FieldsByTypeName {\n [typeName: string]: {\n [responseKey: string]: ResolveTree;\n };\n}\n\n/** One selected field: what was asked for, under what alias, with which arguments. */\nexport interface ResolveTree {\n /** The field name as declared in the schema. */\n name: string;\n /** The response key — the alias when the selection carried one, otherwise `name`. */\n alias: string;\n /** The field's arguments, coerced by graphql's own `getArgumentValues`. */\n args: {\n [argName: string]: unknown;\n };\n /** The field's own sub-selections, keyed by the type they were written against. */\n fieldsByTypeName: FieldsByTypeName;\n}\n\n/** Options accepted by {@link parseResolveInfo}. */\nexport interface ParseResolveInfoOptions {\n /**\n * Whether to descend into sub-selections and fragments. Defaults to `true`; `false` reads\n * only the root field's own name, alias and arguments.\n */\n deep?: boolean;\n}\n\n/**\n * A GraphQL type as this module needs to see it. Deliberately structural: the type objects on\n * `info` come from whichever copy of graphql is executing the query, which is not necessarily\n * the copy this module imported, so `instanceof` is not a question that can be asked here.\n */\ntype TypeLike = {\n name?: string;\n ofType?: TypeLike;\n getFields?: () => Record<string, { type?: TypeLike }>;\n getTypes?: () => unknown[];\n};\n\n/** Unwraps `[T]!`-style wrappers down to the named type. `getNamedType` without the realm tie. */\nconst namedTypeOf = (type: TypeLike | undefined): TypeLike | undefined => {\n let current = type;\n while (current?.ofType) {\n current = current.ofType;\n }\n return current;\n};\n\n/**\n * Whether a field's named output type has sub-selections. Object types and interfaces expose\n * `getFields`, unions expose `getTypes`; scalars and enums expose neither. Input object types\n * also expose `getFields`, but an input type can never be a field's output type, so there is\n * nothing here for that to collide with.\n */\nconst isCompositeLike = (type: TypeLike | undefined): boolean =>\n !!type && (typeof type.getFields === 'function' || typeof type.getTypes === 'function');\n\n/**\n * The fields declared on a type, or `undefined` when it has none to declare. A union is the\n * case that matters: it has no fields of its own, so a selection directly against one resolves\n * to nothing and is dropped — only the inline fragments underneath contribute.\n */\nconst fieldsOf = (type: TypeLike | undefined): Record<string, { type?: TypeLike }> | undefined =>\n typeof type?.getFields === 'function' ? type.getFields() : undefined;\n\n/**\n * The runtime variable values, in the plain-map form the directive check wants. graphql 17\n * wraps them in `{ sources, coerced }`; graphql 16 hands over the map itself.\n */\nconst coercedVariables = (info: GraphQLResolveInfo): Record<string, unknown> => {\n const values = info.variableValues as unknown;\n if (values && typeof values === 'object' && 'coerced' in (values as Record<string, unknown>)) {\n return ((values as { coerced?: Record<string, unknown> }).coerced ?? {}) as Record<string, unknown>;\n }\n return (values ?? {}) as Record<string, unknown>;\n};\n\n/** The value of a `@skip` / `@include` `if:` argument — a literal or a variable reference. */\nconst directiveIfValue = (info: GraphQLResolveInfo, value: ValueNode): unknown => {\n if (value.kind === Kind.VARIABLE) {\n return coercedVariables(info)[value.name.value];\n }\n if (value.kind === Kind.BOOLEAN) {\n return value.value;\n }\n return undefined;\n};\n\n/**\n * Whether `@skip` / `@include` on this selection exclude it. Applies to fields, fragment\n * spreads and inline fragments alike, which is where graphql puts them.\n */\nconst isExcluded = (\n info: GraphQLResolveInfo,\n node: { readonly directives?: ReadonlyArray<DirectiveNode> },\n): boolean => {\n for (const directive of node.directives ?? []) {\n const directiveName = directive.name.value;\n if (directiveName !== 'skip' && directiveName !== 'include') {\n continue;\n }\n const ifArgument = directive.arguments?.find((argument) => argument.name.value === 'if');\n if (!ifArgument) {\n continue;\n }\n const value = directiveIfValue(info, ifArgument.value);\n if (directiveName === 'skip' ? !!value : !value) {\n return true;\n }\n }\n return false;\n};\n\n/** The type a fragment's `on Type` condition names, looked up in the executing schema. */\nconst typeFromCondition = (info: GraphQLResolveInfo, condition: NamedTypeNode): TypeLike | undefined =>\n info.schema.getType(condition.name.value) as TypeLike | undefined;\n\n/**\n * Introspection meta-fields are not schema fields and never reach the database. `__typename` is\n * the one that turns up in practice; `__id` is excluded from the rule because a schema is free\n * to declare a field by that name.\n */\nconst isMetaField = (name: string): boolean => name.startsWith('__') && name !== '__id';\n\n/**\n * Merges one selection set into `tree`, which is a `fieldsByTypeName` map — the caller owns the\n * level, this owns the entries under `parentType`'s name.\n *\n * `activeFragments` is the set of fragment names on the current spread path. A document that\n * passed validation cannot contain a fragment cycle, but this parser also runs on trees a\n * caller assembled by hand, and an unbounded walk would hang rather than fail.\n */\nconst collectSelections = (\n selections: ReadonlyArray<SelectionNode>,\n info: GraphQLResolveInfo,\n tree: FieldsByTypeName,\n parentType: TypeLike | undefined,\n deep: boolean,\n activeFragments: Set<string>,\n): FieldsByTypeName => {\n const parentTypeName = parentType?.name;\n if (!parentTypeName) {\n return tree;\n }\n // Seeded even when nothing under it survives, so a consumer can tell \"selected nothing on\n // this type\" from \"never reached this type\" — the shape `graphql-parse-resolve-info` produced.\n let fields = tree[parentTypeName];\n if (!fields) {\n fields = {};\n tree[parentTypeName] = fields;\n }\n // Loop-invariant: the parent type is the same for every selection in this set, and this\n // walk runs on every resolve of every request.\n const parentFields = fieldsOf(parentType);\n\n for (const selection of selections) {\n if (isExcluded(info, selection)) {\n continue;\n }\n\n if (selection.kind === Kind.FIELD) {\n const name = selection.name.value;\n if (isMetaField(name)) {\n continue;\n }\n\n const fieldDef = parentFields?.[name];\n // A field the parent type does not declare: either a union's own selection set, which\n // carries nothing but meta-fields, or a document that never passed validation.\n if (!fieldDef) {\n continue;\n }\n\n const fieldType = namedTypeOf(fieldDef.type);\n if (!fieldType) {\n continue;\n }\n const composite = isCompositeLike(fieldType);\n\n const alias = selection.alias?.value || name;\n let node = fields[alias];\n if (!node) {\n node = {\n name,\n alias,\n // Spread out of the null-prototype object graphql returns, so downstream code can\n // treat it as an ordinary record. The casts are on the installed major's own\n // signature: graphql 17 brands its field type and takes a `{ sources, coerced }`\n // variables record where 16 takes a plain map, and `info` carries whichever shape\n // that major's executor produced.\n args: {\n ...getArgumentValues(\n fieldDef as unknown as Parameters<typeof getArgumentValues>[0],\n selection,\n info.variableValues as unknown as Parameters<typeof getArgumentValues>[2],\n ),\n },\n fieldsByTypeName: composite && fieldType.name ? { [fieldType.name]: {} } : {},\n };\n fields[alias] = node;\n }\n\n // Two selections of the same response key merge, exactly as execution merges them: the\n // first one's arguments stand (validation requires them to be identical) and both\n // sub-selections are collected into the one node.\n if (selection.selectionSet && deep && composite) {\n collectSelections(\n selection.selectionSet.selections,\n info,\n node.fieldsByTypeName,\n fieldType,\n deep,\n activeFragments,\n );\n }\n continue;\n }\n\n if (!deep) {\n continue;\n }\n\n if (selection.kind === Kind.FRAGMENT_SPREAD) {\n const fragmentName = selection.name.value;\n const fragment = info.fragments?.[fragmentName];\n if (!fragment) {\n throw new Error(\n `Drizzle-GraphQL Error: unknown fragment '${fragmentName}' — it is spread in the query but not defined in the document.`,\n );\n }\n if (activeFragments.has(fragmentName)) {\n continue;\n }\n\n const fragmentType = fragment.typeCondition ? typeFromCondition(info, fragment.typeCondition) : parentType;\n if (!isCompositeLike(fragmentType)) {\n continue;\n }\n\n activeFragments.add(fragmentName);\n try {\n // Spread into the *caller's* level, not a nested one: a fragment contributes its fields\n // to the selection it was spread into, keyed by its own type condition.\n collectSelections(fragment.selectionSet.selections, info, tree, fragmentType, deep, activeFragments);\n } finally {\n activeFragments.delete(fragmentName);\n }\n continue;\n }\n\n if (selection.kind === Kind.INLINE_FRAGMENT) {\n const fragmentType = selection.typeCondition ? typeFromCondition(info, selection.typeCondition) : parentType;\n if (!isCompositeLike(fragmentType)) {\n continue;\n }\n collectSelections(selection.selectionSet.selections, info, tree, fragmentType, deep, activeFragments);\n }\n }\n\n return tree;\n};\n\n/** The first key of an object, without materializing the whole key array to discard it. */\nconst firstKey = (object: Record<string, unknown>): string | undefined => {\n for (const key in object) {\n return key;\n }\n return undefined;\n};\n\n/**\n * Reads the selection under a resolver's own field out of its `info`, as a tree of\n * {@link ResolveTree} nodes.\n *\n * ```ts\n * const parsed = parseResolveInfo(info, { deep: true })!;\n * const selected = parsed.fieldsByTypeName['Users']; // keyed by response key\n * ```\n *\n * Returns `undefined` when the resolver's field produced no node at all, which in practice\n * means `info` carried no field nodes.\n */\nexport const parseResolveInfo = (\n info: GraphQLResolveInfo,\n options: ParseResolveInfoOptions = {},\n): ResolveTree | undefined => {\n const fieldNodes = info.fieldNodes;\n if (!fieldNodes) {\n throw new Error(\n 'Drizzle-GraphQL Error: resolve info carries no fieldNodes, so no selection could be read from it.',\n );\n }\n\n const tree = collectSelections(\n fieldNodes,\n info,\n {},\n info.parentType as unknown as TypeLike,\n options.deep ?? true,\n new Set(),\n );\n\n // Every field node handed to one resolver shares one response key under one parent type, so\n // the tree has exactly one entry at each of its two top levels — which is the node wanted.\n const typeKey = firstKey(tree);\n const fields = typeKey === undefined ? undefined : tree[typeKey];\n const fieldKey = fields && firstKey(fields);\n return fieldKey === undefined ? undefined : fields?.[fieldKey];\n};\n","/**\n * Atomic column operations on the update `set` (`features.fieldUpdateOperations`).\n *\n * Without them `Update<Table>Input` is set-only, so \"increment the view count\" is a read\n * followed by a write of the value the read returned — two round trips, and a lost update\n * whenever two clients read the same number. The operation happens in the database instead:\n * `set: { views: { increment: 1 } }` compiles to `SET views = views + 1`.\n *\n * The build side turns a qualifying column's update-input field into an operations input;\n * the runtime side splits a `set` back into plain column values and SQL expressions, which\n * drizzle's `.set()` accepts side by side.\n */\nimport type { Column, SQL, Table } from 'drizzle-orm';\nimport { getColumns, sql } from 'drizzle-orm';\nimport {\n GraphQLFloat,\n GraphQLInputObjectType,\n type GraphQLInputType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n type GraphQLScalarType,\n} from 'graphql';\nimport { remapFromGraphQLCore, remapFromGraphQLSingleInput } from '../data-mappers/index.ts';\nimport { GraphQLBigIntString, GraphQLDecimalString } from '../scalars/index.ts';\nimport { drizzleColumnToGraphQLType, getColumnScalarOverride } from '../type-converter/index.ts';\nimport { drizzleError } from './common/errors.ts';\nimport type { TypeNameResolver } from './common/type-names.ts';\n\n/** What a column's update-input field offers: arithmetic, list append, or nothing. */\nexport type FieldUpdateKind = 'numeric' | 'list' | 'none';\n\n/**\n * The scalars arithmetic is offered on. Decimal and BigInt transport as strings but are\n * numbers in the database, so `views: { increment: \"1\" }` is as meaningful there as on an\n * `Int`. Identity rather than name: a column an override owns is excluded before this is\n * consulted, so these are always the built-ins.\n */\nconst NUMERIC_SCALARS = new Set<GraphQLInputType>([\n GraphQLInt,\n GraphQLFloat,\n GraphQLBigIntString,\n GraphQLDecimalString,\n]);\n\n/**\n * Column types that convert to a GraphQL list without being a list *in the database* —\n * a bytea reads as `[Int]`, a vector and a geometry point as `[Float]` — so appending to\n * them is not the operation `push` means.\n */\nconst NON_LIST_ARRAY_COLUMNS = new Set(['PgVector', 'PgGeometry', 'PgBytea']);\n\nconst kindCache = new WeakMap<Column, FieldUpdateKind>();\n\n/**\n * Whether a column takes an operations input, and which one.\n *\n * A column owned by a scalar override is always `'none'`: the override decides what the\n * column accepts, and wrapping it would overrule that. Everything else is decided by the\n * GraphQL type the column already converts to, so the operations follow the same\n * scalar-mapping rules as the rest of the schema.\n */\nexport const fieldUpdateKind = (column: Column, columnName: string, tableName: string): FieldUpdateKind => {\n const cached = kindCache.get(column);\n if (cached) {\n return cached;\n }\n\n let kind: FieldUpdateKind = 'none';\n if (!getColumnScalarOverride(column, true)) {\n const { type } = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, true);\n if (NUMERIC_SCALARS.has(type)) {\n kind = 'numeric';\n } else if (type instanceof GraphQLList && !NON_LIST_ARRAY_COLUMNS.has((column as any).columnType)) {\n kind = 'list';\n }\n }\n\n kindCache.set(column, kind);\n return kind;\n};\n\n/** `${Scalar}FieldUpdate` / `${Scalar}ListFieldUpdate`, shared by every column of that type. */\nconst inputCache = new Map<string, GraphQLInputObjectType>();\n\nconst namedFieldUpdateInput = (\n name: string,\n fields: () => Record<string, { type: GraphQLInputType; description: string }>,\n description: string,\n): GraphQLInputObjectType => {\n const cached = inputCache.get(name);\n if (cached) {\n return cached;\n }\n const input = new GraphQLInputObjectType({ name, description, fields: fields() });\n inputCache.set(name, input);\n return input;\n};\n\n/**\n * The operations input replacing a column's plain field on the update input, or `undefined`\n * when the column keeps its plain type.\n *\n * The type is named for the scalar, not the column, so every `Int` column in the schema\n * shares one `IntFieldUpdate` — the operations are the same wherever they appear.\n */\nexport const fieldUpdateInputType = (\n column: Column,\n columnName: string,\n tableName: string,\n resolveName?: TypeNameResolver,\n): GraphQLInputObjectType | undefined => {\n const kind = fieldUpdateKind(column, columnName, tableName);\n if (kind === 'none') {\n return undefined;\n }\n // Named for the scalar rather than the column, so the naming rule is asked without a table:\n // one instance covers every column of that type across the schema.\n const nameOf = (defaultName: string) =>\n resolveName?.({ kind: 'fieldUpdateInput', defaultName, operation: kind }) ?? defaultName;\n\n const { type } = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, true);\n\n if (kind === 'numeric') {\n const scalar = type as GraphQLScalarType;\n return namedFieldUpdateInput(\n nameOf(`${scalar.name}FieldUpdate`),\n () => ({\n set: { type: scalar, description: 'Replace the current value with this one' },\n increment: { type: scalar, description: 'Add this to the current value (SQL `column + value`)' },\n decrement: { type: scalar, description: 'Subtract this from the current value (SQL `column - value`)' },\n multiply: { type: scalar, description: 'Multiply the current value by this (SQL `column * value`)' },\n divide: {\n type: scalar,\n description: 'Divide the current value by this (SQL `column / value`), rounding as the database does',\n },\n }),\n `An update to a ${scalar.name} column: exactly one of these operations`,\n );\n }\n\n // The element type carries the list's own non-null wrapper, so `push` and `set` accept\n // exactly what the plain field accepted.\n const list = type as GraphQLList<GraphQLInputType>;\n const element = list.ofType;\n const elementName = element instanceof GraphQLNonNull ? String(element.ofType) : String(element);\n return namedFieldUpdateInput(\n nameOf(`${elementName}ListFieldUpdate`),\n () => ({\n set: { type: list, description: 'Replace the current array with this one' },\n push: { type: list, description: 'Append these elements to the current array' },\n }),\n `An update to a ${elementName} array column: exactly one of these operations`,\n );\n};\n\n/** The operation keys, in the order they are reported when a caller passes several. */\nconst OPERATIONS = ['set', 'increment', 'decrement', 'multiply', 'divide', 'push'] as const;\n\n/**\n * The single operation an operations input carries. graphql-js has no `@oneOf` on the\n * version range this library supports, so \"exactly one\" is enforced here rather than by the\n * type — and a caller who passes none has written `{}`, which would otherwise update\n * nothing while looking like it updated something.\n */\nconst singleOperation = (value: Record<string, any>, columnName: string): [string, any] => {\n const given = OPERATIONS.filter((operation) => value[operation] !== undefined);\n if (given.length === 1) {\n return [given[0]!, value[given[0]!]];\n }\n throw drizzleError(\n given.length\n ? `Field '${columnName}' takes exactly one update operation, but ${given.length} were given (${given.join(', ')}).`\n : `Field '${columnName}' was given no update operation. Pass exactly one of ${OPERATIONS.join(', ')}.`,\n { code: 'DRIZZLE_INVALID_UPDATE_OPERATION' },\n );\n};\n\n/** An update `set` split into values drizzle assigns directly and ones it assigns from SQL. */\nexport type SplitUpdateValues = {\n /** Column values still to go through `remapFromGraphQLSingleInput`. */\n columns: Record<string, any>;\n /** Column-relative expressions, already driver-ready, to merge into the same `.set()`. */\n expressions: Record<string, SQL>;\n};\n\n/**\n * Splits an update `set` into plain values and column-relative SQL expressions.\n *\n * Only columns the build side gave an operations input to are read as operations, so a JSON\n * column that happens to hold `{ increment: 1 }` is still just a value. `set` is the\n * explicit spelling of a plain assignment and stays on the plain side, where the usual\n * input remapping applies to it.\n */\nexport const splitFieldUpdateOperations = (\n values: Record<string, any>,\n table: Table,\n tableName: string,\n): SplitUpdateValues => {\n const cols = getColumns(table);\n const columns: Record<string, any> = {};\n const expressions: Record<string, SQL> = {};\n\n for (const [columnName, value] of Object.entries(values)) {\n const column = cols[columnName];\n // An unknown key is left for the remapper, whose error names it.\n if (!column || value === null || value === undefined) {\n columns[columnName] = value;\n continue;\n }\n\n // The operations arrive as an input object; a plain value is a plain assignment. That\n // is what makes this safe to run whether or not `features.fieldUpdateOperations` is on —\n // with it off, a numeric or list column's field is typed as the scalar or the list, so\n // graphql-js has already ruled out the object shape by the time the value gets here.\n const isOperations = typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date);\n if (!isOperations || fieldUpdateKind(column as Column, columnName, tableName) === 'none') {\n columns[columnName] = value;\n continue;\n }\n\n const [operation, operand] = singleOperation(value, columnName);\n if (operation === 'set') {\n columns[columnName] = operand;\n continue;\n }\n\n const param = sql.param(remapFromGraphQLCore(operand, column as Column, columnName), column);\n expressions[columnName] =\n operation === 'increment'\n ? sql`${column} + ${param}`\n : operation === 'decrement'\n ? sql`${column} - ${param}`\n : operation === 'multiply'\n ? sql`${column} * ${param}`\n : operation === 'divide'\n ? sql`${column} / ${param}`\n : // `push`: array concatenation, which is the only dialect-specific operation\n // here — and arrays are a PostgreSQL column type to begin with.\n sql`${column} || ${param}`;\n }\n\n return { columns, expressions };\n};\n\n/**\n * Remaps an update `set` into the values drizzle's `.set()` takes: plain columns through the\n * usual input remapping, column-relative operations as SQL expressions alongside them.\n *\n * Safe to call on every update path regardless of `features.fieldUpdateOperations` — see the\n * shape check in {@link splitFieldUpdateOperations}.\n *\n * This is the single funnel every update goes through — the plural and `Single` mutations,\n * `updateMany`, the `Count` mutations and the MySQL builder's own — which is why it is the\n * one place that has to tell the remapper it is serving an update rather than an insert.\n */\nexport const remapUpdateInput = (values: Record<string, any>, table: Table, tableName: string): Record<string, any> => {\n const { columns, expressions } = splitFieldUpdateOperations(values, table, tableName);\n const remapped = remapFromGraphQLSingleInput(columns, table, 'update');\n return Object.keys(expressions).length ? { ...remapped, ...expressions } : remapped;\n};\n","// Shaping of the config objects handed to drizzle's relational query builder\n// (`findMany` / `findFirst` and each entry of a `with:` tree).\n\n/**\n * A copy of a relational query config with every key whose value is `undefined` left out.\n *\n * drizzle-orm rc.5 snapshots test `\"where\" in params` rather than its value, and throw\n * `Unexpected 'undefined' in filter value` for `{ where: undefined }`; rc.4 read the value and\n * treated both the same. The library builds its configs with conditional keys\n * (`where: cond ? … : undefined`), so every config goes through here before it reaches drizzle.\n * Only `where` is checked that way today, but leaving out every undefined key costs nothing\n * and keeps the next key that gets the same treatment from breaking queries.\n *\n * Shallow on purpose: nested `with:` entries are built (and passed through here) one level at\n * a time, and the values of the other keys are drizzle's own (column maps, callbacks, RAW).\n */\nexport const omitUndefinedKeys = <T extends Record<string, unknown>>(config: T): T => {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(config)) {\n if (value !== undefined) {\n out[key] = value;\n }\n }\n return out as T;\n};\n","// Reading the requested columns off a parsed selection tree, in both shapes the builders need —\n// the relational query builder's `columns` map, and a SQL select list.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { getColumns } from 'drizzle-orm';\nimport type { ResolveTree } from '../../parse-resolve-info.ts';\nimport type { SelectedColumnsRaw, SelectedSQLColumns, TableNamedRelations } from '../types.ts';\nimport { extractRelationJoinColumns } from './relations.ts';\n\nconst rqbCrashTypes = ['SQLiteBigInt', 'SQLiteBlobJson', 'SQLiteBlobBuffer'];\n\n/**\n * Everything needed to work out which extra columns a selection implies. Passed to the column\n * extractors so a requested `<relation>Aggregate` field can pull in the join column it resolves\n * from, which the client has no reason to have selected itself.\n */\nexport interface SelectionCtx {\n tableName: string;\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n tables: Record<string, Table>;\n /**\n * Every relation on the table, including those `relationMap` omits because they are not\n * eager-loaded. A lazily-resolved relation still correlates on a join column, so the\n * column extractors need to see it even when the eager map doesn't.\n */\n allRelations?: Record<string, Record<string, TableNamedRelations>>;\n}\n\nconst AGGREGATE_FIELD_SUFFIX = 'Aggregate';\n\n/**\n * Property names of the join columns that this selection's relation fields correlate on.\n * Without them the parent row reaches the relation resolver with no key: an aggregate counts\n * 0 and a relation list comes back empty.\n *\n * Needed by every relation field that resolves through its own resolver rather than the\n * parent's `with:` clause — `<relation>Aggregate` fields, which are always lazy; relations\n * excluded by `eagerLoadRelations`; and relations dropped from `with:` because they were\n * selected more than once under different aliases. Forcing the column for *any* selected\n * relation covers all three without the extractor having to predict which path will run: the\n * cost is one extra column (usually the primary key) in the parent SELECT, and GraphQL only\n * returns the fields the query asked for, so it never reaches the response.\n */\nconst relationJoinColumns = (\n tree: Record<string, ResolveTree>,\n table: Table,\n selectionCtx: SelectionCtx | undefined,\n): string[] => {\n if (!selectionCtx) {\n return [];\n }\n const relations =\n (selectionCtx.allRelations ?? selectionCtx.relationMap)[selectionCtx.tableName] ??\n selectionCtx.relationMap[selectionCtx.tableName];\n if (!relations) {\n return [];\n }\n\n const tableColumns = getColumns(table);\n const needed: string[] = [];\n\n for (const fieldData of Object.values(tree)) {\n // A column that happens to be named like a relation is a column.\n if (tableColumns[fieldData.name]) {\n continue;\n }\n\n const relEntry = fieldData.name.endsWith(AGGREGATE_FIELD_SUFFIX)\n ? relations[fieldData.name.slice(0, -AGGREGATE_FIELD_SUFFIX.length)]\n : relations[fieldData.name];\n const targetTable = relEntry ? selectionCtx.tables[relEntry.targetTableName] : undefined;\n if (!relEntry || !targetTable) {\n continue;\n }\n\n const joinCols = extractRelationJoinColumns(relEntry, table, targetTable);\n if (joinCols) {\n needed.push(joinCols.localColPropName);\n }\n }\n\n return needed;\n};\n\n/**\n * The column the extractors fall back to when a selection names none of its own — a query that\n * asked only for `__typename`, or only for relation fields. The relational query builder still\n * needs at least one column, and some SQLite column types crash it when they are the only one\n * selected, so a column of any other type is preferred and the first column is the last resort.\n */\nconst fallbackColumnName = (tableColumns: Record<string, Column>): string => {\n const columnKeys = Object.entries(tableColumns);\n return columnKeys.find(([, column]) => !rqbCrashTypes.includes(column.columnType))?.[0] ?? columnKeys[0]![0];\n};\n\n/**\n * Property names of the columns a selection reads: the ones it names itself, plus the join\n * columns its relation fields correlate on, plus the fallback when that leaves nothing.\n */\nconst selectedColumnNames = (\n tree: Record<string, ResolveTree>,\n table: Table,\n selectionCtx: SelectionCtx | undefined,\n): string[] => {\n const tableColumns = getColumns(table);\n const names: string[] = [];\n\n for (const fieldData of Object.values(tree)) {\n if (!tableColumns[fieldData.name]) {\n continue;\n }\n\n names.push(fieldData.name);\n }\n\n names.push(...relationJoinColumns(tree, table, selectionCtx));\n\n if (!names.length) {\n names.push(fallbackColumnName(tableColumns));\n }\n\n return names;\n};\n\n/** The requested columns as the relational query builder's `columns` map. */\nexport const extractSelectedColumnsFromTree = (\n tree: Record<string, ResolveTree>,\n table: Table,\n selectionCtx?: SelectionCtx,\n): Record<string, true> => {\n const selectedColumns: SelectedColumnsRaw = selectedColumnNames(tree, table, selectionCtx).map((columnName) => [\n columnName,\n true,\n ]);\n\n return Object.fromEntries(selectedColumns);\n};\n\n/**\n * The same columns as a SQL select list.\n *\n * Can't automatically determine column type on type level\n * Since drizzle table types extend eachother\n */\nexport const extractSelectedColumnsFromTreeSQLFormat = <TColType extends Column = Column>(\n tree: Record<string, ResolveTree>,\n table: Table,\n selectionCtx?: SelectionCtx,\n): Record<string, TColType> => {\n const tableColumns = getColumns(table);\n const selectedColumns: SelectedSQLColumns = selectedColumnNames(tree, table, selectionCtx).map((columnName) => [\n columnName,\n tableColumns[columnName]!,\n ]);\n\n return Object.fromEntries(selectedColumns) as Record<string, TColType>;\n};\n","// Turning a parsed selection tree into the relational query builder's `with:` clause, and\n// pruning the relations that opted out of eager loading.\n\nimport type { Table } from 'drizzle-orm';\nimport { is, One } from 'drizzle-orm';\nimport type { ResolveTree } from '../../parse-resolve-info.ts';\nimport type { ProcessedTableSelectArgs, TableNamedRelations, TableSelectArgs } from '../types.ts';\nimport { isCursorFieldSelected } from './cursor.ts';\nimport { primaryKeyOrderExprs } from './keys.ts';\nimport type { DefaultOrderByFor, LimitPolicyFor } from './limits.ts';\nimport { applyLimitPolicy, withDefaultOrderBy } from './limits.ts';\nimport type { TypeNameMapper } from './naming.ts';\nimport { resolveObjectTypeName } from './naming.ts';\nimport { extractOrderBy } from './order-by.ts';\nimport type { DeletedMode, ScopeResolver } from './policies.ts';\nimport { withScope } from './policies.ts';\nimport type { RelationFilterBase } from './relation-filters.ts';\nimport { extractFilters, relationFilterCtx } from './relation-filters.ts';\nimport { omitUndefinedKeys } from './rqb-config.ts';\nimport { extractSelectedColumnsFromTree } from './selected-columns.ts';\nimport type { TypeNameResolver } from './type-names.ts';\n\n/**\n * The build-wide policy the walk carries down unchanged. Grouped rather than passed\n * positionally because the recursion below re-passes every one of them as it descends, and\n * five of the six are object-or-undefined — a positional list of those is a silent hazard\n * (a caller that means \"no limits, no scope\" writes three bare `undefined`s in a row).\n */\nexport interface RelationParamsOptions {\n typeNameMapper?: TypeNameMapper;\n filterCtx?: RelationFilterBase;\n limits?: LimitPolicyFor;\n scope?: ScopeResolver;\n defaultOrderBy?: DefaultOrderByFor;\n resolveName?: TypeNameResolver;\n}\n\nexport const extractRelationsParams = (\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n tables: Record<string, Table>,\n tableName: string,\n info: ResolveTree | undefined,\n typeName: string,\n options: RelationParamsOptions = {},\n): Record<string, Partial<ProcessedTableSelectArgs>> | undefined => {\n const { typeNameMapper, filterCtx, limits, scope, defaultOrderBy, resolveName } = options;\n if (!info) {\n return undefined;\n }\n\n const relationsForTable = relationMap[tableName];\n if (!relationsForTable) {\n return undefined;\n }\n\n const baseField = info.fieldsByTypeName[typeName];\n if (!baseField) {\n return undefined;\n }\n\n // The parsed tree keys its entries by response key — the alias — so a relation is found by\n // the `name` its selections carry, not by the key they sit under. Grouped once here rather\n // than searched per relation: the loop below runs over every relation the table declares,\n // selected or not, and used to walk the whole selection set three times for each of them.\n const selectionsByName = new Map<string, ResolveTree[]>();\n for (const selection of Object.values(baseField) as ResolveTree[]) {\n const selections = selectionsByName.get(selection.name);\n if (selections) {\n selections.push(selection);\n } else {\n selectionsByName.set(selection.name, [selection]);\n }\n }\n\n const args: Record<string, Partial<ProcessedTableSelectArgs>> = {};\n\n for (const [relName, relEntry] of Object.entries(relationsForTable)) {\n const { targetTableName, targetPkNames } = relEntry;\n // The relation field resolves to the target table's own type, e.g. \"Posts\" not \"UsersPostsRelation\".\n const relTypeName = resolveObjectTypeName(targetTableName, typeNameMapper, resolveName);\n const selections = selectionsByName.get(relName);\n if (!selections) {\n continue;\n }\n const field = selections[0]!;\n\n // The `with:` clause is keyed by relation name, so one relation selected twice under\n // different aliases has no eager representation: the first selection's args and column\n // set would win, and both aliases would then read the same pre-fetched array off the\n // parent — wrong rows for the loser, and missing columns it selected. Drizzle's RQB\n // cannot fetch one relation twice under two keys, so there is no eager fix. Leave the\n // relation out of `with:` and let every alias resolve through the field resolver's\n // batch loader, which keys its loader by the serialized args and so is per-alias\n // correct (and still batched across parents).\n if (selections.length > 1) {\n continue;\n }\n const relFieldSelection = field.fieldsByTypeName[relTypeName];\n\n // Guard: if the relation type is not in fieldsByTypeName, this field is\n // either an aliased scalar column (not an actual relation) or the relation\n // was not selected in the query. Skip it in both cases.\n if (!relFieldSelection) {\n continue;\n }\n\n // `after`, `distinct` and the `cursor` field are the relation-level half of the root\n // list's keyset and distinct machinery, and drizzle's `with:` clause can express none of\n // them: keyset needs a predicate over the request's own total order, distinct needs a\n // window pass, and a cursor has to be computed from the raw row. As with an aliased\n // relation above, the fix is to leave the relation out of the eager clause — the field\n // resolver's batch loader implements all three, still in one query per relation.\n const eagerArgs = field.args as Partial<TableSelectArgs> | undefined;\n if (\n !is((relEntry as any).relation ?? relEntry, One) &&\n (eagerArgs?.after != null ||\n !!(eagerArgs?.distinct as string[] | undefined)?.length ||\n isCursorFieldSelected(relFieldSelection, tables[targetTableName]!))\n ) {\n continue;\n }\n\n const columns = extractSelectedColumnsFromTree(relFieldSelection, tables[targetTableName]!, {\n tableName: targetTableName,\n relationMap,\n tables,\n allRelations: filterCtx?.relationMap,\n });\n\n const thisRecord: Partial<ProcessedTableSelectArgs> = {};\n thisRecord.columns = columns;\n\n // The eager path reads its arguments off the AST rather than through the relation field's\n // resolver, so the target's default ordering has to be substituted here too — otherwise\n // an eagerly loaded relation would come back in a different order from a lazily loaded one.\n const relationArgs: Partial<TableSelectArgs> | undefined = is(relEntry.relation, One)\n ? field.args\n : withDefaultOrderBy(field.args ?? {}, targetTableName, defaultOrderBy);\n\n const offset = relationArgs?.offset ?? undefined;\n // The eager path reads its arguments off the AST rather than through the relation field's\n // resolver, so the policy has to be applied here too — otherwise an eagerly loaded\n // relation would be the one way around it. A to-one relation takes no `limit` and is a\n // single row by definition, so it is left alone.\n const limit = is(relEntry.relation, One)\n ? (relationArgs?.limit ?? undefined)\n : applyLimitPolicy(relationArgs?.limit, limits?.(targetTableName), {\n table: targetTableName,\n operation: 'relation',\n relation: relName,\n });\n\n // drizzle-orm v1 RQB calls both `where` and `orderBy` callbacks with an\n // aliased table proxy (e.g. d0, d1). Pass the proxy through so column\n // references in the generated SQL match the CTE alias rather than the\n // original unaliased table name.\n const relWhere = relationArgs?.where;\n // A relation field's soft-delete default is the target's, not the root default — a\n // required to-one relation, and a table declared `scope: 'root'`, both read INCLUDE.\n const relDeleted =\n ((relationArgs as any)?.deleted as DeletedMode | undefined) ??\n scope?.relationDefault(\n targetTableName,\n is(relEntry.relation, One) && (relEntry.relation as any).optional === false,\n );\n // The eager path is the one read that never passes through the relation field's own\n // resolver, so the target's scope has to be applied here as well — otherwise selecting a\n // relation would be the way around it.\n thisRecord.where =\n relWhere || scope?.has(targetTableName, relDeleted)\n ? {\n RAW: (aliasedTable: Table) =>\n withScope(\n scope,\n targetTableName,\n aliasedTable,\n relWhere\n ? extractFilters(aliasedTable, relName, relWhere, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n relDeleted,\n ),\n }\n : undefined;\n // When a relation is paginated (limit/offset) but unordered, default to the target's\n // primary key so the per-parent slice is deterministic. Drizzle's RQB calls orderBy\n // with the aliased table proxy, so resolve the PK columns from it. targetPkNames is\n // resolved at build time and includes composite keys.\n const hasPagination = offset != null || limit != null;\n const pkNames = targetPkNames ?? [];\n thisRecord.orderBy = relationArgs?.orderBy\n ? (aliasedTable: Table) =>\n extractOrderBy(aliasedTable, relationArgs.orderBy!, relationFilterCtx(filterCtx, targetTableName), relWhere)\n : hasPagination && pkNames.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined;\n thisRecord.offset = offset;\n thisRecord.limit = limit;\n\n const relWith = extractRelationsParams(relationMap, tables, targetTableName, field, relTypeName, options);\n thisRecord.with = relWith;\n\n args[relName] = omitUndefinedKeys(thisRecord);\n }\n\n return args;\n};\n\n/**\n * Returns a copy of `relationMap` containing only the relations that should be eagerly\n * pre-fetched (per the `shouldEagerLoad` predicate). Pass the result wherever a query or\n * mutation resolver builds its `with:` clause; pass the full map to type generation so\n * opted-out relations still get a (lazily-resolved) field. Relations excluded here are\n * never added to `with:`, so they don't overfetch — they resolve through their field\n * resolver instead (or a resolver you override, e.g. via `@graphql-tools/schema`).\n */\nexport const pruneNonEagerRelations = (\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n shouldEagerLoad: (tableName: string, relationName: string) => boolean,\n): Record<string, Record<string, TableNamedRelations>> => {\n const out: Record<string, Record<string, TableNamedRelations>> = {};\n for (const [tableName, rels] of Object.entries(relationMap)) {\n out[tableName] = Object.fromEntries(\n Object.entries(rels).filter(([relationName]) => shouldEagerLoad(tableName, relationName)),\n );\n }\n return out;\n};\n","// The read path at resolve time: running a relational select with everything the arguments\n// asked for, and eager-loading relations onto the rows a mutation returns.\n\nimport type { Table } from 'drizzle-orm';\nimport { and, inArray, type SQL, sql } from 'drizzle-orm';\nimport { remapToGraphQLArrayOutput, remapToGraphQLSingleOutput } from '../../data-mappers/index.ts';\nimport type { ResolveTree } from '../../parse-resolve-info.ts';\nimport type { ProcessedTableSelectArgs, TableNamedRelations } from '../types.ts';\nimport type { CursorOrderEntry, NullOrdering } from './cursor.ts';\nimport {\n attachRowCursors,\n buildCursorCondition,\n cursorOrderExprs,\n cursorOrderingEntries,\n decodeCursor,\n isCursorFieldSelected,\n orderByCursorObstacle,\n} from './cursor.ts';\nimport { primaryKeyRestriction, selectDistinctKeys } from './distinct.ts';\nimport { drizzleError } from './errors.ts';\nimport { primaryKeyOrderExprs } from './keys.ts';\nimport type { DefaultOrderByFor, LimitPolicyFor } from './limits.ts';\nimport type { TypeNameMapper } from './naming.ts';\nimport { extractOrderBy } from './order-by.ts';\nimport type { DeletedMode, ScopeResolver } from './policies.ts';\nimport { withScope } from './policies.ts';\nimport type { RelationFilterBase } from './relation-filters.ts';\nimport { extractFilters, relationFilterCtx } from './relation-filters.ts';\nimport { extractRelationsParams } from './relation-params.ts';\nimport { omitUndefinedKeys } from './rqb-config.ts';\nimport { extractSelectedColumnsFromTree } from './selected-columns.ts';\nimport type { TypeNameResolver } from './type-names.ts';\n\n/**\n * Runs the relational-query-builder select shared by every dialect's `generateSelect*`\n * resolver: selected columns + offset/limit + aliased orderBy/where callbacks + the eager\n * `with:` relation params, then remaps the result. `single` switches between\n * findFirst/findMany (and the single path omits `limit`). The PG fallback for tables\n * without RQB support stays in pg.ts; this covers the common RQB path for all three.\n */\nexport const runRelationalSelect = async (opts: {\n queryBase: any;\n tables: Record<string, Table>;\n tableName: string;\n table: Table;\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n typeName: string;\n typeNameMapper: TypeNameMapper | undefined;\n parsedInfo: ResolveTree;\n offset?: number;\n limit?: number;\n orderBy?: any;\n where?: any;\n single: boolean;\n filterCtx?: RelationFilterBase;\n pkNames?: readonly string[];\n db?: any;\n distinct?: string[];\n after?: string;\n nullOrdering?: NullOrdering;\n limits?: LimitPolicyFor;\n scope?: ScopeResolver;\n defaultOrderBy?: DefaultOrderByFor;\n deleted?: DeletedMode;\n /** The build's type-naming rule, so a relation's target type is looked up under its real name. */\n resolveName?: TypeNameResolver;\n}): Promise<any> => {\n const {\n queryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n offset,\n orderBy,\n where,\n single,\n filterCtx,\n pkNames,\n after,\n scope,\n deleted,\n } = opts;\n const distinct = opts.distinct?.length ? opts.distinct : undefined;\n\n // ── keyset (cursor) pagination ──\n // Active when the request passes `after` or selects the `cursor` meta field. The cursor is\n // defined over a total order — the request's orderBy plus the primary-key tiebreak — so both\n // need the PK; a table without one gets an error for `after` and null cursors otherwise.\n const cursorSelected = !single && isCursorFieldSelected(parsedInfo.fieldsByTypeName[typeName], table);\n let cursorEntries: CursorOrderEntry[] | undefined;\n if (!single && (after != null || cursorSelected)) {\n if (after != null && distinct) {\n throw drizzleError(\"'after' cannot be combined with 'distinct'.\", { code: 'DRIZZLE_INVALID_CURSOR' });\n }\n const cursorObstacle = orderByCursorObstacle(orderBy);\n if (cursorObstacle) {\n if (after != null) {\n throw drizzleError(cursorObstacle, { code: 'DRIZZLE_INVALID_CURSOR' });\n }\n // `cursor` was selected under an ordering a cursor cannot express — the field resolves\n // to null and the ordering itself still applies.\n } else if (!pkNames?.length) {\n if (after != null) {\n throw drizzleError(`Table ${tableName} has no primary key, so cursor pagination cannot be used on it.`, {\n code: 'DRIZZLE_INVALID_CURSOR',\n });\n }\n // `cursor` was selected but no total order exists — the field resolves to null.\n } else {\n cursorEntries = cursorOrderingEntries(orderBy, pkNames);\n }\n }\n const cursorValues = after != null && cursorEntries ? decodeCursor(after, cursorEntries) : undefined;\n // Taking a slice of an unordered result lets the database return any rows it likes, so\n // `limit`/`offset` pages can overlap or skip rows between requests, and a single query\n // can return a different row each time. Default to the primary key whenever the query is\n // narrowed to a subset, mirroring the relation-level default in extractRelationsParams.\n const needsDefaultOrder = single || offset != null || opts.limit != null;\n\n // `distinct` runs as its own pass — the relational query builder cannot express it — and\n // the main query is then narrowed to the primary keys it picked, with the same ordering\n // and without re-applying limit/offset.\n let distinctKeys: Record<string, any>[] | undefined;\n if (distinct) {\n distinctKeys = await selectDistinctKeys({\n db: opts.db,\n table,\n tableName,\n distinct,\n pkNames: pkNames ?? [],\n where: withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n deleted,\n ),\n orderBy,\n limit: single ? 1 : opts.limit,\n offset,\n });\n\n if (!distinctKeys.length) {\n return single ? undefined : [];\n }\n }\n\n const params: any = {\n columns: extractSelectedColumnsFromTree(parsedInfo.fieldsByTypeName[typeName]!, table, {\n tableName,\n relationMap,\n tables,\n allRelations: filterCtx?.relationMap,\n }),\n offset: distinctKeys ? undefined : offset,\n // drizzle-orm v1 RQB calls orderBy/where with the aliased table proxy — use it\n // directly so column refs match the CTE alias.\n orderBy: distinctKeys\n ? (aliasedTable: Table) => [\n ...(orderBy ? extractOrderBy(aliasedTable, orderBy, relationFilterCtx(filterCtx, tableName), where) : []),\n ...primaryKeyOrderExprs(aliasedTable, pkNames!),\n ]\n : cursorEntries\n ? // Cursor pagination needs a total order: the request's orderBy plus the PK tiebreak,\n // exactly the ordering the cursor encodes and the keyset predicate compares against.\n (aliasedTable: Table) => cursorOrderExprs(aliasedTable, cursorEntries!)\n : orderBy\n ? (aliasedTable: Table) =>\n extractOrderBy(aliasedTable, orderBy, relationFilterCtx(filterCtx, tableName), where)\n : needsDefaultOrder && pkNames?.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined,\n where: distinctKeys\n ? // The distinct pass already ran inside the scope, so the keys it picked are in it.\n { RAW: (aliasedTable: Table) => primaryKeyRestriction(aliasedTable, pkNames!, distinctKeys!) }\n : where || cursorValues || scope?.has(tableName, deleted)\n ? {\n RAW: (aliasedTable: Table) =>\n withScope(\n scope,\n tableName,\n aliasedTable,\n and(\n where\n ? extractFilters(aliasedTable, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n cursorValues\n ? buildCursorCondition(\n aliasedTable,\n cursorEntries!,\n cursorValues,\n opts.nullOrdering ?? 'nulls-smallest',\n )\n : undefined,\n ),\n deleted,\n ),\n }\n : undefined,\n with: relationMap[tableName]\n ? extractRelationsParams(relationMap, tables, tableName, parsedInfo, typeName, {\n typeNameMapper,\n filterCtx,\n limits: opts.limits,\n scope,\n defaultOrderBy: opts.defaultOrderBy,\n resolveName: opts.resolveName,\n })\n : undefined,\n };\n\n if (single) {\n const result = await queryBase.findFirst(omitUndefinedKeys(params));\n return result ? remapToGraphQLSingleOutput(result, tableName, table, relationMap) : undefined;\n }\n\n // Computing each row's cursor needs the whole ordering tuple, which the client has no\n // reason to have selected — force those columns into the fetch (GraphQL only returns\n // the fields the query asked for, so extra properties never leak into the response).\n if (cursorEntries && cursorSelected) {\n for (const [column] of cursorEntries) {\n params.columns[column] = true;\n }\n }\n\n params.limit = distinctKeys ? undefined : opts.limit;\n const result = await queryBase.findMany(omitUndefinedKeys(params));\n if (cursorEntries && cursorSelected) {\n // On the raw rows, before remapping rewrites dates/bigints into transport forms.\n attachRowCursors(result, cursorEntries);\n }\n return remapToGraphQLArrayOutput(result, tableName, table, relationMap);\n};\n\n/**\n * After a mutation, re-fetch the mutated rows through the relational query builder so the\n * selected relations are eagerly loaded in a single query, then merge those relations onto\n * the `.returning()` rows — making the per-field BatchLoader fallback unnecessary.\n *\n * `withParams` is the pre-computed relation selection (from extractRelationsParams); the\n * caller only invokes this when relations are actually selected, so it also gates whether\n * the PK was forced into RETURNING.\n *\n * Falls back to the original `.returning()` rows (relations then resolve via the\n * field-level BatchLoader) when the table has no RQB support, no primary key columns can be\n * determined, or the re-fetch fails. Supports single- and multi-column primary keys.\n */\nexport const eagerLoadMutationRelations = async (\n db: any,\n tableName: string,\n rows: any[],\n pkNames: readonly string[],\n withParams: Record<string, Partial<ProcessedTableSelectArgs>> | undefined,\n): Promise<any[]> => {\n if (!rows.length || !pkNames.length || !withParams || !Object.keys(withParams).length) {\n return rows;\n }\n\n const queryBase = db.query?.[tableName];\n if (!queryBase) {\n return rows;\n }\n\n // Only rows that carry every PK value can be re-keyed. Callers force the PK into\n // RETURNING, but if a value is still missing for some rows, eager-load just those that\n // are keyable and leave the rest untouched (their relations resolve lazily) rather than\n // bailing the whole batch.\n const keyableRows = rows.filter((row) => pkNames.every((n) => row[n] != null));\n if (!keyableRows.length) {\n return rows;\n }\n\n // Re-fetch ONLY the primary key + relations: the scalar columns are already present\n // on `rows` from RETURNING, so re-selecting them would transfer them a second time\n // (and would lose them on the fallback path). We merge the fetched relations back in.\n const pkColumns: Record<string, true> = {};\n for (const pk of pkNames) {\n pkColumns[pk] = true;\n }\n const relationNames = Object.keys(withParams);\n\n // Normalize bigint PK values to strings: JSON.stringify throws on bigint, and a\n // bigint and its string form never collide within a single column's values.\n const keyOf = (row: any) =>\n JSON.stringify(pkNames.map((n) => (typeof row[n] === 'bigint' ? row[n].toString() : row[n])));\n\n let whereRaw: (aliased: any) => SQL | undefined;\n if (pkNames.length === 1) {\n const pkName = pkNames[0]!;\n const ids = keyableRows.map((r) => r[pkName]);\n // drizzle-orm v1 RQB calls the where callback with the aliased table proxy;\n // reference the PK through it so the column ref matches the CTE alias.\n whereRaw = (aliased: any) => inArray(aliased[pkName], ids);\n } else {\n // Composite PK: use a row-value IN — `(a, b) IN ((..), (..))` — so the database can\n // plan it as a set membership test, instead of an OR of N per-row AND-tuples that\n // blows up for large bulk mutations.\n whereRaw = (aliased: any) => {\n const lhs = sql.join(\n pkNames.map((n) => sql`${aliased[n]}`),\n sql`, `,\n );\n const tuples = sql.join(\n keyableRows.map(\n (row) =>\n sql`(${sql.join(\n pkNames.map((n) => sql`${row[n]}`),\n sql`, `,\n )})`,\n ),\n sql`, `,\n );\n return sql`(${lhs}) in (${tuples})`;\n };\n }\n\n let enriched: any[];\n try {\n enriched = await queryBase.findMany({\n columns: pkColumns,\n where: { RAW: whereRaw },\n with: withParams,\n });\n } catch (err) {\n // The write has already committed; a re-fetch failure (e.g. an RQB-incompatible\n // column or relation) must not turn a successful mutation into an error. Fall back\n // to the raw rows — relations then resolve lazily via the batch loader — but surface\n // the cause so a genuine misconfiguration isn't silently hidden.\n console.warn(\n `[drizzle-graphql] eager-loading relations for a \"${tableName}\" mutation failed; ` +\n 'falling back to lazy resolution.',\n err,\n );\n return rows;\n }\n\n // Merge the fetched relations onto the RETURNING rows in place, preserving order. A row\n // the re-fetch didn't return (e.g. deleted concurrently) keeps its scalar columns and\n // its relations resolve lazily, so the result never reports fewer rows than were mutated.\n const byKey = new Map(enriched.map((e) => [keyOf(e), e]));\n for (const row of rows) {\n const match = byKey.get(keyOf(row));\n if (!match) {\n continue;\n }\n for (const rel of relationNames) {\n row[rel] = match[rel];\n }\n }\n return rows;\n};\n","// =============================================================================\n// Automatic per-request transactions for multi-mutation documents\n// (`BuildSchemaConfig.transactions: 'auto'`).\n//\n// GraphQL executes root mutation fields serially, but each one is a separate\n// resolver call on whatever server hosts the schema — the library never sees\n// the request as a whole. So the FIRST mutation resolver of a request inspects\n// `info.operation`: when the document selects more than one root mutation\n// field, it opens `db.transaction()` once, parks the transaction on a\n// per-request state object (WeakMap keyed by the context object), and every\n// later mutation resolver of the same request runs on that transaction. The\n// transaction callback awaits a latch; the last field to complete resolves it\n// (COMMIT) and the first failure rejects it (ROLLBACK).\n// =============================================================================\n\nimport type { GraphQLError } from 'graphql';\nimport { drizzleError } from './errors.ts';\nimport { drizzleExecutorKey, resolveExecutor } from './executor.ts';\n\n/** How long a shared transaction may sit idle between resolver calls before it is rolled back. */\nexport const DEFAULT_TRANSACTION_TIMEOUT_MS = 30_000;\n\n/**\n * One per built schema (when `transactions: 'auto'` is on). `fieldNames` is filled by the\n * dialect generator once every mutation field name is known, so a request-time count can\n * tell library mutations apart from consumer-added ones.\n */\nexport type MutationTxCtx = {\n timeoutMs: number;\n fieldNames: Set<string>;\n states: WeakMap<object, RequestTxState>;\n};\n\nexport const createMutationTxCtx = (options: { timeoutMs: number } | undefined): MutationTxCtx | undefined =>\n options ? { timeoutMs: options.timeoutMs, fieldNames: new Set(), states: new WeakMap() } : undefined;\n\ntype SharedTxState = {\n kind: 'shared';\n /** Distinct root mutation response keys the document will execute. */\n expected: number;\n completed: number;\n /** First failure; set once, before the latch is rejected. */\n failure: unknown;\n aborted: boolean;\n /** True once the underlying `db.transaction()` promise has settled (committed or rolled back). */\n done: boolean;\n /** Resolves with the transaction once BEGIN succeeded; rejects if it never will. */\n ready: Promise<any>;\n /** The `db.transaction()` promise itself — rejects when the transaction rolls back. */\n settled: Promise<unknown>;\n release: () => void;\n abort: (e: unknown) => void;\n /** Pause the inactivity timer while a resolver is actively working. */\n suspendTimer: () => void;\n /** (Re)arm the inactivity timer while waiting for the next resolver call. */\n bumpTimer: () => void;\n};\n\ntype RequestTxState = { kind: 'passthrough' } | SharedTxState;\n\nconst includedByDirectives = (node: { directives?: readonly any[] }, variables: any): boolean => {\n for (const directive of node.directives ?? []) {\n const name = directive.name.value;\n if (name !== 'skip' && name !== 'include') {\n continue;\n }\n const ifArg = directive.arguments?.find((arg: any) => arg.name.value === 'if');\n let value: unknown;\n if (ifArg?.value.kind === 'BooleanValue') {\n value = ifArg.value.value;\n } else if (ifArg?.value.kind === 'Variable') {\n value = variables?.[ifArg.value.name.value];\n }\n if (name === 'skip' && value === true) {\n return false;\n }\n if (name === 'include' && value !== true) {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Collects the response keys of every root mutation field the executor will run, expanding\n * fragments and honoring `@skip` / `@include`. Distinct response keys (alias ?? name) are\n * counted, matching graphql-js field collection, so a field selected twice under one key is\n * still one resolver call. Returns `false` when the document selects a root mutation field\n * this build did not generate — its completion cannot be tracked, so the caller must not\n * open a transaction it might never be able to close.\n */\nconst collectRootMutationKeys = (\n selectionSet: any,\n fragments: any,\n variables: any,\n known: ReadonlySet<string>,\n keys: Set<string>,\n visitedFragments: Set<string>,\n): boolean => {\n for (const selection of selectionSet.selections) {\n if (!includedByDirectives(selection, variables)) {\n continue;\n }\n if (selection.kind === 'Field') {\n const name = selection.name.value;\n if (name === '__typename') {\n continue;\n }\n if (!known.has(name)) {\n return false;\n }\n keys.add(selection.alias?.value ?? name);\n } else if (selection.kind === 'InlineFragment') {\n if (!collectRootMutationKeys(selection.selectionSet, fragments, variables, known, keys, visitedFragments)) {\n return false;\n }\n } else if (selection.kind === 'FragmentSpread') {\n const fragmentName = selection.name.value;\n if (visitedFragments.has(fragmentName)) {\n continue;\n }\n visitedFragments.add(fragmentName);\n const fragment = fragments?.[fragmentName];\n if (!fragment) {\n return false;\n }\n if (!collectRootMutationKeys(fragment.selectionSet, fragments, variables, known, keys, visitedFragments)) {\n return false;\n }\n }\n }\n return true;\n};\n\nconst abortedBatchError = (): GraphQLError =>\n drizzleError(\n 'Drizzle-GraphQL Error: Mutation was not executed because an earlier mutation in the same request failed and the shared transaction was rolled back.',\n { code: 'DRIZZLE_TRANSACTION_ABORTED' },\n );\n\n/** Opens the request-wide transaction and wires up latch, inactivity timer and cleanup. */\nconst openSharedTx = (\n db: any,\n context: any,\n txCtx: MutationTxCtx,\n stateKey: object,\n expected: number,\n): SharedTxState => {\n let release!: () => void;\n let rejectLatch!: (e: unknown) => void;\n const latch = new Promise<void>((resolve, reject) => {\n release = resolve;\n rejectLatch = reject;\n });\n\n let readyResolve!: (tx: any) => void;\n let readyReject!: (e: unknown) => void;\n const ready = new Promise<any>((resolve, reject) => {\n readyResolve = resolve;\n readyReject = reject;\n });\n // Nobody may be awaiting `ready` when BEGIN fails — keep that from surfacing as an\n // unhandled rejection; each resolver still observes it through its own `await`.\n ready.catch(() => {});\n\n const canStash = context !== null && typeof context === 'object' && !Object.isFrozen(context);\n\n const settled: Promise<unknown> = db.transaction(async (tx: any) => {\n if (canStash) {\n // Publish our transaction under the caller-facing key so nested resolvers (lazy\n // relation fields, relation aggregates) selected under a mutation read through it\n // and see its uncommitted rows — the same wrapper a caller-supplied transaction uses.\n context[drizzleExecutorKey] = tx;\n }\n readyResolve(tx);\n // Held open across resolver calls: the last mutation field to complete resolves the\n // latch (COMMIT); the first failure — or the inactivity timeout — rejects it (ROLLBACK).\n await latch;\n });\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const clearTimer = () => {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n\n const state: SharedTxState = {\n kind: 'shared',\n expected,\n completed: 0,\n failure: undefined,\n aborted: false,\n done: false,\n ready,\n settled,\n release,\n abort: (e: unknown) => {\n if (!state.aborted) {\n state.aborted = true;\n state.failure = e;\n }\n rejectLatch(e);\n },\n suspendTimer: clearTimer,\n bumpTimer: () => {\n clearTimer();\n if (state.done) {\n return;\n }\n timer = setTimeout(() => {\n // The host never called the remaining resolvers (e.g. a non-null completion error\n // outside our resolvers aborted serial execution). Roll back rather than leak.\n state.abort(\n drizzleError(\n `Drizzle-GraphQL Error: Shared mutation transaction timed out after ${txCtx.timeoutMs}ms waiting for the remaining mutation fields; rolling back.`,\n { code: 'DRIZZLE_TRANSACTION_ABORTED' },\n ),\n );\n }, txCtx.timeoutMs);\n (timer as any).unref?.();\n },\n };\n\n const cleanup = () => {\n state.done = true;\n clearTimer();\n if (canStash) {\n delete context[drizzleExecutorKey];\n }\n // A committed state left in the map would poison a reused context object; an aborted\n // one must stay so late-arriving fields of THIS request keep failing fast.\n if (!state.aborted) {\n txCtx.states.delete(stateKey);\n }\n };\n settled.then(cleanup, (e) => {\n cleanup();\n // BEGIN itself may have failed (driver without transaction support) — unblock waiters.\n readyReject(e);\n });\n\n state.bumpTimer();\n return state;\n};\n\nconst runOnSharedTx = async <T>(state: SharedTxState, body: (executor: any) => Promise<T>): Promise<T> => {\n if (state.aborted) {\n // Fail fast: never run a later field against a transaction that already rolled back.\n await (state.settled as Promise<unknown>).catch(() => {});\n throw abortedBatchError();\n }\n state.suspendTimer();\n const tx = await state.ready;\n try {\n if (state.aborted) {\n throw abortedBatchError();\n }\n const result = await body(tx);\n state.completed += 1;\n if (state.completed >= state.expected) {\n state.release();\n // COMMIT before this (final) field resolves, so the data is durable — and a commit\n // failure surfaces as this field's error.\n await state.settled;\n } else {\n state.bumpTimer();\n }\n return result;\n } catch (e) {\n state.abort(e);\n // Wait for the ROLLBACK to finish before surfacing, so the caller never observes a\n // response produced while the transaction is still being unwound.\n await (state.settled as Promise<unknown>).catch(() => {});\n throw e;\n }\n};\n\n/**\n * Executor selection for every generated mutation resolver. Runs `body` with:\n *\n * - the caller-supplied executor, when the context carries one under\n * {@link drizzleExecutorKey} — the library never nests a transaction inside it;\n * - the build-time `db`, when auto-transactions are off, the document has at most one root\n * mutation field, or it selects a mutation field this build did not generate (a consumer\n * extension whose completion cannot be tracked);\n * - otherwise, the request's shared transaction, opened on the first mutation resolver call\n * and committed when the last one completes / rolled back when any fails.\n */\nexport const runMutation = async <T>(\n db: any,\n context: any,\n info: any,\n txCtx: MutationTxCtx | undefined,\n body: (executor: any) => Promise<T>,\n /**\n * Opens a transaction for a field that would otherwise have run straight on `db`. Set when\n * the field carries an `onWrite` hook, whose whole purpose is to write atomically with the\n * mutation — a hook that ran outside a transaction could not roll anything back.\n */\n forceTx?: boolean,\n): Promise<T> => {\n const contextIsObject = context !== null && (typeof context === 'object' || typeof context === 'function');\n // Check our own request state FIRST: once the shared transaction is stashed on the\n // context it is indistinguishable from a caller-supplied one, but its completion still\n // has to be accounted here.\n const stateKey: object = contextIsObject ? context : info.operation;\n let state = txCtx?.states.get(stateKey);\n\n if (!state) {\n if (contextIsObject && context[drizzleExecutorKey]) {\n // The caller already runs this request on its own transaction/executor — use it as-is.\n return body(context[drizzleExecutorKey]);\n }\n if (!txCtx || info.operation.operation !== 'mutation') {\n return forceTx ? db.transaction((tx: any) => body(tx)) : body(db);\n }\n const keys = new Set<string>();\n const allKnown = collectRootMutationKeys(\n info.operation.selectionSet,\n info.fragments,\n info.variableValues,\n txCtx.fieldNames,\n keys,\n new Set(),\n );\n state =\n !allKnown || keys.size <= 1 ? { kind: 'passthrough' } : openSharedTx(db, context, txCtx, stateKey, keys.size);\n txCtx.states.set(stateKey, state);\n }\n\n if (state.kind === 'passthrough') {\n const executor = resolveExecutor(db, context);\n return forceTx && executor === db ? db.transaction((tx: any) => body(tx)) : body(executor);\n }\n return runOnSharedTx(state, body);\n};\n","// Write hooks (`BuildSchemaConfig.onWrite`): the payload a hook is handed, and running one\n// around the statement it is attached to.\n\nimport type { Column } from 'drizzle-orm';\nimport type { TablePolicies } from './policies.ts';\n\n/** The write a hook is attached to. `restore` only exists for a soft-deleting table. */\nexport type WriteOperation = 'insert' | 'update' | 'updateMany' | 'upsert' | 'delete' | 'restore';\n\n/** Which input of a relation field a nested write came from. */\nexport type NestedWriteOp = 'create' | 'connect' | 'disconnect' | 'set';\n\n/**\n * Where a nested write came from: set on the payload of a hook that fires for a row a nested\n * `create` / `connect` / `disconnect` / `set` wrote, and absent at the mutation field's own\n * table. See {@link WriteHookPayload.nested}.\n */\nexport type NestedWriteOrigin = {\n /** Drizzle schema key of the table whose input carried the relation field. */\n parentTable: string;\n /** The relation field the write went through, as named on the parent table. */\n relation: string;\n /** The relation field's input that produced this statement. */\n op: NestedWriteOp;\n};\n\n/** What a write hook is handed. See {@link BuildSchemaConfig.onWrite}. */\nexport type WriteHookPayload = {\n /** Drizzle schema key of the table being written. */\n table: string;\n /**\n * What happened to `table`. A nested write reports what its statement did to *that* table:\n * `insert` for a nested `create`, `update` for a `connect` / `disconnect` / `set` that\n * changes the foreign key on the target, and `insert` / `delete` on the junction table for\n * a many-to-many link / unlink.\n */\n operation: WriteOperation;\n /** `'before'` runs ahead of the statement, `'after'` once it has returned. */\n position: 'before' | 'after';\n /**\n * Whether the field writes a single row (`createUsersSingle`) or a list. For a nested\n * write, whether the relation it went through is a to-one.\n */\n single: boolean;\n /**\n * The field's GraphQL arguments, exactly as the resolver received them — for a nested\n * write, the arguments of the root mutation field it is part of.\n */\n args: any;\n /**\n * Set when the rows were written by a nested write under another table's mutation, and\n * `undefined` for the mutation field's own table. A hook that only cares about root writes\n * skips the rest with `if (payload.nested) return;`.\n */\n nested?: NestedWriteOrigin;\n /**\n * The rows the write produced, as the database returned them — before the output mapper,\n * so values are database-shaped. Empty at the `before` position, and on MySQL, whose\n * mutations return no rows.\n *\n * Each row holds the columns the client's selection asked for (plus any key a relation or\n * nested write needed), **and** every column the hook names in `columns`. A column the\n * client did not select and the hook did not name is absent. The count mutations select\n * nothing, so there a row holds the named columns, or the primary key when none are named.\n *\n * A nested write has no selection of its own, so its rows hold the table's primary key and\n * the join column(s) the write changed, plus the hook's `columns`.\n */\n rows: any[];\n context: any;\n info: any;\n /** The executor the mutation itself ran on. Throwing from the hook rolls it back. */\n tx: any;\n};\n\nexport type WriteHook = (payload: WriteHookPayload) => void | Promise<void>;\nexport type WriteHookPositions = {\n before?: WriteHook;\n after?: WriteHook;\n /**\n * Columns the `after` hook's `rows` always carry, whatever the client selected: a list of\n * column keys (the table object's property names, as `rows` is keyed), or `'all'` for\n * every column of the table. They are added to the statement's `RETURNING` and taken back\n * off before the result is mapped, so the client's response is unchanged.\n *\n * An unknown column fails the build, and so does `columns` without an `after` hook. On a\n * top-level (every-table) registration a named column must exist on every table.\n */\n columns?: readonly string[] | 'all';\n};\nexport type WriteHooks = WriteHook | WriteHookPositions;\n\n/**\n * Resolved, per-field hooks: `undefined` when the table registered none. `columns` is the\n * hook's `columns` resolved against the table, or `undefined` when it named none.\n */\nexport type ResolvedWriteHooks = { before?: WriteHook; after?: WriteHook; columns?: Record<string, Column> };\n\n/** Build-time lookup of a table's hooks, installed on {@link TablePolicies}. */\nexport type WriteHookFor = (tableName: string, operation: WriteOperation) => ResolvedWriteHooks | undefined;\n\n/**\n * Normalizes the two registration shapes: a bare function is the `after` hook — the position\n * that has rows, and the one the common audit/outbox case wants — while `{ before, after }`\n * names them explicitly.\n */\nexport const normalizeWriteHooks = (\n hooks: WriteHooks | undefined | null,\n tableColumns: Record<string, Column>,\n where: string,\n): ResolvedWriteHooks | undefined => {\n if (!hooks) {\n return undefined;\n }\n if (typeof hooks === 'function') {\n return { after: hooks };\n }\n const resolved: ResolvedWriteHooks = { before: hooks.before, after: hooks.after };\n if (hooks.columns !== undefined) {\n resolved.columns = resolveHookColumns(hooks.columns, !!hooks.after, tableColumns, where);\n }\n return resolved.before || resolved.after ? resolved : undefined;\n};\n\n/**\n * Resolves a hook's `columns` against the table it runs on. `where` names the registration\n * (`config.onWrite.posts`) and, for a top-level one, the table, so the error says which.\n */\nconst resolveHookColumns = (\n spec: readonly string[] | 'all',\n hasAfter: boolean,\n tableColumns: Record<string, Column>,\n where: string,\n): Record<string, Column> => {\n // Only the `after` hook is handed rows, so naming columns for a `before` hook alone is a\n // config that asks for something nothing will ever receive.\n if (!hasAfter) {\n throw new Error(`Drizzle-GraphQL Error: ${where}.columns only applies to an 'after' hook, and none is registered.`);\n }\n if (spec === 'all') {\n return { ...tableColumns };\n }\n if (!Array.isArray(spec)) {\n throw new Error(`Drizzle-GraphQL Error: ${where}.columns must be an array of column names or 'all'.`);\n }\n const resolved: Record<string, Column> = {};\n for (const name of spec) {\n const column =\n typeof name === 'string' && Object.keys(tableColumns).includes(name) ? tableColumns[name] : undefined;\n if (!column) {\n throw new Error(\n `Drizzle-GraphQL Error: ${where}.columns names '${String(name)}', which is not a column of that table.`,\n );\n }\n resolved[name] = column;\n }\n return resolved;\n};\n\n/**\n * Adds a hook's `columns` to a RETURNING column map, and reports which keys it added — the\n * ones the client never asked for, which have to come back off before the rows are mapped.\n * Returns the map untouched, and no keys, when the hook named none or the selection already\n * covers them.\n */\nexport const withHookColumns = <T extends Record<string, Column>>(\n hooks: ResolvedWriteHooks | undefined,\n columns: T,\n): { returning: T; added: string[] | undefined } => {\n const hookColumns = hooks?.columns;\n if (!hookColumns) {\n return { returning: columns, added: undefined };\n }\n const selected = new Set(Object.keys(columns));\n const added = Object.keys(hookColumns).filter((key) => !selected.has(key));\n if (!added.length) {\n return { returning: columns, added: undefined };\n }\n const returning: Record<string, Column> = { ...columns };\n for (const key of added) {\n returning[key] = hookColumns[key]!;\n }\n return { returning: returning as T, added };\n};\n\n/**\n * The rows with the hook-only keys taken off, as fresh objects: the hook was handed the\n * originals and may still hold them, so they are not mutated under it.\n */\nexport const omitHookColumns = <T extends Record<string, any>>(rows: T[], added: string[] | undefined): T[] => {\n if (!added) {\n return rows;\n }\n return rows.map((row) => {\n const copy: Record<string, any> = { ...row };\n for (const key of added) {\n delete copy[key];\n }\n return copy as T;\n });\n};\n\n/**\n * Invokes one position of a field's hooks. Returns `undefined` rather than a resolved promise\n * when nothing is registered, so the awaiting call site costs nothing on an unhooked build.\n */\nexport const runWriteHook = (\n hooks: ResolvedWriteHooks | undefined,\n position: 'before' | 'after',\n payload: Omit<WriteHookPayload, 'position' | 'rows'> & { rows?: any[] },\n): Promise<void> | undefined => {\n const hook = position === 'before' ? hooks?.before : hooks?.after;\n if (!hook) {\n return undefined;\n }\n return Promise.resolve(hook({ ...payload, position, rows: payload.rows ?? [] }));\n};\n","// The scaffolding every generated mutation resolver shares, whatever the dialect or the\n// operation: look up the table's write hooks, run the statement inside the request's\n// transaction, emit the hooks around it, and tag anything that escapes with the field it\n// came from.\n//\n// This was written out by hand at twelve call sites — six in the MySQL builder, five in the\n// shared pg/SQLite write resolvers, one in the shared `updateMany` — and every one of them\n// spelled the same hook payload, the same `runMutation` wrapper and the same catch clause.\n// What actually differs between a MySQL insert and a PostgreSQL one is the statement in the\n// middle: MySQL has no RETURNING clause, so it writes and reports `{ isSuccess }`, while the\n// others select their rows back on the way out. That difference lives in the body below,\n// which is exactly the shape a caller passes in.\n\nimport type { Column } from 'drizzle-orm';\nimport type { GraphQLFieldConfigArgumentMap } from 'graphql';\nimport type { CreatedResolver } from '../types.ts';\nimport { type DrizzleErrorContext, toGraphQLError, withErrorContext } from './errors.ts';\nimport type { ResolverPolicies } from './policies.ts';\nimport { type MutationTxCtx, runMutation } from './transactions.ts';\nimport { omitHookColumns, runWriteHook, type WriteOperation, withHookColumns } from './write-hooks.ts';\n\n/**\n * The table's `onWrite` hooks, bound to this field and this request. A body calls `before()`\n * ahead of its statement and `after(rows)` once the statement has returned; both are no-ops\n * when the table registered no hook.\n */\nexport type WriteHookEmitter = {\n before: () => Promise<void> | undefined;\n /** @param rows the rows the write produced, or `[]` where the dialect returns none. */\n after: (rows?: any[]) => Promise<void> | undefined;\n /**\n * The RETURNING column map the statement should use: the selection's `columns` plus the\n * ones the `after` hook named. Returns `columns` itself when the hook named none.\n */\n returning: <T extends Record<string, Column>>(columns: T) => T;\n /**\n * The rows to map for the client: the statement's rows with the hook-only columns that\n * {@link WriteHookEmitter.returning} added taken back off. Call it after `after(rows)`.\n */\n output: <T extends Record<string, any>>(rows: T[]) => T[];\n};\n\n/** The statement a mutation field runs, and whatever it resolves to. */\nexport type WriteBody<TArgs> = (\n params: {\n /** The transaction (or bare `db`) the write must run on. */\n executor: any;\n args: TArgs;\n context: any;\n info: any;\n } & WriteHookEmitter,\n) => Promise<any>;\n\nexport type WriteResolverSpec<TArgs> = {\n db: any;\n tableName: string;\n operation: WriteOperation;\n /** Whether the field writes one row or a list — reported to the hooks, nothing else. */\n single: boolean;\n fieldName: string;\n /** The field's GraphQL arguments, passed through untouched. */\n args: GraphQLFieldConfigArgumentMap;\n txCtx?: MutationTxCtx;\n policies?: ResolverPolicies;\n run: WriteBody<TArgs>;\n};\n\n/**\n * Wraps one mutation body in the scaffolding above and returns the field it becomes.\n *\n * A field carrying a hook is forced into a transaction even when it would have run straight\n * on `db`: a hook exists to write atomically with the mutation, and one that ran outside the\n * transaction could not roll anything back.\n */\nexport const writeResolver = <TArgs = any>({\n db,\n tableName,\n operation,\n single,\n fieldName,\n args: queryArgs,\n txCtx,\n policies,\n run,\n}: WriteResolverSpec<TArgs>): CreatedResolver => {\n const hooks = policies?.onWrite?.(tableName, operation);\n const errorCtx: DrizzleErrorContext = { table: tableName, operation, field: fieldName };\n\n return {\n name: fieldName,\n resolver: async (_source, args: TArgs, context, info) => {\n try {\n return await runMutation(\n db,\n context,\n info,\n txCtx,\n (executor) => {\n const payload = { table: tableName, operation, single, args, context, info, tx: executor };\n // Per request: which keys `returning` added is a function of this request's selection.\n let added: string[] | undefined;\n return run({\n executor,\n args,\n context,\n info,\n before: () => runWriteHook(hooks, 'before', payload),\n after: (rows) => runWriteHook(hooks, 'after', { ...payload, rows: rows ?? [] }),\n returning: (columns) => {\n const withHook = withHookColumns(hooks, columns);\n added = withHook.added;\n return withHook.returning;\n },\n output: (rows) => omitHookColumns(rows, added),\n });\n },\n !!hooks,\n );\n } catch (e) {\n throw withErrorContext(toGraphQLError(e), errorCtx);\n }\n },\n args: queryArgs,\n };\n};\n","// Pieces the generated mutations share: the relation columns a write has to prepare, the batch\n// update's input type, the filters a write requires, and the write-count return type.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { getColumns, type SQL, sql } from 'drizzle-orm';\nimport type { GraphQLFieldConfigArgumentMap } from 'graphql';\nimport { GraphQLBoolean, GraphQLInputObjectType, GraphQLNonNull } from 'graphql';\nimport { capitalize } from '../../case-ops/index.ts';\nimport type { ResolveTree } from '../../parse-resolve-info.ts';\nimport { parseResolveInfo } from '../../parse-resolve-info.ts';\nimport { remapUpdateInput } from '../field-updates.ts';\n// Type-only: the nested-write module imports this one at runtime, so the dependency has to\n// stay one-directional. The implementation is injected by the dialect builder.\nimport type { NestedWriteRuntime } from '../nested-writes.ts';\nimport type { CreatedResolver, Filters, ProcessedTableSelectArgs, TableNamedRelations } from '../types.ts';\nimport { drizzleError } from './errors.ts';\nimport { withPrimaryKeyColumns } from './keys.ts';\nimport type { DefaultOrderByFor, LimitPolicyFor } from './limits.ts';\nimport type { TypeNameMapper } from './naming.ts';\nimport { resolveObjectTypeName } from './naming.ts';\nimport type { DeletedMode, ResolverPolicies, ScopeResolver } from './policies.ts';\nimport { stripContextValues, withScope } from './policies.ts';\nimport type { RelationFilterBase, RelationFilterContext } from './relation-filters.ts';\nimport { extractFilters, relationFilterCtx } from './relation-filters.ts';\nimport { extractRelationsParams } from './relation-params.ts';\nimport { eagerLoadMutationRelations } from './select-runtime.ts';\nimport { extractSelectedColumnsFromTreeSQLFormat } from './selected-columns.ts';\nimport type { MutationTxCtx } from './transactions.ts';\nimport type { TypeCacheCtx } from './type-cache.ts';\nimport type { TypeNameResolver } from './type-names.ts';\nimport { writeResolver } from './write-scaffold.ts';\n\n/**\n * The `hard` argument on the delete mutations of a soft-deleting table that opted into\n * `hardDelete`. One config shared by every such field — argument configs carry no per-field\n * state — and generated nowhere else, so the schema says which tables can be purged.\n */\nexport const hardDeleteArg = {\n type: GraphQLBoolean,\n defaultValue: false,\n description:\n 'Remove the matched rows instead of marking them deleted. Reads at `INCLUDE`, so it reaches rows that are already marked; a `scope` still confines what it can reach.',\n} as const;\n\n/**\n * Computes the RETURNING columns and relation selection for a mutation resolver: extracts\n * the selected scalar columns, determines whether any relations were selected, and only\n * then forces the primary key into the column set (so the post-mutation eager-load can\n * re-key rows). Returns everything the resolver needs to decide whether to eager-load.\n */\nexport interface PrepareMutationRelationColumnsParams {\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n tables: Record<string, Table>;\n tableName: string;\n typeName: string;\n typeNameMapper: TypeNameMapper | undefined;\n table: Table;\n pkNames: readonly string[];\n parsedInfo: ResolveTree;\n limits?: LimitPolicyFor;\n scope?: ScopeResolver;\n defaultOrderBy?: DefaultOrderByFor;\n /** The build's type-naming rule — the selection tree is keyed by the name it produced. */\n resolveName?: TypeNameResolver;\n}\n\nexport const prepareMutationRelationColumns = (\n params: PrepareMutationRelationColumnsParams,\n): {\n columns: Record<string, Column>;\n hasRelations: boolean;\n withParams: Record<string, Partial<ProcessedTableSelectArgs>> | undefined;\n} => {\n const { relationMap, tables, tableName, typeNameMapper, table, pkNames, parsedInfo, resolveName } = params;\n const typeName = resolveObjectTypeName(tableName, typeNameMapper, resolveName);\n const withParams = relationMap[tableName]\n ? extractRelationsParams(relationMap, tables, tableName, parsedInfo, typeName, {\n typeNameMapper,\n limits: params.limits,\n scope: params.scope,\n defaultOrderBy: params.defaultOrderBy,\n resolveName,\n })\n : undefined;\n const hasRelations = !!(withParams && Object.keys(withParams).length);\n const baseColumns = extractSelectedColumnsFromTreeSQLFormat(parsedInfo.fieldsByTypeName[typeName]!, table, {\n tableName,\n relationMap,\n tables,\n });\n const columns = hasRelations ? withPrimaryKeyColumns(baseColumns, table, pkNames) : baseColumns;\n return { columns, hasRelations, withParams };\n};\n\n/**\n * The prologue every write resolver runs: parse the resolve info, then work out the columns\n * to return and the relations to eager-load from it. `parsedInfo` comes back too — the delete\n * resolver reads its own columns off the tree rather than taking the prepared set.\n */\nexport const mutationSelection = (\n info: any,\n params: Omit<PrepareMutationRelationColumnsParams, 'parsedInfo'>,\n): {\n parsedInfo: ResolveTree;\n columns: Record<string, Column>;\n hasRelations: boolean;\n withParams: Record<string, Partial<ProcessedTableSelectArgs>> | undefined;\n} => {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n return { parsedInfo, ...prepareMutationRelationColumns({ ...params, parsedInfo }) };\n};\n\n/**\n * The `where` a write runs under: the caller's filters — required when the mutation refuses to\n * run unbounded — with the row scope ANDed on last, so a supplied filter can only narrow the\n * scope and never widen it. An out-of-scope row is simply not matched.\n *\n * `deleted` states which soft-delete mode the match reads at, for the writes that need one:\n * `restore` sees only marked rows, a hard delete has to see them too.\n */\nexport const scopedWhere = <TTable extends Table>(params: {\n scope: ScopeResolver | undefined;\n tableName: string;\n table: TTable;\n where: Filters<TTable> | undefined;\n relationCtx?: RelationFilterContext;\n /** The single-row writes always require a `where`; the plural ones do under `requireWhere`. */\n required?: boolean;\n deleted?: DeletedMode;\n}): SQL | undefined => {\n const { scope, tableName, table, where, relationCtx, required, deleted } = params;\n return withScope(\n scope,\n tableName,\n table,\n required\n ? extractRequiredFilters(table, tableName, where, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined,\n deleted,\n );\n};\n\n/**\n * The epilogue: the written rows with their selected relations attached, or the rows as they\n * came back when the selection asked for no relation at all.\n */\nexport const withEagerRelations = (\n executor: any,\n tableName: string,\n rows: any[],\n pkNames: readonly string[],\n withParams: Record<string, Partial<ProcessedTableSelectArgs>> | undefined,\n hasRelations: boolean,\n): Promise<any[]> | any[] =>\n hasRelations ? eagerLoadMutationRelations(executor, tableName, rows, pkNames, withParams) : rows;\n\n/**\n * The per-entry input of `update<Table>Many`: `{ where, set }`, reusing the table's\n * update `set` input and filter input. Shared by all three dialect builders.\n */\nexport const generateUpdateManyInput = (params: {\n tableName: string;\n typeName: string;\n updatePrefix: string;\n updateInput: GraphQLInputObjectType;\n tableFilters: GraphQLInputObjectType;\n cacheCtx: TypeCacheCtx;\n}): GraphQLInputObjectType => {\n const { tableName, typeName, updatePrefix, updateInput, tableFilters, cacheCtx } = params;\n return new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'updateManyInput',\n defaultName: `${capitalize(updatePrefix)}${typeName}ManyInput`,\n table: tableName,\n }),\n description: `One entry of a batch update of ${typeName}: the rows \\`where\\` matches get this entry's \\`set\\` applied.`,\n fields: {\n where: {\n type: tableFilters,\n description: 'Rows this entry updates. An omitted filter updates every row.',\n },\n set: {\n type: new GraphQLNonNull(updateInput),\n },\n },\n });\n};\n\n/**\n * Extracts a `where` argument that a mutation refuses to run without: missing, or present\n * but matching every row (e.g. `where: {}` or filters that all collapse to nothing), both\n * throw instead of becoming an unbounded write. Used by the `Single` write variants always\n * and by the plural update/delete mutations when `features.requireWhere` is on.\n */\nexport const extractRequiredFilters = <TTable extends Table>(\n table: TTable,\n tableName: string,\n where: Filters<TTable> | undefined,\n relationCtx?: RelationFilterContext,\n): SQL => {\n const filters = where ? extractFilters(table, tableName, where, relationCtx) : undefined;\n if (!filters) {\n throw drizzleError(\n \"A 'where' argument with at least one filter is required — this mutation does not run unbounded.\",\n { code: 'DRIZZLE_WHERE_REQUIRED' },\n );\n }\n return filters;\n};\n\n/**\n * How many rows a returnless write reported affecting. The three dialects' drivers each\n * spell it differently — `rowCount` (node-postgres, Neon), `affectedRows` (PGlite, and MySQL\n * on its result header), `count` (postgres.js), `rowsAffected` (libsql), `changes`\n * (better-sqlite3) — and none of them is reachable through a common drizzle type, so the\n * shape is probed rather than declared.\n *\n * Only the result object itself is read, plus `affectedRows` one level in, since MySQL\n * returns `[header, fields]`. A row of the table is never inspected, so a table with a\n * column named `count` cannot be mistaken for a count.\n */\nexport const rowsAffected = (result: any): number => {\n const asNumber = (value: unknown): number | undefined =>\n typeof value === 'number' ? value : typeof value === 'bigint' ? Number(value) : undefined;\n\n if (result && typeof result === 'object') {\n for (const key of ['rowCount', 'affectedRows', 'rowsAffected', 'changes', 'count']) {\n const value = asNumber((result as any)[key]);\n if (value !== undefined) {\n return value;\n }\n }\n const header = Array.isArray(result) ? result[0] : undefined;\n const affected = header && typeof header === 'object' ? asNumber(header.affectedRows) : undefined;\n if (affected !== undefined) {\n return affected;\n }\n }\n\n throw drizzleError('The driver did not report how many rows the write affected.', {\n code: 'DRIZZLE_ROW_COUNT_UNAVAILABLE',\n });\n};\n\n/**\n * Guard for the `Single` write variants: throws before anything is written when `where`\n * matches more than one row, so a multi-row update/delete never executes. Probed with a\n * `LIMIT 2` select rather than a count so the check stays cheap on large matches.\n */\nexport const assertSingleMatch = async (executor: any, table: Table, filters: SQL): Promise<void> => {\n const matched = await executor.select({ found: sql`1` }).from(table).where(filters).limit(2);\n if (matched.length > 1) {\n throw drizzleError(\"'where' matched more than one row — nothing was written!\", {\n code: 'DRIZZLE_MULTI_ROW_MATCH',\n });\n }\n};\n\n/**\n * `update<Tables>Count` / `delete<Tables>Count` — the plural write without the payload\n * (`features.countMutations`).\n *\n * The plural `update` and `delete` always `RETURNING *`, which is the wrong shape for\n * \"archive everything older than a year\": the caller pays to ship rows it does not want, and\n * on a large match that cost is the whole mutation. These return `Int!` instead — how many\n * rows the write touched.\n *\n * Leaving the payload off changes nothing else: the write obeys every rule of the plural\n * mutation it mirrors, through the same {@link writeResolver} scaffolding.\n *\n * - `scope` (and the soft-delete marker) is ANDed into the `where`, so only rows the plural\n * write could reach are counted and written.\n * - On a soft-deleting table the delete is the marking `UPDATE`, not a `DELETE`, and rows that\n * are already marked are not matched; the update skips marked rows too. `hard: true` exists\n * exactly where the plural delete takes it.\n * - Context-derived columns are stripped from the update's `set`, as the plural update does.\n * - `onWrite` hooks run `before` and `after`, inside a transaction. The `after` hook is handed\n * rows, so a table with one pays for a `RETURNING` — of the columns the hook names in\n * `columns`, or of the primary key when it names none (the whole row on a table without a\n * key) — and the count is the number of rows returned. Every other write, and every write on\n * MySQL (no `RETURNING`; its hooks see `rows: []` as on every MySQL mutation), skips the\n * `RETURNING` and reads the count off the driver's result via {@link rowsAffected}.\n */\nexport const generateWriteCount = ({\n db,\n tableName,\n table,\n kind,\n setArgs,\n filterArgs,\n fieldName,\n requireWhere,\n filterCtx,\n txCtx,\n nested,\n policies,\n pkNames = [],\n returnsRows,\n}: {\n db: any;\n tableName: string;\n table: Table;\n kind: 'update' | 'delete';\n /** The update `set` input; omitted for the delete variant, which has nothing to set. */\n setArgs?: GraphQLInputObjectType;\n filterArgs: GraphQLInputObjectType;\n fieldName: string;\n requireWhere: boolean;\n filterCtx?: RelationFilterBase;\n txCtx?: MutationTxCtx;\n nested?: NestedWriteRuntime;\n policies?: ResolverPolicies;\n /** The table's primary-key property names: what an `after` hook that named no columns gets. */\n pkNames?: readonly string[];\n /** Whether the dialect has `RETURNING` (false on MySQL), which an `after` hook's rows need. */\n returnsRows: boolean;\n}): CreatedResolver => {\n const softDelete = kind === 'delete' ? policies?.softDelete?.(tableName) : undefined;\n // The plural delete's rule: only a soft-deleting table that opted in can purge.\n const canHardDelete = softDelete?.hardDelete === true;\n const queryArgs = {\n ...(setArgs ? { set: { type: new GraphQLNonNull(setArgs) } } : {}),\n where: {\n type: requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n ...(canHardDelete ? { hard: hardDeleteArg } : {}),\n } as GraphQLFieldConfigArgumentMap;\n\n // Only an `after` hook is handed rows, so only a table with one gives up the returnless write.\n const readsRows = returnsRows && !!policies?.onWrite?.(tableName, kind)?.after;\n // What the `after` hook's rows carry when it named no `columns`: the key, which identifies\n // each written row without shipping the rest of it — or the whole row when there is no key.\n const allColumns = getColumns(table) as Record<string, Column>;\n const keyColumns: Record<string, Column> = pkNames.length\n ? Object.fromEntries(pkNames.map((name) => [name, allColumns[name]!]))\n : allColumns;\n\n return writeResolver<{ where?: Filters<Table>; set?: Record<string, any>; hard?: boolean }>({\n db,\n tableName,\n operation: kind,\n single: false,\n fieldName,\n txCtx,\n policies,\n args: queryArgs,\n run: async ({ executor, args, context, before, after, returning }) => {\n const { where, set } = args;\n // `canHardDelete` decides whether the argument exists; this decides what it does, so a\n // stitched-in `hard: true` on a table that never opted in stays a soft delete.\n const hard = canHardDelete && args.hard === true;\n const scope = policies?.scope?.(context);\n await before();\n\n let query: any;\n if (kind === 'delete') {\n query =\n softDelete && !hard\n ? executor.update(table).set({ [softDelete.columnName]: softDelete.writeDeleted() })\n : executor.delete(table);\n } else {\n // Nested writes need the parent rows they attach to, which is exactly what this\n // mutation exists not to fetch — so they are refused rather than silently dropped.\n const entry = nested?.enabled(tableName) ? nested.split(tableName, set!) : undefined;\n if (entry && nested!.hasOps(entry.ops)) {\n throw drizzleError(\n 'This mutation does not support nested writes — use the one that returns the rows instead.',\n { code: 'DRIZZLE_NESTED_WRITES_UNSUPPORTED' },\n );\n }\n // A context-derived column is the server's to set, so an update never reassigns one.\n const values = stripContextValues(\n remapUpdateInput(entry ? entry.columns : set!, table, tableName),\n policies?.contextValues?.(tableName),\n );\n if (!Object.keys(values).length) {\n throw drizzleError('Unable to update with no values specified!', {\n code: 'DRIZZLE_NO_VALUES',\n });\n }\n query = executor.update(table).set(values);\n }\n\n // The scope — and on a soft-deleting table the not-yet-marked predicate — is ANDed on\n // last, so a caller's `where` can only narrow what the write reaches.\n const filters = scopedWhere({\n scope,\n tableName,\n table,\n where,\n relationCtx: relationFilterCtx(filterCtx, tableName),\n required: requireWhere,\n // A hard delete reads at INCLUDE, so it reaches the rows that are already marked.\n deleted: hard ? 'INCLUDE' : undefined,\n });\n if (filters) {\n query = query.where(filters);\n }\n\n if (!readsRows) {\n const result = await query;\n await after();\n return rowsAffected(result);\n }\n\n // The client selected nothing, so the rows hold only what the hook asked for.\n const named = returning({});\n const rows = (await query.returning(Object.keys(named).length ? named : keyColumns)) as any[];\n await after(rows);\n return rows.length;\n },\n });\n};\n","const DRIZZLE_LOADERS_KEY = Symbol('drizzle-graphql-loaders');\nconst DRIZZLE_REQUEST_CACHE_KEY = Symbol('drizzle-graphql-request-cache');\n\ntype BatchFn<K, V> = (keys: readonly K[]) => Promise<readonly V[]>;\n\nclass BatchLoader<K, V> {\n private batch: Array<{ key: K; resolve: (v: V) => void; reject: (e: unknown) => void }> = [];\n private scheduled = false;\n\n constructor(private readonly batchFn: BatchFn<K, V>) {}\n\n load(key: K): Promise<V> {\n return new Promise<V>((resolve, reject) => {\n this.batch.push({ key, resolve, reject });\n if (!this.scheduled) {\n this.scheduled = true;\n Promise.resolve().then(() => this.dispatch());\n }\n });\n }\n\n private async dispatch(): Promise<void> {\n const current = this.batch.splice(0);\n this.scheduled = false;\n try {\n const results = await this.batchFn(current.map(({ key }) => key));\n for (let i = 0; i < current.length; i++) {\n current[i]!.resolve(results[i] as V);\n }\n } catch (err) {\n for (const { reject } of current) {\n reject(err);\n }\n }\n }\n}\n\n/**\n * Returns a BatchLoader keyed by `key` on the GraphQL context object.\n * Loaders are stored under a Symbol so they never collide with consumer properties.\n * If context is absent or not an object, a fresh (unbatched) loader is returned.\n */\nexport const getOrCreateLoader = <K, V>(context: any, key: string, batchFn: BatchFn<K, V>): BatchLoader<K, V> => {\n if (!context || typeof context !== 'object') {\n return new BatchLoader<K, V>(batchFn);\n }\n if (!context[DRIZZLE_LOADERS_KEY]) {\n context[DRIZZLE_LOADERS_KEY] = new Map<string, BatchLoader<any, any>>();\n }\n const loaders = context[DRIZZLE_LOADERS_KEY] as Map<string, BatchLoader<any, any>>;\n if (!loaders.has(key)) {\n loaders.set(key, new BatchLoader<K, V>(batchFn));\n }\n return loaders.get(key) as BatchLoader<K, V>;\n};\n\n/**\n * Memoizes a value that a resolver derives from its own field — its args and its selection —\n * for the length of one request. Resolvers run once per parent row, so anything derived only\n * from the field is otherwise recomputed for every row of a batch.\n *\n * The cache lives on the context (weakly keyed by the AST node the value is derived from, so a\n * document cached across requests never carries values between them) and `key` separates fields\n * that share a node: one fragment selection can resolve for more than one parent type. Without a\n * context object there is nowhere request-scoped to cache, so the value is simply computed.\n *\n * `compute` must not read the parent row.\n */\nexport const getOrCreateRequestValue = <T>(\n context: any,\n node: object | undefined,\n key: string,\n compute: () => T,\n): T => {\n if (!context || typeof context !== 'object' || !node || typeof node !== 'object') {\n return compute();\n }\n if (!context[DRIZZLE_REQUEST_CACHE_KEY]) {\n context[DRIZZLE_REQUEST_CACHE_KEY] = new WeakMap<object, Map<string, unknown>>();\n }\n const cache = context[DRIZZLE_REQUEST_CACHE_KEY] as WeakMap<object, Map<string, unknown>>;\n let entries = cache.get(node);\n if (!entries) {\n entries = new Map<string, unknown>();\n cache.set(node, entries);\n }\n if (entries.has(key)) {\n return entries.get(key) as T;\n }\n const value = compute();\n entries.set(key, value);\n return value;\n};\n","/**\n * The identity a generated field publishes about itself, under `extensions.drizzle`.\n *\n * Every field this library generates carries one, so a wrapper — `graphql-middleware`,\n * envelop, `graphql-shield`, an audit log, a cache invalidator — can ask the schema what a\n * field is instead of reverse-engineering its name. Names are configurable (`prefixes`,\n * `suffixes`, `typeNameMapper`), so name parsing is ambiguous by construction; this is not.\n *\n * This shape is stable API: fields are only ever added to it, never removed or repurposed.\n */\n\n/** What family of field this is. */\nexport type DrizzleFieldKind = 'query' | 'mutation' | 'relation' | 'aggregate' | 'type';\n\n/**\n * What the field does. Arity is carried separately by `single`, so `select` covers both\n * the list query and its `…Single` sibling rather than being spelled twice.\n */\nexport type DrizzleFieldOperation =\n | 'select'\n | 'insert'\n | 'update'\n | 'updateMany'\n | 'upsert'\n | 'delete'\n | 'restore'\n | 'aggregate'\n | 'groupBy'\n | 'relation'\n | 'relationAggregate';\n\n/** The argument holding the rows a field is about, when it has one. */\nexport type DrizzleTargetArg = 'where' | 'values' | 'updates';\n\n/** `extensions.drizzle` on a generated field. */\nexport type DrizzleFieldExtension = {\n /** The Drizzle schema key of the table the field reads or writes. */\n table: string;\n kind: Exclude<DrizzleFieldKind, 'type'>;\n operation: DrizzleFieldOperation;\n /** Whether the field resolves to one row (or one aggregate) rather than a list. */\n single: boolean;\n /**\n * Which argument names the rows: `where` for select/update/delete/aggregate, `values`\n * for insert and upsert, `updates` for the batch update's per-entry `{ where, set }`.\n * Absent when the field takes no such argument.\n */\n targetArg?: DrizzleTargetArg;\n /**\n * Primary-key property names of `table`, in schema order. Empty when the table declares\n * no primary key. Carried here so {@link identifyRows} works from the field alone.\n */\n primaryKey: readonly string[];\n /**\n * For `operation: 'delete'` on a soft-deleting table that opted into `hardDelete`: the\n * field takes a `hard` argument that issues a real `DELETE` rather than writing the marker.\n * Absent everywhere else, so a wrapper can gate purging without parsing arguments.\n */\n hardDelete?: boolean;\n /**\n * `true` on the count mutations (`update<Table>Count` / `delete<Table>Count`,\n * `features.countMutations`): the field writes like its plural `update` / `delete` sibling\n * — same `operation`, same rows — but resolves to how many rows it wrote (`Int!`) rather\n * than to the rows. Absent everywhere else.\n */\n count?: boolean;\n /** For `kind: 'relation'` and `operation: 'relationAggregate'`: the relation's name. */\n relation?: string;\n /** For `kind: 'relation'` and `operation: 'relationAggregate'`: the table it hangs off. */\n parentTable?: string;\n};\n\n/** `extensions.drizzle` on a generated object type. */\nexport type DrizzleTypeExtension = {\n /** The Drizzle schema key this type was generated from. */\n table: string;\n kind: 'type';\n /** Primary-key property names of `table`, in schema order. Empty when there is none. */\n primaryKey: readonly string[];\n};\n\nexport type DrizzleExtension = DrizzleFieldExtension | DrizzleTypeExtension;\n\n/** Anything carrying GraphQL `extensions` — a field config, a field, or a named type. */\ntype WithExtensions = { extensions?: { drizzle?: unknown } | null } | null | undefined;\n\n/**\n * Reads the `drizzle` extension off a field or type, typed. Returns `undefined` for\n * anything this library did not generate, which is the check a wrapper wants before it\n * treats a field as one of ours.\n */\nexport const drizzleExtension = (target: WithExtensions): DrizzleExtension | undefined => {\n const value = target?.extensions?.drizzle;\n return value && typeof value === 'object' ? (value as DrizzleExtension) : undefined;\n};\n\n/** Narrows to the field form — object types carry `kind: 'type'` and no operation. */\nexport const isDrizzleFieldExtension = (value: DrizzleExtension | undefined): value is DrizzleFieldExtension =>\n !!value && value.kind !== 'type';\n\n/**\n * Builds the extension for one table's fields. Dialect builders make one per table so each\n * call site only states what differs.\n */\nexport const tableFieldExtensions =\n (table: string, primaryKey: readonly string[]) =>\n (meta: Omit<DrizzleFieldExtension, 'table' | 'primaryKey'>): DrizzleFieldExtension => ({\n table,\n primaryKey,\n ...meta,\n });\n\n/**\n * One table's bound extension builder — what {@link tableFieldExtensions} returns. Named so\n * the shared build helpers can take one without restating the signature.\n */\nexport type TableFieldExtensionFactory = ReturnType<typeof tableFieldExtensions>;\n\n/**\n * The parts of a mutation's identity that differ between mutations. Dialect builders that\n * assign every mutation in one loop pair each generated mutation with one of these.\n */\nexport type DrizzleMutationMeta = Pick<\n DrizzleFieldExtension,\n 'operation' | 'single' | 'targetArg' | 'hardDelete' | 'count'\n>;\n\n/** Builds the extension a generated object type carries. */\nexport const tableTypeExtension = (table: string, primaryKey: readonly string[]): DrizzleTypeExtension => ({\n table,\n kind: 'type',\n primaryKey,\n});\n\n/**\n * Builds the extension a relation field carries. `table` is the relation's *target* — the\n * table the field resolves rows of — while `parentTable` is the type the field hangs off,\n * so a wrapper can tell `Users.posts` from `Customers.posts`.\n */\nexport const relationFieldExtension = (params: {\n targetTable: string;\n parentTable: string;\n relation: string;\n single: boolean;\n primaryKey: readonly string[];\n aggregate?: boolean;\n}): DrizzleFieldExtension => ({\n table: params.targetTable,\n kind: params.aggregate ? 'aggregate' : 'relation',\n operation: params.aggregate ? 'relationAggregate' : 'relation',\n // An aggregate over a to-many relation still resolves to a single aggregate object.\n single: params.aggregate ? true : params.single,\n targetArg: 'where',\n primaryKey: params.primaryKey,\n relation: params.relation,\n parentTable: params.parentTable,\n});\n\n/** The rows a field's arguments name. */\nexport type IdentifiedRows = {\n /** The Drizzle schema key of the table being read or written. */\n table: string;\n /** Primary-key property names, in schema order. */\n primaryKey: readonly string[];\n /** One entry per identified row: the primary-key values, keyed by property name. */\n rows: Record<string, unknown>[];\n /**\n * Whether `rows` is exactly the set the operation affects.\n *\n * `false` means the arguments do not pin the rows down — an insert whose key the\n * database generates, a `where` that filters on something other than the primary key,\n * a plural update with no filter at all, or a table with no primary key. `rows` is then\n * a best-effort subset-free superset: every entry in it is a row the key values name,\n * but other filters may narrow the real set further, and it may be empty.\n */\n complete: boolean;\n};\n\n/** Pulls the primary-key values out of one `values` entry; `undefined` if any are missing. */\nconst keyFromValues = (entry: unknown, primaryKey: readonly string[]): Record<string, unknown> | undefined => {\n if (!entry || typeof entry !== 'object') {\n return undefined;\n }\n const row: Record<string, unknown> = {};\n for (const column of primaryKey) {\n const value = (entry as Record<string, unknown>)[column];\n if (value === undefined || value === null) {\n return undefined;\n }\n row[column] = value;\n }\n return row;\n};\n\n/**\n * Pulls primary-key values out of a filter argument.\n *\n * Only top-level equality counts: `{ id: { eq } }` names one row, `{ id: { inArray } }`\n * names a list, and a composite key needs `eq` on every one of its columns. A boolean\n * group (`OR` / `AND` / `NOT`) or any other operator on a key column means the filter is\n * not a key lookup, and the rows are reported as not identified.\n */\nconst keysFromWhere = (\n where: unknown,\n primaryKey: readonly string[],\n): { rows: Record<string, unknown>[]; complete: boolean } => {\n const none = { rows: [], complete: false };\n if (!where || typeof where !== 'object' || Array.isArray(where)) {\n return none;\n }\n const filters = where as { OR?: unknown; AND?: unknown; NOT?: unknown; [column: string]: any };\n if (filters.OR || filters.AND || filters.NOT) {\n return none;\n }\n\n // A composite key is only pinned by an equality on each of its columns — one column\n // carrying a list would describe a rectangle of key tuples, not the rows written.\n if (primaryKey.length > 1) {\n const row: Record<string, unknown> = {};\n for (const column of primaryKey) {\n const operators = filters[column];\n if (!operators || typeof operators !== 'object' || operators.eq === undefined) {\n return none;\n }\n row[column] = operators.eq;\n }\n // Filters beyond the key can only narrow further, so the key alone is not the answer.\n return { rows: [row], complete: Object.keys(filters).length === primaryKey.length };\n }\n\n const column = primaryKey[0];\n if (!column) {\n return none;\n }\n const operators = filters[column];\n if (!operators || typeof operators !== 'object') {\n return none;\n }\n\n const exact = Object.keys(filters).length === 1 && Object.keys(operators).length === 1;\n if (operators.eq !== undefined) {\n return { rows: [{ [column]: operators.eq }], complete: exact };\n }\n if (Array.isArray(operators.inArray)) {\n return { rows: operators.inArray.map((value: unknown) => ({ [column]: value })), complete: exact };\n }\n return none;\n};\n\n/**\n * The rows a generated field's arguments are about, as primary-key values.\n *\n * The row identity of a mutation lives in a different argument for every operation —\n * `where` for update and delete, `values` for insert and upsert, a per-entry `where` inside\n * `updates` for the batch update — and each of those has both a one-row and a many-row\n * spelling. This reads whichever one applies:\n *\n * ```ts\n * const field = info.parentType.getFields()[info.fieldName];\n * const target = identifyRows(field, args);\n * if (target?.complete) await invalidate(target.table, target.rows);\n * ```\n *\n * Returns `undefined` for a field this library did not generate, or an object type. Check\n * `complete` before treating `rows` as the affected set — see {@link IdentifiedRows}.\n */\nexport const identifyRows = (\n field: WithExtensions,\n args: Record<string, unknown> | undefined,\n): IdentifiedRows | undefined => {\n const meta = drizzleExtension(field);\n if (!isDrizzleFieldExtension(meta)) {\n return undefined;\n }\n\n const { table, primaryKey, targetArg } = meta;\n const empty: IdentifiedRows = { table, primaryKey, rows: [], complete: false };\n if (!primaryKey.length || !targetArg) {\n return empty;\n }\n\n const target = args?.[targetArg];\n\n if (targetArg === 'values') {\n // Both spellings of insert/upsert land here: the single variant takes one object.\n const entries = Array.isArray(target) ? target : target === undefined ? [] : [target];\n const rows = entries.map((entry) => keyFromValues(entry, primaryKey));\n return {\n table,\n primaryKey,\n rows: rows.filter((row): row is Record<string, unknown> => !!row),\n // A row whose key the database generates is not identifiable before the write.\n complete: entries.length > 0 && rows.every(Boolean),\n };\n }\n\n if (targetArg === 'updates') {\n if (!Array.isArray(target)) {\n return empty;\n }\n const perEntry = target.map((entry) =>\n keysFromWhere((entry as { where?: unknown } | undefined)?.where, primaryKey),\n );\n return {\n table,\n primaryKey,\n rows: perEntry.flatMap((entry) => entry.rows),\n complete: target.length > 0 && perEntry.every((entry) => entry.complete),\n };\n }\n\n return { table, primaryKey, ...keysFromWhere(target, primaryKey) };\n};\n","// The field resolver every relation gets. It returns what the parent already fetched when the\n// eager path ran, and otherwise batches all sibling calls in the same execution tick into one\n// IN-clause query.\n\nimport type { Column, Table } from 'drizzle-orm';\nimport { and, eq, getColumns, gt, inArray, lte, or, type SQL, sql } from 'drizzle-orm';\nimport { getOrCreateLoader, getOrCreateRequestValue } from '../../batch-loader/index.ts';\nimport { remapToGraphQLArrayOutput } from '../../data-mappers/index.ts';\nimport { relationFieldExtension } from '../../extensions.ts';\nimport type { ResolveTree } from '../../parse-resolve-info.ts';\nimport { parseResolveInfo } from '../../parse-resolve-info.ts';\nimport type { TableNamedRelations } from '../types.ts';\nimport type { CursorOrderEntry, NullOrdering } from './cursor.ts';\nimport {\n attachRowCursors,\n buildCursorCondition,\n cursorOrderExprs,\n cursorOrderingEntries,\n decodeCursor,\n orderByHasRelationEntry,\n selectsCursorField,\n} from './cursor.ts';\nimport { DISTINCT_PARENT, primaryKeyRestriction, selectDistinctKeys } from './distinct.ts';\nimport { type DrizzleErrorContext, drizzleError, toGraphQLError, withErrorContext } from './errors.ts';\nimport { resolveExecutor } from './executor.ts';\nimport { primaryKeyOrderExprs } from './keys.ts';\nimport type { LimitPolicyFor } from './limits.ts';\nimport { applyLimitPolicy, withDefaultOrderBy } from './limits.ts';\nimport { extractOrderBy } from './order-by.ts';\nimport type { TablePolicies } from './policies.ts';\nimport { relationDeletedDefault, resolveScope, withScope } from './policies.ts';\nimport type { RelationFilterBase, RelationFilterContext } from './relation-filters.ts';\nimport { extractFilters, relationFilterCtx } from './relation-filters.ts';\nimport type { RelationResolverFactory } from './relations.ts';\nimport { extractJunctionColumns, extractRelationJoinColumns, relationOwnCondition } from './relations.ts';\nimport { extractSelectedColumnsFromTreeSQLFormat } from './selected-columns.ts';\n\n/**\n * Fetches a to-many relation with per-parent limit/offset for ALL parents in a\n * single query, using a window function (ROW_NUMBER() OVER (PARTITION BY fk ...)).\n *\n * This replaces the previous per-parent fallback that issued one query per parent\n * (true N+1) whenever pagination args were present. Each parent gets its own\n * limit/offset window while the database is hit exactly once for the whole batch.\n *\n * Window functions require PostgreSQL, MySQL >= 8.0, or SQLite >= 3.25.\n * Returns raw rows (NOT remapped); the caller groups + remaps them.\n */\nconst batchedPaginatedRelationQuery = async (\n db: any,\n targetTable: Table,\n foreignCol: Column,\n whereCondition: SQL | undefined,\n orderByArg: any,\n limit: number | null,\n offset: number | null,\n pkNames: readonly string[],\n columns: Record<string, Column> | undefined,\n orderCtx?: RelationFilterContext,\n whereArgs?: Record<string, any>,\n junction?: RelationJunction,\n): Promise<any[]> => {\n const cols = columns ?? getColumns(targetTable);\n\n // Always tiebreak the window by the target's primary key so per-parent limit/offset\n // slices are deterministic even when the client supplies no (or a non-unique) orderBy.\n // pkNames is resolved at build time and includes composite keys.\n const orderExprs = [\n ...(orderByArg ? extractOrderBy(targetTable, orderByArg, orderCtx, whereArgs) : []),\n ...primaryKeyOrderExprs(targetTable, pkNames),\n ];\n const orderClause = orderExprs.length ? sql` order by ${sql.join(orderExprs, sql`, `)}` : sql``;\n // Namespaced alias so it can't collide with a real column on the target table.\n const RN = '__drizzle_graphql_rn';\n // A junction relation partitions by the parent key the junction holds, not the target's own.\n const partitionCol = junction ? junction.sourceCol : foreignCol;\n const rowNumber = sql`row_number() over (partition by ${partitionCol}${orderClause})`.as(RN);\n\n // Subquery: every target column plus a per-partition row number.\n const sub = withJunction(db.select({ ...cols, [RN]: rowNumber }).from(targetTable), junction, foreignCol)\n .where(whereCondition)\n .as('__paginated');\n\n // Outer: keep only the rows that fall inside each parent's window.\n const lower = offset ?? 0;\n const windowConds: any[] = [gt(sub[RN], lower)];\n if (limit != null) {\n windowConds.push(lte(sub[RN], lower + limit));\n }\n\n const rows: any[] = await db\n .select()\n .from(sub)\n .where(and(...windowConds))\n .orderBy(sub[RN]);\n\n // Strip the helper column so it doesn't leak into remapping/output.\n for (const row of rows) {\n delete row[RN];\n }\n return rows;\n};\n\ntype RelationJunction = { table: Table; sourceCol: Column; targetCol: Column };\n\n/**\n * Alias the parent key is selected under when a relation goes through a junction table. The\n * key lives on the junction, not the target, so it has to be selected explicitly to group the\n * rows by parent — and a target row linked to several parents comes back once per parent.\n */\nconst PARENT_KEY = '__drizzle_graphql_parent';\n\n/** `from(target)`, joined to the junction table when the relation has one. */\nconst withJunction = (query: any, junction: RelationJunction | undefined, foreignCol: Column) =>\n junction ? query.innerJoin(junction.table, eq(junction.targetCol, foreignCol)) : query;\n\n/**\n * Creates a RelationResolverFactory that generates field-level resolvers for each relation.\n * Each resolver:\n * 1. Returns pre-fetched data if the parent resolver already included it (eager path, zero cost).\n * 2. When limit/offset args are present, falls back to a direct per-item query.\n * 3. Otherwise batches all sibling resolver calls within the same GraphQL execution tick\n * into a single IN-clause query, eliminating N+1 database round-trips.\n *\n * `nullOrdering` is the dialect's native `ORDER BY` placement for `NULL` — the keyset\n * predicate behind a relation's `after` argument has to match it, or rows with a `NULL` in an\n * ordered column would be skipped instead of paged through. It has no sensible default, so\n * each dialect builder states it: `'nulls-largest'` for PostgreSQL, `'nulls-smallest'` for\n * MySQL and SQLite.\n */\nexport const createRelationResolverFactory =\n (\n db: any,\n tables: Record<string, Table>,\n nullOrdering: NullOrdering,\n filterCtx?: RelationFilterBase,\n limits?: LimitPolicyFor,\n policies?: TablePolicies,\n ): RelationResolverFactory =>\n ({ tableName, relationName, relEntry, isOne }) => {\n const parentTable = tables[tableName];\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n\n if (!parentTable || !targetTable) {\n return undefined;\n }\n\n const joinCols = extractRelationJoinColumns(relEntry, parentTable, targetTable);\n if (!joinCols) {\n return undefined;\n }\n\n const { localColPropName, foreignCol, foreignColPropName } = joinCols;\n // A `.through()` relation keeps the parent key on its junction table: rows are read with\n // the junction joined in and grouped by its source column. `null` is a junction this\n // resolver cannot express (composite keys); the eager path still serves that relation.\n const junction = extractJunctionColumns(relEntry);\n const groupCol = junction ? junction.sourceCol : foreignCol;\n const groupKey = junction ? PARENT_KEY : foreignColPropName;\n // The relation's own `where`, which drizzle applies on the eager path.\n const ownCondition = relationOwnCondition(\n relEntry,\n parentTable,\n targetTable,\n getColumns(parentTable)[localColPropName] as Column,\n groupCol,\n );\n // The mode this field reads its target with when the request passes no `deleted` — see\n // `relationDeletedDefault`. Required to-one relations and `scope: 'root'` tables read\n // marked rows; everything else keeps hiding them.\n const defaultDeleted = relationDeletedDefault(\n policies?.softDelete,\n targetTableName,\n isOne && (relEntry.relation as any)?.optional === false,\n );\n // A relation field is bounded by the policy of the table it reads, not the parent's.\n const limitPolicy = isOne ? undefined : limits?.(targetTableName);\n // Resolved at build time (composite keys included) — used to tiebreak paginated batches.\n const targetPkNames = relEntry.targetPkNames ?? [];\n const errorCtx: DrizzleErrorContext = { table: targetTableName, operation: 'relation', relation: relationName };\n\n /**\n * The columns one batch reads: the ones the selection names, plus the ones the batch needs\n * whatever the client asked for — the key it groups the rows by, and the ordering columns a\n * row cursor is encoded from. Nested relation fields contribute their own join column\n * through the selection context, the same way the root select path narrows.\n *\n * `undefined` means \"every column\", which is what a resolver with no readable resolve info\n * has to fall back to.\n */\n const selectedColumns = (info: any, cursorEntries: CursorOrderEntry[] | undefined) => {\n const parsed = info ? (parseResolveInfo(info) as ResolveTree | undefined) : undefined;\n if (!parsed) {\n return undefined;\n }\n // A relation field returns one object type, but merging every entry costs nothing and\n // keeps this honest if the target is ever reached through an abstract type.\n const tree: Record<string, ResolveTree> = Object.assign({}, ...Object.values(parsed.fieldsByTypeName));\n\n const columns = extractSelectedColumnsFromTreeSQLFormat(tree, targetTable, {\n tableName: targetTableName,\n relationMap: filterCtx?.relationMap ?? {},\n tables,\n allRelations: filterCtx?.relationMap,\n });\n\n const targetColumns = getColumns(targetTable);\n columns[foreignColPropName] = foreignCol;\n for (const [columnName] of cursorEntries ?? []) {\n const column = targetColumns[columnName];\n if (column) {\n columns[columnName] = column;\n }\n }\n return columns;\n };\n\n const resolve = async (parent: any, args: any, context: any, info: any) => {\n // Eager path: the parent resolver pre-fetched this relation via Drizzle's `with`.\n if (parent[relationName] !== undefined) {\n return parent[relationName];\n }\n\n const localValue = parent[localColPropName];\n if (localValue == null) {\n return isOne ? null : [];\n }\n\n const { where: whereArg, limit: requestedLimit, offset, after, deleted } = (args ?? {}) as any;\n\n // Everything below is derived from this field alone — its args and its selection — so it is\n // identical for every parent row the batch fetches. Resolvers run once per parent row, so it\n // is computed once per field per request and reused, rather than re-reading the selection and\n // re-stringifying the loader key N times.\n const { orderByArg, limit, distinct, cursorEntries, cursorValues, columns, loaderKey } = getOrCreateRequestValue(\n context,\n info?.fieldNodes?.[0],\n `relation:${tableName}::${relationName}`,\n () => {\n // A relation field falls back to the *target* table's default ordering, since that is\n // the table it reads. A to-one relation is a single row and takes no ordering at all.\n const orderByArg = isOne\n ? (args as any)?.orderBy\n : withDefaultOrderBy(args ?? {}, targetTableName, policies?.defaultOrderBy).orderBy;\n const limit = applyLimitPolicy(requestedLimit, limitPolicy, errorCtx);\n const distinct = ((args ?? {}) as any).distinct?.length ? ((args ?? {}) as any).distinct : undefined;\n\n // ── keyset (cursor) pagination ──\n // The same rules the root list follows, over the related rows of one parent: the cursor\n // is defined over the request's orderBy plus the target's primary-key tiebreak, and the\n // keyset predicate is a plain condition on the target's own columns — so it filters each\n // parent's rows independently even though the batch fetches them all at once.\n const cursorSelected = !isOne && !!info && selectsCursorField(info, targetTable);\n let cursorEntries: CursorOrderEntry[] | undefined;\n if (!isOne && (after != null || cursorSelected)) {\n if (after != null && distinct) {\n throw drizzleError(\"'after' cannot be combined with 'distinct'.\", { code: 'DRIZZLE_INVALID_CURSOR' });\n }\n if (orderByHasRelationEntry(orderByArg)) {\n if (after != null) {\n throw drizzleError(\n \"'after' cannot be combined with an orderBy that orders through a relation — a related row's value cannot be encoded into a cursor.\",\n { code: 'DRIZZLE_INVALID_CURSOR' },\n );\n }\n // `cursor` was selected under a relation ordering — the field resolves to null.\n } else if (!targetPkNames.length) {\n if (after != null) {\n throw drizzleError(\n `Table ${targetTableName} has no primary key, so cursor pagination cannot be used on it.`,\n { code: 'DRIZZLE_INVALID_CURSOR' },\n );\n }\n // `cursor` was selected but no total order exists — the field resolves to null.\n } else {\n cursorEntries = cursorOrderingEntries(orderByArg, targetPkNames);\n }\n }\n const cursorValues = after != null && cursorEntries ? decodeCursor(after, cursorEntries) : undefined;\n\n const columns = selectedColumns(info, cursorEntries);\n\n // Batch path: collect all sibling calls in this tick and execute one query.\n // Pagination args are part of the loader key so siblings sharing identical\n // args batch together; per-parent limit/offset is applied inside the batch\n // via a window function rather than bailing to a per-parent query (N+1).\n // `cursorEntries` joins the key because it changes the ordering, not just the filter.\n // The column list joins it too: one batch runs one SELECT, so two aliases of the same\n // relation asking for different columns need a batch each.\n const argsKey = JSON.stringify({\n where: whereArg ?? null,\n orderBy: orderByArg ?? null,\n limit: limit ?? null,\n offset: offset ?? null,\n deleted: deleted ?? defaultDeleted ?? null,\n after: after ?? null,\n distinct: distinct ?? null,\n cursor: cursorEntries ? 1 : 0,\n columns: columns ? Object.keys(columns).sort() : null,\n });\n\n return {\n orderByArg,\n limit,\n distinct,\n cursorEntries,\n cursorValues,\n columns,\n loaderKey: `${tableName}::${relationName}::${argsKey}`,\n };\n },\n );\n\n if (junction === null) {\n throw drizzleError(\n `Relation '${tableName}.${relationName}' goes through a junction with a composite key, which can only be loaded together with its parent. Leave it to eager loading (eagerLoadRelations).`,\n { code: 'DRIZZLE_UNSUPPORTED_RELATION' },\n );\n }\n\n const loader = getOrCreateLoader(context, loaderKey, async (parentIds: readonly any[]) => {\n // Loaders are cached per context, so every call batched here shares this request's\n // executor — the transaction on the context, when there is one.\n const executor = resolveExecutor(db, context);\n const uniqueIds = [...new Set(parentIds)];\n // Loaders are keyed per context too, so the scope resolved here is this request's.\n const scope = resolveScope(policies, context, filterCtx);\n let whereCondition = withScope(\n scope,\n targetTableName,\n targetTable,\n and(\n inArray(groupCol, uniqueIds),\n ownCondition,\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n cursorValues ? buildCursorCondition(targetTable, cursorEntries!, cursorValues, nullOrdering) : undefined,\n ),\n deleted ?? defaultDeleted,\n );\n\n if (distinct) {\n // Partitioned by the foreign key as well as the requested columns, so \"one row per\n // distinct value\" means one per parent — `users { posts(distinct: [status]) }` gives\n // each user one post per status, not one post per status across all users. The pass\n // runs first and the batch query is then narrowed to the keys it picked, exactly as\n // the root list does.\n const keys = await selectDistinctKeys({\n db: executor,\n table: targetTable,\n tableName: targetTableName,\n distinct,\n pkNames: targetPkNames,\n where: whereCondition,\n orderBy: orderByArg,\n partitionBy: [groupCol],\n junction: junction\n ? { table: junction.table, on: eq(junction.targetCol, foreignCol), parentKey: groupCol }\n : undefined,\n });\n if (!keys.length) {\n return parentIds.map(() => (isOne ? null : []));\n }\n // Through a junction, a key is kept for one parent and not necessarily another, so the\n // batch is narrowed to (parent, row) pairs rather than to rows.\n whereCondition = and(\n whereCondition,\n junction\n ? or(\n ...keys.map((key) =>\n and(eq(groupCol, key[DISTINCT_PARENT]), primaryKeyRestriction(targetTable, targetPkNames, [key])),\n ),\n )\n : primaryKeyRestriction(targetTable, targetPkNames, keys),\n );\n }\n\n // A junction relation selects the parent key from the junction under its own alias.\n const selection = junction ? { ...(columns ?? getColumns(targetTable)), [PARENT_KEY]: groupCol } : columns;\n\n let rows: any[];\n if (limit != null || offset != null) {\n // Per-parent pagination across the whole batch in one query. Its window ordering is\n // the request's orderBy plus the primary key, which is the cursor's total order too,\n // so a cursor page and a limit/offset page agree on row order.\n rows = await batchedPaginatedRelationQuery(\n executor,\n targetTable,\n foreignCol,\n whereCondition,\n orderByArg,\n limit ?? null,\n offset ?? null,\n targetPkNames,\n selection,\n relationFilterCtx(filterCtx, targetTableName),\n whereArg,\n junction,\n );\n } else {\n // Use plain db.select() so column refs are never aliased — avoids drizzle-orm v1\n // RQB aliasing requirements that would require referencing via aliasedTable proxy.\n let q = withJunction(\n (selection ? executor.select(selection) : executor.select()).from(targetTable),\n junction,\n foreignCol,\n ).where(whereCondition) as any;\n const orderExprs = cursorEntries\n ? cursorOrderExprs(targetTable, cursorEntries)\n : orderByArg\n ? extractOrderBy(targetTable, orderByArg, relationFilterCtx(filterCtx, targetTableName), whereArg)\n : [];\n if (orderExprs.length) {\n q = q.orderBy(...orderExprs);\n }\n rows = await q;\n }\n\n // Before remapping, which rewrites dates and bigints into their transport forms.\n if (cursorEntries) {\n attachRowCursors(rows, cursorEntries);\n }\n\n // Group by parent key before remapping (remapping may delete null fields). A junction\n // relation's key is a helper column, dropped once it has been read.\n const keyOf = (row: any) => {\n const key = String(row[groupKey]);\n if (junction) {\n delete row[PARENT_KEY];\n }\n return key;\n };\n\n if (isOne) {\n const byKey = new Map(rows.map((row: any) => [keyOf(row), row]));\n remapToGraphQLArrayOutput(rows, targetTableName, targetTable);\n return parentIds.map((id) => byKey.get(String(id)) ?? null);\n }\n\n const grouped = new Map<string, any[]>(uniqueIds.map((id) => [String(id), []]));\n for (const row of rows) {\n grouped.get(keyOf(row))?.push(row);\n }\n remapToGraphQLArrayOutput(rows, targetTableName, targetTable);\n return parentIds.map((id) => grouped.get(String(id)) ?? []);\n });\n\n return loader.load(localValue);\n };\n\n // The context goes on here rather than at each throw: everything this resolver leans on —\n // filter compilation, ordering, the cursor — raises coded errors that know nothing about\n // which relation field called them.\n return async (parent, args, context, info) => {\n try {\n return await resolve(parent, args, context, info);\n } catch (e) {\n throw withErrorContext(toGraphQLError(e), errorCtx);\n }\n };\n };\n\n/**\n * The `extensions.drizzle` block for one relation field. The relation entry already carries\n * the target table's primary key (resolved at build time for pagination), so the field can\n * publish it without the dialect's key resolver being reachable from here.\n */\nexport const relationExtensionFor = (\n relEntry: TableNamedRelations,\n parentTable: string,\n relationName: string,\n isOne: boolean,\n aggregate?: boolean,\n) =>\n relationFieldExtension({\n targetTable: relEntry.targetTableName,\n parentTable,\n relation: relationName,\n single: isOne,\n primaryKey: relEntry.targetPkNames ?? [],\n aggregate,\n });\n","// The field names one table's generated resolvers get, after prefixes, suffixes and the\n// type-name mapper have been applied.\n\nimport { capitalize, uncapitalize } from '../../case-ops/index.ts';\nimport type { TypeNameMapper } from './naming.ts';\n\n/** The query and mutation field names one table generates. */\nexport type ResolverFieldNames = {\n typeName: string;\n listFieldName: string;\n singleFieldName: string;\n aggregateFieldName: string;\n groupByFieldName: string;\n createArrayFieldName: string;\n createSingleFieldName: string;\n upsertArrayFieldName: string;\n upsertSingleFieldName: string;\n updateFieldName: string;\n updateManyFieldName: string;\n updateSingleFieldName: string;\n updateCountFieldName: string;\n deleteFieldName: string;\n deleteSingleFieldName: string;\n restoreFieldName: string;\n restoreSingleFieldName: string;\n deleteCountFieldName: string;\n};\n\n/**\n * Derives the generated query/mutation field names for a table from the naming config\n * (typeNameMapper + prefixes/suffixes). Shared by all three dialect builders.\n */\nexport const computeResolverFieldNames = (\n tableName: string,\n typeNameMapper: TypeNameMapper | undefined,\n prefixes: { insert: string; update: string; delete: string; upsert?: string; restore?: string },\n suffixes: { list: string; single: string },\n): ResolverFieldNames => {\n const mapped = typeNameMapper?.(tableName);\n const typeName = mapped ? capitalize(mapped.singular) : capitalize(tableName);\n const listFieldName = (mapped?.plural ?? uncapitalize(tableName)) + suffixes.list;\n const singleFieldName = mapped?.singular ?? uncapitalize(tableName) + suffixes.single;\n const aggregateFieldName = `${mapped?.plural ?? uncapitalize(tableName)}Aggregate`;\n const groupByFieldName = `${mapped?.plural ?? uncapitalize(tableName)}GroupBy`;\n const pluralNoun = mapped ? capitalize(mapped.plural) : capitalize(tableName);\n const singularNoun = mapped ? capitalize(mapped.singular) : capitalize(tableName);\n // The write mutations take the same two suffixes the queries do, and in the same places:\n // `list` on the form that operates on a set of rows, `single` on the one that operates on\n // one. They used to take only `single`, so a build that renamed the list side got\n // `usersAll` on the query and a bare `createUsers` next to it — and, worse, a\n // `{ list: 'All', single: '' }` build silently lost the array insert, because both insert\n // mutations resolved to `createUsers` and the second registration overwrote the first.\n const createArrayFieldName = `${prefixes.insert}${pluralNoun}${suffixes.list}`;\n const createSingleFieldName = mapped\n ? `${prefixes.insert}${capitalize(mapped.singular)}`\n : `${prefixes.insert}${capitalize(tableName)}${suffixes.single}`;\n const upsertPrefix = prefixes.upsert ?? 'upsert';\n const upsertArrayFieldName = `${upsertPrefix}${pluralNoun}${suffixes.list}`;\n const upsertSingleFieldName = mapped\n ? `${upsertPrefix}${capitalize(mapped.singular)}`\n : `${upsertPrefix}${capitalize(tableName)}${suffixes.single}`;\n const restorePrefix = prefixes.restore ?? 'restore';\n // update/delete/restore are named the way create and upsert are: the plural noun on the\n // form that operates on a set of rows, the singular noun on the one that operates on one.\n // They used to put the *singular* noun on the list form — they filter rather than\n // enumerate — which read as a single-row operation and was not one (`deleteUser(where:)`\n // deleting every match), and which left the one-row variant no name but `Single` even\n // under a mapper whose singular/plural pair had already separated every other operation.\n const updateFieldName = `${prefixes.update}${pluralNoun}${suffixes.list}`;\n // The batch variant is plural like the array insert/upsert, with an explicit `Many`\n // suffix so it never collides with the single-set update.\n const updateManyFieldName = `${prefixes.update}${pluralNoun}Many`;\n const deleteFieldName = `${prefixes.delete}${pluralNoun}${suffixes.list}`;\n // The soft-delete counterpart, named the same way so `deleteUsers` / `restoreUsers` and\n // `deleteUser` / `restoreUser` read as pairs however the prefixes and suffixes are set.\n const restoreFieldName = `${restorePrefix}${pluralNoun}${suffixes.list}`;\n // With a mapper the singular noun is separation enough, exactly as it is for the single\n // query and the single insert, so those take no suffix at all. Without one both nouns are\n // the table key and `suffixes.single` is what separates the pair — the same string the\n // single query is separated by, so a build where it cannot separate them has already\n // failed on the queries (or, with no mapper at all, on the suffix check in `buildSchema`)\n // before reaching here. These used to carry a 'Single' fallback for that case; it was\n // unreachable once the list forms above stopped taking the singular noun.\n const singleWrite = (prefix: string) =>\n mapped ? `${prefix}${singularNoun}` : `${prefix}${singularNoun}${suffixes.single}`;\n const updateSingleFieldName = singleWrite(prefixes.update);\n const deleteSingleFieldName = singleWrite(prefixes.delete);\n const restoreSingleFieldName = singleWrite(restorePrefix);\n // The count variants are the plural write under another name, so they take the plural\n // noun the plural writes take. Their explicit `Count` is the disambiguator, so they take\n // no configured suffix.\n const updateCountFieldName = `${prefixes.update}${pluralNoun}Count`;\n const deleteCountFieldName = `${prefixes.delete}${pluralNoun}Count`;\n return {\n typeName,\n listFieldName,\n singleFieldName,\n aggregateFieldName,\n groupByFieldName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n updateManyFieldName,\n updateSingleFieldName,\n updateCountFieldName,\n deleteFieldName,\n deleteSingleFieldName,\n restoreFieldName,\n restoreSingleFieldName,\n deleteCountFieldName,\n };\n};\n","// Registration of the generated root fields, with the collision check that the naming\n// config cannot do for itself.\n\nimport type { GraphQLFieldConfig } from 'graphql';\n\n/**\n * Registers one generated root field, refusing to overwrite a name already taken.\n *\n * A generated name is the table name run through `typeNameMapper`, a prefix and a suffix,\n * and the pluralization each operation applies — so whether two operations collide is a\n * property of the finished names, not of any one piece of the config. `buildSchema` checks\n * what it can up front (identical list and single suffixes with no mapper), but that check\n * compares the suffix *strings*, which cannot see a collision the rest of the naming rules\n * produce: `{ list: 'All', single: '' }` used to give both insert mutations the name\n * `createUsers`, and the array insert simply disappeared from the schema.\n *\n * Assigning into the record silently kept the last registration. Throwing here means a\n * naming config that cannot work says so at build time, naming the field it lost.\n */\nexport const defineRootField = (\n fields: Record<string, GraphQLFieldConfig<any, any>>,\n kind: 'query' | 'mutation',\n name: string,\n config: GraphQLFieldConfig<any, any>,\n): void => {\n if (Object.getOwnPropertyDescriptor(fields, name) !== undefined) {\n throw new Error(\n `Drizzle-GraphQL Error: two generated ${kind} fields are both named '${name}'. Generated names come from the table name plus config.prefixes, config.suffixes and config.typeNameMapper — some combination of those gives two operations the same name. Adjust one of them so each operation gets its own.`,\n );\n }\n\n fields[name] = config;\n};\n","// The per-table input types — Filters, OrderBy, and the select field map — each cached so a\n// schema builds one of them per table no matter how many fields reference it.\n\nimport type { Table } from 'drizzle-orm';\nimport { is, One } from 'drizzle-orm';\nimport { GraphQLInputObjectType, GraphQLList, GraphQLNonNull, GraphQLString } from 'graphql';\nimport { drizzleColumnToGraphQLType } from '../../type-converter/index.ts';\nimport type { ConvertedColumn, ConvertedInputColumn } from '../../type-converter/types.ts';\nimport type { TableNamedRelations } from '../types.ts';\nimport { generateColumnFilterValues } from './column-filters.ts';\nimport { CURSOR_FIELD_NAME, rowCursorResolver } from './cursor.ts';\nimport { columnDocs } from './docs.ts';\nimport { hasExcludedColumns, visibleColumns } from './exclusions.ts';\nimport { innerOrderType } from './input-order.ts';\nimport type { TypeNameMapper } from './naming.ts';\nimport { resolveTypeName } from './naming.ts';\nimport { isFilterableRelation } from './relations.ts';\nimport type { TypeCacheCtx } from './type-cache.ts';\nimport { generateUniqueKeyFilterFields } from './unique-keys.ts';\n\n// Keyed by the `InnerOrder` instance as well as the table: the type's name follows the\n// build's naming rule, and the cache outlives a build, so two builds that name it differently\n// must not share one field map.\nconst orderMap = new WeakMap<object, Map<GraphQLInputObjectType, Record<string, ConvertedInputColumn>>>();\nconst generateTableOrderCached = (table: Table, innerOrder: GraphQLInputObjectType) => {\n // The cache outlives a build, so a table whose columns this build hides must not read from\n // it (a previous build may have cached the full set) or write to it (a later unfiltered\n // build would inherit the holes).\n const cacheable = !hasExcludedColumns(table);\n const cached = cacheable ? orderMap.get(table)?.get(innerOrder) : undefined;\n if (cached) {\n return cached;\n }\n\n let remapped = {};\n try {\n const columns = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n remapped = Object.fromEntries(\n columnEntries.map(([columnName, _columnDescription]) => [columnName, { type: innerOrder }]),\n );\n\n if (cacheable) {\n let byInnerOrder = orderMap.get(table);\n if (!byInnerOrder) {\n byInnerOrder = new Map();\n orderMap.set(table, byInnerOrder);\n }\n byInnerOrder.set(innerOrder, remapped);\n }\n } catch (_err) {}\n return remapped;\n};\n\nconst generateTableFilterValuesCached = (table: Table, tableName: string, cacheCtx: TypeCacheCtx) => {\n if (cacheCtx.filterFieldCache.has(table)) {\n return cacheCtx.filterFieldCache.get(table)!;\n }\n\n const columns = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n const remapped = Object.fromEntries(\n columnEntries.map(([columnName, column]) => [\n columnName,\n {\n type: generateColumnFilterValues(column, tableName, columnName, cacheCtx),\n // A filter field is the same column, so it carries the same documentation. Deprecation\n // is not propagated: filtering on a deprecated column is how a caller finds the rows\n // that still use it.\n ...(cacheCtx.docs.describeColumn\n ? { description: cacheCtx.docs.describeColumn(column, { tableName, columnName }) }\n : {}),\n },\n ]),\n );\n\n cacheCtx.filterFieldCache.set(table, remapped);\n\n return remapped;\n};\n\nexport const generateTableSelectTypeFieldsCached = (\n table: Table,\n tableName: string,\n cacheCtx: TypeCacheCtx,\n): Record<string, ConvertedColumn> => {\n if (cacheCtx.selectFieldCache.has(table)) {\n return cacheCtx.selectFieldCache.get(table)!;\n }\n\n const columns = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n const remapped = Object.fromEntries(\n columnEntries.map(([columnName, column]) => [\n columnName,\n {\n ...drizzleColumnToGraphQLType(column, columnName, tableName),\n ...columnDocs(cacheCtx.docs, column, tableName, columnName),\n },\n ]),\n );\n\n // Opaque keyset-pagination cursor. Only populated on rows returned by a list query; a real\n // column named `cursor` keeps the field for itself instead.\n if (!remapped[CURSOR_FIELD_NAME]) {\n remapped[CURSOR_FIELD_NAME] = {\n type: GraphQLString,\n description:\n \"Opaque cursor of this row's position in the query's ordering. Pass it as `after` to resume from here. Only set on rows returned by a list query.\",\n resolve: rowCursorResolver,\n } as ConvertedColumn;\n }\n\n cacheCtx.selectFieldCache.set(table, remapped);\n\n return remapped;\n};\n\n/**\n * Order fields for a table's to-one relations: each takes the target table's own OrderBy\n * input, so a list can be sorted by a related row's column (compiled as a correlated\n * subquery in the ORDER BY — see `extractOrderBy`). To-many relations are left out: \"order\n * a parent by its many children\" has no single defined value to sort on. A relation whose\n * name collides with a column is skipped — the column keeps the field.\n */\nconst generateRelationOrderFields = (\n tableName: string,\n cacheCtx: TypeCacheCtx,\n typeNameMapper: TypeNameMapper | undefined,\n columnFields: Record<string, ConvertedInputColumn>,\n relationMap?: Record<string, Record<string, TableNamedRelations>>,\n tables?: Record<string, Table>,\n): Record<string, { type: GraphQLInputObjectType; description?: string }> => {\n const relations = relationMap?.[tableName];\n if (!relations || !tables) {\n return {};\n }\n\n const fields: Record<string, { type: GraphQLInputObjectType; description?: string }> = {};\n\n for (const [relationName, relEntry] of Object.entries(relations)) {\n if (relationName in columnFields) {\n continue;\n }\n\n const targetTable = tables[relEntry.targetTableName];\n const relation = (relEntry as any).relation ?? relEntry;\n if (!targetTable || !is(relation, One) || !isFilterableRelation(relation)) {\n continue;\n }\n\n fields[relationName] = {\n type: generateTableOrderTypeCached(\n targetTable,\n relEntry.targetTableName,\n typeNameMapper,\n cacheCtx,\n relationMap,\n tables,\n ),\n description: `Order by columns of the related ${relationName} row`,\n };\n }\n\n return fields;\n};\n\nexport const generateTableOrderTypeCached = (\n table: Table,\n tableName: string,\n typeNameMapper: TypeNameMapper | undefined,\n cacheCtx: TypeCacheCtx,\n relationMap?: Record<string, Record<string, TableNamedRelations>>,\n tables?: Record<string, Table>,\n) => {\n if (cacheCtx.orderTypeCache.has(table)) {\n return cacheCtx.orderTypeCache.get(table)!;\n }\n\n // Fields are thunked so that relation order fields, which reference other tables' order\n // inputs (and eventually this one again), are only resolved after this type is cached.\n const order = new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'orderBy',\n defaultName: `${resolveTypeName(tableName, typeNameMapper)}OrderBy`,\n table: tableName,\n }),\n fields: () => {\n const orderColumns = generateTableOrderCached(table, innerOrderType(cacheCtx.typeName));\n return {\n ...orderColumns,\n ...generateRelationOrderFields(tableName, cacheCtx, typeNameMapper, orderColumns, relationMap, tables),\n };\n },\n });\n\n cacheCtx.orderTypeCache.set(table, order);\n\n return order;\n};\n\n/**\n * `${Target}ListRelationFilter` — the Prisma-style some/every/none wrapper for a to-many\n * relation. Shared by every table that points at the same target, and built through a thunk\n * so mutually-referencing tables (Users.posts ⇄ Posts.author) don't recurse forever.\n */\nconst generateListRelationFilterCached = (\n targetTable: Table,\n targetTableName: string,\n cacheCtx: TypeCacheCtx,\n typeNameMapper: TypeNameMapper | undefined,\n relationMap: Record<string, Record<string, TableNamedRelations>> | undefined,\n tables: Record<string, Table> | undefined,\n): GraphQLInputObjectType => {\n const cached = cacheCtx.listRelationFilterCache.get(targetTableName);\n if (cached) {\n return cached;\n }\n\n const listFilter = new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'listRelationFilter',\n defaultName: `${resolveTypeName(targetTableName, typeNameMapper)}ListRelationFilter`,\n table: targetTableName,\n }),\n fields: () => {\n const targetFilters = generateTableFilterTypeCached(\n targetTable,\n targetTableName,\n cacheCtx,\n typeNameMapper,\n relationMap,\n tables,\n );\n\n return {\n some: { type: targetFilters, description: 'At least one related row matches' },\n none: { type: targetFilters, description: 'No related row matches' },\n every: { type: targetFilters, description: 'Every related row matches' },\n };\n },\n });\n\n cacheCtx.listRelationFilterCache.set(targetTableName, listFilter);\n\n return listFilter;\n};\n\n/**\n * Filter fields for a table's relations: a to-one relation takes the target's own filter input\n * directly, a to-many relation takes the some/every/none wrapper. A relation whose name collides\n * with a column name is skipped — the column keeps the field.\n */\nconst generateRelationFilterFields = (\n tableName: string,\n cacheCtx: TypeCacheCtx,\n typeNameMapper: TypeNameMapper | undefined,\n columnFields: Record<string, ConvertedInputColumn>,\n relationMap?: Record<string, Record<string, TableNamedRelations>>,\n tables?: Record<string, Table>,\n): Record<string, { type: GraphQLInputObjectType; description?: string }> => {\n const relations = relationMap?.[tableName];\n if (!relations || !tables) {\n return {};\n }\n\n const fields: Record<string, { type: GraphQLInputObjectType; description?: string }> = {};\n\n for (const [relationName, relEntry] of Object.entries(relations)) {\n if (relationName in columnFields) {\n continue;\n }\n\n const targetTable = tables[relEntry.targetTableName];\n const relation = (relEntry as any).relation ?? relEntry;\n if (!targetTable) {\n continue;\n }\n\n fields[relationName] = is(relation, One)\n ? {\n type: generateTableFilterTypeCached(\n targetTable,\n relEntry.targetTableName,\n cacheCtx,\n typeNameMapper,\n relationMap,\n tables,\n ),\n description: `Matches rows whose ${relationName} matches these filters`,\n }\n : {\n type: generateListRelationFilterCached(\n targetTable,\n relEntry.targetTableName,\n cacheCtx,\n typeNameMapper,\n relationMap,\n tables,\n ),\n };\n }\n\n return fields;\n};\n\nexport const generateTableFilterTypeCached = (\n table: Table,\n tableName: string,\n cacheCtx: TypeCacheCtx,\n typeNameMapper?: TypeNameMapper,\n relationMap?: Record<string, Record<string, TableNamedRelations>>,\n tables?: Record<string, Table>,\n) => {\n if (cacheCtx.filterTypeCache.has(table)) {\n return cacheCtx.filterTypeCache.get(table)!;\n }\n\n // Fields are thunked so that relation filters, which reference other tables' filter inputs\n // (and eventually this one again), are only resolved after this type is in the cache.\n const buildFields = () => {\n const filterColumns = generateTableFilterValuesCached(table, tableName, cacheCtx);\n const uniqueKeys = cacheCtx.uniqueKeysOf?.(tableName);\n return {\n ...filterColumns,\n ...generateRelationFilterFields(tableName, cacheCtx, typeNameMapper, filterColumns, relationMap, tables),\n // Last, and already filtered against both — a key field only exists under a name no\n // column and no relation claimed.\n ...(uniqueKeys ? generateUniqueKeyFilterFields(table, tableName, uniqueKeys, typeNameMapper, cacheCtx) : {}),\n };\n };\n\n // The boolean branches (OR / AND / NOT) are recursive — each branch is this filter type\n // itself — so the thunk references the type being constructed. Siblings and branches\n // compose: sibling fields are implicitly ANDed with the OR / AND / NOT groups.\n const filters: GraphQLInputObjectType = new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'filter',\n defaultName: `${resolveTypeName(tableName, typeNameMapper)}Filters`,\n table: tableName,\n }),\n fields: () => ({\n ...buildFields(),\n OR: {\n type: new GraphQLList(new GraphQLNonNull(filters)),\n description: 'At least one branch matches; ANDed with any sibling fields',\n },\n AND: {\n type: new GraphQLList(new GraphQLNonNull(filters)),\n description: 'Every branch matches',\n },\n NOT: {\n type: filters,\n description: 'Negates the nested filters',\n },\n }),\n });\n\n cacheCtx.filterTypeCache.set(table, filters);\n\n return filters;\n};\n","// The per-table object types and the fields on them, including relation fields and the type a\n// mutation returns.\n\nimport type { Table } from 'drizzle-orm';\nimport { is, One } from 'drizzle-orm';\nimport {\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n GraphQLString,\n} from 'graphql';\nimport { capitalize } from '../../case-ops/index.ts';\nimport { tableTypeExtension } from '../../extensions.ts';\nimport { drizzleColumnToGraphQLType } from '../../type-converter/index.ts';\nimport type { ConvertedRelationColumnWithArgs } from '../../type-converter/types.ts';\nimport { fieldUpdateInputType } from '../field-updates.ts';\n// Type-only: the nested-write module imports this one at runtime, so the dependency has to\n// stay one-directional. The implementation is injected by the dialect builder.\nimport type { NestedWriteTypes } from '../nested-writes.ts';\nimport type { GeneratedTableTypes, GeneratedTableTypesOutputs, SelectData, TableNamedRelations } from '../types.ts';\nimport { deletedArg } from './args.ts';\nimport { generateDistinctEnum } from './column-enums.ts';\nimport { inputFieldDocs } from './docs.ts';\nimport { visibleColumns } from './exclusions.ts';\nimport { aggregateFieldComplexity, listFieldComplexity } from './limits.ts';\nimport type { TypeNameMapper } from './naming.ts';\nimport { resolveTypeName } from './naming.ts';\nimport { relationExtensionFor } from './relation-resolvers.ts';\nimport type { RelationAggregateFactory, RelationResolverFactory } from './relations.ts';\nimport {\n generateTableFilterTypeCached,\n generateTableOrderTypeCached,\n generateTableSelectTypeFieldsCached,\n} from './table-inputs.ts';\nimport type { TypeCacheCtx } from './type-cache.ts';\n\n/**\n * Build the select fields for a table.\n * Creates:\n * - Main select type: ${capitalize(tableName)} (e.g. Users)\n * - Relation fields reference the target table's own type directly (e.g. posts: [Posts!]!)\n * rather than creating intermediate relation types.\n *\n * The function is called recursively for relation targets.\n * Cycle detection: usedTables tracks tables currently being processed in the call stack.\n * When we see a table already in usedTables, we stop recursing (no relation fields for that type).\n */\nconst generateSelectFields = <TWithOrder extends boolean>(\n tables: Record<string, Table>,\n tableName: string,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n fromTableName: string,\n fromRelationName: string,\n withOrder: TWithOrder,\n relationsDepthLimit: number | undefined,\n cacheCtx: TypeCacheCtx,\n typeNameMapper: TypeNameMapper | undefined,\n usedTables: Set<string> = new Set(),\n resolverFactory?: RelationResolverFactory,\n currentDepth: number = 0,\n relationAggregateFactory?: RelationAggregateFactory,\n): SelectData<TWithOrder> => {\n const table = tables[tableName]!;\n const order = withOrder\n ? generateTableOrderTypeCached(table, tableName, typeNameMapper, cacheCtx, relationMap, tables)\n : undefined;\n const filters = generateTableFilterTypeCached(table, tableName, cacheCtx, typeNameMapper, relationMap, tables);\n const tableFields = generateTableSelectTypeFieldsCached(table, tableName, cacheCtx);\n\n const relationsForTable = relationMap[tableName];\n const relationEntries: [string, TableNamedRelations][] = relationsForTable ? Object.entries(relationsForTable) : [];\n\n // Depth limit: stop generating relation fields once we reach the configured maximum.\n // relationsDepthLimit: 0 → no relation fields on any type.\n // relationsDepthLimit: N → each table's own root call (depth 0) generates its relations,\n // but traversals beyond depth N stop, which prevents unbounded recursive generation.\n if (relationsDepthLimit !== undefined && currentDepth >= relationsDepthLimit) {\n return {\n order,\n filters,\n tableFields,\n relationFields: {},\n } as SelectData<TWithOrder>;\n }\n\n // If this table is already being processed (cycle), stop recursing.\n // Return just the base fields with no relation fields.\n if (usedTables.has(tableName)) {\n return {\n order,\n filters,\n tableFields,\n relationFields: {},\n } as SelectData<TWithOrder>;\n }\n\n // For the root call (fromTableName === '' && fromRelationName === ''), this builds the\n // main ${capitalize(tableName)}SelectItem type.\n // For recursive calls, this builds the relation type.\n const isRootCall = fromTableName === '' && fromRelationName === '';\n\n // If the root type has already been fully built (not just pre-registered as a shell), return early.\n if (isRootCall && cacheCtx.fullyBuiltTables.has(tableName)) {\n return {\n order,\n filters,\n tableFields,\n relationFields: {},\n } as SelectData<TWithOrder>;\n }\n\n // Obtain or create the mutable relation-fields container for this table.\n // The container is a plain object whose `fields` property the GraphQLObjectType thunk reads.\n // Pre-registering it here (before recursion) allows sibling relation traversals to reference\n // the same single GraphQLObjectType instance even when it hasn't been fully built yet.\n let container = cacheCtx.relationFieldContainers.get(tableName);\n if (!container) {\n container = { fields: {} };\n cacheCtx.relationFieldContainers.set(tableName, container);\n }\n\n if (isRootCall && !cacheCtx.objectTypeCache.has(tableName)) {\n const typeName = cacheCtx.typeName({\n kind: 'object',\n defaultName: resolveTypeName(tableName, typeNameMapper),\n table: tableName,\n });\n // Pre-register shell with thunk BEFORE recursing to break circular refs.\n // The thunk reads container.fields, which will be populated after recursion completes.\n const shell = new GraphQLObjectType({\n name: typeName,\n description: cacheCtx.docs.describeTable?.(tableName, table),\n fields: () => ({ ...tableFields, ...container!.fields }),\n extensions: { drizzle: tableTypeExtension(tableName, cacheCtx.primaryKeyOf?.(tableName) ?? []) },\n });\n cacheCtx.objectTypeCache.set(tableName, shell);\n }\n\n // Build relation fields — recurse into each related table.\n // Mark this table as in-progress before recursing to detect cycles.\n if (relationEntries.length > 0) {\n const rawRelationFields: [string, ConvertedRelationColumnWithArgs][] = [];\n\n // Mark this table as currently being processed.\n const nextUsedTables = new Set(usedTables);\n nextUsedTables.add(tableName);\n\n for (const [relationName, relEntry] of relationEntries) {\n const { targetTableName } = relEntry;\n const relation = (relEntry as any).relation ?? relEntry;\n const isOne = is(relation, One);\n\n // Always recurse to get the target table's filters/order (needed for args).\n // The usedTables check inside the recursive call prevents actual infinite recursion.\n const relSelectData = generateSelectFields(\n tables,\n targetTableName,\n relationMap,\n tableName, // fromTableName for the relation type\n relationName, // fromRelationName for the relation type\n !isOne,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n nextUsedTables,\n resolverFactory,\n currentDepth + 1,\n relationAggregateFactory,\n );\n\n // Use the target table's own GraphQL type directly instead of creating an intermediate relation type.\n // Ensure exactly one GraphQLObjectType instance exists for the target table.\n // If the root call for the target table has already run (or pre-registered a shell),\n // reuse that instance so the schema never contains duplicate type names.\n let relType = cacheCtx.objectTypeCache.get(targetTableName);\n if (!relType) {\n // The target table hasn't been processed yet. Pre-register a shell so that:\n // (a) this relation field has a concrete type reference, and\n // (b) when the target table's root call eventually runs, it reuses this same object.\n const targetTable = tables[targetTableName]!;\n const targetTableFields = generateTableSelectTypeFieldsCached(targetTable, targetTableName, cacheCtx);\n // Get or create a container for the target table's relation fields.\n let targetContainer = cacheCtx.relationFieldContainers.get(targetTableName);\n if (!targetContainer) {\n targetContainer = { fields: {} };\n cacheCtx.relationFieldContainers.set(targetTableName, targetContainer);\n }\n const capturedTargetContainer = targetContainer;\n // The thunk reads capturedTargetContainer.fields so that when the target table's root\n // call populates the container, the shell automatically includes those relation fields.\n relType = new GraphQLObjectType({\n name: cacheCtx.typeName({\n kind: 'object',\n defaultName: resolveTypeName(targetTableName, typeNameMapper),\n table: targetTableName,\n }),\n description: cacheCtx.docs.describeTable?.(targetTableName, targetTable),\n fields: () => ({ ...targetTableFields, ...capturedTargetContainer.fields }),\n extensions: {\n drizzle: tableTypeExtension(targetTableName, cacheCtx.primaryKeyOf?.(targetTableName) ?? []),\n },\n });\n cacheCtx.objectTypeCache.set(targetTableName, relType);\n }\n\n const resolve = resolverFactory?.({ tableName, relationName, relEntry: relEntry as TableNamedRelations, isOne });\n const relationDescription = cacheCtx.docs.describeRelation?.(tableName, relationName);\n const relationDocs = relationDescription !== undefined ? { description: relationDescription } : {};\n\n if (isOne) {\n // Honor the relation's declared optionality: `r.one.Target({ ..., optional: false })`\n // asserts the related row always exists (a NOT NULL foreign key), so the field is\n // emitted as `Target!`. The default (`optional: true` / omitted) stays nullable.\n // Column nullability alone is NOT used to infer this — a notNull `from` column does\n // not guarantee a related row exists when the FK constraint lives on the other side\n // (e.g. `Users.customer` joins the notNull `Users.id` to `Customers.userId`).\n const isRequired = (relation as One<any, any>).optional === false;\n rawRelationFields.push([\n relationName,\n {\n type: isRequired ? new GraphQLNonNull(relType) : relType,\n args: {\n where: { type: relSelectData.filters },\n ...deletedArg(cacheCtx.softDeleteOf, targetTableName, cacheCtx.typeName),\n },\n resolve,\n ...relationDocs,\n extensions: { drizzle: relationExtensionFor(relEntry, tableName, relationName, true) },\n },\n ]);\n continue;\n }\n\n // A to-many relation field is a list of the target table, so it takes the same\n // pagination surface a root list of that table does. `after` and `distinct` are the\n // two drizzle's `with:` clause cannot express, so a request that passes either drops\n // the relation out of the eager fetch and resolves it through the batch loader, which\n // implements both — see extractRelationsParams.\n const targetDistinctEnum = cacheCtx.featureOf(targetTableName).distinct\n ? generateDistinctEnum(\n tables[targetTableName]!,\n resolveTypeName(targetTableName, typeNameMapper),\n cacheCtx.typeName,\n targetTableName,\n )\n : undefined;\n\n rawRelationFields.push([\n relationName,\n {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(relType))),\n args: {\n where: { type: relSelectData.filters },\n orderBy: { type: relSelectData.order! },\n offset: { type: GraphQLInt },\n limit: { type: GraphQLInt },\n ...deletedArg(cacheCtx.softDeleteOf, targetTableName, cacheCtx.typeName),\n after: {\n type: GraphQLString,\n description:\n \"Keyset pagination: only return related rows strictly after this cursor (a row's `cursor` field from a previous page of this relation, under the same orderBy).\",\n },\n ...(targetDistinctEnum\n ? { distinct: { type: new GraphQLList(new GraphQLNonNull(targetDistinctEnum)) } }\n : {}),\n },\n resolve,\n ...relationDocs,\n extensions: {\n drizzle: relationExtensionFor(relEntry, tableName, relationName, false),\n ...(cacheCtx.complexity\n ? { complexity: listFieldComplexity(cacheCtx.complexity, cacheCtx.limits?.(targetTableName)) }\n : {}),\n },\n },\n ]);\n\n // Aggregate over the related rows without fetching them: `user { postsAggregate { count } }`.\n // Skipped when the name would shadow a column or another relation.\n const aggregateFieldName = `${relationName}Aggregate`;\n if (!tableFields[aggregateFieldName] && !relationsForTable?.[aggregateFieldName]) {\n const relationAggregate = relationAggregateFactory?.({\n tableName,\n relationName,\n relEntry: relEntry as TableNamedRelations,\n });\n\n if (relationAggregate) {\n rawRelationFields.push([\n aggregateFieldName,\n {\n type: new GraphQLNonNull(relationAggregate.type),\n args: {\n where: { type: relSelectData.filters },\n ...deletedArg(cacheCtx.softDeleteOf, targetTableName, cacheCtx.typeName),\n },\n resolve: relationAggregate.resolve,\n extensions: {\n drizzle: relationExtensionFor(relEntry, tableName, relationName, isOne, true),\n ...(cacheCtx.complexity ? { complexity: aggregateFieldComplexity(cacheCtx.complexity) } : {}),\n },\n } as unknown as ConvertedRelationColumnWithArgs,\n ]);\n }\n }\n }\n\n const builtRelationFields = Object.fromEntries(rawRelationFields);\n\n // Only the root call should populate the container — non-root calls are temporary traversals\n // to collect filters/order for args and should not overwrite the canonical relation fields.\n if (isRootCall) {\n // Populate the container so that the thunk on the GraphQLObjectType shell (whether it was\n // created here or pre-registered by another table's relation traversal) picks up the fields.\n container.fields = builtRelationFields;\n cacheCtx.fullyBuiltTables.add(tableName);\n }\n\n return {\n order,\n filters,\n tableFields,\n relationFields: builtRelationFields,\n } as SelectData<TWithOrder>;\n }\n\n // No relation entries — mark as fully built if root call.\n if (isRootCall) {\n cacheCtx.fullyBuiltTables.add(tableName);\n }\n\n return {\n order,\n filters,\n tableFields,\n relationFields: {},\n } as SelectData<TWithOrder>;\n};\n\nexport const generateTableTypes = <WithReturning extends boolean>(\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n withReturning: WithReturning,\n relationsDepthLimit: number | undefined,\n cacheCtx: TypeCacheCtx,\n typeNameMapper: TypeNameMapper | undefined = undefined,\n insertPrefix: string = 'create',\n updatePrefix: string = 'update',\n resolverFactory?: RelationResolverFactory,\n relationAggregateFactory?: RelationAggregateFactory,\n nestedWrites?: NestedWriteTypes,\n): GeneratedTableTypes<WithReturning> => {\n const { tableFields, relationFields, filters, order } = generateSelectFields(\n tables,\n tableName,\n relationMap,\n '', // root call: no fromTableName\n '', // root call: no fromRelationName\n true,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n new Set(),\n resolverFactory,\n 0,\n relationAggregateFactory,\n );\n\n const table = tables[tableName]!;\n const columns = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n // A column whose value comes from the request context is not part of any write input: the\n // client cannot supply one on create, and cannot reassign one on update. It stays an\n // ordinary column everywhere else — the output type, the filters, the ordering.\n const contextColumns = cacheCtx.contextValuesOf?.(tableName);\n // Same for the column that marks a row deleted: `delete` and `restore` own it, and a client\n // that could write it through an ordinary create or update could delete or undelete a row\n // without going through either.\n const markerColumn = cacheCtx.softDeleteOf?.(tableName)?.columnName;\n const writableEntries =\n contextColumns || markerColumn\n ? columnEntries.filter(\n ([columnName]) => !(contextColumns && columnName in contextColumns) && columnName !== markerColumn,\n )\n : columnEntries;\n\n // A column a nested write can supply (`author: { create: … }` fills in `authorId`) cannot\n // stay required on the create input, or the two ways of setting it would be mutually\n // exclusive at the type level.\n const relaxedColumns = nestedWrites?.relaxedColumns(tableName);\n\n const insertFields = Object.fromEntries(\n writableEntries.map(([columnName, column]) => {\n const converted = drizzleColumnToGraphQLType(\n column,\n columnName,\n tableName,\n !!relaxedColumns?.has(columnName),\n true,\n true,\n );\n return [\n columnName,\n { ...converted, ...inputFieldDocs(cacheCtx.docs, column, tableName, columnName, converted.type) },\n ];\n }),\n );\n\n const updateFields = Object.fromEntries(\n writableEntries.map(([columnName, column]) => {\n const converted = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, true);\n // A numeric or array column takes an operations input instead of the bare scalar, so\n // it can be changed relative to its current value rather than only replaced.\n const operations = cacheCtx.featureOf(tableName).fieldUpdateOperations\n ? fieldUpdateInputType(column, columnName, tableName, cacheCtx.typeName)\n : undefined;\n const field = operations ? { ...converted, type: operations } : converted;\n return [columnName, { ...field, ...inputFieldDocs(cacheCtx.docs, column, tableName, columnName, field.type) }];\n }),\n );\n\n const typeName = resolveTypeName(tableName, typeNameMapper);\n\n // Insert/update input types: ${capitalize(insertPrefix)}${resolveTypeName(tableName)}Input / ${capitalize(updatePrefix)}${resolveTypeName(tableName)}Input\n // With nested writes on, the fields are thunked: a relation field's operand is the target\n // table's filter input, which does not exist yet while this table is being generated.\n const insertInput = new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'createInput',\n defaultName: `${capitalize(insertPrefix)}${typeName}Input`,\n table: tableName,\n }),\n fields: nestedWrites\n ? () => ({ ...insertFields, ...nestedWrites.createFields(tableName, typeName) })\n : insertFields,\n });\n\n const updateInput = new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'updateInput',\n defaultName: `${capitalize(updatePrefix)}${typeName}Input`,\n table: tableName,\n }),\n fields: nestedWrites\n ? () => ({ ...updateFields, ...nestedWrites.updateFields(tableName, typeName) })\n : updateFields,\n });\n\n // Select type: ${resolveTypeName(tableName)} (with relation fields)\n // Reuse the cached shell created in generateSelectFields.\n const selectSingleOutput =\n cacheCtx.objectTypeCache.get(tableName) ??\n new GraphQLObjectType({\n name: cacheCtx.typeName({\n kind: 'object',\n defaultName: resolveTypeName(tableName, typeNameMapper),\n table: tableName,\n }),\n description: cacheCtx.docs.describeTable?.(tableName, tables[tableName]!),\n fields: { ...tableFields, ...relationFields },\n extensions: { drizzle: tableTypeExtension(tableName, cacheCtx.primaryKeyOf?.(tableName) ?? []) },\n });\n\n const selectArrOutput = new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(selectSingleOutput)));\n\n // Mutation return type: ${capitalize(tableName)}Item (table columns only, no relations)\n // const singleTableItemOutput = withReturning\n // ? new GraphQLObjectType({\n // name: `${capitalize(tableName)}`,\n // // name: `${capitalize(tableName)}Item`,\n // fields: tableFields,\n // })\n // : undefined;\n\n const arrTableItemOutput = withReturning\n ? // ? new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(singleTableItemOutput!)))\n new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(selectSingleOutput!)))\n : undefined;\n\n const inputs = {\n insertInput,\n updateInput,\n tableOrder: order,\n tableFilters: filters,\n };\n\n const outputs = (\n withReturning\n ? {\n selectSingleOutput,\n selectArrOutput,\n singleTableItemOutput: selectSingleOutput!,\n // singleTableItemOutput: singleTableItemOutput!,\n arrTableItemOutput: arrTableItemOutput!,\n }\n : {\n selectSingleOutput,\n selectArrOutput,\n }\n ) as GeneratedTableTypesOutputs<WithReturning>;\n\n return {\n inputs,\n outputs,\n };\n};\n","import type { SchemaFeatures } from '../types.ts';\nimport type { TableFeatures } from './builders/types.ts';\n\n/**\n * What a table generates when the config says nothing. Everything is on except the opt-in\n * features, so a build with no `features` block generates what it always did.\n */\nexport const featureDefaults: TableFeatures = {\n aggregates: true,\n groupBy: true,\n relationAggregates: true,\n distinct: true,\n insert: true,\n update: true,\n updateMany: true,\n delete: true,\n upsert: false,\n fieldUpdateOperations: false,\n countMutations: false,\n requireWhere: false,\n uniqueKeyFilters: false,\n};\n\n/**\n * Turns `BuildSchemaConfig.features` — booleans, per-table predicates, or nothing at all —\n * into a lookup the generators can ask about one table. Memoized, so a predicate is run once\n * per table however many places consult it.\n */\nexport const resolveTableFeatures = (features: SchemaFeatures | undefined): ((tableName: string) => TableFeatures) => {\n const cache = new Map<string, TableFeatures>();\n const names = Object.keys(featureDefaults) as (keyof TableFeatures)[];\n return (tableName: string): TableFeatures => {\n let resolved = cache.get(tableName);\n if (!resolved) {\n resolved = {} as TableFeatures;\n for (const name of names) {\n const configured = features?.[name];\n // A predicate answering with something other than a boolean is answering \"yes\" for\n // anything truthy, matching how the flags read everywhere else.\n resolved[name] =\n configured === undefined\n ? featureDefaults[name]\n : typeof configured === 'function'\n ? !!configured(tableName)\n : !!configured;\n }\n cache.set(tableName, resolved);\n }\n return resolved;\n };\n};\n","// =============================================================================\n// `BuildSchemaConfig` -> `SchemaGeneratorOptions`.\n//\n// Everything `buildSchema` decides before it knows which dialect it is talking\n// to: defaults filled in, per-table configuration resolved against the real\n// schema (so a renamed table or column fails the build rather than silently\n// doing nothing), contradictory feature flags warned about, and the whole lot\n// normalized into the single options object the three dialect generators take.\n// =============================================================================\n\nimport { getColumns, is, Table } from 'drizzle-orm';\nimport type { BuildSchemaConfig, TableLimitPolicy } from '../types.ts';\nimport {\n DEFAULT_TRANSACTION_TIMEOUT_MS,\n type DefaultOrderByFor,\n type LimitPolicyFor,\n normalizeWriteHooks,\n type ResolvedLimitPolicy,\n type ResolvedWriteHooks,\n resolveGeneratedTypeNames,\n resolveLimitPolicy,\n resolveSoftDeleteInfo,\n type SoftDeleteInfo,\n type TablePolicies,\n type WriteHookFor,\n type WriteHookPositions,\n type WriteHooks,\n} from './builders/common.ts';\nimport type { SchemaGeneratorOptions } from './builders/types.ts';\nimport { singularizeMapper } from './case-ops/index.ts';\nimport { resolveTableFeatures } from './features.ts';\n\n/**\n * Resolves a caller's `BuildSchemaConfig` against the Drizzle schema it will be applied to.\n *\n * Throws on configuration that names a table or column the schema does not have, and warns on\n * feature flags whose combination generates something other than what it appears to ask for.\n *\n * @param config the caller's config, or `undefined` for an all-defaults build\n * @param schema the Drizzle schema map `buildSchema` resolved from the database instance\n */\nexport const resolveBuildConfig = (\n config: BuildSchemaConfig | undefined,\n schema: Record<string, unknown>,\n): SchemaGeneratorOptions => {\n const prefixes = {\n insert: config?.prefixes?.insert ?? 'create',\n delete: config?.prefixes?.delete ?? 'delete',\n update: config?.prefixes?.update ?? 'update',\n upsert: config?.prefixes?.upsert ?? 'upsert',\n restore: config?.prefixes?.restore ?? 'restore',\n };\n\n const suffixes = {\n list: config?.suffixes?.list ?? '',\n single: config?.suffixes?.single ?? 'Single',\n };\n\n // `'singularize'` is the one shipped preset; anything else is the caller's own function.\n const typeNameMapper = config?.typeNameMapper === 'singularize' ? singularizeMapper : config?.typeNameMapper;\n\n // The naming rule for every generated type. Validated here rather than left to graphql-js,\n // whose complaint names the finished type and not the affix that produced it.\n const affix = (value: string | undefined, key: 'typeNamePrefix' | 'typeNameSuffix', pattern: RegExp) => {\n if (value !== undefined && !pattern.test(value)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.${key} must be a valid GraphQL name fragment (letters, digits and underscores${key === 'typeNamePrefix' ? ', not starting with a digit' : ''}), got '${value}'.`,\n );\n }\n return value;\n };\n const typeName = resolveGeneratedTypeNames({\n derivedTypeNameMapper: config?.derivedTypeNameMapper,\n typeNamePrefix: affix(config?.typeNamePrefix, 'typeNamePrefix', /^[_A-Za-z][_0-9A-Za-z]*$/),\n typeNameSuffix: affix(config?.typeNameSuffix, 'typeNameSuffix', /^[_0-9A-Za-z]+$/),\n });\n\n // Table keys this build generates for — what a per-table feature predicate is asked about.\n // Excluded tables are dropped up front so no predicate is ever consulted for a table that\n // generates nothing.\n const tableKeys = Object.entries(schema as Record<string, unknown>)\n .filter(([, value]) => is(value, Table))\n .map(([key]) => key);\n const excludedTableNames = new Set(config?.exclude?.tables ?? []);\n const featureTables = tableKeys.filter((key) => !excludedTableNames.has(key));\n\n // Resolved the same way the generators resolve it, so the implication warnings below\n // describe exactly what gets generated.\n const forTable = resolveTableFeatures(config?.features);\n\n // Cost hints are inert without a complexity rule installed, so they are generated unless the\n // caller opts out.\n const complexityConfig = config?.complexity ?? true;\n const complexity =\n complexityConfig === false\n ? undefined\n : {\n defaultListSize: (complexityConfig === true ? undefined : complexityConfig.defaultListSize) ?? 10,\n aggregateCost: (complexityConfig === true ? undefined : complexityConfig.aggregateCost) ?? 10,\n };\n\n // Off unless asked for: opening transactions the caller did not wire up themselves is a\n // behavior change (and some drivers, e.g. neon-http, cannot open one at all).\n const transactionsOpt = config?.transactions;\n const transactions =\n transactionsOpt === undefined || transactionsOpt === 'none'\n ? undefined\n : {\n timeoutMs:\n (transactionsOpt === 'auto' ? undefined : transactionsOpt.timeoutMs) ?? DEFAULT_TRANSACTION_TIMEOUT_MS,\n };\n\n // A limit policy is only built when the caller configured one; otherwise `limits` stays\n // undefined and every list keeps its unbounded behavior. Policies are resolved once per\n // table and memoized, since the lookup runs on every relation field build and every list\n // resolve.\n const limitsConfig = config?.limits;\n if (limitsConfig) {\n const check = (policy: TableLimitPolicy, where: string) => {\n for (const key of ['defaultLimit', 'maxLimit'] as const) {\n const value = policy[key];\n if (value === undefined) {\n continue;\n }\n if (!Number.isInteger(value) || value < 1) {\n throw new Error(`Drizzle-GraphQL Error: config.limits${where}.${key} must be a positive integer.`);\n }\n }\n };\n check(limitsConfig, '');\n for (const [tableName, policy] of Object.entries(limitsConfig.tables ?? {})) {\n check(policy, `.tables.${tableName}`);\n }\n }\n const limitPolicyCache = new Map<string, ResolvedLimitPolicy | undefined>();\n const limits: LimitPolicyFor | undefined = limitsConfig\n ? (tableName: string) => {\n if (limitPolicyCache.has(tableName)) {\n return limitPolicyCache.get(tableName);\n }\n const resolved = resolveLimitPolicy(limitsConfig, limitsConfig.tables?.[tableName]);\n limitPolicyCache.set(tableName, resolved);\n return resolved;\n }\n : undefined;\n\n // Per-table defaults are resolved against the real schema at build time, so a renamed table\n // or column fails the build rather than silently ordering by nothing. The normalized form is\n // the same shape the generated `orderBy` argument has, so every read path can substitute it\n // without knowing where it came from.\n const defaultsConfig = config?.defaults;\n const defaultOrderByByTable = new Map<string, Record<string, any>>();\n if (defaultsConfig) {\n const defaultsTableNames = new Set(tableKeys);\n for (const [tableName, tableDefaults] of Object.entries(defaultsConfig)) {\n if (!defaultsTableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.defaults names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n const orderBy = tableDefaults?.orderBy;\n if (!orderBy || !Object.keys(orderBy).length) {\n continue;\n }\n const columns = getColumns(schema[tableName] as Table);\n const normalized: Record<string, any> = {};\n for (const [columnName, entry] of Object.entries(orderBy)) {\n if (!columns[columnName]) {\n throw new Error(\n `Drizzle-GraphQL Error: config.defaults.${tableName}.orderBy names '${columnName}', which is not a column of '${tableName}'.`,\n );\n }\n const direction = typeof entry === 'string' ? entry : entry?.direction;\n if (direction !== 'asc' && direction !== 'desc') {\n throw new Error(\n `Drizzle-GraphQL Error: config.defaults.${tableName}.orderBy.${columnName} must be 'asc', 'desc', or { direction, priority? }.`,\n );\n }\n const priority = typeof entry === 'string' ? undefined : entry?.priority;\n if (priority !== undefined && !Number.isInteger(priority)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.defaults.${tableName}.orderBy.${columnName}.priority must be an integer.`,\n );\n }\n normalized[columnName] = priority === undefined ? { direction } : { direction, priority };\n }\n defaultOrderByByTable.set(tableName, normalized);\n }\n }\n const defaultOrderBy: DefaultOrderByFor | undefined = defaultOrderByByTable.size\n ? (tableName: string) => defaultOrderByByTable.get(tableName)\n : undefined;\n\n // A row scope and the context-derived columns are resolved against the real schema for the\n // same reason exclusions are: a renamed table or column must fail the build, not silently\n // stop scoping. Both stay undefined unless configured, so an unconfigured build emits the\n // same SQL it always did.\n const scopeConfig = config?.scope;\n const contextValuesConfig = config?.contextValues;\n if (scopeConfig || contextValuesConfig) {\n const tableNames = new Set(tableKeys);\n for (const [tableName, hook] of Object.entries(scopeConfig ?? {})) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.scope names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n if (typeof hook !== 'function') {\n throw new Error(`Drizzle-GraphQL Error: config.scope.${tableName} must be a function.`);\n }\n }\n for (const [tableName, columnHooks] of Object.entries(contextValuesConfig ?? {})) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.contextValues names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n const columns = getColumns(schema[tableName] as Table);\n for (const [columnName, hook] of Object.entries(columnHooks)) {\n if (!columns[columnName]) {\n throw new Error(\n `Drizzle-GraphQL Error: config.contextValues names '${tableName}.${columnName}', which is not a column of that table.`,\n );\n }\n if (typeof hook !== 'function') {\n throw new Error(`Drizzle-GraphQL Error: config.contextValues.${tableName}.${columnName} must be a function.`);\n }\n }\n }\n }\n // Soft delete is resolved against the real columns here, once, so a renamed column or a\n // NOT NULL column with no restore value fails the build rather than silently making every\n // row visible again at runtime.\n const softDeleteConfig = config?.softDelete;\n const softDeleteInfos = new Map<string, SoftDeleteInfo>();\n if (softDeleteConfig) {\n if (typeof softDeleteConfig === 'function') {\n for (const tableName of tableKeys) {\n const declaration = softDeleteConfig(schema[tableName] as Table, tableName);\n if (declaration) {\n softDeleteInfos.set(tableName, resolveSoftDeleteInfo(schema[tableName] as Table, tableName, declaration));\n }\n }\n } else {\n const tableNames = new Set(tableKeys);\n for (const [tableName, declaration] of Object.entries(softDeleteConfig)) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n softDeleteInfos.set(tableName, resolveSoftDeleteInfo(schema[tableName] as Table, tableName, declaration));\n }\n }\n }\n\n // Write hooks are resolved the same way: a table name that matches nothing fails the build,\n // and the two registration shapes collapse into one per-table lookup here rather than in\n // every resolver.\n const onWriteConfig = config?.onWrite;\n const writeHooks = new Map<string, ResolvedWriteHooks | undefined>();\n if (onWriteConfig) {\n // A bare function, or an object naming the positions, applies to every table; anything\n // else is a table map. `before`/`after` are reserved as position names for that reason.\n const isGlobal =\n typeof onWriteConfig === 'function' ||\n typeof (onWriteConfig as WriteHookPositions).before === 'function' ||\n typeof (onWriteConfig as WriteHookPositions).after === 'function';\n if (isGlobal) {\n // Resolved per table rather than once, because a hook's `columns` resolve to that\n // table's own column objects — and a named column every table must actually have.\n for (const tableName of featureTables) {\n writeHooks.set(\n tableName,\n normalizeWriteHooks(\n onWriteConfig as WriteHooks,\n getColumns(schema[tableName] as Table),\n `config.onWrite (on table '${tableName}')`,\n ),\n );\n }\n } else {\n const tableNames = new Set(tableKeys);\n for (const [tableName, hooks] of Object.entries(onWriteConfig as Record<string, WriteHooks>)) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.onWrite names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n if (typeof hooks !== 'function' && typeof hooks !== 'object') {\n throw new Error(\n `Drizzle-GraphQL Error: config.onWrite.${tableName} must be a function or an object with 'before' and/or 'after'.`,\n );\n }\n writeHooks.set(\n tableName,\n normalizeWriteHooks(hooks, getColumns(schema[tableName] as Table), `config.onWrite.${tableName}`),\n );\n }\n }\n }\n const onWrite: WriteHookFor | undefined = writeHooks.size\n ? (tableName: string) => writeHooks.get(tableName)\n : undefined;\n\n const policies: TablePolicies | undefined =\n scopeConfig || contextValuesConfig || softDeleteInfos.size || onWrite || defaultOrderBy\n ? {\n scope: scopeConfig ? (tableName: string) => scopeConfig[tableName] : undefined,\n contextValues: contextValuesConfig ? (tableName: string) => contextValuesConfig[tableName] : undefined,\n softDelete: softDeleteInfos.size ? (tableName: string) => softDeleteInfos.get(tableName) : undefined,\n onWrite,\n defaultOrderBy,\n }\n : undefined;\n\n // Exclusions are resolved against the real schema so a renamed table or column fails the\n // build instead of quietly un-hiding itself — the failure mode that matters when this config\n // is what keeps a secret out of the API.\n const exclude = config?.exclude;\n if (exclude) {\n const tableNames = new Set(tableKeys);\n const excludedTables = excludedTableNames;\n for (const tableName of excludedTables) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.exclude.tables names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n }\n if (excludedTables.size >= tableNames.size) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.exclude.tables excludes every table in the schema, leaving nothing to generate.',\n );\n }\n for (const [tableName, columnNames] of Object.entries(exclude.columns ?? {})) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.exclude.columns names table '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n // An excluded table has no columns left to hide; listing them too is redundant, not wrong.\n if (excludedTables.has(tableName)) {\n continue;\n }\n const columns = getColumns(schema[tableName] as Table);\n for (const columnName of columnNames) {\n const column = columns[columnName];\n if (!column) {\n throw new Error(\n `Drizzle-GraphQL Error: config.exclude.columns names '${tableName}.${columnName}', which is not a column of that table.`,\n );\n }\n // Hiding a column every insert must supply leaves the table readable but unwritable.\n // That is a reasonable thing to configure deliberately, so it warns rather than throws.\n if (column.notNull && !column.hasDefault && !column.defaultFn) {\n console.warn(\n `Drizzle-GraphQL Warning: excluded column '${tableName}.${columnName}' is NOT NULL with no default, so generated inserts for '${tableName}' can never succeed.`,\n );\n }\n }\n }\n }\n\n // Some operations are built out of others: an upsert writes through the insert and update\n // paths, a batch update reuses the update input, a grouped result reuses the aggregate\n // output types. The generator knows those implications; a table whose flags contradict them\n // is told at build time rather than leaving the consumer to notice a second write path (or a\n // missing operation) later. These warn rather than throw — the resulting schema is coherent,\n // it just isn't what the config appears to ask for.\n const featureConflicts = new Map<string, string[]>();\n const noteConflict = (message: string, tableName: string) => {\n const tables = featureConflicts.get(message);\n if (tables) {\n tables.push(tableName);\n } else {\n featureConflicts.set(message, [tableName]);\n }\n };\n for (const tableName of featureTables) {\n const tableFeatures = forTable(tableName);\n if (tableFeatures.upsert) {\n const missing = [!tableFeatures.insert ? 'insert' : undefined, !tableFeatures.update ? 'update' : undefined]\n .filter(Boolean)\n .join(' and ');\n if (missing) {\n noteConflict(\n `upsert is on while ${missing} is off, so the upsert mutations are a second write path past the operation you turned off`,\n tableName,\n );\n }\n }\n // Nested writes are not a conflict: a nested input whose write the target table turns off\n // is left out of the schema, and the build notes which (see `gateNestedWritePlans`).\n // Only flagged when the caller actually asked for the dependent feature: both default to\n // on, so turning off the operation they build on is the normal way to remove them.\n if (config?.features?.updateMany !== undefined && tableFeatures.updateMany && !tableFeatures.update) {\n noteConflict('updateMany is on while update is off, so no batch update is generated', tableName);\n }\n if (config?.features?.groupBy !== undefined && tableFeatures.groupBy && !tableFeatures.aggregates) {\n noteConflict('groupBy is on while aggregates is off, so no grouped query is generated', tableName);\n }\n // The count mutations mirror the plural write they count, so they need at least one of the\n // two to be generated at all.\n if (tableFeatures.countMutations && !tableFeatures.update && !tableFeatures.delete) {\n noteConflict(\n 'countMutations is on while update and delete are both off, so no count mutation is generated',\n tableName,\n );\n }\n }\n for (const [message, tables] of featureConflicts) {\n const listed =\n tables.length > 5 ? `${tables.slice(0, 5).join(', ')} and ${tables.length - 5} more` : tables.join(', ');\n console.warn(`Drizzle-GraphQL Warning: config.features — ${message} (${listed}).`);\n }\n\n // Normalize eagerLoadRelations (boolean | predicate | undefined) into a predicate.\n const eagerOpt = config?.eagerLoadRelations;\n const shouldEagerLoad: (tableName: string, relationName: string) => boolean =\n eagerOpt === undefined || eagerOpt === true ? () => true : eagerOpt === false ? () => false : eagerOpt;\n\n // When a typeNameMapper is provided, the mapper's singular/plural forms disambiguate the\n // list and single fields even if the suffixes are identical (e.g. both '').\n // Only enforce the suffix-collision check when no mapper is active.\n if (!typeNameMapper && suffixes.list === suffixes.single) {\n throw new Error(\n 'Drizzle-GraphQL Error: List and single query suffixes cannot be the same. This would create conflicting GraphQL field names.',\n );\n }\n\n if (typeof config?.relationsDepthLimit === 'number') {\n if (config.relationsDepthLimit < 0) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.relationsDepthLimit is supposed to be nonnegative integer or undefined!',\n );\n }\n if (config.relationsDepthLimit !== ~~config.relationsDepthLimit) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.relationsDepthLimit is supposed to be nonnegative integer or undefined!',\n );\n }\n }\n\n const generatorOptions: SchemaGeneratorOptions = {\n relationsDepthLimit: config?.relationsDepthLimit,\n prefixes,\n suffixes,\n conflictDoNothing: config?.conflictDoNothing ?? false,\n typeNameMapper,\n typeName,\n shouldEagerLoad,\n features: config?.features ?? {},\n complexity,\n scalars: config?.scalars,\n mapColumnType: config?.mapColumnType,\n enumNameMapper: config?.enumNameMapper,\n enumValueNameMapper: config?.enumValueNameMapper,\n transactions,\n limits,\n policies,\n exclude,\n docs: {\n describeColumn: config?.describeColumn,\n describeTable: config?.describeTable,\n describeRelation: config?.describeRelation,\n deprecateColumn: config?.deprecateColumn,\n },\n };\n\n return generatorOptions;\n};\n","import {\n and,\n avg,\n type Column,\n count,\n countDistinct,\n eq,\n extractExtendedColumnType,\n getColumns,\n gt,\n gte,\n inArray,\n lt,\n lte,\n max,\n min,\n ne,\n sum,\n type Table,\n} from 'drizzle-orm';\nimport {\n type GraphQLEnumType,\n GraphQLFloat,\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport { getOrCreateLoader, getOrCreateRequestValue } from '../batch-loader/index.ts';\nimport { capitalize } from '../case-ops/index.ts';\nimport { remapToGraphQLCore } from '../data-mappers/index.ts';\nimport type { ResolveTree } from '../parse-resolve-info.ts';\nimport { parseResolveInfo } from '../parse-resolve-info.ts';\nimport { drizzleColumnToGraphQLType } from '../type-converter/index.ts';\nimport type { ConvertedColumn } from '../type-converter/types.ts';\nimport {\n columnDocs,\n type DeletedMode,\n type DrizzleErrorContext,\n deletedArg,\n drizzleError,\n extractFilters,\n extractJunctionColumns,\n extractRelationJoinColumns,\n type GeneratedTypeInfo,\n generateColumnEnum,\n type RelationAggregateFactory,\n type RelationFilterBase,\n relationDeletedDefault,\n relationFilterCtx,\n relationOwnCondition,\n resolveExecutor,\n resolveScope,\n resolveTypeName,\n sharedType,\n type TablePolicies,\n type TypeCacheCtx,\n type TypeNameMapper,\n type TypeNameResolver,\n toGraphQLError,\n visibleColumns,\n warnUnresolvedJoin,\n withErrorContext,\n withScope,\n} from './common.ts';\nimport type { CreatedResolver, Filters } from './types.ts';\n\n/** Operations that aggregate over a set of column values. `count` is handled separately (whole rows). */\nconst AGGREGATE_OPS = ['avg', 'sum', 'min', 'max', 'countNonNull', 'countDistinct'] as const;\ntype AggregateOp = (typeof AGGREGATE_OPS)[number];\n\n/** Ops whose result is a row count: never null, and returned as `Int!` rather than the column's type. */\nconst COUNT_OPS = new Set<AggregateOp>(['countNonNull', 'countDistinct']);\n\nconst OP_FNS: Record<AggregateOp, (col: Column) => any> = {\n avg,\n sum,\n min,\n max,\n countNonNull: count,\n countDistinct,\n};\n\n/** Separator for flat select aliases (`avg__price`) — reassembled into nested output by the resolver. */\nconst SEP = '__';\n\ninterface AggregateColumnSets {\n /** Columns avg/sum apply to: plain Int/Float scalars. */\n numeric: Record<string, Column>;\n /** Columns min/max apply to: anything with a total ordering the DB supports (numbers, strings, dates, enums). */\n orderable: Record<string, { column: Column; converted: ConvertedColumn }>;\n /** Every column — `count(col)` is valid whatever the type. */\n all: Record<string, Column>;\n}\n\n/**\n * Classifies a table's columns for aggregation. avg/sum only make sense on numeric scalars;\n * min/max work on any orderable scalar (numbers, strings, bigints, dates, enums). Booleans,\n * arrays (including array-typed number columns), JSON, buffers, and object-shaped columns\n * (e.g. geometry) are excluded entirely.\n */\n/**\n * Cache for {@link classifyAggregateColumns}. Keyed on the table object, then on the name it\n * was classified under — the name only reaches `drizzleColumnToGraphQLType` for enum naming,\n * but a table registered under two names would name its enums differently, so it is part of\n * the key rather than assumed irrelevant.\n *\n * The entries hold this build's GraphQL types and this build's column exclusions, so the\n * cache lives exactly as long as a build: {@link resetAggregateColumnCache} runs at the start\n * of every one, alongside the other per-build registries. Kept across builds it would hand a\n * second build the first build's enum instances, which is a schema with two types of one name.\n */\nlet aggregateColumnSetsCache = new WeakMap<Table, Map<string, AggregateColumnSets>>();\n\n/** Drops the classifications cached for the previous build. Called once per `generateSchemaData`. */\nexport const resetAggregateColumnCache = (): void => {\n aggregateColumnSetsCache = new WeakMap();\n};\n\nconst classifyAggregateColumns = (table: Table, tableName: string): AggregateColumnSets => {\n // Called from every aggregate/group-by generator for the same table — five times per table\n // at build time, plus twice per to-many relation — and each call re-converts every column.\n let byName = aggregateColumnSetsCache.get(table);\n if (!byName) {\n byName = new Map();\n aggregateColumnSetsCache.set(table, byName);\n }\n const cached = byName.get(tableName);\n if (cached) {\n return cached;\n }\n\n const numeric: AggregateColumnSets['numeric'] = {};\n const orderable: AggregateColumnSets['orderable'] = {};\n const all: AggregateColumnSets['all'] = {};\n\n for (const [columnName, column] of Object.entries(visibleColumns(table))) {\n all[columnName] = column;\n const converted = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, false);\n const gqlType = converted.type;\n\n // Anything that isn't a plain scalar in the generated schema (arrays, geometry objects)\n // has no meaningful min/max. This also catches array-typed number columns, which keep\n // their scalar drizzle dataType but convert to a GraphQL list.\n if (gqlType instanceof GraphQLList || gqlType instanceof GraphQLObjectType) {\n continue;\n }\n\n // Classify on the drizzle data type rather than the GraphQL one: date columns convert to\n // different GraphQL scalars per dialect, but are orderable everywhere.\n const { type: dataType, constraint } = extractExtendedColumnType(column);\n if (dataType === 'boolean' || dataType === 'array' || dataType === 'custom') {\n continue;\n }\n if (dataType === 'object' && constraint !== 'date') {\n continue;\n }\n\n orderable[columnName] = { column, converted };\n if (dataType === 'number') {\n numeric[columnName] = column;\n }\n }\n\n const sets = { numeric, orderable, all };\n byName.set(tableName, sets);\n\n return sets;\n};\n\n/**\n * Builds the `${typeName}Aggregate` output type for a table:\n * - `count: Int!` — number of matching rows\n * - `avg` / `sum` — per numeric column, always nullable Float (SQL returns NULL on empty sets,\n * and avg/sum of integers overflow Int / produce decimals)\n * - `min` / `max` — per orderable column, the column's own (nullable) scalar type\n * - `countNonNull` — per column, `Int!`: how many matching rows have a non-null value there\n * - `countDistinct` — per orderable column, `Int!`: how many distinct non-null values there are\n * Each wrapper is omitted when no column qualifies for it.\n */\nexport const generateAggregateTypes = (\n table: Table,\n tableName: string,\n typeName: string,\n cacheCtx?: TypeCacheCtx,\n): GraphQLObjectType => {\n const cached = cacheCtx?.aggregateTypeCache.get(tableName);\n if (cached) {\n return cached;\n }\n\n const { numeric, orderable, all } = classifyAggregateColumns(table, tableName);\n const nameOf = (op: string) =>\n cacheCtx?.typeName({\n kind: 'aggregate',\n defaultName: `${typeName}${capitalize(op)}Aggregate`,\n table: tableName,\n operation: op,\n }) ?? `${typeName}${capitalize(op)}Aggregate`;\n\n const fields: Record<string, { type: any }> = {\n count: { type: new GraphQLNonNull(GraphQLInt) },\n };\n\n if (Object.keys(numeric).length) {\n for (const op of ['avg', 'sum'] as const) {\n fields[op] = {\n type: new GraphQLObjectType({\n name: nameOf(op),\n fields: Object.fromEntries(Object.keys(numeric).map((columnName) => [columnName, { type: GraphQLFloat }])),\n }),\n };\n }\n }\n\n if (Object.keys(orderable).length) {\n for (const op of ['min', 'max'] as const) {\n fields[op] = {\n type: new GraphQLObjectType({\n name: nameOf(op),\n fields: Object.fromEntries(\n Object.entries(orderable).map(([columnName, { column, converted }]) => [\n columnName,\n { type: converted.type, ...columnDocs(cacheCtx?.docs ?? {}, column, tableName, columnName) },\n ]),\n ),\n }),\n };\n }\n }\n\n // `count(col)` works on any column type; `count(distinct col)` needs an equality operator,\n // which is the same requirement min/max have, so it reuses the orderable set.\n const countSets: Record<string, Record<string, unknown>> = { countNonNull: all, countDistinct: orderable };\n for (const [op, columns] of Object.entries(countSets)) {\n const columnNames = Object.keys(columns);\n if (!columnNames.length) {\n continue;\n }\n fields[op] = {\n type: new GraphQLObjectType({\n name: nameOf(op),\n fields: Object.fromEntries(\n columnNames.map((columnName) => [columnName, { type: new GraphQLNonNull(GraphQLInt) }]),\n ),\n }),\n };\n }\n\n const aggregateType = new GraphQLObjectType({\n name:\n cacheCtx?.typeName({ kind: 'aggregate', defaultName: `${typeName}Aggregate`, table: tableName }) ??\n `${typeName}Aggregate`,\n fields,\n });\n\n cacheCtx?.aggregateTypeCache.set(tableName, aggregateType);\n\n return aggregateType;\n};\n\n/** Parses a driver-level date/time string (`2024-04-02 06:44:41.785`, `2024-04-02`) as UTC. */\nconst parseDriverDateTime = (raw: string): Date => {\n let v = raw.includes(' ') ? raw.replace(' ', 'T') : raw;\n if (!v.includes('T')) {\n v = `${v}T00:00:00`;\n }\n if (!/(?:[Zz]|[+-]\\d{2}(?::?\\d{2})?)$/.test(v)) {\n v = `${v}Z`;\n }\n const parsed = new Date(v);\n return Number.isNaN(parsed.getTime()) ? new Date(raw) : parsed;\n};\n\n/** What the client asked for, plus the drizzle select map that computes it. */\ninterface AggregateRequest {\n count: boolean;\n ops: Record<AggregateOp, string[]>;\n selection: Record<string, any>;\n}\n\n/** Everything about a table that aggregating over it needs, resolved once at build time. */\ninterface AggregateTarget {\n tableName: string;\n typeName: string;\n /** The name the `${Table}Aggregate` object type actually carries, which keys the resolve tree. */\n aggregateTypeName: string;\n /** The same for each per-op sub-type, e.g. `${Table}AvgAggregate`. */\n opTypeName: (op: AggregateOp) => string;\n columns: Record<string, Column>;\n /** Columns whose GraphQL output is DateTime — their min/max may need string→Date coercion. */\n dateTimeColumns: Set<string>;\n}\n\nconst aggregateTarget = (\n table: Table,\n tableName: string,\n typeName: string,\n resolveName?: TypeNameResolver,\n): AggregateTarget => {\n const { orderable } = classifyAggregateColumns(table, tableName);\n // Named exactly the way `generateAggregateTypes` names them, so the resolver reads the\n // selection tree under the key the schema actually published.\n return {\n tableName,\n typeName,\n aggregateTypeName:\n resolveName?.({ kind: 'aggregate', defaultName: `${typeName}Aggregate`, table: tableName }) ??\n `${typeName}Aggregate`,\n opTypeName: (op) =>\n resolveName?.({\n kind: 'aggregate',\n defaultName: `${typeName}${capitalize(op)}Aggregate`,\n table: tableName,\n operation: op,\n }) ?? `${typeName}${capitalize(op)}Aggregate`,\n columns: getColumns(table),\n dateTimeColumns: new Set(\n Object.entries(orderable)\n .filter(([, { converted }]) => converted.typeLabel === 'DateTime')\n .map(([columnName]) => columnName),\n ),\n };\n};\n\n/**\n * Reads the requested count/avg/sum/min/max selections off the resolve tree and turns them\n * into one drizzle select expression per (op, column) pair. An empty `selection` means the\n * client asked for nothing runnable (`__typename` only, or empty sub-selections).\n */\nconst parseAggregateRequest = (\n info: any,\n target: AggregateTarget,\n rootTypeName = target.aggregateTypeName,\n): AggregateRequest => {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const selectionTree = parsedInfo.fieldsByTypeName[rootTypeName] ?? {};\n\n const request: AggregateRequest = {\n count: false,\n ops: { avg: [], sum: [], min: [], max: [], countNonNull: [], countDistinct: [] },\n selection: {},\n };\n\n // Keys are aliases; `field.name` is the real field. Duplicate selections of the same\n // field under different aliases collapse into one SQL expression — graphql-js resolves\n // every alias from the same result property.\n for (const field of Object.values(selectionTree) as ResolveTree[]) {\n if (field.name === 'count') {\n request.count = true;\n request.selection['count'] = count();\n continue;\n }\n\n if (!AGGREGATE_OPS.includes(field.name as AggregateOp)) {\n continue;\n }\n const op = field.name as AggregateOp;\n const subTree = field.fieldsByTypeName[target.opTypeName(op)];\n if (!subTree) {\n continue;\n }\n\n for (const subField of Object.values(subTree) as ResolveTree[]) {\n const columnName = subField.name;\n const column = target.columns[columnName];\n if (!column || request.ops[op].includes(columnName)) {\n continue;\n }\n request.ops[op].push(columnName);\n request.selection[`${op}${SEP}${columnName}`] = OP_FNS[op](column);\n }\n }\n\n return request;\n};\n\n/** Reassembles a flat aggregate row (`avg__price`) into the nested GraphQL shape. */\nconst assembleAggregateRow = (row: Record<string, any>, request: AggregateRequest, target: AggregateTarget) => {\n const result: Record<string, any> = {};\n\n if (request.count) {\n // drizzle's count() maps to number already; guard for drivers returning strings.\n result['count'] = row['count'] == null ? 0 : Number(row['count']);\n }\n\n for (const op of AGGREGATE_OPS) {\n if (!request.ops[op].length) {\n continue;\n }\n const opResult: Record<string, any> = {};\n for (const columnName of request.ops[op]) {\n const value = row[`${op}${SEP}${columnName}`];\n if (COUNT_OPS.has(op)) {\n // A count is never null: an empty set counts to 0, and a missing group means no rows.\n opResult[columnName] = value == null ? 0 : Number(value);\n } else if (value == null) {\n opResult[columnName] = null;\n } else if (op === 'avg' || op === 'sum') {\n // Drivers return numeric/decimal aggregates as strings — coerce to Float.\n opResult[columnName] = Number(value);\n } else {\n // min/max keep the column's own type — drizzle already ran the column's decoder over\n // the value (`min`/`max` are `mapWith(column)`), so all that's left is coercing a\n // leftover raw date string (PG decodes timestamps in driver-level codecs, which raw\n // select expressions bypass) and remapping for GraphQL output.\n // Present by construction: a name only reaches `request.ops` after the same lookup\n // succeeded in `buildAggregateRequest`.\n const column = target.columns[columnName]!;\n const decoded =\n typeof value === 'string' && target.dateTimeColumns.has(columnName) ? parseDriverDateTime(value) : value;\n opResult[columnName] = remapToGraphQLCore(columnName, decoded, target.tableName, column);\n }\n }\n result[op] = opResult;\n }\n\n return result;\n};\n\n/**\n * Creates the resolver for a table's aggregate query field. Reads the requested\n * count/avg/sum/min/max selections from the resolve tree, runs them all as a single\n * `SELECT` with one aggregate expression per requested (op, column) pair, and\n * reassembles the flat row into the nested GraphQL shape.\n *\n * Shared by all three dialects — it only relies on `db.select().from().where()`.\n */\nexport const generateAggregate = (\n db: any,\n tableName: string,\n table: Table,\n typeName: string,\n fieldName: string,\n filterArgs: GraphQLInputObjectType,\n filterCtx?: RelationFilterBase,\n policies?: TablePolicies,\n resolveName?: TypeNameResolver,\n): CreatedResolver => {\n const target = aggregateTarget(table, tableName, typeName, resolveName);\n const errorCtx: DrizzleErrorContext = { table: tableName, operation: 'aggregate', field: fieldName };\n\n const queryArgs = {\n where: { type: filterArgs },\n ...deletedArg(policies?.softDelete, tableName, resolveName),\n };\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table>; deleted?: DeletedMode }, context, info) => {\n try {\n const request = parseAggregateRequest(info, target);\n if (!Object.keys(request.selection).length) {\n return {};\n }\n\n let query = resolveExecutor(db, context).select(request.selection).from(table);\n const where = withScope(\n resolveScope(policies, context, filterCtx),\n tableName,\n table,\n args.where\n ? extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n args.deleted,\n );\n if (where) {\n query = query.where(where);\n }\n const rows = await query;\n\n return assembleAggregateRow(rows[0] ?? {}, request, target);\n } catch (e) {\n throw withErrorContext(toGraphQLError(e), errorCtx);\n }\n },\n args: queryArgs,\n };\n};\n\n/** Alias the grouping key is selected under. Prefixed so it can't collide with `${op}__${column}`. */\nconst GROUP_KEY = '__dgql_group_key';\n\n/**\n * Builds the `${relationName}Aggregate` field that hangs off a parent type for each to-many\n * relation — `user { postsAggregate { count } }`.\n *\n * Resolution is batched the same way relation fields are: every parent row in the current tick\n * that asked for the same relation with the same arguments is served by one\n * `SELECT fk, <aggregates> ... WHERE fk IN (...) GROUP BY fk`, so a list of N parents costs one\n * extra query rather than N. Parents with no matching related rows get `count: 0` and `null`\n * for every other aggregate.\n */\nexport const createRelationAggregateFactory = (\n db: any,\n tables: Record<string, Table>,\n cacheCtx: TypeCacheCtx,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n policies?: TablePolicies,\n): RelationAggregateFactory => {\n // The factory can be asked for the same relation more than once in a build; warn once.\n const warned = new Set<string>();\n return ({ tableName, relationName, relEntry }) => {\n const parentTable = tables[tableName];\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n\n if (!parentTable || !targetTable) {\n return undefined;\n }\n\n const joinCols = extractRelationJoinColumns(relEntry, parentTable, targetTable);\n if (!joinCols) {\n const key = `${tableName}.${relationName}`;\n if (!warned.has(key)) {\n warned.add(key);\n warnUnresolvedJoin(relEntry, tableName, relationName, `its '${relationName}Aggregate' field`);\n }\n return undefined;\n }\n const { localColPropName, foreignCol } = joinCols;\n // A many-to-many relation reaches its target through a junction table: the parent's key\n // is on the junction, not the target, so the rows are grouped by the junction's column and\n // the target is joined to it. A junction this cannot express gets no aggregate field\n // rather than one that counts the wrong rows.\n const junction = extractJunctionColumns(relEntry);\n if (junction === null) {\n return undefined;\n }\n const groupCol = junction ? junction.sourceCol : foreignCol;\n const ownCondition = relationOwnCondition(\n relEntry,\n parentTable,\n targetTable,\n getColumns(parentTable)[localColPropName] as Column,\n groupCol,\n );\n // An aggregate over a relation counts the rows the relation itself returns, so it takes\n // the same soft-delete default — a `scope: 'root'` target is not hidden here either.\n const defaultDeleted = relationDeletedDefault(policies?.softDelete, targetTableName, false);\n\n const targetTypeName = resolveTypeName(targetTableName, typeNameMapper);\n const type = generateAggregateTypes(targetTable, targetTableName, targetTypeName, cacheCtx);\n const target = aggregateTarget(targetTable, targetTableName, targetTypeName, cacheCtx.typeName);\n const errorCtx: DrizzleErrorContext = {\n table: targetTableName,\n operation: 'relationAggregate',\n relation: relationName,\n };\n\n const resolve = async (\n parent: any,\n args: { where?: Filters<Table>; deleted?: DeletedMode },\n context: any,\n info: any,\n ) => {\n try {\n // This resolver runs once per parent row, and the resolve-info walk and the loader key\n // depend on the field alone, not on the row — so they are derived once per field per\n // request and reused by every sibling the batch serves.\n const { request, loaderKey } = getOrCreateRequestValue(\n context,\n info?.fieldNodes?.[0],\n `aggregate:${tableName}::${relationName}`,\n () => {\n const request = parseAggregateRequest(info, target);\n // Siblings only share a batch when they'd run the same query: same filters, same aggregates.\n const argsKey = JSON.stringify({\n where: args?.where ?? null,\n deleted: args?.deleted ?? defaultDeleted ?? null,\n selection: Object.keys(request.selection).sort(),\n });\n return { request, loaderKey: `${tableName}::${relationName}::aggregate::${argsKey}` };\n },\n );\n if (!Object.keys(request.selection).length) {\n return {};\n }\n\n const localValue = parent[localColPropName];\n // No key to correlate on — the relation is empty by definition.\n if (localValue == null) {\n return assembleAggregateRow({}, request, target);\n }\n\n const whereArg = args?.where;\n const deleted = args?.deleted;\n\n const loader = getOrCreateLoader(context, loaderKey, async (parentIds: readonly any[]) => {\n // Loaders are cached per context, so the whole batch shares this request's executor.\n const executor = resolveExecutor(db, context);\n const uniqueIds = [...new Set(parentIds)];\n // An aggregate over a relation counts the same rows the relation itself returns,\n // so it is narrowed by the target table's scope too.\n const whereCondition = withScope(\n resolveScope(policies, context, filterCtx),\n targetTableName,\n targetTable,\n and(\n inArray(groupCol, uniqueIds),\n ownCondition,\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n ),\n deleted ?? defaultDeleted,\n );\n\n const selected = executor.select({ [GROUP_KEY]: groupCol, ...request.selection }).from(targetTable);\n const joined = junction ? selected.innerJoin(junction.table, eq(junction.targetCol, foreignCol)) : selected;\n const rows: any[] = await joined.where(whereCondition).groupBy(groupCol);\n\n const byKey = new Map(rows.map((row) => [row[GROUP_KEY], row]));\n\n // A parent with no matching rows produces no group — hand back an empty row so it\n // assembles to count 0 / null aggregates rather than dropping the field.\n return parentIds.map((id) => byKey.get(id) ?? {});\n });\n\n return assembleAggregateRow(await loader.load(localValue), request, target);\n } catch (e) {\n throw withErrorContext(toGraphQLError(e), errorCtx);\n }\n };\n\n return { type, resolve };\n };\n};\n\n// ── group by ──────────────────────────────────────────────────────────────────\n\n/** Alias prefix for grouped columns, kept clear of the `${op}__${column}` aggregate aliases. */\nconst GROUP_COL = `group${SEP}`;\n\n/** Comparison operators a `having` clause can apply to an aggregated value. */\nconst HAVING_OPS = { eq, ne, gt, gte, lt, lte } as const;\n\n/**\n * Columns a query can group on. Grouping needs an equality operator, which is the same\n * requirement min/max has, plus booleans — orderable excludes them because a min/max over\n * true/false says nothing, but `GROUP BY isConfirmed` is perfectly ordinary.\n */\nconst groupableColumns = (\n table: Table,\n tableName: string,\n): Record<string, { column: Column; converted: ConvertedColumn }> => {\n const { orderable } = classifyAggregateColumns(table, tableName);\n const groupable: Record<string, { column: Column; converted: ConvertedColumn }> = { ...orderable };\n\n for (const [columnName, column] of Object.entries(visibleColumns(table))) {\n if (groupable[columnName]) {\n continue;\n }\n const { type: dataType } = extractExtendedColumnType(column);\n if (dataType !== 'boolean') {\n continue;\n }\n groupable[columnName] = {\n column,\n converted: drizzleColumnToGraphQLType(column, columnName, tableName, true, false, false),\n };\n }\n\n return groupable;\n};\n\n/** The `${typeName}GroupByColumn` enum listing what a group-by query can group on. */\nexport const generateGroupByEnum = (\n table: Table,\n tableName: string,\n typeName: string,\n cacheCtx?: TypeCacheCtx,\n): GraphQLEnumType | undefined => {\n const groupable = groupableColumns(table, tableName);\n const defaultName = `${typeName}GroupByColumn`;\n\n return generateColumnEnum(\n table,\n cacheCtx?.typeName({ kind: 'columnEnum', defaultName, table: tableName, operation: 'groupBy' }) ?? defaultName,\n `Columns of ${typeName} that a query can group by`,\n (_column, columnName) => Boolean(groupable[columnName]),\n );\n};\n\n/** Shared by every `having` clause, so it is created once per name rather than per table. */\nexport const aggregateNumberFilterType = (typeName: TypeNameResolver): GraphQLInputObjectType =>\n sharedType(\n typeName,\n { kind: 'shared', defaultName: 'AggregateNumberFilter' },\n (name) =>\n new GraphQLInputObjectType({\n name,\n description: 'Compares an aggregated value. Several operators in one filter are ANDed together.',\n fields: Object.fromEntries(Object.keys(HAVING_OPS).map((op) => [op, { type: GraphQLFloat }])),\n }),\n );\n\n/**\n * The `${typeName}Having` input: one entry per aggregate the group-by query can filter on.\n * Several entries are ANDed together, as are several operators within one entry.\n *\n * `min`/`max` are limited to numeric columns here even though the output type computes them\n * for every orderable column — the comparison is numeric, so a min over a text column has\n * nothing to compare against.\n */\nexport const generateHavingInput = (\n table: Table,\n tableName: string,\n typeName: string,\n cacheCtx?: TypeCacheCtx,\n): GraphQLInputObjectType => {\n const { numeric, orderable, all } = classifyAggregateColumns(table, tableName);\n const resolveName = cacheCtx?.typeName ?? ((info: GeneratedTypeInfo) => info.defaultName);\n const numberFilter = aggregateNumberFilterType(resolveName);\n\n const fields: Record<string, { type: any; description?: string }> = {\n count: { type: numberFilter, description: 'Filters groups by how many rows they contain' },\n };\n\n const opColumns: Record<string, Record<string, unknown>> = {\n avg: numeric,\n sum: numeric,\n min: numeric,\n max: numeric,\n countNonNull: all,\n countDistinct: orderable,\n };\n\n for (const [op, columns] of Object.entries(opColumns)) {\n const columnNames = Object.keys(columns);\n if (!columnNames.length) {\n continue;\n }\n fields[op] = {\n type: new GraphQLInputObjectType({\n name: resolveName({\n kind: 'having',\n defaultName: `${typeName}${capitalize(op)}Having`,\n table: tableName,\n operation: op,\n }),\n fields: Object.fromEntries(columnNames.map((columnName) => [columnName, { type: numberFilter }])),\n }),\n };\n }\n\n return new GraphQLInputObjectType({\n name: resolveName({ kind: 'having', defaultName: `${typeName}Having`, table: tableName }),\n description: `Filters ${typeName} groups by their aggregated values`,\n fields,\n });\n};\n\n/**\n * The `${typeName}GroupBy` output type: the grouped columns under `group`, alongside the same\n * aggregate fields the `${typeName}Aggregate` type carries — the wrapper types are the very\n * same instances, so the schema holds one `${typeName}AvgAggregate` however it is reached.\n *\n * The keys are nested rather than spread across the top level so a column called `count`,\n * `avg` or `min` cannot collide with the aggregate it sits next to.\n */\nexport const generateGroupByType = (\n table: Table,\n tableName: string,\n typeName: string,\n cacheCtx?: TypeCacheCtx,\n): GraphQLObjectType | undefined => {\n const groupable = groupableColumns(table, tableName);\n if (!Object.keys(groupable).length) {\n return undefined;\n }\n\n const keysType = new GraphQLObjectType({\n name:\n cacheCtx?.typeName({ kind: 'groupKeys', defaultName: `${typeName}GroupKeys`, table: tableName }) ??\n `${typeName}GroupKeys`,\n description: `The grouped column values of one ${typeName} group. A column the query did not group by is null.`,\n fields: Object.fromEntries(\n Object.entries(groupable).map(([columnName, { column, converted }]) => [\n columnName,\n { type: converted.type, ...columnDocs(cacheCtx?.docs ?? {}, column, tableName, columnName) },\n ]),\n ),\n });\n\n const aggregateType = generateAggregateTypes(table, tableName, typeName, cacheCtx);\n const aggregateFields = Object.fromEntries(\n Object.values(aggregateType.getFields()).map((field) => [\n field.name,\n { type: field.type, description: field.description ?? undefined },\n ]),\n );\n\n return new GraphQLObjectType({\n name:\n cacheCtx?.typeName({ kind: 'groupBy', defaultName: `${typeName}GroupBy`, table: tableName }) ??\n `${typeName}GroupBy`,\n fields: { group: { type: new GraphQLNonNull(keysType) }, ...aggregateFields },\n });\n};\n\n/** Turns one `${typeName}Having` entry into SQL conditions over the matching aggregate expression. */\nconst havingComparisons = (expression: any, filter: Record<string, any>): any[] =>\n Object.entries(filter)\n .filter(([op, value]) => value != null && op in HAVING_OPS)\n .map(([op, value]) => HAVING_OPS[op as keyof typeof HAVING_OPS](expression, value));\n\nconst buildHavingCondition = (having: Record<string, any> | undefined, columns: Record<string, Column>) => {\n if (!having) {\n return undefined;\n }\n\n const conditions: any[] = [];\n\n for (const [key, value] of Object.entries(having)) {\n if (value == null) {\n continue;\n }\n if (key === 'count') {\n conditions.push(...havingComparisons(count(), value));\n continue;\n }\n if (!AGGREGATE_OPS.includes(key as AggregateOp)) {\n continue;\n }\n for (const [columnName, filter] of Object.entries(value as Record<string, any>)) {\n const column = columns[columnName];\n if (!column || filter == null) {\n continue;\n }\n conditions.push(...havingComparisons(OP_FNS[key as AggregateOp](column), filter));\n }\n }\n\n return conditions.length ? and(...conditions) : undefined;\n};\n\n/**\n * Creates the resolver for a table's `<plural>GroupBy` query: the same aggregates the\n * `<plural>Aggregate` query computes, but one row per distinct combination of the requested\n * columns, optionally filtered on the aggregated values with `having`.\n *\n * Shared by all three dialects — `SELECT <keys>, <aggregates> FROM t WHERE … GROUP BY <keys>\n * HAVING …` is the same everywhere.\n */\nexport const generateGroupBy = (\n db: any,\n tableName: string,\n table: Table,\n typeName: string,\n fieldName: string,\n filterArgs: GraphQLInputObjectType,\n groupByEnum: GraphQLEnumType,\n havingInput: GraphQLInputObjectType,\n filterCtx?: RelationFilterBase,\n policies?: TablePolicies,\n resolveName?: TypeNameResolver,\n): CreatedResolver => {\n const target = aggregateTarget(table, tableName, typeName, resolveName);\n const groupable = groupableColumns(table, tableName);\n const columns = getColumns(table);\n const rootTypeName =\n resolveName?.({ kind: 'groupBy', defaultName: `${typeName}GroupBy`, table: tableName }) ?? `${typeName}GroupBy`;\n const errorCtx: DrizzleErrorContext = { table: tableName, operation: 'groupBy', field: fieldName };\n\n const queryArgs = {\n groupBy: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByEnum))),\n description: 'Columns to group by. One result row per distinct combination of their values.',\n },\n where: { type: filterArgs, description: 'Filters the rows before they are grouped.' },\n having: { type: havingInput, description: 'Filters the groups after they are aggregated.' },\n ...deletedArg(policies?.softDelete, tableName, resolveName),\n };\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { groupBy?: string[]; where?: Filters<Table>; having?: Record<string, any>; deleted?: DeletedMode },\n context,\n info,\n ) => {\n try {\n const requestedKeys = [...new Set(args.groupBy ?? [])];\n if (!requestedKeys.length) {\n throw drizzleError('At least one column to group by is required!', {\n code: 'DRIZZLE_INVALID_GROUP_BY',\n });\n }\n\n const keyColumns = requestedKeys.map((columnName) => {\n const groupableColumn = groupable[columnName];\n if (!groupableColumn) {\n throw drizzleError(`Cannot group ${typeName} by ${columnName}!`, {\n code: 'DRIZZLE_INVALID_GROUP_BY',\n });\n }\n return [columnName, groupableColumn.column] as const;\n });\n\n const request = parseAggregateRequest(info, target, rootTypeName);\n const selection = {\n ...Object.fromEntries(keyColumns.map(([columnName, column]) => [`${GROUP_COL}${columnName}`, column])),\n ...request.selection,\n };\n\n let query = resolveExecutor(db, context).select(selection).from(table);\n const where = withScope(\n resolveScope(policies, context, filterCtx),\n tableName,\n table,\n args.where\n ? extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n args.deleted,\n );\n if (where) {\n query = query.where(where);\n }\n query = query.groupBy(...keyColumns.map(([, column]) => column));\n\n const havingCondition = buildHavingCondition(args.having, columns);\n if (havingCondition) {\n query = query.having(havingCondition);\n }\n\n const rows: any[] = await query;\n\n return rows.map((row) => {\n const group: Record<string, any> = {};\n for (const [columnName, column] of keyColumns) {\n const value = row[`${GROUP_COL}${columnName}`];\n const decoded =\n typeof value === 'string' && target.dateTimeColumns.has(columnName) ? parseDriverDateTime(value) : value;\n group[columnName] = value == null ? null : remapToGraphQLCore(columnName, decoded, tableName, column);\n }\n\n return { group, ...assembleAggregateRow(row, request, target) };\n });\n } catch (e) {\n throw withErrorContext(toGraphQLError(e), errorCtx);\n }\n },\n args: queryArgs,\n };\n};\n","// =============================================================================\n// Nested writes — `create` / `connect` / `disconnect` / `set` on the relation\n// fields of a table's create and update inputs.\n//\n// A nested write is always several statements (the parent row plus one per\n// relation operation), so every resolver that runs one opens a transaction —\n// a savepoint when the request already carries one. What a relation can offer\n// is decided here, at build time, from which side of the relation stores the\n// foreign key and whether that column is nullable, so the schema never advertises\n// an operation whose every call would be a database error.\n// =============================================================================\nimport { and, type Column, eq, getColumns, inArray, is, One, type Table } from 'drizzle-orm';\nimport { GraphQLBoolean, GraphQLInputObjectType, type GraphQLInputType, GraphQLList, GraphQLNonNull } from 'graphql';\nimport { capitalize } from '../case-ops/index.ts';\nimport { remapFromGraphQLSingleInput } from '../data-mappers/index.ts';\nimport { drizzleColumnToGraphQLType } from '../type-converter/index.ts';\nimport { drizzleError } from './common/errors.ts';\nimport {\n type NestedWriteOp,\n type ResolvedWriteHooks,\n runWriteHook,\n type WriteHookPayload,\n withHookColumns,\n} from './common/write-hooks.ts';\nimport {\n applyContextValues,\n type ContextValuesFor,\n extractFilters,\n type RelationFilterBase,\n relationFilterCtx,\n resolveScope,\n resolveTypeName,\n type ScopeResolver,\n type TablePolicies,\n type TypeCacheCtx,\n type TypeNameMapper,\n unwrapRelationColumn,\n visibleColumns,\n warnUnresolvedJoin,\n withScope,\n} from './common.ts';\nimport type { TableFeatures, TableNamedRelations } from './types.ts';\n\nconst ALL_OPS: readonly NestedWriteOp[] = ['create', 'connect', 'disconnect', 'set'];\n\n/**\n * How one relation can be written through, resolved once at build time.\n *\n * `fkSide` is the whole point: a relation is stored as a value in exactly one of the two\n * tables, and which one decides both what operations make sense and in what order the\n * statements have to run. When the child holds it (`Authors.posts` — `posts.author_id`),\n * the parent has to exist first and the children are attached afterwards. When the parent\n * holds it (`Posts.author` — `posts.author_id` again, seen from the other end), the target\n * row has to exist first so its key can go into the parent's own INSERT.\n */\nexport type NestedRelationPlan = {\n relationName: string;\n targetTableName: string;\n targetTable: Table;\n /** Property name of the join column on the table the input belongs to. */\n localColPropName: string;\n /** Property name of the join column on the relation's target table. */\n foreignColPropName: string;\n foreignCol: Column;\n localCol: Column;\n isOne: boolean;\n /** Which table stores the value that has to change for a row to be attached or detached. */\n fkSide: 'child' | 'parent';\n /** Whether the foreign key is nullable, and so whether a row can be detached at all. */\n canDetach: boolean;\n /** Set when the relation goes through a junction table, which is then what gets written. */\n through?: NestedThroughPlan;\n /**\n * The target's primary-key columns and the join column, keyed by property name — what a\n * nested statement on the target returns to that table's `onWrite` hook when it has one.\n */\n targetKeyColumns: Record<string, Column>;\n /**\n * The relation field's inputs the relation's shape allows (no `create` through a junction,\n * no `disconnect` / `set` on a NOT NULL key), narrowed by {@link gateNestedWritePlans} to\n * the ones whose write the table it lands on has turned on.\n */\n allowed: Set<NestedWriteOp>;\n};\n\n/**\n * The junction table of a `.through()` relation, and the two of its columns this relation\n * joins on. A many-to-many is attached and detached by inserting and deleting junction rows,\n * so neither the parent row nor the target row is written at all.\n */\nexport type NestedThroughPlan = {\n table: Table;\n /** The junction's Drizzle schema key — what its `features` and `onWrite` are keyed by. */\n tableName: string | undefined;\n /** Property name of the junction column holding the parent's key. */\n sourceColPropName: string;\n /** Property name of the junction column holding the target's key. */\n targetColPropName: string;\n sourceCol: Column;\n targetCol: Column;\n};\n\n/** Every writable relation of every table: table name → relation name → plan. */\nexport type NestedWritePlans = Record<string, Record<string, NestedRelationPlan>>;\n\n/** The nested operations of one mutation input, keyed by relation name. */\nexport type NestedOps = Record<string, Record<string, any>>;\n\n/**\n * Whether a column can be left out of an INSERT — either the database fills it in or it\n * accepts NULL.\n */\nconst isOptionalOnInsert = (column: Column): boolean =>\n !column.notNull || !!column.hasDefault || !!(column as any).defaultFn;\n\n/** The property name a column is stored under on its table, matched by identity. */\nconst propNameOf = (table: Table, column: Column | undefined): string | undefined => {\n if (!column) {\n return undefined;\n }\n for (const [propName, candidate] of Object.entries(getColumns(table))) {\n if (candidate === column) {\n return propName;\n }\n }\n return undefined;\n};\n\n/**\n * A `.through()` relation's plan: the junction table plus the two columns it joins on.\n *\n * Nothing about the parent or the target row changes when a many-to-many link is made or\n * broken — only junction rows are inserted and deleted — so `canDetach` is unconditional\n * here, and there is no nullable-foreign-key question to ask.\n *\n * Left unplanned, and so absent from the inputs: a to-one `.through()`, whose \"exactly one\n * row\" guarantee lives in the junction's constraints rather than in the relation; a relation\n * joining on more than one column per side; and a junction carrying a further NOT NULL column\n * with no default, which no `connect` operand could supply a value for.\n *\n * `onUnresolved` is called when the relation's columns are of a supported shape but cannot be\n * matched to the three tables — a drizzle-orm mismatch rather than an unsupported relation.\n */\nconst buildThroughPlan = (\n relationName: string,\n relation: any,\n table: Table,\n targetTableName: string,\n targetTable: Table,\n tableNameOf: (table: Table) => string | undefined,\n onUnresolved: () => void,\n): NestedRelationPlan | undefined => {\n if (is(relation, One)) {\n return undefined;\n }\n\n const junction = relation.throughTable as Table | undefined;\n const sourceEntries = relation.through?.source;\n const targetEntries = relation.through?.target;\n if (!junction || sourceEntries?.length !== 1 || targetEntries?.length !== 1) {\n return undefined;\n }\n if (relation.sourceColumns?.length !== 1 || relation.targetColumns?.length !== 1) {\n return undefined;\n }\n\n // Drizzle normalizes the two ends before it stores them, so `source` is the parent's side\n // even on the relation declared from the other table. Each column is looked up on the table\n // it is supposed to belong to, which is also the check that the normalization held.\n const localCol = unwrapRelationColumn(relation.sourceColumns[0]);\n const foreignCol = unwrapRelationColumn(relation.targetColumns[0]);\n const localColPropName = propNameOf(table, localCol);\n const foreignColPropName = propNameOf(targetTable, foreignCol);\n const sourceColPropName = propNameOf(junction, unwrapRelationColumn(sourceEntries[0]));\n const targetColPropName = propNameOf(junction, unwrapRelationColumn(targetEntries[0]));\n if (\n !localCol ||\n !foreignCol ||\n !localColPropName ||\n !foreignColPropName ||\n !sourceColPropName ||\n !targetColPropName\n ) {\n onUnresolved();\n return undefined;\n }\n\n const junctionColumns = getColumns(junction);\n const sourceCol = junctionColumns[sourceColPropName] as Column;\n const targetCol = junctionColumns[targetColPropName] as Column;\n const unsuppliable = Object.entries(junctionColumns).some(\n ([propName, column]) =>\n propName !== sourceColPropName && propName !== targetColPropName && !isOptionalOnInsert(column as Column),\n );\n if (unsuppliable) {\n return undefined;\n }\n\n return {\n relationName,\n targetTableName,\n targetTable,\n localColPropName,\n foreignColPropName,\n foreignCol,\n localCol,\n isOne: false,\n // The link is written after the parent row exists, exactly like a child-side foreign key.\n fkSide: 'child',\n canDetach: true,\n through: {\n table: junction,\n tableName: tableNameOf(junction),\n sourceColPropName,\n targetColPropName,\n sourceCol,\n targetCol,\n },\n targetKeyColumns: { [foreignColPropName]: foreignCol },\n allowed: new Set(['connect', 'disconnect', 'set']),\n };\n};\n\n/**\n * Which relations of which tables can be written through.\n *\n * A `.through()` (many-to-many) relation is planned too, but as a junction-table write\n * rather than a foreign-key one — see {@link buildThroughPlan}.\n *\n * Skipped, and so absent from the generated inputs rather than failing at runtime:\n * relations whose join columns cannot be read off the drizzle relation; and relations where\n * neither join column is unique, which leaves no way to tell which side stores the key.\n */\nexport const buildNestedWritePlans = (\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n resolveUniqueSets: (table: Table) => string[][],\n resolvePrimaryKeys: (table: Table) => string[],\n extractJoinColumns: (\n relEntry: TableNamedRelations,\n parentTable: Table,\n targetTable: Table,\n ) => { localColPropName: string; foreignCol: Column; foreignColPropName: string } | undefined,\n /**\n * The schema key of any table in the Drizzle schema, excluded ones included — a junction\n * table is written without being a relation target, so it is looked up here.\n */\n tableNameOf: (table: Table) => string | undefined = () => undefined,\n): NestedWritePlans => {\n const uniqueCache = new Map<string, Set<string>>();\n // Only single-column unique keys matter here: a relation joins on one column, so a\n // composite key says nothing about whether that column identifies a row on its own.\n const singleColumnUniques = (tableName: string, table: Table): Set<string> => {\n let cached = uniqueCache.get(tableName);\n if (!cached) {\n cached = new Set(\n resolveUniqueSets(table)\n .filter((set) => set.length === 1)\n .map((set) => set[0]!),\n );\n uniqueCache.set(tableName, cached);\n }\n return cached;\n };\n\n const pkCache = new Map<string, string | undefined>();\n // Only a single-column primary key identifies a row by one join column, which is the only\n // shape a relation can be written through.\n const singleColumnPk = (tableName: string, table: Table): string | undefined => {\n if (!pkCache.has(tableName)) {\n const pk = resolvePrimaryKeys(table);\n pkCache.set(tableName, pk.length === 1 ? pk[0] : undefined);\n }\n return pkCache.get(tableName);\n };\n\n const plans: NestedWritePlans = {};\n\n for (const [tableName, relations] of Object.entries(relationMap)) {\n const table = tables[tableName];\n if (!table) {\n continue;\n }\n\n const tablePlans: Record<string, NestedRelationPlan> = {};\n\n for (const [relationName, relEntry] of Object.entries(relations)) {\n const relation = (relEntry as any).relation;\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n if (!targetTable) {\n continue;\n }\n\n const omitted = `the '${relationName}' field of its nested-write create and update inputs`;\n if ((relation as any).through) {\n const throughPlan = buildThroughPlan(\n relationName,\n relation,\n table,\n targetTableName,\n targetTable,\n tableNameOf,\n () => warnUnresolvedJoin(relEntry, tableName, relationName, omitted),\n );\n if (throughPlan) {\n tablePlans[relationName] = throughPlan;\n }\n continue;\n }\n\n const joinColumns = extractJoinColumns(relEntry, table, targetTable);\n if (!joinColumns) {\n warnUnresolvedJoin(relEntry, tableName, relationName, omitted);\n continue;\n }\n const { localColPropName, foreignCol, foreignColPropName } = joinColumns;\n const localCol = getColumns(table)[localColPropName] as Column | undefined;\n if (!localCol) {\n continue;\n }\n\n const isOne = is(relation, One);\n const localIsPk = singleColumnPk(tableName, table) === localColPropName;\n const foreignIsPk = singleColumnPk(targetTableName, targetTable) === foreignColPropName;\n const localIsUnique = singleColumnUniques(tableName, table).has(localColPropName);\n const foreignIsUnique = singleColumnUniques(targetTableName, targetTable).has(foreignColPropName);\n\n // Which of the two columns actually holds the reference. A to-many is always the\n // child's — one parent column cannot point at many rows. For a to-one, the side that\n // joins on its own primary key is the one being pointed *at*, so the reference lives on\n // the other side; a unique constraint is the fallback signal when neither is a key.\n // A relation whose join column identifies a row on neither side is left out entirely:\n // there would be no way to say which row an operation meant.\n let fkSide: 'child' | 'parent';\n if (!isOne) {\n fkSide = 'child';\n } else if (foreignIsPk && !localIsPk) {\n fkSide = 'parent';\n } else if (localIsPk) {\n fkSide = 'child';\n } else if (foreignIsUnique) {\n fkSide = 'parent';\n } else if (localIsUnique) {\n fkSide = 'child';\n } else {\n continue;\n }\n\n const fkColumn = fkSide === 'child' ? foreignCol : localCol;\n const targetColumns = getColumns(targetTable);\n const targetKeyColumns: Record<string, Column> = Object.fromEntries(\n resolvePrimaryKeys(targetTable)\n .filter((name) => targetColumns[name])\n .map((name) => [name, targetColumns[name] as Column]),\n );\n targetKeyColumns[foreignColPropName] = foreignCol;\n\n tablePlans[relationName] = {\n relationName,\n targetTableName,\n targetTable,\n localColPropName,\n foreignColPropName,\n foreignCol,\n localCol,\n isOne,\n fkSide,\n canDetach: !fkColumn.notNull,\n targetKeyColumns,\n // `set` replaces a to-many's whole set, and `disconnect` / `set` need a key that can\n // be nulled. Whether the input is the update one, and whether `connect` has a filter\n // to select with, is decided where the input types are built.\n allowed: new Set<NestedWriteOp>(\n !fkColumn.notNull ? (isOne ? ['create', 'connect', 'disconnect'] : ALL_OPS) : ['create', 'connect'],\n ),\n };\n }\n\n if (Object.keys(tablePlans).length) {\n plans[tableName] = tablePlans;\n }\n }\n\n return plans;\n};\n\n/** The writes one relation-field input performs, as `[table, operation]` pairs. */\ntype RequiredWrite = { tableName: string | undefined; feature: 'insert' | 'update' | 'delete' };\n\n/**\n * Which of the target's (or junction's) write features each input of a relation needs. A\n * parent-side `connect` / `disconnect` only rewrites the parent's own column, so it needs\n * nothing of the target; a child-side one moves the target's foreign key, which is an update\n * of the target. A to-one child-side `create` also detaches the row attached before it, when\n * the key is nullable.\n */\nconst requiredWrites = (plan: NestedRelationPlan, op: NestedWriteOp): RequiredWrite[] => {\n if (plan.through) {\n const junction = plan.through.tableName;\n if (op === 'connect') {\n return [{ tableName: junction, feature: 'insert' }];\n }\n if (op === 'disconnect') {\n return [{ tableName: junction, feature: 'delete' }];\n }\n if (op === 'set') {\n return [\n { tableName: junction, feature: 'delete' },\n { tableName: junction, feature: 'insert' },\n ];\n }\n return [];\n }\n const target = plan.targetTableName;\n if (op === 'create') {\n const detaches = plan.fkSide === 'child' && plan.isOne && plan.canDetach;\n return detaches\n ? [\n { tableName: target, feature: 'insert' },\n { tableName: target, feature: 'update' },\n ]\n : [{ tableName: target, feature: 'insert' }];\n }\n return plan.fkSide === 'child' ? [{ tableName: target, feature: 'update' }] : [];\n};\n\n/**\n * Narrows every plan's `allowed` inputs to the ones whose writes the table they land on\n * permits: its `features.insert` / `update` / `delete`, and for a junction table that it is\n * not excluded. A plan left with nothing is dropped, so its relation field is not generated.\n *\n * Returns one line per input taken out, for the build note.\n */\nexport const gateNestedWritePlans = (\n plans: NestedWritePlans,\n featureOf: (tableName: string) => TableFeatures,\n isExcluded: (tableName: string) => boolean,\n): string[] => {\n const omitted: string[] = [];\n for (const [tableName, tablePlans] of Object.entries(plans)) {\n for (const [relationName, plan] of Object.entries(tablePlans)) {\n for (const op of [...plan.allowed]) {\n const blocked = requiredWrites(plan, op).filter(\n ({ tableName: target, feature }) =>\n target !== undefined && (isExcluded(target) || !featureOf(target)[feature]),\n );\n if (blocked.length) {\n plan.allowed.delete(op);\n const reasons = blocked.map(({ tableName: target, feature }) =>\n isExcluded(target!) ? `${target} is excluded` : `${target}.${feature} is off`,\n );\n omitted.push(`${tableName}.${relationName}.${op} (${[...new Set(reasons)].join(', ')})`);\n }\n }\n if (!plan.allowed.size) {\n delete tablePlans[relationName];\n }\n }\n if (!Object.keys(tablePlans).length) {\n delete plans[tableName];\n }\n }\n return omitted;\n};\n\n// ── input types ──────────────────────────────────────────────────────────────\n\n/**\n * The extra input fields nested writes add to a table's create and update inputs, plus the\n * columns whose NOT NULL requirement the create input has to relax.\n */\nexport type NestedWriteTypes = {\n /** Relation fields for `Create<Table>Input`, empty when the table has no writable relation. */\n createFields: (\n tableName: string,\n typeName: string,\n ) => Record<string, { type: GraphQLInputType; description: string }>;\n /** Relation fields for `Update<Table>Input`. */\n updateFields: (\n tableName: string,\n typeName: string,\n ) => Record<string, { type: GraphQLInputType; description: string }>;\n /**\n * Columns a relation on the same input can fill in, which therefore cannot stay required:\n * `authorId` is NOT NULL, but `author: { create: … }` supplies it.\n */\n relaxedColumns: (tableName: string) => ReadonlySet<string>;\n};\n\nconst NO_COLUMNS: ReadonlySet<string> = new Set();\n\n/**\n * Builds the nested-write input types for a schema.\n *\n * Every field map is produced lazily, from inside the enclosing input type's own thunk: the\n * operand of `connect` is the target table's `Filters` input, which does not exist yet while\n * the first table's types are being generated.\n */\nexport const createNestedWriteTypes = (params: {\n plans: NestedWritePlans;\n cacheCtx: TypeCacheCtx;\n typeNameMapper: TypeNameMapper | undefined;\n}): NestedWriteTypes => {\n const { plans, cacheCtx, typeNameMapper } = params;\n const wrapperCache = new Map<string, GraphQLInputObjectType>();\n const payloadCache = new Map<string, GraphQLInputObjectType>();\n\n /**\n * `<Type><Relation>NestedCreatePayloadInput` — the row a nested `create` inserts. Built from\n * the target's columns rather than from its create input: the join column this relation\n * fills in is left out (setting it by hand could point the new row somewhere other than its\n * parent), and the nesting stops here, so the type carries no relation fields of its own.\n *\n * The name shares the wrapper's `<Type><Relation>Nested…` segment rather than reading\n * `Create<Type><Relation>Input`, which lands in the same namespace as a table's own create\n * input: `item.type` spells `CreateItemTypeInput`, and so does a sibling table named\n * `itemType`. Two types of that name is a schema that cannot be built at all, and\n * `nestedWrites` is a whole-schema flag, so one such pair made it unusable.\n */\n const payloadType = (tableName: string, typeName: string, plan: NestedRelationPlan): GraphQLInputObjectType => {\n const key = `${tableName}.${plan.relationName}`;\n const cached = payloadCache.get(key);\n if (cached) {\n return cached;\n }\n\n const omitted = plan.fkSide === 'child' ? plan.foreignColPropName : undefined;\n // Same rule as the table's own create input: a column the server fills in from context\n // is not something a nested `create` may supply either.\n const contextColumns = cacheCtx.contextValuesOf?.(plan.targetTableName);\n const fields = Object.fromEntries(\n Object.entries(visibleColumns(plan.targetTable))\n .filter(([columnName]) => columnName !== omitted && !contextColumns?.[columnName])\n .map(([columnName, column]) => [\n columnName,\n drizzleColumnToGraphQLType(column as Column, columnName, plan.targetTableName, false, true, true),\n ]),\n );\n\n const type = new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'nestedWriteInput',\n defaultName: `${typeName}${capitalize(plan.relationName)}NestedCreatePayloadInput`,\n table: tableName,\n operation: plan.relationName,\n }),\n description:\n omitted === undefined\n ? `A new ${resolveTypeName(plan.targetTableName, typeNameMapper)} row for ${typeName}.${plan.relationName}`\n : `A new ${resolveTypeName(plan.targetTableName, typeNameMapper)} row for ${typeName}.${plan.relationName}. \\`${omitted}\\` is set from the ${typeName} row this is written with.`,\n fields,\n });\n payloadCache.set(key, type);\n return type;\n };\n\n /** The target's `Filters` input, which every `connect` / `disconnect` / `set` selects with. */\n const targetFilters = (plan: NestedRelationPlan): GraphQLInputObjectType | undefined =>\n cacheCtx.filterTypeCache.get(plan.targetTable);\n\n const listOf = (type: GraphQLInputObjectType) => new GraphQLList(new GraphQLNonNull(type));\n\n /**\n * `<Type><Relation>NestedCreateInput` / `<Type><Relation>NestedUpdateInput` — the operations\n * offered on one relation. The create variant has no `disconnect` or `set`: a row that does\n * not exist yet has nothing attached to detach or replace.\n *\n * A many-to-many relation offers no `create`: inserting a row *and* linking it is two\n * writes to two tables, and the link half is what the relation field is for. Its\n * `disconnect` and `set` do not depend on nullability, since breaking a link deletes a\n * junction row rather than nulling a column that might be NOT NULL.\n *\n * Each input is also subject to `plan.allowed` — the table it writes has to have that\n * write turned on (see {@link gateNestedWritePlans}).\n */\n const wrapperType = (\n tableName: string,\n typeName: string,\n plan: NestedRelationPlan,\n forUpdate: boolean,\n ): GraphQLInputObjectType | undefined => {\n const key = `${tableName}.${plan.relationName}.${forUpdate ? 'update' : 'create'}`;\n const cached = wrapperCache.get(key);\n if (cached) {\n return cached;\n }\n\n const filters = targetFilters(plan);\n const targetTypeName = resolveTypeName(plan.targetTableName, typeNameMapper);\n const fields: Record<string, { type: GraphQLInputType; description: string }> = {};\n\n const offers = (op: NestedWriteOp) => plan.allowed.has(op);\n\n if (plan.through) {\n // Without a `Filters` input there is no way to name the rows to link, and `create` is\n // not offered here.\n if (filters && offers('connect')) {\n fields['connect'] = {\n type: listOf(filters),\n description: `Link every existing ${targetTypeName} row these match. Already-linked rows are left alone.`,\n };\n }\n if (filters && forUpdate && offers('disconnect')) {\n fields['disconnect'] = {\n type: listOf(filters),\n description: `Unlink every linked ${targetTypeName} row these match, leaving the rows in place`,\n };\n }\n if (filters && forUpdate && offers('set')) {\n fields['set'] = {\n type: listOf(filters),\n description: `Replace the whole set: unlink everything linked, then link every ${targetTypeName} row these match. \\`set: []\\` clears the relation. Applied before \\`disconnect\\` and \\`connect\\`.`,\n };\n }\n } else if (plan.isOne) {\n if (offers('create')) {\n fields['create'] = {\n type: payloadType(tableName, typeName, plan),\n description: `Insert a ${targetTypeName} row and attach it`,\n };\n }\n if (filters && offers('connect')) {\n fields['connect'] = {\n type: filters,\n description: `Attach the existing ${targetTypeName} row this matches. Must match exactly one row.`,\n };\n }\n if (forUpdate && offers('disconnect')) {\n fields['disconnect'] = {\n type: GraphQLBoolean,\n description: `Detach the currently attached ${targetTypeName} row, leaving it in place`,\n };\n }\n } else {\n if (offers('create')) {\n fields['create'] = {\n type: listOf(payloadType(tableName, typeName, plan)),\n description: `Insert these ${targetTypeName} rows and attach them`,\n };\n }\n if (filters && offers('connect')) {\n fields['connect'] = {\n type: listOf(filters),\n description: `Attach every existing ${targetTypeName} row these match`,\n };\n }\n if (filters && forUpdate && offers('disconnect')) {\n fields['disconnect'] = {\n type: listOf(filters),\n description: `Detach every attached ${targetTypeName} row these match, leaving the rows in place`,\n };\n }\n if (filters && forUpdate && offers('set')) {\n fields['set'] = {\n type: listOf(filters),\n description: `Replace the whole set: detach everything attached, then attach every ${targetTypeName} row these match. Applied before \\`disconnect\\`, \\`connect\\` and \\`create\\`.`,\n };\n }\n }\n\n // The target's (or junction's) features can leave a relation with nothing on it, and a\n // GraphQL input object needs at least one field — so the relation is left out instead.\n if (!Object.keys(fields).length) {\n return undefined;\n }\n\n const type = new GraphQLInputObjectType({\n name: cacheCtx.typeName({\n kind: 'nestedWriteInput',\n defaultName: `${typeName}${capitalize(plan.relationName)}Nested${forUpdate ? 'Update' : 'Create'}Input`,\n table: tableName,\n operation: plan.relationName,\n }),\n description: `Writes through ${typeName}.${plan.relationName}`,\n fields,\n });\n wrapperCache.set(key, type);\n return type;\n };\n\n const relationFields = (tableName: string, typeName: string, forUpdate: boolean) => {\n const tablePlans = plans[tableName];\n if (!tablePlans) {\n return {};\n }\n return Object.fromEntries(\n Object.values(tablePlans).flatMap((plan) => {\n const wrapper = wrapperType(tableName, typeName, plan, forUpdate);\n return wrapper\n ? [[plan.relationName, { type: wrapper, description: `Writes through ${typeName}.${plan.relationName}` }]]\n : [];\n }),\n );\n };\n\n return {\n createFields: (tableName, typeName) => relationFields(tableName, typeName, false),\n updateFields: (tableName, typeName) => relationFields(tableName, typeName, true),\n relaxedColumns: (tableName) => {\n const tablePlans = plans[tableName];\n if (!tablePlans) {\n return NO_COLUMNS;\n }\n const relaxed = new Set<string>();\n for (const plan of Object.values(tablePlans)) {\n // Only a parent-side relation writes a column of *this* table, and only a column that\n // is otherwise required needs relaxing.\n if (\n plan.fkSide === 'parent' &&\n (plan.allowed.has('create') || plan.allowed.has('connect')) &&\n !isOptionalOnInsert(plan.localCol)\n ) {\n relaxed.add(plan.localColPropName);\n }\n }\n return relaxed.size ? relaxed : NO_COLUMNS;\n },\n };\n};\n\n// ── runtime ──────────────────────────────────────────────────────────────────\n\n/**\n * The request a nested write runs for. `context` drives the scope and the context values;\n * all three are what the target table's `onWrite` hooks are handed alongside the rows.\n */\nexport type NestedWriteRequest = { context?: any; args?: any; info?: any };\n\n/** What the resolvers call into. Created once per build, next to the plans it closes over. */\nexport type NestedWriteRuntime = {\n /** Whether the table has any writable relation at all — the cheap check on the hot path. */\n enabled: (tableName: string) => boolean;\n /** Splits one mutation input into plain column values and the nested operations. */\n split: (tableName: string, values: Record<string, any>) => { columns: Record<string, any>; ops: NestedOps };\n /** Whether a split produced anything to do. */\n hasOps: (ops: NestedOps) => boolean;\n /**\n * Adds the join columns the child-side operations will need to a RETURNING column map, so\n * the parent rows come back with the key their children are attached by.\n */\n withJoinColumns: <T extends Record<string, Column>>(tableName: string, ops: NestedOps, columns: T, table: Table) => T;\n /**\n * Runs the operations that have to happen *before* the parent row is written, and returns\n * the parent column values they produced.\n */\n applyParentSide: (\n executor: any,\n tableName: string,\n ops: NestedOps,\n request?: NestedWriteRequest,\n ) => Promise<Record<string, any>>;\n /** Runs the operations that attach to a parent row, once that row exists. */\n applyChildSide: (\n executor: any,\n tableName: string,\n ops: NestedOps,\n parentRows: Record<string, any>[],\n request?: NestedWriteRequest,\n ) => Promise<void>;\n};\n\n/**\n * The union of the relation names a batch of entries writes through — enough to decide which\n * join columns the whole batch's RETURNING clause needs, without inspecting each row's write.\n */\nexport const mergedOps = (entries: { ops: NestedOps }[]): NestedOps =>\n Object.assign({}, ...entries.map((entry) => entry.ops));\n\nconst asArray = (value: any): any[] => (Array.isArray(value) ? value : value === undefined ? [] : [value]);\n\nconst supplied = (value: any) => value !== undefined && value !== null;\n\n/** The write a nested statement performs on the table it lands on. */\ntype NestedOperation = 'insert' | 'update' | 'delete';\n\n/**\n * One `onWrite` call for a nested write: every statement one relation-field input runs\n * against one table with one operation, within one call of the runtime. Their rows are\n * collected and handed to `after` together, the way a root field's hook sees its whole\n * statement's rows at once.\n */\ntype HookStep = {\n tableName: string;\n operation: NestedOperation;\n op: NestedWriteOp;\n hooks: ResolvedWriteHooks;\n /** The keys the write touches plus the hook's `columns` — what each statement returns. */\n returning: Record<string, Column>;\n rows: any[];\n};\n\n/**\n * The hook calls one relation field makes. Every step is registered before the field's first\n * statement, so each `before` runs ahead of all of them and each `after` once the last has\n * returned. A table without hooks registers nothing, and its statements run exactly as they\n * did before hooks reached nested writes — no RETURNING clause is added.\n */\nconst createHookSteps = (\n onWrite: TablePolicies['onWrite'],\n executor: any,\n request: NestedWriteRequest | undefined,\n parentTable: string,\n plan: NestedRelationPlan,\n) => {\n const steps = new Map<string, HookStep>();\n const keyOf = (op: NestedWriteOp, operation: NestedOperation) => `${op}:${operation}`;\n\n const payload = (step: HookStep): Omit<WriteHookPayload, 'position' | 'rows'> => ({\n table: step.tableName,\n operation: step.operation,\n single: plan.isOne,\n args: request?.args,\n context: request?.context,\n info: request?.info,\n tx: executor,\n nested: { parentTable, relation: plan.relationName, op: step.op },\n });\n\n return {\n /** Registers the hook call for `op`'s `operation` statements, if that table has hooks. */\n add: (op: NestedWriteOp, operation: NestedOperation) => {\n const through = plan.through;\n const tableName = through ? through.tableName : plan.targetTableName;\n const hooks = tableName ? onWrite?.(tableName, operation) : undefined;\n if (!tableName || !hooks || steps.has(keyOf(op, operation))) {\n return;\n }\n const keyColumns: Record<string, Column> = through\n ? { [through.sourceColPropName]: through.sourceCol, [through.targetColPropName]: through.targetCol }\n : { ...plan.targetKeyColumns };\n steps.set(keyOf(op, operation), {\n tableName,\n operation,\n op,\n hooks,\n returning: withHookColumns(hooks, keyColumns).returning,\n rows: [],\n });\n },\n get: (op: NestedWriteOp, operation: NestedOperation) => steps.get(keyOf(op, operation)),\n /** Runs one statement, returning its rows to the step it belongs to when there is one. */\n run: async (query: any, op: NestedWriteOp, operation: NestedOperation) => {\n const step = steps.get(keyOf(op, operation));\n if (!step) {\n await query;\n return;\n }\n step.rows.push(...((await query.returning(step.returning)) as any[]));\n },\n before: async () => {\n for (const step of steps.values()) {\n await runWriteHook(step.hooks, 'before', payload(step));\n }\n },\n after: async () => {\n for (const step of steps.values()) {\n await runWriteHook(step.hooks, 'after', { ...payload(step), rows: step.rows });\n }\n },\n };\n};\n\ntype HookSteps = ReturnType<typeof createHookSteps>;\n\n/**\n * Registers the hook calls a child-side relation field will make, in the order its\n * statements run, so the `before` hooks fire in that order too. Mirrors the branches of\n * `applyChildSide` and `applyThroughOps` exactly: a step registered for an input that runs no\n * statement would fire with no rows, and one missing would miss them.\n */\nconst registerChildSteps = (steps: HookSteps, plan: NestedRelationPlan, op: Record<string, any>) => {\n if (plan.through) {\n if (supplied(op['set'])) {\n steps.add('set', 'delete');\n steps.add('set', 'insert');\n }\n if (supplied(op['disconnect'])) {\n steps.add('disconnect', 'delete');\n }\n if (supplied(op['connect'])) {\n steps.add('connect', 'insert');\n }\n return;\n }\n if (op['set'] !== undefined) {\n steps.add('set', 'update');\n }\n if (op['disconnect'] !== undefined && (!plan.isOne || op['disconnect'] === true)) {\n steps.add('disconnect', 'update');\n }\n const attachedBy = attachingOp(op);\n if (plan.isOne && attachedBy && plan.canDetach && op['set'] === undefined) {\n steps.add(attachedBy, 'update');\n }\n if (op['connect'] !== undefined) {\n steps.add('connect', 'update');\n }\n if (op['create'] !== undefined) {\n steps.add('create', 'insert');\n }\n};\n\n/** The input that attaches a row to a to-one, which detaches whatever was attached before. */\nconst attachingOp = (op: Record<string, any>): NestedWriteOp | undefined =>\n op['connect'] !== undefined ? 'connect' : op['create'] !== undefined ? 'create' : undefined;\n\nexport const createNestedWriteRuntime = (params: {\n plans: NestedWritePlans;\n filterCtx: RelationFilterBase | undefined;\n policies?: TablePolicies;\n contextValues?: ContextValuesFor;\n}): NestedWriteRuntime => {\n const { plans, filterCtx, policies, contextValues } = params;\n const onWrite = policies?.onWrite;\n\n /**\n * A `connect` / `disconnect` / `set` operand compiled to SQL. An operand that compiles to\n * nothing is rejected: `connect: {}` would otherwise attach every row in the table.\n */\n const conditionOf = (\n plan: NestedRelationPlan,\n filter: Record<string, any>,\n operation: string,\n scope: ScopeResolver | undefined,\n ) => {\n const condition = extractFilters(\n plan.targetTable,\n plan.targetTableName,\n filter,\n relationFilterCtx(filterCtx, plan.targetTableName),\n );\n if (!condition) {\n throw drizzleError(\n `Drizzle-GraphQL Error: '${operation}' on '${plan.relationName}' needs a filter that selects rows — it was given one that matches everything.`,\n { code: 'DRIZZLE_NESTED_WRITE_INVALID' },\n );\n }\n // The filter selects rows to attach or detach, so it is a write against the target\n // table and is narrowed by its scope: `connect` cannot reach a row the caller cannot\n // see, and out-of-scope rows are not detached.\n return withScope(scope, plan.targetTableName, plan.targetTable, condition)!;\n };\n\n const assertSingleOperation = (plan: NestedRelationPlan, op: Record<string, any>) => {\n const given = ['create', 'connect', 'disconnect'].filter((key) => supplied(op[key]));\n if (given.length > 1) {\n throw drizzleError(\n `Drizzle-GraphQL Error: '${plan.relationName}' takes one of ${given.join(', ')} at a time — it holds a single row.`,\n { code: 'DRIZZLE_NESTED_WRITE_INVALID' },\n );\n }\n };\n\n /** The values the junction stores for the target rows one operand selects. */\n const selectedTargetKeys = async (\n executor: any,\n plan: NestedRelationPlan,\n filter: Record<string, any>,\n operation: string,\n scope: ScopeResolver | undefined,\n ): Promise<any[]> => {\n // Only the key the junction stores is read back, so the projection asks for that column\n // alone — a wide target row is never dragged across the wire to pick one value off it.\n const rows = await executor\n .select({ [plan.foreignColPropName]: plan.foreignCol })\n .from(plan.targetTable)\n .where(conditionOf(plan, filter, operation, scope));\n return rows\n .map((row: any) => row[plan.foreignColPropName])\n .filter((value: any) => value !== undefined && value !== null);\n };\n\n /**\n * The link half of a many-to-many write: junction rows are inserted and deleted, and both\n * the parent row and the target rows are left exactly as they are.\n *\n * `connect` reads the parent's existing links first and inserts only the missing ones, so\n * re-connecting a linked row is a no-op on every dialect rather than a unique-constraint\n * error on some of them — the read and the write share the surrounding transaction, so no\n * other writer can slip a duplicate in between them.\n */\n const applyThroughOps = async (\n executor: any,\n plan: NestedRelationPlan,\n key: any,\n op: Record<string, any>,\n scope: ScopeResolver | undefined,\n steps: HookSteps,\n ) => {\n const through = plan.through!;\n\n const link = async (operands: any[], operation: 'connect' | 'set') => {\n const existing = new Set(\n (\n await executor\n .select({ [through.targetColPropName]: through.targetCol })\n .from(through.table)\n .where(eq(through.sourceCol, key))\n ).map((row: any) => row[through.targetColPropName]),\n );\n const rows: Record<string, any>[] = [];\n for (const filter of operands) {\n for (const targetKey of await selectedTargetKeys(executor, plan, filter, operation, scope)) {\n if (!existing.has(targetKey)) {\n existing.add(targetKey);\n rows.push({ [through.sourceColPropName]: key, [through.targetColPropName]: targetKey });\n }\n }\n }\n if (rows.length) {\n await steps.run(executor.insert(through.table).values(rows), operation, 'insert');\n }\n };\n\n // Replace-the-set first, so a `set` alongside a `connect` reads as \"these rows, plus that\n // one\". `set: []` unlinks everything and links nothing back, which is how the relation is\n // cleared.\n if (supplied(op['set'])) {\n await steps.run(executor.delete(through.table).where(eq(through.sourceCol, key)), 'set', 'delete');\n await link(asArray(op['set']), 'set');\n }\n\n if (supplied(op['disconnect'])) {\n for (const filter of asArray(op['disconnect'])) {\n const targetKeys = await selectedTargetKeys(executor, plan, filter, 'disconnect', scope);\n if (targetKeys.length) {\n await steps.run(\n executor\n .delete(through.table)\n .where(and(eq(through.sourceCol, key), inArray(through.targetCol, targetKeys))),\n 'disconnect',\n 'delete',\n );\n }\n }\n }\n\n if (supplied(op['connect'])) {\n await link(asArray(op['connect']), 'connect');\n }\n };\n\n const detachAll = (\n executor: any,\n plan: NestedRelationPlan,\n key: any,\n scope: ScopeResolver | undefined,\n steps: HookSteps,\n op: NestedWriteOp,\n ) =>\n steps.run(\n executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: null })\n .where(withScope(scope, plan.targetTableName, plan.targetTable, eq(plan.foreignCol, key))),\n op,\n 'update',\n );\n\n return {\n enabled: (tableName) => !!plans[tableName],\n\n split: (tableName, values) => {\n const tablePlans = plans[tableName];\n if (!tablePlans) {\n return { columns: values, ops: {} };\n }\n const columns: Record<string, any> = {};\n const ops: NestedOps = {};\n for (const [key, value] of Object.entries(values)) {\n if (tablePlans[key] && value !== undefined && value !== null) {\n ops[key] = value;\n } else if (!tablePlans[key]) {\n columns[key] = value;\n }\n }\n return { columns, ops };\n },\n\n hasOps: (ops) => Object.keys(ops).length > 0,\n\n withJoinColumns: (tableName, ops, columns, table) => {\n const tablePlans = plans[tableName];\n if (!tablePlans) {\n return columns;\n }\n const allColumns = getColumns(table);\n for (const relationName of Object.keys(ops)) {\n const plan = tablePlans[relationName];\n if (plan?.fkSide === 'child' && !(plan.localColPropName in columns) && allColumns[plan.localColPropName]) {\n (columns as any)[plan.localColPropName] = allColumns[plan.localColPropName];\n }\n }\n return columns;\n },\n\n applyParentSide: async (executor, tableName, ops, request) => {\n const tablePlans = plans[tableName];\n const patch: Record<string, any> = {};\n if (!tablePlans) {\n return patch;\n }\n const context = request?.context;\n const scope = resolveScope(policies, context, filterCtx);\n\n for (const [relationName, op] of Object.entries(ops)) {\n const plan = tablePlans[relationName];\n if (plan?.fkSide !== 'parent') {\n continue;\n }\n assertSingleOperation(plan, op);\n\n if (op['create'] !== undefined) {\n // The only parent-side input that writes the target: `connect` and `disconnect`\n // change the parent's own column, which the parent's own hooks already cover.\n const steps = createHookSteps(onWrite, executor, request, tableName, plan);\n steps.add('create', 'insert');\n await steps.before();\n const values = applyContextValues(\n remapFromGraphQLSingleInput({ ...op['create'] }, plan.targetTable),\n contextValues?.(plan.targetTableName),\n context,\n );\n // The hook's RETURNING always includes the join column, which the patch reads.\n const step = steps.get('create', 'insert');\n const inserted = await executor\n .insert(plan.targetTable)\n .values(values)\n .returning(step ? step.returning : { [plan.foreignColPropName]: plan.foreignCol });\n step?.rows.push(...inserted);\n const created = inserted[0];\n if (!created) {\n throw drizzleError(\n `Drizzle-GraphQL Error: 'create' on '${relationName}' inserted no row, so there is nothing to attach.`,\n { code: 'DRIZZLE_NESTED_WRITE_INVALID' },\n );\n }\n await steps.after();\n patch[plan.localColPropName] = created[plan.foreignColPropName];\n } else if (op['connect'] !== undefined) {\n // `rows.length` drives the match check and is unaffected by the projection, so the\n // read asks only for the key that ends up on the parent's patch.\n const rows = await executor\n .select({ [plan.foreignColPropName]: plan.foreignCol })\n .from(plan.targetTable)\n .where(conditionOf(plan, op['connect'], 'connect', scope));\n if (rows.length !== 1) {\n throw drizzleError(\n `Drizzle-GraphQL Error: 'connect' on '${relationName}' matched ${rows.length} rows — it attaches a single row, so its filter must match exactly one.`,\n { code: 'DRIZZLE_NESTED_WRITE_INVALID' },\n );\n }\n patch[plan.localColPropName] = rows[0][plan.foreignColPropName];\n } else if (op['disconnect'] === true) {\n patch[plan.localColPropName] = null;\n }\n }\n\n return patch;\n },\n\n applyChildSide: async (executor, tableName, ops, parentRows, request) => {\n const tablePlans = plans[tableName];\n if (!tablePlans) {\n return;\n }\n const context = request?.context;\n const scope = resolveScope(policies, context, filterCtx);\n\n for (const [relationName, op] of Object.entries(ops)) {\n const plan = tablePlans[relationName];\n if (plan?.fkSide !== 'child') {\n continue;\n }\n if (plan.isOne) {\n assertSingleOperation(plan, op);\n }\n\n // One hook call per input and operation for the whole batch of parent rows: an update\n // matching several rows writes each one's children, and the hook sees them together.\n const steps = createHookSteps(onWrite, executor, request, tableName, plan);\n registerChildSteps(steps, plan, op);\n await steps.before();\n\n for (const parentRow of parentRows) {\n const key = parentRow?.[plan.localColPropName];\n if (key === undefined || key === null) {\n throw drizzleError(\n `Drizzle-GraphQL Error: cannot write through '${relationName}': the ${tableName} row has no '${plan.localColPropName}' value to attach to.`,\n { code: 'DRIZZLE_NESTED_WRITE_INVALID' },\n );\n }\n\n if (plan.through) {\n await applyThroughOps(executor, plan, key, op, scope, steps);\n continue;\n }\n\n // Replace-the-set first, so a `set` alongside a `create` reads as \"these rows, plus\n // this new one\" rather than dropping the row it just inserted.\n if (op['set'] !== undefined) {\n await detachAll(executor, plan, key, scope, steps, 'set');\n for (const filter of asArray(op['set'])) {\n await steps.run(\n executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: key })\n .where(conditionOf(plan, filter, 'set', scope)),\n 'set',\n 'update',\n );\n }\n }\n\n if (op['disconnect'] !== undefined) {\n if (plan.isOne) {\n if (op['disconnect'] === true) {\n await detachAll(executor, plan, key, scope, steps, 'disconnect');\n }\n } else {\n for (const filter of asArray(op['disconnect'])) {\n await steps.run(\n executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: null })\n .where(and(eq(plan.foreignCol, key), conditionOf(plan, filter, 'disconnect', scope))),\n 'disconnect',\n 'update',\n );\n }\n }\n }\n\n // A to-one relation holds one row, so attaching a new one detaches whatever was\n // there — otherwise both rows point at this parent and the relation is ambiguous.\n const attachedBy = attachingOp(op);\n if (plan.isOne && attachedBy && plan.canDetach && op['set'] === undefined) {\n await detachAll(executor, plan, key, scope, steps, attachedBy);\n }\n\n if (op['connect'] !== undefined) {\n for (const filter of asArray(op['connect'])) {\n await steps.run(\n executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: key })\n .where(conditionOf(plan, filter, 'connect', scope)),\n 'connect',\n 'update',\n );\n }\n }\n\n if (op['create'] !== undefined) {\n const rows = asArray(op['create']).map((row) => ({\n ...applyContextValues(\n remapFromGraphQLSingleInput({ ...row }, plan.targetTable),\n contextValues?.(plan.targetTableName),\n context,\n ),\n [plan.foreignColPropName]: key,\n }));\n if (rows.length) {\n await steps.run(executor.insert(plan.targetTable).values(rows), 'create', 'insert');\n }\n }\n }\n\n await steps.after();\n }\n },\n };\n};\n\n/**\n * Runs one parent write per input entry, with that entry's nested operations around it, all\n * inside a single transaction — a savepoint when the caller already runs on one, so a failing\n * entry rolls the whole batch back.\n *\n * That transaction is also the `tx` the target tables' `onWrite` hooks run on. Every nested\n * write opens it, so a hook on a nested target has the whole tree to roll back even when the\n * root field carries no hook of its own and was not forced into a transaction for one.\n *\n * Entries are written one at a time rather than as a single multi-row statement: a nested\n * operation attaches to the row its own entry produced, so the two have to stay correlated.\n * The batch path is untouched when no entry carries a nested operation.\n */\nexport const writeWithNestedOps = async (params: {\n executor: any;\n runtime: NestedWriteRuntime;\n tableName: string;\n entries: { columns: Record<string, any>; ops: NestedOps }[];\n remapValues: (columns: Record<string, any>) => Record<string, any>;\n write: (executor: any, values: Record<string, any>) => Promise<Record<string, any>[]>;\n request?: NestedWriteRequest;\n}): Promise<Record<string, any>[]> => {\n const { executor, runtime, tableName, entries, remapValues, write, request } = params;\n\n return executor.transaction(async (tx: any) => {\n const rows: Record<string, any>[] = [];\n for (const entry of entries) {\n const patch = await runtime.applyParentSide(tx, tableName, entry.ops, request);\n const written = await write(tx, { ...remapValues(entry.columns), ...patch });\n await runtime.applyChildSide(tx, tableName, entry.ops, written, request);\n rows.push(...written);\n }\n return rows;\n });\n};\n\n/**\n * The update counterpart: one `set` whose nested operations apply to every row the `where`\n * matched. Resolves the parent-side operations into the values first, writes once, then\n * attaches to each row that came back.\n */\nexport const updateWithNestedOps = async (params: {\n executor: any;\n runtime: NestedWriteRuntime;\n tableName: string;\n columns: Record<string, any>;\n ops: NestedOps;\n remapValues: (columns: Record<string, any>) => Record<string, any>;\n write: (executor: any, values: Record<string, any>) => Promise<Record<string, any>[]>;\n request?: NestedWriteRequest;\n}): Promise<Record<string, any>[]> => {\n const { executor, runtime, tableName, columns, ops, remapValues, write, request } = params;\n\n return executor.transaction(async (tx: any) => {\n const patch = await runtime.applyParentSide(tx, tableName, ops, request);\n const rows = await write(tx, { ...remapValues(columns), ...patch });\n await runtime.applyChildSide(tx, tableName, ops, rows, request);\n return rows;\n });\n};\n","/**\n * A table the drizzle instance has no relational query builder for.\n *\n * Both the generated schema and `db.query` are keyed by the relations config, so under\n * drizzle-orm v1 the two agree by construction and this should never fire — a table left out\n * of the relations config is simply never generated for. It stays as a guard because the\n * alternative is a `TypeError` on `undefined` deep inside a resolver, and because earlier v1\n * release candidates *could* disagree: they took the schema as a separate constructor\n * argument, so a table passed there but left out of `buildRelations`/`defineRelations` was\n * generated for and then had nothing to read through.\n */\nexport const missingQueryBuilderError = (tableName: string): Error =>\n new Error(\n `Drizzle-GraphQL Error: Table '${tableName}' has no query builder on the drizzle instance, so there is nothing for its resolvers to read through. Include it in the relations you pass to buildRelations/defineRelations, or drop it from the generated schema with config.exclude.tables.`,\n );\n","// =============================================================================\n// The read side of a table's root fields: `<table>` and `<table>Single`.\n//\n// All three dialects generate these identically. Everything dialect-specific\n// about a relational read lives below this layer — `runRelationalSelect` takes\n// the NULL ordering as a parameter, and the primary-key lookup is passed in —\n// so a dialect supplies two values and gets both resolvers.\n// =============================================================================\n\nimport type { Table } from 'drizzle-orm';\nimport type { RelationalQueryBuilder } from 'drizzle-orm/mysql-core/query-builders/query';\nimport type { GraphQLInputObjectType } from 'graphql';\nimport {\n applyLimitPolicy,\n type DrizzleErrorContext,\n generateDistinctEnum,\n type LimitPolicyFor,\n type NullOrdering,\n type RelationFilterBase,\n type ResolverPolicies,\n resolveObjectTypeName,\n resolveQueryExecutor,\n runRelationalSelect,\n selectArrayArgs,\n selectSingleArgs,\n type TypeNameMapper,\n type TypeNameResolver,\n toGraphQLError,\n withDefaultOrderBy,\n withErrorContext,\n} from '../builders/common.ts';\nimport type { ResolveTree } from '../parse-resolve-info.ts';\nimport { parseResolveInfo } from '../parse-resolve-info.ts';\nimport { missingQueryBuilderError } from './errors.ts';\nimport type { CreatedResolver, TableNamedRelations, TableSelectArgs } from './types.ts';\n\n/** `<table>` — the list field. */\nexport type SelectArrayGenerator = (\n db: any,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n distinctEnabled?: boolean,\n limits?: LimitPolicyFor,\n policies?: ResolverPolicies,\n /** The build's type-naming rule, which names the `distinct` enum. */\n resolveName?: TypeNameResolver,\n) => CreatedResolver;\n\n/** `<table>Single` — the same read, capped at one row. */\nexport type SelectSingleGenerator = (\n db: any,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n limits?: LimitPolicyFor,\n policies?: ResolverPolicies,\n /** The build's type-naming rule, which names the `deleted` argument's enum. */\n resolveName?: TypeNameResolver,\n) => CreatedResolver;\n\n/** The table's entry in `db.query`, which is what a relational read runs through. */\nconst queryBaseFor = (db: any, tableName: string): RelationalQueryBuilder<any, any, any> => {\n const queryBase = db.query[tableName] as RelationalQueryBuilder<any, any, any> | undefined;\n if (!queryBase) {\n throw missingQueryBuilderError(tableName);\n }\n return queryBase;\n};\n\n/**\n * Builds a dialect's two select generators.\n *\n * @param primaryKeyPropNames the dialect's composite-aware primary-key lookup\n * @param nullOrdering how the dialect's `ORDER BY` sorts NULLs, which keyset pagination has\n * to agree with\n */\nexport const createSelectGenerators = (\n primaryKeyPropNames: (table: any) => string[],\n nullOrdering: NullOrdering,\n): { generateSelectArray: SelectArrayGenerator; generateSelectSingle: SelectSingleGenerator } => {\n const generateSelectArray: SelectArrayGenerator = (\n db,\n tableName,\n tables,\n relationMap,\n orderArgs,\n filterArgs,\n fieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n distinctEnabled = true,\n limits,\n policies,\n resolveName,\n ): CreatedResolver => {\n const queryBase = queryBaseFor(db, tableName);\n\n const table = tables[tableName]!;\n const limitPolicy = limits?.(tableName);\n const pkNames = primaryKeyPropNames(table);\n const errorCtx: DrizzleErrorContext = { table: tableName, operation: 'select', field: fieldName };\n const queryArgs = selectArrayArgs(\n orderArgs,\n filterArgs,\n distinctEnabled ? generateDistinctEnum(table, typeName, resolveName, tableName) : undefined,\n policies?.softDelete,\n tableName,\n resolveName,\n );\n // The name the object type actually carries — what `fieldsByTypeName` is keyed by.\n const objectTypeName = resolveObjectTypeName(tableName, typeNameMapper, resolveName);\n\n return {\n name: fieldName,\n resolver: async (_source: any, rawArgs: Partial<TableSelectArgs>, context: any, info: any) => {\n // An omitted `orderBy` falls back to the table's configured default ordering here,\n // before anything reads the arguments — the cursor tuple and a `distinct` pass both\n // have to agree on one effective ordering.\n const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName: objectTypeName,\n typeNameMapper,\n resolveName,\n parsedInfo,\n ...args,\n limit: applyLimitPolicy(args.limit, limitPolicy),\n single: false,\n filterCtx,\n limits,\n defaultOrderBy: policies?.defaultOrderBy,\n pkNames,\n db: executor,\n scope: policies?.scope?.(context),\n nullOrdering,\n });\n } catch (e) {\n throw withErrorContext(toGraphQLError(e), errorCtx);\n }\n },\n args: queryArgs,\n };\n };\n\n const generateSelectSingle: SelectSingleGenerator = (\n db,\n tableName,\n tables,\n relationMap,\n orderArgs,\n filterArgs,\n fieldName,\n // The list field's only use for the default type name is naming its `distinct` enum,\n // and a single-row read has no `distinct` argument. The slot stays so the two\n // generators keep one positional shape at the call site in `build-context.ts`.\n _typeName,\n typeNameMapper,\n filterCtx,\n limits,\n policies,\n resolveName,\n ): CreatedResolver => {\n const queryBase = queryBaseFor(db, tableName);\n\n const queryArgs = selectSingleArgs(orderArgs, filterArgs, policies?.softDelete, tableName, resolveName);\n const objectTypeName = resolveObjectTypeName(tableName, typeNameMapper, resolveName);\n\n const table = tables[tableName]!;\n const pkNames = primaryKeyPropNames(table);\n const errorCtx: DrizzleErrorContext = { table: tableName, operation: 'select', field: fieldName };\n\n return {\n name: fieldName,\n resolver: async (_source: any, rawArgs: Partial<TableSelectArgs>, context: any, info: any) => {\n // Same as the list field: the effective ordering is resolved before anything reads it.\n const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName: objectTypeName,\n typeNameMapper,\n resolveName,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n limits,\n defaultOrderBy: policies?.defaultOrderBy,\n pkNames,\n db: executor,\n scope: policies?.scope?.(context),\n });\n } catch (e) {\n throw withErrorContext(toGraphQLError(e), errorCtx);\n }\n },\n args: queryArgs,\n };\n };\n\n return { generateSelectArray, generateSelectSingle };\n};\n","// =============================================================================\n// The part of a schema build that has nothing to do with the dialect.\n//\n// Every builder starts the same way: find the tables, resolve the feature flags,\n// flatten the relation graph, register the per-build scalar/enum/exclusion state,\n// assemble the filter context and the type cache, and generate each table's types.\n// Every builder ends the same way too, and the read half in between — the two\n// select fields, the aggregate field and the group-by field — is identical down to\n// the argument lists.\n//\n// The per-table loop is shared as well: `forEachTable` works out what every dialect\n// needs per table, calls the dialect back for the mutations it generated, and then\n// registers those and the inputs and outputs they reference. What a dialect still\n// owns is the mutation half itself — PostgreSQL and SQLite return the rows they\n// wrote, MySQL cannot, so its mutation fields, return types and resolvers differ\n// throughout.\n//\n// Keeping this shared is not just deduplication. A feature added to the prelude\n// used to reach two of the three dialects — `uniqueKeyFilters` (#90) shipped as a\n// flag MySQL accepted and never acted on, because MySQL carried its own copy.\n// =============================================================================\n\nimport { is, One, type Table } from 'drizzle-orm';\nimport type { GraphQLFieldConfig, GraphQLInputObjectType, GraphQLObjectType, GraphQLOutputType } from 'graphql';\nimport { GraphQLList, GraphQLNonNull } from 'graphql';\nimport {\n aggregateFieldComplexity,\n attachTargetPrimaryKeys,\n bindPolicies,\n buildNamedRelations,\n buildUniqueKeyMap,\n computeResolverFieldNames,\n createMutationTxCtx,\n createRelationResolverFactory,\n defineRootField,\n extractRelationJoinColumns,\n generateTableTypes,\n getUniqueColumnSets,\n type LimitPolicyFor,\n listFieldComplexity,\n type MutationTxCtx,\n type NullOrdering,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n type ResolverFieldNames,\n type ResolverPolicies,\n registerColumnExclusions,\n type SoftDeleteInfo,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n type UniqueKeyMap,\n visibleColumns,\n} from '../builders/common.ts';\nimport { type DrizzleMutationMeta, type TableFieldExtensionFactory, tableFieldExtensions } from '../extensions.ts';\nimport { resolveTableFeatures } from '../features.ts';\nimport { registerEnumConfig, registerScalarOverrides } from '../type-converter/index.ts';\nimport {\n createRelationAggregateFactory,\n generateAggregate,\n generateAggregateTypes,\n generateGroupBy,\n generateGroupByEnum,\n generateGroupByType,\n generateHavingInput,\n resetAggregateColumnCache,\n} from './aggregates.ts';\nimport {\n buildNestedWritePlans,\n createNestedWriteRuntime,\n createNestedWriteTypes,\n gateNestedWritePlans,\n type NestedWriteRuntime,\n type NestedWriteTypes,\n} from './nested-writes.ts';\nimport { createSelectGenerators } from './select.ts';\nimport type {\n CreatedResolver,\n GeneratedTableTypes,\n GeneratedTableTypesOutputs,\n SchemaGeneratorOptions,\n TableFeatures,\n TableNamedRelations,\n} from './types.ts';\n\n/** What {@link createSchemaBuilder} cannot work out for itself. */\nexport type SchemaBuildAdapter<WithReturning extends boolean = boolean> = {\n /** The dialect's table class, used with `is()` to pick tables out of the schema module. */\n tableClass: any;\n /**\n * The dialect's `getTableConfig`. The three dialects expose the same\n * `{ primaryKeys, uniqueConstraints, indexes }` shape from different modules.\n */\n getTableConfig: (table: any) => any;\n /** Primary-key property names, composite-aware — built on the dialect's `getTableConfig`. */\n primaryKeyPropNames: (table: any) => string[];\n /** How the dialect's `ORDER BY` sorts NULLs, which relation pagination has to match. */\n nullOrdering: NullOrdering;\n /**\n * Whether a write can return the rows it wrote. `false` on MySQL, which has no `RETURNING`\n * clause — its table types carry no `${Table}Item` outputs because no mutation returns one.\n */\n returnsRows: WithReturning;\n /**\n * Dialect-specific validation of the database handle against the requested options, run\n * once the tables are known but before anything is generated. SQLite uses it to reject\n * features a synchronous driver cannot support; MySQL to reject nested writes.\n */\n preflight?: (db: any, options: SchemaGeneratorOptions) => void;\n};\n\n/**\n * Everything a build accumulates before its root fields exist, handed to the dialect so it\n * can generate its mutation half against the same tables, caches and policies the shared\n * half used.\n */\nexport type SchemaBuildContext<WithReturning extends boolean = boolean> = {\n db: any;\n /** The schema module as given, including whatever is not a table. */\n schema: Record<string, unknown>;\n options: SchemaGeneratorOptions;\n /** The tables this build covers — excluded ones already dropped. */\n tables: Record<string, Table>;\n tableEntries: [string, Table][];\n /** This table's feature flags, with any per-table predicate already run. */\n featureOf: (tableName: string) => TableFeatures;\n /** Whether any table in the build wants a feature — i.e. whether to build shared machinery. */\n anyTable: (feature: keyof TableFeatures) => boolean;\n /** The full relation graph, used by type generation. */\n namedRelations: Record<string, Record<string, TableNamedRelations>>;\n /** The relations to eager-load via `with:`, used by the resolvers. */\n eagerRelations: Record<string, Record<string, TableNamedRelations>>;\n filterCtx: RelationFilterBase;\n /** The build's policies as configured, before binding. */\n tablePolicies: SchemaGeneratorOptions['policies'];\n policies: ResolverPolicies | undefined;\n softDeleteOf: NonNullable<SchemaGeneratorOptions['policies']>['softDelete'];\n resolverFactory: RelationResolverFactory;\n cacheCtx: TypeCacheCtx;\n nestedRuntime: NestedWriteRuntime | undefined;\n nestedTypes: NestedWriteTypes | undefined;\n /** Undefined unless `transactions: 'auto'`; its field-name set is filled by `finalizeBuild`. */\n mutationTxCtx: MutationTxCtx | undefined;\n gqlSchemaTypes: Record<string, GeneratedTableTypes<WithReturning>>;\n // A plain map rather than graphql's `ThunkObjMap`, which is a union with a thunk and so\n // cannot be indexed through a property. Still assignable wherever a thunk map is wanted.\n queries: Record<string, GraphQLFieldConfig<any, any>>;\n mutations: Record<string, GraphQLFieldConfig<any, any>>;\n inputs: Record<string, GraphQLInputObjectType>;\n outputs: Record<string, GraphQLObjectType>;\n limits: LimitPolicyFor | undefined;\n typeNameMapper: TypeNameMapper | undefined;\n};\n\n/**\n * One generated mutation, ready to be hung off the mutation root: what the field returns,\n * and what it says about itself. A dialect's per-table callback answers with a list of these\n * rather than registering fields itself, so the registration — and the collision check in\n * {@link defineRootField} — happens in one place for all three dialects.\n */\nexport type MutationRegistration = {\n /** Undefined when this table's features left the mutation ungenerated. */\n generated: CreatedResolver | undefined;\n type: GraphQLOutputType;\n /**\n * The identity published on `extensions.drizzle`. The count mutations carry their plural\n * sibling's operation plus `count: true`, so a wrapper gating writes on `operation` cannot\n * be bypassed by swapping in the count variant.\n */\n meta?: DrizzleMutationMeta;\n description?: string;\n};\n\n/** What a dialect's per-table callback hands back for {@link forEachTable} to register. */\nexport type TableMutations = {\n /** In registration order, which is the order the fields appear in the schema. */\n mutations: MutationRegistration[];\n /**\n * The two inputs whose presence is decided by the mutation half rather than by a feature\n * flag, and which the shared loop needs in order to know whether to publish them.\n */\n onConflictInput?: GraphQLInputObjectType;\n updateManyInput?: GraphQLInputObjectType;\n};\n\n/** The per-table values {@link forEachTable} has already worked out, handed to the dialect. */\nexport type TableBuild<WithReturning extends boolean = boolean> = {\n tableName: string;\n table: Table;\n /** This table's feature flags, with any per-table predicate already run. */\n tableFeatures: TableFeatures;\n /** Builds what a field of this table publishes under `extensions.drizzle`. */\n drizzleMeta: TableFieldExtensionFactory;\n /** The generated field names, from the naming config. */\n names: ResolverFieldNames;\n types: GeneratedTableTypes<WithReturning>;\n /** Set when the table marks rows deleted instead of removing them. */\n softDeleteInfo: SoftDeleteInfo | undefined;\n};\n\n/**\n * Binds a dialect and returns the shared halves of its build.\n *\n * Called once per dialect module at import time, so the select generators — which close over\n * the dialect's primary-key lookup and NULL ordering — are built once rather than per\n * `buildSchema`.\n */\nexport const createSchemaBuilder = <WithReturning extends boolean>(adapter: SchemaBuildAdapter<WithReturning>) => {\n const primaryKeyPropNames = adapter.primaryKeyPropNames;\n const uniqueColumnSets = (table: Table): string[][] => getUniqueColumnSets(table, adapter.getTableConfig);\n const { generateSelectArray, generateSelectSingle } = createSelectGenerators(\n primaryKeyPropNames,\n adapter.nullOrdering,\n );\n\n /** Everything up to and including each table's generated types. */\n const prepareBuild = (\n db: any,\n schema: Record<string, unknown>,\n relations: TablesRelationalConfig,\n options: SchemaGeneratorOptions,\n ): SchemaBuildContext<WithReturning> => {\n const { relationsDepthLimit, prefixes, typeNameMapper, shouldEagerLoad, features, complexity, limits } = options;\n const schemaEntries = Object.entries(schema);\n // Excluded tables are dropped here, before anything reads `tableEntries` — which also makes\n // `buildNamedRelations` skip every relation pointing at one, since it resolves targets\n // through this list.\n const excludedTables = new Set(options.exclude?.tables ?? []);\n const tableEntries = schemaEntries.filter(\n ([key, value]) => is(value, adapter.tableClass) && !excludedTables.has(key),\n ) as [string, Table][];\n const tables = Object.fromEntries(tableEntries) as Record<string, Table>;\n\n // A feature flag may be a per-table predicate, so every flag is resolved against the table\n // it applies to. `anyTable` answers the build-wide question — whether machinery shared\n // across tables is worth constructing at all.\n const featureOf = resolveTableFeatures(features);\n const anyTable = (feature: keyof TableFeatures) => tableEntries.some(([name]) => featureOf(name)[feature]);\n\n if (!tableEntries.length) {\n throw new Error(\n \"Drizzle-GraphQL Error: No tables detected in Drizzle-ORM's database instance. Did you forget to pass schema to drizzle constructor?\",\n );\n }\n\n // Resolve scalar overrides into the type-converter's registry before any type generation —\n // every subsequent column→GraphQL type decision and runtime value remap consults it.\n registerScalarOverrides(tables, options);\n // Same lifecycle: the enum registry is per-build, so a second build never reuses the first\n // build's enum types (and with them its naming decisions).\n registerEnumConfig(options);\n // And the same for column exclusions: a per-build registry read by every site that decides\n // what the schema contains, reset here so a rebuild never inherits the previous build's.\n registerColumnExclusions(tables, options.exclude);\n // Column classifications for the aggregates are cached across the tables of one build, and\n // hold that build's types and exclusions — so they are dropped here for the same reason.\n resetAggregateColumnCache();\n\n // Flatten drizzle-orm v1 TablesRelationalConfig into the canonical shape\n // used throughout common.ts: Record<tableName, Record<relName, TableNamedRelations>>\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Relations *into* an excluded table are already gone (their target no longer resolves);\n // relations *out of* one have no type left to hang a field on.\n for (const excluded of excludedTables) {\n delete namedRelations[excluded];\n }\n // Record each relation target's primary key (composite-aware) so paginated relations\n // default to a deterministic PK order. Must run before pruning / type generation, which\n // share these entry objects.\n attachTargetPrimaryKeys(namedRelations, tables, (table) => primaryKeyPropNames(table));\n // Relations to eager-load via `with:`. Query/mutation resolvers use this pruned map so\n // opted-out relations never overfetch; type generation keeps the full map so their\n // fields still exist and resolve lazily.\n const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);\n\n // A `where` field per compound unique constraint, for the tables that asked for one. Built\n // once and shared by the input types and the resolvers: the fields a request may spell and\n // the fields a resolver understands are the same map, so neither can drift from the other.\n const uniqueKeys: Record<string, UniqueKeyMap> = {};\n for (const [tableName, table] of tableEntries) {\n if (!featureOf(tableName).uniqueKeyFilters) {\n continue;\n }\n // Whatever the filter input already offers under a name keeps it — columns are added\n // first, then relations, and a key field last.\n const taken = new Set([...Object.keys(visibleColumns(table)), ...Object.keys(namedRelations[tableName] ?? {})]);\n const map = buildUniqueKeyMap(uniqueColumnSets(table), taken);\n if (Object.keys(map).length) {\n uniqueKeys[tableName] = map;\n }\n }\n\n const filterCtx: RelationFilterBase = { tables, relationMap: namedRelations, uniqueKeys };\n\n // The row scope compiled against this build's relation graph, plus the columns whose value\n // the server supplies. Both stay undefined unless configured.\n const tablePolicies = options.policies;\n const contextValuesOf = tablePolicies?.contextValues;\n const softDeleteOf = tablePolicies?.softDelete;\n const policies = bindPolicies(tablePolicies, filterCtx);\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(\n db,\n tables,\n adapter.nullOrdering,\n filterCtx,\n limits,\n tablePolicies,\n );\n\n // Fresh cache per build — prevents type name collisions when buildSchema() is called\n // multiple times.\n const cacheCtx: TypeCacheCtx = {\n typeName: options.typeName ?? ((info) => info.defaultName),\n genericFilterCache: new Map(),\n objectTypeCache: new Map(),\n relationFieldContainers: new Map(),\n fullyBuiltTables: new Set(),\n relationTypeCache: new Map(),\n selectFieldCache: new WeakMap(),\n filterFieldCache: new WeakMap(),\n orderTypeCache: new WeakMap(),\n filterTypeCache: new WeakMap(),\n listRelationFilterCache: new Map(),\n aggregateTypeCache: new Map(),\n complexity,\n limits,\n docs: options.docs ?? {},\n primaryKeyOf: (name) => (tables[name] ? primaryKeyPropNames(tables[name] as Table) : []),\n contextValuesOf,\n softDeleteOf,\n featureOf,\n uniqueKeysOf: (tableName) => uniqueKeys[tableName],\n };\n\n adapter.preflight?.(db, options);\n\n // Nested writes: the plans decide which relations are writable at all, the types add their\n // fields to the create/update inputs, and the runtime executes them. All three are left\n // undefined when the feature is off, so the inputs and the resolvers stay as they were.\n const nestedPlans = features.nestedWrites\n ? buildNestedWritePlans(\n tables,\n namedRelations,\n (target) => uniqueColumnSets(target as Table),\n (target) => primaryKeyPropNames(target as Table),\n extractRelationJoinColumns,\n // A junction is written without being a relation target, so it is named from the\n // whole schema — excluded tables included, which the gate below then refuses.\n (junction) => schemaEntries.find(([, value]) => value === junction)?.[0],\n )\n : undefined;\n // A nested write is a write to the target (or junction) table, so it obeys that table's\n // features: an input whose write is turned off there is left out of the schema.\n if (nestedPlans) {\n const omitted = gateNestedWritePlans(nestedPlans, featureOf, (tableName) => excludedTables.has(tableName));\n if (omitted.length) {\n const listed =\n omitted.length > 5 ? `${omitted.slice(0, 5).join(', ')} and ${omitted.length - 5} more` : omitted.join(', ');\n console.warn(\n `Drizzle-GraphQL Warning: config.features — nestedWrites leaves out the nested inputs whose table has that write turned off: ${listed}.`,\n );\n }\n }\n const nestedTypes = nestedPlans\n ? createNestedWriteTypes({ plans: nestedPlans, cacheCtx, typeNameMapper })\n : undefined;\n const nestedRuntime = nestedPlans\n ? createNestedWriteRuntime({\n plans: nestedPlans,\n filterCtx,\n policies: tablePolicies,\n contextValues: contextValuesOf,\n })\n : undefined;\n\n // Built when at least one table wants relation aggregates; a table that has them off is\n // handed `undefined` below, so `generateTableTypes` emits no `${relation}Aggregate` fields\n // on its object type.\n const relationAggregateFactory: RelationAggregateFactory | undefined = anyTable('relationAggregates')\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx, tablePolicies)\n : undefined;\n\n const gqlSchemaTypes = Object.fromEntries(\n Object.entries(tables).map(([tableName, _table]) => [\n tableName,\n generateTableTypes(\n tableName,\n tables,\n namedRelations,\n adapter.returnsRows,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n prefixes.insert,\n prefixes.update,\n resolverFactory,\n featureOf(tableName).relationAggregates ? relationAggregateFactory : undefined,\n nestedTypes,\n ),\n ]),\n ) as Record<string, GeneratedTableTypes<WithReturning>>;\n\n return {\n db,\n schema,\n options,\n tables,\n tableEntries,\n featureOf,\n anyTable,\n namedRelations,\n eagerRelations,\n filterCtx,\n tablePolicies,\n policies,\n softDeleteOf,\n resolverFactory,\n cacheCtx,\n nestedRuntime,\n nestedTypes,\n // Shared per-request transaction machinery for multi-mutation documents; undefined\n // unless `transactions: 'auto'`. Its field-name set is filled once all mutations exist.\n mutationTxCtx: createMutationTxCtx(options.transactions),\n gqlSchemaTypes,\n queries: {},\n mutations: {},\n inputs: {},\n outputs: {},\n limits,\n typeNameMapper,\n };\n };\n\n /**\n * The table's read fields — both selects, the aggregate and the group-by — generated and\n * hung off the query root. Identical for every dialect: a read returns rows everywhere.\n *\n * The types it built are returned rather than registered, because where they land in the\n * schema's type map is the caller's business — MySQL has no `${Table}Item` output to\n * interleave them with, and the printed order of the two schemas should not drift.\n */\n const addReadFields = (\n ctx: SchemaBuildContext<WithReturning>,\n tableName: string,\n names: ResolverFieldNames,\n tableTypes: GeneratedTableTypes<WithReturning>,\n drizzleMeta: TableFieldExtensionFactory,\n ) => {\n const { db, tables, cacheCtx, filterCtx, eagerRelations, policies, tablePolicies, limits, typeNameMapper } = ctx;\n const { complexity } = ctx.options;\n const table = tables[tableName] as Table;\n const tableFeatures = ctx.featureOf(tableName);\n const { tableFilters, tableOrder } = tableTypes.inputs;\n const { selectSingleOutput, selectArrOutput } = tableTypes.outputs;\n const { typeName, listFieldName, singleFieldName, aggregateFieldName, groupByFieldName } = names;\n\n const selectArrGenerated = generateSelectArray(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n listFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n tableFeatures.distinct,\n limits,\n policies,\n cacheCtx.typeName,\n );\n const selectSingleGenerated = generateSelectSingle(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n singleFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n limits,\n policies,\n cacheCtx.typeName,\n );\n\n const aggregateType = tableFeatures.aggregates\n ? generateAggregateTypes(table, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = tableFeatures.aggregates\n ? generateAggregate(\n db,\n tableName,\n table,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n tablePolicies,\n cacheCtx.typeName,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n tableFeatures.aggregates && tableFeatures.groupBy\n ? generateGroupByType(table, tableName, typeName, cacheCtx)\n : undefined;\n const groupByEnum = groupByType ? generateGroupByEnum(table, tableName, typeName, cacheCtx) : undefined;\n const havingInput = groupByEnum ? generateHavingInput(table, tableName, typeName, cacheCtx) : undefined;\n const groupByGenerated =\n groupByType && groupByEnum && havingInput\n ? generateGroupBy(\n db,\n tableName,\n table,\n typeName,\n groupByFieldName,\n tableFilters,\n groupByEnum,\n havingInput,\n filterCtx,\n tablePolicies,\n cacheCtx.typeName,\n )\n : undefined;\n\n defineRootField(ctx.queries, 'query', selectArrGenerated.name, {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: listFieldComplexity(complexity, limits?.(tableName)) } : {}),\n },\n });\n defineRootField(ctx.queries, 'query', selectSingleGenerated.name, {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: true, targetArg: 'where' }),\n },\n });\n if (aggregateGenerated && aggregateType) {\n defineRootField(ctx.queries, 'query', aggregateGenerated.name, {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'aggregate', single: true, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n });\n }\n if (groupByGenerated && groupByType) {\n defineRootField(ctx.queries, 'query', groupByGenerated.name, {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'groupBy', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n });\n }\n\n return { aggregateType, groupByType, havingInput };\n };\n\n /**\n * The per-table loop, run once for every table the build covers.\n *\n * The dialect's callback receives the values the loop has already worked out — the feature\n * flags, the extension factory, the field names, the table's generated types and its\n * soft-delete config — and answers with the mutations it generated. Registering them, and\n * registering the inputs and outputs those mutations reference, happens here: both sides\n * did it identically, down to the `description` strings on the count mutations, so a gate\n * changed on one side and forgotten on the other used to be a silent dialect divergence.\n *\n * What stays in the dialect is what genuinely differs — which generators run, what each\n * mutation returns, and (on MySQL) that a write cannot report the rows it touched.\n */\n const forEachTable = (\n ctx: SchemaBuildContext<WithReturning>,\n perTable: (build: TableBuild<WithReturning>) => TableMutations,\n ): void => {\n const { schema, featureOf, softDeleteOf, typeNameMapper, gqlSchemaTypes, mutations, inputs, outputs } = ctx;\n const { prefixes, suffixes } = ctx.options;\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n // Everything this table generates, with any per-table predicate already run.\n const tableFeatures = featureOf(tableName);\n // What every field this table generates publishes about itself under `extensions.drizzle`,\n // so a wrapper can read a field's identity instead of parsing its configurable name.\n const drizzleMeta = tableFieldExtensions(tableName, primaryKeyPropNames(schema[tableName] as Table));\n // Compute field names using the mapper logic\n const names = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\n // A table that marks rows deleted instead of removing them also gets the mutation that\n // reverses it — clearing the column through an ordinary update is not possible, since the\n // column is not in the update input and a marked row is invisible to a `where` anyway.\n const softDeleteInfo = softDeleteOf?.(tableName);\n\n // Both selects, the aggregate and the group-by: generated and hung off the query root\n // by the shared builder, since a read is a read on every dialect.\n const readTypes = addReadFields(ctx, tableName, names, tableTypes, drizzleMeta);\n\n const built = perTable({\n tableName,\n table: schema[tableName] as Table,\n tableFeatures,\n drizzleMeta,\n names,\n types: tableTypes,\n softDeleteInfo,\n });\n\n for (const { generated, type, meta, description } of built.mutations) {\n if (generated) {\n defineRootField(mutations, 'mutation', generated.name, {\n type,\n args: generated.args,\n resolve: generated.resolver,\n ...(meta ? { extensions: { drizzle: drizzleMeta({ kind: 'mutation', ...meta }) } } : {}),\n ...(description ? { description } : {}),\n });\n }\n }\n\n const { insertInput, updateInput, tableFilters, tableOrder } = tableTypes.inputs;\n // The insert/update inputs are still built (they type the mutations that survive) but\n // only reach the schema's type map when a mutation actually references them.\n const activeInputs = [\n // The insert input types the upsert mutations too, so either feature keeps it.\n ...(tableFeatures.insert || built.onConflictInput ? [insertInput] : []),\n ...(built.onConflictInput ? [built.onConflictInput] : []),\n ...(tableFeatures.update ? [updateInput] : []),\n ...(built.updateManyInput ? [built.updateManyInput] : []),\n tableFilters,\n tableOrder,\n ];\n activeInputs.forEach((e) => {\n inputs[e.name] = e;\n });\n const { selectSingleOutput } = tableTypes.outputs;\n outputs[selectSingleOutput.name] = selectSingleOutput;\n if (adapter.returnsRows) {\n // Only a dialect with RETURNING has a `${Table}Item` type — its mutations answer with\n // one, where MySQL's answer with the build's shared `MutationReturn`.\n const { singleTableItemOutput } = tableTypes.outputs as GeneratedTableTypesOutputs<true>;\n outputs[singleTableItemOutput.name] = singleTableItemOutput;\n }\n const { aggregateType, groupByType, havingInput } = readTypes;\n if (aggregateType) {\n outputs[aggregateType.name] = aggregateType;\n }\n if (groupByType && havingInput) {\n outputs[groupByType.name] = groupByType;\n inputs[havingInput.name] = havingInput;\n }\n }\n };\n\n /** The relation field resolvers and the transaction roster, once every root field exists. */\n const finalizeBuild = (ctx: SchemaBuildContext<WithReturning>): any => {\n // Every generated mutation name is now known — the first mutation resolver of a request\n // uses this set to count the document's root mutation fields (and to leave documents\n // containing consumer-added mutations alone).\n if (ctx.mutationTxCtx) {\n for (const name of Object.keys(ctx.mutations)) {\n ctx.mutationTxCtx.fieldNames.add(name);\n }\n }\n\n const fieldResolvers: Record<string, Record<string, any>> = {};\n for (const [tableName, tableRelations] of Object.entries(ctx.namedRelations)) {\n const relResolvers: Record<string, any> = {};\n for (const [relName, relEntry] of Object.entries(tableRelations)) {\n const isOne = is((relEntry as any).relation ?? relEntry, One);\n const resolver = ctx.resolverFactory({ tableName, relationName: relName, relEntry, isOne });\n if (resolver) {\n relResolvers[relName] = resolver;\n }\n }\n if (Object.keys(relResolvers).length > 0) {\n fieldResolvers[tableName] = relResolvers;\n }\n }\n\n return {\n queries: ctx.queries,\n mutations: ctx.mutations,\n inputs: ctx.inputs,\n types: ctx.outputs,\n fieldResolvers,\n };\n };\n\n return { primaryKeyPropNames, uniqueColumnSets, prepareBuild, forEachTable, finalizeBuild };\n};\n","import type { Table } from 'drizzle-orm';\nimport { type MySqlAsyncDatabase, MySqlTable, getTableConfig as mysqlTableConfig } from 'drizzle-orm/mysql-core';\nimport {\n GraphQLBoolean,\n type GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n applyContextValues,\n applyContextValuesAll,\n assertSingleMatch,\n drizzleError,\n extractFilters,\n generateOnConflictInput,\n generateUpdateManyInput,\n generateWriteCount,\n getPrimaryKeyPropNamesFromConfig,\n hardDeleteArg,\n type MutationTxCtx,\n memoizeTableConfig,\n mysqlValuesColumnRef,\n type OnConflictArg,\n type RelationFilterBase,\n type ResolverPolicies,\n relationFilterCtx,\n resolveConflictPlan,\n scopedWhere,\n stripContextValues,\n type TablesRelationalConfig,\n type WriteOperation,\n withScope,\n writeResolver,\n} from '../builders/common.ts';\nimport { remapFromGraphQLArrayInput, remapFromGraphQLSingleInput } from '../data-mappers/index.ts';\nimport type { DrizzleMutationMeta } from '../extensions.ts';\nimport { createSchemaBuilder, type MutationRegistration } from './build-context.ts';\nimport { remapUpdateInput } from './field-updates.ts';\nimport type { CreatedResolver, Filters, SchemaGeneratorOptions } from './types.ts';\n\n// Every MySQL mutation answers `{ isSuccess: true }`: with no RETURNING clause there is\n// nothing else the statement can report.\nconst isSuccess = { isSuccess: true };\n\nconst generateInsertArray = (\n db: MySqlAsyncDatabase<any, any>,\n tableName: string,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n txCtx?: MutationTxCtx,\n policies?: ResolverPolicies,\n): CreatedResolver =>\n writeResolver<{ values: Record<string, any>[] }>({\n db,\n tableName,\n operation: 'insert',\n single: false,\n fieldName,\n txCtx,\n policies,\n args: {\n values: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(baseType))),\n },\n },\n run: async ({ executor, args, context, before, after }) => {\n const input = applyContextValuesAll(\n remapFromGraphQLArrayInput(args.values, table),\n policies?.contextValues?.(tableName),\n context,\n );\n if (!input.length) {\n throw drizzleError('No values were provided!', { code: 'DRIZZLE_NO_VALUES' });\n }\n await before();\n\n await executor.insert(table).values(input);\n\n await after();\n return isSuccess;\n },\n });\n\nconst generateInsertSingle = (\n db: MySqlAsyncDatabase<any, any>,\n tableName: string,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n txCtx?: MutationTxCtx,\n policies?: ResolverPolicies,\n): CreatedResolver =>\n writeResolver<{ values: Record<string, any> }>({\n db,\n tableName,\n operation: 'insert',\n single: true,\n fieldName,\n txCtx,\n policies,\n args: {\n values: {\n type: new GraphQLNonNull(baseType),\n },\n },\n run: async ({ executor, args, context, before, after }) => {\n await before();\n const input = applyContextValues(\n remapFromGraphQLSingleInput(args.values, table),\n policies?.contextValues?.(tableName),\n context,\n );\n\n await executor.insert(table).values(input);\n\n await after();\n return isSuccess;\n },\n });\n\nconst generateUpsert = (\n db: MySqlAsyncDatabase<any, any>,\n tableName: string,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n onConflictType: GraphQLInputObjectType,\n fieldName: string,\n single: boolean,\n txCtx?: MutationTxCtx,\n policies?: ResolverPolicies,\n): CreatedResolver => {\n const pkNames = mysqlPrimaryKeyPropNames(table);\n\n return writeResolver<{ values: Record<string, any> | Record<string, any>[]; onConflict?: OnConflictArg }>({\n db,\n tableName,\n operation: 'upsert',\n single,\n fieldName,\n txCtx,\n policies,\n args: {\n values: {\n type: single ? new GraphQLNonNull(baseType) : new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(baseType))),\n },\n onConflict: {\n type: onConflictType,\n description: 'How a conflicting row is resolved. Defaults to overwriting it.',\n },\n },\n run: async ({ executor, args, context, before, after }) => {\n const input = applyContextValuesAll(\n single\n ? [remapFromGraphQLSingleInput(args.values as Record<string, any>, table)]\n : remapFromGraphQLArrayInput(args.values as Record<string, any>[], table),\n policies?.contextValues?.(tableName),\n context,\n );\n if (!input.length) {\n throw drizzleError('No values were provided!', { code: 'DRIZZLE_NO_VALUES' });\n }\n await before();\n\n // MySQL's ON DUPLICATE KEY UPDATE fires on whichever unique key was violated, so\n // there is no target to resolve and no predicate to attach.\n const plan = resolveConflictPlan({\n table,\n values: input,\n onConflict: args.onConflict,\n pkNames,\n uniqueSets: [],\n excludedRef: mysqlValuesColumnRef,\n withTarget: false,\n });\n\n if (plan.action === 'NOTHING') {\n // INSERT IGNORE is the closest MySQL gets to DO NOTHING.\n await executor.insert(table).ignore().values(input);\n } else {\n await executor.insert(table).values(input).onDuplicateKeyUpdate({ set: plan.set });\n }\n\n await after();\n return isSuccess;\n },\n });\n};\n\nconst generateUpdate = (\n db: MySqlAsyncDatabase<any, any>,\n tableName: string,\n table: MySqlTable,\n setArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n single: boolean,\n requireWhere: boolean,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n policies?: ResolverPolicies,\n): CreatedResolver =>\n writeResolver<{ where?: Filters<Table>; set: Record<string, any> }>({\n db,\n tableName,\n operation: 'update',\n single,\n fieldName,\n txCtx,\n policies,\n args: {\n set: {\n type: new GraphQLNonNull(setArgs),\n },\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n },\n run: async ({ executor, args, context, before, after }) => {\n const { where, set } = args;\n const scope = policies?.scope?.(context);\n\n // A context-derived column is the server's to set, so an update never reassigns\n // one — that is what stops a row being handed to another owner.\n const input = stripContextValues(remapUpdateInput(set, table, tableName), policies?.contextValues?.(tableName));\n if (!Object.keys(input).length) {\n throw drizzleError('Unable to update with no values specified!', { code: 'DRIZZLE_NO_VALUES' });\n }\n await before();\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // The scope is ANDed on last, so a caller-supplied `where` can only narrow it.\n const filters = scopedWhere({\n scope,\n tableName,\n table,\n where,\n relationCtx,\n required: single || requireWhere,\n });\n\n if (single) {\n await assertSingleMatch(executor, table, filters!);\n }\n\n let query = executor.update(table).set(input);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n await query;\n\n await after();\n return isSuccess;\n },\n });\n\n/**\n * `update<Table>Many` — batch update with a per-entry `set` and `where`.\n *\n * The entries run as one UPDATE statement each, in input order, inside a single\n * transaction (a savepoint when the request context already carries one), so a failing\n * entry rolls the whole batch back and a row matched by several entries sees them applied\n * in order. MySQL has no RETURNING, so — like every other MySQL mutation — the result is\n * `{ isSuccess: true }` rather than the updated rows.\n */\nconst generateUpdateMany = (\n db: MySqlAsyncDatabase<any, any>,\n tableName: string,\n table: MySqlTable,\n updateManyInput: GraphQLInputObjectType,\n fieldName: string,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n policies?: ResolverPolicies,\n): CreatedResolver =>\n writeResolver<{ updates: { where?: Filters<Table>; set: Record<string, any> }[] }>({\n db,\n tableName,\n operation: 'updateMany',\n single: false,\n fieldName,\n txCtx,\n policies,\n args: {\n updates: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(updateManyInput))),\n },\n },\n run: async ({ executor, args, context, before, after }) => {\n const { updates } = args;\n if (!updates.length) {\n throw drizzleError('No updates were provided!', { code: 'DRIZZLE_NO_VALUES' });\n }\n await before();\n const scope = policies?.scope?.(context);\n const contextColumns = policies?.contextValues?.(tableName);\n\n // Remap and validate every entry before the transaction opens, so a malformed\n // entry rejects the request instead of rolling back mid-batch.\n const entries = updates.map(({ where, set }) => {\n const input = stripContextValues(remapUpdateInput(set, table, tableName), contextColumns);\n if (!Object.keys(input).length) {\n throw drizzleError('Unable to update with no values specified!', { code: 'DRIZZLE_NO_VALUES' });\n }\n return {\n set: input,\n filters: withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n ),\n };\n });\n\n // On a caller-supplied transaction — or the shared multi-mutation transaction\n // opened by `runMutation` — this opens a savepoint, so the batch stays atomic\n // without breaking the outer transaction.\n await executor.transaction(async (tx: any) => {\n for (const entry of entries) {\n let query = tx.update(table).set(entry.set);\n if (entry.filters) {\n query = query.where(entry.filters) as any;\n }\n await query;\n }\n });\n\n await after();\n return isSuccess;\n },\n });\n\n/**\n * `delete<Table>` and, for a table that declares a soft-delete column, `restore<Table>`.\n * MySQL's writes return no rows either way, so both answer `{ isSuccess: true }` — the\n * difference from the other dialects is only what the payload can say, not what runs.\n *\n * A table that opted into `hardDelete` also takes `hard: true`, which issues the real\n * `DELETE` instead of writing the marker, reading at `INCLUDE` so it reaches marked rows.\n */\nconst generateDelete = (\n db: MySqlAsyncDatabase<any, any>,\n tableName: string,\n table: MySqlTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n single: boolean,\n requireWhere: boolean,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n policies?: ResolverPolicies,\n restore: boolean = false,\n): CreatedResolver => {\n const softDelete = policies?.softDelete?.(tableName);\n const operation: WriteOperation = restore ? 'restore' : 'delete';\n // Only a soft-deleting table that opted in gets the argument, so the schema itself says\n // which tables can be purged — and `restore` never takes one, having nothing to remove.\n const canHardDelete = !restore && softDelete?.hardDelete === true;\n\n return writeResolver<{ where?: Filters<Table>; hard?: boolean }>({\n db,\n tableName,\n operation,\n single,\n fieldName,\n txCtx,\n policies,\n args: {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n ...(canHardDelete ? { hard: hardDeleteArg } : {}),\n },\n run: async ({ executor, args, context, before, after }) => {\n await before();\n const { where } = args;\n // `canHardDelete` decides whether the argument exists; this decides what it does,\n // so a stitched-in `hard: true` on a table that never opted in stays a soft delete.\n const hard = canHardDelete && args.hard === true;\n const scope = policies?.scope?.(context);\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // Same rule as update: the scope is ANDed on last, so a delete can only ever reach\n // rows inside it — an out-of-scope row is not matched rather than being refused.\n // A soft-deleting table adds the marker predicate the same way: `delete` only sees\n // rows that are not already marked, `restore` only sees the ones that are.\n const filters = scopedWhere({\n scope,\n tableName,\n table,\n where,\n relationCtx,\n required: single || requireWhere,\n // A hard delete reads at INCLUDE: the rows it mostly exists to remove are the\n // ones already marked, which the default EXCLUDE could not reach at all.\n deleted: restore ? 'ONLY' : hard ? 'INCLUDE' : undefined,\n });\n\n if (single) {\n await assertSingleMatch(executor, table, filters!);\n }\n\n let query =\n softDelete && !hard\n ? executor\n .update(table)\n .set({ [softDelete.columnName]: restore ? softDelete.writeRestored : softDelete.writeDeleted() })\n : executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n await query;\n\n await after();\n return isSuccess;\n },\n });\n};\n\n/** The dialect's table config, cached per table — see {@link memoizeTableConfig}. */\nconst getTableConfig = memoizeTableConfig(mysqlTableConfig);\n\n/** Primary-key property names for a MySQL table, including table-level composite keys. */\nconst mysqlPrimaryKeyPropNames = (table: MySqlTable): string[] =>\n getPrimaryKeyPropNamesFromConfig(table, getTableConfig);\n\n// MySQL sorts NULLs as the smallest values (first in ASC), and its writes return no rows.\nconst { prepareBuild, forEachTable, finalizeBuild } = createSchemaBuilder({\n tableClass: MySqlTable,\n getTableConfig,\n primaryKeyPropNames: mysqlPrimaryKeyPropNames,\n nullOrdering: 'nulls-smallest',\n returnsRows: false,\n // A nested write reads the key of the row it just wrote back out of the statement that\n // wrote it, which MySQL has no RETURNING clause for.\n preflight: (_db, options) => {\n if (options.features.nestedWrites) {\n throw new Error(\n 'Drizzle-GraphQL Error: features.nestedWrites is not supported on MySQL — a nested write needs the parent row it just inserted returned to it, and MySQL has no RETURNING clause.',\n );\n }\n },\n});\n\nexport const generateSchemaData = <\n TDrizzleInstance extends MySqlAsyncDatabase<any, any>,\n TSchema extends Record<string, Table | unknown>,\n>(\n db: TDrizzleInstance,\n schema: TSchema,\n relations: TablesRelationalConfig,\n options: SchemaGeneratorOptions,\n): GeneratedEntities<TDrizzleInstance, TSchema> => {\n const { prefixes } = options;\n\n // Table discovery, the relation graph, the per-build registries, the filter context, the\n // type cache and every table's types — all of it dialect-independent, so all of it lives\n // in `build-context.ts` and is shared with the PostgreSQL/SQLite builder.\n const ctx = prepareBuild(db, schema as Record<string, unknown>, relations, options);\n const { anyTable, filterCtx, policies, cacheCtx, mutationTxCtx, outputs } = ctx;\n\n // MySQL cannot return the rows a write touched, so every mutation reports only whether it\n // succeeded — one shared type for the whole build.\n const mutationReturnType = new GraphQLObjectType({\n name: cacheCtx.typeName({ kind: 'shared', defaultName: 'MutationReturn' }),\n fields: {\n isSuccess: {\n type: new GraphQLNonNull(GraphQLBoolean),\n },\n },\n });\n // Every MySQL mutation returns it, so it only belongs in the type map when at least one\n // mutation is generated.\n if ((['insert', 'upsert', 'update', 'delete'] as const).some((feature) => anyTable(feature))) {\n outputs['MutationReturn'] = mutationReturnType;\n }\n\n forEachTable(ctx, ({ tableName, tableFeatures, names, types, softDeleteInfo }) => {\n const { insertInput, updateInput, tableFilters } = types.inputs;\n const {\n typeName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n updateManyFieldName,\n updateSingleFieldName,\n updateCountFieldName,\n deleteFieldName,\n deleteSingleFieldName,\n restoreFieldName,\n restoreSingleFieldName,\n deleteCountFieldName,\n } = names;\n\n const insertArrGenerated = tableFeatures.insert\n ? generateInsertArray(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n createArrayFieldName,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const insertSingleGenerated = tableFeatures.insert\n ? generateInsertSingle(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n createSingleFieldName,\n mutationTxCtx,\n policies,\n )\n : undefined;\n // MySQL detects a conflict on any unique key, so unlike PostgreSQL and SQLite every\n // table can be upserted — there is no target to validate.\n const onConflictInput = tableFeatures.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as MySqlTable,\n tableName,\n typeName,\n uniqueSets: [],\n tableFilters,\n withTarget: false,\n cacheCtx,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n onConflictInput,\n upsertArrayFieldName,\n false,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const upsertSingleGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n onConflictInput,\n upsertSingleFieldName,\n true,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const updateGenerated = tableFeatures.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateFieldName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const updateSingleGenerated = tableFeatures.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n tableFeatures.update && tableFeatures.updateMany\n ? generateUpdateManyInput({\n tableName,\n typeName,\n updatePrefix: prefixes.update,\n updateInput,\n tableFilters,\n cacheCtx,\n })\n : undefined;\n const updateManyGenerated = updateManyInput\n ? generateUpdateMany(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateManyInput,\n updateManyFieldName,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const deleteGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteFieldName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const deleteSingleGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteSingleFieldName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const restoreGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n restoreFieldName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n const restoreSingleGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n restoreSingleFieldName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n // The count variants are the plural write with its payload left off, so each follows the\n // same feature switch — and the same scope, soft-delete, context-value and hook rules —\n // as the write it mirrors. No RETURNING here, so an `after` hook sees `rows: []`, exactly\n // as it does on the plural MySQL write.\n const updateCountGenerated =\n tableFeatures.update && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as MySqlTable,\n kind: 'update',\n setArgs: updateInput,\n filterArgs: tableFilters,\n fieldName: updateCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n policies,\n returnsRows: false,\n })\n : undefined;\n const deleteCountGenerated =\n tableFeatures.delete && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as MySqlTable,\n kind: 'delete',\n filterArgs: tableFilters,\n fieldName: deleteCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n policies,\n returnsRows: false,\n })\n : undefined;\n // Each mutation is paired with the identity it publishes on `extensions.drizzle`, so a\n // consumer can tell an insert from an upsert without unpicking the configured prefixes —\n // and, for a delete, whether the field can purge rather than mark. Every row-touching\n // mutation shares one return type here, since MySQL answers with `isSuccess` rather than\n // with rows; the count pair is the exception, returning `Int!` and marked `count: true`.\n const hardDeleteMeta = softDeleteInfo?.hardDelete ? ({ hardDelete: true } as const) : {};\n const withMeta = (generated: CreatedResolver | undefined, meta: DrizzleMutationMeta): MutationRegistration => ({\n generated,\n type: mutationReturnType,\n meta,\n });\n const generatedMutations: MutationRegistration[] = [\n withMeta(insertArrGenerated, { operation: 'insert', single: false, targetArg: 'values' }),\n withMeta(insertSingleGenerated, { operation: 'insert', single: true, targetArg: 'values' }),\n withMeta(upsertArrGenerated, { operation: 'upsert', single: false, targetArg: 'values' }),\n withMeta(upsertSingleGenerated, { operation: 'upsert', single: true, targetArg: 'values' }),\n withMeta(updateGenerated, { operation: 'update', single: false, targetArg: 'where' }),\n withMeta(updateManyGenerated, { operation: 'updateMany', single: false, targetArg: 'updates' }),\n withMeta(updateSingleGenerated, { operation: 'update', single: true, targetArg: 'where' }),\n withMeta(deleteGenerated, { operation: 'delete', single: false, targetArg: 'where', ...hardDeleteMeta }),\n withMeta(deleteSingleGenerated, { operation: 'delete', single: true, targetArg: 'where', ...hardDeleteMeta }),\n withMeta(restoreGenerated, { operation: 'restore', single: false, targetArg: 'where' }),\n withMeta(restoreSingleGenerated, { operation: 'restore', single: true, targetArg: 'where' }),\n {\n generated: updateCountGenerated,\n type: new GraphQLNonNull(GraphQLInt),\n meta: { operation: 'update', single: false, targetArg: 'where', count: true },\n description:\n 'How many rows the update touched. The rows themselves are not read back, which is the point of this mutation.',\n },\n {\n generated: deleteCountGenerated,\n type: new GraphQLNonNull(GraphQLInt),\n meta: { operation: 'delete', single: false, targetArg: 'where', count: true, ...hardDeleteMeta },\n description:\n 'How many rows the delete removed — or, on a soft-deleting table, marked deleted. The rows themselves are not read back, which is the point of this mutation.',\n },\n ];\n\n return { mutations: generatedMutations, onConflictInput, updateManyInput };\n });\n\n return finalizeBuild(ctx);\n};\n","// The five write resolvers PostgreSQL and SQLite generate identically.\n//\n// Both dialects insert/upsert/update/delete through the same drizzle-orm surface, so these\n// bodies were duplicated verbatim between pg.ts and sqlite.ts. The only differences were the\n// dialect spellings of `db` and `table` and how primary-key prop names are derived — the\n// first two collapse into the union/base types below, the third is the factory's parameter.\n// MySQL is NOT built from here: it has no RETURNING clause, so where these bodies read their\n// rows back out of the statement, MySQL's report `{ isSuccess }` — a genuinely different\n// shape, not a spelling difference. What all three dialects do share is the scaffolding\n// around the statement (hooks, transaction, error context), which lives in\n// `common/write-scaffold.ts` and wraps every body below.\n\nimport type { Table } from 'drizzle-orm';\nimport type { PgAsyncDatabase } from 'drizzle-orm/pg-core';\nimport type { SQLiteAsyncDatabase } from 'drizzle-orm/sqlite-core';\nimport { type GraphQLFieldConfigArgumentMap, type GraphQLInputObjectType, GraphQLList, GraphQLNonNull } from 'graphql';\nimport {\n remapFromGraphQLArrayInput,\n remapFromGraphQLSingleInput,\n remapToGraphQLArrayOutput,\n remapToGraphQLSingleOutput,\n} from '../data-mappers/index.ts';\nimport type { ResolveTree } from '../parse-resolve-info.ts';\nimport { parseResolveInfo } from '../parse-resolve-info.ts';\nimport {\n applyContextValues,\n applyContextValuesAll,\n applyObjectTypeName,\n assertSingleMatch,\n drizzleError,\n excludedColumnRef,\n extractFilters,\n extractSelectedColumnsFromTreeSQLFormat,\n hardDeleteArg,\n type LimitPolicyFor,\n type MutationTxCtx,\n mutationSelection,\n type OnConflictArg,\n type RelationFilterBase,\n type ResolverPolicies,\n relationFilterCtx,\n resolveConflictPlan,\n type SelectionCtx,\n scopedWhere,\n stripContextValues,\n type TypeNameMapper,\n type TypeNameResolver,\n type WriteOperation,\n withEagerRelations,\n withScope,\n writeResolver,\n} from './common.ts';\nimport { remapUpdateInput } from './field-updates.ts';\nimport { mergedOps, type NestedWriteRuntime, updateWithNestedOps, writeWithNestedOps } from './nested-writes.ts';\nimport type { CreatedResolver, Filters, TableNamedRelations } from './types.ts';\n\n/** Every database handle these resolvers can run on. `runMutation` takes `any`, so this is purely a call-site guard. */\nexport type WriteDatabase = PgAsyncDatabase<any, any> | SQLiteAsyncDatabase<any, any, any>;\n\n/**\n * The dialect's build-time primary-key lookup (`getTableConfig`-based, so it cannot be shared).\n * Typed on `any` because `PgTable` and `SQLiteTable` are unrelated subtypes of `Table`, and a\n * parameter of the base type would not accept either dialect's narrower function.\n */\n/**\n * What a write generator gets from the build rather than from the table. Every field is the\n * same for every table in one `buildSchema` call, so the call sites assemble it once and pass\n * it along unchanged — leaving each call to name only what actually varies per table.\n */\nexport interface WriteBuildOptions {\n db: WriteDatabase;\n /** Every table in the build — the relation columns a selection can reach live here. */\n tables: Record<string, Table>;\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n typeNameMapper?: TypeNameMapper;\n filterCtx?: RelationFilterBase;\n txCtx?: MutationTxCtx;\n nested?: NestedWriteRuntime;\n limits?: LimitPolicyFor;\n policies?: ResolverPolicies;\n /** The build's type-naming rule — the resolve tree is keyed by the names it produced. */\n resolveName?: TypeNameResolver;\n}\n\n/** The half of a write generator's options that changes from table to table. */\ninterface WriteTableOptions {\n tableName: string;\n table: Table;\n /** The mutation field's name, already run through the build's naming rules. */\n fieldName: string;\n typeName: string;\n /** One row in, one row out — as opposed to the list-shaped variant of the same mutation. */\n single: boolean;\n}\n\nexport interface InsertOptions extends WriteTableOptions {\n /** The table's create input, shared by both insert shapes and by the upsert. */\n baseType: GraphQLInputObjectType;\n /** Conflicting rows are skipped rather than failing the statement. */\n conflictDoNothing?: boolean;\n}\n\nexport interface UpsertOptions extends WriteTableOptions {\n baseType: GraphQLInputObjectType;\n onConflictType: GraphQLInputObjectType;\n uniqueSets: string[][];\n}\n\nexport interface UpdateOptions extends WriteTableOptions {\n setArgs: GraphQLInputObjectType;\n filterArgs: GraphQLInputObjectType;\n /** The table refuses an unfiltered write, so `where` is required even on the list shape. */\n requireWhere: boolean;\n}\n\nexport interface DeleteOptions extends WriteTableOptions {\n filterArgs: GraphQLInputObjectType;\n requireWhere: boolean;\n /** Builds `restore<Table>` — the same resolver reading and writing the other way. */\n restore?: boolean;\n selectionCtx?: SelectionCtx;\n}\n\nexport type PrimaryKeyPropNames = (table: any) => string[];\n\n/**\n * Binds the five resolvers to one dialect. Call once per dialect module and destructure the\n * result, so the generator call sites read exactly as they did when the functions were local.\n */\nexport const buildWriteResolvers = (primaryKeyPropNames: PrimaryKeyPropNames) => {\n /**\n * `insert<Table>` / `insert<Table>Single` — one generator for both shapes, the way\n * {@link generateUpsert} handles its pair. `single` decides the argument type, whether the\n * result is remapped as a row or a list, and whether an empty return is an error; the write\n * itself is the same multi-row statement either way, with the single variant supplying a\n * one-element list.\n */\n const generateInsert = (build: WriteBuildOptions, opts: InsertOptions): CreatedResolver => {\n const { db, tables, relationMap, typeNameMapper, txCtx, nested, limits, policies, resolveName } = build;\n const { tableName, table, baseType, fieldName, typeName, single, conflictDoNothing = false } = opts;\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: single ? new GraphQLNonNull(baseType) : new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(baseType))),\n },\n };\n\n // Primary-key prop names are constant per table — derive them once at build time\n // rather than re-running getTableConfig on every mutation request.\n const pkNames = primaryKeyPropNames(table);\n\n return writeResolver<{ values: Record<string, any> | Record<string, any>[] }>({\n db,\n tableName,\n operation: 'insert',\n single,\n fieldName,\n txCtx,\n policies,\n args: queryArgs,\n run: async ({ executor, args, context, info, before, after, returning: withHookReturning, output }) => {\n const supplied = single ? [args.values as Record<string, any>] : (args.values as Record<string, any>[]);\n if (!supplied.length) {\n throw drizzleError('No values were provided!', { code: 'DRIZZLE_NO_VALUES' });\n }\n await before();\n\n // Split each row's relation fields off its columns. Only when something is actually\n // nested does the write leave the single multi-row statement below.\n const entries = nested?.enabled(tableName)\n ? supplied.map((values) => nested.split(tableName, values))\n : undefined;\n const nestedEntries = entries?.some((entry) => nested!.hasOps(entry.ops)) ? entries : undefined;\n const contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntries\n ? []\n : applyContextValuesAll(\n remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table),\n contextColumns,\n context,\n );\n\n const { columns, hasRelations, withParams } = mutationSelection(info, {\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n resolveName,\n table,\n pkNames,\n limits,\n scope,\n defaultOrderBy: policies?.defaultOrderBy,\n });\n\n const returning = withHookReturning(\n nestedEntries ? nested!.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table) : columns,\n );\n\n const runInsert = async (target: any, values: Record<string, any>[]) => {\n let query = target.insert(table).values(values).returning(returning);\n if (conflictDoNothing) {\n query = query.onConflictDoNothing() as any;\n }\n return (await query) as Record<string, any>[];\n };\n\n const written = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: (tx, values) => runInsert(tx, [values]),\n request: { context, args, info },\n })\n : await runInsert(executor, input);\n\n await after(written);\n const result = output(written);\n\n if (single && !result[0]) {\n // Only reachable under `conflictDoNothing`, which is why the field is nullable\n // there and non-null everywhere else.\n if (!conflictDoNothing) {\n throw drizzleError('The insert returned no row.', { code: 'DRIZZLE_NO_ROW_RETURNED' });\n }\n return undefined;\n }\n\n const enriched = await withEagerRelations(executor, tableName, result, pkNames, withParams, hasRelations);\n\n return single\n ? remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap)\n : remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n },\n });\n };\n\n /**\n * `upsert<Table>` / `upsert<Table>Single` — an insert that resolves a unique-key conflict\n * the way the request's `onConflict` argument asks, rather than failing.\n *\n * Shares the insert input: an upsert supplies a whole row, same as a create.\n */\n const generateUpsert = (build: WriteBuildOptions, opts: UpsertOptions): CreatedResolver => {\n const { db, tables, relationMap, typeNameMapper, filterCtx, txCtx, nested, limits, policies, resolveName } = build;\n const { tableName, table, baseType, onConflictType, uniqueSets, fieldName, typeName, single } = opts;\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: single ? new GraphQLNonNull(baseType) : new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(baseType))),\n },\n onConflict: {\n type: onConflictType,\n description: 'How a conflicting row is resolved. Defaults to overwriting it on the primary key.',\n },\n };\n\n const pkNames = primaryKeyPropNames(table);\n\n return writeResolver<{ values: Record<string, any> | Record<string, any>[]; onConflict?: OnConflictArg }>({\n db,\n tableName,\n operation: 'upsert',\n single,\n fieldName,\n txCtx,\n policies,\n args: queryArgs,\n run: async ({ executor, args, context, info, before, after, returning: withHookReturning, output }) => {\n const supplied = single ? [args.values as Record<string, any>] : (args.values as Record<string, any>[]);\n if (!supplied.length) {\n throw drizzleError('No values were provided!', { code: 'DRIZZLE_NO_VALUES' });\n }\n await before();\n\n const entries = nested?.enabled(tableName)\n ? supplied.map((values) => nested.split(tableName, values))\n : undefined;\n const nestedEntries = entries?.some((entry) => nested!.hasOps(entry.ops)) ? entries : undefined;\n const contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntries\n ? []\n : applyContextValuesAll(\n remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table),\n contextColumns,\n context,\n );\n\n const { columns, hasRelations, withParams } = mutationSelection(info, {\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n resolveName,\n table,\n pkNames,\n limits,\n scope,\n defaultOrderBy: policies?.defaultOrderBy,\n });\n\n const returning = withHookReturning(\n nestedEntries ? nested!.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table) : columns,\n );\n\n // The conflict plan reads the columns the write actually supplies, so a nested write\n // — whose rows go in one at a time, each already carrying whatever its parent-side\n // operations produced — resolves its plan per row rather than once for the batch.\n const runUpsert = async (target: any, values: Record<string, any>[]) => {\n const plan = resolveConflictPlan({\n table,\n values,\n onConflict: args.onConflict,\n pkNames,\n uniqueSets,\n excludedRef: excludedColumnRef,\n withTarget: true,\n buildWhere: (where) => extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)),\n });\n\n let query = target.insert(table).values(values).returning(returning);\n // On conflict the statement updates a row that already exists, so the scope applies\n // to it exactly as it would to `update<Table>`: a conflicting row the caller cannot\n // see is left alone rather than taken over.\n const setWhere = withScope(scope, tableName, table, plan.setWhere);\n query =\n plan.action === 'NOTHING'\n ? (query.onConflictDoNothing(plan.target ? { target: plan.target } : undefined) as any)\n : (query.onConflictDoUpdate({ target: plan.target!, set: plan.set, setWhere }) as any);\n\n return (await query) as Record<string, any>[];\n };\n\n const written = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: (tx, values) => runUpsert(tx, [values]),\n request: { context, args, info },\n })\n : await runUpsert(executor, input);\n\n await after(written);\n const result = output(written);\n\n if (single && !result[0]) {\n return undefined;\n }\n\n const enriched = await withEagerRelations(executor, tableName, result, pkNames, withParams, hasRelations);\n\n return single\n ? remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap)\n : remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n },\n });\n };\n\n const generateUpdate = (build: WriteBuildOptions, opts: UpdateOptions): CreatedResolver => {\n const { db, tables, relationMap, typeNameMapper, filterCtx, txCtx, nested, limits, policies, resolveName } = build;\n const { tableName, table, setArgs, filterArgs, fieldName, typeName, single, requireWhere } = opts;\n const queryArgs = {\n set: {\n type: new GraphQLNonNull(setArgs),\n },\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n // Derived once at build time — PK prop names don't change per request.\n const pkNames = primaryKeyPropNames(table);\n\n return writeResolver<{ where?: Filters<Table>; set: Record<string, any> }>({\n db,\n tableName,\n operation: 'update',\n single,\n fieldName,\n txCtx,\n policies,\n args: queryArgs,\n run: async ({ executor, args, context, info, before, after, returning: withHookReturning, output }) => {\n const { where, set } = args;\n const scope = policies?.scope?.(context);\n await before();\n\n const { columns, hasRelations, withParams } = mutationSelection(info, {\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n resolveName,\n table,\n pkNames,\n limits,\n scope,\n defaultOrderBy: policies?.defaultOrderBy,\n });\n\n const entry = nested?.enabled(tableName) ? nested.split(tableName, set) : undefined;\n const nestedOps = entry && nested!.hasOps(entry.ops) ? entry.ops : undefined;\n // A context-derived column is the server's to set, so an update never reassigns\n // one — that is what stops a row being handed to another owner.\n const input = stripContextValues(\n remapUpdateInput(entry ? entry.columns : set, table, tableName),\n policies?.contextValues?.(tableName),\n );\n // A `set` that carries only nested operations is a legitimate update — of the\n // relation rather than of the row — so it is only empty when neither is present.\n if (!Object.keys(input).length && !nestedOps) {\n throw drizzleError('Unable to update with no values specified!', { code: 'DRIZZLE_NO_VALUES' });\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // The scope is ANDed on last, so a caller-supplied `where` can only narrow it.\n const filters = scopedWhere({\n scope,\n tableName,\n table,\n where,\n relationCtx,\n required: single || requireWhere,\n });\n\n if (single) {\n await assertSingleMatch(executor, table, filters!);\n }\n\n const returning = withHookReturning(\n nestedOps ? nested!.withJoinColumns(tableName, nestedOps, { ...columns }, table) : columns,\n );\n\n const runUpdate = async (target: any, values: Record<string, any>) => {\n // Nothing to write to the row itself: the operations attach to whatever the\n // `where` matched, so the rows are read rather than rewritten.\n const writes = Object.keys(values).length > 0;\n let query = writes ? target.update(table).set(values) : target.select(returning).from(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n return (await (writes ? (query.returning(returning) as any) : query)) as Record<string, any>[];\n };\n\n const written = nestedOps\n ? await updateWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n columns: input,\n ops: nestedOps,\n remapValues: (values) => values,\n write: runUpdate,\n request: { context, args, info },\n })\n : await runUpdate(executor, input);\n\n await after(written);\n const result = output(written);\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw drizzleError(\"'where' matched more than one row!\", { code: 'DRIZZLE_MULTI_ROW_MATCH' });\n }\n\n if (single && !result[0]) {\n return undefined;\n }\n\n const enriched = await withEagerRelations(executor, tableName, result, pkNames, withParams, hasRelations);\n\n return single\n ? remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap)\n : remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n },\n });\n };\n\n /**\n * `delete<Table>` and, for a table that declares a soft-delete column, `restore<Table>`.\n *\n * A soft-deleting table normally issues no `DELETE`: both mutations are an `UPDATE` of the\n * marker column, and the rows they return are the rows as they now stand. `restore` is the\n * same resolver reading the other way — it matches only marked rows (`deleted: ONLY`) and\n * writes the restored value.\n *\n * A table that opted into `hardDelete` also takes `hard: true`, which issues the real\n * `DELETE` — emptying the trash, reclaiming a unique key. It reads at `INCLUDE`, since the\n * rows it mostly exists to remove are the ones already marked; a `scope` still confines it.\n */\n const generateDelete = (build: WriteBuildOptions, opts: DeleteOptions): CreatedResolver => {\n const { db, filterCtx, txCtx, policies, resolveName } = build;\n const { tableName, table, filterArgs, fieldName, typeName, single, requireWhere, selectionCtx } = opts;\n const restore = opts.restore ?? false;\n const softDelete = policies?.softDelete?.(tableName);\n const operation: WriteOperation = restore ? 'restore' : 'delete';\n // Only a soft-deleting table that opted in gets the argument, so the schema itself says\n // which tables can be purged — and `restore` never takes one, having nothing to remove.\n const canHardDelete = !restore && softDelete?.hardDelete === true;\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n ...(canHardDelete ? { hard: hardDeleteArg } : {}),\n } as GraphQLFieldConfigArgumentMap;\n\n return writeResolver<{ where?: Filters<Table>; hard?: boolean }>({\n db,\n tableName,\n operation,\n single,\n fieldName,\n txCtx,\n policies,\n args: queryArgs,\n run: async ({ executor, args, context, info, before, after, returning: withHookReturning, output }) => {\n const { where } = args;\n // `canHardDelete` decides whether the argument exists; this decides what it does,\n // so a stitched-in `hard: true` on a table that never opted in stays a soft delete.\n const hard = canHardDelete && args.hard === true;\n const scope = policies?.scope?.(context);\n await before();\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const columns = extractSelectedColumnsFromTreeSQLFormat(\n parsedInfo.fieldsByTypeName[applyObjectTypeName(typeName, tableName, resolveName)]!,\n table,\n selectionCtx,\n );\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // Same rule as update: the scope is ANDed on last, so a delete can only ever reach\n // rows inside it — an out-of-scope row is not matched rather than being refused.\n // A soft-deleting table adds the marker predicate the same way: `delete` only sees\n // rows that are not already marked, `restore` only sees the ones that are.\n const filters = scopedWhere({\n scope,\n tableName,\n table,\n where,\n relationCtx,\n required: single || requireWhere,\n // A hard delete reads at INCLUDE: the rows it mostly exists to remove are the\n // ones already marked, which the default EXCLUDE could not reach at all.\n deleted: restore ? 'ONLY' : hard ? 'INCLUDE' : undefined,\n });\n\n if (single) {\n await assertSingleMatch(executor, table, filters!);\n }\n\n let query =\n softDelete && !hard\n ? executor.update(table).set({\n [softDelete.columnName]: restore ? softDelete.writeRestored : softDelete.writeDeleted(),\n })\n : executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n query = query.returning(withHookReturning(columns)) as any;\n\n const written = await query;\n\n await after(written);\n const result = output(written);\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw drizzleError(\"'where' matched more than one row!\", { code: 'DRIZZLE_MULTI_ROW_MATCH' });\n }\n\n if (single) {\n return result[0] ? remapToGraphQLSingleOutput(result[0], tableName, table) : undefined;\n }\n\n return remapToGraphQLArrayOutput(result, tableName, table);\n },\n });\n };\n return { generateInsert, generateUpsert, generateUpdate, generateDelete };\n};\n","// =============================================================================\n// `generateSchemaData` for the two dialects whose writes return the rows they\n// wrote — PostgreSQL and SQLite. They build a schema identically, so this module\n// holds it once and a dialect supplies only what it genuinely owns, through\n// {@link DialectSchemaAdapter}.\n//\n// The parts that are not even dialect-specific — everything up to each table's\n// types, the read fields, the per-table loop and the relation resolvers at the end\n// — live in `build-context.ts`, which MySQL shares. What remains here is the\n// mutation half, handed back to `forEachTable` for registration: MySQL has no\n// RETURNING clause, so its mutation fields, return types and resolvers differ\n// throughout.\n// =============================================================================\n\nimport type { Table } from 'drizzle-orm';\nimport type { GraphQLInputObjectType } from 'graphql';\nimport { GraphQLInt, GraphQLList, GraphQLNonNull } from 'graphql';\nimport {\n generateOnConflictInput,\n generateUpdateManyInput,\n generateWriteCount,\n getUniqueColumnSets,\n type TablesRelationalConfig,\n} from '../builders/common.ts';\nimport { createSchemaBuilder, type MutationRegistration, type SchemaBuildAdapter } from './build-context.ts';\nimport type { CreatedResolver, SchemaGeneratorOptions } from './types.ts';\nimport { buildWriteResolvers, type WriteBuildOptions } from './write-resolvers.ts';\n\n/** The per-table half of {@link UpdateManyGenerator}'s options; the rest comes from the build. */\nexport interface UpdateManyOptions {\n tableName: string;\n table: any;\n updateManyInput: GraphQLInputObjectType;\n fieldName: string;\n typeName: string;\n}\n\n/** `update<Table>Many` — batch update, whose statement loop is dialect-specific. */\nexport type UpdateManyGenerator = (build: WriteBuildOptions, opts: UpdateManyOptions) => CreatedResolver;\n\n/**\n * Everything {@link createSchemaDataGenerator} cannot decide for itself: the shared build's\n * adapter, plus the one generator whose statement loop is dialect-specific. Both dialects on\n * this path return the rows they write, so it is fixed to `true`.\n */\nexport type DialectSchemaAdapter = SchemaBuildAdapter<true> & {\n generateUpdateMany: UpdateManyGenerator;\n};\n\n/**\n * Binds an adapter and returns the dialect's `generateSchemaData` implementation.\n *\n * Called once per dialect module at import time, so the write resolvers — which close\n * over the dialect's primary-key lookup — are built once rather than per `buildSchema`.\n */\nexport const createSchemaDataGenerator = (adapter: DialectSchemaAdapter) => {\n const primaryKeyPropNames = adapter.primaryKeyPropNames;\n const uniqueColumnSets = (table: Table): string[][] => getUniqueColumnSets(table, adapter.getTableConfig);\n const { generateInsert, generateUpsert, generateUpdate, generateDelete } = buildWriteResolvers(primaryKeyPropNames);\n // The three stretches of a build that have nothing to do with the dialect: everything up to\n // each table's types, the read fields in the middle, and the relation resolvers at the end.\n const { prepareBuild, forEachTable, finalizeBuild } = createSchemaBuilder(adapter);\n\n return (\n db: any,\n schema: Record<string, unknown>,\n relations: TablesRelationalConfig,\n options: SchemaGeneratorOptions,\n ): any => {\n const { prefixes, conflictDoNothing, typeNameMapper, limits } = options;\n\n // Table discovery, the relation graph, the per-build registries, the filter context, the\n // type cache and every table's types — all of it dialect-independent, so all of it lives\n // in `build-context.ts` and is shared with the MySQL builder.\n const ctx = prepareBuild(db, schema, relations, options);\n const { tables, eagerRelations, filterCtx, policies, namedRelations, cacheCtx, nestedRuntime, mutationTxCtx } = ctx;\n\n // Everything a write generator takes from the build rather than from the table. The same\n // object serves every table below, so each call names only what varies per table.\n const writeBuild: WriteBuildOptions = {\n db,\n tables,\n relationMap: eagerRelations,\n typeNameMapper,\n filterCtx,\n txCtx: mutationTxCtx,\n nested: nestedRuntime,\n limits,\n policies,\n resolveName: cacheCtx.typeName,\n };\n\n forEachTable(ctx, ({ tableName, tableFeatures, names, types, softDeleteInfo }) => {\n const { insertInput, updateInput, tableFilters } = types.inputs;\n const { singleTableItemOutput, arrTableItemOutput } = types.outputs;\n const {\n typeName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n updateManyFieldName,\n updateSingleFieldName,\n updateCountFieldName,\n deleteFieldName,\n deleteSingleFieldName,\n restoreFieldName,\n restoreSingleFieldName,\n deleteCountFieldName,\n } = names;\n\n const insertArrGenerated = tableFeatures.insert\n ? generateInsert(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n baseType: insertInput,\n fieldName: createArrayFieldName,\n typeName,\n single: false,\n conflictDoNothing,\n })\n : undefined;\n const insertSingleGenerated = tableFeatures.insert\n ? generateInsert(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n baseType: insertInput,\n fieldName: createSingleFieldName,\n typeName,\n single: true,\n conflictDoNothing,\n })\n : undefined;\n // An upsert needs something to conflict on, so a table with no primary key and no\n // unique constraint gets no upsert mutations rather than ones that always fail.\n const uniqueSets = tableFeatures.upsert ? uniqueColumnSets(schema[tableName] as Table) : [];\n const onConflictInput = tableFeatures.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as Table,\n tableName,\n typeName,\n uniqueSets,\n tableFilters,\n withTarget: true,\n cacheCtx,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n baseType: insertInput,\n onConflictType: onConflictInput,\n uniqueSets,\n fieldName: upsertArrayFieldName,\n typeName,\n single: false,\n })\n : undefined;\n const upsertSingleGenerated = onConflictInput\n ? generateUpsert(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n baseType: insertInput,\n onConflictType: onConflictInput,\n uniqueSets,\n fieldName: upsertSingleFieldName,\n typeName,\n single: true,\n })\n : undefined;\n const updateGenerated = tableFeatures.update\n ? generateUpdate(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n setArgs: updateInput,\n filterArgs: tableFilters,\n fieldName: updateFieldName,\n typeName,\n single: false,\n requireWhere: tableFeatures.requireWhere,\n })\n : undefined;\n const updateSingleGenerated = tableFeatures.update\n ? generateUpdate(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n setArgs: updateInput,\n filterArgs: tableFilters,\n fieldName: updateSingleFieldName,\n typeName,\n single: true,\n requireWhere: tableFeatures.requireWhere,\n })\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n tableFeatures.update && tableFeatures.updateMany\n ? generateUpdateManyInput({\n tableName,\n typeName,\n updatePrefix: prefixes.update,\n updateInput,\n tableFilters,\n cacheCtx,\n })\n : undefined;\n const updateManyGenerated = updateManyInput\n ? adapter.generateUpdateMany(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n updateManyInput,\n fieldName: updateManyFieldName,\n typeName,\n })\n : undefined;\n const deleteGenerated = tableFeatures.delete\n ? generateDelete(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n filterArgs: tableFilters,\n fieldName: deleteFieldName,\n typeName,\n single: false,\n requireWhere: tableFeatures.requireWhere,\n restore: false,\n selectionCtx: { tableName, relationMap: namedRelations, tables },\n })\n : undefined;\n const deleteSingleGenerated = tableFeatures.delete\n ? generateDelete(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n filterArgs: tableFilters,\n fieldName: deleteSingleFieldName,\n typeName,\n single: true,\n requireWhere: tableFeatures.requireWhere,\n restore: false,\n selectionCtx: { tableName, relationMap: namedRelations, tables },\n })\n : undefined;\n const restoreGenerated = softDeleteInfo\n ? generateDelete(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n filterArgs: tableFilters,\n fieldName: restoreFieldName,\n typeName,\n single: false,\n requireWhere: tableFeatures.requireWhere,\n restore: true,\n selectionCtx: { tableName, relationMap: namedRelations, tables },\n })\n : undefined;\n const restoreSingleGenerated = softDeleteInfo\n ? generateDelete(writeBuild, {\n tableName,\n table: schema[tableName] as Table,\n filterArgs: tableFilters,\n fieldName: restoreSingleFieldName,\n typeName,\n single: true,\n requireWhere: tableFeatures.requireWhere,\n restore: true,\n selectionCtx: { tableName, relationMap: namedRelations, tables },\n })\n : undefined;\n // The count variants are the plural write with its payload left off, so each follows the\n // same feature switch — and the same scope, soft-delete, context-value and hook rules —\n // as the write it mirrors.\n const updateCountGenerated =\n tableFeatures.update && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as Table,\n kind: 'update',\n setArgs: updateInput,\n filterArgs: tableFilters,\n fieldName: updateCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n nested: nestedRuntime,\n policies,\n pkNames: primaryKeyPropNames(schema[tableName] as Table),\n returnsRows: true,\n })\n : undefined;\n const deleteCountGenerated =\n tableFeatures.delete && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as Table,\n kind: 'delete',\n filterArgs: tableFilters,\n fieldName: deleteCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n policies,\n pkNames: primaryKeyPropNames(schema[tableName] as Table),\n returnsRows: true,\n })\n : undefined;\n // Each mutation is paired with the type it returns and the identity it publishes on\n // `extensions.drizzle`, so a consumer can tell an insert from an upsert without unpicking\n // the configured prefixes — and, for a delete, whether the field can purge rather than\n // mark. The count pair publishes its plural sibling's identity plus `count: true`, so a\n // wrapper gating on `operation` sees it as the write it is.\n const hardDeleteMeta = softDeleteInfo?.hardDelete ? ({ hardDelete: true } as const) : {};\n const generatedMutations: MutationRegistration[] = [\n {\n generated: insertArrGenerated,\n type: arrTableItemOutput,\n meta: { operation: 'insert', single: false, targetArg: 'values' },\n },\n {\n generated: insertSingleGenerated,\n // An insert either returns the row it inserted or throws — the one path to `null` is\n // `conflictDoNothing` swallowing the insert, so the field is nullable only there.\n type: conflictDoNothing ? singleTableItemOutput : new GraphQLNonNull(singleTableItemOutput),\n meta: { operation: 'insert', single: true, targetArg: 'values' },\n },\n {\n generated: upsertArrGenerated,\n type: arrTableItemOutput,\n meta: { operation: 'upsert', single: false, targetArg: 'values' },\n },\n {\n generated: upsertSingleGenerated,\n type: singleTableItemOutput,\n meta: { operation: 'upsert', single: true, targetArg: 'values' },\n },\n {\n generated: updateGenerated,\n type: arrTableItemOutput,\n meta: { operation: 'update', single: false, targetArg: 'where' },\n },\n {\n generated: updateManyGenerated,\n type: new GraphQLNonNull(new GraphQLList(singleTableItemOutput)),\n meta: { operation: 'updateMany', single: false, targetArg: 'updates' },\n // The nullable element is deliberate, and the reason this mutation's return type\n // differs from every sibling's: the result is aligned with the input, one slot per\n // entry, so an entry that matched nothing has to be able to say so.\n description:\n \"Each entry's updated rows, in entry order. An entry whose `where` matched no rows contributes `null` in its slot; an entry that matched several contributes each of its rows.\",\n },\n {\n generated: updateSingleGenerated,\n type: singleTableItemOutput,\n meta: { operation: 'update', single: true, targetArg: 'where' },\n },\n {\n generated: deleteGenerated,\n type: arrTableItemOutput,\n meta: { operation: 'delete', single: false, targetArg: 'where', ...hardDeleteMeta },\n },\n {\n generated: deleteSingleGenerated,\n type: singleTableItemOutput,\n meta: { operation: 'delete', single: true, targetArg: 'where', ...hardDeleteMeta },\n },\n {\n generated: restoreGenerated,\n type: arrTableItemOutput,\n meta: { operation: 'restore', single: false, targetArg: 'where' },\n },\n {\n generated: restoreSingleGenerated,\n type: singleTableItemOutput,\n meta: { operation: 'restore', single: true, targetArg: 'where' },\n },\n {\n generated: updateCountGenerated,\n type: new GraphQLNonNull(GraphQLInt),\n meta: { operation: 'update', single: false, targetArg: 'where', count: true },\n description:\n 'How many rows the update touched. The rows themselves are not read back, which is the point of this mutation.',\n },\n {\n generated: deleteCountGenerated,\n type: new GraphQLNonNull(GraphQLInt),\n meta: { operation: 'delete', single: false, targetArg: 'where', count: true, ...hardDeleteMeta },\n description:\n 'How many rows the delete removed — or, on a soft-deleting table, marked deleted. The rows themselves are not read back, which is the point of this mutation.',\n },\n ];\n\n return { mutations: generatedMutations, onConflictInput, updateManyInput };\n });\n\n return finalizeBuild(ctx);\n };\n};\n","// =============================================================================\n// The dialect-independent half of `update<Table>Many`.\n//\n// PostgreSQL and SQLite build this resolver identically right up to the point\n// where the entries actually execute — argument parsing, the per-entry remap\n// and validation, the nested-write split, the write hooks, relation\n// enrichment and the per-entry output slots are all the same. The two dialects\n// differ only in HOW the batch runs inside its transaction, which is what\n// {@link UpdateManyBatchRunner} abstracts.\n// =============================================================================\n\nimport type { Table } from 'drizzle-orm';\nimport type { GraphQLFieldConfigArgumentMap } from 'graphql';\nimport { GraphQLList, GraphQLNonNull } from 'graphql';\nimport {\n drizzleError,\n extractFilters,\n mutationSelection,\n relationFilterCtx,\n stripContextValues,\n withEagerRelations,\n withScope,\n writeResolver,\n} from '../builders/common.ts';\nimport { remapToGraphQLSingleOutput } from '../data-mappers/index.ts';\nimport { remapUpdateInput } from './field-updates.ts';\nimport { mergedOps, type NestedWriteRequest, type NestedWriteRuntime } from './nested-writes.ts';\nimport type { UpdateManyGenerator, UpdateManyOptions } from './schema-data.ts';\nimport type { CreatedResolver, Filters } from './types.ts';\nimport type { WriteBuildOptions } from './write-resolvers.ts';\n\n/** One entry of the `updates` argument, already remapped and validated. */\nexport type UpdateManyEntry = {\n /** Column values to write, context-supplied columns stripped. */\n set: Record<string, any>;\n /** Nested-write operations, or `undefined` when the entry writes columns only. */\n ops: Record<string, any> | undefined;\n /** The entry's `where`, already combined with the row scope. */\n filters: any;\n};\n\n/** Everything a batch runner needs; assembled by the shared resolver before the batch opens. */\nexport type UpdateManyBatchCtx = {\n /** The executor the mutation runs on — `db`, a caller's transaction, or the shared one. */\n executor: any;\n entries: UpdateManyEntry[];\n table: any;\n /** The columns each statement returns, join columns included when nested writes are on. */\n returning: Record<string, any>;\n /** True when at least one entry carries nested-write operations. */\n anyNested: boolean;\n nested: NestedWriteRuntime | undefined;\n tableName: string;\n /** The request the nested writes run for — its context, and what their hooks are handed. */\n request: NestedWriteRequest;\n};\n\n/** Runs the entries and returns each one's rows, in entry order. */\nexport type UpdateManyBatchRunner = (ctx: UpdateManyBatchCtx) => Promise<Record<string, any>[][]>;\n\n/**\n * The batch runner for a dialect whose driver is always asynchronous: one UPDATE per entry,\n * awaited in input order, inside a single transaction. On a caller-supplied transaction — or\n * the shared multi-mutation transaction opened by `runMutation` — this opens a savepoint, so\n * the batch stays atomic without breaking the outer transaction.\n */\nexport const runUpdateManyBatch: UpdateManyBatchRunner = ({\n executor,\n entries,\n table,\n returning,\n nested,\n tableName,\n request,\n}) =>\n executor.transaction(async (tx: any) => {\n const results: Record<string, any>[][] = [];\n for (const entry of entries) {\n const values = entry.ops\n ? { ...entry.set, ...(await nested!.applyParentSide(tx, tableName, entry.ops, request)) }\n : entry.set;\n\n // Same as the single update: an entry with no column values reads the rows its\n // `where` matched so the nested operations have something to attach to.\n const writes = Object.keys(values).length > 0;\n let query = writes ? tx.update(table).set(values) : tx.select(returning).from(table);\n if (entry.filters) {\n query = query.where(entry.filters) as any;\n }\n const rows = (await (writes ? (query.returning(returning) as any) : query)) as Record<string, any>[];\n\n if (entry.ops) {\n await nested!.applyChildSide(tx, tableName, entry.ops, rows, request);\n }\n results.push(rows);\n }\n return results;\n });\n\n/**\n * Builds a dialect's `update<Table>Many` generator.\n *\n * `update<Table>Many` is a batch update with a per-entry `set` and `where`. The entries run\n * as one UPDATE statement each, in input order, inside a single transaction (a savepoint when\n * the request context already carries one), so a failing entry rolls the whole batch back and\n * a row matched by several entries sees them applied in order. The result lists each entry's\n * updated rows in entry order, with `null` standing in for an entry whose `where` matched no\n * rows, so the common one-row-per-entry case stays aligned with the input.\n *\n * @param primaryKeyPropNames the dialect's composite-aware primary-key lookup\n * @param runBatch how the entries execute; defaults to {@link runUpdateManyBatch}\n */\nexport const createUpdateManyGenerator = (\n primaryKeyPropNames: (table: any) => string[],\n runBatch: UpdateManyBatchRunner = runUpdateManyBatch,\n): UpdateManyGenerator => {\n return (build: WriteBuildOptions, opts: UpdateManyOptions): CreatedResolver => {\n const { db, tables, relationMap, typeNameMapper, filterCtx, txCtx, nested, limits, policies, resolveName } = build;\n const { tableName, table, updateManyInput, fieldName, typeName } = opts;\n const queryArgs = {\n updates: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(updateManyInput))),\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n // Derived once at build time — PK prop names don't change per request.\n const pkNames = primaryKeyPropNames(table);\n\n return writeResolver<{ updates: { where?: Filters<Table>; set: Record<string, any> }[] }>({\n db,\n tableName,\n operation: 'updateMany',\n single: false,\n fieldName,\n txCtx,\n policies,\n args: queryArgs,\n run: async ({\n executor,\n args,\n context,\n info,\n before,\n after,\n returning: withHookReturning,\n output: withoutHookColumns,\n }) => {\n const { updates } = args;\n if (!updates.length) {\n throw drizzleError('No updates were provided!', { code: 'DRIZZLE_NO_VALUES' });\n }\n await before();\n const scope = policies?.scope?.(context);\n const contextColumns = policies?.contextValues?.(tableName);\n\n const { columns, hasRelations, withParams } = mutationSelection(info, {\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n resolveName,\n table,\n pkNames,\n limits,\n scope,\n defaultOrderBy: policies?.defaultOrderBy,\n });\n\n // Remap and validate every entry before the transaction opens, so a malformed\n // entry rejects the request instead of rolling back mid-batch.\n const entries: UpdateManyEntry[] = updates.map(({ where, set }) => {\n const split = nested?.enabled(tableName) ? nested.split(tableName, set) : undefined;\n const ops = split && nested!.hasOps(split.ops) ? split.ops : undefined;\n const input = stripContextValues(\n remapUpdateInput(split ? split.columns : set, table, tableName),\n contextColumns,\n );\n // An entry that only writes through a relation still has work to do.\n if (!Object.keys(input).length && !ops) {\n throw drizzleError('Unable to update with no values specified!', { code: 'DRIZZLE_NO_VALUES' });\n }\n return {\n set: input,\n ops,\n filters: withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n ),\n };\n });\n\n const anyNested = entries.some((entry) => entry.ops);\n const returning = withHookReturning(\n anyNested\n ? nested!.withJoinColumns(\n tableName,\n mergedOps(entries.map((entry) => ({ ops: entry.ops ?? {} }))),\n { ...columns },\n table,\n )\n : columns,\n );\n\n const perEntry = await runBatch({\n executor,\n entries,\n table,\n returning,\n anyNested,\n nested,\n tableName,\n request: { context, args, info },\n });\n\n const written = perEntry.flat();\n await after(written);\n const flatRows = withoutHookColumns(written);\n\n const enriched = await withEagerRelations(executor, tableName, flatRows, pkNames, withParams, hasRelations);\n\n // Rebuild the per-entry slots: a no-match entry contributes `null`, a multi-match\n // entry contributes each of its rows.\n const output: (Record<string, any> | null)[] = [];\n let offset = 0;\n for (const rows of perEntry) {\n if (!rows.length) {\n output.push(null);\n continue;\n }\n for (let i = 0; i < rows.length; i++) {\n output.push(remapToGraphQLSingleOutput(enriched[offset + i], tableName, table, relationMap));\n }\n offset += rows.length;\n }\n return output;\n },\n });\n };\n};\n","import type { Table } from 'drizzle-orm';\nimport { type PgAsyncDatabase, PgTable, getTableConfig as pgTableConfig } from 'drizzle-orm/pg-core';\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n getPrimaryKeyPropNamesFromConfig,\n memoizeTableConfig,\n type TablesRelationalConfig,\n} from '../builders/common.ts';\nimport { createSchemaDataGenerator } from './schema-data.ts';\nimport type { SchemaGeneratorOptions } from './types.ts';\nimport { createUpdateManyGenerator } from './update-many.ts';\n\n/** The dialect's table config, cached per table — see {@link memoizeTableConfig}. */\nconst getTableConfig = memoizeTableConfig(pgTableConfig);\n\n/** Primary-key property names for a PG table, including table-level composite keys. */\nconst pgPrimaryKeyPropNames = (table: PgTable): string[] => getPrimaryKeyPropNamesFromConfig(table, getTableConfig);\n\nconst generateUpdateMany = createUpdateManyGenerator(pgPrimaryKeyPropNames);\n\nconst pgSchemaData = createSchemaDataGenerator({\n tableClass: PgTable,\n getTableConfig,\n primaryKeyPropNames: pgPrimaryKeyPropNames,\n // PostgreSQL sorts NULLs as the largest values (last in ASC).\n nullOrdering: 'nulls-largest',\n // Writes come back with their rows, so the table types carry the `${Table}Item` outputs.\n returnsRows: true,\n generateUpdateMany,\n});\n\nexport const generateSchemaData = <\n TDrizzleInstance extends PgAsyncDatabase<any, any>,\n TSchema extends Record<string, Table | unknown>,\n>(\n db: TDrizzleInstance,\n schema: TSchema,\n relations: TablesRelationalConfig,\n options: SchemaGeneratorOptions,\n): GeneratedEntities<TDrizzleInstance, TSchema> => pgSchemaData(db, schema, relations, options);\n","import type { Table } from 'drizzle-orm';\nimport { type SQLiteAsyncDatabase, SQLiteTable, getTableConfig as sqliteTableConfig } from 'drizzle-orm/sqlite-core';\n\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n getPrimaryKeyPropNamesFromConfig,\n memoizeTableConfig,\n type TablesRelationalConfig,\n} from '../builders/common.ts';\nimport { createSchemaDataGenerator } from './schema-data.ts';\nimport type { SchemaGeneratorOptions } from './types.ts';\nimport { createUpdateManyGenerator, type UpdateManyBatchRunner, type UpdateManyEntry } from './update-many.ts';\n\n/** The dialect's table config, cached per table — see {@link memoizeTableConfig}. */\nconst getTableConfig = memoizeTableConfig(sqliteTableConfig);\n\n/** Primary-key property names for a SQLite table, including table-level composite keys. */\nconst sqlitePrimaryKeyPropNames = (table: SQLiteTable): string[] =>\n getPrimaryKeyPropNamesFromConfig(table, getTableConfig);\n\n/**\n * SQLite's batch runner. A synchronous driver (better-sqlite3) commits the moment its\n * transaction callback returns, so that callback must not be async — an awaited statement\n * would run after the COMMIT. The driver kind is probed from the first statement's result\n * rather than declared, so the same resolver serves both driver families.\n */\nconst runSqliteUpdateManyBatch: UpdateManyBatchRunner = ({\n executor,\n entries,\n table,\n returning,\n anyNested,\n nested,\n tableName,\n request,\n}) => {\n const runEntry = (tx: any, entry: UpdateManyEntry) => {\n let query = tx.update(table).set(entry.set);\n if (entry.filters) {\n query = query.where(entry.filters);\n }\n // `.all()` instead of awaiting the thenable: a sync driver executes it immediately,\n // which is the only way the statement still runs inside the native transaction below.\n return query.returning(returning).all();\n };\n\n // Nested writes need statements interleaved with awaited reads, which only an async driver\n // can do inside a transaction — `features.nestedWrites` rejects a sync driver at build\n // time, so this path is always on one.\n const runNestedEntry = async (tx: any, entry: UpdateManyEntry) => {\n const values = entry.ops\n ? { ...entry.set, ...(await nested!.applyParentSide(tx, tableName, entry.ops, request)) }\n : entry.set;\n\n // Same as the single update: an entry with no column values reads the rows its `where`\n // matched so the nested operations have something to attach to.\n const writes = Object.keys(values).length > 0;\n let query = writes ? tx.update(table).set(values) : tx.select(returning).from(table);\n if (entry.filters) {\n query = query.where(entry.filters);\n }\n const rows = (await (writes ? query.returning(returning) : query)) as Record<string, any>[];\n\n if (entry.ops) {\n await nested!.applyChildSide(tx, tableName, entry.ops, rows, request);\n }\n return rows;\n };\n\n // On a caller-supplied transaction — or the shared multi-mutation transaction opened by\n // `runMutation` — this opens a savepoint, so the batch stays atomic without breaking the\n // outer transaction.\n return executor.transaction((tx: any) => {\n if (anyNested) {\n return (async () => {\n const results: Record<string, any>[][] = [];\n for (const entry of entries) {\n results.push(await runNestedEntry(tx, entry));\n }\n return results;\n })();\n }\n\n const first = runEntry(tx, entries[0]!);\n if (typeof (first as any)?.then === 'function') {\n // Async driver: await sequentially so the entries apply in input order.\n return (async () => {\n const results: Record<string, any>[][] = [await first];\n for (let i = 1; i < entries.length; i++) {\n results.push(await runEntry(tx, entries[i]!));\n }\n return results;\n })();\n }\n const results: Record<string, any>[][] = [first];\n for (let i = 1; i < entries.length; i++) {\n results.push(runEntry(tx, entries[i]!));\n }\n return results;\n });\n};\n\nconst generateUpdateMany = createUpdateManyGenerator(sqlitePrimaryKeyPropNames, runSqliteUpdateManyBatch);\n\nconst sqliteSchemaData = createSchemaDataGenerator({\n tableClass: SQLiteTable,\n getTableConfig,\n primaryKeyPropNames: sqlitePrimaryKeyPropNames,\n // SQLite sorts NULLs as the smallest values (first in ASC).\n nullOrdering: 'nulls-smallest',\n // Writes come back with their rows, so the table types carry the `${Table}Item` outputs.\n returnsRows: true,\n // A synchronous driver (e.g. better-sqlite3) commits the moment its transaction callback\n // returns, so it can neither interleave awaited statements inside one transaction nor hold\n // one open across resolver calls — which is what both of these features require.\n preflight: (db, options) => {\n if (options.features.nestedWrites && (db as any).resultKind === 'sync') {\n throw new Error(\n 'Drizzle-GraphQL Error: features.nestedWrites requires an asynchronous SQLite driver (e.g. libsql). Synchronous drivers cannot run the multi-statement transaction a nested write needs.',\n );\n }\n if (options.transactions && (db as any).resultKind === 'sync') {\n throw new Error(\n \"Drizzle-GraphQL Error: transactions: 'auto' requires an asynchronous SQLite driver (e.g. libsql). Synchronous drivers cannot hold a transaction open across resolvers.\",\n );\n }\n },\n generateUpdateMany,\n});\n\nexport const generateSchemaData = <\n TDrizzleInstance extends SQLiteAsyncDatabase<any, any, any>,\n TSchema extends Record<string, Table | unknown>,\n>(\n db: TDrizzleInstance,\n schema: TSchema,\n relations: TablesRelationalConfig,\n options: SchemaGeneratorOptions,\n): GeneratedEntities<TDrizzleInstance, TSchema> => sqliteSchemaData(db, schema, relations, options);\n","import { is, Table } from 'drizzle-orm';\nimport { MySqlAsyncDatabase, getTableConfig as mysqlTableConfig } from 'drizzle-orm/mysql-core';\nimport { PgAsyncDatabase, getTableConfig as pgTableConfig } from 'drizzle-orm/pg-core';\nimport { SQLiteAsyncDatabase, getTableConfig as sqliteTableConfig } from 'drizzle-orm/sqlite-core';\nimport type { GraphQLResolveInfo } from 'graphql';\nimport type { AnyDrizzleDB } from '../types.ts';\nimport {\n attachTargetPrimaryKeys,\n buildNamedRelations,\n type DerivedTypeNameMapper,\n extractRelationsParams,\n getPrimaryKeyPropNamesFromConfig,\n memoizeTableConfig,\n type RelationFilterBase,\n resolveGeneratedTypeNames,\n resolveObjectTypeName,\n runRelationalSelect,\n type TypeNameMapper,\n type TypeNameResolver,\n} from './builders/common.ts';\nimport type { TableNamedRelations } from './builders/types.ts';\nimport { parseResolveInfo, type ResolveTree } from './parse-resolve-info.ts';\n\n/**\n * Everything the translation needs about a drizzle instance: the tables it holds, the\n * relation graph in this library's canonical shape, and the filter context that lets a\n * nested `where` reach a relation's target table. Derived once per instance — the same\n * derivation `buildSchema` does — and cached, since an overriding resolver calls this on\n * every request.\n */\ntype SelectionContext = {\n tables: Record<string, Table>;\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n filterCtx: RelationFilterBase;\n primaryKeyOf: (tableName: string) => readonly string[];\n};\n\nconst contextCache = new WeakMap<object, SelectionContext>();\n\ntype TableConfigLookup = (table: Table) => { primaryKeys: { columns: { name: string }[] }[] };\n\n// Cached per table, and bound at module scope so the cache is shared with every selection\n// this process translates — the same memoization each dialect builder applies.\nconst getMySqlTableConfig = memoizeTableConfig(mysqlTableConfig as unknown as TableConfigLookup);\nconst getPgTableConfig = memoizeTableConfig(pgTableConfig as unknown as TableConfigLookup);\nconst getSQLiteTableConfig = memoizeTableConfig(sqliteTableConfig as unknown as TableConfigLookup);\n\n/** The dialect's `getTableConfig`, which is the only place a composite primary key shows up. */\nconst tableConfigFor = (db: AnyDrizzleDB<any>): TableConfigLookup => {\n if (is(db, MySqlAsyncDatabase)) {\n return getMySqlTableConfig;\n }\n if (is(db, PgAsyncDatabase)) {\n return getPgTableConfig;\n }\n if (is(db, SQLiteAsyncDatabase)) {\n return getSQLiteTableConfig;\n }\n throw new Error('Drizzle-GraphQL Error: unsupported database instance — expected a PostgreSQL, MySQL or SQLite one.');\n};\n\nconst contextFor = (db: AnyDrizzleDB<any>): SelectionContext => {\n const cached = contextCache.get(db as object);\n if (cached) {\n return cached;\n }\n\n const relations = (db as any)._.relations ?? {};\n // Same reconstruction `buildSchema` does: the relations config is the only table map a v1\n // handle carries, and each of its entries carries its table.\n const schema = Object.fromEntries(\n Object.entries(relations as Record<string, any>)\n .filter(([, config]) => config?.table != null)\n .map(([key, config]) => [key, config.table]),\n );\n\n const tableEntries = Object.entries(schema as Record<string, unknown>).filter(([, value]) => is(value, Table)) as [\n string,\n Table,\n ][];\n if (!tableEntries.length) {\n throw new Error(\n 'Drizzle-GraphQL Error: Schema not found in drizzle instance. Pass relations (from buildRelations/defineRelations) to the drizzle constructor so drizzle-graphql can read your tables.',\n );\n }\n\n const tables = Object.fromEntries(tableEntries);\n const getTableConfig = tableConfigFor(db);\n const primaryKeyCache = new Map<string, readonly string[]>();\n const primaryKeyOf = (tableName: string): readonly string[] => {\n let pk = primaryKeyCache.get(tableName);\n if (!pk) {\n const table = tables[tableName];\n pk = table ? getPrimaryKeyPropNamesFromConfig(table, getTableConfig) : [];\n primaryKeyCache.set(tableName, pk);\n }\n return pk;\n };\n\n const relationMap = buildNamedRelations(relations, tableEntries);\n // Paginated relations fall back to a primary-key order, which is resolved once per target\n // and hung off the relation entry — exactly as the generated schema does it.\n attachTargetPrimaryKeys(relationMap, tables, (table) => [...primaryKeyOf(tableNameOf(tables, table))]);\n\n const context: SelectionContext = {\n tables,\n relationMap,\n filterCtx: { tables, relationMap },\n primaryKeyOf,\n };\n contextCache.set(db as object, context);\n return context;\n};\n\n/** Reverse lookup for `attachTargetPrimaryKeys`, which hands back the table, not its key. */\nconst tableNameOf = (tables: Record<string, Table>, table: Table): string =>\n Object.keys(tables).find((name) => tables[name] === table) ?? '';\n\n/** Options shared by {@link selectionToWith} and {@link resolveSelection}. */\nexport type SelectionOptions = {\n /** The drizzle instance the schema was built from. */\n db: AnyDrizzleDB<any>;\n /** The Drizzle schema key of the table the selection is rooted at. */\n table: string;\n /**\n * The `typeNameMapper` the schema was built with, when one was configured. The translation\n * matches selections against GraphQL type names, so a build that renames its types has to\n * pass the same mapper here or nothing will match.\n */\n typeNameMapper?: TypeNameMapper;\n /**\n * The `derivedTypeNameMapper` / `typeNamePrefix` / `typeNameSuffix` the schema was built\n * with, when any were configured. Same reason as `typeNameMapper`: the translation matches\n * selections against the names the build actually published.\n */\n derivedTypeNameMapper?: DerivedTypeNameMapper;\n typeNamePrefix?: string;\n typeNameSuffix?: string;\n};\n\n/** The build's naming rule, reassembled from the three options a caller passes back. */\nconst namingRuleOf = (options: SelectionOptions): TypeNameResolver =>\n resolveGeneratedTypeNames({\n derivedTypeNameMapper: options.derivedTypeNameMapper,\n typeNamePrefix: options.typeNamePrefix,\n typeNameSuffix: options.typeNameSuffix,\n });\n\n/**\n * Reads the parsed selection tree out of a resolver's `info`, resolving fragments and\n * inline fragments. Accepts an already-parsed tree so a caller that has one (or is chaining\n * these helpers) does not pay for the walk twice.\n */\nconst parseInfo = (info: GraphQLResolveInfo | ResolveTree): ResolveTree | undefined => {\n if ('fieldsByTypeName' in info) {\n return info as ResolveTree;\n }\n return parseResolveInfo(info, { deep: true }) as ResolveTree | undefined;\n};\n\n/**\n * Translates a GraphQL selection set into the relational query builder's `with` tree — the\n * same translation the generated resolvers use for their own queries.\n *\n * A resolver that replaces a generated one has to return a row shaped like the type it\n * replaced, and the field resolvers underneath only fill in relations the parent did not\n * already provide. Reproducing that by hand means resolving fragments against\n * `info.fragments`, intersecting selection names against the relations config (so scalars\n * and consumer-added fields drop out instead of becoming invalid `with` keys), following\n * aliases, compiling each relation's `where` / `orderBy` / `limit` / `offset` arguments into\n * its nested entry, and leaving `<relation>Aggregate` selections out — they are not `with`\n * entries at all. This does all of it.\n *\n * ```ts\n * const withTree = selectionToWith(info, { db, table: 'Users' });\n * const row = await tx.query.Users.findFirst({ where: { id: { eq } }, with: withTree });\n * ```\n *\n * Returns `undefined` when the selection asks for no relations, which is the value the\n * query builder wants for \"no `with` clause\".\n */\nexport const selectionToWith = (\n info: GraphQLResolveInfo | ResolveTree,\n options: SelectionOptions,\n): Record<string, any> | undefined => {\n const { db, table, typeNameMapper } = options;\n const resolveName = namingRuleOf(options);\n const { tables, relationMap, filterCtx } = contextFor(db);\n if (!tables[table]) {\n throw new Error(`Drizzle-GraphQL Error: '${table}' is not a table in the Drizzle schema.`);\n }\n if (!relationMap[table]) {\n return undefined;\n }\n\n const parsed = parseInfo(info);\n const params = extractRelationsParams(\n relationMap,\n tables,\n table,\n parsed,\n resolveObjectTypeName(table, typeNameMapper, resolveName),\n { typeNameMapper, filterCtx, resolveName },\n );\n // A selection with no relations in it gets no `with` clause at all, rather than an empty\n // object the query builder would have to be asked to ignore.\n return params && Object.keys(params).length ? params : undefined;\n};\n\n/** Options for {@link resolveSelection} — the selection options plus the read itself. */\nexport type ResolveSelectionOptions = SelectionOptions & {\n /**\n * The transaction (or other drizzle executor) to read on. Defaults to `db`, so an override\n * that has opened its own transaction passes it here to see its own uncommitted writes.\n */\n executor?: any;\n /** Whether to return one row or a list. A single read ignores `limit`. */\n single?: boolean;\n /** The generated `where` argument, in the schema's filter DSL — compiled the same way. */\n where?: any;\n /** The generated `orderBy` argument. */\n orderBy?: any;\n limit?: number;\n offset?: number;\n /** The generated `after` cursor argument, for keyset pagination. */\n after?: string;\n};\n\n/**\n * Runs the read a generated select resolver would have run, against whichever executor is\n * given — the whole body, not just the `with` tree: selected columns, relation arguments,\n * eager loading, cursor pagination, and the transport remapping of the result.\n *\n * This is what an override usually wants after it has done its own work:\n *\n * ```ts\n * const rows = await resolveSelection(info, { db, table: 'Users', where, executor: tx });\n * ```\n *\n * Relation arguments and aggregate fields keep behaving as they do in the generated schema,\n * because it is the generated schema's own code path.\n */\nexport const resolveSelection = async (\n info: GraphQLResolveInfo | ResolveTree,\n options: ResolveSelectionOptions,\n): Promise<any> => {\n const {\n db,\n table: tableName,\n typeNameMapper,\n executor,\n single = false,\n where,\n orderBy,\n limit,\n offset,\n after,\n } = options;\n const resolveName = namingRuleOf(options);\n const { tables, relationMap, filterCtx, primaryKeyOf } = contextFor(db);\n const table = tables[tableName];\n if (!table) {\n throw new Error(`Drizzle-GraphQL Error: '${tableName}' is not a table in the Drizzle schema.`);\n }\n\n const parsedInfo = parseInfo(info);\n if (!parsedInfo) {\n throw new Error('Drizzle-GraphQL Error: resolveSelection could not read a selection set from the resolve info.');\n }\n\n const source = executor ?? db;\n const queryBase = (source as any).query?.[tableName];\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: the executor passed to resolveSelection has no relational query builder for '${tableName}'.`,\n );\n }\n\n return runRelationalSelect({\n queryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName: resolveObjectTypeName(tableName, typeNameMapper, resolveName),\n typeNameMapper,\n resolveName,\n parsedInfo,\n single,\n where,\n orderBy,\n limit,\n offset,\n after,\n filterCtx,\n pkNames: primaryKeyOf(tableName),\n db: source,\n });\n};\n","import { is } from 'drizzle-orm';\nimport { MySqlAsyncDatabase } from 'drizzle-orm/mysql-core';\nimport { PgAsyncDatabase } from 'drizzle-orm/pg-core';\nimport { SQLiteAsyncDatabase } from 'drizzle-orm/sqlite-core';\nimport {\n type GraphQLFieldConfig,\n type GraphQLInputObjectType,\n GraphQLObjectType,\n GraphQLSchema,\n type GraphQLSchemaConfig,\n} from 'graphql';\nimport type { AnyDrizzleDB, BuildSchemaConfig, GeneratedData, NamingOf } from './types.ts';\nimport { resolveBuildConfig } from './util/build-config.ts';\nimport { applyErrorMapper, defaultErrorMapper } from './util/builders/common.ts';\nimport { generateMySQL, generatePG, generateSQLite } from './util/builders/index.ts';\n\nexport type {\n AggregateResolver,\n AnyDrizzleDB,\n BuildSchemaConfig,\n ComplexityConfig,\n ContextValuesConfig,\n DefaultOrderByEntry,\n DefaultsConfig,\n DeleteResolver,\n DeleteSingleResolver,\n DerivedTypeNameMapper,\n ExtractRelations,\n ExtractTableByName,\n ExtractTableRelations,\n ExtractTables,\n FeatureSwitch,\n GeneratedData,\n GeneratedEntities,\n GeneratedInputs,\n GeneratedOutputs,\n GeneratedTypeInfo,\n GeneratedTypeKind,\n InsertArrResolver,\n InsertResolver,\n LimitsConfig,\n MutationReturnlessResult,\n MutationsCore,\n NamingOf,\n NestedWriteOp,\n NestedWriteOrigin,\n OnWriteConfig,\n QueriesCore,\n RowScope,\n RowScopeFilter,\n SchemaExclusions,\n SchemaFeatures,\n ScopeConfig,\n SelectResolver,\n SelectSingleResolver,\n SoftDeleteColumn,\n SoftDeleteConfig,\n TableDefaults,\n TableLimitPolicy,\n TypeNameMapper,\n UpdateManyArgs,\n UpdateManyEntry,\n UpdateManyResolver,\n UpdateResolver,\n UpdateSingleResolver,\n UpsertArgs,\n UpsertArrResolver,\n UpsertConflictArgs,\n UpsertResolver,\n WriteHook,\n WriteHookPayload,\n WriteHookPositions,\n WriteHooks,\n WriteOperation,\n} from './types.ts';\nexport type { DrizzleErrorCode, DrizzleErrorContext, RelationResolverFactory } from './util/builders/common.ts';\nexport {\n createRelationResolverFactory,\n defaultErrorMapper,\n drizzleError,\n drizzleExecutorKey,\n extractFilters,\n extractOrderBy,\n extractRelationJoinColumns,\n} from './util/builders/common.ts';\nexport type { TableNamedRelations } from './util/builders/types.ts';\nexport { singularizeMapper } from './util/case-ops/index.ts';\nexport type {\n DrizzleExtension,\n DrizzleFieldExtension,\n DrizzleFieldKind,\n DrizzleFieldOperation,\n DrizzleTargetArg,\n DrizzleTypeExtension,\n IdentifiedRows,\n} from './util/extensions.ts';\nexport { drizzleExtension, identifyRows, isDrizzleFieldExtension } from './util/extensions.ts';\nexport type { FieldsByTypeName, ParseResolveInfoOptions, ResolveTree } from './util/parse-resolve-info.ts';\nexport { parseResolveInfo } from './util/parse-resolve-info.ts';\nexport {\n GraphQLBigIntString,\n GraphQLDate,\n GraphQLDateTime,\n GraphQLDecimalString,\n GraphQLJSON,\n GraphQLUUID,\n} from './util/scalars/index.ts';\nexport type { ResolveSelectionOptions, SelectionOptions } from './util/selection.ts';\nexport { resolveSelection, selectionToWith } from './util/selection.ts';\nexport type {\n ColumnDeprecator,\n ColumnDescriber,\n ColumnDocInfo,\n ColumnTypeMapper,\n ColumnTypeMapperInfo,\n EnumNameInfo,\n EnumNameMapper,\n EnumValueNameInfo,\n EnumValueNameMapper,\n RelationDescriber,\n ScalarOverride,\n ScalarOverridesConfig,\n SchemaDocs,\n TableDescriber,\n} from './util/type-converter/types.ts';\nexport type { Pluralize, Singularize, TypeNaming } from './util/type-naming.ts';\n\ntype ObjMap<T> = Record<string, T>;\n\nexport const buildSchema = <TDbClient extends AnyDrizzleDB<any>, TConfig extends BuildSchemaConfig = BuildSchemaConfig>(\n db: TDbClient,\n config?: TConfig,\n): GeneratedData<TDbClient, NamingOf<TConfig>> => {\n const relations = db._.relations;\n // The relations config is the only table map a v1 handle carries: `_.fullSchema` is gone\n // from all three dialects, and the constructor's separate `schema` argument no longer\n // reaches the handle at all. Each entry carries its own table, so the map is rebuilt from\n // there — a table left out of the relations config is simply not part of the schema.\n const schema = Object.fromEntries(\n Object.entries(relations as Record<string, any>)\n .filter(([, config]) => config?.table != null)\n .map(([key, config]) => [key, config.table]),\n );\n\n if (!Object.keys(schema).length) {\n throw new Error(\n 'Drizzle-GraphQL Error: Schema not found in drizzle instance. Pass relations (from buildRelations/defineRelations) to the drizzle constructor so drizzle-graphql can detect your tables.',\n );\n }\n\n const generatorOptions = resolveBuildConfig(config, schema as Record<string, unknown>);\n\n let generatorOutput;\n if (is(db, MySqlAsyncDatabase)) {\n generatorOutput = generateMySQL(db, schema, relations, generatorOptions);\n } else if (is(db, PgAsyncDatabase)) {\n generatorOutput = generatePG(db, schema, relations, generatorOptions);\n } else if (is(db, SQLiteAsyncDatabase)) {\n generatorOutput = generateSQLite(db, schema, relations, generatorOptions);\n } else {\n throw new Error('Drizzle-GraphQL Error: Unknown database instance type');\n }\n\n // Wrap resolvers before the schema is assembled, so the generated schema and the returned\n // entities share the same handling.\n const onError = config?.onError;\n applyErrorMapper(\n generatorOutput as any,\n onError ? (error) => onError(error) ?? defaultErrorMapper(error) : defaultErrorMapper,\n );\n\n const { queries, mutations, inputs, types } = generatorOutput;\n\n const graphQLSchemaConfig: GraphQLSchemaConfig = {\n types: [...Object.values(inputs), ...Object.values(types)] as (GraphQLInputObjectType | GraphQLObjectType)[],\n query: new GraphQLObjectType({\n name: 'Query',\n fields: queries as ObjMap<GraphQLFieldConfig<any, any, any>>,\n }),\n };\n\n // An empty Mutation type is invalid GraphQL, so turning off every mutation feature\n // omits the type the same way `mutations: false` does.\n if (config?.mutations !== false && Object.keys(mutations).length) {\n const mutation = new GraphQLObjectType({\n name: 'Mutation',\n fields: mutations as ObjMap<GraphQLFieldConfig<any, any, any>>,\n });\n\n graphQLSchemaConfig.mutation = mutation;\n }\n\n const outputSchema = new GraphQLSchema(graphQLSchemaConfig);\n\n // The three dialect generators are typed on their own dialect's database, so their union\n // does not structurally match `GeneratedEntities<TDbClient>` for a still-generic TDbClient.\n // The runtime branch above is what guarantees the right one was built.\n return {\n schema: outputSchema,\n entities: generatorOutput as unknown as GeneratedData<TDbClient, NamingOf<TConfig>>['entities'],\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiFA,MAAa,gBACX,SACA,EACE,MACA,OACA,GAAG,cAOL,IAAIA,QAAAA,aAAa,SAAS;CACxB;CACA,YAAY,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS;EAAE;EAAM,SAAS;CAAQ,IAAI,EAAE,KAAK;AAChF,CAAC;;;;;;;;AASH,MAAa,oBAAoB,OAAgB,YAA0C;CACzF,IAAI,EAAE,iBAAiBA,QAAAA,eACrB,OAAO;CAET,MAAM,EAAE,MAAM,YAAa,MAAM,cAAc,CAAC;CAChD,IAAI,OAAO,SAAS,YAAY,CAAC,KAAK,WAAW,UAAU,GACzD,OAAO;CAET,OAAO,IAAIA,QAAAA,aAAa,MAAM,SAAS;EACrC,OAAO,MAAM;EACb,QAAQ,MAAM;EACd,WAAW,MAAM;EACjB,MAAM,MAAM;EACZ,eAAe,MAAM;EACrB,YAAY;GAAE,GAAG,MAAM;GAAY,SAAS;IAAE,GAAG;IAAS,GAAG;GAAQ;EAAE;CACzE,CAAC;AACH;;;;;;AAOA,MAAa,kBAAkB,MAAwB;CACrD,IAAI,aAAaA,QAAAA,cACf,OAAO;CAET,OAAO,aAAa,QAAQ,IAAIA,QAAAA,aAAa,EAAE,SAAS,EAAE,eAAe,EAAE,CAAC,IAAI;AAClF;;;;;;;AAQA,MAAa,sBAAsB,UAA4B;CAC7D,IAAI,iBAAiBA,QAAAA,gBAAgB,CAAC,MAA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AAe,OAAO,OAAO,qBAAqB;EAChF,MAAM,EAAE,aAAa,aAAa,iBAAiB,MAAM;EACzD,MAAM,EACJ,UACA,sBACA,uBACA,sBACA,uBACA,iBACA,qBACA,uBACA,sBACA,iBACA,uBACA,kBACA,wBACA,yBACE;EAEJ,MAAM,qBAAqB,cAAc,SACrC,oBACE,IACA,WACA,OAAO,YACP,aACA,sBACA,eACA,QACF,IACA,KAAA;EACJ,MAAM,wBAAwB,cAAc,SACxC,qBACE,IACA,WACA,OAAO,YACP,aACA,uBACA,eACA,QACF,IACA,KAAA;EAGJ,MAAM,kBAAkB,cAAc,SAClC,wBAAwB;GACtB,OAAO,OAAO;GACd;GACA;GACA,YAAY,CAAC;GACb;GACA,YAAY;GACZ;EACF,CAAC,IACD,KAAA;EACJ,MAAM,qBAAqB,kBACvB,eACE,IACA,WACA,OAAO,YACP,aACA,iBACA,sBACA,OACA,eACA,QACF,IACA,KAAA;EACJ,MAAM,wBAAwB,kBAC1B,eACE,IACA,WACA,OAAO,YACP,aACA,iBACA,uBACA,MACA,eACA,QACF,IACA,KAAA;EACJ,MAAM,kBAAkB,cAAc,SAClC,eACE,IACA,WACA,OAAO,YACP,aACA,cACA,iBACA,OACA,cAAc,cACd,WACA,eACA,QACF,IACA,KAAA;EACJ,MAAM,wBAAwB,cAAc,SACxC,eACE,IACA,WACA,OAAO,YACP,aACA,cACA,uBACA,MACA,cAAc,cACd,WACA,eACA,QACF,IACA,KAAA;EAEJ,MAAM,kBACJ,cAAc,UAAU,cAAc,aAClC,wBAAwB;GACtB;GACA;GACA,cAAc,SAAS;GACvB;GACA;GACA;EACF,CAAC,IACD,KAAA;EACN,MAAM,sBAAsB,kBACxBN,qBACE,IACA,WACA,OAAO,YACP,iBACA,qBACA,WACA,eACA,QACF,IACA,KAAA;EACJ,MAAM,kBAAkB,cAAc,SAClC,eACE,IACA,WACA,OAAO,YACP,cACA,iBACA,OACA,cAAc,cACd,WACA,eACA,QACF,IACA,KAAA;EACJ,MAAM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