class DatabaseCleaner::Sequel::Truncation

Public Class Methods

new(only: [], except: [], pre_count: false) click to toggle source
# File lib/database_cleaner/sequel/truncation.rb, line 6
def initialize only: [], except: [], pre_count: false
  @only = only
  @except = except
  @pre_count = pre_count
end

Public Instance Methods

clean() click to toggle source
# File lib/database_cleaner/sequel/truncation.rb, line 16
def clean
  return unless dirty?

  tables = tables_to_truncate(db)

  # Count rows before truncating
  if pre_count?
    tables = pre_count_tables(tables)
  end

  case db.database_type
  when :postgres
    # PostgreSQL requires all tables with FKs to be truncates in the same command, or have the CASCADE keyword
    # appended. Bulk truncation without CASCADE is:
    # * Safer. Tables outside of tables_to_truncate won't be affected.
    # * Faster. Less roundtrips to the db.
    unless tables.empty?
      tables_sql = tables.map { |t| %("#{t}") }.join(',')
      db.run "TRUNCATE TABLE #{tables_sql} RESTART IDENTITY;"
    end
  else
    truncate_tables(db, tables)
  end
end
start() click to toggle source
# File lib/database_cleaner/sequel/truncation.rb, line 12
def start
  @last_txid = txid
end

Private Instance Methods

dirty?() click to toggle source
# File lib/database_cleaner/sequel/truncation.rb, line 56
def dirty?
  @last_txid != txid || @last_txid.nil?
end
migration_storage_names() click to toggle source

overwritten

# File lib/database_cleaner/sequel/truncation.rb, line 72
def migration_storage_names
  %w(schema_info schema_migrations)
end
pre_count?() click to toggle source
# File lib/database_cleaner/sequel/truncation.rb, line 76
def pre_count?
  @pre_count == true
end
pre_count_tables(tables) click to toggle source
# File lib/database_cleaner/sequel/truncation.rb, line 43
def pre_count_tables tables
  tables.reject { |table| db[table.to_sym].count == 0 }
end
tables_to_truncate(db) click to toggle source
# File lib/database_cleaner/sequel/truncation.rb, line 67
def tables_to_truncate(db)
  (@only.any? ? @only : db.tables.map(&:to_s)) - @except - migration_storage_names
end
truncate_tables(db, tables) click to toggle source
# File lib/database_cleaner/sequel/truncation.rb, line 47
def truncate_tables(db, tables)
  tables.each do |table|
    db[table.to_sym].truncate
    if db.database_type == :sqlite && db.table_exists?(:sqlite_sequence)
      db[:sqlite_sequence].where(name: table).delete
    end
  end
end
txid() click to toggle source
# File lib/database_cleaner/sequel/truncation.rb, line 60
def txid
  case db.database_type
  when :postgres
    db.fetch('SELECT txid_snapshot_xmax(txid_current_snapshot()) AS txid').first[:txid]
  end
end