@vantreeseba/drizzle-graphql 4.0.0 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -0
- package/dist/README.md +46 -0
- package/dist/index.cjs +56 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +46 -1
- package/dist/index.d.ts +46 -1
- package/dist/index.js +56 -15
- package/dist/index.js.map +1 -1
- package/dist/package.json +1 -1
- package/package.json +1 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/util/builders/common.ts","../src/util/batch-loader/index.ts","../src/util/case-ops/index.ts","../src/util/data-mappers/index.ts","../src/util/type-converter/index.ts","../src/util/scalars/index.ts","../src/util/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 DeleteResolver,\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 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 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 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 };\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 };\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, DateTimeFilter, BooleanFilter, per-enum)\n// instead of one type per (table, column) pair.\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 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 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 { 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): 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) : []),\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 );\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));\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 type pairs, keyed by generic name (e.g. \"String\", \"DateTime\"). */\n genericFilterCache: Map<string, { main: GraphQLInputObjectType; or: 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\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\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 } as const,\n});\n\n/**\n * Maps a Drizzle column to the generic filter type name to use.\n * - \"Id\" → uuid PK/FK columns (no like/ilike operators)\n * - \"DateTime\" → timestamp and date columns\n * - \"Boolean\" → boolean columns\n * - the enum GraphQL type name → enum columns (still unique per enum)\n * - \"IntArray\" → integer[]/serial[] array columns\n * - \"FloatArray\" → float[]/numeric[] array columns\n * - \"String\" → all other text/varchar columns\n */\nconst resolveGenericFilterName = (\n column: Column,\n columnName: string,\n columnGraphQLType: ReturnType<typeof drizzleColumnToGraphQLType>,\n): string => {\n // ID / foreign-key columns\n if (columnName === 'id' || columnName.endsWith('Id')) {\n return 'Id';\n }\n // Boolean scalar\n if (columnGraphQLType.type === GraphQLBoolean) {\n return 'Boolean';\n }\n // Enum type — keep unique per enum since values differ\n if (columnGraphQLType.type instanceof GraphQLEnumType) {\n return columnGraphQLType.type.name;\n }\n // Array columns — give them a distinct name so they never collide with StringFilter.\n // integer().array() columns have a `dimensions` property set on them.\n if (columnGraphQLType.type instanceof GraphQLList) {\n const desc = (columnGraphQLType as any).description ?? '';\n return desc.includes('Integer') ? 'IntArray' : 'FloatArray';\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 'DateTime';\n }\n // Default: plain text/varchar\n return 'String';\n};\n\nconst generateColumnFilterValues = (\n column: Column,\n tableName: string,\n columnName: string,\n cacheCtx: TypeCacheCtx,\n): GraphQLInputObjectType => {\n const columnGraphQLType = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, true);\n\n const genericName = resolveGenericFilterName(column, columnName, columnGraphQLType);\n const cached = cacheCtx.genericFilterCache.get(genericName);\n if (cached) {\n return cached.main;\n }\n\n const colType = columnGraphQLType.type;\n const colDesc = columnGraphQLType.description;\n const colArr = new GraphQLList(new GraphQLNonNull(colType));\n\n // IdFilter omits like/notLike/ilike/notIlike — they are nonsensical on UUIDs.\n const isId = genericName === 'Id';\n\n const baseFields = {\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 ...(isId\n ? {}\n : {\n like: { type: GraphQLString },\n notLike: { type: GraphQLString },\n ilike: { type: GraphQLString },\n notIlike: { type: GraphQLString },\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 const orType = new GraphQLInputObjectType({\n name: `${genericName}FilterOr`,\n fields: { ...baseFields },\n });\n\n const mainType = new GraphQLInputObjectType({\n name: `${genericName}Filter`,\n fields: {\n ...baseFields,\n OR: {\n type: new GraphQLList(new GraphQLNonNull(orType)),\n },\n },\n });\n\n cacheCtx.genericFilterCache.set(genericName, { main: mainType, or: orType });\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\nconst generateTableOrderTypeCached = (\n table: Table,\n tableName: string,\n typeNameMapper: TypeNameMapper | undefined,\n cacheCtx: TypeCacheCtx,\n) => {\n if (cacheCtx.orderTypeCache.has(table)) {\n return cacheCtx.orderTypeCache.get(table)!;\n }\n\n const orderColumns = generateTableOrderCached(table);\n const order = new GraphQLInputObjectType({\n name: `${resolveTypeName(tableName, typeNameMapper)}OrderBy`,\n fields: orderColumns,\n });\n\n cacheCtx.orderTypeCache.set(table, order);\n\n return order;\n};\n\n/**\n * Relations that can be expressed as a correlated `EXISTS` subquery. Many-to-many relations\n * declared with `.through()` need a junction join that the filter builder doesn't emit yet,\n * so they're left out of the filter input entirely — a missing field is a clean GraphQL\n * validation error, whereas a silently ignored filter would return too many rows.\n */\nconst isFilterableRelation = (relation: Relation<string>): boolean => !(relation as any).through;\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 || !isFilterableRelation(relation)) {\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 const orFilters = new GraphQLInputObjectType({\n name: `${resolveTypeName(tableName, typeNameMapper)}FiltersOr`,\n fields: buildFields,\n });\n\n const filters = new GraphQLInputObjectType({\n name: `${resolveTypeName(tableName, typeNameMapper)}Filters`,\n fields: () => ({\n ...buildFields(),\n OR: {\n type: new GraphQLList(new GraphQLNonNull(orFilters)),\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 ? generateTableOrderTypeCached(table, tableName, typeNameMapper, cacheCtx) : 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 rawRelationFields.push([\n relationName,\n {\n type: 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 },\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 } 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/**\n * Column name / direction pairs from an `orderBy` argument, highest priority first. Split out\n * of `extractOrderBy` so the same ordering can be rebuilt against a subquery's fields, where\n * there is no `Table` to read columns from.\n */\nexport const orderByEntries = (orderArgs: Record<string, any>): [string, 'asc' | 'desc'][] =>\n Object.entries(orderArgs)\n .sort((a, b) => (b[1]?.priority ?? 0) - (a[1]?.priority ?? 0))\n .filter(([, config]) => config)\n .map(([column, config]) => [column, config.direction]);\n\nexport const extractOrderBy = <TTable extends Table, TArgs extends OrderByArgs<any> = OrderByArgs<TTable>>(\n table: TTable,\n orderArgs: TArgs,\n): SQL[] =>\n orderByEntries(orderArgs).map(([column, direction]) =>\n direction === 'asc' ? asc(getColumns(table)[column]!) : desc(getColumns(table)[column]!),\n );\n\nexport const extractFiltersColumn = <TColumn extends Column>(\n column: TColumn,\n columnName: string,\n operators: FilterColumnOperators<TColumn>,\n): SQL | undefined => {\n if (!operators.OR?.length) {\n delete operators.OR;\n }\n\n const entries = Object.entries(operators as FilterColumnOperatorsCore<TColumn>);\n\n if (operators.OR) {\n if (entries.length > 1) {\n throw new GraphQLError(`WHERE ${columnName}: Cannot specify both fields and 'OR' in column operators!`);\n }\n\n const variants = [] as SQL[];\n\n for (const variant of operators.OR) {\n const extracted = extractFiltersColumn(column, columnName, variant);\n\n if (extracted) {\n variants.push(extracted);\n }\n }\n\n return variants.length ? (variants.length > 1 ? or(...variants) : variants[0]) : undefined;\n }\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 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 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 in nullableOps) {\n variants.push(nullableOps[operatorName]!(column));\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 * Builds one `[NOT] EXISTS (SELECT 1 FROM target alias WHERE …)` for a relation filter.\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 || !isFilterableRelation(relation)) {\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 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 // 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 ${getTableAsAliasSQL(aliasedTarget)} 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 ${getTableAsAliasSQL(aliasedTarget)} where ${condition})`\n : sql`exists (select 1 from ${getTableAsAliasSQL(aliasedTarget)} 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 variants: SQL[] = [];\n for (const mode of ['some', 'none', 'every'] as const) {\n const inner = value[mode];\n if (inner === undefined || inner === null) {\n continue;\n }\n\n const extracted = buildRelationExists(parentTable, relationName, relEntry, inner, mode, 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 if (!filters.OR?.length) {\n delete filters.OR;\n }\n\n const entries = Object.entries(filters as FiltersCore<TTable>);\n if (!entries.length) {\n return;\n }\n\n if (filters.OR) {\n if (entries.length > 1) {\n throw new GraphQLError(`WHERE ${tableName}: Cannot specify both fields and 'OR' in table filters!`);\n }\n\n const variants = [] as SQL[];\n\n for (const variant of filters.OR) {\n const extracted = extractFilters(table, tableName, variant, relationCtx);\n if (extracted) {\n variants.push(extracted);\n }\n }\n\n return variants.length ? (variants.length > 1 ? or(...variants) : variants[0]) : undefined;\n }\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 const extracted = column\n ? extractFiltersColumn(column, fieldName, operators)\n : relations?.[fieldName] && relationCtx\n ? extractRelationFilter(table, fieldName, relations[fieldName]!, operators as any, relationCtx)\n : undefined;\n\n if (extracted) {\n variants.push(extracted);\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) => extractOrderBy(aliasedTable, relationArgs.orderBy!)\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.map(([column, direction]) => (direction === 'asc' ? asc(cols[column]!) : desc(cols[column]!))),\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.map(([column, direction]) => (direction === 'asc' ? asc(sub[column]) : desc(sub[column]))),\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 createArrayFieldName: string;\n createSingleFieldName: string;\n upsertArrayFieldName: string;\n upsertSingleFieldName: string;\n updateFieldName: string;\n deleteFieldName: 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 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 return {\n typeName,\n listFieldName,\n singleFieldName,\n aggregateFieldName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n deleteFieldName,\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) : []),\n ...primaryKeyOrderExprs(aliasedTable, pkNames!),\n ]\n : orderBy\n ? (aliasedTable: Table) => extractOrderBy(aliasedTable, orderBy)\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 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 { GraphQLBigIntString, GraphQLDate, GraphQLDateTime, GraphQLJSON, GraphQLUUID } 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 const { type: baseType } = 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 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 // integer().array() columns keep columnType=PgInteger but gain a `dimensions` property.\n // drizzle-orm's extractExtendedColumnType still returns 'number' for them, so we\n // detect the array wrapper here and recurse with a synthetic base-int scalar.\n const dims = (column as any).dimensions as number | undefined;\n if (dims !== undefined && dims > 0) {\n const baseDesc = is(column, PgInteger) || is(column, PgSerial) ? 'Integer' : 'Float';\n const baseType = baseDesc === 'Integer' ? GraphQLInt : GraphQLFloat;\n return {\n type: new GraphQLList(new GraphQLNonNull(baseType)),\n description: `Array<${baseDesc}>`,\n };\n }\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","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\nexport { GraphQLDate, GraphQLDateTime, GraphQLJSON, GraphQLUUID };\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { is, One, type Table } from 'drizzle-orm';\nimport { getTableConfig, type MySqlDatabase, MySqlTable } from 'drizzle-orm/mysql-core';\nimport type { RelationalQueryBuilder } from 'drizzle-orm/mysql-core/query-builders/query';\nimport type { GraphQLFieldConfig, GraphQLFieldConfigArgumentMap, ThunkObjMap } from 'graphql';\nimport {\n GraphQLBoolean,\n GraphQLError,\n type GraphQLInputObjectType,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\n\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createRelationResolverFactory,\n extractFilters,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n getPrimaryKeyPropNamesFromConfig,\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 { createRelationAggregateFactory, generateAggregate, generateAggregateTypes } 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 filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryArgs = {\n set: {\n type: new GraphQLNonNull(setArgs),\n },\n where: {\n type: 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 executor = resolveExecutor(db, context);\n let query = executor.update(table).set(input);\n if (where) {\n const filters = extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName));\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 filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: 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 executor = resolveExecutor(db, context);\n let query = executor.delete(table);\n if (where) {\n const filters = extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName));\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 } = 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 };\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 createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n deleteFieldName,\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 filterCtx,\n )\n : undefined;\n const deleteGenerated = features.delete\n ? generateDelete(db, tableName, schema[tableName] as MySqlTable, tableFilters, deleteFieldName, filterCtx)\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 queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\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 };\n }\n for (const generated of [\n insertArrGenerated,\n insertSingleGenerated,\n upsertArrGenerated,\n upsertSingleGenerated,\n updateGenerated,\n deleteGenerated,\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 }\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 extractExtendedColumnType,\n getColumns,\n inArray,\n max,\n min,\n sum,\n type Table,\n} from 'drizzle-orm';\nimport {\n GraphQLFloat,\n type GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\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 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 = (info: any, target: AggregateTarget): AggregateRequest => {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const selectionTree = parsedInfo.fieldsByTypeName[`${target.typeName}Aggregate`] ?? {};\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","// @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 attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createRelationResolverFactory,\n eagerLoadMutationRelations,\n excludedColumnRef,\n extractFilters,\n extractOrderBy,\n extractSelectedColumnsFromTreeSQLFormat,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n getPrimaryKeyPropNamesFromConfig,\n getUniqueColumnSets,\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 { createRelationAggregateFactory, generateAggregate, generateAggregateTypes } 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),\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)) 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 typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryArgs = {\n set: {\n type: new GraphQLNonNull(setArgs),\n },\n where: {\n type: 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 executor = resolveExecutor(db, context);\n let query = executor.update(table).set(input);\n if (where) {\n const filters = extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName));\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) 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 generateDelete = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n filterCtx?: RelationFilterBase,\n selectionCtx?: SelectionCtx,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: 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 executor = resolveExecutor(db, context);\n let query = executor.delete(table);\n if (where) {\n const filters = extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName));\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) as any;\n\n const result = await query;\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 { relationsDepthLimit, prefixes, suffixes, conflictDoNothing, typeNameMapper, shouldEagerLoad, features } =\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 };\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 createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n deleteFieldName,\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 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 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 queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\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 };\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 (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.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 }\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 attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createRelationResolverFactory,\n eagerLoadMutationRelations,\n excludedColumnRef,\n extractFilters,\n extractSelectedColumnsFromTreeSQLFormat,\n generateDistinctEnum,\n generateOnConflictInput,\n generateTableTypes,\n getPrimaryKeyPropNamesFromConfig,\n getUniqueColumnSets,\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 { createRelationAggregateFactory, generateAggregate, generateAggregateTypes } 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 typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryArgs = {\n set: {\n type: new GraphQLNonNull(setArgs),\n },\n where: {\n type: 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 executor = resolveExecutor(db, context);\n let query = executor.update(table).set(input);\n if (where) {\n const filters = extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName));\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) 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 generateDelete = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n filterCtx?: RelationFilterBase,\n selectionCtx?: SelectionCtx,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: 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 executor = resolveExecutor(db, context);\n let query = executor.delete(table);\n if (where) {\n const filters = extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName));\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) as any;\n\n const result = await query;\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 { relationsDepthLimit, prefixes, suffixes, conflictDoNothing, typeNameMapper, shouldEagerLoad, features } =\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 };\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 createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n deleteFieldName,\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 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 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 queries[selectArrGenerated.name] = {\n type: selectArrOutput,\n args: selectArrGenerated.args,\n resolve: selectArrGenerated.resolver,\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 };\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 (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.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 }\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,IAAAA,sBAAmB;AACnB,IAAAC,qBAA8B;AAC9B,IAAAC,kBAAgC;AAChC,IAAAC,sBAAmC;AACnC,IAAAC,kBAMO;;;ACMP,IAAAC,sBA4BO;AAEP,IAAAC,kBAUO;;;ACvDP,IAAM,sBAAsB,uBAAO,yBAAyB;AAI5D,IAAM,cAAN,MAAwB;AAAA,EAItB,YAA6B,SAAwB;AAAxB;AAAA,EAAyB;AAAA,EAH9C,QAAkF,CAAC;AAAA,EACnF,YAAY;AAAA,EAIpB,KAAK,KAAoB;AACvB,WAAO,IAAI,QAAW,CAAC,SAAS,WAAW;AACzC,WAAK,MAAM,KAAK,EAAE,KAAK,SAAS,OAAO,CAAC;AACxC,UAAI,CAAC,KAAK,WAAW;AACnB,aAAK,YAAY;AACjB,gBAAQ,QAAQ,EAAE,KAAK,MAAM,KAAK,SAAS,CAAC;AAAA,MAC9C;AAAA,I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E1D,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_drizzle_orm","import_graphql","import_graphql","baseType","desc","variants","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/type-converter/index.ts","../src/util/scalars/index.ts","../src/util/builders/mysql.ts","../src/util/builders/aggregates.ts","../src/util/builders/pg.ts","../src/util/builders/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 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 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 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 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 };\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, DateTimeFilter, BooleanFilter, per-enum)\n// instead of one type per (table, column) pair.\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 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 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 { 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): 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) : []),\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 );\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));\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 type pairs, keyed by generic name (e.g. \"String\", \"DateTime\"). */\n genericFilterCache: Map<string, { main: GraphQLInputObjectType; or: 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\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 } as const,\n});\n\n/**\n * Maps a Drizzle column to the generic filter type name to use.\n * - \"Id\" → uuid PK/FK columns (no like/ilike operators)\n * - \"DateTime\" → timestamp and date columns\n * - \"Boolean\" → boolean columns\n * - the enum GraphQL type name → enum columns (still unique per enum)\n * - \"IntArray\" → integer[]/serial[] array columns\n * - \"FloatArray\" → float[]/numeric[] array columns\n * - \"String\" → all other text/varchar columns\n */\nconst resolveGenericFilterName = (\n column: Column,\n columnName: string,\n columnGraphQLType: ReturnType<typeof drizzleColumnToGraphQLType>,\n): string => {\n // ID / foreign-key columns\n if (columnName === 'id' || columnName.endsWith('Id')) {\n return 'Id';\n }\n // Boolean scalar\n if (columnGraphQLType.type === GraphQLBoolean) {\n return 'Boolean';\n }\n // Enum type — keep unique per enum since values differ\n if (columnGraphQLType.type instanceof GraphQLEnumType) {\n return columnGraphQLType.type.name;\n }\n // Array columns — give them a distinct name so they never collide with StringFilter.\n // integer().array() columns have a `dimensions` property set on them.\n if (columnGraphQLType.type instanceof GraphQLList) {\n const desc = (columnGraphQLType as any).description ?? '';\n return desc.includes('Integer') ? 'IntArray' : 'FloatArray';\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 'DateTime';\n }\n // Default: plain text/varchar\n return 'String';\n};\n\nconst generateColumnFilterValues = (\n column: Column,\n tableName: string,\n columnName: string,\n cacheCtx: TypeCacheCtx,\n): GraphQLInputObjectType => {\n const columnGraphQLType = drizzleColumnToGraphQLType(column, columnName, tableName, true, false, true);\n\n const genericName = resolveGenericFilterName(column, columnName, columnGraphQLType);\n const cached = cacheCtx.genericFilterCache.get(genericName);\n if (cached) {\n return cached.main;\n }\n\n const colType = columnGraphQLType.type;\n const colDesc = columnGraphQLType.description;\n const colArr = new GraphQLList(new GraphQLNonNull(colType));\n\n // IdFilter omits like/notLike/ilike/notIlike — they are nonsensical on UUIDs.\n const isId = genericName === 'Id';\n\n const baseFields = {\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 ...(isId\n ? {}\n : {\n like: { type: GraphQLString },\n notLike: { type: GraphQLString },\n ilike: { type: GraphQLString },\n notIlike: { type: GraphQLString },\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 const orType = new GraphQLInputObjectType({\n name: `${genericName}FilterOr`,\n fields: { ...baseFields },\n });\n\n const mainType = new GraphQLInputObjectType({\n name: `${genericName}Filter`,\n fields: {\n ...baseFields,\n OR: {\n type: new GraphQLList(new GraphQLNonNull(orType)),\n },\n },\n });\n\n cacheCtx.genericFilterCache.set(genericName, { main: mainType, or: orType });\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\nconst generateTableOrderTypeCached = (\n table: Table,\n tableName: string,\n typeNameMapper: TypeNameMapper | undefined,\n cacheCtx: TypeCacheCtx,\n) => {\n if (cacheCtx.orderTypeCache.has(table)) {\n return cacheCtx.orderTypeCache.get(table)!;\n }\n\n const orderColumns = generateTableOrderCached(table);\n const order = new GraphQLInputObjectType({\n name: `${resolveTypeName(tableName, typeNameMapper)}OrderBy`,\n fields: orderColumns,\n });\n\n cacheCtx.orderTypeCache.set(table, order);\n\n return order;\n};\n\n/**\n * Relations that can be expressed as a correlated `EXISTS` subquery. Many-to-many relations\n * declared with `.through()` need a junction join that the filter builder doesn't emit yet,\n * so they're left out of the filter input entirely — a missing field is a clean GraphQL\n * validation error, whereas a silently ignored filter would return too many rows.\n */\nconst isFilterableRelation = (relation: Relation<string>): boolean => !(relation as any).through;\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 || !isFilterableRelation(relation)) {\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 const orFilters = new GraphQLInputObjectType({\n name: `${resolveTypeName(tableName, typeNameMapper)}FiltersOr`,\n fields: buildFields,\n });\n\n const filters = new GraphQLInputObjectType({\n name: `${resolveTypeName(tableName, typeNameMapper)}Filters`,\n fields: () => ({\n ...buildFields(),\n OR: {\n type: new GraphQLList(new GraphQLNonNull(orFilters)),\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 ? generateTableOrderTypeCached(table, tableName, typeNameMapper, cacheCtx) : 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 rawRelationFields.push([\n relationName,\n {\n type: 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/**\n * Column name / direction pairs from an `orderBy` argument, highest priority first. Split out\n * of `extractOrderBy` so the same ordering can be rebuilt against a subquery's fields, where\n * there is no `Table` to read columns from.\n */\nexport const orderByEntries = (orderArgs: Record<string, any>): [string, 'asc' | 'desc'][] =>\n Object.entries(orderArgs)\n .sort((a, b) => (b[1]?.priority ?? 0) - (a[1]?.priority ?? 0))\n .filter(([, config]) => config)\n .map(([column, config]) => [column, config.direction]);\n\nexport const extractOrderBy = <TTable extends Table, TArgs extends OrderByArgs<any> = OrderByArgs<TTable>>(\n table: TTable,\n orderArgs: TArgs,\n): SQL[] =>\n orderByEntries(orderArgs).map(([column, direction]) =>\n direction === 'asc' ? asc(getColumns(table)[column]!) : desc(getColumns(table)[column]!),\n );\n\nexport const extractFiltersColumn = <TColumn extends Column>(\n column: TColumn,\n columnName: string,\n operators: FilterColumnOperators<TColumn>,\n): SQL | undefined => {\n if (!operators.OR?.length) {\n delete operators.OR;\n }\n\n const entries = Object.entries(operators as FilterColumnOperatorsCore<TColumn>);\n\n if (operators.OR) {\n if (entries.length > 1) {\n throw new GraphQLError(`WHERE ${columnName}: Cannot specify both fields and 'OR' in column operators!`);\n }\n\n const variants = [] as SQL[];\n\n for (const variant of operators.OR) {\n const extracted = extractFiltersColumn(column, columnName, variant);\n\n if (extracted) {\n variants.push(extracted);\n }\n }\n\n return variants.length ? (variants.length > 1 ? or(...variants) : variants[0]) : undefined;\n }\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 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 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 in nullableOps) {\n variants.push(nullableOps[operatorName]!(column));\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 * Builds one `[NOT] EXISTS (SELECT 1 FROM target alias WHERE …)` for a relation filter.\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 || !isFilterableRelation(relation)) {\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 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 // 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 ${getTableAsAliasSQL(aliasedTarget)} 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 ${getTableAsAliasSQL(aliasedTarget)} where ${condition})`\n : sql`exists (select 1 from ${getTableAsAliasSQL(aliasedTarget)} 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 variants: SQL[] = [];\n for (const mode of ['some', 'none', 'every'] as const) {\n const inner = value[mode];\n if (inner === undefined || inner === null) {\n continue;\n }\n\n const extracted = buildRelationExists(parentTable, relationName, relEntry, inner, mode, 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 if (!filters.OR?.length) {\n delete filters.OR;\n }\n\n const entries = Object.entries(filters as FiltersCore<TTable>);\n if (!entries.length) {\n return;\n }\n\n if (filters.OR) {\n if (entries.length > 1) {\n throw new GraphQLError(`WHERE ${tableName}: Cannot specify both fields and 'OR' in table filters!`);\n }\n\n const variants = [] as SQL[];\n\n for (const variant of filters.OR) {\n const extracted = extractFilters(table, tableName, variant, relationCtx);\n if (extracted) {\n variants.push(extracted);\n }\n }\n\n return variants.length ? (variants.length > 1 ? or(...variants) : variants[0]) : undefined;\n }\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 const extracted = column\n ? extractFiltersColumn(column, fieldName, operators)\n : relations?.[fieldName] && relationCtx\n ? extractRelationFilter(table, fieldName, relations[fieldName]!, operators as any, relationCtx)\n : undefined;\n\n if (extracted) {\n variants.push(extracted);\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) => extractOrderBy(aliasedTable, relationArgs.orderBy!)\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.map(([column, direction]) => (direction === 'asc' ? asc(cols[column]!) : desc(cols[column]!))),\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.map(([column, direction]) => (direction === 'asc' ? asc(sub[column]) : desc(sub[column]))),\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 createArrayFieldName: string;\n createSingleFieldName: string;\n upsertArrayFieldName: string;\n upsertSingleFieldName: string;\n updateFieldName: string;\n deleteFieldName: 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 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 return {\n typeName,\n listFieldName,\n singleFieldName,\n aggregateFieldName,\n createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n deleteFieldName,\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) : []),\n ...primaryKeyOrderExprs(aliasedTable, pkNames!),\n ]\n : orderBy\n ? (aliasedTable: Table) => extractOrderBy(aliasedTable, orderBy)\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 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 { GraphQLBigIntString, GraphQLDate, GraphQLDateTime, GraphQLJSON, GraphQLUUID } 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 const { type: baseType } = 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 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 // integer().array() columns keep columnType=PgInteger but gain a `dimensions` property.\n // drizzle-orm's extractExtendedColumnType still returns 'number' for them, so we\n // detect the array wrapper here and recurse with a synthetic base-int scalar.\n const dims = (column as any).dimensions as number | undefined;\n if (dims !== undefined && dims > 0) {\n const baseDesc = is(column, PgInteger) || is(column, PgSerial) ? 'Integer' : 'Float';\n const baseType = baseDesc === 'Integer' ? GraphQLInt : GraphQLFloat;\n return {\n type: new GraphQLList(new GraphQLNonNull(baseType)),\n description: `Array<${baseDesc}>`,\n };\n }\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","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\nexport { GraphQLDate, GraphQLDateTime, GraphQLJSON, GraphQLUUID };\n","// @ts-nocheck — vendored file, drizzle-orm 1.0 type compat not guaranteed\nimport { is, One, type Table } from 'drizzle-orm';\nimport { getTableConfig, type MySqlDatabase, MySqlTable } from 'drizzle-orm/mysql-core';\nimport type { RelationalQueryBuilder } from 'drizzle-orm/mysql-core/query-builders/query';\nimport type { GraphQLFieldConfig, GraphQLFieldConfigArgumentMap, ThunkObjMap } from 'graphql';\nimport {\n GraphQLBoolean,\n GraphQLError,\n type GraphQLInputObjectType,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\n\nimport type { GeneratedEntities } from '../../types.ts';\nimport {\n aggregateFieldComplexity,\n attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createRelationResolverFactory,\n extractFilters,\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 { createRelationAggregateFactory, generateAggregate, generateAggregateTypes } 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 filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryArgs = {\n set: {\n type: new GraphQLNonNull(setArgs),\n },\n where: {\n type: 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 executor = resolveExecutor(db, context);\n let query = executor.update(table).set(input);\n if (where) {\n const filters = extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName));\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 filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: 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 executor = resolveExecutor(db, context);\n let query = executor.delete(table);\n if (where) {\n const filters = extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName));\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 createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n deleteFieldName,\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 filterCtx,\n )\n : undefined;\n const deleteGenerated = features.delete\n ? generateDelete(db, tableName, schema[tableName] as MySqlTable, tableFilters, deleteFieldName, filterCtx)\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 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 for (const generated of [\n insertArrGenerated,\n insertSingleGenerated,\n upsertArrGenerated,\n upsertSingleGenerated,\n updateGenerated,\n deleteGenerated,\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 }\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 extractExtendedColumnType,\n getColumns,\n inArray,\n max,\n min,\n sum,\n type Table,\n} from 'drizzle-orm';\nimport {\n GraphQLFloat,\n type GraphQLInputObjectType,\n GraphQLInt,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n} from 'graphql';\nimport type { ResolveTree } from 'graphql-parse-resolve-info';\nimport { parseResolveInfo } from 'graphql-parse-resolve-info';\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 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 = (info: any, target: AggregateTarget): AggregateRequest => {\n const parsedInfo = parseResolveInfo(info, { deep: true }) as ResolveTree;\n const selectionTree = parsedInfo.fieldsByTypeName[`${target.typeName}Aggregate`] ?? {};\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","// @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 attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createRelationResolverFactory,\n eagerLoadMutationRelations,\n excludedColumnRef,\n extractFilters,\n extractOrderBy,\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 { createRelationAggregateFactory, generateAggregate, generateAggregateTypes } 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),\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)) 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 typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryArgs = {\n set: {\n type: new GraphQLNonNull(setArgs),\n },\n where: {\n type: 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 executor = resolveExecutor(db, context);\n let query = executor.update(table).set(input);\n if (where) {\n const filters = extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName));\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) 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 generateDelete = (\n db: PgAsyncDatabase<any, any, any>,\n tableName: string,\n table: PgTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n filterCtx?: RelationFilterBase,\n selectionCtx?: SelectionCtx,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: 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 executor = resolveExecutor(db, context);\n let query = executor.delete(table);\n if (where) {\n const filters = extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName));\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) as any;\n\n const result = await query;\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 createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n deleteFieldName,\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 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 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 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 (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 (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.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 }\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 attachTargetPrimaryKeys,\n buildNamedRelations,\n computeResolverFieldNames,\n createRelationResolverFactory,\n eagerLoadMutationRelations,\n excludedColumnRef,\n extractFilters,\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 { createRelationAggregateFactory, generateAggregate, generateAggregateTypes } 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 typeNameMapper?: TypeNameMapper,\n filterCtx?: RelationFilterBase,\n): CreatedResolver => {\n const queryArgs = {\n set: {\n type: new GraphQLNonNull(setArgs),\n },\n where: {\n type: 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 executor = resolveExecutor(db, context);\n let query = executor.update(table).set(input);\n if (where) {\n const filters = extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName));\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) 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 generateDelete = (\n db: BaseSQLiteDatabase<any, any, any, any>,\n tableName: string,\n table: SQLiteTable,\n filterArgs: GraphQLInputObjectType,\n fieldName: string,\n typeName: string,\n filterCtx?: RelationFilterBase,\n selectionCtx?: SelectionCtx,\n): CreatedResolver => {\n const queryArgs = {\n where: {\n type: 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 executor = resolveExecutor(db, context);\n let query = executor.delete(table);\n if (where) {\n const filters = extractFilters(table, tableName, where, relationFilterCtx(filterCtx, tableName));\n query = query.where(filters) as any;\n }\n\n query = query.returning(columns) as any;\n\n const result = await query;\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 createArrayFieldName,\n createSingleFieldName,\n upsertArrayFieldName,\n upsertSingleFieldName,\n updateFieldName,\n deleteFieldName,\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 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 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 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 (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 (deleteGenerated) {\n mutations[deleteGenerated.name] = {\n type: arrTableItemOutput,\n args: deleteGenerated.args,\n resolve: deleteGenerated.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 }\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":";;;;;;;;;;;;;;;;;;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AAW,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_drizzle_orm","import_graphql","import_graphql","baseType","desc","variants","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"]}
|