Skip to content

Commit df781eb

Browse files
committed
Add PostgreSQL support for tables_with_new_rows optimization
Extends the `tables_with_new_rows` method to work with PostgreSQL. Previously, this optimization only worked for MySQL/Trilogy adapters.
1 parent 874dea9 commit df781eb

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

lib/database_cleaner/active_record/deletion.rb

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,17 @@ def table_stats_query(connection)
6464
end
6565

6666
def build_table_stats_query(connection)
67+
case connection.adapter_name
68+
when "Mysql2", "Trilogy"
69+
build_mysql_table_stats_query(connection)
70+
when "PostgreSQL"
71+
build_postgresql_table_stats_query(connection)
72+
else
73+
''
74+
end
75+
end
76+
77+
def build_mysql_table_stats_query(connection)
6778
tables = connection.select_values(<<-SQL)
6879
SELECT table_name
6980
FROM information_schema.tables
@@ -76,8 +87,22 @@ def build_table_stats_query(connection)
7687
queries.join(' UNION ALL ')
7788
end
7889

90+
def build_postgresql_table_stats_query(connection)
91+
tables = connection.select_values(<<-SQL)
92+
SELECT table_name
93+
FROM information_schema.tables
94+
WHERE table_schema = current_schema()
95+
AND table_type = 'BASE TABLE'
96+
AND #{self.class.exclusion_condition('table_name')};
97+
SQL
98+
queries = tables.map do |table|
99+
"(SELECT #{connection.quote(table)} FROM #{connection.quote_table_name(table)} LIMIT 1)"
100+
end
101+
queries.join(' UNION ALL ')
102+
end
103+
79104
def information_schema_exists? connection
80-
["Mysql2", "Trilogy"].include?(connection.adapter_name)
105+
["Mysql2", "Trilogy", "PostgreSQL"].include?(connection.adapter_name)
81106
end
82107
end
83108
end

spec/database_cleaner/active_record/deletion_spec.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@
9999
subject(:strategy) { described_class.new(cache_tables: true) }
100100

101101
it 'caches the list of tables to be deleted from' do
102-
if [:mysql2, :trilogy].include?(helper.db)
102+
if [:mysql2, :trilogy, :postgres].include?(helper.db)
103103
expect(strategy).to receive(:build_table_stats_query).once.and_return("")
104104
elsif helper.db == :postgres
105105
expect(strategy.send(:connection)).to receive(:tables_with_schema).once.and_return([])
@@ -116,7 +116,7 @@
116116
subject(:strategy) { described_class.new(cache_tables: false) }
117117

118118
it 'does not cache the list of tables to be deleted from' do
119-
if [:mysql2, :trilogy].include?(helper.db)
119+
if [:mysql2, :trilogy, :postgres].include?(helper.db)
120120
expect(strategy).to receive(:build_table_stats_query).twice.and_return("")
121121
elsif helper.db == :postgres
122122
expect(strategy.send(:connection)).to receive(:tables_with_schema).twice.and_return([])

0 commit comments

Comments
 (0)