Foreign Key Constraint Issues Using Sequel and Database Cleaner

I am having problems using a database cleaner with sequel and sqlite external key constraints. In particular, I use a strategy :truncationwith Capybara integration tests.

For this sampling scheme:

CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE events(id INTEGER PRIMARY KEY, title TEXT);

CREATE TABLE events_users(
  user_id INTEGER,
  event_id INTEGER,

  FOREIGN KEY(user_id) REFERENCES users(id),
  FOREIGN KEY(event_id) REFERENCES events(id)
);

And the sequel to the model:

class User < Sequel::Model
  many_to_many :events
end

class Event < Sequel::Model
  many_to_many :users
end

Doing the following:

# normally this would be run in
# an rspec before(:each) for my :feature specs
DatabaseCleaner.start
DatabaseCleaner.strategy = :truncation

bob = User.create(name: "bob")
sally = User.create(name: "sally")
event = Event.create(title: "Everyone invited")
event.users << [bob, sally]

DatabaseCleaner.clean

Error Results

SQLite3::ConstraintException: FOREIGN KEY constraint failed (Sequel::ForeignKeyConstraintViolation)

I can get around this by changing my before statement to disable PRAGMA foreign_keys:

DB.foreign_keys = false
DatabaseCleaner.start
DatabaseCleaner.strategy = :truncation

(or not using FOREIGN KEY in my tables), but this seems wrong, because I want the benefits of foreign key constraints, or at least I think I do;).

Is this a fundamental misunderstanding of how to use foreign key constraints, or is there a better way to do this?

+4
1

, T_T.

FOREIGN KEY constraint failed sequel. , DatabaseCleaner.strategy = :truncation DatabaseCleaner.strategy = :deletion.

/ :truncate :delete, ( , postgres) . :delete .

0

Source: https://habr.com/ru/post/1621651/


All Articles