Skip to content

Commit

Permalink
[auto_encode_arrays, perf] fix empty array
Browse files Browse the repository at this point in the history
  • Loading branch information
ermolaev committed Aug 21, 2024
1 parent 253f913 commit 6dc5312
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
24 changes: 13 additions & 11 deletions lib/mini_sql/inline_param_encoder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,21 @@ def quoted_time(value)
value.utc.iso8601
end

EMPTY_ARRAY = [].freeze

def quote_val(value)
case value
when String then "'#{conn.escape_string(value.to_s)}'"
when Numeric then value.to_s
when BigDecimal then value.to_s("F")
when Time then "'#{quoted_time(value)}'"
when Date then "'#{value.to_s}'"
when Symbol then "'#{conn.escape_string(value.to_s)}'"
when true then "true"
when false then "false"
when nil then "NULL"
when [] then "NULL"
when Array then array_encoder ? "'#{array_encoder.encode(value)}'" : value.map { |v| quote_val(v) }.join(', ')
when String then "'#{conn.escape_string(value.to_s)}'"
when Numeric then value.to_s
when BigDecimal then value.to_s("F")
when Time then "'#{quoted_time(value)}'"
when Date then "'#{value.to_s}'"
when Symbol then "'#{conn.escape_string(value.to_s)}'"
when true then "true"
when false then "false"
when nil then "NULL"
when EMPTY_ARRAY then array_encoder ? "{}" : "NULL"
when Array then array_encoder ? "'#{array_encoder.encode(value)}'" : value.map { |v| quote_val(v) }.join(', ')
else raise TypeError, "can't quote #{value.class.name}"
end
end
Expand Down
4 changes: 3 additions & 1 deletion test/mini_sql/postgres/connection_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -160,10 +160,12 @@ def test_encode_array

ints = [1, 2, 3]
strings = %w[a b c]
row = connection.query("select ?::int[] ints, ?::text[] strings", ints, strings).first
empty_array = []
row = connection.query("select ?::int[] ints, ?::text[] strings, ? empty_array", ints, strings, empty_array).first

assert_equal(row.ints, ints)
assert_equal(row.strings, strings)
assert_equal(row.empty_array, empty_array)
end

end

0 comments on commit 6dc5312

Please sign in to comment.