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



478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
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 478

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



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

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: report_error_message(e)}, status: :unprocessable_entity
end

#download_query_monitorObject



603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 603

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



84
85
86
87
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 84

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

#execute_queryObject



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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 326

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



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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 250

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



30
31
32
33
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 30

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

#live_metricsObject



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

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



586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 586

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



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

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



548
549
550
551
552
553
554
555
556
557
558
559
560
561
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 548

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],
    history_available: status[:history_available]
  }
rescue => e
  render json: {success: false, error: e.message}, status: :unprocessable_entity
end

#reset_statisticsObject



89
90
91
92
93
94
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 89

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



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

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: report_error_message(e)}, 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.



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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 416

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



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 204

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: report_error_message(e)}, status: :unprocessable_entity
end

#showObject



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

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 = report_error_message(e)
  @report = nil
end

#start_query_monitoringObject



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

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



534
535
536
537
538
539
540
541
542
543
544
545
546
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 534

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.



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

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_localeObject

POST /switch_target Persists the chosen target in session, clears the database choice (each target has its own list of databases), and redirects back. POST /switch_locale Persists the chosen language in session; #within_selected_locale applies it to this and every later request.



56
57
58
59
60
61
62
63
64
65
66
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 56

def switch_locale
  requested = params[:locale].to_s

  if requested.empty?
    session.delete(:pg_reports_locale)
  elsif dashboard_locales.any? { |locale| locale.to_s == requested }
    session[:pg_reports_locale] = requested
  end

  redirect_back fallback_location: root_path
end

#switch_targetObject



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'app/controllers/pg_reports/dashboard_controller.rb', line 68

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