@vantreeseba/drizzle-graphql 6.0.0 → 7.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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/util/builders/common.ts","../src/util/batch-loader/index.ts","../src/util/case-ops/index.ts","../src/util/data-mappers/index.ts","../src/util/type-converter/index.ts","../src/util/scalars/index.ts","../src/util/builders/mysql.ts","../src/util/builders/aggregates.ts","../src/util/builders/pg.ts","../src/util/builders/nested-writes.ts","../src/util/builders/sqlite.ts"],"sourcesContent":["import { is } from 'drizzle-orm';\nimport { MySqlDatabase } from 'drizzle-orm/mysql-core';\nimport { PgAsyncDatabase } from 'drizzle-orm/pg-core';\nimport { BaseSQLiteDatabase } 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 } from './types.ts';\nimport { applyErrorMapper, defaultErrorMapper } from './util/builders/common.ts';\nimport { generateMySQL, generatePG, generateSQLite } from './util/builders/index.ts';\nimport type { SchemaGeneratorOptions } from './util/builders/types.ts';\n\nexport type {\n AggregateResolver,\n AnyDrizzleDB,\n BuildSchemaConfig,\n ComplexityConfig,\n DeleteResolver,\n DeleteSingleResolver,\n ExtractRelations,\n ExtractTableByName,\n ExtractTableRelations,\n ExtractTables,\n GeneratedData,\n GeneratedEntities,\n GeneratedInputs,\n GeneratedOutputs,\n InsertArrResolver,\n InsertResolver,\n MutationReturnlessResult,\n MutationsCore,\n QueriesCore,\n SchemaFeatures,\n SelectResolver,\n SelectSingleResolver,\n UpdateManyArgs,\n UpdateManyEntry,\n UpdateManyResolver,\n UpdateResolver,\n UpdateSingleResolver,\n UpsertArgs,\n UpsertArrResolver,\n UpsertConflictArgs,\n UpsertResolver,\n} from './types.ts';\nexport type { RelationResolverFactory } from './util/builders/common.ts';\nexport {\n createRelationResolverFactory,\n defaultErrorMapper,\n drizzleExecutorKey,\n extractFilters,\n extractOrderBy,\n extractRelationJoinColumns,\n} from './util/builders/common.ts';\nexport type { TableNamedRelations } from './util/builders/types.ts';\nexport {\n GraphQLBigIntString,\n GraphQLDate,\n GraphQLDateTime,\n GraphQLDecimalString,\n GraphQLJSON,\n GraphQLUUID,\n} from './util/scalars/index.ts';\nexport type {\n ColumnDeprecator,\n ColumnDescriber,\n ColumnDocInfo,\n ColumnTypeMapper,\n ColumnTypeMapperInfo,\n EnumNameInfo,\n EnumNameMapper,\n RelationDescriber,\n ScalarOverride,\n ScalarOverridesConfig,\n SchemaDocs,\n TableDescriber,\n} from './util/type-converter/types.ts';\n\ntype ObjMap<T> = Record<string, T>;\n\nexport const buildSchema = <TDbClient extends AnyDrizzleDB<any>>(\n db: TDbClient,\n config?: BuildSchemaConfig,\n): GeneratedData<TDbClient> => {\n const relations = db._.relations;\n // drizzle-orm v1 rc.2 removed fullSchema from PgAsyncDatabase._\n // For PG, reconstruct a schema-like map from db._.relations (each entry has { table }).\n // MySQL and SQLite still expose fullSchema directly.\n const schema =\n (db._ as any).fullSchema ??\n 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 (!schema || !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 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 };\n\n const suffixes = {\n list: config?.suffixes?.list ?? '',\n single: config?.suffixes?.single ?? 'Single',\n };\n\n const typeNameMapper = config?.typeNameMapper;\n\n // Every feature is on unless the caller says otherwise, so a build without a `features`\n // block generates what it always did — except upsert, which is new surface and so has to\n // be asked for.\n const features = {\n aggregates: config?.features?.aggregates ?? true,\n groupBy: config?.features?.groupBy ?? true,\n relationAggregates: config?.features?.relationAggregates ?? true,\n distinct: config?.features?.distinct ?? true,\n insert: config?.features?.insert ?? true,\n update: config?.features?.update ?? true,\n updateMany: config?.features?.updateMany ?? true,\n delete: config?.features?.delete ?? true,\n upsert: config?.features?.upsert ?? false,\n nestedWrites: config?.features?.nestedWrites ?? false,\n requireWhere: config?.features?.requireWhere ?? false,\n };\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 : { timeoutMs: (transactionsOpt === 'auto' ? undefined : transactionsOpt.timeoutMs) ?? 30_000 };\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 shouldEagerLoad,\n features,\n complexity,\n scalars: config?.scalars,\n mapColumnType: config?.mapColumnType,\n enumNameMapper: config?.enumNameMapper,\n transactions,\n docs: {\n describeColumn: config?.describeColumn,\n describeTable: config?.describeTable,\n describeRelation: config?.describeRelation,\n deprecateColumn: config?.deprecateColumn,\n },\n };\n\n let generatorOutput;\n if (is(db, MySqlDatabase)) {\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, BaseSQLiteDatabase)) {\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 return { schema: outputSchema, entities: generatorOutput };\n};\n","// =============================================================================\n// LOCAL MODIFICATION — diverges from upstream drizzle-graphql\n//\n// 1. generateColumnFilterValues() rewritten to produce generic shared filter\n// types (IdFilter, StringFilter, IntFilter, FloatFilter, BigIntFilter,\n// DecimalFilter, DateTimeFilter, BooleanFilter, per-enum, per-array) instead\n// of one type per (table, column) pair. The filter is picked by column data\n// type, not name.\n//\n// 2. Type naming:\n// - Select types: ${capitalize(tableName)} (e.g. Users)\n// - Relation fields: reference the target table's type directly (e.g. posts: [Posts!]!)\n// - Mutation return: same type as select (${capitalize(tableName)})\n// - Insert input: ${capitalize(insertPrefix)}${toTypeName(tableName)}Input (e.g. CreateUsersInput)\n// - Update input: ${capitalize(updatePrefix)}${toTypeName(tableName)}Input (e.g. UpdateUsersInput)\n// =============================================================================\n// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport type { Column, Relation, Table } from 'drizzle-orm';\nimport {\n aliasedTable,\n and,\n arrayContains,\n arrayOverlaps,\n asc,\n desc,\n eq,\n extractExtendedColumnType,\n getColumns,\n getTableAsAliasSQL,\n gt,\n gte,\n ilike,\n inArray,\n is,\n isNotNull,\n isNull,\n like,\n lt,\n lte,\n ne,\n not,\n notIlike,\n notInArray,\n notLike,\n One,\n or,\n relationsFilterToSQL,\n type SQL,\n sql,\n} from 'drizzle-orm';\nimport type { GraphQLFieldResolver } from 'graphql';\nimport {\n GraphQLBoolean,\n GraphQLEnumType,\n GraphQLError,\n GraphQLFloat,\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n type GraphQLScalarType,\n GraphQLString,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { getOrCreateLoader } from '../batch-loader/index.ts';\nimport { capitalize, uncapitalize } from '../case-ops/index.ts';\nimport { remapFromGraphQLCore, remapToGraphQLArrayOutput, remapToGraphQLSingleOutput } from '../data-mappers/index.ts';\nimport {\n GraphQLBigIntString,\n GraphQLDate,\n GraphQLDateTime,\n GraphQLDecimalString,\n GraphQLJSON,\n GraphQLUUID,\n} from '../scalars/index.ts';\nimport { drizzleColumnToGraphQLType, getColumnScalarOverride } from '../type-converter/index.ts';\nimport type {\n ConvertedColumn,\n ConvertedInputColumn,\n ConvertedRelationColumnWithArgs,\n SchemaDocs,\n} from '../type-converter/types.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 {\n FilterColumnOperators,\n FilterColumnOperatorsCore,\n Filters,\n FiltersCore,\n GeneratedTableTypes,\n GeneratedTableTypesOutputs,\n OrderByArgs,\n ProcessedTableSelectArgs,\n SelectData,\n SelectedColumnsRaw,\n SelectedSQLColumns,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst rqbCrashTypes = ['SQLiteBigInt', 'SQLiteBlobJson', 'SQLiteBlobBuffer'];\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 * 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 * 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 sourceColumns: any[] | undefined = rel.sourceColumns;\n const targetColumns: any[] | undefined = rel.targetColumns;\n\n if (!sourceColumns?.length || !targetColumns?.length) {\n return undefined;\n }\n\n const sourceCol = sourceColumns[0];\n const targetCol = targetColumns[0];\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 * 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\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\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 new GraphQLError(\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 );\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 new GraphQLError(\n `Drizzle-GraphQL Error: Shared mutation transaction timed out after ${txCtx.timeoutMs}ms waiting for the remaining mutation fields; rolling back.`,\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): 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 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 return body(resolveExecutor(db, context));\n }\n return runOnSharedTx(state, body);\n};\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 orderCtx?: RelationFilterContext,\n): Promise<any[]> => {\n const cols = 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) : []),\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 */\nexport const createRelationResolverFactory =\n (db: any, tables: Record<string, Table>, filterCtx?: RelationFilterBase): 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 // Resolved at build time (composite keys included) — used to tiebreak paginated batches.\n const targetPkNames = relEntry.targetPkNames ?? [];\n\n return async (parent, args, context) => {\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, orderBy: orderByArg, limit, offset } = (args ?? {}) as any;\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 const argsKey = JSON.stringify({\n where: whereArg ?? null,\n orderBy: orderByArg ?? null,\n limit: limit ?? null,\n offset: offset ?? null,\n });\n const loaderKey = `${tableName}::${relationName}::${argsKey}`;\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 const whereCondition = and(\n inArray(foreignCol, uniqueIds),\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n );\n\n let rows: any[];\n if (limit != null || offset != null) {\n // Per-parent pagination across the whole batch in one query.\n rows = await batchedPaginatedRelationQuery(\n executor,\n targetTable,\n foreignCol,\n whereCondition,\n orderByArg,\n limit ?? null,\n offset ?? null,\n targetPkNames,\n relationFilterCtx(filterCtx, targetTableName),\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 = executor.select().from(targetTable).where(whereCondition) as any;\n if (orderByArg) {\n q = q.orderBy(...extractOrderBy(targetTable, orderByArg, relationFilterCtx(filterCtx, targetTableName)));\n }\n rows = await q;\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\n/** Per-call cache context — created fresh on each generateSchemaData call to avoid type name collisions. */\nexport interface TypeCacheCtx {\n /** Cache of generic filter types, keyed by generic name (e.g. \"String\", \"DateTime\"). */\n genericFilterCache: Map<string, GraphQLInputObjectType>;\n /**\n * Cache of shared select object types, keyed by table name.\n * Value: the ${capitalize(tableName)} type (columns + relation fields).\n * A table may be pre-registered here as a columns-only shell before its root call runs.\n * Use fullyBuiltTables to distinguish a complete type from a pre-registered shell.\n */\n objectTypeCache: Map<string, GraphQLObjectType>;\n /**\n * Mutable containers for relation fields, keyed by table name.\n * Each container object is closed over by the corresponding GraphQLObjectType thunk so that\n * when the root call for a table populates its relation fields, the thunk automatically picks\n * them up — even if the shell was pre-registered by a different table's relation traversal.\n */\n relationFieldContainers: Map<string, { fields: Record<string, ConvertedRelationColumnWithArgs> }>;\n /**\n * Set of table names whose GraphQL object type has been fully built (root call completed).\n * Pre-registered shells (created when another table references this table as a relation target)\n * are NOT in this set until the root call for that table runs.\n */\n fullyBuiltTables: Set<string>;\n /**\n * Cache of relation types, keyed by \"${fromTableName}::${relName}\".\n * @deprecated No longer used — relation fields now reference the target table's own type directly.\n */\n relationTypeCache: Map<string, GraphQLObjectType>;\n /**\n * Per-call cache for a table's converted select-field map, keyed by table reference.\n * Per-call (not module-level) because scalar overrides can differ between builds that\n * share the same table objects.\n */\n selectFieldCache: WeakMap<object, Record<string, ConvertedColumn>>;\n /** Per-call cache for a table's column-filter field map, keyed by table reference. */\n filterFieldCache: WeakMap<object, Record<string, ConvertedInputColumn>>;\n /** Per-call cache for order GraphQL input types, keyed by table reference. */\n orderTypeCache: WeakMap<object, GraphQLInputObjectType>;\n /** Per-call cache for filter GraphQL input types, keyed by table reference. */\n filterTypeCache: WeakMap<object, GraphQLInputObjectType>;\n /**\n * Per-call cache for `${Target}ListRelationFilter` input types (the some/every/none wrapper\n * used by to-many relation filters), keyed by target table name.\n */\n listRelationFilterCache: Map<string, GraphQLInputObjectType>;\n /**\n * Per-call cache for `${Table}Aggregate` output types, keyed by table name. Shared between the\n * root `<table>Aggregate` query and the `<relation>Aggregate` field on every table that points\n * at it, so the schema never holds two types with the same name.\n */\n aggregateTypeCache: Map<string, GraphQLObjectType>;\n /**\n * Resolved complexity settings for this call, or `undefined` when the caller turned the hints\n * off. Not a cache, but the type builders are several calls deep and this context is already\n * threaded through all of them.\n */\n complexity: ResolvedComplexityOptions | undefined;\n /**\n * The build's documentation hooks (`describeColumn`, `describeTable`, `describeRelation`,\n * `deprecateColumn`). Empty when the caller configured none, which is the default — the\n * generator emits no descriptions of its own for column and relation fields.\n */\n docs: SchemaDocs;\n}\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 */\nconst 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\n/** The shape `graphql-query-complexity`'s `fieldExtensionsEstimator` hands to a field's hint. */\nexport type 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/**\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 */\nexport const listFieldComplexity =\n (options: ResolvedComplexityOptions): ComplexityEstimator =>\n ({ args, childComplexity }) => {\n const limit = args['limit'];\n const rows = typeof limit === 'number' && limit > 0 ? limit : options.defaultListSize;\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\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\nexport const extractSelectedColumnsFromTree = (\n tree: Record<string, ResolveTree>,\n table: Table,\n selectionCtx?: SelectionCtx,\n): Record<string, true> => {\n const tableColumns = getColumns(table);\n\n const treeEntries = Object.entries(tree);\n const selectedColumns: SelectedColumnsRaw = [];\n\n for (const [_fieldName, fieldData] of treeEntries) {\n if (!tableColumns[fieldData.name]) {\n continue;\n }\n\n selectedColumns.push([fieldData.name, true]);\n }\n\n for (const columnName of relationJoinColumns(tree, table, selectionCtx)) {\n selectedColumns.push([columnName, true]);\n }\n\n if (!selectedColumns.length) {\n const columnKeys = Object.entries(tableColumns);\n const columnName =\n columnKeys.find((e) => rqbCrashTypes.find((haram) => e[1].columnType !== haram))?.[0] ?? columnKeys[0]![0];\n\n selectedColumns.push([columnName, true]);\n }\n\n return Object.fromEntries(selectedColumns);\n};\n\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\n const treeEntries = Object.entries(tree);\n const selectedColumns: SelectedSQLColumns = [];\n\n for (const [_fieldName, fieldData] of treeEntries) {\n if (!tableColumns[fieldData.name]) {\n continue;\n }\n\n selectedColumns.push([fieldData.name, tableColumns[fieldData.name]!]);\n }\n\n for (const columnName of relationJoinColumns(tree, table, selectionCtx)) {\n selectedColumns.push([columnName, tableColumns[columnName]!]);\n }\n\n if (!selectedColumns.length) {\n const columnKeys = Object.entries(tableColumns);\n const columnName =\n columnKeys.find((e) => rqbCrashTypes.find((haram) => e[1].columnType !== haram))?.[0] ?? columnKeys[0]![0];\n\n selectedColumns.push([columnName, tableColumns[columnName]!]);\n }\n\n return Object.fromEntries(selectedColumns) as Record<string, TColType>;\n};\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 orderNulls = new GraphQLEnumType({\n name: 'OrderNulls',\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\nexport const innerOrder = new GraphQLInputObjectType({\n name: 'InnerOrder' as const,\n fields: {\n direction: {\n type: new GraphQLNonNull(\n new GraphQLEnumType({\n name: 'OrderDirection',\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 },\n priority: {\n type: new GraphQLNonNull(GraphQLInt),\n description: 'Priority of current field',\n },\n nulls: {\n type: orderNulls,\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 } as const,\n});\n\n/** The dialect a column belongs to, inferred from its drizzle columnType string (e.g. 'PgJsonb'). */\nconst 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/** 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\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\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)\n * - \"DateTime\" → timestamp and date columns\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' };\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 // Date / timestamp columns (check Drizzle internal columnType string)\n const ct: string = (column as any).columnType ?? '';\n if (ct === 'PgTimestamp' || ct === 'PgTimestampString' || ct === 'PgDate') {\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: ReturnType<typeof drizzleColumnToGraphQLType>['type']) => {\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 isNull: { type: GraphQLBoolean },\n isNotNull: { type: GraphQLBoolean },\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/…): they are nonsensical on opaque uuids and invalid SQL on numeric\n * columns. Keyed on the generic filter name (i.e. on column type) — a string-typed column\n * keeps the string operators whatever it is called.\n */\nconst FILTERS_WITHOUT_STRING_OPS = new Set(['Id', 'Int', 'Float', 'BigInt', 'Decimal']);\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\nconst 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 { name: genericName, kind } = inputOverride\n ? resolveOverrideFilterDescriptor(inputOverride)\n : resolveGenericFilterDescriptor(column, columnGraphQLType);\n const cached = cacheCtx.genericFilterCache.get(genericName);\n if (cached) {\n return cached;\n }\n\n const colType = columnGraphQLType.type;\n const colArr = new GraphQLList(new GraphQLNonNull(colType));\n\n // Uuid and numeric filters omit the string pattern operators\n // (like/ilike/startsWith/contains/…) — decided by column type, never by column name.\n // A filter shared with the built-ins keeps that name-keyed rule even for an overridden\n // column, so the shared type's shape never depends on which column built it first. A\n // custom override scalar's own filter carries the pattern operators only when a pattern\n // match is valid SQL on the underlying database column: string-typed, and not\n // numeric/decimal (those transport as strings but reject LIKE).\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 : FILTERS_WITHOUT_STRING_OPS.has(genericName);\n\n const baseFields =\n kind === 'json'\n ? jsonFilterFields(column, colType)\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 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 ...(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 }),\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: `${genericName}Filter`,\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\nconst orderMap = new WeakMap<object, Record<string, ConvertedInputColumn>>();\nconst generateTableOrderCached = (table: Table) => {\n if (orderMap.has(table)) {\n return orderMap.get(table)!;\n }\n\n let remapped = {};\n try {\n const columns = getColumns(table);\n const columnEntries = Object.entries(columns);\n\n remapped = Object.fromEntries(\n columnEntries.map(([columnName, _columnDescription]) => [columnName, { type: innerOrder }]),\n );\n\n orderMap.set(table, remapped);\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 = getColumns(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\nconst 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 = getColumns(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 * 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 */\nconst isFilterableRelation = (relation: Relation<string>): boolean => !(relation as any).through;\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\nconst 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: `${resolveTypeName(tableName, typeNameMapper)}OrderBy`,\n fields: () => {\n const orderColumns = generateTableOrderCached(table);\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: `${resolveTypeName(targetTableName, typeNameMapper)}ListRelationFilter`,\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\nconst 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 return {\n ...filterColumns,\n ...generateRelationFilterFields(tableName, cacheCtx, typeNameMapper, filterColumns, relationMap, tables),\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: `${resolveTypeName(tableName, typeNameMapper)}Filters`,\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\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 = resolveTypeName(tableName, typeNameMapper);\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 });\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: resolveTypeName(targetTableName, typeNameMapper),\n description: cacheCtx.docs.describeTable?.(targetTableName),\n fields: () => ({ ...targetTableFields, ...capturedTargetContainer.fields }),\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 },\n resolve,\n ...relationDocs,\n },\n ]);\n continue;\n }\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 },\n resolve,\n ...relationDocs,\n ...(cacheCtx.complexity ? { extensions: { complexity: listFieldComplexity(cacheCtx.complexity) } } : {}),\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 },\n resolve: relationAggregate.resolve,\n ...(cacheCtx.complexity\n ? { extensions: { 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 = getColumns(table);\n const columnEntries = Object.entries(columns);\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 columnEntries.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 columnEntries.map(([columnName, column]) => {\n const converted = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, true);\n return [\n columnName,\n { ...converted, ...inputFieldDocs(cacheCtx.docs, column, tableName, columnName, converted.type) },\n ];\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: `${capitalize(insertPrefix)}${typeName}Input`,\n fields: nestedWrites\n ? () => ({ ...insertFields, ...nestedWrites.createFields(tableName, typeName) })\n : insertFields,\n });\n\n const updateInput = new GraphQLInputObjectType({\n name: `${capitalize(updatePrefix)}${typeName}Input`,\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: resolveTypeName(tableName, typeNameMapper),\n description: cacheCtx.docs.describeTable?.(tableName),\n fields: { ...tableFields, ...relationFields },\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\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 .sort((a, b) => (b[1]?.priority ?? 0) - (a[1]?.priority ?? 0))\n .filter(([, config]) => config)\n .map(([column, config]) => {\n if (typeof config === 'object' && config.direction === undefined) {\n throw new GraphQLError(`ORDER BY ${column}: ordering through a relation is not supported in this query`);\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 new GraphQLError(`ORDER BY ${relationName}: Relation cannot be used for ordering`);\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 relationWhere = (relation as any).where\n ? relationsFilterToSQL((relation as any).isReversed ? parentTable : aliasedTarget, (relation as any).where)\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 * 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): 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 out.push({\n expression: 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 new GraphQLError(`ORDER BY ${key}: Unknown column or relation`);\n }\n\n const nextChain = extendRelationOrderChain(chain?.table ?? table, key, relEntry, ctx, chain);\n collectOrderEntries(nextChain.table, relEntry.targetTableName, config, ctx, nextChain, out);\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 * `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): SQL[] => {\n const entries: FlatOrderEntry[] = [];\n collectOrderEntries(table, ctx?.tableKey ?? '', orderArgs, ctx, undefined, entries);\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\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 * Whether the column stores JSON — its `contains` operator is structural containment,\n * not the safe substring operator string columns get.\n */\nconst isJsonColumn = (column: Column): boolean => (((column as any).columnType ?? '') as string).includes('Json');\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 new GraphQLError(`WHERE ${columnName}: Operator 'contains' is not supported for this dialect!`);\n }\n};\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, ...restOperators } = operators;\n\n const entries = Object.entries(restOperators as FilterColumnOperatorsCore<TColumn>);\n\n const singleValueOps: Record<string, (...args: any[]) => SQL> = { eq, ne, gt, gte, lt, lte };\n const stringValueOps: Record<string, (...args: any[]) => SQL> = { like, notLike, ilike, notIlike };\n const arrayValueOps: Record<string, (...args: any[]) => SQL> = { inArray, notInArray };\n // Membership operators for array columns: element list → SQL. Empty lists are rejected below.\n const arrayMembershipOps: Record<string, (...args: any[]) => SQL> = {\n hasSome: arrayOverlaps,\n hasEvery: arrayContains,\n };\n const nullableOps: Record<string, (...args: any[]) => SQL> = { isNull, isNotNull };\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(singleValueOps[operatorName]!(column, singleValue));\n } else if (operatorName in stringValueOps) {\n variants.push(stringValueOps[operatorName]!(column, operatorValue as string));\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 } = safeLikeOps[operatorName]!;\n variants.push(safeLikeCondition(column, buildPattern(operatorValue as string), insensitive));\n } else if (operatorName in arrayValueOps) {\n if (!(operatorValue as any[]).length) {\n throw new GraphQLError(`WHERE ${columnName}: Unable to use operator ${operatorName} with an empty array!`);\n }\n const arrayValue = (operatorValue as any[]).map((val) => remapFromGraphQLCore(val, column, columnName));\n variants.push(arrayValueOps[operatorName]!(column, arrayValue));\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 if (!(operatorValue as any[]).length) {\n throw new GraphQLError(`WHERE ${columnName}: Unable to use operator ${operatorName} with an empty array!`);\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 new GraphQLError(`WHERE ${columnName}: Unknown operator: ${operatorName}`);\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 if (extracted) {\n variants.push(not(extracted));\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\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\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'>;\n\n/** Narrows the build-scoped relation filter context to the table a resolver is filtering. */\nexport const relationFilterCtx = (\n base: RelationFilterBase | undefined,\n tableKey: string,\n): RelationFilterContext | undefined => (base ? { ...base, tableKey } : undefined);\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 */\nconst buildRelationJoinCondition = (\n parentTable: Table,\n relation: Relation<string>,\n aliasedTarget: Table,\n relationName: string,\n): SQL | undefined => {\n const sourceColumns = (relation as any).sourceColumns as Column[] | undefined;\n const targetColumns = (relation as any).targetColumns as Column[] | undefined;\n\n if (!sourceColumns?.length || sourceColumns.length !== targetColumns?.length) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\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 new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\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 = junctionRef?._?.column?.name;\n const byName = columnName ? Object.values(throughColumns).find((c) => c.name === columnName) : undefined;\n if (!byName) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\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 = (relation as any).sourceColumns as Column[] | undefined;\n const targetColumns = (relation as any).targetColumns as Column[] | undefined;\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 new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\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 new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\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 new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\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 new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\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 relationWhere = (relation as any).where\n ? relationsFilterToSQL((relation as any).isReversed ? parentTable : aliasedTarget, (relation as any).where)\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 new GraphQLError(`WHERE ${relationName}: Unknown relation filter key: ${mode}`);\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 const entries = Object.entries(fieldFilters as FiltersCore<TTable>);\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\n // A key that is neither a column nor a filterable relation must throw rather than be\n // dropped: when the generated schema is stitched/merged with another schema, same-named\n // inputs can contribute foreign keys that pass input validation, and a where that loses\n // all of its keys silently becomes an unbounded select/update/delete.\n if (!column && !(relations?.[fieldName] && relationCtx)) {\n throw new GraphQLError(`WHERE ${tableName}: Unknown filter key: ${fieldName}`);\n }\n\n const extracted = column\n ? extractFiltersColumn(column, fieldName, operators)\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 if (extracted) {\n variants.push(not(extracted));\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\nconst extractRelationsParamsInner = (\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n tables: Record<string, Table>,\n tableName: string,\n typeName: string,\n originField: ResolveTree,\n typeNameMapper?: TypeNameMapper,\n _isInitial: boolean = false,\n filterCtx?: RelationFilterBase,\n) => {\n const relationsForTable = relationMap[tableName];\n if (!relationsForTable) {\n return undefined;\n }\n\n const baseField = Object.entries(originField.fieldsByTypeName).find(([key, _value]) => key === typeName)?.[1];\n if (!baseField) {\n return undefined;\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 = resolveTypeName(targetTableName, typeNameMapper);\n // Look up by field name OR by alias (when the caller uses an alias for the relation).\n // graphql-parse-resolve-info keys fieldsByTypeName entries by alias.\n const field = baseField[relName] ?? Object.values(baseField).find((f) => (f as ResolveTree).name === relName);\n if (!field) {\n continue;\n }\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 const selectionCount = Object.values(baseField).reduce(\n (n, f) => n + ((f as ResolveTree).name === relName ? 1 : 0),\n 0,\n );\n if (selectionCount > 1) {\n continue;\n }\n const relField = (field as ResolveTree)?.fieldsByTypeName;\n const relFieldSelection = relField?.[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 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 const relationField = Object.values(baseField).find((e) => e.name === relName);\n const relationArgs: Partial<TableSelectArgs> | undefined = relationField?.args;\n\n const offset = relationArgs?.offset ?? undefined;\n const limit = relationArgs?.limit ?? undefined;\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 thisRecord.where = relWhere\n ? {\n RAW: (aliasedTable: Table) =>\n extractFilters(aliasedTable, relName, relWhere, relationFilterCtx(filterCtx, targetTableName)),\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))\n : hasPagination && pkNames.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined;\n thisRecord.offset = offset;\n thisRecord.limit = limit;\n\n const relWith = relationField\n ? extractRelationsParamsInner(\n relationMap,\n tables,\n targetTableName,\n relTypeName,\n relationField,\n typeNameMapper,\n false,\n filterCtx,\n )\n : undefined;\n thisRecord.with = relWith;\n\n args[relName] = thisRecord;\n }\n\n return args;\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 typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): Record<string, Partial<ProcessedTableSelectArgs>> | undefined => {\n if (!info) {\n return undefined;\n }\n\n return extractRelationsParamsInner(relationMap, tables, tableName, typeName, info, typeNameMapper, true, filterCtx);\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\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 * 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 = (\n table: Table,\n getTableConfig: (table: Table) => { 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/** 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 * 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 const payload = {\n o: entries,\n v: entries.map(([column]) => encodeCursorValue(row[column] ?? null)),\n };\n return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');\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 new GraphQLError('Invalid cursor: unable to decode it. Pass a cursor returned by a previous page.');\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 new GraphQLError('Invalid cursor: malformed payload. Pass a cursor returned by a previous page.');\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 new GraphQLError(\n \"Invalid cursor: it was issued for a different ordering. Pass the same orderBy the cursor's page used.\",\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 new GraphQLError(`Invalid cursor: unknown column '${column}'.`);\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 * 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 for (const row of rows) {\n row[ROW_CURSOR_PROP] = encodeCursor(entries, 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\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 = (\n table: Table,\n getTableConfig: (table: Table) => {\n primaryKeys: { columns: { name: string }[] }[];\n uniqueConstraints?: { columns: { name: string }[] }[];\n indexes?: { config: { unique?: boolean; columns: any[] } }[];\n },\n): string[][] => {\n const cols = getColumns(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\n/** Alias of the row-number helper column in the `distinct` pass. Namespaced against real columns. */\nconst 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\n * name), like the order/filter inputs, so repeated builds reuse one instance and two enums\n * 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 let tableCache = columnEnumCache.get(table);\n const cached = tableCache?.get(enumName);\n if (cached) {\n return cached;\n }\n\n const columnNames = Object.entries(getColumns(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(enumName, enumType);\n return enumType;\n};\n\n/** `${typeName}DistinctColumn` — the enum of columns a list query may be made distinct on. */\nexport const generateDistinctEnum = (table: Table, typeName: string): GraphQLEnumType | undefined =>\n generateColumnEnum(table, `${typeName}DistinctColumn`, `Columns of ${typeName} that a query can be made distinct on`);\n\n// ── upsert / conflict handling ────────────────────────────────────────────────\n\n/** Shared by every table's `${typeName}OnConflict` input, so it is created once. */\nexport const conflictActionEnum = new GraphQLEnumType({\n name: 'ConflictAction',\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 * 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 typeName: string;\n uniqueSets: string[][];\n tableFilters: GraphQLInputObjectType;\n withTarget: boolean;\n}): GraphQLInputObjectType | undefined => {\n const { table, typeName, uniqueSets, tableFilters, withTarget } = params;\n\n const updateEnum = generateColumnEnum(\n table,\n `${typeName}UpdateColumn`,\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: conflictActionEnum,\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 `${typeName}ConflictTarget`,\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: `${typeName}OnConflict`,\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 new GraphQLError(\n 'Unable to upsert: no conflict target was given and this table has no primary key. Pass onConflict.target.',\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 new GraphQLError(\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 );\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 new GraphQLError(\n `Unable to upsert: onConflict.update lists ${unsupplied.join(', ')}, which the values do not supply.`,\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\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 */\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}): Promise<Record<string, any>[]> => {\n const { db, table, tableName, distinct, pkNames, where, orderBy, limit, offset } = params;\n const cols = getColumns(table);\n\n if (!pkNames.length) {\n throw new GraphQLError(`Table ${tableName} has no primary key, so 'distinct' cannot be applied to it.`);\n }\n\n const partitionCols = distinct.map((name) => cols[name]).filter(Boolean);\n if (!partitionCols.length) {\n throw new GraphQLError(`No known columns were given to 'distinct' on ${tableName}.`);\n }\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\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 const prepareMutationRelationColumns = (params: {\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}): {\n columns: Record<string, Column>;\n hasRelations: boolean;\n withParams: Record<string, Partial<ProcessedTableSelectArgs>> | undefined;\n} => {\n const { relationMap, tables, tableName, typeName, typeNameMapper, table, pkNames, parsedInfo } = params;\n const withParams = relationMap[tableName]\n ? extractRelationsParams(relationMap, tables, tableName, parsedInfo, typeName, typeNameMapper)\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/** Wraps a thrown Error as a (message-only) GraphQLError; passes non-Errors through unchanged. */\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\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 },\n suffixes: { list: string; single: string },\n): {\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 deleteFieldName: string;\n deleteSingleFieldName: string;\n} => {\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 createArrayFieldName = `${prefixes.insert}${mapped ? capitalize(mapped.plural) : capitalize(tableName)}`;\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}${mapped ? capitalize(mapped.plural) : capitalize(tableName)}`;\n const upsertSingleFieldName = mapped\n ? `${upsertPrefix}${capitalize(mapped.singular)}`\n : `${upsertPrefix}${capitalize(tableName)}${suffixes.single}`;\n const updateFieldName = `${prefixes.update}${mapped ? capitalize(mapped.singular) : capitalize(tableName)}`;\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}${mapped ? capitalize(mapped.plural) : capitalize(tableName)}Many`;\n const deleteFieldName = `${prefixes.delete}${mapped ? capitalize(mapped.singular) : capitalize(tableName)}`;\n // The plural update/delete mutations already use the singular noun when a mapper is\n // present, so — unlike create — the Single variants can't rely on singular vs plural to\n // stay distinct. They always carry a suffix, falling back to 'Single' when the configured\n // suffix is empty (a mapper config may set it to '' for the query side).\n const writeSingleSuffix = suffixes.single === '' ? 'Single' : suffixes.single;\n const updateSingleFieldName = `${updateFieldName}${writeSingleSuffix}`;\n const deleteSingleFieldName = `${deleteFieldName}${writeSingleSuffix}`;\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 deleteFieldName,\n deleteSingleFieldName,\n };\n};\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 typeName: string;\n updatePrefix: string;\n updateInput: GraphQLInputObjectType;\n tableFilters: GraphQLInputObjectType;\n}): GraphQLInputObjectType => {\n const { typeName, updatePrefix, updateInput, tableFilters } = params;\n return new GraphQLInputObjectType({\n name: `${capitalize(updatePrefix)}${typeName}ManyInput`,\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 fieldName: string,\n relationCtx?: RelationFilterContext,\n): SQL => {\n const filters = where ? extractFilters(table, tableName, where, relationCtx) : undefined;\n if (!filters) {\n throw new GraphQLError(`${fieldName} requires a 'where' argument with at least one filter!`);\n }\n return filters;\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 (\n executor: any,\n table: Table,\n filters: SQL,\n fieldName: string,\n): Promise<void> => {\n const matched = await executor.select({ found: sql`1` }).from(table).where(filters).limit(2);\n if (matched.length > 1) {\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row — nothing was written!`);\n }\n};\n\n/** GraphQL argument map for a list/array select field. */\nexport const selectArrayArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n distinctEnum?: GraphQLEnumType,\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});\n\n/** GraphQL argument map for a single-row select field (no `limit`). */\nexport const selectSingleArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n): Record<string, { type: any }> => ({\n offset: { type: GraphQLInt },\n orderBy: { type: orderArgs },\n where: { type: filterArgs },\n});\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}): 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 } = 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 new GraphQLError(\"'after' cannot be combined with 'distinct'.\");\n }\n if (orderByHasRelationEntry(orderBy)) {\n if (after != null) {\n throw new GraphQLError(\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 );\n }\n // `cursor` was selected under a relation ordering — the field resolves to null and the\n // relation ordering itself still applies.\n } else if (!pkNames?.length) {\n if (after != null) {\n throw new GraphQLError(`Table ${tableName} has no primary key, so cursor pagination cannot be used on it.`);\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 extractRelationsParamsInner.\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: where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\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)) : []),\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) => extractOrderBy(aliasedTable, orderBy, relationFilterCtx(filterCtx, tableName))\n : needsDefaultOrder && pkNames?.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined,\n where: distinctKeys\n ? { RAW: (aliasedTable: Table) => primaryKeyRestriction(aliasedTable, pkNames!, distinctKeys!) }\n : where || cursorValues\n ? {\n RAW: (aliasedTable: Table) =>\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 }\n : undefined,\n with: relationMap[tableName]\n ? extractRelationsParams(relationMap, tables, tableName, parsedInfo, typeName, typeNameMapper, filterCtx)\n : undefined,\n };\n\n if (single) {\n const result = await queryBase.findFirst(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(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","// @ts-nocheck\nconst DRIZZLE_LOADERS_KEY = Symbol('drizzle-graphql-loaders');\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","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","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { type Column, getTableColumns, is, One, type Table } from 'drizzle-orm';\nimport { GraphQLError } from 'graphql';\nimport type { TableNamedRelations } from '../builders/index.ts';\nimport { getColumnScalarOverride } from '../type-converter/index.ts';\n\n// drizzle-orm v1 uses compound dataType strings (e.g. \"object json\"), so inclusion rather\n// than equality. PgGeometryObject is stored as json but has its own object type.\nconst isJsonColumn = (column: Column): boolean =>\n ((column as any).dataType ?? '').includes('json') && (column as any).columnType !== 'PgGeometryObject';\n\nexport const remapToGraphQLCore = (\n key: string,\n value: any,\n tableName: string,\n column: Column,\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 if (value instanceof Date) {\n return value.toISOString();\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 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 = table[key as keyof Table] as Column | undefined;\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) => {\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 (SQLite: \"object date\", MySQL timestamp/datetime: \"object date\").\n // Only convert string→Date for timestamp/datetime columns, NOT pure DATE columns.\n // MySqlDateString has dataType \"string date\" (excluded by startsWith check).\n // MySqlDate has columnType \"MySqlDate\" — excluded below since it can accept raw strings.\n const columnType: string = (column as any).columnType ?? '';\n const isTimestampColumn =\n columnType === 'SQLiteTimestamp' ||\n columnType === 'SQLiteTimestampMs' ||\n columnType === 'MySqlTimestamp' ||\n columnType === 'MySqlDateTime' ||\n columnType === 'PgTimestamp' ||\n columnType === 'PgTimestampString';\n if (isTimestampColumn) {\n const formatted = new Date(value);\n if (Number.isNaN(formatted.getTime())) {\n throw new GraphQLError(`Field '${columnName}' is not a valid date!`);\n }\n\n return formatted;\n }\n\n // Date-only columns (no time component) — extract YYYY-MM-DD portion to avoid\n // timezone shifts when mysql2 formats Date objects using local time.\n const isDateOnlyColumn = columnType === 'MySqlDate' || columnType === 'PgDate';\n if (isDateOnlyColumn && typeof value === 'string') {\n // Accept ISO strings like \"2024-04-04T00:00:00.000Z\" or plain \"2024-04-04\"\n const dateOnly = value.includes('T') ? value.split('T')[0] : value;\n // Validate it's a real date by parsing\n const check = new Date(dateOnly!);\n if (Number.isNaN(check.getTime())) {\n throw new GraphQLError(`Field '${columnName}' is not a valid date!`);\n }\n\n return dateOnly;\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 new GraphQLError(`Field '${columnName}' is not a BigInt!`);\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 new GraphQLError(`Field '${columnName}' is not a valid date!`);\n }\n\n return formatted;\n }\n\n case 'buffer': {\n if (!Array.isArray(value)) {\n throw new GraphQLError(`Field '${columnName}' is not an array!`);\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 new GraphQLError(\n `Invalid JSON in field '${columnName}':\\n${e instanceof Error ? e.message : 'Unknown error'}`,\n );\n }\n }\n\n case 'array': {\n if (!Array.isArray(value)) {\n throw new GraphQLError(`Field '${columnName}' is not an array!`);\n }\n\n if (column.columnType === 'PgGeometry' && value.length !== 2) {\n throw new GraphQLError(\n `Invalid float tuple in field '${columnName}': expected array with length of 2, received ${value.length}`,\n );\n }\n\n return value;\n }\n\n case 'bigint': {\n try {\n return BigInt(value);\n } catch (_error) {\n throw new GraphQLError(`Field '${columnName}' is not a BigInt!`);\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\nexport const remapFromGraphQLSingleInput = (queryInput: Record<string, any>, table: Table) => {\n for (const [key, value] of Object.entries(queryInput)) {\n if (value === undefined) {\n delete queryInput[key];\n } else {\n const column = getTableColumns(table)[key];\n if (!column) {\n throw new GraphQLError(`Unknown column: ${key}`);\n }\n\n if (value === null && column.notNull) {\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 = (queryInput: Record<string, any>[], table: Table) => {\n for (const entry of queryInput) {\n remapFromGraphQLSingleInput(entry, table);\n }\n\n return queryInput;\n};\n","import type { Column, Table } from 'drizzle-orm';\nimport { extractExtendedColumnType, getTableColumns, is } from 'drizzle-orm';\nimport { MySqlInt, MySqlSerial } from 'drizzle-orm/mysql-core';\nimport { PgDate, PgDateString, PgInteger, PgSerial, PgTimestamp, PgTimestampString, PgUUID } from 'drizzle-orm/pg-core';\nimport { SQLiteInteger } 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 } 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 ScalarOverride,\n ScalarOverridesConfig,\n} from './types.ts';\n\nconst allowedNameChars = /^[a-zA-Z0-9_]+$/;\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 * 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 }>();\nlet enumNameMapper: EnumNameMapper | undefined;\n\n/**\n * Resets the enum registry for a fresh schema build and installs that build's\n * `enumNameMapper`. 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: { enumNameMapper?: EnumNameMapper }): void => {\n enumNameMapper = config.enumNameMapper;\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 valuesKey = enumValuesKey(values);\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 return claimed.type;\n }\n\n const gqlEnum = new GraphQLEnumType({\n name,\n values: Object.fromEntries(\n values.map((e, index) => [\n allowedNameChars.test(e) ? e : `Option${index}`,\n {\n value: e,\n description: `Value: ${e}`,\n },\n ]),\n ),\n });\n\n enumNamesInUse.set(name, { type: gqlEnum, valuesKey });\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\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 (column instanceof PgTimestamp || column instanceof PgDate) {\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 (column instanceof PgTimestamp || column instanceof PgTimestampString) {\n return { type: GraphQLDateTime, typeLabel: 'DateTime' };\n }\n if (column instanceof PgUUID) {\n return { type: GraphQLUUID, typeLabel: 'UUID' };\n }\n if (column instanceof PgDateString) {\n // For input, accept any string (drivers truncate ISO timestamps to date on write).\n // For output, keep the strict GraphQLDate scalar so the returned value is validated.\n return isInput ? { type: GraphQLString, typeLabel: 'Date' } : { 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 return 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(getTableColumns(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>(\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 type: new GraphQLNonNull(typeDesc.type),\n typeLabel: typeDesc.typeLabel,\n } as ConvertedColumn<TIsInput>;\n }\n\n return typeDesc as ConvertedColumn<TIsInput>;\n};\n","import { GraphQLError, GraphQLScalarType, Kind } from 'graphql';\nimport { GraphQLDate, GraphQLDateTime, GraphQLJSON, GraphQLUUID } from 'graphql-scalars';\n\nconst asDecimalString = (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 new GraphQLError(`BigInt cannot represent non-integer value: ${value}`);\n }\n if (!Number.isSafeInteger(value)) {\n throw new GraphQLError(\n `BigInt cannot represent the number ${value} without precision loss — pass it as a string instead`,\n );\n }\n return String(value);\n }\n\n if (typeof value === 'string') {\n if (!/^-?\\d+$/.test(value)) {\n throw new GraphQLError(`BigInt cannot represent non-integer value: \"${value}\"`);\n }\n return value;\n }\n\n throw new GraphQLError(`BigInt cannot represent value: ${JSON.stringify(value)}`);\n};\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: asDecimalString,\n parseValue: asDecimalString,\n parseLiteral: (ast) => {\n if (ast.kind !== Kind.STRING && ast.kind !== Kind.INT) {\n throw new GraphQLError(`BigInt cannot represent a ${ast.kind}`, { nodes: ast });\n }\n return asDecimalString(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 asNumericString = (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 new GraphQLError(`Decimal cannot represent non-finite value: ${value}`);\n }\n return String(value);\n }\n\n if (typeof value === 'string') {\n if (!numericStringPattern.test(value)) {\n throw new GraphQLError(`Decimal cannot represent non-numeric value: \"${value}\"`);\n }\n return value;\n }\n\n throw new GraphQLError(`Decimal cannot represent value: ${JSON.stringify(value)}`);\n};\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: asNumericString,\n parseValue: asNumericString,\n parseLiteral: (ast) => {\n if (ast.kind !== Kind.STRING && ast.kind !== Kind.INT && ast.kind !== Kind.FLOAT) {\n throw new GraphQLError(`Decimal cannot represent a ${ast.kind}`, { nodes: ast });\n }\n return asNumericString(ast.value);\n },\n});\n\nexport { GraphQLDate, GraphQLDateTime, GraphQLJSON, GraphQLUUID };\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { is, One, type Table } from 'drizzle-orm';\nimport { getTableConfig, type MySqlDatabase, MySqlTable } from 'drizzle-orm/mysql-core';\nimport type { RelationalQueryBuilder } from 'drizzle-orm/mysql-core/query-builders/query';\nimport type { GraphQLFieldConfig, GraphQLFieldConfigArgumentMap, ThunkObjMap } from 'graphql';\nimport {\n GraphQLBoolean,\n GraphQLError,\n type GraphQLInputObjectType,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\n\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n aggregateFieldComplexity,\n assertSingleMatch,\n attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createMutationTxCtx,\n createRelationResolverFactory,\n extractFilters,\n extractRequiredFilters,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n generateUpdateManyInput,\n getPrimaryKeyPropNamesFromConfig,\n listFieldComplexity,\n type MutationTxCtx,\n mysqlValuesColumnRef,\n type OnConflictArg,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n relationFilterCtx,\n resolveConflictPlan,\n resolveQueryExecutor,\n runMutation,\n runRelationalSelect,\n selectArrayArgs,\n selectSingleArgs,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n} from '../builders/common.ts';\nimport { remapFromGraphQLArrayInput, remapFromGraphQLSingleInput } from '../data-mappers/index.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} from './aggregates.ts';\nimport type {\n CreatedResolver,\n Filters,\n SchemaGeneratorOptions,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst generateSelectArray = (\n db: MySqlDatabase<any, any, 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 = true,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const table = tables[tableName]!;\n const pkNames = mysqlPrimaryKeyPropNames(table as MySqlTable);\n const queryArgs = selectArrayArgs(\n orderArgs,\n filterArgs,\n distinctEnabled ? generateDistinctEnum(table, typeName) : undefined,\n );\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\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,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: false,\n filterCtx,\n pkNames,\n db: executor,\n // MySQL sorts NULLs as the smallest values (first in ASC).\n nullOrdering: 'nulls-smallest',\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateSelectSingle = (\n db: MySqlDatabase<any, any, 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): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const queryArgs = selectSingleArgs(orderArgs, filterArgs);\n\n const table = tables[tableName]!;\n const pkNames = mysqlPrimaryKeyPropNames(table as MySqlTable);\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\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,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n pkNames,\n db: executor,\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateInsertArray = (\n db: MySqlDatabase<any, any, any, any>,\n _tableName: string,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n txCtx?: MutationTxCtx,\n): CreatedResolver => {\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(baseType))),\n },\n };\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any>[] }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const input = remapFromGraphQLArrayInput(args.values, table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n\n await executor.insert(table).values(input);\n\n return { isSuccess: true };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateInsertSingle = (\n db: MySqlDatabase<any, any, any, any>,\n _tableName: string,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n txCtx?: MutationTxCtx,\n): CreatedResolver => {\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: new GraphQLNonNull(baseType),\n },\n };\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const input = remapFromGraphQLSingleInput(args.values, table);\n\n await executor.insert(table).values(input);\n\n return { isSuccess: true };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateUpsert = (\n db: MySqlDatabase<any, any, any, any>,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n onConflictType: GraphQLInputObjectType,\n fieldName: string,\n single: boolean,\n txCtx?: MutationTxCtx,\n): CreatedResolver => {\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.',\n },\n };\n\n const pkNames = mysqlPrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { values: Record<string, any> | Record<string, any>[]; onConflict?: OnConflictArg },\n context,\n info,\n ) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const input = single\n ? [remapFromGraphQLSingleInput(args.values as Record<string, any>, table)]\n : remapFromGraphQLArrayInput(args.values as Record<string, any>[], table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\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 return { isSuccess: true };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateUpdate = (\n db: MySqlDatabase<any, 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): CreatedResolver => {\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 return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table>; set: Record<string, any> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { where, set } = args;\n\n const input = remapFromGraphQLSingleInput(set, table);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\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 return { isSuccess: true };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\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: MySqlDatabase<any, any, any>,\n tableName: string,\n table: MySqlTable,\n updateManyInput: GraphQLInputObjectType,\n fieldName: string,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n): CreatedResolver => {\n const queryArgs = {\n updates: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(updateManyInput))),\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { updates: { where?: Filters<Table>; set: Record<string, any> }[] },\n context,\n info,\n ) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { updates } = args;\n if (!updates.length) {\n throw new GraphQLError('No updates were provided!');\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 = updates.map(({ where, set }) => {\n const input = remapFromGraphQLSingleInput(set, table);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n filters: where\n ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined,\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 return { isSuccess: true };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateDelete = (\n db: MySqlDatabase<any, 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): CreatedResolver => {\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { where } = args;\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n await query;\n\n return { isSuccess: true };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\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\nexport const generateSchemaData = <\n TDrizzleInstance extends MySqlDatabase<any, 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> => {\n const { relationsDepthLimit, prefixes, suffixes, typeNameMapper, shouldEagerLoad, features, complexity } = options;\n const rawSchema = schema;\n const schemaEntries = Object.entries(rawSchema);\n\n const tableEntries = schemaEntries.filter(([_key, value]) => is(value, MySqlTable)) as [string, MySqlTable][];\n const tables = Object.fromEntries(tableEntries);\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 // 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 if (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 // 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\n // Build namedRelations from the drizzle-orm v1 relations config.\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Record each relation target's (composite-aware) primary key for deterministic\n // paginated ordering. Must run before pruning / type generation (shared entry objects).\n attachTargetPrimaryKeys(namedRelations, tables, mysqlPrimaryKeyPropNames);\n // Pruned map for query resolvers' `with:`; type generation keeps the full map.\n const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);\n\n const filterCtx: RelationFilterBase = { tables, relationMap: namedRelations };\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(db, tables, filterCtx);\n\n // Fresh cache per generateSchemaData call — prevents type name collisions\n // when buildSchema() is called multiple times.\n const cacheCtx: TypeCacheCtx = {\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 docs: options.docs ?? {},\n };\n\n // Left undefined when the feature is off — generateTableTypes then emits no\n // `${relation}Aggregate` fields at all.\n const relationAggregateFactory: RelationAggregateFactory | undefined = features.relationAggregates\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx)\n : undefined;\n\n const queries: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const mutations: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n // One per schema build: every mutation resolver shares it so a multi-mutation request can\n // ride a single transaction. Undefined unless transactions were requested.\n const mutationTxCtx = createMutationTxCtx(options.transactions);\n const gqlSchemaTypes = Object.fromEntries(\n Object.entries(tables).map(([tableName, _table]) => [\n tableName,\n generateTableTypes(\n tableName,\n tables,\n namedRelations,\n false,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n prefixes.insert,\n prefixes.update,\n resolverFactory,\n relationAggregateFactory,\n ),\n ]),\n );\n\n const mutationReturnType = new GraphQLObjectType({\n name: 'MutationReturn',\n fields: {\n isSuccess: {\n type: new GraphQLNonNull(GraphQLBoolean),\n },\n },\n });\n\n const inputs: Record<string, GraphQLInputObjectType> = {};\n const outputs: Record<string, GraphQLObjectType> = {};\n // Every MySQL mutation returns it, so it only belongs in the type map when at least one\n // mutation is generated.\n if (features.insert || features.upsert || features.update || features.delete) {\n outputs.MutationReturn = mutationReturnType;\n }\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n const { insertInput, updateInput, tableFilters, tableOrder } = tableTypes.inputs;\n const { selectSingleOutput, selectArrOutput } = tableTypes.outputs;\n\n // Compute field names using the mapper logic\n const {\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 deleteFieldName,\n deleteSingleFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\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 features.distinct,\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 );\n const insertArrGenerated = features.insert\n ? generateInsertArray(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n createArrayFieldName,\n mutationTxCtx,\n )\n : undefined;\n const insertSingleGenerated = features.insert\n ? generateInsertSingle(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n createSingleFieldName,\n mutationTxCtx,\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 = features.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as MySqlTable,\n typeName,\n uniqueSets: [],\n tableFilters,\n withTarget: false,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(\n db,\n schema[tableName] as MySqlTable,\n insertInput,\n onConflictInput,\n upsertArrayFieldName,\n false,\n mutationTxCtx,\n )\n : undefined;\n const upsertSingleGenerated = onConflictInput\n ? generateUpsert(\n db,\n schema[tableName] as MySqlTable,\n insertInput,\n onConflictInput,\n upsertSingleFieldName,\n true,\n mutationTxCtx,\n )\n : undefined;\n const updateGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateFieldName,\n false,\n features.requireWhere,\n filterCtx,\n mutationTxCtx,\n )\n : undefined;\n const updateSingleGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n true,\n features.requireWhere,\n filterCtx,\n mutationTxCtx,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n features.update && features.updateMany\n ? generateUpdateManyInput({ typeName, updatePrefix: prefixes.update, updateInput, tableFilters })\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 )\n : undefined;\n const deleteGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteFieldName,\n false,\n features.requireWhere,\n filterCtx,\n mutationTxCtx,\n )\n : undefined;\n const deleteSingleGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteSingleFieldName,\n true,\n features.requireWhere,\n filterCtx,\n mutationTxCtx,\n )\n : undefined;\n const aggregateType = features.aggregates\n ? generateAggregateTypes(schema[tableName] as MySqlTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = features.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n features.aggregates && features.groupBy\n ? generateGroupByType(schema[tableName] as MySqlTable, tableName, typeName, cacheCtx)\n : undefined;\n const groupByEnum = groupByType\n ? generateGroupByEnum(schema[tableName] as MySqlTable, tableName, typeName)\n : undefined;\n const havingInput = groupByEnum\n ? generateHavingInput(schema[tableName] as MySqlTable, tableName, typeName)\n : undefined;\n const groupByGenerated =\n groupByType && groupByEnum && havingInput\n ? generateGroupBy(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n typeName,\n groupByFieldName,\n tableFilters,\n groupByEnum,\n havingInput,\n filterCtx,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n ...(complexity ? { extensions: { complexity: listFieldComplexity(complexity) } } : {}),\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n for (const generated of [\n insertArrGenerated,\n insertSingleGenerated,\n upsertArrGenerated,\n upsertSingleGenerated,\n updateGenerated,\n updateManyGenerated,\n updateSingleGenerated,\n deleteGenerated,\n deleteSingleGenerated,\n ]) {\n if (generated) {\n mutations[generated.name] = {\n type: mutationReturnType,\n args: generated.args,\n resolve: generated.resolver,\n };\n }\n }\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 ...(features.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(features.update ? [updateInput] : []),\n ...(updateManyInput ? [updateManyInput] : []),\n tableFilters,\n tableOrder,\n ];\n activeInputs.forEach((e) => {\n inputs[e.name] = e;\n });\n outputs[selectSingleOutput.name] = selectSingleOutput;\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 // The first mutation resolver of a request counts the operation's root mutation fields to\n // know how many completions to wait for — but only fields this library generated can report\n // completion, so the shared-transaction path needs the full roster of generated names.\n if (mutationTxCtx) {\n for (const name of Object.keys(mutations)) {\n mutationTxCtx.fieldNames.add(name);\n }\n }\n\n const fieldResolvers: Record<string, Record<string, any>> = {};\n for (const [tableName, tableRelations] of Object.entries(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 = 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 { queries, mutations, inputs, types: outputs, fieldResolvers } as any;\n};\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport {\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 GraphQLError,\n GraphQLFloat,\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\nimport { getOrCreateLoader } from '../batch-loader/index.ts';\nimport { capitalize } from '../case-ops/index.ts';\nimport { remapToGraphQLCore } from '../data-mappers/index.ts';\nimport { drizzleColumnToGraphQLType } from '../type-converter/index.ts';\nimport type { ConvertedColumn } from '../type-converter/types.ts';\nimport {\n columnDocs,\n extractFilters,\n extractRelationJoinColumns,\n generateColumnEnum,\n type RelationAggregateFactory,\n type RelationFilterBase,\n relationFilterCtx,\n resolveExecutor,\n resolveTypeName,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\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 */\nconst classifyAggregateColumns = (table: Table, tableName: string): AggregateColumnSets => {\n const numeric: AggregateColumnSets['numeric'] = {};\n const orderable: AggregateColumnSets['orderable'] = {};\n const all: AggregateColumnSets['all'] = {};\n\n for (const [columnName, column] of Object.entries(getColumns(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 return { numeric, orderable, all };\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\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: `${typeName}${capitalize(op)}Aggregate`,\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: `${typeName}${capitalize(op)}Aggregate`,\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: `${typeName}${capitalize(op)}Aggregate`,\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: `${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 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 = (table: Table, tableName: string, typeName: string): AggregateTarget => {\n const { orderable } = classifyAggregateColumns(table, tableName);\n\n return {\n tableName,\n typeName,\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.typeName}Aggregate`,\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.typeName}${capitalize(op)}Aggregate`];\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 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): CreatedResolver => {\n const target = aggregateTarget(table, tableName, typeName);\n\n const queryArgs = {\n where: { type: filterArgs },\n };\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, 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 if (args.where) {\n query = query.where(extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName)));\n }\n const rows = await query;\n\n return assembleAggregateRow(rows[0] ?? {}, request, target);\n } catch (e) {\n throw toGraphQLError(e);\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): RelationAggregateFactory => {\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 return undefined;\n }\n const { localColPropName, foreignCol } = joinCols;\n\n const targetTypeName = resolveTypeName(targetTableName, typeNameMapper);\n const type = generateAggregateTypes(targetTable, targetTableName, targetTypeName, cacheCtx);\n const target = aggregateTarget(targetTable, targetTableName, targetTypeName);\n\n const resolve = async (parent: any, args: { where?: Filters<Table> }, context: any, info: any) => {\n try {\n const request = parseAggregateRequest(info, target);\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 // Siblings only share a batch when they'd run the same query: same filters, same aggregates.\n const argsKey = JSON.stringify({\n where: whereArg ?? null,\n selection: Object.keys(request.selection).sort(),\n });\n const loaderKey = `${tableName}::${relationName}::aggregate::${argsKey}`;\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 const whereCondition = and(\n inArray(foreignCol, uniqueIds),\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\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 toGraphQLError(e);\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(getColumns(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 = (table: Table, tableName: string, typeName: string): GraphQLEnumType | undefined => {\n const groupable = groupableColumns(table, tableName);\n\n return generateColumnEnum(\n table,\n `${typeName}GroupByColumn`,\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 rather than per table. */\nexport const aggregateNumberFilter = new GraphQLInputObjectType({\n name: 'AggregateNumberFilter',\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 * 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 = (table: Table, tableName: string, typeName: string): GraphQLInputObjectType => {\n const { numeric, orderable, all } = classifyAggregateColumns(table, tableName);\n\n const fields: Record<string, { type: any; description?: string }> = {\n count: { type: aggregateNumberFilter, 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: `${typeName}${capitalize(op)}Having`,\n fields: Object.fromEntries(columnNames.map((columnName) => [columnName, { type: aggregateNumberFilter }])),\n }),\n };\n }\n\n return new GraphQLInputObjectType({\n name: `${typeName}Having`,\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: `${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: `${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): CreatedResolver => {\n const target = aggregateTarget(table, tableName, typeName);\n const groupable = groupableColumns(table, tableName);\n const columns = getColumns(table);\n const rootTypeName = `${typeName}GroupBy`;\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 };\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { groupBy?: string[]; where?: Filters<Table>; having?: Record<string, any> },\n context,\n info,\n ) => {\n try {\n const requestedKeys = [...new Set(args.groupBy ?? [])];\n if (!requestedKeys.length) {\n throw new GraphQLError('At least one column to group by is required!');\n }\n\n const keyColumns = requestedKeys.map((columnName) => {\n const groupableColumn = groupable[columnName];\n if (!groupableColumn) {\n throw new GraphQLError(`Cannot group ${typeName} by ${columnName}!`);\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 if (args.where) {\n query = query.where(extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName)));\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 toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { and, getColumns, is, One, type Table, type View } from 'drizzle-orm';\nimport type { RelationalQueryBuilder } from 'drizzle-orm/mysql-core/query-builders/query';\nimport { getTableConfig, type PgAsyncDatabase, type PgColumn, PgTable } from 'drizzle-orm/pg-core';\nimport type { GraphQLFieldConfig, GraphQLFieldConfigArgumentMap, ThunkObjMap } from 'graphql';\nimport {\n GraphQLError,\n type GraphQLInputObjectType,\n GraphQLList,\n GraphQLNonNull,\n type GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n aggregateFieldComplexity,\n assertSingleMatch,\n attachRowCursors,\n attachTargetPrimaryKeys,\n buildCursorCondition,\n buildNamedRelations,\n type CursorOrderEntry,\n computeResolverFieldNames,\n createMutationTxCtx,\n createRelationResolverFactory,\n cursorOrderExprs,\n cursorOrderingEntries,\n decodeCursor,\n eagerLoadMutationRelations,\n excludedColumnRef,\n extractFilters,\n extractOrderBy,\n extractRelationJoinColumns,\n extractRequiredFilters,\n extractSelectedColumnsFromTreeSQLFormat,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n generateUpdateManyInput,\n getPrimaryKeyPropNamesFromConfig,\n getUniqueColumnSets,\n isCursorFieldSelected,\n listFieldComplexity,\n type MutationTxCtx,\n type OnConflictArg,\n orderByHasRelationEntry,\n prepareMutationRelationColumns,\n primaryKeyOrderExprs,\n primaryKeyRestriction,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n relationFilterCtx,\n resolveConflictPlan,\n resolveQueryExecutor,\n runMutation,\n runRelationalSelect,\n type SelectionCtx,\n selectArrayArgs,\n selectDistinctKeys,\n selectSingleArgs,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n} from '../builders/common.ts';\nimport {\n remapFromGraphQLArrayInput,\n remapFromGraphQLSingleInput,\n remapToGraphQLArrayOutput,\n remapToGraphQLSingleOutput,\n} from '../data-mappers/index.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} from './aggregates.ts';\nimport {\n buildNestedWritePlans,\n createNestedWriteRuntime,\n createNestedWriteTypes,\n mergedOps,\n type NestedWriteRuntime,\n updateWithNestedOps,\n writeWithNestedOps,\n} from './nested-writes.ts';\nimport type {\n CreatedResolver,\n Filters,\n SchemaGeneratorOptions,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst generateSelectArray = (\n db: PgAsyncDatabase<any, any, 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 = true,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n // Tables without relations won't have db.query support — fall back to basic select.\n\n const table = tables[tableName]!;\n const pkNames = pgPrimaryKeyPropNames(table as PgTable);\n const queryArgs = selectArrayArgs(\n orderArgs,\n filterArgs,\n distinctEnabled ? generateDistinctEnum(table, typeName) : undefined,\n );\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n\n if (requestQueryBase) {\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: false,\n filterCtx,\n pkNames,\n db: executor,\n // PostgreSQL sorts NULLs as the largest values (last in ASC).\n nullOrdering: 'nulls-largest',\n });\n }\n\n // Fallback for tables without relational query builder support.\n // Use SQL column objects (not Record<string,true>) so db.select() receives valid expressions.\n const { offset, limit, orderBy, where, distinct, after } = args;\n const selectedColumnsSql = extractSelectedColumnsFromTreeSQLFormat<PgColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n { tableName, relationMap, tables },\n );\n\n // Keyset pagination (see runRelationalSelect, which handles the RQB path).\n const cursorSelected = isCursorFieldSelected(parsedInfo.fieldsByTypeName[typeName], table);\n let cursorEntries: CursorOrderEntry[] | undefined;\n if (after != null || cursorSelected) {\n if (after != null && distinct?.length) {\n throw new GraphQLError(\"'after' cannot be combined with 'distinct'.\");\n }\n if (orderByHasRelationEntry(orderBy)) {\n if (after != null) {\n throw new GraphQLError(\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 );\n }\n // `cursor` selected under a relation ordering — resolves to null; ordering still applies.\n } else if (!pkNames.length) {\n if (after != null) {\n throw new GraphQLError(\n `Table ${tableName} has no primary key, so cursor pagination cannot be used on it.`,\n );\n }\n } else {\n cursorEntries = cursorOrderingEntries(orderBy, pkNames);\n if (cursorSelected) {\n // The whole ordering tuple is needed to compute each row's cursor.\n const allColumns = getColumns(table);\n for (const [column] of cursorEntries) {\n selectedColumnsSql[column] ??= allColumns[column] as PgColumn;\n }\n }\n }\n }\n const cursorCondition =\n after != null && cursorEntries\n ? buildCursorCondition(table, cursorEntries, decodeCursor(after, cursorEntries), 'nulls-largest')\n : undefined;\n\n const baseWhereSql = where\n ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined;\n const whereSql = cursorCondition ? and(baseWhereSql, cursorCondition) : baseWhereSql;\n\n // `distinct` picks the surviving rows in its own pass; the main query is then narrowed\n // to those primary keys and re-orders them the same way. See runRelationalSelect.\n let distinctKeys: Record<string, any>[] | undefined;\n if (distinct?.length) {\n distinctKeys = await selectDistinctKeys({\n db: executor,\n table,\n tableName,\n distinct,\n pkNames,\n where: whereSql,\n orderBy,\n limit,\n offset,\n });\n if (!distinctKeys.length) {\n return [];\n }\n }\n\n let q = executor.select(selectedColumnsSql).from(table);\n if (distinctKeys) {\n q = q.where(primaryKeyRestriction(table, pkNames, distinctKeys)) as any;\n } else if (whereSql) {\n q = q.where(whereSql) as any;\n }\n if (cursorEntries && !distinctKeys) {\n // Cursor pagination pages over a total order: orderBy plus the PK tiebreak.\n q = q.orderBy(...cursorOrderExprs(table, cursorEntries)) as any;\n } else if (orderBy) {\n q = q.orderBy(\n ...extractOrderBy(table, orderBy, relationFilterCtx(filterCtx, tableName)),\n ...(distinctKeys ? primaryKeyOrderExprs(table, pkNames) : []),\n ) as any;\n } else if ((distinctKeys || offset != null || limit != null) && pkNames.length) {\n // See runRelationalSelect: an unordered slice is not stable between requests.\n q = q.orderBy(...primaryKeyOrderExprs(table, pkNames)) as any;\n }\n if (!distinctKeys) {\n if (offset) {\n q = q.offset(offset) as any;\n }\n if (limit) {\n q = q.limit(limit) as any;\n }\n }\n const rows = await q;\n if (cursorEntries && cursorSelected) {\n attachRowCursors(rows, cursorEntries);\n }\n return remapToGraphQLArrayOutput(rows, tableName, table, relationMap);\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateSelectSingle = (\n db: PgAsyncDatabase<any, any, 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): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n // Tables without relations won't have db.query support — fall back to basic select.\n\n const queryArgs = selectSingleArgs(orderArgs, filterArgs);\n\n const table = tables[tableName]!;\n const pkNames = pgPrimaryKeyPropNames(table as PgTable);\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n\n if (requestQueryBase) {\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n pkNames,\n db: executor,\n });\n }\n\n // Fallback for tables without relational query builder support.\n const { offset, orderBy, where } = args;\n const selectedColumnsSql = extractSelectedColumnsFromTreeSQLFormat<PgColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n { tableName, relationMap, tables },\n );\n let q = executor.select(selectedColumnsSql).from(table);\n if (where) {\n q = q.where(extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))) as any;\n }\n if (orderBy) {\n q = q.orderBy(...extractOrderBy(table, orderBy, relationFilterCtx(filterCtx, tableName))) as any;\n } else if (pkNames.length) {\n // A single query is an implicit `limit 1` — order it so the row is deterministic.\n q = q.orderBy(...primaryKeyOrderExprs(table, pkNames)) as any;\n }\n if (offset) {\n q = q.offset(offset) as any;\n }\n const rows = await q.limit(1);\n const result = rows[0];\n return result ? remapToGraphQLSingleOutput(result, tableName, table, relationMap) : undefined;\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\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 generateInsertArray = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n conflictDoNothing: boolean = false,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n): CreatedResolver => {\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: 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 = pgPrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any>[] }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n if (!args.values.length) {\n throw new GraphQLError('No values were provided!');\n }\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 ? args.values.map((values) => nested.split(tableName, values))\n : undefined;\n const nestedEntries = entries?.some((entry) => nested!.hasOps(entry.ops)) ? entries : undefined;\n const input = nestedEntries\n ? []\n : remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : args.values, table);\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const returning = nestedEntries\n ? nested!.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table)\n : columns;\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 result = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) => remapFromGraphQLSingleInput(values, table),\n write: (tx, values) => runInsert(tx, [values]),\n })\n : await runInsert(executor, input);\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateInsertSingle = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n conflictDoNothing: boolean = false,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n): CreatedResolver => {\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: new GraphQLNonNull(baseType),\n },\n };\n\n // Derived once at build time — PK prop names don't change per request.\n const pkNames = pgPrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const entry = nested?.enabled(tableName) ? nested.split(tableName, args.values) : undefined;\n const nestedEntry = entry && nested!.hasOps(entry.ops) ? entry : undefined;\n const input = nestedEntry ? {} : remapFromGraphQLSingleInput(entry ? entry.columns : args.values, table);\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const returning = nestedEntry\n ? nested!.withJoinColumns(tableName, nestedEntry.ops, { ...columns }, table)\n : columns;\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 result = nestedEntry\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: [nestedEntry],\n remapValues: (values) => remapFromGraphQLSingleInput(values, table),\n write: runInsert,\n })\n : await runInsert(executor, input);\n\n if (!result[0]) {\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\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 */\nconst generateUpsert = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n onConflictType: GraphQLInputObjectType,\n uniqueSets: string[][],\n fieldName: string,\n typeName: string,\n single: boolean,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n): CreatedResolver => {\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 = pgPrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { values: Record<string, any> | Record<string, any>[]; onConflict?: OnConflictArg },\n context,\n info,\n ) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const supplied = single ? [args.values as Record<string, any>] : (args.values as Record<string, any>[]);\n if (!supplied.length) {\n throw new GraphQLError('No values were provided!');\n }\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 input = nestedEntries\n ? []\n : remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table);\n\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const returning = nestedEntries\n ? nested!.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table)\n : columns;\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 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: plan.setWhere }) as any);\n\n return (await query) as Record<string, any>[];\n };\n\n const result = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) => remapFromGraphQLSingleInput(values, table),\n write: (tx, values) => runUpsert(tx, [values]),\n })\n : await runUpsert(executor, input);\n\n if (single && !result[0]) {\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return single\n ? remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap)\n : remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateUpdate = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n setArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n single: boolean,\n requireWhere: boolean,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n): CreatedResolver => {\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 = pgPrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table>; set: Record<string, any> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { where, set } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\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 const input = remapFromGraphQLSingleInput(entry ? entry.columns : set, table);\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 new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n const returning = nestedOps ? nested!.withJoinColumns(tableName, nestedOps, { ...columns }, table) : columns;\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 result = 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 })\n : await runUpdate(executor, input);\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row!`);\n }\n\n if (single && !result[0]) {\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return single\n ? remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap)\n : remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\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. The result lists each entry's updated rows in entry order, with `null`\n * standing in for an entry whose `where` matched no rows, so the common one-row-per-entry\n * case stays aligned with the input.\n */\nconst generateUpdateMany = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n updateManyInput: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n): CreatedResolver => {\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 = pgPrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { updates: { where?: Filters<Table>; set: Record<string, any> }[] },\n context,\n info,\n ) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { updates } = args;\n if (!updates.length) {\n throw new GraphQLError('No updates were provided!');\n }\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\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 = 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 = remapFromGraphQLSingleInput(split ? split.columns : set, table);\n // An entry that only writes through a relation still has work to do.\n if (!Object.keys(input).length && !ops) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n ops,\n filters: where\n ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n };\n });\n\n const returning = entries.some((entry) => entry.ops)\n ? nested!.withJoinColumns(\n tableName,\n mergedOps(entries.map((entry) => ({ ops: entry.ops ?? {} }))),\n {\n ...columns,\n },\n table,\n )\n : columns;\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 const perEntry: Record<string, any>[][] = await 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)) }\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);\n }\n results.push(rows);\n }\n return results;\n });\n\n const flatRows = perEntry.flat();\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, flatRows, pkNames, withParams)\n : flatRows;\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 } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateDelete = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n single: boolean,\n requireWhere: boolean,\n filterCtx?: RelationFilterBase,\n selectionCtx?: SelectionCtx,\n txCtx?: MutationTxCtx,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { where } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const columns = extractSelectedColumnsFromTreeSQLFormat<PgColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n selectionCtx,\n );\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) as any;\n\n const result = await query;\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row!`);\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 } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\ntype SchemaEntry = Table<any> | View<string, boolean, any>;\n\nexport function generateSchemaData<\n TDrizzleInstance extends PgAsyncDatabase<any, any>,\n TRelations extends TablesRelationalConfig,\n TSchema extends Record<string, SchemaEntry>,\n>(\n db: TDrizzleInstance,\n schema: TSchema,\n relations: TRelations,\n options: SchemaGeneratorOptions,\n): GeneratedEntities<TDrizzleInstance, TSchema> {\n const {\n relationsDepthLimit,\n prefixes,\n suffixes,\n conflictDoNothing,\n typeNameMapper,\n shouldEagerLoad,\n features,\n complexity,\n } = options;\n const schemaEntries = Object.entries(schema);\n const tableEntries = schemaEntries.filter(([_key, value]) => is(value, PgTable)) as [string, PgTable][];\n const tables = Object.fromEntries(tableEntries) as Record<string, PgTable>;\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\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 // 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, pgPrimaryKeyPropNames);\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 const filterCtx: RelationFilterBase = { tables, relationMap: namedRelations };\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(db, tables, filterCtx);\n\n // Fresh cache per generateSchemaData call — prevents type name collisions\n // when buildSchema() is called multiple times.\n const cacheCtx: TypeCacheCtx = {\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 docs: options.docs ?? {},\n };\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) => getUniqueColumnSets(target as PgTable, getTableConfig),\n (target) => pgPrimaryKeyPropNames(target as PgTable),\n extractRelationJoinColumns,\n )\n : undefined;\n const nestedTypes = nestedPlans\n ? createNestedWriteTypes({ plans: nestedPlans, cacheCtx, typeNameMapper, insertPrefix: prefixes.insert })\n : undefined;\n const nestedRuntime = nestedPlans ? createNestedWriteRuntime({ plans: nestedPlans, filterCtx }) : undefined;\n\n // Left undefined when the feature is off — generateTableTypes then emits no\n // `${relation}Aggregate` fields at all.\n const relationAggregateFactory: RelationAggregateFactory | undefined = features.relationAggregates\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx)\n : undefined;\n\n const queries: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const mutations: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n\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 const mutationTxCtx = createMutationTxCtx(options.transactions);\n\n const gqlSchemaTypes = Object.fromEntries(\n Object.entries(tables).map(([tableName, _table]) => [\n tableName,\n generateTableTypes(\n tableName,\n tables,\n namedRelations,\n true,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n prefixes.insert,\n prefixes.update,\n resolverFactory,\n relationAggregateFactory,\n nestedTypes,\n ),\n ]),\n );\n\n const inputs: Record<string, GraphQLInputObjectType> = {};\n const outputs: Record<string, GraphQLObjectType> = {};\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n const { insertInput, updateInput, tableFilters, tableOrder } = tableTypes.inputs;\n const { selectSingleOutput, selectArrOutput, singleTableItemOutput, arrTableItemOutput } = tableTypes.outputs;\n\n // Compute field names using the mapper logic\n const {\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 deleteFieldName,\n deleteSingleFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\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 features.distinct,\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 );\n const insertArrGenerated = features.insert\n ? generateInsertArray(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n insertInput,\n createArrayFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n mutationTxCtx,\n nestedRuntime,\n )\n : undefined;\n const insertSingleGenerated = features.insert\n ? generateInsertSingle(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n insertInput,\n createSingleFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n mutationTxCtx,\n nestedRuntime,\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 = features.upsert ? getUniqueColumnSets(schema[tableName] as PgTable, getTableConfig) : [];\n const onConflictInput = features.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as PgTable,\n typeName,\n uniqueSets,\n tableFilters,\n withTarget: true,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n insertInput,\n onConflictInput,\n uniqueSets,\n upsertArrayFieldName,\n typeName,\n false,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n )\n : undefined;\n const upsertSingleGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n insertInput,\n onConflictInput,\n uniqueSets,\n upsertSingleFieldName,\n typeName,\n true,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n )\n : undefined;\n const updateGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateFieldName,\n typeName,\n false,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n )\n : undefined;\n const updateSingleGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n features.update && features.updateMany\n ? generateUpdateManyInput({ typeName, updatePrefix: prefixes.update, updateInput, tableFilters })\n : undefined;\n const updateManyGenerated = updateManyInput\n ? generateUpdateMany(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n updateManyInput,\n updateManyFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n )\n : undefined;\n const deleteGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n deleteFieldName,\n typeName,\n false,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n )\n : undefined;\n const deleteSingleGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n deleteSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n )\n : undefined;\n const aggregateType = features.aggregates\n ? generateAggregateTypes(schema[tableName] as PgTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = features.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as PgTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n features.aggregates && features.groupBy\n ? generateGroupByType(schema[tableName] as PgTable, tableName, typeName, cacheCtx)\n : undefined;\n const groupByEnum = groupByType\n ? generateGroupByEnum(schema[tableName] as PgTable, tableName, typeName)\n : undefined;\n const havingInput = groupByEnum\n ? generateHavingInput(schema[tableName] as PgTable, tableName, typeName)\n : undefined;\n const groupByGenerated =\n groupByType && groupByEnum && havingInput\n ? generateGroupBy(\n db,\n tableName,\n schema[tableName] as PgTable,\n typeName,\n groupByFieldName,\n tableFilters,\n groupByEnum,\n havingInput,\n filterCtx,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n ...(complexity ? { extensions: { complexity: listFieldComplexity(complexity) } } : {}),\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (insertArrGenerated) {\n mutations[insertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: insertArrGenerated.args,\n resolve: insertArrGenerated.resolver,\n };\n }\n if (insertSingleGenerated) {\n mutations[insertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: insertSingleGenerated.args,\n resolve: insertSingleGenerated.resolver,\n };\n }\n if (upsertArrGenerated) {\n mutations[upsertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: upsertArrGenerated.args,\n resolve: upsertArrGenerated.resolver,\n };\n }\n if (upsertSingleGenerated) {\n mutations[upsertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: upsertSingleGenerated.args,\n resolve: upsertSingleGenerated.resolver,\n };\n }\n if (updateGenerated) {\n mutations[updateGenerated.name] = {\n type: arrTableItemOutput,\n args: updateGenerated.args,\n resolve: updateGenerated.resolver,\n };\n }\n if (updateManyGenerated) {\n mutations[updateManyGenerated.name] = {\n // Nullable items: a no-match entry yields `null` in its slot.\n type: new GraphQLNonNull(new GraphQLList(singleTableItemOutput)),\n args: updateManyGenerated.args,\n resolve: updateManyGenerated.resolver,\n };\n }\n if (updateSingleGenerated) {\n mutations[updateSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: updateSingleGenerated.args,\n resolve: updateSingleGenerated.resolver,\n };\n }\n if (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.resolver,\n };\n }\n if (deleteSingleGenerated) {\n mutations[deleteSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: deleteSingleGenerated.args,\n resolve: deleteSingleGenerated.resolver,\n };\n }\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 ...(features.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(features.update ? [updateInput] : []),\n ...(updateManyInput ? [updateManyInput] : []),\n tableFilters,\n tableOrder,\n ];\n activeInputs.forEach((e) => {\n inputs[e.name] = e;\n });\n outputs[selectSingleOutput.name] = selectSingleOutput;\n outputs[singleTableItemOutput.name] = singleTableItemOutput;\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 // 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 (mutationTxCtx) {\n for (const name of Object.keys(mutations)) {\n mutationTxCtx.fieldNames.add(name);\n }\n }\n\n const fieldResolvers: Record<string, Record<string, any>> = {};\n for (const [tableName, tableRelations] of Object.entries(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 = 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 { queries, mutations, inputs, types: outputs, fieldResolvers } as any;\n}\n","// @ts-nocheck — drizzle-orm 1.0 type compat not guaranteed, same as its sibling builders\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, is, One, type Table } from 'drizzle-orm';\nimport {\n GraphQLBoolean,\n GraphQLError,\n GraphQLInputObjectType,\n type GraphQLInputType,\n GraphQLList,\n GraphQLNonNull,\n} from 'graphql';\nimport { capitalize } from '../case-ops/index.ts';\nimport { remapFromGraphQLSingleInput } from '../data-mappers/index.ts';\nimport { drizzleColumnToGraphQLType } from '../type-converter/index.ts';\nimport {\n extractFilters,\n type RelationFilterBase,\n relationFilterCtx,\n resolveTypeName,\n type TypeCacheCtx,\n type TypeNameMapper,\n} from './common.ts';\nimport type { TableNamedRelations } from './types.ts';\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};\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/**\n * Which relations of which tables can be written through.\n *\n * Skipped, and so absent from the generated inputs rather than failing at runtime:\n * `.through()` (many-to-many) relations, whose write target is a junction table this pass\n * does not model; relations whose join columns cannot be read off the drizzle relation;\n * and relations where neither join column is unique, which leaves no way to tell which\n * 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): 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 if ((relation as any).through) {\n continue;\n }\n\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n if (!targetTable) {\n continue;\n }\n\n const joinColumns = extractJoinColumns(relEntry, table, targetTable);\n if (!joinColumns) {\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\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 };\n }\n\n if (Object.keys(tablePlans).length) {\n plans[tableName] = tablePlans;\n }\n }\n\n return plans;\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 insertPrefix: string;\n}): NestedWriteTypes => {\n const { plans, cacheCtx, typeNameMapper, insertPrefix } = params;\n const wrapperCache = new Map<string, GraphQLInputObjectType>();\n const payloadCache = new Map<string, GraphQLInputObjectType>();\n\n /**\n * `Create<Type><Relation>Input` — the row a nested `create` inserts. Built from the target's\n * columns rather than from its create input: the join column this relation fills in is left\n * out (setting it by hand could point the new row somewhere other than its parent), and the\n * nesting stops here, so the type carries no relation fields of its own.\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 const fields = Object.fromEntries(\n Object.entries(getColumns(plan.targetTable))\n .filter(([columnName]) => columnName !== omitted)\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: `${capitalize(insertPrefix)}${typeName}${capitalize(plan.relationName)}Input`,\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 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 payload = payloadType(tableName, typeName, plan);\n const targetTypeName = resolveTypeName(plan.targetTableName, typeNameMapper);\n const fields: Record<string, { type: GraphQLInputType; description: string }> = {};\n\n if (plan.isOne) {\n fields['create'] = { type: payload, description: `Insert a ${targetTypeName} row and attach it` };\n if (filters) {\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 && plan.canDetach) {\n fields['disconnect'] = {\n type: GraphQLBoolean,\n description: `Detach the currently attached ${targetTypeName} row, leaving it in place`,\n };\n }\n } else {\n fields['create'] = { type: listOf(payload), description: `Insert these ${targetTypeName} rows and attach them` };\n if (filters) {\n fields['connect'] = {\n type: listOf(filters),\n description: `Attach every existing ${targetTypeName} row these match`,\n };\n if (forUpdate && plan.canDetach) {\n fields['disconnect'] = {\n type: listOf(filters),\n description: `Detach every attached ${targetTypeName} row these match, leaving the rows in place`,\n };\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\n // `create` alone is still a usable relation field, but a relation with nothing on it at\n // all cannot happen: `create` is unconditional.\n const type = new GraphQLInputObjectType({\n name: `${typeName}${capitalize(plan.relationName)}Nested${forUpdate ? 'Update' : 'Create'}Input`,\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 (plan.fkSide === 'parent' && !isOptionalOnInsert(plan.localCol)) {\n relaxed.add(plan.localColPropName);\n }\n }\n return relaxed.size ? relaxed : NO_COLUMNS;\n },\n };\n};\n\n// ── runtime ──────────────────────────────────────────────────────────────────\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: (executor: any, tableName: string, ops: NestedOps) => 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 ) => 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\nexport const createNestedWriteRuntime = (params: {\n plans: NestedWritePlans;\n filterCtx: RelationFilterBase | undefined;\n}): NestedWriteRuntime => {\n const { plans, filterCtx } = params;\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 = (plan: NestedRelationPlan, filter: Record<string, any>, operation: string) => {\n const condition = extractFilters(\n plan.targetTable,\n plan.targetTableName,\n filter,\n relationFilterCtx(filterCtx, plan.targetTableName),\n );\n if (!condition) {\n throw new GraphQLError(\n `Drizzle-GraphQL Error: '${operation}' on '${plan.relationName}' needs a filter that selects rows — it was given one that matches everything.`,\n );\n }\n return condition;\n };\n\n const assertSingleOperation = (plan: NestedRelationPlan, op: Record<string, any>) => {\n const supplied = ['create', 'connect', 'disconnect'].filter((key) => op[key] !== undefined && op[key] !== null);\n if (supplied.length > 1) {\n throw new GraphQLError(\n `Drizzle-GraphQL Error: '${plan.relationName}' takes one of ${supplied.join(', ')} at a time — it holds a single row.`,\n );\n }\n };\n\n const detachAll = async (executor: any, plan: NestedRelationPlan, key: any) =>\n executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: null })\n .where(eq(plan.foreignCol, key));\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) => {\n const tablePlans = plans[tableName];\n const patch: Record<string, any> = {};\n if (!tablePlans) {\n return patch;\n }\n\n for (const [relationName, op] of Object.entries(ops)) {\n const plan = tablePlans[relationName];\n if (!plan || plan.fkSide !== 'parent') {\n continue;\n }\n assertSingleOperation(plan, op);\n\n if (op['create'] !== undefined) {\n const values = remapFromGraphQLSingleInput({ ...op['create'] }, plan.targetTable);\n const inserted = await executor.insert(plan.targetTable).values(values).returning();\n const created = inserted[0];\n if (!created) {\n throw new GraphQLError(\n `Drizzle-GraphQL Error: 'create' on '${relationName}' inserted no row, so there is nothing to attach.`,\n );\n }\n patch[plan.localColPropName] = created[plan.foreignColPropName];\n } else if (op['connect'] !== undefined) {\n const rows = await executor\n .select()\n .from(plan.targetTable)\n .where(conditionOf(plan, op['connect'], 'connect'));\n if (rows.length !== 1) {\n throw new GraphQLError(\n `Drizzle-GraphQL Error: 'connect' on '${relationName}' matched ${rows.length} rows — it attaches a single row, so its filter must match exactly one.`,\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) => {\n const tablePlans = plans[tableName];\n if (!tablePlans) {\n return;\n }\n\n for (const [relationName, op] of Object.entries(ops)) {\n const plan = tablePlans[relationName];\n if (!plan || plan.fkSide !== 'child') {\n continue;\n }\n if (plan.isOne) {\n assertSingleOperation(plan, op);\n }\n\n for (const parentRow of parentRows) {\n const key = parentRow?.[plan.localColPropName];\n if (key === undefined || key === null) {\n throw new GraphQLError(\n `Drizzle-GraphQL Error: cannot write through '${relationName}': the ${tableName} row has no '${plan.localColPropName}' value to attach to.`,\n );\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);\n for (const filter of asArray(op['set'])) {\n await executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: key })\n .where(conditionOf(plan, filter, 'set'));\n }\n }\n\n if (op['disconnect'] !== undefined) {\n if (plan.isOne) {\n if (op['disconnect'] === true) {\n await detachAll(executor, plan, key);\n }\n } else {\n for (const filter of asArray(op['disconnect'])) {\n await executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: null })\n .where(and(eq(plan.foreignCol, key), conditionOf(plan, filter, 'disconnect')));\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 attaches = op['connect'] !== undefined || op['create'] !== undefined;\n if (plan.isOne && attaches && plan.canDetach && op['set'] === undefined) {\n await detachAll(executor, plan, key);\n }\n\n if (op['connect'] !== undefined) {\n for (const filter of asArray(op['connect'])) {\n await executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: key })\n .where(conditionOf(plan, filter, 'connect'));\n }\n }\n\n if (op['create'] !== undefined) {\n const rows = asArray(op['create']).map((row) => ({\n ...remapFromGraphQLSingleInput({ ...row }, plan.targetTable),\n [plan.foreignColPropName]: key,\n }));\n if (rows.length) {\n await executor.insert(plan.targetTable).values(rows);\n }\n }\n }\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 * 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}): Promise<Record<string, any>[]> => {\n const { executor, runtime, tableName, entries, remapValues, write } = 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);\n const written = await write(tx, { ...remapValues(entry.columns), ...patch });\n await runtime.applyChildSide(tx, tableName, entry.ops, written);\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}): Promise<Record<string, any>[]> => {\n const { executor, runtime, tableName, columns, ops, remapValues, write } = params;\n\n return executor.transaction(async (tx: any) => {\n const patch = await runtime.applyParentSide(tx, tableName, ops);\n const rows = await write(tx, { ...remapValues(columns), ...patch });\n await runtime.applyChildSide(tx, tableName, ops, rows);\n return rows;\n });\n};\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { is, One, type Table } from 'drizzle-orm';\nimport type { RelationalQueryBuilder } from 'drizzle-orm/mysql-core/query-builders/query';\nimport { type BaseSQLiteDatabase, getTableConfig, type SQLiteColumn, SQLiteTable } from 'drizzle-orm/sqlite-core';\nimport type { GraphQLFieldConfig, GraphQLFieldConfigArgumentMap, GraphQLResolveInfo, ThunkObjMap } from 'graphql';\nimport {\n GraphQLError,\n type GraphQLInputObjectType,\n GraphQLList,\n GraphQLNonNull,\n type GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\n\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n aggregateFieldComplexity,\n assertSingleMatch,\n attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createMutationTxCtx,\n createRelationResolverFactory,\n eagerLoadMutationRelations,\n excludedColumnRef,\n extractFilters,\n extractRelationJoinColumns,\n extractRequiredFilters,\n extractSelectedColumnsFromTreeSQLFormat,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n generateUpdateManyInput,\n getPrimaryKeyPropNamesFromConfig,\n getUniqueColumnSets,\n listFieldComplexity,\n type MutationTxCtx,\n type OnConflictArg,\n prepareMutationRelationColumns,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n relationFilterCtx,\n resolveConflictPlan,\n resolveQueryExecutor,\n runMutation,\n runRelationalSelect,\n type SelectionCtx,\n selectArrayArgs,\n selectSingleArgs,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n} from '../builders/common.ts';\nimport {\n remapFromGraphQLArrayInput,\n remapFromGraphQLSingleInput,\n remapToGraphQLArrayOutput,\n remapToGraphQLSingleOutput,\n} from '../data-mappers/index.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} from './aggregates.ts';\nimport {\n buildNestedWritePlans,\n createNestedWriteRuntime,\n createNestedWriteTypes,\n mergedOps,\n type NestedWriteRuntime,\n updateWithNestedOps,\n writeWithNestedOps,\n} from './nested-writes.ts';\nimport type {\n CreatedResolver,\n Filters,\n SchemaGeneratorOptions,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst generateSelectArray = (\n db: BaseSQLiteDatabase<any, any, any, 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 = true,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const table = tables[tableName]!;\n const pkNames = sqlitePrimaryKeyPropNames(table as SQLiteTable);\n const queryArgs = selectArrayArgs(\n orderArgs,\n filterArgs,\n distinctEnabled ? generateDistinctEnum(table, typeName) : undefined,\n );\n\n return {\n name: fieldName,\n resolver: async (_source: any, args: Partial<TableSelectArgs>, context: any, info: GraphQLResolveInfo) => {\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,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: false,\n filterCtx,\n pkNames,\n db: executor,\n // SQLite sorts NULLs as the smallest values (first in ASC).\n nullOrdering: 'nulls-smallest',\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateSelectSingle = (\n db: BaseSQLiteDatabase<any, any, any, 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): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const queryArgs = selectSingleArgs(orderArgs, filterArgs);\n\n const table = tables[tableName]!;\n const pkNames = sqlitePrimaryKeyPropNames(table as SQLiteTable);\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\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,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n pkNames,\n db: executor,\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\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\nconst generateInsertArray = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n conflictDoNothing: boolean = false,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n): CreatedResolver => {\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: 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 = sqlitePrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any>[] }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n if (!args.values.length) {\n throw new GraphQLError('No values were provided!');\n }\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 ? args.values.map((values) => nested.split(tableName, values))\n : undefined;\n const nestedEntries = entries?.some((entry) => nested!.hasOps(entry.ops)) ? entries : undefined;\n const input = nestedEntries\n ? []\n : remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : args.values, table);\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const returning = nestedEntries\n ? nested!.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table)\n : columns;\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 result = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) => remapFromGraphQLSingleInput(values, table),\n write: (tx, values) => runInsert(tx, [values]),\n })\n : await runInsert(executor, input);\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateInsertSingle = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n conflictDoNothing: boolean = false,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n): CreatedResolver => {\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: new GraphQLNonNull(baseType),\n },\n };\n\n // Derived once at build time — PK prop names don't change per request.\n const pkNames = sqlitePrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const entry = nested?.enabled(tableName) ? nested.split(tableName, args.values) : undefined;\n const nestedEntry = entry && nested!.hasOps(entry.ops) ? entry : undefined;\n const input = nestedEntry ? {} : remapFromGraphQLSingleInput(entry ? entry.columns : args.values, table);\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n const returning = nestedEntry\n ? nested!.withJoinColumns(tableName, nestedEntry.ops, { ...columns }, table)\n : columns;\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 result = nestedEntry\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: [nestedEntry],\n remapValues: (values) => remapFromGraphQLSingleInput(values, table),\n write: runInsert,\n })\n : await runInsert(executor, input);\n\n if (!result[0]) {\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\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 */\nconst generateUpsert = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n onConflictType: GraphQLInputObjectType,\n uniqueSets: string[][],\n fieldName: string,\n typeName: string,\n single: boolean,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n): CreatedResolver => {\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 = sqlitePrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { values: Record<string, any> | Record<string, any>[]; onConflict?: OnConflictArg },\n context,\n info,\n ) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const supplied = single ? [args.values as Record<string, any>] : (args.values as Record<string, any>[]);\n if (!supplied.length) {\n throw new GraphQLError('No values were provided!');\n }\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 input = nestedEntries\n ? []\n : remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table);\n\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const returning = nestedEntries\n ? nested!.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table)\n : columns;\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 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: plan.setWhere }) as any);\n\n return (await query) as Record<string, any>[];\n };\n\n const result = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) => remapFromGraphQLSingleInput(values, table),\n write: (tx, values) => runUpsert(tx, [values]),\n })\n : await runUpsert(executor, input);\n\n if (single && !result[0]) {\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return single\n ? remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap)\n : remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateUpdate = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n setArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n single: boolean,\n requireWhere: boolean,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n): CreatedResolver => {\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 = sqlitePrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table>; set: Record<string, any> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { where, set } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\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 const input = remapFromGraphQLSingleInput(entry ? entry.columns : set, table);\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 new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n const returning = nestedOps ? nested!.withJoinColumns(tableName, nestedOps, { ...columns }, table) : columns;\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 result = 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 })\n : await runUpdate(executor, input);\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row!`);\n }\n\n if (single && !result[0]) {\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return single\n ? remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap)\n : remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\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. The result lists each entry's updated rows in entry order, with `null`\n * standing in for an entry whose `where` matched no rows, so the common one-row-per-entry\n * case stays aligned with the input.\n */\nconst generateUpdateMany = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n updateManyInput: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n): CreatedResolver => {\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 = sqlitePrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { updates: { where?: Filters<Table>; set: Record<string, any> }[] },\n context,\n info,\n ) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { updates } = args;\n if (!updates.length) {\n throw new GraphQLError('No updates were provided!');\n }\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\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 = 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 = remapFromGraphQLSingleInput(split ? split.columns : set, table);\n // An entry that only writes through a relation still has work to do.\n if (!Object.keys(input).length && !ops) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n ops,\n filters: where\n ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n };\n });\n\n const anyNested = entries.some((entry) => entry.ops);\n const returning = anyNested\n ? nested!.withJoinColumns(\n tableName,\n mergedOps(entries.map((entry) => ({ ops: entry.ops ?? {} }))),\n { ...columns },\n table,\n )\n : columns;\n\n const runEntry = (tx: any, entry: (typeof entries)[number]) => {\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 (better-sqlite3)\n // executes it immediately, which is the only way the statement still runs\n // inside the synchronous native transaction below.\n return query.returning(returning).all();\n };\n\n // Nested writes need statements interleaved with awaited reads, which only an async\n // driver can do inside a transaction — `features.nestedWrites` rejects a sync driver\n // at build time, so this branch is always on one.\n const runNestedEntry = async (tx: any, entry: (typeof entries)[number]) => {\n const values = entry.ops\n ? { ...entry.set, ...(await nested!.applyParentSide(tx, tableName, entry.ops)) }\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);\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);\n }\n return rows;\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. A sync driver's transaction callback\n // must not be async — it would commit before any awaited statement ran — so the\n // driver kind is probed from the first statement's result instead.\n const perEntry: Record<string, any>[][] = await 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 const flatRows = perEntry.flat();\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, flatRows, pkNames, withParams)\n : flatRows;\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 } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateDelete = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n single: boolean,\n requireWhere: boolean,\n filterCtx?: RelationFilterBase,\n selectionCtx?: SelectionCtx,\n txCtx?: MutationTxCtx,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { where } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const columns = extractSelectedColumnsFromTreeSQLFormat<SQLiteColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n selectionCtx,\n );\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) as any;\n\n const result = await query;\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row!`);\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 } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nexport const generateSchemaData = <\n TDrizzleInstance extends BaseSQLiteDatabase<any, 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> => {\n const {\n relationsDepthLimit,\n prefixes,\n suffixes,\n conflictDoNothing,\n typeNameMapper,\n shouldEagerLoad,\n features,\n complexity,\n } = options;\n const rawSchema = schema;\n const schemaEntries = Object.entries(rawSchema);\n\n const tableEntries = schemaEntries.filter(([_key, value]) => is(value, SQLiteTable)) as [string, SQLiteTable][];\n const tables = Object.fromEntries(tableEntries) as Record<string, SQLiteTable>;\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\n // Build namedRelations from the drizzle-orm v1 relations config.\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Record each relation target's (composite-aware) primary key for deterministic\n // paginated ordering. Must run before pruning / type generation (shared entry objects).\n attachTargetPrimaryKeys(namedRelations, tables, sqlitePrimaryKeyPropNames);\n // Pruned map for query/mutation resolvers' `with:`; type generation keeps the full map.\n const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);\n\n const filterCtx: RelationFilterBase = { tables, relationMap: namedRelations };\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(db, tables, filterCtx);\n\n // Fresh cache per generateSchemaData call — prevents type name collisions\n // when buildSchema() is called multiple times.\n const cacheCtx: TypeCacheCtx = {\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 docs: options.docs ?? {},\n };\n\n // A nested write interleaves reads and writes inside one transaction, which a synchronous\n // driver cannot do — its transaction callback commits before an awaited statement runs.\n if (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\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) => getUniqueColumnSets(target as SQLiteTable, getTableConfig),\n (target) => sqlitePrimaryKeyPropNames(target as SQLiteTable),\n extractRelationJoinColumns,\n )\n : undefined;\n const nestedTypes = nestedPlans\n ? createNestedWriteTypes({ plans: nestedPlans, cacheCtx, typeNameMapper, insertPrefix: prefixes.insert })\n : undefined;\n const nestedRuntime = nestedPlans ? createNestedWriteRuntime({ plans: nestedPlans, filterCtx }) : undefined;\n\n // Left undefined when the feature is off — generateTableTypes then emits no\n // `${relation}Aggregate` fields at all.\n const relationAggregateFactory: RelationAggregateFactory | undefined = features.relationAggregates\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx)\n : undefined;\n\n const queries: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const mutations: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n\n // A synchronous driver (e.g. better-sqlite3) commits the moment its transaction callback\n // returns, so a transaction cannot be held open across resolver calls.\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 // 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 const mutationTxCtx = createMutationTxCtx(options.transactions);\n\n const gqlSchemaTypes = Object.fromEntries(\n Object.entries(tables).map(([tableName, _table]) => [\n tableName,\n generateTableTypes(\n tableName,\n tables,\n namedRelations,\n true,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n prefixes.insert,\n prefixes.update,\n resolverFactory,\n relationAggregateFactory,\n nestedTypes,\n ),\n ]),\n );\n\n const inputs: Record<string, GraphQLInputObjectType> = {};\n const outputs: Record<string, GraphQLObjectType> = {};\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n const { insertInput, updateInput, tableFilters, tableOrder } = tableTypes.inputs;\n const { selectSingleOutput, selectArrOutput, singleTableItemOutput, arrTableItemOutput } = tableTypes.outputs;\n\n // Compute field names using the mapper logic\n const {\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 deleteFieldName,\n deleteSingleFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\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 features.distinct,\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 );\n const insertArrGenerated = features.insert\n ? generateInsertArray(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n insertInput,\n createArrayFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n mutationTxCtx,\n nestedRuntime,\n )\n : undefined;\n const insertSingleGenerated = features.insert\n ? generateInsertSingle(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n insertInput,\n createSingleFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n mutationTxCtx,\n nestedRuntime,\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 = features.upsert ? getUniqueColumnSets(schema[tableName] as SQLiteTable, getTableConfig) : [];\n const onConflictInput = features.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as SQLiteTable,\n typeName,\n uniqueSets,\n tableFilters,\n withTarget: true,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n insertInput,\n onConflictInput,\n uniqueSets,\n upsertArrayFieldName,\n typeName,\n false,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n )\n : undefined;\n const upsertSingleGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n insertInput,\n onConflictInput,\n uniqueSets,\n upsertSingleFieldName,\n typeName,\n true,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n )\n : undefined;\n const updateGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateFieldName,\n typeName,\n false,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n )\n : undefined;\n const updateSingleGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n features.update && features.updateMany\n ? generateUpdateManyInput({ typeName, updatePrefix: prefixes.update, updateInput, tableFilters })\n : undefined;\n const updateManyGenerated = updateManyInput\n ? generateUpdateMany(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n updateManyInput,\n updateManyFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n )\n : undefined;\n const deleteGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n deleteFieldName,\n typeName,\n false,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n )\n : undefined;\n const deleteSingleGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n deleteSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n )\n : undefined;\n const aggregateType = features.aggregates\n ? generateAggregateTypes(schema[tableName] as SQLiteTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = features.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n features.aggregates && features.groupBy\n ? generateGroupByType(schema[tableName] as SQLiteTable, tableName, typeName, cacheCtx)\n : undefined;\n const groupByEnum = groupByType\n ? generateGroupByEnum(schema[tableName] as SQLiteTable, tableName, typeName)\n : undefined;\n const havingInput = groupByEnum\n ? generateHavingInput(schema[tableName] as SQLiteTable, tableName, typeName)\n : undefined;\n const groupByGenerated =\n groupByType && groupByEnum && havingInput\n ? generateGroupBy(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n typeName,\n groupByFieldName,\n tableFilters,\n groupByEnum,\n havingInput,\n filterCtx,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n ...(complexity ? { extensions: { complexity: listFieldComplexity(complexity) } } : {}),\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (insertArrGenerated) {\n mutations[insertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: insertArrGenerated.args,\n resolve: insertArrGenerated.resolver,\n };\n }\n if (insertSingleGenerated) {\n mutations[insertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: insertSingleGenerated.args,\n resolve: insertSingleGenerated.resolver,\n };\n }\n if (upsertArrGenerated) {\n mutations[upsertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: upsertArrGenerated.args,\n resolve: upsertArrGenerated.resolver,\n };\n }\n if (upsertSingleGenerated) {\n mutations[upsertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: upsertSingleGenerated.args,\n resolve: upsertSingleGenerated.resolver,\n };\n }\n if (updateGenerated) {\n mutations[updateGenerated.name] = {\n type: arrTableItemOutput,\n args: updateGenerated.args,\n resolve: updateGenerated.resolver,\n };\n }\n if (updateManyGenerated) {\n mutations[updateManyGenerated.name] = {\n // Nullable items: a no-match entry yields `null` in its slot.\n type: new GraphQLNonNull(new GraphQLList(singleTableItemOutput)),\n args: updateManyGenerated.args,\n resolve: updateManyGenerated.resolver,\n };\n }\n if (updateSingleGenerated) {\n mutations[updateSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: updateSingleGenerated.args,\n resolve: updateSingleGenerated.resolver,\n };\n }\n if (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.resolver,\n };\n }\n if (deleteSingleGenerated) {\n mutations[deleteSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: deleteSingleGenerated.args,\n resolve: deleteSingleGenerated.resolver,\n };\n }\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 ...(features.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(features.update ? [updateInput] : []),\n ...(updateManyInput ? [updateManyInput] : []),\n tableFilters,\n tableOrder,\n ];\n activeInputs.forEach((e) => {\n inputs[e.name] = e;\n });\n outputs[selectSingleOutput.name] = selectSingleOutput;\n outputs[singleTableItemOutput.name] = singleTableItemOutput;\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 // 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 (mutationTxCtx) {\n for (const name of Object.keys(mutations)) {\n mutationTxCtx.fieldNames.add(name);\n }\n }\n\n const fieldResolvers: Record<string, Record<string, any>> = {};\n for (const [tableName, tableRelations] of Object.entries(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 = 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 { queries, mutations, inputs, types: outputs, fieldResolvers } as any;\n};\n"],"mappings":";AAAA,SAAS,MAAAA,WAAU;AACnB,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC;AAAA,EAGE,qBAAAC;AAAA,EACA;AAAA,OAEK;;;ACQP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,6BAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA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,mBAAmB,KAAK,IAAI;AAAA,EACrE;AAEA,QAAM,EAAE,SAAS,WAAW,QAAQ,MAAM,IAAI;AAE9C,QAAM,sBAA2C;AAAA,IAC/C,OAAO,CAAC,GAAG,OAAO,OAAO,MAAM,GAAG,GAAG,OAAO,OAAO,KAAK,CAAC;AAAA,IACzD,OAAO,IAAIC,mBAAkB;AAAA,MAC3B,MAAM;AAAA,MACN,QAAQ;AAAA,IACV,CAAC;AAAA,EACH;AAIA,MAAI,QAAQ,cAAc,SAAS,OAAO,KAAK,SAAS,EAAE,QAAQ;AAChE,UAAM,WAAW,IAAIA,mBAAkB;AAAA,MACrC,MAAM;AAAA,MACN,QAAQ;AAAA,IACV,CAAC;AAED,wBAAoB,WAAW;AAAA,EACjC;AAEA,QAAM,eAAe,IAAI,cAAc,mBAAmB;AAE1D,SAAO,EAAE,QAAQ,cAAc,UAAU,gBAAgB;AAC3D;","names":["is","GraphQLObjectType","extractExtendedColumnType","is","One","GraphQLBoolean","GraphQLEnumType","GraphQLError","GraphQLFloat","GraphQLInputObjectType","GraphQLInt","GraphQLList","GraphQLNonNull","GraphQLObjectType","GraphQLString","getTableColumns","is","GraphQLError","GraphQLScalarType","GraphQLScalarType","is","GraphQLError","getTableColumns","GraphQLError","GraphQLNonNull","GraphQLEnumType","GraphQLInputObjectType","GraphQLInt","GraphQLList","GraphQLBoolean","GraphQLFloat","GraphQLString","extractExtendedColumnType","is","One","GraphQLObjectType","isJsonColumn","aliasedTable","getTableConfig","targetNames","set","result","is","One","GraphQLBoolean","GraphQLError","GraphQLList","GraphQLNonNull","GraphQLObjectType","parseResolveInfo","and","eq","extractExtendedColumnType","getColumns","gt","gte","inArray","lt","lte","ne","GraphQLError","GraphQLFloat","GraphQLInputObjectType","GraphQLInt","GraphQLList","GraphQLNonNull","GraphQLObjectType","getColumns","GraphQLList","GraphQLObjectType","extractExtendedColumnType","GraphQLNonNull","GraphQLInt","GraphQLFloat","and","inArray","eq","ne","gt","gte","lt","lte","GraphQLInputObjectType","GraphQLError","parseResolveInfo","GraphQLNonNull","GraphQLList","GraphQLError","is","GraphQLObjectType","GraphQLBoolean","One","and","getColumns","is","One","getTableConfig","GraphQLError","GraphQLList","GraphQLNonNull","parseResolveInfo","and","eq","getColumns","is","One","GraphQLBoolean","GraphQLError","GraphQLInputObjectType","GraphQLList","GraphQLNonNull","getColumns","is","One","GraphQLInputObjectType","GraphQLList","GraphQLNonNull","GraphQLBoolean","GraphQLError","eq","and","generateSelectArray","parseResolveInfo","GraphQLError","getColumns","and","generateSelectSingle","getTableConfig","generateInsertArray","GraphQLNonNull","GraphQLList","generateInsertSingle","generateUpsert","generateUpdate","generateUpdateMany","generateDelete","generateSchemaData","is","One","is","One","getTableConfig","GraphQLError","GraphQLList","GraphQLNonNull","parseResolveInfo","generateSelectArray","parseResolveInfo","generateSelectSingle","getTableConfig","generateInsertArray","GraphQLNonNull","GraphQLList","GraphQLError","generateInsertSingle","generateUpsert","generateUpdate","generateUpdateMany","results","generateDelete","generateSchemaData","is","One","config","is","generateSchemaData","GraphQLObjectType"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/util/builders/common.ts","../src/util/batch-loader/index.ts","../src/util/case-ops/index.ts","../src/util/data-mappers/index.ts","../src/util/type-converter/index.ts","../src/util/scalars/index.ts","../src/util/builders/field-updates.ts","../src/util/builders/mysql.ts","../src/util/builders/aggregates.ts","../src/util/builders/pg.ts","../src/util/builders/nested-writes.ts","../src/util/builders/sqlite.ts"],"sourcesContent":["import { is } from 'drizzle-orm';\nimport { MySqlDatabase } from 'drizzle-orm/mysql-core';\nimport { PgAsyncDatabase } from 'drizzle-orm/pg-core';\nimport { BaseSQLiteDatabase } 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, TableLimitPolicy } from './types.ts';\nimport {\n applyErrorMapper,\n defaultErrorMapper,\n type LimitPolicyFor,\n type ResolvedLimitPolicy,\n resolveLimitPolicy,\n} from './util/builders/common.ts';\nimport { generateMySQL, generatePG, generateSQLite } from './util/builders/index.ts';\nimport type { SchemaGeneratorOptions } from './util/builders/types.ts';\n\nexport type {\n AggregateResolver,\n AnyDrizzleDB,\n BuildSchemaConfig,\n ComplexityConfig,\n DeleteResolver,\n DeleteSingleResolver,\n ExtractRelations,\n ExtractTableByName,\n ExtractTableRelations,\n ExtractTables,\n GeneratedData,\n GeneratedEntities,\n GeneratedInputs,\n GeneratedOutputs,\n InsertArrResolver,\n InsertResolver,\n LimitsConfig,\n MutationReturnlessResult,\n MutationsCore,\n QueriesCore,\n SchemaFeatures,\n SelectResolver,\n SelectSingleResolver,\n TableLimitPolicy,\n UpdateManyArgs,\n UpdateManyEntry,\n UpdateManyResolver,\n UpdateResolver,\n UpdateSingleResolver,\n UpsertArgs,\n UpsertArrResolver,\n UpsertConflictArgs,\n UpsertResolver,\n} from './types.ts';\nexport type { RelationResolverFactory } from './util/builders/common.ts';\nexport {\n createRelationResolverFactory,\n defaultErrorMapper,\n drizzleExecutorKey,\n extractFilters,\n extractOrderBy,\n extractRelationJoinColumns,\n} from './util/builders/common.ts';\nexport type { TableNamedRelations } from './util/builders/types.ts';\nexport {\n GraphQLBigIntString,\n GraphQLDate,\n GraphQLDateTime,\n GraphQLDecimalString,\n GraphQLJSON,\n GraphQLUUID,\n} from './util/scalars/index.ts';\nexport type {\n ColumnDeprecator,\n ColumnDescriber,\n ColumnDocInfo,\n ColumnTypeMapper,\n ColumnTypeMapperInfo,\n EnumNameInfo,\n EnumNameMapper,\n RelationDescriber,\n ScalarOverride,\n ScalarOverridesConfig,\n SchemaDocs,\n TableDescriber,\n} from './util/type-converter/types.ts';\n\ntype ObjMap<T> = Record<string, T>;\n\nexport const buildSchema = <TDbClient extends AnyDrizzleDB<any>>(\n db: TDbClient,\n config?: BuildSchemaConfig,\n): GeneratedData<TDbClient> => {\n const relations = db._.relations;\n // drizzle-orm v1 rc.2 removed fullSchema from PgAsyncDatabase._\n // For PG, reconstruct a schema-like map from db._.relations (each entry has { table }).\n // MySQL and SQLite still expose fullSchema directly.\n const schema =\n (db._ as any).fullSchema ??\n 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 (!schema || !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 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 };\n\n const suffixes = {\n list: config?.suffixes?.list ?? '',\n single: config?.suffixes?.single ?? 'Single',\n };\n\n const typeNameMapper = config?.typeNameMapper;\n\n // Every feature is on unless the caller says otherwise, so a build without a `features`\n // block generates what it always did — except upsert, which is new surface and so has to\n // be asked for.\n const features = {\n aggregates: config?.features?.aggregates ?? true,\n groupBy: config?.features?.groupBy ?? true,\n relationAggregates: config?.features?.relationAggregates ?? true,\n distinct: config?.features?.distinct ?? true,\n insert: config?.features?.insert ?? true,\n update: config?.features?.update ?? true,\n updateMany: config?.features?.updateMany ?? true,\n delete: config?.features?.delete ?? true,\n upsert: config?.features?.upsert ?? false,\n nestedWrites: config?.features?.nestedWrites ?? false,\n fieldUpdateOperations: config?.features?.fieldUpdateOperations ?? false,\n countMutations: config?.features?.countMutations ?? false,\n requireWhere: config?.features?.requireWhere ?? false,\n };\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 : { timeoutMs: (transactionsOpt === 'auto' ? undefined : transactionsOpt.timeoutMs) ?? 30_000 };\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 // 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 shouldEagerLoad,\n features,\n complexity,\n scalars: config?.scalars,\n mapColumnType: config?.mapColumnType,\n enumNameMapper: config?.enumNameMapper,\n transactions,\n limits,\n docs: {\n describeColumn: config?.describeColumn,\n describeTable: config?.describeTable,\n describeRelation: config?.describeRelation,\n deprecateColumn: config?.deprecateColumn,\n },\n };\n\n let generatorOutput;\n if (is(db, MySqlDatabase)) {\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, BaseSQLiteDatabase)) {\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 return { schema: outputSchema, entities: generatorOutput };\n};\n","// =============================================================================\n// LOCAL MODIFICATION — diverges from upstream drizzle-graphql\n//\n// 1. generateColumnFilterValues() rewritten to produce generic shared filter\n// types (IdFilter, StringFilter, IntFilter, FloatFilter, BigIntFilter,\n// DecimalFilter, DateTimeFilter, BooleanFilter, per-enum, per-array) instead\n// of one type per (table, column) pair. The filter is picked by column data\n// type, not name.\n//\n// 2. Type naming:\n// - Select types: ${capitalize(tableName)} (e.g. Users)\n// - Relation fields: reference the target table's type directly (e.g. posts: [Posts!]!)\n// - Mutation return: same type as select (${capitalize(tableName)})\n// - Insert input: ${capitalize(insertPrefix)}${toTypeName(tableName)}Input (e.g. CreateUsersInput)\n// - Update input: ${capitalize(updatePrefix)}${toTypeName(tableName)}Input (e.g. UpdateUsersInput)\n// =============================================================================\n// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport type { Column, Relation, Table } from 'drizzle-orm';\nimport {\n aliasedTable,\n and,\n arrayContains,\n arrayOverlaps,\n asc,\n desc,\n eq,\n extractExtendedColumnType,\n getColumns,\n getTableAsAliasSQL,\n gt,\n gte,\n ilike,\n inArray,\n is,\n isNotNull,\n isNull,\n like,\n lt,\n lte,\n ne,\n not,\n notIlike,\n notInArray,\n notLike,\n One,\n or,\n relationsFilterToSQL,\n type SQL,\n sql,\n} from 'drizzle-orm';\nimport type { GraphQLFieldConfigArgumentMap, GraphQLFieldResolver } from 'graphql';\nimport {\n GraphQLBoolean,\n GraphQLEnumType,\n GraphQLError,\n GraphQLFloat,\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n type GraphQLScalarType,\n GraphQLString,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { getOrCreateLoader } from '../batch-loader/index.ts';\nimport { capitalize, uncapitalize } from '../case-ops/index.ts';\nimport { remapFromGraphQLCore, remapToGraphQLArrayOutput, remapToGraphQLSingleOutput } from '../data-mappers/index.ts';\nimport {\n GraphQLBigIntString,\n GraphQLDate,\n GraphQLDateTime,\n GraphQLDecimalString,\n GraphQLJSON,\n GraphQLUUID,\n} from '../scalars/index.ts';\nimport { drizzleColumnToGraphQLType, getColumnScalarOverride } from '../type-converter/index.ts';\nimport type {\n ConvertedColumn,\n ConvertedInputColumn,\n ConvertedRelationColumnWithArgs,\n SchemaDocs,\n} from '../type-converter/types.ts';\nimport { fieldUpdateInputType, 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, NestedWriteTypes } from './nested-writes.ts';\nimport type {\n CreatedResolver,\n FilterColumnOperators,\n FilterColumnOperatorsCore,\n Filters,\n FiltersCore,\n GeneratedTableTypes,\n GeneratedTableTypesOutputs,\n GeneratorFeatures,\n OrderByArgs,\n ProcessedTableSelectArgs,\n SelectData,\n SelectedColumnsRaw,\n SelectedSQLColumns,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst rqbCrashTypes = ['SQLiteBigInt', 'SQLiteBlobJson', 'SQLiteBlobBuffer'];\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 * 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 * 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 sourceColumns: any[] | undefined = rel.sourceColumns;\n const targetColumns: any[] | undefined = rel.targetColumns;\n\n if (!sourceColumns?.length || !targetColumns?.length) {\n return undefined;\n }\n\n const sourceCol = sourceColumns[0];\n const targetCol = targetColumns[0];\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 * 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\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\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 new GraphQLError(\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 );\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 new GraphQLError(\n `Drizzle-GraphQL Error: Shared mutation transaction timed out after ${txCtx.timeoutMs}ms waiting for the remaining mutation fields; rolling back.`,\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): 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 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 return body(resolveExecutor(db, context));\n }\n return runOnSharedTx(state, body);\n};\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 orderCtx?: RelationFilterContext,\n): Promise<any[]> => {\n const cols = 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) : []),\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 ): 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 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\n return async (parent, args, context, info) => {\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, orderBy: orderByArg, limit: requestedLimit, offset, after } = (args ?? {}) as any;\n const limit = applyLimitPolicy(requestedLimit, limitPolicy, `${tableName}.${relationName}`);\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 new GraphQLError(\"'after' cannot be combined with 'distinct'.\");\n }\n if (orderByHasRelationEntry(orderByArg)) {\n if (after != null) {\n throw new GraphQLError(\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 );\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 new GraphQLError(\n `Table ${targetTableName} has no primary key, so cursor pagination cannot be used on it.`,\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 // 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 const argsKey = JSON.stringify({\n where: whereArg ?? null,\n orderBy: orderByArg ?? null,\n limit: limit ?? null,\n offset: offset ?? null,\n after: after ?? null,\n distinct: distinct ?? null,\n cursor: cursorEntries ? 1 : 0,\n });\n const loaderKey = `${tableName}::${relationName}::${argsKey}`;\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 let whereCondition = 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\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 relationFilterCtx(filterCtx, targetTableName),\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 = executor.select().from(targetTable).where(whereCondition) as any;\n const orderExprs = cursorEntries\n ? cursorOrderExprs(targetTable, cursorEntries)\n : orderByArg\n ? extractOrderBy(targetTable, orderByArg, relationFilterCtx(filterCtx, targetTableName))\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\n/** Per-call cache context — created fresh on each generateSchemaData call to avoid type name collisions. */\nexport interface TypeCacheCtx {\n /** Cache of generic filter types, keyed by generic name (e.g. \"String\", \"DateTime\"). */\n genericFilterCache: Map<string, GraphQLInputObjectType>;\n /**\n * Cache of shared select object types, keyed by table name.\n * Value: the ${capitalize(tableName)} type (columns + relation fields).\n * A table may be pre-registered here as a columns-only shell before its root call runs.\n * Use fullyBuiltTables to distinguish a complete type from a pre-registered shell.\n */\n objectTypeCache: Map<string, GraphQLObjectType>;\n /**\n * Mutable containers for relation fields, keyed by table name.\n * Each container object is closed over by the corresponding GraphQLObjectType thunk so that\n * when the root call for a table populates its relation fields, the thunk automatically picks\n * them up — even if the shell was pre-registered by a different table's relation traversal.\n */\n relationFieldContainers: Map<string, { fields: Record<string, ConvertedRelationColumnWithArgs> }>;\n /**\n * Set of table names whose GraphQL object type has been fully built (root call completed).\n * Pre-registered shells (created when another table references this table as a relation target)\n * are NOT in this set until the root call for that table runs.\n */\n fullyBuiltTables: Set<string>;\n /**\n * Cache of relation types, keyed by \"${fromTableName}::${relName}\".\n * @deprecated No longer used — relation fields now reference the target table's own type directly.\n */\n relationTypeCache: Map<string, GraphQLObjectType>;\n /**\n * Per-call cache for a table's converted select-field map, keyed by table reference.\n * Per-call (not module-level) because scalar overrides can differ between builds that\n * share the same table objects.\n */\n selectFieldCache: WeakMap<object, Record<string, ConvertedColumn>>;\n /** Per-call cache for a table's column-filter field map, keyed by table reference. */\n filterFieldCache: WeakMap<object, Record<string, ConvertedInputColumn>>;\n /** Per-call cache for order GraphQL input types, keyed by table reference. */\n orderTypeCache: WeakMap<object, GraphQLInputObjectType>;\n /** Per-call cache for filter GraphQL input types, keyed by table reference. */\n filterTypeCache: WeakMap<object, GraphQLInputObjectType>;\n /**\n * Per-call cache for `${Target}ListRelationFilter` input types (the some/every/none wrapper\n * used by to-many relation filters), keyed by target table name.\n */\n listRelationFilterCache: Map<string, GraphQLInputObjectType>;\n /**\n * Per-call cache for `${Table}Aggregate` output types, keyed by table name. Shared between the\n * root `<table>Aggregate` query and the `<relation>Aggregate` field on every table that points\n * at it, so the schema never holds two types with the same name.\n */\n aggregateTypeCache: Map<string, GraphQLObjectType>;\n /**\n * Resolved complexity settings for this call, or `undefined` when the caller turned the hints\n * off. Not a cache, but the type builders are several calls deep and this context is already\n * threaded through all of them.\n */\n complexity: ResolvedComplexityOptions | undefined;\n /**\n * The build's documentation hooks (`describeColumn`, `describeTable`, `describeRelation`,\n * `deprecateColumn`). Empty when the caller configured none, which is the default — the\n * generator emits no descriptions of its own for column and relation fields.\n */\n docs: SchemaDocs;\n /**\n * The build's resolved limit policy, or `undefined` when the caller configured none. Read\n * here so a to-many relation field can price its cost hint against the policy of the table\n * it targets, the same one its resolver enforces.\n */\n limits: LimitPolicyFor | undefined;\n /**\n * The build's resolved feature flags. Like `complexity` and `docs`, not a cache — the type\n * builders are several calls deep and this context is already threaded through them.\n */\n features: GeneratorFeatures;\n}\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 */\nconst 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\n/** The shape `graphql-query-complexity`'s `fieldExtensionsEstimator` hands to a field's hint. */\nexport type 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 * 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 fieldName: string,\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 new GraphQLError(`${fieldName}: 'limit' of ${limit} exceeds the maximum of ${maxLimit}.`);\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\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\nexport const extractSelectedColumnsFromTree = (\n tree: Record<string, ResolveTree>,\n table: Table,\n selectionCtx?: SelectionCtx,\n): Record<string, true> => {\n const tableColumns = getColumns(table);\n\n const treeEntries = Object.entries(tree);\n const selectedColumns: SelectedColumnsRaw = [];\n\n for (const [_fieldName, fieldData] of treeEntries) {\n if (!tableColumns[fieldData.name]) {\n continue;\n }\n\n selectedColumns.push([fieldData.name, true]);\n }\n\n for (const columnName of relationJoinColumns(tree, table, selectionCtx)) {\n selectedColumns.push([columnName, true]);\n }\n\n if (!selectedColumns.length) {\n const columnKeys = Object.entries(tableColumns);\n const columnName =\n columnKeys.find((e) => rqbCrashTypes.find((haram) => e[1].columnType !== haram))?.[0] ?? columnKeys[0]![0];\n\n selectedColumns.push([columnName, true]);\n }\n\n return Object.fromEntries(selectedColumns);\n};\n\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\n const treeEntries = Object.entries(tree);\n const selectedColumns: SelectedSQLColumns = [];\n\n for (const [_fieldName, fieldData] of treeEntries) {\n if (!tableColumns[fieldData.name]) {\n continue;\n }\n\n selectedColumns.push([fieldData.name, tableColumns[fieldData.name]!]);\n }\n\n for (const columnName of relationJoinColumns(tree, table, selectionCtx)) {\n selectedColumns.push([columnName, tableColumns[columnName]!]);\n }\n\n if (!selectedColumns.length) {\n const columnKeys = Object.entries(tableColumns);\n const columnName =\n columnKeys.find((e) => rqbCrashTypes.find((haram) => e[1].columnType !== haram))?.[0] ?? columnKeys[0]![0];\n\n selectedColumns.push([columnName, tableColumns[columnName]!]);\n }\n\n return Object.fromEntries(selectedColumns) as Record<string, TColType>;\n};\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 orderNulls = new GraphQLEnumType({\n name: 'OrderNulls',\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\nexport const innerOrder = new GraphQLInputObjectType({\n name: 'InnerOrder' as const,\n fields: {\n direction: {\n type: new GraphQLNonNull(\n new GraphQLEnumType({\n name: 'OrderDirection',\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 },\n priority: {\n type: new GraphQLNonNull(GraphQLInt),\n description: 'Priority of current field',\n },\n nulls: {\n type: orderNulls,\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 } as const,\n});\n\n/** The dialect a column belongs to, inferred from its drizzle columnType string (e.g. 'PgJsonb'). */\nconst 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/** 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\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\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)\n * - \"DateTime\" → timestamp and date columns\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' };\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 // Date / timestamp columns (check Drizzle internal columnType string)\n const ct: string = (column as any).columnType ?? '';\n if (ct === 'PgTimestamp' || ct === 'PgTimestampString' || ct === 'PgDate') {\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: ReturnType<typeof drizzleColumnToGraphQLType>['type']) => {\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 isNull: { type: GraphQLBoolean },\n isNotNull: { type: GraphQLBoolean },\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/…): they are nonsensical on opaque uuids and invalid SQL on numeric\n * columns. Keyed on the generic filter name (i.e. on column type) — a string-typed column\n * keeps the string operators whatever it is called.\n */\nconst FILTERS_WITHOUT_STRING_OPS = new Set(['Id', 'Int', 'Float', 'BigInt', 'Decimal']);\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\nconst 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 { name: genericName, kind } = inputOverride\n ? resolveOverrideFilterDescriptor(inputOverride)\n : resolveGenericFilterDescriptor(column, columnGraphQLType);\n const cached = cacheCtx.genericFilterCache.get(genericName);\n if (cached) {\n return cached;\n }\n\n const colType = columnGraphQLType.type;\n const colArr = new GraphQLList(new GraphQLNonNull(colType));\n\n // Uuid and numeric filters omit the string pattern operators\n // (like/ilike/startsWith/contains/…) — decided by column type, never by column name.\n // A filter shared with the built-ins keeps that name-keyed rule even for an overridden\n // column, so the shared type's shape never depends on which column built it first. A\n // custom override scalar's own filter carries the pattern operators only when a pattern\n // match is valid SQL on the underlying database column: string-typed, and not\n // numeric/decimal (those transport as strings but reject LIKE).\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 : FILTERS_WITHOUT_STRING_OPS.has(genericName);\n\n const baseFields =\n kind === 'json'\n ? jsonFilterFields(column, colType)\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 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 ...(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 }),\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: `${genericName}Filter`,\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\nconst orderMap = new WeakMap<object, Record<string, ConvertedInputColumn>>();\nconst generateTableOrderCached = (table: Table) => {\n if (orderMap.has(table)) {\n return orderMap.get(table)!;\n }\n\n let remapped = {};\n try {\n const columns = getColumns(table);\n const columnEntries = Object.entries(columns);\n\n remapped = Object.fromEntries(\n columnEntries.map(([columnName, _columnDescription]) => [columnName, { type: innerOrder }]),\n );\n\n orderMap.set(table, remapped);\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 = getColumns(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\nconst 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 = getColumns(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 * 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 */\nconst isFilterableRelation = (relation: Relation<string>): boolean => !(relation as any).through;\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\nconst 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: `${resolveTypeName(tableName, typeNameMapper)}OrderBy`,\n fields: () => {\n const orderColumns = generateTableOrderCached(table);\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: `${resolveTypeName(targetTableName, typeNameMapper)}ListRelationFilter`,\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\nconst 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 return {\n ...filterColumns,\n ...generateRelationFilterFields(tableName, cacheCtx, typeNameMapper, filterColumns, relationMap, tables),\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: `${resolveTypeName(tableName, typeNameMapper)}Filters`,\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\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 = resolveTypeName(tableName, typeNameMapper);\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 });\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: resolveTypeName(targetTableName, typeNameMapper),\n description: cacheCtx.docs.describeTable?.(targetTableName),\n fields: () => ({ ...targetTableFields, ...capturedTargetContainer.fields }),\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 },\n resolve,\n ...relationDocs,\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 extractRelationsParamsInner.\n const targetDistinctEnum = cacheCtx.features.distinct\n ? generateDistinctEnum(tables[targetTableName]!, resolveTypeName(targetTableName, typeNameMapper))\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 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 ...(cacheCtx.complexity\n ? {\n extensions: {\n complexity: listFieldComplexity(cacheCtx.complexity, cacheCtx.limits?.(targetTableName)),\n },\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 },\n resolve: relationAggregate.resolve,\n ...(cacheCtx.complexity\n ? { extensions: { 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 = getColumns(table);\n const columnEntries = Object.entries(columns);\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 columnEntries.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 columnEntries.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.features.fieldUpdateOperations\n ? fieldUpdateInputType(column, columnName, tableName)\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: `${capitalize(insertPrefix)}${typeName}Input`,\n fields: nestedWrites\n ? () => ({ ...insertFields, ...nestedWrites.createFields(tableName, typeName) })\n : insertFields,\n });\n\n const updateInput = new GraphQLInputObjectType({\n name: `${capitalize(updatePrefix)}${typeName}Input`,\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: resolveTypeName(tableName, typeNameMapper),\n description: cacheCtx.docs.describeTable?.(tableName),\n fields: { ...tableFields, ...relationFields },\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\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 .sort((a, b) => (b[1]?.priority ?? 0) - (a[1]?.priority ?? 0))\n .filter(([, config]) => config)\n .map(([column, config]) => {\n if (typeof config === 'object' && config.direction === undefined) {\n throw new GraphQLError(`ORDER BY ${column}: ordering through a relation is not supported in this query`);\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 new GraphQLError(`ORDER BY ${relationName}: Relation cannot be used for ordering`);\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 relationWhere = (relation as any).where\n ? relationsFilterToSQL((relation as any).isReversed ? parentTable : aliasedTarget, (relation as any).where)\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 * 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): 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 out.push({\n expression: 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 new GraphQLError(`ORDER BY ${key}: Unknown column or relation`);\n }\n\n const nextChain = extendRelationOrderChain(chain?.table ?? table, key, relEntry, ctx, chain);\n collectOrderEntries(nextChain.table, relEntry.targetTableName, config, ctx, nextChain, out);\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 * `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): SQL[] => {\n const entries: FlatOrderEntry[] = [];\n collectOrderEntries(table, ctx?.tableKey ?? '', orderArgs, ctx, undefined, entries);\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\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 * Whether the column stores JSON — its `contains` operator is structural containment,\n * not the safe substring operator string columns get.\n */\nconst isJsonColumn = (column: Column): boolean => (((column as any).columnType ?? '') as string).includes('Json');\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 new GraphQLError(`WHERE ${columnName}: Operator 'contains' is not supported for this dialect!`);\n }\n};\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, ...restOperators } = operators;\n\n const entries = Object.entries(restOperators as FilterColumnOperatorsCore<TColumn>);\n\n const singleValueOps: Record<string, (...args: any[]) => SQL> = { eq, ne, gt, gte, lt, lte };\n const stringValueOps: Record<string, (...args: any[]) => SQL> = { like, notLike, ilike, notIlike };\n const arrayValueOps: Record<string, (...args: any[]) => SQL> = { inArray, notInArray };\n // Membership operators for array columns: element list → SQL. Empty lists are rejected below.\n const arrayMembershipOps: Record<string, (...args: any[]) => SQL> = {\n hasSome: arrayOverlaps,\n hasEvery: arrayContains,\n };\n const nullableOps: Record<string, (...args: any[]) => SQL> = { isNull, isNotNull };\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(singleValueOps[operatorName]!(column, singleValue));\n } else if (operatorName in stringValueOps) {\n variants.push(stringValueOps[operatorName]!(column, operatorValue as string));\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 } = safeLikeOps[operatorName]!;\n variants.push(safeLikeCondition(column, buildPattern(operatorValue as string), insensitive));\n } else if (operatorName in arrayValueOps) {\n if (!(operatorValue as any[]).length) {\n throw new GraphQLError(`WHERE ${columnName}: Unable to use operator ${operatorName} with an empty array!`);\n }\n const arrayValue = (operatorValue as any[]).map((val) => remapFromGraphQLCore(val, column, columnName));\n variants.push(arrayValueOps[operatorName]!(column, arrayValue));\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 if (!(operatorValue as any[]).length) {\n throw new GraphQLError(`WHERE ${columnName}: Unable to use operator ${operatorName} with an empty array!`);\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 new GraphQLError(`WHERE ${columnName}: Unknown operator: ${operatorName}`);\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 if (extracted) {\n variants.push(not(extracted));\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\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\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'>;\n\n/** Narrows the build-scoped relation filter context to the table a resolver is filtering. */\nexport const relationFilterCtx = (\n base: RelationFilterBase | undefined,\n tableKey: string,\n): RelationFilterContext | undefined => (base ? { ...base, tableKey } : undefined);\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 */\nconst buildRelationJoinCondition = (\n parentTable: Table,\n relation: Relation<string>,\n aliasedTarget: Table,\n relationName: string,\n): SQL | undefined => {\n const sourceColumns = (relation as any).sourceColumns as Column[] | undefined;\n const targetColumns = (relation as any).targetColumns as Column[] | undefined;\n\n if (!sourceColumns?.length || sourceColumns.length !== targetColumns?.length) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\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 new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\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 = junctionRef?._?.column?.name;\n const byName = columnName ? Object.values(throughColumns).find((c) => c.name === columnName) : undefined;\n if (!byName) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\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 = (relation as any).sourceColumns as Column[] | undefined;\n const targetColumns = (relation as any).targetColumns as Column[] | undefined;\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 new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\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 new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\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 new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\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 new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\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 relationWhere = (relation as any).where\n ? relationsFilterToSQL((relation as any).isReversed ? parentTable : aliasedTarget, (relation as any).where)\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 new GraphQLError(`WHERE ${relationName}: Unknown relation filter key: ${mode}`);\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 const entries = Object.entries(fieldFilters as FiltersCore<TTable>);\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\n // A key that is neither a column nor a filterable relation must throw rather than be\n // dropped: when the generated schema is stitched/merged with another schema, same-named\n // inputs can contribute foreign keys that pass input validation, and a where that loses\n // all of its keys silently becomes an unbounded select/update/delete.\n if (!column && !(relations?.[fieldName] && relationCtx)) {\n throw new GraphQLError(`WHERE ${tableName}: Unknown filter key: ${fieldName}`);\n }\n\n const extracted = column\n ? extractFiltersColumn(column, fieldName, operators)\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 if (extracted) {\n variants.push(not(extracted));\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\nconst extractRelationsParamsInner = (\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n tables: Record<string, Table>,\n tableName: string,\n typeName: string,\n originField: ResolveTree,\n typeNameMapper?: TypeNameMapper,\n _isInitial: boolean = false,\n filterCtx?: RelationFilterBase,\n limits?: LimitPolicyFor,\n) => {\n const relationsForTable = relationMap[tableName];\n if (!relationsForTable) {\n return undefined;\n }\n\n const baseField = Object.entries(originField.fieldsByTypeName).find(([key, _value]) => key === typeName)?.[1];\n if (!baseField) {\n return undefined;\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 = resolveTypeName(targetTableName, typeNameMapper);\n // Look up by field name OR by alias (when the caller uses an alias for the relation).\n // graphql-parse-resolve-info keys fieldsByTypeName entries by alias.\n const field = baseField[relName] ?? Object.values(baseField).find((f) => (f as ResolveTree).name === relName);\n if (!field) {\n continue;\n }\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 const selectionCount = Object.values(baseField).reduce(\n (n, f) => n + ((f as ResolveTree).name === relName ? 1 : 0),\n 0,\n );\n if (selectionCount > 1) {\n continue;\n }\n const relField = (field as ResolveTree)?.fieldsByTypeName;\n const relFieldSelection = relField?.[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 as ResolveTree).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 const relationField = Object.values(baseField).find((e) => e.name === relName);\n const relationArgs: Partial<TableSelectArgs> | undefined = relationField?.args;\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), `${tableName}.${relName}`);\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 thisRecord.where = relWhere\n ? {\n RAW: (aliasedTable: Table) =>\n extractFilters(aliasedTable, relName, relWhere, relationFilterCtx(filterCtx, targetTableName)),\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))\n : hasPagination && pkNames.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined;\n thisRecord.offset = offset;\n thisRecord.limit = limit;\n\n const relWith = relationField\n ? extractRelationsParamsInner(\n relationMap,\n tables,\n targetTableName,\n relTypeName,\n relationField,\n typeNameMapper,\n false,\n filterCtx,\n limits,\n )\n : undefined;\n thisRecord.with = relWith;\n\n args[relName] = thisRecord;\n }\n\n return args;\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 typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n limits?: LimitPolicyFor,\n): Record<string, Partial<ProcessedTableSelectArgs>> | undefined => {\n if (!info) {\n return undefined;\n }\n\n return extractRelationsParamsInner(\n relationMap,\n tables,\n tableName,\n typeName,\n info,\n typeNameMapper,\n true,\n filterCtx,\n limits,\n );\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\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 * 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 = (\n table: Table,\n getTableConfig: (table: Table) => { 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/** 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 * 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 const payload = {\n o: entries,\n v: entries.map(([column]) => encodeCursorValue(row[column] ?? null)),\n };\n return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');\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 new GraphQLError('Invalid cursor: unable to decode it. Pass a cursor returned by a previous page.');\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 new GraphQLError('Invalid cursor: malformed payload. Pass a cursor returned by a previous page.');\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 new GraphQLError(\n \"Invalid cursor: it was issued for a different ordering. Pass the same orderBy the cursor's page used.\",\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 new GraphQLError(`Invalid cursor: unknown column '${column}'.`);\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 */\nconst 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 for (const row of rows) {\n row[ROW_CURSOR_PROP] = encodeCursor(entries, 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\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 = (\n table: Table,\n getTableConfig: (table: Table) => {\n primaryKeys: { columns: { name: string }[] }[];\n uniqueConstraints?: { columns: { name: string }[] }[];\n indexes?: { config: { unique?: boolean; columns: any[] } }[];\n },\n): string[][] => {\n const cols = getColumns(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\n/** Alias of the row-number helper column in the `distinct` pass. Namespaced against real columns. */\nconst 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\n * name), like the order/filter inputs, so repeated builds reuse one instance and two enums\n * 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 let tableCache = columnEnumCache.get(table);\n const cached = tableCache?.get(enumName);\n if (cached) {\n return cached;\n }\n\n const columnNames = Object.entries(getColumns(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(enumName, enumType);\n return enumType;\n};\n\n/** `${typeName}DistinctColumn` — the enum of columns a list query may be made distinct on. */\nexport const generateDistinctEnum = (table: Table, typeName: string): GraphQLEnumType | undefined =>\n generateColumnEnum(table, `${typeName}DistinctColumn`, `Columns of ${typeName} that a query can be made distinct on`);\n\n// ── upsert / conflict handling ────────────────────────────────────────────────\n\n/** Shared by every table's `${typeName}OnConflict` input, so it is created once. */\nexport const conflictActionEnum = new GraphQLEnumType({\n name: 'ConflictAction',\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 * 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 typeName: string;\n uniqueSets: string[][];\n tableFilters: GraphQLInputObjectType;\n withTarget: boolean;\n}): GraphQLInputObjectType | undefined => {\n const { table, typeName, uniqueSets, tableFilters, withTarget } = params;\n\n const updateEnum = generateColumnEnum(\n table,\n `${typeName}UpdateColumn`,\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: conflictActionEnum,\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 `${typeName}ConflictTarget`,\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: `${typeName}OnConflict`,\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 new GraphQLError(\n 'Unable to upsert: no conflict target was given and this table has no primary key. Pass onConflict.target.',\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 new GraphQLError(\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 );\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 new GraphQLError(\n `Unable to upsert: onConflict.update lists ${unsupplied.join(', ')}, which the values do not supply.`,\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\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 new GraphQLError(`Table ${tableName} has no primary key, so 'distinct' cannot be applied to it.`);\n }\n\n const requestedCols = distinct.map((name) => cols[name]).filter(Boolean);\n if (!requestedCols.length) {\n throw new GraphQLError(`No known columns were given to 'distinct' on ${tableName}.`);\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\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 const prepareMutationRelationColumns = (params: {\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}): {\n columns: Record<string, Column>;\n hasRelations: boolean;\n withParams: Record<string, Partial<ProcessedTableSelectArgs>> | undefined;\n} => {\n const { relationMap, tables, tableName, typeName, typeNameMapper, table, pkNames, parsedInfo } = params;\n const withParams = relationMap[tableName]\n ? extractRelationsParams(\n relationMap,\n tables,\n tableName,\n parsedInfo,\n typeName,\n typeNameMapper,\n undefined,\n params.limits,\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/** Wraps a thrown Error as a (message-only) GraphQLError; passes non-Errors through unchanged. */\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\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 },\n suffixes: { list: string; single: string },\n): {\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 deleteCountFieldName: string;\n} => {\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 createArrayFieldName = `${prefixes.insert}${mapped ? capitalize(mapped.plural) : capitalize(tableName)}`;\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}${mapped ? capitalize(mapped.plural) : capitalize(tableName)}`;\n const upsertSingleFieldName = mapped\n ? `${upsertPrefix}${capitalize(mapped.singular)}`\n : `${upsertPrefix}${capitalize(tableName)}${suffixes.single}`;\n const updateFieldName = `${prefixes.update}${mapped ? capitalize(mapped.singular) : capitalize(tableName)}`;\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}${mapped ? capitalize(mapped.plural) : capitalize(tableName)}Many`;\n const deleteFieldName = `${prefixes.delete}${mapped ? capitalize(mapped.singular) : capitalize(tableName)}`;\n // The plural update/delete mutations already use the singular noun when a mapper is\n // present, so — unlike create — the Single variants can't rely on singular vs plural to\n // stay distinct. They always carry a suffix, falling back to 'Single' when the configured\n // suffix is empty (a mapper config may set it to '' for the query side).\n const writeSingleSuffix = suffixes.single === '' ? 'Single' : suffixes.single;\n const updateSingleFieldName = `${updateFieldName}${writeSingleSuffix}`;\n const deleteSingleFieldName = `${deleteFieldName}${writeSingleSuffix}`;\n // The count variants are the plural write under another name, so they take the plural\n // noun rather than the singular one the plural mutations inherited from the mapper.\n const pluralNoun = mapped ? capitalize(mapped.plural) : capitalize(tableName);\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 deleteCountFieldName,\n };\n};\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 typeName: string;\n updatePrefix: string;\n updateInput: GraphQLInputObjectType;\n tableFilters: GraphQLInputObjectType;\n}): GraphQLInputObjectType => {\n const { typeName, updatePrefix, updateInput, tableFilters } = params;\n return new GraphQLInputObjectType({\n name: `${capitalize(updatePrefix)}${typeName}ManyInput`,\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 fieldName: string,\n relationCtx?: RelationFilterContext,\n): SQL => {\n const filters = where ? extractFilters(table, tableName, where, relationCtx) : undefined;\n if (!filters) {\n throw new GraphQLError(`${fieldName} requires a 'where' argument with at least one filter!`);\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, fieldName: string): 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 new GraphQLError(`${fieldName}: the driver did not report how many rows the write affected.`);\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 (\n executor: any,\n table: Table,\n filters: SQL,\n fieldName: string,\n): Promise<void> => {\n const matched = await executor.select({ found: sql`1` }).from(table).where(filters).limit(2);\n if (matched.length > 1) {\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row — nothing was written!`);\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, as the driver reported it, with no RETURNING clause at all.\n *\n * Dialect-independent: drizzle's update/delete builders take the same calls everywhere, and\n * the drivers' disagreement about how to spell the row count is handled by\n * {@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}: {\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}): CreatedResolver => {\n const queryArgs = {\n ...(setArgs ? { set: { type: new GraphQLNonNull(setArgs) } } : {}),\n where: {\n type: requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: any; set?: Record<string, any> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { where, set } = args;\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters = requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n let query: any;\n if (kind === 'delete') {\n query = 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 new GraphQLError(\n `${fieldName} does not support nested writes — use ${fieldName.slice(0, -'Count'.length)} instead.`,\n );\n }\n const values = remapUpdateInput(entry ? entry.columns : set!, table, tableName);\n if (!Object.keys(values).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n query = executor.update(table).set(values);\n }\n\n if (filters) {\n query = query.where(filters);\n }\n\n return rowsAffected(await query, fieldName);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\n/** GraphQL argument map for a list/array select field. */\nexport const selectArrayArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n distinctEnum?: GraphQLEnumType,\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});\n\n/** GraphQL argument map for a single-row select field (no `limit`). */\nexport const selectSingleArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n): Record<string, { type: any }> => ({\n offset: { type: GraphQLInt },\n orderBy: { type: orderArgs },\n where: { type: filterArgs },\n});\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}): 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 } = 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 new GraphQLError(\"'after' cannot be combined with 'distinct'.\");\n }\n if (orderByHasRelationEntry(orderBy)) {\n if (after != null) {\n throw new GraphQLError(\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 );\n }\n // `cursor` was selected under a relation ordering — the field resolves to null and the\n // relation ordering itself still applies.\n } else if (!pkNames?.length) {\n if (after != null) {\n throw new GraphQLError(`Table ${tableName} has no primary key, so cursor pagination cannot be used on it.`);\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 extractRelationsParamsInner.\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: where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\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)) : []),\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) => extractOrderBy(aliasedTable, orderBy, relationFilterCtx(filterCtx, tableName))\n : needsDefaultOrder && pkNames?.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined,\n where: distinctKeys\n ? { RAW: (aliasedTable: Table) => primaryKeyRestriction(aliasedTable, pkNames!, distinctKeys!) }\n : where || cursorValues\n ? {\n RAW: (aliasedTable: Table) =>\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 }\n : undefined,\n with: relationMap[tableName]\n ? extractRelationsParams(\n relationMap,\n tables,\n tableName,\n parsedInfo,\n typeName,\n typeNameMapper,\n filterCtx,\n opts.limits,\n )\n : undefined,\n };\n\n if (single) {\n const result = await queryBase.findFirst(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(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","// @ts-nocheck\nconst DRIZZLE_LOADERS_KEY = Symbol('drizzle-graphql-loaders');\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","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","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { type Column, getTableColumns, is, One, type Table } from 'drizzle-orm';\nimport { GraphQLError } from 'graphql';\nimport type { TableNamedRelations } from '../builders/index.ts';\nimport { getColumnScalarOverride } from '../type-converter/index.ts';\n\n// drizzle-orm v1 uses compound dataType strings (e.g. \"object json\"), so inclusion rather\n// than equality. PgGeometryObject is stored as json but has its own object type.\nconst isJsonColumn = (column: Column): boolean =>\n ((column as any).dataType ?? '').includes('json') && (column as any).columnType !== 'PgGeometryObject';\n\nexport const remapToGraphQLCore = (\n key: string,\n value: any,\n tableName: string,\n column: Column,\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 if (value instanceof Date) {\n return value.toISOString();\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 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 = table[key as keyof Table] as Column | undefined;\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) => {\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 (SQLite: \"object date\", MySQL timestamp/datetime: \"object date\").\n // Only convert string→Date for timestamp/datetime columns, NOT pure DATE columns.\n // MySqlDateString has dataType \"string date\" (excluded by startsWith check).\n // MySqlDate has columnType \"MySqlDate\" — excluded below since it can accept raw strings.\n const columnType: string = (column as any).columnType ?? '';\n const isTimestampColumn =\n columnType === 'SQLiteTimestamp' ||\n columnType === 'SQLiteTimestampMs' ||\n columnType === 'MySqlTimestamp' ||\n columnType === 'MySqlDateTime' ||\n columnType === 'PgTimestamp' ||\n columnType === 'PgTimestampString';\n if (isTimestampColumn) {\n const formatted = new Date(value);\n if (Number.isNaN(formatted.getTime())) {\n throw new GraphQLError(`Field '${columnName}' is not a valid date!`);\n }\n\n return formatted;\n }\n\n // Date-only columns (no time component) — extract YYYY-MM-DD portion to avoid\n // timezone shifts when mysql2 formats Date objects using local time.\n const isDateOnlyColumn = columnType === 'MySqlDate' || columnType === 'PgDate';\n if (isDateOnlyColumn && typeof value === 'string') {\n // Accept ISO strings like \"2024-04-04T00:00:00.000Z\" or plain \"2024-04-04\"\n const dateOnly = value.includes('T') ? value.split('T')[0] : value;\n // Validate it's a real date by parsing\n const check = new Date(dateOnly!);\n if (Number.isNaN(check.getTime())) {\n throw new GraphQLError(`Field '${columnName}' is not a valid date!`);\n }\n\n return dateOnly;\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 new GraphQLError(`Field '${columnName}' is not a BigInt!`);\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 new GraphQLError(`Field '${columnName}' is not a valid date!`);\n }\n\n return formatted;\n }\n\n case 'buffer': {\n if (!Array.isArray(value)) {\n throw new GraphQLError(`Field '${columnName}' is not an array!`);\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 new GraphQLError(\n `Invalid JSON in field '${columnName}':\\n${e instanceof Error ? e.message : 'Unknown error'}`,\n );\n }\n }\n\n case 'array': {\n if (!Array.isArray(value)) {\n throw new GraphQLError(`Field '${columnName}' is not an array!`);\n }\n\n if (column.columnType === 'PgGeometry' && value.length !== 2) {\n throw new GraphQLError(\n `Invalid float tuple in field '${columnName}': expected array with length of 2, received ${value.length}`,\n );\n }\n\n return value;\n }\n\n case 'bigint': {\n try {\n return BigInt(value);\n } catch (_error) {\n throw new GraphQLError(`Field '${columnName}' is not a BigInt!`);\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\nexport const remapFromGraphQLSingleInput = (queryInput: Record<string, any>, table: Table) => {\n for (const [key, value] of Object.entries(queryInput)) {\n if (value === undefined) {\n delete queryInput[key];\n } else {\n const column = getTableColumns(table)[key];\n if (!column) {\n throw new GraphQLError(`Unknown column: ${key}`);\n }\n\n if (value === null && column.notNull) {\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 = (queryInput: Record<string, any>[], table: Table) => {\n for (const entry of queryInput) {\n remapFromGraphQLSingleInput(entry, table);\n }\n\n return queryInput;\n};\n","import type { Column, Table } from 'drizzle-orm';\nimport { extractExtendedColumnType, getTableColumns, is } from 'drizzle-orm';\nimport { MySqlInt, MySqlSerial } from 'drizzle-orm/mysql-core';\nimport { PgDate, PgDateString, PgInteger, PgSerial, PgTimestamp, PgTimestampString, PgUUID } from 'drizzle-orm/pg-core';\nimport { SQLiteInteger } 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 } 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 ScalarOverride,\n ScalarOverridesConfig,\n} from './types.ts';\n\nconst allowedNameChars = /^[a-zA-Z0-9_]+$/;\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 * 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 }>();\nlet enumNameMapper: EnumNameMapper | undefined;\n\n/**\n * Resets the enum registry for a fresh schema build and installs that build's\n * `enumNameMapper`. 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: { enumNameMapper?: EnumNameMapper }): void => {\n enumNameMapper = config.enumNameMapper;\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 valuesKey = enumValuesKey(values);\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 return claimed.type;\n }\n\n const gqlEnum = new GraphQLEnumType({\n name,\n values: Object.fromEntries(\n values.map((e, index) => [\n allowedNameChars.test(e) ? e : `Option${index}`,\n {\n value: e,\n description: `Value: ${e}`,\n },\n ]),\n ),\n });\n\n enumNamesInUse.set(name, { type: gqlEnum, valuesKey });\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\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 (column instanceof PgTimestamp || column instanceof PgDate) {\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 (column instanceof PgTimestamp || column instanceof PgTimestampString) {\n return { type: GraphQLDateTime, typeLabel: 'DateTime' };\n }\n if (column instanceof PgUUID) {\n return { type: GraphQLUUID, typeLabel: 'UUID' };\n }\n if (column instanceof PgDateString) {\n // For input, accept any string (drivers truncate ISO timestamps to date on write).\n // For output, keep the strict GraphQLDate scalar so the returned value is validated.\n return isInput ? { type: GraphQLString, typeLabel: 'Date' } : { 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 return 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(getTableColumns(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>(\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 type: new GraphQLNonNull(typeDesc.type),\n typeLabel: typeDesc.typeLabel,\n } as ConvertedColumn<TIsInput>;\n }\n\n return typeDesc as ConvertedColumn<TIsInput>;\n};\n","import { GraphQLError, GraphQLScalarType, Kind } from 'graphql';\nimport { GraphQLDate, GraphQLDateTime, GraphQLJSON, GraphQLUUID } from 'graphql-scalars';\n\nconst asDecimalString = (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 new GraphQLError(`BigInt cannot represent non-integer value: ${value}`);\n }\n if (!Number.isSafeInteger(value)) {\n throw new GraphQLError(\n `BigInt cannot represent the number ${value} without precision loss — pass it as a string instead`,\n );\n }\n return String(value);\n }\n\n if (typeof value === 'string') {\n if (!/^-?\\d+$/.test(value)) {\n throw new GraphQLError(`BigInt cannot represent non-integer value: \"${value}\"`);\n }\n return value;\n }\n\n throw new GraphQLError(`BigInt cannot represent value: ${JSON.stringify(value)}`);\n};\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: asDecimalString,\n parseValue: asDecimalString,\n parseLiteral: (ast) => {\n if (ast.kind !== Kind.STRING && ast.kind !== Kind.INT) {\n throw new GraphQLError(`BigInt cannot represent a ${ast.kind}`, { nodes: ast });\n }\n return asDecimalString(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 asNumericString = (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 new GraphQLError(`Decimal cannot represent non-finite value: ${value}`);\n }\n return String(value);\n }\n\n if (typeof value === 'string') {\n if (!numericStringPattern.test(value)) {\n throw new GraphQLError(`Decimal cannot represent non-numeric value: \"${value}\"`);\n }\n return value;\n }\n\n throw new GraphQLError(`Decimal cannot represent value: ${JSON.stringify(value)}`);\n};\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: asNumericString,\n parseValue: asNumericString,\n parseLiteral: (ast) => {\n if (ast.kind !== Kind.STRING && ast.kind !== Kind.INT && ast.kind !== Kind.FLOAT) {\n throw new GraphQLError(`Decimal cannot represent a ${ast.kind}`, { nodes: ast });\n }\n return asNumericString(ast.value);\n },\n});\n\nexport { GraphQLDate, GraphQLDateTime, GraphQLJSON, GraphQLUUID };\n","// @ts-nocheck — drizzle-orm 1.0 type compat not guaranteed, same as its sibling builders\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 GraphQLError,\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';\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): GraphQLInputObjectType | undefined => {\n const kind = fieldUpdateKind(column, columnName, tableName);\n if (kind === 'none') {\n return undefined;\n }\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 `${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 `${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 new GraphQLError(\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 );\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 */\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);\n return Object.keys(expressions).length ? { ...remapped, ...expressions } : remapped;\n};\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { is, One, type Table } from 'drizzle-orm';\nimport { getTableConfig, type MySqlDatabase, MySqlTable } from 'drizzle-orm/mysql-core';\nimport type { RelationalQueryBuilder } from 'drizzle-orm/mysql-core/query-builders/query';\nimport type { GraphQLFieldConfig, GraphQLFieldConfigArgumentMap, ThunkObjMap } from 'graphql';\nimport {\n GraphQLBoolean,\n GraphQLError,\n type GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\n\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n aggregateFieldComplexity,\n applyLimitPolicy,\n assertSingleMatch,\n attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createMutationTxCtx,\n createRelationResolverFactory,\n extractFilters,\n extractRequiredFilters,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n generateUpdateManyInput,\n generateWriteCount,\n getPrimaryKeyPropNamesFromConfig,\n type LimitPolicyFor,\n listFieldComplexity,\n type MutationTxCtx,\n mysqlValuesColumnRef,\n type OnConflictArg,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n relationFilterCtx,\n resolveConflictPlan,\n resolveQueryExecutor,\n runMutation,\n runRelationalSelect,\n selectArrayArgs,\n selectSingleArgs,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n} from '../builders/common.ts';\nimport { remapFromGraphQLArrayInput, remapFromGraphQLSingleInput } from '../data-mappers/index.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} from './aggregates.ts';\nimport { remapUpdateInput } from './field-updates.ts';\nimport type {\n CreatedResolver,\n Filters,\n SchemaGeneratorOptions,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst generateSelectArray = (\n db: MySqlDatabase<any, any, 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 = true,\n limits?: LimitPolicyFor,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const table = tables[tableName]!;\n const limitPolicy = limits?.(tableName);\n const pkNames = mysqlPrimaryKeyPropNames(table as MySqlTable);\n const queryArgs = selectArrayArgs(\n orderArgs,\n filterArgs,\n distinctEnabled ? generateDistinctEnum(table, typeName) : undefined,\n );\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\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,\n typeNameMapper,\n parsedInfo,\n ...args,\n limit: applyLimitPolicy(args.limit, limitPolicy, fieldName),\n single: false,\n filterCtx,\n limits,\n pkNames,\n db: executor,\n // MySQL sorts NULLs as the smallest values (first in ASC).\n nullOrdering: 'nulls-smallest',\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateSelectSingle = (\n db: MySqlDatabase<any, any, 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): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const queryArgs = selectSingleArgs(orderArgs, filterArgs);\n\n const table = tables[tableName]!;\n const pkNames = mysqlPrimaryKeyPropNames(table as MySqlTable);\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\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,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n limits,\n pkNames,\n db: executor,\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateInsertArray = (\n db: MySqlDatabase<any, any, any, any>,\n _tableName: string,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n txCtx?: MutationTxCtx,\n): CreatedResolver => {\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(baseType))),\n },\n };\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any>[] }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const input = remapFromGraphQLArrayInput(args.values, table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n\n await executor.insert(table).values(input);\n\n return { isSuccess: true };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateInsertSingle = (\n db: MySqlDatabase<any, any, any, any>,\n _tableName: string,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n txCtx?: MutationTxCtx,\n): CreatedResolver => {\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: new GraphQLNonNull(baseType),\n },\n };\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const input = remapFromGraphQLSingleInput(args.values, table);\n\n await executor.insert(table).values(input);\n\n return { isSuccess: true };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateUpsert = (\n db: MySqlDatabase<any, any, any, any>,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n onConflictType: GraphQLInputObjectType,\n fieldName: string,\n single: boolean,\n txCtx?: MutationTxCtx,\n): CreatedResolver => {\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.',\n },\n };\n\n const pkNames = mysqlPrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { values: Record<string, any> | Record<string, any>[]; onConflict?: OnConflictArg },\n context,\n info,\n ) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const input = single\n ? [remapFromGraphQLSingleInput(args.values as Record<string, any>, table)]\n : remapFromGraphQLArrayInput(args.values as Record<string, any>[], table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\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 return { isSuccess: true };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateUpdate = (\n db: MySqlDatabase<any, 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): CreatedResolver => {\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 return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table>; set: Record<string, any> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { where, set } = args;\n\n const input = remapUpdateInput(set, table, tableName);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\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 return { isSuccess: true };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\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: MySqlDatabase<any, any, any>,\n tableName: string,\n table: MySqlTable,\n updateManyInput: GraphQLInputObjectType,\n fieldName: string,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n): CreatedResolver => {\n const queryArgs = {\n updates: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(updateManyInput))),\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { updates: { where?: Filters<Table>; set: Record<string, any> }[] },\n context,\n info,\n ) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { updates } = args;\n if (!updates.length) {\n throw new GraphQLError('No updates were provided!');\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 = updates.map(({ where, set }) => {\n const input = remapUpdateInput(set, table, tableName);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n filters: where\n ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined,\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 return { isSuccess: true };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateDelete = (\n db: MySqlDatabase<any, 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): CreatedResolver => {\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { where } = args;\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n await query;\n\n return { isSuccess: true };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\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\nexport const generateSchemaData = <\n TDrizzleInstance extends MySqlDatabase<any, 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> => {\n const { relationsDepthLimit, prefixes, suffixes, typeNameMapper, shouldEagerLoad, features, complexity, limits } =\n options;\n const rawSchema = schema;\n const schemaEntries = Object.entries(rawSchema);\n\n const tableEntries = schemaEntries.filter(([_key, value]) => is(value, MySqlTable)) as [string, MySqlTable][];\n const tables = Object.fromEntries(tableEntries);\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 // 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 if (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 // 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\n // Build namedRelations from the drizzle-orm v1 relations config.\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Record each relation target's (composite-aware) primary key for deterministic\n // paginated ordering. Must run before pruning / type generation (shared entry objects).\n attachTargetPrimaryKeys(namedRelations, tables, mysqlPrimaryKeyPropNames);\n // Pruned map for query resolvers' `with:`; type generation keeps the full map.\n const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);\n\n const filterCtx: RelationFilterBase = { tables, relationMap: namedRelations };\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(\n db,\n tables,\n 'nulls-smallest',\n filterCtx,\n limits,\n );\n\n // Fresh cache per generateSchemaData call — prevents type name collisions\n // when buildSchema() is called multiple times.\n const cacheCtx: TypeCacheCtx = {\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 features,\n };\n\n // Left undefined when the feature is off — generateTableTypes then emits no\n // `${relation}Aggregate` fields at all.\n const relationAggregateFactory: RelationAggregateFactory | undefined = features.relationAggregates\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx)\n : undefined;\n\n const queries: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const mutations: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n // One per schema build: every mutation resolver shares it so a multi-mutation request can\n // ride a single transaction. Undefined unless transactions were requested.\n const mutationTxCtx = createMutationTxCtx(options.transactions);\n const gqlSchemaTypes = Object.fromEntries(\n Object.entries(tables).map(([tableName, _table]) => [\n tableName,\n generateTableTypes(\n tableName,\n tables,\n namedRelations,\n false,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n prefixes.insert,\n prefixes.update,\n resolverFactory,\n relationAggregateFactory,\n ),\n ]),\n );\n\n const mutationReturnType = new GraphQLObjectType({\n name: 'MutationReturn',\n fields: {\n isSuccess: {\n type: new GraphQLNonNull(GraphQLBoolean),\n },\n },\n });\n\n const inputs: Record<string, GraphQLInputObjectType> = {};\n const outputs: Record<string, GraphQLObjectType> = {};\n // Every MySQL mutation returns it, so it only belongs in the type map when at least one\n // mutation is generated.\n if (features.insert || features.upsert || features.update || features.delete) {\n outputs.MutationReturn = mutationReturnType;\n }\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n const { insertInput, updateInput, tableFilters, tableOrder } = tableTypes.inputs;\n const { selectSingleOutput, selectArrOutput } = tableTypes.outputs;\n\n // Compute field names using the mapper logic\n const {\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 deleteCountFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\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 features.distinct,\n limits,\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 );\n const insertArrGenerated = features.insert\n ? generateInsertArray(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n createArrayFieldName,\n mutationTxCtx,\n )\n : undefined;\n const insertSingleGenerated = features.insert\n ? generateInsertSingle(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n createSingleFieldName,\n mutationTxCtx,\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 = features.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as MySqlTable,\n typeName,\n uniqueSets: [],\n tableFilters,\n withTarget: false,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(\n db,\n schema[tableName] as MySqlTable,\n insertInput,\n onConflictInput,\n upsertArrayFieldName,\n false,\n mutationTxCtx,\n )\n : undefined;\n const upsertSingleGenerated = onConflictInput\n ? generateUpsert(\n db,\n schema[tableName] as MySqlTable,\n insertInput,\n onConflictInput,\n upsertSingleFieldName,\n true,\n mutationTxCtx,\n )\n : undefined;\n const updateGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateFieldName,\n false,\n features.requireWhere,\n filterCtx,\n mutationTxCtx,\n )\n : undefined;\n const updateSingleGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n true,\n features.requireWhere,\n filterCtx,\n mutationTxCtx,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n features.update && features.updateMany\n ? generateUpdateManyInput({ typeName, updatePrefix: prefixes.update, updateInput, tableFilters })\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 )\n : undefined;\n const deleteGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteFieldName,\n false,\n features.requireWhere,\n filterCtx,\n mutationTxCtx,\n )\n : undefined;\n const deleteSingleGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteSingleFieldName,\n true,\n features.requireWhere,\n filterCtx,\n mutationTxCtx,\n )\n : undefined;\n // The count variants are the plural write with its payload left off, so each follows the\n // same feature switch as the write it mirrors.\n const updateCountGenerated =\n features.update && features.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: features.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n })\n : undefined;\n const deleteCountGenerated =\n features.delete && features.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as MySqlTable,\n kind: 'delete',\n filterArgs: tableFilters,\n fieldName: deleteCountFieldName,\n requireWhere: features.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n })\n : undefined;\n const aggregateType = features.aggregates\n ? generateAggregateTypes(schema[tableName] as MySqlTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = features.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n features.aggregates && features.groupBy\n ? generateGroupByType(schema[tableName] as MySqlTable, tableName, typeName, cacheCtx)\n : undefined;\n const groupByEnum = groupByType\n ? generateGroupByEnum(schema[tableName] as MySqlTable, tableName, typeName)\n : undefined;\n const havingInput = groupByEnum\n ? generateHavingInput(schema[tableName] as MySqlTable, tableName, typeName)\n : undefined;\n const groupByGenerated =\n groupByType && groupByEnum && havingInput\n ? generateGroupBy(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n typeName,\n groupByFieldName,\n tableFilters,\n groupByEnum,\n havingInput,\n filterCtx,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n ...(complexity ? { extensions: { complexity: listFieldComplexity(complexity, limits?.(tableName)) } } : {}),\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n for (const generated of [\n insertArrGenerated,\n insertSingleGenerated,\n upsertArrGenerated,\n upsertSingleGenerated,\n updateGenerated,\n updateManyGenerated,\n updateSingleGenerated,\n deleteGenerated,\n deleteSingleGenerated,\n ]) {\n if (generated) {\n mutations[generated.name] = {\n type: mutationReturnType,\n args: generated.args,\n resolve: generated.resolver,\n };\n }\n }\n // Apart from the loop above: the count mutations are the one pair whose return value is\n // not MySQL's shared `isSuccess` shape.\n if (updateCountGenerated) {\n mutations[updateCountGenerated.name] = {\n type: new GraphQLNonNull(GraphQLInt),\n args: updateCountGenerated.args,\n resolve: updateCountGenerated.resolver,\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 if (deleteCountGenerated) {\n mutations[deleteCountGenerated.name] = {\n type: new GraphQLNonNull(GraphQLInt),\n args: deleteCountGenerated.args,\n resolve: deleteCountGenerated.resolver,\n description:\n 'How many rows the delete removed. The rows themselves are not read back, which is the point of this mutation.',\n };\n }\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 ...(features.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(features.update ? [updateInput] : []),\n ...(updateManyInput ? [updateManyInput] : []),\n tableFilters,\n tableOrder,\n ];\n activeInputs.forEach((e) => {\n inputs[e.name] = e;\n });\n outputs[selectSingleOutput.name] = selectSingleOutput;\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 // The first mutation resolver of a request counts the operation's root mutation fields to\n // know how many completions to wait for — but only fields this library generated can report\n // completion, so the shared-transaction path needs the full roster of generated names.\n if (mutationTxCtx) {\n for (const name of Object.keys(mutations)) {\n mutationTxCtx.fieldNames.add(name);\n }\n }\n\n const fieldResolvers: Record<string, Record<string, any>> = {};\n for (const [tableName, tableRelations] of Object.entries(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 = 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 { queries, mutations, inputs, types: outputs, fieldResolvers } as any;\n};\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport {\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 GraphQLError,\n GraphQLFloat,\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\nimport { getOrCreateLoader } from '../batch-loader/index.ts';\nimport { capitalize } from '../case-ops/index.ts';\nimport { remapToGraphQLCore } from '../data-mappers/index.ts';\nimport { drizzleColumnToGraphQLType } from '../type-converter/index.ts';\nimport type { ConvertedColumn } from '../type-converter/types.ts';\nimport {\n columnDocs,\n extractFilters,\n extractRelationJoinColumns,\n generateColumnEnum,\n type RelationAggregateFactory,\n type RelationFilterBase,\n relationFilterCtx,\n resolveExecutor,\n resolveTypeName,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\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 */\nconst classifyAggregateColumns = (table: Table, tableName: string): AggregateColumnSets => {\n const numeric: AggregateColumnSets['numeric'] = {};\n const orderable: AggregateColumnSets['orderable'] = {};\n const all: AggregateColumnSets['all'] = {};\n\n for (const [columnName, column] of Object.entries(getColumns(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 return { numeric, orderable, all };\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\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: `${typeName}${capitalize(op)}Aggregate`,\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: `${typeName}${capitalize(op)}Aggregate`,\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: `${typeName}${capitalize(op)}Aggregate`,\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: `${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 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 = (table: Table, tableName: string, typeName: string): AggregateTarget => {\n const { orderable } = classifyAggregateColumns(table, tableName);\n\n return {\n tableName,\n typeName,\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.typeName}Aggregate`,\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.typeName}${capitalize(op)}Aggregate`];\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 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): CreatedResolver => {\n const target = aggregateTarget(table, tableName, typeName);\n\n const queryArgs = {\n where: { type: filterArgs },\n };\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, 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 if (args.where) {\n query = query.where(extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName)));\n }\n const rows = await query;\n\n return assembleAggregateRow(rows[0] ?? {}, request, target);\n } catch (e) {\n throw toGraphQLError(e);\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): RelationAggregateFactory => {\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 return undefined;\n }\n const { localColPropName, foreignCol } = joinCols;\n\n const targetTypeName = resolveTypeName(targetTableName, typeNameMapper);\n const type = generateAggregateTypes(targetTable, targetTableName, targetTypeName, cacheCtx);\n const target = aggregateTarget(targetTable, targetTableName, targetTypeName);\n\n const resolve = async (parent: any, args: { where?: Filters<Table> }, context: any, info: any) => {\n try {\n const request = parseAggregateRequest(info, target);\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 // Siblings only share a batch when they'd run the same query: same filters, same aggregates.\n const argsKey = JSON.stringify({\n where: whereArg ?? null,\n selection: Object.keys(request.selection).sort(),\n });\n const loaderKey = `${tableName}::${relationName}::aggregate::${argsKey}`;\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 const whereCondition = and(\n inArray(foreignCol, uniqueIds),\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\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 toGraphQLError(e);\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(getColumns(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 = (table: Table, tableName: string, typeName: string): GraphQLEnumType | undefined => {\n const groupable = groupableColumns(table, tableName);\n\n return generateColumnEnum(\n table,\n `${typeName}GroupByColumn`,\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 rather than per table. */\nexport const aggregateNumberFilter = new GraphQLInputObjectType({\n name: 'AggregateNumberFilter',\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 * 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 = (table: Table, tableName: string, typeName: string): GraphQLInputObjectType => {\n const { numeric, orderable, all } = classifyAggregateColumns(table, tableName);\n\n const fields: Record<string, { type: any; description?: string }> = {\n count: { type: aggregateNumberFilter, 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: `${typeName}${capitalize(op)}Having`,\n fields: Object.fromEntries(columnNames.map((columnName) => [columnName, { type: aggregateNumberFilter }])),\n }),\n };\n }\n\n return new GraphQLInputObjectType({\n name: `${typeName}Having`,\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: `${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: `${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): CreatedResolver => {\n const target = aggregateTarget(table, tableName, typeName);\n const groupable = groupableColumns(table, tableName);\n const columns = getColumns(table);\n const rootTypeName = `${typeName}GroupBy`;\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 };\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { groupBy?: string[]; where?: Filters<Table>; having?: Record<string, any> },\n context,\n info,\n ) => {\n try {\n const requestedKeys = [...new Set(args.groupBy ?? [])];\n if (!requestedKeys.length) {\n throw new GraphQLError('At least one column to group by is required!');\n }\n\n const keyColumns = requestedKeys.map((columnName) => {\n const groupableColumn = groupable[columnName];\n if (!groupableColumn) {\n throw new GraphQLError(`Cannot group ${typeName} by ${columnName}!`);\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 if (args.where) {\n query = query.where(extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName)));\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 toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { and, getColumns, is, One, type Table, type View } from 'drizzle-orm';\nimport type { RelationalQueryBuilder } from 'drizzle-orm/mysql-core/query-builders/query';\nimport { getTableConfig, type PgAsyncDatabase, type PgColumn, PgTable } from 'drizzle-orm/pg-core';\nimport type { GraphQLFieldConfig, GraphQLFieldConfigArgumentMap, ThunkObjMap } from 'graphql';\nimport {\n GraphQLError,\n type GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n type GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n aggregateFieldComplexity,\n applyLimitPolicy,\n assertSingleMatch,\n attachRowCursors,\n attachTargetPrimaryKeys,\n buildCursorCondition,\n buildNamedRelations,\n type CursorOrderEntry,\n computeResolverFieldNames,\n createMutationTxCtx,\n createRelationResolverFactory,\n cursorOrderExprs,\n cursorOrderingEntries,\n decodeCursor,\n eagerLoadMutationRelations,\n excludedColumnRef,\n extractFilters,\n extractOrderBy,\n extractRelationJoinColumns,\n extractRequiredFilters,\n extractSelectedColumnsFromTreeSQLFormat,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n generateUpdateManyInput,\n generateWriteCount,\n getPrimaryKeyPropNamesFromConfig,\n getUniqueColumnSets,\n isCursorFieldSelected,\n type LimitPolicyFor,\n listFieldComplexity,\n type MutationTxCtx,\n type OnConflictArg,\n orderByHasRelationEntry,\n prepareMutationRelationColumns,\n primaryKeyOrderExprs,\n primaryKeyRestriction,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n relationFilterCtx,\n resolveConflictPlan,\n resolveQueryExecutor,\n runMutation,\n runRelationalSelect,\n type SelectionCtx,\n selectArrayArgs,\n selectDistinctKeys,\n selectSingleArgs,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n} from '../builders/common.ts';\nimport {\n remapFromGraphQLArrayInput,\n remapFromGraphQLSingleInput,\n remapToGraphQLArrayOutput,\n remapToGraphQLSingleOutput,\n} from '../data-mappers/index.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} from './aggregates.ts';\nimport { remapUpdateInput } from './field-updates.ts';\nimport {\n buildNestedWritePlans,\n createNestedWriteRuntime,\n createNestedWriteTypes,\n mergedOps,\n type NestedWriteRuntime,\n updateWithNestedOps,\n writeWithNestedOps,\n} from './nested-writes.ts';\nimport type {\n CreatedResolver,\n Filters,\n SchemaGeneratorOptions,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst generateSelectArray = (\n db: PgAsyncDatabase<any, any, 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 = true,\n limits?: LimitPolicyFor,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n // Tables without relations won't have db.query support — fall back to basic select.\n\n const table = tables[tableName]!;\n const limitPolicy = limits?.(tableName);\n const pkNames = pgPrimaryKeyPropNames(table as PgTable);\n const queryArgs = selectArrayArgs(\n orderArgs,\n filterArgs,\n distinctEnabled ? generateDistinctEnum(table, typeName) : undefined,\n );\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n // Resolved once here so the relational path and the plain-select fallback below both\n // see the same effective limit.\n const limit = applyLimitPolicy(args.limit, limitPolicy, fieldName);\n\n if (requestQueryBase) {\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n limit,\n single: false,\n filterCtx,\n limits,\n pkNames,\n db: executor,\n // PostgreSQL sorts NULLs as the largest values (last in ASC).\n nullOrdering: 'nulls-largest',\n });\n }\n\n // Fallback for tables without relational query builder support.\n // Use SQL column objects (not Record<string,true>) so db.select() receives valid expressions.\n const { offset, orderBy, where, distinct, after } = args;\n const selectedColumnsSql = extractSelectedColumnsFromTreeSQLFormat<PgColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n { tableName, relationMap, tables },\n );\n\n // Keyset pagination (see runRelationalSelect, which handles the RQB path).\n const cursorSelected = isCursorFieldSelected(parsedInfo.fieldsByTypeName[typeName], table);\n let cursorEntries: CursorOrderEntry[] | undefined;\n if (after != null || cursorSelected) {\n if (after != null && distinct?.length) {\n throw new GraphQLError(\"'after' cannot be combined with 'distinct'.\");\n }\n if (orderByHasRelationEntry(orderBy)) {\n if (after != null) {\n throw new GraphQLError(\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 );\n }\n // `cursor` selected under a relation ordering — resolves to null; ordering still applies.\n } else if (!pkNames.length) {\n if (after != null) {\n throw new GraphQLError(\n `Table ${tableName} has no primary key, so cursor pagination cannot be used on it.`,\n );\n }\n } else {\n cursorEntries = cursorOrderingEntries(orderBy, pkNames);\n if (cursorSelected) {\n // The whole ordering tuple is needed to compute each row's cursor.\n const allColumns = getColumns(table);\n for (const [column] of cursorEntries) {\n selectedColumnsSql[column] ??= allColumns[column] as PgColumn;\n }\n }\n }\n }\n const cursorCondition =\n after != null && cursorEntries\n ? buildCursorCondition(table, cursorEntries, decodeCursor(after, cursorEntries), 'nulls-largest')\n : undefined;\n\n const baseWhereSql = where\n ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined;\n const whereSql = cursorCondition ? and(baseWhereSql, cursorCondition) : baseWhereSql;\n\n // `distinct` picks the surviving rows in its own pass; the main query is then narrowed\n // to those primary keys and re-orders them the same way. See runRelationalSelect.\n let distinctKeys: Record<string, any>[] | undefined;\n if (distinct?.length) {\n distinctKeys = await selectDistinctKeys({\n db: executor,\n table,\n tableName,\n distinct,\n pkNames,\n where: whereSql,\n orderBy,\n limit,\n offset,\n });\n if (!distinctKeys.length) {\n return [];\n }\n }\n\n let q = executor.select(selectedColumnsSql).from(table);\n if (distinctKeys) {\n q = q.where(primaryKeyRestriction(table, pkNames, distinctKeys)) as any;\n } else if (whereSql) {\n q = q.where(whereSql) as any;\n }\n if (cursorEntries && !distinctKeys) {\n // Cursor pagination pages over a total order: orderBy plus the PK tiebreak.\n q = q.orderBy(...cursorOrderExprs(table, cursorEntries)) as any;\n } else if (orderBy) {\n q = q.orderBy(\n ...extractOrderBy(table, orderBy, relationFilterCtx(filterCtx, tableName)),\n ...(distinctKeys ? primaryKeyOrderExprs(table, pkNames) : []),\n ) as any;\n } else if ((distinctKeys || offset != null || limit != null) && pkNames.length) {\n // See runRelationalSelect: an unordered slice is not stable between requests.\n q = q.orderBy(...primaryKeyOrderExprs(table, pkNames)) as any;\n }\n if (!distinctKeys) {\n if (offset) {\n q = q.offset(offset) as any;\n }\n if (limit) {\n q = q.limit(limit) as any;\n }\n }\n const rows = await q;\n if (cursorEntries && cursorSelected) {\n attachRowCursors(rows, cursorEntries);\n }\n return remapToGraphQLArrayOutput(rows, tableName, table, relationMap);\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateSelectSingle = (\n db: PgAsyncDatabase<any, any, 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): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n // Tables without relations won't have db.query support — fall back to basic select.\n\n const queryArgs = selectSingleArgs(orderArgs, filterArgs);\n\n const table = tables[tableName]!;\n const pkNames = pgPrimaryKeyPropNames(table as PgTable);\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n\n if (requestQueryBase) {\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n limits,\n pkNames,\n db: executor,\n });\n }\n\n // Fallback for tables without relational query builder support.\n const { offset, orderBy, where } = args;\n const selectedColumnsSql = extractSelectedColumnsFromTreeSQLFormat<PgColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n { tableName, relationMap, tables },\n );\n let q = executor.select(selectedColumnsSql).from(table);\n if (where) {\n q = q.where(extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))) as any;\n }\n if (orderBy) {\n q = q.orderBy(...extractOrderBy(table, orderBy, relationFilterCtx(filterCtx, tableName))) as any;\n } else if (pkNames.length) {\n // A single query is an implicit `limit 1` — order it so the row is deterministic.\n q = q.orderBy(...primaryKeyOrderExprs(table, pkNames)) as any;\n }\n if (offset) {\n q = q.offset(offset) as any;\n }\n const rows = await q.limit(1);\n const result = rows[0];\n return result ? remapToGraphQLSingleOutput(result, tableName, table, relationMap) : undefined;\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\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 generateInsertArray = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n conflictDoNothing: boolean = false,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n limits?: LimitPolicyFor,\n): CreatedResolver => {\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: 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 = pgPrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any>[] }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n if (!args.values.length) {\n throw new GraphQLError('No values were provided!');\n }\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 ? args.values.map((values) => nested.split(tableName, values))\n : undefined;\n const nestedEntries = entries?.some((entry) => nested!.hasOps(entry.ops)) ? entries : undefined;\n const input = nestedEntries\n ? []\n : remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : args.values, table);\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n limits,\n });\n\n const returning = nestedEntries\n ? nested!.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table)\n : columns;\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 result = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) => remapFromGraphQLSingleInput(values, table),\n write: (tx, values) => runInsert(tx, [values]),\n })\n : await runInsert(executor, input);\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateInsertSingle = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n conflictDoNothing: boolean = false,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n limits?: LimitPolicyFor,\n): CreatedResolver => {\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: new GraphQLNonNull(baseType),\n },\n };\n\n // Derived once at build time — PK prop names don't change per request.\n const pkNames = pgPrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const entry = nested?.enabled(tableName) ? nested.split(tableName, args.values) : undefined;\n const nestedEntry = entry && nested!.hasOps(entry.ops) ? entry : undefined;\n const input = nestedEntry ? {} : remapFromGraphQLSingleInput(entry ? entry.columns : args.values, table);\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n limits,\n });\n\n const returning = nestedEntry\n ? nested!.withJoinColumns(tableName, nestedEntry.ops, { ...columns }, table)\n : columns;\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 result = nestedEntry\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: [nestedEntry],\n remapValues: (values) => remapFromGraphQLSingleInput(values, table),\n write: runInsert,\n })\n : await runInsert(executor, input);\n\n if (!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 new GraphQLError(`${fieldName}: the insert returned no row.`);\n }\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\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 */\nconst generateUpsert = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n onConflictType: GraphQLInputObjectType,\n uniqueSets: string[][],\n fieldName: string,\n typeName: string,\n single: boolean,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n limits?: LimitPolicyFor,\n): CreatedResolver => {\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 = pgPrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { values: Record<string, any> | Record<string, any>[]; onConflict?: OnConflictArg },\n context,\n info,\n ) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const supplied = single ? [args.values as Record<string, any>] : (args.values as Record<string, any>[]);\n if (!supplied.length) {\n throw new GraphQLError('No values were provided!');\n }\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 input = nestedEntries\n ? []\n : remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table);\n\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n limits,\n });\n\n const returning = nestedEntries\n ? nested!.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table)\n : columns;\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 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: plan.setWhere }) as any);\n\n return (await query) as Record<string, any>[];\n };\n\n const result = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) => remapFromGraphQLSingleInput(values, table),\n write: (tx, values) => runUpsert(tx, [values]),\n })\n : await runUpsert(executor, input);\n\n if (single && !result[0]) {\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return single\n ? remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap)\n : remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateUpdate = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n setArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n single: boolean,\n requireWhere: boolean,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n limits?: LimitPolicyFor,\n): CreatedResolver => {\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 = pgPrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table>; set: Record<string, any> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { where, set } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n limits,\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 const input = remapUpdateInput(entry ? entry.columns : set, table, tableName);\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 new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n const returning = nestedOps ? nested!.withJoinColumns(tableName, nestedOps, { ...columns }, table) : columns;\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 result = 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 })\n : await runUpdate(executor, input);\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row!`);\n }\n\n if (single && !result[0]) {\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return single\n ? remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap)\n : remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\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. The result lists each entry's updated rows in entry order, with `null`\n * standing in for an entry whose `where` matched no rows, so the common one-row-per-entry\n * case stays aligned with the input.\n */\nconst generateUpdateMany = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n updateManyInput: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n limits?: LimitPolicyFor,\n): CreatedResolver => {\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 = pgPrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { updates: { where?: Filters<Table>; set: Record<string, any> }[] },\n context,\n info,\n ) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { updates } = args;\n if (!updates.length) {\n throw new GraphQLError('No updates were provided!');\n }\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n limits,\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 = 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 = remapUpdateInput(split ? split.columns : set, table, tableName);\n // An entry that only writes through a relation still has work to do.\n if (!Object.keys(input).length && !ops) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n ops,\n filters: where\n ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n };\n });\n\n const returning = entries.some((entry) => entry.ops)\n ? nested!.withJoinColumns(\n tableName,\n mergedOps(entries.map((entry) => ({ ops: entry.ops ?? {} }))),\n {\n ...columns,\n },\n table,\n )\n : columns;\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 const perEntry: Record<string, any>[][] = await 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)) }\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);\n }\n results.push(rows);\n }\n return results;\n });\n\n const flatRows = perEntry.flat();\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, flatRows, pkNames, withParams)\n : flatRows;\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 } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateDelete = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n single: boolean,\n requireWhere: boolean,\n filterCtx?: RelationFilterBase,\n selectionCtx?: SelectionCtx,\n txCtx?: MutationTxCtx,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { where } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const columns = extractSelectedColumnsFromTreeSQLFormat<PgColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n selectionCtx,\n );\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) as any;\n\n const result = await query;\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row!`);\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 } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\ntype SchemaEntry = Table<any> | View<string, boolean, any>;\n\nexport function generateSchemaData<\n TDrizzleInstance extends PgAsyncDatabase<any, any>,\n TRelations extends TablesRelationalConfig,\n TSchema extends Record<string, SchemaEntry>,\n>(\n db: TDrizzleInstance,\n schema: TSchema,\n relations: TRelations,\n options: SchemaGeneratorOptions,\n): GeneratedEntities<TDrizzleInstance, TSchema> {\n const {\n relationsDepthLimit,\n prefixes,\n suffixes,\n conflictDoNothing,\n typeNameMapper,\n shouldEagerLoad,\n features,\n complexity,\n limits,\n } = options;\n const schemaEntries = Object.entries(schema);\n const tableEntries = schemaEntries.filter(([_key, value]) => is(value, PgTable)) as [string, PgTable][];\n const tables = Object.fromEntries(tableEntries) as Record<string, PgTable>;\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\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 // 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, pgPrimaryKeyPropNames);\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 const filterCtx: RelationFilterBase = { tables, relationMap: namedRelations };\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(\n db,\n tables,\n 'nulls-largest',\n filterCtx,\n limits,\n );\n\n // Fresh cache per generateSchemaData call — prevents type name collisions\n // when buildSchema() is called multiple times.\n const cacheCtx: TypeCacheCtx = {\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 features,\n };\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) => getUniqueColumnSets(target as PgTable, getTableConfig),\n (target) => pgPrimaryKeyPropNames(target as PgTable),\n extractRelationJoinColumns,\n )\n : undefined;\n const nestedTypes = nestedPlans\n ? createNestedWriteTypes({ plans: nestedPlans, cacheCtx, typeNameMapper, insertPrefix: prefixes.insert })\n : undefined;\n const nestedRuntime = nestedPlans ? createNestedWriteRuntime({ plans: nestedPlans, filterCtx }) : undefined;\n\n // Left undefined when the feature is off — generateTableTypes then emits no\n // `${relation}Aggregate` fields at all.\n const relationAggregateFactory: RelationAggregateFactory | undefined = features.relationAggregates\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx)\n : undefined;\n\n const queries: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const mutations: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n\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 const mutationTxCtx = createMutationTxCtx(options.transactions);\n\n const gqlSchemaTypes = Object.fromEntries(\n Object.entries(tables).map(([tableName, _table]) => [\n tableName,\n generateTableTypes(\n tableName,\n tables,\n namedRelations,\n true,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n prefixes.insert,\n prefixes.update,\n resolverFactory,\n relationAggregateFactory,\n nestedTypes,\n ),\n ]),\n );\n\n const inputs: Record<string, GraphQLInputObjectType> = {};\n const outputs: Record<string, GraphQLObjectType> = {};\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n const { insertInput, updateInput, tableFilters, tableOrder } = tableTypes.inputs;\n const { selectSingleOutput, selectArrOutput, singleTableItemOutput, arrTableItemOutput } = tableTypes.outputs;\n\n // Compute field names using the mapper logic\n const {\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 deleteCountFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\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 features.distinct,\n limits,\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 );\n const insertArrGenerated = features.insert\n ? generateInsertArray(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n insertInput,\n createArrayFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n mutationTxCtx,\n nestedRuntime,\n limits,\n )\n : undefined;\n const insertSingleGenerated = features.insert\n ? generateInsertSingle(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n insertInput,\n createSingleFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n mutationTxCtx,\n nestedRuntime,\n limits,\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 = features.upsert ? getUniqueColumnSets(schema[tableName] as PgTable, getTableConfig) : [];\n const onConflictInput = features.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as PgTable,\n typeName,\n uniqueSets,\n tableFilters,\n withTarget: true,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n insertInput,\n onConflictInput,\n uniqueSets,\n upsertArrayFieldName,\n typeName,\n false,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n )\n : undefined;\n const upsertSingleGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n insertInput,\n onConflictInput,\n uniqueSets,\n upsertSingleFieldName,\n typeName,\n true,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n )\n : undefined;\n const updateGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateFieldName,\n typeName,\n false,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n )\n : undefined;\n const updateSingleGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n features.update && features.updateMany\n ? generateUpdateManyInput({ typeName, updatePrefix: prefixes.update, updateInput, tableFilters })\n : undefined;\n const updateManyGenerated = updateManyInput\n ? generateUpdateMany(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n updateManyInput,\n updateManyFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n )\n : undefined;\n const deleteGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n deleteFieldName,\n typeName,\n false,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n )\n : undefined;\n const deleteSingleGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n deleteSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n )\n : undefined;\n // The count variants are the plural write with its payload left off, so each follows the\n // same feature switch as the write it mirrors.\n const updateCountGenerated =\n features.update && features.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as PgTable,\n kind: 'update',\n setArgs: updateInput,\n filterArgs: tableFilters,\n fieldName: updateCountFieldName,\n requireWhere: features.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n nested: nestedRuntime,\n })\n : undefined;\n const deleteCountGenerated =\n features.delete && features.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as PgTable,\n kind: 'delete',\n filterArgs: tableFilters,\n fieldName: deleteCountFieldName,\n requireWhere: features.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n })\n : undefined;\n const aggregateType = features.aggregates\n ? generateAggregateTypes(schema[tableName] as PgTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = features.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as PgTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n features.aggregates && features.groupBy\n ? generateGroupByType(schema[tableName] as PgTable, tableName, typeName, cacheCtx)\n : undefined;\n const groupByEnum = groupByType\n ? generateGroupByEnum(schema[tableName] as PgTable, tableName, typeName)\n : undefined;\n const havingInput = groupByEnum\n ? generateHavingInput(schema[tableName] as PgTable, tableName, typeName)\n : undefined;\n const groupByGenerated =\n groupByType && groupByEnum && havingInput\n ? generateGroupBy(\n db,\n tableName,\n schema[tableName] as PgTable,\n typeName,\n groupByFieldName,\n tableFilters,\n groupByEnum,\n havingInput,\n filterCtx,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n ...(complexity ? { extensions: { complexity: listFieldComplexity(complexity, limits?.(tableName)) } } : {}),\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (insertArrGenerated) {\n mutations[insertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: insertArrGenerated.args,\n resolve: insertArrGenerated.resolver,\n };\n }\n if (insertSingleGenerated) {\n mutations[insertSingleGenerated.name] = {\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 args: insertSingleGenerated.args,\n resolve: insertSingleGenerated.resolver,\n };\n }\n if (upsertArrGenerated) {\n mutations[upsertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: upsertArrGenerated.args,\n resolve: upsertArrGenerated.resolver,\n };\n }\n if (upsertSingleGenerated) {\n mutations[upsertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: upsertSingleGenerated.args,\n resolve: upsertSingleGenerated.resolver,\n };\n }\n if (updateGenerated) {\n mutations[updateGenerated.name] = {\n type: arrTableItemOutput,\n args: updateGenerated.args,\n resolve: updateGenerated.resolver,\n };\n }\n if (updateManyGenerated) {\n mutations[updateManyGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(singleTableItemOutput)),\n args: updateManyGenerated.args,\n resolve: updateManyGenerated.resolver,\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 if (updateSingleGenerated) {\n mutations[updateSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: updateSingleGenerated.args,\n resolve: updateSingleGenerated.resolver,\n };\n }\n if (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.resolver,\n };\n }\n if (deleteSingleGenerated) {\n mutations[deleteSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: deleteSingleGenerated.args,\n resolve: deleteSingleGenerated.resolver,\n };\n }\n if (updateCountGenerated) {\n mutations[updateCountGenerated.name] = {\n type: new GraphQLNonNull(GraphQLInt),\n args: updateCountGenerated.args,\n resolve: updateCountGenerated.resolver,\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 if (deleteCountGenerated) {\n mutations[deleteCountGenerated.name] = {\n type: new GraphQLNonNull(GraphQLInt),\n args: deleteCountGenerated.args,\n resolve: deleteCountGenerated.resolver,\n description:\n 'How many rows the delete removed. The rows themselves are not read back, which is the point of this mutation.',\n };\n }\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 ...(features.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(features.update ? [updateInput] : []),\n ...(updateManyInput ? [updateManyInput] : []),\n tableFilters,\n tableOrder,\n ];\n activeInputs.forEach((e) => {\n inputs[e.name] = e;\n });\n outputs[selectSingleOutput.name] = selectSingleOutput;\n outputs[singleTableItemOutput.name] = singleTableItemOutput;\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 // 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 (mutationTxCtx) {\n for (const name of Object.keys(mutations)) {\n mutationTxCtx.fieldNames.add(name);\n }\n }\n\n const fieldResolvers: Record<string, Record<string, any>> = {};\n for (const [tableName, tableRelations] of Object.entries(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 = 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 { queries, mutations, inputs, types: outputs, fieldResolvers } as any;\n}\n","// @ts-nocheck — drizzle-orm 1.0 type compat not guaranteed, same as its sibling builders\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, is, One, type Table } from 'drizzle-orm';\nimport {\n GraphQLBoolean,\n GraphQLError,\n GraphQLInputObjectType,\n type GraphQLInputType,\n GraphQLList,\n GraphQLNonNull,\n} from 'graphql';\nimport { capitalize } from '../case-ops/index.ts';\nimport { remapFromGraphQLSingleInput } from '../data-mappers/index.ts';\nimport { drizzleColumnToGraphQLType } from '../type-converter/index.ts';\nimport {\n extractFilters,\n type RelationFilterBase,\n relationFilterCtx,\n resolveTypeName,\n type TypeCacheCtx,\n type TypeNameMapper,\n} from './common.ts';\nimport type { TableNamedRelations } from './types.ts';\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};\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/**\n * Which relations of which tables can be written through.\n *\n * Skipped, and so absent from the generated inputs rather than failing at runtime:\n * `.through()` (many-to-many) relations, whose write target is a junction table this pass\n * does not model; relations whose join columns cannot be read off the drizzle relation;\n * and relations where neither join column is unique, which leaves no way to tell which\n * 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): 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 if ((relation as any).through) {\n continue;\n }\n\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n if (!targetTable) {\n continue;\n }\n\n const joinColumns = extractJoinColumns(relEntry, table, targetTable);\n if (!joinColumns) {\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\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 };\n }\n\n if (Object.keys(tablePlans).length) {\n plans[tableName] = tablePlans;\n }\n }\n\n return plans;\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 insertPrefix: string;\n}): NestedWriteTypes => {\n const { plans, cacheCtx, typeNameMapper, insertPrefix } = params;\n const wrapperCache = new Map<string, GraphQLInputObjectType>();\n const payloadCache = new Map<string, GraphQLInputObjectType>();\n\n /**\n * `Create<Type><Relation>Input` — the row a nested `create` inserts. Built from the target's\n * columns rather than from its create input: the join column this relation fills in is left\n * out (setting it by hand could point the new row somewhere other than its parent), and the\n * nesting stops here, so the type carries no relation fields of its own.\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 const fields = Object.fromEntries(\n Object.entries(getColumns(plan.targetTable))\n .filter(([columnName]) => columnName !== omitted)\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: `${capitalize(insertPrefix)}${typeName}${capitalize(plan.relationName)}Input`,\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 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 payload = payloadType(tableName, typeName, plan);\n const targetTypeName = resolveTypeName(plan.targetTableName, typeNameMapper);\n const fields: Record<string, { type: GraphQLInputType; description: string }> = {};\n\n if (plan.isOne) {\n fields['create'] = { type: payload, description: `Insert a ${targetTypeName} row and attach it` };\n if (filters) {\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 && plan.canDetach) {\n fields['disconnect'] = {\n type: GraphQLBoolean,\n description: `Detach the currently attached ${targetTypeName} row, leaving it in place`,\n };\n }\n } else {\n fields['create'] = { type: listOf(payload), description: `Insert these ${targetTypeName} rows and attach them` };\n if (filters) {\n fields['connect'] = {\n type: listOf(filters),\n description: `Attach every existing ${targetTypeName} row these match`,\n };\n if (forUpdate && plan.canDetach) {\n fields['disconnect'] = {\n type: listOf(filters),\n description: `Detach every attached ${targetTypeName} row these match, leaving the rows in place`,\n };\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\n // `create` alone is still a usable relation field, but a relation with nothing on it at\n // all cannot happen: `create` is unconditional.\n const type = new GraphQLInputObjectType({\n name: `${typeName}${capitalize(plan.relationName)}Nested${forUpdate ? 'Update' : 'Create'}Input`,\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 (plan.fkSide === 'parent' && !isOptionalOnInsert(plan.localCol)) {\n relaxed.add(plan.localColPropName);\n }\n }\n return relaxed.size ? relaxed : NO_COLUMNS;\n },\n };\n};\n\n// ── runtime ──────────────────────────────────────────────────────────────────\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: (executor: any, tableName: string, ops: NestedOps) => 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 ) => 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\nexport const createNestedWriteRuntime = (params: {\n plans: NestedWritePlans;\n filterCtx: RelationFilterBase | undefined;\n}): NestedWriteRuntime => {\n const { plans, filterCtx } = params;\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 = (plan: NestedRelationPlan, filter: Record<string, any>, operation: string) => {\n const condition = extractFilters(\n plan.targetTable,\n plan.targetTableName,\n filter,\n relationFilterCtx(filterCtx, plan.targetTableName),\n );\n if (!condition) {\n throw new GraphQLError(\n `Drizzle-GraphQL Error: '${operation}' on '${plan.relationName}' needs a filter that selects rows — it was given one that matches everything.`,\n );\n }\n return condition;\n };\n\n const assertSingleOperation = (plan: NestedRelationPlan, op: Record<string, any>) => {\n const supplied = ['create', 'connect', 'disconnect'].filter((key) => op[key] !== undefined && op[key] !== null);\n if (supplied.length > 1) {\n throw new GraphQLError(\n `Drizzle-GraphQL Error: '${plan.relationName}' takes one of ${supplied.join(', ')} at a time — it holds a single row.`,\n );\n }\n };\n\n const detachAll = async (executor: any, plan: NestedRelationPlan, key: any) =>\n executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: null })\n .where(eq(plan.foreignCol, key));\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) => {\n const tablePlans = plans[tableName];\n const patch: Record<string, any> = {};\n if (!tablePlans) {\n return patch;\n }\n\n for (const [relationName, op] of Object.entries(ops)) {\n const plan = tablePlans[relationName];\n if (!plan || plan.fkSide !== 'parent') {\n continue;\n }\n assertSingleOperation(plan, op);\n\n if (op['create'] !== undefined) {\n const values = remapFromGraphQLSingleInput({ ...op['create'] }, plan.targetTable);\n const inserted = await executor.insert(plan.targetTable).values(values).returning();\n const created = inserted[0];\n if (!created) {\n throw new GraphQLError(\n `Drizzle-GraphQL Error: 'create' on '${relationName}' inserted no row, so there is nothing to attach.`,\n );\n }\n patch[plan.localColPropName] = created[plan.foreignColPropName];\n } else if (op['connect'] !== undefined) {\n const rows = await executor\n .select()\n .from(plan.targetTable)\n .where(conditionOf(plan, op['connect'], 'connect'));\n if (rows.length !== 1) {\n throw new GraphQLError(\n `Drizzle-GraphQL Error: 'connect' on '${relationName}' matched ${rows.length} rows — it attaches a single row, so its filter must match exactly one.`,\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) => {\n const tablePlans = plans[tableName];\n if (!tablePlans) {\n return;\n }\n\n for (const [relationName, op] of Object.entries(ops)) {\n const plan = tablePlans[relationName];\n if (!plan || plan.fkSide !== 'child') {\n continue;\n }\n if (plan.isOne) {\n assertSingleOperation(plan, op);\n }\n\n for (const parentRow of parentRows) {\n const key = parentRow?.[plan.localColPropName];\n if (key === undefined || key === null) {\n throw new GraphQLError(\n `Drizzle-GraphQL Error: cannot write through '${relationName}': the ${tableName} row has no '${plan.localColPropName}' value to attach to.`,\n );\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);\n for (const filter of asArray(op['set'])) {\n await executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: key })\n .where(conditionOf(plan, filter, 'set'));\n }\n }\n\n if (op['disconnect'] !== undefined) {\n if (plan.isOne) {\n if (op['disconnect'] === true) {\n await detachAll(executor, plan, key);\n }\n } else {\n for (const filter of asArray(op['disconnect'])) {\n await executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: null })\n .where(and(eq(plan.foreignCol, key), conditionOf(plan, filter, 'disconnect')));\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 attaches = op['connect'] !== undefined || op['create'] !== undefined;\n if (plan.isOne && attaches && plan.canDetach && op['set'] === undefined) {\n await detachAll(executor, plan, key);\n }\n\n if (op['connect'] !== undefined) {\n for (const filter of asArray(op['connect'])) {\n await executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: key })\n .where(conditionOf(plan, filter, 'connect'));\n }\n }\n\n if (op['create'] !== undefined) {\n const rows = asArray(op['create']).map((row) => ({\n ...remapFromGraphQLSingleInput({ ...row }, plan.targetTable),\n [plan.foreignColPropName]: key,\n }));\n if (rows.length) {\n await executor.insert(plan.targetTable).values(rows);\n }\n }\n }\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 * 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}): Promise<Record<string, any>[]> => {\n const { executor, runtime, tableName, entries, remapValues, write } = 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);\n const written = await write(tx, { ...remapValues(entry.columns), ...patch });\n await runtime.applyChildSide(tx, tableName, entry.ops, written);\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}): Promise<Record<string, any>[]> => {\n const { executor, runtime, tableName, columns, ops, remapValues, write } = params;\n\n return executor.transaction(async (tx: any) => {\n const patch = await runtime.applyParentSide(tx, tableName, ops);\n const rows = await write(tx, { ...remapValues(columns), ...patch });\n await runtime.applyChildSide(tx, tableName, ops, rows);\n return rows;\n });\n};\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { is, One, type Table } from 'drizzle-orm';\nimport type { RelationalQueryBuilder } from 'drizzle-orm/mysql-core/query-builders/query';\nimport { type BaseSQLiteDatabase, getTableConfig, type SQLiteColumn, SQLiteTable } from 'drizzle-orm/sqlite-core';\nimport type { GraphQLFieldConfig, GraphQLFieldConfigArgumentMap, GraphQLResolveInfo, ThunkObjMap } from 'graphql';\nimport {\n GraphQLError,\n type GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n type GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\n\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n aggregateFieldComplexity,\n applyLimitPolicy,\n assertSingleMatch,\n attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createMutationTxCtx,\n createRelationResolverFactory,\n eagerLoadMutationRelations,\n excludedColumnRef,\n extractFilters,\n extractRelationJoinColumns,\n extractRequiredFilters,\n extractSelectedColumnsFromTreeSQLFormat,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n generateUpdateManyInput,\n generateWriteCount,\n getPrimaryKeyPropNamesFromConfig,\n getUniqueColumnSets,\n type LimitPolicyFor,\n listFieldComplexity,\n type MutationTxCtx,\n type OnConflictArg,\n prepareMutationRelationColumns,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n relationFilterCtx,\n resolveConflictPlan,\n resolveQueryExecutor,\n runMutation,\n runRelationalSelect,\n type SelectionCtx,\n selectArrayArgs,\n selectSingleArgs,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n} from '../builders/common.ts';\nimport {\n remapFromGraphQLArrayInput,\n remapFromGraphQLSingleInput,\n remapToGraphQLArrayOutput,\n remapToGraphQLSingleOutput,\n} from '../data-mappers/index.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} from './aggregates.ts';\nimport { remapUpdateInput } from './field-updates.ts';\nimport {\n buildNestedWritePlans,\n createNestedWriteRuntime,\n createNestedWriteTypes,\n mergedOps,\n type NestedWriteRuntime,\n updateWithNestedOps,\n writeWithNestedOps,\n} from './nested-writes.ts';\nimport type {\n CreatedResolver,\n Filters,\n SchemaGeneratorOptions,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst generateSelectArray = (\n db: BaseSQLiteDatabase<any, any, any, 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 = true,\n limits?: LimitPolicyFor,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const table = tables[tableName]!;\n const limitPolicy = limits?.(tableName);\n const pkNames = sqlitePrimaryKeyPropNames(table as SQLiteTable);\n const queryArgs = selectArrayArgs(\n orderArgs,\n filterArgs,\n distinctEnabled ? generateDistinctEnum(table, typeName) : undefined,\n );\n\n return {\n name: fieldName,\n resolver: async (_source: any, args: Partial<TableSelectArgs>, context: any, info: GraphQLResolveInfo) => {\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,\n typeNameMapper,\n parsedInfo,\n ...args,\n limit: applyLimitPolicy(args.limit, limitPolicy, fieldName),\n single: false,\n filterCtx,\n limits,\n pkNames,\n db: executor,\n // SQLite sorts NULLs as the smallest values (first in ASC).\n nullOrdering: 'nulls-smallest',\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateSelectSingle = (\n db: BaseSQLiteDatabase<any, any, any, 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): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const queryArgs = selectSingleArgs(orderArgs, filterArgs);\n\n const table = tables[tableName]!;\n const pkNames = sqlitePrimaryKeyPropNames(table as SQLiteTable);\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\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,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n limits,\n pkNames,\n db: executor,\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\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\nconst generateInsertArray = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n conflictDoNothing: boolean = false,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n limits?: LimitPolicyFor,\n): CreatedResolver => {\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: 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 = sqlitePrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any>[] }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n if (!args.values.length) {\n throw new GraphQLError('No values were provided!');\n }\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 ? args.values.map((values) => nested.split(tableName, values))\n : undefined;\n const nestedEntries = entries?.some((entry) => nested!.hasOps(entry.ops)) ? entries : undefined;\n const input = nestedEntries\n ? []\n : remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : args.values, table);\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n limits,\n });\n\n const returning = nestedEntries\n ? nested!.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table)\n : columns;\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 result = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) => remapFromGraphQLSingleInput(values, table),\n write: (tx, values) => runInsert(tx, [values]),\n })\n : await runInsert(executor, input);\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateInsertSingle = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n conflictDoNothing: boolean = false,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n limits?: LimitPolicyFor,\n): CreatedResolver => {\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: new GraphQLNonNull(baseType),\n },\n };\n\n // Derived once at build time — PK prop names don't change per request.\n const pkNames = sqlitePrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const entry = nested?.enabled(tableName) ? nested.split(tableName, args.values) : undefined;\n const nestedEntry = entry && nested!.hasOps(entry.ops) ? entry : undefined;\n const input = nestedEntry ? {} : remapFromGraphQLSingleInput(entry ? entry.columns : args.values, table);\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n limits,\n });\n const returning = nestedEntry\n ? nested!.withJoinColumns(tableName, nestedEntry.ops, { ...columns }, table)\n : columns;\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 result = nestedEntry\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: [nestedEntry],\n remapValues: (values) => remapFromGraphQLSingleInput(values, table),\n write: runInsert,\n })\n : await runInsert(executor, input);\n\n if (!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 new GraphQLError(`${fieldName}: the insert returned no row.`);\n }\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\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 */\nconst generateUpsert = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n onConflictType: GraphQLInputObjectType,\n uniqueSets: string[][],\n fieldName: string,\n typeName: string,\n single: boolean,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n limits?: LimitPolicyFor,\n): CreatedResolver => {\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 = sqlitePrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { values: Record<string, any> | Record<string, any>[]; onConflict?: OnConflictArg },\n context,\n info,\n ) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const supplied = single ? [args.values as Record<string, any>] : (args.values as Record<string, any>[]);\n if (!supplied.length) {\n throw new GraphQLError('No values were provided!');\n }\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 input = nestedEntries\n ? []\n : remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table);\n\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n limits,\n });\n\n const returning = nestedEntries\n ? nested!.withJoinColumns(tableName, mergedOps(nestedEntries), { ...columns }, table)\n : columns;\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 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: plan.setWhere }) as any);\n\n return (await query) as Record<string, any>[];\n };\n\n const result = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) => remapFromGraphQLSingleInput(values, table),\n write: (tx, values) => runUpsert(tx, [values]),\n })\n : await runUpsert(executor, input);\n\n if (single && !result[0]) {\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return single\n ? remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap)\n : remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateUpdate = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n setArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n single: boolean,\n requireWhere: boolean,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n limits?: LimitPolicyFor,\n): CreatedResolver => {\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 = sqlitePrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table>; set: Record<string, any> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { where, set } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n limits,\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 const input = remapUpdateInput(entry ? entry.columns : set, table, tableName);\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 new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n const returning = nestedOps ? nested!.withJoinColumns(tableName, nestedOps, { ...columns }, table) : columns;\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 result = 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 })\n : await runUpdate(executor, input);\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row!`);\n }\n\n if (single && !result[0]) {\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return single\n ? remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap)\n : remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\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. The result lists each entry's updated rows in entry order, with `null`\n * standing in for an entry whose `where` matched no rows, so the common one-row-per-entry\n * case stays aligned with the input.\n */\nconst generateUpdateMany = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n updateManyInput: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n txCtx?: MutationTxCtx,\n nested?: NestedWriteRuntime,\n limits?: LimitPolicyFor,\n): CreatedResolver => {\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 = sqlitePrimaryKeyPropNames(table);\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { updates: { where?: Filters<Table>; set: Record<string, any> }[] },\n context,\n info,\n ) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { updates } = args;\n if (!updates.length) {\n throw new GraphQLError('No updates were provided!');\n }\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n limits,\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 = 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 = remapUpdateInput(split ? split.columns : set, table, tableName);\n // An entry that only writes through a relation still has work to do.\n if (!Object.keys(input).length && !ops) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n ops,\n filters: where\n ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n };\n });\n\n const anyNested = entries.some((entry) => entry.ops);\n const returning = anyNested\n ? nested!.withJoinColumns(\n tableName,\n mergedOps(entries.map((entry) => ({ ops: entry.ops ?? {} }))),\n { ...columns },\n table,\n )\n : columns;\n\n const runEntry = (tx: any, entry: (typeof entries)[number]) => {\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 (better-sqlite3)\n // executes it immediately, which is the only way the statement still runs\n // inside the synchronous native transaction below.\n return query.returning(returning).all();\n };\n\n // Nested writes need statements interleaved with awaited reads, which only an async\n // driver can do inside a transaction — `features.nestedWrites` rejects a sync driver\n // at build time, so this branch is always on one.\n const runNestedEntry = async (tx: any, entry: (typeof entries)[number]) => {\n const values = entry.ops\n ? { ...entry.set, ...(await nested!.applyParentSide(tx, tableName, entry.ops)) }\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);\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);\n }\n return rows;\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. A sync driver's transaction callback\n // must not be async — it would commit before any awaited statement ran — so the\n // driver kind is probed from the first statement's result instead.\n const perEntry: Record<string, any>[][] = await 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 const flatRows = perEntry.flat();\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, flatRows, pkNames, withParams)\n : flatRows;\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 } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateDelete = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n single: boolean,\n requireWhere: boolean,\n filterCtx?: RelationFilterBase,\n selectionCtx?: SelectionCtx,\n txCtx?: MutationTxCtx,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, info) => {\n try {\n return await runMutation(db, context, info, txCtx, async (executor) => {\n const { where } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const columns = extractSelectedColumnsFromTreeSQLFormat<SQLiteColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n selectionCtx,\n );\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) as any;\n\n const result = await query;\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row!`);\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 } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nexport const generateSchemaData = <\n TDrizzleInstance extends BaseSQLiteDatabase<any, 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> => {\n const {\n relationsDepthLimit,\n prefixes,\n suffixes,\n conflictDoNothing,\n typeNameMapper,\n shouldEagerLoad,\n features,\n complexity,\n limits,\n } = options;\n const rawSchema = schema;\n const schemaEntries = Object.entries(rawSchema);\n\n const tableEntries = schemaEntries.filter(([_key, value]) => is(value, SQLiteTable)) as [string, SQLiteTable][];\n const tables = Object.fromEntries(tableEntries) as Record<string, SQLiteTable>;\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\n // Build namedRelations from the drizzle-orm v1 relations config.\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Record each relation target's (composite-aware) primary key for deterministic\n // paginated ordering. Must run before pruning / type generation (shared entry objects).\n attachTargetPrimaryKeys(namedRelations, tables, sqlitePrimaryKeyPropNames);\n // Pruned map for query/mutation resolvers' `with:`; type generation keeps the full map.\n const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);\n\n const filterCtx: RelationFilterBase = { tables, relationMap: namedRelations };\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(\n db,\n tables,\n 'nulls-smallest',\n filterCtx,\n limits,\n );\n\n // Fresh cache per generateSchemaData call — prevents type name collisions\n // when buildSchema() is called multiple times.\n const cacheCtx: TypeCacheCtx = {\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 features,\n };\n\n // A nested write interleaves reads and writes inside one transaction, which a synchronous\n // driver cannot do — its transaction callback commits before an awaited statement runs.\n if (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\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) => getUniqueColumnSets(target as SQLiteTable, getTableConfig),\n (target) => sqlitePrimaryKeyPropNames(target as SQLiteTable),\n extractRelationJoinColumns,\n )\n : undefined;\n const nestedTypes = nestedPlans\n ? createNestedWriteTypes({ plans: nestedPlans, cacheCtx, typeNameMapper, insertPrefix: prefixes.insert })\n : undefined;\n const nestedRuntime = nestedPlans ? createNestedWriteRuntime({ plans: nestedPlans, filterCtx }) : undefined;\n\n // Left undefined when the feature is off — generateTableTypes then emits no\n // `${relation}Aggregate` fields at all.\n const relationAggregateFactory: RelationAggregateFactory | undefined = features.relationAggregates\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx)\n : undefined;\n\n const queries: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const mutations: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n\n // A synchronous driver (e.g. better-sqlite3) commits the moment its transaction callback\n // returns, so a transaction cannot be held open across resolver calls.\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 // 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 const mutationTxCtx = createMutationTxCtx(options.transactions);\n\n const gqlSchemaTypes = Object.fromEntries(\n Object.entries(tables).map(([tableName, _table]) => [\n tableName,\n generateTableTypes(\n tableName,\n tables,\n namedRelations,\n true,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n prefixes.insert,\n prefixes.update,\n resolverFactory,\n relationAggregateFactory,\n nestedTypes,\n ),\n ]),\n );\n\n const inputs: Record<string, GraphQLInputObjectType> = {};\n const outputs: Record<string, GraphQLObjectType> = {};\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n const { insertInput, updateInput, tableFilters, tableOrder } = tableTypes.inputs;\n const { selectSingleOutput, selectArrOutput, singleTableItemOutput, arrTableItemOutput } = tableTypes.outputs;\n\n // Compute field names using the mapper logic\n const {\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 deleteCountFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\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 features.distinct,\n limits,\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 );\n const insertArrGenerated = features.insert\n ? generateInsertArray(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n insertInput,\n createArrayFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n mutationTxCtx,\n nestedRuntime,\n limits,\n )\n : undefined;\n const insertSingleGenerated = features.insert\n ? generateInsertSingle(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n insertInput,\n createSingleFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n mutationTxCtx,\n nestedRuntime,\n limits,\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 = features.upsert ? getUniqueColumnSets(schema[tableName] as SQLiteTable, getTableConfig) : [];\n const onConflictInput = features.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as SQLiteTable,\n typeName,\n uniqueSets,\n tableFilters,\n withTarget: true,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n insertInput,\n onConflictInput,\n uniqueSets,\n upsertArrayFieldName,\n typeName,\n false,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n )\n : undefined;\n const upsertSingleGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n insertInput,\n onConflictInput,\n uniqueSets,\n upsertSingleFieldName,\n typeName,\n true,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n )\n : undefined;\n const updateGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateFieldName,\n typeName,\n false,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n )\n : undefined;\n const updateSingleGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n features.update && features.updateMany\n ? generateUpdateManyInput({ typeName, updatePrefix: prefixes.update, updateInput, tableFilters })\n : undefined;\n const updateManyGenerated = updateManyInput\n ? generateUpdateMany(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n updateManyInput,\n updateManyFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n )\n : undefined;\n const deleteGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n deleteFieldName,\n typeName,\n false,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n )\n : undefined;\n const deleteSingleGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n deleteSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n )\n : undefined;\n // The count variants are the plural write with its payload left off, so each follows the\n // same feature switch as the write it mirrors.\n const updateCountGenerated =\n features.update && features.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as SQLiteTable,\n kind: 'update',\n setArgs: updateInput,\n filterArgs: tableFilters,\n fieldName: updateCountFieldName,\n requireWhere: features.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n nested: nestedRuntime,\n })\n : undefined;\n const deleteCountGenerated =\n features.delete && features.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as SQLiteTable,\n kind: 'delete',\n filterArgs: tableFilters,\n fieldName: deleteCountFieldName,\n requireWhere: features.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n })\n : undefined;\n const aggregateType = features.aggregates\n ? generateAggregateTypes(schema[tableName] as SQLiteTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = features.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n features.aggregates && features.groupBy\n ? generateGroupByType(schema[tableName] as SQLiteTable, tableName, typeName, cacheCtx)\n : undefined;\n const groupByEnum = groupByType\n ? generateGroupByEnum(schema[tableName] as SQLiteTable, tableName, typeName)\n : undefined;\n const havingInput = groupByEnum\n ? generateHavingInput(schema[tableName] as SQLiteTable, tableName, typeName)\n : undefined;\n const groupByGenerated =\n groupByType && groupByEnum && havingInput\n ? generateGroupBy(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n typeName,\n groupByFieldName,\n tableFilters,\n groupByEnum,\n havingInput,\n filterCtx,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n ...(complexity ? { extensions: { complexity: listFieldComplexity(complexity, limits?.(tableName)) } } : {}),\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (insertArrGenerated) {\n mutations[insertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: insertArrGenerated.args,\n resolve: insertArrGenerated.resolver,\n };\n }\n if (insertSingleGenerated) {\n mutations[insertSingleGenerated.name] = {\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 args: insertSingleGenerated.args,\n resolve: insertSingleGenerated.resolver,\n };\n }\n if (upsertArrGenerated) {\n mutations[upsertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: upsertArrGenerated.args,\n resolve: upsertArrGenerated.resolver,\n };\n }\n if (upsertSingleGenerated) {\n mutations[upsertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: upsertSingleGenerated.args,\n resolve: upsertSingleGenerated.resolver,\n };\n }\n if (updateGenerated) {\n mutations[updateGenerated.name] = {\n type: arrTableItemOutput,\n args: updateGenerated.args,\n resolve: updateGenerated.resolver,\n };\n }\n if (updateManyGenerated) {\n mutations[updateManyGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(singleTableItemOutput)),\n args: updateManyGenerated.args,\n resolve: updateManyGenerated.resolver,\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 if (updateSingleGenerated) {\n mutations[updateSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: updateSingleGenerated.args,\n resolve: updateSingleGenerated.resolver,\n };\n }\n if (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.resolver,\n };\n }\n if (deleteSingleGenerated) {\n mutations[deleteSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: deleteSingleGenerated.args,\n resolve: deleteSingleGenerated.resolver,\n };\n }\n if (updateCountGenerated) {\n mutations[updateCountGenerated.name] = {\n type: new GraphQLNonNull(GraphQLInt),\n args: updateCountGenerated.args,\n resolve: updateCountGenerated.resolver,\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 if (deleteCountGenerated) {\n mutations[deleteCountGenerated.name] = {\n type: new GraphQLNonNull(GraphQLInt),\n args: deleteCountGenerated.args,\n resolve: deleteCountGenerated.resolver,\n description:\n 'How many rows the delete removed. The rows themselves are not read back, which is the point of this mutation.',\n };\n }\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 ...(features.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(features.update ? [updateInput] : []),\n ...(updateManyInput ? [updateManyInput] : []),\n tableFilters,\n tableOrder,\n ];\n activeInputs.forEach((e) => {\n inputs[e.name] = e;\n });\n outputs[selectSingleOutput.name] = selectSingleOutput;\n outputs[singleTableItemOutput.name] = singleTableItemOutput;\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 // 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 (mutationTxCtx) {\n for (const name of Object.keys(mutations)) {\n mutationTxCtx.fieldNames.add(name);\n }\n }\n\n const fieldResolvers: Record<string, Record<string, any>> = {};\n for (const [tableName, tableRelations] of Object.entries(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 = 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 { queries, mutations, inputs, types: outputs, fieldResolvers } as any;\n};\n"],"mappings":";AAAA,SAAS,MAAAA,WAAU;AACnB,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC;AAAA,EAGE,qBAAAC;AAAA,EACA;AAAA,OAEK;;;ACQP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,6BAAAC;AAAA,EACA,cAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,MAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,OAAAC;AAAA,EACA;AAAA,EACA;AAAA,EAEA,OAAAC;AAAA,OACK;AAEP;AAAA,EACE,kBAAAC;AAAA,EACA,mBAAAC;AAAA,EACA,gBAAAC;AAAA,EACA,gBAAAC;AAAA,EACA,0BAAAC;AAAA,EACA,cAAAC;AAAA,EACA,eAAAC;AAAA,EACA,kBAAAC;AAAA,EACA,qBAAAC;AAAA,EAEA,iBAAAC;AAAA,OACK;;;AC9DP,IAAM,sBAAsB,uBAAO,yBAAyB;AAI5D,IAAM,cAAN,MAAwB;AAAA,EAItB,YAA6B,SAAwB;AAAxB;AAAA,EAAyB;AAAA,EAH9C,QAAkF,CAAC;AAAA,EACnF,YAAY;AAAA,EAIpB,KAAK,KAAoB;AACvB,WAAO,IAAI,QAAW,CAAC,SAAS,WAAW;AACzC,WAAK,MAAM,KAAK,EAAE,KAAK,SAAS,OAAO,CAAC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N,QAAQ;AAAA,IACV,CAAC;AAED,wBAAoB,WAAW;AAAA,EACjC;AAEA,QAAM,eAAe,IAAI,cAAc,mBAAmB;AAE1D,SAAO,EAAE,QAAQ,cAAc,UAAU,gBAAgB;AAC3D;","names":["is","GraphQLObjectType","extractExtendedColumnType","getColumns","is","One","sql","GraphQLBoolean","GraphQLEnumType","GraphQLError","GraphQLFloat","GraphQLInputObjectType","GraphQLInt","GraphQLList","GraphQLNonNull","GraphQLObjectType","GraphQLString","getTableColumns","is","GraphQLError","GraphQLScalarType","GraphQLScalarType","is","GraphQLError","getTableColumns","GraphQLError","GraphQLFloat","GraphQLInputObjectType","GraphQLInt","GraphQLList","GraphQLNonNull","GraphQLInt","GraphQLFloat","GraphQLList","GraphQLInputObjectType","GraphQLNonNull","GraphQLError","getColumns","GraphQLError","getColumns","sql","GraphQLNonNull","GraphQLEnumType","GraphQLInputObjectType","GraphQLInt","GraphQLList","GraphQLBoolean","GraphQLFloat","GraphQLString","extractExtendedColumnType","is","One","GraphQLObjectType","isJsonColumn","aliasedTable","getTableConfig","targetNames","set","result","is","One","GraphQLBoolean","GraphQLError","GraphQLInt","GraphQLList","GraphQLNonNull","GraphQLObjectType","parseResolveInfo","and","eq","extractExtendedColumnType","getColumns","gt","gte","inArray","lt","lte","ne","GraphQLError","GraphQLFloat","GraphQLInputObjectType","GraphQLInt","GraphQLList","GraphQLNonNull","GraphQLObjectType","getColumns","GraphQLList","GraphQLObjectType","extractExtendedColumnType","GraphQLNonNull","GraphQLInt","GraphQLFloat","and","inArray","eq","ne","gt","gte","lt","lte","GraphQLInputObjectType","GraphQLError","parseResolveInfo","GraphQLNonNull","GraphQLList","GraphQLError","is","GraphQLObjectType","GraphQLBoolean","GraphQLInt","One","and","getColumns","is","One","getTableConfig","GraphQLError","GraphQLInt","GraphQLList","GraphQLNonNull","parseResolveInfo","and","eq","getColumns","is","One","GraphQLBoolean","GraphQLError","GraphQLInputObjectType","GraphQLList","GraphQLNonNull","getColumns","is","One","GraphQLInputObjectType","GraphQLList","GraphQLNonNull","GraphQLBoolean","GraphQLError","eq","and","generateSelectArray","parseResolveInfo","GraphQLError","getColumns","and","generateSelectSingle","getTableConfig","generateInsertArray","GraphQLNonNull","GraphQLList","generateInsertSingle","generateUpsert","generateUpdate","generateUpdateMany","generateDelete","generateSchemaData","is","GraphQLInt","One","is","One","getTableConfig","GraphQLError","GraphQLInt","GraphQLList","GraphQLNonNull","parseResolveInfo","generateSelectArray","parseResolveInfo","generateSelectSingle","getTableConfig","generateInsertArray","GraphQLNonNull","GraphQLList","GraphQLError","generateInsertSingle","generateUpsert","generateUpdate","generateUpdateMany","results","generateDelete","generateSchemaData","is","GraphQLInt","One","config","is","generateSchemaData","GraphQLObjectType"]}