clockworklabs/SpacetimeDB · error · TypeError

View ' ' can have at most one primaryKey() column on its…

Error message

View '${exportName}' can have at most one primaryKey() column on its returned row type; found ${primaryKeyColumns.join(', ')}

What it means

A view's returned row type may mark at most one column with `.primaryKey()`. `describeView` computes the primary-key columns of the return row and, if more than one is found, throws naming all of them. This is the runtime counterpart of the `ValidateViewPrimaryKey` type-level check — it exists to catch dynamically built or type-widened return types and to emit the `viewPrimaryKeys` module-def metadata.

Solutions

  1. Keep exactly one `.primaryKey()` column on the view's returned row type and express additional uniqueness with a plain column or index.
  2. If a composite key is needed, return it as a single column (e.g. a string `"tenant:user"`) or rely on the underlying table's unique index instead of view primary keys.
  3. In dynamic builders, assert/validate the assembled row: count `primaryKey`-flagged columns and fail early with your own message before calling the view API.

Example fix

// before
spacetimedb.view({ public: true }, { id: t.u32() }, {
  id: t.u32().primaryKey(),
  name: t.string().primaryKey(), // second pk -> TypeError
}, (ctx, p) => ...);

// after
spacetimedb.view({ public: true }, { id: t.u32() }, {
  id: t.u32().primaryKey(),
  name: t.string(),
}, (ctx, p) => ...);
Defensive patterns

Strategy: type-guard

Validate before calling

// For dynamically built view rows: assert at most one primaryKey column.
function countPrimaryKeys(row: Record<string, any>): number {
  return Object.values(row).filter(c => c?.builderMeta?.isPrimaryKey === true).length;
}
function assertSingleViewPk(name: string, row: Record<string, any>) {
  if (countPrimaryKeys(row) > 1) throw new Error(`view ${name}: at most one primaryKey column`);
}

Type guard

// Type-level: reuse the SDK's ValidateViewPrimaryKey when rows are statically typed;
// for widened Ret, narrow back to a concrete builder type before calling the view API.

Prevention

When it happens

Trigger: A view returning a row like `{ id: t.u32().primaryKey(), name: t.string().primaryKey() }`; building the return type dynamically (plain objects, `any`-typed builders) so the compile-time `@ts-expect-error`-style check never ran; widening `Ret` to a general `ViewReturnTypeBuilder` in generic wrappers.

Common situations: Exposing a composite key as two primary-key columns instead of one column or a unique index; copy-pasting a table row (with its single pk) and adding a second `.primaryKey()` for ordering; generic view factories that assemble row types from user input.

Related errors


AI-assisted analysis of clockworklabs/SpacetimeDB@eddf9f5014 (2026-08-20). Data as JSON: /api/errors/a91b5d6d83abb3dd. Report an issue: GitHub.

Appendix: source

Thrown at crates/bindings-typescript/src/server/views.ts:276

  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(', ')}`
    );
  }
  if (primaryKeyColumns.length === 1) {
    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,
      },
    });

View on GitHub (pinned to eddf9f5014)