Skip to content

Commit

Permalink
fix quote and encoding array
Browse files Browse the repository at this point in the history
  • Loading branch information
ermolaev committed Sep 16, 2024
1 parent 3766913 commit c17bcae
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/mini_sql/inline_param_encoder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ def quoted_time(value)
value.utc.iso8601
end

def quoted_native_array(arr)
quoted = arr.map { |v| v.is_a?(String) ? conn.escape_string(v) : v }
"'#{array_encoder.encode(quoted, Encoding::UTF_8)}'"
end

EMPTY_ARRAY = [].freeze

def quote_val(value)
Expand All @@ -65,7 +70,7 @@ def quote_val(value)
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(', ')
when Array then array_encoder ? quoted_native_array(value) : value.map { |v| quote_val(v) }.join(', ')
else raise TypeError, "can't quote #{value.class.name}"
end
end
Expand Down
1 change: 1 addition & 0 deletions mini_sql.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ Gem::Specification.new do |spec|
spec.add_development_dependency 'rubocop', '~> 1.25.0'
spec.add_development_dependency 'rubocop-discourse', '~> 2.5.0'
spec.add_development_dependency 'm', '~> 1.6.0'
spec.add_development_dependency "bigdecimal", "~> 3.1"

if RUBY_ENGINE == 'jruby'
spec.add_development_dependency "activerecord-jdbcpostgresql-adapter", "~> 52.2"
Expand Down
17 changes: 17 additions & 0 deletions test/mini_sql/postgres/auto_encode_arrays_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ def test_hash_params

assert_equal(row, [nums, strings, empty_array])
end

def test_escape_strings
strings = %w['1 "2 3]

row = @connection.query_single("select ?::text[]", strings).first

assert_equal(row[0], "'1")
assert_equal(row[1], "\"2")
assert_equal(row[2], "3")
end
end

class MiniSql::Postgres::TestAutoEncodeArraysPrepared < MiniSql::Postgres::TestPreparedConnection
Expand All @@ -39,4 +49,11 @@ class MiniSql::Postgres::TestAutoEncodeArraysUnprepared < MiniSql::Postgres::Tes
def setup
@connection = pg_connection(auto_encode_arrays: true)
end

def test_encoding
sql = @connection.to_sql("select ?::text[]", %w[hello привет])

assert_equal(sql, "select '{hello,привет}'::text[]")
assert_equal(sql.encoding, Encoding::UTF_8)
end
end

0 comments on commit c17bcae

Please sign in to comment.