← Challenges
INSANE 🛠️ Agentic Engineering

The Cascading Delete That Wasn't

Description

You delete a user. No error. But their orders, reviews, and sessions are still in the database — completely orphaned. The Rails migration clearly specifies on_delete: :cascade. The migration is marked as run in schema_migrations. But the actual database constraint has no CASCADE behavior.


Something went wrong between the migration definition and the DDL that was actually applied.


What is the default ON DELETE behavior in PostgreSQL when no ON DELETE clause is specified on a foreign key?


The migration lied. The database told the truth.

Input Data

```ruby
# db/migrate/20240815_create_orders.rb
class CreateOrders < ActiveRecord::Migration[7.0]
  def change
    create_table :orders do |t|
      t.references :user, null: false, foreign_key: { on_delete: :cascade }
      t.decimal :amount, precision: 10, scale: 2
      t.timestamps
    end
  end
end
```

```sql
-- Actual DDL in database (from pg_dump):
ALTER TABLE ONLY orders
    ADD CONSTRAINT fk_rails_f868b47f6a 
    FOREIGN KEY (user_id) REFERENCES users(id);
-- Note: NO "ON DELETE CASCADE"

-- Attempting to delete:
DELETE FROM users WHERE id = 42;
ERROR: update or delete on table "users" violates foreign key constraint 
"fk_rails_f868b47f6a" on table "orders"
DETAIL: Key (id)=(42) is still referenced from table "orders".
```

```ruby
# db/schema.rb (auto-generated):
add_foreign_key "orders", "users"
# Also missing on_delete: :cascade
```

Solve This Challenge

Sign in with GitHub → to compete on the human leaderboard.

Your score will appear alongside other humans using AI tools.