Sha256: a02c46381e0c644d5a7bad9f66707dfa7865a2dd557bfa7e5aee216fea3ab39e

Contents?: true

Size: 988 Bytes

Versions: 12

Compression:

Stored size: 988 Bytes

Contents

module Adhoq
  class Query < ActiveRecord::Base
    include Adhoq::TimeBasedOrders

    has_many :executions, dependent: :destroy, inverse_of: :query

    PARAMETER_PATTERN = /\$(?<name>\w+)|\${(?<name>\w+)}/i.freeze

    def execute!(report_format, query_parameters = {})
      executions.create! {|exe|
        exe.report_format = report_format
        exe.raw_sql       = substitute_query(query_parameters)
      }.tap(&:generate_report!)
    end

    def parameters
      return @parameters if @parameters

      @parameters = query.scan(PARAMETER_PATTERN).each_with_object([]) do |(match1, match2), arr|
        name = match1 || match2

        arr << name.downcase
      end
    end

    def substitute_query(query_parameters)
      return query if parameters.empty?

      query_parameters = query_parameters.with_indifferent_access
      query.gsub(PARAMETER_PATTERN) do |_, arr|
        name = Regexp.last_match["name"]
        query_parameters[name]
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
adhoq-1.0.2 app/models/adhoq/query.rb
adhoq-1.0.1 app/models/adhoq/query.rb
adhoq-1.0.0 app/models/adhoq/query.rb
adhoq-0.5.0 app/models/adhoq/query.rb
adhoq-0.5.0.beta1 app/models/adhoq/query.rb
adhoq-0.4.0 app/models/adhoq/query.rb
adhoq-0.3.0 app/models/adhoq/query.rb
adhoq-0.2.0 app/models/adhoq/query.rb
adhoq-0.1.2 app/models/adhoq/query.rb
adhoq-0.1.1 app/models/adhoq/query.rb
adhoq-0.1.0 app/models/adhoq/query.rb
adhoq-0.0.7 app/models/adhoq/query.rb