Last active
January 7, 2022 15:15
Star
You must be signed in to star a gist
Hack GitHub sql to work with postgres cast operator
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
# Shorcut because typing GitHub everywhere gets old | |
SQL = GitHub::SQL | |
module GitHub | |
class SQL | |
private | |
# Overwrite interpolate to be ok with postgres casting (::regclass, etc.). | |
def interpolate(sql, extras = nil) | |
sql.gsub(/(:?):([a-z][a-z0-9_]*)/) do |match| | |
if $1 == ":" # skip postgresql casts | |
match # return the whole match | |
else | |
sym = match[1..-1].intern # O.o gensym | |
if extras && extras.include?(sym) | |
val = extras[sym] | |
elsif binds.include?(sym) | |
val = binds[sym] | |
end | |
raise BadBind.new match if val.nil? | |
sanitize val | |
end | |
end | |
end | |
end | |
end |
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
require 'test_helper' | |
class GitHubSQLTest < ActiveSupport::TestCase | |
test "SQL shortcut works" do | |
assert_equal 2, SQL.value("SELECT 1+1") | |
end | |
test "#add works with postgres casts" do | |
assert_equal "foo::bar", GitHub::SQL.new.add("foo::bar").query | |
end | |
test "#add works for normal binds" do | |
assert_equal "foo = 'baz'", GitHub::SQL.new.add("foo = :bar", bar: "baz").query | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment