Second table does not get inserted if first table already exist - sql

I have a user and a log table. I want to keep adding new log, and if the user name does not exist in user, add that too.
What I have however, will only insert into log if user does not exist. If user already exist, no log gets added.
How can I fix this to make it work as intended? Thanks in advance.
CREATE TABLE user (
id serial NOT NULL,
name char(60) NOT NULL,
CONSTRAINT user_pk PRIMARY KEY (id),
CONSTRAINT user_un UNIQUE (name)
)
CREATE TABLE log (
id serial NOT NULL,
name_id int NOT NULL,
detail char(512) NULL,
CONSTRAINT detail_pk PRIMARY KEY (id),
CONSTRAINT detail_user_fk FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE RESTRICT ON UPDATE RESTRICT
)
my attempt
with ins1 as (
insert into user (name)
values ('myname')
on conflict do nothing
returning id as user_id
)
insert into detail (user_id, detail)
select user_id, 'some detail' from ins1;
Following example from other question I changed do nothing to update where false, but still no log is being inserted
with ins1 as (
insert into "user" (name)
values ('myuser')
on conflict (name) do update
set name = null where FALSE
returning id as user_id
)
insert into log (user_id, detail)
select user_id, 'some description' from ins1;

Related

Many-to-Many Link Table Foreign Key Modeling in SQLite

I have the following two tables in SQLite:
CREATE TABLE `Link` (
`link_id` integer NOT NULL,
`part_id` integer NOT NULL,
CONSTRAINT `link_pk` PRIMARY KEY(`link_id`,`part_id`)
);
CREATE TABLE `Main` (
`main_id` integer NOT NULL PRIMARY KEY AUTOINCREMENT,
`link_id` integer NOT NULL REFERENCES `Link`(`link_id`)
);
INSERT INTO `Link` (link_id, part_id) VALUES (1,10);
INSERT INTO `Link` (link_id, part_id) VALUES (1,11);
INSERT INTO `Link` (link_id, part_id) VALUES (1,12);
INSERT INTO `Link` (link_id, part_id) VALUES (2,15);
INSERT INTO `Main` (main_id, link_id) VALUES (1,1);
INSERT INTO `Main` (main_id, link_id) VALUES (2,1);
INSERT INTO `Main` (main_id, link_id) VALUES (3,2);
Many Main rows may reference the same link id, and many Link rows may have the same link id, such that select * from Main natural join Link where main_id=1 will return N rows, and select * from Main where link_id=1 will return K rows. The link id is important, and the original data each main has 1 link id, and each link has N part ids.
Using the schemas above, I am unable to insert any rows in Main due to the foreign key constraint (foreign key mismatch - "Main" referencing "Link": INSERT INTO Main (main_id, link_id) VALUES (1,1);), presumably because of the composite key requirement. I can get this to work by removing the foreign key constraint, but then I am obviously missing a constraint. Reversing the direction of the key wouldn't work either since, as stated above, it's a Many-to-Many relationship. Is there a way to properly model this in SQLite with a constraint that at least one row exists in Link for each link_id in Main?
I would propose a different design.
Each of the 2 entities link_id and part_id should be the primary key in 2 tables, something like:
CREATE TABLE Links (
link_id INTEGER PRIMARY KEY,
link_description TEXT
);
CREATE TABLE Parts (
part_id INTEGER PRIMARY KEY,
part_description TEXT
);
Then, create the junction table of the above tables (like your current Link table):
CREATE TABLE Links_Parts (
link_id INTEGER NOT NULL REFERENCES Links(link_id),
part_id INTEGER NOT NULL REFERENCES Parts(part_id),
PRIMARY KEY(link_id, part_id)
);
and the table Main:
CREATE TABLE Main (
main_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
link_id INTEGER NOT NULL REFERENCES Links(link_id)
);
All the relations are there and you have referential integrity guaranteed if you set foreign key support:
PRAGMA foreign_keys = ON;
See a simplified demo.

Use two foreign key in table with 'on delete cascade'

CREATE TABLE Comments(
Id INT PRIMARY KEY IDENTITY(0,1),
TEXT NOT NULL,
Date Date NOT NULL ,
Point INT NOT NULL DEFAULT(0),
ID_User INT FOREIGN KEY REFERENCES Users(Id) ON DELETE CASCADE NOT NULL,
ID_Post INT FOREIGN KEY REFERENCES Posts(Id) NOT NULL
)
When I delete User from Users table it show me error that Comments table has
other Reference Key. What i have to do ?
The DELETE statement conflicted with the REFERENCE constraint "FK__Comments__ID_Pos__76969D2E". The conflict occurred in database "Facebook", table "dbo.Comments", column 'ID_Post'.
If you want to delete a user record, you need to delete the records in the foreign key tables.
In this case, you need to delete records in Comments table.
DELETE from dbo.Commnts
Where ID_User = "userid"
Then, you can remove the user record from Users table
I did some work on this, there is no error in the foreign keys you referenced here. you may probably have reference to comment id in some other tables.
this is what I tried
CREATE TABLE Users(
Id int primary key
)
CREATE TABLE posts(
Id int primary key
)
insert into Users values(1);
insert into Users values(2);
insert into posts values(3);
insert into posts values(4);
CREATE TABLE Comments(
Id INT PRIMARY KEY IDENTITY(0,1),
ID_User INT FOREIGN KEY REFERENCES Users(Id) ON DELETE CASCADE NOT NULL,
ID_Post INT FOREIGN KEY REFERENCES Posts(Id) NOT NULL
)
insert into Comments values(1,3);
insert into Comments values(2,4);
DELETE
FROM Users
WHERE id = 1 --this works fine

SQL using nested INSERT INTO's?

I am using postgreSQL for storing chat logs, and I have this sample schema:
CREATE TABLE contacts (
"id" BIGSERIAL PRIMARY KEY,
"user" BIGINT NOT NULL,
"contact" BIGINT NOT NULL,
"savedAs" VARCHAR(36),
CONSTRAINT user_fk FOREIGN KEY("user") REFERENCES users("id") ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT contact_fk FOREIGN KEY("contact") REFERENCES users("id") ON DELETE CASCADE ON UPDATE CASCADE,
UNIQUE("user", "contact")
);
CREATE TABLE messages (
"id" BIGSERIAL PRIMARY KEY,
"contact" BIGINT NOT NULL,
"direction" direction_type NOT NULL,
"type" message_type default 'text',
"body" VARCHAR(1000) NULL,
"status" status_type DEFAULT 'none',
"time" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT contact_fk FOREIGN KEY("contact") REFERENCES contacts("id") ON DELETE CASCADE
);
CREATE TABLE last_message (
"id" BIGSERIAL PRIMARY KEY,
"chat" BIGINT NOT NULL UNIQUE,
"message" BIGINT NOT NULL,
CONSTRAINT message_fk FOREIGN KEY("message") REFERENCES messages("id"),
CONSTRAINT chat_fk FOREIGN KEY("chat") REFERENCES contacts("id") ON DELETE CASCADE
);
What I want to do, is store the last message for a particular chat in the last_message table. I was thinking of doing it like this(but not working):
INSERT INTO last_message (chat, message) VALUES (
9,
(INSERT INTO messages (contact, direction, body) VALUES (9, 'sent', 'hello there') RETURNING id)
)
But I get a syntax error(syntax error at or near "into"), so here are my questions,
what is wrong with the above query?
is there a better a way to do this? how?
is there anything that can be improved?
Use a CTE:
WITH toinsert as (
INSERT INTO messages (contact, direction, body)
VALUES (9, 'sent', 'hello there')
RETURNING id
)
INSERT INTO last_message (chat, message)
SELECT 9, id
FROM toinsert;
Step 1
drop table last_message
You can get the last message like this:
select contact, direction, body
from messages
join
(select chat, max(time) maxTime
from messages
group by chat
) temp on messages.chat = temp.chat
and time = maxTime
You can create a view or whatever with this logic, whatever your requirements happent to be.

PostgreSQL check constraint for foreign key condition

I have a table of users eg:
create table "user" (
id serial primary key,
name text not null,
superuser boolean not null default false
);
and a table with jobs:
create table job (
id serial primary key,
description text
);
the jobs can be assigned to users, but only for superusers. other users cannot have jobs assigned.
So I have a table whereby I see which job was assigned to which user:
create table user_has_job (
user_id integer references "user"(id),
job_id integer references job(id),
constraint user_has_job_pk PRIMARY KEY (user_id, job_id)
);
But I want to create a check constraint that the user_id references a user that has user.superuser = True.
Is that possible? Or is there another solution?
This would work for INSERTS:
create or replace function is_superuser(int) returns boolean as $$
select exists (
select 1
from "user"
where id = $1
and superuser = true
);
$$ language sql;
And then a check contraint on the user_has_job table:
create table user_has_job (
user_id integer references "user"(id),
job_id integer references job(id),
constraint user_has_job_pk PRIMARY KEY (user_id, job_id),
constraint chk_is_superuser check (is_superuser(user_id))
);
Works for inserts:
postgres=# insert into "user" (name,superuser) values ('name1',false);
INSERT 0 1
postgres=# insert into "user" (name,superuser) values ('name2',true);
INSERT 0 1
postgres=# insert into job (description) values ('test');
INSERT 0 1
postgres=# insert into user_has_job (user_id,job_id) values (1,1);
ERROR: new row for relation "user_has_job" violates check constraint "chk_is_superuser"
DETAIL: Failing row contains (1, 1).
postgres=# insert into user_has_job (user_id,job_id) values (2,1);
INSERT 0 1
However this is possible:
postgres=# update "user" set superuser=false;
UPDATE 2
So if you allow updating users you need to create an update trigger on the users table to prevent that if the user has jobs.
The only way I can think of is to add a unique constraint on (id, superuser) to the users table and reference that from the user_has_job table by "duplicating" the superuser flag there:
create table users (
id serial primary key,
name text not null,
superuser boolean not null default false
);
-- as id is already unique there is no harm adding this additional
-- unique constraint (from a business perspective)
alter table users add constraint uc_users unique (id, superuser);
create table job (
id serial primary key,
description text
);
create table user_has_job (
user_id integer references users (id),
-- we need a column in order to be able to reference the unique constraint in users
-- the check constraint ensures we only reference superuser
superuser boolean not null default true check (superuser),
job_id integer references job(id),
constraint user_has_job_pk PRIMARY KEY (user_id, job_id),
foreign key (user_id, superuser) references users (id, superuser)
);
insert into users
(id, name, superuser)
values
(1, 'arthur', false),
(2, 'ford', true);
insert into job
(id, description)
values
(1, 'foo'),
(2, 'bar');
Due to the default value, you don't have to specify the superuser column when inserting into the user_has_job table. So the following insert works:
insert into user_has_job
(user_id, job_id)
values
(2, 1);
But trying to insert arthur into the table fails:
insert into user_has_job
(user_id, job_id)
values
(1, 1);
This also prevents turning ford into a non-superuser. The following update:
update users
set superuser = false
where id = 2;
fails with the error
ERROR: update or delete on table "users" violates foreign key constraint "user_has_job_user_id_fkey1" on table "user_has_job"
Detail: Key (id, superuser)=(2, t) is still referenced from table "user_has_job".
Create a separate superuser table that inherits from the user table:
CREATE TABLE "user" (
id serial PRIMARY KEY,
name text NOT NULL,
);
CREATE TABLE superuser () INHERITS ("user");
The user_has_job table can then reference the superuser table:
CREATE TABLE user_has_job (
user_id integer REFERENCES superuser (id),
job_id integer REFERENCES job(id),
PRIMARY KEY (user_id, job_id)
);
Move users around between the tables as needed by inserting and deleting:
WITH promoted_user AS (
DELETE FROM "user" WHERE id = 1 RETURNING *
) INSERT INTO superuser (id, name) SELECT id, name FROM promoted_user;
I don't know if this is a good way to do it but it seems to work
INSERT INTO user_has_job (user_id, job_id) VALUES (you_user_id, your_job_id)
WHERE EXIST (
SELECT * FROM user WHERE id=your_user_id AND superuser=true
);

Want to update foreign key table at same time when primary key update in SQL

I have a scenario with a table RegisteredUsers and a primary key on userid.
Here is code:
create table RegisteredUsers
(
userId INT not null IDENTITY(1,1),
userName varchar(255) not null,
userpassword varchar(255) not null,
primary key (userId)
);
A second table Answers has a foreign key reference to RegisteredUsers:
create table answers (
surveyid int not null
foreign key (userId) references RegisteredUsers (userId)
);
Whenever I insert a row into the first table, I want to also insert a row into table Answers. When I insert value now, it only inserts into the first table. What do I need to do?
I am using SQL Server 2008. Please help. Thanks