forked from elixir-sqlite/ecto_sqlite3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection.ex
More file actions
1990 lines (1631 loc) · 51.5 KB
/
connection.ex
File metadata and controls
1990 lines (1631 loc) · 51.5 KB
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.SQLite3.Connection do
@moduledoc false
@behaviour Ecto.Adapters.SQL.Connection
alias Ecto.Adapters.SQL
alias Ecto.Migration.Constraint
alias Ecto.Migration.Index
alias Ecto.Migration.Reference
alias Ecto.Migration.Table
alias Ecto.Query.BooleanExpr
alias Ecto.Query.ByExpr
alias Ecto.Query.JoinExpr
alias Ecto.Query.QueryExpr
alias Ecto.Query.WithExpr
import Ecto.Adapters.SQLite3.DataType
@parent_as __MODULE__
defp default_opts(opts) do
opts
|> Keyword.put_new(:journal_mode, :wal)
|> Keyword.put_new(:cache_size, -64_000)
|> Keyword.put_new(:temp_store, :memory)
|> Keyword.put_new(:pool_size, 5)
end
def start_link(opts) do
opts = default_opts(opts)
DBConnection.start_link(Exqlite.Connection, opts)
end
@impl true
def child_spec(options) do
{:ok, _} = Application.ensure_all_started(:db_connection)
options = default_opts(options)
DBConnection.child_spec(Exqlite.Connection, options)
end
@impl true
def prepare_execute(conn, name, sql, params, options) do
query = Exqlite.Query.build(name: name, statement: sql)
case DBConnection.prepare_execute(conn, query, params, options) do
{:ok, _, _} = ok -> ok
{:error, %Exqlite.Error{}} = error -> error
{:error, err} -> raise err
end
end
@impl true
def execute(conn, %Exqlite.Query{ref: ref} = cached, params, options)
when ref != nil do
DBConnection.execute(conn, cached, params, options)
end
def execute(
conn,
%Exqlite.Query{statement: statement, ref: nil},
params,
options
) do
execute(conn, statement, params, options)
end
def execute(conn, sql, params, options) when is_binary(sql) or is_list(sql) do
query = Exqlite.Query.build(name: "", statement: IO.iodata_to_binary(sql))
case DBConnection.prepare_execute(conn, query, params, options) do
{:ok, %Exqlite.Query{}, result} -> {:ok, result}
{:error, %Exqlite.Error{}} = error -> error
{:error, err} -> raise err
end
end
def execute(conn, query, params, options) do
case DBConnection.execute(conn, query, params, options) do
{:ok, _} = ok -> ok
{:error, %ArgumentError{} = err} -> {:reset, err}
{:error, %Exqlite.Error{}} = error -> error
{:error, err} -> raise err
end
end
@impl true
def query(conn, sql, params, options) do
query = Exqlite.Query.build(statement: IO.iodata_to_binary(sql))
case DBConnection.execute(conn, query, params, options) do
{:ok, _, result} -> {:ok, result}
other -> other
end
end
@impl true
def query_many(_conn, _sql, _params, _opts) do
raise RuntimeError, "query_many is not supported in the SQLite3 adapter"
end
@impl true
def stream(conn, sql, params, options) do
query = Exqlite.Query.build(statement: sql)
DBConnection.stream(conn, query, params, options)
end
# we want to return the name of the underlying index that caused
# the constraint error, but in SQLite as far as I can tell there
# is no way to do this, so we name the index according to ecto
# convention, even if technically it _could_ have a different name
defp constraint_name_hack(constraint) do
if String.contains?(constraint, ", ") do
# "a.b, a.c" -> a_b_c_index
constraint
|> String.split(", ")
|> Enum.with_index()
|> Enum.map(fn
{table_col, 0} ->
String.replace(table_col, ".", "_")
{table_col, _} ->
table_col
|> String.split(".")
|> List.last()
end)
|> Enum.concat(["index"])
|> Enum.join("_")
else
constraint
|> String.split(".")
|> Enum.concat(["index"])
|> Enum.join("_")
end
end
@impl true
def to_constraints(
%Exqlite.Error{message: "UNIQUE constraint failed: index " <> constraint},
_opts
) do
[unique: String.trim(constraint, ~s('))]
end
def to_constraints(
%Exqlite.Error{message: "UNIQUE constraint failed: " <> constraint},
_opts
) do
[unique: constraint_name_hack(constraint)]
end
def to_constraints(%Exqlite.Error{message: "FOREIGN KEY constraint failed"}, _opts) do
# unfortunately we have no other date from SQLite
[foreign_key: nil]
end
def to_constraints(
%Exqlite.Error{message: "CHECK constraint failed: " <> name},
_opts
) do
[check: name]
end
def to_constraints(_, _), do: []
##
## Queries
##
@impl true
def all(%Ecto.Query{lock: lock}) when lock != nil do
raise ArgumentError, "locks are not supported by SQLite3"
end
def all(query, as_prefix \\ []) do
sources = create_names(query, as_prefix)
cte = cte(query, sources)
from = from(query, sources)
select = select(query, sources)
join = join(query, sources)
where = where(query, sources)
group_by = group_by(query, sources)
having = having(query, sources)
window = window(query, sources)
combinations = combinations(query, as_prefix)
order_by = order_by(query, sources)
limit = limit(query, sources)
offset = offset(query, sources)
[
cte,
select,
from,
join,
where,
group_by,
having,
window,
combinations,
order_by,
limit,
offset
]
end
@impl true
def update_all(query, prefix \\ nil) do
%{from: %{source: source}} = query
sources = create_names(query, [])
cte = cte(query, sources)
{from, name} = get_source(query, sources, 0, source)
fields =
if prefix do
update_fields(:on_conflict, query, sources)
else
update_fields(:update, query, sources)
end
# TODO: Add support for `update or rollback foo`
{join, wheres} = using_join(query, :update_all, "FROM", sources)
prefix = prefix || ["UPDATE ", from, " AS ", name, " SET "]
where = where(%{query | wheres: wheres ++ query.wheres}, sources)
[
cte,
prefix,
fields,
join,
where,
returning(query, sources)
]
end
@impl true
def delete_all(%Ecto.Query{joins: [_ | _]}) do
# TODO: It is supported but not in the traditional sense
raise ArgumentError, "JOINS are not supported on DELETE statements by SQLite"
end
def delete_all(query) do
sources = create_names(query, [])
cte = cte(query, sources)
from = from(query, sources)
where = where(query, sources)
[
cte,
"DELETE",
from,
where,
returning(query, sources)
]
end
@impl true
def insert(prefix, table, [], [[]], on_conflict, returning, []) do
[
"INSERT INTO ",
quote_table(prefix, table),
insert_as(on_conflict),
" DEFAULT VALUES",
returning(returning)
]
end
def insert(prefix, table, header, rows, on_conflict, returning, placeholders) do
counter_offset = length(placeholders) + 1
values =
if header == [] do
[" VALUES " | Enum.map_intersperse(rows, ?,, fn _ -> "(DEFAULT)" end)]
else
[" (", quote_names(header), ") " | insert_all(rows, counter_offset)]
end
[
"INSERT INTO ",
quote_table(prefix, table),
insert_as(on_conflict),
values,
on_conflict(on_conflict, header),
returning(returning)
]
end
@impl true
def update(prefix, table, fields, filters, returning) do
fields = Enum.map_intersperse(fields, ", ", &[quote_name(&1), " = ?"])
filters =
Enum.map_intersperse(filters, " AND ", fn
{field, nil} ->
[quote_name(field), " IS NULL"]
{field, _value} ->
[quote_name(field), " = ?"]
end)
[
"UPDATE ",
quote_table(prefix, table),
" SET ",
fields,
" WHERE ",
filters,
returning(returning)
]
end
@impl true
def delete(prefix, table, filters, returning) do
filters =
Enum.map_intersperse(filters, " AND ", fn
{field, nil} ->
[quote_name(field), " IS NULL"]
{field, _value} ->
[quote_name(field), " = ?"]
end)
[
"DELETE FROM ",
quote_table(prefix, table),
" WHERE ",
filters,
returning(returning)
]
end
@impl true
def explain_query(conn, query, params, opts) do
type = Keyword.get(opts, :type, :query_plan)
case query(conn, build_explain_query(query, type), params, opts) do
{:ok, %Exqlite.Result{} = result} ->
case type do
:query_plan -> {:ok, format_query_plan_explain(result)}
:instructions -> {:ok, SQL.format_table(result)}
end
error ->
error
end
end
def build_explain_query(query, :query_plan) do
IO.iodata_to_binary(["EXPLAIN QUERY PLAN ", query])
end
def build_explain_query(query, :instructions) do
IO.iodata_to_binary(["EXPLAIN ", query])
end
# Mimics the ASCII format of the sqlite CLI
defp format_query_plan_explain(%{rows: rows}) do
{lines, _} =
rows
|> Enum.chunk_every(2, 1, [nil])
|> Enum.map_reduce(0, fn [[id, parent, _, text], next], depth ->
{branch, next_depth} =
case {id, parent, next} do
{id, _, [_, id, _, _]} -> {"|--", depth + 1}
{_, p, [_, p, _, _]} -> {"|--", depth}
_ -> {"`--", depth - 1}
end
formatted_line = String.duplicate("| ", depth) <> branch <> text
{formatted_line, next_depth}
end)
Enum.join(["QUERY PLAN" | lines], "\n")
end
##
## DDL
##
@impl true
def execute_ddl({_command, %Table{options: options}, _}) when is_list(options) do
raise ArgumentError, "SQLite3 adapter does not support keyword lists in :options"
end
def execute_ddl({:create, %Table{} = table, columns}) do
{table, composite_pk_def} = composite_pk_definition(table, columns)
composite_fk_defs = composite_fk_definitions(table, columns)
[
[
"CREATE TABLE ",
quote_table(table.prefix, table.name),
?\s,
?(,
column_definitions(table, columns),
composite_pk_def,
composite_fk_defs,
?),
options_expr(table.options)
]
]
end
def execute_ddl({:create_if_not_exists, %Table{} = table, columns}) do
{table, composite_pk_def} = composite_pk_definition(table, columns)
composite_fk_defs = composite_fk_definitions(table, columns)
[
[
"CREATE TABLE IF NOT EXISTS ",
quote_table(table.prefix, table.name),
?\s,
?(,
column_definitions(table, columns),
composite_pk_def,
composite_fk_defs,
?),
options_expr(table.options)
]
]
end
def execute_ddl({:drop, %Table{} = table}) do
[
[
"DROP TABLE ",
quote_table(table.prefix, table.name)
]
]
end
def execute_ddl({:drop, %Table{} = table, _mode}) do
execute_ddl({:drop, table})
end
def execute_ddl({:drop_if_exists, %Table{} = table}) do
[
[
"DROP TABLE IF EXISTS ",
quote_table(table.prefix, table.name)
]
]
end
def execute_ddl({:drop_if_exists, %Table{} = table, _mode}) do
execute_ddl({:drop_if_exists, table})
end
def execute_ddl({:alter, %Table{} = table, changes}) do
Enum.map(changes, fn change ->
[
"ALTER TABLE ",
quote_table(table.prefix, table.name),
?\s,
column_change(table, change)
]
end)
end
@impl true
def execute_ddl({_, %Index{concurrently: true}}) do
raise ArgumentError, "`concurrently` is not supported with SQLite3"
end
@impl true
def execute_ddl({_, %Index{only: true}}) do
raise ArgumentError, "`only` is not supported with SQLite3"
end
@impl true
def execute_ddl({_, %Index{include: x}}) when length(x) != 0 do
raise ArgumentError, "`include` is not supported with SQLite3"
end
@impl true
def execute_ddl({_, %Index{using: x}}) when not is_nil(x) do
raise ArgumentError, "`using` is not supported with SQLite3"
end
@impl true
def execute_ddl({_, %Index{nulls_distinct: x}}) when not is_nil(x) do
raise ArgumentError, "`nulls_distinct` is not supported with SQLite3"
end
@impl true
def execute_ddl({:create, %Index{} = index}) do
fields = Enum.map_intersperse(index.columns, ", ", &index_expr/1)
[
[
"CREATE ",
if_do(index.unique, "UNIQUE "),
"INDEX ",
quote_name(index.name),
" ON ",
quote_table(index.prefix, index.table),
" (",
fields,
?),
if_do(index.where, [" WHERE ", to_string(index.where)])
]
]
end
@impl true
def execute_ddl({:create_if_not_exists, %Index{} = index}) do
fields = Enum.map_intersperse(index.columns, ", ", &index_expr/1)
[
[
"CREATE ",
if_do(index.unique, "UNIQUE "),
"INDEX IF NOT EXISTS ",
quote_name(index.name),
" ON ",
quote_table(index.prefix, index.table),
" (",
fields,
?),
if_do(index.where, [" WHERE ", to_string(index.where)])
]
]
end
@impl true
def execute_ddl({:drop, %Index{} = index}) do
[
[
"DROP INDEX ",
quote_table(index.prefix, index.name)
]
]
end
@impl true
def execute_ddl({:drop, %Index{} = index, _mode}) do
execute_ddl({:drop, index})
end
@impl true
def execute_ddl({:drop_if_exists, %Index{concurrently: true}}) do
raise ArgumentError, "`concurrently` is not supported with SQLite3"
end
@impl true
def execute_ddl({:drop_if_exists, %Index{} = index}) do
[
[
"DROP INDEX IF EXISTS ",
quote_table(index.prefix, index.name)
]
]
end
@impl true
def execute_ddl({:drop_if_exists, %Index{} = index, _mode}) do
execute_ddl({:drop_if_exists, index})
end
@impl true
def execute_ddl({:rename, %Table{} = current_table, %Table{} = new_table}) do
[
[
"ALTER TABLE ",
quote_table(current_table.prefix, current_table.name),
" RENAME TO ",
quote_table(nil, new_table.name)
]
]
end
@impl true
def execute_ddl({:rename, %Table{} = current_table, old_col, new_col}) do
[
[
"ALTER TABLE ",
quote_table(current_table.prefix, current_table.name),
" RENAME COLUMN ",
quote_name(old_col),
" TO ",
quote_name(new_col)
]
]
end
@impl true
def execute_ddl(string) when is_binary(string), do: [string]
@impl true
def execute_ddl(keyword) when is_list(keyword) do
raise ArgumentError, "SQLite3 adapter does not support keyword lists in execute"
end
@impl true
def execute_ddl({:create, %Index{} = index}) do
fields = Enum.map_intersperse(index.columns, ", ", &index_expr/1)
[
[
"CREATE ",
if_do(index.unique, "UNIQUE "),
"INDEX",
?\s,
quote_name(index.name),
" ON ",
quote_table(index.prefix, index.table),
" (",
fields,
?),
if_do(index.where, [" WHERE ", to_string(index.where)])
]
]
end
def execute_ddl({:create_if_not_exists, %Index{} = index}) do
fields = Enum.map_intersperse(index.columns, ", ", &index_expr/1)
[
[
"CREATE ",
if_do(index.unique, "UNIQUE "),
"INDEX IF NOT EXISTS",
?\s,
quote_name(index.name),
" ON ",
quote_table(index.prefix, index.table),
" (",
fields,
?),
if_do(index.where, [" WHERE ", to_string(index.where)])
]
]
end
def execute_ddl({:create, %Constraint{}}) do
raise ArgumentError, "SQLite3 does not support ALTER TABLE ADD CONSTRAINT."
end
def execute_ddl({:drop, %Index{} = index}) do
[
[
"DROP INDEX ",
quote_table(index.prefix, index.name)
]
]
end
def execute_ddl({:drop, %Index{} = index, _mode}) do
execute_ddl({:drop, index})
end
def execute_ddl({:drop_if_exists, %Index{} = index}) do
[
[
"DROP INDEX IF EXISTS ",
quote_table(index.prefix, index.name)
]
]
end
def execute_ddl({:drop_if_exists, %Index{} = index, _mode}) do
execute_ddl({:drop_if_exists, index})
end
def execute_ddl({:drop, %Constraint{}, _mode}) do
raise ArgumentError, "SQLite3 does not support ALTER TABLE DROP CONSTRAINT."
end
def execute_ddl({:drop_if_exists, %Constraint{}, _mode}) do
raise ArgumentError, "SQLite3 does not support ALTER TABLE DROP CONSTRAINT."
end
def execute_ddl({:rename, %Table{} = current_table, %Table{} = new_table}) do
[
[
"ALTER TABLE ",
quote_table(current_table.prefix, current_table.name),
" RENAME TO ",
quote_table(new_table.prefix, new_table.name)
]
]
end
def execute_ddl({:rename, %Table{} = table, current_column, new_column}) do
[
[
"ALTER TABLE ",
quote_table(table.prefix, table.name),
" RENAME COLUMN ",
quote_name(current_column),
" TO ",
quote_name(new_column)
]
]
end
def execute_ddl({:rename, %Index{} = index, new_index}) do
[
execute_ddl({:drop, index}),
execute_ddl({:create, %Index{index | name: new_index}})
]
end
def execute_ddl(string) when is_binary(string), do: [string]
def execute_ddl(keyword) when is_list(keyword) do
raise ArgumentError, "SQLite3 adapter does not support keyword lists in execute"
end
@impl true
def ddl_logs(_), do: []
@impl true
def table_exists_query(table) do
{"SELECT name FROM sqlite_master WHERE type='table' AND name=? LIMIT 1", [table]}
end
##
## Query generation
##
defp on_conflict({:raise, _, []}, _header), do: []
defp on_conflict({:nothing, _, targets}, _header) do
[" ON CONFLICT ", conflict_target(targets) | "DO NOTHING"]
end
defp on_conflict({:replace_all, _, {:constraint, _}}, _header) do
raise ArgumentError, "Upsert in SQLite3 does not support ON CONSTRAINT"
end
defp on_conflict({:replace_all, _, []}, _header) do
raise ArgumentError, "Upsert in SQLite3 requires :conflict_target"
end
defp on_conflict({:replace_all, _, targets}, header) do
[" ON CONFLICT ", conflict_target(targets), "DO " | replace(header)]
end
defp on_conflict({fields, _, targets}, _header) when is_list(fields) do
[" ON CONFLICT ", conflict_target(targets), "DO " | replace(fields)]
end
defp on_conflict({query, _, targets}, _header) do
[
" ON CONFLICT ",
conflict_target(targets),
"DO " | update_all(query, "UPDATE SET ")
]
end
defp conflict_target([]), do: ""
defp conflict_target({:unsafe_fragment, fragment}),
do: [fragment, ?\s]
defp conflict_target(targets) do
[?(, Enum.map_intersperse(targets, ?,, "e_name/1), ?), ?\s]
end
defp replace(fields) do
[
"UPDATE SET "
| Enum.map_intersperse(fields, ?,, fn field ->
quoted = quote_name(field)
[quoted, " = ", "EXCLUDED." | quoted]
end)
]
end
def insert_all(rows), do: insert_all(rows, 1)
def insert_all(%Ecto.Query{} = query, _counter) do
[all(query)]
end
def insert_all(rows, counter) do
[
"VALUES ",
intersperse_reduce(
rows,
?,,
counter,
fn row, counter ->
{row, counter} = insert_each(row, counter)
{[?(, row, ?)], counter}
end
)
|> elem(0)
]
end
def insert_each(values, counter) do
intersperse_reduce(values, ?,, counter, fn
nil, _counter ->
raise ArgumentError,
"Cell-wise default values are not supported on INSERT statements by SQLite3"
{%Ecto.Query{} = query, params_counter}, counter ->
{[?(, all(query), ?)], counter + params_counter}
{:placeholder, placeholder_index}, counter ->
{[?? | placeholder_index], counter}
_, counter ->
# Cell wise value support ex: (?1, ?2, ?3)
{[?? | Integer.to_string(counter)], counter + 1}
end)
end
defp insert_as({%{sources: sources}, _, _}) do
{_expr, name, _schema} = create_name(sources, 0, [])
[" AS " | name]
end
defp insert_as({_, _, _}) do
[]
end
binary_ops = [
==: " = ",
!=: " != ",
<=: " <= ",
>=: " >= ",
<: " < ",
>: " > ",
+: " + ",
-: " - ",
*: " * ",
/: " / ",
and: " AND ",
or: " OR ",
like: " LIKE "
]
@binary_ops Keyword.keys(binary_ops)
Enum.map(binary_ops, fn {op, str} ->
def handle_call(unquote(op), 2), do: {:binary_op, unquote(str)}
end)
def handle_call(fun, _arity), do: {:fun, Atom.to_string(fun)}
defp distinct(nil, _sources, _query), do: []
defp distinct(%ByExpr{expr: true}, _sources, _query), do: "DISTINCT "
defp distinct(%ByExpr{expr: false}, _sources, _query), do: []
defp distinct(%ByExpr{expr: exprs}, _sources, query) when is_list(exprs) do
raise Ecto.QueryError,
query: query,
message: "DISTINCT with multiple columns is not supported by SQLite3"
end
defp select(%{select: %{fields: fields}, distinct: distinct} = query, sources) do
[
"SELECT ",
distinct(distinct, sources, query) | select_fields(fields, sources, query)
]
end
defp select_fields([], _sources, _query), do: "1"
defp select_fields(fields, sources, query) do
Enum.map_intersperse(fields, ", ", fn
{:&, _, [idx]} ->
case elem(sources, idx) do
{source, _, nil} ->
raise Ecto.QueryError,
query: query,
message: """
SQLite3 does not support selecting all fields from #{source} \
without a schema. Please specify a schema or specify exactly \
which fields you want to select\
"""
{_, source, _} ->
source
end
{key, value} ->
[expr(value, sources, query), " AS ", quote_name(key)]
value ->
expr(value, sources, query)
end)
end
def from(%{from: %{source: source, hints: hints}} = query, sources) do
{from, name} = get_source(query, sources, 0, source)
[
" FROM ",
from,
" AS ",
name
| Enum.map(hints, &[?\s | &1])
]
end
def cte(
%{with_ctes: %WithExpr{recursive: recursive, queries: [_ | _] = queries}} =
query,
sources
) do
recursive_opt = if recursive, do: "RECURSIVE ", else: ""
ctes = Enum.map_intersperse(queries, ", ", &cte_expr(&1, sources, query))
[
"WITH ",
recursive_opt,
ctes,
" "
]
end
def cte(%{with_ctes: _}, _), do: []
defp cte_expr({name, _opts, cte}, sources, query) do
cte_expr({name, cte}, sources, query)
end
defp cte_expr({name, cte}, sources, query) do
[
quote_name(name),
" AS ",
cte_query(cte, sources, query)
]
end
defp cte_query(%Ecto.Query{} = query, sources, parent_query) do
query = put_in(query.aliases[@parent_as], {parent_query, sources})
["(", all(query, subquery_as_prefix(sources)), ")"]
end
defp cte_query(%QueryExpr{expr: expr}, sources, query) do
expr(expr, sources, query)
end
defp update_fields(type, %{updates: updates} = query, sources) do
fields =
for(
%{expr: expression} <- updates,
{op, kw} <- expression,
{key, value} <- kw,
do: update_op(op, update_key(type, key, query, sources), value, sources, query)
)
Enum.intersperse(fields, ", ")
end
defp update_key(_kind, key, _query, _sources) do
quote_name(key)
end
defp update_op(:set, quoted_key, value, sources, query) do
[
quoted_key,
" = " | expr(value, sources, query)
]
end
defp update_op(:inc, quoted_key, value, sources, query) do
[
quoted_key,
" = ",
quoted_key,
" + " | expr(value, sources, query)
]
end
defp update_op(:push, _quoted_key, _value, _sources, query) do
raise Ecto.QueryError,
query: query,
message: "Arrays are not supported for SQLite3"
end
defp update_op(:pull, _quoted_key, _value, _sources, query) do
raise Ecto.QueryError,
query: query,
message: "Arrays are not supported for SQLite3"
end
defp update_op(command, _quoted_key, _value, _sources, query) do
raise Ecto.QueryError,
query: query,
message: "Unknown update operation #{inspect(command)} for SQLite3"
end
defp using_join(%{joins: []}, _kind, _prefix, _sources), do: {[], []}
defp using_join(%{joins: joins} = query, _kind, prefix, sources) do
froms =
Enum.map_intersperse(joins, ", ", fn
%JoinExpr{qual: _qual, ix: ix, source: source} = join ->
assert_valid_join(join, query)
{join, name} = get_source(query, sources, ix, source)
[join, " AS " | name]
end)