@vantreeseba/drizzle-graphql 7.7.0 → 7.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +160 -1
- package/dist/README.md +160 -1
- package/dist/index.cjs +1589 -855
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +148 -3
- package/dist/index.d.ts +148 -3
- package/dist/index.js +1590 -856
- package/dist/index.js.map +1 -1
- package/dist/package.json +1 -1
- package/package.json +1 -1
package/dist/index.cjs.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/extensions.ts","../src/util/builders/field-updates.ts","../src/util/builders/mysql.ts","../src/util/features.ts","../src/util/builders/aggregates.ts","../src/util/builders/pg.ts","../src/util/builders/nested-writes.ts","../src/util/builders/sqlite.ts","../src/util/selection.ts"],"sourcesContent":["import { getColumns, is, Table } 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 resolveSoftDeleteInfo,\n type SoftDeleteInfo,\n type TablePolicies,\n} from './util/builders/common.ts';\nimport { generateMySQL, generatePG, generateSQLite } from './util/builders/index.ts';\nimport type { SchemaGeneratorOptions } from './util/builders/types.ts';\nimport { singularizeMapper } from './util/case-ops/index.ts';\nimport { resolveTableFeatures } from './util/features.ts';\n\nexport type {\n AggregateResolver,\n AnyDrizzleDB,\n BuildSchemaConfig,\n ComplexityConfig,\n ContextValuesConfig,\n DeleteResolver,\n DeleteSingleResolver,\n ExtractRelations,\n ExtractTableByName,\n ExtractTableRelations,\n ExtractTables,\n FeatureSwitch,\n GeneratedData,\n GeneratedEntities,\n GeneratedInputs,\n GeneratedOutputs,\n InsertArrResolver,\n InsertResolver,\n LimitsConfig,\n MutationReturnlessResult,\n MutationsCore,\n QueriesCore,\n RowScope,\n RowScopeFilter,\n SchemaExclusions,\n SchemaFeatures,\n ScopeConfig,\n SelectResolver,\n SelectSingleResolver,\n SoftDeleteColumn,\n SoftDeleteConfig,\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 { singularizeMapper } from './util/case-ops/index.ts';\nexport type {\n DrizzleExtension,\n DrizzleFieldExtension,\n DrizzleFieldKind,\n DrizzleFieldOperation,\n DrizzleTargetArg,\n DrizzleTypeExtension,\n IdentifiedRows,\n} from './util/extensions.ts';\nexport { drizzleExtension, identifyRows, isDrizzleFieldExtension } from './util/extensions.ts';\nexport {\n GraphQLBigIntString,\n GraphQLDate,\n GraphQLDateTime,\n GraphQLDecimalString,\n GraphQLJSON,\n GraphQLUUID,\n} from './util/scalars/index.ts';\nexport type { ResolveSelectionOptions, SelectionOptions } from './util/selection.ts';\nexport { resolveSelection, selectionToWith } from './util/selection.ts';\nexport type {\n ColumnDeprecator,\n ColumnDescriber,\n ColumnDocInfo,\n ColumnTypeMapper,\n ColumnTypeMapperInfo,\n EnumNameInfo,\n EnumNameMapper,\n 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 restore: config?.prefixes?.restore ?? 'restore',\n };\n\n const suffixes = {\n list: config?.suffixes?.list ?? '',\n single: config?.suffixes?.single ?? 'Single',\n };\n\n // `'singularize'` is the one shipped preset; anything else is the caller's own function.\n const typeNameMapper = config?.typeNameMapper === 'singularize' ? singularizeMapper : config?.typeNameMapper;\n\n // Table keys this build generates for — what a per-table feature predicate is asked about.\n // Excluded tables are dropped up front so no predicate is ever consulted for a table that\n // generates nothing.\n const tableKeys = Object.entries(schema as Record<string, unknown>)\n .filter(([, value]) => is(value, Table))\n .map(([key]) => key);\n const excludedTableNames = new Set(config?.exclude?.tables ?? []);\n const featureTables = tableKeys.filter((key) => !excludedTableNames.has(key));\n\n // Resolved the same way the generators resolve it, so the implication warnings below\n // describe exactly what gets generated.\n const forTable = resolveTableFeatures(config?.features);\n\n // Cost hints are inert without a complexity rule installed, so they are generated unless the\n // caller opts out.\n const complexityConfig = config?.complexity ?? true;\n const complexity =\n complexityConfig === false\n ? undefined\n : {\n defaultListSize: (complexityConfig === true ? undefined : complexityConfig.defaultListSize) ?? 10,\n aggregateCost: (complexityConfig === true ? undefined : complexityConfig.aggregateCost) ?? 10,\n };\n\n // Off unless asked for: opening transactions the caller did not wire up themselves is a\n // behavior change (and some drivers, e.g. neon-http, cannot open one at all).\n const transactionsOpt = config?.transactions;\n const transactions =\n transactionsOpt === undefined || transactionsOpt === 'none'\n ? undefined\n : { 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 // A row scope and the context-derived columns are resolved against the real schema for the\n // same reason exclusions are: a renamed table or column must fail the build, not silently\n // stop scoping. Both stay undefined unless configured, so an unconfigured build emits the\n // same SQL it always did.\n const scopeConfig = config?.scope;\n const contextValuesConfig = config?.contextValues;\n if (scopeConfig || contextValuesConfig) {\n const tableNames = new Set(tableKeys);\n for (const [tableName, hook] of Object.entries(scopeConfig ?? {})) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.scope names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n if (typeof hook !== 'function') {\n throw new Error(`Drizzle-GraphQL Error: config.scope.${tableName} must be a function.`);\n }\n }\n for (const [tableName, columnHooks] of Object.entries(contextValuesConfig ?? {})) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.contextValues names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n const columns = getColumns(schema[tableName] as Table);\n for (const [columnName, hook] of Object.entries(columnHooks)) {\n if (!columns[columnName]) {\n throw new Error(\n `Drizzle-GraphQL Error: config.contextValues names '${tableName}.${columnName}', which is not a column of that table.`,\n );\n }\n if (typeof hook !== 'function') {\n throw new Error(`Drizzle-GraphQL Error: config.contextValues.${tableName}.${columnName} must be a function.`);\n }\n }\n }\n }\n // Soft delete is resolved against the real columns here, once, so a renamed column or a\n // NOT NULL column with no restore value fails the build rather than silently making every\n // row visible again at runtime.\n const softDeleteConfig = config?.softDelete;\n const softDeleteInfos = new Map<string, SoftDeleteInfo>();\n if (softDeleteConfig) {\n if (typeof softDeleteConfig === 'function') {\n for (const tableName of tableKeys) {\n const declaration = softDeleteConfig(schema[tableName] as Table, tableName);\n if (declaration) {\n softDeleteInfos.set(tableName, resolveSoftDeleteInfo(schema[tableName] as Table, tableName, declaration));\n }\n }\n } else {\n const tableNames = new Set(tableKeys);\n for (const [tableName, declaration] of Object.entries(softDeleteConfig)) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n softDeleteInfos.set(tableName, resolveSoftDeleteInfo(schema[tableName] as Table, tableName, declaration));\n }\n }\n }\n\n const policies: TablePolicies | undefined =\n scopeConfig || contextValuesConfig || softDeleteInfos.size\n ? {\n scope: scopeConfig ? (tableName: string) => scopeConfig[tableName] : undefined,\n contextValues: contextValuesConfig ? (tableName: string) => contextValuesConfig[tableName] : undefined,\n softDelete: softDeleteInfos.size ? (tableName: string) => softDeleteInfos.get(tableName) : undefined,\n }\n : undefined;\n\n // Exclusions are resolved against the real schema so a renamed table or column fails the\n // build instead of quietly un-hiding itself — the failure mode that matters when this config\n // is what keeps a secret out of the API.\n const exclude = config?.exclude;\n if (exclude) {\n const tableNames = new Set(tableKeys);\n const excludedTables = excludedTableNames;\n for (const tableName of excludedTables) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.exclude.tables names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n }\n if (excludedTables.size >= tableNames.size) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.exclude.tables excludes every table in the schema, leaving nothing to generate.',\n );\n }\n for (const [tableName, columnNames] of Object.entries(exclude.columns ?? {})) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.exclude.columns names table '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n // An excluded table has no columns left to hide; listing them too is redundant, not wrong.\n if (excludedTables.has(tableName)) {\n continue;\n }\n const columns = getColumns(schema[tableName] as Table);\n for (const columnName of columnNames) {\n const column = columns[columnName];\n if (!column) {\n throw new Error(\n `Drizzle-GraphQL Error: config.exclude.columns names '${tableName}.${columnName}', which is not a column of that table.`,\n );\n }\n // Hiding a column every insert must supply leaves the table readable but unwritable.\n // That is a reasonable thing to configure deliberately, so it warns rather than throws.\n if (column.notNull && !column.hasDefault && !column.defaultFn) {\n console.warn(\n `Drizzle-GraphQL Warning: excluded column '${tableName}.${columnName}' is NOT NULL with no default, so generated inserts for '${tableName}' can never succeed.`,\n );\n }\n }\n }\n }\n\n // Some operations are built out of others: an upsert writes through the insert and update\n // paths, a batch update reuses the update input, a grouped result reuses the aggregate\n // output types. The generator knows those implications; a table whose flags contradict them\n // is told at build time rather than leaving the consumer to notice a second write path (or a\n // missing operation) later. These warn rather than throw — the resulting schema is coherent,\n // it just isn't what the config appears to ask for.\n const featureConflicts = new Map<string, string[]>();\n const noteConflict = (message: string, tableName: string) => {\n const tables = featureConflicts.get(message);\n if (tables) {\n tables.push(tableName);\n } else {\n featureConflicts.set(message, [tableName]);\n }\n };\n for (const tableName of featureTables) {\n const tableFeatures = forTable(tableName);\n if (tableFeatures.upsert) {\n const missing = [!tableFeatures.insert ? 'insert' : undefined, !tableFeatures.update ? 'update' : undefined]\n .filter(Boolean)\n .join(' and ');\n if (missing) {\n noteConflict(\n `upsert is on while ${missing} is off, so the upsert mutations are a second write path past the operation you turned off`,\n tableName,\n );\n }\n }\n // Nested writes are build-wide, so a relation pointing at this table can still write it\n // from another table's mutation even with its own write operations turned off.\n if (config?.features?.nestedWrites && (!tableFeatures.insert || !tableFeatures.update)) {\n noteConflict(\n \"nestedWrites is on while this table's own insert or update is off, so a nested `create` or `connect` under another table's mutation can still write it\",\n tableName,\n );\n }\n // Only flagged when the caller actually asked for the dependent feature: both default to\n // on, so turning off the operation they build on is the normal way to remove them.\n if (config?.features?.updateMany !== undefined && tableFeatures.updateMany && !tableFeatures.update) {\n noteConflict('updateMany is on while update is off, so no batch update is generated', tableName);\n }\n if (config?.features?.groupBy !== undefined && tableFeatures.groupBy && !tableFeatures.aggregates) {\n noteConflict('groupBy is on while aggregates is off, so no grouped query is generated', tableName);\n }\n // The count mutations mirror the plural write they count, so they need at least one of the\n // two to be generated at all.\n if (tableFeatures.countMutations && !tableFeatures.update && !tableFeatures.delete) {\n noteConflict(\n 'countMutations is on while update and delete are both off, so no count mutation is generated',\n tableName,\n );\n }\n }\n for (const [message, tables] of featureConflicts) {\n const listed =\n tables.length > 5 ? `${tables.slice(0, 5).join(', ')} and ${tables.length - 5} more` : tables.join(', ');\n console.warn(`Drizzle-GraphQL Warning: config.features — ${message} (${listed}).`);\n }\n\n // Normalize eagerLoadRelations (boolean | predicate | undefined) into a predicate.\n const eagerOpt = config?.eagerLoadRelations;\n const shouldEagerLoad: (tableName: string, relationName: string) => boolean =\n eagerOpt === undefined || eagerOpt === true ? () => true : eagerOpt === false ? () => false : eagerOpt;\n\n // When a typeNameMapper is provided, the mapper's singular/plural forms disambiguate the\n // list and single fields even if the suffixes are identical (e.g. both '').\n // Only enforce the suffix-collision check when no mapper is active.\n if (!typeNameMapper && suffixes.list === suffixes.single) {\n throw new Error(\n 'Drizzle-GraphQL Error: List and single query suffixes cannot be the same. This would create conflicting GraphQL field names.',\n );\n }\n\n if (typeof config?.relationsDepthLimit === 'number') {\n if (config.relationsDepthLimit < 0) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.relationsDepthLimit is supposed to be nonnegative integer or undefined!',\n );\n }\n if (config.relationsDepthLimit !== ~~config.relationsDepthLimit) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.relationsDepthLimit is supposed to be nonnegative integer or undefined!',\n );\n }\n }\n\n const generatorOptions: SchemaGeneratorOptions = {\n relationsDepthLimit: config?.relationsDepthLimit,\n prefixes,\n suffixes,\n conflictDoNothing: config?.conflictDoNothing ?? false,\n typeNameMapper,\n shouldEagerLoad,\n features: config?.features ?? {},\n complexity,\n scalars: config?.scalars,\n mapColumnType: config?.mapColumnType,\n enumNameMapper: config?.enumNameMapper,\n transactions,\n limits,\n policies,\n exclude,\n docs: {\n describeColumn: config?.describeColumn,\n describeTable: config?.describeTable,\n describeRelation: config?.describeRelation,\n deprecateColumn: config?.deprecateColumn,\n },\n };\n\n 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 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 { relationFieldExtension, tableTypeExtension } from '../extensions.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 OrderByArgs,\n ProcessedTableSelectArgs,\n SelectData,\n SelectedColumnsRaw,\n SelectedSQLColumns,\n TableFeatures,\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 whereArgs?: Record<string, any>,\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, whereArgs) : []),\n ...primaryKeyOrderExprs(targetTable, pkNames),\n ];\n const orderClause = orderExprs.length ? sql` order by ${sql.join(orderExprs, sql`, `)}` : sql``;\n // Namespaced alias so it can't collide with a real column on the target table.\n const RN = '__drizzle_graphql_rn';\n const rowNumber = sql`row_number() over (partition by ${foreignCol}${orderClause})`.as(RN);\n\n // Subquery: every target column plus a per-partition row number.\n const sub = db\n .select({ ...cols, [RN]: rowNumber })\n .from(targetTable)\n .where(whereCondition)\n .as('__paginated');\n\n // Outer: keep only the rows that fall inside each parent's window.\n const lower = offset ?? 0;\n const windowConds: any[] = [gt(sub[RN], lower)];\n if (limit != null) {\n windowConds.push(lte(sub[RN], lower + limit));\n }\n\n const rows: any[] = await db\n .select()\n .from(sub)\n .where(and(...windowConds))\n .orderBy(sub[RN]);\n\n // Strip the helper column so it doesn't leak into remapping/output.\n for (const row of rows) {\n delete row[RN];\n }\n return rows;\n};\n\n/**\n * Creates a RelationResolverFactory that generates field-level resolvers for each relation.\n * Each resolver:\n * 1. Returns pre-fetched data if the parent resolver already included it (eager path, zero cost).\n * 2. When limit/offset args are present, falls back to a direct per-item query.\n * 3. Otherwise batches all sibling resolver calls within the same GraphQL execution tick\n * into a single IN-clause query, eliminating N+1 database round-trips.\n *\n * `nullOrdering` is the dialect's native `ORDER BY` placement for `NULL` — the keyset\n * predicate behind a relation's `after` argument has to match it, or rows with a `NULL` in an\n * ordered column would be skipped instead of paged through. It has no sensible default, so\n * each dialect builder states it: `'nulls-largest'` for PostgreSQL, `'nulls-smallest'` for\n * MySQL and SQLite.\n */\nexport const createRelationResolverFactory =\n (\n db: any,\n tables: Record<string, Table>,\n nullOrdering: NullOrdering,\n filterCtx?: RelationFilterBase,\n limits?: LimitPolicyFor,\n policies?: TablePolicies,\n ): RelationResolverFactory =>\n ({ tableName, relationName, relEntry, isOne }) => {\n const parentTable = tables[tableName];\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n\n if (!parentTable || !targetTable) {\n return undefined;\n }\n\n const joinCols = extractRelationJoinColumns(relEntry, parentTable, targetTable);\n if (!joinCols) {\n return undefined;\n }\n\n const { localColPropName, foreignCol, foreignColPropName } = joinCols;\n // 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 {\n where: whereArg,\n orderBy: orderByArg,\n limit: requestedLimit,\n offset,\n after,\n deleted,\n } = (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 deleted: deleted ?? 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 // Loaders are keyed per context too, so the scope resolved here is this request's.\n const scope = resolveScope(policies, context, filterCtx);\n let whereCondition = withScope(\n scope,\n targetTableName,\n targetTable,\n and(\n inArray(foreignCol, uniqueIds),\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n cursorValues ? buildCursorCondition(targetTable, cursorEntries!, cursorValues, nullOrdering) : undefined,\n ),\n deleted,\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 whereArg,\n );\n } else {\n // Use plain db.select() so column refs are never aliased — avoids drizzle-orm v1\n // RQB aliasing requirements that would require referencing via aliasedTable proxy.\n let q = 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), whereArg)\n : [];\n if (orderExprs.length) {\n q = q.orderBy(...orderExprs);\n }\n rows = await q;\n }\n\n // Before remapping, which rewrites dates and bigints into their transport forms.\n if (cursorEntries) {\n attachRowCursors(rows, cursorEntries);\n }\n\n // Group by FK value before remapping (remapping may delete null fields).\n if (isOne) {\n const byKey = new Map(rows.map((row: any) => [String(row[foreignColPropName]), row]));\n remapToGraphQLArrayOutput(rows, targetTableName, targetTable);\n return parentIds.map((id) => byKey.get(String(id)) ?? null);\n }\n\n const grouped = new Map<string, any[]>(uniqueIds.map((id) => [String(id), []]));\n for (const row of rows) {\n grouped.get(String(row[foreignColPropName]))?.push(row);\n }\n remapToGraphQLArrayOutput(rows, targetTableName, targetTable);\n return parentIds.map((id) => grouped.get(String(id)) ?? []);\n });\n\n return loader.load(localValue);\n };\n };\n\n/**\n * The `extensions.drizzle` block for one relation field. The relation entry already carries\n * the target table's primary key (resolved at build time for pagination), so the field can\n * publish it without the dialect's key resolver being reachable from here.\n */\nconst relationExtensionFor = (\n relEntry: TableNamedRelations,\n parentTable: string,\n relationName: string,\n isOne: boolean,\n aggregate?: boolean,\n) =>\n relationFieldExtension({\n targetTable: relEntry.targetTableName,\n parentTable,\n relation: relationName,\n single: isOne,\n primaryKey: relEntry.targetPkNames ?? [],\n aggregate,\n });\n\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 * A table's primary-key property names, from the dialect's own resolver. Object types and\n * relation fields publish it on `extensions.drizzle` so a consumer can identify the rows a\n * field is about without re-deriving the key from the Drizzle schema.\n */\n primaryKeyOf?: (tableName: string) => readonly string[];\n /**\n * The context-derived columns of a table, if any. Read when the create/update inputs are\n * built: a column the server fills in is not part of either.\n */\n contextValuesOf?: ContextValuesFor;\n /**\n * The soft-delete convention of a table, if it declares one. Read when the write inputs are\n * built — the marker column is written by the delete and restore mutations, not by a client\n * — and when a read field's `deleted` argument is generated.\n */\n softDeleteOf?: SoftDeleteFor;\n /**\n * This build's feature flags, resolved for one table. Like `complexity` and `docs`, not a\n * cache — the type builders are several calls deep and this context is already threaded\n * through them. A lookup rather than a flat object because a flag may be a per-table\n * predicate, and because the table a builder is asked about is not always the one whose\n * type it is building: a relation field reads the flags of the table it points at.\n */\n featureOf: (tableName: string) => TableFeatures;\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 * Columns this build keeps out of the generated schema, keyed by the table object.\n *\n * A registry rather than a threaded parameter because the sites that decide schema shape —\n * the object type, every input, the filter, `orderBy`, the aggregates, the column enums —\n * are spread across four files and reach a table with no config in hand. Runtime code keeps\n * calling `getColumns` directly: a primary key that a client cannot name is still the key a\n * cursor is built from, and hiding it there would break pagination rather than secure it.\n *\n * {@link registerColumnExclusions} runs on every build, including with no config, so a\n * second build against the same table objects never inherits the first build's exclusions.\n */\nconst excludedColumnRegistry = new WeakMap<object, Set<string>>();\n\n/** Installs this build's column exclusions and clears any left by a previous build. */\nexport const registerColumnExclusions = (\n tables: Record<string, Table>,\n exclude?: { columns?: Record<string, string[]> },\n): void => {\n for (const [tableName, table] of Object.entries(tables)) {\n const hidden = exclude?.columns?.[tableName];\n if (hidden?.length) {\n excludedColumnRegistry.set(table, new Set(hidden));\n } else {\n excludedColumnRegistry.delete(table);\n }\n }\n};\n\n/** Whether any column of this table was excluded from the schema. */\nexport const hasExcludedColumns = (table: Table): boolean => excludedColumnRegistry.has(table);\n\n/**\n * A stable string naming this build's exclusions for `table`, empty when it has none. Used to\n * key the caches that hold generated types: two builds of the same table objects with\n * different exclusions must not share an entry, but *within* one build every call site has to\n * get the same instance back or the schema ends up with two types of the same name.\n */\nexport const excludedColumnsKey = (table: Table): string => {\n const hidden = excludedColumnRegistry.get(table);\n return hidden ? [...hidden].sort().join(',') : '';\n};\n\n/**\n * The columns of `table` that this build exposes — every column unless some were excluded.\n * Use this anywhere the result decides what the *schema* contains; use `getColumns` where it\n * decides what SQL to write.\n */\nexport const visibleColumns = (table: Table): Record<string, Column> => {\n const columns = getColumns(table);\n const hidden = excludedColumnRegistry.get(table);\n if (!hidden) {\n return columns;\n }\n return Object.fromEntries(Object.entries(columns).filter(([columnName]) => !hidden.has(columnName)));\n};\n\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 matchFilterOrder: {\n type: GraphQLBoolean,\n description:\n \"Sort by this column's position in the `inArray` list the same request's `where` gives it, rather than by the column's own value — `direction: asc` keeps the list's order, `desc` reverses it. Requires an `inArray` filter on the same column at the top level of `where`, and cannot be combined with `after` or `distinct`.\",\n },\n } 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 path: {\n type: new GraphQLList(new GraphQLNonNull(jsonPathFilter)),\n description:\n 'Compares the value at one path inside the document. Several entries are ANDed; a single object may be passed without the list brackets.',\n },\n isNull: { type: GraphQLBoolean },\n isNotNull: { type: GraphQLBoolean },\n };\n};\n\n/**\n * How the value at a JSON path is read before it is compared. Left unset, the operand\n * decides: a GraphQL number compares numerically, a boolean as a boolean, anything else as\n * text. Set it when the operand's type does not match the document's — comparing a numeric\n * field against a `String` variable, say.\n */\nconst jsonPathCast = new GraphQLEnumType({\n name: 'JSONPathCast',\n description: 'How to read the value at a JSON path before comparing it',\n values: {\n TEXT: { value: 'text', description: 'Compare as text (lexicographic ordering)' },\n NUMBER: { value: 'number', description: 'Compare as a number; a non-numeric value never matches' },\n BOOLEAN: { value: 'boolean', description: 'Compare as a boolean' },\n },\n});\n\n/**\n * One predicate on the value at a path inside a json/jsonb column. `path` walks the document\n * key by key (an all-digits element indexes an array), and the remaining operators compare\n * whatever sits there. Operands are `JSON` so a single input type serves string, number and\n * boolean fields; see {@link jsonPathCast} for how the comparison type is chosen.\n *\n * Note that `contains` here is substring matching on the extracted value — unlike `contains`\n * on the column itself, which is structural JSON containment. A path names a scalar, so the\n * string reading is the useful one.\n */\nconst jsonPathFilter = new GraphQLInputObjectType({\n name: 'JSONPathFilter',\n fields: {\n path: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLString))),\n description:\n 'Keys to walk from the document root, e.g. `[\"profile\", \"level\"]`. An all-digits key indexes an array.',\n },\n as: { type: jsonPathCast, description: 'Overrides how the value is read before comparing' },\n eq: { type: GraphQLJSON, description: 'Equal to' },\n ne: { type: GraphQLJSON, description: 'Not equal to' },\n lt: { type: GraphQLJSON, description: 'Less than' },\n lte: { type: GraphQLJSON, description: 'Less than or equal to' },\n gt: { type: GraphQLJSON, description: 'Greater than' },\n gte: { type: GraphQLJSON, description: 'Greater than or equal to' },\n startsWith: {\n type: GraphQLString,\n description: 'Extracted value starts with this string. `%`, `_` and `\\\\` are matched literally.',\n },\n endsWith: {\n type: GraphQLString,\n description: 'Extracted value ends with this string. `%`, `_` and `\\\\` are matched literally.',\n },\n contains: {\n type: GraphQLString,\n description: 'Extracted value contains this string. `%`, `_` and `\\\\` are matched literally.',\n },\n iStartsWith: { type: GraphQLString, description: 'Case-insensitive `startsWith`.' },\n iEndsWith: { type: GraphQLString, description: 'Case-insensitive `endsWith`.' },\n iContains: { type: GraphQLString, description: 'Case-insensitive `contains`.' },\n isNull: {\n type: GraphQLBoolean,\n description: 'When true, matches rows where the path is missing or holds JSON null',\n },\n isNotNull: { type: GraphQLBoolean, description: 'When true, matches rows where the path holds a value' },\n },\n});\n\n/**\n * `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 // The cache outlives a build, so a table whose columns this build hides must not read from\n // it (a previous build may have cached the full set) or write to it (a later unfiltered\n // build would inherit the holes).\n const cacheable = !hasExcludedColumns(table);\n if (cacheable && orderMap.has(table)) {\n return orderMap.get(table)!;\n }\n\n let remapped = {};\n try {\n const columns = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n remapped = Object.fromEntries(\n columnEntries.map(([columnName, _columnDescription]) => [columnName, { type: innerOrder }]),\n );\n\n if (cacheable) {\n orderMap.set(table, remapped);\n }\n } catch (_err) {}\n return remapped;\n};\n\nconst generateTableFilterValuesCached = (table: Table, tableName: string, cacheCtx: TypeCacheCtx) => {\n if (cacheCtx.filterFieldCache.has(table)) {\n return cacheCtx.filterFieldCache.get(table)!;\n }\n\n const columns = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n const remapped = Object.fromEntries(\n columnEntries.map(([columnName, column]) => [\n columnName,\n {\n type: generateColumnFilterValues(column, tableName, columnName, cacheCtx),\n // A filter field is the same column, so it carries the same documentation. Deprecation\n // is not propagated: filtering on a deprecated column is how a caller finds the rows\n // that still use it.\n ...(cacheCtx.docs.describeColumn\n ? { description: cacheCtx.docs.describeColumn(column, { tableName, columnName }) }\n : {}),\n },\n ]),\n );\n\n cacheCtx.filterFieldCache.set(table, remapped);\n\n return remapped;\n};\n\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 = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n const remapped = Object.fromEntries(\n columnEntries.map(([columnName, column]) => [\n columnName,\n {\n ...drizzleColumnToGraphQLType(column, columnName, tableName),\n ...columnDocs(cacheCtx.docs, column, tableName, columnName),\n },\n ]),\n );\n\n // Opaque keyset-pagination cursor. Only populated on rows returned by a list query; a real\n // column named `cursor` keeps the field for itself instead.\n if (!remapped[CURSOR_FIELD_NAME]) {\n remapped[CURSOR_FIELD_NAME] = {\n type: GraphQLString,\n description:\n \"Opaque cursor of this row's position in the query's ordering. Pass it as `after` to resume from here. Only set on rows returned by a list query.\",\n resolve: rowCursorResolver,\n } as ConvertedColumn;\n }\n\n cacheCtx.selectFieldCache.set(table, remapped);\n\n return remapped;\n};\n\n/**\n * 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 extensions: { drizzle: tableTypeExtension(tableName, cacheCtx.primaryKeyOf?.(tableName) ?? []) },\n });\n cacheCtx.objectTypeCache.set(tableName, shell);\n }\n\n // Build relation fields — recurse into each related table.\n // Mark this table as in-progress before recursing to detect cycles.\n if (relationEntries.length > 0) {\n const rawRelationFields: [string, ConvertedRelationColumnWithArgs][] = [];\n\n // Mark this table as currently being processed.\n const nextUsedTables = new Set(usedTables);\n nextUsedTables.add(tableName);\n\n for (const [relationName, relEntry] of relationEntries) {\n const { targetTableName } = relEntry;\n const relation = (relEntry as any).relation ?? relEntry;\n const isOne = is(relation, One);\n\n // Always recurse to get the target table's filters/order (needed for args).\n // The usedTables check inside the recursive call prevents actual infinite recursion.\n const relSelectData = generateSelectFields(\n tables,\n targetTableName,\n relationMap,\n tableName, // fromTableName for the relation type\n relationName, // fromRelationName for the relation type\n !isOne,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n nextUsedTables,\n resolverFactory,\n currentDepth + 1,\n relationAggregateFactory,\n );\n\n // Use the target table's own GraphQL type directly instead of creating an intermediate relation type.\n // Ensure exactly one GraphQLObjectType instance exists for the target table.\n // If the root call for the target table has already run (or pre-registered a shell),\n // reuse that instance so the schema never contains duplicate type names.\n let relType = cacheCtx.objectTypeCache.get(targetTableName);\n if (!relType) {\n // The target table hasn't been processed yet. Pre-register a shell so that:\n // (a) this relation field has a concrete type reference, and\n // (b) when the target table's root call eventually runs, it reuses this same object.\n const targetTable = tables[targetTableName]!;\n const targetTableFields = generateTableSelectTypeFieldsCached(targetTable, targetTableName, cacheCtx);\n // Get or create a container for the target table's relation fields.\n let targetContainer = cacheCtx.relationFieldContainers.get(targetTableName);\n if (!targetContainer) {\n targetContainer = { fields: {} };\n cacheCtx.relationFieldContainers.set(targetTableName, targetContainer);\n }\n const capturedTargetContainer = targetContainer;\n // The thunk reads capturedTargetContainer.fields so that when the target table's root\n // call populates the container, the shell automatically includes those relation fields.\n relType = new GraphQLObjectType({\n name: resolveTypeName(targetTableName, typeNameMapper),\n description: cacheCtx.docs.describeTable?.(targetTableName),\n fields: () => ({ ...targetTableFields, ...capturedTargetContainer.fields }),\n extensions: {\n drizzle: tableTypeExtension(targetTableName, cacheCtx.primaryKeyOf?.(targetTableName) ?? []),\n },\n });\n cacheCtx.objectTypeCache.set(targetTableName, relType);\n }\n\n const resolve = resolverFactory?.({ tableName, relationName, relEntry: relEntry as TableNamedRelations, isOne });\n const relationDescription = cacheCtx.docs.describeRelation?.(tableName, relationName);\n const relationDocs = relationDescription !== undefined ? { description: relationDescription } : {};\n\n if (isOne) {\n // Honor the relation's declared optionality: `r.one.Target({ ..., optional: false })`\n // asserts the related row always exists (a NOT NULL foreign key), so the field is\n // emitted as `Target!`. The default (`optional: true` / omitted) stays nullable.\n // Column nullability alone is NOT used to infer this — a notNull `from` column does\n // not guarantee a related row exists when the FK constraint lives on the other side\n // (e.g. `Users.customer` joins the notNull `Users.id` to `Customers.userId`).\n const isRequired = (relation as One<any, any>).optional === false;\n rawRelationFields.push([\n relationName,\n {\n type: isRequired ? new GraphQLNonNull(relType) : relType,\n args: {\n where: { type: relSelectData.filters },\n ...deletedArg(cacheCtx.softDeleteOf, targetTableName),\n },\n resolve,\n ...relationDocs,\n extensions: { drizzle: relationExtensionFor(relEntry, tableName, relationName, true) },\n },\n ]);\n continue;\n }\n\n // A to-many relation field is a list of the target table, so it takes the same\n // pagination surface a root list of that table does. `after` and `distinct` are the\n // two drizzle's `with:` clause cannot express, so a request that passes either drops\n // the relation out of the eager fetch and resolves it through the batch loader, which\n // implements both — see extractRelationsParamsInner.\n const targetDistinctEnum = cacheCtx.featureOf(targetTableName).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 ...deletedArg(cacheCtx.softDeleteOf, targetTableName),\n after: {\n type: GraphQLString,\n description:\n \"Keyset pagination: only return related rows strictly after this cursor (a row's `cursor` field from a previous page of this relation, under the same orderBy).\",\n },\n ...(targetDistinctEnum\n ? { distinct: { type: new GraphQLList(new GraphQLNonNull(targetDistinctEnum)) } }\n : {}),\n },\n resolve,\n ...relationDocs,\n extensions: {\n drizzle: relationExtensionFor(relEntry, tableName, relationName, false),\n ...(cacheCtx.complexity\n ? { complexity: listFieldComplexity(cacheCtx.complexity, cacheCtx.limits?.(targetTableName)) }\n : {}),\n },\n },\n ]);\n\n // Aggregate over the related rows without fetching them: `user { postsAggregate { count } }`.\n // Skipped when the name would shadow a column or another relation.\n const aggregateFieldName = `${relationName}Aggregate`;\n if (!tableFields[aggregateFieldName] && !relationsForTable?.[aggregateFieldName]) {\n const relationAggregate = relationAggregateFactory?.({\n tableName,\n relationName,\n relEntry: relEntry as TableNamedRelations,\n });\n\n if (relationAggregate) {\n rawRelationFields.push([\n aggregateFieldName,\n {\n type: new GraphQLNonNull(relationAggregate.type),\n args: {\n where: { type: relSelectData.filters },\n ...deletedArg(cacheCtx.softDeleteOf, targetTableName),\n },\n resolve: relationAggregate.resolve,\n extensions: {\n drizzle: relationExtensionFor(relEntry, tableName, relationName, isOne, true),\n ...(cacheCtx.complexity ? { complexity: aggregateFieldComplexity(cacheCtx.complexity) } : {}),\n },\n } as unknown as ConvertedRelationColumnWithArgs,\n ]);\n }\n }\n }\n\n const builtRelationFields = Object.fromEntries(rawRelationFields);\n\n // Only the root call should populate the container — non-root calls are temporary traversals\n // to collect filters/order for args and should not overwrite the canonical relation fields.\n if (isRootCall) {\n // Populate the container so that the thunk on the GraphQLObjectType shell (whether it was\n // created here or pre-registered by another table's relation traversal) picks up the fields.\n container.fields = builtRelationFields;\n cacheCtx.fullyBuiltTables.add(tableName);\n }\n\n return {\n order,\n filters,\n tableFields,\n relationFields: builtRelationFields,\n } as SelectData<TWithOrder>;\n }\n\n // No relation entries — mark as fully built if root call.\n if (isRootCall) {\n cacheCtx.fullyBuiltTables.add(tableName);\n }\n\n return {\n order,\n filters,\n tableFields,\n relationFields: {},\n } as SelectData<TWithOrder>;\n};\n\nexport const generateTableTypes = <WithReturning extends boolean>(\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n withReturning: WithReturning,\n relationsDepthLimit: number | undefined,\n cacheCtx: TypeCacheCtx,\n typeNameMapper: TypeNameMapper | undefined = undefined,\n insertPrefix: string = 'create',\n updatePrefix: string = 'update',\n resolverFactory?: RelationResolverFactory,\n relationAggregateFactory?: RelationAggregateFactory,\n nestedWrites?: NestedWriteTypes,\n): GeneratedTableTypes<WithReturning> => {\n const { tableFields, relationFields, filters, order } = generateSelectFields(\n tables,\n tableName,\n relationMap,\n '', // root call: no fromTableName\n '', // root call: no fromRelationName\n true,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n new Set(),\n resolverFactory,\n 0,\n relationAggregateFactory,\n );\n\n const table = tables[tableName]!;\n const columns = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n // A column whose value comes from the request context is not part of any write input: the\n // client cannot supply one on create, and cannot reassign one on update. It stays an\n // ordinary column everywhere else — the output type, the filters, the ordering.\n const contextColumns = cacheCtx.contextValuesOf?.(tableName);\n // Same for the column that marks a row deleted: `delete` and `restore` own it, and a client\n // that could write it through an ordinary create or update could delete or undelete a row\n // without going through either.\n const markerColumn = cacheCtx.softDeleteOf?.(tableName)?.columnName;\n const writableEntries =\n contextColumns || markerColumn\n ? columnEntries.filter(\n ([columnName]) => !(contextColumns && columnName in contextColumns) && columnName !== markerColumn,\n )\n : columnEntries;\n\n // A column a nested write can supply (`author: { create: … }` fills in `authorId`) cannot\n // stay required on the create input, or the two ways of setting it would be mutually\n // exclusive at the type level.\n const relaxedColumns = nestedWrites?.relaxedColumns(tableName);\n\n const insertFields = Object.fromEntries(\n writableEntries.map(([columnName, column]) => {\n const converted = drizzleColumnToGraphQLType(\n column,\n columnName,\n tableName,\n !!relaxedColumns?.has(columnName),\n true,\n true,\n );\n return [\n columnName,\n { ...converted, ...inputFieldDocs(cacheCtx.docs, column, tableName, columnName, converted.type) },\n ];\n }),\n );\n\n const updateFields = Object.fromEntries(\n writableEntries.map(([columnName, column]) => {\n const converted = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, true);\n // A numeric or array column takes an operations input instead of the bare scalar, so\n // it can be changed relative to its current value rather than only replaced.\n const operations = cacheCtx.featureOf(tableName).fieldUpdateOperations\n ? fieldUpdateInputType(column, columnName, tableName)\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 extensions: { drizzle: tableTypeExtension(tableName, cacheCtx.primaryKeyOf?.(tableName) ?? []) },\n });\n\n const selectArrOutput = new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(selectSingleOutput)));\n\n // Mutation return type: ${capitalize(tableName)}Item (table columns only, no relations)\n // const singleTableItemOutput = withReturning\n // ? new GraphQLObjectType({\n // name: `${capitalize(tableName)}`,\n // // name: `${capitalize(tableName)}Item`,\n // fields: tableFields,\n // })\n // : undefined;\n\n const arrTableItemOutput = withReturning\n ? // ? new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(singleTableItemOutput!)))\n new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(selectSingleOutput!)))\n : undefined;\n\n const inputs = {\n insertInput,\n updateInput,\n tableOrder: order,\n tableFilters: filters,\n };\n\n const outputs = (\n withReturning\n ? {\n selectSingleOutput,\n selectArrOutput,\n singleTableItemOutput: selectSingleOutput!,\n // singleTableItemOutput: singleTableItemOutput!,\n arrTableItemOutput: arrTableItemOutput!,\n }\n : {\n selectSingleOutput,\n selectArrOutput,\n }\n ) as GeneratedTableTypesOutputs<WithReturning>;\n\n return {\n inputs,\n outputs,\n };\n};\n\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 // Same reason as above: the sort key is not a value of the row, so it cannot be\n // rebuilt against a subquery's fields or encoded into a cursor.\n if (config.matchFilterOrder) {\n throw new GraphQLError(`ORDER BY ${column}: 'matchFilterOrder' 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 * The sort key behind `matchFilterOrder`: the column's position in the `inArray` list that\n * the same request's `where` gives it, as a `CASE` ladder over that list.\n *\n * A ladder rather than a dialect array function (`array_position` on Postgres, `FIELD()` on\n * MySQL, neither on SQLite) because it is the one form all three share, and because every\n * list value stays a bound parameter. The branch indices are library-generated integers, so\n * they are written into the SQL text — a bound parameter there would leave Postgres unable\n * to infer the CASE result type. Values outside the list sort after every listed one.\n */\nconst filterOrderExpression = (column: Column, columnName: string, whereArgs: Record<string, any> | undefined): SQL => {\n const values = whereArgs?.[columnName]?.inArray as unknown;\n if (!Array.isArray(values)) {\n throw new GraphQLError(\n `ORDER BY ${columnName}: 'matchFilterOrder' needs an 'inArray' filter on the same column in this query's 'where'`,\n );\n }\n if (!values.length) {\n // An empty `inArray` matches no rows at all, so every row would sort the same anyway;\n // a constant keeps the expression valid without a ladder that has no branches.\n return sql`0`;\n }\n\n const branches = values.map(\n (value, index) =>\n sql`when ${column} = ${remapFromGraphQLCore(value, column, columnName)} then ${sql.raw(String(index))}`,\n );\n return sql`case ${sql.join(branches, sql` `)} else ${sql.raw(String(values.length))} end`;\n};\n\n/**\n * Flattens one level of an `orderBy` argument into `out`. A column key becomes an entry\n * directly (wrapped in a correlated subquery when reached through a relation chain); a\n * to-one relation key recurses with the chain extended by that hop. Priorities live in one\n * global space, so a relation's column can interleave with the parent's own columns.\n */\nconst collectOrderEntries = (\n table: Table,\n tableKey: string,\n orderArgs: Record<string, any>,\n ctx: RelationFilterContext | undefined,\n chain: RelationOrderChain | undefined,\n out: FlatOrderEntry[],\n whereArgs: Record<string, any> | undefined,\n): void => {\n const columns = getColumns(table);\n const relations = ctx?.relationMap[tableKey];\n\n for (const [key, config] of Object.entries(orderArgs)) {\n if (config === null || config === undefined) {\n continue;\n }\n\n const column = columns[key];\n if (column) {\n if (config.matchFilterOrder && chain) {\n throw new GraphQLError(`ORDER BY ${key}: 'matchFilterOrder' is not supported through a relation`);\n }\n out.push({\n expression: config.matchFilterOrder\n ? filterOrderExpression(column, key, whereArgs)\n : chain\n ? sql`(select ${column} from ${sql.join(chain.fromParts, sql`, `)} where ${and(...chain.conditions)})`\n : column,\n column,\n direction: config.direction,\n nulls: config.nulls ?? undefined,\n priority: config.priority ?? 0,\n });\n continue;\n }\n\n const relEntry = relations?.[key];\n if (!relEntry || !ctx) {\n throw 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, undefined);\n }\n};\n\n/**\n * Compiles an `orderBy` argument into ORDER BY expressions, highest priority first.\n *\n * A key naming one of the table's columns orders by that column. A key naming a to-one\n * relation takes the target table's own OrderBy input and orders by the related row's\n * column(s), compiled as a correlated scalar subquery — reusing the aliased-join machinery\n * the relation filters are built on — so it works identically on all three dialects and\n * inside the relational query builder's aliased CTEs. Priorities share one global space\n * across relation boundaries. Each entry may also carry `nulls: first | last`\n * (see {@link orderExpressions} for how MySQL emulates it).\n *\n * An entry may instead set `matchFilterOrder`, which sorts by the column's position in the\n * `inArray` list the same request's `where` gives it — `whereArgs` is that `where`.\n *\n * `ctx` supplies the tables and relation map that relation ordering needs; callers whose\n * inputs cannot contain relation keys may omit it.\n */\nexport const extractOrderBy = <TTable extends Table, TArgs extends OrderByArgs<any> = OrderByArgs<TTable>>(\n table: TTable,\n orderArgs: TArgs,\n ctx?: RelationFilterContext,\n whereArgs?: Record<string, any>,\n): SQL[] => {\n const entries: FlatOrderEntry[] = [];\n collectOrderEntries(table, ctx?.tableKey ?? '', orderArgs, ctx, undefined, entries, whereArgs);\n\n return entries\n .sort((a, b) => b.priority - a.priority)\n .flatMap((entry) => orderExpressions(entry.expression, entry.direction, entry.nulls, entry.column));\n};\n\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\n/**\n * Constant predicates, used where an operator's operand list is empty and the answer is\n * therefore known without touching the column. Written as `1 = 0` / `1 = 1` rather than the\n * `FALSE` / `TRUE` keywords so they compile identically on all three dialects. Built fresh\n * per call because a `SQL` object is spliced into whatever query consumes it.\n */\nconst sqlFalse = (): SQL => sql`1 = 0`;\nconst sqlTrue = (): SQL => sql`1 = 1`;\n\n/**\n * A MySQL / SQLite JSON path expression for the given key walk. Bound as a query parameter,\n * never spliced into the SQL text; an all-digits key becomes an array index, and quotes and\n * backslashes inside a key are escaped so a key can never end the path segment early.\n */\nconst jsonPathString = (path: string[]): string =>\n `$${path.map((part) => (/^\\d+$/.test(part) ? `[${part}]` : `.\"${part.replace(/([\"\\\\])/g, '\\\\$1')}\"`)).join('')}`;\n\n/**\n * Matches the text forms a database will accept as a number. Used to guard both numeric casts —\n * Postgres has no TRY_CAST and errors outright on a bad `::numeric`, while MySQL quietly casts\n * a non-numeric string to 0; neither is what a non-matching row should do.\n */\nconst NUMERIC_TEXT_PATTERN = '^\\\\s*-?(\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)([eE][-+]?\\\\d+)?\\\\s*$';\n\n/**\n * The value at a JSON path, as the expressions a comparison can be built on: read as text,\n * read as a number, and read as the dialect spells a boolean. Each dialect extracts\n * differently, and each needs its own guard so a value of the wrong shape answers \"no match\"\n * rather than erroring or comparing by some unrelated rule:\n *\n * - **Postgres** — `#>>` with a bound `text[]` path, which works on `json` and `jsonb` alike.\n * `::numeric` on a non-numeric string is a hard error, so the numeric read is guarded by a\n * pattern test.\n * - **MySQL** — `JSON_UNQUOTE(JSON_EXTRACT(col, ?))`, so a JSON string arrives without its\n * quotes. Unquoting a JSON *null* would otherwise yield the string `'null'`, so it is mapped\n * back to SQL NULL first. `CAST` quietly turns a non-numeric string into 0, hence the same\n * pattern guard.\n * - **SQLite** — `json_extract` returns the value in SQLite's own type, so the reads cast\n * explicitly: without that, SQLite's cross-type ordering puts every string above every\n * number and `'admin' > 0` would be true.\n */\nconst jsonPathExprs = (\n column: Column,\n path: string[],\n): { text: SQL; number: SQL; boolean: SQL; encodeBoolean: (value: boolean) => string | number } => {\n switch (columnDialect(column)) {\n case 'pg': {\n const pathArray = sql`array[${sql.join(\n path.map((part) => sql`${part}`),\n sql`, `,\n )}]::text[]`;\n const text = sql`(${column} #>> ${pathArray})`;\n return {\n text,\n number: sql`(case when ${text} ~ ${NUMERIC_TEXT_PATTERN} then ${text}::numeric end)`,\n boolean: text,\n encodeBoolean: (value) => String(value),\n };\n }\n case 'mysql': {\n const extracted = sql`json_extract(${column}, ${jsonPathString(path)})`;\n const text = sql`(case when json_type(${extracted}) = 'NULL' then null else json_unquote(${extracted}) end)`;\n return {\n text,\n number: sql`(case when ${text} regexp ${NUMERIC_TEXT_PATTERN} then cast(${text} as decimal(65, 30)) end)`,\n boolean: text,\n encodeBoolean: (value) => String(value),\n };\n }\n default: {\n const extracted = sql`json_extract(${column}, ${jsonPathString(path)})`;\n return {\n text: sql`cast(${extracted} as text)`,\n number: sql`(case when typeof(${extracted}) in ('integer', 'real') then ${extracted} end)`,\n // SQLite has no boolean type: a JSON `true` comes back as the integer 1.\n boolean: extracted,\n encodeBoolean: (value) => (value ? 1 : 0),\n };\n }\n }\n};\n\n/** Comparison operators available inside a JSON path filter, as their SQL spelling. */\nconst JSON_PATH_COMPARISONS: Record<string, string> = {\n eq: '=',\n ne: '<>',\n lt: '<',\n lte: '<=',\n gt: '>',\n gte: '>=',\n};\n\n/**\n * How the value at a path is read when the filter does not say: a GraphQL number compares\n * numerically, a boolean as a boolean, everything else as text.\n */\nconst inferJsonPathCast = (value: unknown): 'text' | 'number' | 'boolean' =>\n typeof value === 'number' ? 'number' : typeof value === 'boolean' ? 'boolean' : 'text';\n\n/**\n * Compiles one entry of a column's `path` filter: `as` (or the operand's own type) picks\n * which of {@link jsonPathExprs}' reads the comparison is built on, and the operand is bound\n * in the shape that read expects.\n */\nconst jsonPathCondition = (column: Column, columnName: string, filter: Record<string, any>): SQL | undefined => {\n const { path, as: castOverride, ...operators } = filter;\n const locator = `${columnName}.path`;\n\n if (!Array.isArray(path) || !path.length) {\n throw new GraphQLError(`WHERE ${locator}: 'path' must name at least one key`);\n }\n\n const exprs = jsonPathExprs(column, path);\n const variants: SQL[] = [];\n\n for (const [operatorName, operatorValue] of Object.entries(operators)) {\n if (operatorValue === null || operatorValue === undefined) {\n continue;\n }\n\n if (operatorName === 'isNull' || operatorName === 'isNotNull') {\n if (operatorValue === false) {\n continue;\n }\n variants.push(operatorName === 'isNull' ? sql`${exprs.text} is null` : sql`${exprs.text} is not null`);\n continue;\n }\n\n if (operatorName in safeLikeOps) {\n const { buildPattern, insensitive } = safeLikeOps[operatorName]!;\n if (typeof operatorValue !== 'string') {\n throw new GraphQLError(`WHERE ${locator}: operator '${operatorName}' takes a string`);\n }\n // The extracted value is an expression, not a column, so the case-insensitive form\n // always goes through `lower()` rather than Postgres's ILIKE.\n variants.push(safeLikeCondition(exprs.text as any, buildPattern(operatorValue), insensitive));\n continue;\n }\n\n const comparison = JSON_PATH_COMPARISONS[operatorName];\n if (!comparison) {\n throw new GraphQLError(`WHERE ${locator}: Unknown operator: ${operatorName}`);\n }\n\n const cast = castOverride ?? inferJsonPathCast(operatorValue);\n if (cast === 'number') {\n const numeric = Number(operatorValue);\n if (Number.isNaN(numeric)) {\n throw new GraphQLError(\n `WHERE ${locator}: operator '${operatorName}' compares as a number, so its value must be one`,\n );\n }\n variants.push(sql`${exprs.number} ${sql.raw(comparison)} ${numeric}`);\n } else if (cast === 'boolean') {\n const truthy = operatorValue === true || operatorValue === 'true';\n variants.push(sql`${exprs.boolean} ${sql.raw(comparison)} ${exprs.encodeBoolean(truthy)}`);\n } else {\n variants.push(sql`${exprs.text} ${sql.raw(comparison)} ${String(operatorValue)}`);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n\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 === 'path' && isJsonColumn(column)) {\n // Several path predicates on one column are ANDed, matching how sibling operators\n // already combine. GraphQL coerces a lone object into a one-element list.\n for (const pathFilter of operatorValue as Record<string, any>[]) {\n const extracted = jsonPathCondition(column, columnName, pathFilter);\n if (extracted) {\n variants.push(extracted);\n }\n }\n } else if (operatorName === 'contains' && isJsonColumn(column)) {\n // `contains` is JSON containment on json/jsonb columns; on string columns it is the\n // safe substring operator handled by safeLikeOps below.\n variants.push(jsonContains(column, columnName, operatorValue));\n } else if (operatorName in safeLikeOps) {\n const { buildPattern, insensitive } = safeLikeOps[operatorName]!;\n variants.push(safeLikeCondition(column, buildPattern(operatorValue as string), insensitive));\n } else if (operatorName in arrayValueOps) {\n // An empty candidate list is a well-formed question with a known answer — nothing is\n // `IN ()`, everything is `NOT IN ()` — so it resolves to a constant predicate rather\n // than an error. SQL has no empty-list literal, hence the constant rather than `IN ()`.\n if (!(operatorValue as any[]).length) {\n variants.push(operatorName === 'inArray' ? sqlFalse() : sqlTrue());\n continue;\n }\n const arrayValue = (operatorValue as any[]).map((val) => remapFromGraphQLCore(val, column, columnName));\n variants.push(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 // Same reasoning as inArray/notInArray: overlapping with no elements is never true,\n // and every array contains all zero of them.\n if (!(operatorValue as any[]).length) {\n variants.push(operatorName === 'hasSome' ? sqlFalse() : sqlTrue());\n continue;\n }\n variants.push(arrayMembershipOps[operatorName]!(column, operatorValue as any[]));\n } else if (operatorName === 'isEmpty') {\n variants.push(sql`cardinality(${column}) = 0`);\n } else if (operatorName in nullableOps) {\n variants.push(nullableOps[operatorName]!(column));\n } else {\n // An unrecognized operator must throw rather than be dropped: when the generated\n // schema is stitched/merged with another schema, foreign operators (e.g. `equals`,\n // `contains`, `mode`) can pass input validation, and silently dropping them could\n // turn a constrained where into an unbounded one.\n throw 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\n// ─────────────────────────────────────────────────────────────────────────────\n// Row-level scoping\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * A table's row-level scope: the predicate every generated read, update and delete on that\n * table is narrowed by. See `BuildSchemaConfig.scope`.\n *\n * `table` is the table the predicate must be built against. On the relational-query path\n * drizzle hands its callbacks an *aliased* proxy (`d0`, `d1`, …), so a predicate built from\n * the imported schema table would reference a name that isn't in the query — always build\n * from the argument. Returning a filter object instead (the same shape as the field's\n * `where`) sidesteps aliasing entirely, and is the only form that can reach through a\n * relation — which is what ownership through a join table needs.\n */\nexport type ScopeHook<TContext = any> = (context: TContext, table: any) => SQL | Record<string, any> | undefined | null;\n\n/** Build-time lookup: the scope configured for a table, if any. */\nexport type ScopeFor = (tableName: string) => ScopeHook | undefined;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Soft delete\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** What a read over a soft-deleting table does with rows that are marked deleted. */\nexport type DeletedMode = 'EXCLUDE' | 'INCLUDE' | 'ONLY';\n\n/**\n * One table's soft-delete convention, resolved against the real column at build time.\n *\n * `nullable` picks the shape of the predicate. A nullable column marks a row deleted by\n * holding a value at all (`deletedAt IS NOT NULL`), which is the common timestamp form; a\n * non-nullable one marks it by holding `marker` (`isDeleted = true`), so the column has to\n * have a constant that means \"deleted\" and another that means \"not deleted\".\n */\nexport type SoftDeleteInfo = {\n /** Property name of the column on the drizzle table — also the key on an aliased proxy. */\n columnName: string;\n column: Column;\n nullable: boolean;\n /** Evaluated per delete, so a timestamp form stamps the moment of the delete. */\n writeDeleted: () => any;\n /** Written by the restore mutation. */\n writeRestored: any;\n /** Non-nullable form only: the constant that means \"this row is deleted\". */\n marker?: any;\n};\n\n/** Build-time lookup: the soft-delete convention of a table, if it declares one. */\nexport type SoftDeleteFor = (tableName: string) => SoftDeleteInfo | undefined;\n\n/**\n * The enum behind the `deleted` argument on every read over a soft-deleting table. One\n * instance shared by every build — it carries no per-build state.\n */\nexport const deletedFilterEnum = new GraphQLEnumType({\n name: 'DeletedFilter',\n description: 'Which rows a read over a soft-deleting table returns.',\n values: {\n EXCLUDE: { value: 'EXCLUDE', description: 'Only rows that are not marked deleted. The default.' },\n INCLUDE: { value: 'INCLUDE', description: 'Marked and unmarked rows alike.' },\n ONLY: { value: 'ONLY', description: 'Only rows that are marked deleted — a trash view.' },\n },\n});\n\n/**\n * Resolves one table's `softDelete` declaration against the real column, at build time, so a\n * renamed column fails the build instead of quietly making every row visible again.\n */\nexport const resolveSoftDeleteInfo = (\n table: Table,\n tableName: string,\n declaration: string | { column: string; deletedValue?: any; restoredValue?: any },\n): SoftDeleteInfo => {\n const config = typeof declaration === 'string' ? { column: declaration } : declaration;\n const columnName = config?.column;\n if (typeof columnName !== 'string' || !columnName) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName} must be a column name or an object with a 'column' property.`,\n );\n }\n const column = getColumns(table)[columnName];\n if (!column) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete names '${tableName}.${columnName}', which is not a column of that table.`,\n );\n }\n const nullable = !column.notNull;\n // drizzle-orm v1 reports compound dataType strings (\"object date\", \"number int32\"), so the\n // shape of the column has to come from the extended type rather than a string compare.\n const { type: baseType, constraint } = extractExtendedColumnType(column);\n const hasDeleted = 'deletedValue' in (config as object) && config.deletedValue !== undefined;\n // The default depends on what the column can hold: a timestamp records when, a flag records\n // whether. Both are the shapes the convention actually takes in the wild.\n const writeDeleted: () => any = hasDeleted\n ? typeof config.deletedValue === 'function'\n ? (config.deletedValue as () => any)\n : () => config.deletedValue\n : constraint === 'date' && baseType === 'object'\n ? () => new Date()\n : baseType === 'string'\n ? () => new Date().toISOString()\n : baseType === 'number'\n ? () => Date.now()\n : baseType === 'bigint'\n ? () => BigInt(Date.now())\n : () => true;\n\n let marker: any;\n if (!nullable) {\n // A non-nullable column has no \"absent\" state, so the predicate has to compare against a\n // constant — which a function cannot supply, and which the boolean form supplies for free.\n if (hasDeleted && typeof config.deletedValue !== 'function') {\n marker = config.deletedValue;\n } else if (!hasDeleted && baseType === 'boolean') {\n marker = true;\n } else {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName} marks a NOT NULL column ('${columnName}'), so 'deletedValue' must be a constant that means deleted — not a function, and not omitted for a non-boolean column.`,\n );\n }\n }\n\n const hasRestored = 'restoredValue' in (config as object);\n const writeRestored = hasRestored\n ? config.restoredValue\n : nullable\n ? null\n : baseType === 'boolean'\n ? false\n : undefined;\n if (!nullable && writeRestored === undefined) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName} marks a NOT NULL column ('${columnName}'), so 'restoredValue' must say what restoring writes back.`,\n );\n }\n\n return { columnName, column, nullable, writeDeleted, writeRestored, marker };\n};\n\n/**\n * The predicate that selects the rows a `deleted` mode asks for: nothing for `INCLUDE`, the\n * marked rows for `ONLY`, the unmarked ones for `EXCLUDE`. Built against the table it is\n * handed, which on the relational path is drizzle's aliased proxy rather than the schema\n * table — the same rule a scope hook follows.\n */\nexport const softDeletePredicate = (info: SoftDeleteInfo, table: Table, mode: DeletedMode): SQL | undefined => {\n if (mode === 'INCLUDE') {\n return undefined;\n }\n const column = ((table as any)?.[info.columnName] ?? info.column) as Column;\n if (info.nullable) {\n return mode === 'ONLY' ? isNotNull(column) : isNull(column);\n }\n return mode === 'ONLY' ? eq(column, info.marker) : ne(column, info.marker);\n};\n\n/**\n * The row policies of one request, bound to its context: the table's scope and its\n * soft-delete convention, which both narrow the same `where`. `has` answers \"does this table\n * restrict anything at all\", cheaply and without evaluating a hook; `on` compiles the\n * predicate against a given table.\n */\nexport type ScopeResolver = {\n has: (tableName: string, mode?: DeletedMode) => boolean;\n on: (tableName: string, table: Table, mode?: DeletedMode) => SQL | undefined;\n};\n\n/**\n * Binds the configured row policies to one request's GraphQL context. Returns `undefined`\n * when neither a scope nor a soft-delete column is configured, so every call site skips the\n * machinery with a single check and an unconfigured build generates exactly the SQL it did\n * before.\n */\nexport const resolveScope = (\n policies: TablePolicies | undefined,\n context: any,\n filterCtx?: RelationFilterBase,\n): ScopeResolver | undefined => {\n const scopes = policies?.scope;\n const softDelete = policies?.softDelete;\n if (!scopes && !softDelete) {\n return undefined;\n }\n return {\n has: (tableName, mode) => !!scopes?.(tableName) || (!!softDelete?.(tableName) && (mode ?? 'EXCLUDE') !== 'INCLUDE'),\n on: (tableName, table, mode) => {\n // Order is fixed: the soft-delete predicate first, the scope after it, both ANDed. They\n // commute, but a fixed order keeps the generated SQL stable between requests.\n const marked = softDelete?.(tableName);\n const deleted = marked ? softDeletePredicate(marked, table, mode ?? 'EXCLUDE') : undefined;\n const hook = scopes?.(tableName);\n if (!hook) {\n return deleted;\n }\n const predicate = hook(context, table);\n if (predicate === undefined || predicate === null) {\n return deleted;\n }\n if (is(predicate, SQL)) {\n return and(deleted, predicate as SQL);\n }\n if (typeof predicate !== 'object') {\n throw new GraphQLError(\n `Drizzle-GraphQL Error: the scope for '${tableName}' returned a ${typeof predicate}. A scope returns a filter object, a Drizzle SQL expression, or undefined.`,\n );\n }\n // A filter object is compiled the same way the field's own `where` is, against the\n // table it was handed — which is what keeps it correct under RQB aliasing.\n return and(deleted, extractFilters(table, tableName, predicate as any, relationFilterCtx(filterCtx, tableName)));\n },\n };\n};\n\n/**\n * `condition AND <the row policies of tableName>` — the single way a scope or a soft-delete\n * predicate is ever combined with a caller-supplied filter, so a `where` can only ever narrow\n * them, never widen them. `mode` is the read's `deleted` argument, and defaults to hiding\n * marked rows; a write passes nothing and so never touches one.\n */\nexport const withScope = (\n scope: ScopeResolver | undefined,\n tableName: string,\n table: Table,\n condition: SQL | undefined,\n mode?: DeletedMode,\n): SQL | undefined => {\n const predicate = scope?.on(tableName, table, mode);\n return predicate ? and(condition, predicate) : condition;\n};\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Context-derived column values\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Produces one column's value from the GraphQL context. See `BuildSchemaConfig.contextValues`. */\nexport type ContextValueHook<TContext = any> = (context: TContext) => any;\n\n/** Build-time lookup: the context-derived columns of a table, keyed by column property name. */\nexport type ContextValuesFor = (tableName: string) => Record<string, ContextValueHook> | undefined;\n\n/**\n * The two request-time policies a generated resolver applies, passed to the dialect\n * generators as one value so a table's read scope and its server-owned columns travel\n * together. Both stay `undefined` when nothing is configured, and every call site checks\n * before doing any work — an unconfigured build generates exactly the SQL it did before.\n */\nexport type TablePolicies = {\n /** See `BuildSchemaConfig.scope`. */\n scope?: ScopeFor;\n /** See `BuildSchemaConfig.contextValues`. */\n contextValues?: ContextValuesFor;\n /** See `BuildSchemaConfig.softDelete`. */\n softDelete?: SoftDeleteFor;\n};\n\n/**\n * {@link TablePolicies} with the scope already bound to the build's relation context, which\n * is what a dialect generator is handed: `scope(context)` is all a resolver needs to compile\n * a predicate, and it stays `undefined` when nothing is scoped.\n */\nexport type ResolverPolicies = {\n scope?: (context: any) => ScopeResolver | undefined;\n contextValues?: ContextValuesFor;\n softDelete?: SoftDeleteFor;\n};\n\n/** Binds a build's {@link TablePolicies} to its relation context, once, at schema-build time. */\nexport const bindPolicies = (\n policies: TablePolicies | undefined,\n filterCtx: RelationFilterBase | undefined,\n): ResolverPolicies | undefined =>\n policies?.scope || policies?.contextValues || policies?.softDelete\n ? {\n scope:\n policies.scope || policies.softDelete\n ? (context: any) => resolveScope(policies, context, filterCtx)\n : undefined,\n contextValues: policies.contextValues,\n softDelete: policies.softDelete,\n }\n : undefined;\n\n/**\n * Merges a table's context-derived values into one row's insert values. The hooks run per\n * row — a value may depend on the row's own contents through the closure the caller built —\n * and they overwrite whatever was there: the columns are not in the create input, so nothing\n * legitimate can be lost, but a stitched-in input could still carry the key and the server's\n * value has to win.\n */\nexport const applyContextValues = (\n values: Record<string, any>,\n hooks: Record<string, ContextValueHook> | undefined,\n context: any,\n): Record<string, any> => {\n if (!hooks) {\n return values;\n }\n for (const [columnName, hook] of Object.entries(hooks)) {\n values[columnName] = hook(context);\n }\n return values;\n};\n\n/** {@link applyContextValues} over a batch — every row in an insert gets its own evaluation. */\nexport const applyContextValuesAll = (\n rows: Record<string, any>[],\n hooks: Record<string, ContextValueHook> | undefined,\n context: any,\n): Record<string, any>[] => {\n if (!hooks) {\n return rows;\n }\n for (const row of rows) {\n applyContextValues(row, hooks, context);\n }\n return rows;\n};\n\n/**\n * Drops context-derived columns from an update's `set`. They are not in the update input\n * either, so this only matters when the key arrives some other way — and reassigning one is\n * exactly the ownership transfer the feature exists to prevent.\n */\nexport const stripContextValues = (\n values: Record<string, any>,\n hooks: Record<string, ContextValueHook> | undefined,\n): Record<string, any> => {\n if (!hooks) {\n return values;\n }\n for (const columnName of Object.keys(hooks)) {\n delete values[columnName];\n }\n return values;\n};\n\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 scope?: ScopeResolver,\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 const relDeleted = (relationArgs as any)?.deleted as DeletedMode | undefined;\n // The eager path is the one read that never passes through the relation field's own\n // resolver, so the target's scope has to be applied here as well — otherwise selecting a\n // relation would be the way around it.\n thisRecord.where =\n relWhere || scope?.has(targetTableName, relDeleted)\n ? {\n RAW: (aliasedTable: Table) =>\n withScope(\n scope,\n targetTableName,\n aliasedTable,\n relWhere\n ? extractFilters(aliasedTable, relName, relWhere, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n relDeleted,\n ),\n }\n : undefined;\n // When a relation is paginated (limit/offset) but unordered, default to the target's\n // primary key so the per-parent slice is deterministic. Drizzle's RQB calls orderBy\n // with the aliased table proxy, so resolve the PK columns from it. targetPkNames is\n // resolved at build time and includes composite keys.\n const hasPagination = offset != null || limit != null;\n const pkNames = targetPkNames ?? [];\n thisRecord.orderBy = relationArgs?.orderBy\n ? (aliasedTable: Table) =>\n extractOrderBy(aliasedTable, relationArgs.orderBy!, relationFilterCtx(filterCtx, targetTableName), relWhere)\n : hasPagination && pkNames.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined;\n thisRecord.offset = offset;\n thisRecord.limit = limit;\n\n const relWith = relationField\n ? extractRelationsParamsInner(\n relationMap,\n tables,\n targetTableName,\n relTypeName,\n relationField,\n typeNameMapper,\n false,\n filterCtx,\n limits,\n scope,\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 scope?: ScopeResolver,\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 scope,\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 * Why the given `orderBy` cannot back a cursor, as the message to raise — or `undefined`\n * when it can. Both cases sort on something that is not a value of the row: a related row's\n * column, or a position in the request's own `inArray` list. `after` raises the message and\n * the `cursor` field resolves to null, while the ordering itself still applies.\n */\nexport const orderByCursorObstacle = (orderBy: Record<string, any> | undefined): string | undefined => {\n if (orderByHasRelationEntry(orderBy)) {\n return \"'after' cannot be combined with an orderBy that orders through a relation — a related row's value cannot be encoded into a cursor.\";\n }\n if (\n orderBy &&\n Object.values(orderBy).some((config) => config && typeof config === 'object' && config.matchFilterOrder)\n ) {\n return \"'after' cannot be combined with 'matchFilterOrder' — a row's position in the request's own filter list is not a value of the row, so it cannot be encoded into a cursor.\";\n }\n return undefined;\n};\n\n/**\n * The total order a list query's rows follow when cursor pagination is in play: the request's\n * `orderBy` entries (highest priority first), then the primary key ascending as a tiebreak —\n * skipping PK columns the `orderBy` already names, so no key appears twice.\n */\nexport const cursorOrderingEntries = (\n orderBy: Record<string, any> | undefined,\n pkNames: readonly string[],\n): CursorOrderEntry[] => {\n const entries: CursorOrderEntry[] = orderBy ? orderByEntries(orderBy) : [];\n const seen = new Set(entries.map(([column]) => column));\n for (const pk of pkNames) {\n if (!seen.has(pk)) {\n entries.push([pk, 'asc']);\n }\n }\n return entries;\n};\n\n/**\n * ORDER BY expressions realizing a cursor's total order on `table` (which may be the aliased\n * RQB proxy) — each key's direction plus its `nulls` override, exactly the order the keyset\n * predicate in {@link buildCursorCondition} compares against.\n */\nexport const cursorOrderExprs = (table: Table, entries: CursorOrderEntry[]): SQL[] => {\n const cols = getColumns(table);\n return entries.flatMap(([column, direction, nulls]) =>\n orderExpressions(cols[column]!, direction, nulls ?? undefined, cols[column]!),\n );\n};\n\n/**\n * Serializes one ordering-tuple value into a JSON-safe shape. Dates and bigints don't survive\n * JSON.stringify losslessly (bigint throws, Date turns into an untagged string), so they are\n * tagged; decimals already arrive from the driver as strings, which are lossless as-is.\n */\nconst encodeCursorValue = (value: any): any => {\n if (value instanceof Date) {\n return { $type: 'date', value: value.toISOString() };\n }\n if (typeof value === 'bigint') {\n return { $type: 'bigint', value: value.toString() };\n }\n return value;\n};\n\nconst decodeCursorValue = (value: any): any => {\n if (value && typeof value === 'object' && typeof value.$type === 'string') {\n if (value.$type === 'date') {\n return new Date(value.value);\n }\n if (value.$type === 'bigint') {\n return BigInt(value.value);\n }\n }\n return value;\n};\n\n/**\n * Encodes a row's position in the given total order as an opaque cursor: base64url of a JSON\n * payload holding the ordering spec (`o`) and the row's values for it (`v`). The spec rides\n * along so a later request can verify the cursor was issued for the same ordering it is using.\n */\nexport const encodeCursor = (entries: CursorOrderEntry[], row: Record<string, any>): string => {\n 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 = visibleColumns(table);\n const propNameByColumnName = new Map(Object.entries(cols).map(([propName, col]) => [(col as any).name, propName]));\n // A set is usable only if every one of its columns maps back to a property on the table.\n const toPropNames = (columnNames: (string | undefined)[]): string[] | undefined => {\n const propNames: string[] = [];\n for (const columnName of columnNames) {\n const propName = columnName === undefined ? undefined : propNameByColumnName.get(columnName);\n if (!propName) {\n return undefined;\n }\n propNames.push(propName);\n }\n return propNames.length ? propNames : undefined;\n };\n\n const config = getTableConfig(table);\n const candidates: (string[] | undefined)[] = [\n // Inline `.primaryKey()` columns, then table-level `primaryKey({ columns })`.\n Object.entries(cols)\n .filter(([, col]) => (col as any).primary)\n .map(([propName]) => propName),\n ...config.primaryKeys.map((pk) => toPropNames(pk.columns.map((c) => c.name))),\n ...(config.uniqueConstraints ?? []).map((uc) => toPropNames(uc.columns.map((c) => c.name))),\n ...(config.indexes ?? [])\n .filter((index) => index.config.unique)\n .map((index) => toPropNames(index.config.columns.map((c) => (c as any)?.name))),\n ...Object.entries(cols)\n .filter(([, col]) => (col as any).isUnique)\n .map(([propName]) => [propName]),\n ];\n\n const seen = new Set<string>();\n const sets: string[][] = [];\n for (const set of candidates) {\n if (!set?.length) {\n continue;\n }\n const key = [...set].sort().join(',');\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n sets.push(set);\n }\n return sets;\n};\n\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 name,\n * exclusions), like the order/filter inputs, so repeated builds reuse one instance and two\n * enums over the same table never collide.\n *\n * Returns `undefined` when no column qualifies — the caller then omits the argument or\n * input field the enum would have typed, rather than emitting an empty enum, which is\n * invalid GraphQL.\n */\nexport const generateColumnEnum = (\n table: Table,\n enumName: string,\n description: string,\n predicate: (column: Column, columnName: string) => boolean = () => true,\n): GraphQLEnumType | undefined => {\n // The exclusions are part of the key, not a reason to skip the cache: a table's enum is\n // asked for from more than one place in a build (a list query's `distinct` argument and the\n // same argument on a to-many relation field pointing at it), and handing those two call\n // sites separate instances would put two types of the same name in one schema.\n const cacheKey = `${enumName}\\u0000${excludedColumnsKey(table)}`;\n let tableCache = columnEnumCache.get(table);\n const cached = tableCache?.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const columnNames = Object.entries(visibleColumns(table))\n .filter(([columnName, column]) => predicate(column as Column, columnName))\n .map(([columnName]) => columnName);\n if (!columnNames.length) {\n return undefined;\n }\n\n const enumType = new GraphQLEnumType({\n name: enumName,\n description,\n values: Object.fromEntries(columnNames.map((columnName) => [columnName, { value: columnName }])),\n });\n\n if (!tableCache) {\n tableCache = new Map();\n columnEnumCache.set(table, tableCache);\n }\n tableCache.set(cacheKey, enumType);\n return enumType;\n};\n\n/** `${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 scope?: ScopeResolver;\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 params.scope,\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; restore?: 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 restoreFieldName: string;\n restoreSingleFieldName: 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 soft-delete counterpart, named the same way so `deleteUser` / `restoreUser` read as a\n // pair however the delete prefix and the single suffix are configured.\n const restoreFieldName = `${prefixes.restore ?? 'restore'}${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 const restoreSingleFieldName = `${restoreFieldName}${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 restoreFieldName,\n restoreSingleFieldName,\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. */\n/**\n * The `deleted` argument, emitted only on reads over a table that declares a soft-delete\n * column — a schema with no soft delete anywhere keeps exactly the arguments it had.\n */\nexport const deletedArg = (\n softDelete: SoftDeleteFor | undefined,\n tableName: string,\n): Record<string, { type: any; description: string }> =>\n softDelete?.(tableName)\n ? {\n deleted: {\n type: deletedFilterEnum,\n description: 'Whether rows marked deleted are returned. Defaults to EXCLUDE.',\n },\n }\n : {};\n\nexport const selectArrayArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n distinctEnum?: GraphQLEnumType,\n softDelete?: SoftDeleteFor,\n tableName?: string,\n): Record<string, { type: any; description?: string }> => ({\n offset: { type: GraphQLInt },\n limit: { type: GraphQLInt },\n orderBy: { type: orderArgs },\n where: { type: filterArgs },\n after: {\n type: GraphQLString,\n description:\n \"Keyset pagination: only return rows strictly after this cursor (a row's `cursor` field from a previous page, under the same orderBy).\",\n },\n ...(distinctEnum ? { distinct: { type: new GraphQLList(new GraphQLNonNull(distinctEnum)) } } : {}),\n ...deletedArg(softDelete, tableName!),\n});\n\n/** GraphQL argument map for a single-row select field (no `limit`). */\nexport const selectSingleArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n softDelete?: SoftDeleteFor,\n tableName?: string,\n): Record<string, { type: any }> => ({\n offset: { type: GraphQLInt },\n orderBy: { type: orderArgs },\n where: { type: filterArgs },\n ...deletedArg(softDelete, tableName!),\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 scope?: ScopeResolver;\n deleted?: DeletedMode;\n}): Promise<any> => {\n const {\n queryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n offset,\n orderBy,\n where,\n single,\n filterCtx,\n pkNames,\n after,\n scope,\n deleted,\n } = opts;\n const distinct = opts.distinct?.length ? opts.distinct : undefined;\n\n // ── keyset (cursor) pagination ──\n // Active when the request passes `after` or selects the `cursor` meta field. The cursor is\n // defined over a total order — the request's orderBy plus the primary-key tiebreak — so both\n // need the PK; a table without one gets an error for `after` and null cursors otherwise.\n const cursorSelected = !single && isCursorFieldSelected(parsedInfo.fieldsByTypeName[typeName], table);\n let cursorEntries: CursorOrderEntry[] | undefined;\n if (!single && (after != null || cursorSelected)) {\n if (after != null && distinct) {\n throw new GraphQLError(\"'after' cannot be combined with 'distinct'.\");\n }\n const cursorObstacle = orderByCursorObstacle(orderBy);\n if (cursorObstacle) {\n if (after != null) {\n throw new GraphQLError(cursorObstacle);\n }\n // `cursor` was selected under an ordering a cursor cannot express — the field resolves\n // to null and the ordering itself still applies.\n } else if (!pkNames?.length) {\n if (after != null) {\n throw 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: withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n deleted,\n ),\n orderBy,\n limit: single ? 1 : opts.limit,\n offset,\n });\n\n if (!distinctKeys.length) {\n return single ? undefined : [];\n }\n }\n\n const params: any = {\n columns: extractSelectedColumnsFromTree(parsedInfo.fieldsByTypeName[typeName]!, table, {\n tableName,\n relationMap,\n tables,\n allRelations: filterCtx?.relationMap,\n }),\n offset: distinctKeys ? undefined : offset,\n // drizzle-orm v1 RQB calls orderBy/where with the aliased table proxy — use it\n // directly so column refs match the CTE alias.\n orderBy: distinctKeys\n ? (aliasedTable: Table) => [\n ...(orderBy ? extractOrderBy(aliasedTable, orderBy, relationFilterCtx(filterCtx, tableName), where) : []),\n ...primaryKeyOrderExprs(aliasedTable, pkNames!),\n ]\n : cursorEntries\n ? // Cursor pagination needs a total order: the request's orderBy plus the PK tiebreak,\n // exactly the ordering the cursor encodes and the keyset predicate compares against.\n (aliasedTable: Table) => cursorOrderExprs(aliasedTable, cursorEntries!)\n : orderBy\n ? (aliasedTable: Table) =>\n extractOrderBy(aliasedTable, orderBy, relationFilterCtx(filterCtx, tableName), where)\n : needsDefaultOrder && pkNames?.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined,\n where: distinctKeys\n ? // The distinct pass already ran inside the scope, so the keys it picked are in it.\n { RAW: (aliasedTable: Table) => primaryKeyRestriction(aliasedTable, pkNames!, distinctKeys!) }\n : where || cursorValues || scope?.has(tableName, deleted)\n ? {\n RAW: (aliasedTable: Table) =>\n withScope(\n scope,\n tableName,\n aliasedTable,\n and(\n where\n ? extractFilters(aliasedTable, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n cursorValues\n ? buildCursorCondition(\n aliasedTable,\n cursorEntries!,\n cursorValues,\n opts.nullOrdering ?? 'nulls-smallest',\n )\n : undefined,\n ),\n deleted,\n ),\n }\n : undefined,\n with: relationMap[tableName]\n ? extractRelationsParams(\n relationMap,\n tables,\n tableName,\n parsedInfo,\n typeName,\n typeNameMapper,\n filterCtx,\n opts.limits,\n scope,\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\n/**\n * The `typeNameMapper` preset behind `typeNameMapper: 'singularize'`.\n *\n * Derives the singular and plural forms of a table key with the library's own `pluralize`,\n * which is what nearly every consumer with plural table keys (`export const tasks =\n * pgTable('tasks', …)`) was writing by hand — and adding `pluralize` to their own\n * dependencies to write.\n *\n * `tasks` becomes type `Task`, queries `tasks` / `task`, mutations `createTasks` /\n * `createTask`. A key that is already singular is pluralized for the list side, so `task`\n * yields the same names, and a capitalized key (`Tasks`) yields them too — the field forms\n * are uncapitalized so the generated names follow GraphQL's camelCase convention whatever\n * the schema key looks like. The type name is capitalized by the generator either way.\n */\nexport const singularizeMapper = (tableName: string): { singular: string; plural: string } => ({\n singular: uncapitalize(pluralize.singular(tableName)),\n plural: uncapitalize(pluralize.plural(tableName)),\n});\n","// @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","/**\n * The identity a generated field publishes about itself, under `extensions.drizzle`.\n *\n * Every field this library generates carries one, so a wrapper — `graphql-middleware`,\n * envelop, `graphql-shield`, an audit log, a cache invalidator — can ask the schema what a\n * field is instead of reverse-engineering its name. Names are configurable (`prefixes`,\n * `suffixes`, `typeNameMapper`), so name parsing is ambiguous by construction; this is not.\n *\n * This shape is stable API: fields are only ever added to it, never removed or repurposed.\n */\n\n/** What family of field this is. */\nexport type DrizzleFieldKind = 'query' | 'mutation' | 'relation' | 'aggregate' | 'type';\n\n/**\n * What the field does. Arity is carried separately by `single`, so `select` covers both\n * the list query and its `…Single` sibling rather than being spelled twice.\n */\nexport type DrizzleFieldOperation =\n | 'select'\n | 'insert'\n | 'update'\n | 'updateMany'\n | 'upsert'\n | 'delete'\n | 'restore'\n | 'aggregate'\n | 'groupBy'\n | 'relation'\n | 'relationAggregate';\n\n/** The argument holding the rows a field is about, when it has one. */\nexport type DrizzleTargetArg = 'where' | 'values' | 'updates';\n\n/** `extensions.drizzle` on a generated field. */\nexport type DrizzleFieldExtension = {\n /** The Drizzle schema key of the table the field reads or writes. */\n table: string;\n kind: Exclude<DrizzleFieldKind, 'type'>;\n operation: DrizzleFieldOperation;\n /** Whether the field resolves to one row (or one aggregate) rather than a list. */\n single: boolean;\n /**\n * Which argument names the rows: `where` for select/update/delete/aggregate, `values`\n * for insert and upsert, `updates` for the batch update's per-entry `{ where, set }`.\n * Absent when the field takes no such argument.\n */\n targetArg?: DrizzleTargetArg;\n /**\n * Primary-key property names of `table`, in schema order. Empty when the table declares\n * no primary key. Carried here so {@link identifyRows} works from the field alone.\n */\n primaryKey: readonly string[];\n /** For `kind: 'relation'` and `operation: 'relationAggregate'`: the relation's name. */\n relation?: string;\n /** For `kind: 'relation'` and `operation: 'relationAggregate'`: the table it hangs off. */\n parentTable?: string;\n};\n\n/** `extensions.drizzle` on a generated object type. */\nexport type DrizzleTypeExtension = {\n /** The Drizzle schema key this type was generated from. */\n table: string;\n kind: 'type';\n /** Primary-key property names of `table`, in schema order. Empty when there is none. */\n primaryKey: readonly string[];\n};\n\nexport type DrizzleExtension = DrizzleFieldExtension | DrizzleTypeExtension;\n\n/** Anything carrying GraphQL `extensions` — a field config, a field, or a named type. */\ntype WithExtensions = { extensions?: { drizzle?: unknown } | null } | null | undefined;\n\n/**\n * Reads the `drizzle` extension off a field or type, typed. Returns `undefined` for\n * anything this library did not generate, which is the check a wrapper wants before it\n * treats a field as one of ours.\n */\nexport const drizzleExtension = (target: WithExtensions): DrizzleExtension | undefined => {\n const value = target?.extensions?.drizzle;\n return value && typeof value === 'object' ? (value as DrizzleExtension) : undefined;\n};\n\n/** Narrows to the field form — object types carry `kind: 'type'` and no operation. */\nexport const isDrizzleFieldExtension = (value: DrizzleExtension | undefined): value is DrizzleFieldExtension =>\n !!value && value.kind !== 'type';\n\n/**\n * Builds the extension for one table's fields. Dialect builders make one per table so each\n * call site only states what differs.\n */\nexport const tableFieldExtensions =\n (table: string, primaryKey: readonly string[]) =>\n (meta: Omit<DrizzleFieldExtension, 'table' | 'primaryKey'>): DrizzleFieldExtension => ({\n table,\n primaryKey,\n ...meta,\n });\n\n/**\n * The parts of a mutation's identity that differ between mutations. Dialect builders that\n * assign every mutation in one loop pair each generated mutation with one of these.\n */\nexport type DrizzleMutationMeta = Pick<DrizzleFieldExtension, 'operation' | 'single' | 'targetArg'>;\n\n/** Builds the extension a generated object type carries. */\nexport const tableTypeExtension = (table: string, primaryKey: readonly string[]): DrizzleTypeExtension => ({\n table,\n kind: 'type',\n primaryKey,\n});\n\n/**\n * Builds the extension a relation field carries. `table` is the relation's *target* — the\n * table the field resolves rows of — while `parentTable` is the type the field hangs off,\n * so a wrapper can tell `Users.posts` from `Customers.posts`.\n */\nexport const relationFieldExtension = (params: {\n targetTable: string;\n parentTable: string;\n relation: string;\n single: boolean;\n primaryKey: readonly string[];\n aggregate?: boolean;\n}): DrizzleFieldExtension => ({\n table: params.targetTable,\n kind: params.aggregate ? 'aggregate' : 'relation',\n operation: params.aggregate ? 'relationAggregate' : 'relation',\n // An aggregate over a to-many relation still resolves to a single aggregate object.\n single: params.aggregate ? true : params.single,\n targetArg: 'where',\n primaryKey: params.primaryKey,\n relation: params.relation,\n parentTable: params.parentTable,\n});\n\n/** The rows a field's arguments name. */\nexport type IdentifiedRows = {\n /** The Drizzle schema key of the table being read or written. */\n table: string;\n /** Primary-key property names, in schema order. */\n primaryKey: readonly string[];\n /** One entry per identified row: the primary-key values, keyed by property name. */\n rows: Record<string, unknown>[];\n /**\n * Whether `rows` is exactly the set the operation affects.\n *\n * `false` means the arguments do not pin the rows down — an insert whose key the\n * database generates, a `where` that filters on something other than the primary key,\n * a plural update with no filter at all, or a table with no primary key. `rows` is then\n * a best-effort subset-free superset: every entry in it is a row the key values name,\n * but other filters may narrow the real set further, and it may be empty.\n */\n complete: boolean;\n};\n\n/** Pulls the primary-key values out of one `values` entry; `undefined` if any are missing. */\nconst keyFromValues = (entry: unknown, primaryKey: readonly string[]): Record<string, unknown> | undefined => {\n if (!entry || typeof entry !== 'object') {\n return undefined;\n }\n const row: Record<string, unknown> = {};\n for (const column of primaryKey) {\n const value = (entry as Record<string, unknown>)[column];\n if (value === undefined || value === null) {\n return undefined;\n }\n row[column] = value;\n }\n return row;\n};\n\n/**\n * Pulls primary-key values out of a filter argument.\n *\n * Only top-level equality counts: `{ id: { eq } }` names one row, `{ id: { inArray } }`\n * names a list, and a composite key needs `eq` on every one of its columns. A boolean\n * group (`OR` / `AND` / `NOT`) or any other operator on a key column means the filter is\n * not a key lookup, and the rows are reported as not identified.\n */\nconst keysFromWhere = (\n where: unknown,\n primaryKey: readonly string[],\n): { rows: Record<string, unknown>[]; complete: boolean } => {\n const none = { rows: [], complete: false };\n if (!where || typeof where !== 'object' || Array.isArray(where)) {\n return none;\n }\n const filters = where as { OR?: unknown; AND?: unknown; NOT?: unknown; [column: string]: any };\n if (filters.OR || filters.AND || filters.NOT) {\n return none;\n }\n\n // A composite key is only pinned by an equality on each of its columns — one column\n // carrying a list would describe a rectangle of key tuples, not the rows written.\n if (primaryKey.length > 1) {\n const row: Record<string, unknown> = {};\n for (const column of primaryKey) {\n const operators = filters[column];\n if (!operators || typeof operators !== 'object' || operators.eq === undefined) {\n return none;\n }\n row[column] = operators.eq;\n }\n // Filters beyond the key can only narrow further, so the key alone is not the answer.\n return { rows: [row], complete: Object.keys(filters).length === primaryKey.length };\n }\n\n const column = primaryKey[0];\n if (!column) {\n return none;\n }\n const operators = filters[column];\n if (!operators || typeof operators !== 'object') {\n return none;\n }\n\n const exact = Object.keys(filters).length === 1 && Object.keys(operators).length === 1;\n if (operators.eq !== undefined) {\n return { rows: [{ [column]: operators.eq }], complete: exact };\n }\n if (Array.isArray(operators.inArray)) {\n return { rows: operators.inArray.map((value: unknown) => ({ [column]: value })), complete: exact };\n }\n return none;\n};\n\n/**\n * The rows a generated field's arguments are about, as primary-key values.\n *\n * The row identity of a mutation lives in a different argument for every operation —\n * `where` for update and delete, `values` for insert and upsert, a per-entry `where` inside\n * `updates` for the batch update — and each of those has both a one-row and a many-row\n * spelling. This reads whichever one applies:\n *\n * ```ts\n * const field = info.parentType.getFields()[info.fieldName];\n * const target = identifyRows(field, args);\n * if (target?.complete) await invalidate(target.table, target.rows);\n * ```\n *\n * Returns `undefined` for a field this library did not generate, or an object type. Check\n * `complete` before treating `rows` as the affected set — see {@link IdentifiedRows}.\n */\nexport const identifyRows = (\n field: WithExtensions,\n args: Record<string, unknown> | undefined,\n): IdentifiedRows | undefined => {\n const meta = drizzleExtension(field);\n if (!isDrizzleFieldExtension(meta)) {\n return undefined;\n }\n\n const { table, primaryKey, targetArg } = meta;\n const empty: IdentifiedRows = { table, primaryKey, rows: [], complete: false };\n if (!primaryKey.length || !targetArg) {\n return empty;\n }\n\n const target = args?.[targetArg];\n\n if (targetArg === 'values') {\n // Both spellings of insert/upsert land here: the single variant takes one object.\n const entries = Array.isArray(target) ? target : target === undefined ? [] : [target];\n const rows = entries.map((entry) => keyFromValues(entry, primaryKey));\n return {\n table,\n primaryKey,\n rows: rows.filter((row): row is Record<string, unknown> => !!row),\n // A row whose key the database generates is not identifiable before the write.\n complete: entries.length > 0 && rows.every(Boolean),\n };\n }\n\n if (targetArg === 'updates') {\n if (!Array.isArray(target)) {\n return empty;\n }\n const perEntry = target.map((entry) =>\n keysFromWhere((entry as { where?: unknown } | undefined)?.where, primaryKey),\n );\n return {\n table,\n primaryKey,\n rows: perEntry.flatMap((entry) => entry.rows),\n complete: target.length > 0 && perEntry.every((entry) => entry.complete),\n };\n }\n\n return { table, primaryKey, ...keysFromWhere(target, primaryKey) };\n};\n","// @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 applyContextValues,\n applyContextValuesAll,\n applyLimitPolicy,\n assertSingleMatch,\n attachTargetPrimaryKeys,\n bindPolicies,\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 type ResolverPolicies,\n registerColumnExclusions,\n relationFilterCtx,\n resolveConflictPlan,\n resolveQueryExecutor,\n runMutation,\n runRelationalSelect,\n selectArrayArgs,\n selectSingleArgs,\n stripContextValues,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n withScope,\n} from '../builders/common.ts';\nimport { remapFromGraphQLArrayInput, remapFromGraphQLSingleInput } from '../data-mappers/index.ts';\nimport { type DrizzleMutationMeta, tableFieldExtensions } from '../extensions.ts';\nimport { resolveTableFeatures } from '../features.ts';\nimport { registerEnumConfig, registerScalarOverrides } from '../type-converter/index.ts';\nimport {\n createRelationAggregateFactory,\n generateAggregate,\n generateAggregateTypes,\n generateGroupBy,\n generateGroupByEnum,\n generateGroupByType,\n generateHavingInput,\n} from './aggregates.ts';\nimport { remapUpdateInput } from './field-updates.ts';\nimport type {\n CreatedResolver,\n Filters,\n SchemaGeneratorOptions,\n TableFeatures,\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 policies?: ResolverPolicies,\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 policies?.softDelete,\n tableName,\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 scope: policies?.scope?.(context),\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 policies?: ResolverPolicies,\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, policies?.softDelete, tableName);\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 scope: policies?.scope?.(context),\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 policies?: ResolverPolicies,\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 = applyContextValuesAll(\n remapFromGraphQLArrayInput(args.values, table),\n policies?.contextValues?.(tableName),\n context,\n );\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 policies?: ResolverPolicies,\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 = applyContextValues(\n remapFromGraphQLSingleInput(args.values, table),\n policies?.contextValues?.(tableName),\n context,\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 generateUpsert = (\n db: MySqlDatabase<any, any, any, any>,\n tableName: string,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n onConflictType: GraphQLInputObjectType,\n fieldName: string,\n single: boolean,\n txCtx?: MutationTxCtx,\n policies?: ResolverPolicies,\n): CreatedResolver => {\n const 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 = applyContextValuesAll(\n single\n ? [remapFromGraphQLSingleInput(args.values as Record<string, any>, table)]\n : remapFromGraphQLArrayInput(args.values as Record<string, any>[], table),\n policies?.contextValues?.(tableName),\n context,\n );\n if (!input.length) {\n throw 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 policies?: ResolverPolicies,\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 const scope = policies?.scope?.(context);\n\n // A context-derived column is the server's to set, so an update never reassigns\n // one — that is what stops a row being handed to another owner.\n const input = stripContextValues(\n remapUpdateInput(set, table, tableName),\n policies?.contextValues?.(tableName),\n );\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 // The scope is ANDed on last, so a caller-supplied `where` can only narrow it.\n const filters = withScope(\n scope,\n tableName,\n table,\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined,\n );\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 policies?: ResolverPolicies,\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 const scope = policies?.scope?.(context);\n const contextColumns = policies?.contextValues?.(tableName);\n\n // Remap and validate every entry before the transaction opens, so a malformed\n // entry rejects the request instead of rolling back mid-batch.\n const entries = updates.map(({ where, set }) => {\n const input = stripContextValues(remapUpdateInput(set, table, tableName), contextColumns);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n filters: withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n ),\n };\n });\n\n // On a caller-supplied transaction — or the shared multi-mutation transaction\n // opened by `runMutation` — this opens a savepoint, so the batch stays atomic\n // without breaking the outer transaction.\n await executor.transaction(async (tx: any) => {\n for (const entry of entries) {\n let query = tx.update(table).set(entry.set);\n if (entry.filters) {\n query = query.where(entry.filters) as any;\n }\n await query;\n }\n });\n\n return { isSuccess: true };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\n/**\n * `delete<Table>` and, for a table that declares a soft-delete column, `restore<Table>`.\n * MySQL's writes return no rows either way, so both answer `{ isSuccess: true }` — the\n * difference from the other dialects is only what the payload can say, not what runs.\n */\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 policies?: ResolverPolicies,\n restore: boolean = false,\n): CreatedResolver => {\n const softDelete = policies?.softDelete?.(tableName);\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 const scope = policies?.scope?.(context);\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // Same rule as update: the scope is ANDed on last, so a delete can only ever reach\n // rows inside it — an out-of-scope row is not matched rather than being refused.\n // A soft-deleting table adds the marker predicate the same way: `delete` only sees\n // rows that are not already marked, `restore` only sees the ones that are.\n const filters = withScope(\n scope,\n tableName,\n table,\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined,\n restore ? 'ONLY' : undefined,\n );\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = softDelete\n ? executor\n .update(table)\n .set({ [softDelete.columnName]: restore ? softDelete.writeRestored : softDelete.writeDeleted() })\n : executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n await query;\n\n 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 // Excluded tables are dropped here, before anything reads `tableEntries` — which also makes\n // `buildNamedRelations` skip every relation pointing at one, since it resolves targets\n // through this list.\n const excludedTables = new Set(options.exclude?.tables ?? []);\n const tableEntries = schemaEntries.filter(([key, value]) => is(value, MySqlTable) && !excludedTables.has(key)) as [\n string,\n MySqlTable,\n ][];\n const tables = Object.fromEntries(tableEntries);\n\n // A feature flag may be a per-table predicate, so every flag is resolved against the table\n // it applies to. `anyTable` answers the build-wide question — whether machinery shared\n // across tables is worth constructing at all.\n const featureOf = resolveTableFeatures(features);\n const anyTable = (feature: keyof TableFeatures) => tableEntries.some(([name]) => featureOf(name)[feature]);\n\n if (!tableEntries.length) {\n throw new Error(\n \"Drizzle-GraphQL Error: No tables detected in Drizzle-ORM's database instance. Did you forget to pass schema to drizzle constructor?\",\n );\n }\n\n // 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 // And the same for column exclusions: a per-build registry read by every site that decides\n // what the schema contains, reset here so a rebuild never inherits the previous build's.\n registerColumnExclusions(tables, options.exclude);\n\n // Build namedRelations from the drizzle-orm v1 relations config.\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Relations *into* an excluded table are already gone (their target no longer resolves);\n // relations *out of* one have no type left to hang a field on.\n for (const excluded of excludedTables) {\n delete namedRelations[excluded];\n }\n // Record each relation target's (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 // The row scope compiled against this build's relation graph, plus the columns whose value\n // the server supplies. Both stay undefined unless configured.\n const tablePolicies = options.policies;\n const contextValuesOf = tablePolicies?.contextValues;\n const softDeleteOf = tablePolicies?.softDelete;\n const policies = bindPolicies(tablePolicies, filterCtx);\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(\n db,\n tables,\n 'nulls-smallest',\n filterCtx,\n limits,\n tablePolicies,\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 primaryKeyOf: (name) => (tables[name] ? mysqlPrimaryKeyPropNames(tables[name] as MySqlTable) : []),\n contextValuesOf,\n softDeleteOf,\n featureOf,\n };\n\n // Built when at least one table wants relation aggregates; a table that has them off is\n // handed `undefined` below, so `generateTableTypes` emits no `${relation}Aggregate` fields\n // on its object type.\n const relationAggregateFactory: RelationAggregateFactory | undefined = anyTable('relationAggregates')\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx, tablePolicies)\n : undefined;\n\n const 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 featureOf(tableName).relationAggregates ? relationAggregateFactory : undefined,\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 ((['insert', 'upsert', 'update', 'delete'] as const).some((feature) => anyTable(feature))) {\n outputs.MutationReturn = mutationReturnType;\n }\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n // Everything this table generates, with any per-table predicate already run.\n const tableFeatures = featureOf(tableName);\n // What every field this table generates publishes about itself under `extensions.drizzle`,\n // so a wrapper can read a field's identity instead of parsing its configurable name.\n const drizzleMeta = tableFieldExtensions(tableName, mysqlPrimaryKeyPropNames(schema[tableName] as MySqlTable));\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 restoreFieldName,\n restoreSingleFieldName,\n deleteCountFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\n // A table that marks rows deleted instead of removing them also gets the mutation that\n // reverses it — clearing the column through an ordinary update is not possible, since the\n // column is not in the update input and a marked row is invisible to a `where` anyway.\n const softDeleteInfo = softDeleteOf?.(tableName);\n\n const selectArrGenerated = generateSelectArray(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n listFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n tableFeatures.distinct,\n limits,\n policies,\n );\n const selectSingleGenerated = generateSelectSingle(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n singleFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n limits,\n policies,\n );\n const insertArrGenerated = tableFeatures.insert\n ? generateInsertArray(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n createArrayFieldName,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const insertSingleGenerated = tableFeatures.insert\n ? generateInsertSingle(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n createSingleFieldName,\n mutationTxCtx,\n policies,\n )\n : undefined;\n // MySQL detects a conflict on any unique key, so unlike PostgreSQL and SQLite every\n // table can be upserted — there is no target to validate.\n const onConflictInput = tableFeatures.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as MySqlTable,\n typeName,\n uniqueSets: [],\n tableFilters,\n withTarget: false,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n onConflictInput,\n upsertArrayFieldName,\n false,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const upsertSingleGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n onConflictInput,\n upsertSingleFieldName,\n true,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const updateGenerated = tableFeatures.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateFieldName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const updateSingleGenerated = tableFeatures.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n tableFeatures.update && tableFeatures.updateMany\n ? generateUpdateManyInput({ 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 policies,\n )\n : undefined;\n const deleteGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteFieldName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const deleteSingleGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteSingleFieldName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const restoreGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n restoreFieldName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n const restoreSingleGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n restoreSingleFieldName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n // The count variants are the plural write with its payload left off, so each follows the\n // same feature switch as the write it mirrors.\n const updateCountGenerated =\n tableFeatures.update && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as MySqlTable,\n kind: 'update',\n setArgs: updateInput,\n filterArgs: tableFilters,\n fieldName: updateCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n })\n : undefined;\n const deleteCountGenerated =\n tableFeatures.delete && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as MySqlTable,\n kind: 'delete',\n filterArgs: tableFilters,\n fieldName: deleteCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n })\n : undefined;\n const aggregateType = tableFeatures.aggregates\n ? generateAggregateTypes(schema[tableName] as MySqlTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = tableFeatures.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n tablePolicies,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n tableFeatures.aggregates && tableFeatures.groupBy\n ? generateGroupByType(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 tablePolicies,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: listFieldComplexity(complexity, limits?.(tableName)) } : {}),\n },\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: true, targetArg: 'where' }),\n },\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'aggregate', single: true, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'groupBy', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n };\n }\n // Each mutation is paired with the identity it publishes on `extensions.drizzle`, so a\n // consumer can tell an insert from an upsert without unpicking the configured prefixes.\n const generatedMutations: [typeof insertArrGenerated, DrizzleMutationMeta][] = [\n [insertArrGenerated, { operation: 'insert', single: false, targetArg: 'values' }],\n [insertSingleGenerated, { operation: 'insert', single: true, targetArg: 'values' }],\n [upsertArrGenerated, { operation: 'upsert', single: false, targetArg: 'values' }],\n [upsertSingleGenerated, { operation: 'upsert', single: true, targetArg: 'values' }],\n [updateGenerated, { operation: 'update', single: false, targetArg: 'where' }],\n [updateManyGenerated, { operation: 'updateMany', single: false, targetArg: 'updates' }],\n [updateSingleGenerated, { operation: 'update', single: true, targetArg: 'where' }],\n [deleteGenerated, { operation: 'delete', single: false, targetArg: 'where' }],\n [deleteSingleGenerated, { operation: 'delete', single: true, targetArg: 'where' }],\n [restoreGenerated, { operation: 'restore', single: false, targetArg: 'where' }],\n [restoreSingleGenerated, { operation: 'restore', single: true, targetArg: 'where' }],\n ];\n for (const [generated, meta] of generatedMutations) {\n if (generated) {\n mutations[generated.name] = {\n type: mutationReturnType,\n args: generated.args,\n resolve: generated.resolver,\n extensions: { drizzle: drizzleMeta({ kind: 'mutation', ...meta }) },\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 ...(tableFeatures.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(tableFeatures.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","import type { SchemaFeatures } from '../types.ts';\nimport type { TableFeatures } from './builders/types.ts';\n\n/**\n * What a table generates when the config says nothing. Everything is on except the opt-in\n * features, so a build with no `features` block generates what it always did.\n */\nexport const featureDefaults: TableFeatures = {\n aggregates: true,\n groupBy: true,\n relationAggregates: true,\n distinct: true,\n insert: true,\n update: true,\n updateMany: true,\n delete: true,\n upsert: false,\n fieldUpdateOperations: false,\n countMutations: false,\n requireWhere: false,\n};\n\n/**\n * Turns `BuildSchemaConfig.features` — booleans, per-table predicates, or nothing at all —\n * into a lookup the generators can ask about one table. Memoized, so a predicate is run once\n * per table however many places consult it.\n */\nexport const resolveTableFeatures = (features: SchemaFeatures | undefined): ((tableName: string) => TableFeatures) => {\n const cache = new Map<string, TableFeatures>();\n const names = Object.keys(featureDefaults) as (keyof TableFeatures)[];\n return (tableName: string): TableFeatures => {\n let resolved = cache.get(tableName);\n if (!resolved) {\n resolved = {} as TableFeatures;\n for (const name of names) {\n const configured = features?.[name];\n // A predicate answering with something other than a boolean is answering \"yes\" for\n // anything truthy, matching how the flags read everywhere else.\n resolved[name] =\n configured === undefined\n ? featureDefaults[name]\n : typeof configured === 'function'\n ? !!configured(tableName)\n : !!configured;\n }\n cache.set(tableName, resolved);\n }\n return resolved;\n };\n};\n","// @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 type DeletedMode,\n deletedArg,\n extractFilters,\n extractRelationJoinColumns,\n generateColumnEnum,\n type RelationAggregateFactory,\n type RelationFilterBase,\n relationFilterCtx,\n resolveExecutor,\n resolveScope,\n resolveTypeName,\n type TablePolicies,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n visibleColumns,\n withScope,\n} from './common.ts';\nimport type { CreatedResolver, Filters } from './types.ts';\n\n/** Operations that aggregate over a set of column values. `count` is handled separately (whole rows). */\nconst AGGREGATE_OPS = ['avg', 'sum', 'min', 'max', 'countNonNull', 'countDistinct'] as const;\ntype AggregateOp = (typeof AGGREGATE_OPS)[number];\n\n/** Ops whose result is a row count: never null, and returned as `Int!` rather than the column's type. */\nconst COUNT_OPS = new Set<AggregateOp>(['countNonNull', 'countDistinct']);\n\nconst OP_FNS: Record<AggregateOp, (col: Column) => any> = {\n avg,\n sum,\n min,\n max,\n countNonNull: count,\n countDistinct,\n};\n\n/** Separator for flat select aliases (`avg__price`) — reassembled into nested output by the resolver. */\nconst SEP = '__';\n\ninterface AggregateColumnSets {\n /** Columns avg/sum apply to: plain Int/Float scalars. */\n numeric: Record<string, Column>;\n /** Columns min/max apply to: anything with a total ordering the DB supports (numbers, strings, dates, enums). */\n orderable: Record<string, { column: Column; converted: ConvertedColumn }>;\n /** Every column — `count(col)` is valid whatever the type. */\n all: Record<string, Column>;\n}\n\n/**\n * Classifies a table's columns for aggregation. avg/sum only make sense on numeric scalars;\n * min/max work on any orderable scalar (numbers, strings, bigints, dates, enums). Booleans,\n * arrays (including array-typed number columns), JSON, buffers, and object-shaped columns\n * (e.g. geometry) are excluded entirely.\n */\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(visibleColumns(table))) {\n all[columnName] = column;\n const converted = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, false);\n const gqlType = converted.type;\n\n // Anything that isn't a plain scalar in the generated schema (arrays, geometry objects)\n // has no meaningful min/max. This also catches array-typed number columns, which keep\n // their scalar drizzle dataType but convert to a GraphQL list.\n if (gqlType instanceof GraphQLList || gqlType instanceof GraphQLObjectType) {\n continue;\n }\n\n // Classify on the drizzle data type rather than the GraphQL one: date columns convert to\n // different GraphQL scalars per dialect, but are orderable everywhere.\n const { type: dataType, constraint } = extractExtendedColumnType(column);\n if (dataType === 'boolean' || dataType === 'array' || dataType === 'custom') {\n continue;\n }\n if (dataType === 'object' && constraint !== 'date') {\n continue;\n }\n\n orderable[columnName] = { column, converted };\n if (dataType === 'number') {\n numeric[columnName] = column;\n }\n }\n\n 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 policies?: TablePolicies,\n): CreatedResolver => {\n const target = aggregateTarget(table, tableName, typeName);\n\n const queryArgs = {\n where: { type: filterArgs },\n ...deletedArg(policies?.softDelete, tableName),\n };\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table>; deleted?: DeletedMode }, context, info) => {\n try {\n const request = parseAggregateRequest(info, target);\n if (!Object.keys(request.selection).length) {\n return {};\n }\n\n let query = resolveExecutor(db, context).select(request.selection).from(table);\n const where = withScope(\n resolveScope(policies, context, filterCtx),\n tableName,\n table,\n args.where\n ? extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n args.deleted,\n );\n if (where) {\n query = query.where(where);\n }\n const rows = await query;\n\n return assembleAggregateRow(rows[0] ?? {}, request, target);\n } catch (e) {\n throw 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 policies?: TablePolicies,\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 (\n parent: any,\n args: { where?: Filters<Table>; deleted?: DeletedMode },\n context: any,\n info: any,\n ) => {\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 const deleted = args?.deleted;\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 deleted: deleted ?? 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 // An aggregate over a relation counts the same rows the relation itself returns,\n // so it is narrowed by the target table's scope too.\n const whereCondition = withScope(\n resolveScope(policies, context, filterCtx),\n targetTableName,\n targetTable,\n and(\n inArray(foreignCol, uniqueIds),\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n ),\n deleted,\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(visibleColumns(table))) {\n if (groupable[columnName]) {\n continue;\n }\n const { type: dataType } = extractExtendedColumnType(column);\n if (dataType !== 'boolean') {\n continue;\n }\n groupable[columnName] = {\n column,\n converted: drizzleColumnToGraphQLType(column, columnName, tableName, true, false, false),\n };\n }\n\n return groupable;\n};\n\n/** The `${typeName}GroupByColumn` enum listing what a group-by query can group on. */\nexport const generateGroupByEnum = (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 policies?: TablePolicies,\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 ...deletedArg(policies?.softDelete, tableName),\n };\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { groupBy?: string[]; where?: Filters<Table>; having?: Record<string, any>; deleted?: DeletedMode },\n context,\n info,\n ) => {\n try {\n const requestedKeys = [...new Set(args.groupBy ?? [])];\n if (!requestedKeys.length) {\n throw 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 const where = withScope(\n resolveScope(policies, context, filterCtx),\n tableName,\n table,\n args.where\n ? extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n args.deleted,\n );\n if (where) {\n query = query.where(where);\n }\n query = query.groupBy(...keyColumns.map(([, column]) => column));\n\n const havingCondition = buildHavingCondition(args.having, columns);\n if (havingCondition) {\n query = query.having(havingCondition);\n }\n\n const rows: any[] = await query;\n\n return rows.map((row) => {\n const group: Record<string, any> = {};\n for (const [columnName, column] of keyColumns) {\n const value = row[`${GROUP_COL}${columnName}`];\n const decoded =\n typeof value === 'string' && target.dateTimeColumns.has(columnName) ? parseDriverDateTime(value) : value;\n group[columnName] = value == null ? null : remapToGraphQLCore(columnName, decoded, tableName, column);\n }\n\n return { group, ...assembleAggregateRow(row, request, target) };\n });\n } catch (e) {\n throw 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 applyContextValues,\n applyContextValuesAll,\n applyLimitPolicy,\n assertSingleMatch,\n attachRowCursors,\n attachTargetPrimaryKeys,\n bindPolicies,\n buildCursorCondition,\n buildNamedRelations,\n type CursorOrderEntry,\n computeResolverFieldNames,\n createMutationTxCtx,\n createRelationResolverFactory,\n cursorOrderExprs,\n cursorOrderingEntries,\n type DeletedMode,\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 orderByCursorObstacle,\n prepareMutationRelationColumns,\n primaryKeyOrderExprs,\n primaryKeyRestriction,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n type ResolverPolicies,\n registerColumnExclusions,\n relationFilterCtx,\n resolveConflictPlan,\n resolveQueryExecutor,\n runMutation,\n runRelationalSelect,\n type SelectionCtx,\n selectArrayArgs,\n selectDistinctKeys,\n selectSingleArgs,\n stripContextValues,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n withScope,\n} from '../builders/common.ts';\nimport {\n remapFromGraphQLArrayInput,\n remapFromGraphQLSingleInput,\n remapToGraphQLArrayOutput,\n remapToGraphQLSingleOutput,\n} from '../data-mappers/index.ts';\nimport { tableFieldExtensions } from '../extensions.ts';\nimport { resolveTableFeatures } from '../features.ts';\nimport { registerEnumConfig, registerScalarOverrides } from '../type-converter/index.ts';\nimport {\n createRelationAggregateFactory,\n generateAggregate,\n generateAggregateTypes,\n generateGroupBy,\n generateGroupByEnum,\n generateGroupByType,\n generateHavingInput,\n} 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 TableFeatures,\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 policies?: ResolverPolicies,\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 policies?.softDelete,\n tableName,\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 const scope = policies?.scope?.(context);\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 scope,\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, deleted } = args as Partial<TableSelectArgs> & {\n deleted?: DeletedMode;\n };\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 const cursorObstacle = orderByCursorObstacle(orderBy);\n if (cursorObstacle) {\n if (after != null) {\n throw new GraphQLError(cursorObstacle);\n }\n // `cursor` selected under an ordering a cursor cannot express — resolves to null;\n // the ordering itself 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 = withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n deleted,\n );\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), where),\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 policies?: ResolverPolicies,\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, policies?.softDelete, tableName);\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 const scope = policies?.scope?.(context);\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 scope,\n });\n }\n\n // Fallback for tables without relational query builder support.\n const { offset, orderBy, where, deleted } = args as Partial<TableSelectArgs> & { deleted?: DeletedMode };\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 const whereSql = withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n deleted,\n );\n if (whereSql) {\n q = q.where(whereSql) as any;\n }\n if (orderBy) {\n q = q.orderBy(...extractOrderBy(table, orderBy, relationFilterCtx(filterCtx, tableName), where)) 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 policies?: ResolverPolicies,\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 contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntries\n ? []\n : applyContextValuesAll(\n remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : args.values, table),\n contextColumns,\n context,\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 scope,\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) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: (tx, values) => runInsert(tx, [values]),\n context,\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 policies?: ResolverPolicies,\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 contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntry\n ? {}\n : applyContextValues(\n remapFromGraphQLSingleInput(entry ? entry.columns : args.values, table),\n contextColumns,\n context,\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 scope,\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) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: runInsert,\n context,\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 policies?: ResolverPolicies,\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 contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntries\n ? []\n : applyContextValuesAll(\n remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table),\n contextColumns,\n context,\n );\n\n const 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 scope,\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 // On conflict the statement updates a row that already exists, so the scope applies\n // to it exactly as it would to `update<Table>`: a conflicting row the caller cannot\n // see is left alone rather than taken over.\n const setWhere = withScope(scope, tableName, table, plan.setWhere);\n query =\n plan.action === 'NOTHING'\n ? (query.onConflictDoNothing(plan.target ? { target: plan.target } : undefined) as any)\n : (query.onConflictDoUpdate({ target: plan.target!, set: plan.set, setWhere }) as any);\n\n return (await query) as Record<string, any>[];\n };\n\n const result = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: (tx, values) => runUpsert(tx, [values]),\n context,\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 policies?: ResolverPolicies,\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 const scope = policies?.scope?.(context);\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 scope,\n });\n\n const entry = nested?.enabled(tableName) ? nested.split(tableName, set) : undefined;\n const nestedOps = entry && nested!.hasOps(entry.ops) ? entry.ops : undefined;\n // A context-derived column is the server's to set, so an update never reassigns\n // one — that is what stops a row being handed to another owner.\n const input = stripContextValues(\n remapUpdateInput(entry ? entry.columns : set, table, tableName),\n policies?.contextValues?.(tableName),\n );\n // A `set` that carries only nested operations is a legitimate update — of the\n // relation rather than of the row — so it is only empty when neither is present.\n if (!Object.keys(input).length && !nestedOps) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // The scope is ANDed on last, so a caller-supplied `where` can only narrow it.\n const filters = withScope(\n scope,\n tableName,\n table,\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined,\n );\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 context,\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 policies?: ResolverPolicies,\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 const scope = policies?.scope?.(context);\n const contextColumns = policies?.contextValues?.(tableName);\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 scope,\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 = stripContextValues(\n remapUpdateInput(split ? split.columns : set, table, tableName),\n contextColumns,\n );\n // An entry that only writes through a relation still has work to do.\n if (!Object.keys(input).length && !ops) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n ops,\n filters: withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n ),\n };\n });\n\n const 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, context)) }\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, context);\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\n/**\n * `delete<Table>` and, for a table that declares a soft-delete column, `restore<Table>`.\n *\n * A soft-deleting table never issues a `DELETE`: both mutations are an `UPDATE` of the marker\n * column, and the rows they return are the rows as they now stand. `restore` is the same\n * resolver reading the other way — it matches only marked rows (`deleted: ONLY`) and writes\n * the restored value.\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 policies?: ResolverPolicies,\n restore: boolean = false,\n): CreatedResolver => {\n const softDelete = policies?.softDelete?.(tableName);\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 const scope = policies?.scope?.(context);\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 // Same rule as update: the scope is ANDed on last, so a delete can only ever reach\n // rows inside it — an out-of-scope row is not matched rather than being refused.\n // A soft-deleting table adds the marker predicate the same way: `delete` only sees\n // rows that are not already marked, `restore` only sees the ones that are.\n const filters = withScope(\n scope,\n tableName,\n table,\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined,\n restore ? 'ONLY' : undefined,\n );\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = softDelete\n ? executor\n .update(table)\n .set({ [softDelete.columnName]: restore ? softDelete.writeRestored : softDelete.writeDeleted() })\n : executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n 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 // Excluded tables are dropped here, before anything reads `tableEntries` — which also makes\n // `buildNamedRelations` skip every relation pointing at one, since it resolves targets\n // through this list.\n const excludedTables = new Set(options.exclude?.tables ?? []);\n const tableEntries = schemaEntries.filter(([key, value]) => is(value, PgTable) && !excludedTables.has(key)) as [\n string,\n PgTable,\n ][];\n const tables = Object.fromEntries(tableEntries) as Record<string, PgTable>;\n\n // A feature flag may be a per-table predicate, so every flag is resolved against the table\n // it applies to. `anyTable` answers the build-wide question — whether machinery shared\n // across tables is worth constructing at all.\n const featureOf = resolveTableFeatures(features);\n const anyTable = (feature: keyof TableFeatures) => tableEntries.some(([name]) => featureOf(name)[feature]);\n\n if (!tableEntries.length) {\n throw new Error(\n \"Drizzle-GraphQL Error: No tables detected in Drizzle-ORM's database instance. Did you forget to pass schema to drizzle constructor?\",\n );\n }\n\n // Resolve scalar overrides into the type-converter's registry before any type generation —\n // every subsequent column→GraphQL type decision and runtime value remap consults it.\n registerScalarOverrides(tables, options);\n // Same lifecycle: the enum registry is per-build, so a second build never reuses the first\n // build's enum types (and with them its naming decisions).\n registerEnumConfig(options);\n // And the same for column exclusions: a per-build registry read by every site that decides\n // what the schema contains, reset here so a rebuild never inherits the previous build's.\n registerColumnExclusions(tables, options.exclude);\n\n // Flatten drizzle-orm v1 TablesRelationalConfig into the canonical shape\n // used throughout common.ts: Record<tableName, Record<relName, TableNamedRelations>>\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Relations *into* an excluded table are already gone (their target no longer resolves);\n // relations *out of* one have no type left to hang a field on.\n for (const excluded of excludedTables) {\n delete namedRelations[excluded];\n }\n // Record each relation target's primary key (composite-aware) so paginated relations\n // default to a deterministic PK order. Must run before pruning / type generation, which\n // share these entry objects.\n attachTargetPrimaryKeys(namedRelations, tables, 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 // The row scope compiled against this build's relation graph, plus the columns whose value\n // the server supplies. Both stay undefined unless configured.\n const tablePolicies = options.policies;\n const contextValuesOf = tablePolicies?.contextValues;\n const softDeleteOf = tablePolicies?.softDelete;\n const policies = bindPolicies(tablePolicies, filterCtx);\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(\n db,\n tables,\n 'nulls-largest',\n filterCtx,\n limits,\n tablePolicies,\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 primaryKeyOf: (name) => (tables[name] ? pgPrimaryKeyPropNames(tables[name] as PgTable) : []),\n contextValuesOf,\n softDeleteOf,\n featureOf,\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\n ? createNestedWriteRuntime({\n plans: nestedPlans,\n filterCtx,\n policies: tablePolicies,\n contextValues: contextValuesOf,\n })\n : undefined;\n\n // Built when at least one table wants relation aggregates; a table that has them off is\n // handed `undefined` below, so `generateTableTypes` emits no `${relation}Aggregate` fields\n // on its object type.\n const relationAggregateFactory: RelationAggregateFactory | undefined = anyTable('relationAggregates')\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx, tablePolicies)\n : undefined;\n\n const 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 featureOf(tableName).relationAggregates ? relationAggregateFactory : undefined,\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 // Everything this table generates, with any per-table predicate already run.\n const tableFeatures = featureOf(tableName);\n // What every field this table generates publishes about itself under `extensions.drizzle`,\n // so a wrapper can read a field's identity instead of parsing its configurable name.\n const drizzleMeta = tableFieldExtensions(tableName, pgPrimaryKeyPropNames(schema[tableName] as PgTable));\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 restoreFieldName,\n restoreSingleFieldName,\n deleteCountFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\n // A table that marks rows deleted instead of removing them also gets the mutation that\n // reverses it — clearing the column through an ordinary update is not possible, since the\n // column is not in the update input and a marked row is invisible to a `where` anyway.\n const softDeleteInfo = softDeleteOf?.(tableName);\n\n const selectArrGenerated = generateSelectArray(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n listFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n tableFeatures.distinct,\n limits,\n policies,\n );\n const selectSingleGenerated = generateSelectSingle(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n singleFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n limits,\n policies,\n );\n const insertArrGenerated = tableFeatures.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 policies,\n )\n : undefined;\n const insertSingleGenerated = tableFeatures.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 policies,\n )\n : undefined;\n // An upsert needs something to conflict on, so a table with no primary key and no\n // unique constraint gets no upsert mutations rather than ones that always fail.\n const uniqueSets = tableFeatures.upsert ? getUniqueColumnSets(schema[tableName] as PgTable, getTableConfig) : [];\n const onConflictInput = tableFeatures.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 policies,\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 policies,\n )\n : undefined;\n const updateGenerated = tableFeatures.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 tableFeatures.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n policies,\n )\n : undefined;\n const updateSingleGenerated = tableFeatures.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 tableFeatures.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n policies,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n tableFeatures.update && tableFeatures.updateMany\n ? generateUpdateManyInput({ 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 policies,\n )\n : undefined;\n const deleteGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n deleteFieldName,\n typeName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n )\n : undefined;\n const deleteSingleGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n deleteSingleFieldName,\n typeName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n )\n : undefined;\n const restoreGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n restoreFieldName,\n typeName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n const restoreSingleGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n restoreSingleFieldName,\n typeName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n // The count variants are the plural write with its payload left off, so each follows the\n // same feature switch as the write it mirrors.\n const updateCountGenerated =\n tableFeatures.update && tableFeatures.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: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n nested: nestedRuntime,\n })\n : undefined;\n const deleteCountGenerated =\n tableFeatures.delete && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as PgTable,\n kind: 'delete',\n filterArgs: tableFilters,\n fieldName: deleteCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n })\n : undefined;\n const aggregateType = tableFeatures.aggregates\n ? generateAggregateTypes(schema[tableName] as PgTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = tableFeatures.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as PgTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n tablePolicies,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n tableFeatures.aggregates && tableFeatures.groupBy\n ? generateGroupByType(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 tablePolicies,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: listFieldComplexity(complexity, limits?.(tableName)) } : {}),\n },\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: true, targetArg: 'where' }),\n },\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'aggregate', single: true, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'groupBy', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n };\n }\n if (insertArrGenerated) {\n mutations[insertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: insertArrGenerated.args,\n resolve: insertArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'insert', single: false, targetArg: 'values' }),\n },\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 extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'insert', single: true, targetArg: 'values' }),\n },\n };\n }\n if (upsertArrGenerated) {\n mutations[upsertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: upsertArrGenerated.args,\n resolve: upsertArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'upsert', single: false, targetArg: 'values' }),\n },\n };\n }\n if (upsertSingleGenerated) {\n mutations[upsertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: upsertSingleGenerated.args,\n resolve: upsertSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'upsert', single: true, targetArg: 'values' }),\n },\n };\n }\n if (updateGenerated) {\n mutations[updateGenerated.name] = {\n type: arrTableItemOutput,\n args: updateGenerated.args,\n resolve: updateGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'update', single: false, targetArg: 'where' }),\n },\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 extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'updateMany', single: false, targetArg: 'updates' }),\n },\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 extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'update', single: true, targetArg: 'where' }),\n },\n };\n }\n if (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'delete', single: false, targetArg: 'where' }),\n },\n };\n }\n if (deleteSingleGenerated) {\n mutations[deleteSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: deleteSingleGenerated.args,\n resolve: deleteSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'delete', single: true, targetArg: 'where' }),\n },\n };\n }\n if (restoreGenerated) {\n mutations[restoreGenerated.name] = {\n type: arrTableItemOutput,\n args: restoreGenerated.args,\n resolve: restoreGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'restore', single: false, targetArg: 'where' }),\n },\n };\n }\n if (restoreSingleGenerated) {\n mutations[restoreSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: restoreSingleGenerated.args,\n resolve: restoreSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'restore', single: true, targetArg: 'where' }),\n },\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 ...(tableFeatures.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(tableFeatures.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 applyContextValues,\n type ContextValuesFor,\n extractFilters,\n type RelationFilterBase,\n relationFilterCtx,\n resolveScope,\n resolveTypeName,\n type ScopeResolver,\n type TablePolicies,\n type TypeCacheCtx,\n type TypeNameMapper,\n visibleColumns,\n withScope,\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 // Same rule as the table's own create input: a column the server fills in from context\n // is not something a nested `create` may supply either.\n const contextColumns = cacheCtx.contextValuesOf?.(plan.targetTableName);\n const fields = Object.fromEntries(\n Object.entries(visibleColumns(plan.targetTable))\n .filter(([columnName]) => columnName !== omitted && !contextColumns?.[columnName])\n .map(([columnName, column]) => [\n columnName,\n drizzleColumnToGraphQLType(column as Column, columnName, plan.targetTableName, false, true, true),\n ]),\n );\n\n const type = new GraphQLInputObjectType({\n name: `${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, context?: any) => 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 context?: 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 policies?: TablePolicies;\n contextValues?: ContextValuesFor;\n}): NestedWriteRuntime => {\n const { plans, filterCtx, policies, contextValues } = 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 = (\n plan: NestedRelationPlan,\n filter: Record<string, any>,\n operation: string,\n scope: ScopeResolver | undefined,\n ) => {\n const condition = extractFilters(\n plan.targetTable,\n plan.targetTableName,\n filter,\n relationFilterCtx(filterCtx, plan.targetTableName),\n );\n if (!condition) {\n throw 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 // The filter selects rows to attach or detach, so it is a write against the target\n // table and is narrowed by its scope: `connect` cannot reach a row the caller cannot\n // see, and out-of-scope rows are not detached.\n return withScope(scope, plan.targetTableName, plan.targetTable, condition)!;\n };\n\n const assertSingleOperation = (plan: NestedRelationPlan, op: Record<string, any>) => {\n const 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, scope: ScopeResolver | undefined) =>\n executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: null })\n .where(withScope(scope, plan.targetTableName, plan.targetTable, 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, context) => {\n const tablePlans = plans[tableName];\n const patch: Record<string, any> = {};\n if (!tablePlans) {\n return patch;\n }\n const scope = resolveScope(policies, context, filterCtx);\n\n for (const [relationName, op] of Object.entries(ops)) {\n const plan = tablePlans[relationName];\n if (!plan || plan.fkSide !== 'parent') {\n continue;\n }\n assertSingleOperation(plan, op);\n\n if (op['create'] !== undefined) {\n const values = applyContextValues(\n remapFromGraphQLSingleInput({ ...op['create'] }, plan.targetTable),\n contextValues?.(plan.targetTableName),\n context,\n );\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', scope));\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, context) => {\n const tablePlans = plans[tableName];\n if (!tablePlans) {\n return;\n }\n const scope = resolveScope(policies, context, filterCtx);\n\n for (const [relationName, op] of Object.entries(ops)) {\n const plan = tablePlans[relationName];\n if (!plan || 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, scope);\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', scope));\n }\n }\n\n if (op['disconnect'] !== undefined) {\n if (plan.isOne) {\n if (op['disconnect'] === true) {\n await detachAll(executor, plan, key, scope);\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', scope)));\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, scope);\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', scope));\n }\n }\n\n if (op['create'] !== undefined) {\n const rows = asArray(op['create']).map((row) => ({\n ...applyContextValues(\n remapFromGraphQLSingleInput({ ...row }, plan.targetTable),\n contextValues?.(plan.targetTableName),\n context,\n ),\n [plan.foreignColPropName]: key,\n }));\n if (rows.length) {\n await 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 context?: any;\n}): Promise<Record<string, any>[]> => {\n const { executor, runtime, tableName, entries, remapValues, write, context } = 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, context);\n const written = await write(tx, { ...remapValues(entry.columns), ...patch });\n await runtime.applyChildSide(tx, tableName, entry.ops, written, context);\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 context?: any;\n}): Promise<Record<string, any>[]> => {\n const { executor, runtime, tableName, columns, ops, remapValues, write, context } = params;\n\n return executor.transaction(async (tx: any) => {\n const patch = await runtime.applyParentSide(tx, tableName, ops, context);\n const rows = await write(tx, { ...remapValues(columns), ...patch });\n await runtime.applyChildSide(tx, tableName, ops, rows, context);\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 applyContextValues,\n applyContextValuesAll,\n applyLimitPolicy,\n assertSingleMatch,\n attachTargetPrimaryKeys,\n bindPolicies,\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 type ResolverPolicies,\n registerColumnExclusions,\n relationFilterCtx,\n resolveConflictPlan,\n resolveQueryExecutor,\n runMutation,\n runRelationalSelect,\n type SelectionCtx,\n selectArrayArgs,\n selectSingleArgs,\n stripContextValues,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n withScope,\n} from '../builders/common.ts';\nimport {\n remapFromGraphQLArrayInput,\n remapFromGraphQLSingleInput,\n remapToGraphQLArrayOutput,\n remapToGraphQLSingleOutput,\n} from '../data-mappers/index.ts';\nimport { tableFieldExtensions } from '../extensions.ts';\nimport { resolveTableFeatures } from '../features.ts';\nimport { registerEnumConfig, registerScalarOverrides } from '../type-converter/index.ts';\nimport {\n createRelationAggregateFactory,\n generateAggregate,\n generateAggregateTypes,\n generateGroupBy,\n generateGroupByEnum,\n generateGroupByType,\n generateHavingInput,\n} 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 TableFeatures,\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 policies?: ResolverPolicies,\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 policies?.softDelete,\n tableName,\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 scope: policies?.scope?.(context),\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 policies?: ResolverPolicies,\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, policies?.softDelete, tableName);\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 scope: policies?.scope?.(context),\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 policies?: ResolverPolicies,\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 contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntries\n ? []\n : applyContextValuesAll(\n remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : args.values, table),\n contextColumns,\n context,\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 scope,\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) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: (tx, values) => runInsert(tx, [values]),\n context,\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 policies?: ResolverPolicies,\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 contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntry\n ? {}\n : applyContextValues(\n remapFromGraphQLSingleInput(entry ? entry.columns : args.values, table),\n contextColumns,\n context,\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 scope,\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) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: runInsert,\n context,\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 policies?: ResolverPolicies,\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 contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntries\n ? []\n : applyContextValuesAll(\n remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table),\n contextColumns,\n context,\n );\n\n const 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 scope,\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 // On conflict the statement updates a row that already exists, so the scope applies\n // to it exactly as it would to `update<Table>`: a conflicting row the caller cannot\n // see is left alone rather than taken over.\n const setWhere = withScope(scope, tableName, table, plan.setWhere);\n query =\n plan.action === 'NOTHING'\n ? (query.onConflictDoNothing(plan.target ? { target: plan.target } : undefined) as any)\n : (query.onConflictDoUpdate({ target: plan.target!, set: plan.set, setWhere }) as any);\n\n return (await query) as Record<string, any>[];\n };\n\n const result = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: (tx, values) => runUpsert(tx, [values]),\n context,\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 policies?: ResolverPolicies,\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 const scope = policies?.scope?.(context);\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 scope,\n });\n\n const entry = nested?.enabled(tableName) ? nested.split(tableName, set) : undefined;\n const nestedOps = entry && nested!.hasOps(entry.ops) ? entry.ops : undefined;\n // A context-derived column is the server's to set, so an update never reassigns\n // one — that is what stops a row being handed to another owner.\n const input = stripContextValues(\n remapUpdateInput(entry ? entry.columns : set, table, tableName),\n policies?.contextValues?.(tableName),\n );\n // A `set` that carries only nested operations is a legitimate update — of the\n // relation rather than of the row — so it is only empty when neither is present.\n if (!Object.keys(input).length && !nestedOps) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // The scope is ANDed on last, so a caller-supplied `where` can only narrow it.\n const filters = withScope(\n scope,\n tableName,\n table,\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined,\n );\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 context,\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 policies?: ResolverPolicies,\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 const scope = policies?.scope?.(context);\n const contextColumns = policies?.contextValues?.(tableName);\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 scope,\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 = stripContextValues(\n remapUpdateInput(split ? split.columns : set, table, tableName),\n contextColumns,\n );\n // An entry that only writes through a relation still has work to do.\n if (!Object.keys(input).length && !ops) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n ops,\n filters: withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n ),\n };\n });\n\n const anyNested = entries.some((entry) => entry.ops);\n const returning = 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, context)) }\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, context);\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\n/**\n * `delete<Table>` and, for a table that declares a soft-delete column, `restore<Table>`.\n * See the PostgreSQL builder's copy for the shape — a soft-deleting table issues an `UPDATE`\n * of the marker column instead of a `DELETE`, and `restore` is the same resolver matching\n * only marked rows and writing the restored value.\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 policies?: ResolverPolicies,\n restore: boolean = false,\n): CreatedResolver => {\n const softDelete = policies?.softDelete?.(tableName);\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 const scope = policies?.scope?.(context);\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 // Same rule as update: the scope is ANDed on last, so a delete can only ever reach\n // rows inside it — an out-of-scope row is not matched rather than being refused.\n // A soft-deleting table adds the marker predicate the same way: `delete` only sees\n // rows that are not already marked, `restore` only sees the ones that are.\n const filters = withScope(\n scope,\n tableName,\n table,\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined,\n restore ? 'ONLY' : undefined,\n );\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = softDelete\n ? executor\n .update(table)\n .set({ [softDelete.columnName]: restore ? softDelete.writeRestored : softDelete.writeDeleted() })\n : executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n 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 // Excluded tables are dropped here, before anything reads `tableEntries` — which also makes\n // `buildNamedRelations` skip every relation pointing at one, since it resolves targets\n // through this list.\n const excludedTables = new Set(options.exclude?.tables ?? []);\n const tableEntries = schemaEntries.filter(([key, value]) => is(value, SQLiteTable) && !excludedTables.has(key)) as [\n string,\n SQLiteTable,\n ][];\n const tables = Object.fromEntries(tableEntries) as Record<string, SQLiteTable>;\n\n // A feature flag may be a per-table predicate, so every flag is resolved against the table\n // it applies to. `anyTable` answers the build-wide question — whether machinery shared\n // across tables is worth constructing at all.\n const featureOf = resolveTableFeatures(features);\n const anyTable = (feature: keyof TableFeatures) => tableEntries.some(([name]) => featureOf(name)[feature]);\n\n if (!tableEntries.length) {\n throw new Error(\n \"Drizzle-GraphQL Error: No tables detected in Drizzle-ORM's database instance. Did you forget to pass schema to drizzle constructor?\",\n );\n }\n\n // Resolve scalar overrides into the type-converter's registry before any type generation —\n // every subsequent column→GraphQL type decision and runtime value remap consults it.\n registerScalarOverrides(tables, options);\n // Same lifecycle: the enum registry is per-build, so a second build never reuses the first\n // build's enum types (and with them its naming decisions).\n registerEnumConfig(options);\n // And the same for column exclusions: a per-build registry read by every site that decides\n // what the schema contains, reset here so a rebuild never inherits the previous build's.\n registerColumnExclusions(tables, options.exclude);\n\n // Build namedRelations from the drizzle-orm v1 relations config.\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Relations *into* an excluded table are already gone (their target no longer resolves);\n // relations *out of* one have no type left to hang a field on.\n for (const excluded of excludedTables) {\n delete namedRelations[excluded];\n }\n // Record each relation target's (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 // The row scope compiled against this build's relation graph, plus the columns whose value\n // the server supplies. Both stay undefined unless configured.\n const tablePolicies = options.policies;\n const contextValuesOf = tablePolicies?.contextValues;\n const softDeleteOf = tablePolicies?.softDelete;\n const policies = bindPolicies(tablePolicies, filterCtx);\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(\n db,\n tables,\n 'nulls-smallest',\n filterCtx,\n limits,\n tablePolicies,\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 primaryKeyOf: (name) => (tables[name] ? sqlitePrimaryKeyPropNames(tables[name] as SQLiteTable) : []),\n contextValuesOf,\n softDeleteOf,\n featureOf,\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\n ? createNestedWriteRuntime({\n plans: nestedPlans,\n filterCtx,\n policies: tablePolicies,\n contextValues: contextValuesOf,\n })\n : undefined;\n\n // Built when at least one table wants relation aggregates; a table that has them off is\n // handed `undefined` below, so `generateTableTypes` emits no `${relation}Aggregate` fields\n // on its object type.\n const relationAggregateFactory: RelationAggregateFactory | undefined = anyTable('relationAggregates')\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx, tablePolicies)\n : undefined;\n\n const 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 featureOf(tableName).relationAggregates ? relationAggregateFactory : undefined,\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 // Everything this table generates, with any per-table predicate already run.\n const tableFeatures = featureOf(tableName);\n // What every field this table generates publishes about itself under `extensions.drizzle`,\n // so a wrapper can read a field's identity instead of parsing its configurable name.\n const drizzleMeta = tableFieldExtensions(tableName, sqlitePrimaryKeyPropNames(schema[tableName] as SQLiteTable));\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 restoreFieldName,\n restoreSingleFieldName,\n deleteCountFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\n // A table that marks rows deleted instead of removing them also gets the mutation that\n // reverses it — clearing the column through an ordinary update is not possible, since the\n // column is not in the update input and a marked row is invisible to a `where` anyway.\n const softDeleteInfo = softDeleteOf?.(tableName);\n\n const selectArrGenerated = generateSelectArray(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n listFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n tableFeatures.distinct,\n limits,\n policies,\n );\n const selectSingleGenerated = generateSelectSingle(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n singleFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n limits,\n policies,\n );\n const insertArrGenerated = tableFeatures.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 policies,\n )\n : undefined;\n const insertSingleGenerated = tableFeatures.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 policies,\n )\n : undefined;\n // An upsert needs something to conflict on, so a table with no primary key and no\n // unique constraint gets no upsert mutations rather than ones that always fail.\n const uniqueSets = tableFeatures.upsert\n ? getUniqueColumnSets(schema[tableName] as SQLiteTable, getTableConfig)\n : [];\n const onConflictInput = tableFeatures.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 policies,\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 policies,\n )\n : undefined;\n const updateGenerated = tableFeatures.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 tableFeatures.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n policies,\n )\n : undefined;\n const updateSingleGenerated = tableFeatures.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 tableFeatures.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n policies,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n tableFeatures.update && tableFeatures.updateMany\n ? generateUpdateManyInput({ 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 policies,\n )\n : undefined;\n const deleteGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n deleteFieldName,\n typeName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n )\n : undefined;\n const deleteSingleGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n deleteSingleFieldName,\n typeName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n )\n : undefined;\n const restoreGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n restoreFieldName,\n typeName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n const restoreSingleGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n restoreSingleFieldName,\n typeName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n // The count variants are the plural write with its payload left off, so each follows the\n // same feature switch as the write it mirrors.\n const updateCountGenerated =\n tableFeatures.update && tableFeatures.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: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n nested: nestedRuntime,\n })\n : undefined;\n const deleteCountGenerated =\n tableFeatures.delete && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as SQLiteTable,\n kind: 'delete',\n filterArgs: tableFilters,\n fieldName: deleteCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n })\n : undefined;\n const aggregateType = tableFeatures.aggregates\n ? generateAggregateTypes(schema[tableName] as SQLiteTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = tableFeatures.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n tablePolicies,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n tableFeatures.aggregates && tableFeatures.groupBy\n ? generateGroupByType(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 tablePolicies,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: listFieldComplexity(complexity, limits?.(tableName)) } : {}),\n },\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: true, targetArg: 'where' }),\n },\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'aggregate', single: true, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'groupBy', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n };\n }\n if (insertArrGenerated) {\n mutations[insertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: insertArrGenerated.args,\n resolve: insertArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'insert', single: false, targetArg: 'values' }),\n },\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 extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'insert', single: true, targetArg: 'values' }),\n },\n };\n }\n if (upsertArrGenerated) {\n mutations[upsertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: upsertArrGenerated.args,\n resolve: upsertArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'upsert', single: false, targetArg: 'values' }),\n },\n };\n }\n if (upsertSingleGenerated) {\n mutations[upsertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: upsertSingleGenerated.args,\n resolve: upsertSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'upsert', single: true, targetArg: 'values' }),\n },\n };\n }\n if (updateGenerated) {\n mutations[updateGenerated.name] = {\n type: arrTableItemOutput,\n args: updateGenerated.args,\n resolve: updateGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'update', single: false, targetArg: 'where' }),\n },\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 extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'updateMany', single: false, targetArg: 'updates' }),\n },\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 extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'update', single: true, targetArg: 'where' }),\n },\n };\n }\n if (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'delete', single: false, targetArg: 'where' }),\n },\n };\n }\n if (deleteSingleGenerated) {\n mutations[deleteSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: deleteSingleGenerated.args,\n resolve: deleteSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'delete', single: true, targetArg: 'where' }),\n },\n };\n }\n if (restoreGenerated) {\n mutations[restoreGenerated.name] = {\n type: arrTableItemOutput,\n args: restoreGenerated.args,\n resolve: restoreGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'restore', single: false, targetArg: 'where' }),\n },\n };\n }\n if (restoreSingleGenerated) {\n mutations[restoreSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: restoreSingleGenerated.args,\n resolve: restoreSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'restore', single: true, targetArg: 'where' }),\n },\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 ...(tableFeatures.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(tableFeatures.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","import { is, Table } from 'drizzle-orm';\nimport { getTableConfig as getMySqlTableConfig, MySqlDatabase } from 'drizzle-orm/mysql-core';\nimport { getTableConfig as getPgTableConfig, PgAsyncDatabase } from 'drizzle-orm/pg-core';\nimport { BaseSQLiteDatabase, getTableConfig as getSQLiteTableConfig } from 'drizzle-orm/sqlite-core';\nimport type { GraphQLResolveInfo } from 'graphql';\nimport { parseResolveInfo, type ResolveTree } from 'graphql-parse-resolve-info';\nimport type { AnyDrizzleDB } from '../types.ts';\nimport {\n attachTargetPrimaryKeys,\n buildNamedRelations,\n extractRelationsParams,\n getPrimaryKeyPropNamesFromConfig,\n type RelationFilterBase,\n resolveTypeName,\n runRelationalSelect,\n type TypeNameMapper,\n} from './builders/common.ts';\nimport type { TableNamedRelations } from './builders/types.ts';\n\n/**\n * Everything the translation needs about a drizzle instance: the tables it holds, the\n * relation graph in this library's canonical shape, and the filter context that lets a\n * nested `where` reach a relation's target table. Derived once per instance — the same\n * derivation `buildSchema` does — and cached, since an overriding resolver calls this on\n * every request.\n */\ntype SelectionContext = {\n tables: Record<string, Table>;\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n filterCtx: RelationFilterBase;\n primaryKeyOf: (tableName: string) => readonly string[];\n};\n\nconst contextCache = new WeakMap<object, SelectionContext>();\n\n/** The dialect's `getTableConfig`, which is the only place a composite primary key shows up. */\nconst tableConfigFor = (db: AnyDrizzleDB<any>) => {\n if (is(db, MySqlDatabase)) {\n return getMySqlTableConfig as (table: Table) => { primaryKeys: { columns: { name: string }[] }[] };\n }\n if (is(db, PgAsyncDatabase)) {\n return getPgTableConfig as unknown as (table: Table) => { primaryKeys: { columns: { name: string }[] }[] };\n }\n if (is(db, BaseSQLiteDatabase)) {\n return getSQLiteTableConfig as unknown as (table: Table) => { primaryKeys: { columns: { name: string }[] }[] };\n }\n throw new Error('Drizzle-GraphQL Error: unsupported database instance — expected a PostgreSQL, MySQL or SQLite one.');\n};\n\nconst contextFor = (db: AnyDrizzleDB<any>): SelectionContext => {\n const cached = contextCache.get(db as object);\n if (cached) {\n return cached;\n }\n\n const relations = (db as any)._.relations ?? {};\n // Same reconstruction `buildSchema` does: PG no longer exposes `fullSchema`, so the table\n // map is rebuilt from the relations config, whose entries each carry their table.\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 const tableEntries = Object.entries(schema as Record<string, unknown>).filter(([, value]) => is(value, Table)) as [\n string,\n Table,\n ][];\n if (!tableEntries.length) {\n throw new Error(\n 'Drizzle-GraphQL Error: Schema not found in drizzle instance. Pass relations (from buildRelations/defineRelations) to the drizzle constructor so drizzle-graphql can read your tables.',\n );\n }\n\n const tables = Object.fromEntries(tableEntries);\n const getTableConfig = tableConfigFor(db);\n const primaryKeyCache = new Map<string, readonly string[]>();\n const primaryKeyOf = (tableName: string): readonly string[] => {\n let pk = primaryKeyCache.get(tableName);\n if (!pk) {\n const table = tables[tableName];\n pk = table ? getPrimaryKeyPropNamesFromConfig(table, getTableConfig) : [];\n primaryKeyCache.set(tableName, pk);\n }\n return pk;\n };\n\n const relationMap = buildNamedRelations(relations, tableEntries);\n // Paginated relations fall back to a primary-key order, which is resolved once per target\n // and hung off the relation entry — exactly as the generated schema does it.\n attachTargetPrimaryKeys(relationMap, tables, (table) => [...primaryKeyOf(tableNameOf(tables, table))]);\n\n const context: SelectionContext = {\n tables,\n relationMap,\n filterCtx: { tables, relationMap },\n primaryKeyOf,\n };\n contextCache.set(db as object, context);\n return context;\n};\n\n/** Reverse lookup for `attachTargetPrimaryKeys`, which hands back the table, not its key. */\nconst tableNameOf = (tables: Record<string, Table>, table: Table): string =>\n Object.keys(tables).find((name) => tables[name] === table) ?? '';\n\n/** Options shared by {@link selectionToWith} and {@link resolveSelection}. */\nexport type SelectionOptions = {\n /** The drizzle instance the schema was built from. */\n db: AnyDrizzleDB<any>;\n /** The Drizzle schema key of the table the selection is rooted at. */\n table: string;\n /**\n * The `typeNameMapper` the schema was built with, when one was configured. The translation\n * matches selections against GraphQL type names, so a build that renames its types has to\n * pass the same mapper here or nothing will match.\n */\n typeNameMapper?: TypeNameMapper;\n};\n\n/**\n * Reads the parsed selection tree out of a resolver's `info`, resolving fragments and\n * inline fragments. Accepts an already-parsed tree so a caller that has one (or is chaining\n * these helpers) does not pay for the walk twice.\n */\nconst parseInfo = (info: GraphQLResolveInfo | ResolveTree): ResolveTree | undefined => {\n if ('fieldsByTypeName' in info) {\n return info as ResolveTree;\n }\n return parseResolveInfo(info, { deep: true }) as ResolveTree | undefined;\n};\n\n/**\n * Translates a GraphQL selection set into the relational query builder's `with` tree — the\n * same translation the generated resolvers use for their own queries.\n *\n * A resolver that replaces a generated one has to return a row shaped like the type it\n * replaced, and the field resolvers underneath only fill in relations the parent did not\n * already provide. Reproducing that by hand means resolving fragments against\n * `info.fragments`, intersecting selection names against the relations config (so scalars\n * and consumer-added fields drop out instead of becoming invalid `with` keys), following\n * aliases, compiling each relation's `where` / `orderBy` / `limit` / `offset` arguments into\n * its nested entry, and leaving `<relation>Aggregate` selections out — they are not `with`\n * entries at all. This does all of it.\n *\n * ```ts\n * const withTree = selectionToWith(info, { db, table: 'Users' });\n * const row = await tx.query.Users.findFirst({ where: { id: { eq } }, with: withTree });\n * ```\n *\n * Returns `undefined` when the selection asks for no relations, which is the value the\n * query builder wants for \"no `with` clause\".\n */\nexport const selectionToWith = (\n info: GraphQLResolveInfo | ResolveTree,\n options: SelectionOptions,\n): Record<string, any> | undefined => {\n const { db, table, typeNameMapper } = options;\n const { tables, relationMap, filterCtx } = contextFor(db);\n if (!tables[table]) {\n throw new Error(`Drizzle-GraphQL Error: '${table}' is not a table in the Drizzle schema.`);\n }\n if (!relationMap[table]) {\n return undefined;\n }\n\n const parsed = parseInfo(info);\n const params = extractRelationsParams(\n relationMap,\n tables,\n table,\n parsed,\n resolveTypeName(table, typeNameMapper),\n typeNameMapper,\n filterCtx,\n );\n // A selection with no relations in it gets no `with` clause at all, rather than an empty\n // object the query builder would have to be asked to ignore.\n return params && Object.keys(params).length ? params : undefined;\n};\n\n/** Options for {@link resolveSelection} — the selection options plus the read itself. */\nexport type ResolveSelectionOptions = SelectionOptions & {\n /**\n * The transaction (or other drizzle executor) to read on. Defaults to `db`, so an override\n * that has opened its own transaction passes it here to see its own uncommitted writes.\n */\n executor?: any;\n /** Whether to return one row or a list. A single read ignores `limit`. */\n single?: boolean;\n /** The generated `where` argument, in the schema's filter DSL — compiled the same way. */\n where?: any;\n /** The generated `orderBy` argument. */\n orderBy?: any;\n limit?: number;\n offset?: number;\n /** The generated `after` cursor argument, for keyset pagination. */\n after?: string;\n};\n\n/**\n * Runs the read a generated select resolver would have run, against whichever executor is\n * given — the whole body, not just the `with` tree: selected columns, relation arguments,\n * eager loading, cursor pagination, and the transport remapping of the result.\n *\n * This is what an override usually wants after it has done its own work:\n *\n * ```ts\n * const rows = await resolveSelection(info, { db, table: 'Users', where, executor: tx });\n * ```\n *\n * Relation arguments and aggregate fields keep behaving as they do in the generated schema,\n * because it is the generated schema's own code path.\n */\nexport const resolveSelection = async (\n info: GraphQLResolveInfo | ResolveTree,\n options: ResolveSelectionOptions,\n): Promise<any> => {\n const {\n db,\n table: tableName,\n typeNameMapper,\n executor,\n single = false,\n where,\n orderBy,\n limit,\n offset,\n after,\n } = options;\n const { tables, relationMap, filterCtx, primaryKeyOf } = contextFor(db);\n const table = tables[tableName];\n if (!table) {\n throw new Error(`Drizzle-GraphQL Error: '${tableName}' is not a table in the Drizzle schema.`);\n }\n\n const parsedInfo = parseInfo(info);\n if (!parsedInfo) {\n throw new Error('Drizzle-GraphQL Error: resolveSelection could not read a selection set from the resolve info.');\n }\n\n const source = executor ?? db;\n const queryBase = (source as any).query?.[tableName];\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: the executor passed to resolveSelection has no relational query builder for '${tableName}'.`,\n );\n }\n\n return runRelationalSelect({\n queryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName: resolveTypeName(tableName, typeNameMapper),\n typeNameMapper,\n parsedInfo,\n single,\n where,\n orderBy,\n limit,\n offset,\n after,\n filterCtx,\n pkNames: primaryKeyOf(tableName),\n db: source,\n });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,uBAAsC;AACtC,IAAAC,qBAA8B;AAC9B,IAAAC,kBAAgC;AAChC,IAAAC,sBAAmC;AACnC,IAAAC,mBAMO;;;ACQP,IAAAC,sBA+BO;AAEP,IAAAC,kBAYO;;;AC9DP,IAAM,sBAAsB,uBAAO,yBAAyB;AAI5D,IAAM,cAAN,MAAwB;AAAA,EAItB,YAA6B,SAAwB;AAAxB;AAAA,EAAyB;AA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E,UAAM,WAAW,IAAI,mCAAkB;AAAA,MACrC,MAAM;AAAA,MACN,QAAQ;AAAA,IACV,CAAC;AAED,wBAAoB,WAAW;AAAA,EACjC;AAEA,QAAM,eAAe,IAAI,+BAAc,mBAAmB;AAE1D,SAAO,EAAE,QAAQ,cAAc,UAAU,gBAAgB;AAC3D;","names":["import_drizzle_orm","import_mysql_core","import_pg_core","import_sqlite_core","import_graphql","import_drizzle_orm","import_graphql","pluralize","import_drizzle_orm","import_graphql","import_graphql","column","operators","import_drizzle_orm","import_graphql","isJsonColumn","aliasedTable","getTableConfig","targetNames","set","result","import_drizzle_orm","import_mysql_core","import_graphql","import_graphql_parse_resolve_info","import_drizzle_orm","import_graphql","import_drizzle_orm","import_pg_core","import_graphql","import_graphql_parse_resolve_info","import_drizzle_orm","import_graphql","generateSelectArray","generateSelectSingle","generateInsertArray","generateInsertSingle","generateUpsert","generateUpdate","generateUpdateMany","generateDelete","generateSchemaData","import_drizzle_orm","import_sqlite_core","import_graphql","import_graphql_parse_resolve_info","generateSelectArray","generateSelectSingle","generateInsertArray","generateInsertSingle","generateUpsert","generateUpdate","generateUpdateMany","results","generateDelete","generateSchemaData","import_drizzle_orm","import_mysql_core","import_pg_core","import_sqlite_core","import_graphql_parse_resolve_info","getMySqlTableConfig","getPgTableConfig","getSQLiteTableConfig","getTableConfig","config","generateSchemaData"]}
|
|
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/extensions.ts","../src/util/builders/field-updates.ts","../src/util/builders/mysql.ts","../src/util/features.ts","../src/util/builders/aggregates.ts","../src/util/builders/pg.ts","../src/util/builders/nested-writes.ts","../src/util/builders/sqlite.ts","../src/util/selection.ts"],"sourcesContent":["import { getColumns, is, Table } 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 type DefaultOrderByFor,\n defaultErrorMapper,\n type LimitPolicyFor,\n normalizeWriteHooks,\n type ResolvedLimitPolicy,\n type ResolvedWriteHooks,\n resolveLimitPolicy,\n resolveSoftDeleteInfo,\n type SoftDeleteInfo,\n type TablePolicies,\n type WriteHookFor,\n type WriteHookPositions,\n type WriteHooks,\n} from './util/builders/common.ts';\nimport { generateMySQL, generatePG, generateSQLite } from './util/builders/index.ts';\nimport type { SchemaGeneratorOptions } from './util/builders/types.ts';\nimport { singularizeMapper } from './util/case-ops/index.ts';\nimport { resolveTableFeatures } from './util/features.ts';\n\nexport type {\n AggregateResolver,\n AnyDrizzleDB,\n BuildSchemaConfig,\n ComplexityConfig,\n ContextValuesConfig,\n DefaultOrderByEntry,\n DefaultsConfig,\n DeleteResolver,\n DeleteSingleResolver,\n ExtractRelations,\n ExtractTableByName,\n ExtractTableRelations,\n ExtractTables,\n FeatureSwitch,\n GeneratedData,\n GeneratedEntities,\n GeneratedInputs,\n GeneratedOutputs,\n InsertArrResolver,\n InsertResolver,\n LimitsConfig,\n MutationReturnlessResult,\n MutationsCore,\n OnWriteConfig,\n QueriesCore,\n RowScope,\n RowScopeFilter,\n SchemaExclusions,\n SchemaFeatures,\n ScopeConfig,\n SelectResolver,\n SelectSingleResolver,\n SoftDeleteColumn,\n SoftDeleteConfig,\n TableDefaults,\n TableLimitPolicy,\n UpdateManyArgs,\n UpdateManyEntry,\n UpdateManyResolver,\n UpdateResolver,\n UpdateSingleResolver,\n UpsertArgs,\n UpsertArrResolver,\n UpsertConflictArgs,\n UpsertResolver,\n WriteHook,\n WriteHookPayload,\n WriteHookPositions,\n WriteHooks,\n WriteOperation,\n} from './types.ts';\nexport type { 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 { singularizeMapper } from './util/case-ops/index.ts';\nexport type {\n DrizzleExtension,\n DrizzleFieldExtension,\n DrizzleFieldKind,\n DrizzleFieldOperation,\n DrizzleTargetArg,\n DrizzleTypeExtension,\n IdentifiedRows,\n} from './util/extensions.ts';\nexport { drizzleExtension, identifyRows, isDrizzleFieldExtension } from './util/extensions.ts';\nexport {\n GraphQLBigIntString,\n GraphQLDate,\n GraphQLDateTime,\n GraphQLDecimalString,\n GraphQLJSON,\n GraphQLUUID,\n} from './util/scalars/index.ts';\nexport type { ResolveSelectionOptions, SelectionOptions } from './util/selection.ts';\nexport { resolveSelection, selectionToWith } from './util/selection.ts';\nexport type {\n ColumnDeprecator,\n ColumnDescriber,\n ColumnDocInfo,\n ColumnTypeMapper,\n ColumnTypeMapperInfo,\n EnumNameInfo,\n EnumNameMapper,\n 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 restore: config?.prefixes?.restore ?? 'restore',\n };\n\n const suffixes = {\n list: config?.suffixes?.list ?? '',\n single: config?.suffixes?.single ?? 'Single',\n };\n\n // `'singularize'` is the one shipped preset; anything else is the caller's own function.\n const typeNameMapper = config?.typeNameMapper === 'singularize' ? singularizeMapper : config?.typeNameMapper;\n\n // Table keys this build generates for — what a per-table feature predicate is asked about.\n // Excluded tables are dropped up front so no predicate is ever consulted for a table that\n // generates nothing.\n const tableKeys = Object.entries(schema as Record<string, unknown>)\n .filter(([, value]) => is(value, Table))\n .map(([key]) => key);\n const excludedTableNames = new Set(config?.exclude?.tables ?? []);\n const featureTables = tableKeys.filter((key) => !excludedTableNames.has(key));\n\n // Resolved the same way the generators resolve it, so the implication warnings below\n // describe exactly what gets generated.\n const forTable = resolveTableFeatures(config?.features);\n\n // Cost hints are inert without a complexity rule installed, so they are generated unless the\n // caller opts out.\n const complexityConfig = config?.complexity ?? true;\n const complexity =\n complexityConfig === false\n ? undefined\n : {\n defaultListSize: (complexityConfig === true ? undefined : complexityConfig.defaultListSize) ?? 10,\n aggregateCost: (complexityConfig === true ? undefined : complexityConfig.aggregateCost) ?? 10,\n };\n\n // Off unless asked for: opening transactions the caller did not wire up themselves is a\n // behavior change (and some drivers, e.g. neon-http, cannot open one at all).\n const transactionsOpt = config?.transactions;\n const transactions =\n transactionsOpt === undefined || transactionsOpt === 'none'\n ? undefined\n : { 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 // Per-table defaults are resolved against the real schema at build time, so a renamed table\n // or column fails the build rather than silently ordering by nothing. The normalized form is\n // the same shape the generated `orderBy` argument has, so every read path can substitute it\n // without knowing where it came from.\n const defaultsConfig = config?.defaults;\n const defaultOrderByByTable = new Map<string, Record<string, any>>();\n if (defaultsConfig) {\n const defaultsTableNames = new Set(tableKeys);\n for (const [tableName, tableDefaults] of Object.entries(defaultsConfig)) {\n if (!defaultsTableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.defaults names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n const orderBy = tableDefaults?.orderBy;\n if (!orderBy || !Object.keys(orderBy).length) {\n continue;\n }\n const columns = getColumns(schema[tableName] as Table);\n const normalized: Record<string, any> = {};\n for (const [columnName, entry] of Object.entries(orderBy)) {\n if (!columns[columnName]) {\n throw new Error(\n `Drizzle-GraphQL Error: config.defaults.${tableName}.orderBy names '${columnName}', which is not a column of '${tableName}'.`,\n );\n }\n const direction = typeof entry === 'string' ? entry : entry?.direction;\n if (direction !== 'asc' && direction !== 'desc') {\n throw new Error(\n `Drizzle-GraphQL Error: config.defaults.${tableName}.orderBy.${columnName} must be 'asc', 'desc', or { direction, priority? }.`,\n );\n }\n const priority = typeof entry === 'string' ? undefined : entry?.priority;\n if (priority !== undefined && !Number.isInteger(priority)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.defaults.${tableName}.orderBy.${columnName}.priority must be an integer.`,\n );\n }\n normalized[columnName] = priority === undefined ? { direction } : { direction, priority };\n }\n defaultOrderByByTable.set(tableName, normalized);\n }\n }\n const defaultOrderBy: DefaultOrderByFor | undefined = defaultOrderByByTable.size\n ? (tableName: string) => defaultOrderByByTable.get(tableName)\n : undefined;\n\n // A row scope and the context-derived columns are resolved against the real schema for the\n // same reason exclusions are: a renamed table or column must fail the build, not silently\n // stop scoping. Both stay undefined unless configured, so an unconfigured build emits the\n // same SQL it always did.\n const scopeConfig = config?.scope;\n const contextValuesConfig = config?.contextValues;\n if (scopeConfig || contextValuesConfig) {\n const tableNames = new Set(tableKeys);\n for (const [tableName, hook] of Object.entries(scopeConfig ?? {})) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.scope names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n if (typeof hook !== 'function') {\n throw new Error(`Drizzle-GraphQL Error: config.scope.${tableName} must be a function.`);\n }\n }\n for (const [tableName, columnHooks] of Object.entries(contextValuesConfig ?? {})) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.contextValues names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n const columns = getColumns(schema[tableName] as Table);\n for (const [columnName, hook] of Object.entries(columnHooks)) {\n if (!columns[columnName]) {\n throw new Error(\n `Drizzle-GraphQL Error: config.contextValues names '${tableName}.${columnName}', which is not a column of that table.`,\n );\n }\n if (typeof hook !== 'function') {\n throw new Error(`Drizzle-GraphQL Error: config.contextValues.${tableName}.${columnName} must be a function.`);\n }\n }\n }\n }\n // Soft delete is resolved against the real columns here, once, so a renamed column or a\n // NOT NULL column with no restore value fails the build rather than silently making every\n // row visible again at runtime.\n const softDeleteConfig = config?.softDelete;\n const softDeleteInfos = new Map<string, SoftDeleteInfo>();\n if (softDeleteConfig) {\n if (typeof softDeleteConfig === 'function') {\n for (const tableName of tableKeys) {\n const declaration = softDeleteConfig(schema[tableName] as Table, tableName);\n if (declaration) {\n softDeleteInfos.set(tableName, resolveSoftDeleteInfo(schema[tableName] as Table, tableName, declaration));\n }\n }\n } else {\n const tableNames = new Set(tableKeys);\n for (const [tableName, declaration] of Object.entries(softDeleteConfig)) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n softDeleteInfos.set(tableName, resolveSoftDeleteInfo(schema[tableName] as Table, tableName, declaration));\n }\n }\n }\n\n // Write hooks are resolved the same way: a table name that matches nothing fails the build,\n // and the two registration shapes collapse into one per-table lookup here rather than in\n // every resolver.\n const onWriteConfig = config?.onWrite;\n const writeHooks = new Map<string, ResolvedWriteHooks | undefined>();\n let globalWriteHooks: ResolvedWriteHooks | undefined;\n if (onWriteConfig) {\n // A bare function, or an object naming the positions, applies to every table; anything\n // else is a table map. `before`/`after` are reserved as position names for that reason.\n const isGlobal =\n typeof onWriteConfig === 'function' ||\n typeof (onWriteConfig as WriteHookPositions).before === 'function' ||\n typeof (onWriteConfig as WriteHookPositions).after === 'function';\n if (isGlobal) {\n globalWriteHooks = normalizeWriteHooks(onWriteConfig as WriteHooks);\n } else {\n const tableNames = new Set(tableKeys);\n for (const [tableName, hooks] of Object.entries(onWriteConfig as Record<string, WriteHooks>)) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.onWrite names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n if (typeof hooks !== 'function' && typeof hooks !== 'object') {\n throw new Error(\n `Drizzle-GraphQL Error: config.onWrite.${tableName} must be a function or an object with 'before' and/or 'after'.`,\n );\n }\n writeHooks.set(tableName, normalizeWriteHooks(hooks));\n }\n }\n }\n const onWrite: WriteHookFor | undefined =\n globalWriteHooks || writeHooks.size\n ? (tableName: string) => globalWriteHooks ?? writeHooks.get(tableName)\n : undefined;\n\n const policies: TablePolicies | undefined =\n scopeConfig || contextValuesConfig || softDeleteInfos.size || onWrite || defaultOrderBy\n ? {\n scope: scopeConfig ? (tableName: string) => scopeConfig[tableName] : undefined,\n contextValues: contextValuesConfig ? (tableName: string) => contextValuesConfig[tableName] : undefined,\n softDelete: softDeleteInfos.size ? (tableName: string) => softDeleteInfos.get(tableName) : undefined,\n onWrite,\n defaultOrderBy,\n }\n : undefined;\n\n // Exclusions are resolved against the real schema so a renamed table or column fails the\n // build instead of quietly un-hiding itself — the failure mode that matters when this config\n // is what keeps a secret out of the API.\n const exclude = config?.exclude;\n if (exclude) {\n const tableNames = new Set(tableKeys);\n const excludedTables = excludedTableNames;\n for (const tableName of excludedTables) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.exclude.tables names '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n }\n if (excludedTables.size >= tableNames.size) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.exclude.tables excludes every table in the schema, leaving nothing to generate.',\n );\n }\n for (const [tableName, columnNames] of Object.entries(exclude.columns ?? {})) {\n if (!tableNames.has(tableName)) {\n throw new Error(\n `Drizzle-GraphQL Error: config.exclude.columns names table '${tableName}', which is not a table in the Drizzle schema.`,\n );\n }\n // An excluded table has no columns left to hide; listing them too is redundant, not wrong.\n if (excludedTables.has(tableName)) {\n continue;\n }\n const columns = getColumns(schema[tableName] as Table);\n for (const columnName of columnNames) {\n const column = columns[columnName];\n if (!column) {\n throw new Error(\n `Drizzle-GraphQL Error: config.exclude.columns names '${tableName}.${columnName}', which is not a column of that table.`,\n );\n }\n // Hiding a column every insert must supply leaves the table readable but unwritable.\n // That is a reasonable thing to configure deliberately, so it warns rather than throws.\n if (column.notNull && !column.hasDefault && !column.defaultFn) {\n console.warn(\n `Drizzle-GraphQL Warning: excluded column '${tableName}.${columnName}' is NOT NULL with no default, so generated inserts for '${tableName}' can never succeed.`,\n );\n }\n }\n }\n }\n\n // Some operations are built out of others: an upsert writes through the insert and update\n // paths, a batch update reuses the update input, a grouped result reuses the aggregate\n // output types. The generator knows those implications; a table whose flags contradict them\n // is told at build time rather than leaving the consumer to notice a second write path (or a\n // missing operation) later. These warn rather than throw — the resulting schema is coherent,\n // it just isn't what the config appears to ask for.\n const featureConflicts = new Map<string, string[]>();\n const noteConflict = (message: string, tableName: string) => {\n const tables = featureConflicts.get(message);\n if (tables) {\n tables.push(tableName);\n } else {\n featureConflicts.set(message, [tableName]);\n }\n };\n for (const tableName of featureTables) {\n const tableFeatures = forTable(tableName);\n if (tableFeatures.upsert) {\n const missing = [!tableFeatures.insert ? 'insert' : undefined, !tableFeatures.update ? 'update' : undefined]\n .filter(Boolean)\n .join(' and ');\n if (missing) {\n noteConflict(\n `upsert is on while ${missing} is off, so the upsert mutations are a second write path past the operation you turned off`,\n tableName,\n );\n }\n }\n // Nested writes are build-wide, so a relation pointing at this table can still write it\n // from another table's mutation even with its own write operations turned off.\n if (config?.features?.nestedWrites && (!tableFeatures.insert || !tableFeatures.update)) {\n noteConflict(\n \"nestedWrites is on while this table's own insert or update is off, so a nested `create` or `connect` under another table's mutation can still write it\",\n tableName,\n );\n }\n // Only flagged when the caller actually asked for the dependent feature: both default to\n // on, so turning off the operation they build on is the normal way to remove them.\n if (config?.features?.updateMany !== undefined && tableFeatures.updateMany && !tableFeatures.update) {\n noteConflict('updateMany is on while update is off, so no batch update is generated', tableName);\n }\n if (config?.features?.groupBy !== undefined && tableFeatures.groupBy && !tableFeatures.aggregates) {\n noteConflict('groupBy is on while aggregates is off, so no grouped query is generated', tableName);\n }\n // The count mutations mirror the plural write they count, so they need at least one of the\n // two to be generated at all.\n if (tableFeatures.countMutations && !tableFeatures.update && !tableFeatures.delete) {\n noteConflict(\n 'countMutations is on while update and delete are both off, so no count mutation is generated',\n tableName,\n );\n }\n }\n for (const [message, tables] of featureConflicts) {\n const listed =\n tables.length > 5 ? `${tables.slice(0, 5).join(', ')} and ${tables.length - 5} more` : tables.join(', ');\n console.warn(`Drizzle-GraphQL Warning: config.features — ${message} (${listed}).`);\n }\n\n // Normalize eagerLoadRelations (boolean | predicate | undefined) into a predicate.\n const eagerOpt = config?.eagerLoadRelations;\n const shouldEagerLoad: (tableName: string, relationName: string) => boolean =\n eagerOpt === undefined || eagerOpt === true ? () => true : eagerOpt === false ? () => false : eagerOpt;\n\n // When a typeNameMapper is provided, the mapper's singular/plural forms disambiguate the\n // list and single fields even if the suffixes are identical (e.g. both '').\n // Only enforce the suffix-collision check when no mapper is active.\n if (!typeNameMapper && suffixes.list === suffixes.single) {\n throw new Error(\n 'Drizzle-GraphQL Error: List and single query suffixes cannot be the same. This would create conflicting GraphQL field names.',\n );\n }\n\n if (typeof config?.relationsDepthLimit === 'number') {\n if (config.relationsDepthLimit < 0) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.relationsDepthLimit is supposed to be nonnegative integer or undefined!',\n );\n }\n if (config.relationsDepthLimit !== ~~config.relationsDepthLimit) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.relationsDepthLimit is supposed to be nonnegative integer or undefined!',\n );\n }\n }\n\n const generatorOptions: SchemaGeneratorOptions = {\n relationsDepthLimit: config?.relationsDepthLimit,\n prefixes,\n suffixes,\n conflictDoNothing: config?.conflictDoNothing ?? false,\n typeNameMapper,\n shouldEagerLoad,\n features: config?.features ?? {},\n complexity,\n scalars: config?.scalars,\n mapColumnType: config?.mapColumnType,\n enumNameMapper: config?.enumNameMapper,\n transactions,\n limits,\n policies,\n exclude,\n docs: {\n describeColumn: config?.describeColumn,\n describeTable: config?.describeTable,\n describeRelation: config?.describeRelation,\n deprecateColumn: config?.deprecateColumn,\n },\n };\n\n 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 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 { relationFieldExtension, tableTypeExtension } from '../extensions.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 OrderByArgs,\n ProcessedTableSelectArgs,\n SelectData,\n SelectedColumnsRaw,\n SelectedSQLColumns,\n TableFeatures,\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 /**\n * Opens a transaction for a field that would otherwise have run straight on `db`. Set when\n * the field carries an `onWrite` hook, whose whole purpose is to write atomically with the\n * mutation — a hook that ran outside a transaction could not roll anything back.\n */\n forceTx?: boolean,\n): Promise<T> => {\n const contextIsObject = context !== null && (typeof context === 'object' || typeof context === 'function');\n // Check our own request state FIRST: once the shared transaction is stashed on the\n // context it is indistinguishable from a caller-supplied one, but its completion still\n // has to be accounted here.\n const stateKey: object = contextIsObject ? context : info.operation;\n let state = txCtx?.states.get(stateKey);\n\n if (!state) {\n if (contextIsObject && context[drizzleExecutorKey]) {\n // The caller already runs this request on its own transaction/executor — use it as-is.\n return body(context[drizzleExecutorKey]);\n }\n if (!txCtx || info.operation.operation !== 'mutation') {\n return forceTx ? db.transaction((tx: any) => body(tx)) : body(db);\n }\n const keys = new Set<string>();\n const allKnown = collectRootMutationKeys(\n info.operation.selectionSet,\n info.fragments,\n info.variableValues,\n txCtx.fieldNames,\n keys,\n new Set(),\n );\n state =\n !allKnown || keys.size <= 1 ? { kind: 'passthrough' } : openSharedTx(db, context, txCtx, stateKey, keys.size);\n txCtx.states.set(stateKey, state);\n }\n\n if (state.kind === 'passthrough') {\n const executor = resolveExecutor(db, context);\n return forceTx && executor === db ? db.transaction((tx: any) => body(tx)) : body(executor);\n }\n return runOnSharedTx(state, body);\n};\n\n// ---------------------------------------------------------------------------\n// Write hooks (`BuildSchemaConfig.onWrite`)\n// ---------------------------------------------------------------------------\n\n/** The write a hook is attached to. `restore` only exists for a soft-deleting table. */\nexport type WriteOperation = 'insert' | 'update' | 'updateMany' | 'upsert' | 'delete' | 'restore';\n\n/** What a write hook is handed. See {@link BuildSchemaConfig.onWrite}. */\nexport type WriteHookPayload = {\n /** Drizzle schema key of the table being written. */\n table: string;\n operation: WriteOperation;\n /** `'before'` runs ahead of the statement, `'after'` once it has returned. */\n position: 'before' | 'after';\n /** Whether the field writes a single row (`createUsersSingle`) or a list. */\n single: boolean;\n /** The field's GraphQL arguments, exactly as the resolver received them. */\n args: any;\n /**\n * The rows the write produced, as the database returned them — before the output mapper,\n * so values are database-shaped. Empty at the `before` position, and on MySQL, whose\n * mutations return no rows.\n */\n rows: any[];\n context: any;\n info: any;\n /** The executor the mutation itself ran on. Throwing from the hook rolls it back. */\n tx: any;\n};\n\nexport type WriteHook = (payload: WriteHookPayload) => void | Promise<void>;\nexport type WriteHookPositions = { before?: WriteHook; after?: WriteHook };\nexport type WriteHooks = WriteHook | WriteHookPositions;\n\n/** Resolved, per-field hooks: `undefined` when the table registered none. */\nexport type ResolvedWriteHooks = { before?: WriteHook; after?: WriteHook };\n\n/** Build-time lookup of a table's hooks, installed on {@link TablePolicies}. */\nexport type WriteHookFor = (tableName: string, operation: WriteOperation) => ResolvedWriteHooks | undefined;\n\n/**\n * Normalizes the two registration shapes: a bare function is the `after` hook — the position\n * that has rows, and the one the common audit/outbox case wants — while `{ before, after }`\n * names them explicitly.\n */\nexport const normalizeWriteHooks = (hooks: WriteHooks | undefined | null): ResolvedWriteHooks | undefined => {\n if (!hooks) {\n return undefined;\n }\n if (typeof hooks === 'function') {\n return { after: hooks };\n }\n const resolved = { before: hooks.before, after: hooks.after };\n return resolved.before || resolved.after ? resolved : undefined;\n};\n\n/**\n * Invokes one position of a field's hooks. Returns `undefined` rather than a resolved promise\n * when nothing is registered, so the awaiting call site costs nothing on an unhooked build.\n */\nexport const runWriteHook = (\n hooks: ResolvedWriteHooks | undefined,\n position: 'before' | 'after',\n payload: Omit<WriteHookPayload, 'position' | 'rows'> & { rows?: any[] },\n): Promise<void> | undefined => {\n const hook = position === 'before' ? hooks?.before : hooks?.after;\n if (!hook) {\n return undefined;\n }\n return Promise.resolve(hook({ ...payload, position, rows: payload.rows ?? [] }));\n};\n\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 whereArgs?: Record<string, any>,\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, whereArgs) : []),\n ...primaryKeyOrderExprs(targetTable, pkNames),\n ];\n const orderClause = orderExprs.length ? sql` order by ${sql.join(orderExprs, sql`, `)}` : sql``;\n // Namespaced alias so it can't collide with a real column on the target table.\n const RN = '__drizzle_graphql_rn';\n const rowNumber = sql`row_number() over (partition by ${foreignCol}${orderClause})`.as(RN);\n\n // Subquery: every target column plus a per-partition row number.\n const sub = db\n .select({ ...cols, [RN]: rowNumber })\n .from(targetTable)\n .where(whereCondition)\n .as('__paginated');\n\n // Outer: keep only the rows that fall inside each parent's window.\n const lower = offset ?? 0;\n const windowConds: any[] = [gt(sub[RN], lower)];\n if (limit != null) {\n windowConds.push(lte(sub[RN], lower + limit));\n }\n\n const rows: any[] = await db\n .select()\n .from(sub)\n .where(and(...windowConds))\n .orderBy(sub[RN]);\n\n // Strip the helper column so it doesn't leak into remapping/output.\n for (const row of rows) {\n delete row[RN];\n }\n return rows;\n};\n\n/**\n * Creates a RelationResolverFactory that generates field-level resolvers for each relation.\n * Each resolver:\n * 1. Returns pre-fetched data if the parent resolver already included it (eager path, zero cost).\n * 2. When limit/offset args are present, falls back to a direct per-item query.\n * 3. Otherwise batches all sibling resolver calls within the same GraphQL execution tick\n * into a single IN-clause query, eliminating N+1 database round-trips.\n *\n * `nullOrdering` is the dialect's native `ORDER BY` placement for `NULL` — the keyset\n * predicate behind a relation's `after` argument has to match it, or rows with a `NULL` in an\n * ordered column would be skipped instead of paged through. It has no sensible default, so\n * each dialect builder states it: `'nulls-largest'` for PostgreSQL, `'nulls-smallest'` for\n * MySQL and SQLite.\n */\nexport const createRelationResolverFactory =\n (\n db: any,\n tables: Record<string, Table>,\n nullOrdering: NullOrdering,\n filterCtx?: RelationFilterBase,\n limits?: LimitPolicyFor,\n policies?: TablePolicies,\n ): RelationResolverFactory =>\n ({ tableName, relationName, relEntry, isOne }) => {\n const parentTable = tables[tableName];\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n\n if (!parentTable || !targetTable) {\n return undefined;\n }\n\n const joinCols = extractRelationJoinColumns(relEntry, parentTable, targetTable);\n if (!joinCols) {\n return undefined;\n }\n\n const { localColPropName, foreignCol, foreignColPropName } = joinCols;\n // 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, limit: requestedLimit, offset, after, deleted } = (args ?? {}) as any;\n // A relation field falls back to the *target* table's default ordering, since that is\n // the table it reads. A to-one relation is a single row and takes no ordering at all.\n const orderByArg = isOne\n ? (args as any)?.orderBy\n : withDefaultOrderBy(args ?? {}, targetTableName, policies?.defaultOrderBy).orderBy;\n const limit = applyLimitPolicy(requestedLimit, limitPolicy, `${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 deleted: deleted ?? 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 // Loaders are keyed per context too, so the scope resolved here is this request's.\n const scope = resolveScope(policies, context, filterCtx);\n let whereCondition = withScope(\n scope,\n targetTableName,\n targetTable,\n and(\n inArray(foreignCol, uniqueIds),\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n cursorValues ? buildCursorCondition(targetTable, cursorEntries!, cursorValues, nullOrdering) : undefined,\n ),\n deleted,\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 whereArg,\n );\n } else {\n // Use plain db.select() so column refs are never aliased — avoids drizzle-orm v1\n // RQB aliasing requirements that would require referencing via aliasedTable proxy.\n let q = 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), whereArg)\n : [];\n if (orderExprs.length) {\n q = q.orderBy(...orderExprs);\n }\n rows = await q;\n }\n\n // Before remapping, which rewrites dates and bigints into their transport forms.\n if (cursorEntries) {\n attachRowCursors(rows, cursorEntries);\n }\n\n // Group by FK value before remapping (remapping may delete null fields).\n if (isOne) {\n const byKey = new Map(rows.map((row: any) => [String(row[foreignColPropName]), row]));\n remapToGraphQLArrayOutput(rows, targetTableName, targetTable);\n return parentIds.map((id) => byKey.get(String(id)) ?? null);\n }\n\n const grouped = new Map<string, any[]>(uniqueIds.map((id) => [String(id), []]));\n for (const row of rows) {\n grouped.get(String(row[foreignColPropName]))?.push(row);\n }\n remapToGraphQLArrayOutput(rows, targetTableName, targetTable);\n return parentIds.map((id) => grouped.get(String(id)) ?? []);\n });\n\n return loader.load(localValue);\n };\n };\n\n/**\n * The `extensions.drizzle` block for one relation field. The relation entry already carries\n * the target table's primary key (resolved at build time for pagination), so the field can\n * publish it without the dialect's key resolver being reachable from here.\n */\nconst relationExtensionFor = (\n relEntry: TableNamedRelations,\n parentTable: string,\n relationName: string,\n isOne: boolean,\n aggregate?: boolean,\n) =>\n relationFieldExtension({\n targetTable: relEntry.targetTableName,\n parentTable,\n relation: relationName,\n single: isOne,\n primaryKey: relEntry.targetPkNames ?? [],\n aggregate,\n });\n\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 * A table's primary-key property names, from the dialect's own resolver. Object types and\n * relation fields publish it on `extensions.drizzle` so a consumer can identify the rows a\n * field is about without re-deriving the key from the Drizzle schema.\n */\n primaryKeyOf?: (tableName: string) => readonly string[];\n /**\n * The context-derived columns of a table, if any. Read when the create/update inputs are\n * built: a column the server fills in is not part of either.\n */\n contextValuesOf?: ContextValuesFor;\n /**\n * The soft-delete convention of a table, if it declares one. Read when the write inputs are\n * built — the marker column is written by the delete and restore mutations, not by a client\n * — and when a read field's `deleted` argument is generated.\n */\n softDeleteOf?: SoftDeleteFor;\n /**\n * This build's feature flags, resolved for one table. Like `complexity` and `docs`, not a\n * cache — the type builders are several calls deep and this context is already threaded\n * through them. A lookup rather than a flat object because a flag may be a per-table\n * predicate, and because the table a builder is asked about is not always the one whose\n * type it is building: a relation field reads the flags of the table it points at.\n */\n featureOf: (tableName: string) => TableFeatures;\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 * {@link BuildSchemaConfig.defaults} resolved for one table: the `orderBy` a read falls back\n * to when the request passes none, already in the shape the generated argument has.\n * `undefined` means the table declares no default and keeps whatever order the database\n * returns.\n */\nexport type DefaultOrderByFor = (tableName: string) => Record<string, any> | undefined;\n\n/**\n * Substitutes a table's default ordering for an absent `orderBy`.\n *\n * Applied where the arguments are first read, so everything downstream — the cursor tuple, a\n * `distinct` pass, the plain-select fallback — sees one effective ordering and cannot\n * disagree about it. Only a missing argument is replaced: `orderBy: {}` is a request for no\n * ordering, and stays one.\n */\nexport const withDefaultOrderBy = <T extends { orderBy?: any }>(\n args: T,\n tableName: string,\n defaults: DefaultOrderByFor | undefined,\n): T => {\n if (!defaults || args?.orderBy != null) {\n return args;\n }\n const fallback = defaults(tableName);\n return fallback ? { ...args, orderBy: fallback } : args;\n};\n\n/**\n * The `limit` a query actually runs with, given the policy for the table it reads.\n *\n * A request that passes no `limit` falls back to `defaultLimit`, or to `maxLimit` when only\n * that is configured — an absent limit means every row, which is above any maximum. A limit\n * the client did ask for is rejected when it exceeds `maxLimit`, since silently truncating a\n * page tells a paginating client it has reached the end when it has not; `clampToMax` opts\n * into the truncation instead. A limit the *policy* supplied is capped rather than rejected —\n * a misconfigured `defaultLimit` above `maxLimit` is the operator's problem, not something to\n * fail a client's query over.\n */\nexport const applyLimitPolicy = (\n limit: number | null | undefined,\n policy: ResolvedLimitPolicy | undefined,\n 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 * Columns this build keeps out of the generated schema, keyed by the table object.\n *\n * A registry rather than a threaded parameter because the sites that decide schema shape —\n * the object type, every input, the filter, `orderBy`, the aggregates, the column enums —\n * are spread across four files and reach a table with no config in hand. Runtime code keeps\n * calling `getColumns` directly: a primary key that a client cannot name is still the key a\n * cursor is built from, and hiding it there would break pagination rather than secure it.\n *\n * {@link registerColumnExclusions} runs on every build, including with no config, so a\n * second build against the same table objects never inherits the first build's exclusions.\n */\nconst excludedColumnRegistry = new WeakMap<object, Set<string>>();\n\n/** Installs this build's column exclusions and clears any left by a previous build. */\nexport const registerColumnExclusions = (\n tables: Record<string, Table>,\n exclude?: { columns?: Record<string, string[]> },\n): void => {\n for (const [tableName, table] of Object.entries(tables)) {\n const hidden = exclude?.columns?.[tableName];\n if (hidden?.length) {\n excludedColumnRegistry.set(table, new Set(hidden));\n } else {\n excludedColumnRegistry.delete(table);\n }\n }\n};\n\n/** Whether any column of this table was excluded from the schema. */\nexport const hasExcludedColumns = (table: Table): boolean => excludedColumnRegistry.has(table);\n\n/**\n * A stable string naming this build's exclusions for `table`, empty when it has none. Used to\n * key the caches that hold generated types: two builds of the same table objects with\n * different exclusions must not share an entry, but *within* one build every call site has to\n * get the same instance back or the schema ends up with two types of the same name.\n */\nexport const excludedColumnsKey = (table: Table): string => {\n const hidden = excludedColumnRegistry.get(table);\n return hidden ? [...hidden].sort().join(',') : '';\n};\n\n/**\n * The columns of `table` that this build exposes — every column unless some were excluded.\n * Use this anywhere the result decides what the *schema* contains; use `getColumns` where it\n * decides what SQL to write.\n */\nexport const visibleColumns = (table: Table): Record<string, Column> => {\n const columns = getColumns(table);\n const hidden = excludedColumnRegistry.get(table);\n if (!hidden) {\n return columns;\n }\n return Object.fromEntries(Object.entries(columns).filter(([columnName]) => !hidden.has(columnName)));\n};\n\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 matchFilterOrder: {\n type: GraphQLBoolean,\n description:\n \"Sort by this column's position in the `inArray` list the same request's `where` gives it, rather than by the column's own value — `direction: asc` keeps the list's order, `desc` reverses it. Requires an `inArray` filter on the same column at the top level of `where`, and cannot be combined with `after` or `distinct`.\",\n },\n } 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 path: {\n type: new GraphQLList(new GraphQLNonNull(jsonPathFilter)),\n description:\n 'Compares the value at one path inside the document. Several entries are ANDed; a single object may be passed without the list brackets.',\n },\n isNull: { type: GraphQLBoolean },\n isNotNull: { type: GraphQLBoolean },\n };\n};\n\n/**\n * How the value at a JSON path is read before it is compared. Left unset, the operand\n * decides: a GraphQL number compares numerically, a boolean as a boolean, anything else as\n * text. Set it when the operand's type does not match the document's — comparing a numeric\n * field against a `String` variable, say.\n */\nconst jsonPathCast = new GraphQLEnumType({\n name: 'JSONPathCast',\n description: 'How to read the value at a JSON path before comparing it',\n values: {\n TEXT: { value: 'text', description: 'Compare as text (lexicographic ordering)' },\n NUMBER: { value: 'number', description: 'Compare as a number; a non-numeric value never matches' },\n BOOLEAN: { value: 'boolean', description: 'Compare as a boolean' },\n },\n});\n\n/**\n * One predicate on the value at a path inside a json/jsonb column. `path` walks the document\n * key by key (an all-digits element indexes an array), and the remaining operators compare\n * whatever sits there. Operands are `JSON` so a single input type serves string, number and\n * boolean fields; see {@link jsonPathCast} for how the comparison type is chosen.\n *\n * Note that `contains` here is substring matching on the extracted value — unlike `contains`\n * on the column itself, which is structural JSON containment. A path names a scalar, so the\n * string reading is the useful one.\n */\nconst jsonPathFilter = new GraphQLInputObjectType({\n name: 'JSONPathFilter',\n fields: {\n path: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLString))),\n description:\n 'Keys to walk from the document root, e.g. `[\"profile\", \"level\"]`. An all-digits key indexes an array.',\n },\n as: { type: jsonPathCast, description: 'Overrides how the value is read before comparing' },\n eq: { type: GraphQLJSON, description: 'Equal to' },\n ne: { type: GraphQLJSON, description: 'Not equal to' },\n lt: { type: GraphQLJSON, description: 'Less than' },\n lte: { type: GraphQLJSON, description: 'Less than or equal to' },\n gt: { type: GraphQLJSON, description: 'Greater than' },\n gte: { type: GraphQLJSON, description: 'Greater than or equal to' },\n startsWith: {\n type: GraphQLString,\n description: 'Extracted value starts with this string. `%`, `_` and `\\\\` are matched literally.',\n },\n endsWith: {\n type: GraphQLString,\n description: 'Extracted value ends with this string. `%`, `_` and `\\\\` are matched literally.',\n },\n contains: {\n type: GraphQLString,\n description: 'Extracted value contains this string. `%`, `_` and `\\\\` are matched literally.',\n },\n iStartsWith: { type: GraphQLString, description: 'Case-insensitive `startsWith`.' },\n iEndsWith: { type: GraphQLString, description: 'Case-insensitive `endsWith`.' },\n iContains: { type: GraphQLString, description: 'Case-insensitive `contains`.' },\n isNull: {\n type: GraphQLBoolean,\n description: 'When true, matches rows where the path is missing or holds JSON null',\n },\n isNotNull: { type: GraphQLBoolean, description: 'When true, matches rows where the path holds a value' },\n },\n});\n\n/**\n * `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 // The cache outlives a build, so a table whose columns this build hides must not read from\n // it (a previous build may have cached the full set) or write to it (a later unfiltered\n // build would inherit the holes).\n const cacheable = !hasExcludedColumns(table);\n if (cacheable && orderMap.has(table)) {\n return orderMap.get(table)!;\n }\n\n let remapped = {};\n try {\n const columns = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n remapped = Object.fromEntries(\n columnEntries.map(([columnName, _columnDescription]) => [columnName, { type: innerOrder }]),\n );\n\n if (cacheable) {\n orderMap.set(table, remapped);\n }\n } catch (_err) {}\n return remapped;\n};\n\nconst generateTableFilterValuesCached = (table: Table, tableName: string, cacheCtx: TypeCacheCtx) => {\n if (cacheCtx.filterFieldCache.has(table)) {\n return cacheCtx.filterFieldCache.get(table)!;\n }\n\n const columns = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n const remapped = Object.fromEntries(\n columnEntries.map(([columnName, column]) => [\n columnName,\n {\n type: generateColumnFilterValues(column, tableName, columnName, cacheCtx),\n // A filter field is the same column, so it carries the same documentation. Deprecation\n // is not propagated: filtering on a deprecated column is how a caller finds the rows\n // that still use it.\n ...(cacheCtx.docs.describeColumn\n ? { description: cacheCtx.docs.describeColumn(column, { tableName, columnName }) }\n : {}),\n },\n ]),\n );\n\n cacheCtx.filterFieldCache.set(table, remapped);\n\n return remapped;\n};\n\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 = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n const remapped = Object.fromEntries(\n columnEntries.map(([columnName, column]) => [\n columnName,\n {\n ...drizzleColumnToGraphQLType(column, columnName, tableName),\n ...columnDocs(cacheCtx.docs, column, tableName, columnName),\n },\n ]),\n );\n\n // Opaque keyset-pagination cursor. Only populated on rows returned by a list query; a real\n // column named `cursor` keeps the field for itself instead.\n if (!remapped[CURSOR_FIELD_NAME]) {\n remapped[CURSOR_FIELD_NAME] = {\n type: GraphQLString,\n description:\n \"Opaque cursor of this row's position in the query's ordering. Pass it as `after` to resume from here. Only set on rows returned by a list query.\",\n resolve: rowCursorResolver,\n } as ConvertedColumn;\n }\n\n cacheCtx.selectFieldCache.set(table, remapped);\n\n return remapped;\n};\n\n/**\n * 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 extensions: { drizzle: tableTypeExtension(tableName, cacheCtx.primaryKeyOf?.(tableName) ?? []) },\n });\n cacheCtx.objectTypeCache.set(tableName, shell);\n }\n\n // Build relation fields — recurse into each related table.\n // Mark this table as in-progress before recursing to detect cycles.\n if (relationEntries.length > 0) {\n const rawRelationFields: [string, ConvertedRelationColumnWithArgs][] = [];\n\n // Mark this table as currently being processed.\n const nextUsedTables = new Set(usedTables);\n nextUsedTables.add(tableName);\n\n for (const [relationName, relEntry] of relationEntries) {\n const { targetTableName } = relEntry;\n const relation = (relEntry as any).relation ?? relEntry;\n const isOne = is(relation, One);\n\n // Always recurse to get the target table's filters/order (needed for args).\n // The usedTables check inside the recursive call prevents actual infinite recursion.\n const relSelectData = generateSelectFields(\n tables,\n targetTableName,\n relationMap,\n tableName, // fromTableName for the relation type\n relationName, // fromRelationName for the relation type\n !isOne,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n nextUsedTables,\n resolverFactory,\n currentDepth + 1,\n relationAggregateFactory,\n );\n\n // Use the target table's own GraphQL type directly instead of creating an intermediate relation type.\n // Ensure exactly one GraphQLObjectType instance exists for the target table.\n // If the root call for the target table has already run (or pre-registered a shell),\n // reuse that instance so the schema never contains duplicate type names.\n let relType = cacheCtx.objectTypeCache.get(targetTableName);\n if (!relType) {\n // The target table hasn't been processed yet. Pre-register a shell so that:\n // (a) this relation field has a concrete type reference, and\n // (b) when the target table's root call eventually runs, it reuses this same object.\n const targetTable = tables[targetTableName]!;\n const targetTableFields = generateTableSelectTypeFieldsCached(targetTable, targetTableName, cacheCtx);\n // Get or create a container for the target table's relation fields.\n let targetContainer = cacheCtx.relationFieldContainers.get(targetTableName);\n if (!targetContainer) {\n targetContainer = { fields: {} };\n cacheCtx.relationFieldContainers.set(targetTableName, targetContainer);\n }\n const capturedTargetContainer = targetContainer;\n // The thunk reads capturedTargetContainer.fields so that when the target table's root\n // call populates the container, the shell automatically includes those relation fields.\n relType = new GraphQLObjectType({\n name: resolveTypeName(targetTableName, typeNameMapper),\n description: cacheCtx.docs.describeTable?.(targetTableName),\n fields: () => ({ ...targetTableFields, ...capturedTargetContainer.fields }),\n extensions: {\n drizzle: tableTypeExtension(targetTableName, cacheCtx.primaryKeyOf?.(targetTableName) ?? []),\n },\n });\n cacheCtx.objectTypeCache.set(targetTableName, relType);\n }\n\n const resolve = resolverFactory?.({ tableName, relationName, relEntry: relEntry as TableNamedRelations, isOne });\n const relationDescription = cacheCtx.docs.describeRelation?.(tableName, relationName);\n const relationDocs = relationDescription !== undefined ? { description: relationDescription } : {};\n\n if (isOne) {\n // Honor the relation's declared optionality: `r.one.Target({ ..., optional: false })`\n // asserts the related row always exists (a NOT NULL foreign key), so the field is\n // emitted as `Target!`. The default (`optional: true` / omitted) stays nullable.\n // Column nullability alone is NOT used to infer this — a notNull `from` column does\n // not guarantee a related row exists when the FK constraint lives on the other side\n // (e.g. `Users.customer` joins the notNull `Users.id` to `Customers.userId`).\n const isRequired = (relation as One<any, any>).optional === false;\n rawRelationFields.push([\n relationName,\n {\n type: isRequired ? new GraphQLNonNull(relType) : relType,\n args: {\n where: { type: relSelectData.filters },\n ...deletedArg(cacheCtx.softDeleteOf, targetTableName),\n },\n resolve,\n ...relationDocs,\n extensions: { drizzle: relationExtensionFor(relEntry, tableName, relationName, true) },\n },\n ]);\n continue;\n }\n\n // A to-many relation field is a list of the target table, so it takes the same\n // pagination surface a root list of that table does. `after` and `distinct` are the\n // two drizzle's `with:` clause cannot express, so a request that passes either drops\n // the relation out of the eager fetch and resolves it through the batch loader, which\n // implements both — see extractRelationsParamsInner.\n const targetDistinctEnum = cacheCtx.featureOf(targetTableName).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 ...deletedArg(cacheCtx.softDeleteOf, targetTableName),\n after: {\n type: GraphQLString,\n description:\n \"Keyset pagination: only return related rows strictly after this cursor (a row's `cursor` field from a previous page of this relation, under the same orderBy).\",\n },\n ...(targetDistinctEnum\n ? { distinct: { type: new GraphQLList(new GraphQLNonNull(targetDistinctEnum)) } }\n : {}),\n },\n resolve,\n ...relationDocs,\n extensions: {\n drizzle: relationExtensionFor(relEntry, tableName, relationName, false),\n ...(cacheCtx.complexity\n ? { complexity: listFieldComplexity(cacheCtx.complexity, cacheCtx.limits?.(targetTableName)) }\n : {}),\n },\n },\n ]);\n\n // Aggregate over the related rows without fetching them: `user { postsAggregate { count } }`.\n // Skipped when the name would shadow a column or another relation.\n const aggregateFieldName = `${relationName}Aggregate`;\n if (!tableFields[aggregateFieldName] && !relationsForTable?.[aggregateFieldName]) {\n const relationAggregate = relationAggregateFactory?.({\n tableName,\n relationName,\n relEntry: relEntry as TableNamedRelations,\n });\n\n if (relationAggregate) {\n rawRelationFields.push([\n aggregateFieldName,\n {\n type: new GraphQLNonNull(relationAggregate.type),\n args: {\n where: { type: relSelectData.filters },\n ...deletedArg(cacheCtx.softDeleteOf, targetTableName),\n },\n resolve: relationAggregate.resolve,\n extensions: {\n drizzle: relationExtensionFor(relEntry, tableName, relationName, isOne, true),\n ...(cacheCtx.complexity ? { complexity: aggregateFieldComplexity(cacheCtx.complexity) } : {}),\n },\n } as unknown as ConvertedRelationColumnWithArgs,\n ]);\n }\n }\n }\n\n const builtRelationFields = Object.fromEntries(rawRelationFields);\n\n // Only the root call should populate the container — non-root calls are temporary traversals\n // to collect filters/order for args and should not overwrite the canonical relation fields.\n if (isRootCall) {\n // Populate the container so that the thunk on the GraphQLObjectType shell (whether it was\n // created here or pre-registered by another table's relation traversal) picks up the fields.\n container.fields = builtRelationFields;\n cacheCtx.fullyBuiltTables.add(tableName);\n }\n\n return {\n order,\n filters,\n tableFields,\n relationFields: builtRelationFields,\n } as SelectData<TWithOrder>;\n }\n\n // No relation entries — mark as fully built if root call.\n if (isRootCall) {\n cacheCtx.fullyBuiltTables.add(tableName);\n }\n\n return {\n order,\n filters,\n tableFields,\n relationFields: {},\n } as SelectData<TWithOrder>;\n};\n\nexport const generateTableTypes = <WithReturning extends boolean>(\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n withReturning: WithReturning,\n relationsDepthLimit: number | undefined,\n cacheCtx: TypeCacheCtx,\n typeNameMapper: TypeNameMapper | undefined = undefined,\n insertPrefix: string = 'create',\n updatePrefix: string = 'update',\n resolverFactory?: RelationResolverFactory,\n relationAggregateFactory?: RelationAggregateFactory,\n nestedWrites?: NestedWriteTypes,\n): GeneratedTableTypes<WithReturning> => {\n const { tableFields, relationFields, filters, order } = generateSelectFields(\n tables,\n tableName,\n relationMap,\n '', // root call: no fromTableName\n '', // root call: no fromRelationName\n true,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n new Set(),\n resolverFactory,\n 0,\n relationAggregateFactory,\n );\n\n const table = tables[tableName]!;\n const columns = visibleColumns(table);\n const columnEntries = Object.entries(columns);\n\n // A column whose value comes from the request context is not part of any write input: the\n // client cannot supply one on create, and cannot reassign one on update. It stays an\n // ordinary column everywhere else — the output type, the filters, the ordering.\n const contextColumns = cacheCtx.contextValuesOf?.(tableName);\n // Same for the column that marks a row deleted: `delete` and `restore` own it, and a client\n // that could write it through an ordinary create or update could delete or undelete a row\n // without going through either.\n const markerColumn = cacheCtx.softDeleteOf?.(tableName)?.columnName;\n const writableEntries =\n contextColumns || markerColumn\n ? columnEntries.filter(\n ([columnName]) => !(contextColumns && columnName in contextColumns) && columnName !== markerColumn,\n )\n : columnEntries;\n\n // A column a nested write can supply (`author: { create: … }` fills in `authorId`) cannot\n // stay required on the create input, or the two ways of setting it would be mutually\n // exclusive at the type level.\n const relaxedColumns = nestedWrites?.relaxedColumns(tableName);\n\n const insertFields = Object.fromEntries(\n writableEntries.map(([columnName, column]) => {\n const converted = drizzleColumnToGraphQLType(\n column,\n columnName,\n tableName,\n !!relaxedColumns?.has(columnName),\n true,\n true,\n );\n return [\n columnName,\n { ...converted, ...inputFieldDocs(cacheCtx.docs, column, tableName, columnName, converted.type) },\n ];\n }),\n );\n\n const updateFields = Object.fromEntries(\n writableEntries.map(([columnName, column]) => {\n const converted = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, true);\n // A numeric or array column takes an operations input instead of the bare scalar, so\n // it can be changed relative to its current value rather than only replaced.\n const operations = cacheCtx.featureOf(tableName).fieldUpdateOperations\n ? fieldUpdateInputType(column, columnName, tableName)\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 extensions: { drizzle: tableTypeExtension(tableName, cacheCtx.primaryKeyOf?.(tableName) ?? []) },\n });\n\n const selectArrOutput = new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(selectSingleOutput)));\n\n // Mutation return type: ${capitalize(tableName)}Item (table columns only, no relations)\n // const singleTableItemOutput = withReturning\n // ? new GraphQLObjectType({\n // name: `${capitalize(tableName)}`,\n // // name: `${capitalize(tableName)}Item`,\n // fields: tableFields,\n // })\n // : undefined;\n\n const arrTableItemOutput = withReturning\n ? // ? new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(singleTableItemOutput!)))\n new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(selectSingleOutput!)))\n : undefined;\n\n const inputs = {\n insertInput,\n updateInput,\n tableOrder: order,\n tableFilters: filters,\n };\n\n const outputs = (\n withReturning\n ? {\n selectSingleOutput,\n selectArrOutput,\n singleTableItemOutput: selectSingleOutput!,\n // singleTableItemOutput: singleTableItemOutput!,\n arrTableItemOutput: arrTableItemOutput!,\n }\n : {\n selectSingleOutput,\n selectArrOutput,\n }\n ) as GeneratedTableTypesOutputs<WithReturning>;\n\n return {\n inputs,\n outputs,\n };\n};\n\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 // Same reason as above: the sort key is not a value of the row, so it cannot be\n // rebuilt against a subquery's fields or encoded into a cursor.\n if (config.matchFilterOrder) {\n throw new GraphQLError(`ORDER BY ${column}: 'matchFilterOrder' 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 * The sort key behind `matchFilterOrder`: the column's position in the `inArray` list that\n * the same request's `where` gives it, as a `CASE` ladder over that list.\n *\n * A ladder rather than a dialect array function (`array_position` on Postgres, `FIELD()` on\n * MySQL, neither on SQLite) because it is the one form all three share, and because every\n * list value stays a bound parameter. The branch indices are library-generated integers, so\n * they are written into the SQL text — a bound parameter there would leave Postgres unable\n * to infer the CASE result type. Values outside the list sort after every listed one.\n */\nconst filterOrderExpression = (column: Column, columnName: string, whereArgs: Record<string, any> | undefined): SQL => {\n const values = whereArgs?.[columnName]?.inArray as unknown;\n if (!Array.isArray(values)) {\n throw new GraphQLError(\n `ORDER BY ${columnName}: 'matchFilterOrder' needs an 'inArray' filter on the same column in this query's 'where'`,\n );\n }\n if (!values.length) {\n // An empty `inArray` matches no rows at all, so every row would sort the same anyway;\n // a constant keeps the expression valid without a ladder that has no branches.\n return sql`0`;\n }\n\n const branches = values.map(\n (value, index) =>\n sql`when ${column} = ${remapFromGraphQLCore(value, column, columnName)} then ${sql.raw(String(index))}`,\n );\n return sql`case ${sql.join(branches, sql` `)} else ${sql.raw(String(values.length))} end`;\n};\n\n/**\n * Flattens one level of an `orderBy` argument into `out`. A column key becomes an entry\n * directly (wrapped in a correlated subquery when reached through a relation chain); a\n * to-one relation key recurses with the chain extended by that hop. Priorities live in one\n * global space, so a relation's column can interleave with the parent's own columns.\n */\nconst collectOrderEntries = (\n table: Table,\n tableKey: string,\n orderArgs: Record<string, any>,\n ctx: RelationFilterContext | undefined,\n chain: RelationOrderChain | undefined,\n out: FlatOrderEntry[],\n whereArgs: Record<string, any> | undefined,\n): void => {\n const columns = getColumns(table);\n const relations = ctx?.relationMap[tableKey];\n\n for (const [key, config] of Object.entries(orderArgs)) {\n if (config === null || config === undefined) {\n continue;\n }\n\n const column = columns[key];\n if (column) {\n if (config.matchFilterOrder && chain) {\n throw new GraphQLError(`ORDER BY ${key}: 'matchFilterOrder' is not supported through a relation`);\n }\n out.push({\n expression: config.matchFilterOrder\n ? filterOrderExpression(column, key, whereArgs)\n : chain\n ? sql`(select ${column} from ${sql.join(chain.fromParts, sql`, `)} where ${and(...chain.conditions)})`\n : column,\n column,\n direction: config.direction,\n nulls: config.nulls ?? undefined,\n priority: config.priority ?? 0,\n });\n continue;\n }\n\n const relEntry = relations?.[key];\n if (!relEntry || !ctx) {\n throw 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, undefined);\n }\n};\n\n/**\n * Compiles an `orderBy` argument into ORDER BY expressions, highest priority first.\n *\n * A key naming one of the table's columns orders by that column. A key naming a to-one\n * relation takes the target table's own OrderBy input and orders by the related row's\n * column(s), compiled as a correlated scalar subquery — reusing the aliased-join machinery\n * the relation filters are built on — so it works identically on all three dialects and\n * inside the relational query builder's aliased CTEs. Priorities share one global space\n * across relation boundaries. Each entry may also carry `nulls: first | last`\n * (see {@link orderExpressions} for how MySQL emulates it).\n *\n * An entry may instead set `matchFilterOrder`, which sorts by the column's position in the\n * `inArray` list the same request's `where` gives it — `whereArgs` is that `where`.\n *\n * `ctx` supplies the tables and relation map that relation ordering needs; callers whose\n * inputs cannot contain relation keys may omit it.\n */\nexport const extractOrderBy = <TTable extends Table, TArgs extends OrderByArgs<any> = OrderByArgs<TTable>>(\n table: TTable,\n orderArgs: TArgs,\n ctx?: RelationFilterContext,\n whereArgs?: Record<string, any>,\n): SQL[] => {\n const entries: FlatOrderEntry[] = [];\n collectOrderEntries(table, ctx?.tableKey ?? '', orderArgs, ctx, undefined, entries, whereArgs);\n\n return entries\n .sort((a, b) => b.priority - a.priority)\n .flatMap((entry) => orderExpressions(entry.expression, entry.direction, entry.nulls, entry.column));\n};\n\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\n/**\n * Constant predicates, used where an operator's operand list is empty and the answer is\n * therefore known without touching the column. Written as `1 = 0` / `1 = 1` rather than the\n * `FALSE` / `TRUE` keywords so they compile identically on all three dialects. Built fresh\n * per call because a `SQL` object is spliced into whatever query consumes it.\n */\nconst sqlFalse = (): SQL => sql`1 = 0`;\nconst sqlTrue = (): SQL => sql`1 = 1`;\n\n/**\n * A MySQL / SQLite JSON path expression for the given key walk. Bound as a query parameter,\n * never spliced into the SQL text; an all-digits key becomes an array index, and quotes and\n * backslashes inside a key are escaped so a key can never end the path segment early.\n */\nconst jsonPathString = (path: string[]): string =>\n `$${path.map((part) => (/^\\d+$/.test(part) ? `[${part}]` : `.\"${part.replace(/([\"\\\\])/g, '\\\\$1')}\"`)).join('')}`;\n\n/**\n * Matches the text forms a database will accept as a number. Used to guard both numeric casts —\n * Postgres has no TRY_CAST and errors outright on a bad `::numeric`, while MySQL quietly casts\n * a non-numeric string to 0; neither is what a non-matching row should do.\n */\nconst NUMERIC_TEXT_PATTERN = '^\\\\s*-?(\\\\d+\\\\.?\\\\d*|\\\\.\\\\d+)([eE][-+]?\\\\d+)?\\\\s*$';\n\n/**\n * The value at a JSON path, as the expressions a comparison can be built on: read as text,\n * read as a number, and read as the dialect spells a boolean. Each dialect extracts\n * differently, and each needs its own guard so a value of the wrong shape answers \"no match\"\n * rather than erroring or comparing by some unrelated rule:\n *\n * - **Postgres** — `#>>` with a bound `text[]` path, which works on `json` and `jsonb` alike.\n * `::numeric` on a non-numeric string is a hard error, so the numeric read is guarded by a\n * pattern test.\n * - **MySQL** — `JSON_UNQUOTE(JSON_EXTRACT(col, ?))`, so a JSON string arrives without its\n * quotes. Unquoting a JSON *null* would otherwise yield the string `'null'`, so it is mapped\n * back to SQL NULL first. `CAST` quietly turns a non-numeric string into 0, hence the same\n * pattern guard.\n * - **SQLite** — `json_extract` returns the value in SQLite's own type, so the reads cast\n * explicitly: without that, SQLite's cross-type ordering puts every string above every\n * number and `'admin' > 0` would be true.\n */\nconst jsonPathExprs = (\n column: Column,\n path: string[],\n): { text: SQL; number: SQL; boolean: SQL; encodeBoolean: (value: boolean) => string | number } => {\n switch (columnDialect(column)) {\n case 'pg': {\n const pathArray = sql`array[${sql.join(\n path.map((part) => sql`${part}`),\n sql`, `,\n )}]::text[]`;\n const text = sql`(${column} #>> ${pathArray})`;\n return {\n text,\n number: sql`(case when ${text} ~ ${NUMERIC_TEXT_PATTERN} then ${text}::numeric end)`,\n boolean: text,\n encodeBoolean: (value) => String(value),\n };\n }\n case 'mysql': {\n const extracted = sql`json_extract(${column}, ${jsonPathString(path)})`;\n const text = sql`(case when json_type(${extracted}) = 'NULL' then null else json_unquote(${extracted}) end)`;\n return {\n text,\n number: sql`(case when ${text} regexp ${NUMERIC_TEXT_PATTERN} then cast(${text} as decimal(65, 30)) end)`,\n boolean: text,\n encodeBoolean: (value) => String(value),\n };\n }\n default: {\n const extracted = sql`json_extract(${column}, ${jsonPathString(path)})`;\n return {\n text: sql`cast(${extracted} as text)`,\n number: sql`(case when typeof(${extracted}) in ('integer', 'real') then ${extracted} end)`,\n // SQLite has no boolean type: a JSON `true` comes back as the integer 1.\n boolean: extracted,\n encodeBoolean: (value) => (value ? 1 : 0),\n };\n }\n }\n};\n\n/** Comparison operators available inside a JSON path filter, as their SQL spelling. */\nconst JSON_PATH_COMPARISONS: Record<string, string> = {\n eq: '=',\n ne: '<>',\n lt: '<',\n lte: '<=',\n gt: '>',\n gte: '>=',\n};\n\n/**\n * How the value at a path is read when the filter does not say: a GraphQL number compares\n * numerically, a boolean as a boolean, everything else as text.\n */\nconst inferJsonPathCast = (value: unknown): 'text' | 'number' | 'boolean' =>\n typeof value === 'number' ? 'number' : typeof value === 'boolean' ? 'boolean' : 'text';\n\n/**\n * Compiles one entry of a column's `path` filter: `as` (or the operand's own type) picks\n * which of {@link jsonPathExprs}' reads the comparison is built on, and the operand is bound\n * in the shape that read expects.\n */\nconst jsonPathCondition = (column: Column, columnName: string, filter: Record<string, any>): SQL | undefined => {\n const { path, as: castOverride, ...operators } = filter;\n const locator = `${columnName}.path`;\n\n if (!Array.isArray(path) || !path.length) {\n throw new GraphQLError(`WHERE ${locator}: 'path' must name at least one key`);\n }\n\n const exprs = jsonPathExprs(column, path);\n const variants: SQL[] = [];\n\n for (const [operatorName, operatorValue] of Object.entries(operators)) {\n if (operatorValue === null || operatorValue === undefined) {\n continue;\n }\n\n if (operatorName === 'isNull' || operatorName === 'isNotNull') {\n if (operatorValue === false) {\n continue;\n }\n variants.push(operatorName === 'isNull' ? sql`${exprs.text} is null` : sql`${exprs.text} is not null`);\n continue;\n }\n\n if (operatorName in safeLikeOps) {\n const { buildPattern, insensitive } = safeLikeOps[operatorName]!;\n if (typeof operatorValue !== 'string') {\n throw new GraphQLError(`WHERE ${locator}: operator '${operatorName}' takes a string`);\n }\n // The extracted value is an expression, not a column, so the case-insensitive form\n // always goes through `lower()` rather than Postgres's ILIKE.\n variants.push(safeLikeCondition(exprs.text as any, buildPattern(operatorValue), insensitive));\n continue;\n }\n\n const comparison = JSON_PATH_COMPARISONS[operatorName];\n if (!comparison) {\n throw new GraphQLError(`WHERE ${locator}: Unknown operator: ${operatorName}`);\n }\n\n const cast = castOverride ?? inferJsonPathCast(operatorValue);\n if (cast === 'number') {\n const numeric = Number(operatorValue);\n if (Number.isNaN(numeric)) {\n throw new GraphQLError(\n `WHERE ${locator}: operator '${operatorName}' compares as a number, so its value must be one`,\n );\n }\n variants.push(sql`${exprs.number} ${sql.raw(comparison)} ${numeric}`);\n } else if (cast === 'boolean') {\n const truthy = operatorValue === true || operatorValue === 'true';\n variants.push(sql`${exprs.boolean} ${sql.raw(comparison)} ${exprs.encodeBoolean(truthy)}`);\n } else {\n variants.push(sql`${exprs.text} ${sql.raw(comparison)} ${String(operatorValue)}`);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n\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 === 'path' && isJsonColumn(column)) {\n // Several path predicates on one column are ANDed, matching how sibling operators\n // already combine. GraphQL coerces a lone object into a one-element list.\n for (const pathFilter of operatorValue as Record<string, any>[]) {\n const extracted = jsonPathCondition(column, columnName, pathFilter);\n if (extracted) {\n variants.push(extracted);\n }\n }\n } else if (operatorName === 'contains' && isJsonColumn(column)) {\n // `contains` is JSON containment on json/jsonb columns; on string columns it is the\n // safe substring operator handled by safeLikeOps below.\n variants.push(jsonContains(column, columnName, operatorValue));\n } else if (operatorName in safeLikeOps) {\n const { buildPattern, insensitive } = safeLikeOps[operatorName]!;\n variants.push(safeLikeCondition(column, buildPattern(operatorValue as string), insensitive));\n } else if (operatorName in arrayValueOps) {\n // An empty candidate list is a well-formed question with a known answer — nothing is\n // `IN ()`, everything is `NOT IN ()` — so it resolves to a constant predicate rather\n // than an error. SQL has no empty-list literal, hence the constant rather than `IN ()`.\n if (!(operatorValue as any[]).length) {\n variants.push(operatorName === 'inArray' ? sqlFalse() : sqlTrue());\n continue;\n }\n const arrayValue = (operatorValue as any[]).map((val) => remapFromGraphQLCore(val, column, columnName));\n variants.push(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 // Same reasoning as inArray/notInArray: overlapping with no elements is never true,\n // and every array contains all zero of them.\n if (!(operatorValue as any[]).length) {\n variants.push(operatorName === 'hasSome' ? sqlFalse() : sqlTrue());\n continue;\n }\n variants.push(arrayMembershipOps[operatorName]!(column, operatorValue as any[]));\n } else if (operatorName === 'isEmpty') {\n variants.push(sql`cardinality(${column}) = 0`);\n } else if (operatorName in nullableOps) {\n variants.push(nullableOps[operatorName]!(column));\n } else {\n // An unrecognized operator must throw rather than be dropped: when the generated\n // schema is stitched/merged with another schema, foreign operators (e.g. `equals`,\n // `contains`, `mode`) can pass input validation, and silently dropping them could\n // turn a constrained where into an unbounded one.\n throw 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\n// ─────────────────────────────────────────────────────────────────────────────\n// Row-level scoping\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * A table's row-level scope: the predicate every generated read, update and delete on that\n * table is narrowed by. See `BuildSchemaConfig.scope`.\n *\n * `table` is the table the predicate must be built against. On the relational-query path\n * drizzle hands its callbacks an *aliased* proxy (`d0`, `d1`, …), so a predicate built from\n * the imported schema table would reference a name that isn't in the query — always build\n * from the argument. Returning a filter object instead (the same shape as the field's\n * `where`) sidesteps aliasing entirely, and is the only form that can reach through a\n * relation — which is what ownership through a join table needs.\n */\nexport type ScopeHook<TContext = any> = (context: TContext, table: any) => SQL | Record<string, any> | undefined | null;\n\n/** Build-time lookup: the scope configured for a table, if any. */\nexport type ScopeFor = (tableName: string) => ScopeHook | undefined;\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Soft delete\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** What a read over a soft-deleting table does with rows that are marked deleted. */\nexport type DeletedMode = 'EXCLUDE' | 'INCLUDE' | 'ONLY';\n\n/**\n * One table's soft-delete convention, resolved against the real column at build time.\n *\n * `nullable` picks the shape of the predicate. A nullable column marks a row deleted by\n * holding a value at all (`deletedAt IS NOT NULL`), which is the common timestamp form; a\n * non-nullable one marks it by holding `marker` (`isDeleted = true`), so the column has to\n * have a constant that means \"deleted\" and another that means \"not deleted\".\n */\nexport type SoftDeleteInfo = {\n /** Property name of the column on the drizzle table — also the key on an aliased proxy. */\n columnName: string;\n column: Column;\n nullable: boolean;\n /** Evaluated per delete, so a timestamp form stamps the moment of the delete. */\n writeDeleted: () => any;\n /** Written by the restore mutation. */\n writeRestored: any;\n /** Non-nullable form only: the constant that means \"this row is deleted\". */\n marker?: any;\n};\n\n/** Build-time lookup: the soft-delete convention of a table, if it declares one. */\nexport type SoftDeleteFor = (tableName: string) => SoftDeleteInfo | undefined;\n\n/**\n * The enum behind the `deleted` argument on every read over a soft-deleting table. One\n * instance shared by every build — it carries no per-build state.\n */\nexport const deletedFilterEnum = new GraphQLEnumType({\n name: 'DeletedFilter',\n description: 'Which rows a read over a soft-deleting table returns.',\n values: {\n EXCLUDE: { value: 'EXCLUDE', description: 'Only rows that are not marked deleted. The default.' },\n INCLUDE: { value: 'INCLUDE', description: 'Marked and unmarked rows alike.' },\n ONLY: { value: 'ONLY', description: 'Only rows that are marked deleted — a trash view.' },\n },\n});\n\n/**\n * Resolves one table's `softDelete` declaration against the real column, at build time, so a\n * renamed column fails the build instead of quietly making every row visible again.\n */\nexport const resolveSoftDeleteInfo = (\n table: Table,\n tableName: string,\n declaration: string | { column: string; deletedValue?: any; restoredValue?: any },\n): SoftDeleteInfo => {\n const config = typeof declaration === 'string' ? { column: declaration } : declaration;\n const columnName = config?.column;\n if (typeof columnName !== 'string' || !columnName) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName} must be a column name or an object with a 'column' property.`,\n );\n }\n const column = getColumns(table)[columnName];\n if (!column) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete names '${tableName}.${columnName}', which is not a column of that table.`,\n );\n }\n const nullable = !column.notNull;\n // drizzle-orm v1 reports compound dataType strings (\"object date\", \"number int32\"), so the\n // shape of the column has to come from the extended type rather than a string compare.\n const { type: baseType, constraint } = extractExtendedColumnType(column);\n const hasDeleted = 'deletedValue' in (config as object) && config.deletedValue !== undefined;\n // The default depends on what the column can hold: a timestamp records when, a flag records\n // whether. Both are the shapes the convention actually takes in the wild.\n const writeDeleted: () => any = hasDeleted\n ? typeof config.deletedValue === 'function'\n ? (config.deletedValue as () => any)\n : () => config.deletedValue\n : constraint === 'date' && baseType === 'object'\n ? () => new Date()\n : baseType === 'string'\n ? () => new Date().toISOString()\n : baseType === 'number'\n ? () => Date.now()\n : baseType === 'bigint'\n ? () => BigInt(Date.now())\n : () => true;\n\n let marker: any;\n if (!nullable) {\n // A non-nullable column has no \"absent\" state, so the predicate has to compare against a\n // constant — which a function cannot supply, and which the boolean form supplies for free.\n if (hasDeleted && typeof config.deletedValue !== 'function') {\n marker = config.deletedValue;\n } else if (!hasDeleted && baseType === 'boolean') {\n marker = true;\n } else {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName} marks a NOT NULL column ('${columnName}'), so 'deletedValue' must be a constant that means deleted — not a function, and not omitted for a non-boolean column.`,\n );\n }\n }\n\n const hasRestored = 'restoredValue' in (config as object);\n const writeRestored = hasRestored\n ? config.restoredValue\n : nullable\n ? null\n : baseType === 'boolean'\n ? false\n : undefined;\n if (!nullable && writeRestored === undefined) {\n throw new Error(\n `Drizzle-GraphQL Error: config.softDelete.${tableName} marks a NOT NULL column ('${columnName}'), so 'restoredValue' must say what restoring writes back.`,\n );\n }\n\n return { columnName, column, nullable, writeDeleted, writeRestored, marker };\n};\n\n/**\n * The predicate that selects the rows a `deleted` mode asks for: nothing for `INCLUDE`, the\n * marked rows for `ONLY`, the unmarked ones for `EXCLUDE`. Built against the table it is\n * handed, which on the relational path is drizzle's aliased proxy rather than the schema\n * table — the same rule a scope hook follows.\n */\nexport const softDeletePredicate = (info: SoftDeleteInfo, table: Table, mode: DeletedMode): SQL | undefined => {\n if (mode === 'INCLUDE') {\n return undefined;\n }\n const column = ((table as any)?.[info.columnName] ?? info.column) as Column;\n if (info.nullable) {\n return mode === 'ONLY' ? isNotNull(column) : isNull(column);\n }\n return mode === 'ONLY' ? eq(column, info.marker) : ne(column, info.marker);\n};\n\n/**\n * The row policies of one request, bound to its context: the table's scope and its\n * soft-delete convention, which both narrow the same `where`. `has` answers \"does this table\n * restrict anything at all\", cheaply and without evaluating a hook; `on` compiles the\n * predicate against a given table.\n */\nexport type ScopeResolver = {\n has: (tableName: string, mode?: DeletedMode) => boolean;\n on: (tableName: string, table: Table, mode?: DeletedMode) => SQL | undefined;\n};\n\n/**\n * Binds the configured row policies to one request's GraphQL context. Returns `undefined`\n * when neither a scope nor a soft-delete column is configured, so every call site skips the\n * machinery with a single check and an unconfigured build generates exactly the SQL it did\n * before.\n */\nexport const resolveScope = (\n policies: TablePolicies | undefined,\n context: any,\n filterCtx?: RelationFilterBase,\n): ScopeResolver | undefined => {\n const scopes = policies?.scope;\n const softDelete = policies?.softDelete;\n if (!scopes && !softDelete) {\n return undefined;\n }\n return {\n has: (tableName, mode) => !!scopes?.(tableName) || (!!softDelete?.(tableName) && (mode ?? 'EXCLUDE') !== 'INCLUDE'),\n on: (tableName, table, mode) => {\n // Order is fixed: the soft-delete predicate first, the scope after it, both ANDed. They\n // commute, but a fixed order keeps the generated SQL stable between requests.\n const marked = softDelete?.(tableName);\n const deleted = marked ? softDeletePredicate(marked, table, mode ?? 'EXCLUDE') : undefined;\n const hook = scopes?.(tableName);\n if (!hook) {\n return deleted;\n }\n const predicate = hook(context, table);\n if (predicate === undefined || predicate === null) {\n return deleted;\n }\n if (is(predicate, SQL)) {\n return and(deleted, predicate as SQL);\n }\n if (typeof predicate !== 'object') {\n throw new GraphQLError(\n `Drizzle-GraphQL Error: the scope for '${tableName}' returned a ${typeof predicate}. A scope returns a filter object, a Drizzle SQL expression, or undefined.`,\n );\n }\n // A filter object is compiled the same way the field's own `where` is, against the\n // table it was handed — which is what keeps it correct under RQB aliasing.\n return and(deleted, extractFilters(table, tableName, predicate as any, relationFilterCtx(filterCtx, tableName)));\n },\n };\n};\n\n/**\n * `condition AND <the row policies of tableName>` — the single way a scope or a soft-delete\n * predicate is ever combined with a caller-supplied filter, so a `where` can only ever narrow\n * them, never widen them. `mode` is the read's `deleted` argument, and defaults to hiding\n * marked rows; a write passes nothing and so never touches one.\n */\nexport const withScope = (\n scope: ScopeResolver | undefined,\n tableName: string,\n table: Table,\n condition: SQL | undefined,\n mode?: DeletedMode,\n): SQL | undefined => {\n const predicate = scope?.on(tableName, table, mode);\n return predicate ? and(condition, predicate) : condition;\n};\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Context-derived column values\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Produces one column's value from the GraphQL context. See `BuildSchemaConfig.contextValues`. */\nexport type ContextValueHook<TContext = any> = (context: TContext) => any;\n\n/** Build-time lookup: the context-derived columns of a table, keyed by column property name. */\nexport type ContextValuesFor = (tableName: string) => Record<string, ContextValueHook> | undefined;\n\n/**\n * The two request-time policies a generated resolver applies, passed to the dialect\n * generators as one value so a table's read scope and its server-owned columns travel\n * together. Both stay `undefined` when nothing is configured, and every call site checks\n * before doing any work — an unconfigured build generates exactly the SQL it did before.\n */\nexport type TablePolicies = {\n /** See `BuildSchemaConfig.scope`. */\n scope?: ScopeFor;\n /** See `BuildSchemaConfig.contextValues`. */\n contextValues?: ContextValuesFor;\n /** See `BuildSchemaConfig.softDelete`. */\n softDelete?: SoftDeleteFor;\n /** See `BuildSchemaConfig.onWrite`. */\n onWrite?: WriteHookFor;\n /** See `BuildSchemaConfig.defaults`. */\n defaultOrderBy?: DefaultOrderByFor;\n};\n\n/**\n * {@link TablePolicies} with the scope already bound to the build's relation context, which\n * is what a dialect generator is handed: `scope(context)` is all a resolver needs to compile\n * a predicate, and it stays `undefined` when nothing is scoped.\n */\nexport type ResolverPolicies = {\n scope?: (context: any) => ScopeResolver | undefined;\n contextValues?: ContextValuesFor;\n softDelete?: SoftDeleteFor;\n onWrite?: WriteHookFor;\n defaultOrderBy?: DefaultOrderByFor;\n};\n\n/** Binds a build's {@link TablePolicies} to its relation context, once, at schema-build time. */\nexport const bindPolicies = (\n policies: TablePolicies | undefined,\n filterCtx: RelationFilterBase | undefined,\n): ResolverPolicies | undefined =>\n policies?.scope || policies?.contextValues || policies?.softDelete || policies?.onWrite || policies?.defaultOrderBy\n ? {\n scope:\n policies.scope || policies.softDelete\n ? (context: any) => resolveScope(policies, context, filterCtx)\n : undefined,\n contextValues: policies.contextValues,\n softDelete: policies.softDelete,\n onWrite: policies.onWrite,\n defaultOrderBy: policies.defaultOrderBy,\n }\n : undefined;\n\n/**\n * Merges a table's context-derived values into one row's insert values. The hooks run per\n * row — a value may depend on the row's own contents through the closure the caller built —\n * and they overwrite whatever was there: the columns are not in the create input, so nothing\n * legitimate can be lost, but a stitched-in input could still carry the key and the server's\n * value has to win.\n */\nexport const applyContextValues = (\n values: Record<string, any>,\n hooks: Record<string, ContextValueHook> | undefined,\n context: any,\n): Record<string, any> => {\n if (!hooks) {\n return values;\n }\n for (const [columnName, hook] of Object.entries(hooks)) {\n values[columnName] = hook(context);\n }\n return values;\n};\n\n/** {@link applyContextValues} over a batch — every row in an insert gets its own evaluation. */\nexport const applyContextValuesAll = (\n rows: Record<string, any>[],\n hooks: Record<string, ContextValueHook> | undefined,\n context: any,\n): Record<string, any>[] => {\n if (!hooks) {\n return rows;\n }\n for (const row of rows) {\n applyContextValues(row, hooks, context);\n }\n return rows;\n};\n\n/**\n * Drops context-derived columns from an update's `set`. They are not in the update input\n * either, so this only matters when the key arrives some other way — and reassigning one is\n * exactly the ownership transfer the feature exists to prevent.\n */\nexport const stripContextValues = (\n values: Record<string, any>,\n hooks: Record<string, ContextValueHook> | undefined,\n): Record<string, any> => {\n if (!hooks) {\n return values;\n }\n for (const columnName of Object.keys(hooks)) {\n delete values[columnName];\n }\n return values;\n};\n\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 scope?: ScopeResolver,\n defaultOrderBy?: DefaultOrderByFor,\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 // The eager path reads its arguments off the AST rather than through the relation field's\n // resolver, so the target's default ordering has to be substituted here too — otherwise\n // an eagerly loaded relation would come back in a different order from a lazily loaded one.\n const relationArgs: Partial<TableSelectArgs> | undefined = is(relEntry.relation, One)\n ? relationField?.args\n : relationField && withDefaultOrderBy(relationField.args ?? {}, targetTableName, defaultOrderBy);\n\n const offset = relationArgs?.offset ?? undefined;\n // The eager path reads its arguments off the AST rather than through the relation field's\n // resolver, so the policy has to be applied here too — otherwise an eagerly loaded\n // relation would be the one way around it. A to-one relation takes no `limit` and is a\n // single row by definition, so it is left alone.\n const limit = is(relEntry.relation, One)\n ? (relationArgs?.limit ?? undefined)\n : applyLimitPolicy(relationArgs?.limit, limits?.(targetTableName), `${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 const relDeleted = (relationArgs as any)?.deleted as DeletedMode | undefined;\n // The eager path is the one read that never passes through the relation field's own\n // resolver, so the target's scope has to be applied here as well — otherwise selecting a\n // relation would be the way around it.\n thisRecord.where =\n relWhere || scope?.has(targetTableName, relDeleted)\n ? {\n RAW: (aliasedTable: Table) =>\n withScope(\n scope,\n targetTableName,\n aliasedTable,\n relWhere\n ? extractFilters(aliasedTable, relName, relWhere, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n relDeleted,\n ),\n }\n : undefined;\n // When a relation is paginated (limit/offset) but unordered, default to the target's\n // primary key so the per-parent slice is deterministic. Drizzle's RQB calls orderBy\n // with the aliased table proxy, so resolve the PK columns from it. targetPkNames is\n // resolved at build time and includes composite keys.\n const hasPagination = offset != null || limit != null;\n const pkNames = targetPkNames ?? [];\n thisRecord.orderBy = relationArgs?.orderBy\n ? (aliasedTable: Table) =>\n extractOrderBy(aliasedTable, relationArgs.orderBy!, relationFilterCtx(filterCtx, targetTableName), relWhere)\n : hasPagination && pkNames.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined;\n thisRecord.offset = offset;\n thisRecord.limit = limit;\n\n const relWith = relationField\n ? extractRelationsParamsInner(\n relationMap,\n tables,\n targetTableName,\n relTypeName,\n relationField,\n typeNameMapper,\n false,\n filterCtx,\n limits,\n scope,\n defaultOrderBy,\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 scope?: ScopeResolver,\n defaultOrderBy?: DefaultOrderByFor,\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 scope,\n defaultOrderBy,\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 * Why the given `orderBy` cannot back a cursor, as the message to raise — or `undefined`\n * when it can. Both cases sort on something that is not a value of the row: a related row's\n * column, or a position in the request's own `inArray` list. `after` raises the message and\n * the `cursor` field resolves to null, while the ordering itself still applies.\n */\nexport const orderByCursorObstacle = (orderBy: Record<string, any> | undefined): string | undefined => {\n if (orderByHasRelationEntry(orderBy)) {\n return \"'after' cannot be combined with an orderBy that orders through a relation — a related row's value cannot be encoded into a cursor.\";\n }\n if (\n orderBy &&\n Object.values(orderBy).some((config) => config && typeof config === 'object' && config.matchFilterOrder)\n ) {\n return \"'after' cannot be combined with 'matchFilterOrder' — a row's position in the request's own filter list is not a value of the row, so it cannot be encoded into a cursor.\";\n }\n return undefined;\n};\n\n/**\n * The total order a list query's rows follow when cursor pagination is in play: the request's\n * `orderBy` entries (highest priority first), then the primary key ascending as a tiebreak —\n * skipping PK columns the `orderBy` already names, so no key appears twice.\n */\nexport const cursorOrderingEntries = (\n orderBy: Record<string, any> | undefined,\n pkNames: readonly string[],\n): CursorOrderEntry[] => {\n const entries: CursorOrderEntry[] = orderBy ? orderByEntries(orderBy) : [];\n const seen = new Set(entries.map(([column]) => column));\n for (const pk of pkNames) {\n if (!seen.has(pk)) {\n entries.push([pk, 'asc']);\n }\n }\n return entries;\n};\n\n/**\n * ORDER BY expressions realizing a cursor's total order on `table` (which may be the aliased\n * RQB proxy) — each key's direction plus its `nulls` override, exactly the order the keyset\n * predicate in {@link buildCursorCondition} compares against.\n */\nexport const cursorOrderExprs = (table: Table, entries: CursorOrderEntry[]): SQL[] => {\n const cols = getColumns(table);\n return entries.flatMap(([column, direction, nulls]) =>\n orderExpressions(cols[column]!, direction, nulls ?? undefined, cols[column]!),\n );\n};\n\n/**\n * Serializes one ordering-tuple value into a JSON-safe shape. Dates and bigints don't survive\n * JSON.stringify losslessly (bigint throws, Date turns into an untagged string), so they are\n * tagged; decimals already arrive from the driver as strings, which are lossless as-is.\n */\nconst encodeCursorValue = (value: any): any => {\n if (value instanceof Date) {\n return { $type: 'date', value: value.toISOString() };\n }\n if (typeof value === 'bigint') {\n return { $type: 'bigint', value: value.toString() };\n }\n return value;\n};\n\nconst decodeCursorValue = (value: any): any => {\n if (value && typeof value === 'object' && typeof value.$type === 'string') {\n if (value.$type === 'date') {\n return new Date(value.value);\n }\n if (value.$type === 'bigint') {\n return BigInt(value.value);\n }\n }\n return value;\n};\n\n/**\n * Encodes a row's position in the given total order as an opaque cursor: base64url of a JSON\n * payload holding the ordering spec (`o`) and the row's values for it (`v`). The spec rides\n * along so a later request can verify the cursor was issued for the same ordering it is using.\n */\nexport const encodeCursor = (entries: CursorOrderEntry[], row: Record<string, any>): string => {\n 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 = visibleColumns(table);\n const propNameByColumnName = new Map(Object.entries(cols).map(([propName, col]) => [(col as any).name, propName]));\n // A set is usable only if every one of its columns maps back to a property on the table.\n const toPropNames = (columnNames: (string | undefined)[]): string[] | undefined => {\n const propNames: string[] = [];\n for (const columnName of columnNames) {\n const propName = columnName === undefined ? undefined : propNameByColumnName.get(columnName);\n if (!propName) {\n return undefined;\n }\n propNames.push(propName);\n }\n return propNames.length ? propNames : undefined;\n };\n\n const config = getTableConfig(table);\n const candidates: (string[] | undefined)[] = [\n // Inline `.primaryKey()` columns, then table-level `primaryKey({ columns })`.\n Object.entries(cols)\n .filter(([, col]) => (col as any).primary)\n .map(([propName]) => propName),\n ...config.primaryKeys.map((pk) => toPropNames(pk.columns.map((c) => c.name))),\n ...(config.uniqueConstraints ?? []).map((uc) => toPropNames(uc.columns.map((c) => c.name))),\n ...(config.indexes ?? [])\n .filter((index) => index.config.unique)\n .map((index) => toPropNames(index.config.columns.map((c) => (c as any)?.name))),\n ...Object.entries(cols)\n .filter(([, col]) => (col as any).isUnique)\n .map(([propName]) => [propName]),\n ];\n\n const seen = new Set<string>();\n const sets: string[][] = [];\n for (const set of candidates) {\n if (!set?.length) {\n continue;\n }\n const key = [...set].sort().join(',');\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n sets.push(set);\n }\n return sets;\n};\n\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 name,\n * exclusions), like the order/filter inputs, so repeated builds reuse one instance and two\n * enums over the same table never collide.\n *\n * Returns `undefined` when no column qualifies — the caller then omits the argument or\n * input field the enum would have typed, rather than emitting an empty enum, which is\n * invalid GraphQL.\n */\nexport const generateColumnEnum = (\n table: Table,\n enumName: string,\n description: string,\n predicate: (column: Column, columnName: string) => boolean = () => true,\n): GraphQLEnumType | undefined => {\n // The exclusions are part of the key, not a reason to skip the cache: a table's enum is\n // asked for from more than one place in a build (a list query's `distinct` argument and the\n // same argument on a to-many relation field pointing at it), and handing those two call\n // sites separate instances would put two types of the same name in one schema.\n const cacheKey = `${enumName}\\u0000${excludedColumnsKey(table)}`;\n let tableCache = columnEnumCache.get(table);\n const cached = tableCache?.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const columnNames = Object.entries(visibleColumns(table))\n .filter(([columnName, column]) => predicate(column as Column, columnName))\n .map(([columnName]) => columnName);\n if (!columnNames.length) {\n return undefined;\n }\n\n const enumType = new GraphQLEnumType({\n name: enumName,\n description,\n values: Object.fromEntries(columnNames.map((columnName) => [columnName, { value: columnName }])),\n });\n\n if (!tableCache) {\n tableCache = new Map();\n columnEnumCache.set(table, tableCache);\n }\n tableCache.set(cacheKey, enumType);\n return enumType;\n};\n\n/** `${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 scope?: ScopeResolver;\n defaultOrderBy?: DefaultOrderByFor;\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 params.scope,\n params.defaultOrderBy,\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; restore?: 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 restoreFieldName: string;\n restoreSingleFieldName: 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 soft-delete counterpart, named the same way so `deleteUser` / `restoreUser` read as a\n // pair however the delete prefix and the single suffix are configured.\n const restoreFieldName = `${prefixes.restore ?? 'restore'}${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 const restoreSingleFieldName = `${restoreFieldName}${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 restoreFieldName,\n restoreSingleFieldName,\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. */\n/**\n * The `deleted` argument, emitted only on reads over a table that declares a soft-delete\n * column — a schema with no soft delete anywhere keeps exactly the arguments it had.\n */\nexport const deletedArg = (\n softDelete: SoftDeleteFor | undefined,\n tableName: string,\n): Record<string, { type: any; description: string }> =>\n softDelete?.(tableName)\n ? {\n deleted: {\n type: deletedFilterEnum,\n description: 'Whether rows marked deleted are returned. Defaults to EXCLUDE.',\n },\n }\n : {};\n\nexport const selectArrayArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n distinctEnum?: GraphQLEnumType,\n softDelete?: SoftDeleteFor,\n tableName?: string,\n): Record<string, { type: any; description?: string }> => ({\n offset: { type: GraphQLInt },\n limit: { type: GraphQLInt },\n orderBy: { type: orderArgs },\n where: { type: filterArgs },\n after: {\n type: GraphQLString,\n description:\n \"Keyset pagination: only return rows strictly after this cursor (a row's `cursor` field from a previous page, under the same orderBy).\",\n },\n ...(distinctEnum ? { distinct: { type: new GraphQLList(new GraphQLNonNull(distinctEnum)) } } : {}),\n ...deletedArg(softDelete, tableName!),\n});\n\n/** GraphQL argument map for a single-row select field (no `limit`). */\nexport const selectSingleArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n softDelete?: SoftDeleteFor,\n tableName?: string,\n): Record<string, { type: any }> => ({\n offset: { type: GraphQLInt },\n orderBy: { type: orderArgs },\n where: { type: filterArgs },\n ...deletedArg(softDelete, tableName!),\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 scope?: ScopeResolver;\n defaultOrderBy?: DefaultOrderByFor;\n deleted?: DeletedMode;\n}): Promise<any> => {\n const {\n queryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n offset,\n orderBy,\n where,\n single,\n filterCtx,\n pkNames,\n after,\n scope,\n deleted,\n } = opts;\n const distinct = opts.distinct?.length ? opts.distinct : undefined;\n\n // ── keyset (cursor) pagination ──\n // Active when the request passes `after` or selects the `cursor` meta field. The cursor is\n // defined over a total order — the request's orderBy plus the primary-key tiebreak — so both\n // need the PK; a table without one gets an error for `after` and null cursors otherwise.\n const cursorSelected = !single && isCursorFieldSelected(parsedInfo.fieldsByTypeName[typeName], table);\n let cursorEntries: CursorOrderEntry[] | undefined;\n if (!single && (after != null || cursorSelected)) {\n if (after != null && distinct) {\n throw new GraphQLError(\"'after' cannot be combined with 'distinct'.\");\n }\n const cursorObstacle = orderByCursorObstacle(orderBy);\n if (cursorObstacle) {\n if (after != null) {\n throw new GraphQLError(cursorObstacle);\n }\n // `cursor` was selected under an ordering a cursor cannot express — the field resolves\n // to null and the ordering itself still applies.\n } else if (!pkNames?.length) {\n if (after != null) {\n throw 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: withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n deleted,\n ),\n orderBy,\n limit: single ? 1 : opts.limit,\n offset,\n });\n\n if (!distinctKeys.length) {\n return single ? undefined : [];\n }\n }\n\n const params: any = {\n columns: extractSelectedColumnsFromTree(parsedInfo.fieldsByTypeName[typeName]!, table, {\n tableName,\n relationMap,\n tables,\n allRelations: filterCtx?.relationMap,\n }),\n offset: distinctKeys ? undefined : offset,\n // drizzle-orm v1 RQB calls orderBy/where with the aliased table proxy — use it\n // directly so column refs match the CTE alias.\n orderBy: distinctKeys\n ? (aliasedTable: Table) => [\n ...(orderBy ? extractOrderBy(aliasedTable, orderBy, relationFilterCtx(filterCtx, tableName), where) : []),\n ...primaryKeyOrderExprs(aliasedTable, pkNames!),\n ]\n : cursorEntries\n ? // Cursor pagination needs a total order: the request's orderBy plus the PK tiebreak,\n // exactly the ordering the cursor encodes and the keyset predicate compares against.\n (aliasedTable: Table) => cursorOrderExprs(aliasedTable, cursorEntries!)\n : orderBy\n ? (aliasedTable: Table) =>\n extractOrderBy(aliasedTable, orderBy, relationFilterCtx(filterCtx, tableName), where)\n : needsDefaultOrder && pkNames?.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined,\n where: distinctKeys\n ? // The distinct pass already ran inside the scope, so the keys it picked are in it.\n { RAW: (aliasedTable: Table) => primaryKeyRestriction(aliasedTable, pkNames!, distinctKeys!) }\n : where || cursorValues || scope?.has(tableName, deleted)\n ? {\n RAW: (aliasedTable: Table) =>\n withScope(\n scope,\n tableName,\n aliasedTable,\n and(\n where\n ? extractFilters(aliasedTable, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n cursorValues\n ? buildCursorCondition(\n aliasedTable,\n cursorEntries!,\n cursorValues,\n opts.nullOrdering ?? 'nulls-smallest',\n )\n : undefined,\n ),\n deleted,\n ),\n }\n : undefined,\n with: relationMap[tableName]\n ? extractRelationsParams(\n relationMap,\n tables,\n tableName,\n parsedInfo,\n typeName,\n typeNameMapper,\n filterCtx,\n opts.limits,\n scope,\n opts.defaultOrderBy,\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\n/**\n * The `typeNameMapper` preset behind `typeNameMapper: 'singularize'`.\n *\n * Derives the singular and plural forms of a table key with the library's own `pluralize`,\n * which is what nearly every consumer with plural table keys (`export const tasks =\n * pgTable('tasks', …)`) was writing by hand — and adding `pluralize` to their own\n * dependencies to write.\n *\n * `tasks` becomes type `Task`, queries `tasks` / `task`, mutations `createTasks` /\n * `createTask`. A key that is already singular is pluralized for the list side, so `task`\n * yields the same names, and a capitalized key (`Tasks`) yields them too — the field forms\n * are uncapitalized so the generated names follow GraphQL's camelCase convention whatever\n * the schema key looks like. The type name is capitalized by the generator either way.\n */\nexport const singularizeMapper = (tableName: string): { singular: string; plural: string } => ({\n singular: uncapitalize(pluralize.singular(tableName)),\n plural: uncapitalize(pluralize.plural(tableName)),\n});\n","// @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","/**\n * The identity a generated field publishes about itself, under `extensions.drizzle`.\n *\n * Every field this library generates carries one, so a wrapper — `graphql-middleware`,\n * envelop, `graphql-shield`, an audit log, a cache invalidator — can ask the schema what a\n * field is instead of reverse-engineering its name. Names are configurable (`prefixes`,\n * `suffixes`, `typeNameMapper`), so name parsing is ambiguous by construction; this is not.\n *\n * This shape is stable API: fields are only ever added to it, never removed or repurposed.\n */\n\n/** What family of field this is. */\nexport type DrizzleFieldKind = 'query' | 'mutation' | 'relation' | 'aggregate' | 'type';\n\n/**\n * What the field does. Arity is carried separately by `single`, so `select` covers both\n * the list query and its `…Single` sibling rather than being spelled twice.\n */\nexport type DrizzleFieldOperation =\n | 'select'\n | 'insert'\n | 'update'\n | 'updateMany'\n | 'upsert'\n | 'delete'\n | 'restore'\n | 'aggregate'\n | 'groupBy'\n | 'relation'\n | 'relationAggregate';\n\n/** The argument holding the rows a field is about, when it has one. */\nexport type DrizzleTargetArg = 'where' | 'values' | 'updates';\n\n/** `extensions.drizzle` on a generated field. */\nexport type DrizzleFieldExtension = {\n /** The Drizzle schema key of the table the field reads or writes. */\n table: string;\n kind: Exclude<DrizzleFieldKind, 'type'>;\n operation: DrizzleFieldOperation;\n /** Whether the field resolves to one row (or one aggregate) rather than a list. */\n single: boolean;\n /**\n * Which argument names the rows: `where` for select/update/delete/aggregate, `values`\n * for insert and upsert, `updates` for the batch update's per-entry `{ where, set }`.\n * Absent when the field takes no such argument.\n */\n targetArg?: DrizzleTargetArg;\n /**\n * Primary-key property names of `table`, in schema order. Empty when the table declares\n * no primary key. Carried here so {@link identifyRows} works from the field alone.\n */\n primaryKey: readonly string[];\n /** For `kind: 'relation'` and `operation: 'relationAggregate'`: the relation's name. */\n relation?: string;\n /** For `kind: 'relation'` and `operation: 'relationAggregate'`: the table it hangs off. */\n parentTable?: string;\n};\n\n/** `extensions.drizzle` on a generated object type. */\nexport type DrizzleTypeExtension = {\n /** The Drizzle schema key this type was generated from. */\n table: string;\n kind: 'type';\n /** Primary-key property names of `table`, in schema order. Empty when there is none. */\n primaryKey: readonly string[];\n};\n\nexport type DrizzleExtension = DrizzleFieldExtension | DrizzleTypeExtension;\n\n/** Anything carrying GraphQL `extensions` — a field config, a field, or a named type. */\ntype WithExtensions = { extensions?: { drizzle?: unknown } | null } | null | undefined;\n\n/**\n * Reads the `drizzle` extension off a field or type, typed. Returns `undefined` for\n * anything this library did not generate, which is the check a wrapper wants before it\n * treats a field as one of ours.\n */\nexport const drizzleExtension = (target: WithExtensions): DrizzleExtension | undefined => {\n const value = target?.extensions?.drizzle;\n return value && typeof value === 'object' ? (value as DrizzleExtension) : undefined;\n};\n\n/** Narrows to the field form — object types carry `kind: 'type'` and no operation. */\nexport const isDrizzleFieldExtension = (value: DrizzleExtension | undefined): value is DrizzleFieldExtension =>\n !!value && value.kind !== 'type';\n\n/**\n * Builds the extension for one table's fields. Dialect builders make one per table so each\n * call site only states what differs.\n */\nexport const tableFieldExtensions =\n (table: string, primaryKey: readonly string[]) =>\n (meta: Omit<DrizzleFieldExtension, 'table' | 'primaryKey'>): DrizzleFieldExtension => ({\n table,\n primaryKey,\n ...meta,\n });\n\n/**\n * The parts of a mutation's identity that differ between mutations. Dialect builders that\n * assign every mutation in one loop pair each generated mutation with one of these.\n */\nexport type DrizzleMutationMeta = Pick<DrizzleFieldExtension, 'operation' | 'single' | 'targetArg'>;\n\n/** Builds the extension a generated object type carries. */\nexport const tableTypeExtension = (table: string, primaryKey: readonly string[]): DrizzleTypeExtension => ({\n table,\n kind: 'type',\n primaryKey,\n});\n\n/**\n * Builds the extension a relation field carries. `table` is the relation's *target* — the\n * table the field resolves rows of — while `parentTable` is the type the field hangs off,\n * so a wrapper can tell `Users.posts` from `Customers.posts`.\n */\nexport const relationFieldExtension = (params: {\n targetTable: string;\n parentTable: string;\n relation: string;\n single: boolean;\n primaryKey: readonly string[];\n aggregate?: boolean;\n}): DrizzleFieldExtension => ({\n table: params.targetTable,\n kind: params.aggregate ? 'aggregate' : 'relation',\n operation: params.aggregate ? 'relationAggregate' : 'relation',\n // An aggregate over a to-many relation still resolves to a single aggregate object.\n single: params.aggregate ? true : params.single,\n targetArg: 'where',\n primaryKey: params.primaryKey,\n relation: params.relation,\n parentTable: params.parentTable,\n});\n\n/** The rows a field's arguments name. */\nexport type IdentifiedRows = {\n /** The Drizzle schema key of the table being read or written. */\n table: string;\n /** Primary-key property names, in schema order. */\n primaryKey: readonly string[];\n /** One entry per identified row: the primary-key values, keyed by property name. */\n rows: Record<string, unknown>[];\n /**\n * Whether `rows` is exactly the set the operation affects.\n *\n * `false` means the arguments do not pin the rows down — an insert whose key the\n * database generates, a `where` that filters on something other than the primary key,\n * a plural update with no filter at all, or a table with no primary key. `rows` is then\n * a best-effort subset-free superset: every entry in it is a row the key values name,\n * but other filters may narrow the real set further, and it may be empty.\n */\n complete: boolean;\n};\n\n/** Pulls the primary-key values out of one `values` entry; `undefined` if any are missing. */\nconst keyFromValues = (entry: unknown, primaryKey: readonly string[]): Record<string, unknown> | undefined => {\n if (!entry || typeof entry !== 'object') {\n return undefined;\n }\n const row: Record<string, unknown> = {};\n for (const column of primaryKey) {\n const value = (entry as Record<string, unknown>)[column];\n if (value === undefined || value === null) {\n return undefined;\n }\n row[column] = value;\n }\n return row;\n};\n\n/**\n * Pulls primary-key values out of a filter argument.\n *\n * Only top-level equality counts: `{ id: { eq } }` names one row, `{ id: { inArray } }`\n * names a list, and a composite key needs `eq` on every one of its columns. A boolean\n * group (`OR` / `AND` / `NOT`) or any other operator on a key column means the filter is\n * not a key lookup, and the rows are reported as not identified.\n */\nconst keysFromWhere = (\n where: unknown,\n primaryKey: readonly string[],\n): { rows: Record<string, unknown>[]; complete: boolean } => {\n const none = { rows: [], complete: false };\n if (!where || typeof where !== 'object' || Array.isArray(where)) {\n return none;\n }\n const filters = where as { OR?: unknown; AND?: unknown; NOT?: unknown; [column: string]: any };\n if (filters.OR || filters.AND || filters.NOT) {\n return none;\n }\n\n // A composite key is only pinned by an equality on each of its columns — one column\n // carrying a list would describe a rectangle of key tuples, not the rows written.\n if (primaryKey.length > 1) {\n const row: Record<string, unknown> = {};\n for (const column of primaryKey) {\n const operators = filters[column];\n if (!operators || typeof operators !== 'object' || operators.eq === undefined) {\n return none;\n }\n row[column] = operators.eq;\n }\n // Filters beyond the key can only narrow further, so the key alone is not the answer.\n return { rows: [row], complete: Object.keys(filters).length === primaryKey.length };\n }\n\n const column = primaryKey[0];\n if (!column) {\n return none;\n }\n const operators = filters[column];\n if (!operators || typeof operators !== 'object') {\n return none;\n }\n\n const exact = Object.keys(filters).length === 1 && Object.keys(operators).length === 1;\n if (operators.eq !== undefined) {\n return { rows: [{ [column]: operators.eq }], complete: exact };\n }\n if (Array.isArray(operators.inArray)) {\n return { rows: operators.inArray.map((value: unknown) => ({ [column]: value })), complete: exact };\n }\n return none;\n};\n\n/**\n * The rows a generated field's arguments are about, as primary-key values.\n *\n * The row identity of a mutation lives in a different argument for every operation —\n * `where` for update and delete, `values` for insert and upsert, a per-entry `where` inside\n * `updates` for the batch update — and each of those has both a one-row and a many-row\n * spelling. This reads whichever one applies:\n *\n * ```ts\n * const field = info.parentType.getFields()[info.fieldName];\n * const target = identifyRows(field, args);\n * if (target?.complete) await invalidate(target.table, target.rows);\n * ```\n *\n * Returns `undefined` for a field this library did not generate, or an object type. Check\n * `complete` before treating `rows` as the affected set — see {@link IdentifiedRows}.\n */\nexport const identifyRows = (\n field: WithExtensions,\n args: Record<string, unknown> | undefined,\n): IdentifiedRows | undefined => {\n const meta = drizzleExtension(field);\n if (!isDrizzleFieldExtension(meta)) {\n return undefined;\n }\n\n const { table, primaryKey, targetArg } = meta;\n const empty: IdentifiedRows = { table, primaryKey, rows: [], complete: false };\n if (!primaryKey.length || !targetArg) {\n return empty;\n }\n\n const target = args?.[targetArg];\n\n if (targetArg === 'values') {\n // Both spellings of insert/upsert land here: the single variant takes one object.\n const entries = Array.isArray(target) ? target : target === undefined ? [] : [target];\n const rows = entries.map((entry) => keyFromValues(entry, primaryKey));\n return {\n table,\n primaryKey,\n rows: rows.filter((row): row is Record<string, unknown> => !!row),\n // A row whose key the database generates is not identifiable before the write.\n complete: entries.length > 0 && rows.every(Boolean),\n };\n }\n\n if (targetArg === 'updates') {\n if (!Array.isArray(target)) {\n return empty;\n }\n const perEntry = target.map((entry) =>\n keysFromWhere((entry as { where?: unknown } | undefined)?.where, primaryKey),\n );\n return {\n table,\n primaryKey,\n rows: perEntry.flatMap((entry) => entry.rows),\n complete: target.length > 0 && perEntry.every((entry) => entry.complete),\n };\n }\n\n return { table, primaryKey, ...keysFromWhere(target, primaryKey) };\n};\n","// @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 applyContextValues,\n applyContextValuesAll,\n applyLimitPolicy,\n assertSingleMatch,\n attachTargetPrimaryKeys,\n bindPolicies,\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 type ResolverPolicies,\n registerColumnExclusions,\n relationFilterCtx,\n resolveConflictPlan,\n resolveQueryExecutor,\n runMutation,\n runRelationalSelect,\n runWriteHook,\n selectArrayArgs,\n selectSingleArgs,\n stripContextValues,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n type WriteOperation,\n withDefaultOrderBy,\n withScope,\n} from '../builders/common.ts';\nimport { remapFromGraphQLArrayInput, remapFromGraphQLSingleInput } from '../data-mappers/index.ts';\nimport { type DrizzleMutationMeta, tableFieldExtensions } from '../extensions.ts';\nimport { resolveTableFeatures } from '../features.ts';\nimport { registerEnumConfig, registerScalarOverrides } from '../type-converter/index.ts';\nimport {\n createRelationAggregateFactory,\n generateAggregate,\n generateAggregateTypes,\n generateGroupBy,\n generateGroupByEnum,\n generateGroupByType,\n generateHavingInput,\n} from './aggregates.ts';\nimport { remapUpdateInput } from './field-updates.ts';\nimport type {\n CreatedResolver,\n Filters,\n SchemaGeneratorOptions,\n TableFeatures,\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 policies?: ResolverPolicies,\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 policies?.softDelete,\n tableName,\n );\n\n return {\n name: fieldName,\n resolver: async (_source, rawArgs: Partial<TableSelectArgs>, context, info) => {\n // An omitted `orderBy` falls back to the table's configured default ordering here,\n // before anything reads the arguments — the cursor tuple, a `distinct` pass and the\n // plain-select fallback all have to agree on one effective ordering.\n const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n limit: applyLimitPolicy(args.limit, limitPolicy, fieldName),\n single: false,\n filterCtx,\n limits,\n defaultOrderBy: policies?.defaultOrderBy,\n scope: policies?.scope?.(context),\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 policies?: ResolverPolicies,\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, policies?.softDelete, tableName);\n\n const table = tables[tableName]!;\n const pkNames = mysqlPrimaryKeyPropNames(table as MySqlTable);\n\n return {\n name: fieldName,\n resolver: async (_source, rawArgs: Partial<TableSelectArgs>, context, info) => {\n // An omitted `orderBy` falls back to the table's configured default ordering here,\n // before anything reads the arguments — the cursor tuple, a `distinct` pass and the\n // plain-select fallback all have to agree on one effective ordering.\n const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n limits,\n defaultOrderBy: policies?.defaultOrderBy,\n scope: policies?.scope?.(context),\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 policies?: ResolverPolicies,\n): CreatedResolver => {\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(baseType))),\n },\n };\n\n const hooks = policies?.onWrite?.(tableName, 'insert');\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any>[] }, context, info) => {\n try {\n return await runMutation(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n const input = applyContextValuesAll(\n remapFromGraphQLArrayInput(args.values, table),\n policies?.contextValues?.(tableName),\n context,\n );\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'insert',\n single: false,\n args,\n context,\n info,\n tx: executor,\n });\n\n await executor.insert(table).values(input);\n\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'insert',\n single: false,\n args,\n rows: [],\n context,\n info,\n tx: executor,\n });\n\n return { isSuccess: true };\n },\n !!hooks,\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 policies?: ResolverPolicies,\n): CreatedResolver => {\n const queryArgs: GraphQLFieldConfigArgumentMap = {\n values: {\n type: new GraphQLNonNull(baseType),\n },\n };\n\n const hooks = policies?.onWrite?.(tableName, 'insert');\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any> }, context, info) => {\n try {\n return await runMutation(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'insert',\n single: true,\n args,\n context,\n info,\n tx: executor,\n });\n const input = applyContextValues(\n remapFromGraphQLSingleInput(args.values, table),\n policies?.contextValues?.(tableName),\n context,\n );\n\n await executor.insert(table).values(input);\n\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'insert',\n single: true,\n args,\n rows: [],\n context,\n info,\n tx: executor,\n });\n\n return { isSuccess: true };\n },\n !!hooks,\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 tableName: string,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n onConflictType: GraphQLInputObjectType,\n fieldName: string,\n single: boolean,\n txCtx?: MutationTxCtx,\n policies?: ResolverPolicies,\n): CreatedResolver => {\n const 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 const hooks = policies?.onWrite?.(tableName, 'upsert');\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(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n const input = applyContextValuesAll(\n single\n ? [remapFromGraphQLSingleInput(args.values as Record<string, any>, table)]\n : remapFromGraphQLArrayInput(args.values as Record<string, any>[], table),\n policies?.contextValues?.(tableName),\n context,\n );\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'upsert',\n single,\n args,\n context,\n info,\n tx: executor,\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 await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'upsert',\n single,\n args,\n rows: [],\n context,\n info,\n tx: executor,\n });\n\n return { isSuccess: true };\n },\n !!hooks,\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 policies?: ResolverPolicies,\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 const hooks = policies?.onWrite?.(tableName, 'update');\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(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n const { where, set } = args;\n const scope = policies?.scope?.(context);\n\n // A context-derived column is the server's to set, so an update never reassigns\n // one — that is what stops a row being handed to another owner.\n const input = stripContextValues(\n remapUpdateInput(set, table, tableName),\n policies?.contextValues?.(tableName),\n );\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'update',\n single,\n args,\n context,\n info,\n tx: executor,\n });\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // The scope is ANDed on last, so a caller-supplied `where` can only narrow it.\n const filters = withScope(\n scope,\n tableName,\n table,\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined,\n );\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 await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'update',\n single,\n args,\n rows: [],\n context,\n info,\n tx: executor,\n });\n\n return { isSuccess: true };\n },\n !!hooks,\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 policies?: ResolverPolicies,\n): CreatedResolver => {\n const queryArgs = {\n updates: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(updateManyInput))),\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n const hooks = policies?.onWrite?.(tableName, 'updateMany');\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(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n const { updates } = args;\n if (!updates.length) {\n throw new GraphQLError('No updates were provided!');\n }\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'updateMany',\n single: false,\n args,\n context,\n info,\n tx: executor,\n });\n const scope = policies?.scope?.(context);\n const contextColumns = policies?.contextValues?.(tableName);\n\n // Remap and validate every entry before the transaction opens, so a malformed\n // entry rejects the request instead of rolling back mid-batch.\n const entries = updates.map(({ where, set }) => {\n const input = stripContextValues(remapUpdateInput(set, table, tableName), contextColumns);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n filters: withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n ),\n };\n });\n\n // On a caller-supplied transaction — or the shared multi-mutation transaction\n // opened by `runMutation` — this opens a savepoint, so the batch stays atomic\n // without breaking the outer transaction.\n await executor.transaction(async (tx: any) => {\n for (const entry of entries) {\n let query = tx.update(table).set(entry.set);\n if (entry.filters) {\n query = query.where(entry.filters) as any;\n }\n await query;\n }\n });\n\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'updateMany',\n single: false,\n args,\n rows: [],\n context,\n info,\n tx: executor,\n });\n\n return { isSuccess: true };\n },\n !!hooks,\n );\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\n/**\n * `delete<Table>` and, for a table that declares a soft-delete column, `restore<Table>`.\n * MySQL's writes return no rows either way, so both answer `{ isSuccess: true }` — the\n * difference from the other dialects is only what the payload can say, not what runs.\n */\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 policies?: ResolverPolicies,\n restore: boolean = false,\n): CreatedResolver => {\n const softDelete = policies?.softDelete?.(tableName);\n const operation: WriteOperation = restore ? 'restore' : 'delete';\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n const hooks = policies?.onWrite?.(tableName, operation);\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, info) => {\n try {\n return await runMutation(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation,\n single,\n args,\n context,\n info,\n tx: executor,\n });\n const { where } = args;\n const scope = policies?.scope?.(context);\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // Same rule as update: the scope is ANDed on last, so a delete can only ever reach\n // rows inside it — an out-of-scope row is not matched rather than being refused.\n // A soft-deleting table adds the marker predicate the same way: `delete` only sees\n // rows that are not already marked, `restore` only sees the ones that are.\n const filters = withScope(\n scope,\n tableName,\n table,\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined,\n restore ? 'ONLY' : undefined,\n );\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = softDelete\n ? executor\n .update(table)\n .set({ [softDelete.columnName]: restore ? softDelete.writeRestored : softDelete.writeDeleted() })\n : executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n await query;\n\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation,\n single,\n args,\n rows: [],\n context,\n info,\n tx: executor,\n });\n\n return { isSuccess: true };\n },\n !!hooks,\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 // Excluded tables are dropped here, before anything reads `tableEntries` — which also makes\n // `buildNamedRelations` skip every relation pointing at one, since it resolves targets\n // through this list.\n const excludedTables = new Set(options.exclude?.tables ?? []);\n const tableEntries = schemaEntries.filter(([key, value]) => is(value, MySqlTable) && !excludedTables.has(key)) as [\n string,\n MySqlTable,\n ][];\n const tables = Object.fromEntries(tableEntries);\n\n // A feature flag may be a per-table predicate, so every flag is resolved against the table\n // it applies to. `anyTable` answers the build-wide question — whether machinery shared\n // across tables is worth constructing at all.\n const featureOf = resolveTableFeatures(features);\n const anyTable = (feature: keyof TableFeatures) => tableEntries.some(([name]) => featureOf(name)[feature]);\n\n if (!tableEntries.length) {\n throw new Error(\n \"Drizzle-GraphQL Error: No tables detected in Drizzle-ORM's database instance. Did you forget to pass schema to drizzle constructor?\",\n );\n }\n\n // 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 // And the same for column exclusions: a per-build registry read by every site that decides\n // what the schema contains, reset here so a rebuild never inherits the previous build's.\n registerColumnExclusions(tables, options.exclude);\n\n // Build namedRelations from the drizzle-orm v1 relations config.\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Relations *into* an excluded table are already gone (their target no longer resolves);\n // relations *out of* one have no type left to hang a field on.\n for (const excluded of excludedTables) {\n delete namedRelations[excluded];\n }\n // Record each relation target's (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 // The row scope compiled against this build's relation graph, plus the columns whose value\n // the server supplies. Both stay undefined unless configured.\n const tablePolicies = options.policies;\n const contextValuesOf = tablePolicies?.contextValues;\n const softDeleteOf = tablePolicies?.softDelete;\n const policies = bindPolicies(tablePolicies, filterCtx);\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(\n db,\n tables,\n 'nulls-smallest',\n filterCtx,\n limits,\n tablePolicies,\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 primaryKeyOf: (name) => (tables[name] ? mysqlPrimaryKeyPropNames(tables[name] as MySqlTable) : []),\n contextValuesOf,\n softDeleteOf,\n featureOf,\n };\n\n // Built when at least one table wants relation aggregates; a table that has them off is\n // handed `undefined` below, so `generateTableTypes` emits no `${relation}Aggregate` fields\n // on its object type.\n const relationAggregateFactory: RelationAggregateFactory | undefined = anyTable('relationAggregates')\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx, tablePolicies)\n : undefined;\n\n const 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 featureOf(tableName).relationAggregates ? relationAggregateFactory : undefined,\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 ((['insert', 'upsert', 'update', 'delete'] as const).some((feature) => anyTable(feature))) {\n outputs.MutationReturn = mutationReturnType;\n }\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n // Everything this table generates, with any per-table predicate already run.\n const tableFeatures = featureOf(tableName);\n // What every field this table generates publishes about itself under `extensions.drizzle`,\n // so a wrapper can read a field's identity instead of parsing its configurable name.\n const drizzleMeta = tableFieldExtensions(tableName, mysqlPrimaryKeyPropNames(schema[tableName] as MySqlTable));\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 restoreFieldName,\n restoreSingleFieldName,\n deleteCountFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\n // A table that marks rows deleted instead of removing them also gets the mutation that\n // reverses it — clearing the column through an ordinary update is not possible, since the\n // column is not in the update input and a marked row is invisible to a `where` anyway.\n const softDeleteInfo = softDeleteOf?.(tableName);\n\n const selectArrGenerated = generateSelectArray(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n listFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n tableFeatures.distinct,\n limits,\n policies,\n );\n const selectSingleGenerated = generateSelectSingle(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n singleFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n limits,\n policies,\n );\n const insertArrGenerated = tableFeatures.insert\n ? generateInsertArray(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n createArrayFieldName,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const insertSingleGenerated = tableFeatures.insert\n ? generateInsertSingle(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n createSingleFieldName,\n mutationTxCtx,\n policies,\n )\n : undefined;\n // MySQL detects a conflict on any unique key, so unlike PostgreSQL and SQLite every\n // table can be upserted — there is no target to validate.\n const onConflictInput = tableFeatures.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as MySqlTable,\n typeName,\n uniqueSets: [],\n tableFilters,\n withTarget: false,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n onConflictInput,\n upsertArrayFieldName,\n false,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const upsertSingleGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n insertInput,\n onConflictInput,\n upsertSingleFieldName,\n true,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const updateGenerated = tableFeatures.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateFieldName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const updateSingleGenerated = tableFeatures.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n tableFeatures.update && tableFeatures.updateMany\n ? generateUpdateManyInput({ 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 policies,\n )\n : undefined;\n const deleteGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteFieldName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const deleteSingleGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteSingleFieldName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n )\n : undefined;\n const restoreGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n restoreFieldName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n const restoreSingleGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n restoreSingleFieldName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n // The count variants are the plural write with its payload left off, so each follows the\n // same feature switch as the write it mirrors.\n const updateCountGenerated =\n tableFeatures.update && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as MySqlTable,\n kind: 'update',\n setArgs: updateInput,\n filterArgs: tableFilters,\n fieldName: updateCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n })\n : undefined;\n const deleteCountGenerated =\n tableFeatures.delete && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as MySqlTable,\n kind: 'delete',\n filterArgs: tableFilters,\n fieldName: deleteCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n })\n : undefined;\n const aggregateType = tableFeatures.aggregates\n ? generateAggregateTypes(schema[tableName] as MySqlTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = tableFeatures.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n tablePolicies,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n tableFeatures.aggregates && tableFeatures.groupBy\n ? generateGroupByType(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 tablePolicies,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: listFieldComplexity(complexity, limits?.(tableName)) } : {}),\n },\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: true, targetArg: 'where' }),\n },\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'aggregate', single: true, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'groupBy', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n };\n }\n // Each mutation is paired with the identity it publishes on `extensions.drizzle`, so a\n // consumer can tell an insert from an upsert without unpicking the configured prefixes.\n const generatedMutations: [typeof insertArrGenerated, DrizzleMutationMeta][] = [\n [insertArrGenerated, { operation: 'insert', single: false, targetArg: 'values' }],\n [insertSingleGenerated, { operation: 'insert', single: true, targetArg: 'values' }],\n [upsertArrGenerated, { operation: 'upsert', single: false, targetArg: 'values' }],\n [upsertSingleGenerated, { operation: 'upsert', single: true, targetArg: 'values' }],\n [updateGenerated, { operation: 'update', single: false, targetArg: 'where' }],\n [updateManyGenerated, { operation: 'updateMany', single: false, targetArg: 'updates' }],\n [updateSingleGenerated, { operation: 'update', single: true, targetArg: 'where' }],\n [deleteGenerated, { operation: 'delete', single: false, targetArg: 'where' }],\n [deleteSingleGenerated, { operation: 'delete', single: true, targetArg: 'where' }],\n [restoreGenerated, { operation: 'restore', single: false, targetArg: 'where' }],\n [restoreSingleGenerated, { operation: 'restore', single: true, targetArg: 'where' }],\n ];\n for (const [generated, meta] of generatedMutations) {\n if (generated) {\n mutations[generated.name] = {\n type: mutationReturnType,\n args: generated.args,\n resolve: generated.resolver,\n extensions: { drizzle: drizzleMeta({ kind: 'mutation', ...meta }) },\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 ...(tableFeatures.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(tableFeatures.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","import type { SchemaFeatures } from '../types.ts';\nimport type { TableFeatures } from './builders/types.ts';\n\n/**\n * What a table generates when the config says nothing. Everything is on except the opt-in\n * features, so a build with no `features` block generates what it always did.\n */\nexport const featureDefaults: TableFeatures = {\n aggregates: true,\n groupBy: true,\n relationAggregates: true,\n distinct: true,\n insert: true,\n update: true,\n updateMany: true,\n delete: true,\n upsert: false,\n fieldUpdateOperations: false,\n countMutations: false,\n requireWhere: false,\n};\n\n/**\n * Turns `BuildSchemaConfig.features` — booleans, per-table predicates, or nothing at all —\n * into a lookup the generators can ask about one table. Memoized, so a predicate is run once\n * per table however many places consult it.\n */\nexport const resolveTableFeatures = (features: SchemaFeatures | undefined): ((tableName: string) => TableFeatures) => {\n const cache = new Map<string, TableFeatures>();\n const names = Object.keys(featureDefaults) as (keyof TableFeatures)[];\n return (tableName: string): TableFeatures => {\n let resolved = cache.get(tableName);\n if (!resolved) {\n resolved = {} as TableFeatures;\n for (const name of names) {\n const configured = features?.[name];\n // A predicate answering with something other than a boolean is answering \"yes\" for\n // anything truthy, matching how the flags read everywhere else.\n resolved[name] =\n configured === undefined\n ? featureDefaults[name]\n : typeof configured === 'function'\n ? !!configured(tableName)\n : !!configured;\n }\n cache.set(tableName, resolved);\n }\n return resolved;\n };\n};\n","// @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 type DeletedMode,\n deletedArg,\n extractFilters,\n extractRelationJoinColumns,\n generateColumnEnum,\n type RelationAggregateFactory,\n type RelationFilterBase,\n relationFilterCtx,\n resolveExecutor,\n resolveScope,\n resolveTypeName,\n type TablePolicies,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n visibleColumns,\n withScope,\n} from './common.ts';\nimport type { CreatedResolver, Filters } from './types.ts';\n\n/** Operations that aggregate over a set of column values. `count` is handled separately (whole rows). */\nconst AGGREGATE_OPS = ['avg', 'sum', 'min', 'max', 'countNonNull', 'countDistinct'] as const;\ntype AggregateOp = (typeof AGGREGATE_OPS)[number];\n\n/** Ops whose result is a row count: never null, and returned as `Int!` rather than the column's type. */\nconst COUNT_OPS = new Set<AggregateOp>(['countNonNull', 'countDistinct']);\n\nconst OP_FNS: Record<AggregateOp, (col: Column) => any> = {\n avg,\n sum,\n min,\n max,\n countNonNull: count,\n countDistinct,\n};\n\n/** Separator for flat select aliases (`avg__price`) — reassembled into nested output by the resolver. */\nconst SEP = '__';\n\ninterface AggregateColumnSets {\n /** Columns avg/sum apply to: plain Int/Float scalars. */\n numeric: Record<string, Column>;\n /** Columns min/max apply to: anything with a total ordering the DB supports (numbers, strings, dates, enums). */\n orderable: Record<string, { column: Column; converted: ConvertedColumn }>;\n /** Every column — `count(col)` is valid whatever the type. */\n all: Record<string, Column>;\n}\n\n/**\n * Classifies a table's columns for aggregation. avg/sum only make sense on numeric scalars;\n * min/max work on any orderable scalar (numbers, strings, bigints, dates, enums). Booleans,\n * arrays (including array-typed number columns), JSON, buffers, and object-shaped columns\n * (e.g. geometry) are excluded entirely.\n */\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(visibleColumns(table))) {\n all[columnName] = column;\n const converted = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, false);\n const gqlType = converted.type;\n\n // Anything that isn't a plain scalar in the generated schema (arrays, geometry objects)\n // has no meaningful min/max. This also catches array-typed number columns, which keep\n // their scalar drizzle dataType but convert to a GraphQL list.\n if (gqlType instanceof GraphQLList || gqlType instanceof GraphQLObjectType) {\n continue;\n }\n\n // Classify on the drizzle data type rather than the GraphQL one: date columns convert to\n // different GraphQL scalars per dialect, but are orderable everywhere.\n const { type: dataType, constraint } = extractExtendedColumnType(column);\n if (dataType === 'boolean' || dataType === 'array' || dataType === 'custom') {\n continue;\n }\n if (dataType === 'object' && constraint !== 'date') {\n continue;\n }\n\n orderable[columnName] = { column, converted };\n if (dataType === 'number') {\n numeric[columnName] = column;\n }\n }\n\n 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 policies?: TablePolicies,\n): CreatedResolver => {\n const target = aggregateTarget(table, tableName, typeName);\n\n const queryArgs = {\n where: { type: filterArgs },\n ...deletedArg(policies?.softDelete, tableName),\n };\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table>; deleted?: DeletedMode }, context, info) => {\n try {\n const request = parseAggregateRequest(info, target);\n if (!Object.keys(request.selection).length) {\n return {};\n }\n\n let query = resolveExecutor(db, context).select(request.selection).from(table);\n const where = withScope(\n resolveScope(policies, context, filterCtx),\n tableName,\n table,\n args.where\n ? extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n args.deleted,\n );\n if (where) {\n query = query.where(where);\n }\n const rows = await query;\n\n return assembleAggregateRow(rows[0] ?? {}, request, target);\n } catch (e) {\n throw 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 policies?: TablePolicies,\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 (\n parent: any,\n args: { where?: Filters<Table>; deleted?: DeletedMode },\n context: any,\n info: any,\n ) => {\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 const deleted = args?.deleted;\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 deleted: deleted ?? 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 // An aggregate over a relation counts the same rows the relation itself returns,\n // so it is narrowed by the target table's scope too.\n const whereCondition = withScope(\n resolveScope(policies, context, filterCtx),\n targetTableName,\n targetTable,\n and(\n inArray(foreignCol, uniqueIds),\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n ),\n deleted,\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(visibleColumns(table))) {\n if (groupable[columnName]) {\n continue;\n }\n const { type: dataType } = extractExtendedColumnType(column);\n if (dataType !== 'boolean') {\n continue;\n }\n groupable[columnName] = {\n column,\n converted: drizzleColumnToGraphQLType(column, columnName, tableName, true, false, false),\n };\n }\n\n return groupable;\n};\n\n/** The `${typeName}GroupByColumn` enum listing what a group-by query can group on. */\nexport const generateGroupByEnum = (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 policies?: TablePolicies,\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 ...deletedArg(policies?.softDelete, tableName),\n };\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { groupBy?: string[]; where?: Filters<Table>; having?: Record<string, any>; deleted?: DeletedMode },\n context,\n info,\n ) => {\n try {\n const requestedKeys = [...new Set(args.groupBy ?? [])];\n if (!requestedKeys.length) {\n throw 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 const where = withScope(\n resolveScope(policies, context, filterCtx),\n tableName,\n table,\n args.where\n ? extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n args.deleted,\n );\n if (where) {\n query = query.where(where);\n }\n query = query.groupBy(...keyColumns.map(([, column]) => column));\n\n const havingCondition = buildHavingCondition(args.having, columns);\n if (havingCondition) {\n query = query.having(havingCondition);\n }\n\n const rows: any[] = await query;\n\n return rows.map((row) => {\n const group: Record<string, any> = {};\n for (const [columnName, column] of keyColumns) {\n const value = row[`${GROUP_COL}${columnName}`];\n const decoded =\n typeof value === 'string' && target.dateTimeColumns.has(columnName) ? parseDriverDateTime(value) : value;\n group[columnName] = value == null ? null : remapToGraphQLCore(columnName, decoded, tableName, column);\n }\n\n return { group, ...assembleAggregateRow(row, request, target) };\n });\n } catch (e) {\n throw 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 applyContextValues,\n applyContextValuesAll,\n applyLimitPolicy,\n assertSingleMatch,\n attachRowCursors,\n attachTargetPrimaryKeys,\n bindPolicies,\n buildCursorCondition,\n buildNamedRelations,\n type CursorOrderEntry,\n computeResolverFieldNames,\n createMutationTxCtx,\n createRelationResolverFactory,\n cursorOrderExprs,\n cursorOrderingEntries,\n type DeletedMode,\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 orderByCursorObstacle,\n prepareMutationRelationColumns,\n primaryKeyOrderExprs,\n primaryKeyRestriction,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n type ResolverPolicies,\n registerColumnExclusions,\n relationFilterCtx,\n resolveConflictPlan,\n resolveQueryExecutor,\n runMutation,\n runRelationalSelect,\n runWriteHook,\n type SelectionCtx,\n selectArrayArgs,\n selectDistinctKeys,\n selectSingleArgs,\n stripContextValues,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n type WriteOperation,\n withDefaultOrderBy,\n withScope,\n} from '../builders/common.ts';\nimport {\n remapFromGraphQLArrayInput,\n remapFromGraphQLSingleInput,\n remapToGraphQLArrayOutput,\n remapToGraphQLSingleOutput,\n} from '../data-mappers/index.ts';\nimport { tableFieldExtensions } from '../extensions.ts';\nimport { resolveTableFeatures } from '../features.ts';\nimport { registerEnumConfig, registerScalarOverrides } from '../type-converter/index.ts';\nimport {\n createRelationAggregateFactory,\n generateAggregate,\n generateAggregateTypes,\n generateGroupBy,\n generateGroupByEnum,\n generateGroupByType,\n generateHavingInput,\n} 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 TableFeatures,\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 policies?: ResolverPolicies,\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 policies?.softDelete,\n tableName,\n );\n\n return {\n name: fieldName,\n resolver: async (_source, rawArgs: Partial<TableSelectArgs>, context, info) => {\n // An omitted `orderBy` falls back to the table's configured default ordering here,\n // before anything reads the arguments — the cursor tuple, a `distinct` pass and the\n // plain-select fallback all have to agree on one effective ordering.\n const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n const scope = policies?.scope?.(context);\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 defaultOrderBy: policies?.defaultOrderBy,\n pkNames,\n db: executor,\n scope,\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, deleted } = args as Partial<TableSelectArgs> & {\n deleted?: DeletedMode;\n };\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 const cursorObstacle = orderByCursorObstacle(orderBy);\n if (cursorObstacle) {\n if (after != null) {\n throw new GraphQLError(cursorObstacle);\n }\n // `cursor` selected under an ordering a cursor cannot express — resolves to null;\n // the ordering itself 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 = withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n deleted,\n );\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), where),\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 policies?: ResolverPolicies,\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, policies?.softDelete, tableName);\n\n const table = tables[tableName]!;\n const pkNames = pgPrimaryKeyPropNames(table as PgTable);\n\n return {\n name: fieldName,\n resolver: async (_source, rawArgs: Partial<TableSelectArgs>, context, info) => {\n // An omitted `orderBy` falls back to the table's configured default ordering here,\n // before anything reads the arguments — the cursor tuple, a `distinct` pass and the\n // plain-select fallback all have to agree on one effective ordering.\n const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n const scope = policies?.scope?.(context);\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 defaultOrderBy: policies?.defaultOrderBy,\n pkNames,\n db: executor,\n scope,\n });\n }\n\n // Fallback for tables without relational query builder support.\n const { offset, orderBy, where, deleted } = args as Partial<TableSelectArgs> & { deleted?: DeletedMode };\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 const whereSql = withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n deleted,\n );\n if (whereSql) {\n q = q.where(whereSql) as any;\n }\n if (orderBy) {\n q = q.orderBy(...extractOrderBy(table, orderBy, relationFilterCtx(filterCtx, tableName), where)) 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 policies?: ResolverPolicies,\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 const hooks = policies?.onWrite?.(tableName, 'insert');\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any>[] }, context, info) => {\n try {\n return await runMutation(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n if (!args.values.length) {\n throw new GraphQLError('No values were provided!');\n }\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'insert',\n single: false,\n args,\n context,\n info,\n tx: executor,\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 contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntries\n ? []\n : applyContextValuesAll(\n remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : args.values, table),\n contextColumns,\n context,\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 scope,\n defaultOrderBy: policies?.defaultOrderBy,\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) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: (tx, values) => runInsert(tx, [values]),\n context,\n })\n : await runInsert(executor, input);\n\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'insert',\n single: false,\n args,\n rows: result,\n context,\n info,\n tx: executor,\n });\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 !!hooks,\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 policies?: ResolverPolicies,\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 const hooks = policies?.onWrite?.(tableName, 'insert');\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any> }, context, info) => {\n try {\n return await runMutation(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'insert',\n single: true,\n args,\n context,\n info,\n tx: executor,\n });\n const entry = nested?.enabled(tableName) ? nested.split(tableName, args.values) : undefined;\n const nestedEntry = entry && nested!.hasOps(entry.ops) ? entry : undefined;\n const contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntry\n ? {}\n : applyContextValues(\n remapFromGraphQLSingleInput(entry ? entry.columns : args.values, table),\n contextColumns,\n context,\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 scope,\n defaultOrderBy: policies?.defaultOrderBy,\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) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: runInsert,\n context,\n })\n : await runInsert(executor, input);\n\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'insert',\n single: true,\n args,\n rows: result,\n context,\n info,\n tx: executor,\n });\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 !!hooks,\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 policies?: ResolverPolicies,\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 const hooks = policies?.onWrite?.(tableName, 'upsert');\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(\n db,\n context,\n info,\n txCtx,\n 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 await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'upsert',\n single,\n args,\n context,\n info,\n tx: executor,\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 contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntries\n ? []\n : applyContextValuesAll(\n remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table),\n contextColumns,\n context,\n );\n\n const 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 scope,\n defaultOrderBy: policies?.defaultOrderBy,\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 // On conflict the statement updates a row that already exists, so the scope applies\n // to it exactly as it would to `update<Table>`: a conflicting row the caller cannot\n // see is left alone rather than taken over.\n const setWhere = withScope(scope, tableName, table, plan.setWhere);\n query =\n plan.action === 'NOTHING'\n ? (query.onConflictDoNothing(plan.target ? { target: plan.target } : undefined) as any)\n : (query.onConflictDoUpdate({ target: plan.target!, set: plan.set, setWhere }) as any);\n\n return (await query) as Record<string, any>[];\n };\n\n const result = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: (tx, values) => runUpsert(tx, [values]),\n context,\n })\n : await runUpsert(executor, input);\n\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'upsert',\n single,\n args,\n rows: result,\n context,\n info,\n tx: executor,\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 !!hooks,\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 policies?: ResolverPolicies,\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 const hooks = policies?.onWrite?.(tableName, 'update');\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(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n const { where, set } = args;\n const scope = policies?.scope?.(context);\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'update',\n single,\n args,\n context,\n info,\n tx: executor,\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 scope,\n defaultOrderBy: policies?.defaultOrderBy,\n });\n\n const entry = nested?.enabled(tableName) ? nested.split(tableName, set) : undefined;\n const nestedOps = entry && nested!.hasOps(entry.ops) ? entry.ops : undefined;\n // A context-derived column is the server's to set, so an update never reassigns\n // one — that is what stops a row being handed to another owner.\n const input = stripContextValues(\n remapUpdateInput(entry ? entry.columns : set, table, tableName),\n policies?.contextValues?.(tableName),\n );\n // A `set` that carries only nested operations is a legitimate update — of the\n // relation rather than of the row — so it is only empty when neither is present.\n if (!Object.keys(input).length && !nestedOps) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // The scope is ANDed on last, so a caller-supplied `where` can only narrow it.\n const filters = withScope(\n scope,\n tableName,\n table,\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined,\n );\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n const returning = nestedOps\n ? nested!.withJoinColumns(tableName, nestedOps, { ...columns }, table)\n : 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 context,\n })\n : await runUpdate(executor, input);\n\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'update',\n single,\n args,\n rows: result,\n context,\n info,\n tx: executor,\n });\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 !!hooks,\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 policies?: ResolverPolicies,\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 const hooks = policies?.onWrite?.(tableName, 'updateMany');\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(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n const { updates } = args;\n if (!updates.length) {\n throw new GraphQLError('No updates were provided!');\n }\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'updateMany',\n single: false,\n args,\n context,\n info,\n tx: executor,\n });\n const scope = policies?.scope?.(context);\n const contextColumns = policies?.contextValues?.(tableName);\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 scope,\n defaultOrderBy: policies?.defaultOrderBy,\n });\n\n // Remap and validate every entry before the transaction opens, so a malformed\n // entry rejects the request instead of rolling back mid-batch.\n const entries = updates.map(({ where, set }) => {\n const split = nested?.enabled(tableName) ? nested.split(tableName, set) : undefined;\n const ops = split && nested!.hasOps(split.ops) ? split.ops : undefined;\n const input = stripContextValues(\n remapUpdateInput(split ? split.columns : set, table, tableName),\n contextColumns,\n );\n // An entry that only writes through a relation still has work to do.\n if (!Object.keys(input).length && !ops) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n ops,\n filters: withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n ),\n };\n });\n\n const 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, context)) }\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, context);\n }\n results.push(rows);\n }\n return results;\n });\n\n const flatRows = perEntry.flat();\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'updateMany',\n single: false,\n args,\n rows: flatRows,\n context,\n info,\n tx: executor,\n });\n\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 !!hooks,\n );\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\n/**\n * `delete<Table>` and, for a table that declares a soft-delete column, `restore<Table>`.\n *\n * A soft-deleting table never issues a `DELETE`: both mutations are an `UPDATE` of the marker\n * column, and the rows they return are the rows as they now stand. `restore` is the same\n * resolver reading the other way — it matches only marked rows (`deleted: ONLY`) and writes\n * the restored value.\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 policies?: ResolverPolicies,\n restore: boolean = false,\n): CreatedResolver => {\n const softDelete = policies?.softDelete?.(tableName);\n const operation: WriteOperation = restore ? 'restore' : 'delete';\n const hooks = policies?.onWrite?.(tableName, operation);\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(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n const { where } = args;\n const scope = policies?.scope?.(context);\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation,\n single,\n args,\n context,\n info,\n tx: executor,\n });\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 // Same rule as update: the scope is ANDed on last, so a delete can only ever reach\n // rows inside it — an out-of-scope row is not matched rather than being refused.\n // A soft-deleting table adds the marker predicate the same way: `delete` only sees\n // rows that are not already marked, `restore` only sees the ones that are.\n const filters = withScope(\n scope,\n tableName,\n table,\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined,\n restore ? 'ONLY' : undefined,\n );\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = softDelete\n ? executor\n .update(table)\n .set({ [softDelete.columnName]: restore ? softDelete.writeRestored : softDelete.writeDeleted() })\n : executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) as any;\n\n const result = await query;\n\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation,\n single,\n args,\n rows: result,\n context,\n info,\n tx: executor,\n });\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 !!hooks,\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 // Excluded tables are dropped here, before anything reads `tableEntries` — which also makes\n // `buildNamedRelations` skip every relation pointing at one, since it resolves targets\n // through this list.\n const excludedTables = new Set(options.exclude?.tables ?? []);\n const tableEntries = schemaEntries.filter(([key, value]) => is(value, PgTable) && !excludedTables.has(key)) as [\n string,\n PgTable,\n ][];\n const tables = Object.fromEntries(tableEntries) as Record<string, PgTable>;\n\n // A feature flag may be a per-table predicate, so every flag is resolved against the table\n // it applies to. `anyTable` answers the build-wide question — whether machinery shared\n // across tables is worth constructing at all.\n const featureOf = resolveTableFeatures(features);\n const anyTable = (feature: keyof TableFeatures) => tableEntries.some(([name]) => featureOf(name)[feature]);\n\n if (!tableEntries.length) {\n throw new Error(\n \"Drizzle-GraphQL Error: No tables detected in Drizzle-ORM's database instance. Did you forget to pass schema to drizzle constructor?\",\n );\n }\n\n // Resolve scalar overrides into the type-converter's registry before any type generation —\n // every subsequent column→GraphQL type decision and runtime value remap consults it.\n registerScalarOverrides(tables, options);\n // Same lifecycle: the enum registry is per-build, so a second build never reuses the first\n // build's enum types (and with them its naming decisions).\n registerEnumConfig(options);\n // And the same for column exclusions: a per-build registry read by every site that decides\n // what the schema contains, reset here so a rebuild never inherits the previous build's.\n registerColumnExclusions(tables, options.exclude);\n\n // Flatten drizzle-orm v1 TablesRelationalConfig into the canonical shape\n // used throughout common.ts: Record<tableName, Record<relName, TableNamedRelations>>\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Relations *into* an excluded table are already gone (their target no longer resolves);\n // relations *out of* one have no type left to hang a field on.\n for (const excluded of excludedTables) {\n delete namedRelations[excluded];\n }\n // Record each relation target's primary key (composite-aware) so paginated relations\n // default to a deterministic PK order. Must run before pruning / type generation, which\n // share these entry objects.\n attachTargetPrimaryKeys(namedRelations, tables, 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 // The row scope compiled against this build's relation graph, plus the columns whose value\n // the server supplies. Both stay undefined unless configured.\n const tablePolicies = options.policies;\n const contextValuesOf = tablePolicies?.contextValues;\n const softDeleteOf = tablePolicies?.softDelete;\n const policies = bindPolicies(tablePolicies, filterCtx);\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(\n db,\n tables,\n 'nulls-largest',\n filterCtx,\n limits,\n tablePolicies,\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 primaryKeyOf: (name) => (tables[name] ? pgPrimaryKeyPropNames(tables[name] as PgTable) : []),\n contextValuesOf,\n softDeleteOf,\n featureOf,\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\n ? createNestedWriteRuntime({\n plans: nestedPlans,\n filterCtx,\n policies: tablePolicies,\n contextValues: contextValuesOf,\n })\n : undefined;\n\n // Built when at least one table wants relation aggregates; a table that has them off is\n // handed `undefined` below, so `generateTableTypes` emits no `${relation}Aggregate` fields\n // on its object type.\n const relationAggregateFactory: RelationAggregateFactory | undefined = anyTable('relationAggregates')\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx, tablePolicies)\n : undefined;\n\n const 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 featureOf(tableName).relationAggregates ? relationAggregateFactory : undefined,\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 // Everything this table generates, with any per-table predicate already run.\n const tableFeatures = featureOf(tableName);\n // What every field this table generates publishes about itself under `extensions.drizzle`,\n // so a wrapper can read a field's identity instead of parsing its configurable name.\n const drizzleMeta = tableFieldExtensions(tableName, pgPrimaryKeyPropNames(schema[tableName] as PgTable));\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 restoreFieldName,\n restoreSingleFieldName,\n deleteCountFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\n // A table that marks rows deleted instead of removing them also gets the mutation that\n // reverses it — clearing the column through an ordinary update is not possible, since the\n // column is not in the update input and a marked row is invisible to a `where` anyway.\n const softDeleteInfo = softDeleteOf?.(tableName);\n\n const selectArrGenerated = generateSelectArray(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n listFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n tableFeatures.distinct,\n limits,\n policies,\n );\n const selectSingleGenerated = generateSelectSingle(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n singleFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n limits,\n policies,\n );\n const insertArrGenerated = tableFeatures.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 policies,\n )\n : undefined;\n const insertSingleGenerated = tableFeatures.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 policies,\n )\n : undefined;\n // An upsert needs something to conflict on, so a table with no primary key and no\n // unique constraint gets no upsert mutations rather than ones that always fail.\n const uniqueSets = tableFeatures.upsert ? getUniqueColumnSets(schema[tableName] as PgTable, getTableConfig) : [];\n const onConflictInput = tableFeatures.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 policies,\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 policies,\n )\n : undefined;\n const updateGenerated = tableFeatures.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 tableFeatures.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n policies,\n )\n : undefined;\n const updateSingleGenerated = tableFeatures.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 tableFeatures.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n policies,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n tableFeatures.update && tableFeatures.updateMany\n ? generateUpdateManyInput({ 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 policies,\n )\n : undefined;\n const deleteGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n deleteFieldName,\n typeName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n )\n : undefined;\n const deleteSingleGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n deleteSingleFieldName,\n typeName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n )\n : undefined;\n const restoreGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n restoreFieldName,\n typeName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n const restoreSingleGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n restoreSingleFieldName,\n typeName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n // The count variants are the plural write with its payload left off, so each follows the\n // same feature switch as the write it mirrors.\n const updateCountGenerated =\n tableFeatures.update && tableFeatures.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: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n nested: nestedRuntime,\n })\n : undefined;\n const deleteCountGenerated =\n tableFeatures.delete && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as PgTable,\n kind: 'delete',\n filterArgs: tableFilters,\n fieldName: deleteCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n })\n : undefined;\n const aggregateType = tableFeatures.aggregates\n ? generateAggregateTypes(schema[tableName] as PgTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = tableFeatures.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as PgTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n tablePolicies,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n tableFeatures.aggregates && tableFeatures.groupBy\n ? generateGroupByType(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 tablePolicies,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: listFieldComplexity(complexity, limits?.(tableName)) } : {}),\n },\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: true, targetArg: 'where' }),\n },\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'aggregate', single: true, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'groupBy', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n };\n }\n if (insertArrGenerated) {\n mutations[insertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: insertArrGenerated.args,\n resolve: insertArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'insert', single: false, targetArg: 'values' }),\n },\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 extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'insert', single: true, targetArg: 'values' }),\n },\n };\n }\n if (upsertArrGenerated) {\n mutations[upsertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: upsertArrGenerated.args,\n resolve: upsertArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'upsert', single: false, targetArg: 'values' }),\n },\n };\n }\n if (upsertSingleGenerated) {\n mutations[upsertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: upsertSingleGenerated.args,\n resolve: upsertSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'upsert', single: true, targetArg: 'values' }),\n },\n };\n }\n if (updateGenerated) {\n mutations[updateGenerated.name] = {\n type: arrTableItemOutput,\n args: updateGenerated.args,\n resolve: updateGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'update', single: false, targetArg: 'where' }),\n },\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 extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'updateMany', single: false, targetArg: 'updates' }),\n },\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 extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'update', single: true, targetArg: 'where' }),\n },\n };\n }\n if (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'delete', single: false, targetArg: 'where' }),\n },\n };\n }\n if (deleteSingleGenerated) {\n mutations[deleteSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: deleteSingleGenerated.args,\n resolve: deleteSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'delete', single: true, targetArg: 'where' }),\n },\n };\n }\n if (restoreGenerated) {\n mutations[restoreGenerated.name] = {\n type: arrTableItemOutput,\n args: restoreGenerated.args,\n resolve: restoreGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'restore', single: false, targetArg: 'where' }),\n },\n };\n }\n if (restoreSingleGenerated) {\n mutations[restoreSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: restoreSingleGenerated.args,\n resolve: restoreSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'restore', single: true, targetArg: 'where' }),\n },\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 ...(tableFeatures.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(tableFeatures.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, Column, eq, getColumns, inArray, 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 applyContextValues,\n type ContextValuesFor,\n extractFilters,\n type RelationFilterBase,\n relationFilterCtx,\n resolveScope,\n resolveTypeName,\n type ScopeResolver,\n type TablePolicies,\n type TypeCacheCtx,\n type TypeNameMapper,\n visibleColumns,\n withScope,\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 /** Set when the relation goes through a junction table, which is then what gets written. */\n through?: NestedThroughPlan;\n};\n\n/**\n * The junction table of a `.through()` relation, and the two of its columns this relation\n * joins on. A many-to-many is attached and detached by inserting and deleting junction rows,\n * so neither the parent row nor the target row is written at all.\n */\nexport type NestedThroughPlan = {\n table: Table;\n /** Property name of the junction column holding the parent's key. */\n sourceColPropName: string;\n /** Property name of the junction column holding the target's key. */\n targetColPropName: string;\n sourceCol: Column;\n targetCol: Column;\n};\n\n/** Every writable relation of every table: table name → relation name → plan. */\nexport type NestedWritePlans = Record<string, Record<string, NestedRelationPlan>>;\n\n/** The nested operations of one mutation input, keyed by relation name. */\nexport type NestedOps = Record<string, Record<string, any>>;\n\n/**\n * Whether a column can be left out of an INSERT — either the database fills it in or it\n * accepts NULL.\n */\nconst isOptionalOnInsert = (column: Column): boolean =>\n !column.notNull || !!column.hasDefault || !!(column as any).defaultFn;\n\n/** The property name a column is stored under on its table, matched by identity. */\nconst propNameOf = (table: Table, column: Column | undefined): string | undefined => {\n if (!column) {\n return undefined;\n }\n for (const [propName, candidate] of Object.entries(getColumns(table))) {\n if (candidate === column) {\n return propName;\n }\n }\n return undefined;\n};\n\n/**\n * The junction column one entry of a relation's `through` config points at. Drizzle wraps it\n * in a descriptor while the relation is being defined; the raw column is accepted too, so a\n * change of shape there degrades to skipping the relation rather than mis-planning it.\n */\nconst throughColumn = (entry: any): Column | undefined =>\n entry && is(entry, Column) ? (entry as Column) : (entry?._?.column as Column | undefined);\n\n/**\n * A `.through()` relation's plan: the junction table plus the two columns it joins on.\n *\n * Nothing about the parent or the target row changes when a many-to-many link is made or\n * broken — only junction rows are inserted and deleted — so `canDetach` is unconditional\n * here, and there is no nullable-foreign-key question to ask.\n *\n * Left unplanned, and so absent from the inputs: a to-one `.through()`, whose \"exactly one\n * row\" guarantee lives in the junction's constraints rather than in the relation; a relation\n * joining on more than one column per side; and a junction carrying a further NOT NULL column\n * with no default, which no `connect` operand could supply a value for.\n */\nconst buildThroughPlan = (\n relationName: string,\n relation: any,\n table: Table,\n targetTableName: string,\n targetTable: Table,\n): NestedRelationPlan | undefined => {\n if (is(relation, One)) {\n return undefined;\n }\n\n const junction = relation.throughTable as Table | undefined;\n const sourceEntries = relation.through?.source;\n const targetEntries = relation.through?.target;\n if (!junction || sourceEntries?.length !== 1 || targetEntries?.length !== 1) {\n return undefined;\n }\n if (relation.sourceColumns?.length !== 1 || relation.targetColumns?.length !== 1) {\n return undefined;\n }\n\n // Drizzle normalizes the two ends before it stores them, so `source` is the parent's side\n // even on the relation declared from the other table. Each column is looked up on the table\n // it is supposed to belong to, which is also the check that the normalization held.\n const localCol = relation.sourceColumns[0] as Column;\n const foreignCol = relation.targetColumns[0] as Column;\n const localColPropName = propNameOf(table, localCol);\n const foreignColPropName = propNameOf(targetTable, foreignCol);\n const sourceColPropName = propNameOf(junction, throughColumn(sourceEntries[0]));\n const targetColPropName = propNameOf(junction, throughColumn(targetEntries[0]));\n if (!localColPropName || !foreignColPropName || !sourceColPropName || !targetColPropName) {\n return undefined;\n }\n\n const junctionColumns = getColumns(junction);\n const sourceCol = junctionColumns[sourceColPropName] as Column;\n const targetCol = junctionColumns[targetColPropName] as Column;\n const unsuppliable = Object.entries(junctionColumns).some(\n ([propName, column]) =>\n propName !== sourceColPropName && propName !== targetColPropName && !isOptionalOnInsert(column as Column),\n );\n if (unsuppliable) {\n return undefined;\n }\n\n return {\n relationName,\n targetTableName,\n targetTable,\n localColPropName,\n foreignColPropName,\n foreignCol,\n localCol,\n isOne: false,\n // The link is written after the parent row exists, exactly like a child-side foreign key.\n fkSide: 'child',\n canDetach: true,\n through: { table: junction, sourceColPropName, targetColPropName, sourceCol, targetCol },\n };\n};\n\n/**\n * Which relations of which tables can be written through.\n *\n * A `.through()` (many-to-many) relation is planned too, but as a junction-table write\n * rather than a foreign-key one — see {@link buildThroughPlan}.\n *\n * Skipped, and so absent from the generated inputs rather than failing at runtime:\n * relations whose join columns cannot be read off the drizzle relation; and relations where\n * neither join column is unique, which leaves no way to tell which side stores the key.\n */\nexport const buildNestedWritePlans = (\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n resolveUniqueSets: (table: Table) => string[][],\n resolvePrimaryKeys: (table: Table) => string[],\n extractJoinColumns: (\n relEntry: TableNamedRelations,\n parentTable: Table,\n targetTable: Table,\n ) => { localColPropName: string; foreignCol: Column; foreignColPropName: string } | undefined,\n): NestedWritePlans => {\n const uniqueCache = new Map<string, Set<string>>();\n // Only single-column unique keys matter here: a relation joins on one column, so a\n // composite key says nothing about whether that column identifies a row on its own.\n const singleColumnUniques = (tableName: string, table: Table): Set<string> => {\n let cached = uniqueCache.get(tableName);\n if (!cached) {\n cached = new Set(\n resolveUniqueSets(table)\n .filter((set) => set.length === 1)\n .map((set) => set[0]!),\n );\n uniqueCache.set(tableName, cached);\n }\n return cached;\n };\n\n const pkCache = new Map<string, string | undefined>();\n // Only a single-column primary key identifies a row by one join column, which is the only\n // shape a relation can be written through.\n const singleColumnPk = (tableName: string, table: Table): string | undefined => {\n if (!pkCache.has(tableName)) {\n const pk = resolvePrimaryKeys(table);\n pkCache.set(tableName, pk.length === 1 ? pk[0] : undefined);\n }\n return pkCache.get(tableName);\n };\n\n const plans: NestedWritePlans = {};\n\n for (const [tableName, relations] of Object.entries(relationMap)) {\n const table = tables[tableName];\n if (!table) {\n continue;\n }\n\n const tablePlans: Record<string, NestedRelationPlan> = {};\n\n for (const [relationName, relEntry] of Object.entries(relations)) {\n const relation = (relEntry as any).relation;\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n if (!targetTable) {\n continue;\n }\n\n if ((relation as any).through) {\n const throughPlan = buildThroughPlan(relationName, relation, table, targetTableName, targetTable);\n if (throughPlan) {\n tablePlans[relationName] = throughPlan;\n }\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 // Same rule as the table's own create input: a column the server fills in from context\n // is not something a nested `create` may supply either.\n const contextColumns = cacheCtx.contextValuesOf?.(plan.targetTableName);\n const fields = Object.fromEntries(\n Object.entries(visibleColumns(plan.targetTable))\n .filter(([columnName]) => columnName !== omitted && !contextColumns?.[columnName])\n .map(([columnName, column]) => [\n columnName,\n drizzleColumnToGraphQLType(column as Column, columnName, plan.targetTableName, false, true, true),\n ]),\n );\n\n const type = new GraphQLInputObjectType({\n name: `${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 * A many-to-many relation offers no `create`: inserting a row *and* linking it is two\n * writes to two tables, and the link half is what the relation field is for. Its\n * `disconnect` and `set` are offered unconditionally, since breaking a link deletes a\n * junction row rather than nulling a column that might be NOT NULL.\n */\n const wrapperType = (\n tableName: string,\n typeName: string,\n plan: NestedRelationPlan,\n forUpdate: boolean,\n ): GraphQLInputObjectType | undefined => {\n const key = `${tableName}.${plan.relationName}.${forUpdate ? 'update' : 'create'}`;\n const cached = wrapperCache.get(key);\n if (cached) {\n return cached;\n }\n\n const filters = targetFilters(plan);\n const targetTypeName = resolveTypeName(plan.targetTableName, typeNameMapper);\n const fields: Record<string, { type: GraphQLInputType; description: string }> = {};\n\n if (plan.through) {\n // Without a `Filters` input there is no way to name the rows to link, and `create` is\n // not offered here, so the whole field would be empty — the relation is left out.\n if (!filters) {\n return undefined;\n }\n fields['connect'] = {\n type: listOf(filters),\n description: `Link every existing ${targetTypeName} row these match. Already-linked rows are left alone.`,\n };\n if (forUpdate) {\n fields['disconnect'] = {\n type: listOf(filters),\n description: `Unlink every linked ${targetTypeName} row these match, leaving the rows in place`,\n };\n fields['set'] = {\n type: listOf(filters),\n description: `Replace the whole set: unlink everything linked, then link every ${targetTypeName} row these match. \\`set: []\\` clears the relation. Applied before \\`disconnect\\` and \\`connect\\`.`,\n };\n }\n } else if (plan.isOne) {\n fields['create'] = {\n type: payloadType(tableName, typeName, plan),\n description: `Insert a ${targetTypeName} row and attach it`,\n };\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'] = {\n type: listOf(payloadType(tableName, typeName, plan)),\n description: `Insert these ${targetTypeName} rows and attach them`,\n };\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, and outside a many-to-many a relation\n // with nothing on it at all cannot happen: `create` is unconditional there.\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, context?: any) => 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 context?: 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 policies?: TablePolicies;\n contextValues?: ContextValuesFor;\n}): NestedWriteRuntime => {\n const { plans, filterCtx, policies, contextValues } = 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 = (\n plan: NestedRelationPlan,\n filter: Record<string, any>,\n operation: string,\n scope: ScopeResolver | undefined,\n ) => {\n const condition = extractFilters(\n plan.targetTable,\n plan.targetTableName,\n filter,\n relationFilterCtx(filterCtx, plan.targetTableName),\n );\n if (!condition) {\n throw 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 // The filter selects rows to attach or detach, so it is a write against the target\n // table and is narrowed by its scope: `connect` cannot reach a row the caller cannot\n // see, and out-of-scope rows are not detached.\n return withScope(scope, plan.targetTableName, plan.targetTable, condition)!;\n };\n\n const assertSingleOperation = (plan: NestedRelationPlan, op: Record<string, any>) => {\n const 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 /** The values the junction stores for the target rows one operand selects. */\n const selectedTargetKeys = async (\n executor: any,\n plan: NestedRelationPlan,\n filter: Record<string, any>,\n operation: string,\n scope: ScopeResolver | undefined,\n ): Promise<any[]> => {\n const rows = await executor\n .select()\n .from(plan.targetTable)\n .where(conditionOf(plan, filter, operation, scope));\n return rows\n .map((row: any) => row[plan.foreignColPropName])\n .filter((value: any) => value !== undefined && value !== null);\n };\n\n /**\n * The link half of a many-to-many write: junction rows are inserted and deleted, and both\n * the parent row and the target rows are left exactly as they are.\n *\n * `connect` reads the parent's existing links first and inserts only the missing ones, so\n * re-connecting a linked row is a no-op on every dialect rather than a unique-constraint\n * error on some of them — the read and the write share the surrounding transaction, so no\n * other writer can slip a duplicate in between them.\n */\n const applyThroughOps = async (\n executor: any,\n plan: NestedRelationPlan,\n key: any,\n op: Record<string, any>,\n scope: ScopeResolver | undefined,\n ) => {\n const through = plan.through!;\n const unlinkAll = () => executor.delete(through.table).where(eq(through.sourceCol, key));\n\n const link = async (operands: any[], operation: string) => {\n const existing = new Set(\n (await executor.select().from(through.table).where(eq(through.sourceCol, key))).map(\n (row: any) => row[through.targetColPropName],\n ),\n );\n const rows: Record<string, any>[] = [];\n for (const filter of operands) {\n for (const targetKey of await selectedTargetKeys(executor, plan, filter, operation, scope)) {\n if (!existing.has(targetKey)) {\n existing.add(targetKey);\n rows.push({ [through.sourceColPropName]: key, [through.targetColPropName]: targetKey });\n }\n }\n }\n if (rows.length) {\n await executor.insert(through.table).values(rows);\n }\n };\n\n // Replace-the-set first, so a `set` alongside a `connect` reads as \"these rows, plus that\n // one\". `set: []` unlinks everything and links nothing back, which is how the relation is\n // cleared.\n if (op['set'] !== undefined && op['set'] !== null) {\n await unlinkAll();\n await link(asArray(op['set']), 'set');\n }\n\n if (op['disconnect'] !== undefined && op['disconnect'] !== null) {\n for (const filter of asArray(op['disconnect'])) {\n const targetKeys = await selectedTargetKeys(executor, plan, filter, 'disconnect', scope);\n if (targetKeys.length) {\n await executor\n .delete(through.table)\n .where(and(eq(through.sourceCol, key), inArray(through.targetCol, targetKeys)));\n }\n }\n }\n\n if (op['connect'] !== undefined && op['connect'] !== null) {\n await link(asArray(op['connect']), 'connect');\n }\n };\n\n const detachAll = async (executor: any, plan: NestedRelationPlan, key: any, scope: ScopeResolver | undefined) =>\n executor\n .update(plan.targetTable)\n .set({ [plan.foreignColPropName]: null })\n .where(withScope(scope, plan.targetTableName, plan.targetTable, 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, context) => {\n const tablePlans = plans[tableName];\n const patch: Record<string, any> = {};\n if (!tablePlans) {\n return patch;\n }\n const scope = resolveScope(policies, context, filterCtx);\n\n for (const [relationName, op] of Object.entries(ops)) {\n const plan = tablePlans[relationName];\n if (!plan || plan.fkSide !== 'parent') {\n continue;\n }\n assertSingleOperation(plan, op);\n\n if (op['create'] !== undefined) {\n const values = applyContextValues(\n remapFromGraphQLSingleInput({ ...op['create'] }, plan.targetTable),\n contextValues?.(plan.targetTableName),\n context,\n );\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', scope));\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, context) => {\n const tablePlans = plans[tableName];\n if (!tablePlans) {\n return;\n }\n const scope = resolveScope(policies, context, filterCtx);\n\n for (const [relationName, op] of Object.entries(ops)) {\n const plan = tablePlans[relationName];\n if (!plan || 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 if (plan.through) {\n await applyThroughOps(executor, plan, key, op, scope);\n continue;\n }\n\n // Replace-the-set first, so a `set` alongside a `create` reads as \"these rows, plus\n // this new one\" rather than dropping the row it just inserted.\n if (op['set'] !== undefined) {\n await detachAll(executor, plan, key, scope);\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', scope));\n }\n }\n\n if (op['disconnect'] !== undefined) {\n if (plan.isOne) {\n if (op['disconnect'] === true) {\n await detachAll(executor, plan, key, scope);\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', scope)));\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, scope);\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', scope));\n }\n }\n\n if (op['create'] !== undefined) {\n const rows = asArray(op['create']).map((row) => ({\n ...applyContextValues(\n remapFromGraphQLSingleInput({ ...row }, plan.targetTable),\n contextValues?.(plan.targetTableName),\n context,\n ),\n [plan.foreignColPropName]: key,\n }));\n if (rows.length) {\n await 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 context?: any;\n}): Promise<Record<string, any>[]> => {\n const { executor, runtime, tableName, entries, remapValues, write, context } = 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, context);\n const written = await write(tx, { ...remapValues(entry.columns), ...patch });\n await runtime.applyChildSide(tx, tableName, entry.ops, written, context);\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 context?: any;\n}): Promise<Record<string, any>[]> => {\n const { executor, runtime, tableName, columns, ops, remapValues, write, context } = params;\n\n return executor.transaction(async (tx: any) => {\n const patch = await runtime.applyParentSide(tx, tableName, ops, context);\n const rows = await write(tx, { ...remapValues(columns), ...patch });\n await runtime.applyChildSide(tx, tableName, ops, rows, context);\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 applyContextValues,\n applyContextValuesAll,\n applyLimitPolicy,\n assertSingleMatch,\n attachTargetPrimaryKeys,\n bindPolicies,\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 type ResolverPolicies,\n registerColumnExclusions,\n relationFilterCtx,\n resolveConflictPlan,\n resolveQueryExecutor,\n runMutation,\n runRelationalSelect,\n runWriteHook,\n type SelectionCtx,\n selectArrayArgs,\n selectSingleArgs,\n stripContextValues,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n type WriteOperation,\n withDefaultOrderBy,\n withScope,\n} from '../builders/common.ts';\nimport {\n remapFromGraphQLArrayInput,\n remapFromGraphQLSingleInput,\n remapToGraphQLArrayOutput,\n remapToGraphQLSingleOutput,\n} from '../data-mappers/index.ts';\nimport { tableFieldExtensions } from '../extensions.ts';\nimport { resolveTableFeatures } from '../features.ts';\nimport { registerEnumConfig, registerScalarOverrides } from '../type-converter/index.ts';\nimport {\n createRelationAggregateFactory,\n generateAggregate,\n generateAggregateTypes,\n generateGroupBy,\n generateGroupByEnum,\n generateGroupByType,\n generateHavingInput,\n} 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 TableFeatures,\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 policies?: ResolverPolicies,\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 policies?.softDelete,\n tableName,\n );\n\n return {\n name: fieldName,\n resolver: async (_source: any, rawArgs: Partial<TableSelectArgs>, context: any, info: GraphQLResolveInfo) => {\n // An omitted `orderBy` falls back to the table's configured default ordering here,\n // before anything reads the arguments — the cursor tuple, a `distinct` pass and the\n // plain-select fallback all have to agree on one effective ordering.\n const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n limit: applyLimitPolicy(args.limit, limitPolicy, fieldName),\n single: false,\n filterCtx,\n limits,\n defaultOrderBy: policies?.defaultOrderBy,\n pkNames,\n db: executor,\n scope: policies?.scope?.(context),\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 policies?: ResolverPolicies,\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, policies?.softDelete, tableName);\n\n const table = tables[tableName]!;\n const pkNames = sqlitePrimaryKeyPropNames(table as SQLiteTable);\n\n return {\n name: fieldName,\n resolver: async (_source, rawArgs: Partial<TableSelectArgs>, context, info) => {\n // An omitted `orderBy` falls back to the table's configured default ordering here,\n // before anything reads the arguments — the cursor tuple, a `distinct` pass and the\n // plain-select fallback all have to agree on one effective ordering.\n const args = withDefaultOrderBy(rawArgs, tableName, policies?.defaultOrderBy);\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n limits,\n defaultOrderBy: policies?.defaultOrderBy,\n pkNames,\n db: executor,\n scope: policies?.scope?.(context),\n });\n } catch (e) {\n throw 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 policies?: ResolverPolicies,\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 const hooks = policies?.onWrite?.(tableName, 'insert');\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any>[] }, context, info) => {\n try {\n return await runMutation(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n if (!args.values.length) {\n throw new GraphQLError('No values were provided!');\n }\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'insert',\n single: false,\n args,\n context,\n info,\n tx: executor,\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 contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntries\n ? []\n : applyContextValuesAll(\n remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : args.values, table),\n contextColumns,\n context,\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 scope,\n defaultOrderBy: policies?.defaultOrderBy,\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) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: (tx, values) => runInsert(tx, [values]),\n context,\n })\n : await runInsert(executor, input);\n\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'insert',\n single: false,\n args,\n rows: result,\n context,\n info,\n tx: executor,\n });\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 !!hooks,\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 policies?: ResolverPolicies,\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 const hooks = policies?.onWrite?.(tableName, 'insert');\n\n return {\n name: fieldName,\n resolver: async (_source, args: { values: Record<string, any> }, context, info) => {\n try {\n return await runMutation(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'insert',\n single: true,\n args,\n context,\n info,\n tx: executor,\n });\n const entry = nested?.enabled(tableName) ? nested.split(tableName, args.values) : undefined;\n const nestedEntry = entry && nested!.hasOps(entry.ops) ? entry : undefined;\n const contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntry\n ? {}\n : applyContextValues(\n remapFromGraphQLSingleInput(entry ? entry.columns : args.values, table),\n contextColumns,\n context,\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 scope,\n defaultOrderBy: policies?.defaultOrderBy,\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) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: runInsert,\n context,\n })\n : await runInsert(executor, input);\n\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'insert',\n single: true,\n args,\n rows: result,\n context,\n info,\n tx: executor,\n });\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 !!hooks,\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 policies?: ResolverPolicies,\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 const hooks = policies?.onWrite?.(tableName, 'upsert');\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(\n db,\n context,\n info,\n txCtx,\n 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 await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'upsert',\n single,\n args,\n context,\n info,\n tx: executor,\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 contextColumns = policies?.contextValues?.(tableName);\n const scope = policies?.scope?.(context);\n const input = nestedEntries\n ? []\n : applyContextValuesAll(\n remapFromGraphQLArrayInput(entries ? entries.map((entry) => entry.columns) : supplied, table),\n contextColumns,\n context,\n );\n\n const 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 scope,\n defaultOrderBy: policies?.defaultOrderBy,\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 // On conflict the statement updates a row that already exists, so the scope applies\n // to it exactly as it would to `update<Table>`: a conflicting row the caller cannot\n // see is left alone rather than taken over.\n const setWhere = withScope(scope, tableName, table, plan.setWhere);\n query =\n plan.action === 'NOTHING'\n ? (query.onConflictDoNothing(plan.target ? { target: plan.target } : undefined) as any)\n : (query.onConflictDoUpdate({ target: plan.target!, set: plan.set, setWhere }) as any);\n\n return (await query) as Record<string, any>[];\n };\n\n const result = nestedEntries\n ? await writeWithNestedOps({\n executor,\n runtime: nested!,\n tableName,\n entries: nestedEntries,\n remapValues: (values) =>\n applyContextValues(remapFromGraphQLSingleInput(values, table), contextColumns, context),\n write: (tx, values) => runUpsert(tx, [values]),\n context,\n })\n : await runUpsert(executor, input);\n\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'upsert',\n single,\n args,\n rows: result,\n context,\n info,\n tx: executor,\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 !!hooks,\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 policies?: ResolverPolicies,\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 const hooks = policies?.onWrite?.(tableName, 'update');\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(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'update',\n single,\n args,\n context,\n info,\n tx: executor,\n });\n const { where, set } = args;\n const scope = policies?.scope?.(context);\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 scope,\n defaultOrderBy: policies?.defaultOrderBy,\n });\n\n const entry = nested?.enabled(tableName) ? nested.split(tableName, set) : undefined;\n const nestedOps = entry && nested!.hasOps(entry.ops) ? entry.ops : undefined;\n // A context-derived column is the server's to set, so an update never reassigns\n // one — that is what stops a row being handed to another owner.\n const input = stripContextValues(\n remapUpdateInput(entry ? entry.columns : set, table, tableName),\n policies?.contextValues?.(tableName),\n );\n // A `set` that carries only nested operations is a legitimate update — of the\n // relation rather than of the row — so it is only empty when neither is present.\n if (!Object.keys(input).length && !nestedOps) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n // The scope is ANDed on last, so a caller-supplied `where` can only narrow it.\n const filters = withScope(\n scope,\n tableName,\n table,\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined,\n );\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n const returning = nestedOps\n ? nested!.withJoinColumns(tableName, nestedOps, { ...columns }, table)\n : 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 context,\n })\n : await runUpdate(executor, input);\n\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'update',\n single,\n args,\n rows: result,\n context,\n info,\n tx: executor,\n });\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 !!hooks,\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 policies?: ResolverPolicies,\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 const hooks = policies?.onWrite?.(tableName, 'updateMany');\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(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n const { updates } = args;\n if (!updates.length) {\n throw new GraphQLError('No updates were provided!');\n }\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation: 'updateMany',\n single: false,\n args,\n context,\n info,\n tx: executor,\n });\n const scope = policies?.scope?.(context);\n const contextColumns = policies?.contextValues?.(tableName);\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 scope,\n defaultOrderBy: policies?.defaultOrderBy,\n });\n\n // Remap and validate every entry before the transaction opens, so a malformed\n // entry rejects the request instead of rolling back mid-batch.\n const entries = updates.map(({ where, set }) => {\n const split = nested?.enabled(tableName) ? nested.split(tableName, set) : undefined;\n const ops = split && nested!.hasOps(split.ops) ? split.ops : undefined;\n const input = stripContextValues(\n remapUpdateInput(split ? split.columns : set, table, tableName),\n contextColumns,\n );\n // An entry that only writes through a relation still has work to do.\n if (!Object.keys(input).length && !ops) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n ops,\n filters: withScope(\n scope,\n tableName,\n table,\n where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n ),\n };\n });\n\n const anyNested = entries.some((entry) => entry.ops);\n const returning = 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, context)) }\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, context);\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 await runWriteHook(hooks, 'after', {\n table: tableName,\n operation: 'updateMany',\n single: false,\n args,\n rows: flatRows,\n context,\n info,\n tx: executor,\n });\n\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 !!hooks,\n );\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\n/**\n * `delete<Table>` and, for a table that declares a soft-delete column, `restore<Table>`.\n * See the PostgreSQL builder's copy for the shape — a soft-deleting table issues an `UPDATE`\n * of the marker column instead of a `DELETE`, and `restore` is the same resolver matching\n * only marked rows and writing the restored value.\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 policies?: ResolverPolicies,\n restore: boolean = false,\n): CreatedResolver => {\n const softDelete = policies?.softDelete?.(tableName);\n const operation: WriteOperation = restore ? 'restore' : 'delete';\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n const hooks = policies?.onWrite?.(tableName, operation);\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, info) => {\n try {\n return await runMutation(\n db,\n context,\n info,\n txCtx,\n async (executor) => {\n await runWriteHook(hooks, 'before', {\n table: tableName,\n operation,\n single,\n args,\n context,\n info,\n tx: executor,\n });\n const { where } = args;\n const scope = policies?.scope?.(context);\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 // Same rule as update: the scope is ANDed on last, so a delete can only ever reach\n // rows inside it — an out-of-scope row is not matched rather than being refused.\n // A soft-deleting table adds the marker predicate the same way: `delete` only sees\n // rows that are not already marked, `restore` only sees the ones that are.\n const filters = withScope(\n scope,\n tableName,\n table,\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined,\n restore ? 'ONLY' : undefined,\n );\n\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = softDelete\n ? executor\n .update(table)\n .set({ [softDelete.columnName]: restore ? softDelete.writeRestored : softDelete.writeDeleted() })\n : executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) as any;\n\n const result = await query;\n\n await runWriteHook(hooks, 'after', {\n table: tableName,\n operation,\n single,\n args,\n rows: result,\n context,\n info,\n tx: executor,\n });\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 !!hooks,\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 // Excluded tables are dropped here, before anything reads `tableEntries` — which also makes\n // `buildNamedRelations` skip every relation pointing at one, since it resolves targets\n // through this list.\n const excludedTables = new Set(options.exclude?.tables ?? []);\n const tableEntries = schemaEntries.filter(([key, value]) => is(value, SQLiteTable) && !excludedTables.has(key)) as [\n string,\n SQLiteTable,\n ][];\n const tables = Object.fromEntries(tableEntries) as Record<string, SQLiteTable>;\n\n // A feature flag may be a per-table predicate, so every flag is resolved against the table\n // it applies to. `anyTable` answers the build-wide question — whether machinery shared\n // across tables is worth constructing at all.\n const featureOf = resolveTableFeatures(features);\n const anyTable = (feature: keyof TableFeatures) => tableEntries.some(([name]) => featureOf(name)[feature]);\n\n if (!tableEntries.length) {\n throw new Error(\n \"Drizzle-GraphQL Error: No tables detected in Drizzle-ORM's database instance. Did you forget to pass schema to drizzle constructor?\",\n );\n }\n\n // Resolve scalar overrides into the type-converter's registry before any type generation —\n // every subsequent column→GraphQL type decision and runtime value remap consults it.\n registerScalarOverrides(tables, options);\n // Same lifecycle: the enum registry is per-build, so a second build never reuses the first\n // build's enum types (and with them its naming decisions).\n registerEnumConfig(options);\n // And the same for column exclusions: a per-build registry read by every site that decides\n // what the schema contains, reset here so a rebuild never inherits the previous build's.\n registerColumnExclusions(tables, options.exclude);\n\n // Build namedRelations from the drizzle-orm v1 relations config.\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Relations *into* an excluded table are already gone (their target no longer resolves);\n // relations *out of* one have no type left to hang a field on.\n for (const excluded of excludedTables) {\n delete namedRelations[excluded];\n }\n // Record each relation target's (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 // The row scope compiled against this build's relation graph, plus the columns whose value\n // the server supplies. Both stay undefined unless configured.\n const tablePolicies = options.policies;\n const contextValuesOf = tablePolicies?.contextValues;\n const softDeleteOf = tablePolicies?.softDelete;\n const policies = bindPolicies(tablePolicies, filterCtx);\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(\n db,\n tables,\n 'nulls-smallest',\n filterCtx,\n limits,\n tablePolicies,\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 primaryKeyOf: (name) => (tables[name] ? sqlitePrimaryKeyPropNames(tables[name] as SQLiteTable) : []),\n contextValuesOf,\n softDeleteOf,\n featureOf,\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\n ? createNestedWriteRuntime({\n plans: nestedPlans,\n filterCtx,\n policies: tablePolicies,\n contextValues: contextValuesOf,\n })\n : undefined;\n\n // Built when at least one table wants relation aggregates; a table that has them off is\n // handed `undefined` below, so `generateTableTypes` emits no `${relation}Aggregate` fields\n // on its object type.\n const relationAggregateFactory: RelationAggregateFactory | undefined = anyTable('relationAggregates')\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx, tablePolicies)\n : undefined;\n\n const 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 featureOf(tableName).relationAggregates ? relationAggregateFactory : undefined,\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 // Everything this table generates, with any per-table predicate already run.\n const tableFeatures = featureOf(tableName);\n // What every field this table generates publishes about itself under `extensions.drizzle`,\n // so a wrapper can read a field's identity instead of parsing its configurable name.\n const drizzleMeta = tableFieldExtensions(tableName, sqlitePrimaryKeyPropNames(schema[tableName] as SQLiteTable));\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 restoreFieldName,\n restoreSingleFieldName,\n deleteCountFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\n // A table that marks rows deleted instead of removing them also gets the mutation that\n // reverses it — clearing the column through an ordinary update is not possible, since the\n // column is not in the update input and a marked row is invisible to a `where` anyway.\n const softDeleteInfo = softDeleteOf?.(tableName);\n\n const selectArrGenerated = generateSelectArray(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n listFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n tableFeatures.distinct,\n limits,\n policies,\n );\n const selectSingleGenerated = generateSelectSingle(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n singleFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n limits,\n policies,\n );\n const insertArrGenerated = tableFeatures.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 policies,\n )\n : undefined;\n const insertSingleGenerated = tableFeatures.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 policies,\n )\n : undefined;\n // An upsert needs something to conflict on, so a table with no primary key and no\n // unique constraint gets no upsert mutations rather than ones that always fail.\n const uniqueSets = tableFeatures.upsert\n ? getUniqueColumnSets(schema[tableName] as SQLiteTable, getTableConfig)\n : [];\n const onConflictInput = tableFeatures.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 policies,\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 policies,\n )\n : undefined;\n const updateGenerated = tableFeatures.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 tableFeatures.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n policies,\n )\n : undefined;\n const updateSingleGenerated = tableFeatures.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 tableFeatures.requireWhere,\n typeNameMapper,\n filterCtx,\n mutationTxCtx,\n nestedRuntime,\n limits,\n policies,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n tableFeatures.update && tableFeatures.updateMany\n ? generateUpdateManyInput({ 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 policies,\n )\n : undefined;\n const deleteGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n deleteFieldName,\n typeName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n )\n : undefined;\n const deleteSingleGenerated = tableFeatures.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n deleteSingleFieldName,\n typeName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n )\n : undefined;\n const restoreGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n restoreFieldName,\n typeName,\n false,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n const restoreSingleGenerated = softDeleteInfo\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n restoreSingleFieldName,\n typeName,\n true,\n tableFeatures.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n mutationTxCtx,\n policies,\n true,\n )\n : undefined;\n // The count variants are the plural write with its payload left off, so each follows the\n // same feature switch as the write it mirrors.\n const updateCountGenerated =\n tableFeatures.update && tableFeatures.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: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n nested: nestedRuntime,\n })\n : undefined;\n const deleteCountGenerated =\n tableFeatures.delete && tableFeatures.countMutations\n ? generateWriteCount({\n db,\n tableName,\n table: schema[tableName] as SQLiteTable,\n kind: 'delete',\n filterArgs: tableFilters,\n fieldName: deleteCountFieldName,\n requireWhere: tableFeatures.requireWhere,\n filterCtx,\n txCtx: mutationTxCtx,\n })\n : undefined;\n const aggregateType = tableFeatures.aggregates\n ? generateAggregateTypes(schema[tableName] as SQLiteTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = tableFeatures.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n tablePolicies,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n tableFeatures.aggregates && tableFeatures.groupBy\n ? generateGroupByType(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 tablePolicies,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: listFieldComplexity(complexity, limits?.(tableName)) } : {}),\n },\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'query', operation: 'select', single: true, targetArg: 'where' }),\n },\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'aggregate', single: true, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'aggregate', operation: 'groupBy', single: false, targetArg: 'where' }),\n ...(complexity ? { complexity: aggregateFieldComplexity(complexity) } : {}),\n },\n };\n }\n if (insertArrGenerated) {\n mutations[insertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: insertArrGenerated.args,\n resolve: insertArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'insert', single: false, targetArg: 'values' }),\n },\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 extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'insert', single: true, targetArg: 'values' }),\n },\n };\n }\n if (upsertArrGenerated) {\n mutations[upsertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: upsertArrGenerated.args,\n resolve: upsertArrGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'upsert', single: false, targetArg: 'values' }),\n },\n };\n }\n if (upsertSingleGenerated) {\n mutations[upsertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: upsertSingleGenerated.args,\n resolve: upsertSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'upsert', single: true, targetArg: 'values' }),\n },\n };\n }\n if (updateGenerated) {\n mutations[updateGenerated.name] = {\n type: arrTableItemOutput,\n args: updateGenerated.args,\n resolve: updateGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'update', single: false, targetArg: 'where' }),\n },\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 extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'updateMany', single: false, targetArg: 'updates' }),\n },\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 extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'update', single: true, targetArg: 'where' }),\n },\n };\n }\n if (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'delete', single: false, targetArg: 'where' }),\n },\n };\n }\n if (deleteSingleGenerated) {\n mutations[deleteSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: deleteSingleGenerated.args,\n resolve: deleteSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'delete', single: true, targetArg: 'where' }),\n },\n };\n }\n if (restoreGenerated) {\n mutations[restoreGenerated.name] = {\n type: arrTableItemOutput,\n args: restoreGenerated.args,\n resolve: restoreGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'restore', single: false, targetArg: 'where' }),\n },\n };\n }\n if (restoreSingleGenerated) {\n mutations[restoreSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: restoreSingleGenerated.args,\n resolve: restoreSingleGenerated.resolver,\n extensions: {\n drizzle: drizzleMeta({ kind: 'mutation', operation: 'restore', single: true, targetArg: 'where' }),\n },\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 ...(tableFeatures.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(tableFeatures.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","import { is, Table } from 'drizzle-orm';\nimport { getTableConfig as getMySqlTableConfig, MySqlDatabase } from 'drizzle-orm/mysql-core';\nimport { getTableConfig as getPgTableConfig, PgAsyncDatabase } from 'drizzle-orm/pg-core';\nimport { BaseSQLiteDatabase, getTableConfig as getSQLiteTableConfig } from 'drizzle-orm/sqlite-core';\nimport type { GraphQLResolveInfo } from 'graphql';\nimport { parseResolveInfo, type ResolveTree } from 'graphql-parse-resolve-info';\nimport type { AnyDrizzleDB } from '../types.ts';\nimport {\n attachTargetPrimaryKeys,\n buildNamedRelations,\n extractRelationsParams,\n getPrimaryKeyPropNamesFromConfig,\n type RelationFilterBase,\n resolveTypeName,\n runRelationalSelect,\n type TypeNameMapper,\n} from './builders/common.ts';\nimport type { TableNamedRelations } from './builders/types.ts';\n\n/**\n * Everything the translation needs about a drizzle instance: the tables it holds, the\n * relation graph in this library's canonical shape, and the filter context that lets a\n * nested `where` reach a relation's target table. Derived once per instance — the same\n * derivation `buildSchema` does — and cached, since an overriding resolver calls this on\n * every request.\n */\ntype SelectionContext = {\n tables: Record<string, Table>;\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n filterCtx: RelationFilterBase;\n primaryKeyOf: (tableName: string) => readonly string[];\n};\n\nconst contextCache = new WeakMap<object, SelectionContext>();\n\n/** The dialect's `getTableConfig`, which is the only place a composite primary key shows up. */\nconst tableConfigFor = (db: AnyDrizzleDB<any>) => {\n if (is(db, MySqlDatabase)) {\n return getMySqlTableConfig as (table: Table) => { primaryKeys: { columns: { name: string }[] }[] };\n }\n if (is(db, PgAsyncDatabase)) {\n return getPgTableConfig as unknown as (table: Table) => { primaryKeys: { columns: { name: string }[] }[] };\n }\n if (is(db, BaseSQLiteDatabase)) {\n return getSQLiteTableConfig as unknown as (table: Table) => { primaryKeys: { columns: { name: string }[] }[] };\n }\n throw new Error('Drizzle-GraphQL Error: unsupported database instance — expected a PostgreSQL, MySQL or SQLite one.');\n};\n\nconst contextFor = (db: AnyDrizzleDB<any>): SelectionContext => {\n const cached = contextCache.get(db as object);\n if (cached) {\n return cached;\n }\n\n const relations = (db as any)._.relations ?? {};\n // Same reconstruction `buildSchema` does: PG no longer exposes `fullSchema`, so the table\n // map is rebuilt from the relations config, whose entries each carry their table.\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 const tableEntries = Object.entries(schema as Record<string, unknown>).filter(([, value]) => is(value, Table)) as [\n string,\n Table,\n ][];\n if (!tableEntries.length) {\n throw new Error(\n 'Drizzle-GraphQL Error: Schema not found in drizzle instance. Pass relations (from buildRelations/defineRelations) to the drizzle constructor so drizzle-graphql can read your tables.',\n );\n }\n\n const tables = Object.fromEntries(tableEntries);\n const getTableConfig = tableConfigFor(db);\n const primaryKeyCache = new Map<string, readonly string[]>();\n const primaryKeyOf = (tableName: string): readonly string[] => {\n let pk = primaryKeyCache.get(tableName);\n if (!pk) {\n const table = tables[tableName];\n pk = table ? getPrimaryKeyPropNamesFromConfig(table, getTableConfig) : [];\n primaryKeyCache.set(tableName, pk);\n }\n return pk;\n };\n\n const relationMap = buildNamedRelations(relations, tableEntries);\n // Paginated relations fall back to a primary-key order, which is resolved once per target\n // and hung off the relation entry — exactly as the generated schema does it.\n attachTargetPrimaryKeys(relationMap, tables, (table) => [...primaryKeyOf(tableNameOf(tables, table))]);\n\n const context: SelectionContext = {\n tables,\n relationMap,\n filterCtx: { tables, relationMap },\n primaryKeyOf,\n };\n contextCache.set(db as object, context);\n return context;\n};\n\n/** Reverse lookup for `attachTargetPrimaryKeys`, which hands back the table, not its key. */\nconst tableNameOf = (tables: Record<string, Table>, table: Table): string =>\n Object.keys(tables).find((name) => tables[name] === table) ?? '';\n\n/** Options shared by {@link selectionToWith} and {@link resolveSelection}. */\nexport type SelectionOptions = {\n /** The drizzle instance the schema was built from. */\n db: AnyDrizzleDB<any>;\n /** The Drizzle schema key of the table the selection is rooted at. */\n table: string;\n /**\n * The `typeNameMapper` the schema was built with, when one was configured. The translation\n * matches selections against GraphQL type names, so a build that renames its types has to\n * pass the same mapper here or nothing will match.\n */\n typeNameMapper?: TypeNameMapper;\n};\n\n/**\n * Reads the parsed selection tree out of a resolver's `info`, resolving fragments and\n * inline fragments. Accepts an already-parsed tree so a caller that has one (or is chaining\n * these helpers) does not pay for the walk twice.\n */\nconst parseInfo = (info: GraphQLResolveInfo | ResolveTree): ResolveTree | undefined => {\n if ('fieldsByTypeName' in info) {\n return info as ResolveTree;\n }\n return parseResolveInfo(info, { deep: true }) as ResolveTree | undefined;\n};\n\n/**\n * Translates a GraphQL selection set into the relational query builder's `with` tree — the\n * same translation the generated resolvers use for their own queries.\n *\n * A resolver that replaces a generated one has to return a row shaped like the type it\n * replaced, and the field resolvers underneath only fill in relations the parent did not\n * already provide. Reproducing that by hand means resolving fragments against\n * `info.fragments`, intersecting selection names against the relations config (so scalars\n * and consumer-added fields drop out instead of becoming invalid `with` keys), following\n * aliases, compiling each relation's `where` / `orderBy` / `limit` / `offset` arguments into\n * its nested entry, and leaving `<relation>Aggregate` selections out — they are not `with`\n * entries at all. This does all of it.\n *\n * ```ts\n * const withTree = selectionToWith(info, { db, table: 'Users' });\n * const row = await tx.query.Users.findFirst({ where: { id: { eq } }, with: withTree });\n * ```\n *\n * Returns `undefined` when the selection asks for no relations, which is the value the\n * query builder wants for \"no `with` clause\".\n */\nexport const selectionToWith = (\n info: GraphQLResolveInfo | ResolveTree,\n options: SelectionOptions,\n): Record<string, any> | undefined => {\n const { db, table, typeNameMapper } = options;\n const { tables, relationMap, filterCtx } = contextFor(db);\n if (!tables[table]) {\n throw new Error(`Drizzle-GraphQL Error: '${table}' is not a table in the Drizzle schema.`);\n }\n if (!relationMap[table]) {\n return undefined;\n }\n\n const parsed = parseInfo(info);\n const params = extractRelationsParams(\n relationMap,\n tables,\n table,\n parsed,\n resolveTypeName(table, typeNameMapper),\n typeNameMapper,\n filterCtx,\n );\n // A selection with no relations in it gets no `with` clause at all, rather than an empty\n // object the query builder would have to be asked to ignore.\n return params && Object.keys(params).length ? params : undefined;\n};\n\n/** Options for {@link resolveSelection} — the selection options plus the read itself. */\nexport type ResolveSelectionOptions = SelectionOptions & {\n /**\n * The transaction (or other drizzle executor) to read on. Defaults to `db`, so an override\n * that has opened its own transaction passes it here to see its own uncommitted writes.\n */\n executor?: any;\n /** Whether to return one row or a list. A single read ignores `limit`. */\n single?: boolean;\n /** The generated `where` argument, in the schema's filter DSL — compiled the same way. */\n where?: any;\n /** The generated `orderBy` argument. */\n orderBy?: any;\n limit?: number;\n offset?: number;\n /** The generated `after` cursor argument, for keyset pagination. */\n after?: string;\n};\n\n/**\n * Runs the read a generated select resolver would have run, against whichever executor is\n * given — the whole body, not just the `with` tree: selected columns, relation arguments,\n * eager loading, cursor pagination, and the transport remapping of the result.\n *\n * This is what an override usually wants after it has done its own work:\n *\n * ```ts\n * const rows = await resolveSelection(info, { db, table: 'Users', where, executor: tx });\n * ```\n *\n * Relation arguments and aggregate fields keep behaving as they do in the generated schema,\n * because it is the generated schema's own code path.\n */\nexport const resolveSelection = async (\n info: GraphQLResolveInfo | ResolveTree,\n options: ResolveSelectionOptions,\n): Promise<any> => {\n const {\n db,\n table: tableName,\n typeNameMapper,\n executor,\n single = false,\n where,\n orderBy,\n limit,\n offset,\n after,\n } = options;\n const { tables, relationMap, filterCtx, primaryKeyOf } = contextFor(db);\n const table = tables[tableName];\n if (!table) {\n throw new Error(`Drizzle-GraphQL Error: '${tableName}' is not a table in the Drizzle schema.`);\n }\n\n const parsedInfo = parseInfo(info);\n if (!parsedInfo) {\n throw new Error('Drizzle-GraphQL Error: resolveSelection could not read a selection set from the resolve info.');\n }\n\n const source = executor ?? db;\n const queryBase = (source as any).query?.[tableName];\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: the executor passed to resolveSelection has no relational query builder for '${tableName}'.`,\n );\n }\n\n return runRelationalSelect({\n queryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName: resolveTypeName(tableName, typeNameMapper),\n typeNameMapper,\n parsedInfo,\n single,\n where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AAe,IAAI,+BAAc,mBAAmB;AAE1D,SAAO,EAAE,QAAQ,cAAc,UAAU,gBAAgB;AAC3D;","names":["import_drizzle_orm","import_mysql_core","import_pg_core","import_sqlite_core","import_graphql","import_drizzle_orm","import_graphql","pluralize","import_drizzle_orm","import_graphql","import_graphql","column","operators","import_drizzle_orm","import_graphql","isJsonColumn","aliasedTable","getTableConfig","targetNames","set","result","import_drizzle_orm","import_mysql_core","import_graphql","import_graphql_parse_resolve_info","import_drizzle_orm","import_graphql","import_drizzle_orm","import_pg_core","import_graphql","import_graphql_parse_resolve_info","import_drizzle_orm","import_graphql","generateSelectArray","generateSelectSingle","generateInsertArray","generateInsertSingle","generateUpsert","generateUpdate","generateUpdateMany","generateDelete","generateSchemaData","import_drizzle_orm","import_sqlite_core","import_graphql","import_graphql_parse_resolve_info","generateSelectArray","generateSelectSingle","generateInsertArray","generateInsertSingle","generateUpsert","generateUpdate","generateUpdateMany","results","generateDelete","generateSchemaData","import_drizzle_orm","import_mysql_core","import_pg_core","import_sqlite_core","import_graphql_parse_resolve_info","getMySqlTableConfig","getPgTableConfig","getSQLiteTableConfig","getTableConfig","config","generateSchemaData"]}
|