Skip to content

Support custom structs as primary keys #5425

Description

@website-features

Allow custom structs marked with [SpacetimeDB.Type] to be used as primary keys when they wrap a SpacetimeDB-supported primary-key type.

For example:

[SpacetimeDB.Type]
public partial struct ItemKey
{
    public ulong Value;

    public bool IsReserved()
    public ItemCategory GetItemCategory()

    public static implicit operator ulong(ItemKey key) => key.Value;
    public static implicit operator ItemKey(ulong value) =>
        new() { Value = value };
}

[SpacetimeDB.Table(Accessor = "Item", Public = true)]
public partial struct Item
{
    [SpacetimeDB.PrimaryKey]
    public ItemKey Key;

    public string Name;
}

Why?

Custom key types make it possible to attach arbitrary methods directly to a key.

This also could help prevent different kinds of keys from being mixed together accidentally, even when they use the same underlying type.

Without this support, the table field must use a built-in type, and the user has to repeatedly convert between that type and the custom struct before calling methods or passing the key to other parts of the application.

Proposed behavior

A struct marked with [SpacetimeDB.Type] should be usable as a primary key, unique key, or single-column index key when it wraps exactly one SpacetimeDB-supported primary-key type.

It would be acceptable to require implicit conversions and/or to and from the supported type. Alternatively, a dedicated attribute or other explicit way to identify the underlying key type would be reasonable.

SpacetimeDB could store and index the value using the supported underlying type, while generated APIs continue to use the custom struct.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions