tags:

views:

38

answers:

3

I'm manually constructing a DELETE CASCADE statement for postgres.

I have a 'transaction' and a 'slice' table, related as shown below:

    Table "public.slice"
  Column  | Type | Modifiers 
----------+------+-----------
 id       | text | not null
 name     | text | 
Referenced by:
    TABLE "transaction" CONSTRAINT "transaction_slice_id_fkey" FOREIGN KEY (slice_id) REFERENCES slice(id)
 Table "public.transaction"
  Column  | Type | Modifiers 
----------+------+-----------
 id       | text | not null
 slice_id | text | 
Referenced by:
    TABLE "classification_item" CONSTRAINT "classification_item_transaction_id_fkey" FOREIGN KEY (transaction_id) REFERENCES transaction(id)
Table "public.classification_item"
     Column     | Type | Modifiers 
----------------+------+-----------
 id             | text | not null
 transaction_id | text | 
Foreign-key constraints:
    "classification_item_transaction_id_fkey" FOREIGN KEY (transaction_id) REFERENCES transaction(id)

Say I want to delete all transactions and classification_items referenced by the slice whose name is 'my_slice'. What do I need to write?

=# delete from classification_item where transaction_id= #...? 
=# delete from transaction where slice_id= #...? 
=# delete from slice where name='my_slice';
+2  A: 

Postgres foreign keys support the CASCADE deletes:

slice_id integer REFERENCES slice(id) ON DELETE CASCADE

etc

jira
In other words, you dont write it, you just describe the relations and let Postgre handle the deletion.
Anti Veeranna
A: 

In case you can't do what others have suggested:

begin;
delete from classification_item where transaction_id in (select id from "transaction" where slice_id = (select id from slice where name = 'my_slice'));
delete from "transaction" where slice_id in (select id from slice where name='my_slice');
delete from slice where name='my_slice';
commit;
Milen A. Radev
I can't; I've inherited fairly complex code that uses SQLAlchemy. This is ideal, thank you.
AP257
A: 

It's soemthing that is defined in the table rather than the DELETE Query. Example (look at order_id):

CREATE TABLE order_items (
    product_no integer REFERENCES products ON DELETE RESTRICT,
    order_id integer REFERENCES orders ON DELETE CASCADE,
    quantity integer,
    PRIMARY KEY (product_no, order_id)
);
Abe Miessler
Thanks, but I've inherited code that uses SQLAlchemy...
AP257