Skip to content

Commit bded429

Browse files
committed
Add Duplicate Indexes and Table Size
1 parent b58c62b commit bded429

5 files changed

Lines changed: 226 additions & 47 deletions

File tree

‎README.md‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
# MysqlGenius
1+
# MySQLGenius
22

3-
A MySQL performance dashboard and query explorer for Rails. Like [PgHero](https://github.com/ankane/pghero), but for MySQL -- with AI-powered query suggestions and optimization.
3+
A MySQL performance dashboard and query explorer for Rails, inspired by [PgHero](https://github.com/ankane/pghero). If you've used PgHero for PostgreSQL and wished something similar existed for MySQL -- this is it, with AI-powered query suggestions and optimization on top.
44

55
## Features
66

@@ -10,6 +10,8 @@ A MySQL performance dashboard and query explorer for Rails. Like [PgHero](https:
1010
- **AI Query Suggestions** -- describe what you want in plain English, get SQL back (optional, any OpenAI-compatible API)
1111
- **AI Query Optimization** -- get actionable optimization suggestions from EXPLAIN output (optional)
1212
- **Slow Query Monitoring** -- captures slow SELECT queries via ActiveSupport notifications and Redis
13+
- **Duplicate Index Detection** -- finds redundant indexes whose columns are a left-prefix of another index
14+
- **Table Size Dashboard** -- view row counts, data size, index size, and fragmentation for all tables
1315
- **Audit Logging** -- logs all query executions, rejections, and errors
1416
- **MariaDB Support** -- automatically detects MariaDB and uses appropriate timeout syntax
1517
- **Self-contained UI** -- no external CSS/JS dependencies, works with any Rails layout
@@ -118,7 +120,7 @@ end
118120

119121
### 3. AI Features (optional)
120122

121-
MysqlGenius supports AI-powered query suggestions and optimization via any OpenAI-compatible API, including OpenAI, Azure OpenAI, Ollama Cloud, and local Ollama instances.
123+
MySQLGenius supports AI-powered query suggestions and optimization via any OpenAI-compatible API, including OpenAI, Azure OpenAI, Ollama Cloud, and local Ollama instances.
122124

123125
```ruby
124126
MysqlGenius.configure do |config|
@@ -176,7 +178,7 @@ When AI is not configured, the AI Assistant panel and optimization buttons are h
176178

177179
## Usage
178180

179-
Visit `/mysql_genius` in your browser. The dashboard has three tabs:
181+
Visit `/mysql_genius` in your browser. The dashboard has five tabs:
180182

181183
### Visual Builder
182184
Select a table, pick columns, add type-aware filters (dates get date pickers, booleans get dropdowns), add sort orders, and run queries -- no SQL knowledge required. The generated SQL is shown and synced with the SQL tab.
@@ -190,6 +192,12 @@ View slow SELECT queries captured from your application in real time. Each slow
190192
- **Used** -- copy to the SQL tab for editing and re-running
191193
- **Optimized** -- get AI-powered optimization suggestions with specific index and rewrite recommendations
192194

195+
### Duplicate Indexes
196+
Scans all tables for redundant indexes -- indexes whose columns are a left-prefix of another index on the same table. Shows the `ALTER TABLE ... DROP INDEX` statement for each duplicate, ready to copy and run.
197+
198+
### Table Sizes
199+
Displays every table sorted by total size, with columns for estimated row count, data size, index size, total size, and fragmented space. Includes a visual size bar for quick comparison.
200+
193201
## Configuration Reference
194202

195203
| Option | Type | Default | Description |

‎app/controllers/mysql_genius/queries_controller.rb‎

Lines changed: 71 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
module MysqlGenius
22
class QueriesController < BaseController
3-
FORBIDDEN_KEYWORDS = %w[INSERT UPDATE DELETE DROP ALTER CREATE TRUNCATE GRANT REVOKE].freeze
4-
53
def index
64
@featured_tables = if mysql_genius_config.featured_tables.any?
75
mysql_genius_config.featured_tables.sort
@@ -149,42 +147,84 @@ def optimize
149147
render json: { error: "Optimization failed: #{e.message}" }, status: :unprocessable_entity
150148
end
151149

152-
private
153-
154-
def queryable_tables
155-
ActiveRecord::Base.connection.tables - mysql_genius_config.blocked_tables
156-
end
157-
158-
def validate_sql(sql)
159-
return "Please enter a query." if sql.blank?
160-
161-
normalized = sql.gsub(/--.*$/, "").gsub(%r{/\*.*?\*/}m, "").strip
150+
def duplicate_indexes
151+
connection = ActiveRecord::Base.connection
152+
duplicates = []
153+
154+
queryable_tables.each do |table|
155+
indexes = connection.indexes(table)
156+
next if indexes.size < 2
157+
158+
indexes.each do |idx|
159+
indexes.each do |other|
160+
next if idx.name == other.name
161+
# idx is duplicate if its columns are a left-prefix of other's columns
162+
if idx.columns.size <= other.columns.size &&
163+
other.columns.first(idx.columns.size) == idx.columns &&
164+
!(idx.unique && !other.unique) # don't drop a unique index covered by a non-unique one
165+
duplicates << {
166+
table: table,
167+
duplicate_index: idx.name,
168+
duplicate_columns: idx.columns,
169+
covered_by_index: other.name,
170+
covered_by_columns: other.columns,
171+
unique: idx.unique
172+
}
173+
end
174+
end
175+
end
176+
end
162177

163-
unless normalized.match?(/\ASELECT\b/i) || normalized.match?(/\AWITH\b/i)
164-
return "Only SELECT queries are allowed."
178+
# Deduplicate (A covers B and B covers A when columns are identical — keep only one)
179+
seen = Set.new
180+
duplicates = duplicates.reject do |d|
181+
key = [d[:table], [d[:duplicate_index], d[:covered_by_index]].sort].flatten.join(":")
182+
seen.include?(key) ? true : (seen.add(key); false)
165183
end
166184

167-
return "Access to system schemas is not allowed." if normalized.match?(/\b(information_schema|mysql|performance_schema|sys)\b/i)
185+
render json: duplicates
186+
end
168187

169-
FORBIDDEN_KEYWORDS.each do |keyword|
170-
return "#{keyword} statements are not allowed." if normalized.match?(/\b#{keyword}\b/i)
188+
def table_sizes
189+
connection = ActiveRecord::Base.connection
190+
db_name = connection.current_database
191+
192+
results = connection.exec_query(<<~SQL)
193+
SELECT
194+
table_name,
195+
table_rows,
196+
ROUND(data_length / 1024 / 1024, 2) AS data_mb,
197+
ROUND(index_length / 1024 / 1024, 2) AS index_mb,
198+
ROUND((data_length + index_length) / 1024 / 1024, 2) AS total_mb,
199+
ROUND(data_free / 1024 / 1024, 2) AS fragmented_mb
200+
FROM information_schema.tables
201+
WHERE table_schema = #{connection.quote(db_name)}
202+
AND table_type = 'BASE TABLE'
203+
ORDER BY (data_length + index_length) DESC
204+
SQL
205+
206+
tables = results.map do |row|
207+
{
208+
table: row["table_name"] || row["TABLE_NAME"],
209+
rows: row["table_rows"] || row["TABLE_ROWS"],
210+
data_mb: row["data_mb"].to_f,
211+
index_mb: row["index_mb"].to_f,
212+
total_mb: row["total_mb"].to_f,
213+
fragmented_mb: row["fragmented_mb"].to_f
214+
}
171215
end
172216

173-
tables_in_query = extract_table_references(normalized)
174-
blocked = tables_in_query & mysql_genius_config.blocked_tables
175-
if blocked.any?
176-
return "Access denied for table(s): #{blocked.join(', ')}."
177-
end
217+
render json: tables
218+
end
219+
220+
private
178221

179-
nil
222+
def queryable_tables
223+
ActiveRecord::Base.connection.tables - mysql_genius_config.blocked_tables
180224
end
181225

182-
def extract_table_references(sql)
183-
tables = []
184-
sql.scan(/\bFROM\s+((?:`?\w+`?(?:\s*,\s*`?\w+`?)*)+)/i) { |m| m[0].scan(/`?(\w+)`?/) { |t| tables << t[0] } }
185-
sql.scan(/\bJOIN\s+`?(\w+)`?/i) { |m| tables << m[0] }
186-
sql.scan(/\b(?:INTO|UPDATE)\s+`?(\w+)`?/i) { |m| tables << m[0] }
187-
tables.uniq.map(&:downcase) & ActiveRecord::Base.connection.tables
226+
def validate_sql(sql)
227+
SqlValidator.validate(sql, blocked_tables: mysql_genius_config.blocked_tables, connection: ActiveRecord::Base.connection)
188228
end
189229

190230
def apply_timeout_hint(sql)
@@ -201,15 +241,7 @@ def mariadb?
201241
end
202242

203243
def apply_row_limit(sql, limit)
204-
if sql.match?(/\bLIMIT\s+\d+\s*,\s*\d+/i)
205-
sql.gsub(/\bLIMIT\s+(\d+)\s*,\s*(\d+)/i) do
206-
"LIMIT #{::Regexp.last_match(1).to_i}, #{[::Regexp.last_match(2).to_i, limit].min}"
207-
end
208-
elsif sql.match?(/\bLIMIT\s+\d+/i)
209-
sql.gsub(/\bLIMIT\s+(\d+)/i) { "LIMIT #{[::Regexp.last_match(1).to_i, limit].min}" }
210-
else
211-
"#{sql.gsub(/;\s*\z/, '')} LIMIT #{limit}"
212-
end
244+
SqlValidator.apply_row_limit(sql, limit)
213245
end
214246

215247
def timeout_error?(exception)
@@ -218,7 +250,7 @@ def timeout_error?(exception)
218250
end
219251

220252
def masked_column?(column_name)
221-
mysql_genius_config.masked_column_patterns.any? { |pattern| column_name.downcase.include?(pattern) }
253+
SqlValidator.masked_column?(column_name, mysql_genius_config.masked_column_patterns)
222254
end
223255

224256
def sanitize_ai_sql(sql)

‎app/views/layouts/mysql_genius/application.html.erb‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<!DOCTYPE html>
22
<html>
33
<head>
4-
<title>MysqlGenius</title>
4+
<title>MySQLGenius</title>
55
<meta name="viewport" content="width=device-width, initial-scale=1">
66
<meta name="csrf-token" content="<%= form_authenticity_token %>">
77
<style>

‎app/views/mysql_genius/queries/index.html.erb‎

Lines changed: 139 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
<h4>&#128024; MysqlGenius</h4>
1+
<h4>&#128024; MySQLGenius</h4>
22

33
<div class="mg-tabs">
44
<button class="mg-tab active" data-tab="visual">Visual Builder</button>
55
<button class="mg-tab" data-tab="sql">SQL Query</button>
66
<button class="mg-tab" data-tab="slow">Slow Queries</button>
7+
<button class="mg-tab" data-tab="indexes">Duplicate Indexes</button>
8+
<button class="mg-tab" data-tab="sizes">Table Sizes</button>
79
</div>
810

911
<!-- Visual Builder Tab -->
@@ -123,6 +125,56 @@
123125
</div>
124126
</div>
125127

128+
<!-- Duplicate Indexes Tab -->
129+
<div class="mg-tab-content" id="tab-indexes">
130+
<div class="mg-row" style="justify-content:space-between;align-items:center;margin-bottom:12px;">
131+
<div class="mg-text-muted">Indexes whose columns are a left-prefix of another index on the same table. These are redundant and can safely be dropped. <span id="dup-count" class="mg-badge mg-badge-secondary"></span></div>
132+
<button id="dup-refresh" class="mg-btn mg-btn-outline-secondary mg-btn-sm">&#8635; Refresh</button>
133+
</div>
134+
<div id="dup-loading" class="mg-text-center mg-hidden"><span class="mg-spinner"></span> Scanning indexes...</div>
135+
<div id="dup-empty" class="mg-text-center mg-text-muted mg-hidden">No duplicate indexes found.</div>
136+
<div id="dup-table-wrapper" class="mg-table-wrap mg-hidden">
137+
<table class="mg-table">
138+
<thead>
139+
<tr>
140+
<th>Table</th>
141+
<th>Duplicate Index</th>
142+
<th>Columns</th>
143+
<th>Covered By</th>
144+
<th>Covered Columns</th>
145+
<th>DROP Statement</th>
146+
</tr>
147+
</thead>
148+
<tbody id="dup-tbody"></tbody>
149+
</table>
150+
</div>
151+
</div>
152+
153+
<!-- Table Sizes Tab -->
154+
<div class="mg-tab-content" id="tab-sizes">
155+
<div class="mg-row" style="justify-content:space-between;align-items:center;margin-bottom:12px;">
156+
<div class="mg-text-muted">Table sizes from <code>information_schema</code>, sorted by total size. Row counts are estimates. <span id="sizes-total" class="mg-badge mg-badge-secondary"></span></div>
157+
<button id="sizes-refresh" class="mg-btn mg-btn-outline-secondary mg-btn-sm">&#8635; Refresh</button>
158+
</div>
159+
<div id="sizes-loading" class="mg-text-center mg-hidden"><span class="mg-spinner"></span> Loading...</div>
160+
<div id="sizes-table-wrapper" class="mg-table-wrap mg-hidden">
161+
<table class="mg-table">
162+
<thead>
163+
<tr>
164+
<th>Table</th>
165+
<th style="text-align:right">Rows (est.)</th>
166+
<th style="text-align:right">Data</th>
167+
<th style="text-align:right">Indexes</th>
168+
<th style="text-align:right">Total</th>
169+
<th style="text-align:right">Fragmented</th>
170+
<th style="width:200px"></th>
171+
</tr>
172+
</thead>
173+
<tbody id="sizes-tbody"></tbody>
174+
</table>
175+
</div>
176+
</div>
177+
126178
<!-- Explain Results -->
127179
<div id="explain-results" class="mg-mt mg-hidden">
128180
<div class="mg-card">
@@ -176,7 +228,9 @@
176228
explain: '<%= mysql_genius.explain_path %>',
177229
suggest: '<%= mysql_genius.suggest_path %>',
178230
optimize: '<%= mysql_genius.optimize_path %>',
179-
slow_queries: '<%= mysql_genius.slow_queries_path %>'
231+
slow_queries: '<%= mysql_genius.slow_queries_path %>',
232+
duplicate_indexes: '<%= mysql_genius.duplicate_indexes_path %>',
233+
table_sizes: '<%= mysql_genius.table_sizes_path %>'
180234
};
181235

182236
var csrfMeta = document.querySelector('meta[name="csrf-token"]');
@@ -251,6 +305,8 @@
251305
tab.classList.add('active');
252306
el('tab-' + tab.dataset.tab).classList.add('active');
253307
if (tab.dataset.tab === 'slow') loadSlowQueries();
308+
if (tab.dataset.tab === 'indexes') loadDuplicateIndexes();
309+
if (tab.dataset.tab === 'sizes') loadTableSizes();
254310
});
255311
});
256312

@@ -651,6 +707,87 @@
651707
}
652708
});
653709

710+
// --- Duplicate Indexes ---
711+
712+
function loadDuplicateIndexes() {
713+
show(el('dup-loading'));
714+
hide(el('dup-empty')); hide(el('dup-table-wrapper'));
715+
el('dup-tbody').innerHTML = '';
716+
717+
ajaxGet(ROUTES.duplicate_indexes, {}, function(data) {
718+
hide(el('dup-loading'));
719+
if (!data || !data.length) { show(el('dup-empty')); el('dup-count').textContent = '0'; return; }
720+
el('dup-count').textContent = data.length + ' found';
721+
el('dup-tbody').innerHTML = data.map(function(d) {
722+
var dropSql = 'ALTER TABLE `' + d.table + '` DROP INDEX `' + d.duplicate_index + '`;';
723+
return '<tr>' +
724+
'<td><strong>' + escHtml(d.table) + '</strong></td>' +
725+
'<td><code>' + escHtml(d.duplicate_index) + '</code>' + (d.unique ? ' <span class="mg-badge mg-badge-warning">UNIQUE</span>' : '') + '</td>' +
726+
'<td>' + d.duplicate_columns.map(function(c) { return '<code>' + escHtml(c) + '</code>'; }).join(', ') + '</td>' +
727+
'<td><code>' + escHtml(d.covered_by_index) + '</code></td>' +
728+
'<td>' + d.covered_by_columns.map(function(c) { return '<code>' + escHtml(c) + '</code>'; }).join(', ') + '</td>' +
729+
'<td><code style="font-size:11px;user-select:all;cursor:pointer;" title="Click to select">' + escHtml(dropSql) + '</code></td>' +
730+
'</tr>';
731+
}).join('');
732+
show(el('dup-table-wrapper'));
733+
}, function() {
734+
hide(el('dup-loading'));
735+
el('dup-empty').textContent = 'Failed to scan indexes.';
736+
show(el('dup-empty'));
737+
});
738+
}
739+
740+
el('dup-refresh').addEventListener('click', loadDuplicateIndexes);
741+
742+
// --- Table Sizes ---
743+
744+
function formatMb(mb) {
745+
if (mb >= 1024) return (mb / 1024).toFixed(2) + ' GB';
746+
if (mb >= 1) return mb.toFixed(2) + ' MB';
747+
return (mb * 1024).toFixed(0) + ' KB';
748+
}
749+
750+
function sizeBar(pct, color) {
751+
return '<div style="background:#e9ecef;border-radius:3px;height:8px;width:100%;">' +
752+
'<div style="background:' + color + ';border-radius:3px;height:8px;width:' + Math.max(pct, 1) + '%;"></div></div>';
753+
}
754+
755+
function loadTableSizes() {
756+
show(el('sizes-loading'));
757+
hide(el('sizes-table-wrapper'));
758+
el('sizes-tbody').innerHTML = '';
759+
760+
ajaxGet(ROUTES.table_sizes, {}, function(data) {
761+
hide(el('sizes-loading'));
762+
if (!data || !data.length) { el('sizes-total').textContent = '0 tables'; show(el('sizes-table-wrapper')); return; }
763+
764+
var totalMb = data.reduce(function(sum, t) { return sum + t.total_mb; }, 0);
765+
el('sizes-total').textContent = data.length + ' tables, ' + formatMb(totalMb) + ' total';
766+
var maxMb = data[0].total_mb || 1;
767+
768+
el('sizes-tbody').innerHTML = data.map(function(t) {
769+
var pct = (t.total_mb / maxMb) * 100;
770+
var color = t.total_mb >= 100 ? '#dc3545' : t.total_mb >= 10 ? '#ffc107' : '#28a745';
771+
var rows = t.rows != null ? Number(t.rows).toLocaleString() : '?';
772+
return '<tr>' +
773+
'<td><strong>' + escHtml(t.table) + '</strong></td>' +
774+
'<td style="text-align:right">' + rows + '</td>' +
775+
'<td style="text-align:right">' + formatMb(t.data_mb) + '</td>' +
776+
'<td style="text-align:right">' + formatMb(t.index_mb) + '</td>' +
777+
'<td style="text-align:right"><strong>' + formatMb(t.total_mb) + '</strong></td>' +
778+
'<td style="text-align:right">' + (t.fragmented_mb > 0 ? formatMb(t.fragmented_mb) : '-') + '</td>' +
779+
'<td>' + sizeBar(pct, color) + '</td>' +
780+
'</tr>';
781+
}).join('');
782+
show(el('sizes-table-wrapper'));
783+
}, function() {
784+
hide(el('sizes-loading'));
785+
el('sizes-total').textContent = 'Failed to load';
786+
});
787+
}
788+
789+
el('sizes-refresh').addEventListener('click', loadTableSizes);
790+
654791
// --- SQL to Builder sync ---
655792

656793
function parseSqlToBuilder(sql) {

‎config/routes.rb‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,7 @@
66
post "explain", to: "queries#explain"
77
post "suggest", to: "queries#suggest"
88
post "optimize", to: "queries#optimize"
9-
get "slow_queries", to: "queries#slow_queries"
9+
get "slow_queries", to: "queries#slow_queries"
10+
get "duplicate_indexes", to: "queries#duplicate_indexes"
11+
get "table_sizes", to: "queries#table_sizes"
1012
end

0 commit comments

Comments
 (0)