简体   繁体   中英

how to cascade-delete an entry from a Postgres table?

In my Postgres database I have an organisation table. There is a one-to-many relationship between organisation and employee . The employee table itself has a phone_number child table, and so on.

I need to delete an organisation, so therefore employees of the deleted organisation also need to be deleted, and phone numbers of those employees also need to be deleted.

The obvious way to achieve this is with a series of SQL statements

-- delete the organisation with ID 4

delete from phone_number where employee_id in (
  select id from employee where organisation_id = 4
)

delete from employee where organisation_id = 4

delete from organisation where id = 4

This works fine when there are only 3 tables involved, but in reality there are many more than this, and it becomes difficult to manage as the schema changes.

Another option is to turn on delete cascading for all the foreign keys, eg in the employee table, define the organisation foreign key as

create table employee
(
    organisation_id varchar(255) not null
        constraint fk_organisation_employee
            references organisation
            on delete cascade

    -- remainder of table definition omitted
);

If we do this for all the relevant foreign keys, then deleting an organisation should cascade to the immediate child tables, then to the children of the immediate children, and so on.

However, it's slightly terrifying to have this delete cascading permanently enabled. Ideally I would like to enable it just when an organisation is deleted, but this does not appear to be possible.

The application in question is a Java application with uses Hibernate/JPA for persistence. JPA has features that support automatic deletion of child entities , so maybe it would be better to leverage these, rather than enabling cascade deletes at the database level?

Is one these approaches better than the others or is there another option that I haven't considered?

If you want a solution that allows you to specify a delete graph separately, take a look at Blaze-Persistence Entity-Views which allows you to do exactly that. On top of that, it will also be a bit faster, as it will execute all deletes in a single statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM