Skip to content

Commit 5827857

Browse files
committed
Fix retrieve_indexes_from_table when indexes is empty and base table does not exist.
Some tables may have a table_name_prefix but no indexes. Previous versions of the code would strip the prefix and look for indexes on the resulting table which likely would not exist. This causes DB errors, at least in MySQL. So now check if the new table exists first before trying to show its indexes.
1 parent 7d211dd commit 5827857

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

lib/annotate/annotate_models.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,11 @@ def retrieve_indexes_from_table(klass)
124124

125125
# Try to search the table without prefix
126126
table_name_without_prefix = table_name.to_s.sub(klass.table_name_prefix, '')
127-
klass.connection.indexes(table_name_without_prefix)
127+
if klass.connection.table_exists?(table_name_without_prefix)
128+
klass.connection.indexes(table_name_without_prefix)
129+
else
130+
[]
131+
end
128132
end
129133

130134
# Use the column information in an ActiveRecord class

spec/lib/annotate/annotate_models_spec.rb

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ def mock_connection(indexes = [], foreign_keys = [])
4545
double('Conn',
4646
indexes: indexes,
4747
foreign_keys: foreign_keys,
48-
supports_foreign_keys?: true)
48+
supports_foreign_keys?: true,
49+
table_exists?: true)
4950
end
5051

5152
def mock_class(table_name, primary_key, columns, indexes = [], foreign_keys = [])
@@ -520,7 +521,7 @@ def mock_column(name, type, options = {})
520521
end
521522
end
522523

523-
context 'when one of indexes includes orderd index key' do
524+
context 'when one of indexes includes ordered index key' do
524525
let :columns do
525526
[
526527
mock_column("id", :integer),
@@ -676,6 +677,20 @@ def mock_column(name, type, options = {})
676677
it 'returns schema info without index information' do
677678
is_expected.to eq expected_result
678679
end
680+
681+
context 'when the unprefixed table name does not exist' do
682+
let :klass do
683+
mock_class(:users, primary_key, columns, indexes, foreign_keys).tap do |mock_klass|
684+
expect(mock_klass).to receive(:table_name_prefix).and_return('my_prefix_')
685+
expect(mock_klass.connection).to receive(:table_exists?).with('users').and_return(false)
686+
allow(mock_klass.connection).to receive(:indexes).with('users').and_raise('error fetching indexes on nonexistent table')
687+
end
688+
end
689+
690+
it 'returns schema info without index information' do
691+
is_expected.to eq expected_result
692+
end
693+
end
679694
end
680695
end
681696

0 commit comments

Comments
 (0)