module Relationizer::Postgresql

Constants

DEFAULT_TYPES

Public Instance Methods

create_relation_literal(schema, tuples) click to toggle source
# File lib/relationizer/postgresql.rb, line 33
def create_relation_literal(schema, tuples)
  _select_exp = select_exp(schema, tuples)

  tuples_exp = tuples.map { |tuple|
    tuple.
      map(&method(:to_text_literal)).
      join(", ").
      tap { |t| break "(#{t})" }
  }.join(", ")

  schema_exp = schema.keys.map(&method(:identifer_quote)).join(", ")

  "SELECT #{_select_exp} FROM (VALUES#{tuples_exp}) AS t(#{schema_exp})"
end

Private Instance Methods

empty_candidate_check(types) click to toggle source
# File lib/relationizer/postgresql.rb, line 68
def empty_candidate_check(types)
  raise ReasonlessTypeError.new("Candidate nothing") if types.empty?
end
identifer_quote(w) click to toggle source
# File lib/relationizer/postgresql.rb, line 72
def identifer_quote(w)
  %Q{"#{w.to_s.gsub(/"/, '""')}"}
end
many_candidate_check(types) click to toggle source
# File lib/relationizer/postgresql.rb, line 64
def many_candidate_check(types)
  raise ReasonlessTypeError.new("Many candidate: #{types.join(', ')}") unless types.one?
end
select_exp(schema, tuples) click to toggle source
# File lib/relationizer/postgresql.rb, line 50
def select_exp(schema, tuples)
  tuples.transpose.zip(schema.to_a).map { |(values, (name, type))|
    next %Q{"#{name}"::#{type.to_s.upcase}} if type

    values.
      map(&DEFAULT_TYPES).compact.uniq.
      tap(&method(:empty_candidate_check)).
      tap(&method(:many_candidate_check)).
      first.
      to_s.upcase.
      tap { |fixed_type| break %Q{"#{name}"::#{fixed_type}} }
  }.join(", ")
end
to_text_literal(obj) click to toggle source
# File lib/relationizer/postgresql.rb, line 76
def to_text_literal(obj)
  return "NULL" if obj.nil?

  obj.to_s.gsub(/'/, "''").tap do |s|
    break "'#{s}'"
  end
end