File: deletion.rb

package info (click to toggle)
ruby-database-cleaner 1.7.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 768 kB
  • sloc: ruby: 4,854; makefile: 10; sh: 4
file content (47 lines) | stat: -rw-r--r-- 1,223 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
require 'database_cleaner/sequel/base'
require 'database_cleaner/generic/truncation'
require 'database_cleaner/sequel/truncation'

module DatabaseCleaner::Sequel
  class Deletion < Truncation
    def disable_referential_integrity(tables)
      case db.database_type
      when :postgres
        db.run('SET CONSTRAINTS ALL DEFERRED')
        tables_to_truncate(db).each do |table|
          db.run("ALTER TABLE \"#{table}\" DISABLE TRIGGER ALL")
        end
      when :mysql
        old = db.fetch('SELECT @@FOREIGN_KEY_CHECKS').first[:@@FOREIGN_KEY_CHECKS]
        db.run('SET FOREIGN_KEY_CHECKS = 0')
      end
      yield
    ensure
      case db.database_type
      when :postgres
        tables.each do |table|
          db.run("ALTER TABLE \"#{table}\" ENABLE TRIGGER ALL")
        end
      when :mysql
        db.run("SET FOREIGN_KEY_CHECKS = #{old}")
      end
    end

    def delete_tables(db, tables)
      tables.each do |table|
        db[table.to_sym].delete
      end
    end

    def clean
      return unless dirty?

      tables = tables_to_truncate(db)
      db.transaction do
        disable_referential_integrity(tables) do
          delete_tables(db, tables)
        end
      end
    end
  end
end