Sha256: 46e5490299f2ca92b332c8f9fc725ced79a78aaa524a268653c57e21c58babd9

Contents?: true

Size: 840 Bytes

Versions: 3

Compression:

Stored size: 840 Bytes

Contents

module BqFactory
  class Attribute
    PERMIT_TYPES = %i(STRING INTEGER FLOAT TIMESTAMP BOOLEAN RECORD).freeze

    attr_accessor :value
    attr_reader :name, :type

    def initialize(name, type)
      type = type.to_sym
      raise ArgumentError.new, "#{type} is not implemented" unless PERMIT_TYPES.include?(type)
      @name = name
      @type = type
    end

    def to_sql
      "#{cast_to_sql(value)} AS #{name}"
    end

    private

    def cast_to_sql(value)
      return "CAST(NULL AS #{type})" if value.nil?

      case type
      when :STRING then %("#{value.gsub(/"/, '\"')}")
      when :INTEGER, :FLOAT, :BOOLEAN then value.to_s
      when :TIMESTAMP then %{TIMESTAMP("#{value.strftime('%Y-%m-%d %X')}")}
      when :RECORD then raise NotImplementedError.new, "sorry, RECORD is not implemented"
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
bq_factory-0.2.0 lib/bq_factory/attribute.rb
bq_factory-0.1.1 lib/bq_factory/attribute.rb
bq_factory-0.1.0 lib/bq_factory/attribute.rb