import { type ArgumentRef, type CheckAsyncSelection, type DistributeOmit, type FieldKind, type FieldMap, type FieldNullability, type FieldOptionsFromKind, type InferredFieldOptionKeys, type InferredFieldOptionsByKind, type InputFieldMap, type InputFieldsFromShape, type InputShapeFromFields, type InterfaceParam, type InterfaceRef, type InterfaceTypeOptions, type ListResolveValue, type MaybeAsyncSelection, type MaybePromise, type Merge, type Normalize, type ObjectRef, type ObjectTypeOptions, type OutputShape, type OutputType, type SchemaTypes, type ShapeFromTypeParam, type TypeParam, typeBrandKey, } from '@pothos/core'; import type { IndirectInclude, IndirectPathSegment, PathSegment } from '@pothos/selection-mapper'; import type { AnyRelations, BuildQueryResult, Column, DBQueryConfig, Many, Relation, SQL, SQLWrapper, Table, TableRelationalConfig, } from 'drizzle-orm'; import type { FieldNode, GraphQLResolveInfo } from 'graphql'; import type { DrizzleObjectFieldBuilder } from './drizzle-field-builder.js'; import type { DrizzleRef } from './interface-ref.js'; import type { DrizzleRelationsHint } from './utils/refs.js'; import type { SelectionMap } from './utils/selections.js'; /** * A segment of a `path` given to `queryFromInfo` or `nestedSelection`: a field name, or * `{ name, type }` to pin the type the field must be selected under (a fragment on it). */ export type { IndirectInclude, IndirectPathSegment, PathSegment }; export interface FieldPathInfo { field: string; alias: string; parentType: string; isList: boolean; } export interface PathInfo { path: string[]; segments: FieldPathInfo[]; } export type DrizzleClient< TCountSource = Table | SQL | SQLWrapper, TTable = Extract, > = { readonly _: { readonly relations: AnyRelations; }; query: Record< string, { // Each table accepts its own schema-specific config. The loader supplies that config. findMany: (config: never) => PromiseLike[]>; } >; $count: (source: TCountSource, filter?: SQL) => SQL; /** Core SQL construction used for relation predicates and counts; it does not execute a query. */ select: (fields: Record) => { from(table: TTable): { innerJoin(table: TTable, on: SQL): { where: (filter?: SQL) => SQLWrapper }; where: (filter?: SQL) => SQLWrapper; }; }; }; type GetTableConfigFn = (table: TTable) => { primaryKeys: { readonly columns: Column[]; }[]; uniqueConstraints?: { readonly columns: Column[]; }[]; readonly columns: Column[]; }; type AnyRelationTable = Types['DrizzleRelations'][keyof Types['DrizzleRelations']]['table']; // The `client` option only requires each `query` entry to have a `findMany`. Checking the real // client against the `findMany` signature in `DrizzleClient` compares every table's generic // relational `findMany`, which makes setup cost grow with the number of tables. type DrizzleClientForTypes = Omit< DrizzleClient< AnyRelationTable | SQL | SQLWrapper, Table extends AnyRelationTable ? Table : never >, 'query' > & { query: Record; }; type DrizzlePluginBaseOptions = { maxConnectionSize?: number; defaultConnectionSize?: number; skipDeferredFragments?: boolean; /** * When `true` (the default), the `totalCount` of a `relatedConnection` applies the `where` * returned by the field's `query`, so it counts the same rows the connection paginates. Set to * `false` to count every related row regardless of the filter. */ filterConnectionTotalCount?: boolean; }; export type DrizzlePluginOptions = DrizzlePluginBaseOptions & ( | { client: DrizzleClientForTypes; getTableConfig: GetTableConfigFn>; relations?: Types['DrizzleRelations']; } | { client: (ctx: Types['Context']) => DrizzleClientForTypes; getTableConfig: GetTableConfigFn>; relations: Types['DrizzleRelations']; } ); export const drizzleTableName = Symbol.for('Pothos.drizzleTableName'); /** Marks a parent shape with its table name. */ export interface DrizzleTableNameBrand { [drizzleTableName]?: Table; } type NameOrVariant = | { name?: never; variant?: string; } | { name?: string; variant?: never; }; export type DrizzleObjectOptions< Types extends SchemaTypes, Table extends keyof Types['DrizzleRelations'], Shape, Selection, Interfaces extends InterfaceParam[], > = Omit, Shape, Interfaces>, 'fields'> & NameOrVariant & { select?: Selection; fields?: ( t: DrizzleObjectFieldBuilder< Types, Types['DrizzleRelations'][Table], Shape & DrizzleTableNameBrand
>, ) => FieldMap; }; export type DrizzleInterfaceOptions< Types extends SchemaTypes, Table extends keyof Types['DrizzleRelations'], Shape, Selection, Interfaces extends InterfaceParam[], > = Omit, Shape, Interfaces>, 'fields'> & NameOrVariant & { select?: Selection; fields?: ( t: DrizzleObjectFieldBuilder< Types, Types['DrizzleRelations'][Table], Shape & DrizzleTableNameBrand
>, ) => FieldMap; }; export type DrizzleNodeOptions< Types extends SchemaTypes, Table extends keyof Types['DrizzleRelations'], Shape, Selection, Interfaces extends InterfaceParam[], IDColumns, > = NameOrVariant & Omit< | PothosSchemaTypes.ObjectTypeOptions | PothosSchemaTypes.ObjectTypeWithInterfaceOptions, 'fields' | 'isTypeOf' > & { id: Omit< FieldOptionsFromKind< Types, Shape, 'ID', false, {}, 'Object', OutputShape, MaybePromise> >, 'args' | 'nullable' | 'type' | InferredFieldOptionKeys > & { column: IDColumns & ( | Column | Column[] | ((columns: Types['DrizzleRelations'][Table]['table']) => Column | Column[]) ); }; select?: Selection; fields?: ( t: DrizzleObjectFieldBuilder< Types, Types['DrizzleRelations'][Table], Shape & DrizzleTableNameBrand
>, ) => FieldMap; } & NameOrVariant; export type ShapeFromIdColumns< Types extends SchemaTypes, Table extends keyof Types['DrizzleRelations'], IDColumns, > = IDColumns extends Column ? IDColumns['_']['data'] : IDColumns extends Column[] ? { [K in IDColumns[number]['_']['name']]: Extract< IDColumns[number], { _: { name: K } } >['_']['data']; } : // biome-ignore lint/suspicious/noExplicitAny: this is fine IDColumns extends ((...args: any[]) => infer R extends Column | Column[]) ? ShapeFromIdColumns : never; export type DrizzleFieldOptions< Types extends SchemaTypes, ParentShape, Table extends keyof Types['DrizzleRelations'], Type extends TypeParam, Nullable extends FieldNullability, Args extends InputFieldMap, Kind extends FieldKind, ResolveShape, ResolveReturnShape, Param, > = Omit< FieldOptionsFromKind< Types, ParentShape, Type, Nullable, Args, Kind, ResolveShape, ResolveReturnShape >, 'type' | InferredFieldOptionKeys > & { type: Param | DrizzleRelationsHint; resolve: ( query: ( selection?: T & QueryForDrizzleField, ) => Omit & { columns: T extends { columns: infer C extends {} } ? C : {}; extras: { $pothosQueryFor: SQL
; } & (T extends { extra: infer E } ? E : {}); }, parent: ParentShape, args: InputShapeFromFields, ctx: Types['Context'], info: GraphQLResolveInfo, ) => MaybePromise>; }; export type DrizzleFieldWithInputOptions< Types extends SchemaTypes, ParentShape, Table extends keyof Types['DrizzleRelations'], Type extends TypeParam, Nullable extends FieldNullability, Args extends InputFieldMap, Kind extends FieldKind, ResolveShape, ResolveReturnShape, Param, InputName extends string, Fields extends InputFieldMap, ArgRequired extends boolean, > = DistributeOmit< DrizzleFieldOptions< Types, ParentShape, Table, Type, Nullable, Args & { [K in InputName]: ArgumentRef< Types, InputShapeFromFields | (true extends ArgRequired ? never : null | undefined) >; }, Kind, ResolveShape, ResolveReturnShape, Param >, 'args' > & PothosSchemaTypes.FieldWithInputBaseOptions; export type DrizzleObjectFieldOptions< Types extends SchemaTypes, ParentShape, Type extends TypeParam, Nullable extends FieldNullability, Args extends InputFieldMap, Select, ResolveReturnShape, ShapeWithSelection = Normalize< Omit< unknown extends Select ? ParentShape : BuildQueryResult< Types['DrizzleRelations'], ExtractTable, Record & // biome-ignore lint/suspicious/noExplicitAny: this is fine Select extends (...args: any[]) => infer R ? Awaited & { columns: {} } : Select & { columns: {} } > & ParentShape, typeof drizzleTableName > >, > = PothosSchemaTypes.ObjectFieldOptions< Types, ShapeWithSelection, Type, Nullable, Args, ResolveReturnShape > & InferredFieldOptionsByKind< Types, Types['InferredFieldOptionsKind'], ShapeWithSelection, Type, Nullable, Args, ResolveReturnShape > & { /** * What the field needs from its parent row. With `AsyncSelections: true` the function may be * async, and `nestedSelection` is then a promise when a selection beneath it is async, and * must be awaited. */ select?: Select & CheckAsyncSelection & ( | DBQueryConfig<'one', Types['DrizzleRelations'], ExtractTable> | (( args: InputShapeFromFields, ctx: Types['Context'], nestedSelection: NestedSelectionFn, ) => MaybeAsyncSelection< Types, DBQueryConfig<'one', Types['DrizzleRelations'], ExtractTable> >) ); }; /** The table a field's type param names: a drizzle ref, or a list of one. */ export type TableForTypeParam = Type extends [infer Item] ? TableForTypeParam : // biome-ignore lint/suspicious/noExplicitAny: matching against any ref Type extends DrizzleRef ? Table & keyof Types['DrizzleRelations'] : never; /** * The query config for the table a field's type param names (a `many` config for a list field), * or never when the type has no table. */ export type QueryForTypeParam = TableForTypeParam extends infer Table ? [Table] extends [never] ? never : DBQueryConfig< Type extends [unknown] ? 'many' : 'one', Types['DrizzleRelations'], Types['DrizzleRelations'][Table & keyof Types['DrizzleRelations']] > : never; /** * What `nestedSelection` returns: the query config for the field's table, keeping the keys of * the given selection as they were given (so `columns` in it still narrow the parent shape). * With no selection, or `true`, it is the config itself. A field whose type has no table keeps * the selection it was given. */ export type NestedSelectionResult = [ QueryForTypeParam, ] extends [never] ? Selection : Selection extends boolean ? QueryForTypeParam : Normalize, keyof Selection> & Selection>; /** * The callback a field's `select` function plans the selection beneath the field with: `path` * walks a field nested under the field's type, `type` names the type the selection is read as. * It also carries the `PathInfo` of the field being planned. The selection is typed by the * field's table when it has one, so `columns: { title: true }` keeps its literal `true`. */ export type NestedSelectionFn = (< Selection extends | boolean | ([QueryForTypeParam] extends [never] ? {} : QueryForTypeParam) = true, >( selection?: NestedSelectionArg, path?: PathSegment[], type?: string, ) => NestedSelectionResult) & PathInfo; /** * The selection given to `nestedSelection`: the query config itself, or a callback building it * from the field's arguments, the context, and the field's `PathInfo`. A schema with * `AsyncSelections: true` may also give a promise of the config, or an async callback; the result * is typed by the query either way, and is a promise at runtime only when a promise or an async * callback was given, or a selection beneath it is async, and must then be awaited. */ export type NestedSelectionArg = | Selection | (true extends Types['AsyncSelections'] ? PromiseLike : never) | (( args: InputShapeFromFields, ctx: Types['Context'], pathInfo: PathInfo, ) => MaybeAsyncSelection); export type DrizzleFieldSelection = | DBQueryConfig<'one'> | (( args: {}, ctx: object, mergeNestedSelection: ( selection: | SelectionMap | boolean | (( args: object, context: object, pathInfo: PathInfo, ) => MaybePromise>), path?: IndirectInclude | PathSegment[], type?: string, ) => DBQueryConfig<'one'> | boolean, resolveSelection: (path: string[]) => FieldNode | null, pathInfo: PathInfo, ) => MaybePromise); export type ExtractTable = Shape extends { [drizzleTableName]?: keyof Types['DrizzleRelations']; } ? Types['DrizzleRelations'][NonNullable] : never; export type RelatedFieldOptions< Types extends SchemaTypes, Table extends TableRelationalConfig, Field extends keyof Table['relations'], Nullable extends boolean, Args extends InputFieldMap, ResolveReturnShape, Shape, > = Omit< DrizzleObjectFieldOptions< Types, Shape, RefForRelation, Nullable, Args, { columns: {}; with: { [K in Field]: true }; }, ResolveReturnShape >, 'description' | 'select' | 'type' | InferredFieldOptionKeys > & { description?: string | false; // biome-ignore lint/suspicious/noExplicitAny: this is fine type?: DrizzleRef; query?: QueryForField; }; export type VariantFieldOptions< Types extends SchemaTypes, Table extends keyof Types['DrizzleRelations'], // biome-ignore lint/suspicious/noExplicitAny: this is fine Variant extends DrizzleRef | Table, Args extends InputFieldMap, isNull, Shape, ResolveShape, ResolveReturnShape, > = Omit< FieldOptionsFromKind< Types, Shape, // biome-ignore lint/suspicious/noExplicitAny: this is fine Variant extends DrizzleRef ? Variant : DrizzleRef, unknown extends isNull ? false : true, Args, 'DrizzleObject', ResolveShape, ResolveReturnShape >, InferredFieldOptionKeys | 'type' > & { isNull?: isNull & (( parent: Normalize< Omit< unknown extends ResolveShape ? Shape : BuildQueryResult< Types['DrizzleRelations'], ExtractTable, Record & // biome-ignore lint/suspicious/noExplicitAny: this is fine ResolveShape extends (...args: any[]) => infer R ? R & { columns: {} } : ResolveShape & { columns: {} } > & Shape, typeof drizzleTableName > >, args: InputShapeFromFields, context: Types['Context'], info: GraphQLResolveInfo, ) => MaybePromise); }; export type RefForRelation = Rel extends { relationType: 'one'; } ? ObjectRef> : [ObjectRef>]; export type RelatedCountOptions< Types extends SchemaTypes, Shape, Args extends InputFieldMap, Where, > = Omit< PothosSchemaTypes.ObjectFieldOptions, 'type' | InferredFieldOptionKeys > & { where?: | Where | (( args: InputShapeFromFields, context: Types['Context'], ) => MaybeAsyncSelection); }; /** * The options of `t.relatedField`: the ordinary object field options (description, deprecation, * extensions, and what other plugins add), with a `select` that plans a query on the relation. */ export type RelatedSelectionFieldOptions< Types extends SchemaTypes, TableConfig extends TableRelationalConfig, Type extends TypeParam, Nullable extends boolean, Args extends InputFieldMap, Select, ShapeWithSelection, > = Omit< PothosSchemaTypes.ObjectFieldOptions, InferredFieldOptionKeys > & { /** * The query planned on the parent row for this field: `buildFilter` filters the related table * to the parent's rows, `nestedQuery` plans the field's own selection beneath a query. With * `AsyncSelections: true` the function may be async. */ select: (( buildFilter: (parentTable: TableConfig['table']) => SQL, args: InputShapeFromFields, ctx: Types['Context'], nestedQuery: ( query: DBQueryConfig<'many', Types['DrizzleRelations'], TableConfig>, ) => DBQueryConfig<'many', Types['DrizzleRelations'], TableConfig>, ) => MaybeAsyncSelection) & CheckAsyncSelection; resolve: ( parent: ShapeWithSelection, args: InputShapeFromFields, ctx: Types['Context'], info: GraphQLResolveInfo, ) => MaybePromise>; }; export type TypesForRelation = BuildQueryResult< Types['DrizzleRelations'], Types['DrizzleRelations'][Rel['targetTableName']], true >; export type QueryForField< Types extends SchemaTypes, Args extends InputFieldMap, Rel extends Relation, > = ( Rel extends { relationType: 'one'; } ? Omit< DBQueryConfig< 'one', Types['DrizzleRelations'], Types['DrizzleRelations'][Rel['targetTableName']] >, 'columns' | 'extra' | 'with' > : Omit< DBQueryConfig< 'many', Types['DrizzleRelations'], Types['DrizzleRelations'][Rel['targetTableName']] >, 'columns' | 'extra' | 'with' > ) extends infer QueryConfig ? | QueryConfig | (( args: InputShapeFromFields, context: Types['Context'], pathInfo: PathInfo, ) => MaybeAsyncSelection) : never; export type QueryForDrizzleField< Types extends SchemaTypes, Param, Table extends keyof Types['DrizzleRelations'], > = DBQueryConfig< Param extends [unknown] ? 'one' : 'many', Types['DrizzleRelations'], Types['DrizzleRelations'][Table] >; export type QueryForRelatedConnection< Types extends SchemaTypes, Table extends TableRelationalConfig, Args, > = Omit< DBQueryConfig<'many', Types['DrizzleRelations'], Table>, 'limit' | 'offset' | 'columns' | 'extra' | 'with' | 'orderBy' > & { orderBy?: ConnectionOrderBy
| ((table: Table) => ConnectionOrderBy
); } extends infer QueryConfig ? | QueryConfig | (( args: Args, context: Types['Context'], pathInfo: PathInfo, ) => MaybeAsyncSelection) : never; export type QueryForDrizzleConnection< Types extends SchemaTypes, TableConfig extends TableRelationalConfig, > = Omit< DBQueryConfig<'many', Types['DrizzleRelations'], TableConfig>, 'limit' | 'offset' | 'orderBy' > & { orderBy?: ConnectionOrderBy | ((table: Table) => ConnectionOrderBy); }; type TableColumns = T extends { columns: infer Columns } ? Columns : never; /** * The column names of a table config. Reads each table's columns separately, because inferring * them from a union of every table made table name completion slow. */ type TableColumnKeys = [T['table']['_']] extends [ { columns: unknown }, ] ? keyof TableColumns : never; export type ListRelation = { [K in keyof T['relations']]: T['relations'][K] extends Many ? K : never; }[keyof T['relations']]; export type DrizzleConnectionFieldOptions< Types extends SchemaTypes, ParentShape, Type extends // biome-ignore lint/suspicious/noExplicitAny: this is fine DrizzleRef | keyof Types['DrizzleRelations'], TableConfig extends TableRelationalConfig, Param extends OutputType, Nullable extends boolean, Args extends InputFieldMap, ResolveReturnShape, Kind extends FieldKind, > = Omit< FieldOptionsFromKind< Types, ParentShape, Param, Nullable, InputFieldsFromShape & (InputFieldMap extends Args ? {} : Args), Kind, ParentShape, ResolveReturnShape >, 'args' | 'type' | InferredFieldOptionKeys > & Omit< PothosSchemaTypes.ConnectionFieldOptions< Types, ParentShape, Param, Nullable, false, false, Args, ResolveReturnShape >, 'type' | InferredFieldOptionKeys > & (InputShapeFromFields & PothosSchemaTypes.DefaultConnectionArguments extends infer ConnectionArgs ? { type: Type | DrizzleRelationsHint; defaultSize?: number | ((args: ConnectionArgs, ctx: Types['Context']) => number); maxSize?: number | ((args: ConnectionArgs, ctx: Types['Context']) => number); totalCount?: ( parent: ParentShape, args: ConnectionArgs, context: Types['Context'], info: GraphQLResolveInfo, ) => MaybePromise; resolve: ( query: ( selection?: T & QueryForDrizzleConnection, ) => Omit & { columns: T extends { columns: infer C extends {} } ? C : {}; orderBy: { [K in TableColumnKeys]?: 'asc' | 'desc' | undefined; }; extras: { $pothosQueryFor: () => SQL; } & (T extends { extra: infer E } ? E : {}); }, parent: ParentShape, args: ConnectionArgs, context: Types['Context'], info: GraphQLResolveInfo, ) => ShapeFromTypeParam extends infer Shape ? [Shape] extends [[readonly (infer Item)[] | null | undefined]] ? ListResolveValue : MaybePromise : never; } : never); export type RelatedConnectionOptions< Types extends SchemaTypes, Shape, Table extends TableRelationalConfig, Field extends keyof Table['relations'], Nullable extends boolean, Args extends InputFieldMap, Type = unknown, NodeTable extends TableRelationalConfig = Types['DrizzleRelations'][Table['relations'][Field]['targetTableName']], > = Omit< PothosSchemaTypes.ObjectFieldOptions< Types, Shape, ObjectRef, Nullable, InputFieldsFromShape & (InputFieldMap extends Args ? {} : Args), unknown >, 'args' | 'type' | InferredFieldOptionKeys > & Omit< PothosSchemaTypes.ConnectionFieldOptions< Types, Shape, ObjectRef, false, false, Nullable, Args, unknown >, 'type' | InferredFieldOptionKeys > & (InputShapeFromFields & PothosSchemaTypes.DefaultConnectionArguments extends infer ConnectionArgs ? { query?: QueryForRelatedConnection; // biome-ignore lint/suspicious/noExplicitAny: this is fine type?: Type & DrizzleRef; defaultSize?: number | ((args: ConnectionArgs, ctx: Types['Context']) => number); maxSize?: number | ((args: ConnectionArgs, ctx: Types['Context']) => number); totalCount?: boolean; } : never); export type ConnectionOrderBy = | Column | Column[] // keys name a column, or an extra the same query selects. `string & {}` keeps // the column names in autocomplete while letting extra names through | { [K in TableColumnKeys | (string & {})]?: 'asc' | 'desc' | undefined; }; export type ShapeFromConnection = T extends { shape: unknown } ? T['shape'] : never; export type DrizzleConnectionShape< Types extends SchemaTypes, T, Parent, Args extends InputFieldMap, > = Merge< ShapeFromConnection< PothosSchemaTypes.ConnectionShapeHelper > extends infer Shape ? Shape & { parent: Parent; args: InputShapeFromFields & PothosSchemaTypes.DefaultConnectionArguments; } : never > extends infer C ? [C] extends [ { edges: infer Edges; }, ] ? Merge< Omit & { edges: Edges extends Iterable | null | undefined> ? Merge[] : never; } > : C : never; export type WithBrand = T & { [typeBrandKey]: string }; export { DrizzleInterfaceRef, type DrizzleRef } from './interface-ref.js'; export { DrizzleObjectRef } from './object-ref.js';