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

#available_connectionsObject

Get list of available connections



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
89
90
91
92
93
94
95
96
97
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 64

def available_connections
  connections = Dbviewer.configuration.database_connections.map do |key, config|
    # Try to determine the adapter name if it's not already stored
    adapter_name = nil
    if config[:adapter_name].present?
      adapter_name = config[:adapter_name]
    elsif config[:connection].present?
      begin
        adapter_name = config[:connection].connection.adapter_name
      rescue => e
        Rails.logger.error("Error getting adapter name: #{e.message}")
      end
    end

    {
      key: key,
      name: config[:name] || key.to_s.humanize,
      adapter_name: adapter_name,
      current: key.to_sym == current_connection_key.to_sym
    }
  end

  # Ensure at least one connection is marked as current
  unless connections.any? { |c| c[:current] }
    # If no connection is current, mark the first one as current
    if connections.any?
      connections.first[:current] = true
      # Also update the session
      session[:dbviewer_connection] = connections.first[:key]
    end
  end

  connections
end

#current_connection_keyObject

Get the current active connection key



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

def current_connection_key
  # Get the connection key from the session or fall back to the default
  key = session[:dbviewer_connection] || Dbviewer.configuration.current_connection

  # Ensure the key actually exists in our configured connections
  if key && Dbviewer.configuration.database_connections.key?(key.to_sym)
    return key.to_sym
  end

  # If the key doesn't exist, fall back to any available connection
  first_key = Dbviewer.configuration.database_connections.keys.first
  if first_key
    session[:dbviewer_connection] = first_key # Update the session
    return first_key
  end

  # If there are no connections configured, use a default key
  # This should never happen in normal operation, but it's a safety measure
  :default
end

#database_managerObject

Initialize the database manager with the current connection



100
101
102
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 100

def database_manager
  @database_manager = ::Dbviewer::Database::Manager.new(current_connection_key)
end

#fetch_database_analyticsObject

Gather database analytics information



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 183

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



216
217
218
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 216

def fetch_filtered_record_count(table_name, column_filters)
  database_manager.filtered_record_count(table_name, column_filters)
end

#fetch_table_columns(table_name) ⇒ Object

Get column information for a specific table



201
202
203
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 201

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)



229
230
231
232
233
234
235
236
237
238
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 229

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



206
207
208
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 206

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



211
212
213
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 211

def fetch_table_records(table_name, query_params)
  database_manager.table_records(table_name, query_params)
end

#fetch_table_relationshipsObject

Fetch relationships between tables for ERD visualization



241
242
243
244
245
246
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 241

def fetch_table_relationships
  # Use functional approach: flat_map to extract all relationships from all tables
  @tables.flat_map do |table|
    (table[:name])
  end
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



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 159

def fetch_tables(include_record_counts = false)
  database_manager.tables.map do |table_name|
    table_stats = {
      name: table_name
    }

    # Only fetch record count if specifically requested
    if include_record_counts
      begin
        table_stats[:record_count] = database_manager.record_count(table_name)
      rescue => e
        Rails.logger.error("Error fetching record count for #{table_name}: #{e.message}")
        table_stats[:record_count] = 0
      end
    end

    table_stats
  end
rescue => e
  Rails.logger.error("Error fetching tables: #{e.message}")
  []
end

#get_adapter_nameObject

Get the name of the current database adapter



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

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

#get_database_nameObject

Get the name of the current database



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 111

def get_database_name
  # First check if this connection has a name in the configuration
  current_conn_config = Dbviewer.configuration.database_connections[current_connection_key]
  if current_conn_config && current_conn_config[:name].present?
    return current_conn_config[:name]
  end

  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 = database_manager.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

#safe_quote_table_name(table_name) ⇒ Object

Safely quote a table name, with fallback



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

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

#switch_connection(connection_key) ⇒ Object

Set the current connection to use



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 35

def switch_connection(connection_key)
  connection_key = connection_key.to_sym if connection_key.respond_to?(:to_sym)

  if connection_key && Dbviewer.configuration.database_connections.key?(connection_key)
    session[:dbviewer_connection] = connection_key
    # Clear the database manager to force it to be recreated with the new connection
    @database_manager = nil
    return true
  else
    # If the connection key doesn't exist, reset to default connection
    if Dbviewer.configuration.database_connections.key?(Dbviewer.configuration.current_connection)
      session[:dbviewer_connection] = Dbviewer.configuration.current_connection
      @database_manager = nil
      return true
    else
      # If even the default connection isn't valid, try the first available connection
      first_key = Dbviewer.configuration.database_connections.keys.first
      if first_key
        session[:dbviewer_connection] = first_key
        @database_manager = nil
        return true
      end
    end
  end

  false # Return false if we couldn't set a valid connection
end

#table_query_operationsObject

Initialize the table query operations manager This gives direct access to table query operations when needed



106
107
108
# File 'app/controllers/concerns/dbviewer/database_operations.rb', line 106

def table_query_operations
  @table_query_operations ||= database_manager.table_query_operations
end