DatabaseCleaner.clean_with(:truncate) 不会重置自动递增的 id

Hyu*_*Kim 6 ruby postgresql ruby-on-rails rspec-rails database-cleaner

我目前DatabaseCleaner在运行 PostgreSQL 的 Rails 项目中使用,并将其设置如下。

RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation, { pre_count: true, reset_ids: true })
  end

  config.before(:each, js: true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end
end
Run Code Online (Sandbox Code Playgroud)

在我的一个 rails 测试套件中,我打印了一个实例的 id。我认为它应该是相对较小的数字,因为 clean_with(:truncate) 假设清除数据库并对其运行真空。但每次我运行测试时它都会增加。

测试通过,它使用什么序列并不重要。但为什么clean_with(:truncation)不以它应该的方式工作?

====== 编辑 ======

这在 RSpec 测试的范围内。我知道序列编号对性能没有影响,但对每个 :suite 进行昂贵的清理 (:truncation) 并使用廉价且快速的清理 (:transaction) 会。所以我想了解为什么clean_with(:truncation)在运行测试套件之前不为我重置 id 以获得干净的数据库状态。

AJc*_*dez 5

这就是数据库的工作原理。

$ createdb test1
$ psql -d test1

> create table numbers (id serial, x integer);
> insert into numbers (x) values (1), (2), (3);
> select id from numbers order by id desc limit 1;

# 3

> truncate numbers;
> insert into numbers (x) values (1), (2);
> select id from numbers order by id desc limit 1;

# 5
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,:truncate数据库清理器意味着truncate. 希望这是有道理的。

编辑——完全错过了这个问题。

:reset_ids不起作用的原因是 postgresql 版本较低。使用 查找您的版本psql --version,并从数据库清理器源中查找您需要 8.4 或更高版本。

@restart_identity ||= db_version >=  80400 ? 'RESTART IDENTITY' : ''
Run Code Online (Sandbox Code Playgroud)

我运行的是 9.3.5,运行良好。

> truncate numbers restart identity;
> insert into numbers (x) values (1);
> select * from numbers;

#  id | x 
# ----+---
#   1 | 1
Run Code Online (Sandbox Code Playgroud)

为了确保数据库清理器也能正常工作。

require 'rails/all'
require 'database_cleaner'
ActiveRecord::Base.establish_connection('postgres://localhost/test1')
class Number < ActiveRecord::Base; end
Number.count
# => 1
DatabaseCleaner.clean_with(:truncation, reset_ids: true)
Run Code Online (Sandbox Code Playgroud)

它重置串行列。

$ psql -d test1
> insert into numbers (x) values (1);
> select * from numbers;

#  id | x 
# ----+---
#   1 | 1
Run Code Online (Sandbox Code Playgroud)