I'm trying to design a database structure that allows me to extract common fields into one table called "entity".
You could think of "entity" as an abstract class. Every "entity" has an owner (a referenced user-account), a creation-time and some key-value tags.
Every "entity" is actually either an "object" or an "view". Never both. Never none of them.
Is this constraint possible to enforce on an PostgreSQL Database (latest version)? If not, tell me and feel free to suggest changes for my current schema.
My initialization SQL looks like this:
CREATE TABLE "account" (
"id" BIGSERIAL NOT NULL,
"issuer" VARCHAR NOT NULL,
"name" VARCHAR NOT NULL,
PRIMARY KEY ("id"),
UNIQUE ("issuer", "name")
) ;
CREATE TABLE "entity" (
"id" BIGSERIAL NOT NULL,
"owner_account_id" BIGINT NOT NULL,
"creation_time" TIMESTAMP NOT NULL,
PRIMARY KEY ("id"),
FOREIGN KEY ("owner_account_id") REFERENCES "account" ("id") ON DELETE CASCADE ON UPDATE CASCADE
) ;
CREATE TABLE "entity_tag" (
"entity_id" BIGINT NOT NULL,
"key" VARCHAR(100) NOT NULL,
"value" VARCHAR(1000) NOT NULL,
PRIMARY KEY ("entity_id", "key"),
FOREIGN KEY ("entity_id") REFERENCES "entity" ("id") ON DELETE CASCADE ON UPDATE CASCADE
) ;
CREATE TABLE "object" (
"id" BIGSERIAL NOT NULL,
"entity_id" BIGINT NOT NULL,
"mime_type" VARCHAR NOT NULL,
"size" BIGINT NOT NULL,
PRIMARY KEY ("id"),
FOREIGN KEY ("entity_id") REFERENCES "entity" ("id") ON DELETE CASCADE ON UPDATE CASCADE
) ;
CREATE TABLE "view" (
"id" BIGSERIAL NOT NULL,
"entity_id" BIGINT NOT NULL,
"view_expression" JSON NOT NULL,
PRIMARY KEY ("id"),
FOREIGN KEY ("entity_id") REFERENCES "entity" ("id") ON DELETE CASCADE ON UPDATE CASCADE
) ;
(Sure, I can and I actually currently do enforce this in my application. But if there's a way to enforce this on the Database too, I would like to do it)