import { createContextCache } from '@pothos/core'; import { type Node, NodeAdapter, type Plan, type PlayedPlan, type QueryVisitor, type SelectFn, } from '@pothos/selection-mapper'; import { getColumns, type Table, type TableRelationalConfig } from 'drizzle-orm'; import type { GraphQLField, GraphQLNamedType } from 'graphql'; import type { DrizzleFieldSelection, PathInfo } from '../types.js'; import type { PothosDrizzleSchemaConfig } from './config.js'; import { InternalError } from './errors.js'; import { pathInfoFor } from './path-info.js'; import { omitUndefinedKeys, type SelectionMap } from './selections.js'; export type DrizzleNode = Node; export type DrizzlePlan = Plan; export type DrizzlePlayedPlan = PlayedPlan; type DrizzleVisitor = QueryVisitor; /** A map without `columns`: every column. Shared and never mutated. */ const ALL: SelectionMap = Object.freeze({}); /** * How drizzle selections (`DBQueryConfig`: `columns`, `with`, `extras` and query arguments) read * onto the shared query tree, and how a node is written back. A node whose columns are `null` * selects every column; a named-column node always adds the table's primary key so rows can be * matched back to their parent. * * The merge, compare and conflict rules are `NodeAdapter`'s: this is the schema side, the key * loop and `toQuery`. The schema config every one of them needs is the adapter's own state. */ export class DrizzleAdapter extends NodeAdapter { override skipDeferredFragments: boolean; private readonly fieldSelections = new WeakMap< GraphQLField, SelectFn >(); constructor(private readonly config: PothosDrizzleSchemaConfig) { super(); this.skipDeferredFragments = config.skipDeferredFragments; } // Set by drizzleObject/drizzleInterface and propagated to implementing types by onTypeConfig. modelFor(type: GraphQLNamedType) { return type.extensions?.pothosDrizzleTable as TableRelationalConfig | undefined; } typeSelection(type: GraphQLNamedType) { // schema-builder stores `{ columns: {}, ...select }`, or `true` for every column. const selection = type.extensions?.pothosDrizzleSelect as SelectionMap | true | undefined; return selection === true ? ALL : selection || undefined; } fieldSelection(field: GraphQLField) { const selection = field.extensions?.pothosDrizzleSelect as DrizzleFieldSelection | undefined; if (typeof selection !== 'function') { return selection || undefined; } let compiled = this.fieldSelections.get(field); if (!compiled) { compiled = (args, context, nested, selected, position) => { // Keep the public metadata at the adapter boundary. Static query objects do not need // either path array; callbacks that inspect metadata build them once per invocation. let resolvedPath: PathInfo | undefined; const pathInfo: PathInfo = { get path() { resolvedPath ??= pathInfoFor(position)!; return resolvedPath.path; }, get segments() { resolvedPath ??= pathInfoFor(position)!; return resolvedPath.segments; }, }; return selection( args, context, (query, path, type) => nested( // The public API also accepts false, which the walker treats as an empty seed. (typeof query === 'function' ? query(args, context, pathInfo) : query) as Parameters< typeof nested >[0], path, type, ), selected, pathInfo, ); }; this.fieldSelections.set(field, compiled); } return compiled; } visitQuery( { columns, with: withSelection, extras, ...args }: SelectionMap, model: TableRelationalConfig, visit: DrizzleVisitor, ) { this.readRelations(withSelection, model, visit); visit.args(omitUndefinedKeys(args)); for (const key of Object.keys(extras ?? {})) { visit.computed(key, extras![key]); } if (!columns) { // No `columns` means every column, which a node never goes back from. visit.allColumns(); return; } const selected = Object.keys(columns).filter((key) => columns[key]); if (selected.length > 0) { for (const key of selected) { visit.column(key); } } else if (Object.values(columns).some((value) => value === false)) { // An exclusion-only projection selects every other column. Resolve it before // merging so another field can still request a column excluded here. for (const key of Object.keys(getColumns(model.table as Table))) { if (columns[key] !== false) { visit.column(key); } } } } /** * Drizzle's `extras` are functions, compared by identity: the inherited deep-equal would let * two different functions computing the same shape merge. */ override computedConflicts(computed: ReadonlyMap, name: string, value: unknown) { return computed.has(name) && computed.get(name) !== value; } toQuery(node: DrizzleNode): SelectionMap { // `columns` stays present (as undefined) for an every-column node: it is what callers // spreading or comparing the query have always seen. const query: SelectionMap & { with: Record; extras: Record; } = { ...node.args, columns: undefined, with: {}, extras: {} }; if (node.columns) { query.columns = {}; for (const column of node.columns) { query.columns[column] = true; } // Read when a row is reloaded. A table without a key cannot be reloaded, with or without it. for (const column of this.config.findPrimaryKey(node.model.name) ?? []) { query.columns[this.config.columnToTsName(column)] = true; } } for (const [key, value] of node.computed) { query.extras[key] = value as never; } for (const [key, child] of node.relations) { query.with[key] = this.toQuery(child); } return query; } /** The keys of a `with` map, resolved to the tables they target. */ private readRelations( withSelection: Record | undefined, model: TableRelationalConfig, visit: DrizzleVisitor, ) { for (const key of Object.keys(withSelection ?? {})) { const value = withSelection![key]; if (!value) { continue; } const relationConfig = model.relations[key]; if (!relationConfig) { throw new UnknownRelationError(key, model.name); } visit.relation( key, this.config.relations[relationConfig.targetTableName], value === true ? ALL : (value as SelectionMap), ); } } } /** A select naming a relation its table does not have. */ export class UnknownRelationError extends InternalError { constructor( readonly relation: string, readonly table: string, ) { super(`Relation ${relation} does not exist on ${table}`); } } export const drizzleAdapter = createContextCache( (config: PothosDrizzleSchemaConfig) => new DrizzleAdapter(config), );