Skip to content

Commit

Permalink
PERF: Optimize multiple use param in prepared postgres sql (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ermolaev Andrey authored Mar 7, 2022
1 parent ea5f6e2 commit c624406
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
27 changes: 27 additions & 0 deletions lib/mini_sql/postgres/prepared_binds.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,33 @@ module MiniSql
module Postgres
class PreparedBinds < ::MiniSql::Abstract::PreparedBinds

def bind_hash(sql, hash)
sql = sql.dup
binds = []
bind_names = []
i = 0

hash.each do |k, v|
bind_outputs =
array_wrap(v).map { |vv|
binds << vv
bind_names << [BindName.new(k)]
bind_output(i += 1)
}.join(', ')

sql.gsub!(":#{k}") do
# ignore ::int and stuff like that
# $` is previous to match
if $` && $`[-1] != ":"
bind_outputs
else
":#{k}"
end
end
end
[sql, binds, bind_names]
end

def bind_output(i)
"$#{i}"
end
Expand Down
7 changes: 7 additions & 0 deletions test/mini_sql/postgres/prepared_connection_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,11 @@ def test_limit_prepared_cache
assert_equal ps[0].statement, 'SELECT $1, $2, $3'
end

def test_single_named_param
r = @prepared_connection.query_single("select :n, :n, :n", n: 'test')

assert_last_stmt "select $1, $1, $1"
assert_equal %w[test test test], r
end

end

0 comments on commit c624406

Please sign in to comment.