Created
March 22, 2012 03:19
-
-
Save tagomoris/2155389 to your computer and use it in GitHub Desktop.
pseudo bind mix-in for mysql2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Mysql2::Client::PseudoBindMixi | |
def pseudo_bind(sql, values) | |
sql = sql.dup | |
placeholders = [] | |
search_pos = 0 | |
while pos = sql.index('?', search_pos) | |
placeholders.push(pos) | |
search_pos = pos + 1 | |
end | |
raise ArgumentError, "mismatch between placeholders number and values arguments" if placeholders.length != values.length | |
while pos = placeholders.pop() | |
rawvalue = values.pop() | |
if rawvalue.nil? | |
sql[pos] = 'NULL' | |
elsif rawvalue.is_a?(Time) | |
val = rawvalue.strftime('%Y-%m-%d %H:%M:%S') | |
sql[pos] = "'" + val + "'" | |
else | |
val = @handler.escape(rawvalue.to_s) | |
sql[pos] = "'" + val + "'" | |
end | |
end | |
sql | |
end | |
def bound_query(sql, *values) | |
values = values.flatten | |
# pseudo prepared statements | |
return self.query(sql) if values.length < 1 | |
self.query(self.pseudo_bind(sql, values)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment