@vantreeseba/drizzle-graphql 5.2.0 → 5.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -0
- package/dist/README.md +47 -0
- package/dist/index.cjs +493 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +39 -1
- package/dist/index.d.ts +39 -1
- package/dist/index.js +494 -12
- 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/scalars/index.ts","../src/util/type-converter/index.ts","../src/util/builders/mysql.ts","../src/util/builders/aggregates.ts","../src/util/builders/pg.ts","../src/util/builders/sqlite.ts"],"sourcesContent":["import { is } from 'drizzle-orm';\nimport { MySqlDatabase } from 'drizzle-orm/mysql-core';\nimport { PgAsyncDatabase } from 'drizzle-orm/pg-core';\nimport { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';\nimport {\n type GraphQLFieldConfig,\n type GraphQLInputObjectType,\n GraphQLObjectType,\n GraphQLSchema,\n type GraphQLSchemaConfig,\n} from 'graphql';\nimport type { AnyDrizzleDB, BuildSchemaConfig, GeneratedData } from './types.ts';\nimport { applyErrorMapper, defaultErrorMapper } from './util/builders/common.ts';\nimport { generateMySQL, generatePG, generateSQLite } from './util/builders/index.ts';\nimport type { SchemaGeneratorOptions } from './util/builders/types.ts';\n\nexport type {\n AggregateResolver,\n AnyDrizzleDB,\n BuildSchemaConfig,\n ComplexityConfig,\n DeleteResolver,\n DeleteSingleResolver,\n ExtractRelations,\n ExtractTableByName,\n ExtractTableRelations,\n ExtractTables,\n GeneratedData,\n GeneratedEntities,\n GeneratedInputs,\n GeneratedOutputs,\n InsertArrResolver,\n InsertResolver,\n MutationReturnlessResult,\n MutationsCore,\n QueriesCore,\n SchemaFeatures,\n SelectResolver,\n SelectSingleResolver,\n UpdateResolver,\n UpdateSingleResolver,\n UpsertArgs,\n UpsertArrResolver,\n UpsertConflictArgs,\n UpsertResolver,\n} from './types.ts';\nexport type { RelationResolverFactory } from './util/builders/common.ts';\nexport {\n createRelationResolverFactory,\n defaultErrorMapper,\n drizzleExecutorKey,\n extractFilters,\n extractOrderBy,\n extractRelationJoinColumns,\n} from './util/builders/common.ts';\nexport type { TableNamedRelations } from './util/builders/types.ts';\nexport {\n GraphQLBigIntString,\n GraphQLDate,\n GraphQLDateTime,\n GraphQLDecimalString,\n GraphQLJSON,\n GraphQLUUID,\n} from './util/scalars/index.ts';\n\ntype ObjMap<T> = Record<string, T>;\n\nexport const buildSchema = <TDbClient extends AnyDrizzleDB<any>>(\n db: TDbClient,\n config?: BuildSchemaConfig,\n): GeneratedData<TDbClient> => {\n const relations = db._.relations;\n // drizzle-orm v1 rc.2 removed fullSchema from PgAsyncDatabase._\n // For PG, reconstruct a schema-like map from db._.relations (each entry has { table }).\n // MySQL and SQLite still expose fullSchema directly.\n const schema =\n (db._ as any).fullSchema ??\n Object.fromEntries(\n Object.entries(relations as Record<string, any>)\n .filter(([, config]) => config?.table != null)\n .map(([key, config]) => [key, config.table]),\n );\n\n if (!schema || !Object.keys(schema).length) {\n throw new Error(\n 'Drizzle-GraphQL Error: Schema not found in drizzle instance. Pass relations (from buildRelations/defineRelations) to the drizzle constructor so drizzle-graphql can detect your tables.',\n );\n }\n\n const prefixes = {\n insert: config?.prefixes?.insert ?? 'create',\n delete: config?.prefixes?.delete ?? 'delete',\n update: config?.prefixes?.update ?? 'update',\n upsert: config?.prefixes?.upsert ?? 'upsert',\n };\n\n const suffixes = {\n list: config?.suffixes?.list ?? '',\n single: config?.suffixes?.single ?? 'Single',\n };\n\n const typeNameMapper = config?.typeNameMapper;\n\n // Every feature is on unless the caller says otherwise, so a build without a `features`\n // block generates what it always did — except upsert, which is new surface and so has to\n // be asked for.\n const features = {\n aggregates: config?.features?.aggregates ?? true,\n groupBy: config?.features?.groupBy ?? true,\n relationAggregates: config?.features?.relationAggregates ?? true,\n distinct: config?.features?.distinct ?? true,\n insert: config?.features?.insert ?? true,\n update: config?.features?.update ?? true,\n delete: config?.features?.delete ?? true,\n upsert: config?.features?.upsert ?? false,\n requireWhere: config?.features?.requireWhere ?? false,\n };\n\n // Cost hints are inert without a complexity rule installed, so they are generated unless the\n // caller opts out.\n const complexityConfig = config?.complexity ?? true;\n const complexity =\n complexityConfig === false\n ? undefined\n : {\n defaultListSize: (complexityConfig === true ? undefined : complexityConfig.defaultListSize) ?? 10,\n aggregateCost: (complexityConfig === true ? undefined : complexityConfig.aggregateCost) ?? 10,\n };\n\n // Normalize eagerLoadRelations (boolean | predicate | undefined) into a predicate.\n const eagerOpt = config?.eagerLoadRelations;\n const shouldEagerLoad: (tableName: string, relationName: string) => boolean =\n eagerOpt === undefined || eagerOpt === true ? () => true : eagerOpt === false ? () => false : eagerOpt;\n\n // When a typeNameMapper is provided, the mapper's singular/plural forms disambiguate the\n // list and single fields even if the suffixes are identical (e.g. both '').\n // Only enforce the suffix-collision check when no mapper is active.\n if (!typeNameMapper && suffixes.list === suffixes.single) {\n throw new Error(\n 'Drizzle-GraphQL Error: List and single query suffixes cannot be the same. This would create conflicting GraphQL field names.',\n );\n }\n\n if (typeof config?.relationsDepthLimit === 'number') {\n if (config.relationsDepthLimit < 0) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.relationsDepthLimit is supposed to be nonnegative integer or undefined!',\n );\n }\n if (config.relationsDepthLimit !== ~~config.relationsDepthLimit) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.relationsDepthLimit is supposed to be nonnegative integer or undefined!',\n );\n }\n }\n\n const generatorOptions: SchemaGeneratorOptions = {\n relationsDepthLimit: config?.relationsDepthLimit,\n prefixes,\n suffixes,\n conflictDoNothing: config?.conflictDoNothing ?? false,\n typeNameMapper,\n shouldEagerLoad,\n features,\n complexity,\n };\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 getColumns,\n getTableAsAliasSQL,\n gt,\n gte,\n ilike,\n inArray,\n is,\n isNotNull,\n isNull,\n like,\n lt,\n lte,\n ne,\n not,\n notIlike,\n notInArray,\n notLike,\n One,\n or,\n relationsFilterToSQL,\n type SQL,\n sql,\n} from 'drizzle-orm';\nimport type { GraphQLFieldResolver } from 'graphql';\nimport {\n GraphQLBoolean,\n GraphQLEnumType,\n GraphQLError,\n GraphQLFloat,\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n 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 { GraphQLBigIntString, GraphQLDecimalString, GraphQLJSON, GraphQLUUID } from '../scalars/index.ts';\nimport { drizzleColumnToGraphQLType } from '../type-converter/index.ts';\nimport type {\n ConvertedColumn,\n ConvertedInputColumn,\n ConvertedRelationColumnWithArgs,\n} from '../type-converter/types.ts';\nimport type {\n FilterColumnOperators,\n FilterColumnOperatorsCore,\n Filters,\n FiltersCore,\n GeneratedTableTypes,\n GeneratedTableTypesOutputs,\n OrderByArgs,\n ProcessedTableSelectArgs,\n SelectData,\n SelectedColumnsRaw,\n SelectedSQLColumns,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst rqbCrashTypes = ['SQLiteBigInt', 'SQLiteBlobJson', 'SQLiteBlobBuffer'];\n\n/** Optional mapper from table key to singular/plural name pair. Return undefined to use default naming for a table. */\nexport type TypeNameMapper = (tableName: string) => { singular: string; plural: string } | undefined;\n\n/** Produce the GraphQL object type name for a table, using the mapper if provided. */\nexport const resolveTypeName = (name: string, typeNameMapper?: TypeNameMapper): string => {\n const mapped = typeNameMapper?.(name);\n return mapped ? capitalize(mapped.singular) : capitalize(name);\n};\n\n/**\n * Shape of the relational config from drizzle-orm v1 db._.relations.\n * Each entry has { table, name, relations }.\n */\ninterface TableRelationalConfig {\n table: Table;\n name: string;\n relations: Record<string, Relation<string>>;\n}\nexport type TablesRelationalConfig = Record<string, TableRelationalConfig>;\n\n/**\n * Flatten drizzle-orm v1 TablesRelationalConfig into the canonical\n * Record<tableName, Record<relName, TableNamedRelations>> shape used\n * throughout common.ts. Both pg.ts and sqlite.ts call this before\n * passing the relation map to any shared function.\n */\nexport const buildNamedRelations = (\n relations: TablesRelationalConfig,\n tableEntries: [string, Table][],\n): Record<string, Record<string, TableNamedRelations>> => {\n const namedRelations: Record<string, Record<string, TableNamedRelations>> = {};\n\n for (const [relTableName, relConfig] of Object.entries(relations)) {\n if (!relConfig?.relations) {\n continue;\n }\n\n const namedConfig: Record<string, TableNamedRelations> = {};\n\n for (const [innerRelName, innerRelValue] of Object.entries(relConfig.relations)) {\n // drizzle-orm v1 uses `targetTable` (not `referencedTable`)\n // and provides `targetTableName` directly.\n const targetTable = (innerRelValue as any).targetTable ?? (innerRelValue as any).referencedTable;\n const directTargetName = (innerRelValue as any).targetTableName as string | undefined;\n\n let targetTableName: string | undefined;\n\n if (directTargetName) {\n // v1: use the direct name to find the schema key\n const targetEntry = tableEntries.find(([key]) => key === directTargetName);\n targetTableName = targetEntry?.[0];\n } else if (targetTable) {\n // fallback: match by object reference\n const targetEntry = tableEntries.find(([, tableValue]) => tableValue === targetTable);\n targetTableName = targetEntry?.[0];\n }\n\n if (!targetTableName) {\n continue;\n }\n\n namedConfig[innerRelName] = {\n relation: innerRelValue,\n targetTableName,\n };\n }\n\n if (Object.keys(namedConfig).length > 0) {\n namedRelations[relTableName] = namedConfig;\n }\n }\n\n return namedRelations;\n};\n\n/**\n * Records each relation's target-table primary-key property names on the relation entry,\n * so the pagination paths (the window-function batch loader and the eager `with:` orderBy\n * default) can fall back to a deterministic PK order without re-deriving it per request.\n *\n * Composite primary keys are only visible through the dialect's getTableConfig, so the\n * dialect builder passes a `resolvePkNames` that threads the composite column names in.\n * Mutates the relation entries in place (they are shared with the pruned eager map and\n * the resolver factory, so attaching once covers every consumer).\n */\nexport const attachTargetPrimaryKeys = (\n namedRelations: Record<string, Record<string, TableNamedRelations>>,\n tables: Record<string, Table>,\n resolvePkNames: (table: Table) => string[],\n): void => {\n const cache = new Map<string, readonly string[]>();\n for (const rels of Object.values(namedRelations)) {\n for (const relEntry of Object.values(rels)) {\n const { targetTableName } = relEntry;\n let pk = cache.get(targetTableName);\n if (!pk) {\n const targetTable = tables[targetTableName];\n pk = targetTable ? resolvePkNames(targetTable) : [];\n cache.set(targetTableName, pk);\n }\n relEntry.targetPkNames = pk;\n }\n }\n};\n\n/**\n * Extracts the join column info from a drizzle-orm v1 Relation object.\n * Returns the JS property name of the local column on the parent table and the\n * Column object for the foreign column on the target table, or undefined if the\n * relation internals are not accessible.\n */\nexport const extractRelationJoinColumns = (\n relEntry: TableNamedRelations,\n parentTable: Table,\n targetTable: Table,\n): { localColPropName: string; foreignCol: Column; foreignColPropName: string } | undefined => {\n const rel = (relEntry as any).relation ?? relEntry;\n const sourceColumns: any[] | undefined = rel.sourceColumns;\n const targetColumns: any[] | undefined = rel.targetColumns;\n\n if (!sourceColumns?.length || !targetColumns?.length) {\n return undefined;\n }\n\n const sourceCol = sourceColumns[0];\n const targetCol = targetColumns[0];\n\n const parentCols = getColumns(parentTable);\n const localColPropName = Object.entries(parentCols).find(([, c]) => c === sourceCol)?.[0];\n\n const targetCols = getColumns(targetTable);\n const foreignColPropName = Object.entries(targetCols).find(([, c]) => c === targetCol)?.[0];\n\n if (!localColPropName || !foreignColPropName) {\n return undefined;\n }\n\n return { localColPropName, foreignCol: targetCol, foreignColPropName };\n};\n\nexport type RelationResolverFactory = (params: {\n tableName: string;\n relationName: string;\n relEntry: TableNamedRelations;\n isOne: boolean;\n}) => GraphQLFieldResolver<any, any> | undefined;\n\n/**\n * Builds the `${relationName}Aggregate` field for a to-many relation. Implemented in\n * `aggregates.ts` and injected here so the aggregate code can depend on this module\n * without the two importing each other.\n */\nexport type RelationAggregateFactory = (params: {\n tableName: string;\n relationName: string;\n relEntry: TableNamedRelations;\n}) => { type: GraphQLObjectType; resolve: GraphQLFieldResolver<any, any> } | undefined;\n\n/**\n * Key on the GraphQL context object under which a caller can place a Drizzle transaction\n * (or any other executor: a pooled connection, a logging proxy). Every generated resolver\n * reads it at resolve time and runs its statements there instead of on the database the\n * schema was built from, which is what lets several mutations in one request share a\n * transaction and lets a query see that transaction's uncommitted rows:\n *\n * ```ts\n * await db.transaction(async (tx) => {\n * await graphql({ schema, source, contextValue: { [drizzleExecutorKey]: tx } });\n * });\n * ```\n *\n * Registered with `Symbol.for` so the ESM and CJS builds of this package agree on it when\n * both end up loaded in one process.\n */\nexport const drizzleExecutorKey: unique symbol = Symbol.for('drizzle-graphql:executor') as any;\n\n/**\n * The executor a resolver should run on: the request's transaction when the context\n * carries one, otherwise the database the schema was built from.\n */\nexport const resolveExecutor = <T>(db: T, context: any): T => {\n if (context && typeof context === 'object') {\n const executor = context[drizzleExecutorKey];\n if (executor) {\n return executor as T;\n }\n }\n return db;\n};\n\n/**\n * This request's executor together with the relational query builder to select through.\n *\n * `buildTimeQueryBase` decides whether the table supports the relational query builder at\n * all — a table with no relations has none, and the caller falls back to a plain select.\n * The executor only decides which connection the query runs on, so a transaction that is\n * missing `query` (or a table absent from its schema) keeps the build-time builder.\n */\nexport const resolveQueryExecutor = (\n db: any,\n context: any,\n tableName: string,\n buildTimeQueryBase: any,\n): { executor: any; queryBase: any } => {\n const executor = resolveExecutor(db, context);\n return {\n executor,\n queryBase: buildTimeQueryBase ? (executor?.query?.[tableName] ?? buildTimeQueryBase) : buildTimeQueryBase,\n };\n};\n\n/**\n * Fetches a to-many relation with per-parent limit/offset for ALL parents in a\n * single query, using a window function (ROW_NUMBER() OVER (PARTITION BY fk ...)).\n *\n * This replaces the previous per-parent fallback that issued one query per parent\n * (true N+1) whenever pagination args were present. Each parent gets its own\n * limit/offset window while the database is hit exactly once for the whole batch.\n *\n * Window functions require PostgreSQL, MySQL >= 8.0, or SQLite >= 3.25.\n * Returns raw rows (NOT remapped); the caller groups + remaps them.\n */\nconst batchedPaginatedRelationQuery = async (\n db: any,\n targetTable: Table,\n foreignCol: Column,\n whereCondition: SQL | undefined,\n orderByArg: any,\n limit: number | null,\n offset: number | null,\n pkNames: readonly string[],\n orderCtx?: RelationFilterContext,\n): Promise<any[]> => {\n const cols = getColumns(targetTable);\n\n // Always tiebreak the window by the target's primary key so per-parent limit/offset\n // slices are deterministic even when the client supplies no (or a non-unique) orderBy.\n // pkNames is resolved at build time and includes composite keys.\n const orderExprs = [\n ...(orderByArg ? extractOrderBy(targetTable, orderByArg, orderCtx) : []),\n ...primaryKeyOrderExprs(targetTable, pkNames),\n ];\n const orderClause = orderExprs.length ? sql` order by ${sql.join(orderExprs, sql`, `)}` : sql``;\n // Namespaced alias so it can't collide with a real column on the target table.\n const RN = '__drizzle_graphql_rn';\n const rowNumber = sql`row_number() over (partition by ${foreignCol}${orderClause})`.as(RN);\n\n // Subquery: every target column plus a per-partition row number.\n const sub = db\n .select({ ...cols, [RN]: rowNumber })\n .from(targetTable)\n .where(whereCondition)\n .as('__paginated');\n\n // Outer: keep only the rows that fall inside each parent's window.\n const lower = offset ?? 0;\n const windowConds: any[] = [gt(sub[RN], lower)];\n if (limit != null) {\n windowConds.push(lte(sub[RN], lower + limit));\n }\n\n const rows: any[] = await db\n .select()\n .from(sub)\n .where(and(...windowConds))\n .orderBy(sub[RN]);\n\n // Strip the helper column so it doesn't leak into remapping/output.\n for (const row of rows) {\n delete row[RN];\n }\n return rows;\n};\n\n/**\n * Creates a RelationResolverFactory that generates field-level resolvers for each relation.\n * Each resolver:\n * 1. Returns pre-fetched data if the parent resolver already included it (eager path, zero cost).\n * 2. When limit/offset args are present, falls back to a direct per-item query.\n * 3. Otherwise batches all sibling resolver calls within the same GraphQL execution tick\n * into a single IN-clause query, eliminating N+1 database round-trips.\n */\nexport const createRelationResolverFactory =\n (db: any, tables: Record<string, Table>, filterCtx?: RelationFilterBase): RelationResolverFactory =>\n ({ tableName, relationName, relEntry, isOne }) => {\n const parentTable = tables[tableName];\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n\n if (!parentTable || !targetTable) {\n return undefined;\n }\n\n const joinCols = extractRelationJoinColumns(relEntry, parentTable, targetTable);\n if (!joinCols) {\n return undefined;\n }\n\n const { localColPropName, foreignCol, foreignColPropName } = joinCols;\n // Resolved at build time (composite keys included) — used to tiebreak paginated batches.\n const targetPkNames = relEntry.targetPkNames ?? [];\n\n return async (parent, args, context) => {\n // Eager path: the parent resolver pre-fetched this relation via Drizzle's `with`.\n if (parent[relationName] !== undefined) {\n return parent[relationName];\n }\n\n const localValue = parent[localColPropName];\n if (localValue == null) {\n return isOne ? null : [];\n }\n\n const { where: whereArg, orderBy: orderByArg, limit, offset } = (args ?? {}) as any;\n\n // Batch path: collect all sibling calls in this tick and execute one query.\n // Pagination args are part of the loader key so siblings sharing identical\n // args batch together; per-parent limit/offset is applied inside the batch\n // via a window function rather than bailing to a per-parent query (N+1).\n const argsKey = JSON.stringify({\n where: whereArg ?? null,\n orderBy: orderByArg ?? null,\n limit: limit ?? null,\n offset: offset ?? null,\n });\n const loaderKey = `${tableName}::${relationName}::${argsKey}`;\n\n const loader = getOrCreateLoader(context, loaderKey, async (parentIds: readonly any[]) => {\n // Loaders are cached per context, so every call batched here shares this request's\n // executor — the transaction on the context, when there is one.\n const executor = resolveExecutor(db, context);\n const uniqueIds = [...new Set(parentIds)];\n const whereCondition = and(\n inArray(foreignCol, uniqueIds),\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n );\n\n let rows: any[];\n if (limit != null || offset != null) {\n // Per-parent pagination across the whole batch in one query.\n rows = await batchedPaginatedRelationQuery(\n executor,\n targetTable,\n foreignCol,\n whereCondition,\n orderByArg,\n limit ?? null,\n offset ?? null,\n targetPkNames,\n relationFilterCtx(filterCtx, targetTableName),\n );\n } else {\n // Use plain db.select() so column refs are never aliased — avoids drizzle-orm v1\n // RQB aliasing requirements that would require referencing via aliasedTable proxy.\n let q = executor.select().from(targetTable).where(whereCondition) as any;\n if (orderByArg) {\n q = q.orderBy(...extractOrderBy(targetTable, orderByArg, relationFilterCtx(filterCtx, targetTableName)));\n }\n rows = await q;\n }\n\n // Group by FK value before remapping (remapping may delete null fields).\n if (isOne) {\n const byKey = new Map(rows.map((row: any) => [String(row[foreignColPropName]), row]));\n remapToGraphQLArrayOutput(rows, targetTableName, targetTable);\n return parentIds.map((id) => byKey.get(String(id)) ?? null);\n }\n\n const grouped = new Map<string, any[]>(uniqueIds.map((id) => [String(id), []]));\n for (const row of rows) {\n grouped.get(String(row[foreignColPropName]))?.push(row);\n }\n remapToGraphQLArrayOutput(rows, targetTableName, targetTable);\n return parentIds.map((id) => grouped.get(String(id)) ?? []);\n });\n\n return loader.load(localValue);\n };\n };\n\n/** Per-call cache context — created fresh on each generateSchemaData call to avoid type name collisions. */\nexport interface TypeCacheCtx {\n /** Cache of generic filter types, keyed by generic name (e.g. \"String\", \"DateTime\"). */\n genericFilterCache: Map<string, GraphQLInputObjectType>;\n /**\n * Cache of shared select object types, keyed by table name.\n * Value: the ${capitalize(tableName)} type (columns + relation fields).\n * A table may be pre-registered here as a columns-only shell before its root call runs.\n * Use fullyBuiltTables to distinguish a complete type from a pre-registered shell.\n */\n objectTypeCache: Map<string, GraphQLObjectType>;\n /**\n * Mutable containers for relation fields, keyed by table name.\n * Each container object is closed over by the corresponding GraphQLObjectType thunk so that\n * when the root call for a table populates its relation fields, the thunk automatically picks\n * them up — even if the shell was pre-registered by a different table's relation traversal.\n */\n relationFieldContainers: Map<string, { fields: Record<string, ConvertedRelationColumnWithArgs> }>;\n /**\n * Set of table names whose GraphQL object type has been fully built (root call completed).\n * Pre-registered shells (created when another table references this table as a relation target)\n * are NOT in this set until the root call for that table runs.\n */\n fullyBuiltTables: Set<string>;\n /**\n * Cache of relation types, keyed by \"${fromTableName}::${relName}\".\n * @deprecated No longer used — relation fields now reference the target table's own type directly.\n */\n relationTypeCache: Map<string, GraphQLObjectType>;\n /** 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\n/** The shape `graphql-query-complexity`'s `fieldExtensionsEstimator` hands to a field's hint. */\nexport type ComplexityEstimatorArgs = { args: Record<string, any>; childComplexity: number };\n\n/** A field's cost hint, published as `extensions.complexity` on the generated field config. */\nexport type ComplexityEstimator = (options: ComplexityEstimatorArgs) => number;\n\n/** {@link BuildSchemaConfig.complexity} with its defaults filled in. */\nexport type ResolvedComplexityOptions = {\n /** Rows a list field is assumed to return when the query passes no `limit`. */\n defaultListSize: number;\n /** Flat cost charged for an aggregate field, on top of the fields selected inside it. */\n aggregateCost: number;\n};\n\n/**\n * A paginated field costs its page size times whatever one row of it costs, so `users(limit: 100)\n * { posts(limit: 10) { id } }` is charged for the thousand rows it can return rather than the two\n * fields it mentions. `childComplexity` floors at 1 so a row is never free.\n */\nexport const listFieldComplexity =\n (options: ResolvedComplexityOptions): ComplexityEstimator =>\n ({ args, childComplexity }) => {\n const limit = args['limit'];\n const rows = typeof limit === 'number' && limit > 0 ? limit : options.defaultListSize;\n return rows * Math.max(childComplexity, 1);\n };\n\n/**\n * An aggregate returns a single row but reads however many match, so its cost tracks the scan\n * rather than the response.\n */\nexport const aggregateFieldComplexity =\n (options: ResolvedComplexityOptions): ComplexityEstimator =>\n ({ childComplexity }) =>\n options.aggregateCost + childComplexity;\n\n/**\n * Everything needed to work out which extra columns a selection implies. Passed to the column\n * extractors so a requested `<relation>Aggregate` field can pull in the join column it resolves\n * from, which the client has no reason to have selected itself.\n */\nexport interface SelectionCtx {\n tableName: string;\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n tables: Record<string, Table>;\n}\n\nconst AGGREGATE_FIELD_SUFFIX = 'Aggregate';\n\n/**\n * Property names of the join columns that the `<relation>Aggregate` fields in this selection\n * correlate on. Without them the parent row reaches the aggregate resolver with no key and\n * every count would come back 0.\n */\nconst relationAggregateJoinColumns = (\n tree: Record<string, ResolveTree>,\n table: Table,\n selectionCtx: SelectionCtx | undefined,\n): string[] => {\n const relations = selectionCtx?.relationMap[selectionCtx.tableName];\n if (!relations || !selectionCtx) {\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 end in \"Aggregate\" is a column, not a relation aggregate.\n if (tableColumns[fieldData.name] || !fieldData.name.endsWith(AGGREGATE_FIELD_SUFFIX)) {\n continue;\n }\n\n const relEntry = relations[fieldData.name.slice(0, -AGGREGATE_FIELD_SUFFIX.length)];\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 relationAggregateJoinColumns(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 relationAggregateJoinColumns(tree, table, selectionCtx)) {\n selectedColumns.push([columnName, tableColumns[columnName]!]);\n }\n\n if (!selectedColumns.length) {\n const columnKeys = Object.entries(tableColumns);\n const columnName =\n columnKeys.find((e) => rqbCrashTypes.find((haram) => e[1].columnType !== haram))?.[0] ?? columnKeys[0]![0];\n\n selectedColumns.push([columnName, tableColumns[columnName]!]);\n }\n\n return Object.fromEntries(selectedColumns) as Record<string, TColType>;\n};\n\n/**\n * Where NULL values sort relative to non-NULL values. Compiled to native\n * `NULLS FIRST` / `NULLS LAST` on PostgreSQL and SQLite (3.30+); MySQL has no such\n * clause, so there it is emulated with an extra `<expr> IS NULL` sort key ahead of\n * the column itself.\n */\nexport const orderNulls = new GraphQLEnumType({\n name: 'OrderNulls',\n description: 'Where NULL values sort relative to non-NULL values',\n values: {\n first: {\n value: 'first',\n description: 'NULL values sort before all non-NULL values',\n },\n last: {\n value: 'last',\n description: 'NULL values sort after all non-NULL values',\n },\n },\n});\n\nexport const innerOrder = new GraphQLInputObjectType({\n name: 'InnerOrder' as const,\n fields: {\n direction: {\n type: new GraphQLNonNull(\n new GraphQLEnumType({\n name: 'OrderDirection',\n description: 'Order by direction',\n values: {\n asc: {\n value: 'asc',\n description: 'Ascending order',\n },\n desc: {\n value: 'desc',\n description: 'Descending order',\n },\n },\n }),\n ),\n },\n priority: {\n type: new GraphQLNonNull(GraphQLInt),\n description: 'Priority of current field',\n },\n nulls: {\n type: orderNulls,\n description:\n \"Where NULL values sort. Defaults to the database's own rule (PostgreSQL: last on asc, first on desc; MySQL/SQLite: first on asc, last on desc)\",\n },\n } as const,\n});\n\n/** The dialect a column belongs to, inferred from its drizzle columnType string (e.g. 'PgJsonb'). */\nconst columnDialect = (column: Column): 'pg' | 'mysql' | 'sqlite' | undefined => {\n const ct: string = (column as any).columnType ?? '';\n if (ct.startsWith('Pg')) {\n return 'pg';\n }\n if (ct.startsWith('MySql')) {\n return 'mysql';\n }\n if (ct.startsWith('SQLite')) {\n return 'sqlite';\n }\n return undefined;\n};\n\n/** How a column's generic filter input should be shaped, alongside the cache key to store it under. */\ninterface GenericFilterDescriptor {\n name: string;\n kind: 'scalar' | 'json' | 'array';\n}\n\n/**\n * Maps a Drizzle column to the generic filter type to use.\n *\n * Selection is keyed on the column's data type, never its name: a text column named\n * `userId` gets the full String filter (string operators included), while a uuid column\n * gets the lean Id filter whatever it is called.\n * - \"JSON\" → json/jsonb columns (eq/ne + containment, no scalar comparison ops)\n * - `${Element}Array` → array columns, keyed per element type (IntArray, FloatArray,\n * StringArray, …) so arrays with different element types never share\n * one filter input; membership operators instead of scalar comparisons\n * - \"Id\" → uuid-typed columns (no string pattern operators)\n * - \"Boolean\" → boolean columns\n * - \"BigInt\" → bigint columns (BigInt-scalar-typed operators, no string pattern operators)\n * - \"Decimal\" → numeric/decimal columns (Decimal-scalar-typed operators, no string pattern operators)\n * - the enum GraphQL type name → enum columns (still unique per enum)\n * - \"DateTime\" → timestamp and date columns\n * - \"Int\" → integer/serial columns (no string pattern operators)\n * - \"Float\" → real/double columns (no string pattern operators)\n * - \"String\" → all other text/varchar columns\n */\nconst resolveGenericFilterDescriptor = (\n column: Column,\n columnGraphQLType: ReturnType<typeof drizzleColumnToGraphQLType>,\n): GenericFilterDescriptor => {\n // JSON / JSONB columns — structural values with their own operator set.\n if (columnGraphQLType.type === GraphQLJSON) {\n return { name: 'JSON', kind: 'json' };\n }\n // Array columns — keyed per element type so an int[] and a text[] column never share\n // one cached filter input.\n if (columnGraphQLType.type instanceof GraphQLList) {\n let element = columnGraphQLType.type.ofType;\n if (element instanceof GraphQLNonNull) {\n element = element.ofType;\n }\n return { name: `${element.name}Array`, kind: 'array' };\n }\n // Opaque uuid keys — keyed on the column type, not on an `id`/`*Id` naming convention.\n if (columnGraphQLType.type === GraphQLUUID) {\n return { name: 'Id', kind: 'scalar' };\n }\n // Boolean scalar\n if (columnGraphQLType.type === GraphQLBoolean) {\n return { name: 'Boolean', kind: 'scalar' };\n }\n // Enum type — keep unique per enum since values differ\n if (columnGraphQLType.type instanceof GraphQLEnumType) {\n return { name: columnGraphQLType.type.name, kind: 'scalar' };\n }\n // Named numeric-string scalars — give them their own filters so the operators\n // are typed with the scalar (and validated by it) instead of a shared StringFilter.\n if (columnGraphQLType.type === GraphQLBigIntString) {\n return { name: 'BigInt', kind: 'scalar' };\n }\n if (columnGraphQLType.type === GraphQLDecimalString) {\n return { name: 'Decimal', kind: 'scalar' };\n }\n // Date / timestamp columns (check Drizzle internal columnType string)\n const ct: string = (column as any).columnType ?? '';\n if (ct === 'PgTimestamp' || ct === 'PgTimestampString' || ct === 'PgDate') {\n return { name: 'DateTime', kind: 'scalar' };\n }\n // Numeric scalars — distinct names so an int/float column never shares (and never\n // mistypes) the StringFilter, and integer ids keep a filter without string operators.\n // (BigInt/Decimal columns are handled above via their named scalars.)\n if (columnGraphQLType.type === GraphQLInt) {\n return { name: 'Int', kind: 'scalar' };\n }\n if (columnGraphQLType.type === GraphQLFloat) {\n return { name: 'Float', kind: 'scalar' };\n }\n // Default: plain text/varchar\n return { name: 'String', kind: 'scalar' };\n};\n\n/**\n * Filter fields for a json/jsonb column. `eq`/`ne` compare the whole document (jsonb equality\n * on Postgres, driver-level comparison elsewhere); `contains` is structural containment —\n * Postgres `@>` / MySQL `JSON_CONTAINS`. SQLite stores json as text and has no containment\n * operator, so `contains` is omitted there (same precedent as dialect-specific ops like ilike).\n */\nconst jsonFilterFields = (column: Column, colType: ReturnType<typeof drizzleColumnToGraphQLType>['type']) => {\n const dialect = columnDialect(column);\n return {\n eq: { type: colType, description: 'JSON equality on the whole value' },\n ne: { type: colType, description: 'JSON inequality on the whole value' },\n ...(dialect === 'pg' || dialect === 'mysql'\n ? {\n contains: {\n type: colType,\n description: 'Value structurally contains this JSON (Postgres `@>` / MySQL JSON_CONTAINS)',\n },\n }\n : {}),\n isNull: { type: GraphQLBoolean },\n isNotNull: { type: GraphQLBoolean },\n };\n};\n\n/**\n * 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>, colDesc: string | undefined) => {\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: colDesc },\n ne: { type: colType, description: colDesc },\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: `Array<${colDesc}>` },\n notInArray: { type: colArr, description: `Array<${colDesc}>` },\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\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 const { name: genericName, kind } = 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 colDesc = columnGraphQLType.description;\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 const omitStringOps = 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, colDesc)\n : {\n eq: { type: colType, description: colDesc },\n ne: { type: colType, description: colDesc },\n lt: { type: colType, description: colDesc },\n lte: { type: colType, description: colDesc },\n gt: { type: colType, description: colDesc },\n gte: { type: colType, description: colDesc },\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: `Array<${colDesc}>` },\n notInArray: { type: colArr, description: `Array<${colDesc}>` },\n isNull: { type: GraphQLBoolean },\n isNotNull: { type: GraphQLBoolean },\n };\n\n // The boolean branches are recursive — each branch is this filter type itself — so the\n // fields are thunked and reference the type being constructed.\n const mainType: GraphQLInputObjectType = new GraphQLInputObjectType({\n name: `${genericName}Filter`,\n fields: () => ({\n ...baseFields,\n OR: {\n type: new GraphQLList(new GraphQLNonNull(mainType)),\n description: 'At least one branch matches; ANDed with any sibling operators',\n },\n AND: {\n type: new GraphQLList(new GraphQLNonNull(mainType)),\n description: 'Every branch matches',\n },\n NOT: {\n type: mainType,\n description: 'Negates the nested operators',\n },\n }),\n });\n\n cacheCtx.genericFilterCache.set(genericName, mainType);\n return mainType;\n};\n\nconst orderMap = new WeakMap<object, Record<string, ConvertedInputColumn>>();\nconst generateTableOrderCached = (table: Table) => {\n if (orderMap.has(table)) {\n return orderMap.get(table)!;\n }\n\n let remapped = {};\n try {\n const columns = getColumns(table);\n const columnEntries = Object.entries(columns);\n\n remapped = Object.fromEntries(\n columnEntries.map(([columnName, _columnDescription]) => [columnName, { type: innerOrder }]),\n );\n\n orderMap.set(table, remapped);\n } catch (_err) {}\n return remapped;\n};\n\nconst filterMap = new WeakMap<object, Record<string, ConvertedInputColumn>>();\nconst generateTableFilterValuesCached = (table: Table, tableName: string, cacheCtx: TypeCacheCtx) => {\n if (filterMap.has(table)) {\n return filterMap.get(table)!;\n }\n\n const columns = getColumns(table);\n const columnEntries = Object.entries(columns);\n\n const remapped = Object.fromEntries(\n columnEntries.map(([columnName, columnDescription]) => [\n columnName,\n {\n type: generateColumnFilterValues(columnDescription, tableName, columnName, cacheCtx),\n },\n ]),\n );\n\n filterMap.set(table, remapped);\n\n return remapped;\n};\n\nconst fieldMap = new WeakMap<object, Record<string, ConvertedColumn>>();\nconst generateTableSelectTypeFieldsCached = (table: Table, tableName: string): Record<string, ConvertedColumn> => {\n if (fieldMap.has(table)) {\n return fieldMap.get(table)!;\n }\n\n const columns = getColumns(table);\n const columnEntries = Object.entries(columns);\n\n const remapped = Object.fromEntries(\n columnEntries.map(([columnName, columnDescription]) => [\n columnName,\n drizzleColumnToGraphQLType(columnDescription, columnName, tableName),\n ]),\n );\n\n fieldMap.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);\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 fields: () => ({ ...tableFields, ...container!.fields }),\n });\n cacheCtx.objectTypeCache.set(tableName, shell);\n }\n\n // Build relation fields — recurse into each related table.\n // Mark this table as in-progress before recursing to detect cycles.\n if (relationEntries.length > 0) {\n const rawRelationFields: [string, ConvertedRelationColumnWithArgs][] = [];\n\n // Mark this table as currently being processed.\n const nextUsedTables = new Set(usedTables);\n nextUsedTables.add(tableName);\n\n for (const [relationName, relEntry] of relationEntries) {\n const { targetTableName } = relEntry;\n const relation = (relEntry as any).relation ?? relEntry;\n const isOne = is(relation, One);\n\n // Always recurse to get the target table's filters/order (needed for args).\n // The usedTables check inside the recursive call prevents actual infinite recursion.\n const relSelectData = generateSelectFields(\n tables,\n targetTableName,\n relationMap,\n tableName, // fromTableName for the relation type\n relationName, // fromRelationName for the relation type\n !isOne,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n nextUsedTables,\n resolverFactory,\n currentDepth + 1,\n relationAggregateFactory,\n );\n\n // Use the target table's own GraphQL type directly instead of creating an intermediate relation type.\n // Ensure exactly one GraphQLObjectType instance exists for the target table.\n // If the root call for the target table has already run (or pre-registered a shell),\n // reuse that instance so the schema never contains duplicate type names.\n let relType = cacheCtx.objectTypeCache.get(targetTableName);\n if (!relType) {\n // The target table hasn't been processed yet. Pre-register a shell so that:\n // (a) this relation field has a concrete type reference, and\n // (b) when the target table's root call eventually runs, it reuses this same object.\n const targetTable = tables[targetTableName]!;\n const targetTableFields = generateTableSelectTypeFieldsCached(targetTable, targetTableName);\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 fields: () => ({ ...targetTableFields, ...capturedTargetContainer.fields }),\n });\n cacheCtx.objectTypeCache.set(targetTableName, relType);\n }\n\n const resolve = resolverFactory?.({ tableName, relationName, relEntry: relEntry as TableNamedRelations, isOne });\n\n if (isOne) {\n // Honor the relation's declared optionality: `r.one.Target({ ..., optional: false })`\n // asserts the related row always exists (a NOT NULL foreign key), so the field is\n // emitted as `Target!`. The default (`optional: true` / omitted) stays nullable.\n // Column nullability alone is NOT used to infer this — a notNull `from` column does\n // not guarantee a related row exists when the FK constraint lives on the other side\n // (e.g. `Users.customer` joins the notNull `Users.id` to `Customers.userId`).\n const isRequired = (relation as One<any, any>).optional === false;\n rawRelationFields.push([\n relationName,\n {\n type: isRequired ? new GraphQLNonNull(relType) : relType,\n args: {\n where: { type: relSelectData.filters },\n },\n resolve,\n },\n ]);\n continue;\n }\n\n rawRelationFields.push([\n relationName,\n {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(relType))),\n args: {\n where: { type: relSelectData.filters },\n orderBy: { type: relSelectData.order! },\n offset: { type: GraphQLInt },\n limit: { type: GraphQLInt },\n },\n resolve,\n ...(cacheCtx.complexity ? { extensions: { complexity: listFieldComplexity(cacheCtx.complexity) } } : {}),\n },\n ]);\n\n // Aggregate over the related rows without fetching them: `user { postsAggregate { count } }`.\n // Skipped when the name would shadow a column or another relation.\n const aggregateFieldName = `${relationName}Aggregate`;\n if (!tableFields[aggregateFieldName] && !relationsForTable?.[aggregateFieldName]) {\n const relationAggregate = relationAggregateFactory?.({\n tableName,\n relationName,\n relEntry: relEntry as TableNamedRelations,\n });\n\n if (relationAggregate) {\n rawRelationFields.push([\n aggregateFieldName,\n {\n type: new GraphQLNonNull(relationAggregate.type),\n args: {\n where: { type: relSelectData.filters },\n },\n resolve: relationAggregate.resolve,\n ...(cacheCtx.complexity\n ? { extensions: { complexity: aggregateFieldComplexity(cacheCtx.complexity) } }\n : {}),\n } as unknown as ConvertedRelationColumnWithArgs,\n ]);\n }\n }\n }\n\n const builtRelationFields = Object.fromEntries(rawRelationFields);\n\n // Only the root call should populate the container — non-root calls are temporary traversals\n // to collect filters/order for args and should not overwrite the canonical relation fields.\n if (isRootCall) {\n // Populate the container so that the thunk on the GraphQLObjectType shell (whether it was\n // created here or pre-registered by another table's relation traversal) picks up the fields.\n container.fields = builtRelationFields;\n cacheCtx.fullyBuiltTables.add(tableName);\n }\n\n return {\n order,\n filters,\n tableFields,\n relationFields: builtRelationFields,\n } as SelectData<TWithOrder>;\n }\n\n // No relation entries — mark as fully built if root call.\n if (isRootCall) {\n cacheCtx.fullyBuiltTables.add(tableName);\n }\n\n return {\n order,\n filters,\n tableFields,\n relationFields: {},\n } as SelectData<TWithOrder>;\n};\n\nexport const generateTableTypes = <WithReturning extends boolean>(\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n withReturning: WithReturning,\n relationsDepthLimit: number | undefined,\n cacheCtx: TypeCacheCtx,\n typeNameMapper: TypeNameMapper | undefined = undefined,\n insertPrefix: string = 'create',\n updatePrefix: string = 'update',\n resolverFactory?: RelationResolverFactory,\n relationAggregateFactory?: RelationAggregateFactory,\n): GeneratedTableTypes<WithReturning> => {\n const { tableFields, relationFields, filters, order } = generateSelectFields(\n tables,\n tableName,\n relationMap,\n '', // root call: no fromTableName\n '', // root call: no fromRelationName\n true,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n new Set(),\n resolverFactory,\n 0,\n relationAggregateFactory,\n );\n\n const table = tables[tableName]!;\n const columns = getColumns(table);\n const columnEntries = Object.entries(columns);\n\n const insertFields = Object.fromEntries(\n columnEntries.map(([columnName, columnDescription]) => [\n columnName,\n drizzleColumnToGraphQLType(columnDescription, columnName, tableName, false, true, true),\n ]),\n );\n\n const updateFields = Object.fromEntries(\n columnEntries.map(([columnName, columnDescription]) => [\n columnName,\n drizzleColumnToGraphQLType(columnDescription, columnName, tableName, true, false, true),\n ]),\n );\n\n // Insert/update input types: ${capitalize(insertPrefix)}${resolveTypeName(tableName)}Input / ${capitalize(updatePrefix)}${resolveTypeName(tableName)}Input\n const insertInput = new GraphQLInputObjectType({\n name: `${capitalize(insertPrefix)}${resolveTypeName(tableName, typeNameMapper)}Input`,\n fields: insertFields,\n });\n\n const updateInput = new GraphQLInputObjectType({\n name: `${capitalize(updatePrefix)}${resolveTypeName(tableName, typeNameMapper)}Input`,\n fields: 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 fields: { ...tableFields, ...relationFields },\n });\n\n const selectArrOutput = new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(selectSingleOutput)));\n\n // Mutation return type: ${capitalize(tableName)}Item (table columns only, no relations)\n // const singleTableItemOutput = withReturning\n // ? new GraphQLObjectType({\n // name: `${capitalize(tableName)}`,\n // // name: `${capitalize(tableName)}Item`,\n // fields: tableFields,\n // })\n // : undefined;\n\n const arrTableItemOutput = withReturning\n ? // ? new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(singleTableItemOutput!)))\n new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(selectSingleOutput!)))\n : undefined;\n\n const inputs = {\n insertInput,\n updateInput,\n tableOrder: order,\n tableFilters: filters,\n };\n\n const outputs = (\n withReturning\n ? {\n selectSingleOutput,\n selectArrOutput,\n singleTableItemOutput: selectSingleOutput!,\n // singleTableItemOutput: singleTableItemOutput!,\n arrTableItemOutput: arrTableItemOutput!,\n }\n : {\n selectSingleOutput,\n selectArrOutput,\n }\n ) as GeneratedTableTypesOutputs<WithReturning>;\n\n return {\n inputs,\n outputs,\n };\n};\n\n/** How NULLs are placed relative to non-NULL values in an ordered column. */\nexport type OrderNullsOption = 'first' | 'last';\n\n/**\n * Column name / direction / nulls triples from an `orderBy` argument, highest priority\n * first. Split out of `extractOrderBy` so the same ordering can be rebuilt against a\n * subquery's fields, where there is no `Table` to read columns from. Because there is no\n * table, ordering through a relation cannot be compiled here — a relation-shaped entry\n * (an object without a `direction`) is rejected with a clear error instead of being\n * silently dropped.\n */\nexport const orderByEntries = (\n orderArgs: Record<string, any>,\n): [string, 'asc' | 'desc', OrderNullsOption | undefined][] =>\n Object.entries(orderArgs)\n .sort((a, b) => (b[1]?.priority ?? 0) - (a[1]?.priority ?? 0))\n .filter(([, config]) => config)\n .map(([column, config]) => {\n if (typeof config === 'object' && config.direction === undefined) {\n throw new GraphQLError(`ORDER BY ${column}: ordering through a relation is not supported in this query`);\n }\n return [column, config.direction, config.nulls ?? undefined];\n });\n\n/**\n * The ORDER BY expression(s) for one ordered value. Without a `nulls` option this is the\n * plain `asc`/`desc` of the expression. With one:\n * - PostgreSQL and SQLite (3.30+) support `NULLS FIRST` / `NULLS LAST` natively, so the\n * clause is emitted as-is.\n * - MySQL has no such clause, so it is emulated with an extra `<expr> IS NULL` sort key\n * ahead of the expression itself (`IS NULL DESC` puts nulls first, `ASC` puts them\n * last). The same GraphQL surface is kept on all three dialects.\n *\n * `dialectColumn` is the real table column the expression derives from — used only to\n * detect the dialect (its `columnType` is prefixed `Pg` / `MySql` / `SQLite`), so `expr`\n * may be the column itself, a subquery field, or a correlated subquery.\n */\nexport const orderExpressions = (\n expr: Column | SQL | SQL.Aliased | any,\n direction: 'asc' | 'desc',\n nulls: OrderNullsOption | undefined,\n dialectColumn: Column,\n): SQL[] => {\n const directed = direction === 'asc' ? asc(expr) : desc(expr);\n\n if (!nulls) {\n return [directed];\n }\n\n const isMySql = (((dialectColumn as any).columnType as string) ?? '').startsWith('MySql');\n if (isMySql) {\n const nullsKey = nulls === 'first' ? desc(sql`(${expr} is null)`) : asc(sql`(${expr} is null)`);\n return [nullsKey, directed];\n }\n\n return [nulls === 'first' ? sql`${directed} nulls first` : sql`${directed} nulls last`];\n};\n\n/**\n * One ordering term, flattened out of a (possibly relation-nested) `orderBy` argument.\n * `expression` is what the ORDER BY sorts on — the column itself, or a correlated\n * subquery reaching it through one or more to-one relations. `column` is the leaf table\n * column, kept for dialect detection.\n */\ninterface FlatOrderEntry {\n expression: Column | SQL;\n column: Column;\n direction: 'asc' | 'desc';\n nulls: OrderNullsOption | undefined;\n priority: number;\n}\n\n/**\n * The chain of aliased to-one hops a relation-ordered column is reached through. Rendered\n * as a single correlated scalar subquery: every hop's target sits in the FROM list and\n * its join condition (plus the relation's own `where`, when it declares one) in the WHERE.\n */\ninterface RelationOrderChain {\n fromParts: SQL[];\n conditions: SQL[];\n /** The aliased target of the last hop — the table the next hop or leaf column resolves from. */\n table: Table;\n}\n\n/** Extends the chain (or starts one from `parentTable`) with one to-one hop. */\nconst extendRelationOrderChain = (\n parentTable: Table,\n relationName: string,\n relEntry: TableNamedRelations,\n ctx: RelationFilterContext,\n chain: RelationOrderChain | undefined,\n): RelationOrderChain => {\n const targetTable = ctx.tables[relEntry.targetTableName];\n const relation = ((relEntry as any).relation ?? relEntry) as Relation<string>;\n\n if (!targetTable || !is(relation, One) || !isFilterableRelation(relation)) {\n throw new GraphQLError(`ORDER BY ${relationName}: Relation cannot be used for ordering`);\n }\n\n ctx.aliases ??= { n: 0 };\n const aliasedTarget = aliasedTable(targetTable, `dgql_ord_${ctx.aliases.n++}`);\n\n const joinCondition = buildRelationJoinCondition(parentTable, relation, aliasedTarget, relationName);\n // A relation declared with its own `where` only ever exposes the rows it selects, so the\n // ordering subquery has to honour it too — mirroring the relation-filter subqueries.\n const relationWhere = (relation as any).where\n ? relationsFilterToSQL((relation as any).isReversed ? parentTable : aliasedTarget, (relation as any).where)\n : undefined;\n\n return {\n fromParts: [...(chain?.fromParts ?? []), getTableAsAliasSQL(aliasedTarget)],\n conditions: [\n ...(chain?.conditions ?? []),\n ...(joinCondition ? [joinCondition] : []),\n ...(relationWhere ? [relationWhere] : []),\n ],\n table: aliasedTarget,\n };\n};\n\n/**\n * Flattens one level of an `orderBy` argument into `out`. A column key becomes an entry\n * directly (wrapped in a correlated subquery when reached through a relation chain); a\n * to-one relation key recurses with the chain extended by that hop. Priorities live in one\n * global space, so a relation's column can interleave with the parent's own columns.\n */\nconst collectOrderEntries = (\n table: Table,\n tableKey: string,\n orderArgs: Record<string, any>,\n ctx: RelationFilterContext | undefined,\n chain: RelationOrderChain | undefined,\n out: FlatOrderEntry[],\n): void => {\n const columns = getColumns(table);\n const relations = ctx?.relationMap[tableKey];\n\n for (const [key, config] of Object.entries(orderArgs)) {\n if (config === null || config === undefined) {\n continue;\n }\n\n const column = columns[key];\n if (column) {\n out.push({\n expression: chain\n ? sql`(select ${column} from ${sql.join(chain.fromParts, sql`, `)} where ${and(...chain.conditions)})`\n : column,\n column,\n direction: config.direction,\n nulls: config.nulls ?? undefined,\n priority: config.priority ?? 0,\n });\n continue;\n }\n\n const relEntry = relations?.[key];\n if (!relEntry || !ctx) {\n throw new GraphQLError(`ORDER BY ${key}: Unknown column or relation`);\n }\n\n const nextChain = extendRelationOrderChain(chain?.table ?? table, key, relEntry, ctx, chain);\n collectOrderEntries(nextChain.table, relEntry.targetTableName, config, ctx, nextChain, out);\n }\n};\n\n/**\n * Compiles an `orderBy` argument into ORDER BY expressions, highest priority first.\n *\n * A key naming one of the table's columns orders by that column. A key naming a to-one\n * relation takes the target table's own OrderBy input and orders by the related row's\n * column(s), compiled as a correlated scalar subquery — reusing the aliased-join machinery\n * the relation filters are built on — so it works identically on all three dialects and\n * inside the relational query builder's aliased CTEs. Priorities share one global space\n * across relation boundaries. Each entry may also carry `nulls: first | last`\n * (see {@link orderExpressions} for how MySQL emulates it).\n *\n * `ctx` supplies the tables and relation map that relation ordering needs; callers whose\n * inputs cannot contain relation keys may omit it.\n */\nexport const extractOrderBy = <TTable extends Table, TArgs extends OrderByArgs<any> = OrderByArgs<TTable>>(\n table: TTable,\n orderArgs: TArgs,\n ctx?: RelationFilterContext,\n): SQL[] => {\n const entries: FlatOrderEntry[] = [];\n collectOrderEntries(table, ctx?.tableKey ?? '', orderArgs, ctx, undefined, entries);\n\n return entries\n .sort((a, b) => b.priority - a.priority)\n .flatMap((entry) => orderExpressions(entry.expression, entry.direction, entry.nulls, entry.column));\n};\n\n/**\n * Escape character pinned via `ESCAPE` on every generated safe-LIKE predicate. Bound as a\n * query parameter (never spliced into the SQL text), so no dialect-specific string-literal\n * escaping rules apply to it.\n */\nconst LIKE_ESCAPE_CHAR = '\\\\';\n\n/**\n * Escapes the LIKE wildcards (`%`, `_`) and the escape character itself (`\\`) in a literal\n * search term, so the term only ever matches literally inside a LIKE pattern.\n */\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (char) => `\\\\${char}`);\n\n/**\n * The injection-safe string operators: the caller passes a literal search term, the library\n * builds the LIKE pattern with the term's `%` / `_` / `\\` escaped and the `ESCAPE` clause pinned.\n * The `i`-prefixed variants match case-insensitively.\n */\nconst safeLikeOps: Record<string, { buildPattern: (value: string) => string; insensitive: boolean }> = {\n startsWith: { buildPattern: (value) => `${escapeLikeValue(value)}%`, insensitive: false },\n endsWith: { buildPattern: (value) => `%${escapeLikeValue(value)}`, insensitive: false },\n contains: { buildPattern: (value) => `%${escapeLikeValue(value)}%`, insensitive: false },\n iStartsWith: { buildPattern: (value) => `${escapeLikeValue(value)}%`, insensitive: true },\n iEndsWith: { buildPattern: (value) => `%${escapeLikeValue(value)}`, insensitive: true },\n iContains: { buildPattern: (value) => `%${escapeLikeValue(value)}%`, insensitive: true },\n};\n\n/**\n * `LIKE <pattern> ESCAPE '\\'` for a safe string operator. Case-insensitive variants use\n * Postgres's native `ILIKE`; MySQL and SQLite have no `ILIKE`, so they compare `lower()`\n * on both sides instead (mirroring how the raw `ilike` operator is Postgres-only).\n */\nconst safeLikeCondition = (column: Column, pattern: string, insensitive: boolean): SQL => {\n if (!insensitive) {\n return sql`${column} like ${pattern} escape ${LIKE_ESCAPE_CHAR}`;\n }\n\n const isPg = (((column as any).columnType ?? '') as string).startsWith('Pg');\n return isPg\n ? sql`${column} ilike ${pattern} escape ${LIKE_ESCAPE_CHAR}`\n : sql`lower(${column}) like ${pattern.toLowerCase()} escape ${LIKE_ESCAPE_CHAR}`;\n};\n\n/**\n * Whether the column stores JSON — its `contains` operator is structural containment,\n * not the safe substring operator string columns get.\n */\nconst isJsonColumn = (column: Column): boolean => (((column as any).columnType ?? '') as string).includes('Json');\n\n/**\n * Structural JSON containment for the `contains` operator on json/jsonb columns.\n * The value is serialized and bound as a parameter (never interpolated into the SQL text):\n * - Postgres: `col @> $1::jsonb` (a plain `json` column is cast through jsonb — `json` has\n * no containment operator of its own)\n * - MySQL: `JSON_CONTAINS(col, ?)`\n * SQLite has no containment operator, so the filter input never exposes `contains` there;\n * reaching this with an unsupported dialect is a programming error surfaced as a GraphQLError.\n */\nconst jsonContains = (column: Column, columnName: string, value: any): SQL => {\n const serialized = JSON.stringify(value);\n\n switch (columnDialect(column)) {\n case 'pg':\n return (column as any).columnType === 'PgJson'\n ? sql`${column}::jsonb @> ${serialized}::jsonb`\n : sql`${column} @> ${serialized}::jsonb`;\n case 'mysql':\n return sql`json_contains(${column}, ${serialized})`;\n default:\n throw new GraphQLError(`WHERE ${columnName}: Operator 'contains' is not supported for this dialect!`);\n }\n};\n\nexport const extractFiltersColumn = <TColumn extends Column>(\n column: TColumn,\n columnName: string,\n operators: FilterColumnOperators<TColumn>,\n): SQL | undefined => {\n // Boolean branches compose with sibling operators: siblings and the AND list are ANDed\n // together, NOT negates its whole branch, and the OR group is ANDed with the rest.\n const { OR, AND, NOT, ...restOperators } = operators;\n\n const entries = Object.entries(restOperators as FilterColumnOperatorsCore<TColumn>);\n\n const singleValueOps: Record<string, (...args: any[]) => SQL> = { eq, ne, gt, gte, lt, lte };\n const stringValueOps: Record<string, (...args: any[]) => SQL> = { like, notLike, ilike, notIlike };\n const arrayValueOps: Record<string, (...args: any[]) => SQL> = { inArray, notInArray };\n // Membership operators for array columns: element list → SQL. Empty lists are rejected below.\n const arrayMembershipOps: Record<string, (...args: any[]) => SQL> = {\n hasSome: arrayOverlaps,\n hasEvery: arrayContains,\n };\n const nullableOps: Record<string, (...args: any[]) => SQL> = { isNull, isNotNull };\n\n const variants = [] as SQL[];\n for (const [operatorName, operatorValue] of entries) {\n if (operatorValue === null || operatorValue === false) {\n continue;\n }\n\n if (operatorName in singleValueOps) {\n const singleValue = remapFromGraphQLCore(operatorValue, column, columnName);\n variants.push(singleValueOps[operatorName]!(column, singleValue));\n } else if (operatorName in stringValueOps) {\n variants.push(stringValueOps[operatorName]!(column, operatorValue as string));\n } else if (operatorName === 'contains' && isJsonColumn(column)) {\n // `contains` is JSON containment on json/jsonb columns; on string columns it is the\n // safe substring operator handled by safeLikeOps below.\n variants.push(jsonContains(column, columnName, operatorValue));\n } else if (operatorName in safeLikeOps) {\n const { buildPattern, insensitive } = safeLikeOps[operatorName]!;\n variants.push(safeLikeCondition(column, buildPattern(operatorValue as string), insensitive));\n } else if (operatorName in arrayValueOps) {\n if (!(operatorValue as any[]).length) {\n throw new GraphQLError(`WHERE ${columnName}: Unable to use operator ${operatorName} with an empty array!`);\n }\n const arrayValue = (operatorValue as any[]).map((val) => remapFromGraphQLCore(val, column, columnName));\n variants.push(arrayValueOps[operatorName]!(column, arrayValue));\n } else if (operatorName === 'has') {\n // Single-element membership: containment with a one-element array (`col @> ARRAY[value]`).\n variants.push(arrayContains(column, [operatorValue]));\n } else if (operatorName in arrayMembershipOps) {\n if (!(operatorValue as any[]).length) {\n throw new GraphQLError(`WHERE ${columnName}: Unable to use operator ${operatorName} with an empty array!`);\n }\n variants.push(arrayMembershipOps[operatorName]!(column, operatorValue as any[]));\n } else if (operatorName === 'isEmpty') {\n variants.push(sql`cardinality(${column}) = 0`);\n } else if (operatorName in nullableOps) {\n variants.push(nullableOps[operatorName]!(column));\n } else {\n // An unrecognized operator must throw rather than be dropped: when the generated\n // schema is stitched/merged with another schema, foreign operators (e.g. `equals`,\n // `contains`, `mode`) can pass input validation, and silently dropping them could\n // turn a constrained where into an unbounded one.\n throw new GraphQLError(`WHERE ${columnName}: Unknown operator: ${operatorName}`);\n }\n }\n\n if (AND?.length) {\n for (const variant of AND) {\n const extracted = extractFiltersColumn(column, columnName, variant);\n if (extracted) {\n variants.push(extracted);\n }\n }\n }\n\n if (NOT) {\n const extracted = extractFiltersColumn(column, columnName, NOT);\n if (extracted) {\n variants.push(not(extracted));\n }\n }\n\n if (OR?.length) {\n const orVariants = [] as SQL[];\n for (const variant of OR) {\n const extracted = extractFiltersColumn(column, columnName, variant);\n if (extracted) {\n orVariants.push(extracted);\n }\n }\n\n if (orVariants.length) {\n variants.push(orVariants.length > 1 ? or(...orVariants)! : orVariants[0]!);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n\n/**\n * Everything `extractFilters` needs to turn a relation key in a `where` argument into a\n * correlated subquery. Omitted by callers that don't generate relation filters, in which case\n * relation keys can't appear in the input to begin with.\n */\nexport interface RelationFilterContext {\n /** Every table in the schema, keyed by its schema key. */\n tables: Record<string, Table>;\n /** Relations keyed by table schema key, then relation name. */\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n /**\n * Schema key of the table being filtered. Not always the same as the `tableName` label\n * used in error messages (relation `where` callbacks pass the relation name there).\n */\n tableKey: string;\n /** Shared counter making every subquery alias unique within one extraction. */\n aliases?: { n: number };\n}\n\n/**\n * The build-scoped half of {@link RelationFilterContext}. Created once per generated schema and\n * handed to every resolver, which adds the table it is filtering.\n */\nexport type RelationFilterBase = Pick<RelationFilterContext, 'tables' | 'relationMap'>;\n\n/** Narrows the build-scoped relation filter context to the table a resolver is filtering. */\nexport const relationFilterCtx = (\n base: RelationFilterBase | undefined,\n tableKey: string,\n): RelationFilterContext | undefined => (base ? { ...base, tableKey } : undefined);\n\n/** The three ways a to-many relation can be required to match, plus the to-one shorthand. */\ntype RelationMatchMode = 'some' | 'none' | 'every';\n\n/**\n * Correlates the parent row with the aliased target table using the relation's own join\n * columns. Columns are matched by SQL name rather than object identity so this also works when\n * the parent is an aliased proxy (as it is inside a relational `with:` where callback).\n */\nconst buildRelationJoinCondition = (\n parentTable: Table,\n relation: Relation<string>,\n aliasedTarget: Table,\n relationName: string,\n): SQL | undefined => {\n const sourceColumns = (relation as any).sourceColumns as Column[] | undefined;\n const targetColumns = (relation as any).targetColumns as Column[] | undefined;\n\n if (!sourceColumns?.length || sourceColumns.length !== targetColumns?.length) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\n }\n\n const parentColumns = Object.values(getColumns(parentTable));\n const targetColumnsByName = Object.values(getColumns(aliasedTarget));\n\n const conditions: SQL[] = [];\n for (let i = 0; i < sourceColumns.length; i++) {\n const localColumn = parentColumns.find((c) => c.name === sourceColumns[i]!.name);\n const foreignColumn = targetColumnsByName.find((c) => c.name === targetColumns[i]!.name);\n\n if (!localColumn || !foreignColumn) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\n }\n\n conditions.push(eq(localColumn, foreignColumn));\n }\n\n return conditions.length > 1 ? and(...conditions) : conditions[0];\n};\n\n/**\n * Resolves one side of a `.through()` junction pair to the corresponding column on the\n * aliased junction table. Drizzle stores the junction column as a RelationsBuilderColumn\n * (`_.column` is the Column, `_.key` its property name), so look up by property name first\n * and fall back to matching by SQL name.\n */\nconst resolveJunctionColumn = (aliasedThrough: Table, junctionRef: any, relationName: string): Column => {\n const throughColumns = getColumns(aliasedThrough);\n\n const key: string | undefined = junctionRef?._?.key;\n const byKey = key ? throughColumns[key] : undefined;\n if (byKey) {\n return byKey;\n }\n\n const columnName: string | undefined = junctionRef?._?.column?.name;\n const byName = columnName ? Object.values(throughColumns).find((c) => c.name === columnName) : undefined;\n if (!byName) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\n }\n\n return byName;\n};\n\n/**\n * Join conditions for a `.through()` (many-to-many) relation, split into the two legs of the\n * junction: `correlation` ties the parent row to the aliased junction table on the relation's\n * source keys, `junctionJoin` ties the aliased junction table to the aliased target on the\n * target keys. Column matching mirrors {@link buildRelationJoinCondition} — by SQL name on the\n * parent/target so aliased proxies work — while junction columns come from the relation's own\n * `through` metadata.\n */\nconst buildThroughJoinConditions = (\n parentTable: Table,\n relation: Relation<string>,\n aliasedThrough: Table,\n aliasedTarget: Table,\n relationName: string,\n): { correlation: SQL | undefined; junctionJoin: SQL | undefined } => {\n const sourceColumns = (relation as any).sourceColumns as Column[] | undefined;\n const targetColumns = (relation as any).targetColumns as Column[] | undefined;\n const through = (relation as any).through as { source: any[]; target: any[] } | undefined;\n\n if (\n !sourceColumns?.length ||\n !targetColumns?.length ||\n through?.source.length !== sourceColumns.length ||\n through.target.length !== targetColumns.length\n ) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\n }\n\n const parentColumns = Object.values(getColumns(parentTable));\n const targetTableColumns = Object.values(getColumns(aliasedTarget));\n\n const correlationConditions: SQL[] = [];\n for (let i = 0; i < sourceColumns.length; i++) {\n const localColumn = parentColumns.find((c) => c.name === sourceColumns[i]!.name);\n if (!localColumn) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\n }\n correlationConditions.push(eq(localColumn, resolveJunctionColumn(aliasedThrough, through.source[i], relationName)));\n }\n\n const junctionJoinConditions: SQL[] = [];\n for (let i = 0; i < targetColumns.length; i++) {\n const foreignColumn = targetTableColumns.find((c) => c.name === targetColumns[i]!.name);\n if (!foreignColumn) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\n }\n junctionJoinConditions.push(\n eq(resolveJunctionColumn(aliasedThrough, through.target[i], relationName), foreignColumn),\n );\n }\n\n return {\n correlation: correlationConditions.length > 1 ? and(...correlationConditions) : correlationConditions[0],\n junctionJoin: junctionJoinConditions.length > 1 ? and(...junctionJoinConditions) : junctionJoinConditions[0],\n };\n};\n\n/**\n * Builds one `[NOT] EXISTS (SELECT 1 FROM target alias WHERE …)` for a relation filter.\n * A `.through()` (many-to-many) relation adds an `INNER JOIN` on the aliased junction table\n * inside the subquery, correlated to the parent on the relation's source keys.\n *\n * `some` / the to-one shorthand match when a related row satisfies the inner filters, `none`\n * when none does, and `every` is expressed as \"no related row fails the inner filters\".\n * Because `every` negates the inner condition, a related row whose compared column is NULL\n * counts as matching (SQL three-valued logic) — the same caveat Prisma carries.\n */\nconst buildRelationExists = (\n parentTable: Table,\n relationName: string,\n relEntry: TableNamedRelations,\n innerFilters: Filters<Table> | undefined,\n mode: RelationMatchMode,\n ctx: RelationFilterContext,\n): SQL | undefined => {\n const { targetTableName } = relEntry;\n const targetTable = ctx.tables[targetTableName];\n const relation = ((relEntry as any).relation ?? relEntry) as Relation<string>;\n\n if (!targetTable) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\n }\n\n ctx.aliases ??= { n: 0 };\n const aliases = ctx.aliases;\n const aliasedTarget = aliasedTable(targetTable, `dgql_rel_${aliases.n++}`);\n\n // A `.through()` relation reaches the target via a junction table: the subquery joins the\n // aliased junction to the aliased target and correlates the junction to the parent, so\n // `some` / `none` / `every` compile exactly like the direct case with a longer FROM clause.\n const throughTable = (relation as any).throughTable as Table | undefined;\n let fromClause: SQL;\n let joinCondition: SQL | undefined;\n if (throughTable) {\n const aliasedThrough = aliasedTable(throughTable, `dgql_rel_${aliases.n++}`);\n const { correlation, junctionJoin } = buildThroughJoinConditions(\n parentTable,\n relation,\n aliasedThrough,\n aliasedTarget,\n relationName,\n );\n fromClause = sql`${getTableAsAliasSQL(aliasedTarget)} inner join ${getTableAsAliasSQL(aliasedThrough)} on ${junctionJoin}`;\n joinCondition = correlation;\n } else {\n fromClause = getTableAsAliasSQL(aliasedTarget);\n joinCondition = buildRelationJoinCondition(parentTable, relation, aliasedTarget, relationName);\n }\n\n // A relation declared with its own `where` only ever exposes the rows it selects, so the\n // subquery has to honour it too — otherwise a filter could match a row the relation hides.\n const relationWhere = (relation as any).where\n ? relationsFilterToSQL((relation as any).isReversed ? parentTable : aliasedTarget, (relation as any).where)\n : undefined;\n\n const inner = innerFilters\n ? extractFilters(aliasedTarget, targetTableName, innerFilters, { ...ctx, tableKey: targetTableName, aliases })\n : undefined;\n\n if (mode === 'every') {\n // \"every related row matches\" with no inner condition is vacuously true.\n if (!inner) {\n return undefined;\n }\n\n return sql`not exists (select 1 from ${fromClause} where ${and(joinCondition, relationWhere, not(inner))})`;\n }\n\n const condition = and(joinCondition, relationWhere, inner);\n\n return mode === 'none'\n ? sql`not exists (select 1 from ${fromClause} where ${condition})`\n : sql`exists (select 1 from ${fromClause} where ${condition})`;\n};\n\n/**\n * Handles one relation key in a `where` argument. To-one relations take the target's filters\n * inline; to-many relations take any combination of `some` / `none` / `every`, ANDed together.\n */\nconst extractRelationFilter = (\n parentTable: Table,\n relationName: string,\n relEntry: TableNamedRelations,\n value: Record<string, any>,\n ctx: RelationFilterContext,\n): SQL | undefined => {\n const relation = ((relEntry as any).relation ?? relEntry) as Relation<string>;\n\n if (is(relation, One)) {\n return buildRelationExists(parentTable, relationName, relEntry, value, 'some', ctx);\n }\n\n const relationMatchModes: readonly RelationMatchMode[] = ['some', 'none', 'every'];\n\n const variants: SQL[] = [];\n for (const [mode, inner] of Object.entries(value)) {\n if (inner === undefined || inner === null) {\n continue;\n }\n\n // Unknown keys inside the some/none/every wrapper must throw rather than be dropped —\n // a stitched schema can contribute foreign keys here too, and dropping them all would\n // silently turn the relation filter into no filter at all.\n if (!relationMatchModes.includes(mode as RelationMatchMode)) {\n throw new GraphQLError(`WHERE ${relationName}: Unknown relation filter key: ${mode}`);\n }\n\n const extracted = buildRelationExists(parentTable, relationName, relEntry, inner, mode as RelationMatchMode, ctx);\n if (extracted) {\n variants.push(extracted);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n\nexport const extractFilters = <TTable extends Table>(\n table: TTable,\n tableName: string,\n filters: Filters<TTable>,\n relationCtx?: RelationFilterContext,\n): SQL | undefined => {\n // Boolean branches compose with sibling fields: siblings and the AND list are ANDed\n // together, NOT negates its whole branch, and the OR group is ANDed with the rest —\n // `{ a: …, OR: [{ b: … }, { c: … }] }` reads as `a AND (b OR c)`. Every branch is the\n // filter type itself, so the tree nests arbitrarily.\n const { OR, AND, NOT, ...fieldFilters } = filters;\n\n const entries = Object.entries(fieldFilters as FiltersCore<TTable>);\n\n const columns = getColumns(table);\n const relations = relationCtx?.relationMap[relationCtx.tableKey];\n\n const variants = [] as SQL[];\n for (const [fieldName, operators] of entries) {\n if (operators === null || operators === undefined) {\n continue;\n }\n\n const column = columns[fieldName];\n\n // A key that is neither a column nor a filterable relation must throw rather than be\n // dropped: when the generated schema is stitched/merged with another schema, same-named\n // inputs can contribute foreign keys that pass input validation, and a where that loses\n // all of its keys silently becomes an unbounded select/update/delete.\n if (!column && !(relations?.[fieldName] && relationCtx)) {\n throw new GraphQLError(`WHERE ${tableName}: Unknown filter key: ${fieldName}`);\n }\n\n const extracted = column\n ? extractFiltersColumn(column, fieldName, operators)\n : extractRelationFilter(table, fieldName, relations![fieldName]!, operators as any, relationCtx!);\n\n if (extracted) {\n variants.push(extracted);\n }\n }\n\n if (AND?.length) {\n for (const variant of AND) {\n const extracted = extractFilters(table, tableName, variant, relationCtx);\n if (extracted) {\n variants.push(extracted);\n }\n }\n }\n\n if (NOT) {\n const extracted = extractFilters(table, tableName, NOT, relationCtx);\n if (extracted) {\n variants.push(not(extracted));\n }\n }\n\n if (OR?.length) {\n const orVariants = [] as SQL[];\n for (const variant of OR) {\n const extracted = extractFilters(table, tableName, variant, relationCtx);\n if (extracted) {\n orVariants.push(extracted);\n }\n }\n\n if (orVariants.length) {\n variants.push(orVariants.length > 1 ? or(...orVariants)! : orVariants[0]!);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n\nconst extractRelationsParamsInner = (\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n tables: Record<string, Table>,\n tableName: string,\n typeName: string,\n originField: ResolveTree,\n typeNameMapper?: TypeNameMapper,\n _isInitial: boolean = false,\n filterCtx?: RelationFilterBase,\n) => {\n const relationsForTable = relationMap[tableName];\n if (!relationsForTable) {\n return undefined;\n }\n\n const baseField = Object.entries(originField.fieldsByTypeName).find(([key, _value]) => key === typeName)?.[1];\n if (!baseField) {\n return undefined;\n }\n\n const args: Record<string, Partial<ProcessedTableSelectArgs>> = {};\n\n for (const [relName, relEntry] of Object.entries(relationsForTable)) {\n const { targetTableName, targetPkNames } = relEntry;\n // The relation field resolves to the target table's own type, e.g. \"Posts\" not \"UsersPostsRelation\".\n const relTypeName = resolveTypeName(targetTableName, typeNameMapper);\n // Look up by field name OR by alias (when the caller uses an alias for the relation).\n // graphql-parse-resolve-info keys fieldsByTypeName entries by alias.\n const field = baseField[relName] ?? Object.values(baseField).find((f) => (f as ResolveTree).name === relName);\n if (!field) {\n continue;\n }\n const relField = (field as ResolveTree)?.fieldsByTypeName;\n const relFieldSelection = relField?.[relTypeName];\n\n // Guard: if the relation type is not in fieldsByTypeName, this field is\n // either an aliased scalar column (not an actual relation) or the relation\n // was not selected in the query. Skip it in both cases.\n if (!relFieldSelection) {\n continue;\n }\n\n const columns = extractSelectedColumnsFromTree(relFieldSelection, tables[targetTableName]!, {\n tableName: targetTableName,\n relationMap,\n tables,\n });\n\n const thisRecord: Partial<ProcessedTableSelectArgs> = {};\n thisRecord.columns = columns;\n\n const relationField = Object.values(baseField).find((e) => e.name === relName);\n const relationArgs: Partial<TableSelectArgs> | undefined = relationField?.args;\n\n const offset = relationArgs?.offset ?? undefined;\n const limit = relationArgs?.limit ?? undefined;\n\n // drizzle-orm v1 RQB calls both `where` and `orderBy` callbacks with an\n // aliased table proxy (e.g. d0, d1). Pass the proxy through so column\n // references in the generated SQL match the CTE alias rather than the\n // original unaliased table name.\n const relWhere = relationArgs?.where;\n thisRecord.where = relWhere\n ? {\n RAW: (aliasedTable: Table) =>\n extractFilters(aliasedTable, relName, relWhere, relationFilterCtx(filterCtx, targetTableName)),\n }\n : undefined;\n // When a relation is paginated (limit/offset) but unordered, default to the target's\n // primary key so the per-parent slice is deterministic. Drizzle's RQB calls orderBy\n // with the aliased table proxy, so resolve the PK columns from it. targetPkNames is\n // resolved at build time and includes composite keys.\n const hasPagination = offset != null || limit != null;\n const pkNames = targetPkNames ?? [];\n thisRecord.orderBy = relationArgs?.orderBy\n ? (aliasedTable: Table) =>\n extractOrderBy(aliasedTable, relationArgs.orderBy!, relationFilterCtx(filterCtx, targetTableName))\n : hasPagination && pkNames.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined;\n thisRecord.offset = offset;\n thisRecord.limit = limit;\n\n const relWith = relationField\n ? extractRelationsParamsInner(\n relationMap,\n tables,\n targetTableName,\n relTypeName,\n relationField,\n typeNameMapper,\n false,\n filterCtx,\n )\n : undefined;\n thisRecord.with = relWith;\n\n args[relName] = thisRecord;\n }\n\n return args;\n};\n\nexport const extractRelationsParams = (\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n tables: Record<string, Table>,\n tableName: string,\n info: ResolveTree | undefined,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): Record<string, Partial<ProcessedTableSelectArgs>> | undefined => {\n if (!info) {\n return undefined;\n }\n\n return extractRelationsParamsInner(relationMap, tables, tableName, typeName, info, typeNameMapper, true, filterCtx);\n};\n\n/**\n * Returns a copy of `relationMap` containing only the relations that should be eagerly\n * pre-fetched (per the `shouldEagerLoad` predicate). Pass the result wherever a query or\n * mutation resolver builds its `with:` clause; pass the full map to type generation so\n * opted-out relations still get a (lazily-resolved) field. Relations excluded here are\n * never added to `with:`, so they don't overfetch — they resolve through their field\n * resolver instead (or a resolver you override, e.g. via `@graphql-tools/schema`).\n */\nexport const pruneNonEagerRelations = (\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n shouldEagerLoad: (tableName: string, relationName: string) => boolean,\n): Record<string, Record<string, TableNamedRelations>> => {\n const out: Record<string, Record<string, TableNamedRelations>> = {};\n for (const [tableName, rels] of Object.entries(relationMap)) {\n out[tableName] = Object.fromEntries(\n Object.entries(rels).filter(([relationName]) => shouldEagerLoad(tableName, relationName)),\n );\n }\n return out;\n};\n\n/**\n * Returns the property names of a table's primary key column(s).\n *\n * drizzle-orm marks inline `.primaryKey()` columns with `column.primary === true`,\n * but table-level composite keys (`primaryKey({ columns })`) leave `column.primary`\n * false on each member — those are only visible via the per-dialect `getTableConfig`.\n * Dialect builders pass the composite members' DB column names in via\n * `compositePkColumnNames`; we map them back to property names here.\n *\n * Resolution order: inline PK columns → composite PK columns → empty. We deliberately\n * do NOT guess a column named `id`: if no real primary key is declared, returning empty\n * lets callers fall back to the batch loader rather than re-keying on a possibly\n * non-unique column.\n */\nexport const getPrimaryKeyPropNames = (table: Table, compositePkColumnNames?: readonly string[]): string[] => {\n const cols = getColumns(table);\n const entries = Object.entries(cols);\n\n // Inline single `.primaryKey()` columns.\n const inlinePks = entries.filter(([, c]) => (c as any).primary).map(([k]) => k);\n if (inlinePks.length) {\n return inlinePks;\n }\n\n // Composite primary key (DB column names supplied by the dialect builder).\n if (compositePkColumnNames?.length) {\n const wanted = new Set(compositePkColumnNames);\n const fromComposite = entries.filter(([, c]) => wanted.has((c as any).name)).map(([k]) => k);\n if (fromComposite.length) {\n return fromComposite;\n }\n }\n\n // No declared primary key — let the caller fall back to the batch loader.\n return [];\n};\n\n/**\n * Ensures a selected-columns map (SQL format: prop name → Column) includes the table's\n * primary-key columns. Mutation resolvers pass their RETURNING columns through this so\n * the eager-loader can re-key rows by PK even when the client didn't select it. Mutates\n * and returns the same map.\n */\nexport const withPrimaryKeyColumns = <T extends Record<string, any>>(\n columns: T,\n table: Table,\n pkNames: readonly string[],\n): T => {\n const allCols = getColumns(table);\n for (const pk of pkNames) {\n if (!(pk in columns) && allCols[pk]) {\n (columns as any)[pk] = allCols[pk];\n }\n }\n return columns;\n};\n\n/**\n * Resolves a table's primary-key property names using a dialect's `getTableConfig` to\n * surface table-level composite keys (whose member columns aren't flagged `.primary`).\n * Each dialect builder binds this with its own getTableConfig and reuses the binding for\n * both relation pagination and mutation re-fetch keying.\n */\nexport const getPrimaryKeyPropNamesFromConfig = (\n table: Table,\n getTableConfig: (table: Table) => { primaryKeys: { columns: { name: string }[] }[] },\n): string[] => {\n const compositePkColumnNames = getTableConfig(table).primaryKeys.flatMap((pk) => pk.columns.map((c) => c.name));\n return getPrimaryKeyPropNames(table, compositePkColumnNames);\n};\n\n/**\n * Ascending order expressions for a table's primary key — the deterministic tiebreak for\n * paginated relations. Shared by the window-function batch path and the eager `with:`\n * orderBy default so both order identically. `table` may be the aliased RQB proxy.\n */\nexport const primaryKeyOrderExprs = (table: Table, pkNames: readonly string[]): any[] => {\n const cols = getColumns(table);\n return pkNames\n .map((n) => cols[n])\n .filter(Boolean)\n .map((col) => asc(col!));\n};\n\n/**\n * Every set of columns that uniquely identifies a row of `table`: the primary key first,\n * then each unique constraint and unique index, then each column declared `.unique()`\n * inline. Sets are property names (what GraphQL inputs use), not database column names.\n *\n * `getTableConfig` is the dialect's own — the three dialects expose the same\n * `{ primaryKeys, uniqueConstraints, indexes }` shape but from different modules, so the\n * caller passes theirs in, as `getPrimaryKeyPropNamesFromConfig` does.\n *\n * Index entries whose columns are SQL expressions rather than plain columns are skipped:\n * an expression index is a valid conflict target in the database but cannot be named by a\n * column enum. Deduplicated, order-insensitive — a column that is both the primary key and\n * a unique constraint yields one set.\n */\nexport const getUniqueColumnSets = (\n table: Table,\n getTableConfig: (table: Table) => {\n primaryKeys: { columns: { name: string }[] }[];\n uniqueConstraints?: { columns: { name: string }[] }[];\n indexes?: { config: { unique?: boolean; columns: any[] } }[];\n },\n): string[][] => {\n const cols = getColumns(table);\n const propNameByColumnName = new Map(Object.entries(cols).map(([propName, col]) => [(col as any).name, propName]));\n // A set is usable only if every one of its columns maps back to a property on the table.\n const toPropNames = (columnNames: (string | undefined)[]): string[] | undefined => {\n const propNames: string[] = [];\n for (const columnName of columnNames) {\n const propName = columnName === undefined ? undefined : propNameByColumnName.get(columnName);\n if (!propName) {\n return undefined;\n }\n propNames.push(propName);\n }\n return propNames.length ? propNames : undefined;\n };\n\n const config = getTableConfig(table);\n const candidates: (string[] | undefined)[] = [\n // Inline `.primaryKey()` columns, then table-level `primaryKey({ columns })`.\n Object.entries(cols)\n .filter(([, col]) => (col as any).primary)\n .map(([propName]) => propName),\n ...config.primaryKeys.map((pk) => toPropNames(pk.columns.map((c) => c.name))),\n ...(config.uniqueConstraints ?? []).map((uc) => toPropNames(uc.columns.map((c) => c.name))),\n ...(config.indexes ?? [])\n .filter((index) => index.config.unique)\n .map((index) => toPropNames(index.config.columns.map((c) => (c as any)?.name))),\n ...Object.entries(cols)\n .filter(([, col]) => (col as any).isUnique)\n .map(([propName]) => [propName]),\n ];\n\n const seen = new Set<string>();\n const sets: string[][] = [];\n for (const set of candidates) {\n if (!set?.length) {\n continue;\n }\n const key = [...set].sort().join(',');\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n sets.push(set);\n }\n return sets;\n};\n\n/** Alias of the row-number helper column in the `distinct` pass. Namespaced against real columns. */\nconst DISTINCT_RN = '__drizzle_graphql_distinct_rn';\n\nconst columnEnumCache = new WeakMap<object, Map<string, GraphQLEnumType>>();\n\n/**\n * An enum of a table's column property names, under `enumName`. Cached per (table, enum\n * name), like the order/filter inputs, so repeated builds reuse one instance and two enums\n * over the same table never collide.\n *\n * Returns `undefined` when no column qualifies — the caller then omits the argument or\n * input field the enum would have typed, rather than emitting an empty enum, which is\n * invalid GraphQL.\n */\nexport const generateColumnEnum = (\n table: Table,\n enumName: string,\n description: string,\n predicate: (column: Column, columnName: string) => boolean = () => true,\n): GraphQLEnumType | undefined => {\n let tableCache = columnEnumCache.get(table);\n const cached = tableCache?.get(enumName);\n if (cached) {\n return cached;\n }\n\n const columnNames = Object.entries(getColumns(table))\n .filter(([columnName, column]) => predicate(column as Column, columnName))\n .map(([columnName]) => columnName);\n if (!columnNames.length) {\n return undefined;\n }\n\n const enumType = new GraphQLEnumType({\n name: enumName,\n description,\n values: Object.fromEntries(columnNames.map((columnName) => [columnName, { value: columnName }])),\n });\n\n if (!tableCache) {\n tableCache = new Map();\n columnEnumCache.set(table, tableCache);\n }\n tableCache.set(enumName, enumType);\n return enumType;\n};\n\n/** `${typeName}DistinctColumn` — the enum of columns a list query may be made distinct on. */\nexport const generateDistinctEnum = (table: Table, typeName: string): GraphQLEnumType | undefined =>\n generateColumnEnum(table, `${typeName}DistinctColumn`, `Columns of ${typeName} that a query can be made distinct on`);\n\n// ── upsert / conflict handling ────────────────────────────────────────────────\n\n/** Shared by every table's `${typeName}OnConflict` input, so it is created once. */\nexport const conflictActionEnum = new GraphQLEnumType({\n name: 'ConflictAction',\n description: 'What an upsert does when a row with the same unique key already exists',\n values: {\n UPDATE: { value: 'UPDATE', description: 'Overwrite the conflicting row with the supplied values' },\n NOTHING: { value: 'NOTHING', description: 'Keep the existing row and insert nothing' },\n },\n});\n\n/**\n * The `${typeName}OnConflict` input that types an upsert's `onConflict` argument.\n *\n * `target` and `where` only exist when the dialect can express them: MySQL's\n * `ON DUPLICATE KEY UPDATE` fires on any unique key and takes no predicate, so offering\n * either there would mean silently ignoring it.\n *\n * Returns `undefined` when the table has nothing to conflict on (`withTarget` dialects\n * only) — the caller then generates no upsert mutations for that table at all, rather than\n * an operation whose every call is a database error.\n */\nexport const generateOnConflictInput = (params: {\n table: Table;\n typeName: string;\n uniqueSets: string[][];\n tableFilters: GraphQLInputObjectType;\n withTarget: boolean;\n}): GraphQLInputObjectType | undefined => {\n const { table, typeName, uniqueSets, tableFilters, withTarget } = params;\n\n const updateEnum = generateColumnEnum(\n table,\n `${typeName}UpdateColumn`,\n `Columns of ${typeName} that an upsert can overwrite`,\n );\n if (!updateEnum) {\n return undefined;\n }\n\n const fields: Record<string, any> = {\n action: {\n type: conflictActionEnum,\n defaultValue: 'UPDATE',\n description: 'Whether a conflicting row is overwritten or left alone. Defaults to UPDATE.',\n },\n update: {\n type: new GraphQLList(new GraphQLNonNull(updateEnum)),\n description:\n 'Columns to overwrite on conflict. Defaults to every column the request supplied, minus the conflict target. Columns the request did not supply cannot be listed here — there would be no value to write.',\n },\n };\n\n if (withTarget) {\n const uniqueColumns = new Set(uniqueSets.flat());\n const targetEnum = generateColumnEnum(\n table,\n `${typeName}ConflictTarget`,\n `Columns of ${typeName} that carry a unique constraint, and so can be conflicted on`,\n (_column, columnName) => uniqueColumns.has(columnName),\n );\n if (!targetEnum) {\n return undefined;\n }\n\n fields['target'] = {\n type: new GraphQLList(new GraphQLNonNull(targetEnum)),\n description:\n 'The unique column set a conflict is detected on. Must match one of the table’s unique constraints exactly. Defaults to the primary key.',\n };\n fields['where'] = {\n type: tableFilters,\n description: 'Only overwrite conflicting rows that match this filter. Others are left alone.',\n };\n }\n\n return new GraphQLInputObjectType({\n name: `${typeName}OnConflict`,\n description: `Conflict handling for an upsert of ${typeName}`,\n fields,\n });\n};\n\n/** The `onConflict` argument as it arrives from GraphQL. */\nexport type OnConflictArg = {\n action?: 'UPDATE' | 'NOTHING';\n target?: string[];\n update?: string[];\n where?: any;\n};\n\n/** What a dialect needs to turn an insert into an upsert. */\nexport type ConflictPlan = {\n action: 'UPDATE' | 'NOTHING';\n /** Columns to conflict on, or `undefined` on dialects that take no conflict target. */\n target: Column[] | undefined;\n /** `column -> value to write`, in Drizzle's `set` shape. Empty when the action is NOTHING. */\n set: Record<string, SQL>;\n setWhere: SQL | undefined;\n};\n\n/**\n * Turns the request's `onConflict` argument and the rows it is inserting into the clause a\n * dialect should attach.\n *\n * `excludedRef` names the row that failed to insert in the dialect's own terms\n * (`excluded.col` on PostgreSQL and SQLite, `values(col)` on MySQL), which is what makes a\n * batch upsert update each row with its own values instead of the last row's.\n *\n * An UPDATE with nothing left to write degrades to NOTHING: `DO UPDATE SET` with an empty\n * body is not valid SQL, and doing nothing is what the request asked for anyway.\n */\nexport const resolveConflictPlan = (params: {\n table: Table;\n values: Record<string, any>[];\n onConflict: OnConflictArg | undefined;\n pkNames: readonly string[];\n uniqueSets: string[][];\n excludedRef: (columnName: string) => SQL;\n withTarget: boolean;\n buildWhere?: (where: any) => SQL | undefined;\n}): ConflictPlan => {\n const { table, values, onConflict, pkNames, uniqueSets, excludedRef, withTarget, buildWhere } = params;\n const columns = getColumns(table) as Record<string, Column>;\n\n let target: Column[] | undefined;\n if (withTarget) {\n const targetNames = onConflict?.target?.length ? onConflict.target : [...pkNames];\n if (!targetNames.length) {\n throw new GraphQLError(\n 'Unable to upsert: no conflict target was given and this table has no primary key. Pass onConflict.target.',\n );\n }\n // A target that is not itself a unique constraint is a database error, and a confusing\n // one (\"there is no unique or exclusion constraint matching the ON CONFLICT\n // specification\"), so reject it here where we can say which sets are valid.\n const requested = [...targetNames].sort().join(',');\n if (!uniqueSets.some((set) => [...set].sort().join(',') === requested)) {\n throw new GraphQLError(\n `Unable to upsert: [${targetNames.join(', ')}] is not a unique constraint on this table. Valid conflict targets: ${uniqueSets\n .map((set) => `[${set.join(', ')}]`)\n .join(', ')}.`,\n );\n }\n target = targetNames.map((name) => columns[name]!);\n }\n\n if ((onConflict?.action ?? 'UPDATE') === 'NOTHING') {\n return { action: 'NOTHING', target, set: {}, setWhere: undefined };\n }\n\n // Only columns the request actually supplied have a value to copy over; anything else\n // would write the column's default (usually null) onto the row that already exists.\n const supplied = new Set(values.flatMap((row) => Object.keys(row)));\n const targetNames = new Set(withTarget ? (onConflict?.target?.length ? onConflict.target : pkNames) : []);\n\n let updateNames: string[];\n if (onConflict?.update?.length) {\n const unsupplied = onConflict.update.filter((name) => !supplied.has(name));\n if (unsupplied.length) {\n throw new GraphQLError(\n `Unable to upsert: onConflict.update lists ${unsupplied.join(', ')}, which the values do not supply.`,\n );\n }\n updateNames = onConflict.update;\n } else {\n updateNames = [...supplied].filter((name) => !targetNames.has(name));\n }\n\n if (!updateNames.length) {\n return { action: 'NOTHING', target, set: {}, setWhere: undefined };\n }\n\n const set = Object.fromEntries(updateNames.map((name) => [name, excludedRef(columns[name]!.name)]));\n const setWhere = onConflict?.where && buildWhere ? buildWhere(onConflict.where) : undefined;\n\n return { action: 'UPDATE', target, set, setWhere };\n};\n\n/** `excluded.<column>` — PostgreSQL and SQLite name the rejected row this way. */\nexport const excludedColumnRef = (columnName: string): SQL => sql`excluded.${sql.identifier(columnName)}`;\n\n/** `values(<column>)` — MySQL's equivalent inside ON DUPLICATE KEY UPDATE. */\nexport const mysqlValuesColumnRef = (columnName: string): SQL => sql`values(${sql.identifier(columnName)})`;\n\n/**\n * Keeps the first row of each distinct combination of the requested columns, following the\n * query's own ordering, then applies `limit`/`offset` to what survives — and returns the\n * surviving rows' primary key values in that order.\n *\n * The relational query builder has no `distinct` support, so this runs as its own\n * `row_number() over (partition by … order by …)` pass and the main query is narrowed to the\n * keys it returns. `orderExprs` is the full ordering (the request's `orderBy` plus the primary\n * key tiebreak); the caller applies the same ordering to the main query, so the two agree.\n */\nexport const selectDistinctKeys = async (params: {\n db: any;\n table: Table;\n tableName: string;\n distinct: string[];\n pkNames: readonly string[];\n where: SQL | undefined;\n orderBy: Record<string, any> | undefined;\n limit?: number;\n offset?: number;\n}): Promise<Record<string, any>[]> => {\n const { db, table, tableName, distinct, pkNames, where, orderBy, limit, offset } = params;\n const cols = getColumns(table);\n\n if (!pkNames.length) {\n throw new GraphQLError(`Table ${tableName} has no primary key, so 'distinct' cannot be applied to it.`);\n }\n\n const partitionCols = distinct.map((name) => cols[name]).filter(Boolean);\n if (!partitionCols.length) {\n throw new GraphQLError(`No known columns were given to 'distinct' on ${tableName}.`);\n }\n\n const orderEntries = orderBy ? orderByEntries(orderBy) : [];\n // Both orderings must agree, so build each from the same entries — once against the table\n // (inside the window) and once against the subquery's fields (for the outer row order).\n const windowOrder = [\n ...orderEntries.flatMap(([column, direction, nulls]) =>\n orderExpressions(cols[column]!, direction, nulls, cols[column]!),\n ),\n ...primaryKeyOrderExprs(table, pkNames),\n ];\n\n const rowNumber = sql`row_number() over (partition by ${sql.join(partitionCols, sql`, `)} order by ${sql.join(\n windowOrder,\n sql`, `,\n )})`.as(DISTINCT_RN);\n\n const sub = db\n .select({ ...cols, [DISTINCT_RN]: rowNumber })\n .from(table)\n .where(where)\n .as('__dgql_distinct');\n\n const outerOrder = [\n ...orderEntries.flatMap(([column, direction, nulls]) =>\n orderExpressions(sub[column], direction, nulls, cols[column]!),\n ),\n ...pkNames.filter((name) => sub[name]).map((name) => asc(sub[name])),\n ];\n\n let query = db\n .select(Object.fromEntries(pkNames.map((name) => [name, sub[name]])))\n .from(sub)\n .where(eq(sub[DISTINCT_RN], 1))\n .orderBy(...outerOrder);\n\n if (offset) {\n query = query.offset(offset);\n }\n if (limit != null) {\n query = query.limit(limit);\n }\n\n return await query;\n};\n\n/**\n * Condition matching exactly the rows identified by `keys` — an `IN (…)` for a single-column\n * primary key, an `OR` of per-row equality for a composite one. `table` may be the aliased\n * RQB proxy.\n */\nexport const primaryKeyRestriction = (table: Table, pkNames: readonly string[], keys: Record<string, any>[]): SQL => {\n const cols = getColumns(table);\n\n if (pkNames.length === 1) {\n const name = pkNames[0]!;\n return inArray(\n cols[name]!,\n keys.map((key) => key[name]),\n );\n }\n\n return or(...keys.map((key) => and(...pkNames.map((name) => eq(cols[name]!, key[name])))))!;\n};\n\n/**\n * Computes the RETURNING columns and relation selection for a mutation resolver: extracts\n * the selected scalar columns, determines whether any relations were selected, and only\n * then forces the primary key into the column set (so the post-mutation eager-load can\n * re-key rows). Returns everything the resolver needs to decide whether to eager-load.\n */\nexport const prepareMutationRelationColumns = (params: {\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n tables: Record<string, Table>;\n tableName: string;\n typeName: string;\n typeNameMapper: TypeNameMapper | undefined;\n table: Table;\n pkNames: readonly string[];\n parsedInfo: ResolveTree;\n}): {\n columns: Record<string, Column>;\n hasRelations: boolean;\n withParams: Record<string, Partial<ProcessedTableSelectArgs>> | undefined;\n} => {\n const { relationMap, tables, tableName, typeName, typeNameMapper, table, pkNames, parsedInfo } = params;\n const withParams = relationMap[tableName]\n ? extractRelationsParams(relationMap, tables, tableName, parsedInfo, typeName, typeNameMapper)\n : undefined;\n const hasRelations = !!(withParams && Object.keys(withParams).length);\n const baseColumns = extractSelectedColumnsFromTreeSQLFormat(parsedInfo.fieldsByTypeName[typeName]!, table, {\n tableName,\n relationMap,\n tables,\n });\n const columns = hasRelations ? withPrimaryKeyColumns(baseColumns, table, pkNames) : baseColumns;\n return { columns, hasRelations, withParams };\n};\n\n/** Wraps a thrown Error as a (message-only) GraphQLError; passes non-Errors through unchanged. */\n/**\n * Normalizes whatever a driver threw into a `GraphQLError`. Errors drizzle-graphql raised\n * itself pass straight through; anything else keeps the thrown value on `originalError`,\n * which is how {@link defaultErrorMapper} later tells the two apart.\n */\nexport const toGraphQLError = (e: unknown): unknown => {\n if (e instanceof GraphQLError) {\n return e;\n }\n return e instanceof Error ? new GraphQLError(e.message, { originalError: e }) : e;\n};\n\n/**\n * Default for `config.onError`: keeps drizzle-graphql's own errors, which are written for\n * the client, and replaces driver/database errors with a generic message. Their text names\n * tables, columns, constraints and offending values, none of which belongs in a response.\n * The original is preserved on `originalError` for server-side logging.\n */\nexport const defaultErrorMapper = (error: unknown): unknown => {\n if (error instanceof GraphQLError && !error.originalError) {\n return error;\n }\n\n return new GraphQLError('Internal server error', {\n originalError:\n error instanceof GraphQLError ? (error.originalError ?? error) : error instanceof Error ? error : null,\n extensions: { code: 'INTERNAL_SERVER_ERROR' },\n });\n};\n\n/**\n * Wraps every resolver reachable from a generated entity set so that its errors pass through\n * `mapError` first. Done here rather than at each `throw` site so that the hook also covers\n * relation field resolvers and anything that throws outside a builder's own try/catch.\n */\nexport const applyErrorMapper = (\n entities: {\n queries: Record<string, { resolve?: (...args: any[]) => any }>;\n mutations: Record<string, { resolve?: (...args: any[]) => any }>;\n types: Record<string, { getFields?: () => Record<string, { resolve?: (...args: any[]) => any }> }>;\n fieldResolvers?: Record<string, Record<string, (...args: any[]) => any>>;\n },\n mapError: (error: unknown) => unknown,\n): void => {\n const wrap =\n (resolve: (...args: any[]) => any) =>\n (...args: any[]) => {\n try {\n const result = resolve(...args);\n if (result && typeof result.then === 'function') {\n return result.then(undefined, (e: unknown) => {\n throw mapError(e);\n });\n }\n return result;\n } catch (e) {\n throw mapError(e);\n }\n };\n\n for (const field of [...Object.values(entities.queries), ...Object.values(entities.mutations)]) {\n if (field?.resolve) {\n field.resolve = wrap(field.resolve);\n }\n }\n\n // Relation and aggregate fields live on the object types, not in the query/mutation maps.\n for (const type of Object.values(entities.types)) {\n if (typeof type?.getFields !== 'function') {\n continue;\n }\n for (const field of Object.values(type.getFields())) {\n if (field?.resolve) {\n field.resolve = wrap(field.resolve);\n }\n }\n }\n\n // Standalone relation resolvers, handed out for use in hand-written schemas.\n for (const tableResolvers of Object.values(entities.fieldResolvers ?? {})) {\n for (const [relationName, resolve] of Object.entries(tableResolvers)) {\n tableResolvers[relationName] = wrap(resolve);\n }\n }\n};\n\n/**\n * Derives the generated query/mutation field names for a table from the naming config\n * (typeNameMapper + prefixes/suffixes). Shared by all three dialect builders.\n */\nexport const computeResolverFieldNames = (\n tableName: string,\n typeNameMapper: TypeNameMapper | undefined,\n prefixes: { insert: string; update: string; delete: string; upsert?: string },\n suffixes: { list: string; single: string },\n): {\n typeName: string;\n listFieldName: string;\n singleFieldName: string;\n aggregateFieldName: string;\n groupByFieldName: string;\n createArrayFieldName: string;\n createSingleFieldName: string;\n upsertArrayFieldName: string;\n upsertSingleFieldName: string;\n updateFieldName: string;\n updateSingleFieldName: string;\n deleteFieldName: string;\n deleteSingleFieldName: string;\n} => {\n const mapped = typeNameMapper?.(tableName);\n const typeName = mapped ? capitalize(mapped.singular) : capitalize(tableName);\n const listFieldName = (mapped?.plural ?? uncapitalize(tableName)) + suffixes.list;\n const singleFieldName = mapped?.singular ?? uncapitalize(tableName) + suffixes.single;\n const aggregateFieldName = `${mapped?.plural ?? uncapitalize(tableName)}Aggregate`;\n const groupByFieldName = `${mapped?.plural ?? uncapitalize(tableName)}GroupBy`;\n const createArrayFieldName = `${prefixes.insert}${mapped ? capitalize(mapped.plural) : capitalize(tableName)}`;\n const createSingleFieldName = mapped\n ? `${prefixes.insert}${capitalize(mapped.singular)}`\n : `${prefixes.insert}${capitalize(tableName)}${suffixes.single}`;\n const upsertPrefix = prefixes.upsert ?? 'upsert';\n const upsertArrayFieldName = `${upsertPrefix}${mapped ? capitalize(mapped.plural) : capitalize(tableName)}`;\n const upsertSingleFieldName = mapped\n ? `${upsertPrefix}${capitalize(mapped.singular)}`\n : `${upsertPrefix}${capitalize(tableName)}${suffixes.single}`;\n const updateFieldName = `${prefixes.update}${mapped ? capitalize(mapped.singular) : capitalize(tableName)}`;\n const deleteFieldName = `${prefixes.delete}${mapped ? capitalize(mapped.singular) : capitalize(tableName)}`;\n // The plural update/delete mutations already use the singular noun when a mapper is\n // present, so — unlike create — the Single variants can't rely on singular vs plural to\n // stay distinct. They always carry a suffix, falling back to 'Single' when the configured\n // suffix is empty (a mapper config may set it to '' for the query side).\n const writeSingleSuffix = suffixes.single === '' ? 'Single' : suffixes.single;\n const updateSingleFieldName = `${updateFieldName}${writeSingleSuffix}`;\n const deleteSingleFieldName = `${deleteFieldName}${writeSingleSuffix}`;\n return {\n typeName,\n listFieldName,\n singleFieldName,\n aggregateFieldName,\n groupByFieldName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n updateSingleFieldName,\n deleteFieldName,\n deleteSingleFieldName,\n };\n};\n\n/**\n * Extracts a `where` argument that a mutation refuses to run without: missing, or present\n * but matching every row (e.g. `where: {}` or filters that all collapse to nothing), both\n * throw instead of becoming an unbounded write. Used by the `Single` write variants always\n * and by the plural update/delete mutations when `features.requireWhere` is on.\n */\nexport const extractRequiredFilters = <TTable extends Table>(\n table: TTable,\n tableName: string,\n where: Filters<TTable> | undefined,\n fieldName: string,\n relationCtx?: RelationFilterContext,\n): SQL => {\n const filters = where ? extractFilters(table, tableName, where, relationCtx) : undefined;\n if (!filters) {\n throw new GraphQLError(`${fieldName} requires a 'where' argument with at least one filter!`);\n }\n return filters;\n};\n\n/**\n * Guard for the `Single` write variants: throws before anything is written when `where`\n * matches more than one row, so a multi-row update/delete never executes. Probed with a\n * `LIMIT 2` select rather than a count so the check stays cheap on large matches.\n */\nexport const assertSingleMatch = async (\n executor: any,\n table: Table,\n filters: SQL,\n fieldName: string,\n): Promise<void> => {\n const matched = await executor.select({ found: sql`1` }).from(table).where(filters).limit(2);\n if (matched.length > 1) {\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row — nothing was written!`);\n }\n};\n\n/** GraphQL argument map for a list/array select field. */\nexport const selectArrayArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n distinctEnum?: GraphQLEnumType,\n): Record<string, { type: any }> => ({\n offset: { type: GraphQLInt },\n limit: { type: GraphQLInt },\n orderBy: { type: orderArgs },\n where: { type: filterArgs },\n ...(distinctEnum ? { distinct: { type: new GraphQLList(new GraphQLNonNull(distinctEnum)) } } : {}),\n});\n\n/** GraphQL argument map for a single-row select field (no `limit`). */\nexport const selectSingleArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n): Record<string, { type: any }> => ({\n offset: { type: GraphQLInt },\n orderBy: { type: orderArgs },\n where: { type: filterArgs },\n});\n\n/**\n * Runs the relational-query-builder select shared by every dialect's `generateSelect*`\n * resolver: selected columns + offset/limit + aliased orderBy/where callbacks + the eager\n * `with:` relation params, then remaps the result. `single` switches between\n * findFirst/findMany (and the single path omits `limit`). The PG fallback for tables\n * without RQB support stays in pg.ts; this covers the common RQB path for all three.\n */\nexport const runRelationalSelect = async (opts: {\n queryBase: any;\n tables: Record<string, Table>;\n tableName: string;\n table: Table;\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n typeName: string;\n typeNameMapper: TypeNameMapper | undefined;\n parsedInfo: ResolveTree;\n offset?: number;\n limit?: number;\n orderBy?: any;\n where?: any;\n single: boolean;\n filterCtx?: RelationFilterBase;\n pkNames?: readonly string[];\n db?: any;\n distinct?: string[];\n}): 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 } = opts;\n const distinct = opts.distinct?.length ? opts.distinct : undefined;\n // Taking a slice of an unordered result lets the database return any rows it likes, so\n // `limit`/`offset` pages can overlap or skip rows between requests, and a single query\n // can return a different row each time. Default to the primary key whenever the query is\n // narrowed to a subset, mirroring the relation-level default in extractRelationsParamsInner.\n const needsDefaultOrder = single || offset != null || opts.limit != null;\n\n // `distinct` runs as its own pass — the relational query builder cannot express it — and\n // the main query is then narrowed to the primary keys it picked, with the same ordering\n // and without re-applying limit/offset.\n let distinctKeys: Record<string, any>[] | undefined;\n if (distinct) {\n distinctKeys = await selectDistinctKeys({\n db: opts.db,\n table,\n tableName,\n distinct,\n pkNames: pkNames ?? [],\n where: where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n orderBy,\n limit: single ? 1 : opts.limit,\n offset,\n });\n\n if (!distinctKeys.length) {\n return single ? undefined : [];\n }\n }\n\n const params: any = {\n columns: extractSelectedColumnsFromTree(parsedInfo.fieldsByTypeName[typeName]!, table, {\n tableName,\n relationMap,\n tables,\n }),\n offset: distinctKeys ? undefined : offset,\n // drizzle-orm v1 RQB calls orderBy/where with the aliased table proxy — use it\n // directly so column refs match the CTE alias.\n orderBy: distinctKeys\n ? (aliasedTable: Table) => [\n ...(orderBy ? extractOrderBy(aliasedTable, orderBy, relationFilterCtx(filterCtx, tableName)) : []),\n ...primaryKeyOrderExprs(aliasedTable, pkNames!),\n ]\n : orderBy\n ? (aliasedTable: Table) => extractOrderBy(aliasedTable, orderBy, relationFilterCtx(filterCtx, tableName))\n : needsDefaultOrder && pkNames?.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined,\n where: distinctKeys\n ? { RAW: (aliasedTable: Table) => primaryKeyRestriction(aliasedTable, pkNames!, distinctKeys!) }\n : where\n ? {\n RAW: (aliasedTable: Table) =>\n extractFilters(aliasedTable, tableName, where, relationFilterCtx(filterCtx, tableName)),\n }\n : undefined,\n with: relationMap[tableName]\n ? extractRelationsParams(relationMap, tables, tableName, parsedInfo, typeName, typeNameMapper, filterCtx)\n : undefined,\n };\n\n if (single) {\n const result = await queryBase.findFirst(params);\n return result ? remapToGraphQLSingleOutput(result, tableName, table, relationMap) : undefined;\n }\n\n params.limit = distinctKeys ? undefined : opts.limit;\n const result = await queryBase.findMany(params);\n return remapToGraphQLArrayOutput(result, tableName, table, relationMap);\n};\n\n/**\n * After a mutation, re-fetch the mutated rows through the relational query builder so the\n * selected relations are eagerly loaded in a single query, then merge those relations onto\n * the `.returning()` rows — making the per-field BatchLoader fallback unnecessary.\n *\n * `withParams` is the pre-computed relation selection (from extractRelationsParams); the\n * caller only invokes this when relations are actually selected, so it also gates whether\n * the PK was forced into RETURNING.\n *\n * Falls back to the original `.returning()` rows (relations then resolve via the\n * field-level BatchLoader) when the table has no RQB support, no primary key columns can be\n * determined, or the re-fetch fails. Supports single- and multi-column primary keys.\n */\nexport const eagerLoadMutationRelations = async (\n db: any,\n tableName: string,\n rows: any[],\n pkNames: readonly string[],\n withParams: Record<string, Partial<ProcessedTableSelectArgs>> | undefined,\n): Promise<any[]> => {\n if (!rows.length || !pkNames.length || !withParams || !Object.keys(withParams).length) {\n return rows;\n }\n\n const queryBase = db.query?.[tableName];\n if (!queryBase) {\n return rows;\n }\n\n // Only rows that carry every PK value can be re-keyed. Callers force the PK into\n // RETURNING, but if a value is still missing for some rows, eager-load just those that\n // are keyable and leave the rest untouched (their relations resolve lazily) rather than\n // bailing the whole batch.\n const keyableRows = rows.filter((row) => pkNames.every((n) => row[n] != null));\n if (!keyableRows.length) {\n return rows;\n }\n\n // Re-fetch ONLY the primary key + relations: the scalar columns are already present\n // on `rows` from RETURNING, so re-selecting them would transfer them a second time\n // (and would lose them on the fallback path). We merge the fetched relations back in.\n const pkColumns: Record<string, true> = {};\n for (const pk of pkNames) {\n pkColumns[pk] = true;\n }\n const relationNames = Object.keys(withParams);\n\n // Normalize bigint PK values to strings: JSON.stringify throws on bigint, and a\n // bigint and its string form never collide within a single column's values.\n const keyOf = (row: any) =>\n JSON.stringify(pkNames.map((n) => (typeof row[n] === 'bigint' ? row[n].toString() : row[n])));\n\n let whereRaw: (aliased: any) => SQL | undefined;\n if (pkNames.length === 1) {\n const pkName = pkNames[0]!;\n const ids = keyableRows.map((r) => r[pkName]);\n // drizzle-orm v1 RQB calls the where callback with the aliased table proxy;\n // reference the PK through it so the column ref matches the CTE alias.\n whereRaw = (aliased: any) => inArray(aliased[pkName], ids);\n } else {\n // Composite PK: use a row-value IN — `(a, b) IN ((..), (..))` — so the database can\n // plan it as a set membership test, instead of an OR of N per-row AND-tuples that\n // blows up for large bulk mutations.\n whereRaw = (aliased: any) => {\n const lhs = sql.join(\n pkNames.map((n) => sql`${aliased[n]}`),\n sql`, `,\n );\n const tuples = sql.join(\n keyableRows.map(\n (row) =>\n sql`(${sql.join(\n pkNames.map((n) => sql`${row[n]}`),\n sql`, `,\n )})`,\n ),\n sql`, `,\n );\n return sql`(${lhs}) in (${tuples})`;\n };\n }\n\n let enriched: any[];\n try {\n enriched = await queryBase.findMany({\n columns: pkColumns,\n where: { RAW: whereRaw },\n with: withParams,\n });\n } catch (err) {\n // The write has already committed; a re-fetch failure (e.g. an RQB-incompatible\n // column or relation) must not turn a successful mutation into an error. Fall back\n // to the raw rows — relations then resolve lazily via the batch loader — but surface\n // the cause so a genuine misconfiguration isn't silently hidden.\n console.warn(\n `[drizzle-graphql] eager-loading relations for a \"${tableName}\" mutation failed; ` +\n 'falling back to lazy resolution.',\n err,\n );\n return rows;\n }\n\n // Merge the fetched relations onto the RETURNING rows in place, preserving order. A row\n // the re-fetch didn't return (e.g. deleted concurrently) keeps its scalar columns and\n // its relations resolve lazily, so the result never reports fewer rows than were mutated.\n const byKey = new Map(enriched.map((e) => [keyOf(e), e]));\n for (const row of rows) {\n const match = byKey.get(keyOf(row));\n if (!match) {\n continue;\n }\n for (const rel of relationNames) {\n row[rel] = match[rel];\n }\n }\n return rows;\n};\n","// @ts-nocheck\nconst DRIZZLE_LOADERS_KEY = Symbol('drizzle-graphql-loaders');\n\ntype BatchFn<K, V> = (keys: readonly K[]) => Promise<readonly V[]>;\n\nclass BatchLoader<K, V> {\n private batch: Array<{ key: K; resolve: (v: V) => void; reject: (e: unknown) => void }> = [];\n private scheduled = false;\n\n constructor(private readonly batchFn: BatchFn<K, V>) {}\n\n load(key: K): Promise<V> {\n return new Promise<V>((resolve, reject) => {\n this.batch.push({ key, resolve, reject });\n if (!this.scheduled) {\n this.scheduled = true;\n Promise.resolve().then(() => this.dispatch());\n }\n });\n }\n\n private async dispatch(): Promise<void> {\n const current = this.batch.splice(0);\n this.scheduled = false;\n try {\n const results = await this.batchFn(current.map(({ key }) => key));\n for (let i = 0; i < current.length; i++) {\n current[i]!.resolve(results[i] as V);\n }\n } catch (err) {\n for (const { reject } of current) {\n reject(err);\n }\n }\n }\n}\n\n/**\n * Returns a BatchLoader keyed by `key` on the GraphQL context object.\n * Loaders are stored under a Symbol so they never collide with consumer properties.\n * If context is absent or not an object, a fresh (unbatched) loader is returned.\n */\nexport const getOrCreateLoader = <K, V>(context: any, key: string, batchFn: BatchFn<K, V>): BatchLoader<K, V> => {\n if (!context || typeof context !== 'object') {\n return new BatchLoader<K, V>(batchFn);\n }\n if (!context[DRIZZLE_LOADERS_KEY]) {\n context[DRIZZLE_LOADERS_KEY] = new Map<string, BatchLoader<any, any>>();\n }\n const loaders = context[DRIZZLE_LOADERS_KEY] as Map<string, BatchLoader<any, any>>;\n if (!loaders.has(key)) {\n loaders.set(key, new BatchLoader<K, V>(batchFn));\n }\n return loaders.get(key) as BatchLoader<K, V>;\n};\n","import pluralize from 'pluralize';\n\nexport const uncapitalize = <T extends string>(input: T) =>\n (input?.length\n ? `${input[0]!.toLocaleLowerCase()}${input.length > 1 ? input.slice(1, input.length) : ''}`\n : input) as Uncapitalize<T>;\n\nexport const capitalize = <T extends string>(input: T) =>\n (input?.length\n ? `${input[0]!.toLocaleUpperCase()}${input.length > 1 ? input.slice(1, input.length) : ''}`\n : input) as Capitalize<T>;\n\nexport const singularize = <T extends string>(input: T) => pluralize.singular(input);\n\nexport const cleanTableName = <T extends string>(input: T) => singularize(uncapitalize(input));\n\nexport const tableNameToModel = <T extends string>(input: T) => singularize(capitalize(input));\n\n// (input.length\n// ? `${input[-]!.toLocaleUpperCase()}${input.length > 1 ? input.slice(1, input.length) : \"\"}`\n// : input) as Capitalize<T>;\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { type Column, getTableColumns, is, One, type Table } from 'drizzle-orm';\nimport { GraphQLError } from 'graphql';\nimport type { TableNamedRelations } from '../builders/index.ts';\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 // 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 // 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 { 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","import type { Column } from 'drizzle-orm';\nimport { extractExtendedColumnType, 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 GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n type 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 { ConvertedColumn } from './types.ts';\n\nconst allowedNameChars = /^[a-zA-Z0-9_]+$/;\n\nconst enumMap = new WeakMap<object, GraphQLEnumType>();\nconst generateEnumCached = (column: Column, columnName: string, tableName: string): GraphQLEnumType => {\n if (enumMap.has(column)) {\n return enumMap.get(column)!;\n }\n\n const gqlEnum = new GraphQLEnumType({\n name: `${capitalize(tableName)}${capitalize(columnName)}Enum`,\n values: Object.fromEntries(\n column.enumValues!.map((e, index) => [\n allowedNameChars.test(e) ? e : `Option${index}`,\n {\n value: e,\n description: `Value: ${e}`,\n },\n ]),\n ),\n });\n\n enumMap.set(column, gqlEnum);\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 innerDesc = inner.description ?? (inner.type as GraphQLScalarType).name;\n\n let type: ConvertedColumn<boolean>['type'] = inner.type;\n let description = innerDesc;\n for (let i = 0; i < dimensions; i++) {\n type = new GraphQLList(new GraphQLNonNull(type as GraphQLScalarType));\n description = `Array<${description}>`;\n }\n\n return { type, description };\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, description: 'Boolean' };\n case 'object':\n if (column instanceof PgTimestamp || column instanceof PgDate) {\n return { type: GraphQLDateTime, description: 'DateTime' };\n }\n return column.columnType === 'PgGeometryObject'\n ? {\n type: isInput ? geoXyInputType : geoXyType,\n description: 'Geometry points XY',\n }\n : column.columnType === 'PgBytea'\n ? {\n type: new GraphQLList(new GraphQLNonNull(GraphQLInt)),\n description: 'Buffer',\n }\n : { type: GraphQLJSON, description: '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, description: 'Decimal' };\n }\n\n if (column instanceof PgTimestamp || column instanceof PgTimestampString) {\n return { type: GraphQLDateTime, description: 'DateTime' };\n }\n if (column instanceof PgUUID) {\n return { type: GraphQLUUID, description: '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, description: 'Date' } : { type: GraphQLDate, description: 'Date' };\n }\n\n return { type: GraphQLString, description: 'String' };\n case 'bigint':\n return { type: GraphQLBigIntString, description: '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, description: 'Integer' }\n : { type: GraphQLFloat, description: 'Float' };\n }\n case 'array': {\n if (column.columnType === 'PgVector') {\n return {\n type: new GraphQLList(new GraphQLNonNull(GraphQLFloat)),\n description: 'Array<Float>',\n };\n }\n\n if (column.columnType === 'PgGeometry') {\n return {\n type: new GraphQLList(new GraphQLNonNull(GraphQLFloat)),\n description: '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 description: `Array<${innerType.description}>`,\n };\n }\n default:\n throw new Error(`Drizzle-GraphQL Error: Type ${column.dataType} is not implemented!`);\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 typeDesc = columnToGraphQLCore(column, columnName, tableName, isInput);\n const noDesc = ['string', 'boolean', 'number'];\n const { type: baseType } = extractExtendedColumnType(column);\n if (noDesc.find((e) => e === baseType)) {\n delete typeDesc.description;\n }\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 description: typeDesc.description,\n } as ConvertedColumn<TIsInput>;\n }\n\n return typeDesc as ConvertedColumn<TIsInput>;\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 GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\n\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n aggregateFieldComplexity,\n assertSingleMatch,\n attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createRelationResolverFactory,\n extractFilters,\n extractRequiredFilters,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n getPrimaryKeyPropNamesFromConfig,\n listFieldComplexity,\n mysqlValuesColumnRef,\n type OnConflictArg,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n relationFilterCtx,\n resolveConflictPlan,\n resolveExecutor,\n resolveQueryExecutor,\n runRelationalSelect,\n selectArrayArgs,\n selectSingleArgs,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n} from '../builders/common.ts';\nimport { remapFromGraphQLArrayInput, remapFromGraphQLSingleInput } from '../data-mappers/index.ts';\nimport {\n createRelationAggregateFactory,\n generateAggregate,\n generateAggregateTypes,\n generateGroupBy,\n generateGroupByEnum,\n generateGroupByType,\n generateHavingInput,\n} from './aggregates.ts';\nimport type {\n CreatedResolver,\n Filters,\n SchemaGeneratorOptions,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst generateSelectArray = (\n db: MySqlDatabase<any, any, any>,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n distinctEnabled: boolean = true,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const table = tables[tableName]!;\n const pkNames = mysqlPrimaryKeyPropNames(table as MySqlTable);\n const queryArgs = selectArrayArgs(\n orderArgs,\n filterArgs,\n distinctEnabled ? generateDistinctEnum(table, typeName) : undefined,\n );\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: false,\n filterCtx,\n pkNames,\n db: executor,\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateSelectSingle = (\n db: MySqlDatabase<any, any, any>,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const queryArgs = selectSingleArgs(orderArgs, filterArgs);\n\n const table = tables[tableName]!;\n const pkNames = mysqlPrimaryKeyPropNames(table as MySqlTable);\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n pkNames,\n db: executor,\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateInsertArray = (\n db: MySqlDatabase<any, any, any, any>,\n _tableName: string,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n): 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 const input = remapFromGraphQLArrayInput(args.values, table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n\n await resolveExecutor(db, context).insert(table).values(input);\n\n return { isSuccess: true };\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): 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 const input = remapFromGraphQLSingleInput(args.values, table);\n\n await resolveExecutor(db, context).insert(table).values(input);\n\n return { isSuccess: true };\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateUpsert = (\n db: MySqlDatabase<any, any, any, any>,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n onConflictType: GraphQLInputObjectType,\n fieldName: string,\n single: boolean,\n): 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 const input = single\n ? [remapFromGraphQLSingleInput(args.values as Record<string, any>, table)]\n : remapFromGraphQLArrayInput(args.values as Record<string, any>[], table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n\n // MySQL's ON DUPLICATE KEY UPDATE fires on whichever unique key was violated, so\n // there is no target to resolve and no predicate to attach.\n const plan = resolveConflictPlan({\n table,\n values: input,\n onConflict: args.onConflict,\n pkNames,\n uniqueSets: [],\n excludedRef: mysqlValuesColumnRef,\n withTarget: false,\n });\n\n const executor = resolveExecutor(db, context);\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 } 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): 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 const { where, set } = args;\n\n const input = remapFromGraphQLSingleInput(set, table);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n const executor = resolveExecutor(db, context);\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 } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateDelete = (\n db: MySqlDatabase<any, any, any>,\n tableName: string,\n table: MySqlTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n single: boolean,\n requireWhere: boolean,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, _info) => {\n try {\n const { where } = args;\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n const executor = resolveExecutor(db, context);\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n await query;\n\n return { isSuccess: true };\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\n/** Primary-key property names for a MySQL table, including table-level composite keys. */\nconst mysqlPrimaryKeyPropNames = (table: MySqlTable): string[] =>\n getPrimaryKeyPropNamesFromConfig(table, getTableConfig);\n\nexport const generateSchemaData = <\n TDrizzleInstance extends MySqlDatabase<any, any, any, any>,\n TSchema extends Record<string, Table | unknown>,\n>(\n db: TDrizzleInstance,\n schema: TSchema,\n relations: TablesRelationalConfig,\n options: SchemaGeneratorOptions,\n): GeneratedEntities<TDrizzleInstance, TSchema> => {\n const { relationsDepthLimit, prefixes, suffixes, typeNameMapper, shouldEagerLoad, features, complexity } = options;\n const rawSchema = schema;\n const schemaEntries = Object.entries(rawSchema);\n\n const tableEntries = schemaEntries.filter(([_key, value]) => is(value, MySqlTable)) as [string, MySqlTable][];\n const tables = Object.fromEntries(tableEntries);\n\n if (!tableEntries.length) {\n throw new Error(\n \"Drizzle-GraphQL Error: No tables detected in Drizzle-ORM's database instance. Did you forget to pass schema to drizzle constructor?\",\n );\n }\n\n // Build namedRelations from the drizzle-orm v1 relations config.\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Record each relation target's (composite-aware) primary key for deterministic\n // paginated ordering. Must run before pruning / type generation (shared entry objects).\n attachTargetPrimaryKeys(namedRelations, tables, mysqlPrimaryKeyPropNames);\n // Pruned map for query resolvers' `with:`; type generation keeps the full map.\n const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);\n\n const filterCtx: RelationFilterBase = { tables, relationMap: namedRelations };\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(db, tables, filterCtx);\n\n // Fresh cache per generateSchemaData call — prevents type name collisions\n // when buildSchema() is called multiple times.\n const cacheCtx: TypeCacheCtx = {\n genericFilterCache: new Map(),\n objectTypeCache: new Map(),\n relationFieldContainers: new Map(),\n fullyBuiltTables: new Set(),\n relationTypeCache: new Map(),\n orderTypeCache: new WeakMap(),\n filterTypeCache: new WeakMap(),\n listRelationFilterCache: new Map(),\n aggregateTypeCache: new Map(),\n complexity,\n };\n\n // Left undefined when the feature is off — generateTableTypes then emits no\n // `${relation}Aggregate` fields at all.\n const relationAggregateFactory: RelationAggregateFactory | undefined = features.relationAggregates\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx)\n : undefined;\n\n const queries: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const mutations: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const gqlSchemaTypes = Object.fromEntries(\n Object.entries(tables).map(([tableName, _table]) => [\n tableName,\n generateTableTypes(\n tableName,\n tables,\n namedRelations,\n false,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n prefixes.insert,\n prefixes.update,\n resolverFactory,\n relationAggregateFactory,\n ),\n ]),\n );\n\n const mutationReturnType = new GraphQLObjectType({\n name: 'MutationReturn',\n fields: {\n isSuccess: {\n type: new GraphQLNonNull(GraphQLBoolean),\n },\n },\n });\n\n const inputs: Record<string, GraphQLInputObjectType> = {};\n const outputs: Record<string, GraphQLObjectType> = {};\n // Every MySQL mutation returns it, so it only belongs in the type map when at least one\n // mutation is generated.\n if (features.insert || features.upsert || features.update || features.delete) {\n outputs.MutationReturn = mutationReturnType;\n }\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n const { insertInput, updateInput, tableFilters, tableOrder } = tableTypes.inputs;\n const { selectSingleOutput, selectArrOutput } = tableTypes.outputs;\n\n // Compute field names using the mapper logic\n const {\n typeName,\n listFieldName,\n singleFieldName,\n aggregateFieldName,\n groupByFieldName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n updateSingleFieldName,\n deleteFieldName,\n deleteSingleFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\n\n const selectArrGenerated = generateSelectArray(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n listFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n features.distinct,\n );\n const selectSingleGenerated = generateSelectSingle(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n singleFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n );\n const insertArrGenerated = features.insert\n ? generateInsertArray(db, tableName, schema[tableName] as MySqlTable, insertInput, createArrayFieldName)\n : undefined;\n const insertSingleGenerated = features.insert\n ? generateInsertSingle(db, tableName, schema[tableName] as MySqlTable, insertInput, createSingleFieldName)\n : undefined;\n // MySQL detects a conflict on any unique key, so unlike PostgreSQL and SQLite every\n // table can be upserted — there is no target to validate.\n const onConflictInput = features.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as MySqlTable,\n typeName,\n uniqueSets: [],\n tableFilters,\n withTarget: false,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(db, schema[tableName] as MySqlTable, insertInput, onConflictInput, upsertArrayFieldName, false)\n : undefined;\n const upsertSingleGenerated = onConflictInput\n ? generateUpsert(db, schema[tableName] as MySqlTable, insertInput, onConflictInput, upsertSingleFieldName, true)\n : undefined;\n const updateGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateFieldName,\n false,\n features.requireWhere,\n filterCtx,\n )\n : undefined;\n const updateSingleGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n true,\n features.requireWhere,\n filterCtx,\n )\n : undefined;\n const deleteGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteFieldName,\n false,\n features.requireWhere,\n filterCtx,\n )\n : undefined;\n const deleteSingleGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteSingleFieldName,\n true,\n features.requireWhere,\n filterCtx,\n )\n : undefined;\n const aggregateType = features.aggregates\n ? generateAggregateTypes(schema[tableName] as MySqlTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = features.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n features.aggregates && features.groupBy\n ? generateGroupByType(schema[tableName] as MySqlTable, tableName, typeName, cacheCtx)\n : undefined;\n const groupByEnum = groupByType\n ? generateGroupByEnum(schema[tableName] as MySqlTable, tableName, typeName)\n : undefined;\n const havingInput = groupByEnum\n ? generateHavingInput(schema[tableName] as MySqlTable, tableName, typeName)\n : undefined;\n const groupByGenerated =\n groupByType && groupByEnum && havingInput\n ? generateGroupBy(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n typeName,\n groupByFieldName,\n tableFilters,\n groupByEnum,\n havingInput,\n filterCtx,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n ...(complexity ? { extensions: { complexity: listFieldComplexity(complexity) } } : {}),\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n for (const generated of [\n insertArrGenerated,\n insertSingleGenerated,\n upsertArrGenerated,\n upsertSingleGenerated,\n updateGenerated,\n updateSingleGenerated,\n deleteGenerated,\n deleteSingleGenerated,\n ]) {\n if (generated) {\n mutations[generated.name] = {\n type: mutationReturnType,\n args: generated.args,\n resolve: generated.resolver,\n };\n }\n }\n // The insert/update inputs are still built (they type the mutations that survive) but\n // only reach the schema's type map when a mutation actually references them.\n const activeInputs = [\n // The insert input types the upsert mutations too, so either feature keeps it.\n ...(features.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(features.update ? [updateInput] : []),\n 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 const fieldResolvers: Record<string, Record<string, any>> = {};\n for (const [tableName, tableRelations] of Object.entries(namedRelations)) {\n const relResolvers: Record<string, any> = {};\n for (const [relName, relEntry] of Object.entries(tableRelations)) {\n const isOne = is((relEntry as any).relation ?? relEntry, One);\n const resolver = resolverFactory({ tableName, relationName: relName, relEntry, isOne });\n if (resolver) {\n relResolvers[relName] = resolver;\n }\n }\n if (Object.keys(relResolvers).length > 0) {\n fieldResolvers[tableName] = relResolvers;\n }\n }\n\n return { queries, mutations, inputs, types: outputs, fieldResolvers } as any;\n};\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport {\n and,\n avg,\n type Column,\n count,\n countDistinct,\n eq,\n extractExtendedColumnType,\n getColumns,\n gt,\n gte,\n inArray,\n lt,\n lte,\n max,\n min,\n ne,\n sum,\n type Table,\n} from 'drizzle-orm';\nimport {\n type GraphQLEnumType,\n GraphQLError,\n GraphQLFloat,\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\nimport { getOrCreateLoader } from '../batch-loader/index.ts';\nimport { capitalize } from '../case-ops/index.ts';\nimport { remapToGraphQLCore } from '../data-mappers/index.ts';\nimport { drizzleColumnToGraphQLType } from '../type-converter/index.ts';\nimport type { ConvertedColumn } from '../type-converter/types.ts';\nimport {\n extractFilters,\n extractRelationJoinColumns,\n generateColumnEnum,\n type RelationAggregateFactory,\n type RelationFilterBase,\n relationFilterCtx,\n resolveExecutor,\n resolveTypeName,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n} from './common.ts';\nimport type { CreatedResolver, Filters } from './types.ts';\n\n/** Operations that aggregate over a set of column values. `count` is handled separately (whole rows). */\nconst AGGREGATE_OPS = ['avg', 'sum', 'min', 'max', 'countNonNull', 'countDistinct'] as const;\ntype AggregateOp = (typeof AGGREGATE_OPS)[number];\n\n/** Ops whose result is a row count: never null, and returned as `Int!` rather than the column's type. */\nconst COUNT_OPS = new Set<AggregateOp>(['countNonNull', 'countDistinct']);\n\nconst OP_FNS: Record<AggregateOp, (col: Column) => any> = {\n avg,\n sum,\n min,\n max,\n countNonNull: count,\n countDistinct,\n};\n\n/** Separator for flat select aliases (`avg__price`) — reassembled into nested output by the resolver. */\nconst SEP = '__';\n\ninterface AggregateColumnSets {\n /** Columns avg/sum apply to: plain Int/Float scalars. */\n numeric: Record<string, Column>;\n /** Columns min/max apply to: anything with a total ordering the DB supports (numbers, strings, dates, enums). */\n orderable: Record<string, { column: Column; converted: ConvertedColumn }>;\n /** Every column — `count(col)` is valid whatever the type. */\n all: Record<string, Column>;\n}\n\n/**\n * Classifies a table's columns for aggregation. avg/sum only make sense on numeric scalars;\n * min/max work on any orderable scalar (numbers, strings, bigints, dates, enums). Booleans,\n * arrays (including array-typed number columns), JSON, buffers, and object-shaped columns\n * (e.g. geometry) are excluded entirely.\n */\nconst classifyAggregateColumns = (table: Table, tableName: string): AggregateColumnSets => {\n const numeric: AggregateColumnSets['numeric'] = {};\n const orderable: AggregateColumnSets['orderable'] = {};\n const all: AggregateColumnSets['all'] = {};\n\n for (const [columnName, column] of Object.entries(getColumns(table))) {\n all[columnName] = column;\n const converted = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, false);\n const gqlType = converted.type;\n\n // Anything that isn't a plain scalar in the generated schema (arrays, geometry objects)\n // has no meaningful min/max. This also catches array-typed number columns, which keep\n // their scalar drizzle dataType but convert to a GraphQL list.\n if (gqlType instanceof GraphQLList || gqlType instanceof GraphQLObjectType) {\n continue;\n }\n\n // Classify on the drizzle data type rather than the GraphQL one: date columns convert to\n // different GraphQL scalars per dialect, but are orderable everywhere.\n const { type: dataType, constraint } = extractExtendedColumnType(column);\n if (dataType === 'boolean' || dataType === 'array' || dataType === 'custom') {\n continue;\n }\n if (dataType === 'object' && constraint !== 'date') {\n continue;\n }\n\n orderable[columnName] = { column, converted };\n if (dataType === 'number') {\n numeric[columnName] = column;\n }\n }\n\n return { numeric, orderable, all };\n};\n\n/**\n * Builds the `${typeName}Aggregate` output type for a table:\n * - `count: Int!` — number of matching rows\n * - `avg` / `sum` — per numeric column, always nullable Float (SQL returns NULL on empty sets,\n * and avg/sum of integers overflow Int / produce decimals)\n * - `min` / `max` — per orderable column, the column's own (nullable) scalar type\n * - `countNonNull` — per column, `Int!`: how many matching rows have a non-null value there\n * - `countDistinct` — per orderable column, `Int!`: how many distinct non-null values there are\n * Each wrapper is omitted when no column qualifies for it.\n */\nexport const generateAggregateTypes = (\n table: Table,\n tableName: string,\n typeName: string,\n cacheCtx?: TypeCacheCtx,\n): GraphQLObjectType => {\n const cached = cacheCtx?.aggregateTypeCache.get(tableName);\n if (cached) {\n return cached;\n }\n\n const { numeric, orderable, all } = classifyAggregateColumns(table, tableName);\n\n const fields: Record<string, { type: any }> = {\n count: { type: new GraphQLNonNull(GraphQLInt) },\n };\n\n if (Object.keys(numeric).length) {\n for (const op of ['avg', 'sum'] as const) {\n fields[op] = {\n type: new GraphQLObjectType({\n name: `${typeName}${capitalize(op)}Aggregate`,\n fields: Object.fromEntries(Object.keys(numeric).map((columnName) => [columnName, { type: GraphQLFloat }])),\n }),\n };\n }\n }\n\n if (Object.keys(orderable).length) {\n for (const op of ['min', 'max'] as const) {\n fields[op] = {\n type: new GraphQLObjectType({\n name: `${typeName}${capitalize(op)}Aggregate`,\n fields: Object.fromEntries(\n Object.entries(orderable).map(([columnName, { converted }]) => [\n columnName,\n { type: converted.type, description: converted.description },\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.description === 'DateTime')\n .map(([columnName]) => columnName),\n ),\n };\n};\n\n/**\n * Reads the requested count/avg/sum/min/max selections off the resolve tree and turns them\n * into one drizzle select expression per (op, column) pair. An empty `selection` means the\n * client asked for nothing runnable (`__typename` only, or empty sub-selections).\n */\nconst parseAggregateRequest = (\n info: any,\n target: AggregateTarget,\n rootTypeName = `${target.typeName}Aggregate`,\n): AggregateRequest => {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const selectionTree = parsedInfo.fieldsByTypeName[rootTypeName] ?? {};\n\n const request: AggregateRequest = {\n count: false,\n ops: { avg: [], sum: [], min: [], max: [], countNonNull: [], countDistinct: [] },\n selection: {},\n };\n\n // Keys are aliases; `field.name` is the real field. Duplicate selections of the same\n // field under different aliases collapse into one SQL expression — graphql-js resolves\n // every alias from the same result property.\n for (const field of Object.values(selectionTree) as ResolveTree[]) {\n if (field.name === 'count') {\n request.count = true;\n request.selection.count = count();\n continue;\n }\n\n if (!AGGREGATE_OPS.includes(field.name as AggregateOp)) {\n continue;\n }\n const op = field.name as AggregateOp;\n const subTree = field.fieldsByTypeName[`${target.typeName}${capitalize(op)}Aggregate`];\n if (!subTree) {\n continue;\n }\n\n for (const subField of Object.values(subTree) as ResolveTree[]) {\n const columnName = subField.name;\n const column = target.columns[columnName];\n if (!column || request.ops[op].includes(columnName)) {\n continue;\n }\n request.ops[op].push(columnName);\n request.selection[`${op}${SEP}${columnName}`] = OP_FNS[op](column);\n }\n }\n\n return request;\n};\n\n/** Reassembles a flat aggregate row (`avg__price`) into the nested GraphQL shape. */\nconst assembleAggregateRow = (row: Record<string, any>, request: AggregateRequest, target: AggregateTarget) => {\n const result: Record<string, any> = {};\n\n if (request.count) {\n // drizzle's count() maps to number already; guard for drivers returning strings.\n result.count = row.count == null ? 0 : Number(row.count);\n }\n\n for (const op of AGGREGATE_OPS) {\n if (!request.ops[op].length) {\n continue;\n }\n const opResult: Record<string, any> = {};\n for (const columnName of request.ops[op]) {\n const value = row[`${op}${SEP}${columnName}`];\n if (COUNT_OPS.has(op)) {\n // A count is never null: an empty set counts to 0, and a missing group means no rows.\n opResult[columnName] = value == null ? 0 : Number(value);\n } else if (value == null) {\n opResult[columnName] = null;\n } else if (op === 'avg' || op === 'sum') {\n // Drivers return numeric/decimal aggregates as strings — coerce to Float.\n opResult[columnName] = Number(value);\n } else {\n // min/max keep the column's own type — drizzle already ran the column's decoder over\n // the value (`min`/`max` are `mapWith(column)`), so all that's left is coercing a\n // leftover raw date string (PG decodes timestamps in driver-level codecs, which raw\n // select expressions bypass) and remapping for GraphQL output.\n const column = target.columns[columnName];\n const decoded =\n typeof value === 'string' && target.dateTimeColumns.has(columnName) ? parseDriverDateTime(value) : value;\n opResult[columnName] = remapToGraphQLCore(columnName, decoded, target.tableName, column);\n }\n }\n result[op] = opResult;\n }\n\n return result;\n};\n\n/**\n * Creates the resolver for a table's aggregate query field. Reads the requested\n * count/avg/sum/min/max selections from the resolve tree, runs them all as a single\n * `SELECT` with one aggregate expression per requested (op, column) pair, and\n * reassembles the flat row into the nested GraphQL shape.\n *\n * Shared by all three dialects — it only relies on `db.select().from().where()`.\n */\nexport const generateAggregate = (\n db: any,\n tableName: string,\n table: Table,\n typeName: string,\n fieldName: string,\n filterArgs: GraphQLInputObjectType,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const target = aggregateTarget(table, tableName, typeName);\n\n const queryArgs = {\n where: { type: filterArgs },\n };\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, info) => {\n try {\n const request = parseAggregateRequest(info, target);\n if (!Object.keys(request.selection).length) {\n return {};\n }\n\n let query = resolveExecutor(db, context).select(request.selection).from(table);\n if (args.where) {\n query = query.where(extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName)));\n }\n const rows = await query;\n\n return assembleAggregateRow(rows[0] ?? {}, request, target);\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\n/** Alias the grouping key is selected under. Prefixed so it can't collide with `${op}__${column}`. */\nconst GROUP_KEY = '__dgql_group_key';\n\n/**\n * Builds the `${relationName}Aggregate` field that hangs off a parent type for each to-many\n * relation — `user { postsAggregate { count } }`.\n *\n * Resolution is batched the same way relation fields are: every parent row in the current tick\n * that asked for the same relation with the same arguments is served by one\n * `SELECT fk, <aggregates> ... WHERE fk IN (...) GROUP BY fk`, so a list of N parents costs one\n * extra query rather than N. Parents with no matching related rows get `count: 0` and `null`\n * for every other aggregate.\n */\nexport const createRelationAggregateFactory = (\n db: any,\n tables: Record<string, Table>,\n cacheCtx: TypeCacheCtx,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): RelationAggregateFactory => {\n return ({ tableName, relationName, relEntry }) => {\n const parentTable = tables[tableName];\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n\n if (!parentTable || !targetTable) {\n return undefined;\n }\n\n const joinCols = extractRelationJoinColumns(relEntry, parentTable, targetTable);\n if (!joinCols) {\n return undefined;\n }\n const { localColPropName, foreignCol } = joinCols;\n\n const targetTypeName = resolveTypeName(targetTableName, typeNameMapper);\n const type = generateAggregateTypes(targetTable, targetTableName, targetTypeName, cacheCtx);\n const target = aggregateTarget(targetTable, targetTableName, targetTypeName);\n\n const resolve = async (parent: any, args: { where?: Filters<Table> }, context: any, info: any) => {\n try {\n const request = parseAggregateRequest(info, target);\n if (!Object.keys(request.selection).length) {\n return {};\n }\n\n const localValue = parent[localColPropName];\n // No key to correlate on — the relation is empty by definition.\n if (localValue == null) {\n return assembleAggregateRow({}, request, target);\n }\n\n const whereArg = args?.where;\n // Siblings only share a batch when they'd run the same query: same filters, same aggregates.\n const argsKey = JSON.stringify({\n where: whereArg ?? null,\n selection: Object.keys(request.selection).sort(),\n });\n const loaderKey = `${tableName}::${relationName}::aggregate::${argsKey}`;\n\n const loader = getOrCreateLoader(context, loaderKey, async (parentIds: readonly any[]) => {\n // Loaders are cached per context, so the whole batch shares this request's executor.\n const executor = resolveExecutor(db, context);\n const uniqueIds = [...new Set(parentIds)];\n const whereCondition = and(\n inArray(foreignCol, uniqueIds),\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n );\n\n const rows: any[] = await executor\n .select({ [GROUP_KEY]: foreignCol, ...request.selection })\n .from(targetTable)\n .where(whereCondition)\n .groupBy(foreignCol);\n\n const byKey = new Map(rows.map((row) => [row[GROUP_KEY], row]));\n\n // A parent with no matching rows produces no group — hand back an empty row so it\n // assembles to count 0 / null aggregates rather than dropping the field.\n return parentIds.map((id) => byKey.get(id) ?? {});\n });\n\n return assembleAggregateRow(await loader.load(localValue), request, target);\n } catch (e) {\n throw toGraphQLError(e);\n }\n };\n\n return { type, resolve };\n };\n};\n\n// ── group by ──────────────────────────────────────────────────────────────────\n\n/** Alias prefix for grouped columns, kept clear of the `${op}__${column}` aggregate aliases. */\nconst GROUP_COL = `group${SEP}`;\n\n/** Comparison operators a `having` clause can apply to an aggregated value. */\nconst HAVING_OPS = { eq, ne, gt, gte, lt, lte } as const;\n\n/**\n * Columns a query can group on. Grouping needs an equality operator, which is the same\n * requirement min/max has, plus booleans — orderable excludes them because a min/max over\n * true/false says nothing, but `GROUP BY isConfirmed` is perfectly ordinary.\n */\nconst groupableColumns = (\n table: Table,\n tableName: string,\n): Record<string, { column: Column; converted: ConvertedColumn }> => {\n const { orderable } = classifyAggregateColumns(table, tableName);\n const groupable: Record<string, { column: Column; converted: ConvertedColumn }> = { ...orderable };\n\n for (const [columnName, column] of Object.entries(getColumns(table))) {\n if (groupable[columnName]) {\n continue;\n }\n const { type: dataType } = extractExtendedColumnType(column);\n if (dataType !== 'boolean') {\n continue;\n }\n groupable[columnName] = {\n column,\n converted: drizzleColumnToGraphQLType(column, columnName, tableName, true, false, false),\n };\n }\n\n return groupable;\n};\n\n/** The `${typeName}GroupByColumn` enum listing what a group-by query can group on. */\nexport const generateGroupByEnum = (table: Table, tableName: string, typeName: string): GraphQLEnumType | undefined => {\n const groupable = groupableColumns(table, tableName);\n\n return generateColumnEnum(\n table,\n `${typeName}GroupByColumn`,\n `Columns of ${typeName} that a query can group by`,\n (_column, columnName) => Boolean(groupable[columnName]),\n );\n};\n\n/** Shared by every `having` clause, so it is created once rather than per table. */\nexport const aggregateNumberFilter = new GraphQLInputObjectType({\n name: 'AggregateNumberFilter',\n description: 'Compares an aggregated value. Several operators in one filter are ANDed together.',\n fields: Object.fromEntries(Object.keys(HAVING_OPS).map((op) => [op, { type: GraphQLFloat }])),\n});\n\n/**\n * The `${typeName}Having` input: one entry per aggregate the group-by query can filter on.\n * Several entries are ANDed together, as are several operators within one entry.\n *\n * `min`/`max` are limited to numeric columns here even though the output type computes them\n * for every orderable column — the comparison is numeric, so a min over a text column has\n * nothing to compare against.\n */\nexport const generateHavingInput = (table: Table, tableName: string, typeName: string): GraphQLInputObjectType => {\n const { numeric, orderable, all } = classifyAggregateColumns(table, tableName);\n\n const fields: Record<string, { type: any; description?: string }> = {\n count: { type: aggregateNumberFilter, description: 'Filters groups by how many rows they contain' },\n };\n\n const opColumns: Record<string, Record<string, unknown>> = {\n avg: numeric,\n sum: numeric,\n min: numeric,\n max: numeric,\n countNonNull: all,\n countDistinct: orderable,\n };\n\n for (const [op, columns] of Object.entries(opColumns)) {\n const columnNames = Object.keys(columns);\n if (!columnNames.length) {\n continue;\n }\n fields[op] = {\n type: new GraphQLInputObjectType({\n name: `${typeName}${capitalize(op)}Having`,\n fields: Object.fromEntries(columnNames.map((columnName) => [columnName, { type: aggregateNumberFilter }])),\n }),\n };\n }\n\n return new GraphQLInputObjectType({\n name: `${typeName}Having`,\n description: `Filters ${typeName} groups by their aggregated values`,\n fields,\n });\n};\n\n/**\n * The `${typeName}GroupBy` output type: the grouped columns under `group`, alongside the same\n * aggregate fields the `${typeName}Aggregate` type carries — the wrapper types are the very\n * same instances, so the schema holds one `${typeName}AvgAggregate` however it is reached.\n *\n * The keys are nested rather than spread across the top level so a column called `count`,\n * `avg` or `min` cannot collide with the aggregate it sits next to.\n */\nexport const generateGroupByType = (\n table: Table,\n tableName: string,\n typeName: string,\n cacheCtx?: TypeCacheCtx,\n): GraphQLObjectType | undefined => {\n const groupable = groupableColumns(table, tableName);\n if (!Object.keys(groupable).length) {\n return undefined;\n }\n\n const keysType = new GraphQLObjectType({\n name: `${typeName}GroupKeys`,\n description: `The grouped column values of one ${typeName} group. A column the query did not group by is null.`,\n fields: Object.fromEntries(\n Object.entries(groupable).map(([columnName, { converted }]) => [\n columnName,\n { type: converted.type, description: converted.description },\n ]),\n ),\n });\n\n const aggregateType = generateAggregateTypes(table, tableName, typeName, cacheCtx);\n const aggregateFields = Object.fromEntries(\n Object.values(aggregateType.getFields()).map((field) => [\n field.name,\n { type: field.type, description: field.description ?? undefined },\n ]),\n );\n\n return new GraphQLObjectType({\n name: `${typeName}GroupBy`,\n fields: { group: { type: new GraphQLNonNull(keysType) }, ...aggregateFields },\n });\n};\n\n/** Turns one `${typeName}Having` entry into SQL conditions over the matching aggregate expression. */\nconst havingComparisons = (expression: any, filter: Record<string, any>): any[] =>\n Object.entries(filter)\n .filter(([op, value]) => value != null && op in HAVING_OPS)\n .map(([op, value]) => HAVING_OPS[op as keyof typeof HAVING_OPS](expression, value));\n\nconst buildHavingCondition = (having: Record<string, any> | undefined, columns: Record<string, Column>) => {\n if (!having) {\n return undefined;\n }\n\n const conditions: any[] = [];\n\n for (const [key, value] of Object.entries(having)) {\n if (value == null) {\n continue;\n }\n if (key === 'count') {\n conditions.push(...havingComparisons(count(), value));\n continue;\n }\n if (!AGGREGATE_OPS.includes(key as AggregateOp)) {\n continue;\n }\n for (const [columnName, filter] of Object.entries(value as Record<string, any>)) {\n const column = columns[columnName];\n if (!column || filter == null) {\n continue;\n }\n conditions.push(...havingComparisons(OP_FNS[key as AggregateOp](column), filter));\n }\n }\n\n return conditions.length ? and(...conditions) : undefined;\n};\n\n/**\n * Creates the resolver for a table's `<plural>GroupBy` query: the same aggregates the\n * `<plural>Aggregate` query computes, but one row per distinct combination of the requested\n * columns, optionally filtered on the aggregated values with `having`.\n *\n * Shared by all three dialects — `SELECT <keys>, <aggregates> FROM t WHERE … GROUP BY <keys>\n * HAVING …` is the same everywhere.\n */\nexport const generateGroupBy = (\n db: any,\n tableName: string,\n table: Table,\n typeName: string,\n fieldName: string,\n filterArgs: GraphQLInputObjectType,\n groupByEnum: GraphQLEnumType,\n havingInput: GraphQLInputObjectType,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const target = aggregateTarget(table, tableName, typeName);\n const groupable = groupableColumns(table, tableName);\n const columns = getColumns(table);\n const rootTypeName = `${typeName}GroupBy`;\n\n const queryArgs = {\n groupBy: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByEnum))),\n description: 'Columns to group by. One result row per distinct combination of their values.',\n },\n where: { type: filterArgs, description: 'Filters the rows before they are grouped.' },\n having: { type: havingInput, description: 'Filters the groups after they are aggregated.' },\n };\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { groupBy?: string[]; where?: Filters<Table>; having?: Record<string, any> },\n context,\n info,\n ) => {\n try {\n const requestedKeys = [...new Set(args.groupBy ?? [])];\n if (!requestedKeys.length) {\n throw new GraphQLError('At least one column to group by is required!');\n }\n\n const keyColumns = requestedKeys.map((columnName) => {\n const groupableColumn = groupable[columnName];\n if (!groupableColumn) {\n throw new GraphQLError(`Cannot group ${typeName} by ${columnName}!`);\n }\n return [columnName, groupableColumn.column] as const;\n });\n\n const request = parseAggregateRequest(info, target, rootTypeName);\n const selection = {\n ...Object.fromEntries(keyColumns.map(([columnName, column]) => [`${GROUP_COL}${columnName}`, column])),\n ...request.selection,\n };\n\n let query = resolveExecutor(db, context).select(selection).from(table);\n if (args.where) {\n query = query.where(extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName)));\n }\n query = query.groupBy(...keyColumns.map(([, column]) => column));\n\n const havingCondition = buildHavingCondition(args.having, columns);\n if (havingCondition) {\n query = query.having(havingCondition);\n }\n\n const rows: any[] = await query;\n\n return rows.map((row) => {\n const group: Record<string, any> = {};\n for (const [columnName, column] of keyColumns) {\n const value = row[`${GROUP_COL}${columnName}`];\n const decoded =\n typeof value === 'string' && target.dateTimeColumns.has(columnName) ? parseDriverDateTime(value) : value;\n group[columnName] = value == null ? null : remapToGraphQLCore(columnName, decoded, tableName, column);\n }\n\n return { group, ...assembleAggregateRow(row, request, target) };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { is, One, type Table, type View } from 'drizzle-orm';\nimport type { RelationalQueryBuilder } from 'drizzle-orm/mysql-core/query-builders/query';\nimport { getTableConfig, type PgAsyncDatabase, type PgColumn, PgTable } from 'drizzle-orm/pg-core';\nimport type { GraphQLFieldConfig, GraphQLFieldConfigArgumentMap, ThunkObjMap } from 'graphql';\nimport {\n GraphQLError,\n type GraphQLInputObjectType,\n GraphQLList,\n GraphQLNonNull,\n type GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n aggregateFieldComplexity,\n assertSingleMatch,\n attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createRelationResolverFactory,\n eagerLoadMutationRelations,\n excludedColumnRef,\n extractFilters,\n extractOrderBy,\n extractRequiredFilters,\n extractSelectedColumnsFromTreeSQLFormat,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n getPrimaryKeyPropNamesFromConfig,\n getUniqueColumnSets,\n listFieldComplexity,\n type OnConflictArg,\n prepareMutationRelationColumns,\n primaryKeyOrderExprs,\n primaryKeyRestriction,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n relationFilterCtx,\n resolveConflictPlan,\n resolveExecutor,\n resolveQueryExecutor,\n runRelationalSelect,\n type SelectionCtx,\n selectArrayArgs,\n selectDistinctKeys,\n selectSingleArgs,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n} from '../builders/common.ts';\nimport {\n remapFromGraphQLArrayInput,\n remapFromGraphQLSingleInput,\n remapToGraphQLArrayOutput,\n remapToGraphQLSingleOutput,\n} from '../data-mappers/index.ts';\nimport {\n createRelationAggregateFactory,\n generateAggregate,\n generateAggregateTypes,\n generateGroupBy,\n generateGroupByEnum,\n generateGroupByType,\n generateHavingInput,\n} from './aggregates.ts';\nimport type {\n CreatedResolver,\n Filters,\n SchemaGeneratorOptions,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst generateSelectArray = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n distinctEnabled: boolean = true,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n // Tables without relations won't have db.query support — fall back to basic select.\n\n const table = tables[tableName]!;\n const pkNames = pgPrimaryKeyPropNames(table as PgTable);\n const queryArgs = selectArrayArgs(\n orderArgs,\n filterArgs,\n distinctEnabled ? generateDistinctEnum(table, typeName) : undefined,\n );\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n\n if (requestQueryBase) {\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: false,\n filterCtx,\n pkNames,\n db: executor,\n });\n }\n\n // Fallback for tables without relational query builder support.\n // Use SQL column objects (not Record<string,true>) so db.select() receives valid expressions.\n const { offset, limit, orderBy, where, distinct } = args;\n const selectedColumnsSql = extractSelectedColumnsFromTreeSQLFormat<PgColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n { tableName, relationMap, tables },\n );\n const whereSql = where\n ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined;\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 (orderBy) {\n q = q.orderBy(\n ...extractOrderBy(table, orderBy, relationFilterCtx(filterCtx, tableName)),\n ...(distinctKeys ? primaryKeyOrderExprs(table, pkNames) : []),\n ) as any;\n } else if ((distinctKeys || offset != null || limit != null) && pkNames.length) {\n // See runRelationalSelect: an unordered slice is not stable between requests.\n q = q.orderBy(...primaryKeyOrderExprs(table, pkNames)) as any;\n }\n if (!distinctKeys) {\n if (offset) {\n q = q.offset(offset) as any;\n }\n if (limit) {\n q = q.limit(limit) as any;\n }\n }\n return remapToGraphQLArrayOutput(await q, tableName, table, relationMap);\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateSelectSingle = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n // Tables without relations won't have db.query support — fall back to basic select.\n\n const queryArgs = selectSingleArgs(orderArgs, filterArgs);\n\n const table = tables[tableName]!;\n const pkNames = pgPrimaryKeyPropNames(table as PgTable);\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n\n if (requestQueryBase) {\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n pkNames,\n db: executor,\n });\n }\n\n // Fallback for tables without relational query builder support.\n const { offset, orderBy, where } = args;\n const selectedColumnsSql = extractSelectedColumnsFromTreeSQLFormat<PgColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n { tableName, relationMap, tables },\n );\n let q = executor.select(selectedColumnsSql).from(table);\n if (where) {\n q = q.where(extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))) as any;\n }\n if (orderBy) {\n q = q.orderBy(...extractOrderBy(table, orderBy, relationFilterCtx(filterCtx, tableName))) as any;\n } else if (pkNames.length) {\n // A single query is an implicit `limit 1` — order it so the row is deterministic.\n q = q.orderBy(...primaryKeyOrderExprs(table, pkNames)) as any;\n }\n if (offset) {\n q = q.offset(offset) as any;\n }\n const rows = await q.limit(1);\n const result = rows[0];\n return result ? remapToGraphQLSingleOutput(result, tableName, table, relationMap) : undefined;\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\n/** Primary-key property names for a PG table, including table-level composite keys. */\nconst pgPrimaryKeyPropNames = (table: PgTable): string[] => getPrimaryKeyPropNamesFromConfig(table, getTableConfig);\n\nconst generateInsertArray = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n conflictDoNothing: boolean = false,\n): 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 const input = remapFromGraphQLArrayInput(args.values, table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const executor = resolveExecutor(db, context);\n let query = executor.insert(table).values(input).returning(columns);\n if (conflictDoNothing) {\n query = query.onConflictDoNothing() as any;\n }\n const result = await query;\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\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): 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 const input = remapFromGraphQLSingleInput(args.values, table);\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const executor = resolveExecutor(db, context);\n let query = executor.insert(table).values(input).returning(columns);\n if (conflictDoNothing) {\n query = query.onConflictDoNothing() as any;\n }\n const result = await query;\n\n if (!result[0]) {\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap);\n } 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): 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 const input = single\n ? [remapFromGraphQLSingleInput(args.values as Record<string, any>, table)]\n : remapFromGraphQLArrayInput(args.values as Record<string, any>[], table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const plan = resolveConflictPlan({\n table,\n values: input,\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 const executor = resolveExecutor(db, context);\n let query = executor.insert(table).values(input).returning(columns);\n query =\n plan.action === 'NOTHING'\n ? (query.onConflictDoNothing(plan.target ? { target: plan.target } : undefined) as any)\n : (query.onConflictDoUpdate({ target: plan.target!, set: plan.set, setWhere: plan.setWhere }) as any);\n\n const result = await query;\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 } 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): 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 const { where, set } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const input = remapFromGraphQLSingleInput(set, table);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n const executor = resolveExecutor(db, context);\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 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 && !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 } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateDelete = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n single: boolean,\n requireWhere: boolean,\n filterCtx?: RelationFilterBase,\n selectionCtx?: SelectionCtx,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, info) => {\n try {\n const { where } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const columns = extractSelectedColumnsFromTreeSQLFormat<PgColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n selectionCtx,\n );\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n const executor = resolveExecutor(db, context);\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) as any;\n\n const result = await query;\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row!`);\n }\n\n if (single) {\n return result[0] ? remapToGraphQLSingleOutput(result[0], tableName, table) : undefined;\n }\n\n return remapToGraphQLArrayOutput(result, tableName, table);\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\ntype SchemaEntry = Table<any> | View<string, boolean, any>;\n\nexport function generateSchemaData<\n TDrizzleInstance extends PgAsyncDatabase<any, any>,\n TRelations extends TablesRelationalConfig,\n TSchema extends Record<string, SchemaEntry>,\n>(\n db: TDrizzleInstance,\n schema: TSchema,\n relations: TRelations,\n options: SchemaGeneratorOptions,\n): GeneratedEntities<TDrizzleInstance, TSchema> {\n const {\n relationsDepthLimit,\n prefixes,\n suffixes,\n conflictDoNothing,\n typeNameMapper,\n shouldEagerLoad,\n features,\n complexity,\n } = options;\n const schemaEntries = Object.entries(schema);\n const tableEntries = schemaEntries.filter(([_key, value]) => is(value, PgTable)) as [string, PgTable][];\n const tables = Object.fromEntries(tableEntries) as Record<string, PgTable>;\n\n if (!tableEntries.length) {\n throw new Error(\n \"Drizzle-GraphQL Error: No tables detected in Drizzle-ORM's database instance. Did you forget to pass schema to drizzle constructor?\",\n );\n }\n\n // Flatten drizzle-orm v1 TablesRelationalConfig into the canonical shape\n // used throughout common.ts: Record<tableName, Record<relName, TableNamedRelations>>\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Record each relation target's primary key (composite-aware) so paginated relations\n // default to a deterministic PK order. Must run before pruning / type generation, which\n // share these entry objects.\n attachTargetPrimaryKeys(namedRelations, tables, pgPrimaryKeyPropNames);\n // Relations to eager-load via `with:`. Query/mutation resolvers use this pruned map so\n // opted-out relations never overfetch; type generation keeps the full map so their\n // fields still exist and resolve lazily.\n const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);\n\n const filterCtx: RelationFilterBase = { tables, relationMap: namedRelations };\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(db, tables, filterCtx);\n\n // Fresh cache per generateSchemaData call — prevents type name collisions\n // when buildSchema() is called multiple times.\n const cacheCtx: TypeCacheCtx = {\n genericFilterCache: new Map(),\n objectTypeCache: new Map(),\n relationFieldContainers: new Map(),\n fullyBuiltTables: new Set(),\n relationTypeCache: new Map(),\n orderTypeCache: new WeakMap(),\n filterTypeCache: new WeakMap(),\n listRelationFilterCache: new Map(),\n aggregateTypeCache: new Map(),\n complexity,\n };\n\n // Left undefined when the feature is off — generateTableTypes then emits no\n // `${relation}Aggregate` fields at all.\n const relationAggregateFactory: RelationAggregateFactory | undefined = features.relationAggregates\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx)\n : undefined;\n\n const queries: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const mutations: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n\n const gqlSchemaTypes = Object.fromEntries(\n Object.entries(tables).map(([tableName, _table]) => [\n tableName,\n generateTableTypes(\n tableName,\n tables,\n namedRelations,\n true,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n prefixes.insert,\n prefixes.update,\n resolverFactory,\n relationAggregateFactory,\n ),\n ]),\n );\n\n const inputs: Record<string, GraphQLInputObjectType> = {};\n const outputs: Record<string, GraphQLObjectType> = {};\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n const { insertInput, updateInput, tableFilters, tableOrder } = tableTypes.inputs;\n const { selectSingleOutput, selectArrOutput, singleTableItemOutput, arrTableItemOutput } = tableTypes.outputs;\n\n // Compute field names using the mapper logic\n const {\n typeName,\n listFieldName,\n singleFieldName,\n aggregateFieldName,\n groupByFieldName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n updateSingleFieldName,\n deleteFieldName,\n deleteSingleFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\n\n const selectArrGenerated = generateSelectArray(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n listFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n features.distinct,\n );\n const selectSingleGenerated = generateSelectSingle(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n singleFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n );\n const insertArrGenerated = features.insert\n ? generateInsertArray(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n insertInput,\n createArrayFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n )\n : undefined;\n const insertSingleGenerated = features.insert\n ? generateInsertSingle(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n insertInput,\n createSingleFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n )\n : undefined;\n // An upsert needs something to conflict on, so a table with no primary key and no\n // unique constraint gets no upsert mutations rather than ones that always fail.\n const uniqueSets = features.upsert ? getUniqueColumnSets(schema[tableName] as PgTable, getTableConfig) : [];\n const onConflictInput = features.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as PgTable,\n typeName,\n uniqueSets,\n tableFilters,\n withTarget: true,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n insertInput,\n onConflictInput,\n uniqueSets,\n upsertArrayFieldName,\n typeName,\n false,\n typeNameMapper,\n filterCtx,\n )\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 )\n : undefined;\n const updateGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateFieldName,\n typeName,\n false,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n )\n : undefined;\n const updateSingleGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n )\n : undefined;\n const deleteGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n deleteFieldName,\n typeName,\n false,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n )\n : undefined;\n const deleteSingleGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n deleteSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n )\n : undefined;\n const aggregateType = features.aggregates\n ? generateAggregateTypes(schema[tableName] as PgTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = features.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as PgTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n features.aggregates && features.groupBy\n ? generateGroupByType(schema[tableName] as PgTable, tableName, typeName, cacheCtx)\n : undefined;\n const groupByEnum = groupByType\n ? generateGroupByEnum(schema[tableName] as PgTable, tableName, typeName)\n : undefined;\n const havingInput = groupByEnum\n ? generateHavingInput(schema[tableName] as PgTable, tableName, typeName)\n : undefined;\n const groupByGenerated =\n groupByType && groupByEnum && havingInput\n ? generateGroupBy(\n db,\n tableName,\n schema[tableName] as PgTable,\n typeName,\n groupByFieldName,\n tableFilters,\n groupByEnum,\n havingInput,\n filterCtx,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n ...(complexity ? { extensions: { complexity: listFieldComplexity(complexity) } } : {}),\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (insertArrGenerated) {\n mutations[insertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: insertArrGenerated.args,\n resolve: insertArrGenerated.resolver,\n };\n }\n if (insertSingleGenerated) {\n mutations[insertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: insertSingleGenerated.args,\n resolve: insertSingleGenerated.resolver,\n };\n }\n if (upsertArrGenerated) {\n mutations[upsertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: upsertArrGenerated.args,\n resolve: upsertArrGenerated.resolver,\n };\n }\n if (upsertSingleGenerated) {\n mutations[upsertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: upsertSingleGenerated.args,\n resolve: upsertSingleGenerated.resolver,\n };\n }\n if (updateGenerated) {\n mutations[updateGenerated.name] = {\n type: arrTableItemOutput,\n args: updateGenerated.args,\n resolve: updateGenerated.resolver,\n };\n }\n if (updateSingleGenerated) {\n mutations[updateSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: updateSingleGenerated.args,\n resolve: updateSingleGenerated.resolver,\n };\n }\n if (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.resolver,\n };\n }\n if (deleteSingleGenerated) {\n mutations[deleteSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: deleteSingleGenerated.args,\n resolve: deleteSingleGenerated.resolver,\n };\n }\n // The insert/update inputs are still built (they type the mutations that survive) but\n // only reach the schema's type map when a mutation actually references them.\n const activeInputs = [\n // The insert input types the upsert mutations too, so either feature keeps it.\n ...(features.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(features.update ? [updateInput] : []),\n 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 const fieldResolvers: Record<string, Record<string, any>> = {};\n for (const [tableName, tableRelations] of Object.entries(namedRelations)) {\n const relResolvers: Record<string, any> = {};\n for (const [relName, relEntry] of Object.entries(tableRelations)) {\n const isOne = is((relEntry as any).relation ?? relEntry, One);\n const resolver = resolverFactory({ tableName, relationName: relName, relEntry, isOne });\n if (resolver) {\n relResolvers[relName] = resolver;\n }\n }\n if (Object.keys(relResolvers).length > 0) {\n fieldResolvers[tableName] = relResolvers;\n }\n }\n\n return { queries, mutations, inputs, types: outputs, fieldResolvers } as any;\n}\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { is, One, type Table } from 'drizzle-orm';\nimport type { RelationalQueryBuilder } from 'drizzle-orm/mysql-core/query-builders/query';\nimport { type BaseSQLiteDatabase, getTableConfig, type SQLiteColumn, SQLiteTable } from 'drizzle-orm/sqlite-core';\nimport type { GraphQLFieldConfig, GraphQLFieldConfigArgumentMap, GraphQLResolveInfo, ThunkObjMap } from 'graphql';\nimport {\n GraphQLError,\n type GraphQLInputObjectType,\n GraphQLList,\n GraphQLNonNull,\n type GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\n\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n aggregateFieldComplexity,\n assertSingleMatch,\n attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createRelationResolverFactory,\n eagerLoadMutationRelations,\n excludedColumnRef,\n extractFilters,\n extractRequiredFilters,\n extractSelectedColumnsFromTreeSQLFormat,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n getPrimaryKeyPropNamesFromConfig,\n getUniqueColumnSets,\n listFieldComplexity,\n type OnConflictArg,\n prepareMutationRelationColumns,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n relationFilterCtx,\n resolveConflictPlan,\n resolveExecutor,\n resolveQueryExecutor,\n runRelationalSelect,\n type SelectionCtx,\n selectArrayArgs,\n selectSingleArgs,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n} from '../builders/common.ts';\nimport {\n remapFromGraphQLArrayInput,\n remapFromGraphQLSingleInput,\n remapToGraphQLArrayOutput,\n remapToGraphQLSingleOutput,\n} from '../data-mappers/index.ts';\nimport {\n createRelationAggregateFactory,\n generateAggregate,\n generateAggregateTypes,\n generateGroupBy,\n generateGroupByEnum,\n generateGroupByType,\n generateHavingInput,\n} from './aggregates.ts';\nimport type {\n CreatedResolver,\n Filters,\n SchemaGeneratorOptions,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst generateSelectArray = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n distinctEnabled: boolean = true,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const table = tables[tableName]!;\n const pkNames = sqlitePrimaryKeyPropNames(table as SQLiteTable);\n const queryArgs = selectArrayArgs(\n orderArgs,\n filterArgs,\n distinctEnabled ? generateDistinctEnum(table, typeName) : undefined,\n );\n\n return {\n name: fieldName,\n resolver: async (_source: any, args: Partial<TableSelectArgs>, context: any, info: GraphQLResolveInfo) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: false,\n filterCtx,\n pkNames,\n db: executor,\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateSelectSingle = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const queryArgs = selectSingleArgs(orderArgs, filterArgs);\n\n const table = tables[tableName]!;\n const pkNames = sqlitePrimaryKeyPropNames(table as SQLiteTable);\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n pkNames,\n db: executor,\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\n/** Primary-key property names for a SQLite table, including table-level composite keys. */\nconst sqlitePrimaryKeyPropNames = (table: SQLiteTable): string[] =>\n getPrimaryKeyPropNamesFromConfig(table, getTableConfig);\n\nconst generateInsertArray = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n conflictDoNothing: boolean = false,\n): 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 const input = remapFromGraphQLArrayInput(args.values, table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const executor = resolveExecutor(db, context);\n let query = executor.insert(table).values(input).returning(columns);\n if (conflictDoNothing) {\n query = query.onConflictDoNothing() as any;\n }\n const result = await query;\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\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): 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 const input = remapFromGraphQLSingleInput(args.values, table);\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n const executor = resolveExecutor(db, context);\n let query = executor.insert(table).values(input).returning(columns);\n if (conflictDoNothing) {\n query = query.onConflictDoNothing() as any;\n }\n const result = await query;\n\n if (!result[0]) {\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap);\n } 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): 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 const input = single\n ? [remapFromGraphQLSingleInput(args.values as Record<string, any>, table)]\n : remapFromGraphQLArrayInput(args.values as Record<string, any>[], table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const plan = resolveConflictPlan({\n table,\n values: input,\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 const executor = resolveExecutor(db, context);\n let query = executor.insert(table).values(input).returning(columns);\n query =\n plan.action === 'NOTHING'\n ? (query.onConflictDoNothing(plan.target ? { target: plan.target } : undefined) as any)\n : (query.onConflictDoUpdate({ target: plan.target!, set: plan.set, setWhere: plan.setWhere }) as any);\n\n const result = await query;\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 } 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): 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 const { where, set } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const input = remapFromGraphQLSingleInput(set, table);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n const executor = resolveExecutor(db, context);\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 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 && !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 } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateDelete = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n single: boolean,\n requireWhere: boolean,\n filterCtx?: RelationFilterBase,\n selectionCtx?: SelectionCtx,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, info) => {\n try {\n const { where } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const columns = extractSelectedColumnsFromTreeSQLFormat<SQLiteColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n selectionCtx,\n );\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n const executor = resolveExecutor(db, context);\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) as any;\n\n const result = await query;\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row!`);\n }\n\n if (single) {\n return result[0] ? remapToGraphQLSingleOutput(result[0], tableName, table) : undefined;\n }\n\n return remapToGraphQLArrayOutput(result, tableName, table);\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nexport const generateSchemaData = <\n TDrizzleInstance extends BaseSQLiteDatabase<any, any, any, any>,\n TSchema extends Record<string, Table | unknown>,\n>(\n db: TDrizzleInstance,\n schema: TSchema,\n relations: TablesRelationalConfig,\n options: SchemaGeneratorOptions,\n): GeneratedEntities<TDrizzleInstance, TSchema> => {\n const {\n relationsDepthLimit,\n prefixes,\n suffixes,\n conflictDoNothing,\n typeNameMapper,\n shouldEagerLoad,\n features,\n complexity,\n } = options;\n const rawSchema = schema;\n const schemaEntries = Object.entries(rawSchema);\n\n const tableEntries = schemaEntries.filter(([_key, value]) => is(value, SQLiteTable)) as [string, SQLiteTable][];\n const tables = Object.fromEntries(tableEntries) as Record<string, SQLiteTable>;\n\n if (!tableEntries.length) {\n throw new Error(\n \"Drizzle-GraphQL Error: No tables detected in Drizzle-ORM's database instance. Did you forget to pass schema to drizzle constructor?\",\n );\n }\n\n // Build namedRelations from the drizzle-orm v1 relations config.\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Record each relation target's (composite-aware) primary key for deterministic\n // paginated ordering. Must run before pruning / type generation (shared entry objects).\n attachTargetPrimaryKeys(namedRelations, tables, sqlitePrimaryKeyPropNames);\n // Pruned map for query/mutation resolvers' `with:`; type generation keeps the full map.\n const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);\n\n const filterCtx: RelationFilterBase = { tables, relationMap: namedRelations };\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(db, tables, filterCtx);\n\n // Fresh cache per generateSchemaData call — prevents type name collisions\n // when buildSchema() is called multiple times.\n const cacheCtx: TypeCacheCtx = {\n genericFilterCache: new Map(),\n objectTypeCache: new Map(),\n relationFieldContainers: new Map(),\n fullyBuiltTables: new Set(),\n relationTypeCache: new Map(),\n orderTypeCache: new WeakMap(),\n filterTypeCache: new WeakMap(),\n listRelationFilterCache: new Map(),\n aggregateTypeCache: new Map(),\n complexity,\n };\n\n // Left undefined when the feature is off — generateTableTypes then emits no\n // `${relation}Aggregate` fields at all.\n const relationAggregateFactory: RelationAggregateFactory | undefined = features.relationAggregates\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx)\n : undefined;\n\n const queries: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const mutations: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const gqlSchemaTypes = Object.fromEntries(\n Object.entries(tables).map(([tableName, _table]) => [\n tableName,\n generateTableTypes(\n tableName,\n tables,\n namedRelations,\n true,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n prefixes.insert,\n prefixes.update,\n resolverFactory,\n relationAggregateFactory,\n ),\n ]),\n );\n\n const inputs: Record<string, GraphQLInputObjectType> = {};\n const outputs: Record<string, GraphQLObjectType> = {};\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n const { insertInput, updateInput, tableFilters, tableOrder } = tableTypes.inputs;\n const { selectSingleOutput, selectArrOutput, singleTableItemOutput, arrTableItemOutput } = tableTypes.outputs;\n\n // Compute field names using the mapper logic\n const {\n typeName,\n listFieldName,\n singleFieldName,\n aggregateFieldName,\n groupByFieldName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n updateSingleFieldName,\n deleteFieldName,\n deleteSingleFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\n\n const selectArrGenerated = generateSelectArray(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n listFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n features.distinct,\n );\n const selectSingleGenerated = generateSelectSingle(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n singleFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n );\n const insertArrGenerated = features.insert\n ? generateInsertArray(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n insertInput,\n createArrayFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n )\n : undefined;\n const insertSingleGenerated = features.insert\n ? generateInsertSingle(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n insertInput,\n createSingleFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n )\n : undefined;\n // An upsert needs something to conflict on, so a table with no primary key and no\n // unique constraint gets no upsert mutations rather than ones that always fail.\n const uniqueSets = features.upsert ? getUniqueColumnSets(schema[tableName] as SQLiteTable, getTableConfig) : [];\n const onConflictInput = features.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as SQLiteTable,\n typeName,\n uniqueSets,\n tableFilters,\n withTarget: true,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n insertInput,\n onConflictInput,\n uniqueSets,\n upsertArrayFieldName,\n typeName,\n false,\n typeNameMapper,\n filterCtx,\n )\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 )\n : undefined;\n const updateGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateFieldName,\n typeName,\n false,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n )\n : undefined;\n const updateSingleGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n )\n : undefined;\n const deleteGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n deleteFieldName,\n typeName,\n false,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n )\n : undefined;\n const deleteSingleGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n deleteSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n )\n : undefined;\n const aggregateType = features.aggregates\n ? generateAggregateTypes(schema[tableName] as SQLiteTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = features.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n features.aggregates && features.groupBy\n ? generateGroupByType(schema[tableName] as SQLiteTable, tableName, typeName, cacheCtx)\n : undefined;\n const groupByEnum = groupByType\n ? generateGroupByEnum(schema[tableName] as SQLiteTable, tableName, typeName)\n : undefined;\n const havingInput = groupByEnum\n ? generateHavingInput(schema[tableName] as SQLiteTable, tableName, typeName)\n : undefined;\n const groupByGenerated =\n groupByType && groupByEnum && havingInput\n ? generateGroupBy(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n typeName,\n groupByFieldName,\n tableFilters,\n groupByEnum,\n havingInput,\n filterCtx,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n ...(complexity ? { extensions: { complexity: listFieldComplexity(complexity) } } : {}),\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (insertArrGenerated) {\n mutations[insertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: insertArrGenerated.args,\n resolve: insertArrGenerated.resolver,\n };\n }\n if (insertSingleGenerated) {\n mutations[insertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: insertSingleGenerated.args,\n resolve: insertSingleGenerated.resolver,\n };\n }\n if (upsertArrGenerated) {\n mutations[upsertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: upsertArrGenerated.args,\n resolve: upsertArrGenerated.resolver,\n };\n }\n if (upsertSingleGenerated) {\n mutations[upsertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: upsertSingleGenerated.args,\n resolve: upsertSingleGenerated.resolver,\n };\n }\n if (updateGenerated) {\n mutations[updateGenerated.name] = {\n type: arrTableItemOutput,\n args: updateGenerated.args,\n resolve: updateGenerated.resolver,\n };\n }\n if (updateSingleGenerated) {\n mutations[updateSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: updateSingleGenerated.args,\n resolve: updateSingleGenerated.resolver,\n };\n }\n if (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.resolver,\n };\n }\n if (deleteSingleGenerated) {\n mutations[deleteSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: deleteSingleGenerated.args,\n resolve: deleteSingleGenerated.resolver,\n };\n }\n // The insert/update inputs are still built (they type the mutations that survive) but\n // only reach the schema's type map when a mutation actually references them.\n const activeInputs = [\n // The insert input types the upsert mutations too, so either feature keeps it.\n ...(features.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(features.update ? [updateInput] : []),\n 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 const fieldResolvers: Record<string, Record<string, any>> = {};\n for (const [tableName, tableRelations] of Object.entries(namedRelations)) {\n const relResolvers: Record<string, any> = {};\n for (const [relName, relEntry] of Object.entries(tableRelations)) {\n const isOne = is((relEntry as any).relation ?? relEntry, One);\n const resolver = resolverFactory({ tableName, relationName: relName, relEntry, isOne });\n if (resolver) {\n relResolvers[relName] = resolver;\n }\n }\n if (Object.keys(relResolvers).length > 0) {\n fieldResolvers[tableName] = relResolvers;\n }\n }\n\n return { queries, mutations, inputs, types: outputs, fieldResolvers } as any;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,sBAAmB;AACnB,IAAAC,qBAA8B;AAC9B,IAAAC,kBAAgC;AAChC,IAAAC,sBAAmC;AACnC,IAAAC,kBAMO;;;ACQP,IAAAC,sBA8BO;AAEP,IAAAC,kBAWO;;;AC5DP,IAAM,sBAAsB,uBAAO,yBAAyB;AAI5D,IAAM,cAAN,MAAwB;AAAA,EAItB,YAA6B,SAAwB;AAAxB;AAAA,EAAyB;AAAA,EAH9C,QAAkF,CAAC;AAAA,EACnF,YAAY;AAAA,EAIpB,KAAK,KAAoB;AACvB,WAAO,IAAI,QAA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drizzle_orm","import_graphql","import_graphql","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","generateSelectArray","generateSelectSingle","generateInsertArray","generateInsertSingle","generateUpsert","generateUpdate","generateDelete","generateSchemaData","import_drizzle_orm","import_sqlite_core","import_graphql","import_graphql_parse_resolve_info","generateSelectArray","generateSelectSingle","generateInsertArray","generateInsertSingle","generateUpsert","generateUpdate","generateDelete","generateSchemaData","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/scalars/index.ts","../src/util/type-converter/index.ts","../src/util/builders/mysql.ts","../src/util/builders/aggregates.ts","../src/util/builders/pg.ts","../src/util/builders/sqlite.ts"],"sourcesContent":["import { is } from 'drizzle-orm';\nimport { MySqlDatabase } from 'drizzle-orm/mysql-core';\nimport { PgAsyncDatabase } from 'drizzle-orm/pg-core';\nimport { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';\nimport {\n type GraphQLFieldConfig,\n type GraphQLInputObjectType,\n GraphQLObjectType,\n GraphQLSchema,\n type GraphQLSchemaConfig,\n} from 'graphql';\nimport type { AnyDrizzleDB, BuildSchemaConfig, GeneratedData } from './types.ts';\nimport { applyErrorMapper, defaultErrorMapper } from './util/builders/common.ts';\nimport { generateMySQL, generatePG, generateSQLite } from './util/builders/index.ts';\nimport type { SchemaGeneratorOptions } from './util/builders/types.ts';\n\nexport type {\n AggregateResolver,\n AnyDrizzleDB,\n BuildSchemaConfig,\n ComplexityConfig,\n DeleteResolver,\n DeleteSingleResolver,\n ExtractRelations,\n ExtractTableByName,\n ExtractTableRelations,\n ExtractTables,\n GeneratedData,\n GeneratedEntities,\n GeneratedInputs,\n GeneratedOutputs,\n InsertArrResolver,\n InsertResolver,\n MutationReturnlessResult,\n MutationsCore,\n QueriesCore,\n SchemaFeatures,\n SelectResolver,\n SelectSingleResolver,\n UpdateManyArgs,\n UpdateManyEntry,\n UpdateManyResolver,\n UpdateResolver,\n UpdateSingleResolver,\n UpsertArgs,\n UpsertArrResolver,\n UpsertConflictArgs,\n UpsertResolver,\n} from './types.ts';\nexport type { RelationResolverFactory } from './util/builders/common.ts';\nexport {\n createRelationResolverFactory,\n defaultErrorMapper,\n drizzleExecutorKey,\n extractFilters,\n extractOrderBy,\n extractRelationJoinColumns,\n} from './util/builders/common.ts';\nexport type { TableNamedRelations } from './util/builders/types.ts';\nexport {\n GraphQLBigIntString,\n GraphQLDate,\n GraphQLDateTime,\n GraphQLDecimalString,\n GraphQLJSON,\n GraphQLUUID,\n} from './util/scalars/index.ts';\n\ntype ObjMap<T> = Record<string, T>;\n\nexport const buildSchema = <TDbClient extends AnyDrizzleDB<any>>(\n db: TDbClient,\n config?: BuildSchemaConfig,\n): GeneratedData<TDbClient> => {\n const relations = db._.relations;\n // drizzle-orm v1 rc.2 removed fullSchema from PgAsyncDatabase._\n // For PG, reconstruct a schema-like map from db._.relations (each entry has { table }).\n // MySQL and SQLite still expose fullSchema directly.\n const schema =\n (db._ as any).fullSchema ??\n Object.fromEntries(\n Object.entries(relations as Record<string, any>)\n .filter(([, config]) => config?.table != null)\n .map(([key, config]) => [key, config.table]),\n );\n\n if (!schema || !Object.keys(schema).length) {\n throw new Error(\n 'Drizzle-GraphQL Error: Schema not found in drizzle instance. Pass relations (from buildRelations/defineRelations) to the drizzle constructor so drizzle-graphql can detect your tables.',\n );\n }\n\n const prefixes = {\n insert: config?.prefixes?.insert ?? 'create',\n delete: config?.prefixes?.delete ?? 'delete',\n update: config?.prefixes?.update ?? 'update',\n upsert: config?.prefixes?.upsert ?? 'upsert',\n };\n\n const suffixes = {\n list: config?.suffixes?.list ?? '',\n single: config?.suffixes?.single ?? 'Single',\n };\n\n const typeNameMapper = config?.typeNameMapper;\n\n // Every feature is on unless the caller says otherwise, so a build without a `features`\n // block generates what it always did — except upsert, which is new surface and so has to\n // be asked for.\n const features = {\n aggregates: config?.features?.aggregates ?? true,\n groupBy: config?.features?.groupBy ?? true,\n relationAggregates: config?.features?.relationAggregates ?? true,\n distinct: config?.features?.distinct ?? true,\n insert: config?.features?.insert ?? true,\n update: config?.features?.update ?? true,\n updateMany: config?.features?.updateMany ?? true,\n delete: config?.features?.delete ?? true,\n upsert: config?.features?.upsert ?? false,\n requireWhere: config?.features?.requireWhere ?? false,\n };\n\n // Cost hints are inert without a complexity rule installed, so they are generated unless the\n // caller opts out.\n const complexityConfig = config?.complexity ?? true;\n const complexity =\n complexityConfig === false\n ? undefined\n : {\n defaultListSize: (complexityConfig === true ? undefined : complexityConfig.defaultListSize) ?? 10,\n aggregateCost: (complexityConfig === true ? undefined : complexityConfig.aggregateCost) ?? 10,\n };\n\n // Normalize eagerLoadRelations (boolean | predicate | undefined) into a predicate.\n const eagerOpt = config?.eagerLoadRelations;\n const shouldEagerLoad: (tableName: string, relationName: string) => boolean =\n eagerOpt === undefined || eagerOpt === true ? () => true : eagerOpt === false ? () => false : eagerOpt;\n\n // When a typeNameMapper is provided, the mapper's singular/plural forms disambiguate the\n // list and single fields even if the suffixes are identical (e.g. both '').\n // Only enforce the suffix-collision check when no mapper is active.\n if (!typeNameMapper && suffixes.list === suffixes.single) {\n throw new Error(\n 'Drizzle-GraphQL Error: List and single query suffixes cannot be the same. This would create conflicting GraphQL field names.',\n );\n }\n\n if (typeof config?.relationsDepthLimit === 'number') {\n if (config.relationsDepthLimit < 0) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.relationsDepthLimit is supposed to be nonnegative integer or undefined!',\n );\n }\n if (config.relationsDepthLimit !== ~~config.relationsDepthLimit) {\n throw new Error(\n 'Drizzle-GraphQL Error: config.relationsDepthLimit is supposed to be nonnegative integer or undefined!',\n );\n }\n }\n\n const generatorOptions: SchemaGeneratorOptions = {\n relationsDepthLimit: config?.relationsDepthLimit,\n prefixes,\n suffixes,\n conflictDoNothing: config?.conflictDoNothing ?? false,\n typeNameMapper,\n shouldEagerLoad,\n features,\n complexity,\n };\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 getColumns,\n getTableAsAliasSQL,\n gt,\n gte,\n ilike,\n inArray,\n is,\n isNotNull,\n isNull,\n like,\n lt,\n lte,\n ne,\n not,\n notIlike,\n notInArray,\n notLike,\n One,\n or,\n relationsFilterToSQL,\n type SQL,\n sql,\n} from 'drizzle-orm';\nimport type { GraphQLFieldResolver } from 'graphql';\nimport {\n GraphQLBoolean,\n GraphQLEnumType,\n GraphQLError,\n GraphQLFloat,\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n 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 { GraphQLBigIntString, GraphQLDecimalString, GraphQLJSON, GraphQLUUID } from '../scalars/index.ts';\nimport { drizzleColumnToGraphQLType } from '../type-converter/index.ts';\nimport type {\n ConvertedColumn,\n ConvertedInputColumn,\n ConvertedRelationColumnWithArgs,\n} from '../type-converter/types.ts';\nimport type {\n FilterColumnOperators,\n FilterColumnOperatorsCore,\n Filters,\n FiltersCore,\n GeneratedTableTypes,\n GeneratedTableTypesOutputs,\n OrderByArgs,\n ProcessedTableSelectArgs,\n SelectData,\n SelectedColumnsRaw,\n SelectedSQLColumns,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst rqbCrashTypes = ['SQLiteBigInt', 'SQLiteBlobJson', 'SQLiteBlobBuffer'];\n\n/** Optional mapper from table key to singular/plural name pair. Return undefined to use default naming for a table. */\nexport type TypeNameMapper = (tableName: string) => { singular: string; plural: string } | undefined;\n\n/** Produce the GraphQL object type name for a table, using the mapper if provided. */\nexport const resolveTypeName = (name: string, typeNameMapper?: TypeNameMapper): string => {\n const mapped = typeNameMapper?.(name);\n return mapped ? capitalize(mapped.singular) : capitalize(name);\n};\n\n/**\n * Shape of the relational config from drizzle-orm v1 db._.relations.\n * Each entry has { table, name, relations }.\n */\ninterface TableRelationalConfig {\n table: Table;\n name: string;\n relations: Record<string, Relation<string>>;\n}\nexport type TablesRelationalConfig = Record<string, TableRelationalConfig>;\n\n/**\n * Flatten drizzle-orm v1 TablesRelationalConfig into the canonical\n * Record<tableName, Record<relName, TableNamedRelations>> shape used\n * throughout common.ts. Both pg.ts and sqlite.ts call this before\n * passing the relation map to any shared function.\n */\nexport const buildNamedRelations = (\n relations: TablesRelationalConfig,\n tableEntries: [string, Table][],\n): Record<string, Record<string, TableNamedRelations>> => {\n const namedRelations: Record<string, Record<string, TableNamedRelations>> = {};\n\n for (const [relTableName, relConfig] of Object.entries(relations)) {\n if (!relConfig?.relations) {\n continue;\n }\n\n const namedConfig: Record<string, TableNamedRelations> = {};\n\n for (const [innerRelName, innerRelValue] of Object.entries(relConfig.relations)) {\n // drizzle-orm v1 uses `targetTable` (not `referencedTable`)\n // and provides `targetTableName` directly.\n const targetTable = (innerRelValue as any).targetTable ?? (innerRelValue as any).referencedTable;\n const directTargetName = (innerRelValue as any).targetTableName as string | undefined;\n\n let targetTableName: string | undefined;\n\n if (directTargetName) {\n // v1: use the direct name to find the schema key\n const targetEntry = tableEntries.find(([key]) => key === directTargetName);\n targetTableName = targetEntry?.[0];\n } else if (targetTable) {\n // fallback: match by object reference\n const targetEntry = tableEntries.find(([, tableValue]) => tableValue === targetTable);\n targetTableName = targetEntry?.[0];\n }\n\n if (!targetTableName) {\n continue;\n }\n\n namedConfig[innerRelName] = {\n relation: innerRelValue,\n targetTableName,\n };\n }\n\n if (Object.keys(namedConfig).length > 0) {\n namedRelations[relTableName] = namedConfig;\n }\n }\n\n return namedRelations;\n};\n\n/**\n * Records each relation's target-table primary-key property names on the relation entry,\n * so the pagination paths (the window-function batch loader and the eager `with:` orderBy\n * default) can fall back to a deterministic PK order without re-deriving it per request.\n *\n * Composite primary keys are only visible through the dialect's getTableConfig, so the\n * dialect builder passes a `resolvePkNames` that threads the composite column names in.\n * Mutates the relation entries in place (they are shared with the pruned eager map and\n * the resolver factory, so attaching once covers every consumer).\n */\nexport const attachTargetPrimaryKeys = (\n namedRelations: Record<string, Record<string, TableNamedRelations>>,\n tables: Record<string, Table>,\n resolvePkNames: (table: Table) => string[],\n): void => {\n const cache = new Map<string, readonly string[]>();\n for (const rels of Object.values(namedRelations)) {\n for (const relEntry of Object.values(rels)) {\n const { targetTableName } = relEntry;\n let pk = cache.get(targetTableName);\n if (!pk) {\n const targetTable = tables[targetTableName];\n pk = targetTable ? resolvePkNames(targetTable) : [];\n cache.set(targetTableName, pk);\n }\n relEntry.targetPkNames = pk;\n }\n }\n};\n\n/**\n * Extracts the join column info from a drizzle-orm v1 Relation object.\n * Returns the JS property name of the local column on the parent table and the\n * Column object for the foreign column on the target table, or undefined if the\n * relation internals are not accessible.\n */\nexport const extractRelationJoinColumns = (\n relEntry: TableNamedRelations,\n parentTable: Table,\n targetTable: Table,\n): { localColPropName: string; foreignCol: Column; foreignColPropName: string } | undefined => {\n const rel = (relEntry as any).relation ?? relEntry;\n const sourceColumns: any[] | undefined = rel.sourceColumns;\n const targetColumns: any[] | undefined = rel.targetColumns;\n\n if (!sourceColumns?.length || !targetColumns?.length) {\n return undefined;\n }\n\n const sourceCol = sourceColumns[0];\n const targetCol = targetColumns[0];\n\n const parentCols = getColumns(parentTable);\n const localColPropName = Object.entries(parentCols).find(([, c]) => c === sourceCol)?.[0];\n\n const targetCols = getColumns(targetTable);\n const foreignColPropName = Object.entries(targetCols).find(([, c]) => c === targetCol)?.[0];\n\n if (!localColPropName || !foreignColPropName) {\n return undefined;\n }\n\n return { localColPropName, foreignCol: targetCol, foreignColPropName };\n};\n\nexport type RelationResolverFactory = (params: {\n tableName: string;\n relationName: string;\n relEntry: TableNamedRelations;\n isOne: boolean;\n}) => GraphQLFieldResolver<any, any> | undefined;\n\n/**\n * Builds the `${relationName}Aggregate` field for a to-many relation. Implemented in\n * `aggregates.ts` and injected here so the aggregate code can depend on this module\n * without the two importing each other.\n */\nexport type RelationAggregateFactory = (params: {\n tableName: string;\n relationName: string;\n relEntry: TableNamedRelations;\n}) => { type: GraphQLObjectType; resolve: GraphQLFieldResolver<any, any> } | undefined;\n\n/**\n * Key on the GraphQL context object under which a caller can place a Drizzle transaction\n * (or any other executor: a pooled connection, a logging proxy). Every generated resolver\n * reads it at resolve time and runs its statements there instead of on the database the\n * schema was built from, which is what lets several mutations in one request share a\n * transaction and lets a query see that transaction's uncommitted rows:\n *\n * ```ts\n * await db.transaction(async (tx) => {\n * await graphql({ schema, source, contextValue: { [drizzleExecutorKey]: tx } });\n * });\n * ```\n *\n * Registered with `Symbol.for` so the ESM and CJS builds of this package agree on it when\n * both end up loaded in one process.\n */\nexport const drizzleExecutorKey: unique symbol = Symbol.for('drizzle-graphql:executor') as any;\n\n/**\n * The executor a resolver should run on: the request's transaction when the context\n * carries one, otherwise the database the schema was built from.\n */\nexport const resolveExecutor = <T>(db: T, context: any): T => {\n if (context && typeof context === 'object') {\n const executor = context[drizzleExecutorKey];\n if (executor) {\n return executor as T;\n }\n }\n return db;\n};\n\n/**\n * This request's executor together with the relational query builder to select through.\n *\n * `buildTimeQueryBase` decides whether the table supports the relational query builder at\n * all — a table with no relations has none, and the caller falls back to a plain select.\n * The executor only decides which connection the query runs on, so a transaction that is\n * missing `query` (or a table absent from its schema) keeps the build-time builder.\n */\nexport const resolveQueryExecutor = (\n db: any,\n context: any,\n tableName: string,\n buildTimeQueryBase: any,\n): { executor: any; queryBase: any } => {\n const executor = resolveExecutor(db, context);\n return {\n executor,\n queryBase: buildTimeQueryBase ? (executor?.query?.[tableName] ?? buildTimeQueryBase) : buildTimeQueryBase,\n };\n};\n\n/**\n * Fetches a to-many relation with per-parent limit/offset for ALL parents in a\n * single query, using a window function (ROW_NUMBER() OVER (PARTITION BY fk ...)).\n *\n * This replaces the previous per-parent fallback that issued one query per parent\n * (true N+1) whenever pagination args were present. Each parent gets its own\n * limit/offset window while the database is hit exactly once for the whole batch.\n *\n * Window functions require PostgreSQL, MySQL >= 8.0, or SQLite >= 3.25.\n * Returns raw rows (NOT remapped); the caller groups + remaps them.\n */\nconst batchedPaginatedRelationQuery = async (\n db: any,\n targetTable: Table,\n foreignCol: Column,\n whereCondition: SQL | undefined,\n orderByArg: any,\n limit: number | null,\n offset: number | null,\n pkNames: readonly string[],\n orderCtx?: RelationFilterContext,\n): Promise<any[]> => {\n const cols = getColumns(targetTable);\n\n // Always tiebreak the window by the target's primary key so per-parent limit/offset\n // slices are deterministic even when the client supplies no (or a non-unique) orderBy.\n // pkNames is resolved at build time and includes composite keys.\n const orderExprs = [\n ...(orderByArg ? extractOrderBy(targetTable, orderByArg, orderCtx) : []),\n ...primaryKeyOrderExprs(targetTable, pkNames),\n ];\n const orderClause = orderExprs.length ? sql` order by ${sql.join(orderExprs, sql`, `)}` : sql``;\n // Namespaced alias so it can't collide with a real column on the target table.\n const RN = '__drizzle_graphql_rn';\n const rowNumber = sql`row_number() over (partition by ${foreignCol}${orderClause})`.as(RN);\n\n // Subquery: every target column plus a per-partition row number.\n const sub = db\n .select({ ...cols, [RN]: rowNumber })\n .from(targetTable)\n .where(whereCondition)\n .as('__paginated');\n\n // Outer: keep only the rows that fall inside each parent's window.\n const lower = offset ?? 0;\n const windowConds: any[] = [gt(sub[RN], lower)];\n if (limit != null) {\n windowConds.push(lte(sub[RN], lower + limit));\n }\n\n const rows: any[] = await db\n .select()\n .from(sub)\n .where(and(...windowConds))\n .orderBy(sub[RN]);\n\n // Strip the helper column so it doesn't leak into remapping/output.\n for (const row of rows) {\n delete row[RN];\n }\n return rows;\n};\n\n/**\n * Creates a RelationResolverFactory that generates field-level resolvers for each relation.\n * Each resolver:\n * 1. Returns pre-fetched data if the parent resolver already included it (eager path, zero cost).\n * 2. When limit/offset args are present, falls back to a direct per-item query.\n * 3. Otherwise batches all sibling resolver calls within the same GraphQL execution tick\n * into a single IN-clause query, eliminating N+1 database round-trips.\n */\nexport const createRelationResolverFactory =\n (db: any, tables: Record<string, Table>, filterCtx?: RelationFilterBase): RelationResolverFactory =>\n ({ tableName, relationName, relEntry, isOne }) => {\n const parentTable = tables[tableName];\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n\n if (!parentTable || !targetTable) {\n return undefined;\n }\n\n const joinCols = extractRelationJoinColumns(relEntry, parentTable, targetTable);\n if (!joinCols) {\n return undefined;\n }\n\n const { localColPropName, foreignCol, foreignColPropName } = joinCols;\n // Resolved at build time (composite keys included) — used to tiebreak paginated batches.\n const targetPkNames = relEntry.targetPkNames ?? [];\n\n return async (parent, args, context) => {\n // Eager path: the parent resolver pre-fetched this relation via Drizzle's `with`.\n if (parent[relationName] !== undefined) {\n return parent[relationName];\n }\n\n const localValue = parent[localColPropName];\n if (localValue == null) {\n return isOne ? null : [];\n }\n\n const { where: whereArg, orderBy: orderByArg, limit, offset } = (args ?? {}) as any;\n\n // Batch path: collect all sibling calls in this tick and execute one query.\n // Pagination args are part of the loader key so siblings sharing identical\n // args batch together; per-parent limit/offset is applied inside the batch\n // via a window function rather than bailing to a per-parent query (N+1).\n const argsKey = JSON.stringify({\n where: whereArg ?? null,\n orderBy: orderByArg ?? null,\n limit: limit ?? null,\n offset: offset ?? null,\n });\n const loaderKey = `${tableName}::${relationName}::${argsKey}`;\n\n const loader = getOrCreateLoader(context, loaderKey, async (parentIds: readonly any[]) => {\n // Loaders are cached per context, so every call batched here shares this request's\n // executor — the transaction on the context, when there is one.\n const executor = resolveExecutor(db, context);\n const uniqueIds = [...new Set(parentIds)];\n const whereCondition = and(\n inArray(foreignCol, uniqueIds),\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n );\n\n let rows: any[];\n if (limit != null || offset != null) {\n // Per-parent pagination across the whole batch in one query.\n rows = await batchedPaginatedRelationQuery(\n executor,\n targetTable,\n foreignCol,\n whereCondition,\n orderByArg,\n limit ?? null,\n offset ?? null,\n targetPkNames,\n relationFilterCtx(filterCtx, targetTableName),\n );\n } else {\n // Use plain db.select() so column refs are never aliased — avoids drizzle-orm v1\n // RQB aliasing requirements that would require referencing via aliasedTable proxy.\n let q = executor.select().from(targetTable).where(whereCondition) as any;\n if (orderByArg) {\n q = q.orderBy(...extractOrderBy(targetTable, orderByArg, relationFilterCtx(filterCtx, targetTableName)));\n }\n rows = await q;\n }\n\n // Group by FK value before remapping (remapping may delete null fields).\n if (isOne) {\n const byKey = new Map(rows.map((row: any) => [String(row[foreignColPropName]), row]));\n remapToGraphQLArrayOutput(rows, targetTableName, targetTable);\n return parentIds.map((id) => byKey.get(String(id)) ?? null);\n }\n\n const grouped = new Map<string, any[]>(uniqueIds.map((id) => [String(id), []]));\n for (const row of rows) {\n grouped.get(String(row[foreignColPropName]))?.push(row);\n }\n remapToGraphQLArrayOutput(rows, targetTableName, targetTable);\n return parentIds.map((id) => grouped.get(String(id)) ?? []);\n });\n\n return loader.load(localValue);\n };\n };\n\n/** Per-call cache context — created fresh on each generateSchemaData call to avoid type name collisions. */\nexport interface TypeCacheCtx {\n /** Cache of generic filter types, keyed by generic name (e.g. \"String\", \"DateTime\"). */\n genericFilterCache: Map<string, GraphQLInputObjectType>;\n /**\n * Cache of shared select object types, keyed by table name.\n * Value: the ${capitalize(tableName)} type (columns + relation fields).\n * A table may be pre-registered here as a columns-only shell before its root call runs.\n * Use fullyBuiltTables to distinguish a complete type from a pre-registered shell.\n */\n objectTypeCache: Map<string, GraphQLObjectType>;\n /**\n * Mutable containers for relation fields, keyed by table name.\n * Each container object is closed over by the corresponding GraphQLObjectType thunk so that\n * when the root call for a table populates its relation fields, the thunk automatically picks\n * them up — even if the shell was pre-registered by a different table's relation traversal.\n */\n relationFieldContainers: Map<string, { fields: Record<string, ConvertedRelationColumnWithArgs> }>;\n /**\n * Set of table names whose GraphQL object type has been fully built (root call completed).\n * Pre-registered shells (created when another table references this table as a relation target)\n * are NOT in this set until the root call for that table runs.\n */\n fullyBuiltTables: Set<string>;\n /**\n * Cache of relation types, keyed by \"${fromTableName}::${relName}\".\n * @deprecated No longer used — relation fields now reference the target table's own type directly.\n */\n relationTypeCache: Map<string, GraphQLObjectType>;\n /** 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\n/** The shape `graphql-query-complexity`'s `fieldExtensionsEstimator` hands to a field's hint. */\nexport type ComplexityEstimatorArgs = { args: Record<string, any>; childComplexity: number };\n\n/** A field's cost hint, published as `extensions.complexity` on the generated field config. */\nexport type ComplexityEstimator = (options: ComplexityEstimatorArgs) => number;\n\n/** {@link BuildSchemaConfig.complexity} with its defaults filled in. */\nexport type ResolvedComplexityOptions = {\n /** Rows a list field is assumed to return when the query passes no `limit`. */\n defaultListSize: number;\n /** Flat cost charged for an aggregate field, on top of the fields selected inside it. */\n aggregateCost: number;\n};\n\n/**\n * A paginated field costs its page size times whatever one row of it costs, so `users(limit: 100)\n * { posts(limit: 10) { id } }` is charged for the thousand rows it can return rather than the two\n * fields it mentions. `childComplexity` floors at 1 so a row is never free.\n */\nexport const listFieldComplexity =\n (options: ResolvedComplexityOptions): ComplexityEstimator =>\n ({ args, childComplexity }) => {\n const limit = args['limit'];\n const rows = typeof limit === 'number' && limit > 0 ? limit : options.defaultListSize;\n return rows * Math.max(childComplexity, 1);\n };\n\n/**\n * An aggregate returns a single row but reads however many match, so its cost tracks the scan\n * rather than the response.\n */\nexport const aggregateFieldComplexity =\n (options: ResolvedComplexityOptions): ComplexityEstimator =>\n ({ childComplexity }) =>\n options.aggregateCost + childComplexity;\n\n/**\n * Everything needed to work out which extra columns a selection implies. Passed to the column\n * extractors so a requested `<relation>Aggregate` field can pull in the join column it resolves\n * from, which the client has no reason to have selected itself.\n */\nexport interface SelectionCtx {\n tableName: string;\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n tables: Record<string, Table>;\n}\n\nconst AGGREGATE_FIELD_SUFFIX = 'Aggregate';\n\n/**\n * Property names of the join columns that the `<relation>Aggregate` fields in this selection\n * correlate on. Without them the parent row reaches the aggregate resolver with no key and\n * every count would come back 0.\n */\nconst relationAggregateJoinColumns = (\n tree: Record<string, ResolveTree>,\n table: Table,\n selectionCtx: SelectionCtx | undefined,\n): string[] => {\n const relations = selectionCtx?.relationMap[selectionCtx.tableName];\n if (!relations || !selectionCtx) {\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 end in \"Aggregate\" is a column, not a relation aggregate.\n if (tableColumns[fieldData.name] || !fieldData.name.endsWith(AGGREGATE_FIELD_SUFFIX)) {\n continue;\n }\n\n const relEntry = relations[fieldData.name.slice(0, -AGGREGATE_FIELD_SUFFIX.length)];\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 relationAggregateJoinColumns(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 relationAggregateJoinColumns(tree, table, selectionCtx)) {\n selectedColumns.push([columnName, tableColumns[columnName]!]);\n }\n\n if (!selectedColumns.length) {\n const columnKeys = Object.entries(tableColumns);\n const columnName =\n columnKeys.find((e) => rqbCrashTypes.find((haram) => e[1].columnType !== haram))?.[0] ?? columnKeys[0]![0];\n\n selectedColumns.push([columnName, tableColumns[columnName]!]);\n }\n\n return Object.fromEntries(selectedColumns) as Record<string, TColType>;\n};\n\n/**\n * Where NULL values sort relative to non-NULL values. Compiled to native\n * `NULLS FIRST` / `NULLS LAST` on PostgreSQL and SQLite (3.30+); MySQL has no such\n * clause, so there it is emulated with an extra `<expr> IS NULL` sort key ahead of\n * the column itself.\n */\nexport const orderNulls = new GraphQLEnumType({\n name: 'OrderNulls',\n description: 'Where NULL values sort relative to non-NULL values',\n values: {\n first: {\n value: 'first',\n description: 'NULL values sort before all non-NULL values',\n },\n last: {\n value: 'last',\n description: 'NULL values sort after all non-NULL values',\n },\n },\n});\n\nexport const innerOrder = new GraphQLInputObjectType({\n name: 'InnerOrder' as const,\n fields: {\n direction: {\n type: new GraphQLNonNull(\n new GraphQLEnumType({\n name: 'OrderDirection',\n description: 'Order by direction',\n values: {\n asc: {\n value: 'asc',\n description: 'Ascending order',\n },\n desc: {\n value: 'desc',\n description: 'Descending order',\n },\n },\n }),\n ),\n },\n priority: {\n type: new GraphQLNonNull(GraphQLInt),\n description: 'Priority of current field',\n },\n nulls: {\n type: orderNulls,\n description:\n \"Where NULL values sort. Defaults to the database's own rule (PostgreSQL: last on asc, first on desc; MySQL/SQLite: first on asc, last on desc)\",\n },\n } as const,\n});\n\n/** The dialect a column belongs to, inferred from its drizzle columnType string (e.g. 'PgJsonb'). */\nconst columnDialect = (column: Column): 'pg' | 'mysql' | 'sqlite' | undefined => {\n const ct: string = (column as any).columnType ?? '';\n if (ct.startsWith('Pg')) {\n return 'pg';\n }\n if (ct.startsWith('MySql')) {\n return 'mysql';\n }\n if (ct.startsWith('SQLite')) {\n return 'sqlite';\n }\n return undefined;\n};\n\n/** How a column's generic filter input should be shaped, alongside the cache key to store it under. */\ninterface GenericFilterDescriptor {\n name: string;\n kind: 'scalar' | 'json' | 'array';\n}\n\n/**\n * Maps a Drizzle column to the generic filter type to use.\n *\n * Selection is keyed on the column's data type, never its name: a text column named\n * `userId` gets the full String filter (string operators included), while a uuid column\n * gets the lean Id filter whatever it is called.\n * - \"JSON\" → json/jsonb columns (eq/ne + containment, no scalar comparison ops)\n * - `${Element}Array` → array columns, keyed per element type (IntArray, FloatArray,\n * StringArray, …) so arrays with different element types never share\n * one filter input; membership operators instead of scalar comparisons\n * - \"Id\" → uuid-typed columns (no string pattern operators)\n * - \"Boolean\" → boolean columns\n * - \"BigInt\" → bigint columns (BigInt-scalar-typed operators, no string pattern operators)\n * - \"Decimal\" → numeric/decimal columns (Decimal-scalar-typed operators, no string pattern operators)\n * - the enum GraphQL type name → enum columns (still unique per enum)\n * - \"DateTime\" → timestamp and date columns\n * - \"Int\" → integer/serial columns (no string pattern operators)\n * - \"Float\" → real/double columns (no string pattern operators)\n * - \"String\" → all other text/varchar columns\n */\nconst resolveGenericFilterDescriptor = (\n column: Column,\n columnGraphQLType: ReturnType<typeof drizzleColumnToGraphQLType>,\n): GenericFilterDescriptor => {\n // JSON / JSONB columns — structural values with their own operator set.\n if (columnGraphQLType.type === GraphQLJSON) {\n return { name: 'JSON', kind: 'json' };\n }\n // Array columns — keyed per element type so an int[] and a text[] column never share\n // one cached filter input.\n if (columnGraphQLType.type instanceof GraphQLList) {\n let element = columnGraphQLType.type.ofType;\n if (element instanceof GraphQLNonNull) {\n element = element.ofType;\n }\n return { name: `${element.name}Array`, kind: 'array' };\n }\n // Opaque uuid keys — keyed on the column type, not on an `id`/`*Id` naming convention.\n if (columnGraphQLType.type === GraphQLUUID) {\n return { name: 'Id', kind: 'scalar' };\n }\n // Boolean scalar\n if (columnGraphQLType.type === GraphQLBoolean) {\n return { name: 'Boolean', kind: 'scalar' };\n }\n // Enum type — keep unique per enum since values differ\n if (columnGraphQLType.type instanceof GraphQLEnumType) {\n return { name: columnGraphQLType.type.name, kind: 'scalar' };\n }\n // Named numeric-string scalars — give them their own filters so the operators\n // are typed with the scalar (and validated by it) instead of a shared StringFilter.\n if (columnGraphQLType.type === GraphQLBigIntString) {\n return { name: 'BigInt', kind: 'scalar' };\n }\n if (columnGraphQLType.type === GraphQLDecimalString) {\n return { name: 'Decimal', kind: 'scalar' };\n }\n // Date / timestamp columns (check Drizzle internal columnType string)\n const ct: string = (column as any).columnType ?? '';\n if (ct === 'PgTimestamp' || ct === 'PgTimestampString' || ct === 'PgDate') {\n return { name: 'DateTime', kind: 'scalar' };\n }\n // Numeric scalars — distinct names so an int/float column never shares (and never\n // mistypes) the StringFilter, and integer ids keep a filter without string operators.\n // (BigInt/Decimal columns are handled above via their named scalars.)\n if (columnGraphQLType.type === GraphQLInt) {\n return { name: 'Int', kind: 'scalar' };\n }\n if (columnGraphQLType.type === GraphQLFloat) {\n return { name: 'Float', kind: 'scalar' };\n }\n // Default: plain text/varchar\n return { name: 'String', kind: 'scalar' };\n};\n\n/**\n * Filter fields for a json/jsonb column. `eq`/`ne` compare the whole document (jsonb equality\n * on Postgres, driver-level comparison elsewhere); `contains` is structural containment —\n * Postgres `@>` / MySQL `JSON_CONTAINS`. SQLite stores json as text and has no containment\n * operator, so `contains` is omitted there (same precedent as dialect-specific ops like ilike).\n */\nconst jsonFilterFields = (column: Column, colType: ReturnType<typeof drizzleColumnToGraphQLType>['type']) => {\n const dialect = columnDialect(column);\n return {\n eq: { type: colType, description: 'JSON equality on the whole value' },\n ne: { type: colType, description: 'JSON inequality on the whole value' },\n ...(dialect === 'pg' || dialect === 'mysql'\n ? {\n contains: {\n type: colType,\n description: 'Value structurally contains this JSON (Postgres `@>` / MySQL JSON_CONTAINS)',\n },\n }\n : {}),\n isNull: { type: GraphQLBoolean },\n isNotNull: { type: GraphQLBoolean },\n };\n};\n\n/**\n * 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>, colDesc: string | undefined) => {\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: colDesc },\n ne: { type: colType, description: colDesc },\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: `Array<${colDesc}>` },\n notInArray: { type: colArr, description: `Array<${colDesc}>` },\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\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 const { name: genericName, kind } = 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 colDesc = columnGraphQLType.description;\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 const omitStringOps = 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, colDesc)\n : {\n eq: { type: colType, description: colDesc },\n ne: { type: colType, description: colDesc },\n lt: { type: colType, description: colDesc },\n lte: { type: colType, description: colDesc },\n gt: { type: colType, description: colDesc },\n gte: { type: colType, description: colDesc },\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: `Array<${colDesc}>` },\n notInArray: { type: colArr, description: `Array<${colDesc}>` },\n isNull: { type: GraphQLBoolean },\n isNotNull: { type: GraphQLBoolean },\n };\n\n // The boolean branches are recursive — each branch is this filter type itself — so the\n // fields are thunked and reference the type being constructed.\n const mainType: GraphQLInputObjectType = new GraphQLInputObjectType({\n name: `${genericName}Filter`,\n fields: () => ({\n ...baseFields,\n OR: {\n type: new GraphQLList(new GraphQLNonNull(mainType)),\n description: 'At least one branch matches; ANDed with any sibling operators',\n },\n AND: {\n type: new GraphQLList(new GraphQLNonNull(mainType)),\n description: 'Every branch matches',\n },\n NOT: {\n type: mainType,\n description: 'Negates the nested operators',\n },\n }),\n });\n\n cacheCtx.genericFilterCache.set(genericName, mainType);\n return mainType;\n};\n\nconst orderMap = new WeakMap<object, Record<string, ConvertedInputColumn>>();\nconst generateTableOrderCached = (table: Table) => {\n if (orderMap.has(table)) {\n return orderMap.get(table)!;\n }\n\n let remapped = {};\n try {\n const columns = getColumns(table);\n const columnEntries = Object.entries(columns);\n\n remapped = Object.fromEntries(\n columnEntries.map(([columnName, _columnDescription]) => [columnName, { type: innerOrder }]),\n );\n\n orderMap.set(table, remapped);\n } catch (_err) {}\n return remapped;\n};\n\nconst filterMap = new WeakMap<object, Record<string, ConvertedInputColumn>>();\nconst generateTableFilterValuesCached = (table: Table, tableName: string, cacheCtx: TypeCacheCtx) => {\n if (filterMap.has(table)) {\n return filterMap.get(table)!;\n }\n\n const columns = getColumns(table);\n const columnEntries = Object.entries(columns);\n\n const remapped = Object.fromEntries(\n columnEntries.map(([columnName, columnDescription]) => [\n columnName,\n {\n type: generateColumnFilterValues(columnDescription, tableName, columnName, cacheCtx),\n },\n ]),\n );\n\n filterMap.set(table, remapped);\n\n return remapped;\n};\n\nconst fieldMap = new WeakMap<object, Record<string, ConvertedColumn>>();\nconst generateTableSelectTypeFieldsCached = (table: Table, tableName: string): Record<string, ConvertedColumn> => {\n if (fieldMap.has(table)) {\n return fieldMap.get(table)!;\n }\n\n const columns = getColumns(table);\n const columnEntries = Object.entries(columns);\n\n const remapped = Object.fromEntries(\n columnEntries.map(([columnName, columnDescription]) => [\n columnName,\n drizzleColumnToGraphQLType(columnDescription, columnName, tableName),\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 fieldMap.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);\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 fields: () => ({ ...tableFields, ...container!.fields }),\n });\n cacheCtx.objectTypeCache.set(tableName, shell);\n }\n\n // Build relation fields — recurse into each related table.\n // Mark this table as in-progress before recursing to detect cycles.\n if (relationEntries.length > 0) {\n const rawRelationFields: [string, ConvertedRelationColumnWithArgs][] = [];\n\n // Mark this table as currently being processed.\n const nextUsedTables = new Set(usedTables);\n nextUsedTables.add(tableName);\n\n for (const [relationName, relEntry] of relationEntries) {\n const { targetTableName } = relEntry;\n const relation = (relEntry as any).relation ?? relEntry;\n const isOne = is(relation, One);\n\n // Always recurse to get the target table's filters/order (needed for args).\n // The usedTables check inside the recursive call prevents actual infinite recursion.\n const relSelectData = generateSelectFields(\n tables,\n targetTableName,\n relationMap,\n tableName, // fromTableName for the relation type\n relationName, // fromRelationName for the relation type\n !isOne,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n nextUsedTables,\n resolverFactory,\n currentDepth + 1,\n relationAggregateFactory,\n );\n\n // Use the target table's own GraphQL type directly instead of creating an intermediate relation type.\n // Ensure exactly one GraphQLObjectType instance exists for the target table.\n // If the root call for the target table has already run (or pre-registered a shell),\n // reuse that instance so the schema never contains duplicate type names.\n let relType = cacheCtx.objectTypeCache.get(targetTableName);\n if (!relType) {\n // The target table hasn't been processed yet. Pre-register a shell so that:\n // (a) this relation field has a concrete type reference, and\n // (b) when the target table's root call eventually runs, it reuses this same object.\n const targetTable = tables[targetTableName]!;\n const targetTableFields = generateTableSelectTypeFieldsCached(targetTable, targetTableName);\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 fields: () => ({ ...targetTableFields, ...capturedTargetContainer.fields }),\n });\n cacheCtx.objectTypeCache.set(targetTableName, relType);\n }\n\n const resolve = resolverFactory?.({ tableName, relationName, relEntry: relEntry as TableNamedRelations, isOne });\n\n if (isOne) {\n // Honor the relation's declared optionality: `r.one.Target({ ..., optional: false })`\n // asserts the related row always exists (a NOT NULL foreign key), so the field is\n // emitted as `Target!`. The default (`optional: true` / omitted) stays nullable.\n // Column nullability alone is NOT used to infer this — a notNull `from` column does\n // not guarantee a related row exists when the FK constraint lives on the other side\n // (e.g. `Users.customer` joins the notNull `Users.id` to `Customers.userId`).\n const isRequired = (relation as One<any, any>).optional === false;\n rawRelationFields.push([\n relationName,\n {\n type: isRequired ? new GraphQLNonNull(relType) : relType,\n args: {\n where: { type: relSelectData.filters },\n },\n resolve,\n },\n ]);\n continue;\n }\n\n rawRelationFields.push([\n relationName,\n {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(relType))),\n args: {\n where: { type: relSelectData.filters },\n orderBy: { type: relSelectData.order! },\n offset: { type: GraphQLInt },\n limit: { type: GraphQLInt },\n },\n resolve,\n ...(cacheCtx.complexity ? { extensions: { complexity: listFieldComplexity(cacheCtx.complexity) } } : {}),\n },\n ]);\n\n // Aggregate over the related rows without fetching them: `user { postsAggregate { count } }`.\n // Skipped when the name would shadow a column or another relation.\n const aggregateFieldName = `${relationName}Aggregate`;\n if (!tableFields[aggregateFieldName] && !relationsForTable?.[aggregateFieldName]) {\n const relationAggregate = relationAggregateFactory?.({\n tableName,\n relationName,\n relEntry: relEntry as TableNamedRelations,\n });\n\n if (relationAggregate) {\n rawRelationFields.push([\n aggregateFieldName,\n {\n type: new GraphQLNonNull(relationAggregate.type),\n args: {\n where: { type: relSelectData.filters },\n },\n resolve: relationAggregate.resolve,\n ...(cacheCtx.complexity\n ? { extensions: { complexity: aggregateFieldComplexity(cacheCtx.complexity) } }\n : {}),\n } as unknown as ConvertedRelationColumnWithArgs,\n ]);\n }\n }\n }\n\n const builtRelationFields = Object.fromEntries(rawRelationFields);\n\n // Only the root call should populate the container — non-root calls are temporary traversals\n // to collect filters/order for args and should not overwrite the canonical relation fields.\n if (isRootCall) {\n // Populate the container so that the thunk on the GraphQLObjectType shell (whether it was\n // created here or pre-registered by another table's relation traversal) picks up the fields.\n container.fields = builtRelationFields;\n cacheCtx.fullyBuiltTables.add(tableName);\n }\n\n return {\n order,\n filters,\n tableFields,\n relationFields: builtRelationFields,\n } as SelectData<TWithOrder>;\n }\n\n // No relation entries — mark as fully built if root call.\n if (isRootCall) {\n cacheCtx.fullyBuiltTables.add(tableName);\n }\n\n return {\n order,\n filters,\n tableFields,\n relationFields: {},\n } as SelectData<TWithOrder>;\n};\n\nexport const generateTableTypes = <WithReturning extends boolean>(\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n withReturning: WithReturning,\n relationsDepthLimit: number | undefined,\n cacheCtx: TypeCacheCtx,\n typeNameMapper: TypeNameMapper | undefined = undefined,\n insertPrefix: string = 'create',\n updatePrefix: string = 'update',\n resolverFactory?: RelationResolverFactory,\n relationAggregateFactory?: RelationAggregateFactory,\n): GeneratedTableTypes<WithReturning> => {\n const { tableFields, relationFields, filters, order } = generateSelectFields(\n tables,\n tableName,\n relationMap,\n '', // root call: no fromTableName\n '', // root call: no fromRelationName\n true,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n new Set(),\n resolverFactory,\n 0,\n relationAggregateFactory,\n );\n\n const table = tables[tableName]!;\n const columns = getColumns(table);\n const columnEntries = Object.entries(columns);\n\n const insertFields = Object.fromEntries(\n columnEntries.map(([columnName, columnDescription]) => [\n columnName,\n drizzleColumnToGraphQLType(columnDescription, columnName, tableName, false, true, true),\n ]),\n );\n\n const updateFields = Object.fromEntries(\n columnEntries.map(([columnName, columnDescription]) => [\n columnName,\n drizzleColumnToGraphQLType(columnDescription, columnName, tableName, true, false, true),\n ]),\n );\n\n // Insert/update input types: ${capitalize(insertPrefix)}${resolveTypeName(tableName)}Input / ${capitalize(updatePrefix)}${resolveTypeName(tableName)}Input\n const insertInput = new GraphQLInputObjectType({\n name: `${capitalize(insertPrefix)}${resolveTypeName(tableName, typeNameMapper)}Input`,\n fields: insertFields,\n });\n\n const updateInput = new GraphQLInputObjectType({\n name: `${capitalize(updatePrefix)}${resolveTypeName(tableName, typeNameMapper)}Input`,\n fields: 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 fields: { ...tableFields, ...relationFields },\n });\n\n const selectArrOutput = new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(selectSingleOutput)));\n\n // Mutation return type: ${capitalize(tableName)}Item (table columns only, no relations)\n // const singleTableItemOutput = withReturning\n // ? new GraphQLObjectType({\n // name: `${capitalize(tableName)}`,\n // // name: `${capitalize(tableName)}Item`,\n // fields: tableFields,\n // })\n // : undefined;\n\n const arrTableItemOutput = withReturning\n ? // ? new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(singleTableItemOutput!)))\n new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(selectSingleOutput!)))\n : undefined;\n\n const inputs = {\n insertInput,\n updateInput,\n tableOrder: order,\n tableFilters: filters,\n };\n\n const outputs = (\n withReturning\n ? {\n selectSingleOutput,\n selectArrOutput,\n singleTableItemOutput: selectSingleOutput!,\n // singleTableItemOutput: singleTableItemOutput!,\n arrTableItemOutput: arrTableItemOutput!,\n }\n : {\n selectSingleOutput,\n selectArrOutput,\n }\n ) as GeneratedTableTypesOutputs<WithReturning>;\n\n return {\n inputs,\n outputs,\n };\n};\n\n/** How NULLs are placed relative to non-NULL values in an ordered column. */\nexport type OrderNullsOption = 'first' | 'last';\n\n/**\n * Column name / direction / nulls triples from an `orderBy` argument, highest priority\n * first. Split out of `extractOrderBy` so the same ordering can be rebuilt against a\n * subquery's fields, where there is no `Table` to read columns from. Because there is no\n * table, ordering through a relation cannot be compiled here — a relation-shaped entry\n * (an object without a `direction`) is rejected with a clear error instead of being\n * silently dropped.\n */\nexport const orderByEntries = (\n orderArgs: Record<string, any>,\n): [string, 'asc' | 'desc', OrderNullsOption | undefined][] =>\n Object.entries(orderArgs)\n .sort((a, b) => (b[1]?.priority ?? 0) - (a[1]?.priority ?? 0))\n .filter(([, config]) => config)\n .map(([column, config]) => {\n if (typeof config === 'object' && config.direction === undefined) {\n throw new GraphQLError(`ORDER BY ${column}: ordering through a relation is not supported in this query`);\n }\n return [column, config.direction, config.nulls ?? undefined];\n });\n\n/**\n * The ORDER BY expression(s) for one ordered value. Without a `nulls` option this is the\n * plain `asc`/`desc` of the expression. With one:\n * - PostgreSQL and SQLite (3.30+) support `NULLS FIRST` / `NULLS LAST` natively, so the\n * clause is emitted as-is.\n * - MySQL has no such clause, so it is emulated with an extra `<expr> IS NULL` sort key\n * ahead of the expression itself (`IS NULL DESC` puts nulls first, `ASC` puts them\n * last). The same GraphQL surface is kept on all three dialects.\n *\n * `dialectColumn` is the real table column the expression derives from — used only to\n * detect the dialect (its `columnType` is prefixed `Pg` / `MySql` / `SQLite`), so `expr`\n * may be the column itself, a subquery field, or a correlated subquery.\n */\nexport const orderExpressions = (\n expr: Column | SQL | SQL.Aliased | any,\n direction: 'asc' | 'desc',\n nulls: OrderNullsOption | undefined,\n dialectColumn: Column,\n): SQL[] => {\n const directed = direction === 'asc' ? asc(expr) : desc(expr);\n\n if (!nulls) {\n return [directed];\n }\n\n const isMySql = (((dialectColumn as any).columnType as string) ?? '').startsWith('MySql');\n if (isMySql) {\n const nullsKey = nulls === 'first' ? desc(sql`(${expr} is null)`) : asc(sql`(${expr} is null)`);\n return [nullsKey, directed];\n }\n\n return [nulls === 'first' ? sql`${directed} nulls first` : sql`${directed} nulls last`];\n};\n\n/**\n * One ordering term, flattened out of a (possibly relation-nested) `orderBy` argument.\n * `expression` is what the ORDER BY sorts on — the column itself, or a correlated\n * subquery reaching it through one or more to-one relations. `column` is the leaf table\n * column, kept for dialect detection.\n */\ninterface FlatOrderEntry {\n expression: Column | SQL;\n column: Column;\n direction: 'asc' | 'desc';\n nulls: OrderNullsOption | undefined;\n priority: number;\n}\n\n/**\n * The chain of aliased to-one hops a relation-ordered column is reached through. Rendered\n * as a single correlated scalar subquery: every hop's target sits in the FROM list and\n * its join condition (plus the relation's own `where`, when it declares one) in the WHERE.\n */\ninterface RelationOrderChain {\n fromParts: SQL[];\n conditions: SQL[];\n /** The aliased target of the last hop — the table the next hop or leaf column resolves from. */\n table: Table;\n}\n\n/** Extends the chain (or starts one from `parentTable`) with one to-one hop. */\nconst extendRelationOrderChain = (\n parentTable: Table,\n relationName: string,\n relEntry: TableNamedRelations,\n ctx: RelationFilterContext,\n chain: RelationOrderChain | undefined,\n): RelationOrderChain => {\n const targetTable = ctx.tables[relEntry.targetTableName];\n const relation = ((relEntry as any).relation ?? relEntry) as Relation<string>;\n\n if (!targetTable || !is(relation, One) || !isFilterableRelation(relation)) {\n throw new GraphQLError(`ORDER BY ${relationName}: Relation cannot be used for ordering`);\n }\n\n ctx.aliases ??= { n: 0 };\n const aliasedTarget = aliasedTable(targetTable, `dgql_ord_${ctx.aliases.n++}`);\n\n const joinCondition = buildRelationJoinCondition(parentTable, relation, aliasedTarget, relationName);\n // A relation declared with its own `where` only ever exposes the rows it selects, so the\n // ordering subquery has to honour it too — mirroring the relation-filter subqueries.\n const relationWhere = (relation as any).where\n ? relationsFilterToSQL((relation as any).isReversed ? parentTable : aliasedTarget, (relation as any).where)\n : undefined;\n\n return {\n fromParts: [...(chain?.fromParts ?? []), getTableAsAliasSQL(aliasedTarget)],\n conditions: [\n ...(chain?.conditions ?? []),\n ...(joinCondition ? [joinCondition] : []),\n ...(relationWhere ? [relationWhere] : []),\n ],\n table: aliasedTarget,\n };\n};\n\n/**\n * Flattens one level of an `orderBy` argument into `out`. A column key becomes an entry\n * directly (wrapped in a correlated subquery when reached through a relation chain); a\n * to-one relation key recurses with the chain extended by that hop. Priorities live in one\n * global space, so a relation's column can interleave with the parent's own columns.\n */\nconst collectOrderEntries = (\n table: Table,\n tableKey: string,\n orderArgs: Record<string, any>,\n ctx: RelationFilterContext | undefined,\n chain: RelationOrderChain | undefined,\n out: FlatOrderEntry[],\n): void => {\n const columns = getColumns(table);\n const relations = ctx?.relationMap[tableKey];\n\n for (const [key, config] of Object.entries(orderArgs)) {\n if (config === null || config === undefined) {\n continue;\n }\n\n const column = columns[key];\n if (column) {\n out.push({\n expression: chain\n ? sql`(select ${column} from ${sql.join(chain.fromParts, sql`, `)} where ${and(...chain.conditions)})`\n : column,\n column,\n direction: config.direction,\n nulls: config.nulls ?? undefined,\n priority: config.priority ?? 0,\n });\n continue;\n }\n\n const relEntry = relations?.[key];\n if (!relEntry || !ctx) {\n throw new GraphQLError(`ORDER BY ${key}: Unknown column or relation`);\n }\n\n const nextChain = extendRelationOrderChain(chain?.table ?? table, key, relEntry, ctx, chain);\n collectOrderEntries(nextChain.table, relEntry.targetTableName, config, ctx, nextChain, out);\n }\n};\n\n/**\n * Compiles an `orderBy` argument into ORDER BY expressions, highest priority first.\n *\n * A key naming one of the table's columns orders by that column. A key naming a to-one\n * relation takes the target table's own OrderBy input and orders by the related row's\n * column(s), compiled as a correlated scalar subquery — reusing the aliased-join machinery\n * the relation filters are built on — so it works identically on all three dialects and\n * inside the relational query builder's aliased CTEs. Priorities share one global space\n * across relation boundaries. Each entry may also carry `nulls: first | last`\n * (see {@link orderExpressions} for how MySQL emulates it).\n *\n * `ctx` supplies the tables and relation map that relation ordering needs; callers whose\n * inputs cannot contain relation keys may omit it.\n */\nexport const extractOrderBy = <TTable extends Table, TArgs extends OrderByArgs<any> = OrderByArgs<TTable>>(\n table: TTable,\n orderArgs: TArgs,\n ctx?: RelationFilterContext,\n): SQL[] => {\n const entries: FlatOrderEntry[] = [];\n collectOrderEntries(table, ctx?.tableKey ?? '', orderArgs, ctx, undefined, entries);\n\n return entries\n .sort((a, b) => b.priority - a.priority)\n .flatMap((entry) => orderExpressions(entry.expression, entry.direction, entry.nulls, entry.column));\n};\n\n/**\n * Escape character pinned via `ESCAPE` on every generated safe-LIKE predicate. Bound as a\n * query parameter (never spliced into the SQL text), so no dialect-specific string-literal\n * escaping rules apply to it.\n */\nconst LIKE_ESCAPE_CHAR = '\\\\';\n\n/**\n * Escapes the LIKE wildcards (`%`, `_`) and the escape character itself (`\\`) in a literal\n * search term, so the term only ever matches literally inside a LIKE pattern.\n */\nconst escapeLikeValue = (value: string): string => value.replace(/[\\\\%_]/g, (char) => `\\\\${char}`);\n\n/**\n * The injection-safe string operators: the caller passes a literal search term, the library\n * builds the LIKE pattern with the term's `%` / `_` / `\\` escaped and the `ESCAPE` clause pinned.\n * The `i`-prefixed variants match case-insensitively.\n */\nconst safeLikeOps: Record<string, { buildPattern: (value: string) => string; insensitive: boolean }> = {\n startsWith: { buildPattern: (value) => `${escapeLikeValue(value)}%`, insensitive: false },\n endsWith: { buildPattern: (value) => `%${escapeLikeValue(value)}`, insensitive: false },\n contains: { buildPattern: (value) => `%${escapeLikeValue(value)}%`, insensitive: false },\n iStartsWith: { buildPattern: (value) => `${escapeLikeValue(value)}%`, insensitive: true },\n iEndsWith: { buildPattern: (value) => `%${escapeLikeValue(value)}`, insensitive: true },\n iContains: { buildPattern: (value) => `%${escapeLikeValue(value)}%`, insensitive: true },\n};\n\n/**\n * `LIKE <pattern> ESCAPE '\\'` for a safe string operator. Case-insensitive variants use\n * Postgres's native `ILIKE`; MySQL and SQLite have no `ILIKE`, so they compare `lower()`\n * on both sides instead (mirroring how the raw `ilike` operator is Postgres-only).\n */\nconst safeLikeCondition = (column: Column, pattern: string, insensitive: boolean): SQL => {\n if (!insensitive) {\n return sql`${column} like ${pattern} escape ${LIKE_ESCAPE_CHAR}`;\n }\n\n const isPg = (((column as any).columnType ?? '') as string).startsWith('Pg');\n return isPg\n ? sql`${column} ilike ${pattern} escape ${LIKE_ESCAPE_CHAR}`\n : sql`lower(${column}) like ${pattern.toLowerCase()} escape ${LIKE_ESCAPE_CHAR}`;\n};\n\n/**\n * Whether the column stores JSON — its `contains` operator is structural containment,\n * not the safe substring operator string columns get.\n */\nconst isJsonColumn = (column: Column): boolean => (((column as any).columnType ?? '') as string).includes('Json');\n\n/**\n * Structural JSON containment for the `contains` operator on json/jsonb columns.\n * The value is serialized and bound as a parameter (never interpolated into the SQL text):\n * - Postgres: `col @> $1::jsonb` (a plain `json` column is cast through jsonb — `json` has\n * no containment operator of its own)\n * - MySQL: `JSON_CONTAINS(col, ?)`\n * SQLite has no containment operator, so the filter input never exposes `contains` there;\n * reaching this with an unsupported dialect is a programming error surfaced as a GraphQLError.\n */\nconst jsonContains = (column: Column, columnName: string, value: any): SQL => {\n const serialized = JSON.stringify(value);\n\n switch (columnDialect(column)) {\n case 'pg':\n return (column as any).columnType === 'PgJson'\n ? sql`${column}::jsonb @> ${serialized}::jsonb`\n : sql`${column} @> ${serialized}::jsonb`;\n case 'mysql':\n return sql`json_contains(${column}, ${serialized})`;\n default:\n throw new GraphQLError(`WHERE ${columnName}: Operator 'contains' is not supported for this dialect!`);\n }\n};\n\nexport const extractFiltersColumn = <TColumn extends Column>(\n column: TColumn,\n columnName: string,\n operators: FilterColumnOperators<TColumn>,\n): SQL | undefined => {\n // Boolean branches compose with sibling operators: siblings and the AND list are ANDed\n // together, NOT negates its whole branch, and the OR group is ANDed with the rest.\n const { OR, AND, NOT, ...restOperators } = operators;\n\n const entries = Object.entries(restOperators as FilterColumnOperatorsCore<TColumn>);\n\n const singleValueOps: Record<string, (...args: any[]) => SQL> = { eq, ne, gt, gte, lt, lte };\n const stringValueOps: Record<string, (...args: any[]) => SQL> = { like, notLike, ilike, notIlike };\n const arrayValueOps: Record<string, (...args: any[]) => SQL> = { inArray, notInArray };\n // Membership operators for array columns: element list → SQL. Empty lists are rejected below.\n const arrayMembershipOps: Record<string, (...args: any[]) => SQL> = {\n hasSome: arrayOverlaps,\n hasEvery: arrayContains,\n };\n const nullableOps: Record<string, (...args: any[]) => SQL> = { isNull, isNotNull };\n\n const variants = [] as SQL[];\n for (const [operatorName, operatorValue] of entries) {\n if (operatorValue === null || operatorValue === false) {\n continue;\n }\n\n if (operatorName in singleValueOps) {\n const singleValue = remapFromGraphQLCore(operatorValue, column, columnName);\n variants.push(singleValueOps[operatorName]!(column, singleValue));\n } else if (operatorName in stringValueOps) {\n variants.push(stringValueOps[operatorName]!(column, operatorValue as string));\n } else if (operatorName === 'contains' && isJsonColumn(column)) {\n // `contains` is JSON containment on json/jsonb columns; on string columns it is the\n // safe substring operator handled by safeLikeOps below.\n variants.push(jsonContains(column, columnName, operatorValue));\n } else if (operatorName in safeLikeOps) {\n const { buildPattern, insensitive } = safeLikeOps[operatorName]!;\n variants.push(safeLikeCondition(column, buildPattern(operatorValue as string), insensitive));\n } else if (operatorName in arrayValueOps) {\n if (!(operatorValue as any[]).length) {\n throw new GraphQLError(`WHERE ${columnName}: Unable to use operator ${operatorName} with an empty array!`);\n }\n const arrayValue = (operatorValue as any[]).map((val) => remapFromGraphQLCore(val, column, columnName));\n variants.push(arrayValueOps[operatorName]!(column, arrayValue));\n } else if (operatorName === 'has') {\n // Single-element membership: containment with a one-element array (`col @> ARRAY[value]`).\n variants.push(arrayContains(column, [operatorValue]));\n } else if (operatorName in arrayMembershipOps) {\n if (!(operatorValue as any[]).length) {\n throw new GraphQLError(`WHERE ${columnName}: Unable to use operator ${operatorName} with an empty array!`);\n }\n variants.push(arrayMembershipOps[operatorName]!(column, operatorValue as any[]));\n } else if (operatorName === 'isEmpty') {\n variants.push(sql`cardinality(${column}) = 0`);\n } else if (operatorName in nullableOps) {\n variants.push(nullableOps[operatorName]!(column));\n } else {\n // An unrecognized operator must throw rather than be dropped: when the generated\n // schema is stitched/merged with another schema, foreign operators (e.g. `equals`,\n // `contains`, `mode`) can pass input validation, and silently dropping them could\n // turn a constrained where into an unbounded one.\n throw new GraphQLError(`WHERE ${columnName}: Unknown operator: ${operatorName}`);\n }\n }\n\n if (AND?.length) {\n for (const variant of AND) {\n const extracted = extractFiltersColumn(column, columnName, variant);\n if (extracted) {\n variants.push(extracted);\n }\n }\n }\n\n if (NOT) {\n const extracted = extractFiltersColumn(column, columnName, NOT);\n if (extracted) {\n variants.push(not(extracted));\n }\n }\n\n if (OR?.length) {\n const orVariants = [] as SQL[];\n for (const variant of OR) {\n const extracted = extractFiltersColumn(column, columnName, variant);\n if (extracted) {\n orVariants.push(extracted);\n }\n }\n\n if (orVariants.length) {\n variants.push(orVariants.length > 1 ? or(...orVariants)! : orVariants[0]!);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n\n/**\n * Everything `extractFilters` needs to turn a relation key in a `where` argument into a\n * correlated subquery. Omitted by callers that don't generate relation filters, in which case\n * relation keys can't appear in the input to begin with.\n */\nexport interface RelationFilterContext {\n /** Every table in the schema, keyed by its schema key. */\n tables: Record<string, Table>;\n /** Relations keyed by table schema key, then relation name. */\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n /**\n * Schema key of the table being filtered. Not always the same as the `tableName` label\n * used in error messages (relation `where` callbacks pass the relation name there).\n */\n tableKey: string;\n /** Shared counter making every subquery alias unique within one extraction. */\n aliases?: { n: number };\n}\n\n/**\n * The build-scoped half of {@link RelationFilterContext}. Created once per generated schema and\n * handed to every resolver, which adds the table it is filtering.\n */\nexport type RelationFilterBase = Pick<RelationFilterContext, 'tables' | 'relationMap'>;\n\n/** Narrows the build-scoped relation filter context to the table a resolver is filtering. */\nexport const relationFilterCtx = (\n base: RelationFilterBase | undefined,\n tableKey: string,\n): RelationFilterContext | undefined => (base ? { ...base, tableKey } : undefined);\n\n/** The three ways a to-many relation can be required to match, plus the to-one shorthand. */\ntype RelationMatchMode = 'some' | 'none' | 'every';\n\n/**\n * Correlates the parent row with the aliased target table using the relation's own join\n * columns. Columns are matched by SQL name rather than object identity so this also works when\n * the parent is an aliased proxy (as it is inside a relational `with:` where callback).\n */\nconst buildRelationJoinCondition = (\n parentTable: Table,\n relation: Relation<string>,\n aliasedTarget: Table,\n relationName: string,\n): SQL | undefined => {\n const sourceColumns = (relation as any).sourceColumns as Column[] | undefined;\n const targetColumns = (relation as any).targetColumns as Column[] | undefined;\n\n if (!sourceColumns?.length || sourceColumns.length !== targetColumns?.length) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\n }\n\n const parentColumns = Object.values(getColumns(parentTable));\n const targetColumnsByName = Object.values(getColumns(aliasedTarget));\n\n const conditions: SQL[] = [];\n for (let i = 0; i < sourceColumns.length; i++) {\n const localColumn = parentColumns.find((c) => c.name === sourceColumns[i]!.name);\n const foreignColumn = targetColumnsByName.find((c) => c.name === targetColumns[i]!.name);\n\n if (!localColumn || !foreignColumn) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\n }\n\n conditions.push(eq(localColumn, foreignColumn));\n }\n\n return conditions.length > 1 ? and(...conditions) : conditions[0];\n};\n\n/**\n * Resolves one side of a `.through()` junction pair to the corresponding column on the\n * aliased junction table. Drizzle stores the junction column as a RelationsBuilderColumn\n * (`_.column` is the Column, `_.key` its property name), so look up by property name first\n * and fall back to matching by SQL name.\n */\nconst resolveJunctionColumn = (aliasedThrough: Table, junctionRef: any, relationName: string): Column => {\n const throughColumns = getColumns(aliasedThrough);\n\n const key: string | undefined = junctionRef?._?.key;\n const byKey = key ? throughColumns[key] : undefined;\n if (byKey) {\n return byKey;\n }\n\n const columnName: string | undefined = junctionRef?._?.column?.name;\n const byName = columnName ? Object.values(throughColumns).find((c) => c.name === columnName) : undefined;\n if (!byName) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\n }\n\n return byName;\n};\n\n/**\n * Join conditions for a `.through()` (many-to-many) relation, split into the two legs of the\n * junction: `correlation` ties the parent row to the aliased junction table on the relation's\n * source keys, `junctionJoin` ties the aliased junction table to the aliased target on the\n * target keys. Column matching mirrors {@link buildRelationJoinCondition} — by SQL name on the\n * parent/target so aliased proxies work — while junction columns come from the relation's own\n * `through` metadata.\n */\nconst buildThroughJoinConditions = (\n parentTable: Table,\n relation: Relation<string>,\n aliasedThrough: Table,\n aliasedTarget: Table,\n relationName: string,\n): { correlation: SQL | undefined; junctionJoin: SQL | undefined } => {\n const sourceColumns = (relation as any).sourceColumns as Column[] | undefined;\n const targetColumns = (relation as any).targetColumns as Column[] | undefined;\n const through = (relation as any).through as { source: any[]; target: any[] } | undefined;\n\n if (\n !sourceColumns?.length ||\n !targetColumns?.length ||\n through?.source.length !== sourceColumns.length ||\n through.target.length !== targetColumns.length\n ) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\n }\n\n const parentColumns = Object.values(getColumns(parentTable));\n const targetTableColumns = Object.values(getColumns(aliasedTarget));\n\n const correlationConditions: SQL[] = [];\n for (let i = 0; i < sourceColumns.length; i++) {\n const localColumn = parentColumns.find((c) => c.name === sourceColumns[i]!.name);\n if (!localColumn) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\n }\n correlationConditions.push(eq(localColumn, resolveJunctionColumn(aliasedThrough, through.source[i], relationName)));\n }\n\n const junctionJoinConditions: SQL[] = [];\n for (let i = 0; i < targetColumns.length; i++) {\n const foreignColumn = targetTableColumns.find((c) => c.name === targetColumns[i]!.name);\n if (!foreignColumn) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\n }\n junctionJoinConditions.push(\n eq(resolveJunctionColumn(aliasedThrough, through.target[i], relationName), foreignColumn),\n );\n }\n\n return {\n correlation: correlationConditions.length > 1 ? and(...correlationConditions) : correlationConditions[0],\n junctionJoin: junctionJoinConditions.length > 1 ? and(...junctionJoinConditions) : junctionJoinConditions[0],\n };\n};\n\n/**\n * Builds one `[NOT] EXISTS (SELECT 1 FROM target alias WHERE …)` for a relation filter.\n * A `.through()` (many-to-many) relation adds an `INNER JOIN` on the aliased junction table\n * inside the subquery, correlated to the parent on the relation's source keys.\n *\n * `some` / the to-one shorthand match when a related row satisfies the inner filters, `none`\n * when none does, and `every` is expressed as \"no related row fails the inner filters\".\n * Because `every` negates the inner condition, a related row whose compared column is NULL\n * counts as matching (SQL three-valued logic) — the same caveat Prisma carries.\n */\nconst buildRelationExists = (\n parentTable: Table,\n relationName: string,\n relEntry: TableNamedRelations,\n innerFilters: Filters<Table> | undefined,\n mode: RelationMatchMode,\n ctx: RelationFilterContext,\n): SQL | undefined => {\n const { targetTableName } = relEntry;\n const targetTable = ctx.tables[targetTableName];\n const relation = ((relEntry as any).relation ?? relEntry) as Relation<string>;\n\n if (!targetTable) {\n throw new GraphQLError(`WHERE ${relationName}: Relation cannot be used as a filter`);\n }\n\n ctx.aliases ??= { n: 0 };\n const aliases = ctx.aliases;\n const aliasedTarget = aliasedTable(targetTable, `dgql_rel_${aliases.n++}`);\n\n // A `.through()` relation reaches the target via a junction table: the subquery joins the\n // aliased junction to the aliased target and correlates the junction to the parent, so\n // `some` / `none` / `every` compile exactly like the direct case with a longer FROM clause.\n const throughTable = (relation as any).throughTable as Table | undefined;\n let fromClause: SQL;\n let joinCondition: SQL | undefined;\n if (throughTable) {\n const aliasedThrough = aliasedTable(throughTable, `dgql_rel_${aliases.n++}`);\n const { correlation, junctionJoin } = buildThroughJoinConditions(\n parentTable,\n relation,\n aliasedThrough,\n aliasedTarget,\n relationName,\n );\n fromClause = sql`${getTableAsAliasSQL(aliasedTarget)} inner join ${getTableAsAliasSQL(aliasedThrough)} on ${junctionJoin}`;\n joinCondition = correlation;\n } else {\n fromClause = getTableAsAliasSQL(aliasedTarget);\n joinCondition = buildRelationJoinCondition(parentTable, relation, aliasedTarget, relationName);\n }\n\n // A relation declared with its own `where` only ever exposes the rows it selects, so the\n // subquery has to honour it too — otherwise a filter could match a row the relation hides.\n const relationWhere = (relation as any).where\n ? relationsFilterToSQL((relation as any).isReversed ? parentTable : aliasedTarget, (relation as any).where)\n : undefined;\n\n const inner = innerFilters\n ? extractFilters(aliasedTarget, targetTableName, innerFilters, { ...ctx, tableKey: targetTableName, aliases })\n : undefined;\n\n if (mode === 'every') {\n // \"every related row matches\" with no inner condition is vacuously true.\n if (!inner) {\n return undefined;\n }\n\n return sql`not exists (select 1 from ${fromClause} where ${and(joinCondition, relationWhere, not(inner))})`;\n }\n\n const condition = and(joinCondition, relationWhere, inner);\n\n return mode === 'none'\n ? sql`not exists (select 1 from ${fromClause} where ${condition})`\n : sql`exists (select 1 from ${fromClause} where ${condition})`;\n};\n\n/**\n * Handles one relation key in a `where` argument. To-one relations take the target's filters\n * inline; to-many relations take any combination of `some` / `none` / `every`, ANDed together.\n */\nconst extractRelationFilter = (\n parentTable: Table,\n relationName: string,\n relEntry: TableNamedRelations,\n value: Record<string, any>,\n ctx: RelationFilterContext,\n): SQL | undefined => {\n const relation = ((relEntry as any).relation ?? relEntry) as Relation<string>;\n\n if (is(relation, One)) {\n return buildRelationExists(parentTable, relationName, relEntry, value, 'some', ctx);\n }\n\n const relationMatchModes: readonly RelationMatchMode[] = ['some', 'none', 'every'];\n\n const variants: SQL[] = [];\n for (const [mode, inner] of Object.entries(value)) {\n if (inner === undefined || inner === null) {\n continue;\n }\n\n // Unknown keys inside the some/none/every wrapper must throw rather than be dropped —\n // a stitched schema can contribute foreign keys here too, and dropping them all would\n // silently turn the relation filter into no filter at all.\n if (!relationMatchModes.includes(mode as RelationMatchMode)) {\n throw new GraphQLError(`WHERE ${relationName}: Unknown relation filter key: ${mode}`);\n }\n\n const extracted = buildRelationExists(parentTable, relationName, relEntry, inner, mode as RelationMatchMode, ctx);\n if (extracted) {\n variants.push(extracted);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n\nexport const extractFilters = <TTable extends Table>(\n table: TTable,\n tableName: string,\n filters: Filters<TTable>,\n relationCtx?: RelationFilterContext,\n): SQL | undefined => {\n // Boolean branches compose with sibling fields: siblings and the AND list are ANDed\n // together, NOT negates its whole branch, and the OR group is ANDed with the rest —\n // `{ a: …, OR: [{ b: … }, { c: … }] }` reads as `a AND (b OR c)`. Every branch is the\n // filter type itself, so the tree nests arbitrarily.\n const { OR, AND, NOT, ...fieldFilters } = filters;\n\n const entries = Object.entries(fieldFilters as FiltersCore<TTable>);\n\n const columns = getColumns(table);\n const relations = relationCtx?.relationMap[relationCtx.tableKey];\n\n const variants = [] as SQL[];\n for (const [fieldName, operators] of entries) {\n if (operators === null || operators === undefined) {\n continue;\n }\n\n const column = columns[fieldName];\n\n // A key that is neither a column nor a filterable relation must throw rather than be\n // dropped: when the generated schema is stitched/merged with another schema, same-named\n // inputs can contribute foreign keys that pass input validation, and a where that loses\n // all of its keys silently becomes an unbounded select/update/delete.\n if (!column && !(relations?.[fieldName] && relationCtx)) {\n throw new GraphQLError(`WHERE ${tableName}: Unknown filter key: ${fieldName}`);\n }\n\n const extracted = column\n ? extractFiltersColumn(column, fieldName, operators)\n : extractRelationFilter(table, fieldName, relations![fieldName]!, operators as any, relationCtx!);\n\n if (extracted) {\n variants.push(extracted);\n }\n }\n\n if (AND?.length) {\n for (const variant of AND) {\n const extracted = extractFilters(table, tableName, variant, relationCtx);\n if (extracted) {\n variants.push(extracted);\n }\n }\n }\n\n if (NOT) {\n const extracted = extractFilters(table, tableName, NOT, relationCtx);\n if (extracted) {\n variants.push(not(extracted));\n }\n }\n\n if (OR?.length) {\n const orVariants = [] as SQL[];\n for (const variant of OR) {\n const extracted = extractFilters(table, tableName, variant, relationCtx);\n if (extracted) {\n orVariants.push(extracted);\n }\n }\n\n if (orVariants.length) {\n variants.push(orVariants.length > 1 ? or(...orVariants)! : orVariants[0]!);\n }\n }\n\n return variants.length ? (variants.length > 1 ? and(...variants) : variants[0]) : undefined;\n};\n\nconst extractRelationsParamsInner = (\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n tables: Record<string, Table>,\n tableName: string,\n typeName: string,\n originField: ResolveTree,\n typeNameMapper?: TypeNameMapper,\n _isInitial: boolean = false,\n filterCtx?: RelationFilterBase,\n) => {\n const relationsForTable = relationMap[tableName];\n if (!relationsForTable) {\n return undefined;\n }\n\n const baseField = Object.entries(originField.fieldsByTypeName).find(([key, _value]) => key === typeName)?.[1];\n if (!baseField) {\n return undefined;\n }\n\n const args: Record<string, Partial<ProcessedTableSelectArgs>> = {};\n\n for (const [relName, relEntry] of Object.entries(relationsForTable)) {\n const { targetTableName, targetPkNames } = relEntry;\n // The relation field resolves to the target table's own type, e.g. \"Posts\" not \"UsersPostsRelation\".\n const relTypeName = resolveTypeName(targetTableName, typeNameMapper);\n // Look up by field name OR by alias (when the caller uses an alias for the relation).\n // graphql-parse-resolve-info keys fieldsByTypeName entries by alias.\n const field = baseField[relName] ?? Object.values(baseField).find((f) => (f as ResolveTree).name === relName);\n if (!field) {\n continue;\n }\n const relField = (field as ResolveTree)?.fieldsByTypeName;\n const relFieldSelection = relField?.[relTypeName];\n\n // Guard: if the relation type is not in fieldsByTypeName, this field is\n // either an aliased scalar column (not an actual relation) or the relation\n // was not selected in the query. Skip it in both cases.\n if (!relFieldSelection) {\n continue;\n }\n\n const columns = extractSelectedColumnsFromTree(relFieldSelection, tables[targetTableName]!, {\n tableName: targetTableName,\n relationMap,\n tables,\n });\n\n const thisRecord: Partial<ProcessedTableSelectArgs> = {};\n thisRecord.columns = columns;\n\n const relationField = Object.values(baseField).find((e) => e.name === relName);\n const relationArgs: Partial<TableSelectArgs> | undefined = relationField?.args;\n\n const offset = relationArgs?.offset ?? undefined;\n const limit = relationArgs?.limit ?? undefined;\n\n // drizzle-orm v1 RQB calls both `where` and `orderBy` callbacks with an\n // aliased table proxy (e.g. d0, d1). Pass the proxy through so column\n // references in the generated SQL match the CTE alias rather than the\n // original unaliased table name.\n const relWhere = relationArgs?.where;\n thisRecord.where = relWhere\n ? {\n RAW: (aliasedTable: Table) =>\n extractFilters(aliasedTable, relName, relWhere, relationFilterCtx(filterCtx, targetTableName)),\n }\n : undefined;\n // When a relation is paginated (limit/offset) but unordered, default to the target's\n // primary key so the per-parent slice is deterministic. Drizzle's RQB calls orderBy\n // with the aliased table proxy, so resolve the PK columns from it. targetPkNames is\n // resolved at build time and includes composite keys.\n const hasPagination = offset != null || limit != null;\n const pkNames = targetPkNames ?? [];\n thisRecord.orderBy = relationArgs?.orderBy\n ? (aliasedTable: Table) =>\n extractOrderBy(aliasedTable, relationArgs.orderBy!, relationFilterCtx(filterCtx, targetTableName))\n : hasPagination && pkNames.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined;\n thisRecord.offset = offset;\n thisRecord.limit = limit;\n\n const relWith = relationField\n ? extractRelationsParamsInner(\n relationMap,\n tables,\n targetTableName,\n relTypeName,\n relationField,\n typeNameMapper,\n false,\n filterCtx,\n )\n : undefined;\n thisRecord.with = relWith;\n\n args[relName] = thisRecord;\n }\n\n return args;\n};\n\nexport const extractRelationsParams = (\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n tables: Record<string, Table>,\n tableName: string,\n info: ResolveTree | undefined,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): Record<string, Partial<ProcessedTableSelectArgs>> | undefined => {\n if (!info) {\n return undefined;\n }\n\n return extractRelationsParamsInner(relationMap, tables, tableName, typeName, info, typeNameMapper, true, filterCtx);\n};\n\n/**\n * Returns a copy of `relationMap` containing only the relations that should be eagerly\n * pre-fetched (per the `shouldEagerLoad` predicate). Pass the result wherever a query or\n * mutation resolver builds its `with:` clause; pass the full map to type generation so\n * opted-out relations still get a (lazily-resolved) field. Relations excluded here are\n * never added to `with:`, so they don't overfetch — they resolve through their field\n * resolver instead (or a resolver you override, e.g. via `@graphql-tools/schema`).\n */\nexport const pruneNonEagerRelations = (\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n shouldEagerLoad: (tableName: string, relationName: string) => boolean,\n): Record<string, Record<string, TableNamedRelations>> => {\n const out: Record<string, Record<string, TableNamedRelations>> = {};\n for (const [tableName, rels] of Object.entries(relationMap)) {\n out[tableName] = Object.fromEntries(\n Object.entries(rels).filter(([relationName]) => shouldEagerLoad(tableName, relationName)),\n );\n }\n return out;\n};\n\n/**\n * Returns the property names of a table's primary key column(s).\n *\n * drizzle-orm marks inline `.primaryKey()` columns with `column.primary === true`,\n * but table-level composite keys (`primaryKey({ columns })`) leave `column.primary`\n * false on each member — those are only visible via the per-dialect `getTableConfig`.\n * Dialect builders pass the composite members' DB column names in via\n * `compositePkColumnNames`; we map them back to property names here.\n *\n * Resolution order: inline PK columns → composite PK columns → empty. We deliberately\n * do NOT guess a column named `id`: if no real primary key is declared, returning empty\n * lets callers fall back to the batch loader rather than re-keying on a possibly\n * non-unique column.\n */\nexport const getPrimaryKeyPropNames = (table: Table, compositePkColumnNames?: readonly string[]): string[] => {\n const cols = getColumns(table);\n const entries = Object.entries(cols);\n\n // Inline single `.primaryKey()` columns.\n const inlinePks = entries.filter(([, c]) => (c as any).primary).map(([k]) => k);\n if (inlinePks.length) {\n return inlinePks;\n }\n\n // Composite primary key (DB column names supplied by the dialect builder).\n if (compositePkColumnNames?.length) {\n const wanted = new Set(compositePkColumnNames);\n const fromComposite = entries.filter(([, c]) => wanted.has((c as any).name)).map(([k]) => k);\n if (fromComposite.length) {\n return fromComposite;\n }\n }\n\n // No declared primary key — let the caller fall back to the batch loader.\n return [];\n};\n\n/**\n * Ensures a selected-columns map (SQL format: prop name → Column) includes the table's\n * primary-key columns. Mutation resolvers pass their RETURNING columns through this so\n * the eager-loader can re-key rows by PK even when the client didn't select it. Mutates\n * and returns the same map.\n */\nexport const withPrimaryKeyColumns = <T extends Record<string, any>>(\n columns: T,\n table: Table,\n pkNames: readonly string[],\n): T => {\n const allCols = getColumns(table);\n for (const pk of pkNames) {\n if (!(pk in columns) && allCols[pk]) {\n (columns as any)[pk] = allCols[pk];\n }\n }\n return columns;\n};\n\n/**\n * Resolves a table's primary-key property names using a dialect's `getTableConfig` to\n * surface table-level composite keys (whose member columns aren't flagged `.primary`).\n * Each dialect builder binds this with its own getTableConfig and reuses the binding for\n * both relation pagination and mutation re-fetch keying.\n */\nexport const getPrimaryKeyPropNamesFromConfig = (\n table: Table,\n getTableConfig: (table: Table) => { primaryKeys: { columns: { name: string }[] }[] },\n): string[] => {\n const compositePkColumnNames = getTableConfig(table).primaryKeys.flatMap((pk) => pk.columns.map((c) => c.name));\n return getPrimaryKeyPropNames(table, compositePkColumnNames);\n};\n\n/**\n * Ascending order expressions for a table's primary key — the deterministic tiebreak for\n * paginated relations. Shared by the window-function batch path and the eager `with:`\n * orderBy default so both order identically. `table` may be the aliased RQB proxy.\n */\nexport const primaryKeyOrderExprs = (table: Table, pkNames: readonly string[]): any[] => {\n const cols = getColumns(table);\n return pkNames\n .map((n) => cols[n])\n .filter(Boolean)\n .map((col) => asc(col!));\n};\n\n// ── cursor (keyset) pagination ───────────────────────────────────────────────\n\n/** Name of the field on generated select types that exposes a row's opaque pagination cursor. */\nexport const CURSOR_FIELD_NAME = 'cursor';\n\n/**\n * Property the list resolvers stash each row's computed cursor under. Namespaced so it can't\n * collide with a real column; the `cursor` field's resolver reads it back off the row.\n */\nconst ROW_CURSOR_PROP = '__drizzle_graphql_cursor';\n\n/**\n * Where a dialect's default sort places NULLs relative to non-NULL values:\n * - `nulls-largest` — PostgreSQL: NULLs sort as the largest values (last in ASC, first in DESC).\n * - `nulls-smallest` — MySQL and SQLite: NULLs sort as the smallest values (first in ASC, last\n * in DESC).\n * The keyset predicate has to agree with the dialect's ORDER BY, so each builder passes its own.\n */\nexport type NullOrdering = 'nulls-largest' | 'nulls-smallest';\n\n/**\n * One key of the total order a cursor is defined over: column property name + direction,\n * plus the request's `nulls: first | last` override when it carries one (absent/null means\n * the dialect's native NULL placement).\n */\nexport type CursorOrderEntry = [string, 'asc' | 'desc', (OrderNullsOption | null)?];\n\n/**\n * Whether an `orderBy` argument orders through a to-one relation (a nested object entry\n * rather than a direction). A cursor encodes the row's own ordering-tuple values, and a\n * related row's value is not part of the row, so cursor pagination refuses these orderings —\n * `after` raises an error and the `cursor` field resolves to null, while the ordering itself\n * still applies.\n */\nexport const orderByHasRelationEntry = (orderBy: Record<string, any> | undefined): boolean =>\n !!orderBy &&\n Object.values(orderBy).some((config) => config && typeof config === 'object' && config.direction === undefined);\n\n/**\n * The total order a list query's rows follow when cursor pagination is in play: the request's\n * `orderBy` entries (highest priority first), then the primary key ascending as a tiebreak —\n * skipping PK columns the `orderBy` already names, so no key appears twice.\n */\nexport const cursorOrderingEntries = (\n orderBy: Record<string, any> | undefined,\n pkNames: readonly string[],\n): CursorOrderEntry[] => {\n const entries: CursorOrderEntry[] = orderBy ? orderByEntries(orderBy) : [];\n const seen = new Set(entries.map(([column]) => column));\n for (const pk of pkNames) {\n if (!seen.has(pk)) {\n entries.push([pk, 'asc']);\n }\n }\n return entries;\n};\n\n/**\n * ORDER BY expressions realizing a cursor's total order on `table` (which may be the aliased\n * RQB proxy) — each key's direction plus its `nulls` override, exactly the order the keyset\n * predicate in {@link buildCursorCondition} compares against.\n */\nexport const cursorOrderExprs = (table: Table, entries: CursorOrderEntry[]): SQL[] => {\n const cols = getColumns(table);\n return entries.flatMap(([column, direction, nulls]) =>\n orderExpressions(cols[column]!, direction, nulls ?? undefined, cols[column]!),\n );\n};\n\n/**\n * Serializes one ordering-tuple value into a JSON-safe shape. Dates and bigints don't survive\n * JSON.stringify losslessly (bigint throws, Date turns into an untagged string), so they are\n * tagged; decimals already arrive from the driver as strings, which are lossless as-is.\n */\nconst encodeCursorValue = (value: any): any => {\n if (value instanceof Date) {\n return { $type: 'date', value: value.toISOString() };\n }\n if (typeof value === 'bigint') {\n return { $type: 'bigint', value: value.toString() };\n }\n return value;\n};\n\nconst decodeCursorValue = (value: any): any => {\n if (value && typeof value === 'object' && typeof value.$type === 'string') {\n if (value.$type === 'date') {\n return new Date(value.value);\n }\n if (value.$type === 'bigint') {\n return BigInt(value.value);\n }\n }\n return value;\n};\n\n/**\n * Encodes a row's position in the given total order as an opaque cursor: base64url of a JSON\n * payload holding the ordering spec (`o`) and the row's values for it (`v`). The spec rides\n * along so a later request can verify the cursor was issued for the same ordering it is using.\n */\nexport const encodeCursor = (entries: CursorOrderEntry[], row: Record<string, any>): string => {\n const payload = {\n o: entries,\n v: entries.map(([column]) => encodeCursorValue(row[column] ?? null)),\n };\n return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');\n};\n\n/**\n * Decodes an `after` cursor and validates it against the ordering the current request pages\n * over. A cursor issued under a different `orderBy` would combine one ordering's predicate\n * with another's sort — silently wrong pages — so a mismatch is an error, as is anything that\n * doesn't decode to the expected payload shape.\n */\nexport const decodeCursor = (after: string, entries: CursorOrderEntry[]): any[] => {\n let payload: any;\n try {\n payload = JSON.parse(Buffer.from(after, 'base64url').toString('utf8'));\n } catch (_e) {\n throw new GraphQLError('Invalid cursor: unable to decode it. Pass a cursor returned by a previous page.');\n }\n\n if (\n !payload ||\n typeof payload !== 'object' ||\n !Array.isArray(payload.o) ||\n !Array.isArray(payload.v) ||\n payload.o.length !== payload.v.length\n ) {\n throw new GraphQLError('Invalid cursor: malformed payload. Pass a cursor returned by a previous page.');\n }\n\n const matchesOrdering =\n payload.o.length === entries.length &&\n payload.o.every(\n (entry: any, i: number) =>\n Array.isArray(entry) &&\n entry[0] === entries[i]![0] &&\n entry[1] === entries[i]![1] &&\n // The nulls override changes where NULLs sort, so it is part of the ordering identity.\n // JSON round-trips undefined as null — compare the normalized forms.\n (entry[2] ?? null) === (entries[i]![2] ?? null),\n );\n if (!matchesOrdering) {\n throw new GraphQLError(\n \"Invalid cursor: it was issued for a different ordering. Pass the same orderBy the cursor's page used.\",\n );\n }\n\n return payload.v.map(decodeCursorValue);\n};\n\n/**\n * The keyset predicate selecting rows strictly after the cursor position in the given total\n * order — the expanded lexicographic form\n * `after(k0) OR (k0 = v0 AND after(k1)) OR (k0 = v0 AND k1 = v1 AND after(k2)) …`,\n * built with and/or/gt/lt/eq rather than SQL row-value syntax, which cannot express mixed\n * asc/desc directions and mishandles NULLs.\n *\n * NULL handling follows each key's `nulls: first | last` override when present, and otherwise\n * the dialect's default sort position (see {@link NullOrdering}): where NULLs sort last for a\n * key, \"after a non-NULL value\" includes the NULL rows and nothing sorts after a NULL one;\n * where NULLs sort first, \"after NULL\" is every non-NULL row.\n * `table` may be the aliased RQB proxy.\n */\nexport const buildCursorCondition = (\n table: Table,\n entries: CursorOrderEntry[],\n values: any[],\n nullOrdering: NullOrdering,\n): SQL => {\n const cols = getColumns(table);\n const disjuncts: SQL[] = [];\n const equalities: SQL[] = [];\n\n entries.forEach(([column, direction, nulls], i) => {\n const col = cols[column];\n if (!col) {\n throw new GraphQLError(`Invalid cursor: unknown column '${column}'.`);\n }\n\n const value = values[i];\n const nullsSortLast =\n nulls != null ? nulls === 'last' : (direction === 'asc') === (nullOrdering === 'nulls-largest');\n\n let strictlyAfter: SQL | undefined;\n if (value === null || value === undefined) {\n // Nothing sorts after NULL when NULLs are last; every non-NULL row does when first.\n strictlyAfter = nullsSortLast ? undefined : isNotNull(col);\n } else {\n const comparison = direction === 'asc' ? gt(col, value) : lt(col, value);\n strictlyAfter = nullsSortLast ? or(comparison, isNull(col)) : comparison;\n }\n\n if (strictlyAfter) {\n disjuncts.push(equalities.length ? and(...equalities, strictlyAfter)! : strictlyAfter);\n }\n equalities.push(value === null || value === undefined ? isNull(col) : eq(col, value));\n });\n\n if (!disjuncts.length) {\n // Every key's strict term was impossible (e.g. a NULLs-last cursor position of all NULLs) —\n // nothing sorts after this cursor.\n return sql`1 = 0`;\n }\n\n return disjuncts.length > 1 ? or(...disjuncts)! : disjuncts[0]!;\n};\n\n/**\n * Whether the selection asks for the `cursor` meta field. A real column named `cursor` keeps\n * the field for itself, so the meta field only exists (and is only computed) when the table\n * has no such column.\n */\nexport const isCursorFieldSelected = (tree: Record<string, ResolveTree> | undefined, table: Table): boolean => {\n if (!tree) {\n return false;\n }\n if (getColumns(table)[CURSOR_FIELD_NAME]) {\n return false;\n }\n return Object.values(tree).some((field) => field.name === CURSOR_FIELD_NAME);\n};\n\n/**\n * Computes and attaches each row's opaque cursor (under a namespaced property the `cursor`\n * field's resolver reads). Must run on the raw driver rows, before output remapping rewrites\n * dates and bigints into their transport forms.\n */\nexport const attachRowCursors = (rows: Record<string, any>[], entries: CursorOrderEntry[]): void => {\n for (const row of rows) {\n row[ROW_CURSOR_PROP] = encodeCursor(entries, row);\n }\n};\n\n/** Resolver for the `cursor` meta field: reads the value a list resolver attached, if any. */\nexport const rowCursorResolver = (source: any): string | null => source?.[ROW_CURSOR_PROP] ?? null;\n\n/**\n * Every set of columns that uniquely identifies a row of `table`: the primary key first,\n * then each unique constraint and unique index, then each column declared `.unique()`\n * inline. Sets are property names (what GraphQL inputs use), not database column names.\n *\n * `getTableConfig` is the dialect's own — the three dialects expose the same\n * `{ primaryKeys, uniqueConstraints, indexes }` shape but from different modules, so the\n * caller passes theirs in, as `getPrimaryKeyPropNamesFromConfig` does.\n *\n * Index entries whose columns are SQL expressions rather than plain columns are skipped:\n * an expression index is a valid conflict target in the database but cannot be named by a\n * column enum. Deduplicated, order-insensitive — a column that is both the primary key and\n * a unique constraint yields one set.\n */\nexport const getUniqueColumnSets = (\n table: Table,\n getTableConfig: (table: Table) => {\n primaryKeys: { columns: { name: string }[] }[];\n uniqueConstraints?: { columns: { name: string }[] }[];\n indexes?: { config: { unique?: boolean; columns: any[] } }[];\n },\n): string[][] => {\n const cols = getColumns(table);\n const propNameByColumnName = new Map(Object.entries(cols).map(([propName, col]) => [(col as any).name, propName]));\n // A set is usable only if every one of its columns maps back to a property on the table.\n const toPropNames = (columnNames: (string | undefined)[]): string[] | undefined => {\n const propNames: string[] = [];\n for (const columnName of columnNames) {\n const propName = columnName === undefined ? undefined : propNameByColumnName.get(columnName);\n if (!propName) {\n return undefined;\n }\n propNames.push(propName);\n }\n return propNames.length ? propNames : undefined;\n };\n\n const config = getTableConfig(table);\n const candidates: (string[] | undefined)[] = [\n // Inline `.primaryKey()` columns, then table-level `primaryKey({ columns })`.\n Object.entries(cols)\n .filter(([, col]) => (col as any).primary)\n .map(([propName]) => propName),\n ...config.primaryKeys.map((pk) => toPropNames(pk.columns.map((c) => c.name))),\n ...(config.uniqueConstraints ?? []).map((uc) => toPropNames(uc.columns.map((c) => c.name))),\n ...(config.indexes ?? [])\n .filter((index) => index.config.unique)\n .map((index) => toPropNames(index.config.columns.map((c) => (c as any)?.name))),\n ...Object.entries(cols)\n .filter(([, col]) => (col as any).isUnique)\n .map(([propName]) => [propName]),\n ];\n\n const seen = new Set<string>();\n const sets: string[][] = [];\n for (const set of candidates) {\n if (!set?.length) {\n continue;\n }\n const key = [...set].sort().join(',');\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n sets.push(set);\n }\n return sets;\n};\n\n/** Alias of the row-number helper column in the `distinct` pass. Namespaced against real columns. */\nconst DISTINCT_RN = '__drizzle_graphql_distinct_rn';\n\nconst columnEnumCache = new WeakMap<object, Map<string, GraphQLEnumType>>();\n\n/**\n * An enum of a table's column property names, under `enumName`. Cached per (table, enum\n * name), like the order/filter inputs, so repeated builds reuse one instance and two enums\n * over the same table never collide.\n *\n * Returns `undefined` when no column qualifies — the caller then omits the argument or\n * input field the enum would have typed, rather than emitting an empty enum, which is\n * invalid GraphQL.\n */\nexport const generateColumnEnum = (\n table: Table,\n enumName: string,\n description: string,\n predicate: (column: Column, columnName: string) => boolean = () => true,\n): GraphQLEnumType | undefined => {\n let tableCache = columnEnumCache.get(table);\n const cached = tableCache?.get(enumName);\n if (cached) {\n return cached;\n }\n\n const columnNames = Object.entries(getColumns(table))\n .filter(([columnName, column]) => predicate(column as Column, columnName))\n .map(([columnName]) => columnName);\n if (!columnNames.length) {\n return undefined;\n }\n\n const enumType = new GraphQLEnumType({\n name: enumName,\n description,\n values: Object.fromEntries(columnNames.map((columnName) => [columnName, { value: columnName }])),\n });\n\n if (!tableCache) {\n tableCache = new Map();\n columnEnumCache.set(table, tableCache);\n }\n tableCache.set(enumName, enumType);\n return enumType;\n};\n\n/** `${typeName}DistinctColumn` — the enum of columns a list query may be made distinct on. */\nexport const generateDistinctEnum = (table: Table, typeName: string): GraphQLEnumType | undefined =>\n generateColumnEnum(table, `${typeName}DistinctColumn`, `Columns of ${typeName} that a query can be made distinct on`);\n\n// ── upsert / conflict handling ────────────────────────────────────────────────\n\n/** Shared by every table's `${typeName}OnConflict` input, so it is created once. */\nexport const conflictActionEnum = new GraphQLEnumType({\n name: 'ConflictAction',\n description: 'What an upsert does when a row with the same unique key already exists',\n values: {\n UPDATE: { value: 'UPDATE', description: 'Overwrite the conflicting row with the supplied values' },\n NOTHING: { value: 'NOTHING', description: 'Keep the existing row and insert nothing' },\n },\n});\n\n/**\n * The `${typeName}OnConflict` input that types an upsert's `onConflict` argument.\n *\n * `target` and `where` only exist when the dialect can express them: MySQL's\n * `ON DUPLICATE KEY UPDATE` fires on any unique key and takes no predicate, so offering\n * either there would mean silently ignoring it.\n *\n * Returns `undefined` when the table has nothing to conflict on (`withTarget` dialects\n * only) — the caller then generates no upsert mutations for that table at all, rather than\n * an operation whose every call is a database error.\n */\nexport const generateOnConflictInput = (params: {\n table: Table;\n typeName: string;\n uniqueSets: string[][];\n tableFilters: GraphQLInputObjectType;\n withTarget: boolean;\n}): GraphQLInputObjectType | undefined => {\n const { table, typeName, uniqueSets, tableFilters, withTarget } = params;\n\n const updateEnum = generateColumnEnum(\n table,\n `${typeName}UpdateColumn`,\n `Columns of ${typeName} that an upsert can overwrite`,\n );\n if (!updateEnum) {\n return undefined;\n }\n\n const fields: Record<string, any> = {\n action: {\n type: conflictActionEnum,\n defaultValue: 'UPDATE',\n description: 'Whether a conflicting row is overwritten or left alone. Defaults to UPDATE.',\n },\n update: {\n type: new GraphQLList(new GraphQLNonNull(updateEnum)),\n description:\n 'Columns to overwrite on conflict. Defaults to every column the request supplied, minus the conflict target. Columns the request did not supply cannot be listed here — there would be no value to write.',\n },\n };\n\n if (withTarget) {\n const uniqueColumns = new Set(uniqueSets.flat());\n const targetEnum = generateColumnEnum(\n table,\n `${typeName}ConflictTarget`,\n `Columns of ${typeName} that carry a unique constraint, and so can be conflicted on`,\n (_column, columnName) => uniqueColumns.has(columnName),\n );\n if (!targetEnum) {\n return undefined;\n }\n\n fields['target'] = {\n type: new GraphQLList(new GraphQLNonNull(targetEnum)),\n description:\n 'The unique column set a conflict is detected on. Must match one of the table’s unique constraints exactly. Defaults to the primary key.',\n };\n fields['where'] = {\n type: tableFilters,\n description: 'Only overwrite conflicting rows that match this filter. Others are left alone.',\n };\n }\n\n return new GraphQLInputObjectType({\n name: `${typeName}OnConflict`,\n description: `Conflict handling for an upsert of ${typeName}`,\n fields,\n });\n};\n\n/** The `onConflict` argument as it arrives from GraphQL. */\nexport type OnConflictArg = {\n action?: 'UPDATE' | 'NOTHING';\n target?: string[];\n update?: string[];\n where?: any;\n};\n\n/** What a dialect needs to turn an insert into an upsert. */\nexport type ConflictPlan = {\n action: 'UPDATE' | 'NOTHING';\n /** Columns to conflict on, or `undefined` on dialects that take no conflict target. */\n target: Column[] | undefined;\n /** `column -> value to write`, in Drizzle's `set` shape. Empty when the action is NOTHING. */\n set: Record<string, SQL>;\n setWhere: SQL | undefined;\n};\n\n/**\n * Turns the request's `onConflict` argument and the rows it is inserting into the clause a\n * dialect should attach.\n *\n * `excludedRef` names the row that failed to insert in the dialect's own terms\n * (`excluded.col` on PostgreSQL and SQLite, `values(col)` on MySQL), which is what makes a\n * batch upsert update each row with its own values instead of the last row's.\n *\n * An UPDATE with nothing left to write degrades to NOTHING: `DO UPDATE SET` with an empty\n * body is not valid SQL, and doing nothing is what the request asked for anyway.\n */\nexport const resolveConflictPlan = (params: {\n table: Table;\n values: Record<string, any>[];\n onConflict: OnConflictArg | undefined;\n pkNames: readonly string[];\n uniqueSets: string[][];\n excludedRef: (columnName: string) => SQL;\n withTarget: boolean;\n buildWhere?: (where: any) => SQL | undefined;\n}): ConflictPlan => {\n const { table, values, onConflict, pkNames, uniqueSets, excludedRef, withTarget, buildWhere } = params;\n const columns = getColumns(table) as Record<string, Column>;\n\n let target: Column[] | undefined;\n if (withTarget) {\n const targetNames = onConflict?.target?.length ? onConflict.target : [...pkNames];\n if (!targetNames.length) {\n throw new GraphQLError(\n 'Unable to upsert: no conflict target was given and this table has no primary key. Pass onConflict.target.',\n );\n }\n // A target that is not itself a unique constraint is a database error, and a confusing\n // one (\"there is no unique or exclusion constraint matching the ON CONFLICT\n // specification\"), so reject it here where we can say which sets are valid.\n const requested = [...targetNames].sort().join(',');\n if (!uniqueSets.some((set) => [...set].sort().join(',') === requested)) {\n throw new GraphQLError(\n `Unable to upsert: [${targetNames.join(', ')}] is not a unique constraint on this table. Valid conflict targets: ${uniqueSets\n .map((set) => `[${set.join(', ')}]`)\n .join(', ')}.`,\n );\n }\n target = targetNames.map((name) => columns[name]!);\n }\n\n if ((onConflict?.action ?? 'UPDATE') === 'NOTHING') {\n return { action: 'NOTHING', target, set: {}, setWhere: undefined };\n }\n\n // Only columns the request actually supplied have a value to copy over; anything else\n // would write the column's default (usually null) onto the row that already exists.\n const supplied = new Set(values.flatMap((row) => Object.keys(row)));\n const targetNames = new Set(withTarget ? (onConflict?.target?.length ? onConflict.target : pkNames) : []);\n\n let updateNames: string[];\n if (onConflict?.update?.length) {\n const unsupplied = onConflict.update.filter((name) => !supplied.has(name));\n if (unsupplied.length) {\n throw new GraphQLError(\n `Unable to upsert: onConflict.update lists ${unsupplied.join(', ')}, which the values do not supply.`,\n );\n }\n updateNames = onConflict.update;\n } else {\n updateNames = [...supplied].filter((name) => !targetNames.has(name));\n }\n\n if (!updateNames.length) {\n return { action: 'NOTHING', target, set: {}, setWhere: undefined };\n }\n\n const set = Object.fromEntries(updateNames.map((name) => [name, excludedRef(columns[name]!.name)]));\n const setWhere = onConflict?.where && buildWhere ? buildWhere(onConflict.where) : undefined;\n\n return { action: 'UPDATE', target, set, setWhere };\n};\n\n/** `excluded.<column>` — PostgreSQL and SQLite name the rejected row this way. */\nexport const excludedColumnRef = (columnName: string): SQL => sql`excluded.${sql.identifier(columnName)}`;\n\n/** `values(<column>)` — MySQL's equivalent inside ON DUPLICATE KEY UPDATE. */\nexport const mysqlValuesColumnRef = (columnName: string): SQL => sql`values(${sql.identifier(columnName)})`;\n\n/**\n * Keeps the first row of each distinct combination of the requested columns, following the\n * query's own ordering, then applies `limit`/`offset` to what survives — and returns the\n * surviving rows' primary key values in that order.\n *\n * The relational query builder has no `distinct` support, so this runs as its own\n * `row_number() over (partition by … order by …)` pass and the main query is narrowed to the\n * keys it returns. `orderExprs` is the full ordering (the request's `orderBy` plus the primary\n * key tiebreak); the caller applies the same ordering to the main query, so the two agree.\n */\nexport const selectDistinctKeys = async (params: {\n db: any;\n table: Table;\n tableName: string;\n distinct: string[];\n pkNames: readonly string[];\n where: SQL | undefined;\n orderBy: Record<string, any> | undefined;\n limit?: number;\n offset?: number;\n}): Promise<Record<string, any>[]> => {\n const { db, table, tableName, distinct, pkNames, where, orderBy, limit, offset } = params;\n const cols = getColumns(table);\n\n if (!pkNames.length) {\n throw new GraphQLError(`Table ${tableName} has no primary key, so 'distinct' cannot be applied to it.`);\n }\n\n const partitionCols = distinct.map((name) => cols[name]).filter(Boolean);\n if (!partitionCols.length) {\n throw new GraphQLError(`No known columns were given to 'distinct' on ${tableName}.`);\n }\n\n const orderEntries = orderBy ? orderByEntries(orderBy) : [];\n // Both orderings must agree, so build each from the same entries — once against the table\n // (inside the window) and once against the subquery's fields (for the outer row order).\n const windowOrder = [\n ...orderEntries.flatMap(([column, direction, nulls]) =>\n orderExpressions(cols[column]!, direction, nulls, cols[column]!),\n ),\n ...primaryKeyOrderExprs(table, pkNames),\n ];\n\n const rowNumber = sql`row_number() over (partition by ${sql.join(partitionCols, sql`, `)} order by ${sql.join(\n windowOrder,\n sql`, `,\n )})`.as(DISTINCT_RN);\n\n const sub = db\n .select({ ...cols, [DISTINCT_RN]: rowNumber })\n .from(table)\n .where(where)\n .as('__dgql_distinct');\n\n const outerOrder = [\n ...orderEntries.flatMap(([column, direction, nulls]) =>\n orderExpressions(sub[column], direction, nulls, cols[column]!),\n ),\n ...pkNames.filter((name) => sub[name]).map((name) => asc(sub[name])),\n ];\n\n let query = db\n .select(Object.fromEntries(pkNames.map((name) => [name, sub[name]])))\n .from(sub)\n .where(eq(sub[DISTINCT_RN], 1))\n .orderBy(...outerOrder);\n\n if (offset) {\n query = query.offset(offset);\n }\n if (limit != null) {\n query = query.limit(limit);\n }\n\n return await query;\n};\n\n/**\n * Condition matching exactly the rows identified by `keys` — an `IN (…)` for a single-column\n * primary key, an `OR` of per-row equality for a composite one. `table` may be the aliased\n * RQB proxy.\n */\nexport const primaryKeyRestriction = (table: Table, pkNames: readonly string[], keys: Record<string, any>[]): SQL => {\n const cols = getColumns(table);\n\n if (pkNames.length === 1) {\n const name = pkNames[0]!;\n return inArray(\n cols[name]!,\n keys.map((key) => key[name]),\n );\n }\n\n return or(...keys.map((key) => and(...pkNames.map((name) => eq(cols[name]!, key[name])))))!;\n};\n\n/**\n * Computes the RETURNING columns and relation selection for a mutation resolver: extracts\n * the selected scalar columns, determines whether any relations were selected, and only\n * then forces the primary key into the column set (so the post-mutation eager-load can\n * re-key rows). Returns everything the resolver needs to decide whether to eager-load.\n */\nexport const prepareMutationRelationColumns = (params: {\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n tables: Record<string, Table>;\n tableName: string;\n typeName: string;\n typeNameMapper: TypeNameMapper | undefined;\n table: Table;\n pkNames: readonly string[];\n parsedInfo: ResolveTree;\n}): {\n columns: Record<string, Column>;\n hasRelations: boolean;\n withParams: Record<string, Partial<ProcessedTableSelectArgs>> | undefined;\n} => {\n const { relationMap, tables, tableName, typeName, typeNameMapper, table, pkNames, parsedInfo } = params;\n const withParams = relationMap[tableName]\n ? extractRelationsParams(relationMap, tables, tableName, parsedInfo, typeName, typeNameMapper)\n : undefined;\n const hasRelations = !!(withParams && Object.keys(withParams).length);\n const baseColumns = extractSelectedColumnsFromTreeSQLFormat(parsedInfo.fieldsByTypeName[typeName]!, table, {\n tableName,\n relationMap,\n tables,\n });\n const columns = hasRelations ? withPrimaryKeyColumns(baseColumns, table, pkNames) : baseColumns;\n return { columns, hasRelations, withParams };\n};\n\n/** Wraps a thrown Error as a (message-only) GraphQLError; passes non-Errors through unchanged. */\n/**\n * Normalizes whatever a driver threw into a `GraphQLError`. Errors drizzle-graphql raised\n * itself pass straight through; anything else keeps the thrown value on `originalError`,\n * which is how {@link defaultErrorMapper} later tells the two apart.\n */\nexport const toGraphQLError = (e: unknown): unknown => {\n if (e instanceof GraphQLError) {\n return e;\n }\n return e instanceof Error ? new GraphQLError(e.message, { originalError: e }) : e;\n};\n\n/**\n * Default for `config.onError`: keeps drizzle-graphql's own errors, which are written for\n * the client, and replaces driver/database errors with a generic message. Their text names\n * tables, columns, constraints and offending values, none of which belongs in a response.\n * The original is preserved on `originalError` for server-side logging.\n */\nexport const defaultErrorMapper = (error: unknown): unknown => {\n if (error instanceof GraphQLError && !error.originalError) {\n return error;\n }\n\n return new GraphQLError('Internal server error', {\n originalError:\n error instanceof GraphQLError ? (error.originalError ?? error) : error instanceof Error ? error : null,\n extensions: { code: 'INTERNAL_SERVER_ERROR' },\n });\n};\n\n/**\n * Wraps every resolver reachable from a generated entity set so that its errors pass through\n * `mapError` first. Done here rather than at each `throw` site so that the hook also covers\n * relation field resolvers and anything that throws outside a builder's own try/catch.\n */\nexport const applyErrorMapper = (\n entities: {\n queries: Record<string, { resolve?: (...args: any[]) => any }>;\n mutations: Record<string, { resolve?: (...args: any[]) => any }>;\n types: Record<string, { getFields?: () => Record<string, { resolve?: (...args: any[]) => any }> }>;\n fieldResolvers?: Record<string, Record<string, (...args: any[]) => any>>;\n },\n mapError: (error: unknown) => unknown,\n): void => {\n const wrap =\n (resolve: (...args: any[]) => any) =>\n (...args: any[]) => {\n try {\n const result = resolve(...args);\n if (result && typeof result.then === 'function') {\n return result.then(undefined, (e: unknown) => {\n throw mapError(e);\n });\n }\n return result;\n } catch (e) {\n throw mapError(e);\n }\n };\n\n for (const field of [...Object.values(entities.queries), ...Object.values(entities.mutations)]) {\n if (field?.resolve) {\n field.resolve = wrap(field.resolve);\n }\n }\n\n // Relation and aggregate fields live on the object types, not in the query/mutation maps.\n for (const type of Object.values(entities.types)) {\n if (typeof type?.getFields !== 'function') {\n continue;\n }\n for (const field of Object.values(type.getFields())) {\n if (field?.resolve) {\n field.resolve = wrap(field.resolve);\n }\n }\n }\n\n // Standalone relation resolvers, handed out for use in hand-written schemas.\n for (const tableResolvers of Object.values(entities.fieldResolvers ?? {})) {\n for (const [relationName, resolve] of Object.entries(tableResolvers)) {\n tableResolvers[relationName] = wrap(resolve);\n }\n }\n};\n\n/**\n * Derives the generated query/mutation field names for a table from the naming config\n * (typeNameMapper + prefixes/suffixes). Shared by all three dialect builders.\n */\nexport const computeResolverFieldNames = (\n tableName: string,\n typeNameMapper: TypeNameMapper | undefined,\n prefixes: { insert: string; update: string; delete: string; upsert?: string },\n suffixes: { list: string; single: string },\n): {\n typeName: string;\n listFieldName: string;\n singleFieldName: string;\n aggregateFieldName: string;\n groupByFieldName: string;\n createArrayFieldName: string;\n createSingleFieldName: string;\n upsertArrayFieldName: string;\n upsertSingleFieldName: string;\n updateFieldName: string;\n updateManyFieldName: string;\n updateSingleFieldName: string;\n deleteFieldName: string;\n deleteSingleFieldName: string;\n} => {\n const mapped = typeNameMapper?.(tableName);\n const typeName = mapped ? capitalize(mapped.singular) : capitalize(tableName);\n const listFieldName = (mapped?.plural ?? uncapitalize(tableName)) + suffixes.list;\n const singleFieldName = mapped?.singular ?? uncapitalize(tableName) + suffixes.single;\n const aggregateFieldName = `${mapped?.plural ?? uncapitalize(tableName)}Aggregate`;\n const groupByFieldName = `${mapped?.plural ?? uncapitalize(tableName)}GroupBy`;\n const createArrayFieldName = `${prefixes.insert}${mapped ? capitalize(mapped.plural) : capitalize(tableName)}`;\n const createSingleFieldName = mapped\n ? `${prefixes.insert}${capitalize(mapped.singular)}`\n : `${prefixes.insert}${capitalize(tableName)}${suffixes.single}`;\n const upsertPrefix = prefixes.upsert ?? 'upsert';\n const upsertArrayFieldName = `${upsertPrefix}${mapped ? capitalize(mapped.plural) : capitalize(tableName)}`;\n const upsertSingleFieldName = mapped\n ? `${upsertPrefix}${capitalize(mapped.singular)}`\n : `${upsertPrefix}${capitalize(tableName)}${suffixes.single}`;\n const updateFieldName = `${prefixes.update}${mapped ? capitalize(mapped.singular) : capitalize(tableName)}`;\n // The batch variant is plural like the array insert/upsert, with an explicit `Many`\n // suffix so it never collides with the single-set update.\n const updateManyFieldName = `${prefixes.update}${mapped ? capitalize(mapped.plural) : capitalize(tableName)}Many`;\n const deleteFieldName = `${prefixes.delete}${mapped ? capitalize(mapped.singular) : capitalize(tableName)}`;\n // The plural update/delete mutations already use the singular noun when a mapper is\n // present, so — unlike create — the Single variants can't rely on singular vs plural to\n // stay distinct. They always carry a suffix, falling back to 'Single' when the configured\n // suffix is empty (a mapper config may set it to '' for the query side).\n const writeSingleSuffix = suffixes.single === '' ? 'Single' : suffixes.single;\n const updateSingleFieldName = `${updateFieldName}${writeSingleSuffix}`;\n const deleteSingleFieldName = `${deleteFieldName}${writeSingleSuffix}`;\n return {\n typeName,\n listFieldName,\n singleFieldName,\n aggregateFieldName,\n groupByFieldName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n updateManyFieldName,\n updateSingleFieldName,\n deleteFieldName,\n deleteSingleFieldName,\n };\n};\n\n/**\n * The per-entry input of `update<Table>Many`: `{ where, set }`, reusing the table's\n * update `set` input and filter input. Shared by all three dialect builders.\n */\nexport const generateUpdateManyInput = (params: {\n typeName: string;\n updatePrefix: string;\n updateInput: GraphQLInputObjectType;\n tableFilters: GraphQLInputObjectType;\n}): GraphQLInputObjectType => {\n const { typeName, updatePrefix, updateInput, tableFilters } = params;\n return new GraphQLInputObjectType({\n name: `${capitalize(updatePrefix)}${typeName}ManyInput`,\n description: `One entry of a batch update of ${typeName}: the rows \\`where\\` matches get this entry's \\`set\\` applied.`,\n fields: {\n where: {\n type: tableFilters,\n description: 'Rows this entry updates. An omitted filter updates every row.',\n },\n set: {\n type: new GraphQLNonNull(updateInput),\n },\n },\n });\n};\n\n/**\n * Extracts a `where` argument that a mutation refuses to run without: missing, or present\n * but matching every row (e.g. `where: {}` or filters that all collapse to nothing), both\n * throw instead of becoming an unbounded write. Used by the `Single` write variants always\n * and by the plural update/delete mutations when `features.requireWhere` is on.\n */\nexport const extractRequiredFilters = <TTable extends Table>(\n table: TTable,\n tableName: string,\n where: Filters<TTable> | undefined,\n fieldName: string,\n relationCtx?: RelationFilterContext,\n): SQL => {\n const filters = where ? extractFilters(table, tableName, where, relationCtx) : undefined;\n if (!filters) {\n throw new GraphQLError(`${fieldName} requires a 'where' argument with at least one filter!`);\n }\n return filters;\n};\n\n/**\n * Guard for the `Single` write variants: throws before anything is written when `where`\n * matches more than one row, so a multi-row update/delete never executes. Probed with a\n * `LIMIT 2` select rather than a count so the check stays cheap on large matches.\n */\nexport const assertSingleMatch = async (\n executor: any,\n table: Table,\n filters: SQL,\n fieldName: string,\n): Promise<void> => {\n const matched = await executor.select({ found: sql`1` }).from(table).where(filters).limit(2);\n if (matched.length > 1) {\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row — nothing was written!`);\n }\n};\n\n/** GraphQL argument map for a list/array select field. */\nexport const selectArrayArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n distinctEnum?: GraphQLEnumType,\n): Record<string, { type: any; description?: string }> => ({\n offset: { type: GraphQLInt },\n limit: { type: GraphQLInt },\n orderBy: { type: orderArgs },\n where: { type: filterArgs },\n after: {\n type: GraphQLString,\n description:\n \"Keyset pagination: only return rows strictly after this cursor (a row's `cursor` field from a previous page, under the same orderBy).\",\n },\n ...(distinctEnum ? { distinct: { type: new GraphQLList(new GraphQLNonNull(distinctEnum)) } } : {}),\n});\n\n/** GraphQL argument map for a single-row select field (no `limit`). */\nexport const selectSingleArgs = (\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n): Record<string, { type: any }> => ({\n offset: { type: GraphQLInt },\n orderBy: { type: orderArgs },\n where: { type: filterArgs },\n});\n\n/**\n * Runs the relational-query-builder select shared by every dialect's `generateSelect*`\n * resolver: selected columns + offset/limit + aliased orderBy/where callbacks + the eager\n * `with:` relation params, then remaps the result. `single` switches between\n * findFirst/findMany (and the single path omits `limit`). The PG fallback for tables\n * without RQB support stays in pg.ts; this covers the common RQB path for all three.\n */\nexport const runRelationalSelect = async (opts: {\n queryBase: any;\n tables: Record<string, Table>;\n tableName: string;\n table: Table;\n relationMap: Record<string, Record<string, TableNamedRelations>>;\n typeName: string;\n typeNameMapper: TypeNameMapper | undefined;\n parsedInfo: ResolveTree;\n offset?: number;\n limit?: number;\n orderBy?: any;\n where?: any;\n single: boolean;\n filterCtx?: RelationFilterBase;\n pkNames?: readonly string[];\n db?: any;\n distinct?: string[];\n after?: string;\n nullOrdering?: NullOrdering;\n}): Promise<any> => {\n const {\n queryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n offset,\n orderBy,\n where,\n single,\n filterCtx,\n pkNames,\n after,\n } = opts;\n const distinct = opts.distinct?.length ? opts.distinct : undefined;\n\n // ── keyset (cursor) pagination ──\n // Active when the request passes `after` or selects the `cursor` meta field. The cursor is\n // defined over a total order — the request's orderBy plus the primary-key tiebreak — so both\n // need the PK; a table without one gets an error for `after` and null cursors otherwise.\n const cursorSelected = !single && isCursorFieldSelected(parsedInfo.fieldsByTypeName[typeName], table);\n let cursorEntries: CursorOrderEntry[] | undefined;\n if (!single && (after != null || cursorSelected)) {\n if (after != null && distinct) {\n throw new GraphQLError(\"'after' cannot be combined with 'distinct'.\");\n }\n if (orderByHasRelationEntry(orderBy)) {\n if (after != null) {\n throw new GraphQLError(\n \"'after' cannot be combined with an orderBy that orders through a relation — a related row's value cannot be encoded into a cursor.\",\n );\n }\n // `cursor` was selected under a relation ordering — the field resolves to null and the\n // relation ordering itself still applies.\n } else if (!pkNames?.length) {\n if (after != null) {\n throw new GraphQLError(`Table ${tableName} has no primary key, so cursor pagination cannot be used on it.`);\n }\n // `cursor` was selected but no total order exists — the field resolves to null.\n } else {\n cursorEntries = cursorOrderingEntries(orderBy, pkNames);\n }\n }\n const cursorValues = after != null && cursorEntries ? decodeCursor(after, cursorEntries) : undefined;\n // Taking a slice of an unordered result lets the database return any rows it likes, so\n // `limit`/`offset` pages can overlap or skip rows between requests, and a single query\n // can return a different row each time. Default to the primary key whenever the query is\n // narrowed to a subset, mirroring the relation-level default in extractRelationsParamsInner.\n const needsDefaultOrder = single || offset != null || opts.limit != null;\n\n // `distinct` runs as its own pass — the relational query builder cannot express it — and\n // the main query is then narrowed to the primary keys it picked, with the same ordering\n // and without re-applying limit/offset.\n let distinctKeys: Record<string, any>[] | undefined;\n if (distinct) {\n distinctKeys = await selectDistinctKeys({\n db: opts.db,\n table,\n tableName,\n distinct,\n pkNames: pkNames ?? [],\n where: where ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName)) : undefined,\n orderBy,\n limit: single ? 1 : opts.limit,\n offset,\n });\n\n if (!distinctKeys.length) {\n return single ? undefined : [];\n }\n }\n\n const params: any = {\n columns: extractSelectedColumnsFromTree(parsedInfo.fieldsByTypeName[typeName]!, table, {\n tableName,\n relationMap,\n tables,\n }),\n offset: distinctKeys ? undefined : offset,\n // drizzle-orm v1 RQB calls orderBy/where with the aliased table proxy — use it\n // directly so column refs match the CTE alias.\n orderBy: distinctKeys\n ? (aliasedTable: Table) => [\n ...(orderBy ? extractOrderBy(aliasedTable, orderBy, relationFilterCtx(filterCtx, tableName)) : []),\n ...primaryKeyOrderExprs(aliasedTable, pkNames!),\n ]\n : cursorEntries\n ? // Cursor pagination needs a total order: the request's orderBy plus the PK tiebreak,\n // exactly the ordering the cursor encodes and the keyset predicate compares against.\n (aliasedTable: Table) => cursorOrderExprs(aliasedTable, cursorEntries!)\n : orderBy\n ? (aliasedTable: Table) => extractOrderBy(aliasedTable, orderBy, relationFilterCtx(filterCtx, tableName))\n : needsDefaultOrder && pkNames?.length\n ? (aliasedTable: Table) => primaryKeyOrderExprs(aliasedTable, pkNames)\n : undefined,\n where: distinctKeys\n ? { RAW: (aliasedTable: Table) => primaryKeyRestriction(aliasedTable, pkNames!, distinctKeys!) }\n : where || cursorValues\n ? {\n RAW: (aliasedTable: Table) =>\n and(\n where\n ? extractFilters(aliasedTable, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n cursorValues\n ? buildCursorCondition(\n aliasedTable,\n cursorEntries!,\n cursorValues,\n opts.nullOrdering ?? 'nulls-smallest',\n )\n : undefined,\n ),\n }\n : undefined,\n with: relationMap[tableName]\n ? extractRelationsParams(relationMap, tables, tableName, parsedInfo, typeName, typeNameMapper, filterCtx)\n : undefined,\n };\n\n if (single) {\n const result = await queryBase.findFirst(params);\n return result ? remapToGraphQLSingleOutput(result, tableName, table, relationMap) : undefined;\n }\n\n // Computing each row's cursor needs the whole ordering tuple, which the client has no\n // reason to have selected — force those columns into the fetch (GraphQL only returns\n // the fields the query asked for, so extra properties never leak into the response).\n if (cursorEntries && cursorSelected) {\n for (const [column] of cursorEntries) {\n params.columns[column] = true;\n }\n }\n\n params.limit = distinctKeys ? undefined : opts.limit;\n const result = await queryBase.findMany(params);\n if (cursorEntries && cursorSelected) {\n // On the raw rows, before remapping rewrites dates/bigints into transport forms.\n attachRowCursors(result, cursorEntries);\n }\n return remapToGraphQLArrayOutput(result, tableName, table, relationMap);\n};\n\n/**\n * After a mutation, re-fetch the mutated rows through the relational query builder so the\n * selected relations are eagerly loaded in a single query, then merge those relations onto\n * the `.returning()` rows — making the per-field BatchLoader fallback unnecessary.\n *\n * `withParams` is the pre-computed relation selection (from extractRelationsParams); the\n * caller only invokes this when relations are actually selected, so it also gates whether\n * the PK was forced into RETURNING.\n *\n * Falls back to the original `.returning()` rows (relations then resolve via the\n * field-level BatchLoader) when the table has no RQB support, no primary key columns can be\n * determined, or the re-fetch fails. Supports single- and multi-column primary keys.\n */\nexport const eagerLoadMutationRelations = async (\n db: any,\n tableName: string,\n rows: any[],\n pkNames: readonly string[],\n withParams: Record<string, Partial<ProcessedTableSelectArgs>> | undefined,\n): Promise<any[]> => {\n if (!rows.length || !pkNames.length || !withParams || !Object.keys(withParams).length) {\n return rows;\n }\n\n const queryBase = db.query?.[tableName];\n if (!queryBase) {\n return rows;\n }\n\n // Only rows that carry every PK value can be re-keyed. Callers force the PK into\n // RETURNING, but if a value is still missing for some rows, eager-load just those that\n // are keyable and leave the rest untouched (their relations resolve lazily) rather than\n // bailing the whole batch.\n const keyableRows = rows.filter((row) => pkNames.every((n) => row[n] != null));\n if (!keyableRows.length) {\n return rows;\n }\n\n // Re-fetch ONLY the primary key + relations: the scalar columns are already present\n // on `rows` from RETURNING, so re-selecting them would transfer them a second time\n // (and would lose them on the fallback path). We merge the fetched relations back in.\n const pkColumns: Record<string, true> = {};\n for (const pk of pkNames) {\n pkColumns[pk] = true;\n }\n const relationNames = Object.keys(withParams);\n\n // Normalize bigint PK values to strings: JSON.stringify throws on bigint, and a\n // bigint and its string form never collide within a single column's values.\n const keyOf = (row: any) =>\n JSON.stringify(pkNames.map((n) => (typeof row[n] === 'bigint' ? row[n].toString() : row[n])));\n\n let whereRaw: (aliased: any) => SQL | undefined;\n if (pkNames.length === 1) {\n const pkName = pkNames[0]!;\n const ids = keyableRows.map((r) => r[pkName]);\n // drizzle-orm v1 RQB calls the where callback with the aliased table proxy;\n // reference the PK through it so the column ref matches the CTE alias.\n whereRaw = (aliased: any) => inArray(aliased[pkName], ids);\n } else {\n // Composite PK: use a row-value IN — `(a, b) IN ((..), (..))` — so the database can\n // plan it as a set membership test, instead of an OR of N per-row AND-tuples that\n // blows up for large bulk mutations.\n whereRaw = (aliased: any) => {\n const lhs = sql.join(\n pkNames.map((n) => sql`${aliased[n]}`),\n sql`, `,\n );\n const tuples = sql.join(\n keyableRows.map(\n (row) =>\n sql`(${sql.join(\n pkNames.map((n) => sql`${row[n]}`),\n sql`, `,\n )})`,\n ),\n sql`, `,\n );\n return sql`(${lhs}) in (${tuples})`;\n };\n }\n\n let enriched: any[];\n try {\n enriched = await queryBase.findMany({\n columns: pkColumns,\n where: { RAW: whereRaw },\n with: withParams,\n });\n } catch (err) {\n // The write has already committed; a re-fetch failure (e.g. an RQB-incompatible\n // column or relation) must not turn a successful mutation into an error. Fall back\n // to the raw rows — relations then resolve lazily via the batch loader — but surface\n // the cause so a genuine misconfiguration isn't silently hidden.\n console.warn(\n `[drizzle-graphql] eager-loading relations for a \"${tableName}\" mutation failed; ` +\n 'falling back to lazy resolution.',\n err,\n );\n return rows;\n }\n\n // Merge the fetched relations onto the RETURNING rows in place, preserving order. A row\n // the re-fetch didn't return (e.g. deleted concurrently) keeps its scalar columns and\n // its relations resolve lazily, so the result never reports fewer rows than were mutated.\n const byKey = new Map(enriched.map((e) => [keyOf(e), e]));\n for (const row of rows) {\n const match = byKey.get(keyOf(row));\n if (!match) {\n continue;\n }\n for (const rel of relationNames) {\n row[rel] = match[rel];\n }\n }\n return rows;\n};\n","// @ts-nocheck\nconst DRIZZLE_LOADERS_KEY = Symbol('drizzle-graphql-loaders');\n\ntype BatchFn<K, V> = (keys: readonly K[]) => Promise<readonly V[]>;\n\nclass BatchLoader<K, V> {\n private batch: Array<{ key: K; resolve: (v: V) => void; reject: (e: unknown) => void }> = [];\n private scheduled = false;\n\n constructor(private readonly batchFn: BatchFn<K, V>) {}\n\n load(key: K): Promise<V> {\n return new Promise<V>((resolve, reject) => {\n this.batch.push({ key, resolve, reject });\n if (!this.scheduled) {\n this.scheduled = true;\n Promise.resolve().then(() => this.dispatch());\n }\n });\n }\n\n private async dispatch(): Promise<void> {\n const current = this.batch.splice(0);\n this.scheduled = false;\n try {\n const results = await this.batchFn(current.map(({ key }) => key));\n for (let i = 0; i < current.length; i++) {\n current[i]!.resolve(results[i] as V);\n }\n } catch (err) {\n for (const { reject } of current) {\n reject(err);\n }\n }\n }\n}\n\n/**\n * Returns a BatchLoader keyed by `key` on the GraphQL context object.\n * Loaders are stored under a Symbol so they never collide with consumer properties.\n * If context is absent or not an object, a fresh (unbatched) loader is returned.\n */\nexport const getOrCreateLoader = <K, V>(context: any, key: string, batchFn: BatchFn<K, V>): BatchLoader<K, V> => {\n if (!context || typeof context !== 'object') {\n return new BatchLoader<K, V>(batchFn);\n }\n if (!context[DRIZZLE_LOADERS_KEY]) {\n context[DRIZZLE_LOADERS_KEY] = new Map<string, BatchLoader<any, any>>();\n }\n const loaders = context[DRIZZLE_LOADERS_KEY] as Map<string, BatchLoader<any, any>>;\n if (!loaders.has(key)) {\n loaders.set(key, new BatchLoader<K, V>(batchFn));\n }\n return loaders.get(key) as BatchLoader<K, V>;\n};\n","import pluralize from 'pluralize';\n\nexport const uncapitalize = <T extends string>(input: T) =>\n (input?.length\n ? `${input[0]!.toLocaleLowerCase()}${input.length > 1 ? input.slice(1, input.length) : ''}`\n : input) as Uncapitalize<T>;\n\nexport const capitalize = <T extends string>(input: T) =>\n (input?.length\n ? `${input[0]!.toLocaleUpperCase()}${input.length > 1 ? input.slice(1, input.length) : ''}`\n : input) as Capitalize<T>;\n\nexport const singularize = <T extends string>(input: T) => pluralize.singular(input);\n\nexport const cleanTableName = <T extends string>(input: T) => singularize(uncapitalize(input));\n\nexport const tableNameToModel = <T extends string>(input: T) => singularize(capitalize(input));\n\n// (input.length\n// ? `${input[-]!.toLocaleUpperCase()}${input.length > 1 ? input.slice(1, input.length) : \"\"}`\n// : input) as Capitalize<T>;\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { type Column, getTableColumns, is, One, type Table } from 'drizzle-orm';\nimport { GraphQLError } from 'graphql';\nimport type { TableNamedRelations } from '../builders/index.ts';\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 // 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 // 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 { 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","import type { Column } from 'drizzle-orm';\nimport { extractExtendedColumnType, 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 GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n type 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 { ConvertedColumn } from './types.ts';\n\nconst allowedNameChars = /^[a-zA-Z0-9_]+$/;\n\nconst enumMap = new WeakMap<object, GraphQLEnumType>();\nconst generateEnumCached = (column: Column, columnName: string, tableName: string): GraphQLEnumType => {\n if (enumMap.has(column)) {\n return enumMap.get(column)!;\n }\n\n const gqlEnum = new GraphQLEnumType({\n name: `${capitalize(tableName)}${capitalize(columnName)}Enum`,\n values: Object.fromEntries(\n column.enumValues!.map((e, index) => [\n allowedNameChars.test(e) ? e : `Option${index}`,\n {\n value: e,\n description: `Value: ${e}`,\n },\n ]),\n ),\n });\n\n enumMap.set(column, gqlEnum);\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 innerDesc = inner.description ?? (inner.type as GraphQLScalarType).name;\n\n let type: ConvertedColumn<boolean>['type'] = inner.type;\n let description = innerDesc;\n for (let i = 0; i < dimensions; i++) {\n type = new GraphQLList(new GraphQLNonNull(type as GraphQLScalarType));\n description = `Array<${description}>`;\n }\n\n return { type, description };\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, description: 'Boolean' };\n case 'object':\n if (column instanceof PgTimestamp || column instanceof PgDate) {\n return { type: GraphQLDateTime, description: 'DateTime' };\n }\n return column.columnType === 'PgGeometryObject'\n ? {\n type: isInput ? geoXyInputType : geoXyType,\n description: 'Geometry points XY',\n }\n : column.columnType === 'PgBytea'\n ? {\n type: new GraphQLList(new GraphQLNonNull(GraphQLInt)),\n description: 'Buffer',\n }\n : { type: GraphQLJSON, description: '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, description: 'Decimal' };\n }\n\n if (column instanceof PgTimestamp || column instanceof PgTimestampString) {\n return { type: GraphQLDateTime, description: 'DateTime' };\n }\n if (column instanceof PgUUID) {\n return { type: GraphQLUUID, description: '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, description: 'Date' } : { type: GraphQLDate, description: 'Date' };\n }\n\n return { type: GraphQLString, description: 'String' };\n case 'bigint':\n return { type: GraphQLBigIntString, description: '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, description: 'Integer' }\n : { type: GraphQLFloat, description: 'Float' };\n }\n case 'array': {\n if (column.columnType === 'PgVector') {\n return {\n type: new GraphQLList(new GraphQLNonNull(GraphQLFloat)),\n description: 'Array<Float>',\n };\n }\n\n if (column.columnType === 'PgGeometry') {\n return {\n type: new GraphQLList(new GraphQLNonNull(GraphQLFloat)),\n description: '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 description: `Array<${innerType.description}>`,\n };\n }\n default:\n throw new Error(`Drizzle-GraphQL Error: Type ${column.dataType} is not implemented!`);\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 typeDesc = columnToGraphQLCore(column, columnName, tableName, isInput);\n const noDesc = ['string', 'boolean', 'number'];\n const { type: baseType } = extractExtendedColumnType(column);\n if (noDesc.find((e) => e === baseType)) {\n delete typeDesc.description;\n }\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 description: typeDesc.description,\n } as ConvertedColumn<TIsInput>;\n }\n\n return typeDesc as ConvertedColumn<TIsInput>;\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 GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\n\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n aggregateFieldComplexity,\n assertSingleMatch,\n attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createRelationResolverFactory,\n extractFilters,\n extractRequiredFilters,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n generateUpdateManyInput,\n getPrimaryKeyPropNamesFromConfig,\n listFieldComplexity,\n mysqlValuesColumnRef,\n type OnConflictArg,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n relationFilterCtx,\n resolveConflictPlan,\n resolveExecutor,\n resolveQueryExecutor,\n runRelationalSelect,\n selectArrayArgs,\n selectSingleArgs,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n} from '../builders/common.ts';\nimport { remapFromGraphQLArrayInput, remapFromGraphQLSingleInput } from '../data-mappers/index.ts';\nimport {\n createRelationAggregateFactory,\n generateAggregate,\n generateAggregateTypes,\n generateGroupBy,\n generateGroupByEnum,\n generateGroupByType,\n generateHavingInput,\n} from './aggregates.ts';\nimport type {\n CreatedResolver,\n Filters,\n SchemaGeneratorOptions,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst generateSelectArray = (\n db: MySqlDatabase<any, any, any>,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n distinctEnabled: boolean = true,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const table = tables[tableName]!;\n const pkNames = mysqlPrimaryKeyPropNames(table as MySqlTable);\n const queryArgs = selectArrayArgs(\n orderArgs,\n filterArgs,\n distinctEnabled ? generateDistinctEnum(table, typeName) : undefined,\n );\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: false,\n filterCtx,\n pkNames,\n db: executor,\n // MySQL sorts NULLs as the smallest values (first in ASC).\n nullOrdering: 'nulls-smallest',\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateSelectSingle = (\n db: MySqlDatabase<any, any, any>,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const queryArgs = selectSingleArgs(orderArgs, filterArgs);\n\n const table = tables[tableName]!;\n const pkNames = mysqlPrimaryKeyPropNames(table as MySqlTable);\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n pkNames,\n db: executor,\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateInsertArray = (\n db: MySqlDatabase<any, any, any, any>,\n _tableName: string,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n): 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 const input = remapFromGraphQLArrayInput(args.values, table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n\n await resolveExecutor(db, context).insert(table).values(input);\n\n return { isSuccess: true };\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): 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 const input = remapFromGraphQLSingleInput(args.values, table);\n\n await resolveExecutor(db, context).insert(table).values(input);\n\n return { isSuccess: true };\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateUpsert = (\n db: MySqlDatabase<any, any, any, any>,\n table: MySqlTable,\n baseType: GraphQLInputObjectType,\n onConflictType: GraphQLInputObjectType,\n fieldName: string,\n single: boolean,\n): 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 const input = single\n ? [remapFromGraphQLSingleInput(args.values as Record<string, any>, table)]\n : remapFromGraphQLArrayInput(args.values as Record<string, any>[], table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n\n // MySQL's ON DUPLICATE KEY UPDATE fires on whichever unique key was violated, so\n // there is no target to resolve and no predicate to attach.\n const plan = resolveConflictPlan({\n table,\n values: input,\n onConflict: args.onConflict,\n pkNames,\n uniqueSets: [],\n excludedRef: mysqlValuesColumnRef,\n withTarget: false,\n });\n\n const executor = resolveExecutor(db, context);\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 } 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): 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 const { where, set } = args;\n\n const input = remapFromGraphQLSingleInput(set, table);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n const executor = resolveExecutor(db, context);\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 } 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): 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 const { updates } = args;\n if (!updates.length) {\n throw new GraphQLError('No updates were provided!');\n }\n\n // Remap and validate every entry before the transaction opens, so a malformed\n // entry rejects the request instead of rolling back mid-batch.\n const entries = updates.map(({ where, set }) => {\n const input = remapFromGraphQLSingleInput(set, table);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n filters: where\n ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n };\n });\n\n const executor = resolveExecutor(db, context);\n // On a caller-supplied transaction this opens a savepoint, so the batch stays\n // atomic without breaking the outer transaction.\n await executor.transaction(async (tx) => {\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 } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateDelete = (\n db: MySqlDatabase<any, any, any>,\n tableName: string,\n table: MySqlTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n single: boolean,\n requireWhere: boolean,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, _info) => {\n try {\n const { where } = args;\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n const executor = resolveExecutor(db, context);\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n await query;\n\n return { isSuccess: true };\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\n/** Primary-key property names for a MySQL table, including table-level composite keys. */\nconst mysqlPrimaryKeyPropNames = (table: MySqlTable): string[] =>\n getPrimaryKeyPropNamesFromConfig(table, getTableConfig);\n\nexport const generateSchemaData = <\n TDrizzleInstance extends MySqlDatabase<any, any, any, any>,\n TSchema extends Record<string, Table | unknown>,\n>(\n db: TDrizzleInstance,\n schema: TSchema,\n relations: TablesRelationalConfig,\n options: SchemaGeneratorOptions,\n): GeneratedEntities<TDrizzleInstance, TSchema> => {\n const { relationsDepthLimit, prefixes, suffixes, typeNameMapper, shouldEagerLoad, features, complexity } = options;\n const rawSchema = schema;\n const schemaEntries = Object.entries(rawSchema);\n\n const tableEntries = schemaEntries.filter(([_key, value]) => is(value, MySqlTable)) as [string, MySqlTable][];\n const tables = Object.fromEntries(tableEntries);\n\n if (!tableEntries.length) {\n throw new Error(\n \"Drizzle-GraphQL Error: No tables detected in Drizzle-ORM's database instance. Did you forget to pass schema to drizzle constructor?\",\n );\n }\n\n // Build namedRelations from the drizzle-orm v1 relations config.\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Record each relation target's (composite-aware) primary key for deterministic\n // paginated ordering. Must run before pruning / type generation (shared entry objects).\n attachTargetPrimaryKeys(namedRelations, tables, mysqlPrimaryKeyPropNames);\n // Pruned map for query resolvers' `with:`; type generation keeps the full map.\n const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);\n\n const filterCtx: RelationFilterBase = { tables, relationMap: namedRelations };\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(db, tables, filterCtx);\n\n // Fresh cache per generateSchemaData call — prevents type name collisions\n // when buildSchema() is called multiple times.\n const cacheCtx: TypeCacheCtx = {\n genericFilterCache: new Map(),\n objectTypeCache: new Map(),\n relationFieldContainers: new Map(),\n fullyBuiltTables: new Set(),\n relationTypeCache: new Map(),\n orderTypeCache: new WeakMap(),\n filterTypeCache: new WeakMap(),\n listRelationFilterCache: new Map(),\n aggregateTypeCache: new Map(),\n complexity,\n };\n\n // Left undefined when the feature is off — generateTableTypes then emits no\n // `${relation}Aggregate` fields at all.\n const relationAggregateFactory: RelationAggregateFactory | undefined = features.relationAggregates\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx)\n : undefined;\n\n const queries: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const mutations: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const gqlSchemaTypes = Object.fromEntries(\n Object.entries(tables).map(([tableName, _table]) => [\n tableName,\n generateTableTypes(\n tableName,\n tables,\n namedRelations,\n false,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n prefixes.insert,\n prefixes.update,\n resolverFactory,\n relationAggregateFactory,\n ),\n ]),\n );\n\n const mutationReturnType = new GraphQLObjectType({\n name: 'MutationReturn',\n fields: {\n isSuccess: {\n type: new GraphQLNonNull(GraphQLBoolean),\n },\n },\n });\n\n const inputs: Record<string, GraphQLInputObjectType> = {};\n const outputs: Record<string, GraphQLObjectType> = {};\n // Every MySQL mutation returns it, so it only belongs in the type map when at least one\n // mutation is generated.\n if (features.insert || features.upsert || features.update || features.delete) {\n outputs.MutationReturn = mutationReturnType;\n }\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n const { insertInput, updateInput, tableFilters, tableOrder } = tableTypes.inputs;\n const { selectSingleOutput, selectArrOutput } = tableTypes.outputs;\n\n // Compute field names using the mapper logic\n const {\n typeName,\n listFieldName,\n singleFieldName,\n aggregateFieldName,\n groupByFieldName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n updateManyFieldName,\n updateSingleFieldName,\n deleteFieldName,\n deleteSingleFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\n\n const selectArrGenerated = generateSelectArray(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n listFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n features.distinct,\n );\n const selectSingleGenerated = generateSelectSingle(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n singleFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n );\n const insertArrGenerated = features.insert\n ? generateInsertArray(db, tableName, schema[tableName] as MySqlTable, insertInput, createArrayFieldName)\n : undefined;\n const insertSingleGenerated = features.insert\n ? generateInsertSingle(db, tableName, schema[tableName] as MySqlTable, insertInput, createSingleFieldName)\n : undefined;\n // MySQL detects a conflict on any unique key, so unlike PostgreSQL and SQLite every\n // table can be upserted — there is no target to validate.\n const onConflictInput = features.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as MySqlTable,\n typeName,\n uniqueSets: [],\n tableFilters,\n withTarget: false,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(db, schema[tableName] as MySqlTable, insertInput, onConflictInput, upsertArrayFieldName, false)\n : undefined;\n const upsertSingleGenerated = onConflictInput\n ? generateUpsert(db, schema[tableName] as MySqlTable, insertInput, onConflictInput, upsertSingleFieldName, true)\n : undefined;\n const updateGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateFieldName,\n false,\n features.requireWhere,\n filterCtx,\n )\n : undefined;\n const updateSingleGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n true,\n features.requireWhere,\n filterCtx,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n features.update && features.updateMany\n ? generateUpdateManyInput({ typeName, updatePrefix: prefixes.update, updateInput, tableFilters })\n : undefined;\n const updateManyGenerated = updateManyInput\n ? generateUpdateMany(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n updateManyInput,\n updateManyFieldName,\n filterCtx,\n )\n : undefined;\n const deleteGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteFieldName,\n false,\n features.requireWhere,\n filterCtx,\n )\n : undefined;\n const deleteSingleGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n tableFilters,\n deleteSingleFieldName,\n true,\n features.requireWhere,\n filterCtx,\n )\n : undefined;\n const aggregateType = features.aggregates\n ? generateAggregateTypes(schema[tableName] as MySqlTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = features.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n features.aggregates && features.groupBy\n ? generateGroupByType(schema[tableName] as MySqlTable, tableName, typeName, cacheCtx)\n : undefined;\n const groupByEnum = groupByType\n ? generateGroupByEnum(schema[tableName] as MySqlTable, tableName, typeName)\n : undefined;\n const havingInput = groupByEnum\n ? generateHavingInput(schema[tableName] as MySqlTable, tableName, typeName)\n : undefined;\n const groupByGenerated =\n groupByType && groupByEnum && havingInput\n ? generateGroupBy(\n db,\n tableName,\n schema[tableName] as MySqlTable,\n typeName,\n groupByFieldName,\n tableFilters,\n groupByEnum,\n havingInput,\n filterCtx,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n ...(complexity ? { extensions: { complexity: listFieldComplexity(complexity) } } : {}),\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n for (const generated of [\n insertArrGenerated,\n insertSingleGenerated,\n upsertArrGenerated,\n upsertSingleGenerated,\n updateGenerated,\n updateManyGenerated,\n updateSingleGenerated,\n deleteGenerated,\n deleteSingleGenerated,\n ]) {\n if (generated) {\n mutations[generated.name] = {\n type: mutationReturnType,\n args: generated.args,\n resolve: generated.resolver,\n };\n }\n }\n // The insert/update inputs are still built (they type the mutations that survive) but\n // only reach the schema's type map when a mutation actually references them.\n const activeInputs = [\n // The insert input types the upsert mutations too, so either feature keeps it.\n ...(features.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(features.update ? [updateInput] : []),\n ...(updateManyInput ? [updateManyInput] : []),\n tableFilters,\n tableOrder,\n ];\n activeInputs.forEach((e) => {\n inputs[e.name] = e;\n });\n outputs[selectSingleOutput.name] = selectSingleOutput;\n if (aggregateType) {\n outputs[aggregateType.name] = aggregateType;\n }\n if (groupByType && havingInput) {\n outputs[groupByType.name] = groupByType;\n inputs[havingInput.name] = havingInput;\n }\n }\n\n const fieldResolvers: Record<string, Record<string, any>> = {};\n for (const [tableName, tableRelations] of Object.entries(namedRelations)) {\n const relResolvers: Record<string, any> = {};\n for (const [relName, relEntry] of Object.entries(tableRelations)) {\n const isOne = is((relEntry as any).relation ?? relEntry, One);\n const resolver = resolverFactory({ tableName, relationName: relName, relEntry, isOne });\n if (resolver) {\n relResolvers[relName] = resolver;\n }\n }\n if (Object.keys(relResolvers).length > 0) {\n fieldResolvers[tableName] = relResolvers;\n }\n }\n\n return { queries, mutations, inputs, types: outputs, fieldResolvers } as any;\n};\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport {\n and,\n avg,\n type Column,\n count,\n countDistinct,\n eq,\n extractExtendedColumnType,\n getColumns,\n gt,\n gte,\n inArray,\n lt,\n lte,\n max,\n min,\n ne,\n sum,\n type Table,\n} from 'drizzle-orm';\nimport {\n type GraphQLEnumType,\n GraphQLError,\n GraphQLFloat,\n GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\nimport { getOrCreateLoader } from '../batch-loader/index.ts';\nimport { capitalize } from '../case-ops/index.ts';\nimport { remapToGraphQLCore } from '../data-mappers/index.ts';\nimport { drizzleColumnToGraphQLType } from '../type-converter/index.ts';\nimport type { ConvertedColumn } from '../type-converter/types.ts';\nimport {\n extractFilters,\n extractRelationJoinColumns,\n generateColumnEnum,\n type RelationAggregateFactory,\n type RelationFilterBase,\n relationFilterCtx,\n resolveExecutor,\n resolveTypeName,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n} from './common.ts';\nimport type { CreatedResolver, Filters } from './types.ts';\n\n/** Operations that aggregate over a set of column values. `count` is handled separately (whole rows). */\nconst AGGREGATE_OPS = ['avg', 'sum', 'min', 'max', 'countNonNull', 'countDistinct'] as const;\ntype AggregateOp = (typeof AGGREGATE_OPS)[number];\n\n/** Ops whose result is a row count: never null, and returned as `Int!` rather than the column's type. */\nconst COUNT_OPS = new Set<AggregateOp>(['countNonNull', 'countDistinct']);\n\nconst OP_FNS: Record<AggregateOp, (col: Column) => any> = {\n avg,\n sum,\n min,\n max,\n countNonNull: count,\n countDistinct,\n};\n\n/** Separator for flat select aliases (`avg__price`) — reassembled into nested output by the resolver. */\nconst SEP = '__';\n\ninterface AggregateColumnSets {\n /** Columns avg/sum apply to: plain Int/Float scalars. */\n numeric: Record<string, Column>;\n /** Columns min/max apply to: anything with a total ordering the DB supports (numbers, strings, dates, enums). */\n orderable: Record<string, { column: Column; converted: ConvertedColumn }>;\n /** Every column — `count(col)` is valid whatever the type. */\n all: Record<string, Column>;\n}\n\n/**\n * Classifies a table's columns for aggregation. avg/sum only make sense on numeric scalars;\n * min/max work on any orderable scalar (numbers, strings, bigints, dates, enums). Booleans,\n * arrays (including array-typed number columns), JSON, buffers, and object-shaped columns\n * (e.g. geometry) are excluded entirely.\n */\nconst classifyAggregateColumns = (table: Table, tableName: string): AggregateColumnSets => {\n const numeric: AggregateColumnSets['numeric'] = {};\n const orderable: AggregateColumnSets['orderable'] = {};\n const all: AggregateColumnSets['all'] = {};\n\n for (const [columnName, column] of Object.entries(getColumns(table))) {\n all[columnName] = column;\n const converted = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, false);\n const gqlType = converted.type;\n\n // Anything that isn't a plain scalar in the generated schema (arrays, geometry objects)\n // has no meaningful min/max. This also catches array-typed number columns, which keep\n // their scalar drizzle dataType but convert to a GraphQL list.\n if (gqlType instanceof GraphQLList || gqlType instanceof GraphQLObjectType) {\n continue;\n }\n\n // Classify on the drizzle data type rather than the GraphQL one: date columns convert to\n // different GraphQL scalars per dialect, but are orderable everywhere.\n const { type: dataType, constraint } = extractExtendedColumnType(column);\n if (dataType === 'boolean' || dataType === 'array' || dataType === 'custom') {\n continue;\n }\n if (dataType === 'object' && constraint !== 'date') {\n continue;\n }\n\n orderable[columnName] = { column, converted };\n if (dataType === 'number') {\n numeric[columnName] = column;\n }\n }\n\n return { numeric, orderable, all };\n};\n\n/**\n * Builds the `${typeName}Aggregate` output type for a table:\n * - `count: Int!` — number of matching rows\n * - `avg` / `sum` — per numeric column, always nullable Float (SQL returns NULL on empty sets,\n * and avg/sum of integers overflow Int / produce decimals)\n * - `min` / `max` — per orderable column, the column's own (nullable) scalar type\n * - `countNonNull` — per column, `Int!`: how many matching rows have a non-null value there\n * - `countDistinct` — per orderable column, `Int!`: how many distinct non-null values there are\n * Each wrapper is omitted when no column qualifies for it.\n */\nexport const generateAggregateTypes = (\n table: Table,\n tableName: string,\n typeName: string,\n cacheCtx?: TypeCacheCtx,\n): GraphQLObjectType => {\n const cached = cacheCtx?.aggregateTypeCache.get(tableName);\n if (cached) {\n return cached;\n }\n\n const { numeric, orderable, all } = classifyAggregateColumns(table, tableName);\n\n const fields: Record<string, { type: any }> = {\n count: { type: new GraphQLNonNull(GraphQLInt) },\n };\n\n if (Object.keys(numeric).length) {\n for (const op of ['avg', 'sum'] as const) {\n fields[op] = {\n type: new GraphQLObjectType({\n name: `${typeName}${capitalize(op)}Aggregate`,\n fields: Object.fromEntries(Object.keys(numeric).map((columnName) => [columnName, { type: GraphQLFloat }])),\n }),\n };\n }\n }\n\n if (Object.keys(orderable).length) {\n for (const op of ['min', 'max'] as const) {\n fields[op] = {\n type: new GraphQLObjectType({\n name: `${typeName}${capitalize(op)}Aggregate`,\n fields: Object.fromEntries(\n Object.entries(orderable).map(([columnName, { converted }]) => [\n columnName,\n { type: converted.type, description: converted.description },\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.description === 'DateTime')\n .map(([columnName]) => columnName),\n ),\n };\n};\n\n/**\n * Reads the requested count/avg/sum/min/max selections off the resolve tree and turns them\n * into one drizzle select expression per (op, column) pair. An empty `selection` means the\n * client asked for nothing runnable (`__typename` only, or empty sub-selections).\n */\nconst parseAggregateRequest = (\n info: any,\n target: AggregateTarget,\n rootTypeName = `${target.typeName}Aggregate`,\n): AggregateRequest => {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const selectionTree = parsedInfo.fieldsByTypeName[rootTypeName] ?? {};\n\n const request: AggregateRequest = {\n count: false,\n ops: { avg: [], sum: [], min: [], max: [], countNonNull: [], countDistinct: [] },\n selection: {},\n };\n\n // Keys are aliases; `field.name` is the real field. Duplicate selections of the same\n // field under different aliases collapse into one SQL expression — graphql-js resolves\n // every alias from the same result property.\n for (const field of Object.values(selectionTree) as ResolveTree[]) {\n if (field.name === 'count') {\n request.count = true;\n request.selection.count = count();\n continue;\n }\n\n if (!AGGREGATE_OPS.includes(field.name as AggregateOp)) {\n continue;\n }\n const op = field.name as AggregateOp;\n const subTree = field.fieldsByTypeName[`${target.typeName}${capitalize(op)}Aggregate`];\n if (!subTree) {\n continue;\n }\n\n for (const subField of Object.values(subTree) as ResolveTree[]) {\n const columnName = subField.name;\n const column = target.columns[columnName];\n if (!column || request.ops[op].includes(columnName)) {\n continue;\n }\n request.ops[op].push(columnName);\n request.selection[`${op}${SEP}${columnName}`] = OP_FNS[op](column);\n }\n }\n\n return request;\n};\n\n/** Reassembles a flat aggregate row (`avg__price`) into the nested GraphQL shape. */\nconst assembleAggregateRow = (row: Record<string, any>, request: AggregateRequest, target: AggregateTarget) => {\n const result: Record<string, any> = {};\n\n if (request.count) {\n // drizzle's count() maps to number already; guard for drivers returning strings.\n result.count = row.count == null ? 0 : Number(row.count);\n }\n\n for (const op of AGGREGATE_OPS) {\n if (!request.ops[op].length) {\n continue;\n }\n const opResult: Record<string, any> = {};\n for (const columnName of request.ops[op]) {\n const value = row[`${op}${SEP}${columnName}`];\n if (COUNT_OPS.has(op)) {\n // A count is never null: an empty set counts to 0, and a missing group means no rows.\n opResult[columnName] = value == null ? 0 : Number(value);\n } else if (value == null) {\n opResult[columnName] = null;\n } else if (op === 'avg' || op === 'sum') {\n // Drivers return numeric/decimal aggregates as strings — coerce to Float.\n opResult[columnName] = Number(value);\n } else {\n // min/max keep the column's own type — drizzle already ran the column's decoder over\n // the value (`min`/`max` are `mapWith(column)`), so all that's left is coercing a\n // leftover raw date string (PG decodes timestamps in driver-level codecs, which raw\n // select expressions bypass) and remapping for GraphQL output.\n const column = target.columns[columnName];\n const decoded =\n typeof value === 'string' && target.dateTimeColumns.has(columnName) ? parseDriverDateTime(value) : value;\n opResult[columnName] = remapToGraphQLCore(columnName, decoded, target.tableName, column);\n }\n }\n result[op] = opResult;\n }\n\n return result;\n};\n\n/**\n * Creates the resolver for a table's aggregate query field. Reads the requested\n * count/avg/sum/min/max selections from the resolve tree, runs them all as a single\n * `SELECT` with one aggregate expression per requested (op, column) pair, and\n * reassembles the flat row into the nested GraphQL shape.\n *\n * Shared by all three dialects — it only relies on `db.select().from().where()`.\n */\nexport const generateAggregate = (\n db: any,\n tableName: string,\n table: Table,\n typeName: string,\n fieldName: string,\n filterArgs: GraphQLInputObjectType,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const target = aggregateTarget(table, tableName, typeName);\n\n const queryArgs = {\n where: { type: filterArgs },\n };\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, info) => {\n try {\n const request = parseAggregateRequest(info, target);\n if (!Object.keys(request.selection).length) {\n return {};\n }\n\n let query = resolveExecutor(db, context).select(request.selection).from(table);\n if (args.where) {\n query = query.where(extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName)));\n }\n const rows = await query;\n\n return assembleAggregateRow(rows[0] ?? {}, request, target);\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\n/** Alias the grouping key is selected under. Prefixed so it can't collide with `${op}__${column}`. */\nconst GROUP_KEY = '__dgql_group_key';\n\n/**\n * Builds the `${relationName}Aggregate` field that hangs off a parent type for each to-many\n * relation — `user { postsAggregate { count } }`.\n *\n * Resolution is batched the same way relation fields are: every parent row in the current tick\n * that asked for the same relation with the same arguments is served by one\n * `SELECT fk, <aggregates> ... WHERE fk IN (...) GROUP BY fk`, so a list of N parents costs one\n * extra query rather than N. Parents with no matching related rows get `count: 0` and `null`\n * for every other aggregate.\n */\nexport const createRelationAggregateFactory = (\n db: any,\n tables: Record<string, Table>,\n cacheCtx: TypeCacheCtx,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): RelationAggregateFactory => {\n return ({ tableName, relationName, relEntry }) => {\n const parentTable = tables[tableName];\n const targetTableName = relEntry.targetTableName;\n const targetTable = tables[targetTableName];\n\n if (!parentTable || !targetTable) {\n return undefined;\n }\n\n const joinCols = extractRelationJoinColumns(relEntry, parentTable, targetTable);\n if (!joinCols) {\n return undefined;\n }\n const { localColPropName, foreignCol } = joinCols;\n\n const targetTypeName = resolveTypeName(targetTableName, typeNameMapper);\n const type = generateAggregateTypes(targetTable, targetTableName, targetTypeName, cacheCtx);\n const target = aggregateTarget(targetTable, targetTableName, targetTypeName);\n\n const resolve = async (parent: any, args: { where?: Filters<Table> }, context: any, info: any) => {\n try {\n const request = parseAggregateRequest(info, target);\n if (!Object.keys(request.selection).length) {\n return {};\n }\n\n const localValue = parent[localColPropName];\n // No key to correlate on — the relation is empty by definition.\n if (localValue == null) {\n return assembleAggregateRow({}, request, target);\n }\n\n const whereArg = args?.where;\n // Siblings only share a batch when they'd run the same query: same filters, same aggregates.\n const argsKey = JSON.stringify({\n where: whereArg ?? null,\n selection: Object.keys(request.selection).sort(),\n });\n const loaderKey = `${tableName}::${relationName}::aggregate::${argsKey}`;\n\n const loader = getOrCreateLoader(context, loaderKey, async (parentIds: readonly any[]) => {\n // Loaders are cached per context, so the whole batch shares this request's executor.\n const executor = resolveExecutor(db, context);\n const uniqueIds = [...new Set(parentIds)];\n const whereCondition = and(\n inArray(foreignCol, uniqueIds),\n whereArg\n ? extractFilters(targetTable, targetTableName, whereArg, relationFilterCtx(filterCtx, targetTableName))\n : undefined,\n );\n\n const rows: any[] = await executor\n .select({ [GROUP_KEY]: foreignCol, ...request.selection })\n .from(targetTable)\n .where(whereCondition)\n .groupBy(foreignCol);\n\n const byKey = new Map(rows.map((row) => [row[GROUP_KEY], row]));\n\n // A parent with no matching rows produces no group — hand back an empty row so it\n // assembles to count 0 / null aggregates rather than dropping the field.\n return parentIds.map((id) => byKey.get(id) ?? {});\n });\n\n return assembleAggregateRow(await loader.load(localValue), request, target);\n } catch (e) {\n throw toGraphQLError(e);\n }\n };\n\n return { type, resolve };\n };\n};\n\n// ── group by ──────────────────────────────────────────────────────────────────\n\n/** Alias prefix for grouped columns, kept clear of the `${op}__${column}` aggregate aliases. */\nconst GROUP_COL = `group${SEP}`;\n\n/** Comparison operators a `having` clause can apply to an aggregated value. */\nconst HAVING_OPS = { eq, ne, gt, gte, lt, lte } as const;\n\n/**\n * Columns a query can group on. Grouping needs an equality operator, which is the same\n * requirement min/max has, plus booleans — orderable excludes them because a min/max over\n * true/false says nothing, but `GROUP BY isConfirmed` is perfectly ordinary.\n */\nconst groupableColumns = (\n table: Table,\n tableName: string,\n): Record<string, { column: Column; converted: ConvertedColumn }> => {\n const { orderable } = classifyAggregateColumns(table, tableName);\n const groupable: Record<string, { column: Column; converted: ConvertedColumn }> = { ...orderable };\n\n for (const [columnName, column] of Object.entries(getColumns(table))) {\n if (groupable[columnName]) {\n continue;\n }\n const { type: dataType } = extractExtendedColumnType(column);\n if (dataType !== 'boolean') {\n continue;\n }\n groupable[columnName] = {\n column,\n converted: drizzleColumnToGraphQLType(column, columnName, tableName, true, false, false),\n };\n }\n\n return groupable;\n};\n\n/** The `${typeName}GroupByColumn` enum listing what a group-by query can group on. */\nexport const generateGroupByEnum = (table: Table, tableName: string, typeName: string): GraphQLEnumType | undefined => {\n const groupable = groupableColumns(table, tableName);\n\n return generateColumnEnum(\n table,\n `${typeName}GroupByColumn`,\n `Columns of ${typeName} that a query can group by`,\n (_column, columnName) => Boolean(groupable[columnName]),\n );\n};\n\n/** Shared by every `having` clause, so it is created once rather than per table. */\nexport const aggregateNumberFilter = new GraphQLInputObjectType({\n name: 'AggregateNumberFilter',\n description: 'Compares an aggregated value. Several operators in one filter are ANDed together.',\n fields: Object.fromEntries(Object.keys(HAVING_OPS).map((op) => [op, { type: GraphQLFloat }])),\n});\n\n/**\n * The `${typeName}Having` input: one entry per aggregate the group-by query can filter on.\n * Several entries are ANDed together, as are several operators within one entry.\n *\n * `min`/`max` are limited to numeric columns here even though the output type computes them\n * for every orderable column — the comparison is numeric, so a min over a text column has\n * nothing to compare against.\n */\nexport const generateHavingInput = (table: Table, tableName: string, typeName: string): GraphQLInputObjectType => {\n const { numeric, orderable, all } = classifyAggregateColumns(table, tableName);\n\n const fields: Record<string, { type: any; description?: string }> = {\n count: { type: aggregateNumberFilter, description: 'Filters groups by how many rows they contain' },\n };\n\n const opColumns: Record<string, Record<string, unknown>> = {\n avg: numeric,\n sum: numeric,\n min: numeric,\n max: numeric,\n countNonNull: all,\n countDistinct: orderable,\n };\n\n for (const [op, columns] of Object.entries(opColumns)) {\n const columnNames = Object.keys(columns);\n if (!columnNames.length) {\n continue;\n }\n fields[op] = {\n type: new GraphQLInputObjectType({\n name: `${typeName}${capitalize(op)}Having`,\n fields: Object.fromEntries(columnNames.map((columnName) => [columnName, { type: aggregateNumberFilter }])),\n }),\n };\n }\n\n return new GraphQLInputObjectType({\n name: `${typeName}Having`,\n description: `Filters ${typeName} groups by their aggregated values`,\n fields,\n });\n};\n\n/**\n * The `${typeName}GroupBy` output type: the grouped columns under `group`, alongside the same\n * aggregate fields the `${typeName}Aggregate` type carries — the wrapper types are the very\n * same instances, so the schema holds one `${typeName}AvgAggregate` however it is reached.\n *\n * The keys are nested rather than spread across the top level so a column called `count`,\n * `avg` or `min` cannot collide with the aggregate it sits next to.\n */\nexport const generateGroupByType = (\n table: Table,\n tableName: string,\n typeName: string,\n cacheCtx?: TypeCacheCtx,\n): GraphQLObjectType | undefined => {\n const groupable = groupableColumns(table, tableName);\n if (!Object.keys(groupable).length) {\n return undefined;\n }\n\n const keysType = new GraphQLObjectType({\n name: `${typeName}GroupKeys`,\n description: `The grouped column values of one ${typeName} group. A column the query did not group by is null.`,\n fields: Object.fromEntries(\n Object.entries(groupable).map(([columnName, { converted }]) => [\n columnName,\n { type: converted.type, description: converted.description },\n ]),\n ),\n });\n\n const aggregateType = generateAggregateTypes(table, tableName, typeName, cacheCtx);\n const aggregateFields = Object.fromEntries(\n Object.values(aggregateType.getFields()).map((field) => [\n field.name,\n { type: field.type, description: field.description ?? undefined },\n ]),\n );\n\n return new GraphQLObjectType({\n name: `${typeName}GroupBy`,\n fields: { group: { type: new GraphQLNonNull(keysType) }, ...aggregateFields },\n });\n};\n\n/** Turns one `${typeName}Having` entry into SQL conditions over the matching aggregate expression. */\nconst havingComparisons = (expression: any, filter: Record<string, any>): any[] =>\n Object.entries(filter)\n .filter(([op, value]) => value != null && op in HAVING_OPS)\n .map(([op, value]) => HAVING_OPS[op as keyof typeof HAVING_OPS](expression, value));\n\nconst buildHavingCondition = (having: Record<string, any> | undefined, columns: Record<string, Column>) => {\n if (!having) {\n return undefined;\n }\n\n const conditions: any[] = [];\n\n for (const [key, value] of Object.entries(having)) {\n if (value == null) {\n continue;\n }\n if (key === 'count') {\n conditions.push(...havingComparisons(count(), value));\n continue;\n }\n if (!AGGREGATE_OPS.includes(key as AggregateOp)) {\n continue;\n }\n for (const [columnName, filter] of Object.entries(value as Record<string, any>)) {\n const column = columns[columnName];\n if (!column || filter == null) {\n continue;\n }\n conditions.push(...havingComparisons(OP_FNS[key as AggregateOp](column), filter));\n }\n }\n\n return conditions.length ? and(...conditions) : undefined;\n};\n\n/**\n * Creates the resolver for a table's `<plural>GroupBy` query: the same aggregates the\n * `<plural>Aggregate` query computes, but one row per distinct combination of the requested\n * columns, optionally filtered on the aggregated values with `having`.\n *\n * Shared by all three dialects — `SELECT <keys>, <aggregates> FROM t WHERE … GROUP BY <keys>\n * HAVING …` is the same everywhere.\n */\nexport const generateGroupBy = (\n db: any,\n tableName: string,\n table: Table,\n typeName: string,\n fieldName: string,\n filterArgs: GraphQLInputObjectType,\n groupByEnum: GraphQLEnumType,\n havingInput: GraphQLInputObjectType,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const target = aggregateTarget(table, tableName, typeName);\n const groupable = groupableColumns(table, tableName);\n const columns = getColumns(table);\n const rootTypeName = `${typeName}GroupBy`;\n\n const queryArgs = {\n groupBy: {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByEnum))),\n description: 'Columns to group by. One result row per distinct combination of their values.',\n },\n where: { type: filterArgs, description: 'Filters the rows before they are grouped.' },\n having: { type: havingInput, description: 'Filters the groups after they are aggregated.' },\n };\n\n return {\n name: fieldName,\n resolver: async (\n _source,\n args: { groupBy?: string[]; where?: Filters<Table>; having?: Record<string, any> },\n context,\n info,\n ) => {\n try {\n const requestedKeys = [...new Set(args.groupBy ?? [])];\n if (!requestedKeys.length) {\n throw new GraphQLError('At least one column to group by is required!');\n }\n\n const keyColumns = requestedKeys.map((columnName) => {\n const groupableColumn = groupable[columnName];\n if (!groupableColumn) {\n throw new GraphQLError(`Cannot group ${typeName} by ${columnName}!`);\n }\n return [columnName, groupableColumn.column] as const;\n });\n\n const request = parseAggregateRequest(info, target, rootTypeName);\n const selection = {\n ...Object.fromEntries(keyColumns.map(([columnName, column]) => [`${GROUP_COL}${columnName}`, column])),\n ...request.selection,\n };\n\n let query = resolveExecutor(db, context).select(selection).from(table);\n if (args.where) {\n query = query.where(extractFilters(table, tableName, args.where, relationFilterCtx(filterCtx, tableName)));\n }\n query = query.groupBy(...keyColumns.map(([, column]) => column));\n\n const havingCondition = buildHavingCondition(args.having, columns);\n if (havingCondition) {\n query = query.having(havingCondition);\n }\n\n const rows: any[] = await query;\n\n return rows.map((row) => {\n const group: Record<string, any> = {};\n for (const [columnName, column] of keyColumns) {\n const value = row[`${GROUP_COL}${columnName}`];\n const decoded =\n typeof value === 'string' && target.dateTimeColumns.has(columnName) ? parseDriverDateTime(value) : value;\n group[columnName] = value == null ? null : remapToGraphQLCore(columnName, decoded, tableName, column);\n }\n\n return { group, ...assembleAggregateRow(row, request, target) };\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { and, getColumns, is, One, type Table, type View } from 'drizzle-orm';\nimport type { RelationalQueryBuilder } from 'drizzle-orm/mysql-core/query-builders/query';\nimport { getTableConfig, type PgAsyncDatabase, type PgColumn, PgTable } from 'drizzle-orm/pg-core';\nimport type { GraphQLFieldConfig, GraphQLFieldConfigArgumentMap, ThunkObjMap } from 'graphql';\nimport {\n GraphQLError,\n type GraphQLInputObjectType,\n GraphQLList,\n GraphQLNonNull,\n type GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n aggregateFieldComplexity,\n assertSingleMatch,\n attachRowCursors,\n attachTargetPrimaryKeys,\n buildCursorCondition,\n buildNamedRelations,\n type CursorOrderEntry,\n computeResolverFieldNames,\n createRelationResolverFactory,\n cursorOrderExprs,\n cursorOrderingEntries,\n decodeCursor,\n eagerLoadMutationRelations,\n excludedColumnRef,\n extractFilters,\n extractOrderBy,\n extractRequiredFilters,\n extractSelectedColumnsFromTreeSQLFormat,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n generateUpdateManyInput,\n getPrimaryKeyPropNamesFromConfig,\n getUniqueColumnSets,\n isCursorFieldSelected,\n listFieldComplexity,\n type OnConflictArg,\n orderByHasRelationEntry,\n prepareMutationRelationColumns,\n primaryKeyOrderExprs,\n primaryKeyRestriction,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n relationFilterCtx,\n resolveConflictPlan,\n resolveExecutor,\n resolveQueryExecutor,\n runRelationalSelect,\n type SelectionCtx,\n selectArrayArgs,\n selectDistinctKeys,\n selectSingleArgs,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n} from '../builders/common.ts';\nimport {\n remapFromGraphQLArrayInput,\n remapFromGraphQLSingleInput,\n remapToGraphQLArrayOutput,\n remapToGraphQLSingleOutput,\n} from '../data-mappers/index.ts';\nimport {\n createRelationAggregateFactory,\n generateAggregate,\n generateAggregateTypes,\n generateGroupBy,\n generateGroupByEnum,\n generateGroupByType,\n generateHavingInput,\n} from './aggregates.ts';\nimport type {\n CreatedResolver,\n Filters,\n SchemaGeneratorOptions,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst generateSelectArray = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n distinctEnabled: boolean = true,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n // Tables without relations won't have db.query support — fall back to basic select.\n\n const table = tables[tableName]!;\n const pkNames = pgPrimaryKeyPropNames(table as PgTable);\n const queryArgs = selectArrayArgs(\n orderArgs,\n filterArgs,\n distinctEnabled ? generateDistinctEnum(table, typeName) : undefined,\n );\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n\n if (requestQueryBase) {\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: false,\n filterCtx,\n pkNames,\n db: executor,\n // PostgreSQL sorts NULLs as the largest values (last in ASC).\n nullOrdering: 'nulls-largest',\n });\n }\n\n // Fallback for tables without relational query builder support.\n // Use SQL column objects (not Record<string,true>) so db.select() receives valid expressions.\n const { offset, limit, orderBy, where, distinct, after } = args;\n const selectedColumnsSql = extractSelectedColumnsFromTreeSQLFormat<PgColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n { tableName, relationMap, tables },\n );\n\n // Keyset pagination (see runRelationalSelect, which handles the RQB path).\n const cursorSelected = isCursorFieldSelected(parsedInfo.fieldsByTypeName[typeName], table);\n let cursorEntries: CursorOrderEntry[] | undefined;\n if (after != null || cursorSelected) {\n if (after != null && distinct?.length) {\n throw new GraphQLError(\"'after' cannot be combined with 'distinct'.\");\n }\n if (orderByHasRelationEntry(orderBy)) {\n if (after != null) {\n throw new GraphQLError(\n \"'after' cannot be combined with an orderBy that orders through a relation — a related row's value cannot be encoded into a cursor.\",\n );\n }\n // `cursor` selected under a relation ordering — resolves to null; ordering still applies.\n } else if (!pkNames.length) {\n if (after != null) {\n throw new GraphQLError(\n `Table ${tableName} has no primary key, so cursor pagination cannot be used on it.`,\n );\n }\n } else {\n cursorEntries = cursorOrderingEntries(orderBy, pkNames);\n if (cursorSelected) {\n // The whole ordering tuple is needed to compute each row's cursor.\n const allColumns = getColumns(table);\n for (const [column] of cursorEntries) {\n selectedColumnsSql[column] ??= allColumns[column] as PgColumn;\n }\n }\n }\n }\n const cursorCondition =\n after != null && cursorEntries\n ? buildCursorCondition(table, cursorEntries, decodeCursor(after, cursorEntries), 'nulls-largest')\n : undefined;\n\n const baseWhereSql = where\n ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined;\n const whereSql = cursorCondition ? and(baseWhereSql, cursorCondition) : baseWhereSql;\n\n // `distinct` picks the surviving rows in its own pass; the main query is then narrowed\n // to those primary keys and re-orders them the same way. See runRelationalSelect.\n let distinctKeys: Record<string, any>[] | undefined;\n if (distinct?.length) {\n distinctKeys = await selectDistinctKeys({\n db: executor,\n table,\n tableName,\n distinct,\n pkNames,\n where: whereSql,\n orderBy,\n limit,\n offset,\n });\n if (!distinctKeys.length) {\n return [];\n }\n }\n\n let q = executor.select(selectedColumnsSql).from(table);\n if (distinctKeys) {\n q = q.where(primaryKeyRestriction(table, pkNames, distinctKeys)) as any;\n } else if (whereSql) {\n q = q.where(whereSql) as any;\n }\n if (cursorEntries && !distinctKeys) {\n // Cursor pagination pages over a total order: orderBy plus the PK tiebreak.\n q = q.orderBy(...cursorOrderExprs(table, cursorEntries)) as any;\n } else if (orderBy) {\n q = q.orderBy(\n ...extractOrderBy(table, orderBy, relationFilterCtx(filterCtx, tableName)),\n ...(distinctKeys ? primaryKeyOrderExprs(table, pkNames) : []),\n ) as any;\n } else if ((distinctKeys || offset != null || limit != null) && pkNames.length) {\n // See runRelationalSelect: an unordered slice is not stable between requests.\n q = q.orderBy(...primaryKeyOrderExprs(table, pkNames)) as any;\n }\n if (!distinctKeys) {\n if (offset) {\n q = q.offset(offset) as any;\n }\n if (limit) {\n q = q.limit(limit) as any;\n }\n }\n const rows = await q;\n if (cursorEntries && cursorSelected) {\n attachRowCursors(rows, cursorEntries);\n }\n return remapToGraphQLArrayOutput(rows, tableName, table, relationMap);\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateSelectSingle = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n // Tables without relations won't have db.query support — fall back to basic select.\n\n const queryArgs = selectSingleArgs(orderArgs, filterArgs);\n\n const table = tables[tableName]!;\n const pkNames = pgPrimaryKeyPropNames(table as PgTable);\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n\n if (requestQueryBase) {\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n pkNames,\n db: executor,\n });\n }\n\n // Fallback for tables without relational query builder support.\n const { offset, orderBy, where } = args;\n const selectedColumnsSql = extractSelectedColumnsFromTreeSQLFormat<PgColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n { tableName, relationMap, tables },\n );\n let q = executor.select(selectedColumnsSql).from(table);\n if (where) {\n q = q.where(extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))) as any;\n }\n if (orderBy) {\n q = q.orderBy(...extractOrderBy(table, orderBy, relationFilterCtx(filterCtx, tableName))) as any;\n } else if (pkNames.length) {\n // A single query is an implicit `limit 1` — order it so the row is deterministic.\n q = q.orderBy(...primaryKeyOrderExprs(table, pkNames)) as any;\n }\n if (offset) {\n q = q.offset(offset) as any;\n }\n const rows = await q.limit(1);\n const result = rows[0];\n return result ? remapToGraphQLSingleOutput(result, tableName, table, relationMap) : undefined;\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\n/** Primary-key property names for a PG table, including table-level composite keys. */\nconst pgPrimaryKeyPropNames = (table: PgTable): string[] => getPrimaryKeyPropNamesFromConfig(table, getTableConfig);\n\nconst generateInsertArray = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n conflictDoNothing: boolean = false,\n): 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 const input = remapFromGraphQLArrayInput(args.values, table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const executor = resolveExecutor(db, context);\n let query = executor.insert(table).values(input).returning(columns);\n if (conflictDoNothing) {\n query = query.onConflictDoNothing() as any;\n }\n const result = await query;\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\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): 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 const input = remapFromGraphQLSingleInput(args.values, table);\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const executor = resolveExecutor(db, context);\n let query = executor.insert(table).values(input).returning(columns);\n if (conflictDoNothing) {\n query = query.onConflictDoNothing() as any;\n }\n const result = await query;\n\n if (!result[0]) {\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap);\n } 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): 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 const input = single\n ? [remapFromGraphQLSingleInput(args.values as Record<string, any>, table)]\n : remapFromGraphQLArrayInput(args.values as Record<string, any>[], table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const plan = resolveConflictPlan({\n table,\n values: input,\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 const executor = resolveExecutor(db, context);\n let query = executor.insert(table).values(input).returning(columns);\n query =\n plan.action === 'NOTHING'\n ? (query.onConflictDoNothing(plan.target ? { target: plan.target } : undefined) as any)\n : (query.onConflictDoUpdate({ target: plan.target!, set: plan.set, setWhere: plan.setWhere }) as any);\n\n const result = await query;\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 } 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): 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 const { where, set } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const input = remapFromGraphQLSingleInput(set, table);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n const executor = resolveExecutor(db, context);\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 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 && !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 } 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): 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 const { updates } = args;\n if (!updates.length) {\n throw new GraphQLError('No updates were provided!');\n }\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n // Remap and validate every entry before the transaction opens, so a malformed\n // entry rejects the request instead of rolling back mid-batch.\n const entries = updates.map(({ where, set }) => {\n const input = remapFromGraphQLSingleInput(set, table);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n filters: where\n ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n };\n });\n\n const executor = resolveExecutor(db, context);\n // On a caller-supplied transaction this opens a savepoint, so the batch stays\n // atomic without breaking the outer transaction.\n const perEntry: Record<string, any>[][] = await executor.transaction(async (tx) => {\n const results: Record<string, 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 results.push(await (query.returning(columns) as any));\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 } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateDelete = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n single: boolean,\n requireWhere: boolean,\n filterCtx?: RelationFilterBase,\n selectionCtx?: SelectionCtx,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, info) => {\n try {\n const { where } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const columns = extractSelectedColumnsFromTreeSQLFormat<PgColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n selectionCtx,\n );\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n const executor = resolveExecutor(db, context);\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) as any;\n\n const result = await query;\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row!`);\n }\n\n if (single) {\n return result[0] ? remapToGraphQLSingleOutput(result[0], tableName, table) : undefined;\n }\n\n return remapToGraphQLArrayOutput(result, tableName, table);\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\ntype SchemaEntry = Table<any> | View<string, boolean, any>;\n\nexport function generateSchemaData<\n TDrizzleInstance extends PgAsyncDatabase<any, any>,\n TRelations extends TablesRelationalConfig,\n TSchema extends Record<string, SchemaEntry>,\n>(\n db: TDrizzleInstance,\n schema: TSchema,\n relations: TRelations,\n options: SchemaGeneratorOptions,\n): GeneratedEntities<TDrizzleInstance, TSchema> {\n const {\n relationsDepthLimit,\n prefixes,\n suffixes,\n conflictDoNothing,\n typeNameMapper,\n shouldEagerLoad,\n features,\n complexity,\n } = options;\n const schemaEntries = Object.entries(schema);\n const tableEntries = schemaEntries.filter(([_key, value]) => is(value, PgTable)) as [string, PgTable][];\n const tables = Object.fromEntries(tableEntries) as Record<string, PgTable>;\n\n if (!tableEntries.length) {\n throw new Error(\n \"Drizzle-GraphQL Error: No tables detected in Drizzle-ORM's database instance. Did you forget to pass schema to drizzle constructor?\",\n );\n }\n\n // Flatten drizzle-orm v1 TablesRelationalConfig into the canonical shape\n // used throughout common.ts: Record<tableName, Record<relName, TableNamedRelations>>\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Record each relation target's primary key (composite-aware) so paginated relations\n // default to a deterministic PK order. Must run before pruning / type generation, which\n // share these entry objects.\n attachTargetPrimaryKeys(namedRelations, tables, pgPrimaryKeyPropNames);\n // Relations to eager-load via `with:`. Query/mutation resolvers use this pruned map so\n // opted-out relations never overfetch; type generation keeps the full map so their\n // fields still exist and resolve lazily.\n const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);\n\n const filterCtx: RelationFilterBase = { tables, relationMap: namedRelations };\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(db, tables, filterCtx);\n\n // Fresh cache per generateSchemaData call — prevents type name collisions\n // when buildSchema() is called multiple times.\n const cacheCtx: TypeCacheCtx = {\n genericFilterCache: new Map(),\n objectTypeCache: new Map(),\n relationFieldContainers: new Map(),\n fullyBuiltTables: new Set(),\n relationTypeCache: new Map(),\n orderTypeCache: new WeakMap(),\n filterTypeCache: new WeakMap(),\n listRelationFilterCache: new Map(),\n aggregateTypeCache: new Map(),\n complexity,\n };\n\n // Left undefined when the feature is off — generateTableTypes then emits no\n // `${relation}Aggregate` fields at all.\n const relationAggregateFactory: RelationAggregateFactory | undefined = features.relationAggregates\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx)\n : undefined;\n\n const queries: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const mutations: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n\n const gqlSchemaTypes = Object.fromEntries(\n Object.entries(tables).map(([tableName, _table]) => [\n tableName,\n generateTableTypes(\n tableName,\n tables,\n namedRelations,\n true,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n prefixes.insert,\n prefixes.update,\n resolverFactory,\n relationAggregateFactory,\n ),\n ]),\n );\n\n const inputs: Record<string, GraphQLInputObjectType> = {};\n const outputs: Record<string, GraphQLObjectType> = {};\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n const { insertInput, updateInput, tableFilters, tableOrder } = tableTypes.inputs;\n const { selectSingleOutput, selectArrOutput, singleTableItemOutput, arrTableItemOutput } = tableTypes.outputs;\n\n // Compute field names using the mapper logic\n const {\n typeName,\n listFieldName,\n singleFieldName,\n aggregateFieldName,\n groupByFieldName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n updateManyFieldName,\n updateSingleFieldName,\n deleteFieldName,\n deleteSingleFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\n\n const selectArrGenerated = generateSelectArray(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n listFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n features.distinct,\n );\n const selectSingleGenerated = generateSelectSingle(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n singleFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n );\n const insertArrGenerated = features.insert\n ? generateInsertArray(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n insertInput,\n createArrayFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n )\n : undefined;\n const insertSingleGenerated = features.insert\n ? generateInsertSingle(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n insertInput,\n createSingleFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n )\n : undefined;\n // An upsert needs something to conflict on, so a table with no primary key and no\n // unique constraint gets no upsert mutations rather than ones that always fail.\n const uniqueSets = features.upsert ? getUniqueColumnSets(schema[tableName] as PgTable, getTableConfig) : [];\n const onConflictInput = features.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as PgTable,\n typeName,\n uniqueSets,\n tableFilters,\n withTarget: true,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n insertInput,\n onConflictInput,\n uniqueSets,\n upsertArrayFieldName,\n typeName,\n false,\n typeNameMapper,\n filterCtx,\n )\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 )\n : undefined;\n const updateGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateFieldName,\n typeName,\n false,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n )\n : undefined;\n const updateSingleGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n features.update && features.updateMany\n ? generateUpdateManyInput({ typeName, updatePrefix: prefixes.update, updateInput, tableFilters })\n : undefined;\n const updateManyGenerated = updateManyInput\n ? generateUpdateMany(\n db,\n tableName,\n schema[tableName] as PgTable,\n tables,\n eagerRelations,\n updateManyInput,\n updateManyFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n )\n : undefined;\n const deleteGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n deleteFieldName,\n typeName,\n false,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n )\n : undefined;\n const deleteSingleGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as PgTable,\n tableFilters,\n deleteSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n )\n : undefined;\n const aggregateType = features.aggregates\n ? generateAggregateTypes(schema[tableName] as PgTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = features.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as PgTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n features.aggregates && features.groupBy\n ? generateGroupByType(schema[tableName] as PgTable, tableName, typeName, cacheCtx)\n : undefined;\n const groupByEnum = groupByType\n ? generateGroupByEnum(schema[tableName] as PgTable, tableName, typeName)\n : undefined;\n const havingInput = groupByEnum\n ? generateHavingInput(schema[tableName] as PgTable, tableName, typeName)\n : undefined;\n const groupByGenerated =\n groupByType && groupByEnum && havingInput\n ? generateGroupBy(\n db,\n tableName,\n schema[tableName] as PgTable,\n typeName,\n groupByFieldName,\n tableFilters,\n groupByEnum,\n havingInput,\n filterCtx,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n ...(complexity ? { extensions: { complexity: listFieldComplexity(complexity) } } : {}),\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (insertArrGenerated) {\n mutations[insertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: insertArrGenerated.args,\n resolve: insertArrGenerated.resolver,\n };\n }\n if (insertSingleGenerated) {\n mutations[insertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: insertSingleGenerated.args,\n resolve: insertSingleGenerated.resolver,\n };\n }\n if (upsertArrGenerated) {\n mutations[upsertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: upsertArrGenerated.args,\n resolve: upsertArrGenerated.resolver,\n };\n }\n if (upsertSingleGenerated) {\n mutations[upsertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: upsertSingleGenerated.args,\n resolve: upsertSingleGenerated.resolver,\n };\n }\n if (updateGenerated) {\n mutations[updateGenerated.name] = {\n type: arrTableItemOutput,\n args: updateGenerated.args,\n resolve: updateGenerated.resolver,\n };\n }\n if (updateManyGenerated) {\n mutations[updateManyGenerated.name] = {\n // Nullable items: a no-match entry yields `null` in its slot.\n type: new GraphQLNonNull(new GraphQLList(singleTableItemOutput)),\n args: updateManyGenerated.args,\n resolve: updateManyGenerated.resolver,\n };\n }\n if (updateSingleGenerated) {\n mutations[updateSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: updateSingleGenerated.args,\n resolve: updateSingleGenerated.resolver,\n };\n }\n if (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.resolver,\n };\n }\n if (deleteSingleGenerated) {\n mutations[deleteSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: deleteSingleGenerated.args,\n resolve: deleteSingleGenerated.resolver,\n };\n }\n // The insert/update inputs are still built (they type the mutations that survive) but\n // only reach the schema's type map when a mutation actually references them.\n const activeInputs = [\n // The insert input types the upsert mutations too, so either feature keeps it.\n ...(features.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(features.update ? [updateInput] : []),\n ...(updateManyInput ? [updateManyInput] : []),\n tableFilters,\n tableOrder,\n ];\n activeInputs.forEach((e) => {\n inputs[e.name] = e;\n });\n outputs[selectSingleOutput.name] = selectSingleOutput;\n outputs[singleTableItemOutput.name] = singleTableItemOutput;\n if (aggregateType) {\n outputs[aggregateType.name] = aggregateType;\n }\n if (groupByType && havingInput) {\n outputs[groupByType.name] = groupByType;\n inputs[havingInput.name] = havingInput;\n }\n }\n\n const fieldResolvers: Record<string, Record<string, any>> = {};\n for (const [tableName, tableRelations] of Object.entries(namedRelations)) {\n const relResolvers: Record<string, any> = {};\n for (const [relName, relEntry] of Object.entries(tableRelations)) {\n const isOne = is((relEntry as any).relation ?? relEntry, One);\n const resolver = resolverFactory({ tableName, relationName: relName, relEntry, isOne });\n if (resolver) {\n relResolvers[relName] = resolver;\n }\n }\n if (Object.keys(relResolvers).length > 0) {\n fieldResolvers[tableName] = relResolvers;\n }\n }\n\n return { queries, mutations, inputs, types: outputs, fieldResolvers } as any;\n}\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { is, One, type Table } from 'drizzle-orm';\nimport type { RelationalQueryBuilder } from 'drizzle-orm/mysql-core/query-builders/query';\nimport { type BaseSQLiteDatabase, getTableConfig, type SQLiteColumn, SQLiteTable } from 'drizzle-orm/sqlite-core';\nimport type { GraphQLFieldConfig, GraphQLFieldConfigArgumentMap, GraphQLResolveInfo, ThunkObjMap } from 'graphql';\nimport {\n GraphQLError,\n type GraphQLInputObjectType,\n GraphQLList,\n GraphQLNonNull,\n type GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\n\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n aggregateFieldComplexity,\n assertSingleMatch,\n attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createRelationResolverFactory,\n eagerLoadMutationRelations,\n excludedColumnRef,\n extractFilters,\n extractRequiredFilters,\n extractSelectedColumnsFromTreeSQLFormat,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n generateUpdateManyInput,\n getPrimaryKeyPropNamesFromConfig,\n getUniqueColumnSets,\n listFieldComplexity,\n type OnConflictArg,\n prepareMutationRelationColumns,\n pruneNonEagerRelations,\n type RelationAggregateFactory,\n type RelationFilterBase,\n type RelationResolverFactory,\n relationFilterCtx,\n resolveConflictPlan,\n resolveExecutor,\n resolveQueryExecutor,\n runRelationalSelect,\n type SelectionCtx,\n selectArrayArgs,\n selectSingleArgs,\n type TablesRelationalConfig,\n type TypeCacheCtx,\n type TypeNameMapper,\n toGraphQLError,\n} from '../builders/common.ts';\nimport {\n remapFromGraphQLArrayInput,\n remapFromGraphQLSingleInput,\n remapToGraphQLArrayOutput,\n remapToGraphQLSingleOutput,\n} from '../data-mappers/index.ts';\nimport {\n createRelationAggregateFactory,\n generateAggregate,\n generateAggregateTypes,\n generateGroupBy,\n generateGroupByEnum,\n generateGroupByType,\n generateHavingInput,\n} from './aggregates.ts';\nimport type {\n CreatedResolver,\n Filters,\n SchemaGeneratorOptions,\n TableNamedRelations,\n TableSelectArgs,\n} from './types.ts';\n\nconst generateSelectArray = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n distinctEnabled: boolean = true,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const table = tables[tableName]!;\n const pkNames = sqlitePrimaryKeyPropNames(table as SQLiteTable);\n const queryArgs = selectArrayArgs(\n orderArgs,\n filterArgs,\n distinctEnabled ? generateDistinctEnum(table, typeName) : undefined,\n );\n\n return {\n name: fieldName,\n resolver: async (_source: any, args: Partial<TableSelectArgs>, context: any, info: GraphQLResolveInfo) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: false,\n filterCtx,\n pkNames,\n db: executor,\n // SQLite sorts NULLs as the smallest values (first in ASC).\n nullOrdering: 'nulls-smallest',\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateSelectSingle = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n orderArgs: GraphQLInputObjectType,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryBase = db.query[tableName as keyof typeof db.query] as unknown as\n | RelationalQueryBuilder<any, any, any>\n | undefined;\n if (!queryBase) {\n throw new Error(\n `Drizzle-GraphQL Error: Table ${tableName} not found in drizzle instance. Did you forget to pass schema to drizzle constructor?`,\n );\n }\n\n const queryArgs = selectSingleArgs(orderArgs, filterArgs);\n\n const table = tables[tableName]!;\n const pkNames = sqlitePrimaryKeyPropNames(table as SQLiteTable);\n\n return {\n name: fieldName,\n resolver: async (_source, args: Partial<TableSelectArgs>, context, info) => {\n try {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const { executor, queryBase: requestQueryBase } = resolveQueryExecutor(db, context, tableName, queryBase);\n return await runRelationalSelect({\n queryBase: requestQueryBase,\n tables,\n tableName,\n table,\n relationMap,\n typeName,\n typeNameMapper,\n parsedInfo,\n ...args,\n single: true,\n filterCtx,\n pkNames,\n db: executor,\n });\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\n/** Primary-key property names for a SQLite table, including table-level composite keys. */\nconst sqlitePrimaryKeyPropNames = (table: SQLiteTable): string[] =>\n getPrimaryKeyPropNamesFromConfig(table, getTableConfig);\n\nconst generateInsertArray = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n tables: Record<string, Table>,\n relationMap: Record<string, Record<string, TableNamedRelations>>,\n baseType: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n typeNameMapper?: TypeNameMapper,\n conflictDoNothing: boolean = false,\n): 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 const input = remapFromGraphQLArrayInput(args.values, table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const executor = resolveExecutor(db, context);\n let query = executor.insert(table).values(input).returning(columns);\n if (conflictDoNothing) {\n query = query.onConflictDoNothing() as any;\n }\n const result = await query;\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLArrayOutput(enriched, tableName, table, relationMap);\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): 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 const input = remapFromGraphQLSingleInput(args.values, table);\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n const executor = resolveExecutor(db, context);\n let query = executor.insert(table).values(input).returning(columns);\n if (conflictDoNothing) {\n query = query.onConflictDoNothing() as any;\n }\n const result = await query;\n\n if (!result[0]) {\n return undefined;\n }\n\n const enriched = hasRelations\n ? await eagerLoadMutationRelations(executor, tableName, result, pkNames, withParams)\n : result;\n\n return remapToGraphQLSingleOutput(enriched[0], tableName, table, relationMap);\n } 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): 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 const input = single\n ? [remapFromGraphQLSingleInput(args.values as Record<string, any>, table)]\n : remapFromGraphQLArrayInput(args.values as Record<string, any>[], table);\n if (!input.length) {\n throw new GraphQLError('No values were provided!');\n }\n\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const plan = resolveConflictPlan({\n table,\n values: input,\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 const executor = resolveExecutor(db, context);\n let query = executor.insert(table).values(input).returning(columns);\n query =\n plan.action === 'NOTHING'\n ? (query.onConflictDoNothing(plan.target ? { target: plan.target } : undefined) as any)\n : (query.onConflictDoUpdate({ target: plan.target!, set: plan.set, setWhere: plan.setWhere }) as any);\n\n const result = await query;\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 } 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): 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 const { where, set } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n const input = remapFromGraphQLSingleInput(set, table);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n const executor = resolveExecutor(db, context);\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 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 && !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 } 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): 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 const { updates } = args;\n if (!updates.length) {\n throw new GraphQLError('No updates were provided!');\n }\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const { columns, hasRelations, withParams } = prepareMutationRelationColumns({\n relationMap,\n tables,\n tableName,\n typeName,\n typeNameMapper,\n table,\n pkNames,\n parsedInfo,\n });\n\n // Remap and validate every entry before the transaction opens, so a malformed\n // entry rejects the request instead of rolling back mid-batch.\n const entries = updates.map(({ where, set }) => {\n const input = remapFromGraphQLSingleInput(set, table);\n if (!Object.keys(input).length) {\n throw new GraphQLError('Unable to update with no values specified!');\n }\n return {\n set: input,\n filters: where\n ? extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName))\n : undefined,\n };\n });\n\n 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(columns).all();\n };\n\n const executor = resolveExecutor(db, context);\n // On a caller-supplied transaction this opens a savepoint, so the batch stays\n // atomic without breaking the outer transaction. A sync driver's transaction\n // callback must not be async — it would commit before any awaited statement ran —\n // so the driver kind is probed from the first statement's result instead.\n const perEntry: Record<string, any>[][] = await executor.transaction((tx: any) => {\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 } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nconst generateDelete = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n single: boolean,\n requireWhere: boolean,\n filterCtx?: RelationFilterBase,\n selectionCtx?: SelectionCtx,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: single || requireWhere ? new GraphQLNonNull(filterArgs) : filterArgs,\n },\n } as const satisfies GraphQLFieldConfigArgumentMap;\n\n return {\n name: fieldName,\n resolver: async (_source, args: { where?: Filters<Table> }, context, info) => {\n try {\n const { where } = args;\n\n const parsedInfo = parseResolveInfo(info, {\n deep: true,\n }) as ResolveTree;\n\n const columns = extractSelectedColumnsFromTreeSQLFormat<SQLiteColumn>(\n parsedInfo.fieldsByTypeName[typeName]!,\n table,\n selectionCtx,\n );\n\n const relationCtx = relationFilterCtx(filterCtx, tableName);\n const filters =\n single || requireWhere\n ? extractRequiredFilters(table, tableName, where, fieldName, relationCtx)\n : where\n ? extractFilters(table, tableName, where, relationCtx)\n : undefined;\n\n const executor = resolveExecutor(db, context);\n if (single) {\n await assertSingleMatch(executor, table, filters!, fieldName);\n }\n\n let query = executor.delete(table);\n if (filters) {\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) as any;\n\n const result = await query;\n\n if (single && result.length > 1) {\n // A row started matching between the pre-check and the write.\n throw new GraphQLError(`${fieldName}: 'where' matched more than one row!`);\n }\n\n if (single) {\n return result[0] ? remapToGraphQLSingleOutput(result[0], tableName, table) : undefined;\n }\n\n return remapToGraphQLArrayOutput(result, tableName, table);\n } catch (e) {\n throw toGraphQLError(e);\n }\n },\n args: queryArgs,\n };\n};\n\nexport const generateSchemaData = <\n TDrizzleInstance extends BaseSQLiteDatabase<any, any, any, any>,\n TSchema extends Record<string, Table | unknown>,\n>(\n db: TDrizzleInstance,\n schema: TSchema,\n relations: TablesRelationalConfig,\n options: SchemaGeneratorOptions,\n): GeneratedEntities<TDrizzleInstance, TSchema> => {\n const {\n relationsDepthLimit,\n prefixes,\n suffixes,\n conflictDoNothing,\n typeNameMapper,\n shouldEagerLoad,\n features,\n complexity,\n } = options;\n const rawSchema = schema;\n const schemaEntries = Object.entries(rawSchema);\n\n const tableEntries = schemaEntries.filter(([_key, value]) => is(value, SQLiteTable)) as [string, SQLiteTable][];\n const tables = Object.fromEntries(tableEntries) as Record<string, SQLiteTable>;\n\n if (!tableEntries.length) {\n throw new Error(\n \"Drizzle-GraphQL Error: No tables detected in Drizzle-ORM's database instance. Did you forget to pass schema to drizzle constructor?\",\n );\n }\n\n // Build namedRelations from the drizzle-orm v1 relations config.\n const namedRelations = buildNamedRelations(relations ?? {}, tableEntries);\n // Record each relation target's (composite-aware) primary key for deterministic\n // paginated ordering. Must run before pruning / type generation (shared entry objects).\n attachTargetPrimaryKeys(namedRelations, tables, sqlitePrimaryKeyPropNames);\n // Pruned map for query/mutation resolvers' `with:`; type generation keeps the full map.\n const eagerRelations = pruneNonEagerRelations(namedRelations, shouldEagerLoad);\n\n const filterCtx: RelationFilterBase = { tables, relationMap: namedRelations };\n\n const resolverFactory: RelationResolverFactory = createRelationResolverFactory(db, tables, filterCtx);\n\n // Fresh cache per generateSchemaData call — prevents type name collisions\n // when buildSchema() is called multiple times.\n const cacheCtx: TypeCacheCtx = {\n genericFilterCache: new Map(),\n objectTypeCache: new Map(),\n relationFieldContainers: new Map(),\n fullyBuiltTables: new Set(),\n relationTypeCache: new Map(),\n orderTypeCache: new WeakMap(),\n filterTypeCache: new WeakMap(),\n listRelationFilterCache: new Map(),\n aggregateTypeCache: new Map(),\n complexity,\n };\n\n // Left undefined when the feature is off — generateTableTypes then emits no\n // `${relation}Aggregate` fields at all.\n const relationAggregateFactory: RelationAggregateFactory | undefined = features.relationAggregates\n ? createRelationAggregateFactory(db, tables, cacheCtx, typeNameMapper, filterCtx)\n : undefined;\n\n const queries: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const mutations: ThunkObjMap<GraphQLFieldConfig<any, any>> = {};\n const gqlSchemaTypes = Object.fromEntries(\n Object.entries(tables).map(([tableName, _table]) => [\n tableName,\n generateTableTypes(\n tableName,\n tables,\n namedRelations,\n true,\n relationsDepthLimit,\n cacheCtx,\n typeNameMapper,\n prefixes.insert,\n prefixes.update,\n resolverFactory,\n relationAggregateFactory,\n ),\n ]),\n );\n\n const inputs: Record<string, GraphQLInputObjectType> = {};\n const outputs: Record<string, GraphQLObjectType> = {};\n\n for (const [tableName, tableTypes] of Object.entries(gqlSchemaTypes)) {\n const { insertInput, updateInput, tableFilters, tableOrder } = tableTypes.inputs;\n const { selectSingleOutput, selectArrOutput, singleTableItemOutput, arrTableItemOutput } = tableTypes.outputs;\n\n // Compute field names using the mapper logic\n const {\n typeName,\n listFieldName,\n singleFieldName,\n aggregateFieldName,\n groupByFieldName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n updateManyFieldName,\n updateSingleFieldName,\n deleteFieldName,\n deleteSingleFieldName,\n } = computeResolverFieldNames(tableName, typeNameMapper, prefixes, suffixes);\n\n const selectArrGenerated = generateSelectArray(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n listFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n features.distinct,\n );\n const selectSingleGenerated = generateSelectSingle(\n db,\n tableName,\n tables,\n eagerRelations,\n tableOrder,\n tableFilters,\n singleFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n );\n const insertArrGenerated = features.insert\n ? generateInsertArray(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n insertInput,\n createArrayFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n )\n : undefined;\n const insertSingleGenerated = features.insert\n ? generateInsertSingle(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n insertInput,\n createSingleFieldName,\n typeName,\n typeNameMapper,\n conflictDoNothing,\n )\n : undefined;\n // An upsert needs something to conflict on, so a table with no primary key and no\n // unique constraint gets no upsert mutations rather than ones that always fail.\n const uniqueSets = features.upsert ? getUniqueColumnSets(schema[tableName] as SQLiteTable, getTableConfig) : [];\n const onConflictInput = features.upsert\n ? generateOnConflictInput({\n table: schema[tableName] as SQLiteTable,\n typeName,\n uniqueSets,\n tableFilters,\n withTarget: true,\n })\n : undefined;\n const upsertArrGenerated = onConflictInput\n ? generateUpsert(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n insertInput,\n onConflictInput,\n uniqueSets,\n upsertArrayFieldName,\n typeName,\n false,\n typeNameMapper,\n filterCtx,\n )\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 )\n : undefined;\n const updateGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateFieldName,\n typeName,\n false,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n )\n : undefined;\n const updateSingleGenerated = features.update\n ? generateUpdate(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n updateInput,\n tableFilters,\n updateSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n typeNameMapper,\n filterCtx,\n )\n : undefined;\n // The batch update reuses the update `set` input, so it needs `update` on too.\n const updateManyInput =\n features.update && features.updateMany\n ? generateUpdateManyInput({ typeName, updatePrefix: prefixes.update, updateInput, tableFilters })\n : undefined;\n const updateManyGenerated = updateManyInput\n ? generateUpdateMany(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tables,\n eagerRelations,\n updateManyInput,\n updateManyFieldName,\n typeName,\n typeNameMapper,\n filterCtx,\n )\n : undefined;\n const deleteGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n deleteFieldName,\n typeName,\n false,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n )\n : undefined;\n const deleteSingleGenerated = features.delete\n ? generateDelete(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n tableFilters,\n deleteSingleFieldName,\n typeName,\n true,\n features.requireWhere,\n filterCtx,\n { tableName, relationMap: namedRelations, tables },\n )\n : undefined;\n const aggregateType = features.aggregates\n ? generateAggregateTypes(schema[tableName] as SQLiteTable, tableName, typeName, cacheCtx)\n : undefined;\n const aggregateGenerated = features.aggregates\n ? generateAggregate(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n typeName,\n aggregateFieldName,\n tableFilters,\n filterCtx,\n )\n : undefined;\n\n // The grouped result reuses the aggregate output types, so it only exists alongside them.\n const groupByType =\n features.aggregates && features.groupBy\n ? generateGroupByType(schema[tableName] as SQLiteTable, tableName, typeName, cacheCtx)\n : undefined;\n const groupByEnum = groupByType\n ? generateGroupByEnum(schema[tableName] as SQLiteTable, tableName, typeName)\n : undefined;\n const havingInput = groupByEnum\n ? generateHavingInput(schema[tableName] as SQLiteTable, tableName, typeName)\n : undefined;\n const groupByGenerated =\n groupByType && groupByEnum && havingInput\n ? generateGroupBy(\n db,\n tableName,\n schema[tableName] as SQLiteTable,\n typeName,\n groupByFieldName,\n tableFilters,\n groupByEnum,\n havingInput,\n filterCtx,\n )\n : undefined;\n\n queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\n ...(complexity ? { extensions: { complexity: listFieldComplexity(complexity) } } : {}),\n };\n queries[selectSingleGenerated.name] = {\n type: selectSingleOutput,\n args: selectSingleGenerated.args,\n resolve: selectSingleGenerated.resolver,\n };\n if (aggregateGenerated && aggregateType) {\n queries[aggregateGenerated.name] = {\n type: new GraphQLNonNull(aggregateType),\n args: aggregateGenerated.args,\n resolve: aggregateGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (groupByGenerated && groupByType) {\n queries[groupByGenerated.name] = {\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(groupByType))),\n args: groupByGenerated.args,\n resolve: groupByGenerated.resolver,\n ...(complexity ? { extensions: { complexity: aggregateFieldComplexity(complexity) } } : {}),\n };\n }\n if (insertArrGenerated) {\n mutations[insertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: insertArrGenerated.args,\n resolve: insertArrGenerated.resolver,\n };\n }\n if (insertSingleGenerated) {\n mutations[insertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: insertSingleGenerated.args,\n resolve: insertSingleGenerated.resolver,\n };\n }\n if (upsertArrGenerated) {\n mutations[upsertArrGenerated.name] = {\n type: arrTableItemOutput,\n args: upsertArrGenerated.args,\n resolve: upsertArrGenerated.resolver,\n };\n }\n if (upsertSingleGenerated) {\n mutations[upsertSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: upsertSingleGenerated.args,\n resolve: upsertSingleGenerated.resolver,\n };\n }\n if (updateGenerated) {\n mutations[updateGenerated.name] = {\n type: arrTableItemOutput,\n args: updateGenerated.args,\n resolve: updateGenerated.resolver,\n };\n }\n if (updateManyGenerated) {\n mutations[updateManyGenerated.name] = {\n // Nullable items: a no-match entry yields `null` in its slot.\n type: new GraphQLNonNull(new GraphQLList(singleTableItemOutput)),\n args: updateManyGenerated.args,\n resolve: updateManyGenerated.resolver,\n };\n }\n if (updateSingleGenerated) {\n mutations[updateSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: updateSingleGenerated.args,\n resolve: updateSingleGenerated.resolver,\n };\n }\n if (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.resolver,\n };\n }\n if (deleteSingleGenerated) {\n mutations[deleteSingleGenerated.name] = {\n type: singleTableItemOutput,\n args: deleteSingleGenerated.args,\n resolve: deleteSingleGenerated.resolver,\n };\n }\n // The insert/update inputs are still built (they type the mutations that survive) but\n // only reach the schema's type map when a mutation actually references them.\n const activeInputs = [\n // The insert input types the upsert mutations too, so either feature keeps it.\n ...(features.insert || onConflictInput ? [insertInput] : []),\n ...(onConflictInput ? [onConflictInput] : []),\n ...(features.update ? [updateInput] : []),\n ...(updateManyInput ? [updateManyInput] : []),\n tableFilters,\n tableOrder,\n ];\n activeInputs.forEach((e) => {\n inputs[e.name] = e;\n });\n outputs[selectSingleOutput.name] = selectSingleOutput;\n outputs[singleTableItemOutput.name] = singleTableItemOutput;\n if (aggregateType) {\n outputs[aggregateType.name] = aggregateType;\n }\n if (groupByType && havingInput) {\n outputs[groupByType.name] = groupByType;\n inputs[havingInput.name] = havingInput;\n }\n }\n\n const fieldResolvers: Record<string, Record<string, any>> = {};\n for (const [tableName, tableRelations] of Object.entries(namedRelations)) {\n const relResolvers: Record<string, any> = {};\n for (const [relName, relEntry] of Object.entries(tableRelations)) {\n const isOne = is((relEntry as any).relation ?? relEntry, One);\n const resolver = resolverFactory({ tableName, relationName: relName, relEntry, isOne });\n if (resolver) {\n relResolvers[relName] = resolver;\n }\n }\n if (Object.keys(relResolvers).length > 0) {\n fieldResolvers[tableName] = relResolvers;\n }\n }\n\n return { queries, mutations, inputs, types: outputs, fieldResolvers } as any;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,sBAAmB;AACnB,IAAAC,qBAA8B;AAC9B,IAAAC,kBAAgC;AAChC,IAAAC,sBAAmC;AACnC,IAAAC,kBAMO;;;ACQP,IAAAC,sBA8BO;AAEP,IAAAC,kBAWO;;;AC5DP,IAAM,sBAAsB,uBAAO,yBAAyB;AAI5D,IAAM,cAAN,MAAwB;AAAA,EAItB,YAA6B,SAAwB;AAAxB;AAAA,EAAyB;AAAA,EAH9C,QAAkF,CAAC;AAAA,EACnF,YAAY;AAAA,EAIpB,KAAK,KAAoB;AACvB,WAAO,IAAI,QAAW,CAAC,SAAS,WAAW;AACzC,WAAK,MAAM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C,sBAAkBC,oBAAW,IAAI,QAAQ,WAAW,gBAAgB;AAAA,EACtE,eAAW,wBAAG,IAAI,sCAAkB,GAAG;AACrC,sBAAkBA,oBAAe,IAAI,QAAQ,WAAW,gBAAgB;AAAA,EAC1E,OAAO;AACL,UAAM,IAAI,MAAM,uDAAuD;AAAA,EACzE;AAIA,QAAM,UAAU,QAAQ;AACxB;AAAA,IACE;AAAA,IACA,UAAU,CAAC,UAAU,QAAQ,KAAK,KAAK,mBAAmB,KAAK,IAAI;AAAA,EACrE;AAEA,QAAM,EAAE,SAAS,WAAW,QAAQ,MAAM,IAAI;AAE9C,QAAM,sBAA2C;AAAA,IAC/C,OAAO,CAAC,GAAG,OAAO,OAAO,MAAM,GAAG,GAAG,OAAO,OAAO,KAAK,CAAC;AAAA,IACzD,OAAO,IAAI,kCAAkB;AAAA,MAC3B,MAAM;AAAA,MACN,QAAQ;AAAA,IACV,CAAC;AAAA,EACH;AAIA,MAAI,QAAQ,cAAc,SAAS,OAAO,KAAK,SAAS,EAAE,QAAQ;AAChE,UAAM,WAAW,IAAI,kCAAkB;AAAA,MACrC,MAAM;AAAA,MACN,QAAQ;AAAA,IACV,CAAC;AAED,wBAAoB,WAAW;AAAA,EACjC;AAEA,QAAM,eAAe,IAAI,8BAAc,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","import_graphql","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","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","config","generateSchemaData"]}
|