to_sql.rb 1.8 KB
Newer Older
A
Aaron Patterson 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
module Arel
  module Visitors
    class ToSql
      def initialize engine
        @engine     = engine
        @connection = nil
      end

      def accept object
        @connection = @engine.connection
        visit object
      end

      private
A
Aaron Patterson 已提交
15 16 17 18 19 20 21 22
      def visit_Arel_Nodes_SelectStatement o
        [
          o.cores.map { |x| visit x }.join,
          ("LIMIT #{o.limit}" if o.limit)
        ].compact.join ' '
      end

      def visit_Arel_Nodes_SelectCore o
A
Aaron Patterson 已提交
23 24
        [
          "SELECT #{o.projections.map { |x| visit x }.join ', '}",
A
Aaron Patterson 已提交
25 26
          ("FROM #{o.froms.map { |x| visit x }.join ', ' }" unless o.froms.empty?),
          ("WHERE #{o.wheres.map { |x| visit x }.join ' AND ' }" unless o.wheres.empty?)
A
Aaron Patterson 已提交
27 28 29 30 31 32 33
        ].compact.join ' '
      end

      def visit_Arel_Table o
        quote_table_name o.name
      end

A
Aaron Patterson 已提交
34 35 36 37 38 39 40 41 42
      def visit_Arel_Nodes_Equality o
        "#{visit o.left} = #{visit o.right}"
      end

      def visit_Arel_Attributes_Integer o
        "#{quote_table_name o.relation.name}.#{quote_column_name o.name}"
      end

      def visit_Fixnum o; o end
A
Aaron Patterson 已提交
43 44 45
      alias :visit_String :visit_Fixnum
      alias :visit_Arel_Nodes_SqlLiteral :visit_Fixnum
      alias :visit_Arel_SqlLiteral :visit_Fixnum # This is deprecated
A
Aaron Patterson 已提交
46

A
Aaron Patterson 已提交
47
      DISPATCH = {}
A
Aaron Patterson 已提交
48
      def visit object
A
Aaron Patterson 已提交
49 50
        send "visit_#{object.class.name.gsub('::', '_')}", object
        #send DISPATCH[object.class], object
A
Aaron Patterson 已提交
51 52 53 54 55 56 57
      end

      private_instance_methods(false).each do |method|
        method = method.to_s
        next unless method =~ /^visit_(.*)$/
        const = $1.split('_').inject(Object) { |m,s| m.const_get s }
        DISPATCH[const] = method
A
Aaron Patterson 已提交
58 59 60 61 62 63 64 65 66 67 68 69
      end

      def quote_table_name name
        @connection.quote_table_name name
      end

      def quote_column_name name
        @connection.quote_column_name name
      end
    end
  end
end