Module: Dbviewer::DatabaseOperations
- Extended by:
- ActiveSupport::Concern
- Included in:
- ApplicationController
- Defined in:
- app/controllers/concerns/dbviewer/database_operations.rb
Instance Method Summary collapse
-
#current_table?(table_name) ⇒ Boolean
Helper to check if this is the current table in the UI.
-
#database_manager ⇒ Object
Initialize the database manager.
-
#execute_query ⇒ Object
Execute the prepared SQL query.
-
#export_table_to_csv(table_name, query_params = nil, include_headers = true) ⇒ Object
Export table data to CSV.
-
#fetch_database_analytics ⇒ Object
Gather database analytics information.
-
#fetch_filtered_record_count(table_name, column_filters) ⇒ Object
Get filtered record count for a table.
-
#fetch_mini_erd_for_table(table_name) ⇒ Object
Get mini ERD data for a specific table and its relationships.
-
#fetch_table_columns(table_name) ⇒ Object
Get column information for a specific table.
-
#fetch_table_metadata(table_name) ⇒ Object
Get table metadata for display (e.g., primary key, foreign keys, indexes).
-
#fetch_table_record_count(table_name) ⇒ Object
Get the total number of records in a table.
-
#fetch_table_records(table_name, query_params) ⇒ Object
Fetch records for a table with pagination and sorting.
-
#fetch_table_relationships ⇒ Object
Fetch relationships between tables for ERD visualization.
-
#fetch_tables(include_record_counts = false) ⇒ Object
Fetch all tables with their stats By default, don’t include record counts for better performance on sidebar.
-
#get_adapter_name ⇒ Object
Get the name of the current database adapter.
-
#get_database_name ⇒ Object
Get the name of the current database.
-
#prepare_query ⇒ Object
Prepare the SQL query - either from params or default.
-
#safe_quote_table_name(table_name) ⇒ Object
Safely quote a table name, with fallback.
-
#table_query_operations ⇒ Object
Initialize the table query operations manager This gives direct access to table query operations when needed.
Instance Method Details
#current_table?(table_name) ⇒ Boolean
Helper to check if this is the current table in the UI
317 318 319 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 317 def current_table?(table_name) params[:id] == table_name end |
#database_manager ⇒ Object
Initialize the database manager
12 13 14 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 12 def database_manager @database_manager ||= ::Dbviewer::Database::Manager.new end |
#execute_query ⇒ Object
Execute the prepared SQL query
305 306 307 308 309 310 311 312 313 314 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 305 def execute_query begin @records = database_manager.execute_query(@query) @error = nil rescue => e @records = nil @error = e. Rails.logger.error("SQL Query Error: #{e.} for query: #{@query}") end end |
#export_table_to_csv(table_name, query_params = nil, include_headers = true) ⇒ Object
Export table data to CSV
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 322 def export_table_to_csv(table_name, query_params = nil, include_headers = true) records = database_manager.table_query_operations.table_records(table_name, query_params) csv_data = CSV.generate do |csv| # Add headers if requested csv << records.columns if include_headers # Add rows records.rows.each do |row| csv << row.map { |cell| format_csv_value(cell) } end end csv_data end |
#fetch_database_analytics ⇒ Object
Gather database analytics information
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 79 def fetch_database_analytics # For analytics, we do need record counts tables = fetch_tables(include_record_counts: true) # Calculate overall statistics analytics = { total_tables: tables.size, total_records: tables.sum { |t| t[:record_count] }, largest_tables: tables.sort_by { |t| -t[:record_count] }.first(10), empty_tables: tables.select { |t| t[:record_count] == 0 } } # Calculate schema size if possible analytics[:schema_size] = calculate_schema_size analytics end |
#fetch_filtered_record_count(table_name, column_filters) ⇒ Object
Get filtered record count for a table
112 113 114 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 112 def fetch_filtered_record_count(table_name, column_filters) database_manager.filtered_record_count(table_name, column_filters) end |
#fetch_mini_erd_for_table(table_name) ⇒ Object
Get mini ERD data for a specific table and its relationships
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 166 def fetch_mini_erd_for_table(table_name) = [] relationships = [] # Validate the table exists unless database_manager.tables.include?(table_name) Rails.logger.error("[DBViewer] Table not found for mini ERD: #{table_name}") return { tables: [], relationships: [], error: "Table '#{table_name}' not found in the database" } end # Add current table << { name: table_name } Rails.logger.info("[DBViewer] Generating mini ERD for table: #{table_name}") # Get foreign keys from this table to others (outgoing relationships) begin = (table_name) Rails.logger.debug("[DBViewer] Table metadata: #{.inspect}") if && [:foreign_keys].present? [:foreign_keys].each do |fk| # Ensure all required fields are present next unless fk[:to_table].present? && fk[:column].present? # Sanitize table and column names for display from_table = table_name.to_s to_table = fk[:to_table].to_s from_column = fk[:column].to_s to_column = fk[:primary_key].to_s.presence || "id" relationship_name = fk[:name].to_s.presence || "#{from_table}_to_#{to_table}" relationship = { from_table: from_table, to_table: to_table, from_column: from_column, to_column: to_column, name: relationship_name, direction: "outgoing" } relationships << relationship Rails.logger.debug("[DBViewer] Added outgoing relationship: #{relationship.inspect}") # Add the related table if not already included unless .any? { |t| t[:name] == to_table } << { name: to_table } end end end rescue => e Rails.logger.error("[DBViewer] Error fetching outgoing relationships for #{table_name}: #{e.}") Rails.logger.error(e.backtrace.join("\n")) end # Get foreign keys from other tables to this one (incoming relationships) begin database_manager.tables.each do |other_table_name| next if other_table_name == table_name # Skip self begin = (other_table_name) if && [:foreign_keys].present? [:foreign_keys].each do |fk| if fk[:to_table] == table_name # Ensure all required fields are present next unless fk[:column].present? # Sanitize table and column names for display from_table = other_table_name.to_s to_table = table_name.to_s from_column = fk[:column].to_s to_column = fk[:primary_key].to_s.presence || "id" relationship_name = fk[:name].to_s.presence || "#{from_table}_to_#{to_table}" relationship = { from_table: from_table, to_table: to_table, from_column: from_column, to_column: to_column, name: relationship_name, direction: "incoming" } relationships << relationship Rails.logger.debug("[DBViewer] Added incoming relationship: #{relationship.inspect}") # Add the related table if not already included unless .any? { |t| t[:name] == from_table } << { name: from_table } end end end end rescue => e Rails.logger.error("[DBViewer] Error processing relationships for table #{other_table_name}: #{e.}") # Continue to the next table end end rescue => e Rails.logger.error("[DBViewer] Error fetching incoming relationships for #{table_name}: #{e.}") Rails.logger.error(e.backtrace.join("\n")) end # If no relationships were found, make sure to still include at least the current table if relationships.empty? Rails.logger.info("[DBViewer] No relationships found for table: #{table_name}") end result = { tables: , relationships: relationships, timestamp: Time.now.to_i } Rails.logger.info("[DBViewer] Mini ERD data generated: #{.length} tables, #{relationships.length} relationships") result end |
#fetch_table_columns(table_name) ⇒ Object
Get column information for a specific table
97 98 99 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 97 def fetch_table_columns(table_name) database_manager.table_columns(table_name) end |
#fetch_table_metadata(table_name) ⇒ Object
Get table metadata for display (e.g., primary key, foreign keys, indexes)
125 126 127 128 129 130 131 132 133 134 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 125 def (table_name) return {} unless database_manager.respond_to?(:table_metadata) begin database_manager.(table_name) rescue => e Rails.logger.warn("Failed to fetch table metadata: #{e.}") {} end end |
#fetch_table_record_count(table_name) ⇒ Object
Get the total number of records in a table
102 103 104 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 102 def fetch_table_record_count(table_name) database_manager.table_count(table_name) end |
#fetch_table_records(table_name, query_params) ⇒ Object
Fetch records for a table with pagination and sorting
107 108 109 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 107 def fetch_table_records(table_name, query_params) database_manager.table_records(table_name, query_params) end |
#fetch_table_relationships ⇒ Object
Fetch relationships between tables for ERD visualization
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 137 def fetch_table_relationships relationships = [] @tables.each do |table| table_name = table[:name] # Get foreign keys defined in this table pointing to others begin = database_manager.(table_name) if && [:foreign_keys].present? [:foreign_keys].each do |fk| relationships << { from_table: table_name, to_table: fk[:to_table], from_column: fk[:column], to_column: fk[:primary_key], name: fk[:name] } end end rescue => e Rails.logger.error("Error fetching relationships for #{table_name}: #{e.}") end end relationships end |
#fetch_tables(include_record_counts = false) ⇒ Object
Fetch all tables with their stats By default, don’t include record counts for better performance on sidebar
65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 65 def fetch_tables(include_record_counts = false) database_manager.tables.map do |table_name| table_stats = { name: table_name } # Only fetch record counts if explicitly requested table_stats[:record_count] = database_manager.record_count(table_name) if include_record_counts table_stats end end |
#get_adapter_name ⇒ Object
Get the name of the current database adapter
48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 48 def get_adapter_name adapter_name = database_manager.connection.adapter_name.downcase adapter_mappings = { /mysql/i => "MySQL", /postgres/i => "PostgreSQL", /sqlite/i => "SQLite", /oracle/i => "Oracle", /sqlserver|mssql/i => "SQL Server" } adapter_mappings.find { |pattern, _| adapter_name =~ pattern }&.last || adapter_name.titleize rescue => e Rails.logger.error("Error retrieving adapter name: #{e.}") "Unknown" end |
#get_database_name ⇒ Object
Get the name of the current database
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 23 def get_database_name adapter = database_manager.connection.adapter_name.downcase case adapter when /mysql/ query = "SELECT DATABASE() as db_name" result = database_manager.execute_query(query).first result ? result["db_name"] : "Database" when /postgres/ query = "SELECT current_database() as db_name" result = database_manager.execute_query(query).first result ? result["db_name"] : "Database" when /sqlite/ # For SQLite, extract the database name from the connection_config database_path = ActiveRecord::Base.connection.pool.spec.config[:database] || "" File.basename(database_path, ".*") || "SQLite Database" else "Database" # Default fallback end rescue => e Rails.logger.error("Error retrieving database name: #{e.}") "Database" end |
#prepare_query ⇒ Object
Prepare the SQL query - either from params or default
290 291 292 293 294 295 296 297 298 299 300 301 302 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 290 def prepare_query quoted_table = safe_quote_table_name(@table_name) default_query = "SELECT * FROM #{quoted_table} LIMIT 100" # Use the raw query parameter, or fall back to default @query = params[:query].present? ? params[:query].to_s : default_query # Validate query for security unless ::Dbviewer::SqlValidator.safe_query?(@query) @query = default_query flash.now[:warning] = "Only SELECT queries are allowed. Your query contained potentially unsafe operations. Using default query instead." end end |
#safe_quote_table_name(table_name) ⇒ Object
Safely quote a table name, with fallback
117 118 119 120 121 122 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 117 def safe_quote_table_name(table_name) database_manager.connection.quote_table_name(table_name) rescue => e Rails.logger.warn("Failed to quote table name: #{e.}") table_name end |
#table_query_operations ⇒ Object
Initialize the table query operations manager This gives direct access to table query operations when needed
18 19 20 |
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 18 def table_query_operations @table_query_operations ||= database_manager.table_query_operations end |