lib/pg_conn.rb in pg_conn-0.21.0 vs lib/pg_conn.rb in pg_conn-0.22.0
- old
+ new
@@ -513,12 +513,13 @@
h
end
# Returns a hash from the first field to a tuple of the remaining fields.
# If there is only one remaining field then that value is used instead of a
- # tuple of that value. The optional +key+ argument sets the mapping field
- def map(query, key = nil) # TODO Swap arguments
+ # tuple. The optional +key+ argument sets the mapping field and the
+ # +symbol+ option convert key to Symbol objects when true
+ def map(query, key = nil, symbol: false) # TODO Swap arguments
r = pg_exec(query)
begin
key = (key || r.fname(0)).to_s
key_index = r.fnumber(key.to_s)
one = (r.nfields == 2)
@@ -526,17 +527,22 @@
raise Error, "Can't find column #{key}"
end
h = {}
r.each_row { |row|
key_value = row.delete_at(key_index)
+ key_value = key_value.to_sym if symbol
!h.key?(key_value) or raise Error, "Duplicate key: #{key_value}"
h[key_value] = (one ? row.first : row)
}
h
end
- def multimap(query, key = nil)
+ # Like #map but values of duplicate keys are concatenated. It acts as a
+ # group-by on the key and array_agg on the remaining values. The value is
+ # an array of tuples if the query has more than one value field and an
+ # array of values if there is only one value field
+ def multimap(query, key = nil, symbol: false)
r = pg_exec(query)
begin
key = (key || r.fname(0)).to_s
key_index = r.fnumber(key.to_s)
one = (r.nfields == 2)
@@ -544,9 +550,10 @@
raise Error, "Can't find column #{key}"
end
h = {}
r.each_row { |row|
key_value = row.delete_at(key_index)
+ key_value = key_value.to_sym if symbol
(h[key_value] ||= []) << (one ? row.first : row)
}
h
end