Tables containing referenced foreign keys will not be dropped by default

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the databases category.

Last Updated: 2022-12-01

I tried to run the following code in a DB migration as part of a deploy:

drop_table :tutoring_requests
drop_table :tutor_matchings

It failed

PG::DependentObjectsStillExist: ERROR:  cannot drop table tutoring_requests because other objects depend on it

DETAIL:  constraint fk_rails_106fcdf9ef on table tutor_matchings depends on table tutoring_requests
constraint fk_rails_057e82c9d8 on table tutoring_discipline_selections depends on table tutoring_requests

HINT:  Use DROP ... CASCADE to drop the dependent objects too.

Looking at the ORM-ified schema, I saw the following constraints:

# add_foreign_key(from_table, to_table, options = {})
# Adds a new foreign key. from_table is the table with the key column, to_table
# contains the referenced primary key.

add_foreign_key "tutor_matchings", "tutoring_requests"
add_foreign_key "tutor_matchings", "tutors"
add_foreign_key "tutoring_discipline_selections", "tutoring_requests"
add_foreign_key "tutoring_requests", "users"

You can see here that tutor_matchings and tutoring_discipline_selections reference tutoring_requests. Both these tables have a column referencing tutoring_requests. Because of these foreign key constraints, the DB will not allow that table to be dropped, thus the migration failed.