diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 782f25b..17f670d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -13,14 +13,9 @@ jobs:
strategy:
fail-fast: false
matrix:
- ruby: ["2.7", "3.0", "3.1", "3.2", "3.3"]
- rails: ["5.2", "6.0", "6.1", "7.0", "7.1", "7.2"]
+ ruby: ["2.7", "3.0", "3.1", "3.2", "3.3", "3.4"]
+ rails: ["5.2", "6.0", "6.1", "7.0", "7.1", "7.2", "8.0", "8.1"]
exclude:
- # Rails 7.0+ requires Ruby 2.7+, but 7.2 requires 3.1+
- - ruby: "2.7"
- rails: "7.2"
- - ruby: "3.0"
- rails: "7.2"
# Rails 5.2 doesn't support Ruby 3.1+
- ruby: "3.1"
rails: "5.2"
@@ -28,11 +23,39 @@ jobs:
rails: "5.2"
- ruby: "3.3"
rails: "5.2"
+ - ruby: "3.4"
+ rails: "5.2"
# Rails 6.0 doesn't support Ruby 3.2+
- ruby: "3.2"
rails: "6.0"
- ruby: "3.3"
rails: "6.0"
+ - ruby: "3.4"
+ rails: "6.0"
+ # Rails 6.1 doesn't support Ruby 3.4 (mutex_m removed from stdlib)
+ - ruby: "3.4"
+ rails: "6.1"
+ # Rails 7.0 doesn't support Ruby 3.4 (mutex_m removed from stdlib)
+ - ruby: "3.4"
+ rails: "7.0"
+ # Rails 7.2+ requires Ruby 3.1+
+ - ruby: "2.7"
+ rails: "7.2"
+ - ruby: "3.0"
+ rails: "7.2"
+ # Rails 8.0+ requires Ruby 3.2+
+ - ruby: "2.7"
+ rails: "8.0"
+ - ruby: "3.0"
+ rails: "8.0"
+ - ruby: "3.1"
+ rails: "8.0"
+ - ruby: "2.7"
+ rails: "8.1"
+ - ruby: "3.0"
+ rails: "8.1"
+ - ruby: "3.1"
+ rails: "8.1"
env:
RAILS_VERSION: ${{ matrix.rails }}
@@ -51,3 +74,6 @@ jobs:
- name: Run specs
run: bundle exec rspec
+
+ - name: Run RuboCop
+ run: bundle exec rubocop
diff --git a/.gitignore b/.gitignore
index 1694fee..a57b256 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,3 +10,5 @@
# rspec failure tracking
.rspec_status
/vendor
+CLAUDE.md
+Gemfile.lock
diff --git a/.rubocop.yml b/.rubocop.yml
new file mode 100644
index 0000000..d6227cd
--- /dev/null
+++ b/.rubocop.yml
@@ -0,0 +1,24 @@
+inherit_gem:
+ rubocop-shopify: rubocop.yml
+
+require:
+ - rubocop-rspec
+
+AllCops:
+ TargetRubyVersion: 2.6
+ NewCops: enable
+
+Layout/LineLength:
+ Max: 250
+
+RSpec/MessageSpies:
+ Enabled: false
+
+RSpec/VerifiedDoubles:
+ Enabled: false
+
+RSpec/ExampleLength:
+ Max: 25
+
+RSpec/MultipleExpectations:
+ Max: 5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 38c00ea..8290e45 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,19 @@
# Changelog
+## 0.2.0
+
+- **Dashboard-first redesign** -- new default landing page with server health, top slow queries, top expensive queries, and index alert badges
+- **Query Explorer** -- merged Visual Builder and SQL Query into one tab with a mode toggle
+- **Suggested migrations** -- duplicate and unused index tabs generate timestamped Rails migrations with copy-to-clipboard
+- **Install generator** -- `rails generate mysql_genius:install` creates initializer and mounts the engine
+- **RuboCop** -- added rubocop-shopify and rubocop-rspec, enforced across the codebase
+- **CI matrix** -- added Ruby 3.4, Rails 8.0 and 8.1; excluded incompatible Ruby 3.4 + Rails 6.1/7.0 combos
+- **SSL fix** -- explicit CA certificate file for AI API requests
+- Tab reorder: Dashboard, Slow Queries, Query Stats, Server, Table Sizes, Unused Indexes, Duplicate Indexes, Query Explorer, AI Tools
+- Dashboard links to Server tab for full details
+- Clipboard fallback for non-HTTPS environments
+- Gemspec description updated to lead with monitoring features
+
## 0.1.0
- Initial release
diff --git a/Gemfile b/Gemfile
index a275d2c..f5b1395 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,15 +1,20 @@
+# frozen_string_literal: true
+
source "https://rubygems.org"
gemspec
if ENV["RAILS_VERSION"]
rails_version = ENV["RAILS_VERSION"]
- gem "railties", "~> #{rails_version}.0"
- gem "activerecord", "~> #{rails_version}.0"
gem "actionpack", "~> #{rails_version}.0"
+ gem "activerecord", "~> #{rails_version}.0"
+ gem "railties", "~> #{rails_version}.0"
end
group :development, :test do
gem "rake"
gem "rspec", "~> 3.0"
+ gem "rubocop"
+ gem "rubocop-shopify"
+ gem "rubocop-rspec"
end
diff --git a/README.md b/README.md
index 229faf2..0666a45 100644
--- a/README.md
+++ b/README.md
@@ -4,37 +4,48 @@ A MySQL performance dashboard and query explorer for Rails, inspired by [PgHero]
## Screenshots
-### Visual Builder
-Build queries visually -- select tables, pick columns, add type-aware filters, and sort results without writing SQL.
+### Dashboard
-
+At-a-glance server health, top slow queries, most expensive queries, and index alerts.
-### SQL Query with AI Assistant
-Write raw SQL or describe what you want in plain English and let the AI generate the query for you.
+
-
+### Slow Queries
-### Duplicate Index Detection
-Find redundant indexes whose columns are a left-prefix of another index, with ready-to-run `DROP INDEX` statements.
+SELECT queries exceeding the configured threshold, captured via ActiveSupport notifications and Redis.
-
+### Query Stats
+
+Top queries from `performance_schema` sorted by total time, with call counts, avg/max time, and rows examined.
+
+
+
+### Server Dashboard
+
+Server health: version, connections, InnoDB buffer pool, and query activity with AI-powered diagnostics.
+
+
### Table Sizes
+
View row counts, data size, index size, fragmentation, and a visual size chart for every table.

-### Query Stats
-Top queries from `performance_schema` sorted by total time, with call counts, avg/max time, and rows examined.
+### Duplicate Index Detection
-
+Find redundant indexes whose columns are a left-prefix of another index, with ready-to-run `DROP INDEX` statements.
-### Server Dashboard
-At-a-glance server health: version, connections, InnoDB buffer pool, and query activity with AI-powered diagnostics.
+
-
+### Query Explorer
+
+Build queries visually or write raw SQL. Optional AI assistant generates queries from plain English descriptions.
+
+
### AI Tools
+
Schema review that finds anti-patterns -- missing primary keys, nullable foreign keys, inappropriate column types, and more.

@@ -77,7 +88,7 @@ gem "mysql_genius", github: "antarr/mysql_genius"
Then run:
-```
+```bash
bundle install
```
@@ -215,25 +226,24 @@ When AI is not configured, the AI Assistant panel and optimization buttons are h
## Usage
-Visit `/mysql_genius` in your browser. The dashboard has five tabs:
+Visit `/mysql_genius` in your browser. The dashboard loads automatically with an overview of your database health.
-### Visual Builder
-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.
+### Dashboard
-### SQL Query
-Write raw SQL directly. The optional AI Assistant lets you describe what you want in plain English and generates a query. AI-generated queries are synced back to the Visual Builder for further refinement.
+The default landing page shows server health cards, top 5 slow queries, top 5 most expensive queries (from performance_schema), and index alert badges for duplicate and unused indexes. Each section links to its detailed tab.
-### Slow Queries
-View slow SELECT queries captured from your application in real time. Each slow query can be:
-- **Explained** -- run EXPLAIN to see the execution plan (bypasses blocked table restrictions)
-- **Used** -- copy to the SQL tab for editing and re-running
-- **Optimized** -- get AI-powered optimization suggestions with specific index and rewrite recommendations
+### Query Explorer
-### Duplicate Indexes
-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.
+Combines the visual query builder and raw SQL editor in one tab. Toggle between Visual mode (point-and-click with column selection, filters, and ordering) and SQL mode (raw SQL with optional AI assistant). Generated SQL syncs between modes.
-### Table Sizes
-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.
+### Monitoring Tabs
+
+- **Slow Queries** -- slow SELECT queries captured from your application in real time, with Explain and Optimize actions
+- **Query Stats** -- top queries from `performance_schema` sorted by total time, avg time, calls, or rows examined
+- **Server** -- connections, InnoDB buffer pool, query activity, with AI-powered diagnostics
+- **Table Sizes** -- row counts, data size, index size, fragmentation for all tables
+- **Unused Indexes** -- indexes with zero reads since server restart
+- **Duplicate Indexes** -- redundant indexes with ready-to-run DROP statements
## Configuration Reference
@@ -264,16 +274,18 @@ Tested against:
| Rails | Ruby |
|-------|------|
-| 5.2 | 2.6, 2.7, 3.0 |
-| 6.0 | 2.6, 2.7, 3.0, 3.1 |
-| 6.1 | 2.6, 2.7, 3.0, 3.1, 3.2, 3.3 |
+| 5.2 | 2.7, 3.0 |
+| 6.0 | 2.7, 3.0, 3.1 |
+| 6.1 | 2.7, 3.0, 3.1, 3.2, 3.3 |
| 7.0 | 2.7, 3.0, 3.1, 3.2, 3.3 |
-| 7.1 | 2.7, 3.0, 3.1, 3.2, 3.3 |
-| 7.2 | 3.1, 3.2, 3.3 |
+| 7.1 | 2.7, 3.0, 3.1, 3.2, 3.3, 3.4 |
+| 7.2 | 3.1, 3.2, 3.3, 3.4 |
+| 8.0 | 3.2, 3.3, 3.4 |
+| 8.1 | 3.2, 3.3, 3.4 |
## Development
-```
+```bash
git clone https://github.com/antarr/mysql_genius.git
cd mysql_genius
bin/setup
@@ -282,7 +294,7 @@ bundle exec rspec
To test against a specific Rails version:
-```
+```bash
RAILS_VERSION=6.1 bundle update && bundle exec rspec
```
diff --git a/Rakefile b/Rakefile
index b7e9ed5..b6ae734 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,6 +1,8 @@
+# frozen_string_literal: true
+
require "bundler/gem_tasks"
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec)
-task :default => :spec
+task default: :spec
diff --git a/app/controllers/concerns/mysql_genius/ai_features.rb b/app/controllers/concerns/mysql_genius/ai_features.rb
index 8f88cf9..f239fe8 100644
--- a/app/controllers/concerns/mysql_genius/ai_features.rb
+++ b/app/controllers/concerns/mysql_genius/ai_features.rb
@@ -1,44 +1,47 @@
+# frozen_string_literal: true
+
module MysqlGenius
module AiFeatures
extend ActiveSupport::Concern
def suggest
unless mysql_genius_config.ai_enabled?
- return render json: { error: "AI features are not configured." }, status: :not_found
+ return render(json: { error: "AI features are not configured." }, status: :not_found)
end
prompt = params[:prompt].to_s.strip
- return render json: { error: "Please describe what you want to query." }, status: :unprocessable_entity if prompt.blank?
+ return render(json: { error: "Please describe what you want to query." }, status: :unprocessable_entity) if prompt.blank?
result = AiSuggestionService.new.call(prompt, queryable_tables)
sql = sanitize_ai_sql(result["sql"].to_s)
- render json: { sql: sql, explanation: result["explanation"] }
+ render(json: { sql: sql, explanation: result["explanation"] })
rescue StandardError => e
- render json: { error: "AI suggestion failed: #{e.message}" }, status: :unprocessable_entity
+ render(json: { error: "AI suggestion failed: #{e.message}" }, status: :unprocessable_entity)
end
def optimize
unless mysql_genius_config.ai_enabled?
- return render json: { error: "AI features are not configured." }, status: :not_found
+ return render(json: { error: "AI features are not configured." }, status: :not_found)
end
sql = params[:sql].to_s.strip
explain_rows = Array(params[:explain_rows]).map { |row| row.respond_to?(:values) ? row.values : Array(row) }
if sql.blank? || explain_rows.blank?
- return render json: { error: "SQL and EXPLAIN output are required." }, status: :unprocessable_entity
+ return render(json: { error: "SQL and EXPLAIN output are required." }, status: :unprocessable_entity)
end
result = AiOptimizationService.new.call(sql, explain_rows, queryable_tables)
- render json: result
+ render(json: result)
rescue StandardError => e
- render json: { error: "Optimization failed: #{e.message}" }, status: :unprocessable_entity
+ render(json: { error: "Optimization failed: #{e.message}" }, status: :unprocessable_entity)
end
def describe_query
return ai_not_configured unless mysql_genius_config.ai_enabled?
+
sql = params[:sql].to_s.strip
- return render json: { error: "SQL is required." }, status: :unprocessable_entity if sql.blank?
+ return render(json: { error: "SQL is required." }, status: :unprocessable_entity) if sql.blank?
messages = [
{ role: "system", content: <<~PROMPT },
@@ -50,31 +53,33 @@ def describe_query
#{ai_domain_context}
Respond with JSON: {"explanation": "your plain-English explanation using markdown formatting"}
PROMPT
- { role: "user", content: sql }
+ { role: "user", content: sql },
]
result = AiClient.new.chat(messages: messages)
- render json: result
+ render(json: result)
rescue StandardError => e
- render json: { error: "Explanation failed: #{e.message}" }, status: :unprocessable_entity
+ render(json: { error: "Explanation failed: #{e.message}" }, status: :unprocessable_entity)
end
def schema_review
return ai_not_configured unless mysql_genius_config.ai_enabled?
+
table = params[:table].to_s.strip
connection = ActiveRecord::Base.connection
tables_to_review = table.present? ? [table] : queryable_tables.first(20)
schema_desc = tables_to_review.map do |t|
next unless connection.tables.include?(t)
- cols = connection.columns(t).map { |c| "#{c.name} #{c.sql_type}#{c.null ? '' : ' NOT NULL'}#{c.default ? " DEFAULT #{c.default}" : ''}" }
+
+ cols = connection.columns(t).map { |c| "#{c.name} #{c.sql_type}#{" NOT NULL" unless c.null}#{" DEFAULT #{c.default}" if c.default}" }
pk = connection.primary_key(t)
- indexes = connection.indexes(t).map { |idx| "#{idx.unique ? 'UNIQUE ' : ''}INDEX #{idx.name} (#{idx.columns.join(', ')})" }
+ indexes = connection.indexes(t).map { |idx| "#{"UNIQUE " if idx.unique}INDEX #{idx.name} (#{idx.columns.join(", ")})" }
row_count = connection.exec_query("SELECT TABLE_ROWS FROM information_schema.tables WHERE table_schema = #{connection.quote(connection.current_database)} AND table_name = #{connection.quote(t)}").rows.first&.first
desc = "Table: #{t} (~#{row_count} rows)\n"
- desc += "Primary Key: #{pk || 'NONE'}\n"
- desc += "Columns: #{cols.join(', ')}\n"
- desc += "Indexes: #{indexes.any? ? indexes.join(', ') : 'NONE'}"
+ desc += "Primary Key: #{pk || "NONE"}\n"
+ desc += "Columns: #{cols.join(", ")}\n"
+ desc += "Indexes: #{indexes.any? ? indexes.join(", ") : "NONE"}"
desc
end.compact.join("\n\n")
@@ -92,19 +97,20 @@ def schema_review
#{ai_domain_context}
Respond with JSON: {"findings": "markdown-formatted findings organized by severity (Critical, Warning, Suggestion). Include specific ALTER TABLE statements where applicable."}
PROMPT
- { role: "user", content: schema_desc }
+ { role: "user", content: schema_desc },
]
result = AiClient.new.chat(messages: messages)
- render json: result
+ render(json: result)
rescue StandardError => e
- render json: { error: "Schema review failed: #{e.message}" }, status: :unprocessable_entity
+ render(json: { error: "Schema review failed: #{e.message}" }, status: :unprocessable_entity)
end
def rewrite_query
return ai_not_configured unless mysql_genius_config.ai_enabled?
+
sql = params[:sql].to_s.strip
- return render json: { error: "SQL is required." }, status: :unprocessable_entity if sql.blank?
+ return render(json: { error: "SQL is required." }, status: :unprocessable_entity) if sql.blank?
schema = build_schema_for_query(sql)
@@ -127,30 +133,31 @@ def rewrite_query
Respond with JSON: {"original": "the original SQL", "rewritten": "the improved SQL", "changes": "markdown list of each change and why it helps"}
PROMPT
- { role: "user", content: sql }
+ { role: "user", content: sql },
]
result = AiClient.new.chat(messages: messages)
- render json: result
+ render(json: result)
rescue StandardError => e
- render json: { error: "Rewrite failed: #{e.message}" }, status: :unprocessable_entity
+ render(json: { error: "Rewrite failed: #{e.message}" }, status: :unprocessable_entity)
end
def index_advisor
return ai_not_configured unless mysql_genius_config.ai_enabled?
+
sql = params[:sql].to_s.strip
explain_rows = Array(params[:explain_rows]).map { |row| row.respond_to?(:values) ? row.values : Array(row) }
- return render json: { error: "SQL and EXPLAIN output are required." }, status: :unprocessable_entity if sql.blank? || explain_rows.blank?
+ return render(json: { error: "SQL and EXPLAIN output are required." }, status: :unprocessable_entity) if sql.blank? || explain_rows.blank?
connection = ActiveRecord::Base.connection
tables_in_query = SqlValidator.extract_table_references(sql, connection)
index_detail = tables_in_query.map do |t|
- indexes = connection.indexes(t).map { |idx| "#{idx.unique ? 'UNIQUE ' : ''}INDEX #{idx.name} (#{idx.columns.join(', ')})" }
+ indexes = connection.indexes(t).map { |idx| "#{"UNIQUE " if idx.unique}INDEX #{idx.name} (#{idx.columns.join(", ")})" }
stats = connection.exec_query("SELECT INDEX_NAME, COLUMN_NAME, CARDINALITY, SEQ_IN_INDEX FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = #{connection.quote(connection.current_database)} AND TABLE_NAME = #{connection.quote(t)} ORDER BY INDEX_NAME, SEQ_IN_INDEX")
cardinality = stats.rows.map { |r| "#{r[0]}.#{r[1]}: cardinality=#{r[2]}" }.join(", ")
row_count = connection.exec_query("SELECT TABLE_ROWS FROM information_schema.tables WHERE table_schema = #{connection.quote(connection.current_database)} AND table_name = #{connection.quote(t)}").rows.first&.first
- "Table: #{t} (~#{row_count} rows)\nIndexes: #{indexes.any? ? indexes.join('; ') : 'NONE'}\nCardinality: #{cardinality}"
+ "Table: #{t} (~#{row_count} rows)\nIndexes: #{indexes.any? ? indexes.join("; ") : "NONE"}\nCardinality: #{cardinality}"
end.join("\n\n")
messages = [
@@ -165,17 +172,18 @@ def index_advisor
Respond with JSON: {"indexes": "markdown-formatted recommendations with exact CREATE INDEX statements, rationale for column ordering, and estimated impact. Include any indexes that should be DROPPED as part of the change."}
PROMPT
- { role: "user", content: "Query:\n#{sql}\n\nEXPLAIN:\n#{explain_rows.map { |r| r.join(' | ') }.join("\n")}\n\nCurrent Indexes:\n#{index_detail}" }
+ { role: "user", content: "Query:\n#{sql}\n\nEXPLAIN:\n#{explain_rows.map { |r| r.join(" | ") }.join("\n")}\n\nCurrent Indexes:\n#{index_detail}" },
]
result = AiClient.new.chat(messages: messages)
- render json: result
+ render(json: result)
rescue StandardError => e
- render json: { error: "Index advisor failed: #{e.message}" }, status: :unprocessable_entity
+ render(json: { error: "Index advisor failed: #{e.message}" }, status: :unprocessable_entity)
end
def anomaly_detection
return ai_not_configured unless mysql_genius_config.ai_enabled?
+
connection = ActiveRecord::Base.connection
# Gather recent slow queries
@@ -183,7 +191,11 @@ def anomaly_detection
if mysql_genius_config.redis_url
redis = Redis.new(url: mysql_genius_config.redis_url)
raw = redis.lrange(SlowQueryMonitor.redis_key, 0, 99)
- slow_data = raw.map { |e| JSON.parse(e) rescue nil }.compact
+ slow_data = raw.map do |e|
+ JSON.parse(e)
+ rescue
+ nil
+ end.compact
end
# Gather top query stats
@@ -205,7 +217,7 @@ def anomaly_detection
# performance_schema may not be available
end
- slow_summary = slow_data.first(50).map { |q| "#{q['duration_ms']}ms @ #{q['timestamp']}: #{q['sql'].to_s.truncate(150)}" }.join("\n")
+ slow_summary = slow_data.first(50).map { |q| "#{q["duration_ms"]}ms @ #{q["timestamp"]}: #{q["sql"].to_s.truncate(150)}" }.join("\n")
stats_summary = stats.map { |q| "calls=#{q[:calls]} avg=#{q[:avg_ms]}ms total=#{q[:total_ms]}ms exam=#{q[:rows_examined]} sent=#{q[:rows_sent]}: #{q[:sql]}" }.join("\n")
messages = [
@@ -220,17 +232,18 @@ def anomaly_detection
Respond with JSON: {"report": "markdown-formatted health report organized by severity. For each finding, explain the issue, affected query, and recommended fix."}
PROMPT
- { role: "user", content: "Recent Slow Queries (last #{slow_data.size}):\n#{slow_summary.presence || 'None captured'}\n\nTop Queries by Total Time:\n#{stats_summary.presence || 'Not available'}" }
+ { role: "user", content: "Recent Slow Queries (last #{slow_data.size}):\n#{slow_summary.presence || "None captured"}\n\nTop Queries by Total Time:\n#{stats_summary.presence || "Not available"}" },
]
result = AiClient.new.chat(messages: messages)
- render json: result
+ render(json: result)
rescue StandardError => e
- render json: { error: "Anomaly detection failed: #{e.message}" }, status: :unprocessable_entity
+ render(json: { error: "Anomaly detection failed: #{e.message}" }, status: :unprocessable_entity)
end
def root_cause
return ai_not_configured unless mysql_genius_config.ai_enabled?
+
connection = ActiveRecord::Base.connection
# PROCESSLIST
@@ -242,16 +255,26 @@ def root_cause
status = {}
status_rows.each { |r| status[(r["Variable_name"] || r["variable_name"]).to_s] = (r["Value"] || r["value"]).to_s }
- key_stats = %w[Threads_connected Threads_running Innodb_row_lock_waits Innodb_row_lock_current_waits
- Innodb_buffer_pool_reads Innodb_buffer_pool_read_requests Slow_queries Created_tmp_disk_tables
- Connections Aborted_connects].map { |k| "#{k}=#{status[k]}" }.join(", ")
+ key_stats = [
+ "Threads_connected",
+ "Threads_running",
+ "Innodb_row_lock_waits",
+ "Innodb_row_lock_current_waits",
+ "Innodb_buffer_pool_reads",
+ "Innodb_buffer_pool_read_requests",
+ "Slow_queries",
+ "Created_tmp_disk_tables",
+ "Connections",
+ "Aborted_connects",
+ ].map { |k| "#{k}=#{status[k]}" }.join(", ")
# InnoDB status (truncated)
innodb_status = ""
begin
result = connection.exec_query("SHOW ENGINE INNODB STATUS")
innodb_status = result.rows.first&.last.to_s.truncate(3000)
- rescue
+ rescue ActiveRecord::StatementInvalid
+ # InnoDB status may be unavailable depending on MySQL user privileges
end
# Recent slow queries
@@ -259,8 +282,12 @@ def root_cause
if mysql_genius_config.redis_url
redis = Redis.new(url: mysql_genius_config.redis_url)
raw = redis.lrange(SlowQueryMonitor.redis_key, 0, 19)
- slows = raw.map { |e| JSON.parse(e) rescue nil }.compact
- slow_summary = slows.map { |q| "#{q['duration_ms']}ms: #{q['sql'].to_s.truncate(150)}" }.join("\n")
+ slows = raw.map do |e|
+ JSON.parse(e)
+ rescue
+ nil
+ end.compact
+ slow_summary = slows.map { |q| "#{q["duration_ms"]}ms: #{q["sql"].to_s.truncate(150)}" }.join("\n")
end
messages = [
@@ -277,19 +304,20 @@ def root_cause
Respond with JSON: {"diagnosis": "markdown-formatted root cause analysis. Start with a 1-2 sentence summary, then detailed findings. Include specific actionable steps to resolve the issue."}
PROMPT
- { role: "user", content: "PROCESSLIST:\n#{process_info}\n\nKey Status:\n#{key_stats}\n\nInnoDB Status (excerpt):\n#{innodb_status.presence || 'Not available'}\n\nRecent Slow Queries:\n#{slow_summary.presence || 'None captured'}" }
+ { role: "user", content: "PROCESSLIST:\n#{process_info}\n\nKey Status:\n#{key_stats}\n\nInnoDB Status (excerpt):\n#{innodb_status.presence || "Not available"}\n\nRecent Slow Queries:\n#{slow_summary.presence || "None captured"}" },
]
result = AiClient.new.chat(messages: messages)
- render json: result
+ render(json: result)
rescue StandardError => e
- render json: { error: "Root cause analysis failed: #{e.message}" }, status: :unprocessable_entity
+ render(json: { error: "Root cause analysis failed: #{e.message}" }, status: :unprocessable_entity)
end
def migration_risk
return ai_not_configured unless mysql_genius_config.ai_enabled?
+
migration_sql = params[:migration].to_s.strip
- return render json: { error: "Migration SQL or Ruby code is required." }, status: :unprocessable_entity if migration_sql.blank?
+ return render(json: { error: "Migration SQL or Ruby code is required." }, status: :unprocessable_entity) if migration_sql.blank?
connection = ActiveRecord::Base.connection
@@ -299,8 +327,9 @@ def migration_risk
table_info = table_names.uniq.map do |t|
next unless connection.tables.include?(t)
+
row_count = connection.exec_query("SELECT TABLE_ROWS FROM information_schema.tables WHERE table_schema = #{connection.quote(connection.current_database)} AND table_name = #{connection.quote(t)}").rows.first&.first
- indexes = connection.indexes(t).map { |idx| "#{idx.name} (#{idx.columns.join(', ')})" }
+ indexes = connection.indexes(t).map { |idx| "#{idx.name} (#{idx.columns.join(", ")})" }
"Table: #{t} (~#{row_count} rows, #{indexes.size} indexes)"
end.compact.join("\n")
@@ -317,7 +346,8 @@ def migration_risk
SQL
matching = results.rows.select { |r| table_names.any? { |t| r[0].to_s.downcase.include?(t.downcase) } }
active = matching.map { |r| "calls=#{r[1]} avg=#{r[2]}ms: #{r[0].to_s.truncate(200)}" }.join("\n")
- rescue
+ rescue ActiveRecord::StatementInvalid
+ # performance_schema may be unavailable
end
messages = [
@@ -333,19 +363,19 @@ def migration_risk
Respond with JSON: {"risk_level": "low|medium|high|critical", "assessment": "markdown-formatted risk assessment with specific recommendations and estimated lock duration"}
PROMPT
- { role: "user", content: "Migration:\n#{migration_sql}\n\nAffected Tables:\n#{table_info.presence || 'Could not determine'}\n\nActive Queries on These Tables:\n#{active.presence || 'None found or performance_schema unavailable'}" }
+ { role: "user", content: "Migration:\n#{migration_sql}\n\nAffected Tables:\n#{table_info.presence || "Could not determine"}\n\nActive Queries on These Tables:\n#{active.presence || "None found or performance_schema unavailable"}" },
]
result = AiClient.new.chat(messages: messages)
- render json: result
+ render(json: result)
rescue StandardError => e
- render json: { error: "Migration risk assessment failed: #{e.message}" }, status: :unprocessable_entity
+ render(json: { error: "Migration risk assessment failed: #{e.message}" }, status: :unprocessable_entity)
end
private
def ai_not_configured
- render json: { error: "AI features are not configured." }, status: :not_found
+ render(json: { error: "AI features are not configured." }, status: :not_found)
end
def ai_domain_context
@@ -361,7 +391,7 @@ def build_schema_for_query(sql)
tables = SqlValidator.extract_table_references(sql, connection)
tables.map do |t|
cols = connection.columns(t).map { |c| "#{c.name} (#{c.type})" }
- "#{t}: #{cols.join(', ')}"
+ "#{t}: #{cols.join(", ")}"
end.join("\n")
end
end
diff --git a/app/controllers/concerns/mysql_genius/database_analysis.rb b/app/controllers/concerns/mysql_genius/database_analysis.rb
index 1a5f024..8fa6849 100644
--- a/app/controllers/concerns/mysql_genius/database_analysis.rb
+++ b/app/controllers/concerns/mysql_genius/database_analysis.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module MysqlGenius
module DatabaseAnalysis
extend ActiveSupport::Concern
@@ -13,19 +15,20 @@ def duplicate_indexes
indexes.each do |idx|
indexes.each do |other|
next if idx.name == other.name
+
# idx is duplicate if its columns are a left-prefix of other's columns
- if idx.columns.size <= other.columns.size &&
- other.columns.first(idx.columns.size) == idx.columns &&
- !(idx.unique && !other.unique) # don't drop a unique index covered by a non-unique one
- duplicates << {
- table: table,
- duplicate_index: idx.name,
- duplicate_columns: idx.columns,
- covered_by_index: other.name,
- covered_by_columns: other.columns,
- unique: idx.unique
- }
- end
+ next unless idx.columns.size <= other.columns.size &&
+ other.columns.first(idx.columns.size) == idx.columns &&
+ !(idx.unique && !other.unique) # don't drop a unique index covered by a non-unique one
+
+ duplicates << {
+ table: table,
+ duplicate_index: idx.name,
+ duplicate_columns: idx.columns,
+ covered_by_index: other.name,
+ covered_by_columns: other.columns,
+ unique: idx.unique,
+ }
end
end
end
@@ -34,10 +37,15 @@ def duplicate_indexes
seen = Set.new
duplicates = duplicates.reject do |d|
key = [d[:table], [d[:duplicate_index], d[:covered_by_index]].sort].flatten.join(":")
- seen.include?(key) ? true : (seen.add(key); false)
+ if seen.include?(key)
+ true
+ else
+ (seen.add(key)
+ false)
+ end
end
- render json: duplicates
+ render(json: duplicates)
end
def table_sizes
@@ -65,23 +73,25 @@ def table_sizes
data_mb: row["data_mb"].to_f,
index_mb: row["index_mb"].to_f,
total_mb: row["total_mb"].to_f,
- fragmented_mb: row["fragmented_mb"].to_f
+ fragmented_mb: row["fragmented_mb"].to_f,
}
end
- render json: tables
+ render(json: tables)
end
def query_stats
connection = ActiveRecord::Base.connection
- sort = %w[total_time avg_time calls rows_examined].include?(params[:sort]) ? params[:sort] : "total_time"
+ sort = ["total_time", "avg_time", "calls", "rows_examined"].include?(params[:sort]) ? params[:sort] : "total_time"
order_clause = case sort
- when "total_time" then "SUM_TIMER_WAIT DESC"
- when "avg_time" then "AVG_TIMER_WAIT DESC"
- when "calls" then "COUNT_STAR DESC"
- when "rows_examined" then "SUM_ROWS_EXAMINED DESC"
- end
+ when "total_time" then "SUM_TIMER_WAIT DESC"
+ when "avg_time" then "AVG_TIMER_WAIT DESC"
+ when "calls" then "COUNT_STAR DESC"
+ when "rows_examined" then "SUM_ROWS_EXAMINED DESC"
+ end
+
+ limit = params.fetch(:limit, 50).to_i.clamp(1, 50)
results = connection.exec_query(<<~SQL)
SELECT
@@ -101,7 +111,7 @@ def query_stats
AND DIGEST_TEXT IS NOT NULL
AND DIGEST_TEXT NOT LIKE 'EXPLAIN%'
ORDER BY #{order_clause}
- LIMIT 50
+ LIMIT #{limit}
SQL
queries = results.map do |row|
@@ -121,13 +131,13 @@ def query_stats
tmp_disk_tables: (row["tmp_disk_tables"] || row["TMP_DISK_TABLES"] || 0).to_i,
sort_rows: (row["sort_rows"] || row["SORT_ROWS"] || 0).to_i,
first_seen: row["FIRST_SEEN"] || row["first_seen"],
- last_seen: row["LAST_SEEN"] || row["last_seen"]
+ last_seen: row["LAST_SEEN"] || row["last_seen"],
}
end
- render json: queries
+ render(json: queries)
rescue ActiveRecord::StatementInvalid => e
- render json: { error: "Query statistics require performance_schema to be enabled. #{e.message.split(':').last.strip}" }, status: :unprocessable_entity
+ render(json: { error: "Query statistics require performance_schema to be enabled. #{e.message.split(":").last.strip}" }, status: :unprocessable_entity)
end
def unused_indexes
@@ -162,13 +172,13 @@ def unused_indexes
reads: (row["reads"] || row["READS"] || 0).to_i,
writes: (row["writes"] || row["WRITES"] || 0).to_i,
table_rows: (row["table_rows"] || row["TABLE_ROWS"] || 0).to_i,
- drop_sql: "ALTER TABLE `#{table}` DROP INDEX `#{index_name}`;"
+ drop_sql: "ALTER TABLE `#{table}` DROP INDEX `#{index_name}`;",
}
end
- render json: indexes
+ render(json: indexes)
rescue ActiveRecord::StatementInvalid => e
- render json: { error: "Unused index detection requires performance_schema. #{e.message.split(':').last.strip}" }, status: :unprocessable_entity
+ render(json: { error: "Unused index detection requires performance_schema. #{e.message.split(":").last.strip}" }, status: :unprocessable_entity)
end
def server_overview
@@ -215,11 +225,11 @@ def server_overview
questions = status["Questions"].to_i
qps = uptime_seconds > 0 ? (questions.to_f / uptime_seconds).round(1) : 0
- render json: {
+ render(json: {
server: {
version: version,
uptime: "#{days}d #{hours}h #{minutes}m",
- uptime_seconds: uptime_seconds
+ uptime_seconds: uptime_seconds,
},
connections: {
max: max_conn,
@@ -230,7 +240,7 @@ def server_overview
threads_created: status["Threads_created"].to_i,
aborted_connects: status["Aborted_connects"].to_i,
aborted_clients: status["Aborted_clients"].to_i,
- max_used: status["Max_used_connections"].to_i
+ max_used: status["Max_used_connections"].to_i,
},
innodb: {
buffer_pool_mb: buffer_pool_mb,
@@ -239,7 +249,7 @@ def server_overview
buffer_pool_pages_free: status["Innodb_buffer_pool_pages_free"].to_i,
buffer_pool_pages_total: status["Innodb_buffer_pool_pages_total"].to_i,
row_lock_waits: status["Innodb_row_lock_waits"].to_i,
- row_lock_time_ms: (status["Innodb_row_lock_time"].to_f).round(0)
+ row_lock_time_ms: status["Innodb_row_lock_time"].to_f.round(0),
},
queries: {
questions: questions,
@@ -249,11 +259,11 @@ def server_overview
tmp_disk_tables: tmp_disk_tables,
tmp_disk_pct: tmp_disk_pct,
select_full_join: status["Select_full_join"].to_i,
- sort_merge_passes: status["Sort_merge_passes"].to_i
- }
- }
+ sort_merge_passes: status["Sort_merge_passes"].to_i,
+ },
+ })
rescue => e
- render json: { error: "Failed to load server overview: #{e.message}" }, status: :unprocessable_entity
+ render(json: { error: "Failed to load server overview: #{e.message}" }, status: :unprocessable_entity)
end
end
end
diff --git a/app/controllers/concerns/mysql_genius/query_execution.rb b/app/controllers/concerns/mysql_genius/query_execution.rb
index fd20b55..48c9e29 100644
--- a/app/controllers/concerns/mysql_genius/query_execution.rb
+++ b/app/controllers/concerns/mysql_genius/query_execution.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module MysqlGenius
module QueryExecution
extend ActiveSupport::Concern
@@ -5,15 +7,15 @@ module QueryExecution
def execute
sql = params[:sql].to_s.strip
row_limit = if params[:row_limit].present?
- [[params[:row_limit].to_i, 1].max, mysql_genius_config.max_row_limit].min
- else
- mysql_genius_config.default_row_limit
- end
+ params[:row_limit].to_i.clamp(1, mysql_genius_config.max_row_limit)
+ else
+ mysql_genius_config.default_row_limit
+ end
error = validate_sql(sql)
if error
audit(:rejection, sql: sql, reason: error)
- return render json: { error: error }, status: :unprocessable_entity
+ return render(json: { error: error }, status: :unprocessable_entity)
end
limited_sql = apply_row_limit(sql, row_limit)
@@ -35,20 +37,20 @@ def execute
audit(:query, sql: sql, execution_time_ms: execution_time_ms, row_count: rows.length)
- render json: {
+ render(json: {
columns: columns,
rows: rows,
row_count: rows.length,
execution_time_ms: execution_time_ms,
- truncated: truncated
- }
+ truncated: truncated,
+ })
rescue ActiveRecord::StatementInvalid => e
if timeout_error?(e)
audit(:error, sql: sql, error: "Query timeout")
- render json: { error: "Query exceeded the #{mysql_genius_config.query_timeout_ms / 1000} second timeout limit.", timeout: true }, status: :unprocessable_entity
+ render(json: { error: "Query exceeded the #{mysql_genius_config.query_timeout_ms / 1000} second timeout limit.", timeout: true }, status: :unprocessable_entity)
else
audit(:error, sql: sql, error: e.message)
- render json: { error: "Query error: #{e.message.split(':').last.strip}" }, status: :unprocessable_entity
+ render(json: { error: "Query error: #{e.message.split(":").last.strip}" }, status: :unprocessable_entity)
end
end
end
@@ -59,20 +61,20 @@ def explain
unless skip_validation
error = validate_sql(sql)
- return render json: { error: error }, status: :unprocessable_entity if error
+ return render(json: { error: error }, status: :unprocessable_entity) if error
end
# Reject truncated SQL (captured slow queries are capped at 2000 chars)
unless sql.match?(/\)\s*$/) || sql.match?(/\w\s*$/) || sql.match?(/['"`]\s*$/) || sql.match?(/\d\s*$/)
- return render json: { error: "This query appears to be truncated and cannot be explained." }, status: :unprocessable_entity
+ return render(json: { error: "This query appears to be truncated and cannot be explained." }, status: :unprocessable_entity)
end
- explain_sql = "EXPLAIN #{sql.gsub(/;\s*\z/, '')}"
+ explain_sql = "EXPLAIN #{sql.gsub(/;\s*\z/, "")}"
results = ActiveRecord::Base.connection.exec_query(explain_sql)
- render json: { columns: results.columns, rows: results.rows }
+ render(json: { columns: results.columns, rows: results.rows })
rescue ActiveRecord::StatementInvalid => e
- render json: { error: "Explain error: #{e.message.split(':').last.strip}" }, status: :unprocessable_entity
+ render(json: { error: "Explain error: #{e.message.split(":").last.strip}" }, status: :unprocessable_entity)
end
private
@@ -108,7 +110,7 @@ def masked_column?(column_name)
end
def sanitize_ai_sql(sql)
- sql.gsub(/```(?:sql)?\s*/i, "").gsub(/```/, "").strip
+ sql.gsub(/```(?:sql)?\s*/i, "").gsub("```", "").strip
end
def audit(type, **attrs)
diff --git a/app/controllers/mysql_genius/base_controller.rb b/app/controllers/mysql_genius/base_controller.rb
index b4787f2..8d70f67 100644
--- a/app/controllers/mysql_genius/base_controller.rb
+++ b/app/controllers/mysql_genius/base_controller.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module MysqlGenius
class BaseController < MysqlGenius.configuration.base_controller.constantize
layout "mysql_genius/application"
@@ -7,7 +9,7 @@ class BaseController < MysqlGenius.configuration.base_controller.constantize
def authenticate_mysql_genius!
unless MysqlGenius.configuration.authenticate.call(self)
- render plain: "Not authorized", status: :unauthorized
+ render(plain: "Not authorized", status: :unauthorized)
end
end
diff --git a/app/controllers/mysql_genius/queries_controller.rb b/app/controllers/mysql_genius/queries_controller.rb
index 042b17e..b9ef213 100644
--- a/app/controllers/mysql_genius/queries_controller.rb
+++ b/app/controllers/mysql_genius/queries_controller.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module MysqlGenius
class QueriesController < BaseController
include QueryExecution
@@ -6,10 +8,10 @@ class QueriesController < BaseController
def index
@featured_tables = if mysql_genius_config.featured_tables.any?
- mysql_genius_config.featured_tables.sort
- else
- queryable_tables.sort
- end
+ mysql_genius_config.featured_tables.sort
+ else
+ queryable_tables.sort
+ end
@all_tables = queryable_tables.sort
@ai_enabled = mysql_genius_config.ai_enabled?
end
@@ -17,32 +19,37 @@ def index
def columns
table = params[:table]
if mysql_genius_config.blocked_tables.include?(table)
- return render json: { error: "Table '#{table}' is not available for querying." }, status: :forbidden
+ return render(json: { error: "Table '#{table}' is not available for querying." }, status: :forbidden)
end
unless ActiveRecord::Base.connection.tables.include?(table)
- return render json: { error: "Table '#{table}' does not exist." }, status: :not_found
+ return render(json: { error: "Table '#{table}' does not exist." }, status: :not_found)
end
defaults = mysql_genius_config.default_columns[table] || []
cols = ActiveRecord::Base.connection.columns(table).reject { |c| masked_column?(c.name) }.map do |c|
{ name: c.name, type: c.type.to_s, default: defaults.empty? || defaults.include?(c.name) }
end
- render json: cols
+ render(json: cols)
end
def slow_queries
unless mysql_genius_config.redis_url.present?
- return render json: { error: "Slow query monitoring is not configured." }, status: :not_found
+ return render(json: [], status: :ok)
end
+ require "redis"
redis = Redis.new(url: mysql_genius_config.redis_url)
key = SlowQueryMonitor.redis_key
raw = redis.lrange(key, 0, 199)
- queries = raw.map { |entry| JSON.parse(entry) rescue nil }.compact
- render json: queries
- rescue => e
- render json: [], status: :ok
+ queries = raw.map do |entry|
+ JSON.parse(entry)
+ rescue JSON::ParserError
+ nil
+ end.compact
+ render(json: queries)
+ rescue StandardError => e
+ render(json: { error: "Slow query error: #{e.message}" }, status: :unprocessable_entity)
end
private
diff --git a/app/services/mysql_genius/ai_client.rb b/app/services/mysql_genius/ai_client.rb
index be22bf3..8cf7720 100644
--- a/app/services/mysql_genius/ai_client.rb
+++ b/app/services/mysql_genius/ai_client.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
require "net/http"
require "json"
require "uri"
@@ -20,7 +22,7 @@ def chat(messages:, temperature: 0)
body = {
messages: messages,
response_format: { type: "json_object" },
- temperature: temperature
+ temperature: temperature,
}
body[:model] = @config.ai_model if @config.ai_model && !@config.ai_model.empty?
@@ -28,7 +30,7 @@ def chat(messages:, temperature: 0)
parsed = JSON.parse(response.body)
if parsed["error"]
- raise Error, "AI API error: #{parsed['error']['message'] || parsed['error']}"
+ raise Error, "AI API error: #{parsed["error"]["message"] || parsed["error"]}"
end
content = parsed.dig("choices", 0, "message", "content")
@@ -60,6 +62,11 @@ def post_with_redirects(uri, body, redirects = 0)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == "https"
+ if http.use_ssl?
+ http.verify_mode = OpenSSL::SSL::VERIFY_PEER
+ cert_file = ENV["SSL_CERT_FILE"] || OpenSSL::X509::DEFAULT_CERT_FILE
+ http.ca_file = cert_file if File.exist?(cert_file)
+ end
http.open_timeout = 10
http.read_timeout = 60
diff --git a/app/services/mysql_genius/ai_optimization_service.rb b/app/services/mysql_genius/ai_optimization_service.rb
index 9a48eb8..6a1341a 100644
--- a/app/services/mysql_genius/ai_optimization_service.rb
+++ b/app/services/mysql_genius/ai_optimization_service.rb
@@ -1,10 +1,12 @@
+# frozen_string_literal: true
+
module MysqlGenius
class AiOptimizationService
def call(sql, explain_rows, allowed_tables)
schema = build_schema_description(allowed_tables)
messages = [
{ role: "system", content: system_prompt(schema) },
- { role: "user", content: user_prompt(sql, explain_rows) }
+ { role: "user", content: user_prompt(sql, explain_rows) },
]
AiClient.new.chat(messages: messages)
@@ -38,6 +40,7 @@ def user_prompt(sql, explain_rows)
def format_explain(explain_rows)
return explain_rows if explain_rows.is_a?(String)
+
explain_rows.map { |row| row.join(" | ") }.join("\n")
end
@@ -45,10 +48,11 @@ def build_schema_description(allowed_tables)
connection = ActiveRecord::Base.connection
allowed_tables.map do |table|
next unless connection.tables.include?(table)
+
columns = connection.columns(table).map { |c| "#{c.name} (#{c.type})" }
- indexes = connection.indexes(table).map { |idx| "#{idx.name}: [#{idx.columns.join(', ')}]#{idx.unique ? ' UNIQUE' : ''}" }
- desc = "#{table}: #{columns.join(', ')}"
- desc += "\n Indexes: #{indexes.join('; ')}" if indexes.any?
+ indexes = connection.indexes(table).map { |idx| "#{idx.name}: [#{idx.columns.join(", ")}]#{" UNIQUE" if idx.unique}" }
+ desc = "#{table}: #{columns.join(", ")}"
+ desc += "\n Indexes: #{indexes.join("; ")}" if indexes.any?
desc
end.compact.join("\n")
end
diff --git a/app/services/mysql_genius/ai_suggestion_service.rb b/app/services/mysql_genius/ai_suggestion_service.rb
index 51bb581..38aad0c 100644
--- a/app/services/mysql_genius/ai_suggestion_service.rb
+++ b/app/services/mysql_genius/ai_suggestion_service.rb
@@ -1,10 +1,12 @@
+# frozen_string_literal: true
+
module MysqlGenius
class AiSuggestionService
def call(user_prompt, allowed_tables)
schema = build_schema_description(allowed_tables)
messages = [
{ role: "system", content: system_prompt(schema) },
- { role: "user", content: user_prompt }
+ { role: "user", content: user_prompt },
]
AiClient.new.chat(messages: messages)
@@ -48,8 +50,9 @@ def build_schema_description(allowed_tables)
connection = ActiveRecord::Base.connection
allowed_tables.map do |table|
next unless connection.tables.include?(table)
+
columns = connection.columns(table).map { |c| "#{c.name} (#{c.type})" }
- "#{table}: #{columns.join(', ')}"
+ "#{table}: #{columns.join(", ")}"
end.compact.join("\n")
end
end
diff --git a/app/views/mysql_genius/queries/_tab_dashboard.html.erb b/app/views/mysql_genius/queries/_tab_dashboard.html.erb
new file mode 100644
index 0000000..1c86c1c
--- /dev/null
+++ b/app/views/mysql_genius/queries/_tab_dashboard.html.erb
@@ -0,0 +1,95 @@
+
+
+
Loading dashboard...
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Query Calls Total Time Avg Time
+
+
+
+
+
+
+
+
+
+
+
--
+
Duplicate Indexes
+
+
+
+
+
+
+
diff --git a/app/views/mysql_genius/queries/_tab_duplicate_indexes.html.erb b/app/views/mysql_genius/queries/_tab_duplicate_indexes.html.erb
index 4d447aa..71245a5 100644
--- a/app/views/mysql_genius/queries/_tab_duplicate_indexes.html.erb
+++ b/app/views/mysql_genius/queries/_tab_duplicate_indexes.html.erb
@@ -21,4 +21,15 @@
+
diff --git a/app/views/mysql_genius/queries/_tab_query_explorer.html.erb b/app/views/mysql_genius/queries/_tab_query_explorer.html.erb
new file mode 100644
index 0000000..bdba576
--- /dev/null
+++ b/app/views/mysql_genius/queries/_tab_query_explorer.html.erb
@@ -0,0 +1,110 @@
+
+
+
+ Visual Builder
+ SQL Editor
+
+
+
+
+
+
+ Table
+
+ -- Select a table --
+ <% if @featured_tables != @all_tables %>
+
+ <% @featured_tables.each do |table| %>
+ <%= table %>
+ <% end %>
+
+
+ <% (@all_tables - @featured_tables).each do |table| %>
+ <%= table %>
+ <% end %>
+
+ <% else %>
+ <% @all_tables.each do |table| %>
+ <%= table %>
+ <% end %>
+ <% end %>
+
+
+
+ Row Limit
+
+
+
+
+ ▶ Run Query
+ 🔎 Explain
+
+
+
+
+
Columns
+ Toggle All
+ Reset Defaults
+
+
+
+
+
+
Filters
+
+
+ Add Filter
+
+
+
+
Order By
+
+
+ Add Sort
+
+
+
+ Generated SQL
+
+
+
+
+
+
+ <% if @ai_enabled %>
+
+
+
+
+
+
Only table names and column names are sent to the AI. No row data leaves the system.
+
+
⚡ Suggest Query
+
+
+
+ <% end %>
+
+
+ SQL Query
+
+
+
+
+ Row Limit
+
+
+
+
+ ▶ Run Query
+ 🔎 Explain
+ <% if @ai_enabled %>
+ ⚡ Describe
+ ⚡ Rewrite
+ <% end %>
+
+
+
+
diff --git a/app/views/mysql_genius/queries/_tab_sql_query.html.erb b/app/views/mysql_genius/queries/_tab_sql_query.html.erb
deleted file mode 100644
index a3f4266..0000000
--- a/app/views/mysql_genius/queries/_tab_sql_query.html.erb
+++ /dev/null
@@ -1,40 +0,0 @@
-
-
- <% if @ai_enabled %>
-
-
-
-
-
-
Only table names and column names are sent to the AI. No row data leaves the system.
-
-
⚡ Suggest Query
-
-
-
- <% end %>
-
-
- SQL Query
-
-
-
-
- Row Limit
-
-
-
-
- ▶ Run Query
- 🔎 Explain
- <% if @ai_enabled %>
- ⚡ Describe
- ⚡ Rewrite
- <% end %>
-
-
-
diff --git a/app/views/mysql_genius/queries/_tab_unused_indexes.html.erb b/app/views/mysql_genius/queries/_tab_unused_indexes.html.erb
index 2523331..9358a18 100644
--- a/app/views/mysql_genius/queries/_tab_unused_indexes.html.erb
+++ b/app/views/mysql_genius/queries/_tab_unused_indexes.html.erb
@@ -22,4 +22,15 @@
+
diff --git a/app/views/mysql_genius/queries/_tab_visual_builder.html.erb b/app/views/mysql_genius/queries/_tab_visual_builder.html.erb
deleted file mode 100644
index 1af4d91..0000000
--- a/app/views/mysql_genius/queries/_tab_visual_builder.html.erb
+++ /dev/null
@@ -1,61 +0,0 @@
-
-
-
-
- Table
-
- -- Select a table --
- <% if @featured_tables != @all_tables %>
-
- <% @featured_tables.each do |table| %>
- <%= table %>
- <% end %>
-
-
- <% (@all_tables - @featured_tables).each do |table| %>
- <%= table %>
- <% end %>
-
- <% else %>
- <% @all_tables.each do |table| %>
- <%= table %>
- <% end %>
- <% end %>
-
-
-
- Row Limit
-
-
-
-
- ▶ Run Query
- 🔎 Explain
-
-
-
-
-
Columns
- Toggle All
- Reset Defaults
-
-
-
-
-
-
Filters
-
-
+ Add Filter
-
-
-
-
Order By
-
-
+ Add Sort
-
-
-
- Generated SQL
-
-
-
diff --git a/app/views/mysql_genius/queries/index.html.erb b/app/views/mysql_genius/queries/index.html.erb
index 1be778d..3709037 100644
--- a/app/views/mysql_genius/queries/index.html.erb
+++ b/app/views/mysql_genius/queries/index.html.erb
@@ -1,27 +1,27 @@
🐘 MySQLGenius
- Visual Builder
- SQL Query
+ Dashboard
Slow Queries
- Duplicate Indexes
- Table Sizes
Query Stats
- Unused Indexes
Server
+ Table Sizes
+ Unused Indexes
+ Duplicate Indexes
+ Query Explorer
<% if @ai_enabled %>
AI Tools
<% end %>
-<%= render "mysql_genius/queries/tab_visual_builder" %>
-<%= render "mysql_genius/queries/tab_sql_query" %>
+<%= render "mysql_genius/queries/tab_dashboard" %>
<%= render "mysql_genius/queries/tab_slow_queries" %>
-<%= render "mysql_genius/queries/tab_duplicate_indexes" %>
-<%= render "mysql_genius/queries/tab_table_sizes" %>
<%= render "mysql_genius/queries/tab_query_stats" %>
-<%= render "mysql_genius/queries/tab_unused_indexes" %>
<%= render "mysql_genius/queries/tab_server" %>
+<%= render "mysql_genius/queries/tab_table_sizes" %>
+<%= render "mysql_genius/queries/tab_unused_indexes" %>
+<%= render "mysql_genius/queries/tab_duplicate_indexes" %>
+<%= render "mysql_genius/queries/tab_query_explorer" %>
<% if @ai_enabled %>
<%= render "mysql_genius/queries/tab_ai_tools" %>
<% end %>
@@ -53,6 +53,8 @@
migration_risk: '<%= mysql_genius.migration_risk_path %>'
};
+ var RAILS_MIGRATION_VERSION = '<%= Rails::VERSION::MAJOR %>.<%= Rails::VERSION::MINOR %>';
+
var csrfMeta = document.querySelector('meta[name="csrf-token"]');
var csrfToken = csrfMeta ? csrfMeta.getAttribute('content') : '';
var currentColumns = [];
@@ -69,6 +71,36 @@
function hide(e) { e.classList.add('mg-hidden'); }
function escHtml(s) { var d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
+ function migrationTimestamp() {
+ var now = new Date();
+ return now.getFullYear().toString() +
+ ('0' + (now.getMonth() + 1)).slice(-2) +
+ ('0' + now.getDate()).slice(-2) +
+ ('0' + now.getHours()).slice(-2) +
+ ('0' + now.getMinutes()).slice(-2) +
+ ('0' + now.getSeconds()).slice(-2);
+ }
+
+ function copyToClipboard(text, btn) {
+ var done = function() {
+ btn.innerHTML = '✓ Copied';
+ setTimeout(function() { btn.innerHTML = '📋 Copy'; }, 2000);
+ };
+ if (navigator.clipboard && navigator.clipboard.writeText) {
+ navigator.clipboard.writeText(text).then(done);
+ } else {
+ var ta = document.createElement('textarea');
+ ta.value = text;
+ ta.style.position = 'fixed';
+ ta.style.opacity = '0';
+ document.body.appendChild(ta);
+ ta.select();
+ document.execCommand('copy');
+ document.body.removeChild(ta);
+ done();
+ }
+ }
+
function ajax(method, url, data, onSuccess, onError) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
@@ -123,6 +155,7 @@
qsa('.mg-tab-content').forEach(function(c) { c.classList.remove('active'); });
tab.classList.add('active');
el('tab-' + tab.dataset.tab).classList.add('active');
+ if (tab.dataset.tab === 'dashboard') loadDashboard();
if (tab.dataset.tab === 'slow') loadSlowQueries();
if (tab.dataset.tab === 'indexes') loadDuplicateIndexes();
if (tab.dataset.tab === 'sizes') loadTableSizes();
@@ -132,6 +165,185 @@
});
});
+ // --- Dashboard ---
+
+ function loadDashboard() {
+ show(el('dash-loading'));
+ hide(el('dash-content')); hide(el('dash-error'));
+ // Reset previous data
+ hide(el('dash-slow-table')); hide(el('dash-slow-empty'));
+ hide(el('dash-qstats-table')); hide(el('dash-qstats-empty')); hide(el('dash-qstats-error'));
+ el('dash-slow-tbody').innerHTML = '';
+ el('dash-qstats-tbody').innerHTML = '';
+ el('dash-dup-count').textContent = '--';
+ el('dash-unused-count').textContent = '--';
+
+ var loaded = { server: false, slow: false, qstats: false, dup: false, unused: false };
+
+ function checkAllLoaded() {
+ if (!loaded.server || !loaded.slow || !loaded.qstats || !loaded.dup || !loaded.unused) return;
+ hide(el('dash-loading'));
+ show(el('dash-content'));
+ }
+
+ // Server overview
+ ajaxGet(ROUTES.server_overview, {}, function(data) {
+ if (data.error) { loaded.server = true; checkAllLoaded(); return; }
+ var s = data.server;
+ var c = data.connections;
+ var db = data.innodb;
+ var q = data.queries;
+
+ el('dash-server-info').innerHTML =
+ statRow('Version', '' + escHtml(s.version) + '') +
+ statRow('Uptime', escHtml(s.uptime)) +
+ statRow('Queries/sec', q.qps);
+
+ el('dash-conn-bar').innerHTML = usageBar(c.usage_pct, c.current + ' / ' + c.max + ' (' + c.usage_pct + '%)');
+ el('dash-conn-info').innerHTML =
+ statRow('Threads Running', c.threads_running) +
+ statRow('Max Used', c.max_used);
+
+ var poolUsedPct = db.buffer_pool_pages_total > 0
+ ? (((db.buffer_pool_pages_total - db.buffer_pool_pages_free) / db.buffer_pool_pages_total) * 100).toFixed(1)
+ : 0;
+ el('dash-innodb-bar').innerHTML = usageBar(parseFloat(poolUsedPct), db.buffer_pool_mb + ' MB (' + poolUsedPct + '% used)');
+ el('dash-innodb-info').innerHTML =
+ statRow('Hit Rate', db.buffer_pool_hit_rate + '%') +
+ statRow('Dirty Pages', Number(db.buffer_pool_pages_dirty).toLocaleString());
+
+ var tmpBadge = q.tmp_disk_pct > 25
+ ? '' + q.tmp_disk_pct + '% '
+ : q.tmp_disk_pct + '%';
+ el('dash-query-info').innerHTML =
+ statRow('Slow Queries', Number(q.slow_queries).toLocaleString()) +
+ statRow('Tmp Disk Tables', tmpBadge);
+
+ loaded.server = true;
+ checkAllLoaded();
+ }, function() { loaded.server = true; checkAllLoaded(); });
+
+ // Top 5 slow queries
+ ajaxGet(ROUTES.slow_queries, {}, function(data) {
+ if (!data || !data.length) {
+ el('dash-slow-empty').textContent = 'No slow queries recorded.';
+ show(el('dash-slow-empty'));
+ } else {
+ var top5 = data.slice(0, 5);
+ el('dash-slow-tbody').innerHTML = top5.map(function(q) {
+ var d = q.duration_ms;
+ var cls = d >= 2000 ? 'mg-badge-danger' : d >= 1000 ? 'mg-badge-warning' : 'mg-badge-info';
+ var sqlShort = escHtml(q.sql).length > 120 ? escHtml(q.sql).substring(0, 120) + '...' : escHtml(q.sql);
+ return '' + d + ' ms ' +
+ '' + escHtml(q.timestamp) + ' ' +
+ '' + sqlShort + ' ';
+ }).join('');
+ show(el('dash-slow-table'));
+ }
+ loaded.slow = true;
+ checkAllLoaded();
+ }, function() {
+ el('dash-slow-empty').textContent = 'Configure redis_url to monitor slow queries.';
+ show(el('dash-slow-empty'));
+ loaded.slow = true;
+ checkAllLoaded();
+ });
+
+ // Top 5 expensive queries
+ ajaxGet(ROUTES.query_stats, { sort: 'total_time', limit: 5 }, function(data) {
+ if (data.error) {
+ el('dash-qstats-error').innerHTML = '' + escHtml(data.error) + '
';
+ show(el('dash-qstats-error'));
+ } else if (!data.length) {
+ el('dash-qstats-empty').textContent = 'No query statistics available.';
+ show(el('dash-qstats-empty'));
+ } else {
+ el('dash-qstats-tbody').innerHTML = data.map(function(q) {
+ var sqlShort = q.sql.length > 120 ? q.sql.substring(0, 120) + '...' : q.sql;
+ return '' +
+ '' + escHtml(sqlShort) + ' ' +
+ '' + Number(q.calls).toLocaleString() + ' ' +
+ '' + formatDuration(q.total_time_ms) + ' ' +
+ '' + formatDuration(q.avg_time_ms) + ' ';
+ }).join('');
+ show(el('dash-qstats-table'));
+ }
+ loaded.qstats = true;
+ checkAllLoaded();
+ }, function() {
+ el('dash-qstats-empty').textContent = 'Query statistics unavailable.';
+ show(el('dash-qstats-empty'));
+ loaded.qstats = true;
+ checkAllLoaded();
+ });
+
+ // Duplicate indexes count
+ ajaxGet(ROUTES.duplicate_indexes, {}, function(data) {
+ var count = Array.isArray(data) ? data.length : 0;
+ var countEl = el('dash-dup-count');
+ if (count === 0) {
+ countEl.innerHTML = '✓ 0 ';
+ } else {
+ countEl.innerHTML = '' + count + ' ';
+ }
+ loaded.dup = true;
+ checkAllLoaded();
+ }, function() { el('dash-dup-count').textContent = '?'; loaded.dup = true; checkAllLoaded(); });
+
+ // Unused indexes count
+ ajaxGet(ROUTES.unused_indexes, {}, function(data) {
+ var count = Array.isArray(data) ? data.length : 0;
+ var countEl = el('dash-unused-count');
+ if (count === 0) {
+ countEl.innerHTML = '✓ 0 ';
+ } else {
+ countEl.innerHTML = '' + count + ' ';
+ }
+ loaded.unused = true;
+ checkAllLoaded();
+ }, function() { el('dash-unused-count').textContent = '?'; loaded.unused = true; checkAllLoaded(); });
+ }
+
+ // Dashboard tab-jump buttons
+ document.addEventListener('click', function(e) {
+ var jumpBtn = e.target.closest('.dash-jump-tab');
+ if (jumpBtn) {
+ var target = jumpBtn.dataset.target;
+ qsa('.mg-tab').forEach(function(t) { t.classList.remove('active'); });
+ qsa('.mg-tab-content').forEach(function(c) { c.classList.remove('active'); });
+ qs('[data-tab="' + target + '"]').classList.add('active');
+ el('tab-' + target).classList.add('active');
+ if (target === 'slow') loadSlowQueries();
+ if (target === 'indexes') loadDuplicateIndexes();
+ if (target === 'qstats') loadQueryStats();
+ if (target === 'unused') loadUnusedIndexes();
+ if (target === 'server') loadServerOverview();
+ }
+ });
+
+ // Load dashboard on page load
+ loadDashboard();
+
+ // --- Query Explorer Mode Toggle ---
+
+ qsa('.qe-mode').forEach(function(btn) {
+ btn.addEventListener('click', function() {
+ qsa('.qe-mode').forEach(function(b) {
+ b.classList.remove('active');
+ b.classList.add('mg-btn-outline');
+ });
+ btn.classList.add('active');
+ btn.classList.remove('mg-btn-outline');
+ if (btn.dataset.mode === 'visual') {
+ show(el('qe-visual'));
+ hide(el('qe-sql'));
+ } else {
+ hide(el('qe-visual'));
+ show(el('qe-sql'));
+ }
+ });
+ });
+
// --- Visual Builder ---
var typeLabels = { string: 'text', text: 'text', integer: 'number', boolean: 'yes/no', date: 'date', datetime: 'date/time', decimal: 'decimal', float: 'decimal' };
@@ -524,8 +736,14 @@
el('sql-input').value = useBtn.dataset.sql;
qsa('.mg-tab').forEach(function(t) { t.classList.remove('active'); });
qsa('.mg-tab-content').forEach(function(c) { c.classList.remove('active'); });
- qs('[data-tab="sql"]').classList.add('active');
- el('tab-sql').classList.add('active');
+ qs('[data-tab="explorer"]').classList.add('active');
+ el('tab-explorer').classList.add('active');
+ // Switch to SQL mode within Query Explorer
+ qsa('.qe-mode').forEach(function(b) { b.classList.remove('active'); b.classList.add('mg-btn-outline'); });
+ qs('.qe-mode[data-mode="sql"]').classList.add('active');
+ qs('.qe-mode[data-mode="sql"]').classList.remove('mg-btn-outline');
+ hide(el('qe-visual'));
+ show(el('qe-sql'));
}
});
@@ -552,6 +770,17 @@
'';
}).join('');
show(el('dup-table-wrapper'));
+
+ // Generate migration
+ var ts = migrationTimestamp();
+ var migrationLines = ['# ' + ts + '_remove_duplicate_indexes.rb', '',
+ 'class RemoveDuplicateIndexes < ActiveRecord::Migration[' + RAILS_MIGRATION_VERSION + ']', ' def change'];
+ data.forEach(function(d) {
+ migrationLines.push(' remove_index :' + d.table + ', name: :' + d.duplicate_index);
+ });
+ migrationLines.push(' end', 'end');
+ el('dup-migration-code').textContent = migrationLines.join('\n');
+ show(el('dup-migration'));
}, function() {
hide(el('dup-loading'));
el('dup-empty').textContent = 'Failed to scan indexes.';
@@ -560,6 +789,9 @@
}
el('dup-refresh').addEventListener('click', loadDuplicateIndexes);
+ el('dup-copy-migration').addEventListener('click', function() {
+ copyToClipboard(el('dup-migration-code').textContent, el('dup-copy-migration'));
+ });
// --- Table Sizes ---
@@ -734,6 +966,17 @@
'';
}).join('');
show(el('unused-table-wrapper'));
+
+ // Generate migration
+ var ts = migrationTimestamp();
+ var migrationLines = ['# ' + ts + '_remove_unused_indexes.rb', '',
+ 'class RemoveUnusedIndexes < ActiveRecord::Migration[' + RAILS_MIGRATION_VERSION + ']', ' def change'];
+ data.forEach(function(d) {
+ migrationLines.push(' remove_index :' + d.table + ', name: :' + d.index_name);
+ });
+ migrationLines.push(' end', 'end');
+ el('unused-migration-code').textContent = migrationLines.join('\n');
+ show(el('unused-migration'));
}, function(json) {
hide(el('unused-loading'));
el('unused-error').innerHTML = '' + escHtml((json && json.error) || 'Failed to load unused indexes.') + '
';
@@ -742,6 +985,9 @@
}
el('unused-refresh').addEventListener('click', loadUnusedIndexes);
+ el('unused-copy-migration').addEventListener('click', function() {
+ copyToClipboard(el('unused-migration-code').textContent, el('unused-copy-migration'));
+ });
// --- Server Overview ---
diff --git a/bin/console b/bin/console
index 1ed4168..78b7363 100755
--- a/bin/console
+++ b/bin/console
@@ -1,4 +1,5 @@
#!/usr/bin/env ruby
+# frozen_string_literal: true
require "bundler/setup"
require "mysql_genius"
diff --git a/config/routes.rb b/config/routes.rb
index 754d4c1..358fd01 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
MysqlGenius::Engine.routes.draw do
root to: "queries#index"
diff --git a/docs/screenshots/dashboard.png b/docs/screenshots/dashboard.png
new file mode 100644
index 0000000..c3d9469
Binary files /dev/null and b/docs/screenshots/dashboard.png differ
diff --git a/docs/screenshots/query_explore.png b/docs/screenshots/query_explore.png
new file mode 100644
index 0000000..4132833
Binary files /dev/null and b/docs/screenshots/query_explore.png differ
diff --git a/docs/screenshots/sql_query.png b/docs/screenshots/sql_query.png
deleted file mode 100644
index 9d31ab7..0000000
Binary files a/docs/screenshots/sql_query.png and /dev/null differ
diff --git a/docs/screenshots/visual_builder.png b/docs/screenshots/visual_builder.png
deleted file mode 100644
index e00fd72..0000000
Binary files a/docs/screenshots/visual_builder.png and /dev/null differ
diff --git a/docs/superpowers/plans/2026-04-08-dashboard-first-redesign.md b/docs/superpowers/plans/2026-04-08-dashboard-first-redesign.md
new file mode 100644
index 0000000..7823f21
--- /dev/null
+++ b/docs/superpowers/plans/2026-04-08-dashboard-first-redesign.md
@@ -0,0 +1,741 @@
+# Dashboard-First Redesign Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Make the default landing page a PgHero-style monitoring dashboard instead of a query builder, reorder tabs to lead with monitoring, and merge Visual Builder + SQL Query into one "Query Explorer" tab.
+
+**Architecture:** The dashboard tab is a new partial that reuses all existing AJAX endpoints (server_overview, slow_queries, query_stats, duplicate_indexes, unused_indexes) with no new routes. The query explorer merges two existing partials into one with a mode toggle. The only backend change is adding a `limit` param to the `query_stats` action.
+
+**Tech Stack:** Rails ERB partials, vanilla JavaScript (matching existing patterns), existing CSS utility classes.
+
+---
+
+## File Structure
+
+| File | Action | Responsibility |
+|------|--------|---------------|
+| `app/controllers/concerns/mysql_genius/database_analysis.rb` | Modify | Add `limit` param to `query_stats` |
+| `app/views/mysql_genius/queries/_tab_dashboard.html.erb` | Create | Dashboard HTML structure |
+| `app/views/mysql_genius/queries/_tab_query_explorer.html.erb` | Create | Merged visual builder + SQL query with mode toggle |
+| `app/views/mysql_genius/queries/index.html.erb` | Modify | Tab bar reorder, partial renders, JS for dashboard + query explorer |
+| `app/views/mysql_genius/queries/_tab_visual_builder.html.erb` | Delete | Content moved to query explorer |
+| `app/views/mysql_genius/queries/_tab_sql_query.html.erb` | Delete | Content moved to query explorer |
+| `mysql_genius.gemspec` | Modify | Update description |
+| `README.md` | Modify | Update usage section and screenshot order |
+
+---
+
+### Task 1: Add `limit` param to `query_stats` action
+
+**Files:**
+- Modify: `app/controllers/concerns/mysql_genius/database_analysis.rb:112`
+
+- [ ] **Step 1: Add limit param support**
+
+In `app/controllers/concerns/mysql_genius/database_analysis.rb`, change the hardcoded `LIMIT 50` to use a param with a cap:
+
+```ruby
+ limit = [params.fetch(:limit, 50).to_i, 50].min
+
+ results = connection.exec_query(<<~SQL)
+ SELECT
+ DIGEST_TEXT,
+ COUNT_STAR AS calls,
+ ROUND(SUM_TIMER_WAIT / 1000000000, 1) AS total_time_ms,
+ ROUND(AVG_TIMER_WAIT / 1000000000, 1) AS avg_time_ms,
+ ROUND(MAX_TIMER_WAIT / 1000000000, 1) AS max_time_ms,
+ SUM_ROWS_EXAMINED AS rows_examined,
+ SUM_ROWS_SENT AS rows_sent,
+ SUM_CREATED_TMP_DISK_TABLES AS tmp_disk_tables,
+ SUM_SORT_ROWS AS sort_rows,
+ FIRST_SEEN,
+ LAST_SEEN
+ FROM performance_schema.events_statements_summary_by_digest
+ WHERE SCHEMA_NAME = #{connection.quote(connection.current_database)}
+ AND DIGEST_TEXT IS NOT NULL
+ AND DIGEST_TEXT NOT LIKE 'EXPLAIN%'
+ ORDER BY #{order_clause}
+ LIMIT #{limit}
+ SQL
+```
+
+The key change: replace `LIMIT 50` (line 112) with `LIMIT #{limit}` and add the `limit` local variable before the query. The `[..., 50].min` cap ensures the dashboard's `limit=5` works while the full Query Stats tab still gets up to 50.
+
+- [ ] **Step 2: Run RuboCop to verify**
+
+Run: `bundle exec rubocop app/controllers/concerns/mysql_genius/database_analysis.rb`
+Expected: no offenses
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add app/controllers/concerns/mysql_genius/database_analysis.rb
+git commit -m "Add limit param to query_stats action for dashboard use"
+```
+
+---
+
+### Task 2: Create the Dashboard tab partial
+
+**Files:**
+- Create: `app/views/mysql_genius/queries/_tab_dashboard.html.erb`
+
+- [ ] **Step 1: Create the dashboard partial**
+
+Create `app/views/mysql_genius/queries/_tab_dashboard.html.erb` with this content:
+
+```erb
+
+
+
Loading dashboard...
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Query Calls Total Time Avg Time
+
+
+
+
+
+
+
+
+
+
+
--
+
Duplicate Indexes
+
+
+
+
+
+
+
+```
+
+- [ ] **Step 2: Verify file renders valid HTML**
+
+Run: `ruby -e "puts File.read('app/views/mysql_genius/queries/_tab_dashboard.html.erb').length"` from project root.
+Expected: prints a number (file exists and is readable)
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add app/views/mysql_genius/queries/_tab_dashboard.html.erb
+git commit -m "Add dashboard tab partial with server summary, top queries, and index alerts"
+```
+
+---
+
+### Task 3: Create the Query Explorer tab partial
+
+**Files:**
+- Create: `app/views/mysql_genius/queries/_tab_query_explorer.html.erb`
+
+- [ ] **Step 1: Create the query explorer partial**
+
+Create `app/views/mysql_genius/queries/_tab_query_explorer.html.erb`. This combines the content from `_tab_visual_builder.html.erb` and `_tab_sql_query.html.erb` with a mode toggle. The visual builder content keeps its existing `id="tab-visual"` inner div (now `id="qe-visual"`) and the SQL content keeps `id="tab-sql"` inner div (now `id="qe-sql"`) so existing JS references work after updating.
+
+```erb
+
+
+
+ Visual Builder
+ SQL Editor
+
+
+
+
+
+
+ Table
+
+ -- Select a table --
+ <% if @featured_tables != @all_tables %>
+
+ <% @featured_tables.each do |table| %>
+ <%= table %>
+ <% end %>
+
+
+ <% (@all_tables - @featured_tables).each do |table| %>
+ <%= table %>
+ <% end %>
+
+ <% else %>
+ <% @all_tables.each do |table| %>
+ <%= table %>
+ <% end %>
+ <% end %>
+
+
+
+ Row Limit
+
+
+
+
+ ▶ Run Query
+ 🔎 Explain
+
+
+
+
+
Columns
+ Toggle All
+ Reset Defaults
+
+
+
+
+
+
Filters
+
+
+ Add Filter
+
+
+
+
Order By
+
+
+ Add Sort
+
+
+
+ Generated SQL
+
+
+
+
+
+
+ <% if @ai_enabled %>
+
+
+
+
+
+
Only table names and column names are sent to the AI. No row data leaves the system.
+
+
⚡ Suggest Query
+
+
+
+ <% end %>
+
+
+ SQL Query
+
+
+
+
+ Row Limit
+
+
+
+
+ ▶ Run Query
+ 🔎 Explain
+ <% if @ai_enabled %>
+ ⚡ Describe
+ ⚡ Rewrite
+ <% end %>
+
+
+
+
+```
+
+- [ ] **Step 2: Commit**
+
+```bash
+git add app/views/mysql_genius/queries/_tab_query_explorer.html.erb
+git commit -m "Add query explorer partial merging visual builder and SQL editor"
+```
+
+---
+
+### Task 4: Update index.html.erb — tab bar and partials
+
+**Files:**
+- Modify: `app/views/mysql_genius/queries/index.html.erb:1-29`
+- Delete: `app/views/mysql_genius/queries/_tab_visual_builder.html.erb`
+- Delete: `app/views/mysql_genius/queries/_tab_sql_query.html.erb`
+
+- [ ] **Step 1: Replace the tab bar and partial renders**
+
+Replace lines 1-29 of `app/views/mysql_genius/queries/index.html.erb` (the header, tab buttons, and partial renders) with:
+
+```erb
+🐘 MySQLGenius
+
+
+ Dashboard
+ Slow Queries
+ Query Stats
+ Server
+ Table Sizes
+ Unused Indexes
+ Duplicate Indexes
+ Query Explorer
+ <% if @ai_enabled %>
+ AI Tools
+ <% end %>
+
+
+<%= render "mysql_genius/queries/tab_dashboard" %>
+<%= render "mysql_genius/queries/tab_slow_queries" %>
+<%= render "mysql_genius/queries/tab_query_stats" %>
+<%= render "mysql_genius/queries/tab_server" %>
+<%= render "mysql_genius/queries/tab_table_sizes" %>
+<%= render "mysql_genius/queries/tab_unused_indexes" %>
+<%= render "mysql_genius/queries/tab_duplicate_indexes" %>
+<%= render "mysql_genius/queries/tab_query_explorer" %>
+<% if @ai_enabled %>
+ <%= render "mysql_genius/queries/tab_ai_tools" %>
+<% end %>
+
+<%= render "mysql_genius/queries/shared_results" %>
+```
+
+- [ ] **Step 2: Delete the old partials**
+
+```bash
+rm app/views/mysql_genius/queries/_tab_visual_builder.html.erb
+rm app/views/mysql_genius/queries/_tab_sql_query.html.erb
+```
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add app/views/mysql_genius/queries/index.html.erb
+git add app/views/mysql_genius/queries/_tab_visual_builder.html.erb
+git add app/views/mysql_genius/queries/_tab_sql_query.html.erb
+git commit -m "Reorder tabs to lead with dashboard, remove old visual builder and SQL partials"
+```
+
+---
+
+### Task 5: Update JavaScript — tab switching, dashboard loader, query explorer toggle
+
+**Files:**
+- Modify: `app/views/mysql_genius/queries/index.html.erb` (JS section)
+
+- [ ] **Step 1: Update the tab click handler**
+
+Replace the tab click handler (lines 120-133) with:
+
+```javascript
+ qsa('.mg-tab').forEach(function(tab) {
+ tab.addEventListener('click', function() {
+ qsa('.mg-tab').forEach(function(t) { t.classList.remove('active'); });
+ qsa('.mg-tab-content').forEach(function(c) { c.classList.remove('active'); });
+ tab.classList.add('active');
+ el('tab-' + tab.dataset.tab).classList.add('active');
+ if (tab.dataset.tab === 'dashboard') loadDashboard();
+ if (tab.dataset.tab === 'slow') loadSlowQueries();
+ if (tab.dataset.tab === 'indexes') loadDuplicateIndexes();
+ if (tab.dataset.tab === 'sizes') loadTableSizes();
+ if (tab.dataset.tab === 'qstats') loadQueryStats();
+ if (tab.dataset.tab === 'unused') loadUnusedIndexes();
+ if (tab.dataset.tab === 'server') loadServerOverview();
+ });
+ });
+```
+
+- [ ] **Step 2: Add the `loadDashboard` function**
+
+Insert this function before the `// --- Visual Builder ---` comment (around line 135). This function fires 4 parallel AJAX calls and populates the dashboard sections:
+
+```javascript
+ // --- Dashboard ---
+
+ function loadDashboard() {
+ show(el('dash-loading'));
+ hide(el('dash-content')); hide(el('dash-error'));
+
+ var loaded = { server: false, slow: false, qstats: false, dup: false, unused: false };
+
+ function checkAllLoaded() {
+ if (!loaded.server || !loaded.slow || !loaded.qstats || !loaded.dup || !loaded.unused) return;
+ hide(el('dash-loading'));
+ show(el('dash-content'));
+ }
+
+ // Server overview
+ ajaxGet(ROUTES.server_overview, {}, function(data) {
+ if (data.error) { loaded.server = true; checkAllLoaded(); return; }
+ var s = data.server;
+ var c = data.connections;
+ var db = data.innodb;
+ var q = data.queries;
+
+ el('dash-server-info').innerHTML =
+ statRow('Version', '' + escHtml(s.version) + '') +
+ statRow('Uptime', escHtml(s.uptime)) +
+ statRow('Queries/sec', q.qps);
+
+ el('dash-conn-bar').innerHTML = usageBar(c.usage_pct, c.current + ' / ' + c.max + ' (' + c.usage_pct + '%)');
+ el('dash-conn-info').innerHTML =
+ statRow('Threads Running', c.threads_running) +
+ statRow('Max Used', c.max_used);
+
+ var poolUsedPct = db.buffer_pool_pages_total > 0
+ ? (((db.buffer_pool_pages_total - db.buffer_pool_pages_free) / db.buffer_pool_pages_total) * 100).toFixed(1)
+ : 0;
+ el('dash-innodb-bar').innerHTML = usageBar(parseFloat(poolUsedPct), db.buffer_pool_mb + ' MB (' + poolUsedPct + '% used)');
+ el('dash-innodb-info').innerHTML =
+ statRow('Hit Rate', db.buffer_pool_hit_rate + '%') +
+ statRow('Dirty Pages', Number(db.buffer_pool_pages_dirty).toLocaleString());
+
+ var tmpBadge = q.tmp_disk_pct > 25
+ ? '' + q.tmp_disk_pct + '% '
+ : q.tmp_disk_pct + '%';
+ el('dash-query-info').innerHTML =
+ statRow('Slow Queries', Number(q.slow_queries).toLocaleString()) +
+ statRow('Tmp Disk Tables', tmpBadge);
+
+ loaded.server = true;
+ checkAllLoaded();
+ }, function() { loaded.server = true; checkAllLoaded(); });
+
+ // Top 5 slow queries
+ ajaxGet(ROUTES.slow_queries, {}, function(data) {
+ if (!data || !data.length) {
+ el('dash-slow-empty').textContent = '<%= MysqlGenius.configuration.redis_url ? "No slow queries recorded." : "Configure redis_url to monitor slow queries." %>';
+ show(el('dash-slow-empty'));
+ } else {
+ var top5 = data.slice(0, 5);
+ el('dash-slow-tbody').innerHTML = top5.map(function(q) {
+ var d = q.duration_ms;
+ var cls = d >= 2000 ? 'mg-badge-danger' : d >= 1000 ? 'mg-badge-warning' : 'mg-badge-info';
+ var sqlShort = escHtml(q.sql).length > 120 ? escHtml(q.sql).substring(0, 120) + '...' : escHtml(q.sql);
+ return '' + d + ' ms ' +
+ '' + escHtml(q.timestamp) + ' ' +
+ '' + sqlShort + ' ';
+ }).join('');
+ show(el('dash-slow-table'));
+ }
+ loaded.slow = true;
+ checkAllLoaded();
+ }, function() {
+ el('dash-slow-empty').textContent = 'Configure redis_url to monitor slow queries.';
+ show(el('dash-slow-empty'));
+ loaded.slow = true;
+ checkAllLoaded();
+ });
+
+ // Top 5 expensive queries
+ ajaxGet(ROUTES.query_stats, { sort: 'total_time', limit: 5 }, function(data) {
+ if (data.error) {
+ el('dash-qstats-error').innerHTML = '' + escHtml(data.error) + '
';
+ show(el('dash-qstats-error'));
+ } else if (!data.length) {
+ el('dash-qstats-empty').textContent = 'No query statistics available.';
+ show(el('dash-qstats-empty'));
+ } else {
+ el('dash-qstats-tbody').innerHTML = data.map(function(q) {
+ var sqlShort = q.sql.length > 120 ? q.sql.substring(0, 120) + '...' : q.sql;
+ return '' +
+ '' + escHtml(sqlShort) + ' ' +
+ '' + Number(q.calls).toLocaleString() + ' ' +
+ '' + formatDuration(q.total_time_ms) + ' ' +
+ '' + formatDuration(q.avg_time_ms) + ' ';
+ }).join('');
+ show(el('dash-qstats-table'));
+ }
+ loaded.qstats = true;
+ checkAllLoaded();
+ }, function() {
+ el('dash-qstats-empty').textContent = 'Query statistics unavailable.';
+ show(el('dash-qstats-empty'));
+ loaded.qstats = true;
+ checkAllLoaded();
+ });
+
+ // Duplicate indexes count
+ ajaxGet(ROUTES.duplicate_indexes, {}, function(data) {
+ var count = Array.isArray(data) ? data.length : 0;
+ var countEl = el('dash-dup-count');
+ if (count === 0) {
+ countEl.innerHTML = '✓ 0 ';
+ } else {
+ countEl.innerHTML = '' + count + ' ';
+ }
+ loaded.dup = true;
+ checkAllLoaded();
+ }, function() { el('dash-dup-count').textContent = '?'; loaded.dup = true; checkAllLoaded(); });
+
+ // Unused indexes count
+ ajaxGet(ROUTES.unused_indexes, {}, function(data) {
+ var count = Array.isArray(data) ? data.length : 0;
+ var countEl = el('dash-unused-count');
+ if (count === 0) {
+ countEl.innerHTML = '✓ 0 ';
+ } else {
+ countEl.innerHTML = '' + count + ' ';
+ }
+ loaded.unused = true;
+ checkAllLoaded();
+ }, function() { el('dash-unused-count').textContent = '?'; loaded.unused = true; checkAllLoaded(); });
+ }
+
+ // Dashboard tab-jump buttons
+ document.addEventListener('click', function(e) {
+ var jumpBtn = e.target.closest('.dash-jump-tab');
+ if (jumpBtn) {
+ var target = jumpBtn.dataset.target;
+ qsa('.mg-tab').forEach(function(t) { t.classList.remove('active'); });
+ qsa('.mg-tab-content').forEach(function(c) { c.classList.remove('active'); });
+ qs('[data-tab="' + target + '"]').classList.add('active');
+ el('tab-' + target).classList.add('active');
+ if (target === 'slow') loadSlowQueries();
+ if (target === 'indexes') loadDuplicateIndexes();
+ if (target === 'qstats') loadQueryStats();
+ if (target === 'unused') loadUnusedIndexes();
+ }
+ });
+
+ // Load dashboard on page load
+ loadDashboard();
+```
+
+- [ ] **Step 3: Add the query explorer mode toggle**
+
+Insert this after the dashboard section, before the existing visual builder JS (the `var typeLabels = ...` line):
+
+```javascript
+ // --- Query Explorer Mode Toggle ---
+
+ qsa('.qe-mode').forEach(function(btn) {
+ btn.addEventListener('click', function() {
+ qsa('.qe-mode').forEach(function(b) {
+ b.classList.remove('active');
+ b.classList.add('mg-btn-outline');
+ });
+ btn.classList.add('active');
+ btn.classList.remove('mg-btn-outline');
+ if (btn.dataset.mode === 'visual') {
+ show(el('qe-visual'));
+ hide(el('qe-sql'));
+ } else {
+ hide(el('qe-visual'));
+ show(el('qe-sql'));
+ }
+ });
+ });
+```
+
+- [ ] **Step 4: Update the slow query "Use" button handler**
+
+Find the existing handler (around line 522-529) that switches to the SQL tab when clicking "Use" on a slow query. Update it to switch to the Query Explorer tab in SQL mode instead:
+
+Change:
+```javascript
+ qs('[data-tab="sql"]').classList.add('active');
+ el('tab-sql').classList.add('active');
+```
+
+To:
+```javascript
+ qs('[data-tab="explorer"]').classList.add('active');
+ el('tab-explorer').classList.add('active');
+ // Switch to SQL mode within Query Explorer
+ qsa('.qe-mode').forEach(function(b) { b.classList.remove('active'); b.classList.add('mg-btn-outline'); });
+ qs('.qe-mode[data-mode="sql"]').classList.add('active');
+ qs('.qe-mode[data-mode="sql"]').classList.remove('mg-btn-outline');
+ hide(el('qe-visual'));
+ show(el('qe-sql'));
+```
+
+- [ ] **Step 5: Run specs and RuboCop**
+
+Run: `bundle exec rspec && bundle exec rubocop`
+Expected: all specs pass, no offenses
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add app/views/mysql_genius/queries/index.html.erb
+git commit -m "Add dashboard JS loader, query explorer toggle, and auto-load on page mount"
+```
+
+---
+
+### Task 6: Update gemspec description
+
+**Files:**
+- Modify: `mysql_genius.gemspec:14-16`
+
+- [ ] **Step 1: Update the description**
+
+Change the description in `mysql_genius.gemspec` from:
+
+```ruby
+ spec.description = "MysqlGenius gives Rails apps a mountable admin dashboard for MySQL databases. " \
+ "Includes a safe SQL query explorer with visual builder, EXPLAIN analysis, " \
+ "slow query monitoring, audit logging, and optional AI-powered query suggestions and optimization."
+```
+
+To:
+
+```ruby
+ spec.description = "MysqlGenius gives Rails apps a mountable performance dashboard for MySQL databases. " \
+ "Monitor slow queries, analyze query statistics from performance_schema, detect unused and duplicate indexes, " \
+ "and explore your database with optional AI-powered optimization."
+```
+
+- [ ] **Step 2: Commit**
+
+```bash
+git add mysql_genius.gemspec
+git commit -m "Update gemspec description to lead with monitoring features"
+```
+
+---
+
+### Task 7: Update README
+
+**Files:**
+- Modify: `README.md`
+
+- [ ] **Step 1: Reorder screenshots section**
+
+Move the screenshots section so Dashboard is first. Replace the current screenshots block (lines 6-41) with:
+
+```markdown
+### Dashboard
+At-a-glance server health, top slow queries, most expensive queries, and index alerts.
+
+
+
+### Slow Queries
+SELECT queries exceeding the configured threshold, captured via ActiveSupport notifications and Redis.
+
+### Query Stats
+Top queries from `performance_schema` sorted by total time, with call counts, avg/max time, and rows examined.
+
+
+
+### Server Dashboard
+Server health: version, connections, InnoDB buffer pool, and query activity with AI-powered diagnostics.
+
+
+
+### Table Sizes
+View row counts, data size, index size, fragmentation, and a visual size chart for every table.
+
+
+
+### Duplicate Index Detection
+Find redundant indexes whose columns are a left-prefix of another index, with ready-to-run `DROP INDEX` statements.
+
+
+
+### Query Explorer
+Build queries visually or write raw SQL. Optional AI assistant generates queries from plain English descriptions.
+
+
+
+### AI Tools
+Schema review that finds anti-patterns -- missing primary keys, nullable foreign keys, inappropriate column types, and more.
+
+
+```
+
+- [ ] **Step 2: Update the Usage section**
+
+Replace the current "Usage" section (starting around line 218) with:
+
+```markdown
+## Usage
+
+Visit `/mysql_genius` in your browser. The dashboard loads automatically with an overview of your database health.
+
+### Dashboard
+The default landing page shows server health cards, top 5 slow queries, top 5 most expensive queries (from performance_schema), and index alert badges for duplicate and unused indexes. Each section links to its detailed tab.
+
+### Query Explorer
+Combines the visual query builder and raw SQL editor in one tab. Toggle between Visual mode (point-and-click with column selection, filters, and ordering) and SQL mode (raw SQL with optional AI assistant). Generated SQL syncs between modes.
+
+### Monitoring Tabs
+- **Slow Queries** -- slow SELECT queries captured from your application in real time, with Explain and Optimize actions
+- **Query Stats** -- top queries from `performance_schema` sorted by total time, avg time, calls, or rows examined
+- **Server** -- connections, InnoDB buffer pool, query activity, with AI-powered diagnostics
+- **Table Sizes** -- row counts, data size, index size, fragmentation for all tables
+- **Unused Indexes** -- indexes with zero reads since server restart
+- **Duplicate Indexes** -- redundant indexes with ready-to-run DROP statements
+```
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add README.md
+git commit -m "Update README to reflect dashboard-first layout and new tab order"
+```
diff --git a/docs/superpowers/specs/2026-04-08-dashboard-first-redesign.md b/docs/superpowers/specs/2026-04-08-dashboard-first-redesign.md
new file mode 100644
index 0000000..ead2bea
--- /dev/null
+++ b/docs/superpowers/specs/2026-04-08-dashboard-first-redesign.md
@@ -0,0 +1,87 @@
+# Dashboard-First Redesign
+
+Redesign the default landing experience to lead with PgHero-style monitoring instead of the SQL query builder. Based on Reddit feedback that the current Visual Builder default makes the engine look like "another DB GUI" rather than a MySQL performance dashboard.
+
+## Changes
+
+### 1. New Dashboard Tab (default)
+
+A new tab that becomes the active tab on page load. Loads all data immediately via parallel AJAX calls to existing endpoints. Four stacked sections:
+
+**Server Summary** (reuses `server_overview` endpoint)
+- Four cards in a responsive grid: Server (version, uptime), Connections (used/max progress bar), InnoDB Buffer Pool (hit rate progress bar), Query Activity (questions/sec, slow queries count)
+
+**Top 5 Slow Queries** (reuses `slow_queries` endpoint)
+- Compact table: duration, timestamp, truncated SQL
+- "View all" link switches to Slow Queries tab
+- If Redis not configured: muted placeholder "Configure `redis_url` to monitor slow queries."
+
+**Top 5 Expensive Queries** (reuses `query_stats` endpoint with new `limit` param)
+- Compact table: query digest, calls, total time, avg time
+- Sorted by total time descending
+- "View all" link switches to Query Stats tab
+- If `performance_schema` unavailable: muted placeholder
+
+**Index Alerts** (reuses `duplicate_indexes` and `unused_indexes` endpoints)
+- Two badge cards showing counts: "X duplicate indexes", "X unused indexes"
+- Green checkmark if count is zero
+- Each badge is clickable, switches to the corresponding tab
+
+### 2. Query Explorer Tab (merged Visual Builder + SQL Query)
+
+The two existing query tabs merge into one "Query Explorer" tab with a mode toggle:
+
+- **Visual mode** -- existing visual builder UI (table selector, columns, filters, ordering)
+- **SQL mode** -- existing raw SQL textarea with AI suggestion panel
+- Small toggle buttons at top of tab to switch modes
+- Default mode: Visual
+- SQL generated by visual builder carries over when switching to SQL mode (existing behavior preserved)
+- Shared results area unchanged
+
+### 3. Tab Reorder
+
+New order:
+1. Dashboard (new, default active)
+2. Slow Queries
+3. Query Stats
+4. Server
+5. Table Sizes
+6. Unused Indexes
+7. Duplicate Indexes
+8. Query Explorer (merged)
+9. AI Tools (conditional on `@ai_enabled`)
+
+### 4. Backend Change
+
+Add `limit` parameter support to the `query_stats` action. When present, cap the result set to the given limit. The dashboard passes `limit=5`; the Query Stats tab continues to omit it for the full list.
+
+### 5. Gemspec Description Update
+
+Change description to lead with monitoring:
+> "MysqlGenius gives Rails apps a mountable performance dashboard for MySQL databases. Monitor slow queries, analyze query statistics from performance_schema, detect unused and duplicate indexes, and explore your database with optional AI-powered optimization."
+
+### 6. README Updates
+
+- Reorder screenshots section to lead with Dashboard
+- Update "Usage" section to reflect new tab order and dashboard-first experience
+- Add Dashboard screenshot placeholder
+
+## Not Changing
+
+- No new routes -- dashboard reuses existing endpoints
+- No new controller actions -- only a `limit` param added to `query_stats`
+- All existing tab partials remain intact, just reordered in the view
+- Shared results area unchanged
+- AI features unchanged
+- Authentication unchanged
+
+## Files Affected
+
+- `app/views/mysql_genius/queries/index.html.erb` -- tab bar reorder, new dashboard partial render, merge visual/sql tabs, JS changes for dashboard auto-load and query explorer toggle
+- `app/views/mysql_genius/queries/_tab_dashboard.html.erb` -- new partial
+- `app/views/mysql_genius/queries/_tab_query_explorer.html.erb` -- new partial combining visual builder and sql query content
+- `app/views/mysql_genius/queries/_tab_visual_builder.html.erb` -- removed (content moves to query explorer)
+- `app/views/mysql_genius/queries/_tab_sql_query.html.erb` -- removed (content moves to query explorer)
+- `app/controllers/concerns/mysql_genius/database_analysis.rb` -- add `limit` param to `query_stats`
+- `mysql_genius.gemspec` -- updated description
+- `README.md` -- updated screenshots order, usage section
diff --git a/lib/generators/mysql_genius/install/install_generator.rb b/lib/generators/mysql_genius/install/install_generator.rb
new file mode 100644
index 0000000..27ceac5
--- /dev/null
+++ b/lib/generators/mysql_genius/install/install_generator.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module MysqlGenius
+ module Generators
+ class InstallGenerator < Rails::Generators::Base
+ source_root File.expand_path("templates", __dir__)
+
+ desc "Creates a MysqlGenius initializer and mounts the engine in routes."
+
+ def copy_initializer
+ template("initializer.rb", "config/initializers/mysql_genius.rb")
+ end
+
+ def mount_engine
+ route('mount MysqlGenius::Engine, at: "/mysql_genius"')
+ end
+ end
+ end
+end
diff --git a/lib/generators/mysql_genius/install/templates/initializer.rb b/lib/generators/mysql_genius/install/templates/initializer.rb
new file mode 100644
index 0000000..3a1dac3
--- /dev/null
+++ b/lib/generators/mysql_genius/install/templates/initializer.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+MysqlGenius.configure do |config|
+ # --- Authentication ---
+ # Lambda that receives the controller instance. Return true to allow access.
+ # Default: allows everyone. Use route constraints for most cases.
+ # config.authenticate = ->(controller) { controller.current_user&.admin? }
+
+ # To use current_user or other app helpers, inherit from ApplicationController:
+ # config.base_controller = "ApplicationController"
+
+ # --- Tables ---
+ # Tables featured at the top of the visual builder dropdown (optional).
+ # config.featured_tables = %w[users posts comments]
+
+ # Tables blocked from querying (defaults: sessions, schema_migrations, ar_internal_metadata).
+ # config.blocked_tables += %w[oauth_tokens api_keys]
+
+ # Column patterns to redact with [REDACTED] in results (case-insensitive substring match).
+ # config.masked_column_patterns = %w[password secret digest token ssn]
+
+ # Default columns checked in the visual builder per table (optional).
+ # config.default_columns = {
+ # "users" => %w[id name email created_at],
+ # "posts" => %w[id title user_id published_at]
+ # }
+
+ # --- Query Safety ---
+ # config.max_row_limit = 1000 # Hard cap on rows returned
+ # config.default_row_limit = 25 # Default when no limit specified
+ # config.query_timeout_ms = 30_000 # 30 second timeout
+
+ # --- Slow Query Monitoring ---
+ # Requires Redis. Set to nil to disable.
+ # config.redis_url = ENV["REDIS_URL"]
+ # config.slow_query_threshold_ms = 250
+
+ # --- Audit Logging ---
+ # Set to nil to disable. Logs query executions, rejections, and errors.
+ # config.audit_logger = Logger.new(Rails.root.join("log", "mysql_genius.log"))
+
+ # --- AI Features (optional) ---
+ # Supports any OpenAI-compatible API: OpenAI, Azure OpenAI, Ollama, or a custom client.
+ # config.ai_endpoint = "https://api.openai.com/v1/chat/completions"
+ # config.ai_api_key = ENV["OPENAI_API_KEY"]
+ # config.ai_model = "gpt-4o"
+ # config.ai_auth_style = :bearer # :bearer for OpenAI/Ollama, :api_key for Azure
+
+ # Domain context helps the AI understand your schema and generate better queries.
+ # config.ai_system_context = <<~CONTEXT
+ # This is an e-commerce database.
+ # - `users` stores customer accounts.
+ # - `orders` tracks purchases, linked to users via `user_id`.
+ # - Soft-deleted records have `deleted_at IS NOT NULL`.
+ # CONTEXT
+end
diff --git a/lib/mysql_genius.rb b/lib/mysql_genius.rb
index a391ae8..accda73 100644
--- a/lib/mysql_genius.rb
+++ b/lib/mysql_genius.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
require "mysql_genius/version"
require "mysql_genius/configuration"
require "mysql_genius/sql_validator"
diff --git a/lib/mysql_genius/configuration.rb b/lib/mysql_genius/configuration.rb
index 11e1718..9d46c5e 100644
--- a/lib/mysql_genius/configuration.rb
+++ b/lib/mysql_genius/configuration.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module MysqlGenius
class Configuration
# Tables to feature in the visual builder dropdown (array of strings).
@@ -66,17 +68,17 @@ class Configuration
def initialize
@featured_tables = []
- @blocked_tables = %w[
- sessions
- ar_internal_metadata
- schema_migrations
+ @blocked_tables = [
+ "sessions",
+ "ar_internal_metadata",
+ "schema_migrations",
]
- @masked_column_patterns = %w[password secret digest token]
+ @masked_column_patterns = ["password", "secret", "digest", "token"]
@default_columns = {}
@max_row_limit = 1000
@default_row_limit = 25
@query_timeout_ms = 30_000
- @authenticate = ->(controller) { true }
+ @authenticate = ->(_controller) { true }
@ai_client = nil
@ai_endpoint = nil
@ai_api_key = nil
diff --git a/lib/mysql_genius/engine.rb b/lib/mysql_genius/engine.rb
index 7138148..9f58e7a 100644
--- a/lib/mysql_genius/engine.rb
+++ b/lib/mysql_genius/engine.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module MysqlGenius
class Engine < ::Rails::Engine
isolate_namespace MysqlGenius
diff --git a/lib/mysql_genius/slow_query_monitor.rb b/lib/mysql_genius/slow_query_monitor.rb
index 2c39402..f3e320f 100644
--- a/lib/mysql_genius/slow_query_monitor.rb
+++ b/lib/mysql_genius/slow_query_monitor.rb
@@ -1,37 +1,41 @@
+# frozen_string_literal: true
+
require "json"
require "time"
module MysqlGenius
class SlowQueryMonitor
- def self.redis_key
- "mysql_genius:slow_queries"
- end
+ class << self
+ def redis_key
+ "mysql_genius:slow_queries"
+ end
- def self.subscribe!
- ActiveSupport::Notifications.subscribe("sql.active_record") do |_name, start, finish, _id, payload|
- duration_ms = ((finish - start) * 1000).round(1)
- sql = payload[:sql].to_s
- threshold = MysqlGenius.configuration.slow_query_threshold_ms
+ def subscribe!
+ ActiveSupport::Notifications.subscribe("sql.active_record") do |_name, start, finish, _id, payload|
+ duration_ms = ((finish - start) * 1000).round(1)
+ sql = payload[:sql].to_s
+ threshold = MysqlGenius.configuration.slow_query_threshold_ms
- next unless duration_ms >= threshold
- next unless sql.match?(/\ASELECT\b/i)
- next if sql.include?("SCHEMA")
- next if sql.include?("EXPLAIN")
- next if payload[:name] == "SCHEMA"
+ next if duration_ms < threshold
+ next unless sql.match?(/\ASELECT\b/i)
+ next if sql.include?("SCHEMA")
+ next if sql.include?("EXPLAIN")
+ next if payload[:name] == "SCHEMA"
- begin
- redis = Redis.new(url: MysqlGenius.configuration.redis_url)
- entry = {
- sql: sql.length > 10_000 ? sql[0, 10_000] : sql,
- duration_ms: duration_ms,
- timestamp: Time.now.iso8601,
- name: payload[:name]
- }.to_json
+ begin
+ redis = Redis.new(url: MysqlGenius.configuration.redis_url)
+ entry = {
+ sql: sql.length > 10_000 ? sql[0, 10_000] : sql,
+ duration_ms: duration_ms,
+ timestamp: Time.now.iso8601,
+ name: payload[:name],
+ }.to_json
- redis.lpush(redis_key, entry)
- redis.ltrim(redis_key, 0, 199)
- rescue => e
- Rails.logger.debug("[mysql_genius] Slow query logger error: #{e.message}") if defined?(Rails)
+ redis.lpush(redis_key, entry)
+ redis.ltrim(redis_key, 0, 199)
+ rescue => e
+ Rails.logger.debug("[mysql_genius] Slow query logger error: #{e.message}") if defined?(Rails)
+ end
end
end
end
diff --git a/lib/mysql_genius/sql_validator.rb b/lib/mysql_genius/sql_validator.rb
index 67d652a..7a537c3 100644
--- a/lib/mysql_genius/sql_validator.rb
+++ b/lib/mysql_genius/sql_validator.rb
@@ -1,8 +1,10 @@
+# frozen_string_literal: true
+
module MysqlGenius
module SqlValidator
- FORBIDDEN_KEYWORDS = %w[INSERT UPDATE DELETE DROP ALTER CREATE TRUNCATE GRANT REVOKE].freeze
+ FORBIDDEN_KEYWORDS = ["INSERT", "UPDATE", "DELETE", "DROP", "ALTER", "CREATE", "TRUNCATE", "GRANT", "REVOKE"].freeze
- module_function
+ extend self
def validate(sql, blocked_tables:, connection:)
return "Please enter a query." if sql.nil? || sql.strip.empty?
@@ -22,7 +24,7 @@ def validate(sql, blocked_tables:, connection:)
tables_in_query = extract_table_references(normalized, connection)
blocked = tables_in_query & blocked_tables
if blocked.any?
- return "Access denied for table(s): #{blocked.join(', ')}."
+ return "Access denied for table(s): #{blocked.join(", ")}."
end
nil
@@ -44,7 +46,7 @@ def apply_row_limit(sql, limit)
elsif sql.match?(/\bLIMIT\s+\d+/i)
sql.gsub(/\bLIMIT\s+(\d+)/i) { "LIMIT #{[::Regexp.last_match(1).to_i, limit].min}" }
else
- "#{sql.gsub(/;\s*\z/, '')} LIMIT #{limit}"
+ "#{sql.gsub(/;\s*\z/, "")} LIMIT #{limit}"
end
end
diff --git a/lib/mysql_genius/version.rb b/lib/mysql_genius/version.rb
index dd20331..0102dc9 100644
--- a/lib/mysql_genius/version.rb
+++ b/lib/mysql_genius/version.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
module MysqlGenius
- VERSION = "0.1.1"
+ VERSION = "0.2.0"
end
diff --git a/mysql_genius.gemspec b/mysql_genius.gemspec
index cef7002..5f97c96 100644
--- a/mysql_genius.gemspec
+++ b/mysql_genius.gemspec
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "mysql_genius/version"
@@ -9,9 +11,9 @@ Gem::Specification.new do |spec|
spec.email = ["antarr.t.byrd@uth.tmc.edu"]
spec.summary = "A MySQL performance dashboard and query explorer for Rails — like PgHero, but for MySQL."
- spec.description = "MysqlGenius gives Rails apps a mountable admin dashboard for MySQL databases. " \
- "Includes a safe SQL query explorer with visual builder, EXPLAIN analysis, " \
- "slow query monitoring, audit logging, and optional AI-powered query suggestions and optimization."
+ spec.description = "MysqlGenius gives Rails apps a mountable performance dashboard for MySQL databases. " \
+ "Monitor slow queries, analyze query statistics from performance_schema, detect unused and duplicate indexes, " \
+ "and explore your database with optional AI-powered optimization."
spec.homepage = "https://github.com/antarr/mysql_genius"
spec.license = "MIT"
@@ -21,14 +23,13 @@ Gem::Specification.new do |spec|
spec.metadata["source_code_uri"] = spec.homepage
spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/main/CHANGELOG.md"
- spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
- `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
+ spec.files = Dir.chdir(File.expand_path("..", __FILE__)) do
+ %x(git ls-files -z).split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
- spec.add_dependency "railties", ">= 5.2", "< 9"
- spec.add_dependency "activerecord", ">= 5.2", "< 9"
-
+ spec.add_dependency("activerecord", ">= 5.2", "< 9")
+ spec.add_dependency("railties", ">= 5.2", "< 9")
end
diff --git a/spec/mysql_genius/ai_client_spec.rb b/spec/mysql_genius/ai_client_spec.rb
index 410d000..eecdb19 100644
--- a/spec/mysql_genius/ai_client_spec.rb
+++ b/spec/mysql_genius/ai_client_spec.rb
@@ -1,7 +1,9 @@
+# frozen_string_literal: true
+
require "spec_helper"
require "mysql_genius/ai_client"
-RSpec.describe MysqlGenius::AiClient do
+RSpec.describe(MysqlGenius::AiClient) do
subject(:client) { described_class.new }
before do
@@ -13,28 +15,66 @@
end
end
+ def stub_http(response: nil, &block)
+ http = instance_double(Net::HTTP)
+ allow(Net::HTTP).to(receive(:new).and_return(http))
+ allow(http).to(receive(:use_ssl=))
+ allow(http).to(receive(:verify_mode=))
+ allow(http).to(receive(:ca_file=))
+ allow(http).to(receive(:open_timeout=))
+ allow(http).to(receive(:read_timeout=))
+ allow(http).to(receive_messages(use_ssl?: false))
+ if block
+ allow(http).to(receive(:request, &block))
+ elsif response
+ allow(http).to(receive(:request).and_return(response))
+ end
+ http
+ end
+
+ def stub_http_with_block(&block)
+ allow(Net::HTTP).to(receive(:new)) do
+ http = instance_double(Net::HTTP)
+ allow(http).to(receive(:use_ssl=))
+ allow(http).to(receive(:verify_mode=))
+ allow(http).to(receive(:ca_file=))
+ allow(http).to(receive(:open_timeout=))
+ allow(http).to(receive(:read_timeout=))
+ allow(http).to(receive_messages(use_ssl?: false))
+ block.call(http)
+ http
+ end
+ end
+
+ def ok_response(content)
+ body = { "choices" => [{ "message" => { "content" => content } }] }.to_json
+ instance_double(Net::HTTPOK, body: body).tap do |r|
+ allow(r).to(receive(:is_a?).with(Net::HTTPRedirection).and_return(false))
+ end
+ end
+
describe "#chat" do
context "with a custom ai_client callable" do
before do
- MysqlGenius.configuration.ai_client = lambda { |messages:, temperature:|
+ MysqlGenius.configuration.ai_client = lambda { |**_kwargs|
{ "sql" => "SELECT 1", "explanation" => "test" }
}
end
it "delegates to the custom client" do
result = client.chat(messages: [{ role: "user", content: "test" }])
- expect(result).to eq({ "sql" => "SELECT 1", "explanation" => "test" })
+ expect(result).to(eq({ "sql" => "SELECT 1", "explanation" => "test" }))
end
it "passes temperature through" do
called_temp = nil
- MysqlGenius.configuration.ai_client = lambda { |messages:, temperature:|
+ MysqlGenius.configuration.ai_client = lambda { |temperature:, **|
called_temp = temperature
{}
}
client.chat(messages: [], temperature: 0.5)
- expect(called_temp).to eq(0.5)
+ expect(called_temp).to(eq(0.5))
end
end
@@ -46,69 +86,40 @@
end
it "raises an error" do
- expect {
+ expect do
client.chat(messages: [])
- }.to raise_error(MysqlGenius::Error, /AI is not configured/)
+ end.to(raise_error(MysqlGenius::Error, /AI is not configured/))
end
end
context "with an HTTP endpoint" do
- let(:response_body) do
- {
- "choices" => [
- { "message" => { "content" => '{"sql":"SELECT 1"}' } }
- ]
- }.to_json
- end
+ let(:http_response) { ok_response('{"sql":"SELECT 1"}') }
- let(:http_response) do
- instance_double(Net::HTTPOK, body: response_body, :is_a? => false).tap do |r|
- allow(r).to receive(:is_a?).with(Net::HTTPRedirection).and_return(false)
- end
- end
-
- before do
- http = instance_double(Net::HTTP)
- allow(Net::HTTP).to receive(:new).and_return(http)
- allow(http).to receive(:use_ssl=)
- allow(http).to receive(:open_timeout=)
- allow(http).to receive(:read_timeout=)
- allow(http).to receive(:request).and_return(http_response)
- end
+ before { stub_http(response: http_response) }
it "returns parsed JSON from the response content" do
result = client.chat(messages: [{ role: "user", content: "hello" }])
- expect(result).to eq({ "sql" => "SELECT 1" })
+ expect(result).to(eq({ "sql" => "SELECT 1" }))
end
it "includes the model in the request body" do
- allow(Net::HTTP).to receive(:new) do |host, port|
- http = instance_double(Net::HTTP)
- allow(http).to receive(:use_ssl=)
- allow(http).to receive(:open_timeout=)
- allow(http).to receive(:read_timeout=)
- allow(http).to receive(:request) do |req|
+ stub_http_with_block do |http|
+ allow(http).to(receive(:request)) do |req|
body = JSON.parse(req.body)
- expect(body["model"]).to eq("gpt-4o")
+ expect(body["model"]).to(eq("gpt-4o"))
http_response
end
- http
end
client.chat(messages: [])
end
it "uses Bearer auth when ai_auth_style is :bearer" do
- allow(Net::HTTP).to receive(:new) do |host, port|
- http = instance_double(Net::HTTP)
- allow(http).to receive(:use_ssl=)
- allow(http).to receive(:open_timeout=)
- allow(http).to receive(:read_timeout=)
- allow(http).to receive(:request) do |req|
- expect(req["Authorization"]).to eq("Bearer sk-test-key")
+ stub_http_with_block do |http|
+ allow(http).to(receive(:request)) do |req|
+ expect(req["Authorization"]).to(eq("Bearer sk-test-key"))
http_response
end
- http
end
client.chat(messages: [])
@@ -117,16 +128,11 @@
it "uses api-key header when ai_auth_style is :api_key" do
MysqlGenius.configuration.ai_auth_style = :api_key
- allow(Net::HTTP).to receive(:new) do |host, port|
- http = instance_double(Net::HTTP)
- allow(http).to receive(:use_ssl=)
- allow(http).to receive(:open_timeout=)
- allow(http).to receive(:read_timeout=)
- allow(http).to receive(:request) do |req|
- expect(req["api-key"]).to eq("sk-test-key")
+ stub_http_with_block do |http|
+ allow(http).to(receive(:request)) do |req|
+ expect(req["api-key"]).to(eq("sk-test-key"))
http_response
end
- http
end
client.chat(messages: [])
@@ -134,144 +140,103 @@
end
context "when the API returns an error" do
- let(:error_body) { { "error" => { "message" => "Rate limit exceeded" } }.to_json }
- let(:http_response) do
- instance_double(Net::HTTPOK, body: error_body).tap do |r|
- allow(r).to receive(:is_a?).with(Net::HTTPRedirection).and_return(false)
- end
- end
-
before do
- http = instance_double(Net::HTTP)
- allow(Net::HTTP).to receive(:new).and_return(http)
- allow(http).to receive(:use_ssl=)
- allow(http).to receive(:open_timeout=)
- allow(http).to receive(:read_timeout=)
- allow(http).to receive(:request).and_return(http_response)
+ body = { "error" => { "message" => "Rate limit exceeded" } }.to_json
+ response = instance_double(Net::HTTPOK, body: body).tap do |r|
+ allow(r).to(receive(:is_a?).with(Net::HTTPRedirection).and_return(false))
+ end
+ stub_http(response: response)
end
it "raises an error with the API message" do
- expect {
+ expect do
client.chat(messages: [])
- }.to raise_error(MysqlGenius::Error, /Rate limit exceeded/)
+ end.to(raise_error(MysqlGenius::Error, /Rate limit exceeded/))
end
end
context "when the response has no content" do
- let(:empty_body) { { "choices" => [{ "message" => { "content" => nil } }] }.to_json }
- let(:http_response) do
- instance_double(Net::HTTPOK, body: empty_body).tap do |r|
- allow(r).to receive(:is_a?).with(Net::HTTPRedirection).and_return(false)
- end
- end
-
before do
- http = instance_double(Net::HTTP)
- allow(Net::HTTP).to receive(:new).and_return(http)
- allow(http).to receive(:use_ssl=)
- allow(http).to receive(:open_timeout=)
- allow(http).to receive(:read_timeout=)
- allow(http).to receive(:request).and_return(http_response)
+ body = { "choices" => [{ "message" => { "content" => nil } }] }.to_json
+ response = instance_double(Net::HTTPOK, body: body).tap do |r|
+ allow(r).to(receive(:is_a?).with(Net::HTTPRedirection).and_return(false))
+ end
+ stub_http(response: response)
end
it "raises an error" do
- expect {
+ expect do
client.chat(messages: [])
- }.to raise_error(MysqlGenius::Error, /No content/)
+ end.to(raise_error(MysqlGenius::Error, /No content/))
end
end
end
describe "#parse_json_content (via chat)" do
- let(:make_response) do
- ->(content) do
- body = { "choices" => [{ "message" => { "content" => content } }] }.to_json
- instance_double(Net::HTTPOK, body: body).tap do |r|
- allow(r).to receive(:is_a?).with(Net::HTTPRedirection).and_return(false)
- end
- end
- end
+ let(:current_response) { { value: nil } }
before do
- http = instance_double(Net::HTTP)
- allow(Net::HTTP).to receive(:new).and_return(http)
- allow(http).to receive(:use_ssl=)
- allow(http).to receive(:open_timeout=)
- allow(http).to receive(:read_timeout=)
- allow(http).to receive(:request) { |_| @current_response }
+ response_holder = current_response
+ stub_http { |_| response_holder[:value] }
end
it "parses plain JSON" do
- @current_response = make_response.call('{"sql":"SELECT 1"}')
+ current_response[:value] = ok_response('{"sql":"SELECT 1"}')
result = client.chat(messages: [])
- expect(result).to eq({ "sql" => "SELECT 1" })
+ expect(result).to(eq({ "sql" => "SELECT 1" }))
end
it "strips markdown code fences" do
- @current_response = make_response.call("```json\n{\"sql\":\"SELECT 1\"}\n```")
+ current_response[:value] = ok_response("```json\n{\"sql\":\"SELECT 1\"}\n```")
result = client.chat(messages: [])
- expect(result).to eq({ "sql" => "SELECT 1" })
+ expect(result).to(eq({ "sql" => "SELECT 1" }))
end
it "strips code fences without language tag" do
- @current_response = make_response.call("```\n{\"sql\":\"SELECT 1\"}\n```")
+ current_response[:value] = ok_response("```\n{\"sql\":\"SELECT 1\"}\n```")
result = client.chat(messages: [])
- expect(result).to eq({ "sql" => "SELECT 1" })
+ expect(result).to(eq({ "sql" => "SELECT 1" }))
end
it "returns raw content when JSON is unparseable" do
- @current_response = make_response.call("This is not JSON at all")
+ current_response[:value] = ok_response("This is not JSON at all")
result = client.chat(messages: [])
- expect(result).to eq({ "raw" => "This is not JSON at all" })
+ expect(result).to(eq({ "raw" => "This is not JSON at all" }))
end
end
describe "redirect handling" do
it "follows redirects up to MAX_REDIRECTS" do
redirect_response = instance_double(Net::HTTPRedirection, :[] => "https://api2.example.com/v1/chat").tap do |r|
- allow(r).to receive(:is_a?).with(Net::HTTPRedirection).and_return(true)
- end
-
- final_body = { "choices" => [{ "message" => { "content" => '{"ok":true}' } }] }.to_json
- final_response = instance_double(Net::HTTPOK, body: final_body).tap do |r|
- allow(r).to receive(:is_a?).with(Net::HTTPRedirection).and_return(false)
+ allow(r).to(receive(:is_a?).with(Net::HTTPRedirection).and_return(true))
end
+ final_response = ok_response('{"ok":true}')
call_count = 0
- allow(Net::HTTP).to receive(:new) do
- http = instance_double(Net::HTTP)
- allow(http).to receive(:use_ssl=)
- allow(http).to receive(:open_timeout=)
- allow(http).to receive(:read_timeout=)
- allow(http).to receive(:request) do
+ stub_http_with_block do |http|
+ allow(http).to(receive(:request)) do
call_count += 1
call_count == 1 ? redirect_response : final_response
end
- http
end
result = client.chat(messages: [])
- expect(result).to eq({ "ok" => true })
- expect(call_count).to eq(2)
+ expect(result).to(eq({ "ok" => true }))
+ expect(call_count).to(eq(2))
end
it "raises on too many redirects" do
redirect_response = instance_double(Net::HTTPRedirection, :[] => "https://api.example.com/loop").tap do |r|
- allow(r).to receive(:is_a?).with(Net::HTTPRedirection).and_return(true)
+ allow(r).to(receive(:is_a?).with(Net::HTTPRedirection).and_return(true))
end
- allow(Net::HTTP).to receive(:new) do
- http = instance_double(Net::HTTP)
- allow(http).to receive(:use_ssl=)
- allow(http).to receive(:open_timeout=)
- allow(http).to receive(:read_timeout=)
- allow(http).to receive(:request).and_return(redirect_response)
- http
+ stub_http_with_block do |http|
+ allow(http).to(receive(:request).and_return(redirect_response))
end
- expect {
+ expect do
client.chat(messages: [])
- }.to raise_error(MysqlGenius::Error, /Too many redirects/)
+ end.to(raise_error(MysqlGenius::Error, /Too many redirects/))
end
end
end
diff --git a/spec/mysql_genius/ai_optimization_service_spec.rb b/spec/mysql_genius/ai_optimization_service_spec.rb
index 60721f0..323749f 100644
--- a/spec/mysql_genius/ai_optimization_service_spec.rb
+++ b/spec/mysql_genius/ai_optimization_service_spec.rb
@@ -1,23 +1,25 @@
+# frozen_string_literal: true
+
require "spec_helper"
require "mysql_genius/ai_client"
require "mysql_genius/ai_optimization_service"
-RSpec.describe MysqlGenius::AiOptimizationService do
+RSpec.describe(MysqlGenius::AiOptimizationService) do
subject(:service) { described_class.new }
- let(:connection) { double("connection", tables: %w[users posts]) }
+ let(:connection) { double("connection", tables: ["users", "posts"]) }
let(:columns_map) do
{
"users" => [double(name: "id", type: :integer), double(name: "email", type: :string)],
- "posts" => [double(name: "id", type: :integer), double(name: "user_id", type: :integer)]
+ "posts" => [double(name: "id", type: :integer), double(name: "user_id", type: :integer)],
}
end
let(:indexes_map) do
{
"users" => [double(name: "index_users_on_email", columns: ["email"], unique: true)],
- "posts" => [double(name: "index_posts_on_user_id", columns: ["user_id"], unique: false)]
+ "posts" => [double(name: "index_posts_on_user_id", columns: ["user_id"], unique: false)],
}
end
@@ -28,65 +30,65 @@
c.ai_auth_style = :bearer
end
- allow(ActiveRecord::Base).to receive(:connection).and_return(connection)
- allow(connection).to receive(:columns) { |table| columns_map[table] || [] }
- allow(connection).to receive(:indexes) { |table| indexes_map[table] || [] }
+ allow(ActiveRecord::Base).to(receive(:connection).and_return(connection))
+ allow(connection).to(receive(:columns) { |table| columns_map[table] || [] })
+ allow(connection).to(receive(:indexes) { |table| indexes_map[table] || [] })
end
describe "#call" do
- let(:explain_rows) { [%w[1 SIMPLE users ALL], %w[1 SIMPLE posts ref]] }
+ let(:explain_rows) { [["1", "SIMPLE", "users", "ALL"], ["1", "SIMPLE", "posts", "ref"]] }
let(:ai_response) { { "suggestions" => "Add an index on users.email" } }
before do
ai_client = instance_double(MysqlGenius::AiClient)
- allow(MysqlGenius::AiClient).to receive(:new).and_return(ai_client)
- allow(ai_client).to receive(:chat).and_return(ai_response)
+ allow(MysqlGenius::AiClient).to(receive(:new).and_return(ai_client))
+ allow(ai_client).to(receive(:chat).and_return(ai_response))
end
it "returns suggestions from the AI" do
- result = service.call("SELECT * FROM users", explain_rows, %w[users])
- expect(result).to eq(ai_response)
+ result = service.call("SELECT * FROM users", explain_rows, ["users"])
+ expect(result).to(eq(ai_response))
end
it "includes schema with indexes in the system prompt" do
ai_client = instance_double(MysqlGenius::AiClient)
- allow(MysqlGenius::AiClient).to receive(:new).and_return(ai_client)
+ allow(MysqlGenius::AiClient).to(receive(:new).and_return(ai_client))
- expect(ai_client).to receive(:chat) do |messages:|
+ expect(ai_client).to(receive(:chat)) do |messages:|
system_prompt = messages[0][:content]
- expect(system_prompt).to include("users")
- expect(system_prompt).to include("index_users_on_email")
+ expect(system_prompt).to(include("users"))
+ expect(system_prompt).to(include("index_users_on_email"))
ai_response
end
- service.call("SELECT * FROM users", explain_rows, %w[users])
+ service.call("SELECT * FROM users", explain_rows, ["users"])
end
it "includes the SQL and EXPLAIN output in the user prompt" do
ai_client = instance_double(MysqlGenius::AiClient)
- allow(MysqlGenius::AiClient).to receive(:new).and_return(ai_client)
+ allow(MysqlGenius::AiClient).to(receive(:new).and_return(ai_client))
- expect(ai_client).to receive(:chat) do |messages:|
+ expect(ai_client).to(receive(:chat)) do |messages:|
user_prompt = messages[1][:content]
- expect(user_prompt).to include("SELECT * FROM users")
- expect(user_prompt).to include("SIMPLE")
+ expect(user_prompt).to(include("SELECT * FROM users"))
+ expect(user_prompt).to(include("SIMPLE"))
ai_response
end
- service.call("SELECT * FROM users", explain_rows, %w[users])
+ service.call("SELECT * FROM users", explain_rows, ["users"])
end
it "handles string explain rows" do
ai_client = instance_double(MysqlGenius::AiClient)
- allow(MysqlGenius::AiClient).to receive(:new).and_return(ai_client)
+ allow(MysqlGenius::AiClient).to(receive(:new).and_return(ai_client))
- expect(ai_client).to receive(:chat) do |messages:|
+ expect(ai_client).to(receive(:chat)) do |messages:|
user_prompt = messages[1][:content]
- expect(user_prompt).to include("pre-formatted explain")
+ expect(user_prompt).to(include("pre-formatted explain"))
ai_response
end
- service.call("SELECT 1", "pre-formatted explain", %w[users])
+ service.call("SELECT 1", "pre-formatted explain", ["users"])
end
end
end
diff --git a/spec/mysql_genius/ai_suggestion_service_spec.rb b/spec/mysql_genius/ai_suggestion_service_spec.rb
index 0a47932..e4e80c5 100644
--- a/spec/mysql_genius/ai_suggestion_service_spec.rb
+++ b/spec/mysql_genius/ai_suggestion_service_spec.rb
@@ -1,24 +1,26 @@
+# frozen_string_literal: true
+
require "spec_helper"
require "mysql_genius/ai_client"
require "mysql_genius/ai_suggestion_service"
-RSpec.describe MysqlGenius::AiSuggestionService do
+RSpec.describe(MysqlGenius::AiSuggestionService) do
subject(:service) { described_class.new }
- let(:connection) { double("connection", tables: %w[users posts comments]) }
+ let(:connection) { double("connection", tables: ["users", "posts", "comments"]) }
let(:columns_map) do
{
"users" => [
double(name: "id", type: :integer),
double(name: "name", type: :string),
- double(name: "email", type: :string)
+ double(name: "email", type: :string),
],
"posts" => [
double(name: "id", type: :integer),
double(name: "title", type: :string),
- double(name: "user_id", type: :integer)
- ]
+ double(name: "user_id", type: :integer),
+ ],
}
end
@@ -30,8 +32,8 @@
c.ai_auth_style = :bearer
end
- allow(ActiveRecord::Base).to receive(:connection).and_return(connection)
- allow(connection).to receive(:columns) { |table| columns_map[table] || [] }
+ allow(ActiveRecord::Base).to(receive(:connection).and_return(connection))
+ allow(connection).to(receive(:columns) { |table| columns_map[table] || [] })
end
describe "#call" do
@@ -39,70 +41,70 @@
before do
ai_client = instance_double(MysqlGenius::AiClient)
- allow(MysqlGenius::AiClient).to receive(:new).and_return(ai_client)
- allow(ai_client).to receive(:chat).and_return(ai_response)
+ allow(MysqlGenius::AiClient).to(receive(:new).and_return(ai_client))
+ allow(ai_client).to(receive(:chat).and_return(ai_response))
end
it "returns sql and explanation from the AI" do
- result = service.call("show me all users", %w[users posts])
- expect(result).to eq(ai_response)
+ result = service.call("show me all users", ["users", "posts"])
+ expect(result).to(eq(ai_response))
end
it "passes messages with system and user roles" do
ai_client = instance_double(MysqlGenius::AiClient)
- allow(MysqlGenius::AiClient).to receive(:new).and_return(ai_client)
+ allow(MysqlGenius::AiClient).to(receive(:new).and_return(ai_client))
- expect(ai_client).to receive(:chat) do |messages:|
- expect(messages.length).to eq(2)
- expect(messages[0][:role]).to eq("system")
- expect(messages[1][:role]).to eq("user")
- expect(messages[1][:content]).to eq("show me all users")
+ expect(ai_client).to(receive(:chat)) do |messages:|
+ expect(messages.length).to(eq(2))
+ expect(messages[0][:role]).to(eq("system"))
+ expect(messages[1][:role]).to(eq("user"))
+ expect(messages[1][:content]).to(eq("show me all users"))
ai_response
end
- service.call("show me all users", %w[users posts])
+ service.call("show me all users", ["users", "posts"])
end
it "includes schema description in the system prompt" do
ai_client = instance_double(MysqlGenius::AiClient)
- allow(MysqlGenius::AiClient).to receive(:new).and_return(ai_client)
+ allow(MysqlGenius::AiClient).to(receive(:new).and_return(ai_client))
- expect(ai_client).to receive(:chat) do |messages:|
+ expect(ai_client).to(receive(:chat)) do |messages:|
system_prompt = messages[0][:content]
- expect(system_prompt).to include("users")
- expect(system_prompt).to include("id (integer)")
- expect(system_prompt).to include("name (string)")
+ expect(system_prompt).to(include("users"))
+ expect(system_prompt).to(include("id (integer)"))
+ expect(system_prompt).to(include("name (string)"))
ai_response
end
- service.call("test", %w[users])
+ service.call("test", ["users"])
end
it "includes custom domain context when configured" do
MysqlGenius.configuration.ai_system_context = "This is an e-commerce DB"
ai_client = instance_double(MysqlGenius::AiClient)
- allow(MysqlGenius::AiClient).to receive(:new).and_return(ai_client)
+ allow(MysqlGenius::AiClient).to(receive(:new).and_return(ai_client))
- expect(ai_client).to receive(:chat) do |messages:|
- expect(messages[0][:content]).to include("e-commerce DB")
+ expect(ai_client).to(receive(:chat)) do |messages:|
+ expect(messages[0][:content]).to(include("e-commerce DB"))
ai_response
end
- service.call("test", %w[users])
+ service.call("test", ["users"])
end
it "only includes tables that exist in the connection" do
ai_client = instance_double(MysqlGenius::AiClient)
- allow(MysqlGenius::AiClient).to receive(:new).and_return(ai_client)
+ allow(MysqlGenius::AiClient).to(receive(:new).and_return(ai_client))
- expect(ai_client).to receive(:chat) do |messages:|
+ expect(ai_client).to(receive(:chat)) do |messages:|
system_prompt = messages[0][:content]
- expect(system_prompt).not_to include("nonexistent_table")
+ expect(system_prompt).not_to(include("nonexistent_table"))
ai_response
end
- service.call("test", %w[users nonexistent_table])
+ service.call("test", ["users", "nonexistent_table"])
end
end
end
diff --git a/spec/mysql_genius/configuration_spec.rb b/spec/mysql_genius/configuration_spec.rb
index f14b85b..19d8b48 100644
--- a/spec/mysql_genius/configuration_spec.rb
+++ b/spec/mysql_genius/configuration_spec.rb
@@ -1,63 +1,65 @@
-RSpec.describe MysqlGenius::Configuration do
+# frozen_string_literal: true
+
+RSpec.describe(MysqlGenius::Configuration) do
subject(:config) { described_class.new }
describe "defaults" do
it "has sensible blocked tables" do
- expect(config.blocked_tables).to include("sessions", "schema_migrations")
+ expect(config.blocked_tables).to(include("sessions", "schema_migrations"))
end
it "has default masked column patterns" do
- expect(config.masked_column_patterns).to include("password", "token", "secret")
+ expect(config.masked_column_patterns).to(include("password", "token", "secret"))
end
it "defaults max_row_limit to 1000" do
- expect(config.max_row_limit).to eq(1000)
+ expect(config.max_row_limit).to(eq(1000))
end
it "defaults default_row_limit to 25" do
- expect(config.default_row_limit).to eq(25)
+ expect(config.default_row_limit).to(eq(25))
end
it "defaults query_timeout_ms to 30000" do
- expect(config.query_timeout_ms).to eq(30_000)
+ expect(config.query_timeout_ms).to(eq(30_000))
end
it "defaults slow_query_threshold_ms to 250" do
- expect(config.slow_query_threshold_ms).to eq(250)
+ expect(config.slow_query_threshold_ms).to(eq(250))
end
it "defaults authenticate to allow all" do
- expect(config.authenticate.call(nil)).to be true
+ expect(config.authenticate.call(nil)).to(be(true))
end
it "has no featured tables by default" do
- expect(config.featured_tables).to be_empty
+ expect(config.featured_tables).to(be_empty)
end
it "has no default columns by default" do
- expect(config.default_columns).to be_empty
+ expect(config.default_columns).to(be_empty)
end
end
describe "#ai_enabled?" do
it "returns false when nothing is configured" do
- expect(config.ai_enabled?).to be false
+ expect(config.ai_enabled?).to(be(false))
end
it "returns true when ai_endpoint and ai_api_key are set" do
config.ai_endpoint = "https://api.example.com/v1/chat"
config.ai_api_key = "sk-test"
- expect(config.ai_enabled?).to be true
+ expect(config.ai_enabled?).to(be(true))
end
it "returns true when ai_client is set" do
config.ai_client = ->(**) { {} }
- expect(config.ai_enabled?).to be true
+ expect(config.ai_enabled?).to(be(true))
end
it "returns false when only ai_endpoint is set" do
config.ai_endpoint = "https://api.example.com/v1/chat"
- expect(config.ai_enabled?).to be false
+ expect(config.ai_enabled?).to(be(false))
end
end
@@ -65,11 +67,11 @@
it "yields the configuration" do
MysqlGenius.configure do |c|
c.max_row_limit = 500
- c.blocked_tables = %w[users]
+ c.blocked_tables = ["users"]
end
- expect(MysqlGenius.configuration.max_row_limit).to eq(500)
- expect(MysqlGenius.configuration.blocked_tables).to eq(%w[users])
+ expect(MysqlGenius.configuration.max_row_limit).to(eq(500))
+ expect(MysqlGenius.configuration.blocked_tables).to(eq(["users"]))
end
end
end
diff --git a/spec/mysql_genius/slow_query_monitor_spec.rb b/spec/mysql_genius/slow_query_monitor_spec.rb
index 2943926..be70b53 100644
--- a/spec/mysql_genius/slow_query_monitor_spec.rb
+++ b/spec/mysql_genius/slow_query_monitor_spec.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
require "spec_helper"
require "active_support/notifications"
require "mysql_genius/slow_query_monitor"
@@ -12,10 +14,10 @@ def ltrim(key, start, stop); end
end
end
-RSpec.describe MysqlGenius::SlowQueryMonitor do
+RSpec.describe(MysqlGenius::SlowQueryMonitor) do
describe ".redis_key" do
it "returns the expected key" do
- expect(described_class.redis_key).to eq("mysql_genius:slow_queries")
+ expect(described_class.redis_key).to(eq("mysql_genius:slow_queries"))
end
end
@@ -28,16 +30,20 @@ def ltrim(key, start, stop); end
c.slow_query_threshold_ms = 250
end
- allow(Redis).to receive(:new).and_return(redis)
- allow(redis).to receive(:lpush)
- allow(redis).to receive(:ltrim)
+ allow(Redis).to(receive(:new).and_return(redis))
+ allow(redis).to(receive(:lpush))
+ allow(redis).to(receive(:ltrim))
# Clear any existing subscriptions
- ActiveSupport::Notifications.unsubscribe("sql.active_record") rescue nil
+ begin
+ ActiveSupport::Notifications.unsubscribe("sql.active_record")
+ rescue
+ nil
+ end
end
it "subscribes to sql.active_record notifications" do
- expect(ActiveSupport::Notifications).to receive(:subscribe).with("sql.active_record")
+ expect(ActiveSupport::Notifications).to(receive(:subscribe).with("sql.active_record"))
described_class.subscribe!
end
@@ -59,42 +65,42 @@ def fire_callback(callback, duration_sec:, sql:, name: "SQL")
end
it "captures slow SELECT queries" do
- expect(redis).to receive(:lpush).with("mysql_genius:slow_queries", anything)
- expect(redis).to receive(:ltrim).with("mysql_genius:slow_queries", 0, 199)
+ expect(redis).to(receive(:lpush).with("mysql_genius:slow_queries", anything))
+ expect(redis).to(receive(:ltrim).with("mysql_genius:slow_queries", 0, 199))
fire_callback(callback, duration_sec: 0.5, sql: "SELECT * FROM users", name: "User Load")
end
it "ignores queries below the threshold" do
- expect(redis).not_to receive(:lpush)
+ expect(redis).not_to(receive(:lpush))
fire_callback(callback, duration_sec: 0.01, sql: "SELECT * FROM users", name: "User Load")
end
it "ignores non-SELECT queries" do
- expect(redis).not_to receive(:lpush)
+ expect(redis).not_to(receive(:lpush))
fire_callback(callback, duration_sec: 1.0, sql: "INSERT INTO users VALUES (1)")
end
it "ignores EXPLAIN queries" do
- expect(redis).not_to receive(:lpush)
+ expect(redis).not_to(receive(:lpush))
fire_callback(callback, duration_sec: 1.0, sql: "SELECT * FROM users EXPLAIN something")
end
it "ignores SCHEMA queries" do
- expect(redis).not_to receive(:lpush)
+ expect(redis).not_to(receive(:lpush))
fire_callback(callback, duration_sec: 1.0, sql: "SELECT * FROM SCHEMA tables", name: "SCHEMA")
end
it "gracefully handles Redis errors" do
- allow(redis).to receive(:lpush).and_raise(StandardError.new("Connection refused"))
+ allow(redis).to(receive(:lpush).and_raise(StandardError.new("Connection refused")))
- expect {
+ expect do
fire_callback(callback, duration_sec: 1.0, sql: "SELECT * FROM users")
- }.not_to raise_error
+ end.not_to(raise_error)
end
end
end
diff --git a/spec/mysql_genius/sql_validation_spec.rb b/spec/mysql_genius/sql_validator_spec.rb
similarity index 68%
rename from spec/mysql_genius/sql_validation_spec.rb
rename to spec/mysql_genius/sql_validator_spec.rb
index 6fcfadd..86b1f05 100644
--- a/spec/mysql_genius/sql_validation_spec.rb
+++ b/spec/mysql_genius/sql_validator_spec.rb
@@ -1,6 +1,8 @@
-RSpec.describe MysqlGenius::SqlValidator do
- let(:blocked_tables) { %w[sessions authentication_tokens] }
- let(:all_tables) { %w[users posts sessions authentication_tokens] }
+# frozen_string_literal: true
+
+RSpec.describe(MysqlGenius::SqlValidator) do
+ let(:blocked_tables) { ["sessions", "authentication_tokens"] }
+ let(:all_tables) { ["users", "posts", "sessions", "authentication_tokens"] }
let(:connection) do
double("connection", tables: all_tables)
end
@@ -11,120 +13,120 @@ def validate(sql)
describe ".validate" do
it "rejects blank queries" do
- expect(validate("")).to eq("Please enter a query.")
- expect(validate(nil)).to eq("Please enter a query.")
+ expect(validate("")).to(eq("Please enter a query."))
+ expect(validate(nil)).to(eq("Please enter a query."))
end
it "rejects non-SELECT queries" do
- expect(validate("DELETE FROM users")).to eq("Only SELECT queries are allowed.")
+ expect(validate("DELETE FROM users")).to(eq("Only SELECT queries are allowed."))
end
it "allows SELECT queries" do
- expect(validate("SELECT * FROM users")).to be_nil
+ expect(validate("SELECT * FROM users")).to(be_nil)
end
it "allows WITH (CTE) queries" do
- expect(validate("WITH cte AS (SELECT 1) SELECT * FROM cte")).to be_nil
+ expect(validate("WITH cte AS (SELECT 1) SELECT * FROM cte")).to(be_nil)
end
it "rejects INSERT statements" do
- expect(validate("SELECT * FROM users; INSERT INTO users VALUES (1)")).to include("INSERT")
+ expect(validate("SELECT * FROM users; INSERT INTO users VALUES (1)")).to(include("INSERT"))
end
it "rejects DROP statements" do
- expect(validate("SELECT * FROM users; DROP TABLE users")).to include("DROP")
+ expect(validate("SELECT * FROM users; DROP TABLE users")).to(include("DROP"))
end
it "rejects queries against blocked tables" do
result = validate("SELECT * FROM sessions")
- expect(result).to include("sessions")
+ expect(result).to(include("sessions"))
end
it "rejects queries accessing information_schema" do
result = validate("SELECT * FROM information_schema.tables")
- expect(result).to include("system schemas")
+ expect(result).to(include("system schemas"))
end
it "rejects queries accessing mysql system schema" do
result = validate("SELECT * FROM mysql.user")
- expect(result).to include("system schemas")
+ expect(result).to(include("system schemas"))
end
it "strips SQL comments before validation" do
- expect(validate("SELECT * FROM users -- safe query")).to be_nil
+ expect(validate("SELECT * FROM users -- safe query")).to(be_nil)
end
end
describe ".extract_table_references" do
it "extracts tables from FROM clause" do
tables = described_class.extract_table_references("SELECT * FROM users", connection)
- expect(tables).to include("users")
+ expect(tables).to(include("users"))
end
it "extracts tables from JOIN clause" do
tables = described_class.extract_table_references("SELECT * FROM users JOIN posts ON users.id = posts.user_id", connection)
- expect(tables).to include("users", "posts")
+ expect(tables).to(include("users", "posts"))
end
it "extracts comma-separated tables" do
tables = described_class.extract_table_references("SELECT * FROM users, posts", connection)
- expect(tables).to include("users", "posts")
+ expect(tables).to(include("users", "posts"))
end
it "handles backtick-quoted table names" do
tables = described_class.extract_table_references("SELECT * FROM `users`", connection)
- expect(tables).to include("users")
+ expect(tables).to(include("users"))
end
end
describe ".apply_row_limit" do
it "appends LIMIT when none exists" do
result = described_class.apply_row_limit("SELECT * FROM users", 25)
- expect(result).to eq("SELECT * FROM users LIMIT 25")
+ expect(result).to(eq("SELECT * FROM users LIMIT 25"))
end
it "caps existing LIMIT to the configured max" do
result = described_class.apply_row_limit("SELECT * FROM users LIMIT 5000", 25)
- expect(result).to eq("SELECT * FROM users LIMIT 25")
+ expect(result).to(eq("SELECT * FROM users LIMIT 25"))
end
it "preserves lower LIMIT" do
result = described_class.apply_row_limit("SELECT * FROM users LIMIT 10", 25)
- expect(result).to eq("SELECT * FROM users LIMIT 10")
+ expect(result).to(eq("SELECT * FROM users LIMIT 10"))
end
it "handles LIMIT with offset" do
result = described_class.apply_row_limit("SELECT * FROM users LIMIT 100, 5000", 25)
- expect(result).to eq("SELECT * FROM users LIMIT 100, 25")
+ expect(result).to(eq("SELECT * FROM users LIMIT 100, 25"))
end
it "strips trailing semicolons" do
result = described_class.apply_row_limit("SELECT * FROM users;", 25)
- expect(result).to eq("SELECT * FROM users LIMIT 25")
+ expect(result).to(eq("SELECT * FROM users LIMIT 25"))
end
end
describe ".masked_column?" do
- let(:patterns) { %w[password secret digest token] }
+ let(:patterns) { ["password", "secret", "digest", "token"] }
it "masks columns containing 'password'" do
- expect(described_class.masked_column?("encrypted_password", patterns)).to be true
+ expect(described_class.masked_column?("encrypted_password", patterns)).to(be(true))
end
it "masks columns containing 'token'" do
- expect(described_class.masked_column?("reset_token", patterns)).to be true
+ expect(described_class.masked_column?("reset_token", patterns)).to(be(true))
end
it "masks columns containing 'secret'" do
- expect(described_class.masked_column?("api_secret", patterns)).to be true
+ expect(described_class.masked_column?("api_secret", patterns)).to(be(true))
end
it "does not mask normal columns" do
- expect(described_class.masked_column?("email", patterns)).to be false
+ expect(described_class.masked_column?("email", patterns)).to(be(false))
end
it "is case insensitive" do
- expect(described_class.masked_column?("Password_Hash", patterns)).to be true
+ expect(described_class.masked_column?("Password_Hash", patterns)).to(be(true))
end
end
end
diff --git a/spec/mysql_genius_spec.rb b/spec/mysql_genius_spec.rb
index 685a6ee..f005965 100644
--- a/spec/mysql_genius_spec.rb
+++ b/spec/mysql_genius_spec.rb
@@ -1,5 +1,7 @@
-RSpec.describe MysqlGenius do
+# frozen_string_literal: true
+
+RSpec.describe(MysqlGenius) do
it "has a version number" do
- expect(MysqlGenius::VERSION).not_to be_nil
+ expect(MysqlGenius::VERSION).not_to(be_nil)
end
end
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 1dcf0ed..f5a9c1f 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,14 +1,18 @@
+# frozen_string_literal: true
+
require "bundler/setup"
require "mysql_genius"
-$LOAD_PATH.unshift File.expand_path("../app/services", __dir__)
+$LOAD_PATH.unshift(File.expand_path("../app/services", __dir__))
# Stub ActiveRecord::Base.connection for service specs (avoids loading full ActiveRecord
# which has compatibility issues with system Ruby 2.6)
unless defined?(ActiveRecord::Base)
module ActiveRecord
class Base
- def self.connection; end
+ class << self
+ def connection; end
+ end
end
end
end
@@ -17,11 +21,11 @@ def self.connection; end
config.example_status_persistence_file_path = ".rspec_status"
config.disable_monkey_patching!
- config.expect_with :rspec do |c|
+ config.expect_with(:rspec) do |c|
c.syntax = :expect
end
- config.before(:each) do
+ config.before do
MysqlGenius.reset_configuration!
end
end