tywalch/electrodb

Simplest implementation of unique constraint for non-key attributes

Opened this issue · 0 comments

jckdn commented

I see a suggested pattern in the docs to implement a unique constraint for non-key attributes: https://electrodb.dev/en/mutations/transact-write/

I'm wondering if there is a simpler way to implement this. The example includes a PK, SK, and a GSI also with its own PK and SK. The index is called gsi1pk-gsi2sk-index (btw I think this is a typo and should actually be gsi1pk-gsi1sk-index). This entity design is similar to other examples in the docs. But I'm wondering if this example is as complex just for consistency or if it can be simplified, i.e, the SK and GSI might not be required?

An AWS blog describes how to implement unique constraints like so: https://aws.amazon.com/blogs/database/simulating-amazon-dynamodb-unique-constraints-using-transactions/

My table will only have one entity, with a PK, and a few attributes one of which I need to also be unique, and so doesn't really require single table design aside from what's needed to implement the unique constraint. I'd like to know if it's possible to simplify the electrodb pattern at all, perhaps in a way similar to the pattern in the AWS blog.

Reminder of what the electrodb "constraint" entity example looks like:

// entity that owns unique constraints
const constraint = new Entity(
  {
    model: {
      entity: "constraint",
      version: "1",
      service: "MI6",
    },
    attributes: {
      name: {
        type: "string",
        required: true,
      },
      value: {
        type: "string",
        required: true,
      },
      entity: {
        type: "string",
        required: true,
      },
    },
    indexes: {
      value: {
        pk: {
          field: "pk",
          composite: ["value"],
        },
        sk: {
          field: "sk",
          composite: ["name", "entity"],
        },
      },
      name: {
        index: "gsi1pk-gsi2sk-index",
        pk: {
          field: "gsi1pk",
          composite: ["name", "entity"],
        },
        sk: {
          field: "gsi1sk",
          composite: ["value"],
        },
      },
    },
  },
  { table, client },
);