Skip to content

Migrations that alter SQLite table structure can cause data loss #55866

@skipkayhil

Description

@skipkayhil

A mere add_foreign_key can wipe out your whole Rails+SQLite production table

We likely should be disabling and re-enabling the foreign_keys PRAGMA before/after the transaction to change the table per the sqlite docs.

Edit: actually it looks like we already do that since 45881b0

Edit2: Ah, this is complex. We currently do

transaction do
  disable_referential_integrity do

but it should be

disable_pragma_foreign_keys do
  transaction do
    enable_defer_foreign_keys do

because PRAGMA foreign_keys

is a no-op within a transaction; foreign key constraint enforcement may only be enabled or disabled when there is no pending BEGIN or SAVEPOINT.

per doc, and "PRAGMA foreign_keys before TRANSACTION" is the order recommended in the first sqlite doc link above. However, PRAGMA defer_foreign_keys is set per transaction so it has to be inside the transaction block.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions