Many-to-one relationship using two unique keys - postgresql

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)

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.

Postgres - Create or replace table

I have a table that is already created with data and I need only modify the schema to add some constraints .
my created tabled schema
CREATE TABLE public.note (
note_id bigint NOT NULL,
confidential boolean NOT NULL,
follow_up_date date,
notification_date date,
priority integer NOT NULL,
recurring_follow_up_interval interval,
status character varying(255) NOT NULL,
create_date timestamp with time zone,
deleted boolean NOT NULL,
last_modified_date timestamp with time zone,
time_spent integer,
title text,
version bigint NOT NULL,
assigned_to_id bigint,
note_category_id bigint NOT NULL,
created_by_id bigint,
last_modified_by_id bigint
);
what I need to match
create table note
(
note_id bigint default nextval('note_id_seq'::regclass) not null,
confidential boolean not null,
follow_up_date date,
notification_date date,
priority integer default 0 not null,
recurring_follow_up_interval interval,
status varchar(255) not null,
create_date timestamp with time zone,
deleted boolean default false not null,
last_modified_date timestamp with time zone,
time_spent integer,
title text,
version bigint default 0 not null,
assigned_to_id bigint,
note_category_id bigint not null,
created_by_id bigint,
last_modified_by_id bigint,
constraint note_pkey
primary key (note_id),
constraint fk_4nrhbn2j8j2vqqh78vleef9xr
foreign key (created_by_id) references admin_user,
constraint fk_eid7x7jfvjoe1h5tnyouhmqpa
foreign key (assigned_to_id) references admin_user,
constraint fk_oi5l4dg3sg5ep5neagmvp9r7o
foreign key (note_category_id) references note_category,
constraint fk_tk8ncyc0hmdi3gfh67b4jyu3l
foreign key (last_modified_by_id) references admin_user
);
as you can see it missing all defaults + all constraint to the other tables
any way to copy the intended schema to the created one without loosing the data
I am using Postgres 12
UPDATE
I know I could use alter to modify some columns but it will be a long process for me as there are many columns and I got more than 300 tables that have the same case
I manually alter one column to add sequence but I need easier way to do that for all columns
ALTER TABLE ONLY note ALTER COLUMN note_id SET DEFAULT nextval('note_id_seq'::regclass);

relation tables inheritance modeling

I want to understand inheritance in postgresql, simple whitch columns in whitch tables.
CREATE TABLE users (
id serial PRIMARY KEY,
username VARCHAR UNIQUE NOT NULL,
email VARCHAR NOT NULL,
password_salt VARCHAR,
password_hash VARCHAR,
avatar serial
)
CREATE TABLE groups (
id serial PRIMARY KEY NOT NULL,
name VARCHAR,
email VARCHAR,
avatar serial,
)
CREATE TABLE accounts (
id serial PRIMARY KEY NOT NULL,
name VARCHAR,
avatar serial,
rating json NOT NULL,
);
CREATE TABLE users_to_accounts (
id serial PRIMARY KEY NOT NULL,
start_time DATETIME NOT NULL,
end_time DATETIME,
)
CREATE TABLE account_subscryptions (
user_id serial NOT NULL,
account_id serial NOT NULL,
) INHERITS users_to_accounts
CREATE TABLE account_memberships (
user_id serial NOT NULL,
account_id serial NOT NULL,
) INHERITS users_to_accounts
CREATE TABLE users_to_groups (
id serial PRIMARY KEY NOT NULL,
start_time DATETIME NOT NULL,
end_time DATETIME,
)
CREATE TABLE group_subscryptions (
user_id serial NOT NULL,
group_id serial NOT NULL,
) INHERITS users_to_groups
CREATE TABLE group_memberships (
user_id serial NOT NULL,
group_id serial NOT NULL,
) INHERITS users_to_groups
Now.
1. Is it good design to have foreign keys in child tables an all common data in "abstract" table?
2. Is there any traps in future changes of database with inherited relantion tables?
3. I am all wrong and there is a better way for this schema?
4. I want to create good database schema and generate graphql api in postgraphile, looking in google for half day, did not gave me any one good or best solution, so every link will by great.
It may be usefull for others, I think. Thanks

Flyway: Relation does not exist

ERROR: relation "signature_level" does not exist
I'm having trouble figuring out what's the problem. Flyway is throwing me this error when migrating.
CREATE TABLE IF NOT EXISTS "user" (
id SERIAL NOT NULL PRIMARY KEY,
name text NOT NULL,
id_code numeric NOT NULL,
email text NOT NULL,
address text,
alt_contact_relation text NULL,
alt_contact_phone numeric NULL,
signature_level_id integer NULL,
username text NOT NULL,
password text NOT NULL,
create_time TIMESTAMP without TIME ZONE DEFAULT now() NOT NULL,
update_time TIMESTAMP without TIME ZONE DEFAULT now() NOT NULL,
status active_status NOT NULL DEFAULT 'active',
work_detail_id integer NULL,
CONSTRAINT FK_user_signature_level FOREIGN KEY (signature_level_id) REFERENCES signature_level (id)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT FK_user_work_detail FOREIGN KEY (work_detail_id) REFERENCES work_detail (id)
ON DELETE NO ACTION ON UPDATE NO ACTION
);
This is the signature level table.
CREATE TABLE IF NOT EXISTS "signature_level" (
id SERIAL NOT NULL PRIMARY KEY,
name text NOT NULL,
create_time TIMESTAMP without TIME ZONE DEFAULT now() NOT NULL,
update_time TIMESTAMP without TIME ZONE DEFAULT now() NOT NULL
);

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');
});