Sha256: f70fdcebd17b99903ccfb622b56eded9cb1ea9595c848941de464a73afc17198

Contents?: true

Size: 1.3 KB

Versions: 5

Compression:

Stored size: 1.3 KB

Contents

require 'bigdecimal'
require 'date'
require 'time'

module Cassanity
  class Statement
    def initialize(cql, options = {})
      @cql = cql
      @options = options

      @cql_version = @options.fetch(:cql_version, '3.0.0')
    end

    def interpolate(variables)
      e = variables.to_enum
      @cql.gsub(/\?/) { quote(e.next) }
    end

    private
    def quote(var)
      if Array === var
        var.map { |v| quote(v) }.join(',')
      elsif Hash === var
        %({#{var.map { |k, v| "#{quote(k)}:#{quote(v)}" }.join(',')}})
      elsif String === var
        %('#{escape_string(var)}')
      elsif BigDecimal === var && cql2?
        %('#{var.to_s}')
      elsif Numeric === var
        var.to_s
      elsif Date === var
        %('#{var.strftime('%Y-%m-%d')}')
      elsif Time === var
        (var.to_f * 1000).to_i
      elsif TrueClass === var || FalseClass === var
        if cql2?
          %('#{var.to_s}')
        else
          var.to_s
        end
      elsif var.respond_to?(:to_guid)
        var.to_guid
      elsif var.respond_to?(:to_s)
        %('#{var.to_s}')
      else
        raise ArgumentError, "Unable to escape #{var} (of type #{var.class})"
      end
    end

    def escape_string(str)
      str.gsub("'", "''")
    end

    def cql2?
      @cql_version.start_with?('2')
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
cassanity-0.6.0.beta5 lib/cassanity/statement.rb
cassanity-0.6.0.beta4 lib/cassanity/statement.rb
cassanity-0.6.0.beta3 lib/cassanity/statement.rb
cassanity-0.6.0.beta2 lib/cassanity/statement.rb
cassanity-0.6.0.beta1 lib/cassanity/statement.rb