Skip to content

Commit c0a195c

Browse files
committed
Add UNLOGGED tables rake task for optional test performance
Adds db:test:unlogged task that converts all PostgreSQL tables to UNLOGGED mode. UNLOGGED tables skip WAL logging, which can make writes faster during test setup. Benchmarks on this codebase showed minimal impact (~1%): - Model specs: 13.7s (LOGGED) vs 13.8s (UNLOGGED) - Full suite: 87s (LOGGED) vs 86s (UNLOGGED) The benefit depends on your test suite characteristics: - More useful if you have many feature specs with heavy database writes - Less useful if most tests use transactional fixtures Auto-runs after db:test:prepare when in test environment. Can be removed if it causes issues or doesn't help your workload.
1 parent 7640305 commit c0a195c

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

lib/tasks/test_unlogged.rake

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
namespace :db do
2+
namespace :test do
3+
desc "Convert all tables to UNLOGGED for faster test performance"
4+
task unlogged: :environment do
5+
raise "This task only works in test environment" unless Rails.env.test?
6+
7+
tables = ActiveRecord::Base.connection.tables
8+
converted = 0
9+
tables.each do |table|
10+
next if table == "schema_migrations" || table == "ar_internal_metadata"
11+
result = ActiveRecord::Base.connection.execute(
12+
"SELECT relpersistence FROM pg_class WHERE relname = '#{table}'"
13+
)
14+
if result.first && result.first["relpersistence"] != "u"
15+
ActiveRecord::Base.connection.execute("ALTER TABLE #{table} SET UNLOGGED")
16+
converted += 1
17+
end
18+
end
19+
puts "Converted #{converted} tables to UNLOGGED" if converted > 0
20+
end
21+
end
22+
end
23+
24+
# Auto-run after db:test:prepare
25+
Rake::Task["db:test:prepare"].enhance do
26+
Rake::Task["db:test:unlogged"].invoke if Rails.env.test?
27+
end

0 commit comments

Comments
 (0)