electric-sql / electric

Local-first sync layer for web and mobile apps. Build reactive, realtime, local-first apps directly on Postgres.
https://electric-sql.com
Apache License 2.0
5.37k stars 124 forks source link

LiveUnique query fails validation when using compound unique index #1419

Closed emckay closed 1 day ago

emckay commented 2 days ago

My table schema looks like this:

CREATE TABLE "categories" (
    "id" TEXT NOT NULL,
    "slug" TEXT NOT NULL,
    "account_id" TEXT NOT NULL,
    CONSTRAINT "categories_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX categories_slug_uniq ON categories (slug, account_id);

I want to query by slug & account_id:

  const query = useLiveQuery(
    db.categories.liveUnique({
      where: {
        slug_account_id: { slug: "asdf", account_id: "asdf" },
      },
    })
  );

The code passes the TypeScript type check and is valid in vanilla prisma. But at runtime, the query fails to execute because of a zod validation failure:

{
  "error": {
    "issues": [
      {
        "code": "unrecognized_keys",
        "keys": [
          "slug",
          "account_id"
        ],
        "path": [],
        "message": "Unrecognized key(s) in object: 'slug', 'account_id'"
      },
      {
        "code": "custom",
        "message": "Please provide at least one filter.",
        "path": []
      }
    ],
    "name": "ZodError"
  },
  "updatedAt": "2024-07-02T17:25:34.095Z"
}

Here is a repo with a reproduction based on the create-electric-app react repo: https://github.com/emckay/electric-liveUnique-bug-repro

linear[bot] commented 2 days ago

VAX-2002 LiveUnique query fails validation when using compound unique index

emckay commented 1 day ago

Ah just found in the docs that unique constraints are not supported. Too bad this isn't flagged when electrifying the table. It'd also be nice if the unique index doesn't show up in the prisma generated types, so typescript also blocks this type of query.