Skip to content

Instantly share code, notes, and snippets.

@jnunemaker
Last active January 7, 2022 15:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnunemaker/123be8db3d95d8386fc258f99e7fd99a to your computer and use it in GitHub Desktop.
Save jnunemaker/123be8db3d95d8386fc258f99e7fd99a to your computer and use it in GitHub Desktop.
Hack GitHub sql to work with postgres cast operator
# 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
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