import type { RemoteReducer } from './remote_module.ts'; import type { ProcedureExport, ReducerExport, t } from '../server/index.ts'; import { RawTableDefV10 } from './autogen/types.ts'; import type { AllUnique, ConstraintOpts } from './constraints.ts'; import type { ColumnIndex, IndexColumns, Indexes, IndexOpts, ReadonlyIndexes, UntypedIndex } from './indexes.ts'; import type { OutboxMetadata, TableSchema } 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'; export type AlgebraicTypeRef = number; /** * Check if any column in the row has invalid metadata. */ type HasInvalidColumn = (() => 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: 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 | 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>>; 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 extends never ? never : K]: ColumnIndex; } & { [I in TableDef['indexes'][number] as I['accessor'] & {}]: TableIndexFromDef; }; type TableIndexFromDef> = NormalizeIndexColumns extends infer Cols extends ReadonlyArray ? { name: I['accessor']; unique: AllUnique; algorithm: Lowercase; columns: Cols; } : never; type NormalizeIndexColumns> = 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[]; 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; }, ReturnType>; event?: boolean; outbox?: undefined; }; /** Options for an insert-only outbox using a generated receiver handle. */ export type OutboxTableOpts = Omit, '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<[]>; 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 & Indexes>>; /** Insert/read operations for outboxes, separate from the existing Table API. */ export type OutboxTable = Prettify & Pick, 'insert'>>; export type ReadonlyTable = Prettify & 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 declare function table | OutboxTableOpts>(opts: Opts, row: Row | RowBuilder, ..._: HasInvalidColumn extends true ? [ error: ERROR_default_cannot_be_combined_with_primaryKey_unique_or_autoInc> ] : []): TableSchema, OptsIndices, OptsOutbox>; export {}; //# sourceMappingURL=table.d.ts.map