discourse/lib/sql_builder.rb

58 lines
1.3 KiB
Ruby
Raw Normal View History

2013-02-06 03:16:51 +08:00
class SqlBuilder
def initialize(template,klass=nil)
2013-02-06 03:16:51 +08:00
@args = {}
@sql = template
@sections = {}
@klass = klass
2013-02-06 03:16:51 +08:00
end
[:set, :where2,:where,:order_by,:limit,:left_join,:join,:offset].each do |k|
define_method k do |data, args = {}|
@args.merge!(args)
@sections[k] ||= []
@sections[k] << data
self
end
end
def exec(args = {})
sql = @sql.dup
@args.merge!(args)
@sections.each do |k,v|
joined = nil
2013-02-26 00:42:20 +08:00
case k
2013-02-06 03:16:51 +08:00
when :where, :where2
joined = "WHERE " << v.join(" AND ")
when :join
joined = v.map{|v| "JOIN " << v }.join("\n")
when :left_join
joined = v.map{|v| "LEFT JOIN " << v }.join("\n")
when :limit
joined = "LIMIT " << v.last.to_s
when :offset
joined = "OFFSET " << v.last.to_s
when :order_by
joined = "ORDER BY " << v.join(" , ")
when :set
joined = "SET " << v.join(" , ")
end
sql.sub!("/*#{k}*/", joined)
end
2013-02-26 00:42:20 +08:00
if @klass
@klass.find_by_sql(ActiveRecord::Base.send(:sanitize_sql_array, [sql, @args]))
else
ActiveRecord::Base.exec_sql(sql,@args)
end
2013-02-06 03:16:51 +08:00
end
end
2013-02-06 03:16:51 +08:00
2013-02-26 00:42:20 +08:00
class ActiveRecord::Base
def self.sql_builder(template)
SqlBuilder.new(template, self)
end
2013-02-06 03:16:51 +08:00
end