import type { EnvironmentFor } from '../lib/environment.ts'; import { AlgebraicType, ProductType, type AlgebraicTypeVariants, type Deserializer, type Serializer, } from '../lib/algebraic_type.ts'; import type { Identity } from '../lib/identity.ts'; import type { OptionAlgebraicType } from '../lib/option.ts'; import type { ParamsObj } from '../lib/reducers.ts'; import { type UntypedSchemaDef } from '../lib/schema.ts'; import { ArrayBuilder, OptionBuilder, RowBuilder, type ColumnBuilder, type ColumnMetadata, type Infer, type InferSpacetimeTypeOfTypeBuilder, type InferTypeOfRow, type RowObj, type TypeBuilder, } from '../lib/type_builders.ts'; import type { IsUnion } from '../lib/type_util.ts'; import { bsatnBaseSize, toPascalCase } from '../lib/util.ts'; import type { ReadonlyDbView } from './db_view.ts'; import { type QueryBuilder, type RowTypedQuery } from './query.ts'; import { exportContext, registerExport, type ModuleExport, type SchemaInner, } from './schema.ts'; export type ViewExport = ViewFn & ModuleExport; export function makeViewExport< S extends UntypedSchemaDef, Params extends ParamsObj, Ret extends ViewReturnTypeBuilder, F extends ViewFn, >( ctx: SchemaInner, opts: ViewOpts, params: Params, ret: Ret, fn: F ): ViewExport { const viewExport = // @ts-expect-error typescript incorrectly says Function#bind requires an argument. fn.bind() as ViewExport; viewExport[exportContext] = ctx; viewExport[registerExport] = (ctx, exportName) => { registerView(ctx, opts, exportName, params, ret, fn); }; return viewExport; } export function makeAnonViewExport< S extends UntypedSchemaDef, Params extends ParamsObj, Ret extends ViewReturnTypeBuilder, F extends AnonymousViewFn, >( ctx: SchemaInner, opts: ViewOpts, params: Params, ret: Ret, fn: F ): ViewExport { const viewExport = // @ts-expect-error typescript incorrectly says Function#bind requires an argument. fn.bind() as ViewExport; viewExport[exportContext] = ctx; viewExport[registerExport] = (ctx, exportName) => { registerAnonymousView(ctx, opts, exportName, params, ret, fn); }; return viewExport; } export type ViewCtx = Readonly<{ sender: Identity; db: ReadonlyDbView; env: EnvironmentFor; from: QueryBuilder; }>; export type AnonymousViewCtx = Readonly<{ db: ReadonlyDbView; env: EnvironmentFor; from: QueryBuilder; }>; export type ViewOpts = { name?: string; public: true; }; type FlattenedArray = T extends readonly (infer E)[] ? E : never; // Compile-time mirror of `viewReturnRow` below. Views currently return either // `array(row(...))` or `option(row(...))`; this extracts the row object type // from those builders so we can inspect column metadata at the type level. // Non-row returns collapse to `never`, which makes the primary-key validation // below a no-op for unsupported shapes. type ViewReturnRow = Ret extends ArrayBuilder ? Element extends RowBuilder ? Row : never : Ret extends OptionBuilder ? Value extends RowBuilder ? Row : never : never; // Produces a union of the returned row's column names marked with // `.primaryKey()`. For example, `{ id: t.u32().primaryKey(), name: t.string() }` // becomes `"id"`, while two marked columns becomes `"id" | "name"`. type PrimaryKeyColumnNames = { [K in keyof Row & string]: Row[K] extends ColumnBuilder ? M extends { isPrimaryKey: true } ? K : never : never; }[keyof Row & string]; // In generic code, row keys may widen from literal names like "id" | "name" // to plain `string`. That means "unknown column name", not "multiple primary // keys", so avoid a false-positive type error and rely on the runtime check. type HasMultiplePrimaryKeys = string extends PrimaryKeyColumnNames ? false : IsUnion>; type MultiplePrimaryKeyColumns = PrimaryKeyColumnNames>; type ERROR_view_return_type_can_have_at_most_one_primaryKey< Columns extends string, > = { _primaryKeyColumns: Columns; _fix: 'Remove primaryKey() from all but one column on the returned row type'; }; // Used as a rest parameter type on `Schema.view` and `Schema.anonymousView`. // Valid return builders produce `[]`, so callers pass no extra arguments. If // the returned row has multiple `.primaryKey()` columns, this becomes a // one-element tuple containing an explanatory error type, which makes the // normal three-argument call fail to type-check. export type ValidateViewPrimaryKey = HasMultiplePrimaryKeys> extends true ? [ error: ERROR_view_return_type_can_have_at_most_one_primaryKey< MultiplePrimaryKeyColumns >, ] : []; // // If we allowed functions to return either. // type ViewReturn = // | Infer // | RowTypedQuery>>; export type ViewFn< S extends UntypedSchemaDef, Params extends ParamsObj, Ret extends ViewReturnTypeBuilder, > = | ((ctx: ViewCtx, params: InferTypeOfRow) => Infer) | (( ctx: ViewCtx, params: InferTypeOfRow ) => RowTypedQuery>, ExtractArrayProduct>); export type AnonymousViewFn< S extends UntypedSchemaDef, Params extends ParamsObj, Ret extends ViewReturnTypeBuilder, > = | ((ctx: AnonymousViewCtx, params: InferTypeOfRow) => Infer) | (( ctx: AnonymousViewCtx, params: InferTypeOfRow ) => RowTypedQuery>, ExtractArrayProduct>); export type ViewReturnTypeBuilder = | TypeBuilder< readonly object[], { tag: 'Array'; value: AlgebraicTypeVariants.Product } > | TypeBuilder< object | undefined, OptionAlgebraicType >; export function registerView< S extends UntypedSchemaDef, Params extends ParamsObj, Ret extends ViewReturnTypeBuilder, >( ctx: SchemaInner, opts: ViewOpts, exportName: string, params: Params, ret: Ret, fn: ViewFn ) { const described = describeView(ctx, opts, exportName, false, params, ret); // `ctx.views` is schema-erased. `ViewCtx` and `ViewCtx` describe the same // shape, but TypeScript cannot relate two instantiations of the mapped type // `ReadonlyDbView` while the schema is still a type parameter, so erasing `S` here // needs an assertion. It is sound because the runtime builds the context it passes // back in from this very schema. ctx.views.push(buildViewInfo(ctx, described, fn as AnyViewFn)); } export function registerAnonymousView< S extends UntypedSchemaDef, Params extends ParamsObj, Ret extends ViewReturnTypeBuilder, >( ctx: SchemaInner, opts: ViewOpts, exportName: string, params: Params, ret: Ret, fn: AnonymousViewFn ) { const described = describeView(ctx, opts, exportName, true, params, ret); // Schema-erased for the same reason as `registerView` above. ctx.anonViews.push(buildViewInfo(ctx, described, fn as AnyAnonymousViewFn)); } /** * The flavor-independent part of registering a view: register its types, record * it in the module def, and validate its primary key. Everything here is the * same for regular and anonymous views, so it is factored out of both. */ function describeView< Params extends ParamsObj, Ret extends ViewReturnTypeBuilder, >( ctx: SchemaInner, opts: ViewOpts, exportName: string, anon: boolean, params: Params, ret: Ret ) { ctx.defineFunction(exportName); const paramsBuilder = new RowBuilder(params, toPascalCase(exportName)); // Register return types if they are product types let returnType = ctx.registerTypesRecursively(ret).algebraicType; const { value: paramType } = ctx.resolveType( ctx.registerTypesRecursively(paramsBuilder) ); ctx.moduleDef.views.push({ sourceName: exportName, index: (anon ? ctx.anonViews : ctx.views).length, isPublic: opts.public, isAnonymous: anon, params: paramType, returnType, }); // Runtime counterpart to `ValidateViewPrimaryKey`: the type-level check gives // users an early diagnostic in normal code, but this still protects dynamic // or widened builders and is the source of the raw module-def metadata. const primaryKeyColumns = viewPrimaryKeyColumns(ret); if (primaryKeyColumns.length > 1) { throw new TypeError( `View '${exportName}' can have at most one primaryKey() column on its returned row type; found ${primaryKeyColumns.join(', ')}` ); } // A view with params doesn't get a primary key: the host rejects one, and a // table's `rowType` carries its `.primaryKey()` into views that return it. if (primaryKeyColumns.length === 1 && paramType.elements.length === 0) { ctx.moduleDef.viewPrimaryKeys.push({ viewSourceName: exportName, columns: primaryKeyColumns, }); } if (opts.name != null) { ctx.moduleDef.explicitNames.entries.push({ tag: 'Function', value: { sourceName: exportName, canonicalName: opts.name, }, }); } // An option-returning view is presented to the host as an array of zero or one // rows, so its function needs wrapping and its return type rewriting. const wrapOption = returnType.tag == 'Sum'; // Tested directly rather than via `wrapOption` so that TypeScript narrows `returnType`. if (returnType.tag == 'Sum') { returnType = AlgebraicType.Array( returnType.value.variants[0].algebraicType ); } return { paramType, returnType, wrapOption }; } // Build the stored `ViewInfo` for `fn`. Generic over the stored function type so // the regular and anonymous cases each keep their own context shape here, instead // of being collapsed into one type by a cast. function buildViewInfo any>( ctx: SchemaInner, { paramType, returnType, wrapOption }: ReturnType, fn: F ): ViewInfo { const { typespace } = ctx; return { fn: wrapOption ? (((viewCtx, args) => { const ret = fn(viewCtx, args); return ret == null ? [] : [ret]; }) as F) : fn, deserializeParams: ProductType.makeDeserializer(paramType, typespace), serializeReturn: AlgebraicType.makeSerializer(returnType, typespace), returnTypeBaseSize: bsatnBaseSize(typespace, returnType), }; } // Inspect the returned row builder and collect the column property names marked // with `.primaryKey()`. These names are the TypeScript row-builder keys, which // are also the raw column names in the module definition emitted by the TS SDK. function viewPrimaryKeyColumns(ret: ViewReturnTypeBuilder): string[] { const row = viewReturnRow(ret); if (row == null) { return []; } return Object.entries(row.row) .filter( ( entry ): entry is [string, ColumnBuilder>] => entry[1].columnMetadata.isPrimaryKey === true ) .map(([name]) => name); } // Views can return either `array(row(...))` or `option(row(...))`. The primary // key marker lives on the inner `RowBuilder`, so unwrap those two supported // shapes and ignore anything else. function viewReturnRow( ret: ViewReturnTypeBuilder ): RowBuilder | undefined { if (ret instanceof ArrayBuilder && ret.element instanceof RowBuilder) { return ret.element; } if (ret instanceof OptionBuilder && ret.value instanceof RowBuilder) { return ret.value; } return undefined; } type ViewInfo = { fn: F; deserializeParams: Deserializer; serializeReturn: Serializer; returnTypeBaseSize: number; }; type AnyViewFn = (ctx: ViewCtx, params: any) => any; type AnyAnonymousViewFn = (ctx: AnonymousViewCtx, params: any) => any; export type Views = ViewInfo[]; export type AnonViews = ViewInfo[]; // A helper to get the product type out of a type builder. // This is only non-never if the type builder is an array. type ExtractArrayProduct> = InferSpacetimeTypeOfTypeBuilder extends { tag: 'Array'; value: infer V } ? V extends { tag: 'Product'; value: infer P } ? P : never : never;