Module: Dbviewer::DatabaseOperations

Extended by:
ActiveSupport::Concern
Included in:
ApplicationController
Defined in:
app/controllers/concerns/dbviewer/database_operations.rb

Instance Method Summary collapse

Instance Method Details

#calculate_schema_sizeObject

Calculate approximate schema size



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 91

def calculate_schema_size
  adapter = database_manager.connection.adapter_name.downcase

  case adapter
  when /mysql/
    query = <<-SQL
      SELECT
        SUM(data_length + index_length) AS size
      FROM
        information_schema.TABLES
      WHERE
        table_schema = DATABASE()
    SQL
    result = database_manager.execute_query(query).first
    result ? result["size"].to_i : nil
  when /postgres/
    query = <<-SQL
      SELECT pg_database_size(current_database()) AS size
    SQL
    result = database_manager.execute_query(query).first
    result ? result["size"].to_i : nil
  when /sqlite/
    # For SQLite, we need to use the special PRAGMA method without LIMIT
    # Get page count
    page_count_result = database_manager.execute_sqlite_pragma("page_count")
    page_count = page_count_result.first.values.first.to_i

    # Get page size
    page_size_result = database_manager.execute_sqlite_pragma("page_size")
    page_size = page_size_result.first.values.first.to_i

    # Calculate total size
    page_count * page_size
  else
    nil # Unsupported database type for size calculation
  end
rescue => e
  Rails.logger.error("Error calculating database size: #{e.message}")
  nil
end

#current_table?(table_name) ⇒ Boolean

Helper to check if this is the current table in the UI

Returns:

  • (Boolean)


230
231
232
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 230

def current_table?(table_name)
  params[:id] == table_name
end

#database_managerObject

Initialize the database manager



10
11
12
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 10

def database_manager
  @database_manager ||= ::Dbviewer::DatabaseManager.new
end

#execute_queryObject

Execute the prepared SQL query



218
219
220
221
222
223
224
225
226
227
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 218

def execute_query
  begin
    @records = database_manager.execute_query(@query)
    @error = nil
  rescue => e
    @records = nil
    @error = e.message
    Rails.logger.error("SQL Query Error: #{e.message} for query: #{@query}")
  end
end

#export_table_to_csv(table_name, limit = 10000, include_headers = true) ⇒ Object

Export table data to CSV



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
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 235

def export_table_to_csv(table_name, limit = 10000, include_headers = true)
  require "csv"

  begin
    records = database_manager.table_records(
      table_name,
      1, # First page
      nil, # Default sorting
      "asc",
      limit # Limit number of records
    )

    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
  rescue => e
    Rails.logger.error("CSV Export error for table #{table_name}: #{e.message}")
    raise "Error exporting to CSV: #{e.message}"
  end
end

#fetch_database_analyticsObject

Gather database analytics information



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 56

def fetch_database_analytics
  # For analytics, we do need record counts
  tables = fetch_tables_with_stats(include_record_counts: true)

  # Calculate overall statistics
  analytics = {
    total_tables: tables.size,
    total_records: tables.sum { |t| t[:record_count] },
    total_columns: tables.sum { |t| t[:columns_count] },
    largest_tables: tables.sort_by { |t| -t[:record_count] }.first(5),
    widest_tables: tables.sort_by { |t| -t[:columns_count] }.first(5),
    empty_tables: tables.select { |t| t[:record_count] == 0 }
  }

  # Calculate schema size if possible
  begin
    analytics[:schema_size] = calculate_schema_size
  rescue => e
    Rails.logger.error("Error calculating schema size: #{e.message}")
    analytics[:schema_size] = nil
  end

  # Calculate average rows per table
  if tables.any?
    analytics[:avg_records_per_table] = (analytics[:total_records].to_f / tables.size).round(1)
    analytics[:avg_columns_per_table] = (analytics[:total_columns].to_f / tables.size).round(1)
  else
    analytics[:avg_records_per_table] = 0
    analytics[:avg_columns_per_table] = 0
  end

  analytics
end

#fetch_table_columns(table_name) ⇒ Object

Get column information for a specific table



133
134
135
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 133

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)



162
163
164
165
166
167
168
169
170
171
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 162

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.message}")
    {}
  end
end

#fetch_table_record_count(table_name) ⇒ Object

Get the total number of records in a table



138
139
140
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 138

def fetch_table_record_count(table_name)
  database_manager.table_count(table_name)
end

#fetch_table_records(table_name) ⇒ Object

Fetch records for a table with pagination and sorting



143
144
145
146
147
148
149
150
151
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 143

def fetch_table_records(table_name)
  database_manager.table_records(
    table_name,
    @current_page,
    @order_by,
    @order_direction,
    @per_page
  )
end

#fetch_table_relationshipsObject

Fetch relationships between tables for ERD visualization



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
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 174

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.message}")
    end
  end

  relationships
end

#fetch_tables_with_stats(include_record_counts = false) ⇒ Object

Fetch all tables with their stats By default, don’t include record counts for better performance on sidebar



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 41

def fetch_tables_with_stats(include_record_counts = false)
  database_manager.tables.map do |table_name|
    table_stats = {
      name: table_name,
      columns_count: database_manager.column_count(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_database_nameObject

Get the name of the current database



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 15

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.message}")
  "Database"
end

#prepare_queryObject

Prepare the SQL query - either from params or default



203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 203

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



154
155
156
157
158
159
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 154

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.message}")
  table_name
end