Class: Rails::Hyperdrive::Tools::RunSql

Inherits:
Base
  • Object
show all
Defined in:
lib/rails/hyperdrive/tools/run_sql.rb

Constant Summary collapse

ROW_CAP =
100

Class Method Summary collapse

Methods inherited from Base

respond_error, respond_json, respond_text, with_dev_guard

Class Method Details

.call(sql:, server_context: nil) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rails/hyperdrive/tools/run_sql.rb', line 20

def self.call(sql:, server_context: nil)
  with_dev_guard do
    begin
      Rails::Hyperdrive::SqlSafety.assert_read_only!(sql)
    rescue Rails::Hyperdrive::SqlSafety::Error => e
      return respond_error("SQL not allowed: #{e.message}")
    end

    begin
      result = ActiveRecord::Base.connection.exec_query(sql)
    rescue ActiveRecord::ActiveRecordError => e
      return respond_error("#{e.class}: #{e.message}")
    end

    respond_text(format_table(result))
  end
end

.format_table(result) ⇒ Object



38
39
40
41
42
43
44
45
# File 'lib/rails/hyperdrive/tools/run_sql.rb', line 38

def self.format_table(result)
  rows = result.rows
  shown = rows.first(ROW_CAP)
  lines = [result.columns.join("\t")]
  shown.each { |row| lines << row.map { |v| v.to_s }.join("\t") }
  lines << "(#{rows.length} rows, truncated)" if rows.length > ROW_CAP
  lines.join("\n")
end