postgresql key contraint fault - postgresql

I try to create code for postgresql
CREATE TABLE kaart (
kaartid integer NOT NULL,
naam character varying,
saldo real,
kaarthouderid integer
);
CREATE TABLE kaart_product (
kaartkaartid integer,
productid2 integer
);
CREATE TABLE kaarthouder (
id integer NOT NULL,
naam character varying(255),
naw character varying(255),
geslacht "char"
);
CREATE TABLE product (
naam character varying,
id integer NOT NULL
);
ALTER TABLE ONLY kaart
ADD CONSTRAINT kaart_pkey PRIMARY KEY (kaartid);
ALTER TABLE ONLY kaarthouder
ADD CONSTRAINT kaarthouder_pkey PRIMARY KEY (id);
ALTER TABLE ONLY product
ADD CONSTRAINT product_pkey PRIMARY KEY (id);
ALTER TABLE ONLY kaart
ADD CONSTRAINT kaartco FOREIGN KEY (kaartid) REFERENCES kaarthouder(id) ON UPDATE CASCADE ON DELETE CASCADE;
ALTER TABLE ONLY kaart_product
ADD CONSTRAINT kaartkaartidco FOREIGN KEY (kaartkaartid) REFERENCES kaart(kaartid) ON UPDATE CASCADE ON DELETE CASCADE;
ALTER TABLE ONLY kaart_product
ADD CONSTRAINT productidco FOREIGN KEY (kaartkaartid) REFERENCES product(id) ON UPDATE CASCADE ON DELETE CASCADE;
INSERT INTO kaart VALUES (1, 'Sander',50.00 ,1);
INSERT INTO kaart_product VALUES (1,1);
INSERT INTO kaarthouder VALUES (1, 'Sander','test,testing','man');
INSERT INTO product VALUES ('studentenproduct',1);
But whenever i try to run it it gives me this error:
23503: insert or update on table "kaart" violates foreign key constraint "kaartco"
But i really dont know why this happens since it is the same to the other foreign keys that are below it
So can someone help me fix this?

You try to link to a product and a kaart that doesn't exist yet.
Move:
INSERT INTO kaart_product VALUES (1,1);
Two lines down under:
INSERT INTO product VALUES ('studentenproduct',1);
That should do the job for you.
Try to search google for forgein key contstraints and how they work.

Related

Altering Column Type in SQL (PGadmin) not working

I am new to DB design and have created my tables in Postgres. However, I need to change the datatype of one of my tables from date to integer'. However, when I add the code in to do this, I get the following error:
ERROR: cannot cast type date to integer
LINE 13: ALTER COLUMN year TYPE INT USING year::integer;
It was recommended that I add the USING line to override this error, but it did not solve my problem.
Below is the entire code, any advice would be great appreciated.
BEGIN;
CREATE TABLE IF NOT EXISTS public."Actor"
(
actor1_name "char",
actor_id numeric,
actor_type "char",
PRIMARY KEY (actor_id)
);
CREATE TABLE IF NOT EXISTS public."Country"
(
country_name "char",
country_id numeric,
PRIMARY KEY (country_id)
);
CREATE TABLE IF NOT EXISTS public."Event"
(
event_id numeric,
event_type_descr "char",
event_date date,
**year date,**
fatalities numeric,
event_type "char",
PRIMARY KEY (event_id)
);
**ALTER TABLE "Event"
ALTER COLUMN year TYPE INT USING year::integer;**
CREATE TABLE IF NOT EXISTS public."Location"
(
location_name "char",
longitude numeric,
latitude numeric,
location_id numeric,
PRIMARY KEY (location_id)
);
CREATE TABLE IF NOT EXISTS public."Region"
(
region_name "char",
region_id numeric,
PRIMARY KEY (region_id)
);
CREATE TABLE IF NOT EXISTS public."Event_Actor"
(
"Event_event_id" numeric,
"Actor_actor_id" numeric
);
ALTER TABLE public."Location"
ADD FOREIGN KEY (location_id)
REFERENCES public."Country" (country_id)
NOT VALID;
ALTER TABLE public."Country"
ADD FOREIGN KEY (country_id)
REFERENCES public."Region" (region_id)
NOT VALID;
ALTER TABLE public."Event_Actor"
ADD FOREIGN KEY ("Event_event_id")
REFERENCES public."Event" (event_id)
NOT VALID;
ALTER TABLE public."Event_Actor"
ADD FOREIGN KEY ("Actor_actor_id")
REFERENCES public."Actor" (actor_id)
NOT VALID;
ALTER TABLE public."Event"
ADD FOREIGN KEY (event_id)
REFERENCES public."Location" (location_id)
NOT VALID;
END;
Assuming from the column names that you want the year part of the date as integer (you should clearly express that in a question!), you can use extract().
ALTER TABLE "Event"
ALTER COLUMN year
TYPE integer
USING extract(YEAR FROM year);
And as a side note: Avoid case sensitive object names like "Event". They only make things harder but have no benefit. If you need "pretty" labels, that's a job for the presentation layer, not the database anyway.

postgresql: constaint to have unique values across 2 tables

I have 2 tables:
CREATE TABLE public."user"
(
id integer NOT NULL DEFAULT nextval('user_id_seq'::regclass),
username character varying(256) COLLATE pg_catalog."default",
CONSTRAINT user_pkey PRIMARY KEY (id)
)
CREATE TABLE public.user_tenant
(
user_id integer NOT NULL,
tenant_id integer NOT NULL,
CONSTRAINT user_fk FOREIGN KEY (user_id)
REFERENCES public."user" (id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE CASCADE
)
I need to have unique values (user.username, user_tenant.tenant_id). How can I declare such a constraint?
I would make the username unique, just like the tenant that is in another table. When that is done, you can put a primary key on the user_id and tenant_id:
CREATE TABLE public."user"
(
id integer NOT NULL DEFAULT nextval('user_id_seq'::regclass),
username character varying(256) COLLATE pg_catalog."default" unique,
CONSTRAINT user_pkey PRIMARY KEY (id)
);
CREATE TABLE public.user_tenant
(
user_id integer NOT NULL,
tenant_id integer NOT NULL,
CONSTRAINT user_fk FOREIGN KEY (user_id)
REFERENCES public."user" (id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE CASCADE,
CONSTRAINT user_tenant_pk PRIMARY KEY (user_id, tenant_id)
);
By the way, don't use reserved names like "user" for table names.
You can create a function which can check for uniqueness across multiple tables (example here: Postgres unique combination constraint across tables) but it looks like you may need to the structure of your tables or follow Frank Heikens' answer.
EDIT:
CREATE TABLE public."user"
(
id SERIAL,
username character varying(256) COLLATE pg_catalog."default",
PRIMARY KEY (id)
);
CREATE TABLE public.user_tenant
(
user_id integer NOT NULL,
tenant_id integer NOT NULL,
CONSTRAINT user_fk FOREIGN KEY (user_id)
REFERENCES public."user" (id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE CASCADE
);
CREATE OR REPLACE FUNCTION public.check_user_tenant(user_id integer, tenant_id integer)
RETURNS boolean AS
$$
DECLARE b_result boolean;
BEGIN
SELECT (COUNT(*) = 0) INTO b_result
FROM public.user u
JOIN public.user_tenant ut ON ut.user_id IN (SELECT id
FROM public.user i_u
WHERE i_u.username = u.username)
WHERE u.id = $1 AND ut.tenant_id = $2;
RETURN b_result;
END
$$ LANGUAGE 'plpgsql';
ALTER TABLE public.user_tenant
ADD CONSTRAINT check_filename CHECK
(public.check_user_tenant(user_id, tenant_id));
-- Testing:
insert into public."user" (username) VALUES ('foo');
insert into public.user_tenant (user_id, tenant_id) VALUES (1,3);
insert into public."user" (username) VALUES ('foo');
-- Violates constraint:
insert into public.user_tenant (user_id, tenant_id) VALUES (2,3);

How to add a foreign key for table B by referring of table A and foreign key for table A by referring table B in PostgreSQL?

I need to add a foreign keys for two tables each other. Can this be done ?
As an example:
CREATE SCHEMA IF NOT EXISTS schema1;
CREATE TABLE schema1.tableA
(
id serial NOT NULL,
tableB_id integer,
PRIMARY KEY (id),
FOREIGN KEY (tableB_id) REFERENCES schema1.tableB (id)
);
CREATE TABLE schema1.tableB
(
id serial NOT NULL,
tableA_id integer,
PRIMARY KEY (id),
FOREIGN KEY (tableA_id) REFERENCES schema1.tableA(id)
);
Above query causes an error !
ERROR: relation "schema1.tableb" does not exist SQL state: 42P01
Can this be done or is there any better solution?
I'am using PostgreSQL version 10.5 and pgAdmin 3.6
Add the foreign keys after creating both tables:
CREATE SCHEMA IF NOT EXISTS schema1;
CREATE TABLE schema1.tableA
(
id serial NOT NULL,
tableB_id integer,
PRIMARY KEY (id)
);
CREATE TABLE schema1.tableB
(
id serial NOT NULL,
tableA_id integer,
PRIMARY KEY (id)
);
ALTER TABLE schema1.tablea
add FOREIGN KEY (tableB_id) REFERENCES schema1.tableB (id);
ALTER TABLE schema1.tableb
add foreign key (tableA_id) REFERENCES schema1.tableA(id);

Find cause of error "constraint xxxx is not a foreign key constraint" in Postgresql

I have defined these tables:
CREATE TABLE "public".category (id BIGSERIAL NOT NULL, name varchar(255) NOT NULL, PRIMARY KEY (id));
CREATE UNIQUE INDEX category_name ON "public".category (name);
CREATE TABLE "public".clusters (id BIGSERIAL NOT NULL, name varchar(255) NOT NULL, PRIMARY KEY (id));
CREATE INDEX clusters_name ON "public".clusters (name);
CREATE TABLE "public".keywords (id BIGSERIAL NOT NULL, text varchar(255) NOT NULL, category_id int8 NOT NULL, top_results int4, cluster_id int8, month_requests int4, click_cost float8, PRIMARY KEY (id));
CREATE INDEX keywords_text ON "public".keywords (text);
ALTER TABLE "public".keywords ADD CONSTRAINT FKkeywords488682 FOREIGN KEY (cluster_id) REFERENCES "public".clusters (id);
ALTER TABLE "public".keywords ADD CONSTRAINT FKkeywords446526 FOREIGN KEY (category_id) REFERENCES "public".category (id) ON UPDATE CASCADE ON DELETE CASCADE;
added one record to category table:
INSERT INTO "public".category(id, name) VALUES (1, 'Test');
And now when I try to add record to keyword table
insert into "public"."keywords" ( "category_id", "text") values ( 1, 'testkey')
I got error:
ERROR: constraint 16959 is not a foreign key constraint
When I do
select * FROM pg_constraint;
I can't see constraint with this id. I can't understand what is the cause of this problem.

Foreign keys in Postgres

i´ve got a problem with foreign keys, it´s an strange problem.
First table:
CREATE TABLE adjunto
(
id serial NOT NULL,
codigo text,
descripcion text,
usuario integer,
file integer,
nombre text,
propiedades hstore,
CONSTRAINT adjunto_pkey PRIMARY KEY (id ),
CONSTRAINT adjunto_file_fkey FOREIGN KEY (file)
REFERENCES file (file_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE
) WITH (
OIDS=FALSE
);
Second table:
CREATE TABLE adjunto_coleccion_privada
(
id serial NOT NULL,
adjunto integer,
coleccion integer,
CONSTRAINT adjunto_coleccion_privada_pkey PRIMARY KEY (id ),
CONSTRAINT adjunto_coleccion_privada_adjunto_fkey FOREIGN KEY (adjunto)
REFERENCES adjunto (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE,
CONSTRAINT adjunto_coleccion_privada_coleccion_fkey FOREIGN KEY (coleccion)
REFERENCES coleccion (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE
)
WITH (
OIDS=FALSE
);
Command:
INSERT INTO adjunto_coleccion_privada (adjunto, coleccion)
VALUES (600, 2) RETURNING id
Values 600 and 2 exist in both tables, adjunto and colecion.
Detailed error:
Mensaje: ERROR: insert or update on table "adjunto_coleccion_privada"
violates foreign key
constraint "adjunto_coleccion_privada_adjunto_fkey"
Detail: Key (adjunto)=(600) is not present in table "adjunto".
I tested your code (I dropped the adjunto_coleccion_privada_coleccion_fkey constraint since referred table does not exist in your pasted code).
I see no problem at all.
Are you really sure that there is a record with id = 600 in the adjunto table?