'Prisma: make boolean so only one can be true at the same time

Is it possible to make a boolean "unique" in Prisma? I want only one row to be 'true' at the same time. @Unique doesn't work because there can be multiple 'false'.

I know there are better options to keep track of whether someone is logged in, but according to the assignment I MUST do it this way....

Screenshot of Database

Thanks in advance.



Solution 1:[1]

You can create a unique index with a custom migration:

npx prisma migrate dev --create-only --name init

PostgreSQL constraint - only one row can have flag set

-- CreateTable
CREATE TABLE "Entity" (
    "id" TEXT NOT NULL,
    "value" BOOLEAN NOT NULL,

    CONSTRAINT "Entity_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX on "Entity" ("value") 
WHERE "value" = true;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ironolife