PostgreSQL foreign keys multiple keys on single table - postgresql

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?

Related

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.

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

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 :)

PGSQL Insert into A get ID to Insert into B

Table A is a kind of unique sequence for all my tables.
-- Table: public."IdCentral"
-- DROP TABLE public."IdCentral";
CREATE TABLE public."IdCentral"
(
"Id" bigint NOT NULL DEFAULT nextval('"IdCentral_Id_seq"'::regclass),
"Tag" character varying(127) COLLATE pg_catalog."default",
CONSTRAINT "IdCentral_pkey" PRIMARY KEY ("Id")
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
Table B is any table of my database
-- Table: public."Users"
-- DROP TABLE public."Users";
CREATE TABLE public."Users"
(
"Id" bigint NOT NULL,
"Login" character varying(30) COLLATE pg_catalog."default" NOT NULL,
CONSTRAINT "Users_pkey" PRIMARY KEY ("Id"),
CONSTRAINT "PK" FOREIGN KEY ("Id")
REFERENCES public."IdCentral" ("Id") MATCH FULL
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE public."Users"
OWNER to dba;
When I want to insert into B, I need to create a new record in A passing the B Table name as Tag.
What you want is CURRVAL:
SELECT CURRVAL('IdCentral_Id_seq');
... which will give you the current value for the ID sequence after insert. For safety, it's best to use it inside a transaction, especially if you're combining it with load-balancing:
BEGIN;
INSERT INTO "a" ...
INSERT INTO "b" VALUES ( CURRVAL('IdCentral_Id_seq', ... )
COMMIT;
That being said, it appears that you're implementing a "universal ID" system for your database. This is something every new DBA tries (I did), and it's inevitably a bad idea which you end up spending a lot of time refactoring out later. If there's some reason you genuinely need some kind of universal ID, consider using a UUID instead.

Update ID column from another table while using copy from csv

I am trying to import data to a table using COPY from a csv file. This is the table in which I want to import:
CREATE TABLE public.forms_member_registration
(
baseformmodel_ptr_id integer NOT NULL,
"Agrihub" character varying(200) NOT NULL,
"Ward_Number" character varying(300) NOT NULL,
"Area" character varying(300) NOT NULL,
"First_Name" character varying(300) NOT NULL,
"Last_Name" character varying(300) NOT NULL,
"Other_Name" character varying(300) NOT NULL,
-----------snip--------------------------------
"L3_Modules_Completed" character varying(200),
"L3_Specify_Other" character varying(300) NOT NULL,
gps_location geometry(Point,4326),
CONSTRAINT forms_member_registration_pkey
PRIMARY KEY (baseformmodel_ptr_id),
CONSTRAINT baseformmodel_ptr_id_refs_id_c03f6c72
FOREIGN KEY (baseformmodel_ptr_id)
REFERENCES public.forms_baseformmodel (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
)
The primary key is referencing this table:
CREATE TABLE public.forms_baseformmodel
(
id integer NOT NULL DEFAULT nextval('forms_baseformmodel_id_seq'::regclass),
user_id integer NOT NULL,
created_at timestamp with time zone NOT NULL,
CONSTRAINT forms_baseformmodel_pkey
PRIMARY KEY (id),
CONSTRAINT user_id_refs_id_3a410ec9
FOREIGN KEY (user_id)
REFERENCES public.auth_user (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
)
I am using this copy command:
COPY forms_member_registration("Agrihub", "Ward_Number", "Area","First_Name", "Last_Name", "Other_Name", "SA_ID_Number", "Gender", "Phone_Number") FROM '/opt/project/migration/file-3.csv' DELIMITER ',' CSV HEADER;
Giving this error:
ERROR: null value in column "baseformmodel_ptr_id" violates not-null constraint
So the problem as I see it is that "baseform_ptr_id" needs to be retrieved from the id column of the forms_baseformmodel table for each entry but id only gets created when an entry is made to forms_baseformmodel.
How can I create the entry in forms_baseformmodel, retrieve it and add it to the tuple being copied?
Hope that makes sense... This is all kinda new for me.
Thanks in advance
This is a rather common problem. What you must do is:
COPY the data to a TEMPORARY or UNLOGGED table;
INSERT INTO real_table SELECT ... FROM temp_table INNER JOIN other_table ...
In other words, copy to a staging table, then generate the real data set with a join and insert the join product into the real table.
It's somewhat related to the bulk upsert problem.
So in your case you'd create a temp_forms_member_registration, copy the csv into it including the user_id column you wish to replace, then:
INSERT INTO forms_member_registration(
baseformmodel_ptr_id,
"Agrihub",
...
)
SELECT
fbfm.id,
tfmr."Agrihub",
...
FROM temp_forms_member_registration tfmr
INNER JOIN forms_baseformmodel ON (tfmr.user_id = fbfm.user_id);

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)
)