X
X
xXRustamXx2020-04-30 18:21:52
PostgreSQL
xXRustamXx, 2020-04-30 18:21:52

Does an UPDATE or DELETE on the "users" table violate the "posts_authorid_fkey" foreign key constraint on the "posts" table?

I create the users table:

CREATE TABLE users(
    id UUID DEFAULT uuid_generate_v4(),
    email TEXT,
    name TEXT,
    password TEXT,
    PRIMARY KEY(id)
);
INSERT INTO users(id, email, name, password) VALUES('bdfe5653-f75a-42b4-93d2-f4f739c0bc7d', '[email protected]', 'Jone', 'somehashedpasswprd');

Next is the posts table:
CREATE TABLE posts(
    id uuid DEFAULT uuid_generate_v4(),
    authorID uuid,
    text TEXT,
    FOREIGN KEY(authorID) REFERENCES users(id)
);
INSERT INTO posts(authorID, text) 
VALUES('bdfe5653-f75a-42b4-93d2-f4f739c0bc7d', 'Post description I wrote the post for demonstation how I can use of sql');

Next, I needed to change the foreign key constraint so that after deleting a user, posts are deleted automatically:
ALTER TABLE posts
    DROP CONSTRAINT authorID;

ALTER TABLE posts 
  ADD CONSTRAINT authorID 
  FOREIGN KEY(authorID) 
  REFERENCES users(id)
  ON DELETE CASCADE 
  ON UPDATE CASCADE;

Okay, I removed the default restriction and added my own, now I'm trying to remove the user that was attached to the post:
DELETE FROM users WHERE id = 'bdfe5653-f75a-42b4-93d2-f4f739c0bc7d'';

I can't do this, I get an error:
"UPDATE or DELETE in the 'users' table violates the 'posts_authorid_fkey' foreign key constraint of the 'posts' table?"

Why?! After all, I registered my restriction and, as planned, the post should have been deleted along with the user ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
galaxy, 2020-04-30
@xXRustamXx

ALTER TABLE posts
DROP CONSTRAINT authorID;

Why did you decide that the constraints are called the name of the columns?
I think that this request gave an error for you, and your original constraint was not deleted.
See what foreign keys a table has in psql with the \d+ posts command.

D
d-stream, 2020-04-30
@d-stream

Next, I needed to change the foreign key constraint so that after deleting a user, posts are deleted automatically
It's a pretty vicious way.
More honest on cascade delete | update or "on the forehead" to delete posts first, then the user.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question