Postgres create many to many relationship to table with composite primary key - postgresql

CREATE TABLE "public"."Users" (
id SERIAL PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT now()
);
CREATE TABLE "public"."Boards" (
id SERIAL PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
"ownerId" SERIAL NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
"updatedAt" TIMESTAMP,
FOREIGN KEY ("ownerId") REFERENCES "public"."Users"(id)
);
CREATE TABLE "public"."Board_Members"(
"userId" SERIAL,
"boardId" SERIAL,
CONSTRAINT board_member_pkey PRIMARY KEY ("userId", "boardId"),
FOREIGN KEY ("userId") REFERENCES "public"."Users"(id),
FOREIGN KEY ("boardId") REFERENCES "public"."Boards"(id)
);
CREATE TABLE "public"."Columns" (
id SERIAL PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
"boardId" SERIAL NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
"updatedAt" TIMESTAMP,
FOREIGN KEY ("boardId") REFERENCES "public"."Boards"(id)
);
CREATE TABLE "public"."Cards" (
id SERIAL PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL,
dueDate TIMESTAMP,
"columnId" SERIAL NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
"updatedAt" TIMESTAMP,
FOREIGN KEY ("columnId") REFERENCES "public"."Columns"(id),
);
I have these tables. Now I want to have a field called "assignee" in "Cards" table which will be a many-to-many relationship with "userId" from "Board_Members" table just like "Boards" and "Users" have a many-to-maany relationship. How do I do that? Do I create a new table and just reference the "userId" column as FK?

Just add a table with 2 foreign keys.
And because I think you want to switch the cards, from person to person. you could also want to keep track of the played history. See also the first normal form to check if your database is designed right.
https://en.wikipedia.org/wiki/First_normal_form
I hope I answered your question :)

Related

Postgres Update Query

I'm executing below query in postgres 12.11
Table structure as below:
CREATE TABLE pdb_interface.schedule (
id uuid NOT NULL DEFAULT uuid_generate_v4(),
report varchar NOT NULL,
users varchar NOT NULL,
"hour" int4 NULL,
min int4 NULL,
daily_frequency int4 NULL,
daily_workday bool NULL,
weekly_frequency int4 NULL,
weekly_days varchar NULL,
monthly_sected_days varchar NULL,
last_updated timestamp NULL,
deleted bool NULL,
CONSTRAINT schedule_pkey PRIMARY KEY (id),
CONSTRAINT schedule_report_fkey FOREIGN KEY (report) REFERENCES pdb_interface.report("Id"),
CONSTRAINT schedule_users_fkey FOREIGN KEY (users) REFERENCES pdb_interface.users("Id"));
update schedule
set daily_frequency = 12
where id = 'f2f0ba60-f8b1-49ae-a82c-aaddb1a1834b'
The column "id" is of uuid and value is present in the table . However while executing above query, it is giving below error
SQL Error [XX000]: ERROR: no conversion function from character varying to uuid
Is there any work around for the same

PostgreSQL/pgAdmin4 ERROR: there is no unique constraint matching given keys for referenced table "index"

I'm trying to transform my MySQL design to PostgreSQL but when I try to create the table "index":
CREATE TABLE "model1"."index" (
"id_index" INT GENERATED ALWAYS AS IDENTITY ,
"index_name" VARCHAR(5) NOT NULL,
"index_type_id_index_type" INT NOT NULL,
"index_provider_id_index_provider" INT NOT NULL,
"miseq" VARCHAR(45) NOT NULL,
"nextseq" VARCHAR(45) NOT NULL,
PRIMARY KEY ("id_index"),
CONSTRAINT "fk_index_index_type"
FOREIGN KEY ("index_type_id_index_type")
REFERENCES "model1"."index_type" ("id_index_type")
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT "fk_index_index_provider"
FOREIGN KEY ("index_provider_id_index_provider")
REFERENCES "model1"."index_provider" ("id_index_provider")
ON DELETE NO ACTION
ON UPDATE NO ACTION);
I got this error: ERROR: there is no unique constraint matching given keys for referenced table "index".
The two tables containing the foreign keys were created before the "index" table:
CREATE TABLE "model1"."index_type" (
"id_index_type" INT GENERATED ALWAYS AS IDENTITY ,
"name" VARCHAR(3) NOT NULL,
PRIMARY KEY ("id_index_type"));
CREATE TABLE "model1"."index_provider" (
"id_index_provider" INT GENERATED ALWAYS AS IDENTITY ,
"name" VARCHAR(40) NOT NULL,
PRIMARY KEY ("id_index_provider"));
Solved. The error was in another table as #a_horse_with_no_name suggested.

with migration to fill slug with default value

In my Laravel 5.6/PostgreSQL 10.5 application
I have 2 tables :
CREATE TABLE public.rt_genres (
id serial NOT NULL,
published bool NULL DEFAULT false,
created_at timestamp NOT NULL DEFAULT now(),
updated_at timestamp NULL,
CONSTRAINT rt_genres_pkey PRIMARY KEY (id)
)...
CREATE TABLE public.rt_genre_translations (
id serial NOT NULL,
genre_id int4 NOT NULL,
"name" varchar(100) NOT NULL,
description text NOT NULL,
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
locale varchar(2) NOT NULL,
CONSTRAINT genre_translations_genre_id_locale_unique UNIQUE (genre_id, locale),
CONSTRAINT rt_genre_translations_pkey PRIMARY KEY (id),
CONSTRAINT genre_translations_genre_id_foreign FOREIGN KEY (genre_id) REFERENCES rt_genres(id) ON DELETE CASCADE
)
I need to add slug field in first rt_genres table
with migration rule:
$table->string('slug', 105)->unique();
and got error :
: Unique violation: 7 ERROR: could not create unique index "genres_slug_unique"
DETAIL: Key (slug)=(id) is duplicated.")
1)If there is a way to assign in migration some unique default value, like = id
->default('rt_genres.id')
?
2) That would be cool to assign to slug value from public.rt_genre_translations.name as I use
"cviebrock/eloquent-sluggable": "^4.5" plugin in my app ? Can I do it ?
Thank you!
You can only get the default value from a different column with a trigger (SO answer).
You can make the column nullable:
$table->string('slug', 105)->nullable()->unique();
Or you create the column, insert unique values and then create the index:
Schema::table('rt_genres', function($table) {
$table->string('slug', 105);
});
DB::table('rt_genres')->update(['slug' => DB::raw('"id"')]);
Schema::table('rt_genres', function($table) {
$table->unique('slug');
});

PostgreSQL foreign keys multiple keys on single table

I can imagine that it is unlikely that this question has never been answered. However, I have not found it, so in any case here is my problem:
I am migrating from MySQL.
I am getting an error when I try to create a table with one single data field with 2 foreign keys referencing another table.
My goal is to simply have a phone directory for employees.
The directory table must reference the employee id as well as the phone number type.
I get this error when trying to do so:
ERROR: There is no unique constraint matching given keys, for referenced table: Employees!
Here is my current sql dump:
-- ----------------------------
-- Table structure for EmployeeGroups
-- ----------------------------
DROP TABLE IF EXISTS "public"."EmployeeGroups";
CREATE TABLE "public"."EmployeeGroups" (
"Id" int8 DEFAULT nextval('"EmployeeGroups_Id_seq"'::regclass) NOT NULL,
"EmployeeGroup" varchar(255) COLLATE "default"
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for Employees
-- ----------------------------
DROP TABLE IF EXISTS "public"."Employees";
CREATE TABLE "public"."Employees" (
"Id" int8 DEFAULT nextval('"Employees_Id_seq"'::regclass) NOT NULL,
"EmployeeGroupId" int8 DEFAULT
nextval('"Employees_EmployeeGroupId_seq"'::regclass) NOT NULL,
"FirstName" varchar(255) COLLATE "default",
"LastName" varchar(255) COLLATE "default",
"CivicNumber" int4,
"CivicNumberAlias" int4,
"StreetName" varchar(255) COLLATE "default",
"City" varchar(255) COLLATE "default",
"PostalCode" varchar(255) COLLATE "default",
"UserAcessLevel" int8 DEFAULT
nextval('"Employees_UserAcessLevel_seq"'::regclass) NOT NULL,
"Username" varchar(255) COLLATE "default",
"Password" varchar(255) COLLATE "default",
"Timestamp" date
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for PhoneNumberType
-- ----------------------------
DROP TABLE IF EXISTS "public"."PhoneNumberType";
CREATE TABLE "public"."PhoneNumberType" (
"Id" int8 DEFAULT nextval('"PhoneNumberType_Id_seq1"'::regclass) NOT NULL,
"PhoneNumberType" varchar(150) COLLATE "default" NOT NULL
)
WITH (OIDS=FALSE)
;
-- ----------------------------
-- Table structure for SystemAcessLevel
-- ----------------------------
DROP TABLE IF EXISTS "public"."SystemAcessLevel";
CREATE TABLE "public"."SystemAcessLevel" (
"Id" int8 DEFAULT nextval('"SystemAcessLevel_Id_seq"'::regclass) NOT NULL,
"AcessLevel" varchar(255) COLLATE "default" NOT NULL
)
WITH (OIDS=FALSE);
Here is my error generating statement:
CREATE TABLE "public"."NewTable" (
"Id" serial8 NOT NULL,
"EmployeeId" int8 NOT NULL,
"PhoneNumberTypeId" int8 NOT NULL,
"PhoneNumber" varchar(16) NOT NULL,
PRIMARY KEY ("Id"),
CONSTRAINT "phone_fk_emp_id" FOREIGN KEY ("EmployeeId")
REFERENCES "public"."Employees" ("Id") ON DELETE NO ACTION ON UPDATE
CASCADE,
CONSTRAINT "phone_fk_type_id" FOREIGN KEY ("PhoneNumberTypeId")
REFERENCES "public"."PhoneNumberType" ("Id") ON DELETE NO ACTION ON
UPDATE CASCADE
)
WITH (OIDS=FALSE)
;
As it turns out the problem was identifying the
EmployeeGroupId
field that was referenced in the Employees table as a second primary key created a conflict when adding the EmployeeDirectory table referencing the same foreing key as a second primary key of the Employees.GroupId field.
In other word seems like PostgreSQL considers second primary key as unique identifiers creating a one to one relationship therefore it considers it as an error to have an additional table referencing the same identifier as a foreing key stated as a second primary key, and please correct me if I am wrong since not an expert when it comes to PostgreSQL.
This however is accepted by Mysql; this is why I was having a hard time figuring out this error.
Every column (or set of columns) that you reference in a foreign key must have a primary key or unique constraint on it.
Otherwise, how could you identify which row the foreign key points to?

pgAdmin - When trying to make a foreign key "referencing" gives no options

I have three tables: ModelingAgency.clients, ModelingAgency.models, ModelingAgency.Bookings. All three tables have a primary key column called id.
The table bookings has two columns that reference clients and models. In pgAdmin when I try to create a foreign key in bookings to either clients or models I get the following screens:
What am I overlooking here? I am new to PostgreSQL (This is my first test project with PostgreSQL -- I've always used MySQL and occasionally SQL Server) so it's probably something obvious (I just don't see it).
EDIT: Here is the DDL, as requested:
-- Table: "ModelingAgency.bookings"
-- DROP TABLE "ModelingAgency.bookings";
CREATE TABLE "ModelingAgency.bookings"
(
id integer NOT NULL DEFAULT nextval('"ModelingAgency.Bookings_id_seq"'::regclass),
"clientId" integer NOT NULL,
"modelId" integer NOT NULL,
"time" timestamp with time zone NOT NULL DEFAULT now(),
"location" character varying(100) NOT NULL DEFAULT 'No Location Selected'::character varying,
CONSTRAINT "bookingId" PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE "ModelingAgency.bookings" OWNER TO "MyBatisTutorial";
-- Table: "ModelingAgency.clients"
-- DROP TABLE "ModelingAgency.clients";
CREATE TABLE "ModelingAgency.clients"
(
id integer NOT NULL DEFAULT nextval('"ModelAgency.clients_id_seq"'::regclass),
"name" character varying(45) NOT NULL,
CONSTRAINT "clientId" PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE "ModelingAgency.clients" OWNER TO "MyBatisTutorial";
-- Table: "ModelingAgency.models"
-- DROP TABLE "ModelingAgency.models";
CREATE TABLE "ModelingAgency.models"
(
id serial NOT NULL,
"name" character varying(45) NOT NULL,
CONSTRAINT "modelId" PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE "ModelingAgency.models" OWNER TO "MyBatisTutorial";
Looking into your posted DDL code I see that your table's names are written in wrong way (that causes your issue with pgAdmin):
"ModelingAgency.bookings"
It should be in format "schema"."tableName":
"ModelingAgency"."bookings"
After that Object browser looks like this (probably you need to create schema first using easily pgAdmin or with CREATE SCHEMA SQL statement):
Here is working DDL code (I omitted some things like OIDS and OWNER TO, but that doesn't matter to your case, BTW OIDS are false on default):
DROP TABLE IF EXISTS "ModelingAgency"."bookings";
CREATE TABLE "ModelingAgency"."bookings"
(
id serial,
"clientId" integer NOT NULL,
"modelId" integer NOT NULL,
"time" timestamp with time zone NOT NULL DEFAULT now(),
"location" character varying(100) NOT NULL
DEFAULT 'No Location Selected'::character varying,
CONSTRAINT "bookingId" PRIMARY KEY (id)
);
DROP TABLE IF EXISTS "ModelingAgency"."clients";
CREATE TABLE "ModelingAgency"."clients"
(
id serial,
"name" character varying(45) NOT NULL,
CONSTRAINT "clientId" PRIMARY KEY (id)
);
DROP TABLE IF EXISTS "ModelingAgency"."models";
CREATE TABLE "ModelingAgency"."models"
(
id serial NOT NULL,
"name" character varying(45) NOT NULL,
CONSTRAINT "modelId" PRIMARY KEY (id)
)