{"record":{"id":"a91b5d6d83abb3dd","repo":"clockworklabs/SpacetimeDB","slug":"view-exportname-can-have-at-most-one-primaryk","errorCode":null,"errorMessage":"View '${exportName}' can have at most one primaryKey() column on its returned row type; found ${primaryKeyColumns.join(', ')}","messagePattern":"View '(.+?)' can have at most one primaryKey\\(\\) column on its returned row type; found (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"crates/bindings-typescript/src/server/views.ts","lineNumber":276,"sourceCode":"  const { value: paramType } = ctx.resolveType(\n    ctx.registerTypesRecursively(paramsBuilder)\n  );\n\n  ctx.moduleDef.views.push({\n    sourceName: exportName,\n    index: (anon ? ctx.anonViews : ctx.views).length,\n    isPublic: opts.public,\n    isAnonymous: anon,\n    params: paramType,\n    returnType,\n  });\n\n  // Runtime counterpart to `ValidateViewPrimaryKey`: the type-level check gives\n  // users an early diagnostic in normal code, but this still protects dynamic\n  // or widened builders and is the source of the raw module-def metadata.\n  const primaryKeyColumns = viewPrimaryKeyColumns(ret);\n  if (primaryKeyColumns.length > 1) {\n    throw new TypeError(\n      `View '${exportName}' can have at most one primaryKey() column on its returned row type; found ${primaryKeyColumns.join(', ')}`\n    );\n  }\n  if (primaryKeyColumns.length === 1) {\n    ctx.moduleDef.viewPrimaryKeys.push({\n      viewSourceName: exportName,\n      columns: primaryKeyColumns,\n    });\n  }\n\n  if (opts.name != null) {\n    ctx.moduleDef.explicitNames.entries.push({\n      tag: 'Function',\n      value: {\n        sourceName: exportName,\n        canonicalName: opts.name,\n      },\n    });","sourceCodeStart":258,"sourceCodeEnd":294,"githubUrl":"https://github.com/clockworklabs/SpacetimeDB/blob/eddf9f5014579a50d4b67630e28b6e15cad9c4af/crates/bindings-typescript/src/server/views.ts#L258-L294","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Keep exactly one `.primaryKey()` column on the view's returned row type and express additional uniqueness with a plain column or index.","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.","In dynamic builders, assert/validate the assembled row: count `primaryKey`-flagged columns and fail early with your own message before calling the view API."],"exampleFix":"// before\nspacetimedb.view({ public: true }, { id: t.u32() }, {\n  id: t.u32().primaryKey(),\n  name: t.string().primaryKey(), // second pk -> TypeError\n}, (ctx, p) => ...);\n\n// after\nspacetimedb.view({ public: true }, { id: t.u32() }, {\n  id: t.u32().primaryKey(),\n  name: t.string(),\n}, (ctx, p) => ...);","handlingStrategy":"type-guard","validationCode":"// For dynamically built view rows: assert at most one primaryKey column.\nfunction countPrimaryKeys(row: Record<string, any>): number {\n  return Object.values(row).filter(c => c?.builderMeta?.isPrimaryKey === true).length;\n}\nfunction assertSingleViewPk(name: string, row: Record<string, any>) {\n  if (countPrimaryKeys(row) > 1) throw new Error(`view ${name}: at most one primaryKey column`);\n}","typeGuard":"// Type-level: reuse the SDK's ValidateViewPrimaryKey when rows are statically typed;\n// for widened Ret, narrow back to a concrete builder type before calling the view API.","tryCatchPattern":null,"preventionTips":["Mark exactly one column with `.primaryKey()` on view return rows.","Rely on the compile-time diagnostic in normal code; add runtime counting only for dynamic builders.","Model composite uniqueness as a single concatenated column or via the underlying table index."],"tags":["view","primary-key","schema","build-time","spacetimedb"],"backgroundTag":"multiple-primary-keys","analyzedSha":"eddf9f5014579a50d4b67630e28b6e15cad9c4af","analyzedAt":"2026-08-20T06:08:37.179Z","contentChangedAt":"2026-08-20T06:08:37.179Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}