-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathconnection.ex
1192 lines (952 loc) · 34.2 KB
/
connection.ex
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
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
defmodule Ecto.Adapters.ClickHouse.Connection do
@moduledoc false
@behaviour Ecto.Adapters.SQL.Connection
@dialyzer :no_improper_lists
require Logger
alias Ecto.SubQuery
alias Ecto.Query.{QueryExpr, ByExpr, JoinExpr, BooleanExpr, WithExpr, Tagged}
@parent_as __MODULE__
@impl true
def child_spec(opts) do
Ch.child_spec(opts)
end
@impl true
def prepare_execute(conn, _name, statement, params, opts) do
query = Ch.Query.build(statement, opts[:command])
DBConnection.prepare_execute(conn, query, params, opts)
end
@impl true
def execute(conn, query, params, opts) do
DBConnection.execute(conn, query, params, opts)
end
# TODO what should be done about transactions? probably will need to build custom Repo.stream
@impl true
def query(conn, statement, params, opts) do
Ch.query(conn, statement, params, opts)
end
@impl true
def query_many(_conn, _statement, _params, _opts) do
raise "not implemented"
end
@impl true
def stream(conn, statement, params, opts) do
Ch.stream(conn, statement, params, opts)
end
@impl true
def to_constraints(_exception, _opts) do
raise "not implemented"
end
@impl true
def all(query, params \\ [], as_prefix \\ []) do
if Map.get(query, :lock) do
raise ArgumentError, "ClickHouse does not support locks"
end
sources = create_names(query, as_prefix)
cte = cte(query, sources, params)
from = from(query, sources, params)
select = select(query, sources, params)
join = join(query, sources, params)
where = where(query, sources, params)
group_by = group_by(query, sources, params)
having = having(query, sources, params)
window = window(query, sources, params)
order_by = order_by(query, sources, params)
limit = limit(query, sources, params)
offset = offset(query, sources, params)
combinations = combinations(query, params)
[
cte,
select,
from,
join,
where,
group_by,
having,
window,
order_by,
limit,
offset,
combinations
]
end
@dialyzer {:no_return, update_all: 1, update_all: 2}
@impl true
def update_all(query, _prefix \\ nil) do
raise Ecto.QueryError,
query: query,
message:
"ClickHouse does not support UPDATE statements -- use ALTER TABLE ... UPDATE instead"
end
# https://clickhouse.com/docs/en/sql-reference/statements/alter/update
# https://clickhouse.com/docs/en/guides/developer/mutations#updating-data
def alter_update_all(query, params \\ []) do
# TODO link to https://clickhouse.com/blog/handling-updates-and-deletes-in-clickhouse#updating-and-deleting-using-joins
unless query.joins == [] do
raise Ecto.QueryError,
query: query,
message:
"Ecto.Adapters.ClickHouse does not support JOIN in ALTER TABLE ... UPDATE statements"
end
if query.select do
raise Ecto.QueryError,
query: query,
message:
"Ecto.Adapters.ClickHouse does not support RETURNING in ALTER TABLE ... UPDATE statements"
end
if query.with_ctes do
raise Ecto.QueryError,
query: query,
message:
"Ecto.Adapters.ClickHouse does not support CTEs in ALTER TABLE ... UPDATE statements"
end
%{sources: sources} = query
{table, _schema, prefix} = elem(sources, 0)
fields = update_fields(query, sources, params)
where =
case query.wheres do
[] -> " WHERE 1"
_ -> where(query, {{nil, nil, nil}}, params)
end
["ALTER TABLE ", quote_table(prefix, table), " UPDATE ", fields, where]
end
defp update_fields(%{updates: updates} = query, sources, params) do
fields =
for %{expr: expression} <- updates, {op, kw} <- expression, {key, value} <- kw do
update_op(op, quote_name(key), value, sources, params, query)
end
Enum.intersperse(fields, ?,)
end
defp update_op(:set, quoted_key, value, sources, params, query) do
[quoted_key, ?= | expr(value, sources, params, query)]
end
defp update_op(:inc, quoted_key, value, sources, params, query) do
[quoted_key, ?=, quoted_key, ?+ | expr(value, sources, params, query)]
end
defp update_op(:push, quoted_key, value, sources, params, query) do
[quoted_key, ?=, "arrayPushBack(", quoted_key, ?,, expr(value, sources, params, query), ?)]
end
defp update_op(:pull, quoted_key, value, sources, params, query) do
[
quoted_key,
?=,
"arrayFilter(x->x!=",
expr(value, sources, params, query),
?,,
quoted_key,
?)
]
end
defp update_op(command, _quoted_key, _value, _sources, _params, query) do
raise Ecto.QueryError,
query: query,
message: "Ecto.Adapters.ClickHouse does not support update operation #{inspect(command)}"
end
@impl true
def delete_all(query, params \\ []) do
unless query.joins == [] do
raise Ecto.QueryError,
query: query,
message: "ClickHouse does not support JOIN on DELETE statements"
end
if query.select do
raise Ecto.QueryError,
query: query,
message: "ClickHouse does not support RETURNING on DELETE statements"
end
if query.with_ctes do
raise Ecto.QueryError,
query: query,
message: "ClickHouse does not support CTEs (WITH) on DELETE statements"
end
%{sources: sources} = query
{table, _schema, prefix} = elem(sources, 0)
where =
case query.wheres do
[] -> " WHERE 1"
_ -> where(query, {{nil, nil, nil}}, params)
end
["DELETE FROM ", quote_table(prefix, table) | where]
end
@impl true
def ddl_logs(_), do: []
@impl true
def table_exists_query(table) do
{"SELECT name FROM system.tables WHERE name={$0:String} LIMIT 1", [table]}
end
@impl true
def execute_ddl(command) do
Ecto.Adapters.ClickHouse.Migration.execute_ddl(command)
end
@impl true
def insert(prefix, table, header, rows, _on_conflict, returning, _placeholders) do
unless returning == [] do
raise ArgumentError, "ClickHouse does not support RETURNING on INSERT statements"
end
insert(prefix, table, header, rows)
end
def insert(prefix, table, header, rows) do
insert =
case header do
[] ->
["INSERT INTO " | quote_table(prefix, table)]
_not_empty ->
fields = [?(, intersperse_map(header, ?,, "e_name/1), ?)]
["INSERT INTO ", quote_table(prefix, table) | fields]
end
case rows do
{%Ecto.Query{} = query, params} -> [insert, ?\s | all(query, params)]
rows when is_list(rows) -> insert
end
end
@impl true
def update(_prefix, _table, _fields, _filters, _returning) do
raise ArgumentError,
"ClickHouse does not support UPDATE statements -- use ALTER TABLE ... UPDATE instead"
end
@impl true
# https://clickhouse.com/docs/en/sql-reference/statements/delete
def delete(prefix, table, filters, returning) do
unless returning == [] do
raise ArgumentError, "ClickHouse does not support RETURNING on DELETE statements"
end
filters =
filters
|> Enum.with_index()
|> intersperse_map(" AND ", fn
{{field, nil}, _idx} ->
["isNull(", quote_name(field), ?)]
{{field, value}, idx} ->
[quote_name(field), ?=, build_param(idx, value)]
end)
["DELETE FROM ", quote_table(prefix, table), " WHERE ", filters]
end
@impl true
def explain_query(conn, query, params, opts) do
explain =
case Keyword.get(opts, :type, :plan) do
:ast -> "EXPLAIN AST "
:syntax -> "EXPLAIN SYNTAX "
:query_tree -> "EXPLAIN QUERY TREE "
:plan -> "EXPLAIN PLAN "
:pipeline -> "EXPLAIN PIPELINE "
:table_override -> "EXPLAIN TABLE OVERRIDE"
end
explain_query = [explain | query]
with {:ok, %{rows: rows}} <- query(conn, explain_query, params, opts) do
{:ok, rows}
end
end
binary_ops = [
==: " = ",
!=: " != ",
<=: " <= ",
>=: " >= ",
<: " < ",
>: " > ",
+: " + ",
-: " - ",
*: " * ",
/: " / ",
# TODO ilike()
ilike: " ILIKE ",
# TODO like()
like: " LIKE ",
# TODO in()
in: " IN "
]
@binary_ops Keyword.keys(binary_ops)
for {op, str} <- binary_ops do
defp handle_call(unquote(op), 2), do: {:binary_op, unquote(str)}
end
defp handle_call(fun, _arity), do: {:fun, Atom.to_string(fun)}
defp select(%{select: %{fields: fields}, distinct: distinct} = query, sources, params) do
[
"SELECT ",
distinct(distinct, sources, params, query)
| select_fields(fields, sources, params, query)
]
end
defp select_fields([], _sources, _params, _query), do: "true"
defp select_fields(fields, sources, params, query) do
intersperse_map(fields, ?,, fn
# TODO raise
# this is useful in array joins lie
#
# "arrays_test"
# |> join(:array, [a], r in "arr")
# |> select([a, r], {a.s, fragment("?", r)})
#
{:&, _, [idx]} ->
{_, source, _} = elem(sources, idx)
source
{k, v} ->
[expr(v, sources, params, query), " AS " | quote_name(k)]
v ->
expr(v, sources, params, query)
end)
end
defp distinct(nil, _sources, _params, _query), do: []
defp distinct(%{expr: true}, _sources, _params, _query), do: "DISTINCT "
defp distinct(%{expr: false}, _sources, _params, _query), do: []
defp distinct(%{expr: exprs}, sources, params, query) when is_list(exprs) do
[
"DISTINCT ON (",
intersperse_map(exprs, ?,, &order_by_expr(&1, sources, params, query)) | ") "
]
end
defp from(%{from: %{source: source, hints: hints}} = query, sources, params) do
{from, name} = get_source(query, sources, params, 0, source)
[" FROM ", from, " AS ", name | hints(hints)]
end
def cte(
%{with_ctes: %WithExpr{recursive: recursive, queries: [_ | _] = queries}} = query,
sources,
params
) do
recursive_opt = if recursive, do: "RECURSIVE ", else: ""
ctes =
intersperse_map(queries, ?,, fn {name, _opts, cte} ->
[quote_name(name), " AS ", cte_query(cte, sources, params, query)]
end)
["WITH ", recursive_opt, ctes, " "]
end
def cte(%{with_ctes: _}, _sources, _params), do: []
defp cte_query(%Ecto.Query{} = query, sources, params, parent_query) do
query = put_in(query.aliases[@parent_as], {parent_query, sources})
[?(, all(query, params, subquery_as_prefix(sources)), ?)]
end
defp cte_query(%QueryExpr{expr: expr}, sources, params, query) do
expr(expr, sources, params, query)
end
defp join(%{joins: []}, _sources, _params), do: []
defp join(%{joins: joins} = query, sources, params) do
Enum.map(joins, fn
%JoinExpr{qual: qual, ix: ix, source: source, on: %QueryExpr{expr: on_exrp}, hints: hints} ->
{join, name} = get_source(query, sources, params, ix, source)
[
join_hints(hints, query),
join_qual(qual, hints),
join,
" AS ",
name
| join_on(qual, on_exrp, hints, sources, params, query)
]
end)
end
# TODO maybe add GLOBAL and PASTE
valid_join_strictness_hints = ["ASOF", "ANY", "ANTI", "SEMI"]
valid_join_hints = valid_join_strictness_hints ++ ["ARRAY"]
for hint <- valid_join_strictness_hints do
hints = List.wrap(hint)
defp join_hints(unquote(hints), _query) do
unquote(" " <> Enum.join(hints, " "))
end
end
defp join_hints(["ARRAY"], _query), do: []
defp join_hints([], _query), do: []
defp join_hints(hints, query) do
supported = unquote(valid_join_hints) |> Enum.map(&inspect/1) |> Enum.join(", ")
raise Ecto.QueryError,
query: query,
message: """
unsupported JOIN strictness or type passed in hints: #{inspect(hints)}
supported: #{supported}
"""
end
defp join_on(:cross, true, _hints, _sources, _params, _query), do: []
defp join_on(_qual, true, ["ARRAY"], _sources, _params, _query) do
[]
end
defp join_on(_qual, expr, _hints, sources, params, query) do
[" ON " | expr(expr, sources, params, query)]
end
defp join_qual(:inner, ["ARRAY"]), do: " ARRAY JOIN "
defp join_qual(:inner, _hints), do: " INNER JOIN "
defp join_qual(:left, ["ARRAY"]), do: " LEFT ARRAY JOIN "
defp join_qual(:left, _hints), do: " LEFT JOIN "
defp join_qual(:right, _hints), do: " RIGHT JOIN "
defp join_qual(:full, _hints), do: " FULL JOIN "
defp join_qual(:cross, _hints), do: " CROSS JOIN "
defp join_qual(qual, _hints) do
raise ArgumentError, "join type #{inspect(qual)} is not supported"
end
defp where(%{wheres: wheres} = query, sources, params) do
boolean(" WHERE ", wheres, sources, params, query)
end
defp having(%{havings: havings} = query, sources, params) do
boolean(" HAVING ", havings, sources, params, query)
end
defp group_by(%{group_bys: []}, _sources, _params), do: []
defp group_by(%{group_bys: group_bys} = query, sources, params) do
[
" GROUP BY "
| intersperse_map(group_bys, ?,, fn %ByExpr{expr: expr} ->
intersperse_map(expr, ?,, &expr(&1, sources, params, query))
end)
]
end
defp window(%{windows: []}, _sources, _params), do: []
defp window(%{windows: windows} = query, sources, params) do
[
" WINDOW "
| intersperse_map(windows, ?,, fn {name, %{expr: kw}} ->
[quote_name(name), " AS " | window_exprs(kw, sources, params, query)]
end)
]
end
defp window_exprs(kw, sources, params, query) do
[
?(,
intersperse_map(kw, ?\s, &window_expr(&1, sources, params, query)),
?)
]
end
defp window_expr({:partition_by, fields}, sources, params, query) do
["PARTITION BY " | intersperse_map(fields, ?,, &expr(&1, sources, params, query))]
end
defp window_expr({:order_by, fields}, sources, params, query) do
["ORDER BY " | intersperse_map(fields, ?,, &order_by_expr(&1, sources, params, query))]
end
defp window_expr({:frame, {:fragment, _, _} = fragment}, sources, params, query) do
expr(fragment, sources, params, query)
end
defp order_by(%{order_bys: []}, _sources, _params), do: []
defp order_by(%{order_bys: order_bys} = query, sources, params) do
[
" ORDER BY "
| intersperse_map(order_bys, ?,, fn %{expr: expr} ->
intersperse_map(expr, ?,, &order_by_expr(&1, sources, params, query))
end)
]
end
defp order_by_expr({dir, expr}, sources, params, query) do
str = expr(expr, sources, params, query)
case dir do
:asc ->
str
:desc ->
[str | " DESC"]
:asc_nulls_first ->
[str | " ASC NULLS FIRST"]
:desc_nulls_first ->
[str | " DESC NULLS FIRST"]
:asc_nulls_last ->
[str | " ASC NULLS LAST"]
:desc_nulls_last ->
[str | " DESC NULLS LAST"]
_ ->
raise Ecto.QueryError,
query: query,
message: "ClickHouse does not support #{dir} in ORDER BY"
end
end
defp limit(%{limit: nil}, _sources, _params), do: []
defp limit(%{limit: %{expr: expr}} = query, sources, params) do
[" LIMIT ", expr(expr, sources, params, query)]
end
defp offset(%{offset: nil}, _sources, _params), do: []
defp offset(%{offset: %{expr: expr}} = query, sources, params) do
[" OFFSET ", expr(expr, sources, params, query)]
end
defp combinations(%{combinations: combinations}, params) do
Enum.map(combinations, &combination(&1, params))
end
defp combination({:union, query}, params), do: [" UNION DISTINCT (", all(query, params), ?)]
defp combination({:union_all, query}, params), do: [" UNION ALL (", all(query, params), ?)]
defp combination({:except, query}, params), do: [" EXCEPT (", all(query, params), ?)]
defp combination({:intersect, query}, params), do: [" INTERSECT (", all(query, params), ?)]
defp combination({:except_all, query}, _params) do
raise Ecto.QueryError,
query: query,
message: "ClickHouse does not support EXCEPT ALL"
end
defp combination({:intersect_all, query}, _params) do
raise Ecto.QueryError,
query: query,
message: "ClickHouse does not support INTERSECT ALL"
end
defp hints([_ | _] = hints) do
[" " | intersperse_map(hints, ?\s, &hint/1)]
end
defp hints([]), do: []
defp hint(hint) when is_binary(hint), do: hint
# TODO remove once it's no longer used in plausible/analytics
# https://github.com/elixir-ecto/ecto/pull/4254
defp hint({k, v}) when is_atom(k) and is_integer(v) do
[Atom.to_string(k), ?\s, Integer.to_string(v)]
end
defp boolean(_name, [], _sources, _params, _query), do: []
defp boolean(name, [%{expr: expr, op: op} | exprs], sources, params, query) do
result =
Enum.reduce(exprs, {op, paren_expr(expr, sources, params, query)}, fn
%BooleanExpr{expr: expr, op: op}, {op, acc} ->
{op, [acc, operator_to_boolean(op) | paren_expr(expr, sources, params, query)]}
%BooleanExpr{expr: expr, op: op}, {_, acc} ->
{op, [?(, acc, ?), operator_to_boolean(op) | paren_expr(expr, sources, params, query)]}
end)
[name | elem(result, 1)]
end
defp operator_to_boolean(:and), do: " AND "
defp operator_to_boolean(:or), do: " OR "
defp parens_for_select([first_expr | _] = expression) do
if is_binary(first_expr) and String.match?(first_expr, ~r/^\s*select/i) do
[?(, expression, ?)]
else
expression
end
end
defp paren_expr(expr, sources, params, query) do
[?(, expr(expr, sources, params, query), ?)]
end
defp expr({_type, [literal]}, sources, params, query) do
expr(literal, sources, params, query)
end
defp expr({:^, [], [ix]}, _sources, params, _query) do
build_param(ix, Enum.at(params, ix))
end
defp expr({:^, [], [ix, len]}, _sources, params, _query) when len > 0 do
[?(, build_params(ix, len, params), ?)]
end
# using an empty array literal since empty tuples are not allowed in ClickHouse
defp expr({:^, [], [_, 0]}, _sources, _params, _query), do: "[]"
defp expr({{:., _, [{:&, _, [ix]}, field]}, _, []}, sources, _params, _query)
when is_atom(field) do
quote_qualified_name(field, sources, ix)
end
defp expr({{:., _, [{:parent_as, _, [as]}, field]}, _, []}, _sources, _params, query)
when is_atom(field) do
{ix, sources} = get_parent_sources_ix(query, as)
quote_qualified_name(field, sources, ix)
end
defp expr({:&, _, [ix]}, sources, _params, _query) do
{_, source, _} = elem(sources, ix)
source
end
defp expr({:&, _, [idx, fields, _counter]}, sources, _params, query) do
{_, name, schema} = elem(sources, idx)
if is_nil(schema) and is_nil(fields) do
raise Ecto.QueryError,
query: query,
message:
"ClickHouse requires a schema module when using selector " <>
"#{inspect(name)} but none was given. " <>
"Please specify a schema or specify exactly which fields from " <>
"#{inspect(name)} you desire"
end
intersperse_map(fields, ?,, &[name, ?. | quote_name(&1)])
end
defp expr({:in, _, [_left, []]}, _sources, _params, _query), do: "0"
defp expr({:in, _, [left, right]}, sources, params, query) when is_list(right) do
args = intersperse_map(right, ?,, &expr(&1, sources, params, query))
[expr(left, sources, params, query), " IN (", args, ?)]
end
defp expr({:in, _, [_, {:^, _, [_ix, 0]}]}, _sources, _params, _query), do: "0"
defp expr({:in, _, [left, right]}, sources, params, query) do
[expr(left, sources, params, query), " IN ", expr(right, sources, params, query)]
end
defp expr({:is_nil, _, [arg]}, sources, params, query) do
["isNull(", expr(arg, sources, params, query), ?)]
end
defp expr({:not, _, [expr]}, sources, params, query) do
case expr do
{:is_nil, _, [arg]} ->
["isNotNull(", expr(arg, sources, params, query), ?)]
{:like, _, [l, r]} ->
["notLike(", expr(l, sources, params, query), ", ", expr(r, sources, params, query), ?)]
{:ilike, _, [l, r]} ->
["notILike(", expr(l, sources, params, query), ", ", expr(r, sources, params, query), ?)]
# TODO notIn()
_other ->
["not(", expr(expr, sources, params, query), ?)]
end
end
defp expr({:filter, _, [agg, filter]}, sources, params, query) do
[
expr(agg, sources, params, query),
" FILTER (WHERE ",
expr(filter, sources, params, query),
?)
]
end
defp expr(%SubQuery{query: query}, sources, params, parent_query) do
query = put_in(query.aliases[@parent_as], {parent_query, sources})
[?(, all(query, params, subquery_as_prefix(sources)), ?)]
end
defp expr({:fragment, _, [kw]}, _sources, _params, query)
when is_list(kw) or tuple_size(kw) == 3 do
raise Ecto.QueryError,
query: query,
message: "ClickHouse adapter does not support keyword or interpolated fragments"
end
defp expr({:fragment, _, parts}, sources, params, query) do
parts
|> Enum.map(fn
{:raw, part} -> part
{:expr, expr} -> expr(expr, sources, params, query)
end)
|> parens_for_select()
end
defp expr({:literal, _, [literal]}, _sources, _params, _query) do
quote_name(literal)
end
defp expr({:selected_as, _, [name]}, _sources, _params, _query) do
quote_name(name)
end
defp expr({:over, _, [agg, name]}, sources, params, query) when is_atom(name) do
[expr(agg, sources, params, query), " OVER " | quote_name(name)]
end
defp expr({:over, _, [agg, kw]}, sources, params, query) do
[expr(agg, sources, params, query), " OVER " | window_exprs(kw, sources, params, query)]
end
defp expr({:{}, _, elems}, sources, params, query) do
[?(, intersperse_map(elems, ?,, &expr(&1, sources, params, query)), ?)]
end
defp expr({:count, _, []}, _sources, _params, _query), do: "count(*)"
defp expr({:count, _, [expr]}, sources, params, query) do
["count(", expr(expr, sources, params, query), ?)]
end
defp expr({:count, _, [expr, :distinct]}, sources, params, query) do
["countDistinct(", expr(expr, sources, params, query), ?)]
end
defp expr({:datetime_add, _, [datetime, count, interval]}, sources, params, query) do
[
expr(datetime, sources, params, query),
" + ",
interval(count, interval, sources, params, query)
]
end
defp expr({:date_add, _, [date, count, interval]}, sources, params, query) do
[
"CAST(",
expr(date, sources, params, query),
" + ",
interval(count, interval, sources, params, query)
| " AS Date)"
]
end
defp expr({:json_extract_path, _, [expr, path]}, sources, params, query) do
path =
Enum.map(path, fn
bin when is_binary(bin) -> [?., escape_json_key(bin)]
int when is_integer(int) -> [?[, Integer.to_string(int), ?]]
end)
["JSON_QUERY(", expr(expr, sources, params, query), ", '$", path | "')"]
end
# TODO parens?
defp expr({:exists, _, [subquery]}, sources, params, query) do
["exists" | expr(subquery, sources, params, query)]
end
defp expr({op, _, [l, r]}, sources, params, query) when op in [:and, :or] do
[
logical_expr(op, l, sources, params, query),
operator_to_boolean(op),
logical_expr(op, r, sources, params, query)
]
end
defp expr({fun, _, args}, sources, params, query) when is_atom(fun) and is_list(args) do
case handle_call(fun, length(args)) do
{:binary_op, op} ->
[left, right] = args
[
maybe_paren_expr(left, sources, params, query),
op | maybe_paren_expr(right, sources, params, query)
]
{:fun, fun} ->
[fun, ?(, intersperse_map(args, ?,, &expr(&1, sources, params, query)), ?)]
end
end
defp expr(list, sources, params, query) when is_list(list) do
[?[, intersperse_map(list, ?,, &expr(&1, sources, params, query)), ?]]
end
defp expr(%Decimal{} = decimal, _sources, _params, _query) do
Decimal.to_string(decimal, :normal)
end
defp expr(%Tagged{value: value, type: :any}, sources, params, query) do
expr(value, sources, params, query)
end
defp expr(%Tagged{value: value, type: type}, sources, params, query) do
["CAST(", expr(value, sources, params, query), " AS ", ecto_to_db(type, query), ?)]
end
defp expr(nil, _sources, _params, _query), do: "NULL"
# TODO "true" / "false"?
defp expr(true, _sources, _params, _query), do: "1"
defp expr(false, _sources, _params, _query), do: "0"
defp expr(literal, _sources, _params, _query) when is_binary(literal) do
[?', escape_string(literal), ?']
end
defp expr(literal, _sources, _params, _query) when is_integer(literal) do
inline_param(literal)
end
defp expr(literal, _sources, _params, _query) when is_float(literal) do
Float.to_string(literal)
end
defp expr(expr, _sources, _params, query) do
raise Ecto.QueryError,
query: query,
message: "unsupported expression #{inspect(expr)}"
end
defp logical_expr(parent_op, expr, sources, params, query) do
case expr do
{^parent_op, _, [l, r]} ->
[
logical_expr(parent_op, l, sources, params, query),
operator_to_boolean(parent_op),
logical_expr(parent_op, r, sources, params, query)
]
{op, _, [l, r]} when op in [:and, :or] ->
[
?(,
logical_expr(op, l, sources, params, query),
operator_to_boolean(op),
logical_expr(op, r, sources, params, query),
?)
]
_ ->
maybe_paren_expr(expr, sources, params, query)
end
end
defp maybe_paren_expr({op, _, [_, _]} = expr, sources, params, query) when op in @binary_ops do
paren_expr(expr, sources, params, query)
end
defp maybe_paren_expr(expr, sources, params, query) do
expr(expr, sources, params, query)
end
defp create_names(%{sources: sources}, as_prefix) do
sources |> create_names(0, tuple_size(sources), as_prefix) |> List.to_tuple()
end
defp create_names(sources, pos, limit, as_prefix) when pos < limit do
[create_name(sources, pos, as_prefix) | create_names(sources, pos + 1, limit, as_prefix)]
end
defp create_names(_sources, pos, pos, as_prefix), do: [as_prefix]
defp subquery_as_prefix(sources) do
[?s | :erlang.element(tuple_size(sources), sources)]
end
defp create_name(sources, pos, as_prefix) do
case elem(sources, pos) do
{:fragment, _, _} ->
{nil, as_prefix ++ [?f | Integer.to_string(pos)], nil}
{table, schema, prefix} ->
name = as_prefix ++ [create_alias(table) | Integer.to_string(pos)]
{quote_table(prefix, table), name, schema}
%SubQuery{} ->
{nil, as_prefix ++ [?s | Integer.to_string(pos)], nil}
end
end
defp create_alias(<<first, _rest::bytes>>)
when first in ?a..?z
when first in ?A..?Z do
<<first>>
end
defp create_alias(_), do: ?t
@doc false
def intersperse_map([elem], _separator, mapper), do: [mapper.(elem)]
def intersperse_map([elem | rest], separator, mapper) do
[mapper.(elem), separator | intersperse_map(rest, separator, mapper)]
end
def intersperse_map([], _separator, _mapper), do: []
@inline_tag :__ecto_ch_inline__
@doc false
def mark_inline(param), do: {@inline_tag, param}
@compile inline: [build_param: 2]
defp build_param(ix, param) do
case param do
{@inline_tag, param} -> inline_param(param)
param -> ["{$", Integer.to_string(ix), ?:, param_type(param), ?}]
end
end
@doc false
def build_params(ix, len, params) when len > 1 do
[build_param(ix, Enum.at(params, ix)), ?, | build_params(ix + 1, len - 1, params)]
end
def build_params(ix, _len = 1, params), do: build_param(ix, Enum.at(params, ix))
def build_params(_ix, _len = 0, _params), do: []
@doc false
def quote_name(name, quoter \\ ?")
def quote_name(nil, _), do: []
def quote_name(names, quoter) when is_list(names) do
names
|> Enum.reject(&is_nil/1)
|> intersperse_map(?., "e_name(&1, nil))
|> wrap_in(quoter)
end
def quote_name(name, quoter) when is_atom(name) do
name |> Atom.to_string() |> quote_name(quoter)
end
def quote_name(name, quoter) do
wrap_in(name, quoter)
end
defp quote_qualified_name(name, sources, ix) do
{_, source, _} = elem(sources, ix)
case source do
nil -> quote_name(name)
_other -> [source, ?. | quote_name(name)]
end
end
@doc false
def quote_table(prefix, name)
def quote_table(nil, name), do: quote_name(name)
def quote_table(prefix, name), do: [quote_name(prefix), ?., quote_name(name)]
defp wrap_in(value, nil), do: value
defp wrap_in(value, wrapper), do: [wrapper, value, wrapper]
@doc false
# TODO faster?
def escape_string(value) when is_binary(value) do
value
|> :binary.replace("'", "''", [:global])
|> :binary.replace("\\", "\\\\", [:global])
end