/
api.ex
1134 lines (961 loc) · 34.2 KB
/
api.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.Api do
@moduledoc """
An Api allows you to interact with your resources, and holds non-resource-specific configuration.
For example, the json api extension adds an api extension that lets you toggle authorization on/off
for all resources in that Api. You include them in an Api like so:
```elixir
defmodule MyApp.Registry do
use Ash.Registry,
extensions: [Ash.Registry.ResourceValidations]
entries do
entry OneResource
entry SecondResource
end
end
defmodule MyApp.Api do
use Ash.Api
resources do
registry MyApp.Registry
end
end
```
Then you can interact through that Api with the actions that those resources expose.
For example: `MyApp.Api.create(changeset)`, or `MyApp.Api.read(query)`. Corresponding
actions must be defined in your resources in order to call them through the Api.
## Interface
The functions documented here can be used to call any action on any resource in the Api.
For example, `MyApi.read(Myresource, [...])`.
Additionally, you can define a `code_interface` on each resource to be exposed in the Api module.
See the resource DSL documentation for more.
"""
use Ash.Dsl, default_extensions: [extensions: [Ash.Api.Dsl]]
import Ash.OptionsHelpers, only: [merge_schemas: 3]
alias Ash.Actions.{Create, Destroy, Read, Update}
alias Ash.Error.Invalid.{
NoPrimaryAction,
NoSuchAction,
NoSuchResource
}
alias Ash.Error.Query.NotFound
alias Ash.Dsl.Extension
require Ash.Query
@dialyzer {:nowarn_function, unwrap_or_raise!: 3}
@type t() :: module
@type page_request ::
:next | :prev | :first | :last | integer
@global_opts [
timeout: [
type: :timeout,
doc: """
A positive integer, or `:infinity`. If none is provided, the timeout configured on the api is used (which defaults to `30_000`).
"""
],
verbose?: [
type: :boolean,
default: false,
doc: "Log engine operations (very verbose!)"
],
action: [
type: :any,
doc: "The action to use, either an Action struct or the name of the action"
],
authorize?: [
type: {:in, [true, false, nil]},
doc:
"If an actor option is provided (even if it is `nil`), authorization happens automatically. If not, this flag can be used to authorize with no user."
],
stacktraces?: [
type: :boolean,
default: true,
doc:
"For Ash errors, whether or not each error has a stacktrace. See the error_handling guide for more."
],
tenant: [
type: :any,
doc: "A tenant to set on the query or changeset"
],
actor: [
type: :any,
doc:
"If an actor is provided, it will be used in conjunction with the authorizers of a resource to authorize access"
]
]
@read_opts_schema merge_schemas(
[
page: [
doc:
"Nested pagination options, see the section on pagination for more",
type: {:custom, __MODULE__, :page_opts, []}
],
load: [
type: :any,
doc: "A load statement to add onto the query"
],
return_query?: [
type: :boolean,
doc: """
If `true`, the query that was ultimately used is returned as a third tuple element.
The query goes through many potential changes during a request, potentially adding
authorization filters, or replacing relationships for other data layers with their
corresponding ids. This option can be used to get the true query that was sent to
the data layer.
""",
default: false
]
],
@global_opts,
"Global Options"
)
@doc false
def read_opts_schema, do: @read_opts_schema
@offset_page_opts [
offset: [
type: :non_neg_integer,
doc: "The number of records to skip from the beginning of the query"
],
limit: [
type: :pos_integer,
doc: "The number of records to include in the page"
],
filter: [
type: :any,
doc: """
A filter to apply for pagination purposes, that should not be considered in the full count.
This is used by the liveview paginator to only fetch the records that were *already* on the
page when refreshing data, to avoid pages jittering.
"""
],
count: [
type: :boolean,
doc: "Whether or not to return the page with a full count of all records"
]
]
@keyset_page_opts [
before: [
type: :string,
doc: "Get records that appear before the provided keyset (mutually exclusive with `after`)"
],
after: [
type: :string,
doc: "Get records that appear after the provided keyset (mutually exclusive with `before`)"
],
limit: [
type: :pos_integer,
doc: "How many records to include in the page"
],
filter: [
type: :any,
doc: "See the `filter` option for offset pagination, this behaves the same."
],
count: [
type: :boolean,
doc: "Whether or not to return the page with a full count of all records"
]
]
@doc false
def page_opts(page_opts) do
if page_opts == false do
{:ok, false}
else
if page_opts[:after] || page_opts[:before] do
validate_or_error(page_opts, @keyset_page_opts)
else
if page_opts[:offset] do
validate_or_error(page_opts, @offset_page_opts)
else
validate_or_error(page_opts, @keyset_page_opts)
end
end
end
end
defp validate_or_error(opts, schema) do
case Ash.OptionsHelpers.validate(opts, schema) do
{:ok, value} -> {:ok, value}
{:error, error} -> {:error, Exception.message(error)}
end
end
@load_opts_schema merge_schemas(
[
lazy?: [
type: :boolean,
doc:
"If set to true, values will only be loaded if the related value isn't currently loaded.",
default: false
]
],
@global_opts,
"Global Options"
)
@get_opts_schema [
error?: [
type: :boolean,
default: true,
doc:
"Wether or not an error should be returned or raised when the record is not found. If set to false, `nil` will be returned."
],
load: [
type: :any,
doc: "Fields or relationships to load in the query. See `Ash.Query.load/2`"
],
tenant: [
type: :any,
doc: "The tenant to set on the query being run"
],
action: [
type: :atom,
doc: "The action to use for reading the data"
],
context: [
type: :any,
doc: "Context to be set on the query being run"
]
]
|> merge_schemas(@global_opts, "Global Options")
@shared_created_update_and_destroy_opts_schema [
return_notifications?: [
type: :boolean,
default: false,
doc: """
Use this if you're running ash actions in your own transaction and you want notifications to happen still.
If a transaction is ongoing, and this is false, notifications will be discarded, otherwise
the return value is `{:ok, result, notifications}` (or `{:ok, notifications}`)
To send notifications later, use `Ash.Notifier.notify(notifications)`. It sends any notifications
that can be sent, and returns the rest.
"""
],
notification_metadata: [
type: :any,
default: %{},
doc: """
Metadata to be merged into the metadata field for all notifications sent from this operation.
"""
]
]
@create_update_opts_schema [
after_action: [
type: :any,
doc: """
A hook to be run just before the action returns, but before fields are selected (still inside the same transaction, if your data layer
supports transactions). This is mostly important if you want to load calculations after the action, which depend on having fields
selected, but you want to authorize with the minimal set of fields that are actually being selected. Runs only if the action is
successful, and is passed the changeset and result of the action. Should return `{:ok, result}` or `{:error, error}`.
For example, if you had a `full_name` calculation, but were only selecting, `first_name` and `full_name`, you might do
something like this:
```elixir
MyApp.User
|> Ash.Changeset.for_create(:create, %{first_name: "first_name", last_name: "last_name"}
|> Ash.Changeset.select(:first_name))
|> Api.create(after_action: fn _changeset, user -> Api.load(user, :full_name) end)
```
If you tried to load that `:full_name` calculation after receiving the data, the `last_name` would not be selected and as such would not be
usable in the calculation, regardless of whether or not the calculation includes that field in its select list.
"""
]
]
@create_opts_schema [
upsert?: [
type: :boolean,
default: false,
doc:
"If a conflict is found based on the primary key, the record is updated in the database (requires upsert support)"
],
upsert_identity: [
type: :atom,
doc:
"The identity to use when detecting conflicts for `upsert?`, e.g. `upsert_identity: :full_name`. By default, the primary key is used. Has no effect if `upsert?: true` is not provided"
]
]
|> merge_schemas(@global_opts, "Global Options")
|> merge_schemas(
@create_update_opts_schema,
"Shared create/update Options"
)
|> merge_schemas(
@shared_created_update_and_destroy_opts_schema,
"Shared create/update/destroy Options"
)
@doc false
def create_opts_schema, do: @create_opts_schema
@update_opts_schema []
|> merge_schemas(@global_opts, "Global Options")
|> merge_schemas(
@create_update_opts_schema,
"Shared create/update Options"
)
|> merge_schemas(
@shared_created_update_and_destroy_opts_schema,
"Shared create/update/destroy Options"
)
@doc false
def update_opts_schema, do: @update_opts_schema
@destroy_opts_schema [
return_destroyed?: [
type: :boolean,
default: false,
doc:
"If true, the destroyed record is included in the return result, e.g `{:ok, destroyed}` or `{:ok, destroyed, notifications}`"
]
]
|> merge_schemas(@global_opts, "Global Opts")
|> merge_schemas(
@shared_created_update_and_destroy_opts_schema,
"Shared create/update/destroy Options"
)
def destroy_opts_schema, do: @destroy_opts_schema
@doc """
Get a record by a primary key. See `c:get/3` for more.
"""
@callback get!(
resource :: Ash.Resource.t(),
id_or_filter :: term(),
params :: Keyword.t()
) ::
Ash.Resource.record() | no_return
@doc """
Get a record by a primary key.
For a resource with a composite primary key, pass a keyword list, e.g
`MyApi.get(MyResource, first_key: 1, second_key: 2)`
#{Ash.OptionsHelpers.docs(@get_opts_schema)}
"""
@callback get(
resource :: Ash.Resource.t(),
id_or_filter :: term(),
params :: Keyword.t()
) ::
{:ok, Ash.Resource.record()} | {:error, term}
@doc """
Run an ash query, raising on more than one result. See `c:read_one/2` for more.
"""
@callback read_one!(Ash.Query.t() | Ash.Resource.t(), params :: Keyword.t()) ::
Ash.Resource.record() | {Ash.Resource.record(), Ash.Query.t()} | no_return
@doc """
Run a query on a resource, but fail on more than one result.
This is useful if you have a query that doesn't include a primary key
but you know that it will only ever return a single result.
"""
@callback read_one(Ash.Query.t() | Ash.Resource.t(), params :: Keyword.t()) ::
{:ok, Ash.Resource.record()}
| {:ok, Ash.Resource.record(), Ash.Query.t()}
| {:error, term}
@doc """
Run an ash query. See `c:read/2` for more.
"""
@callback read!(Ash.Query.t() | Ash.Resource.t(), params :: Keyword.t()) ::
list(Ash.Resource.record())
| {list(Ash.Resource.record()), Ash.Query.t()}
| no_return
@doc """
Run a query on a resource.
For more information on building a query, see `Ash.Query`.
#{Ash.OptionsHelpers.docs(@read_opts_schema)}
## Pagination
#### Limit/offset pagination
#{Ash.OptionsHelpers.docs(@offset_page_opts)}
#### Keyset pagination
#{Ash.OptionsHelpers.docs(@keyset_page_opts)}
"""
@callback read(Ash.Query.t(), params :: Keyword.t()) ::
{:ok, list(Ash.Resource.record())}
| {:ok, list(Ash.Resource.record()), Ash.Query.t()}
| {:error, term}
@doc """
Fetch a page relative to the provided page.
"""
@callback page!(Ash.Page.page(), page_request) ::
Ash.Page.page() | no_return
@doc """
Fetch a page relative to the provided page.
A page is the return value of a paginated action called via `c:read/2`.
"""
@callback page(Ash.Page.page(), page_request) ::
{:ok, Ash.Page.page()} | {:error, term}
@type load_statement ::
Ash.Query.t()
| [atom]
| atom
| Keyword.t()
| list(atom | {atom, atom | Keyword.t()})
@doc """
Load fields or relationships on already fetched records. See `c:load/3` for more information.
"""
@callback load!(
record_or_records :: Ash.Resource.record() | [Ash.Resource.record()],
query :: load_statement(),
opts :: Keyword.t()
) ::
Ash.Resource.record() | [Ash.Resource.record()] | no_return
@doc """
Load fields or relationships on already fetched records.
Accepts a list of non-loaded fields and loads them on the provided records or a query, in
which case the loaded fields of the query are used. Relationship loads can be nested, for
example: `MyApi.load(record, [posts: [:comments]])`.
#{Ash.OptionsHelpers.docs(@load_opts_schema)}
"""
@callback load(
record_or_records :: Ash.Resource.record() | [Ash.Resource.record()],
query :: load_statement(),
opts :: Keyword.t()
) ::
{:ok, Ash.Resource.record() | [Ash.Resource.record()]} | {:error, term}
@doc """
Create a record. See `c:create/2` for more information.
"""
@callback create!(Ash.Changeset.t(), params :: Keyword.t()) ::
Ash.Resource.record()
| {Ash.Resource.record(), list(Ash.Notifier.Notification.t())}
| no_return
@doc """
Create a record.
#{Ash.OptionsHelpers.docs(@create_opts_schema)}
"""
@callback create(Ash.Changeset.t(), params :: Keyword.t()) ::
{:ok, Ash.Resource.record()}
| {:ok, Ash.Resource.record(), list(Ash.Notifier.Notification.t())}
| {:error, term}
@doc """
Update a record. See `c:update/2` for more information.
"""
@callback update!(Ash.Changeset.t(), params :: Keyword.t()) ::
Ash.Resource.record()
| {Ash.Resource.record(), list(Ash.Notifier.Notification.t())}
| no_return
@doc """
Update a record.
#{Ash.OptionsHelpers.docs(@update_opts_schema)}
"""
@callback update(Ash.Changeset.t(), params :: Keyword.t()) ::
{:ok, Ash.Resource.record()}
| {:ok, Ash.Resource.record(), list(Ash.Notifier.Notification.t())}
| {:error, term}
@doc """
Destroy a record. See `c:destroy/2` for more information.
"""
@callback destroy!(Ash.Changeset.t() | Ash.Resource.record(), params :: Keyword.t()) ::
:ok
| Ash.Resource.record()
| list(Ash.Notifier.Notification.t())
| {Ash.Resource.record(), list(Ash.Notifier.Notification.t())}
| no_return
@doc """
Destroy a record.
#{Ash.OptionsHelpers.docs(@destroy_opts_schema)}
"""
@callback destroy(Ash.Changeset.t() | Ash.Resource.record(), params :: Keyword.t()) ::
:ok
| {:ok, Ash.Resource.record()}
| {:ok, list(Ash.Notifier.Notification.t())}
| {:ok, Ash.Resource.record(), list(Ash.Notifier.Notification.t())}
| {:error, term}
@doc """
Refetches a record by primary key. See `c:reload/1` for more.
"""
@callback reload!(record :: Ash.Resource.record(), params :: Keyword.t()) ::
Ash.Resource.record() | no_return
@doc """
Refetches a record by primary key.
"""
@callback reload(record :: Ash.Resource.record()) ::
{:ok, Ash.Resource.record()} | {:error, term}
def handle_opts(_) do
quote do
@behaviour Ash.Api
end
end
def handle_before_compile(_) do
quote do
use Ash.Api.Interface
end
end
def resource(api, resource) do
cond do
allow_unregistered?(api) ->
if Ash.Dsl.is?(resource, Ash.Resource) do
resource
else
nil
end
Ash.Resource.Info.embedded?(resource) ->
resource
true ->
api
|> resources()
|> Enum.find(&(&1 == resource))
end
|> case do
nil ->
if allowed?(allow(api), resource) do
{:ok, resource}
else
{:error, NoSuchResource.exception(resource: resource)}
end
resource ->
{:ok, resource}
end
end
@spec allowed?(mfa | nil, module()) :: boolean
defp allowed?({m, f, a}, resource) do
apply(m, f, List.wrap(a) ++ [resource])
end
defp allowed?(_, _), do: false
@doc """
Gets the resources of an Api module. DO NOT USE AT COMPILE TIME.
If you need the resource list at compile time, you will need to introduce a compile time
dependency on all of the resources, and therefore should use the registry directly. `Registry |> Ash.Registry.entries()`.
"""
@spec resources(Ash.Api.t()) :: list(Ash.Resource.t())
def resources(api) do
if registry = registry(api) do
Ash.Registry.entries(registry)
else
[]
end
end
@spec registry(Ash.Api.t()) :: atom | nil
def registry(api) do
Extension.get_opt(api, [:resources], :registry, nil, true)
end
@spec allow(Ash.Api.t()) :: mfa() | nil
def allow(api) do
Extension.get_opt(api, [:resources], :allow, nil, true)
end
@spec timeout(Ash.Api.t()) :: nil | :infinity | integer()
def timeout(api) do
Extension.get_opt(api, [:execution], :timeout, 30_000, true)
end
@spec require_actor?(Ash.Api.t()) :: boolean
def require_actor?(api) do
Extension.get_opt(api, [:authorization], :require_actor?, false, true)
end
@spec authorize(Ash.Api.t()) :: :when_requested | :always | :by_default
def authorize(api) do
Extension.get_opt(api, [:authorization], :authorize, :when_requested, true)
end
@spec allow_unregistered?(Ash.Api.t()) :: atom | nil
def allow_unregistered?(api) do
Extension.get_opt(api, [:resources], :allow_unregistered?, nil)
end
@doc false
@spec get!(Ash.Api.t(), Ash.Resource.t(), term(), Keyword.t()) ::
Ash.Resource.record() | no_return
def get!(api, resource, id, opts \\ []) do
opts = Ash.OptionsHelpers.validate!(opts, @get_opts_schema)
api
|> get(resource, id, opts)
|> unwrap_or_raise!(opts[:stacktraces?])
end
@doc false
@spec get(Ash.Api.t(), Ash.Resource.t(), term(), Keyword.t()) ::
{:ok, Ash.Resource.record()} | {:error, term}
def get(api, resource, id, opts) do
with {:ok, opts} <- Ash.OptionsHelpers.validate(opts, @get_opts_schema),
{:ok, resource} <- Ash.Api.resource(api, resource),
{:ok, filter} <- Ash.Filter.get_filter(resource, id) do
query =
resource
|> Ash.Query.new(api)
|> Ash.Query.set_tenant(opts[:tenant])
|> Ash.Query.filter(^filter)
|> Ash.Query.load(opts[:load] || [])
|> Ash.Query.set_context(opts[:context] || %{})
query =
if Ash.DataLayer.data_layer_can?(query.resource, :limit) do
Ash.Query.limit(query, 2)
else
query
end
query
|> api.read(Keyword.take(opts, Keyword.keys(@read_opts_schema)))
|> case do
{:ok, %{results: [single_result]}} ->
{:ok, single_result}
{:ok, %{results: []}} ->
if opts[:error?] do
{:error,
NotFound.exception(
primary_key: filter,
resource: resource
)}
else
{:ok, nil}
end
{:ok, %{results: results}} ->
{:error,
Ash.Error.Invalid.MultipleResults.exception(
count: Enum.count(results),
query: query,
at_least?: true
)}
{:ok, [single_result]} ->
{:ok, single_result}
{:ok, []} ->
if opts[:error?] do
{:error,
NotFound.exception(
primary_key: filter,
resource: resource
)}
else
{:ok, nil}
end
{:error, error} ->
{:error, error}
{:ok, results} when is_list(results) ->
{:error,
Ash.Error.Invalid.MultipleResults.exception(count: Enum.count(results), query: query)}
end
else
{:error, error} ->
{:error, error}
end
end
def page!(api, keyset, request) do
{_, opts} = keyset.rerun
api
|> page(keyset, request)
|> unwrap_or_raise!(opts[:stacktraces?])
end
def page(_, %Ash.Page.Keyset{results: []} = page, :next) do
{:ok, page}
end
def page(_, %Ash.Page.Keyset{results: []} = page, :prev) do
{:ok, page}
end
def page(_, %Ash.Page.Keyset{}, n) when is_integer(n) do
{:error, "Cannot seek to a specific page with keyset based pagination"}
end
def page(
api,
%Ash.Page.Keyset{results: results, rerun: {query, opts}},
:next
) do
last_keyset =
results
|> :lists.last()
|> Map.get(:__metadata__)
|> Map.get(:keyset)
new_page_opts =
opts[:page]
|> Keyword.delete(:before)
|> Keyword.put(:after, last_keyset)
read(api, query, Keyword.put(opts, :page, new_page_opts))
end
def page(api, %Ash.Page.Keyset{results: results, rerun: {query, opts}}, :prev) do
first_keyset =
results
|> List.first()
|> Map.get(:__metadata__)
|> Map.get(:keyset)
new_page_opts =
opts[:page]
|> Keyword.put(:before, first_keyset)
|> Keyword.delete(:after)
read(api, query, Keyword.put(opts, :page, new_page_opts))
end
def page(api, %Ash.Page.Keyset{rerun: {query, opts}}, :first) do
page_opts =
if opts[:page][:count] do
[count: true]
else
[]
end
read(api, query, Keyword.put(opts, :page, page_opts))
end
def page(
api,
%Ash.Page.Offset{count: count, limit: limit, offset: offset, rerun: {query, opts}},
request
) do
page_opts =
case request do
:next ->
[offset: offset + limit, limit: limit]
:prev ->
[offset: max(offset - limit, 0), limit: limit]
:first ->
[offset: 0, limit: limit]
:last ->
if count do
[offset: count - limit, limit: limit]
else
[offset: 0, limit: limit]
end
page_num when is_integer(page_num) ->
[offset: (page_num - 1) * limit, limit: limit]
end
page_opts =
if opts[:page][:count] do
Keyword.put(page_opts, :count, true)
else
page_opts
end
if request == :last && !count do
{:error, "Cannot fetch last page without counting"}
else
read(api, query, Keyword.put(opts, :page, page_opts))
end
end
@doc false
def load!(api, data, query, opts \\ []) do
opts = Ash.OptionsHelpers.validate!(opts, @load_opts_schema)
api
|> load(data, query, opts)
|> unwrap_or_raise!(opts[:stacktraces?])
end
@doc false
def load(api, data, query, opts \\ [])
def load(_, [], _, _), do: {:ok, []}
def load(_, nil, _, _), do: {:ok, nil}
def load(_, {:error, error}, _, _), do: {:error, error}
def load(api, {:ok, values}, query, opts) do
load(api, values, query, opts)
end
def load(api, %struct{results: results} = page, query, opts)
when struct in [Ash.Page.Offset, Ash.Page.Keyset] do
api
|> load(results, query, opts)
|> case do
{:ok, results} -> %{page | results: results}
{:error, error} -> {:error, error}
end
end
def load(api, data, query, opts) when not is_list(data) do
api
|> load(List.wrap(data), query, opts)
|> case do
{:ok, data} -> {:ok, Enum.at(data, 0)}
{:error, error} -> {:error, error}
end
end
def load(api, [%resource{} = record | _] = data, query, opts) do
query =
case query do
%Ash.Query{} = query ->
Ash.Query.set_tenant(query, query.tenant || Map.get(record.__metadata__, :tenant))
keyword ->
resource
|> Ash.Query.new(api)
|> Ash.Query.set_tenant(Map.get(record.__metadata__, :tenant))
|> Ash.Query.load(keyword)
end
query = Map.put(query, :api, api)
with %{valid?: true} <- query,
{:ok, action} <- get_action(query.resource, opts, :read, query.action),
{:ok, opts} <- Ash.OptionsHelpers.validate(opts, @load_opts_schema) do
Read.unpaginated_read(query, action, Keyword.merge(opts, initial_data: data))
else
{:error, error} ->
{:error, error}
%{errors: errors} ->
{:error, errors}
end
end
@doc false
@spec read!(Ash.Api.t(), Ash.Query.t() | Ash.Resource.t(), Keyword.t()) ::
list(Ash.Resource.record()) | no_return
def read!(api, query, opts \\ []) do
opts = Ash.OptionsHelpers.validate!(opts, @read_opts_schema)
api
|> read(query, opts)
|> unwrap_or_raise!(opts[:stacktraces?])
end
@doc false
@spec read(Ash.Api.t(), Ash.Query.t() | Ash.Resource.t(), Keyword.t()) ::
{:ok, list(Ash.Resource.record()) | Ash.Page.page()} | {:error, term}
def read(api, query, opts \\ [])
def read(api, resource, opts) when is_atom(resource) do
read(api, Ash.Query.new(resource, api), opts)
end
def read(api, query, opts) do
query = Ash.Query.set_api(query, api)
with {:ok, opts} <- Ash.OptionsHelpers.validate(opts, @read_opts_schema),
{:ok, action} <- get_action(query.resource, opts, :read, query.action) do
Read.run(query, action, opts)
else
{:error, error} ->
{:error, error}
end
end
@doc false
def read_one!(api, query, opts) do
api
|> read_one(query, opts)
|> unwrap_or_raise!(opts[:stacktraces?])
end
@doc false
def read_one(api, query, opts) do
api
|> read(query, opts)
|> unwrap_one()
end
defp unwrap_one({:error, error}) do
{:error, error}
end
defp unwrap_one({:ok, result, query}) do
case unwrap_one({:ok, result}) do
{:ok, result} ->
{:ok, result, query}
{:error, %Ash.Error.Invalid.MultipleResults{} = error} ->
{:error, %{error | query: query}}
{:error, error} ->
{:error, error}
end
end
defp unwrap_one({:ok, result}) do
case unwrap_one(result) do
{:ok, result} ->
{:ok, result}
{:error, error} ->
{:error, error}
end
end
defp unwrap_one(%{results: results}) do
unwrap_one(results)
end
defp unwrap_one([]), do: {:ok, nil}
defp unwrap_one([result]), do: {:ok, result}
defp unwrap_one([_ | _] = results) do
error =
Ash.Error.Invalid.MultipleResults.exception(
count: Enum.count(results),
at_least?: true
)
{:error, error}
end
@doc false
@spec create!(Ash.Api.t(), Ash.Changeset.t(), Keyword.t()) ::
Ash.Resource.record()
| {Ash.Resource.record(), list(Ash.Notifier.Notification.t())}
| no_return
def create!(api, changeset, opts) do
opts = Ash.OptionsHelpers.validate!(opts, @create_opts_schema)
api
|> create(changeset, opts)
|> unwrap_or_raise!(opts[:stacktraces?])
end
@doc false
@spec create(Ash.Api.t(), Ash.Changeset.t(), Keyword.t()) ::
{:ok, Ash.Resource.record()}
| {:ok, Ash.Resource.record(), list(Ash.Notifier.Notification.t())}
| {:error, term}
def create(api, changeset, opts) do
with {:ok, opts} <- Ash.OptionsHelpers.validate(opts, @create_opts_schema),
{:ok, resource} <- Ash.Api.resource(api, changeset.resource),
{:ok, action} <- get_action(resource, opts, :create, changeset.action) do
Create.run(api, changeset, action, opts)
end
end