Class: ActiveSqlBindings

Inherits:
Object
  • Object
show all
Defined in:
lib/active_sql_bindings.rb

Overview

Class for work with SQL query. You can use native SQL with bindings as hash. Auto converting JSON fields to hash.

Class Method Summary collapse

Class Method Details

.execute(sql, bind = {}) ⇒ Array

Create sql query with hash named bindings

Example: ActiveSqlBindings.execute(‘SELECT name FROM test WHERE id = :id’, id: id)

Parameters:

  • sql (String)

    SQL query

  • bind (Hash) (defaults to: {})

    bindings data for query

Returns:

  • (Array)

    executed SQL request data and return array with hashes



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/active_sql_bindings.rb', line 17

def self.execute(sql, bind = {})
  bindings = []
  bind_index = 1

  # Get all bindings if exist
  unless bind.empty?
    bind.each do |key, value|
      # Change name bind to $ bind
      sql.gsub!(/(?<!:):#{key}(?=\b)/, "$#{bind_index}")
      bind_index += 1

      # Add new bind data
      bindings << [nil, value]
    end
  end

  # Execute query, convert to hash with symbol keys
  result = ActiveRecord::Base.connection.exec_query(sql, 'SQL', bindings).map(&:symbolize_keys)

  # Convert JSON data to hash
  result.map do |v|
    next if v.nil?

    v.each do |key, val|
      v[key] = json_to_hash(val)
    end
  end
end

.json_to_hash(json) ⇒ Hash

Convert JSON to hash if correct data

Parameters:

  • json (String)

    string

Returns:

  • (Hash)

    return hash if json is correct or input data



50
51
52
# File 'lib/active_sql_bindings.rb', line 50

def self.json_to_hash(json)
  JSON.parse(json, symbolize_names: true) rescue json
end