aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/arel/visitors/to_sql.rb
blob: 4740e6d94f26f7653613fe896897f6c995c34ce1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
# frozen_string_literal: true

module Arel # :nodoc: all
  module Visitors
    class UnsupportedVisitError < StandardError
      def initialize(object)
        super "Unsupported argument type: #{object.class.name}. Construct an Arel node instead."
      end
    end

    class ToSql < Arel::Visitors::Visitor
      def initialize(connection)
        super()
        @connection = connection
      end

      def compile(node, collector = Arel::Collectors::SQLString.new)
        accept(node, collector).value
      end

      private

        def visit_Arel_Nodes_DeleteStatement(o, collector)
          o = prepare_delete_statement(o)

          if has_join_sources?(o)
            collector << "DELETE "
            visit o.relation.left, collector
            collector << " FROM "
          else
            collector << "DELETE FROM "
          end
          collector = visit o.relation, collector

          collect_nodes_for o.wheres, collector, " WHERE ", " AND "
          collect_nodes_for o.orders, collector, " ORDER BY "
          maybe_visit o.limit, collector
        end

        def visit_Arel_Nodes_UpdateStatement(o, collector)
          o = prepare_update_statement(o)

          collector << "UPDATE "
          collector = visit o.relation, collector
          collect_nodes_for o.values, collector, " SET "

          collect_nodes_for o.wheres, collector, " WHERE ", " AND "
          collect_nodes_for o.orders, collector, " ORDER BY "
          maybe_visit o.limit, collector
        end

        def visit_Arel_Nodes_InsertStatement(o, collector)
          collector << "INSERT INTO "
          collector = visit o.relation, collector
          if o.columns.any?
            collector << " (#{o.columns.map { |x|
              quote_column_name x.name
            }.join ', '})"
          end

          if o.values
            maybe_visit o.values, collector
          elsif o.select
            maybe_visit o.select, collector
          else
            collector
          end
        end

        def visit_Arel_Nodes_Exists(o, collector)
          collector << "EXISTS ("
          collector = visit(o.expressions, collector) << ")"
          if o.alias
            collector << " AS "
            visit o.alias, collector
          else
            collector
          end
        end

        def visit_Arel_Nodes_Casted(o, collector)
          collector << quoted(o.val, o.attribute).to_s
        end

        def visit_Arel_Nodes_Quoted(o, collector)
          collector << quoted(o.expr, nil).to_s
        end

        def visit_Arel_Nodes_True(o, collector)
          collector << "TRUE"
        end

        def visit_Arel_Nodes_False(o, collector)
          collector << "FALSE"
        end

        def visit_Arel_Nodes_ValuesList(o, collector)
          collector << "VALUES "

          len = o.rows.length - 1
          o.rows.each_with_index { |row, i|
            collector << "("
            row_len = row.length - 1
            row.each_with_index do |value, k|
              case value
              when Nodes::SqlLiteral, Nodes::BindParam
                collector = visit(value, collector)
              else
                collector << quote(value).to_s
              end
              collector << ", " unless k == row_len
            end
            collector << ")"
            collector << ", " unless i == len
          }
          collector
        end

        def visit_Arel_Nodes_SelectStatement(o, collector)
          if o.with
            collector = visit o.with, collector
            collector << " "
          end

          collector = o.cores.inject(collector) { |c, x|
            visit_Arel_Nodes_SelectCore(x, c)
          }

          unless o.orders.empty?
            collector << " ORDER BY "
            len = o.orders.length - 1
            o.orders.each_with_index { |x, i|
              collector = visit(x, collector)
              collector << ", " unless len == i
            }
          end

          visit_Arel_Nodes_SelectOptions(o, collector)
        end

        def visit_Arel_Nodes_SelectOptions(o, collector)
          collector = maybe_visit o.limit, collector
          collector = maybe_visit o.offset, collector
          maybe_visit o.lock, collector
        end

        def visit_Arel_Nodes_SelectCore(o, collector)
          collector << "SELECT"

          collector = collect_optimizer_hints(o, collector)
          collector = maybe_visit o.set_quantifier, collector

          collect_nodes_for o.projections, collector, " "

          if o.source && !o.source.empty?
            collector << " FROM "
            collector = visit o.source, collector
          end

          collect_nodes_for o.wheres, collector, " WHERE ", " AND "
          collect_nodes_for o.groups, collector, " GROUP BY "
          collect_nodes_for o.havings, collector, " HAVING ", " AND "
          collect_nodes_for o.windows, collector, " WINDOW "

          maybe_visit o.comment, collector
        end

        def visit_Arel_Nodes_OptimizerHints(o, collector)
          hints = o.expr.map { |v| sanitize_as_sql_comment(v) }.join(" ")
          collector << "/*+ #{hints} */"
        end

        def visit_Arel_Nodes_Comment(o, collector)
          collector << o.values.map { |v| "/* #{sanitize_as_sql_comment(v)} */" }.join(" ")
        end

        def collect_nodes_for(nodes, collector, spacer, connector = ", ")
          unless nodes.empty?
            collector << spacer
            inject_join nodes, collector, connector
          end
        end

        def visit_Arel_Nodes_Bin(o, collector)
          visit o.expr, collector
        end

        def visit_Arel_Nodes_Distinct(o, collector)
          collector << "DISTINCT"
        end

        def visit_Arel_Nodes_DistinctOn(o, collector)
          raise NotImplementedError, "DISTINCT ON not implemented for this db"
        end

        def visit_Arel_Nodes_With(o, collector)
          collector << "WITH "
          inject_join o.children, collector, ", "
        end

        def visit_Arel_Nodes_WithRecursive(o, collector)
          collector << "WITH RECURSIVE "
          inject_join o.children, collector, ", "
        end

        def visit_Arel_Nodes_Union(o, collector)
          infix_value_with_paren(o, collector, " UNION ")
        end

        def visit_Arel_Nodes_UnionAll(o, collector)
          infix_value_with_paren(o, collector, " UNION ALL ")
        end

        def visit_Arel_Nodes_Intersect(o, collector)
          collector << "( "
          infix_value(o, collector, " INTERSECT ") << " )"
        end

        def visit_Arel_Nodes_Except(o, collector)
          collector << "( "
          infix_value(o, collector, " EXCEPT ") << " )"
        end

        def visit_Arel_Nodes_NamedWindow(o, collector)
          collector << quote_column_name(o.name)
          collector << " AS "
          visit_Arel_Nodes_Window o, collector
        end

        def visit_Arel_Nodes_Window(o, collector)
          collector << "("

          collect_nodes_for o.partitions, collector, "PARTITION BY "

          if o.orders.any?
            collector << " " if o.partitions.any?
            collector << "ORDER BY "
            collector = inject_join o.orders, collector, ", "
          end

          if o.framing
            collector << " " if o.partitions.any? || o.orders.any?
            collector = visit o.framing, collector
          end

          collector << ")"
        end

        def visit_Arel_Nodes_Rows(o, collector)
          if o.expr
            collector << "ROWS "
            visit o.expr, collector
          else
            collector << "ROWS"
          end
        end

        def visit_Arel_Nodes_Range(o, collector)
          if o.expr
            collector << "RANGE "
            visit o.expr, collector
          else
            collector << "RANGE"
          end
        end

        def visit_Arel_Nodes_Preceding(o, collector)
          collector = if o.expr
            visit o.expr, collector
          else
            collector << "UNBOUNDED"
          end

          collector << " PRECEDING"
        end

        def visit_Arel_Nodes_Following(o, collector)
          collector = if o.expr
            visit o.expr, collector
          else
            collector << "UNBOUNDED"
          end

          collector << " FOLLOWING"
        end

        def visit_Arel_Nodes_CurrentRow(o, collector)
          collector << "CURRENT ROW"
        end

        def visit_Arel_Nodes_Over(o, collector)
          case o.right
          when nil
            visit(o.left, collector) << " OVER ()"
          when Arel::Nodes::SqlLiteral
            infix_value o, collector, " OVER "
          when String, Symbol
            visit(o.left, collector) << " OVER #{quote_column_name o.right.to_s}"
          else
            infix_value o, collector, " OVER "
          end
        end

        def visit_Arel_Nodes_Offset(o, collector)
          collector << "OFFSET "
          visit o.expr, collector
        end

        def visit_Arel_Nodes_Limit(o, collector)
          collector << "LIMIT "
          visit o.expr, collector
        end

        def visit_Arel_Nodes_Lock(o, collector)
          visit o.expr, collector
        end

        def visit_Arel_Nodes_Grouping(o, collector)
          if o.expr.is_a? Nodes::Grouping
            visit(o.expr, collector)
          else
            collector << "("
            visit(o.expr, collector) << ")"
          end
        end

        def visit_Arel_SelectManager(o, collector)
          collector << "("
          visit(o.ast, collector) << ")"
        end

        def visit_Arel_Nodes_Ascending(o, collector)
          visit(o.expr, collector) << " ASC"
        end

        def visit_Arel_Nodes_Descending(o, collector)
          visit(o.expr, collector) << " DESC"
        end

        def visit_Arel_Nodes_Group(o, collector)
          visit o.expr, collector
        end

        def visit_Arel_Nodes_NamedFunction(o, collector)
          collector << o.name
          collector << "("
          collector << "DISTINCT " if o.distinct
          collector = inject_join(o.expressions, collector, ", ") << ")"
          if o.alias
            collector << " AS "
            visit o.alias, collector
          else
            collector
          end
        end

        def visit_Arel_Nodes_Extract(o, collector)
          collector << "EXTRACT(#{o.field.to_s.upcase} FROM "
          visit(o.expr, collector) << ")"
        end

        def visit_Arel_Nodes_Count(o, collector)
          aggregate "COUNT", o, collector
        end

        def visit_Arel_Nodes_Sum(o, collector)
          aggregate "SUM", o, collector
        end

        def visit_Arel_Nodes_Max(o, collector)
          aggregate "MAX", o, collector
        end

        def visit_Arel_Nodes_Min(o, collector)
          aggregate "MIN", o, collector
        end

        def visit_Arel_Nodes_Avg(o, collector)
          aggregate "AVG", o, collector
        end

        def visit_Arel_Nodes_TableAlias(o, collector)
          collector = visit o.relation, collector
          collector << " "
          collector << quote_table_name(o.name)
        end

        def visit_Arel_Nodes_Between(o, collector)
          collector = visit o.left, collector
          collector << " BETWEEN "
          visit o.right, collector
        end

        def visit_Arel_Nodes_GreaterThanOrEqual(o, collector)
          collector = visit o.left, collector
          collector << " >= "
          visit o.right, collector
        end

        def visit_Arel_Nodes_GreaterThan(o, collector)
          collector = visit o.left, collector
          collector << " > "
          visit o.right, collector
        end

        def visit_Arel_Nodes_LessThanOrEqual(o, collector)
          collector = visit o.left, collector
          collector << " <= "
          visit o.right, collector
        end

        def visit_Arel_Nodes_LessThan(o, collector)
          collector = visit o.left, collector
          collector << " < "
          visit o.right, collector
        end

        def visit_Arel_Nodes_Matches(o, collector)
          collector = visit o.left, collector
          collector << " LIKE "
          collector = visit o.right, collector
          if o.escape
            collector << " ESCAPE "
            visit o.escape, collector
          else
            collector
          end
        end

        def visit_Arel_Nodes_DoesNotMatch(o, collector)
          collector = visit o.left, collector
          collector << " NOT LIKE "
          collector = visit o.right, collector
          if o.escape
            collector << " ESCAPE "
            visit o.escape, collector
          else
            collector
          end
        end

        def visit_Arel_Nodes_JoinSource(o, collector)
          if o.left
            collector = visit o.left, collector
          end
          if o.right.any?
            collector << " " if o.left
            collector = inject_join o.right, collector, " "
          end
          collector
        end

        def visit_Arel_Nodes_Regexp(o, collector)
          raise NotImplementedError, "~ not implemented for this db"
        end

        def visit_Arel_Nodes_NotRegexp(o, collector)
          raise NotImplementedError, "!~ not implemented for this db"
        end

        def visit_Arel_Nodes_StringJoin(o, collector)
          visit o.left, collector
        end

        def visit_Arel_Nodes_FullOuterJoin(o, collector)
          collector << "FULL OUTER JOIN "
          collector = visit o.left, collector
          collector << " "
          visit o.right, collector
        end

        def visit_Arel_Nodes_OuterJoin(o, collector)
          collector << "LEFT OUTER JOIN "
          collector = visit o.left, collector
          collector << " "
          visit o.right, collector
        end

        def visit_Arel_Nodes_RightOuterJoin(o, collector)
          collector << "RIGHT OUTER JOIN "
          collector = visit o.left, collector
          collector << " "
          visit o.right, collector
        end

        def visit_Arel_Nodes_InnerJoin(o, collector)
          collector << "INNER JOIN "
          collector = visit o.left, collector
          if o.right
            collector << " "
            visit(o.right, collector)
          else
            collector
          end
        end

        def visit_Arel_Nodes_On(o, collector)
          collector << "ON "
          visit o.expr, collector
        end

        def visit_Arel_Nodes_Not(o, collector)
          collector << "NOT ("
          visit(o.expr, collector) << ")"
        end

        def visit_Arel_Table(o, collector)
          if o.table_alias
            collector << "#{quote_table_name o.name} #{quote_table_name o.table_alias}"
          else
            collector << quote_table_name(o.name)
          end
        end

        def visit_Arel_Nodes_In(o, collector)
          unless Array === o.right
            return collect_in_clause(o.left, o.right, collector)
          end

          unless o.right.empty?
            o.right.delete_if { |value| unboundable?(value) }
          end

          return collector << "1=0" if o.right.empty?

          in_clause_length = @connection.in_clause_length

          if !in_clause_length || o.right.length <= in_clause_length
            collect_in_clause(o.left, o.right, collector)
          else
            collector << "("
            o.right.each_slice(in_clause_length).each_with_index do |right, i|
              collector << " OR " unless i == 0
              collect_in_clause(o.left, right, collector)
            end
            collector << ")"
          end
        end

        def collect_in_clause(left, right, collector)
          collector = visit left, collector
          collector << " IN ("
          visit(right, collector) << ")"
        end

        def visit_Arel_Nodes_NotIn(o, collector)
          unless Array === o.right
            return collect_not_in_clause(o.left, o.right, collector)
          end

          unless o.right.empty?
            o.right.delete_if { |value| unboundable?(value) }
          end

          return collector << "1=1" if o.right.empty?

          in_clause_length = @connection.in_clause_length

          if !in_clause_length || o.right.length <= in_clause_length
            collect_not_in_clause(o.left, o.right, collector)
          else
            o.right.each_slice(in_clause_length).each_with_index do |right, i|
              collector << " AND " unless i == 0
              collect_not_in_clause(o.left, right, collector)
            end
            collector
          end
        end

        def collect_not_in_clause(left, right, collector)
          collector = visit left, collector
          collector << " NOT IN ("
          visit(right, collector) << ")"
        end

        def visit_Arel_Nodes_And(o, collector)
          inject_join o.children, collector, " AND "
        end

        def visit_Arel_Nodes_Or(o, collector)
          collector = visit o.left, collector
          collector << " OR "
          visit o.right, collector
        end

        def visit_Arel_Nodes_Assignment(o, collector)
          case o.right
          when Arel::Nodes::Node, Arel::Attributes::Attribute
            collector = visit o.left, collector
            collector << " = "
            visit o.right, collector
          else
            collector = visit o.left, collector
            collector << " = "
            collector << quote(o.right).to_s
          end
        end

        def visit_Arel_Nodes_Equality(o, collector)
          right = o.right

          return collector << "1=0" if unboundable?(right)

          collector = visit o.left, collector

          if right.nil?
            collector << " IS NULL"
          else
            collector << " = "
            visit right, collector
          end
        end

        def visit_Arel_Nodes_IsNotDistinctFrom(o, collector)
          if o.right.nil?
            collector = visit o.left, collector
            collector << " IS NULL"
          else
            collector = is_distinct_from(o, collector)
            collector << " = 0"
          end
        end

        def visit_Arel_Nodes_IsDistinctFrom(o, collector)
          if o.right.nil?
            collector = visit o.left, collector
            collector << " IS NOT NULL"
          else
            collector = is_distinct_from(o, collector)
            collector << " = 1"
          end
        end

        def visit_Arel_Nodes_NotEqual(o, collector)
          right = o.right

          return collector << "1=1" if unboundable?(right)

          collector = visit o.left, collector

          if right.nil?
            collector << " IS NOT NULL"
          else
            collector << " != "
            visit right, collector
          end
        end

        def visit_Arel_Nodes_As(o, collector)
          collector = visit o.left, collector
          collector << " AS "
          visit o.right, collector
        end

        def visit_Arel_Nodes_Case(o, collector)
          collector << "CASE "
          if o.case
            visit o.case, collector
            collector << " "
          end
          o.conditions.each do |condition|
            visit condition, collector
            collector << " "
          end
          if o.default
            visit o.default, collector
            collector << " "
          end
          collector << "END"
        end

        def visit_Arel_Nodes_When(o, collector)
          collector << "WHEN "
          visit o.left, collector
          collector << " THEN "
          visit o.right, collector
        end

        def visit_Arel_Nodes_Else(o, collector)
          collector << "ELSE "
          visit o.expr, collector
        end

        def visit_Arel_Nodes_UnqualifiedColumn(o, collector)
          collector << "#{quote_column_name o.name}"
          collector
        end

        def visit_Arel_Attributes_Attribute(o, collector)
          join_name = o.relation.table_alias || o.relation.name
          collector << "#{quote_table_name join_name}.#{quote_column_name o.name}"
        end
        alias :visit_Arel_Attributes_Integer :visit_Arel_Attributes_Attribute
        alias :visit_Arel_Attributes_Float :visit_Arel_Attributes_Attribute
        alias :visit_Arel_Attributes_Decimal :visit_Arel_Attributes_Attribute
        alias :visit_Arel_Attributes_String :visit_Arel_Attributes_Attribute
        alias :visit_Arel_Attributes_Time :visit_Arel_Attributes_Attribute
        alias :visit_Arel_Attributes_Boolean :visit_Arel_Attributes_Attribute

        def literal(o, collector); collector << o.to_s; end

        def visit_Arel_Nodes_BindParam(o, collector)
          collector.add_bind(o.value) { "?" }
        end

        alias :visit_Arel_Nodes_SqlLiteral :literal
        alias :visit_Integer               :literal

        def quoted(o, a)
          if a && a.able_to_type_cast?
            quote(a.type_cast_for_database(o))
          else
            quote(o)
          end
        end

        def unsupported(o, collector)
          raise UnsupportedVisitError.new(o)
        end

        alias :visit_ActiveSupport_Multibyte_Chars :unsupported
        alias :visit_ActiveSupport_StringInquirer  :unsupported
        alias :visit_BigDecimal                    :unsupported
        alias :visit_Class                         :unsupported
        alias :visit_Date                          :unsupported
        alias :visit_DateTime                      :unsupported
        alias :visit_FalseClass                    :unsupported
        alias :visit_Float                         :unsupported
        alias :visit_Hash                          :unsupported
        alias :visit_NilClass                      :unsupported
        alias :visit_String                        :unsupported
        alias :visit_Symbol                        :unsupported
        alias :visit_Time                          :unsupported
        alias :visit_TrueClass                     :unsupported

        def visit_Arel_Nodes_InfixOperation(o, collector)
          collector = visit o.left, collector
          collector << " #{o.operator} "
          visit o.right, collector
        end

        alias :visit_Arel_Nodes_Addition       :visit_Arel_Nodes_InfixOperation
        alias :visit_Arel_Nodes_Subtraction    :visit_Arel_Nodes_InfixOperation
        alias :visit_Arel_Nodes_Multiplication :visit_Arel_Nodes_InfixOperation
        alias :visit_Arel_Nodes_Division       :visit_Arel_Nodes_InfixOperation

        def visit_Arel_Nodes_UnaryOperation(o, collector)
          collector << " #{o.operator} "
          visit o.expr, collector
        end

        def visit_Array(o, collector)
          inject_join o, collector, ", "
        end
        alias :visit_Set :visit_Array

        def quote(value)
          return value if Arel::Nodes::SqlLiteral === value
          @connection.quote value
        end

        def quote_table_name(name)
          return name if Arel::Nodes::SqlLiteral === name
          @connection.quote_table_name(name)
        end

        def quote_column_name(name)
          return name if Arel::Nodes::SqlLiteral === name
          @connection.quote_column_name(name)
        end

        def sanitize_as_sql_comment(value)
          return value if Arel::Nodes::SqlLiteral === value
          @connection.sanitize_as_sql_comment(value)
        end

        def collect_optimizer_hints(o, collector)
          maybe_visit o.optimizer_hints, collector
        end

        def maybe_visit(thing, collector)
          return collector unless thing
          collector << " "
          visit thing, collector
        end

        def inject_join(list, collector, join_str)
          len = list.length - 1
          list.each_with_index.inject(collector) { |c, (x, i)|
            if i == len
              visit x, c
            else
              visit(x, c) << join_str
            end
          }
        end

        def unboundable?(value)
          value.respond_to?(:unboundable?) && value.unboundable?
        end

        def has_join_sources?(o)
          o.relation.is_a?(Nodes::JoinSource) && !o.relation.right.empty?
        end

        def has_limit_or_offset_or_orders?(o)
          o.limit || o.offset || !o.orders.empty?
        end

        # The default strategy for an UPDATE with joins is to use a subquery. This doesn't work
        # on MySQL (even when aliasing the tables), but MySQL allows using JOIN directly in
        # an UPDATE statement, so in the MySQL visitor we redefine this to do that.
        def prepare_update_statement(o)
          if o.key && (has_limit_or_offset_or_orders?(o) || has_join_sources?(o))
            stmt = o.clone
            stmt.limit = nil
            stmt.offset = nil
            stmt.orders = []
            stmt.wheres = [Nodes::In.new(o.key, [build_subselect(o.key, o)])]
            stmt.relation = o.relation.left if has_join_sources?(o)
            stmt
          else
            o
          end
        end
        alias :prepare_delete_statement :prepare_update_statement

        # FIXME: we should probably have a 2-pass visitor for this
        def build_subselect(key, o)
          stmt             = Nodes::SelectStatement.new
          core             = stmt.cores.first
          core.froms       = o.relation
          core.wheres      = o.wheres
          core.projections = [key]
          stmt.limit       = o.limit
          stmt.offset      = o.offset
          stmt.orders      = o.orders
          stmt
        end

        def infix_value(o, collector, value)
          collector = visit o.left, collector
          collector << value
          visit o.right, collector
        end

        def infix_value_with_paren(o, collector, value, suppress_parens = false)
          collector << "( " unless suppress_parens
          collector = if o.left.class == o.class
            infix_value_with_paren(o.left, collector, value, true)
          else
            visit o.left, collector
          end
          collector << value
          collector = if o.right.class == o.class
            infix_value_with_paren(o.right, collector, value, true)
          else
            visit o.right, collector
          end
          collector << " )" unless suppress_parens
          collector
        end

        def aggregate(name, o, collector)
          collector << "#{name}("
          if o.distinct
            collector << "DISTINCT "
          end
          collector = inject_join(o.expressions, collector, ", ") << ")"
          if o.alias
            collector << " AS "
            visit o.alias, collector
          else
            collector
          end
        end

        def is_distinct_from(o, collector)
          collector << "CASE WHEN "
          collector = visit o.left, collector
          collector << " = "
          collector = visit o.right, collector
          collector << " OR ("
          collector = visit o.left, collector
          collector << " IS NULL AND "
          collector = visit o.right, collector
          collector << " IS NULL)"
          collector << " THEN 0 ELSE 1 END"
        end
    end
  end
end