-
-
Notifications
You must be signed in to change notification settings - Fork 181
/
ets.ex
1216 lines (1050 loc) · 33.7 KB
/
ets.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 Ash.DataLayer.Ets do
@behaviour Ash.DataLayer
require Ash.Query
@ets %Spark.Dsl.Section{
name: :ets,
describe: """
A section for configuring the ets data layer
""",
examples: [
"""
ets do
# Used in testing
private? true
end
"""
],
schema: [
private?: [
type: :boolean,
default: false,
doc:
"Sets the ets table protection to private, and scopes it to only this process. The table name will not be used directly if this is true, to allow multiple processes to use this resource separately."
],
table: [
type: :atom,
doc: """
The name of the table. Defaults to the resource name.
"""
]
]
}
@moduledoc """
An ETS (Erlang Term Storage) backed Ash Datalayer, for testing and lightweight usage.
Remember, this does not have support for transactions! This is not recommended for production
use, especially in multi-user applications. It can, however, be great for prototyping.
"""
use Spark.Dsl.Extension,
sections: [@ets],
verifiers: [Ash.DataLayer.Verifiers.RequirePreCheckWith]
alias Ash.Actions.Sort
@deprecated "use Ash.DataLayer.Ets.Info.private?/1 instead"
defdelegate private?(resource), to: Ash.DataLayer.Ets.Info
@deprecated "use Ash.DataLayer.Ets.Info.table/1 instead"
defdelegate table(resource), to: Ash.DataLayer.Ets.Info
defmodule Query do
@moduledoc false
defstruct [
:resource,
:filter,
:limit,
:sort,
:tenant,
:api,
:distinct,
:distinct_sort,
calculations: [],
aggregates: [],
relationships: %{},
offset: 0
]
end
defmodule TableManager do
@moduledoc false
use GenServer
def start(resource, tenant) do
table =
if tenant && Ash.Resource.Info.multitenancy_strategy(resource) == :context do
Module.concat(to_string(Ash.DataLayer.Ets.Info.table(resource)), to_string(tenant))
else
Ash.DataLayer.Ets.Info.table(resource)
end
if Ash.DataLayer.Ets.Info.private?(resource) do
do_wrap_existing(resource, table)
else
case GenServer.start(__MODULE__, {resource, table},
name: Module.concat(table, TableManager)
) do
{:error, {:already_started, _pid}} ->
ETS.Set.wrap_existing(table)
{:error, error} ->
{:error, error}
_ ->
ETS.Set.wrap_existing(table)
end
end
end
def init({resource, table}) do
case do_wrap_existing(resource, table) do
{:ok, table} ->
{:ok, {resource, table}, :hibernate}
{:error, error} ->
{:error, error}
end
end
def handle_call(:wait, _, state), do: {:reply, :ok, state}
defp do_wrap_existing(_resource, table) do
case ETS.Set.wrap_existing(table) do
{:error, :table_not_found} ->
case ETS.Set.new(
name: table,
protection: :public,
ordered: true,
read_concurrency: true
) do
{:ok, tab} ->
{:ok, tab}
{:error, :table_already_exists} ->
ETS.Set.wrap_existing(table)
other ->
other
end
{:ok, table} ->
{:ok, table}
{:error, other} ->
{:error, other}
end
end
end
@doc "Stops the storage for a given resource/tenant (deleting all of the data)"
# sobelow_skip ["DOS.StringToAtom"]
def stop(resource, tenant \\ nil) do
tenant =
if Ash.Resource.Info.multitenancy_strategy(resource) == :context do
tenant
end
if Ash.DataLayer.Ets.Info.private?(resource) do
case Process.get({:ash_ets_table, resource, tenant}) do
nil ->
:ok
table ->
ETS.Set.delete(table)
end
else
table =
if tenant && Ash.Resource.Info.multitenancy_strategy(resource) == :context do
String.to_atom(to_string(tenant) <> to_string(resource))
else
resource
end
name = Module.concat(table, TableManager)
case Process.whereis(name) do
nil ->
:ok
pid ->
Process.exit(pid, :shutdown)
end
end
end
@doc false
@impl true
def can?(_, :distinct_sort), do: true
def can?(resource, :async_engine), do: not private?(resource)
def can?(_, {:lateral_join, _}), do: true
def can?(_, :bulk_create), do: true
def can?(_, :composite_primary_key), do: true
def can?(_, :expression_calculation), do: true
def can?(_, :expression_calculation_sort), do: true
def can?(_, :multitenancy), do: true
def can?(_, :upsert), do: true
def can?(_, :aggregate_filter), do: true
def can?(_, :aggregate_sort), do: true
def can?(_, {:aggregate_relationship, _}), do: true
def can?(_, {:filter_relationship, _}), do: true
def can?(_, {:aggregate, :count}), do: true
def can?(_, {:aggregate, :first}), do: true
def can?(_, {:aggregate, :sum}), do: true
def can?(_, {:aggregate, :list}), do: true
def can?(_, {:aggregate, :max}), do: true
def can?(_, {:aggregate, :min}), do: true
def can?(_, {:aggregate, :avg}), do: true
def can?(_, {:aggregate, :exists}), do: true
def can?(_, :create), do: true
def can?(_, :read), do: true
def can?(resource, action_type) when action_type in ~w[update destroy]a do
resource
|> Ash.Resource.Info.primary_key()
|> Enum.any?()
end
def can?(_, :sort), do: true
def can?(_, :filter), do: true
def can?(_, :limit), do: true
def can?(_, :offset), do: true
def can?(_, :boolean_filter), do: true
def can?(_, :distinct), do: true
def can?(_, :transact), do: false
def can?(_, {:filter_expr, _}), do: true
def can?(resource, {:join, other_resource}) do
# See the comment in can?/2 in mnesia data layer to explain this
not (private?(resource) and
Ash.DataLayer.data_layer(other_resource) == Ash.DataLayer.Mnesia)
end
def can?(_, :nested_expressions), do: true
def can?(_, {:query_aggregate, :count}), do: true
def can?(_, {:query_aggregate, :first}), do: true
def can?(_, {:query_aggregate, :sum}), do: true
def can?(_, {:query_aggregate, :list}), do: true
def can?(_, {:query_aggregate, :max}), do: true
def can?(_, {:query_aggregate, :min}), do: true
def can?(_, {:query_aggregate, :avg}), do: true
def can?(_, {:query_aggregate, :exists}), do: true
def can?(_, :expr_error), do: true
def can?(_, {:sort, _}), do: true
def can?(_, {:atomic, :update}), do: true
def can?(_, {:atomic, :upsert}), do: true
def can?(_, _), do: false
@doc false
@impl true
def resource_to_query(resource, api) do
%Query{
resource: resource,
api: api
}
end
@doc false
@impl true
def limit(query, limit, _), do: {:ok, %{query | limit: limit}}
@doc false
@impl true
def offset(query, offset, _), do: {:ok, %{query | offset: offset}}
@doc false
@impl true
def add_calculations(query, calculations, _) do
{:ok, %{query | calculations: query.calculations ++ calculations}}
end
@doc false
@impl true
def add_aggregate(query, aggregate, _),
do: {:ok, %{query | aggregates: [aggregate | query.aggregates]}}
@doc false
@impl true
def set_tenant(_resource, query, tenant) do
{:ok, %{query | tenant: tenant}}
end
@doc false
@impl true
def filter(query, filter, _resource) do
if query.filter do
{:ok, %{query | filter: Ash.Filter.add_to_filter!(query.filter, filter)}}
else
{:ok, %{query | filter: filter}}
end
end
@doc false
@impl true
def sort(query, sort, _resource) do
{:ok, %{query | sort: sort}}
end
@doc false
@impl true
def distinct(query, distinct, _resource) do
{:ok, %{query | distinct: distinct}}
end
@impl true
def distinct_sort(query, distinct_sort, _resource) do
{:ok, %{query | distinct_sort: distinct_sort}}
end
@doc false
@impl true
def run_aggregate_query(%{api: api} = query, aggregates, resource) do
case run_query(query, resource) do
{:ok, results} ->
Enum.reduce_while(aggregates, {:ok, %{}}, fn
%{
kind: kind,
name: name,
query: query,
field: field,
resource: resource,
uniq?: uniq?,
default_value: default_value
},
{:ok, acc} ->
results
|> filter_matches(Map.get(query || %{}, :filter), api)
|> case do
{:ok, matches} ->
field = field || Enum.at(Ash.Resource.Info.primary_key(resource), 0)
value = aggregate_value(matches, kind, field, uniq?, default_value)
{:cont, {:ok, Map.put(acc, name, value)}}
{:error, error} ->
{:halt, {:error, error}}
end
end)
{:error, error} ->
{:error, error}
end
|> case do
{:error, error} ->
{:error, Ash.Error.to_ash_error(error)}
other ->
other
end
end
@doc false
@impl true
def run_query(
%Query{
resource: resource,
filter: filter,
offset: offset,
limit: limit,
sort: sort,
distinct: distinct,
distinct_sort: distinct_sort,
tenant: tenant,
calculations: calculations,
aggregates: aggregates,
api: api
},
_resource,
parent \\ nil
) do
with {:ok, records} <- get_records(resource, tenant),
{:ok, records} <-
filter_matches(records, filter, api, parent),
records <- Sort.runtime_sort(records, distinct_sort || sort, api: api),
records <- Sort.runtime_distinct(records, distinct, api: api),
records <- Sort.runtime_sort(records, sort, api: api),
records <- Enum.drop(records, offset || []),
records <- do_limit(records, limit),
{:ok, records} <-
do_add_aggregates(records, api, resource, aggregates),
{:ok, records} <-
do_add_calculations(records, resource, calculations, api) do
{:ok, records}
else
{:error, error} ->
{:error, Ash.Error.to_ash_error(error)}
end
end
defp do_limit(records, nil), do: records
defp do_limit(records, limit), do: Enum.take(records, limit)
@impl true
def prefer_lateral_join_for_many_to_many?, do: false
@impl true
def run_query_with_lateral_join(
query,
root_data,
_destination_resource,
[{source_query, source_attribute, destination_attribute, relationship}]
) do
source_attributes = Enum.map(root_data, &Map.get(&1, source_attribute))
source_query
|> Ash.Query.filter(ref(^source_attribute) in ^source_attributes)
|> Ash.Query.set_context(%{private: %{internal?: true}})
|> Ash.Query.unset(:load)
|> Ash.Query.unset(:select)
|> query.api.read(authorize?: false)
|> case do
{:error, error} ->
{:error, error}
{:ok, root_data} ->
root_data
|> Enum.reduce_while({:ok, []}, fn parent, {:ok, results} ->
new_filter =
if Map.get(relationship, :no_attributes?) do
query.filter
else
Ash.Filter.add_to_filter(query.filter, [
{destination_attribute, Map.get(parent, source_attribute)}
])
end
query = %{query | filter: new_filter}
case run_query(query, relationship.source, parent) do
{:ok, new_results} ->
new_results =
Enum.map(
new_results,
&Map.put(&1, :__lateral_join_source__, Map.get(parent, source_attribute))
)
{:cont, {:ok, new_results ++ results}}
{:error, error} ->
{:halt, {:error, error}}
end
end)
|> case do
{:ok, results} ->
{:ok, results}
{:error, error} ->
{:error, error}
end
end
end
def run_query_with_lateral_join(query, root_data, _destination_resource, [
{source_query, source_attribute, source_attribute_on_join_resource, relationship},
{through_query, destination_attribute_on_join_resource, destination_attribute,
_through_relationship}
]) do
source_attributes = Enum.map(root_data, &Map.get(&1, source_attribute))
source_query
|> Ash.Query.unset(:load)
|> Ash.Query.filter(ref(^source_attribute) in ^source_attributes)
|> Ash.Query.set_context(%{private: %{internal?: true}})
|> query.api.read(authorize?: false)
|> case do
{:error, error} ->
{:error, error}
{:ok, root_data} ->
root_data
|> Enum.reduce_while({:ok, []}, fn parent, {:ok, results} ->
through_query
|> Ash.Query.filter(
ref(^source_attribute_on_join_resource) ==
^Map.get(parent, source_attribute)
)
|> Ash.Query.set_context(%{private: %{internal?: true}})
|> query.api.read(authorize?: false)
|> case do
{:ok, join_data} ->
join_attrs =
Enum.map(join_data, &Map.get(&1, destination_attribute_on_join_resource))
new_filter =
if is_nil(query.filter) do
Ash.Filter.parse!(query.resource, [
{destination_attribute, [in: join_attrs]}
])
else
Ash.Filter.add_to_filter(query.filter, [
{destination_attribute, [in: join_attrs]}
])
end
query = %{query | filter: new_filter}
case run_query(query, relationship.source, parent) do
{:ok, new_results} ->
new_results =
Enum.flat_map(new_results, fn result ->
join_data
|> Enum.flat_map(fn join_row ->
if Map.get(join_row, destination_attribute_on_join_resource) ==
Map.get(result, destination_attribute) do
[
Map.put(
result,
:__lateral_join_source__,
Map.get(join_row, source_attribute_on_join_resource)
)
]
else
[]
end
end)
end)
{:cont, {:ok, new_results ++ results}}
{:error, error} ->
{:halt, {:error, error}}
end
{:error, error} ->
{:halt, {:error, error}}
end
end)
|> case do
{:ok, results} ->
{:ok, results}
{:error, error} ->
{:error, error}
end
end
end
def do_add_calculations(records, _resource, [], _api), do: {:ok, records}
def do_add_calculations(records, resource, calculations, api) do
Enum.reduce_while(records, {:ok, []}, fn record, {:ok, records} ->
calculations
|> Enum.reduce_while({:ok, record}, fn {calculation, expression}, {:ok, record} ->
case Ash.Filter.hydrate_refs(expression, %{
resource: resource,
public?: false
}) do
{:ok, expression} ->
expression =
Ash.Actions.Read.add_calc_context_to_filter(
expression,
calculation.context[:actor],
calculation.context[:authorize?],
calculation.context[:tenant],
calculation.context[:tracer]
)
case Ash.Expr.eval_hydrated(expression, record: record, resource: resource, api: api) do
{:ok, value} ->
if calculation.load do
{:cont, {:ok, Map.put(record, calculation.load, value)}}
else
{:cont,
{:ok,
Map.update!(
record,
:calculations,
&Map.put(&1, calculation.name, value)
)}}
end
:unknown ->
if calculation.load do
{:cont, {:ok, Map.put(record, calculation.load, nil)}}
else
{:cont,
{:ok,
Map.update!(
record,
:calculations,
&Map.put(&1, calculation.name, nil)
)}}
end
{:error, error} ->
{:halt, {:error, error}}
end
{:error, error} ->
{:halt, {:error, error}}
end
end)
|> case do
{:ok, record} ->
{:cont, {:ok, [record | records]}}
{:error, error} ->
{:halt, {:error, error}}
end
end)
|> case do
{:ok, records} ->
{:ok, Enum.reverse(records)}
{:error, error} ->
{:error, Ash.Error.to_ash_error(error)}
end
end
@doc false
def do_add_aggregates(records, _api, _resource, []), do: {:ok, records}
def do_add_aggregates(records, api, _resource, aggregates) do
# TODO support crossing apis by getting the destination api, and set destination query context.
Enum.reduce_while(records, {:ok, []}, fn record, {:ok, records} ->
aggregates
|> Enum.reduce_while(
{:ok, record},
fn
%{
kind: kind,
field: field,
relationship_path: relationship_path,
query: query,
name: name,
load: load,
uniq?: uniq?,
context: context,
default_value: default_value
},
{:ok, record} ->
with {:ok, loaded_record} <-
api.load(
record,
relationship_path_to_load(relationship_path, field),
actor: Map.get(context, :actor),
authorize?: Map.get(context, :authorize?, true)
),
related <-
Ash.Filter.Runtime.get_related(loaded_record, relationship_path),
{:ok, filtered} <-
filter_matches(related, query.filter, api),
sorted <-
Sort.runtime_sort(filtered, query.sort, api: api) do
field = field || Enum.at(Ash.Resource.Info.primary_key(query.resource), 0)
value =
aggregate_value(sorted, kind, field, uniq?, default_value)
if load do
{:cont, {:ok, Map.put(record, load, value)}}
else
{:cont, {:ok, Map.update!(record, :aggregates, &Map.put(&1, name, value))}}
end
else
other ->
{:halt, other}
end
end
)
|> case do
{:ok, record} ->
{:cont, {:ok, [record | records]}}
{:error, error} ->
{:halt, {:error, error}}
end
end)
|> case do
{:ok, records} ->
{:ok, Enum.reverse(records)}
{:error, error} ->
{:error, Ash.Error.to_ash_error(error)}
end
end
defp relationship_path_to_load([], leaf) do
leaf
end
defp relationship_path_to_load([key | rest], leaf) do
[{key, relationship_path_to_load(rest, leaf)}]
end
@doc false
def aggregate_value(records, kind, field, uniq?, default) do
case kind do
:count ->
if uniq? do
records
|> Stream.map(&Map.get(&1, field))
|> Stream.uniq()
|> Stream.reject(&is_nil/1)
|> Enum.count()
else
Enum.count(records, &(not is_nil(Map.get(&1, field))))
end
:exists ->
case records do
[] ->
false
_ ->
true
end
:first ->
case records do
[] ->
default
[record | _rest] ->
Map.get(record, field)
end
:list ->
records
|> Enum.map(fn record ->
Map.get(record, field)
end)
|> then(fn values ->
if uniq? do
Enum.uniq(values)
else
values
end
end)
:avg ->
records
|> then(fn records ->
if uniq? do
records
|> Stream.map(&Map.get(&1, field))
|> Stream.uniq()
else
records
|> Stream.map(&Map.get(&1, field))
|> Stream.uniq()
end
end)
|> Enum.reduce({0, 0}, fn value, {sum, count} ->
case value do
nil ->
{sum, count}
value ->
{sum + (value || 0), count + 1}
end
end)
|> case do
{_, 0} ->
nil
{sum, count} ->
sum / count
end
kind when kind in [:sum, :max, :min] ->
records
|> Enum.map(&Map.get(&1, field))
|> case do
[] ->
nil
items ->
items =
if uniq? do
items |> Stream.uniq() |> Stream.reject(&is_nil/1)
else
items |> Stream.reject(&is_nil/1)
end
case kind do
:sum ->
Enum.sum(items)
:max ->
Enum.max(items)
:min ->
Enum.min(items)
end
end
end
end
defp get_records(resource, tenant) do
with {:ok, table} <- wrap_or_create_table(resource, tenant),
{:ok, record_tuples} <- ETS.Set.to_list(table),
records <- Enum.map(record_tuples, &elem(&1, 1)) do
cast_records(records, resource)
end
end
@doc false
def cast_records(records, resource) do
records
|> Enum.reduce_while({:ok, []}, fn record, {:ok, casted} ->
case cast_record(record, resource) do
{:ok, casted_record} ->
{:cont, {:ok, [casted_record | casted]}}
{:error, error} ->
{:halt, {:error, error}}
end
end)
|> case do
{:ok, records} ->
{:ok, Enum.reverse(records)}
{:error, error} ->
{:error, error}
end
end
@doc false
def cast_record(record, resource) do
resource
|> Ash.Resource.Info.attributes()
|> Enum.reduce_while({:ok, %{}}, fn attribute, {:ok, attrs} ->
case Map.get(record, attribute.name) do
nil ->
{:cont, {:ok, Map.put(attrs, attribute.name, nil)}}
value ->
case Ash.Type.cast_stored(attribute.type, value, attribute.constraints) do
{:ok, value} ->
{:cont, {:ok, Map.put(attrs, attribute.name, value)}}
:error ->
{:halt,
{:error, "Failed to load #{inspect(value)} as type #{inspect(attribute.type)}"}}
{:error, error} ->
{:halt, {:error, error}}
end
end
end)
|> case do
{:ok, attrs} ->
{:ok,
%{
struct(resource, attrs)
| __meta__: %Ecto.Schema.Metadata{state: :loaded, schema: resource}
}}
{:error, error} ->
{:error, error}
end
end
defp filter_matches(records, filter, api, parent \\ nil)
defp filter_matches(records, nil, _api, _parent), do: {:ok, records}
defp filter_matches(records, filter, api, parent) do
Ash.Filter.Runtime.filter_matches(api, records, filter, parent: parent)
end
@doc false
@impl true
def upsert(resource, changeset, keys) do
pkey = Ash.Resource.Info.primary_key(resource)
keys = keys || pkey
if Enum.any?(keys, &is_nil(Ash.Changeset.get_attribute(changeset, &1))) do
create(resource, changeset)
else
key_filters =
Enum.map(keys, fn key ->
{key,
Ash.Changeset.get_attribute(changeset, key) || Map.get(changeset.params, key) ||
Map.get(changeset.params, to_string(key))}
end)
query = Ash.Query.do_filter(resource, and: [key_filters])
resource
|> resource_to_query(changeset.api)
|> Map.put(:filter, query.filter)
|> Map.put(:tenant, changeset.tenant)
|> run_query(resource)
|> case do
{:ok, []} ->
create(resource, changeset)
{:ok, [result]} ->
to_set = Ash.Changeset.set_on_upsert(changeset, keys)
changeset =
changeset
|> Map.put(:attributes, %{})
|> Map.put(:data, result)
|> Ash.Changeset.force_change_attributes(to_set)
update(resource, changeset, Map.take(result, pkey))
{:ok, _} ->
{:error, "Multiple records matching keys"}
end
end
end
@impl true
def bulk_create(resource, stream, options) do
if options[:upsert?] do
# This is not optimized, but thats okay for now
stream
|> Enum.reduce_while({:ok, []}, fn changeset, {:ok, results} ->
changeset =
Ash.Changeset.set_context(changeset, %{
private: %{upsert_fields: options[:upsert_fields] || []}
})
case upsert(resource, changeset, options.upsert_keys) do
{:ok, result} ->
{:cont,
{:ok,
[
Ash.Resource.put_metadata(
result,
:bulk_create_index,
changeset.context.bulk_create.index
)
| results
]}}
{:error, error} ->
{:halt, {:error, error}}
end
end)
else
with {:ok, table} <- wrap_or_create_table(resource, options.tenant) do
Enum.reduce_while(stream, {:ok, []}, fn changeset, {:ok, results} ->
pkey =
resource
|> Ash.Resource.Info.primary_key()
|> Enum.into(%{}, fn attr ->
{attr, Ash.Changeset.get_attribute(changeset, attr)}
end)
with {:ok, record} <- Ash.Changeset.apply_attributes(changeset),
record <- unload_relationships(resource, record) do
{:cont, {:ok, [{pkey, changeset.context.bulk_create.index, record} | results]}}
else
{:error, error} ->
{:halt, {:error, error}}
end
end)
|> case do
{:ok, records} ->
case put_or_insert_new_batch(table, records, resource, options.return_records?) do
:ok ->
:ok
{:ok, records} ->
{:ok, Stream.map(records, &set_loaded/1)}
{:error, error} ->
{:error, error}
end
{:error, error} ->
{:error, error}
end
end
end
end
@doc false
@impl true
def create(resource, changeset) do
pkey =
resource
|> Ash.Resource.Info.primary_key()
|> Enum.into(%{}, fn attr ->
{attr, Ash.Changeset.get_attribute(changeset, attr)}
end)
with {:ok, table} <- wrap_or_create_table(resource, changeset.tenant),
{:ok, record} <- Ash.Changeset.apply_attributes(changeset),
record <- unload_relationships(resource, record),
{:ok, record} <-
put_or_insert_new(table, {pkey, record}, resource) do
{:ok, set_loaded(record)}
else
{:error, error} -> {:error, Ash.Error.to_ash_error(error)}
end
end
defp set_loaded(%resource{} = record) do
%{record | __meta__: %Ecto.Schema.Metadata{state: :loaded, schema: resource}}
end
defp put_or_insert_new(table, {pkey, record}, resource) do
attributes = resource |> Ash.Resource.Info.attributes()
case dump_to_native(record, attributes) do
{:ok, casted} ->
case ETS.Set.put(table, {pkey, casted}) do
{:ok, set} ->
{_key, record} = ETS.Set.get!(set, pkey)
cast_record(record, resource)
other ->
other
end