On a quite simple table
CREATE TABLE collectionmaster
(
id character varying(32) NOT NULL,
version integer,
publisherid character varying(12),
title character varying(1024),
subtitle character varying(1024),
type character varying(255) NOT NULL,
CONSTRAINT collectionmaster_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
CREATE INDEX idx_coll_title
ON collectionmaster
USING btree
(title COLLATE pg_catalog."default");
I tried to add a unique check either via unique index
CREATE UNIQUE INDEX idx_uni_coll_title
ON collectionmaster
USING btree
(publisherid COLLATE pg_catalog."default", title COLLATE pg_catalog."default", (COALESCE(subtitle, 'no_sub'::character varying)) COLLATE pg_catalog."default");
or via unique constraint
ALTER TABLE collectionmaster
ADD CONSTRAINT uni_coll_title UNIQUE(publisherid, title, subtitle);
to intercept accidentally multiple creation by a java service (spring-jpa on hibernate) executed in several threads. But strangely neither of index and constraint works as expected. Eight records are added by eight threads which are not unique according to either constraint or index in separate transaction, but no unique violations are thrown, and all records are inserted into the table. And none of the values are null, as was the problem in other questions here.
The constaint was not deferred, index as constraint where valid.
Postgres version is 9.2.
I am quite clueless here.
EDIT: These are the results of a query in this table, extracted from pgAdmin (hard to format it nicer here):
"id";"version";"publisherid";"title";"subtitle";"type"
"53b3df625baf40bf885b48daa366fbc8";1;"5109138";"Titel";"Untertitel";"set"
"2673ef9a33f84289995d6f7288f07b46";1;"5109138";"Titel";"Untertitel";"set"
"ef7c385205034fdc89fe39e3eca48408";1;"5109138";"Titel";"Untertitel";"set"
"527922f2f3464f91826dbae2e2b67caf";1;"5109138";"Titel";"Untertitel";"set"
"794638a725324319852d10b828257df7";1;"5109138";"Titel";"Untertitel";"set"
"dbe2201058974d63a2107131f0080233";1;"5109138";"Titel";"Untertitel";"set"
"cbb77c7c1adb415db006853a6f6244ac";1;"5109138";"Titel";"Untertitel";"set"
"0b6606fe015040fbbc85444361ab414c";1;"5109138";"Titel";"Untertitel";"set"
Even on these I can execute
insert into collectionmaster(id, version, publisherid, title, subtitle, type) values('aaa',1,'5109138','Titel','Untertitel','set')
without getting a constraint violation. I can't believe it, too, but this is the problem...
Make sure your spring-jpa config spring.jpa.hibernate.ddl-auto is not set to create-drop.
That way, hibernate will always drop & re-create your whole schema, which won't contain your custom unique constraints, nor your indexes.
Related
I have the following table in my database, the table was created using django and architect.
CREATE TABLE public.results
(
results_id integer NOT NULL DEFAULT nextval('results_results_id_seq'::regclass),
name character varying(45) COLLATE pg_catalog."default" NOT NULL,
value double precision NOT NULL,
scenario_id integer NOT NULL,
CONSTRAINT results_pkey PRIMARY KEY (results_id),
CONSTRAINT results_scenario_id_name_22ad9c45_uniq UNIQUE (scenario_id, name),
CONSTRAINT results_scenario_id_d800e53c_fk_scenario_scenario_id FOREIGN KEY (scenario_id)
REFERENCES public.scenario (scenario_id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
DEFERRABLE INITIALLY DEFERRED
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
The problem I face occurs when I run the following query
insert into
results ("scenario_id","name","value")
values
(44,'footprint_km2',1000)
on conflict
("scenario_id","name")
do update set
"value"= excluded.value;
duplicate key value violates unique constraint "results_1_500000_scenario_id_name_key"
DETAIL: Key (scenario_id, name)=(44, footprint_km2) already exists
which makes no sense to me because I specified an update action when a conflict occurs.
¿Do you know what I am doing wrong?
PostgreSQL/PGAdmin4 ERROR: there is no unique constraint matching given keys for referenced table
This is the ‘schema’ I’m trying to code into PGAdmin4/Postgresql:
http://i.imgur.com/xPEu8Sh.jpg
I was able to convert all tables, except “QUALIFICATIONS”.
I tried to process the following query:
create table REGISTRATION(
StudentID int,
SectionNo int,
Semester varchar(16),
foreign key(StudentID) references Student(StudentID),
foreign key (SectionNo, Semester) references Section(SectionNo, Semester),
primary key(studentID, SectionNo, Semester)
);
I received the following message:
ERROR: there is no unique constraint matching given keys for referenced table "section"
These are the foreign and primary I have in the table SECTION
PKEY: i.imgur.com/BcUNKug.jpg
FKEY: i.imgur.com/D8B8hRW.jpg
Code of SECTION table:
CREATE TABLE class_scheduling_01.section
(
sectionno integer NOT NULL,
semester character varying(16) COLLATE pg_catalog."default" NOT NULL,
courseid character varying(16) COLLATE pg_catalog."default" NOT NULL,
CONSTRAINT section_pkey PRIMARY KEY (sectionno, semester, courseid),
CONSTRAINT section_sectionno_key UNIQUE (sectionno),
CONSTRAINT section_courseid_fkey FOREIGN KEY (courseid)
REFERENCES class_scheduling_01.course (courseid) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
I additionally ran the command: ALTER TABLE section ADD UNIQUE (sectionno);
Since none of the attributes seemed to be repeating itself.
Despite all this I’m getting:
ERROR: there is no unique constraint matching given keys for referenced table "section" Query returned successfully in 642 msec.
Edit: I've gone back to the COURSE table and made courseID a unique constraint. I still get the same message. SECTION table has a composite primary key made up of 3 columns. As seen in the first picture linked, out of all the values, only SECTION.sectionno is the only column with unique/non-repeating values.
2nd edit: I decided to create the table "REGISTRATION" one step at a time, and make the foreign keys last with alter table command.
I was able to make the columns StudentID andd SectionNo foreign keys to their respective columns. When I tried to make REGISTRATION.semester a foreign key to SECTION.semester I got the error message again.
alter table REGISTRATION add foreign key (semester) references section(semester);
As seen in the image I linked Semester value, is repeated; despite this, am I still required to make it unique? Or do I make a unique command assigning all 3 columns (of SECTION) together as unique, instead of just 1? If so, how?
This
foreign key (SectionNo, Semester) references Section(SectionNo, Semester),
requires that there be a unique constraint on the pair of columns SectionNo and Semester.
CREATE TABLE class_scheduling_01.section
(
sectionno integer NOT NULL,
semester character varying(16) COLLATE pg_catalog."default" NOT NULL,
courseid character varying(16) COLLATE pg_catalog."default" NOT NULL,
CONSTRAINT section_pkey PRIMARY KEY (sectionno, semester, courseid),
CONSTRAINT section_sectionno_key UNIQUE (sectionno),
CONSTRAINT section_courseid_fkey FOREIGN KEY (courseid)
REFERENCES class_scheduling_01.course (courseid) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION,
-- Unique constraint on the pair
CONSTRAINT your_constraint_name UNIQUE (SectionNo, Semester)
);
That change should let these SQL statements succeed. I didn't check to see whether that's a good idea.
SQL is case insensitive.
I understand what you mean, but this is a bad way to think about it.
PostgreSQL folds unquoted identifiers to lowercase. So PostgreSQL would treat the identifiers SQL, Sql, and sql as if they were all sql. A quoted or delimited identifier, like "Select" always refers to either a table or a column; it's never interpreted as a keyword. Quoted identifiers are case-sensitive. You can't successfully refer to the table "Select" as select.
In my PostgreSQL database I have the following tables (simplified):
CREATE TABLE quotations (
receipt_id bigint NOT NULL PRIMARY KEY
);
CREATE TABLE order_confirmations (
receipt_id bigint NOT NULL PRIMARY KEY
fk_quotation_receipt_id bigint REFERENCES quotations (receipt_id)
);
My problem now reads as follows:
I have orders which relate to previous quotations (which is fine 'cause I can attach such an order to the quotation referenced by using the FK field), but I also have placed-from-scratch orders without a matching quotation. The FK field would then be NULL, if the database let me, of course. Unfortunately, I get an error when trying to set fk_quotation_receipt_id to NULL in an INSERT statement because of a violated foreign key constraint.
When designing these tables I was still using PgSQL 8.2, which allowed NULL values. Now I've got 9.1.6, which does not allow for this.
What I wish is an optional (or nullable) foreign key constraint order_confirmations (fk_quotation_receipt_id) → quotations (receipt_id). I can't find any hints in the official PgSQL docs, and similar issues posted by other users are already quite old.
Thank you for any useful hints.
Works for me in 9.3 after correcting a missing comma. I'm sure it will work also in 9.1
create table quotations (
receipt_id bigint not null primary key
);
create table order_confirmations (
receipt_id bigint not null primary key,
fk_quotation_receipt_id bigint references quotations (receipt_id)
);
insert into order_confirmations (receipt_id, fk_quotation_receipt_id) values
(1, null);
Confirmation will include:
INSERT 0 1
I am creating tables to handle the security question/selected question/given answer section of our database and getting this error:
there is no unique constraint matching given keys for referenced table "m_security_questions"
Not sure how I fix this?
(Since schema won't build b/c of error, I couldn't add SQL Fiddle)
CREATE TABLE security_question --defines questions
(
id SERIAL PRIMARY KEY NOT NULL,
question character varying(1024) NOT NULL,
is_custom boolean DEFAULT FALSE NOT NULL
);
INSERT INTO security_question
(question,is_custom)
VALUES
('do you know the answer?',FALSE),
('Write your own question',TRUE);
CREATE TABLE m_security_questions
( --defines question a member chooses & allows free form question
-- id SERIAL NOT NULL,
-- I know adding id like this and making keeping same pk solves it
-- but isn't storing the extra sequence not needed?
member integer --REFERENCES member(m_no)
-- commented out reference for so only
NOT NULL,
question integer REFERENCES security_question(id) NOT NULL,
m_note text,
PRIMARY KEY(member,question)
);
-- here I add unique constraint but doesn't the primary already mean I have a unique index?
ALTER TABLE m_security_questions ADD CONSTRAINT m_security_questions_unique_member_question UNIQUE (member,question);
INSERT INTO m_security_questions
(member,question,m_note)
VALUES
(2,1,NULL),
(2,2,'How many marbles in this jar?');
CREATE TABLE m_security_answer --defines members given answer
( -- I want member & question here to line up w/ same from m_security_questions
member integer REFERENCES m_security_questions(member),
question integer REFERENCES m_security_questions(question) NOT NULL,
answer character varying(255) NOT NULL,
PRIMARY KEY (member,question)
);
-- here is where I get the error:
-- there is no unique constraint matching given keys for referenced table "m_security_questions"
INSERT INTO m_security_answer
(member,question,answer)
VALUES
(2,1,'yes'),
(2,2,'431');
The primary key definitely defines a unique constraint. But the unique constraint is on (member,question). Your have two FOREIGN KEY constraints that references just (member) and (question) separately.
I'm pretty sure what you want is:
CREATE TABLE m_security_answer --defines members given answer
(
member integer,
question integer NOT NULL,
answer character varying(255) NOT NULL,
PRIMARY KEY (member,question),
FOREIGN KEY (member, question) REFERENCES m_security_questions(member, question)
);
I have created a database in PostgreSQL (8.4 - I need to use this version because I want to use MapFish which does not (yet) support 9.0) which has some inherited tables:
CREATE TABLE stakeholder
(
pk_stakeholder integer DEFAULT nextval('stakeholder_seq') NOT NULL,
fk_stakeholder_type integer NOT NULL,
name character varying(255) NOT NULL,
CONSTRAINT stakeholder_primarykey PRIMARY KEY (pk_stakeholder),
CONSTRAINT stakeholder_fk_stakeholder_type FOREIGN KEY (fk_stakeholder_type)
REFERENCES stakeholder_type (pk_stakeholder_type) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE NO ACTION
);
CREATE TABLE individual
(
firstname character varying(50),
fk_title integer,
email1 character varying (100),
email2 character varying (100),
phone1 character varying (50),
phone2 character varying (50),
CONSTRAINT individual_primarykey PRIMARY KEY (pk_stakeholder),
CONSTRAINT individual_fk_title FOREIGN KEY (fk_title)
REFERENCES individual_title (pk_individual_title) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE NO ACTION
) INHERITS (stakeholder)
(as learned from an earlier question, I'm using a seperate table (stakeholder_pk) to keep track of my primary keys using triggers)
Now I'd like to reflect my database in SQLAlchemy (0.7.1):
meta.metadata.reflect(bind=engine)
table_stakeholder = meta.metadata.tables["stakeholder"]
table_individual = meta.metadata.tables["individual"]
stakeholder_mapper = orm.mapper(Stakeholder, table_stakeholder,
polymorphic_on=table_stakeholder.c.fk_stakeholder_type,
polymorphic_identity='stakeholder')
orm.mapper(Individual, table_individual, inherits=stakeholder_mapper,
polymorphic_identity='individual')
This however results in an sqlalchemy.exc.ArgumentError: Can't find any foreign key relationships between 'stakeholder' and 'individual'.
Now I've seen some examples where they use the primary key of the child tables (in my case: individual) as a foreign key to point at the primary key of the parent table (stakeholder). However, PostgreSQL will not let me do this, saying that this would violate a foreign key constraint since the primary key in the parent table (stakeholder) is not there (?).
So now I'm pretty much stuck and after hours of searching for a solution I'm starting to lose track of it. Is this a problem in PostgreSQL (similar to the primary key & inheritance issue) or is it because of SQLAlchemy? Or is it just me doing something fundamentally wrong?
It is in PostgreSQL:
All check constraints and not-null constraints on a parent table are automatically inherited by its children. Other types of constraints (unique, primary key, and foreign key constraints) are not inherited.
These deficiencies will probably be fixed in some future release, but in the meantime considerable care is needed in deciding whether inheritance is useful for your application.
http://www.postgresql.org/docs/9.0/interactive/ddl-inherit.html
Is it possible to drop triggers and to have in individual:
pk_stakeholder integer DEFAULT nextval('stakeholder_seq') NOT NULL,
...
CONSTRAINT stakeholder_primarykey PRIMARY KEY (pk_stakeholder),
This will not stop individual to have pk_stakeholder that exists in stakeholder if you update pk_stakeholder later. So here triggers are required to stop update (easier) or to check.