How to translate SQL "CHECK" and "COALESCE" to Entity Framework - postgresql

I am new to Entity Framework and this is working code in PostgreSQL:
CREATE TABLE likes
(
id SERIAL PRIMARY KEY,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
post_id INTEGER REFERENCES posts(id) ON DELETE CASCADE,
comment_id INTEGER REFERENCES comments(id) ON DELETE CASCADE,
CHECK(
COALESCE((post_id)::BOOLEAN::INTEGER, 0)
+
COALESCE((comment_id)::BOOLEAN::INTEGER, 0)
= 1
),
UNIQUE(user_id, post_id, comment_id)
);
Thanks Panagiotis.
I change the database schema as below.
enter image description here

Related

Postgresql - delete on cascade not deleting from a child table

I have tables master_bill and master_bill_order_leg and order_leg.
MasterBill and OrderLeg have many to many relationship.
This is the quick documentation from IntelliJ for the DB tables.
Table master_bill:
create table master_bill
(
id bigint not null
primary key,
mb_no bigint not null,
created_by text not null,
updated_by text not null,
created_at timestamp with time zone default now() not null,
updated_at timestamp with time zone default now() not null
);
Table master_bill_order_leg:
create table master_bill_order_leg
(
mb_id bigint
references master_bill
on delete cascade,
order_leg_id bigint
references order_leg
on delete cascade,
constraint master_bill_order_mb_id_order_leg_id_key
unique (mb_id, order_leg_id)
);
Table order_leg:
create table order_leg
(
id bigserial
primary key,
created_by text not null,
updated_by text not null,
created_at timestamp with time zone default now() not null,
updated_at timestamp with time zone default now() not null,
constraint order_leg_unique_c
unique (flight_id, flight_date, departure_iata, arrival_iata)
);
I have set the foreign keys and they look like this:
Table master_bill_order_leg
master_bill_order_leg_mb_id_fkey (mb_id) -> master_bill(id)
master_bill_order_leg_order_leg_id_fkey (order_leg_id) -> order_leg(id)
I thought that if I delete a row from the parent master_bill table that all relevant rows from the child table master_bill_order_leg would be deleted too because of foreign keys that are set with on delete cascade. So, I have tried with deleting a row from master_bill table:
DELETE
FROM master_bill
WHERE id = :mbId
But, then I get an error:
org.postgresql.util.PSQLException: ERROR: update or delete on table
"master_bill" violates foreign key constraint
"master_bill_order_leg_mb_id_fkey" on table
"master_bill_order_leg" Detail: Key (id)=(1076) is
still referenced from table "master_bill_order_leg".
Why do I get this error, what am I doing wrong here?
If I run this query directly from the query console then a row is deleted from the table master_bill and a child table master_bill_order_leg.

Many-to-one relationship using two unique keys

I have two tables which look like thiS:
uploads
________
id (primary key)
user_id
file_checksum
upload_information
---------
upload_info_id (primary key)
file_checksum
metadata1
metdata2
The "many to one" relationship I am trying to enforce is this:
Many uploads can have the same file checksum
However, the file checksum can only ever point to one upload_information record, thus making the unique constraint between file_checksum and upload_info_id mandatory in the upload_information table.
I am wondering how to alter these tables in Postgres in order to achieve this relationship.
CREATE TABLE uploads (
id SERIAL NOT NULL PRIMARY KEY,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
user_id VARCHAR NOT NULL,
file_checksum VARCHAR NOT NULL,
);
CREATE TABLE upload_information (
upload_info_id SERIAL NOT NULL PRIMARY KEY,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
file_checksum VARCHAR NOT NULL,
file_name VARCHAR NOT NULL,
source_file_url VARCHAR NOT NULL,
);
Add a unique index on file_checksum.
create unique index unique_checksum on upload_information(file_checksum)

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'questions_ibfk_1' in the referenced table 'category'

cannot add foreign key constraint to table
create table users
(
user_id int auto_increment primary key not null,
username varchar(50) unique null ,
email varchar(50) unique ,
passwords varchar(50) not null,
login_status boolean not null
);
create table category (
category_id int primary key not null,
category_name varchar(50) not null
);
create table answers (
id_answer int auto_increment primary key not null,
answer boolean not null
);
create table questions (
question_id int primary key not null,
category_name varchar(50) not null,
content varchar(50) not null ,
foreign key (category_name) references category (category_name)
);
You get this error because there's no index on category_name in the category table. Change that CREATE statement as follows:
create table category (
category_id int primary key not null,
category_name varchar(50) not null,
KEY category_name_index (category_name)
);
From the docs (8.0 version, but the statement is true for older versions):
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.
Also, you're using a varchar(50) as your foreign key, which is not usually a great idea for a variety of reasons. You probably want to use a numeric value, such as category_id, instead.

Resolving ON DELETE CASCADE in many-to-many relation

See: SQLFiddle
I am having a many-to-many relationship as such:
CREATE TABLE IF NOT EXISTS store (
id BIGSERIAL PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS collection (
id BIGSERIAL PRIMARY KEY,
store_id bigint NOT NULL,
FOREIGN KEY (store_id) REFERENCES store (id)
ON UPDATE CASCADE
);
CREATE TABLE IF NOT EXISTS item (
id BIGSERIAL PRIMARY KEY,
store_id bigint NOT NULL,
FOREIGN KEY (store_id) REFERENCES store (id)
ON UPDATE CASCADE
);
CREATE TABLE IF NOT EXISTS collection_item (
id BIGSERIAL PRIMARY KEY,
collection_id bigint NOT NULL,
item_id bigint,
UNIQUE (collection_id, item_id),
FOREIGN KEY (collection_id) REFERENCES collection (id)
ON DELETE CASCADE,
FOREIGN KEY (item_id) REFERENCES item (id)
ON DELETE SET NULL
);
INSERT INTO store (id) VALUES (1);
INSERT INTO item (id, store_id) VALUES (1, 1);
INSERT INTO collection (id, store_id) VALUES (1, 1);
INSERT INTO collection_item (id, collection_id, item_id) VALUES (DEFAULT, 1, 1);
My problem is that deleting a store
DELETE FROM store WHERE store.id = 1;
will give the following error:
ERROR: update or delete on table "store" violates foreign key constraint
"collection_store_id_fkey" on table "collection"
Detail: Key (id)=(1) is still referenced from table "collection".
I understand the problem but I don't know how I can resolve this issue.
If an item gets deleted, the relation in collection_item should not be removed but the item_id should be set to NULL. On the other hand, if a collection gets deleted, all related collection_item records should be removed as well.
How can DELETE CASCADE work in such a setup or do I have to model my tables differently if I need this kind of behavior?
You can just add ON DELETE CASCADE where you have ON UPDATE CASCADE
CREATE TABLE IF NOT EXISTS collection (
id BIGSERIAL PRIMARY KEY,
store_id bigint NOT NULL,
FOREIGN KEY (store_id) REFERENCES store (id)
ON UPDATE CASCADE
ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS item (
id BIGSERIAL PRIMARY KEY,
store_id bigint NOT NULL,
FOREIGN KEY (store_id) REFERENCES store (id)
ON UPDATE CASCADE
ON DELETE CASCADE
);
SQLFiddle
To resolve this issue you can add ON DELETE behavior to the store_id column of the collection table (and that of the item table). Basically you can just change the ON UPDATE to ON DELETE in both of these table definitions, since I doubt you'll be updating the id column for existing rows in the store table. You also mention the ON DELETE behavior for the item_id column of collection_item, if you want the column value to become NULL when an item is deleted, you can use ON DELETE SET NULL.
CREATE TABLE IF NOT EXISTS store (
id BIGSERIAL PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS collection (
id BIGSERIAL PRIMARY KEY,
store_id bigint NOT NULL,
FOREIGN KEY (store_id) REFERENCES store (id)
ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS item (
id BIGSERIAL PRIMARY KEY,
store_id bigint NOT NULL,
FOREIGN KEY (store_id) REFERENCES store (id)
ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS collection_item (
id BIGSERIAL PRIMARY KEY,
collection_id bigint NOT NULL,
item_id bigint NOT NULL,
UNIQUE (collection_id, item_id),
FOREIGN KEY (collection_id) REFERENCES collection (id)
ON DELETE CASCADE,
FOREIGN KEY (item_id) REFERENCES item (id)
ON DELETE SET NULL
);
On this case, you have to delete table refrences before to delete stores id.
Or to do the modifications above.
DELETE FROM item where store_id= 1;
DELETE FROM collection where store_id = 1;
DELETE FROM store where id = 1;

Postgres before insert trigger using sequence from another table

Using Postgres, what I would like to achieve is to be able to have many different instrument types, with corresponding [TYPE].instrument tables, which all have a unique ID in the table, but also reference a unique ID in the instrument.master table. I have the following:
create schema instrument
CREATE TABLE instrument.type (
id smallserial NOT NULL,
name text not null,
code text not null,
CONSTRAINT pk_instrument_type PRIMARY KEY (id)
);
ALTER TABLE instrument.type ADD CONSTRAINT unq_instrument_type_code UNIQUE(code);
ALTER TABLE instrument.type ADD CONSTRAINT unq_instrument_type_name UNIQUE(name);
insert into instrument.type (name, code) values ('futures', 'f');
CREATE TABLE instrument.master (
id serial NOT NULL,
type smallint not null references instrument.type (id),
timestamp timestamp with time zone not null,
CONSTRAINT pk_instrument_master PRIMARY KEY (id)
);
CREATE TABLE futures.definition (
id smallserial NOT NULL,
code text not null,
CONSTRAINT pk_futures_definition PRIMARY KEY (id)
);
ALTER TABLE futures.definition ADD CONSTRAINT unq_futures_definition_code UNIQUE(code);
insert into futures.definition (code) values ('ED');
CREATE TABLE futures.instrument (
id smallserial NOT NULL,
master serial not null references instrument.master (id),
definition smallint not null references futures.definition (id),
month smallint not null,
year smallint not null,
CONSTRAINT pk_futures_instrument PRIMARY KEY (id),
check (month >= 1),
check (month <= 12),
check (year >= 1900)
);
ALTER TABLE futures.instrument ADD CONSTRAINT unq_futures_instrument UNIQUE(definition, month, year);
CREATE OR REPLACE FUNCTION trigger_master_futures()
RETURNS trigger AS
$BODY$
BEGIN
insert into instrument.master (type, timestamp)
select id, current_timestamp from instrument.type where code = 'f';
NEW.master := currval('instrument.master_id_seq');
RETURN NEW;
END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;
create trigger trg_futures_instrument before insert on futures.instrument
for each row
execute procedure trigger_master_futures();
I then test with:
insert into futures.instrument (definition, month, year)
select id, 3, 2015 from futures.definition where code = 'ED';
Everything works almost as I would like it to. The only issue is that somehow, instrument.master.id ends up being one more than futures.instrument.master. I am not sure what I need to do to achieve the behavior I want, which is that whenever an entry is inserted into futures.instrument, an entry should be inserted into instrument.master, and the id entry of the latter should be inserted into the master entry of the former. I actually think it should have failed since the foreign key relationship is violated somehow.
As it turns out, everything was correct. The issue was that in futures.instrument, the type of the master column is serial, and it should have been int.