Class: PgReports::DashboardController

Inherits:
ActionController::Base
  • Object
show all
Defined in:
app/controllers/pg_reports/dashboard_controller.rb

Instance Method Summary collapse

Instance Method Details

#create_migrationObject



461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 461

def create_migration
  unless PgReports.config.allow_migration_creation
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.migration_dev_only")
    }, status: :forbidden
    return
  end

  file_name = params[:file_name]
  code = params[:code]

  if file_name.blank? || code.blank?
    render json: {success: false, error: I18n.t("pg_reports.ui.errors.filename_code_required")}, status: :unprocessable_entity
    return
  end

  # Sanitize file name
  safe_file_name = file_name.gsub(/[^a-z0-9_.]/, "")
  unless safe_file_name.match?(/\A\d{14}_\w+\.rb\z/)
    render json: {success: false, error: I18n.t("pg_reports.ui.errors.invalid_filename_format")}, status: :unprocessable_entity
    return
  end

  # Find migrations directory
  migrations_path = Rails.root.join("db", "migrate")
  unless migrations_path.exist?
    render json: {success: false, error: I18n.t("pg_reports.ui.errors.migrations_dir_not_found")}, status: :unprocessable_entity
    return
  end

  file_path = migrations_path.join(safe_file_name)
  File.write(file_path, code)

  render json: {success: true, file_path: file_path.to_s, message: I18n.t("pg_reports.ui.success.migration_created")}
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#downloadObject



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
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 204

def download
  category = params[:category].to_sym
  report_key = params[:report].to_sym
  format_type = params[:format] || "txt"

  report = execute_report(category, report_key)
  filename = "#{report.title.parameterize}-#{Time.current.strftime("%Y%m%d-%H%M%S")}"

  case format_type
  when "csv"
    send_data report.to_csv,
      filename: "#{filename}.csv",
      type: "text/csv; charset=utf-8",
      disposition: "attachment"
  when "json"
    send_data report.to_a.to_json,
      filename: "#{filename}.json",
      type: "application/json; charset=utf-8",
      disposition: "attachment"
  else
    send_data report.to_text,
      filename: "#{filename}.txt",
      type: "text/plain; charset=utf-8",
      disposition: "attachment"
  end
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#download_query_monitorObject



585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 585

def download_query_monitor
  monitor = PgReports::QueryMonitor.instance

  # Allow download even when monitoring is stopped, as long as there are queries
  queries = monitor.queries
  if queries.empty?
    render json: {success: false, error: "No queries to download"}, status: :unprocessable_entity
    return
  end

  format_type = params[:format] || "txt"
  filename = "query-monitor-#{Time.current.strftime("%Y%m%d-%H%M%S")}"

  case format_type
  when "csv"
    csv_data = generate_query_monitor_csv(queries)
    send_data csv_data,
      filename: "#{filename}.csv",
      type: "text/csv; charset=utf-8",
      disposition: "attachment"
  when "json"
    send_data queries.to_json,
      filename: "#{filename}.json",
      type: "application/json; charset=utf-8",
      disposition: "attachment"
  else
    text_data = generate_query_monitor_text(queries)
    send_data text_data,
      filename: "#{filename}.txt",
      type: "text/plain; charset=utf-8",
      disposition: "attachment"
  end
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#enable_pg_stat_statementsObject



67
68
69
70
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 67

def enable_pg_stat_statements
  result = PgReports.enable_pg_stat_statements!
  render json: result
end

#execute_queryObject



309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 309

def execute_query
  query_hash = params[:query_hash]
  query_params = params[:params] || {}

  if query_hash.blank?
    render json: {success: false, error: I18n.t("pg_reports.ui.errors.query_hash_required")}, status: :unprocessable_entity
    return
  end

  # Security: Check if raw query execution is allowed
  unless PgReports.config.allow_raw_query_execution
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.query_execution_disabled")
    }, status: :forbidden
    return
  end

  # Security: Retrieve and validate query by hash
  begin
    query = retrieve_query_by_hash(query_hash)

    if query.nil?
      render json: {success: false, error: I18n.t("pg_reports.ui.errors.query_not_found_expired")}, status: :not_found
      return
    end
  rescue SecurityError => e
    render json: {success: false, error: "#{I18n.t("pg_reports.ui.errors.security_violation_prefix")} #{e.message}"}, status: :forbidden
    return
  end

  # Substitute parameters if provided
  final_query = substitute_params(query, query_params)

  # Check for remaining unsubstituted parameters
  if final_query.match?(/\$\d+/)
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.missing_parameter_values")
    }, status: :unprocessable_entity
    return
  end

  # Execute with LIMIT to prevent huge result sets
  limited_query = add_limit_if_missing(final_query, 100)

  rows = columns = nil
  total_count = 0
  truncated = false
  execution_time = nil

  with_statement_timeout do
    start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    result = ActiveRecord::Base.connection.execute(limited_query)
    end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    execution_time = ((end_time - start_time) * 1000).round(2)

    rows = result.to_a
    columns = rows.first&.keys || []
    total_count = rows.size

    # Check if we need to get total count
    if rows.size >= 100
      count_result = ActiveRecord::Base.connection.execute("SELECT COUNT(*) FROM (#{final_query}) AS count_query")
      total_count = count_result.first["count"].to_i
      truncated = total_count > 100
    end
  end

  render json: {
    success: true,
    columns: columns,
    rows: rows,
    count: rows.size,
    total_count: total_count,
    truncated: truncated,
    execution_time: execution_time
  }
rescue ActiveRecord::QueryCanceled
  render json: {success: false, error: query_timed_out_message}, status: :unprocessable_entity
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#explain_analyzeObject



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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 233

def explain_analyze
  query_hash = params[:query_hash]
  query_params = params[:params] || {}

  if query_hash.blank?
    render json: {success: false, error: I18n.t("pg_reports.ui.errors.query_hash_required")}, status: :unprocessable_entity
    return
  end

  # Security: Check if raw query execution is allowed
  unless PgReports.config.allow_raw_query_execution
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.query_execution_disabled")
    }, status: :forbidden
    return
  end

  # Security: Retrieve and validate query by hash
  begin
    query = retrieve_query_by_hash(query_hash)

    if query.nil?
      render json: {success: false, error: I18n.t("pg_reports.ui.errors.query_not_found_expired")}, status: :not_found
      return
    end
  rescue SecurityError => e
    render json: {success: false, error: "#{I18n.t("pg_reports.ui.errors.security_violation_prefix")} #{e.message}"}, status: :forbidden
    return
  end

  # Check for trigger variables (NEW, OLD) which are only available in trigger context
  if query.match?(/\b(NEW|OLD)\./i)
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.trigger_variables_not_allowed")
    }, status: :unprocessable_entity
    return
  end

  # Substitute parameters if provided
  final_query = substitute_params(query, query_params)

  # Check for remaining unsubstituted parameters
  if final_query.match?(/\$\d+/)
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.missing_parameter_values")
    }, status: :unprocessable_entity
    return
  end

  explain_output = nil
  with_statement_timeout do
    result = ActiveRecord::Base.connection.execute("EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) #{final_query}")
    explain_output = result.map { |r| r["QUERY PLAN"] }.join("\n")
  end

  # Analyze the EXPLAIN output
  analyzer = ExplainAnalyzer.new(explain_output)
  analysis = analyzer.to_h

  render json: {
    success: true,
    explain: explain_output,
    stats: analysis[:stats],
    annotated_lines: analysis[:annotated_lines],
    problems: analysis[:problems],
    summary: analysis[:summary]
  }
rescue ActiveRecord::QueryCanceled
  render json: {success: false, error: query_timed_out_message}, status: :unprocessable_entity
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#indexObject



28
29
30
31
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 28

def index
  @pg_stat_status = PgReports.pg_stat_statements_status
  @current_database = PgReports.system.current_database
end

#live_metricsObject



79
80
81
82
83
84
85
86
87
88
89
90
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
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 79

def live_metrics
  threshold = params[:long_query_threshold]&.to_i || 5

  # Check if we have access to required statistics
  begin
    data = Modules::System.live_metrics(long_query_threshold: threshold)

    # Validate that we got actual data
    if data[:connections][:total].nil? && data[:transactions][:total].nil?
      render json: {
        success: false,
        error: I18n.t("pg_reports.ui.errors.fetch_metrics_check_perms"),
        available: false
      }, status: :service_unavailable
      return
    end

    render json: {
      success: true,
      metrics: data,
      timestamp: Time.current.to_i,
      available: true
    }
  rescue PG::InsufficientPrivilege
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.insufficient_database_perms"),
      available: false
    }, status: :forbidden
  rescue => e
    render json: {
      success: false,
      error: e.message,
      available: false
    }, status: :unprocessable_entity
  end
end

#load_query_historyObject



568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 568

def load_query_history
  monitor = PgReports::QueryMonitor.instance

  limit = params[:limit]&.to_i || 50
  session_id = params[:session_id]

  queries = monitor.load_from_log(limit: limit, session_id: session_id)

  render json: {
    success: true,
    queries: queries,
    timestamp: Time.current.to_i
  }
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#query_monitor_feedObject



545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 545

def query_monitor_feed
  monitor = PgReports::QueryMonitor.instance

  unless monitor.enabled
    Rails.logger.warn("PgReports: query_monitor_feed called but monitoring not active. Instance: #{monitor.object_id}, enabled: #{monitor.enabled}, session_id: #{monitor.session_id}")
    render json: {success: false, message: "Monitoring not active"}
    return
  end

  limit = params[:limit]&.to_i || 50
  session_id = params[:session_id]

  queries = monitor.queries(limit: limit, session_id: session_id)

  render json: {
    success: true,
    queries: queries,
    timestamp: Time.current.to_i
  }
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#query_monitor_statusObject



531
532
533
534
535
536
537
538
539
540
541
542
543
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 531

def query_monitor_status
  monitor = PgReports::QueryMonitor.instance
  status = monitor.status

  render json: {
    success: true,
    enabled: status[:enabled],
    session_id: status[:session_id],
    query_count: status[:query_count]
  }
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#reset_statisticsObject



72
73
74
75
76
77
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 72

def reset_statistics
  PgReports.reset_statistics!
  render json: {success: true, message: I18n.t("pg_reports.ui.success.statistics_reset")}
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#runObject



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 147

def run
  category = params[:category].to_sym
  report_key = params[:report].to_sym

  # Extract filter parameters from request
  filter_params = extract_filter_params

  report = execute_report(category, report_key, **filter_params)
  thresholds = Dashboard::ReportsRegistry.thresholds(report_key)
  problem_fields = Dashboard::ReportsRegistry.problem_fields(report_key)
  problem_explanations = load_problem_explanations(category, report_key)

  # Add query hashes for security
  data_with_hashes = report.data.first(100).map do |row|
    row_hash = row.dup

    # If this row contains a query column, store it with a hash
    if row_hash.key?("query") && row_hash["query"].present?
      query_hash = store_query_with_hash(row_hash["query"])
      row_hash["query_hash"] = query_hash
    end

    row_hash
  end

  render json: {
    success: true,
    title: report.title,
    columns: report.columns,
    data: data_with_hashes,
    total: report.size,
    generated_at: report.generated_at.strftime("%Y-%m-%d %H:%M:%S"),
    thresholds: thresholds,
    problem_fields: problem_fields,
    problem_explanations: problem_explanations
  }
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#run_queryObject

POST /run_query Free-text SQL runner backing the "Run Query" modal. Unlike #execute_query (which only ever runs queries the server itself generated and cached by hash — see CHANGELOG 0.5.1), this endpoint accepts client-typed SQL directly, so it applies the same SELECT-only/denylist validation that normally happens on cache retrieval directly to the submitted text.



399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 399

def run_query
  raw_query = params[:query].to_s

  if raw_query.blank?
    render json: {success: false, error: I18n.t("pg_reports.ui.errors.query_required")}, status: :unprocessable_entity
    return
  end

  unless PgReports.config.allow_raw_query_execution
    render json: {
      success: false,
      error: I18n.t("pg_reports.ui.errors.query_execution_disabled")
    }, status: :forbidden
    return
  end

  begin
    enforce_select_only!(raw_query)
  rescue SecurityError => e
    render json: {success: false, error: "#{I18n.t("pg_reports.ui.errors.security_violation_prefix")} #{e.message}"}, status: :forbidden
    return
  end

  limited_query = add_limit_if_missing(raw_query, 100)

  rows = columns = nil
  total_count = 0
  truncated = false
  execution_time = nil

  with_statement_timeout do
    start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    result = ActiveRecord::Base.connection.execute(limited_query)
    end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    execution_time = ((end_time - start_time) * 1000).round(2)

    rows = result.to_a
    columns = rows.first&.keys || []
    total_count = rows.size

    if rows.size >= 100
      count_result = ActiveRecord::Base.connection.execute("SELECT COUNT(*) FROM (#{raw_query}) AS count_query")
      total_count = count_result.first["count"].to_i
      truncated = total_count > 100
    end
  end

  render json: {
    success: true,
    columns: columns,
    rows: rows,
    count: rows.size,
    total_count: total_count,
    truncated: truncated,
    execution_time: execution_time
  }
rescue ActiveRecord::QueryCanceled
  render json: {success: false, error: query_timed_out_message}, status: :unprocessable_entity
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#send_to_telegramObject



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 187

def send_to_telegram
  category = params[:category].to_sym
  report_key = params[:report].to_sym

  report = execute_report(category, report_key)

  if report.size > 50
    report.send_to_telegram_as_file
  else
    report.send_to_telegram
  end

  render json: {success: true, message: I18n.t("pg_reports.ui.success.telegram_sent")}
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#showObject



117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 117

def show
  @category = params[:category].to_sym
  @report_key = params[:report].to_sym
  @report_info = Dashboard::ReportsRegistry.find(@category, @report_key)

  if @report_info.nil?
    redirect_to root_path, alert: I18n.t("pg_reports.ui.errors.report_not_found")
    return
  end

  reason = category_disabled_reason(@category)
  if reason
    redirect_to root_path, alert: reason
    return
  end

  # Get documentation for the report
  @documentation = Dashboard::ReportsRegistry.documentation(@report_key)
  @thresholds = Dashboard::ReportsRegistry.thresholds(@report_key)
  @problem_fields = Dashboard::ReportsRegistry.problem_fields(@report_key)

  # Load filter parameters from YAML
  @report_filters = load_report_filters(@category, @report_key)

  @report = execute_report(@category, @report_key)
rescue => e
  @error = e.message
  @report = nil
end

#start_query_monitoringObject



500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 500

def start_query_monitoring
  monitor = PgReports::QueryMonitor.instance
  Rails.logger.info("PgReports: start_query_monitoring called. Instance: #{monitor.object_id}")

  result = monitor.start
  Rails.logger.info("PgReports: start result: #{result.inspect}")

  if result[:success]
    render json: result
  else
    render json: result, status: :unprocessable_entity
  end
rescue => e
  Rails.logger.error("PgReports: start_query_monitoring error: #{e.message}\n#{e.backtrace.first(5).join("\n")}")
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#stop_query_monitoringObject



517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 517

def stop_query_monitoring
  monitor = PgReports::QueryMonitor.instance

  result = monitor.stop

  if result[:success]
    render json: result
  else
    render json: result, status: :unprocessable_entity
  end
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#switch_databaseObject

POST /switch_database Persists the chosen database in session and redirects back. The actual connection switch happens on the next request via #within_selected_database.



36
37
38
39
40
41
42
43
44
45
46
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 36

def switch_database
  requested = params[:database].to_s

  if requested.empty?
    session.delete(:pg_reports_database)
  elsif valid_database?(requested)
    session[:pg_reports_database] = requested
  end

  redirect_back fallback_location: root_path
end

#switch_targetObject

POST /switch_target Persists the chosen target in session, clears the database choice (each target has its own list of databases), and redirects back.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 51

def switch_target
  requested = params[:target].to_s

  if requested.empty?
    session.delete(:pg_reports_target)
    session.delete(:pg_reports_database)
  elsif PgReports.connection_registry.target?(requested)
    session[:pg_reports_target] = requested
    # Database list is target-specific; reset so the next request picks the
    # new target's default rather than carrying a stale name.
    session.delete(:pg_reports_database)
  end

  redirect_back fallback_location: root_path
end