import type { RemoteReducer } from './remote_module.ts'; import { makeOutbox } from './remote_module.ts'; import type { ProcedureExport, ReducerExport, t } from '../server/index.ts'; import type { errors } from '../server/errors.ts'; import { ExplicitNameEntry, RawColumnDefaultValueV10, RawConstraintDefV10, RawIndexAlgorithm, RawIndexDefV10, RawSequenceDefV10, RawTableDefV10, } from './autogen/types.ts'; import BinaryWriter from './binary_writer.ts'; import type { AllUnique, ConstraintOpts } from './constraints.ts'; import type { ColumnIndex, IndexColumns, Indexes, IndexOpts, ReadonlyIndexes, UntypedIndex, } from './indexes.ts'; import ScheduleAt from './schedule_at.ts'; import type { OutboxMetadata, TableSchema, TableSchedule, } from './table_schema.ts'; import { RowBuilder, type ColumnBuilder, type ColumnMetadata, type InferTypeOfRow, type RowObj, type TypeBuilder, } from './type_builders.ts'; import type { InvalidColumnMetadata, Prettify, ValidateColumnMetadata, } from './type_util.ts'; import { toPascalCase } from './util.ts'; export type AlgebraicTypeRef = number; type ColId = number; type ColList = ColId[]; /** * Check if any column in the row has invalid metadata. */ type HasInvalidColumn = // this checks if Row exactly equals RowObj - if it does, we can't // do type-system-level checking, so just let it pass (() => G extends Row ? 1 : 2) extends () => G extends RowObj ? 1 : 2 ? false : { [K in keyof Row]: Row[K] extends ColumnBuilder ? ValidateColumnMetadata extends InvalidColumnMetadata ? true : false : false; }[keyof Row] extends false ? false : true; /** * Extract the names of columns that have invalid metadata. */ type InvalidColumnNames = { [K in keyof Row]: Row[K] extends ColumnBuilder ? ValidateColumnMetadata extends InvalidColumnMetadata ? K & string : never : never; }[keyof Row]; /** * A descriptive error type that surfaces the validation error. * The type name itself contains the error message for better CLI output. */ type ERROR_default_cannot_be_combined_with_primaryKey_unique_or_autoInc< InvalidColumns extends string, > = { _invalidColumns: InvalidColumns; _fix: 'Remove either default() or the constraint (primaryKey/unique/autoInc) from these columns'; }; /** * A helper type to extract the row type from a TableDef */ export type RowType> = InferTypeOfRow; /** * Coerces a column which may be a TypeBuilder or ColumnBuilder into a ColumnBuilder */ export type CoerceColumn< Col extends TypeBuilder | ColumnBuilder, > = Col extends TypeBuilder ? ColumnBuilder> : Col; /** * Coerces a RowObj where TypeBuilders are replaced with ColumnBuilders */ export type CoerceRow = { [k in keyof Row & string]: CoerceColumn; }; /** * Helper type to coerce an array of IndexOpts */ type CoerceArray[]> = X; /** * An untyped representation of a table's schema. */ export type UntypedTableDef = { sourceName: string; accessorName: string; columns: Record>>; // This is really just a ProductType where all the elements have names. rowType: RowBuilder['algebraicType']['value']; /** * Declarative multi-column indexes supplied by user code in `table({ indexes: [...] }, ...)`. * * This is intentionally the *declarative* shape (`IndexOpts`) because a lot of * type-level behavior is derived from these entries (for example query-builder * inference over composite indexes). */ indexes: readonly IndexOpts[]; /** * Fully-resolved runtime indexes materialized from `RawTableDefV10`. * * This contains both: * 1) field-level indexes inferred from column metadata, and * 2) explicit table-level indexes. * * Runtime consumers like `TableCacheImpl` should use this field instead of * reinterpreting `indexes` as runtime index metadata. */ resolvedIndexes: readonly UntypedIndex[]; constraints: readonly ConstraintOpts[]; tableDef: RawTableDefV10; isEvent?: boolean; isOutbox?: boolean; }; /** * A type representing the indexes defined on a table. */ export type TableIndexes = { [K in keyof TableDef['columns'] & string as ColumnIndex< K, TableDef['columns'][K]['columnMetadata'] > extends never ? never : K]: ColumnIndex; } & { [I in TableDef['indexes'][number] as I['accessor'] & {}]: TableIndexFromDef< TableDef, I >; }; type TableIndexFromDef< TableDef extends UntypedTableDef, I extends IndexOpts, > = NormalizeIndexColumns extends infer Cols extends ReadonlyArray< keyof TableDef['columns'] & string > ? { name: I['accessor']; unique: AllUnique; algorithm: Lowercase; columns: Cols; } : never; type NormalizeIndexColumns< TableDef extends UntypedTableDef, I extends IndexOpts, > = IndexColumns extends ReadonlyArray ? IndexColumns : never; /** * Options for configuring a database table. * - `name`: The name of the table. * - `public`: Whether the table is publicly accessible. Defaults to `false`. * - `indexes`: An array of index configurations for the table. * - `constraints`: An array of constraint configurations for the table. * - `scheduled`: The name of the reducer to be executed based on the scheduled rows in this table. */ export type TableOpts = { name?: string; public?: boolean; /** The furthest storage tier the table's pages and blobs may reside in. */ cachePolicy?: 'required_in_memory' | 'required_on_disk' | 'no_requirement'; indexes?: IndexOpts[]; // declarative multi‑column indexes constraints?: ConstraintOpts[]; /** * @deprecated Prefer `spacetime.reducer({ onSchedule: table }, ...)` or * `spacetime.procedure({ onSchedule: table }, ...)` so table definitions can * live in a separate module from reducer/procedure definitions. */ scheduled?: () => | ReducerExport }> | ProcedureExport< any, { [k: string]: RowBuilder }, ReturnType >; event?: boolean; outbox?: undefined; }; /** Options for an insert-only outbox using a generated receiver handle. */ export type OutboxTableOpts = Omit< TableOpts, 'outbox' > & { outbox: { receiver: RemoteReducer }; }; /** * Extracts the indices from TableOpts, defaulting to an empty array if none are provided. */ type OptsIndices | OutboxTableOpts> = Opts extends { indexes: infer Ixs extends NonNullable; } ? Ixs : CoerceArray<[]>; /** * Extracts the constraints from TableOpts, defaulting to an empty array if none are provided. */ type OptsConstraints | OutboxTableOpts> = Opts extends { constraints: infer Constraints extends NonNullable; } ? Constraints : CoerceArray<[]>; // Ordinary TableOpts annotations must keep their existing mutable table API. // OutboxTableOpts requires the discriminator, even when options are widened. type OptsOutbox = Opts extends { outbox: object; } ? OutboxMetadata : undefined; /** * Table * * - Row: row shape * - UCV: unique-constraint violation error type (never if none) * - AIO: auto-increment overflow error type (never if none) */ export type Table = Prettify< TableMethods & Indexes> >; /** Insert/read operations for outboxes, separate from the existing Table API. */ export type OutboxTable = Prettify< ReadonlyTable & Pick, 'insert'> >; export type ReadonlyTable = Prettify< ReadonlyTableMethods & ReadonlyIndexes> >; export interface ReadonlyTableMethods { /** * Returns the number of rows in this table. * * This reads datastore metadata, so it runs in constant time. * It also takes into account modifications by the current transaction. */ count(): bigint; /** Iterate over all rows in the TX state. Rust Iterator → TS IterableIterator. */ iter(): IteratorObject>, undefined>; [Symbol.iterator](): IteratorObject>, undefined>; } /** * A type representing the methods available on a table. */ export interface TableMethods extends ReadonlyTableMethods { /** * Insert and return the inserted row (auto-increment fields filled). * * May throw on error: * * If there are any unique or primary key columns in this table, may throw {@link errors.UniqueAlreadyExists}. * * If there are any auto-incrementing columns in this table, may throw {@link errors.AutoIncOverflow}. * */ insert(row: Prettify>): Prettify>; /** Delete a row equal to `row`. Returns true if something was deleted. */ delete(row: Prettify>): boolean; /** * Clears the table of all rows. * Returns the number of rows deleted, * i.e., the return value of `this.count()` before this call. */ clear(): bigint; } /** * Defines a database table with schema and options. * * @param opts - Table configuration including name, indexes, and access control * @param row - Product type defining the table's row structure * @returns Table handle for use in schema() function * * @example * ```ts * const playerTable = table( * { name: 'player', public: true }, * { * id: t.u32().primaryKey(), * name: t.string().index('btree') * } * ); * ``` * * ## Column Validation Error * * **If you see an error like "Expected 3 arguments, but got 2"**, this means * one of your columns has an invalid combination of attributes. * * Specifically, `default()` cannot be combined with: * - `primaryKey()` * - `unique()` * - `autoInc()` * * **Example of invalid code:** * ```ts * // ERROR: default() + primaryKey() is not allowed * const badTable = table( * { name: 'bad' }, * { id: t.u64().default(0n).primaryKey() } // <- This causes "Expected 3 arguments" * ); * ``` * * **How to fix:** Remove either `default()` or the constraint (`primaryKey`/`unique`/`autoInc`). */ export function table< Row extends RowObj, const Opts extends TableOpts | OutboxTableOpts, >( opts: Opts, row: Row | RowBuilder, // ⚠️ INTERNAL: This parameter enforces compile-time validation of column metadata. // It is never passed at runtime. If you see "Expected 3 arguments, but got 2", // it means a column has an invalid combination (e.g., default + primaryKey). // See the JSDoc above for details on how to fix this error. ..._: HasInvalidColumn extends true ? [ error: ERROR_default_cannot_be_combined_with_primaryKey_unique_or_autoInc< InvalidColumnNames >, ] : [] ): TableSchema, OptsIndices, OptsOutbox> { const { name, public: isPublic = false, cachePolicy = 'required_in_memory', indexes: userIndexes = [], scheduled, event: isEvent = false, } = opts; // 1. column catalogue + helpers const colIds = new Map(); const colNameList: string[] = []; if (!(row instanceof RowBuilder)) { row = new RowBuilder(row); } row.algebraicType.value.elements.forEach((elem, i) => { colIds.set(elem.name, i); colNameList.push(elem.name); }); // gather primary keys, per‑column indexes, uniques, sequences const pk: ColList = []; const indexes: (RawIndexDefV10 & { canonicalName?: string })[] = []; const constraints: RawConstraintDefV10[] = []; const sequences: RawSequenceDefV10[] = []; let scheduleAtCol: ColId | undefined; const defaultValues: RawColumnDefaultValueV10[] = []; for (const [name, builder] of Object.entries(row.row)) { const meta: ColumnMetadata = builder.columnMetadata; if (meta.isPrimaryKey) { pk.push(colIds.get(name)!); } const isUnique = meta.isUnique || meta.isPrimaryKey; // implicit 1‑column indexes if (meta.indexType || isUnique) { const algo = meta.indexType ?? 'btree'; const id = colIds.get(name)!; let algorithm: RawIndexAlgorithm; switch (algo) { case 'btree': algorithm = RawIndexAlgorithm.BTree([id]); break; case 'hash': algorithm = RawIndexAlgorithm.Hash([id]); break; case 'direct': algorithm = RawIndexAlgorithm.Direct(id); break; } indexes.push({ sourceName: undefined, // Unnamed indexes will be assigned a globally unique name accessorName: name, algorithm, }); } if (isUnique) { constraints.push({ sourceName: undefined, data: { tag: 'Unique', value: { columns: [colIds.get(name)!] } }, }); } if (meta.isAutoIncrement) { sequences.push({ sourceName: undefined, start: undefined, minValue: undefined, maxValue: undefined, column: colIds.get(name)!, increment: 1n, }); } // Check for defaultValue on the property to allow for 0, false, '', and undefined as defaults if (Object.prototype.hasOwnProperty.call(meta, 'defaultValue')) { const writer = new BinaryWriter(16); builder.serialize(writer, meta.defaultValue); defaultValues.push({ colId: colIds.get(name)!, value: writer.getBuffer(), }); } // If this column is shaped like ScheduleAtAlgebraicType, mark it as the schedule‑at column const algebraicType = builder.typeBuilder.algebraicType; if (ScheduleAt.isScheduleAt(algebraicType)) { scheduleAtCol = colIds.get(name)!; } } // convert explicit multi‑column indexes coming from options.indexes for (const indexOpts of userIndexes ?? []) { const accessor = indexOpts.accessor; if (typeof accessor !== 'string' || accessor.length === 0) { const tableLabel = name ?? ''; const indexLabel = indexOpts.name ?? ''; throw new TypeError( `Index '${indexLabel}' on table '${tableLabel}' must define a non-empty 'accessor'` ); } let algorithm: RawIndexAlgorithm; switch (indexOpts.algorithm) { case 'btree': algorithm = { tag: 'BTree', value: indexOpts.columns.map(c => colIds.get(c)!), }; break; case 'hash': algorithm = { tag: 'Hash', value: indexOpts.columns.map(c => colIds.get(c)!), }; break; case 'direct': algorithm = { tag: 'Direct', value: colIds.get(indexOpts.column)! }; break; } // Unnamed indexes are assigned a globally unique source name. // `accessor` controls the TypeScript property used to access the index. // `name` (if present) is preserved as the canonical schema name. // // IMPORTANT: we intentionally do not reject duplicate accessor names here. // This preserves existing behavior for raw table definitions. Downstream // runtime consumers decide how duplicates are resolved: // - server runtime merges duplicate accessors onto one accessor object // - client cache assignment is last-write-wins for duplicate accessors indexes.push({ sourceName: undefined, accessorName: accessor, algorithm, canonicalName: indexOpts.name, }); } // add explicit constraints from options.constraints for (const constraintOpts of opts.constraints ?? []) { if (constraintOpts.constraint === 'unique') { const data: RawConstraintDefV10['data'] = { tag: 'Unique', value: { columns: constraintOpts.columns.map(c => colIds.get(c)!) }, }; constraints.push({ sourceName: constraintOpts.name, data }); continue; } } const productType = row.algebraicType.value as RowBuilder< CoerceRow >['algebraicType']['value']; const schedule: TableSchedule | undefined = scheduled && scheduleAtCol !== undefined ? { scheduleAtCol, reducer: scheduled } : undefined; const receiver = opts.outbox?.receiver; const outbox = receiver ? makeOutbox(receiver, row, pk, !!scheduled || isEvent) : undefined; return { outbox: outbox as OptsOutbox, rowType: row as RowBuilder>, tableName: name, rowSpacetimeType: productType, tableDef: (ctx, accName) => { if (cachePolicy !== 'required_in_memory') { let policy; switch (cachePolicy) { case 'required_on_disk': policy = { tag: 'RequiredOnDisk' } as const; break; case 'no_requirement': policy = { tag: 'NoRequirement' } as const; break; default: throw new TypeError(`Invalid cachePolicy: ${cachePolicy}`); } ctx.moduleDef.tableCachePolicies.push({ tableName: accName, policy }); } const tableName = name ?? accName; if (row.typeName === undefined) { row.typeName = toPascalCase(tableName); } // Build index source names using accName for (const index of indexes) { const cols = index.algorithm.tag === 'Direct' ? [index.algorithm.value] : index.algorithm.value; const colS = cols.map(i => colNameList[i]).join('_'); const sourceName = (index.sourceName = `${accName}_${colS}_idx_${index.algorithm.tag.toLowerCase()}`); const { canonicalName } = index; if (canonicalName !== undefined) { ctx.moduleDef.explicitNames.entries.push( ExplicitNameEntry.Index({ sourceName, canonicalName }) ); } } return { sourceName: accName, productTypeRef: ctx.registerTypesRecursively(row).ref, primaryKey: pk, indexes, constraints, sequences, tableType: { tag: 'User' }, tableAccess: { tag: isPublic ? 'Public' : 'Private' }, defaultValues, isEvent, }; }, // Preserve the declared index options as runtime data so `tableToSchema` // can expose them without type-smuggling. idxs: userIndexes as OptsIndices, constraints: constraints as OptsConstraints, scheduleAtCol, schedule, }; }