import { type CompatibleTypes, completeValue, type ExposeNullability, type FieldKind, type FieldRef, fieldBuilderCloneKey, type InferredFieldOptionKeys, type InputFieldMap, type InterfaceParam, isThenable, type MaybePromise, type NormalizeArgs, ObjectRef, type PluginName, PothosSchemaError, RootFieldBuilder, type SchemaTypes, type ShapeFromTypeParam, type TypeParam, } from '@pothos/core'; import { type SelectedFieldNode, selectedFieldNames } from '@pothos/selection-mapper'; import { and, type BuildQueryResult, type DBQueryConfig, type InferSelectModel, is, Many, type Relation, relationsFilterToSQL, SQL, type SQLChunk, type Table, type TableRelationalConfig, type TablesRelationalConfig, } from 'drizzle-orm'; import type { GraphQLResolveInfo } from 'graphql'; import type { DrizzleRef } from './interface-ref.js'; import type { DrizzleConnectionShape, ListRelation, PathInfo, RelatedConnectionOptions, RelatedCountOptions, RelatedFieldOptions, RelatedSelectionFieldOptions, ShapeFromConnection, TypesForRelation, VariantFieldOptions, } from './types.js'; import { getClient, getSchemaConfig } from './utils/config.js'; import { type DrizzleCursorConnectionQueryOptions, drizzleCursorConnectionQuery, getCursorFormatter, wrapConnectionResult, } from './utils/cursors.js'; import { pathInfoFor, plannedPosition } from './utils/path-info.js'; import { getRefFromModel } from './utils/refs.js'; import { buildRelationFilter, type RelationQueryBuilder } from './utils/relation-filter.js'; import type { SelectionMap } from './utils/selections.js'; import { normalizeSQL } from './utils/sql.js'; // Workaround for FieldKind not being extended on Builder classes const RootBuilder: { new ( builder: PothosSchemaTypes.SchemaBuilder, kind: FieldKind, graphqlKind: PothosSchemaTypes.PothosKindToGraphQLType[FieldKind], ): PothosSchemaTypes.RootFieldBuilder; } = RootFieldBuilder as never; type ContextForAuth = PothosSchemaTypes.ScopeAuthContextForAuth extends { Context: infer T; } ? T extends object ? T : object : object; type FieldAuthScopes = PothosSchemaTypes.ScopeAuthFieldAuthScopes extends { Scopes: infer T; } ? T : never; // Older Drizzle declarations omit the relational config parameters supported at runtime. // Supported versions return either SQL or an object containing optional SQL chunks. type RelationsFilterToSQL = ( table: Table, filter: unknown, tableRelations?: TableRelationalConfig['relations'], tablesRelations?: TablesRelationalConfig, ) => SQL | { sql?: SQLChunk[] } | undefined; export class DrizzleObjectFieldBuilder< Types extends SchemaTypes, TableConfig extends TableRelationalConfig, Shape, ExposableShape = InferSelectModel>, > extends RootBuilder { exposeBoolean = this.createExpose('Boolean'); exposeFloat = this.createExpose('Float'); exposeInt = this.createExpose('Int'); exposeID = this.createExpose('ID'); exposeString = this.createExpose('String'); exposeBooleanList = this.createExpose(['Boolean']); exposeFloatList = this.createExpose(['Float']); exposeIntList = this.createExpose(['Int']); exposeIDList = this.createExpose(['ID']); exposeStringList = this.createExpose(['String']); declare withAuth: 'scopeAuth' extends PluginName ? >>( scopes: Scopes, ) => DrizzleObjectFieldBuilder< Omit & { Context: ContextForAuth }, TableConfig, Shape, ExposableShape > : '@pothos/plugin-scope-auth is required to use this method'; table: string; typename: string; relatedConnection: 'relay' extends PluginName ? < // `& keyof` so errors list the valid names instead of the type alias. Field extends ListRelation & keyof TableConfig['relations'], Nullable extends boolean, Args extends InputFieldMap, const ConnectionInterfaces extends InterfaceParam[] = [], const EdgeInterfaces extends InterfaceParam[] = [], Type = unknown, Shape = // biome-ignore lint/suspicious/noExplicitAny: generic match Type extends DrizzleRef ? Type['$inferType'] : TypesForRelation, >( field: Field, ...args: NormalizeArgs< [ options: RelatedConnectionOptions< Types, Shape, TableConfig, Field, Nullable, Args, Type >, connectionOptions: | ObjectRef< Types, ShapeFromConnection> > | PothosSchemaTypes.ConnectionObjectOptions< Types, ObjectRef, false, false, DrizzleConnectionShape, ConnectionInterfaces >, edgeOptions: | ObjectRef< Types, { cursor: string; node?: Shape | null | undefined; } > | PothosSchemaTypes.ConnectionEdgeObjectOptions< Types, ObjectRef, false, DrizzleConnectionShape, EdgeInterfaces >, ], 0 > ) => FieldRef< Types, ShapeFromConnection> > : '@pothos/plugin-relay is required to use this method' = function relatedConnection( this: DrizzleObjectFieldBuilder, name: string, { maxSize = this.builder.options.drizzle?.maxConnectionSize, defaultSize = this.builder.options.drizzle?.defaultConnectionSize, query, extensions, description, totalCount, ...options }: { type?: ObjectRef; maxSize?: number | ((args: {}, ctx: {}) => number); defaultSize?: number | ((args: {}, ctx: {}) => number); extensions?: {}; description?: string; query?: ((args: {}, ctx: {}) => {}) | {}; totalCount?: boolean; } = {}, connectionOptions = {}, edgeOptions = {}, ) { const schemaConfig = getSchemaConfig(this.builder); const relationField = schemaConfig.relations?.[this.table].relations[name as string]; const relatedTable = schemaConfig.relations[relationField.targetTableName]; if (!relatedTable) { throw new PothosSchemaError( `Could not find relation ${name as string} on table ${this.table}`, ); } const ref = options.type ?? getRefFromModel(relationField.targetTableName, this.builder); let typeName: string | undefined; const filterTotalCount = this.builder.options.drizzle?.filterConnectionTotalCount !== false; // The count for `totalCount` matches the connection's own filter: what the relation selects // (including a `through` join and the relation's own `where`) plus the `where` from the // field's `query`, so the count agrees with the rows being paginated. The `where` goes // through the same `relationsFilterToSQL` the relational query builder puts it through, and // `countRows` combines the two in the same order, so the count's predicate is the page // query's predicate less the limit and the keyset clauses. const buildCount = ( client: RelationQueryBuilder, parentTable: TableConfig['table'], where?: unknown, ): SQL => { const { countRows } = buildRelationFilter( client, relationField as Relation, parentTable as Table, ); if (!where || !filterTotalCount) { return countRows(); } const filter = (relationsFilterToSQL as RelationsFilterToSQL)( relatedTable.table as Table, where, relatedTable.relations, schemaConfig.relations, ); return countRows(normalizeSQL(is(filter, SQL) ? filter : filter?.sql)); }; interface ConnectionFieldQuery { limit?: number; orderBy?: unknown; where?: SQL; columns?: Record; extras?: DrizzleCursorConnectionQueryOptions['extras']; } // The field's `query` may be async, so the result is a promise when it is. The `PathInfo` is // provided by the adapter, and only read for a callback that takes one. const resolveFieldQuery = ( args: PothosSchemaTypes.DefaultConnectionArguments, ctx: {}, pathInfo?: PathInfo, ): MaybePromise => completeValue( (typeof query === 'function' ? ( query as ( args: {}, ctx: {}, pathInfo?: PathInfo, ) => MaybePromise<{} | null | undefined> )(args, ctx, pathInfo) : query) as MaybePromise, orEmpty, ); const getQuery = ( args: PothosSchemaTypes.DefaultConnectionArguments, ctx: {}, { limit, orderBy, where, ...fieldQuery }: ConnectionFieldQuery, ) => { const { cursorFields, columns, ...connectionQuery } = drizzleCursorConnectionQuery({ ctx, maxSize, defaultSize, args, orderBy: (typeof orderBy === 'function' ? orderBy(relatedTable.table) : orderBy) ?? getSchemaConfig(this.builder).getPrimaryKey(relationField.targetTableName), extras: fieldQuery.extras, where, config: schemaConfig, table: relatedTable, }); return { select: { ...fieldQuery, ...connectionQuery, columns: { ...fieldQuery.columns, ...columns, }, limit: Math.abs(limit ?? connectionQuery.limit), }, cursorFields, }; }; const countKey = `_${name as string}_count`; // What the document asks of this connection, read the way the planner reads it (through // fragments, directives, and a wrapping type), so the resolve side agrees with the plan. The // selection is read once per request and shared by every parent row. const connectionSelectionFromNames = (selected: ReadonlySet) => { const hasTotalCount = !!totalCount && selected.has('totalCount'); for (const field of selected) { if (field !== 'totalCount' && field !== '__typename') { return { hasTotalCount, totalCountOnly: false }; } } return { hasTotalCount, totalCountOnly: hasTotalCount }; }; const connectionSelection = (context: object, info: GraphQLResolveInfo) => connectionSelectionFromNames(selectedFieldNames(context, info)); // Built once per field, so a synchronous plan allocates nothing beyond the map itself. const selectConnection = ( fieldQuery: ConnectionFieldQuery, nested: SelectionMap | undefined, context: object, hasTotalCount: boolean, totalCountOnly: boolean, ) => { const countSelection = { [countKey]: (parent: TableConfig['table']) => buildCount(getClient(this.builder, context), parent, fieldQuery.where), }; if (totalCountOnly) { return { columns: {}, with: {}, extras: countSelection, }; } return { columns: {}, with: { [name]: nested, }, extras: hasTotalCount ? countSelection : {}, }; }; const relationSelect = ( args: object, context: object, nestedQuery: (query: unknown, path?: unknown) => { select?: object }, getSelection: SelectedFieldNode, pathInfo: PathInfo, ) => { typeName ??= this.builder.configStore.getTypeConfig(ref).name; const { hasTotalCount, totalCountOnly } = connectionSelectionFromNames(getSelection()); const fieldQuery = resolveFieldQuery(args, context, pathInfo); // The nested plan starts now, with a query that waits for the field's `query` when that is // async, so every callback beneath the connection runs in the same tick. const nested = totalCountOnly ? undefined : (nestedQuery( isThenable(fieldQuery) ? fieldQuery.then((resolved) => getQuery(args, context, resolved).select) : getQuery(args, context, fieldQuery).select, { getType: () => typeName!, paths: [[{ name: 'nodes' }], [{ name: 'edges' }, { name: 'node' }]], }, ) as MaybePromise); return isThenable(fieldQuery) || isThenable(nested) ? Promise.all([fieldQuery, nested]).then(([resolvedQuery, resolvedNested]) => selectConnection(resolvedQuery, resolvedNested, context, hasTotalCount, totalCountOnly), ) : selectConnection(fieldQuery, nested, context, hasTotalCount, totalCountOnly); }; // The loaded path, per parent row: the rows are on the parent, only the page is needed. const resolveLoaded = ( fieldQuery: ConnectionFieldQuery, parent: unknown, args: PothosSchemaTypes.DefaultConnectionArguments, context: {}, countValue: number | undefined, ) => { const { select, cursorFields } = getQuery(args, context, fieldQuery); return wrapConnectionResult( (parent as Record)[name] as readonly {}[], args, select.limit, getCursorFormatter(cursorFields, schemaConfig), undefined, parent, countValue, ); }; const fieldRef = ( this as unknown as { connection: (...args: unknown[]) => FieldRef; } ).connection( { ...options, extensions: { ...extensions, pothosDrizzleSelect: relationSelect, pothosDrizzleLoaded: ( value: Record, info: GraphQLResolveInfo, context: object, ) => { const { hasTotalCount, totalCountOnly } = connectionSelection(context, info); return ( (!hasTotalCount || value[countKey] !== undefined) && (totalCountOnly || value[name as string] !== undefined) ); }, }, description, type: ref, resolve: ( parent: unknown, args: PothosSchemaTypes.DefaultConnectionArguments, context: {}, info: GraphQLResolveInfo, ) => { const parentRecord = parent as Record; const countValue = totalCount ? (parentRecord[countKey] as number | undefined) : undefined; // Only totalCount was requested: the relation was never selected, so skip the cursors. if (connectionSelection(context, info).totalCountOnly) { return { parent, args, totalCount: countValue, edges: [], pageInfo: { startCursor: null, endCursor: null, hasPreviousPage: false, hasNextPage: false, }, }; } // The position the rows on `parent` were planned at, recorded by the field's gate for // this execution (or by the reload that fetched `parent`), so a `query` that branches on // its path pages the rows it selected. const fieldQuery = resolveFieldQuery(args, context, pathInfoFor(plannedPosition(info))); return isThenable(fieldQuery) ? fieldQuery.then((resolved) => resolveLoaded(resolved, parent, args, context, countValue), ) : resolveLoaded(fieldQuery, parent, args, context, countValue); }, }, connectionOptions instanceof ObjectRef ? connectionOptions : { ...connectionOptions, fields: totalCount ? ( t: PothosSchemaTypes.ObjectFieldBuilder, ) => ({ totalCount: t.int({ nullable: false, extensions: { pothosDrizzleTotalCount: true, }, resolve: (connection) => connection.totalCount, }), ...(connectionOptions as { fields?: (t: unknown) => {} }).fields?.(t), }) : (connectionOptions as { fields: undefined }).fields, }, edgeOptions, ); return fieldRef; } as never; constructor( typename: string, builder: PothosSchemaTypes.SchemaBuilder, table: string, graphqlKind: PothosSchemaTypes.PothosKindToGraphQLType[FieldKind] = 'Object', ) { super(builder, 'DrizzleObject', graphqlKind); this.table = table; this.typename = typename; } override [fieldBuilderCloneKey](): this { return new DrizzleObjectFieldBuilder( this.typename, this.builder, this.table, this.graphqlKind, ) as this; } variant< // biome-ignore lint/suspicious/noExplicitAny: a ref from before `withAuth` replaced the context Variant extends DrizzleRef | TableConfig['name'], Args extends InputFieldMap, Nullable, ResolveShape, ResolveReturn, >( variant: Variant, ...allArgs: NormalizeArgs< [ options: VariantFieldOptions< Types, TableConfig['name'] & keyof Types['DrizzleRelations'], Variant, Args, Nullable, Shape, ResolveShape, ResolveReturn >, ] > ): FieldRef { const [{ isNull, nullable, ...options } = {} as never] = allArgs; const ref: DrizzleRef = typeof variant === 'string' ? getRefFromModel(variant, this.builder) : variant; const selfSelect = ( _args: object, _context: object, nestedQuery: (query: unknown) => unknown, ) => nestedQuery(options.select ?? {}); return this.field({ ...(options as {}), type: ref, extensions: { ...options?.extensions, pothosDrizzleSelect: selfSelect, }, nullable: nullable ?? !!isNull, resolve: isNull ? (parent, args, context, info) => { const parentIsNull = isNull(parent as never, args as never, context, info); if (parentIsNull) { if (isThenable(parentIsNull)) { return parentIsNull.then((resolved) => (resolved ? null : parent)) as never; } return null as never; } return parent as never; } : (parent) => parent as never, }) as FieldRef; } relation< Field extends keyof TableConfig['relations'], Nullable extends boolean, Args extends InputFieldMap, ResolveReturnShape, >( name: Field, ...allArgs: NormalizeArgs< [ options: RelatedFieldOptions< Types, TableConfig, Field, Nullable, Args, ResolveReturnShape, Shape >, ] > ): FieldRef, 'Object'> { const [options = {} as never] = allArgs; const schemaConfig = getSchemaConfig(this.builder); const relationField = schemaConfig.relations?.[this.table].relations[name as string]; const relatedTable = schemaConfig.relations[relationField.targetTableName]; if (!relatedTable) { throw new PothosSchemaError( `Could not find relation ${name as string} on table ${this.table}`, ); } const ref = options.type ?? getRefFromModel(relatedTable.name, this.builder); const { query = {}, extensions, ...rest } = options; // Built once per field: the select allocates nothing when the nested selection is sync. The // nested selection already carries the field's `query` (it is merged into the child first), // so nothing is spread over it. const selectRelation = (nested: unknown) => ({ columns: {}, with: { [name]: nested } }); const relationSelect = ( args: object, context: object, nestedQuery: (query: unknown) => {}, _resolveSelection: unknown, pathInfo: PathInfo, ) => completeValue( nestedQuery( typeof query === 'function' ? (query as (args: {}, context: {}, pathInfo?: PathInfo) => {})(args, context, pathInfo) : query, ), selectRelation, ); return this.field({ ...(rest as {}), type: relationField instanceof Many ? [ref] : ref, extensions: { ...extensions, pothosDrizzleSelect: relationSelect as never, pothosDrizzleLoaded: (value: Record) => value[name as string] !== undefined, }, resolve: (parent: Record) => parent[name as string], } as never) as never; } relatedField< Field extends keyof TableConfig['relations'], Type extends TypeParam, Nullable extends boolean, Args extends InputFieldMap, Select extends DBQueryConfig<'many', Types['DrizzleRelations'], TableConfig>, ShapeWithSelection = Shape & BuildQueryResult, >( relationName: Field, options: RelatedSelectionFieldOptions< Types, TableConfig, Type, Nullable, Args, Select, ShapeWithSelection >, ): FieldRef, 'DrizzleObject'> { const schemaConfig = getSchemaConfig(this.builder); const relationField = schemaConfig.relations?.[this.table].relations[relationName as string]; if (!relationField) { throw new PothosSchemaError( `Could not find relation ${relationName as string} on table ${this.table}`, ); } // Explicit NOT NULL is required even for primary keys: SQLite permits nullable text and // composite primary keys. Without a total identity the relation filter keeps EXISTS. const targetKey = relationField.throughTable ? schemaConfig .getUniqueConstraints(relationField.targetTableName) .find((columns) => columns.every((column) => column.notNull)) : undefined; const relationSelect = ( args: object, context: Types['Context'], nestedQuery: (query: unknown) => unknown, ) => { const buildFilter = (parentTable: TableConfig['table']): SQL => buildRelationFilter( getClient(this.builder, context), relationField as Relation, parentTable as Table, targetKey, ).filter; return completeValue( options.select(buildFilter as never, args as never, context, nestedQuery as never) as | MaybePromise