Skip to content

Instantly share code, notes, and snippets.

@tagomoris
Created March 22, 2012 03:19
Show Gist options
  • Save tagomoris/2155389 to your computer and use it in GitHub Desktop.
Save tagomoris/2155389 to your computer and use it in GitHub Desktop.
pseudo bind mix-in for mysql2
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