-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathdata_layer.ex
3424 lines (2952 loc) · 100 KB
/
data_layer.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 AshPostgres.DataLayer do
require Ecto.Query
require Ash.Expr
@manage_tenant %Spark.Dsl.Section{
name: :manage_tenant,
describe: """
Configuration for the behavior of a resource that manages a tenant
""",
examples: [
"""
manage_tenant do
template ["organization_", :id]
create? true
update? false
end
"""
],
schema: [
template: [
type: {:wrap_list, {:or, [:string, :atom]}},
required: true,
doc: """
A template that will cause the resource to create/manage the specified schema.
"""
],
create?: [
type: :boolean,
default: true,
doc: "Whether or not to automatically create a tenant when a record is created"
],
update?: [
type: :boolean,
default: true,
doc: "Whether or not to automatically update the tenant name if the record is udpated"
]
]
}
@index %Spark.Dsl.Entity{
name: :index,
describe: """
Add an index to be managed by the migration generator.
""",
examples: [
"index [\"column\", \"column2\"], unique: true, where: \"thing = TRUE\""
],
target: AshPostgres.CustomIndex,
schema: AshPostgres.CustomIndex.schema(),
transform: {AshPostgres.CustomIndex, :transform, []},
args: [:fields]
}
@custom_indexes %Spark.Dsl.Section{
name: :custom_indexes,
describe: """
A section for configuring indexes to be created by the migration generator.
In general, prefer to use `identities` for simple unique constraints. This is a tool to allow
for declaring more complex indexes.
""",
examples: [
"""
custom_indexes do
index [:column1, :column2], unique: true, where: "thing = TRUE"
end
"""
],
entities: [
@index
]
}
@statement %Spark.Dsl.Entity{
name: :statement,
describe: """
Add a custom statement for migrations.
""",
examples: [
"""
statement :pgweb_idx do
up "CREATE INDEX pgweb_idx ON pgweb USING GIN (to_tsvector('english', title || ' ' || body));"
down "DROP INDEX pgweb_idx;"
end
"""
],
target: AshPostgres.Statement,
schema: AshPostgres.Statement.schema(),
args: [:name]
}
@custom_statements %Spark.Dsl.Section{
name: :custom_statements,
describe: """
A section for configuring custom statements to be added to migrations.
Changing custom statements may require manual intervention, because Ash can't determine what order they should run
in (i.e if they depend on table structure that you've added, or vice versa). As such, any `down` statements we run
for custom statements happen first, and any `up` statements happen last.
Additionally, when changing a custom statement, we must make some assumptions, i.e that we should migrate
the old structure down using the previously configured `down` and recreate it.
This may not be desired, and so what you may end up doing is simply modifying the old migration and deleting whatever was
generated by the migration generator. As always: read your migrations after generating them!
""",
examples: [
"""
custom_statements do
# the name is used to detect if you remove or modify the statement
statement :pgweb_idx do
up "CREATE INDEX pgweb_idx ON pgweb USING GIN (to_tsvector('english', title || ' ' || body));"
down "DROP INDEX pgweb_idx;"
end
end
"""
],
entities: [
@statement
]
}
@reference %Spark.Dsl.Entity{
name: :reference,
describe: """
Configures the reference for a relationship in resource migrations.
Keep in mind that multiple relationships can theoretically involve the same destination and foreign keys.
In those cases, you only need to configure the `reference` behavior for one of them. Any conflicts will result
in an error, across this resource and any other resources that share a table with this one. For this reason,
instead of adding a reference configuration for `:nothing`, its best to just leave the configuration out, as that
is the default behavior if *no* relationship anywhere has configured the behavior of that reference.
""",
examples: [
"reference :post, on_delete: :delete, on_update: :update, name: \"comments_to_posts_fkey\""
],
args: [:relationship],
target: AshPostgres.Reference,
schema: AshPostgres.Reference.schema()
}
@references %Spark.Dsl.Section{
name: :references,
describe: """
A section for configuring the references (foreign keys) in resource migrations.
This section is only relevant if you are using the migration generator with this resource.
Otherwise, it has no effect.
""",
examples: [
"""
references do
reference :post, on_delete: :delete, on_update: :update, name: "comments_to_posts_fkey"
end
"""
],
entities: [@reference],
schema: [
polymorphic_on_delete: [
type:
{:or,
[
{:one_of, [:delete, :nilify, :nothing, :restrict]},
{:tagged_tuple, :nilify, {:wrap_list, :atom}}
]},
doc:
"For polymorphic resources, configures the on_delete behavior of the automatically generated foreign keys to source tables."
],
polymorphic_on_update: [
type: {:one_of, [:update, :nilify, :nothing, :restrict]},
doc:
"For polymorphic resources, configures the on_update behavior of the automatically generated foreign keys to source tables."
],
polymorphic_name: [
type: :string,
doc:
"For polymorphic resources, then index name to use for the foreign key to the source table."
]
]
}
@check_constraint %Spark.Dsl.Entity{
name: :check_constraint,
describe: """
Add a check constraint to be validated.
If a check constraint exists on the table but not in this section, and it produces an error, a runtime error will be raised.
Provide a list of attributes instead of a single attribute to add the message to multiple attributes.
By adding the `check` option, the migration generator will include it when generating migrations.
""",
examples: [
"""
check_constraint :price, "price_must_be_positive", check: "price > 0", message: "price must be positive"
"""
],
args: [:attribute, :name],
target: AshPostgres.CheckConstraint,
schema: AshPostgres.CheckConstraint.schema()
}
@check_constraints %Spark.Dsl.Section{
name: :check_constraints,
describe: """
A section for configuring the check constraints for a given table.
This can be used to automatically create those check constraints, or just to provide message when they are raised
""",
examples: [
"""
check_constraints do
check_constraint :price, "price_must_be_positive", check: "price > 0", message: "price must be positive"
end
"""
],
entities: [@check_constraint]
}
@references %Spark.Dsl.Section{
name: :references,
describe: """
A section for configuring the references (foreign keys) in resource migrations.
This section is only relevant if you are using the migration generator with this resource.
Otherwise, it has no effect.
""",
examples: [
"""
references do
reference :post, on_delete: :delete, on_update: :update, name: "comments_to_posts_fkey"
end
"""
],
entities: [@reference],
schema: [
polymorphic_on_delete: [
type:
{:or,
[
{:one_of, [:delete, :nilify, :nothing, :restrict]},
{:tagged_tuple, :nilify, {:wrap_list, :atom}}
]},
doc:
"For polymorphic resources, configures the on_delete behavior of the automatically generated foreign keys to source tables."
],
polymorphic_on_update: [
type: {:one_of, [:update, :nilify, :nothing, :restrict]},
doc:
"For polymorphic resources, configures the on_update behavior of the automatically generated foreign keys to source tables."
]
]
}
@postgres %Spark.Dsl.Section{
name: :postgres,
describe: """
Postgres data layer configuration
""",
sections: [
@custom_indexes,
@custom_statements,
@manage_tenant,
@references,
@check_constraints
],
modules: [
:repo
],
examples: [
"""
postgres do
repo MyApp.Repo
table "organizations"
end
"""
],
schema: [
repo: [
type: {:or, [{:behaviour, Ecto.Repo}, {:fun, 2}]},
required: true,
doc:
"The repo that will be used to fetch your data. See the `AshPostgres.Repo` documentation for more. Can also be a function that takes a resource and a type `:read | :mutate` and returns the repo"
],
migrate?: [
type: :boolean,
default: true,
doc:
"Whether or not to include this resource in the generated migrations with `mix ash.generate_migrations`"
],
storage_types: [
type: :keyword_list,
default: [],
doc:
"A keyword list of attribute names to the ecto type that should be used for that attribute. Only necessary if you need to override the defaults."
],
migration_types: [
type: :keyword_list,
default: [],
doc:
"A keyword list of attribute names to the ecto migration type that should be used for that attribute. Only necessary if you need to override the defaults."
],
migration_defaults: [
type: :keyword_list,
default: [],
doc: """
A keyword list of attribute names to the ecto migration default that should be used for that attribute. The string you use will be placed verbatim in the migration. Use fragments like `fragment(\\\\"now()\\\\")`, or for `nil`, use `\\\\"nil\\\\"`.
"""
],
calculations_to_sql: [
type: :keyword_list,
doc:
"A keyword list of calculations and their SQL representation. Used when creating unique indexes for identities over calculations"
],
identity_wheres_to_sql: [
type: :keyword_list,
doc:
"A keyword list of identity names and the SQL representation of their `where` clause. See `AshPostgres.DataLayer.Info.identity_wheres_to_sql/1` for more details."
],
base_filter_sql: [
type: :string,
doc:
"A raw sql version of the base_filter, e.g `representative = true`. Required if trying to create a unique constraint on a resource with a base_filter"
],
simple_join_first_aggregates: [
type: {:list, :atom},
default: [],
doc: """
A list of `:first` type aggregate names that can be joined to using a simple join. Use when you have a `:first` aggregate that uses a to-many relationship , but your `filter` statement ensures that there is only one result. Optimizes the generated query.
"""
],
skip_unique_indexes: [
type: {:wrap_list, :atom},
default: [],
doc: "Skip generating unique indexes when generating migrations"
],
unique_index_names: [
type:
{:list,
{:or,
[{:tuple, [{:list, :atom}, :string]}, {:tuple, [{:list, :atom}, :string, :string]}]}},
default: [],
doc: """
A list of unique index names that could raise errors that are not configured in identities, or an mfa to a function that takes a changeset and returns the list. In the format `{[:affected, :keys], "name_of_constraint"}` or `{[:affected, :keys], "name_of_constraint", "custom error message"}`
"""
],
exclusion_constraint_names: [
type: :any,
default: [],
doc: """
A list of exclusion constraint names that could raise errors. Must be in the format `{:affected_key, "name_of_constraint"}` or `{:affected_key, "name_of_constraint", "custom error message"}`
"""
],
identity_index_names: [
type: :any,
default: [],
doc: """
A keyword list of identity names to the unique index name that they should use when being managed by the migration generator.
"""
],
foreign_key_names: [
type:
{:list,
{:or,
[
{:tuple, [{:or, [:atom, :string]}, :string]},
{:tuple, [{:or, [:atom, :string]}, :string, :string]}
]}},
default: [],
doc: """
A list of foreign keys that could raise errors, or an mfa to a function that takes a changeset and returns a list. In the format: `{:key, "name_of_constraint"}` or `{:key, "name_of_constraint", "custom error message"}`
"""
],
migration_ignore_attributes: [
type: {:list, :atom},
default: [],
doc: """
A list of attributes that will be ignored when generating migrations.
"""
],
table: [
type: :string,
doc: """
The table to store and read the resource from. If this is changed, the migration generator will not remove the old table.
"""
],
schema: [
type: :string,
doc: """
The schema that the table is located in. Schema-based multitenancy will supercede this option. If this is changed, the migration generator will not remove the old schema.
"""
],
polymorphic?: [
type: :boolean,
default: false,
doc: """
Declares this resource as polymorphic. See the [polymorphic resources guide](/documentation/topics/resources/polymorphic-resources.md) for more.
"""
]
]
}
@behaviour Ash.DataLayer
@sections [@postgres]
@moduledoc """
A postgres data layer that leverages Ecto's postgres capabilities.
"""
use Spark.Dsl.Extension,
sections: @sections,
verifiers: [
AshPostgres.Verifiers.PreventMultidimensionalArrayAggregates,
AshPostgres.Verifiers.ValidateReferences,
AshPostgres.Verifiers.PreventAttributeMultitenancyAndNonFullMatchType,
AshPostgres.Verifiers.EnsureTableOrPolymorphic,
AshPostgres.Verifiers.ValidateIdentityIndexNames
]
def migrate(args) do
Mix.Task.run("ash_postgres.migrate", args)
end
def rollback(args) do
repos = AshPostgres.Mix.Helpers.repos!([], args)
show_for_repo? = Enum.count_until(repos, 2) == 2
for repo <- repos do
{:ok, _, _} =
Ecto.Migrator.with_repo(repo, fn repo ->
for_repo =
if show_for_repo? do
" for repo #{inspect(repo)}"
else
""
end
migrations_path = AshPostgres.Mix.Helpers.migrations_path([], repo)
tenant_migrations_path = AshPostgres.Mix.Helpers.tenant_migrations_path([], repo)
current_migrations =
Ecto.Query.from(row in "schema_migrations",
select: row.version
)
|> repo.all()
|> Enum.map(&to_string/1)
files =
migrations_path
|> Path.join("**/*.exs")
|> Path.wildcard()
|> Enum.sort()
|> Enum.reverse()
|> Enum.filter(fn file ->
Enum.any?(current_migrations, &String.starts_with?(Path.basename(file), &1))
end)
|> Enum.take(20)
|> Enum.map(&String.trim_leading(&1, migrations_path))
|> Enum.with_index()
|> Enum.map(fn {file, index} -> "#{index + 1}: #{file}" end)
n =
Mix.shell().prompt(
"""
How many migrations should be rolled back#{for_repo}? (default: 0)
Last 20 migration names, with the input you must provide to
rollback up to *and including* that migration:
#{Enum.join(files, "\n")}
Rollback to:
"""
|> String.trim_trailing()
)
|> String.trim()
|> case do
"" ->
0
n ->
try do
String.to_integer(n)
rescue
_ ->
reraise "Required an integer value, got: #{n}", __STACKTRACE__
end
end
Mix.Task.run("ash_postgres.rollback", args ++ ["-r", inspect(repo), "-n", to_string(n)])
Mix.Task.reenable("ash_postgres.rollback")
tenant_files =
tenant_migrations_path
|> Path.join("**/*.exs")
|> Path.wildcard()
|> Enum.sort()
|> Enum.reverse()
if !Enum.empty?(tenant_files) do
first_tenant = repo.all_tenants() |> Enum.at(0)
if first_tenant do
current_tenant_migrations =
Ecto.Query.from(row in "schema_migrations",
select: row.version
)
|> repo.all(prefix: first_tenant)
|> Enum.map(&to_string/1)
tenant_files =
tenant_files
|> Enum.filter(fn file ->
Enum.any?(
current_tenant_migrations,
&String.starts_with?(Path.basename(file), &1)
)
end)
|> Enum.take(20)
|> Enum.map(&String.trim_leading(&1, tenant_migrations_path))
|> Enum.with_index()
|> Enum.map(fn {file, index} -> "#{index + 1}: #{file}" end)
n =
Mix.shell().prompt(
"""
How many _tenant_ migrations should be rolled back#{for_repo}? (default: 0)
IMPORTANT: we are assuming that all of your tenants have all had the same migrations run.
If each tenant may be in a different state: *abort this command and roll them back individually*.
To do so, use the `--only-tenants` option to `mix ash_postgres.rollback`.
Last 20 migration names, with the input you must provide to
rollback up to *and including* that migration:
#{Enum.join(tenant_files, "\n")}
Rollback to:
"""
|> String.trim_trailing()
)
|> String.trim()
|> case do
"" ->
0
n ->
try do
String.to_integer(n)
rescue
_ ->
reraise "Required an integer value, got: #{n}", __STACKTRACE__
end
end
Mix.Task.run(
"ash_postgres.rollback",
args ++ ["--tenants", "-r", inspect(repo), "-n", to_string(n)]
)
Mix.Task.reenable("ash_postgres.rollback")
end
end
end)
end
end
def codegen(args) do
Mix.Task.run("ash_postgres.generate_migrations", args)
end
def setup(args) do
# TODO: take args that we care about
Mix.Task.run("ash_postgres.create", args)
Mix.Task.run("ash_postgres.migrate", args)
[]
|> AshPostgres.Mix.Helpers.repos!(args)
|> Enum.all?(&(not has_tenant_migrations?(&1)))
|> case do
true ->
:ok
_ ->
Mix.Task.run("ash_postgres.migrate", ["--tenant" | args])
end
end
def tear_down(args) do
# TODO: take args that we care about
Mix.Task.run("ash_postgres.drop", args)
end
defp has_tenant_migrations?(repo) do
[]
|> AshPostgres.Mix.Helpers.tenant_migrations_path(repo)
|> Path.join("**/*.exs")
|> Path.wildcard()
|> Enum.empty?()
end
import Ecto.Query, only: [from: 2, subquery: 1]
@impl true
def prefer_transaction?(resource) do
AshPostgres.DataLayer.Info.repo(resource, :mutate).prefer_transaction?()
end
@impl true
def prefer_transaction_for_atomic_updates?(resource) do
AshPostgres.DataLayer.Info.repo(resource, :mutate).prefer_transaction_for_atomic_updates?()
end
@impl true
def can?(_, :async_engine), do: true
def can?(_, :bulk_create), do: true
def can?(_, :action_select), do: true
def can?(resource, :update_query) do
# We can't currently support updating a record from a query
# if that record manages a tenant on update
!AshPostgres.DataLayer.Info.manage_tenant_update?(resource)
end
def can?(_, :destroy_query), do: true
def can?(_, {:lock, :for_update}), do: true
def can?(_, :composite_types), do: true
def can?(_, {:lock, string}) do
string = String.trim_trailing(string, " NOWAIT")
String.upcase(string) in [
"FOR UPDATE",
"FOR NO KEY UPDATE",
"FOR SHARE",
"FOR KEY SHARE"
]
end
def can?(_, :transact), do: true
def can?(_, :composite_primary_key), do: true
def can?(resource, {:atomic, :update}),
do: not AshPostgres.DataLayer.Info.repo(resource, :mutate).disable_atomic_actions?()
def can?(resource, {:atomic, :upsert}),
do: not AshPostgres.DataLayer.Info.repo(resource, :mutate).disable_atomic_actions?()
def can?(_, :upsert), do: true
def can?(_, :changeset_filter), do: true
def can?(resource, {:join, other_resource}) do
data_layer = Ash.DataLayer.data_layer(resource)
other_data_layer = Ash.DataLayer.data_layer(other_resource)
data_layer == other_data_layer and
AshPostgres.DataLayer.Info.repo(resource, :read) ==
AshPostgres.DataLayer.Info.repo(other_resource, :read)
end
def can?(resource, {:lateral_join, resources}) do
repo = AshPostgres.DataLayer.Info.repo(resource, :read)
data_layer = Ash.DataLayer.data_layer(resource)
data_layer == __MODULE__ &&
Enum.all?(resources, fn resource ->
Ash.DataLayer.data_layer(resource) == data_layer &&
AshPostgres.DataLayer.Info.repo(resource, :read) == repo
end)
end
def can?(_, :boolean_filter), do: true
def can?(_, {:aggregate, type})
when type in [:count, :sum, :first, :list, :avg, :max, :min, :exists, :custom],
do: true
def can?(_, :aggregate_filter), do: true
def can?(_, :aggregate_sort), do: true
def can?(_, :calculate), do: true
def can?(_, :expression_calculation), do: true
def can?(_, :expression_calculation_sort), do: true
def can?(_, :create), do: true
def can?(_, :select), do: true
def can?(_, :read), do: true
def can?(resource, action) when action in ~w[update destroy]a do
resource
|> Ash.Resource.Info.primary_key()
|> Enum.any?()
end
def can?(_, :filter), do: true
def can?(_, :limit), do: true
def can?(_, :offset), do: true
def can?(_, :multitenancy), do: true
def can?(_, {:filter_relationship, %{manual: {module, _}}}) do
Spark.implements_behaviour?(module, AshPostgres.ManualRelationship)
end
def can?(_, {:filter_relationship, _}), do: true
def can?(_, {:aggregate_relationship, %{manual: {module, _}}}) do
Spark.implements_behaviour?(module, AshPostgres.ManualRelationship)
end
def can?(_, {:aggregate_relationship, _}), do: true
def can?(_, :timeout), do: true
def can?(resource, :expr_error),
do: not AshPostgres.DataLayer.Info.repo(resource, :mutate).disable_expr_error?()
def can?(resource, {:filter_expr, %Ash.Query.Function.Error{}}) do
not AshPostgres.DataLayer.Info.repo(resource, :mutate).disable_expr_error?() &&
"ash-functions" in AshPostgres.DataLayer.Info.repo(resource, :read).installed_extensions() &&
"ash-functions" in AshPostgres.DataLayer.Info.repo(resource, :mutate).installed_extensions()
end
def can?(_, {:filter_expr, _}), do: true
def can?(_, :nested_expressions), do: true
def can?(_, {:query_aggregate, _}), do: true
def can?(_, :sort), do: true
def can?(_, :distinct_sort), do: true
def can?(_, :distinct), do: true
def can?(_, {:sort, _}), do: true
def can?(_, _), do: false
@impl true
def in_transaction?(resource) do
AshPostgres.DataLayer.Info.repo(resource, :mutate).in_transaction?()
end
@impl true
def limit(query, nil, _), do: {:ok, query}
def limit(query, limit, _resource) do
{:ok, from(row in query, limit: ^limit)}
end
@impl true
def source(resource) do
AshPostgres.DataLayer.Info.table(resource) || ""
end
@impl true
def set_context(resource, data_layer_query, context) do
AshSql.Query.set_context(resource, data_layer_query, AshPostgres.SqlImplementation, context)
end
@impl true
def offset(query, nil, _), do: query
def offset(%{offset: old_offset} = query, 0, _resource) when old_offset in [0, nil] do
{:ok, query}
end
def offset(query, offset, _resource) do
{:ok, from(row in query, offset: ^offset)}
end
@impl true
def return_query(query, resource) do
query
|> AshSql.Bindings.default_bindings(resource, AshPostgres.SqlImplementation)
|> AshSql.Query.return_query(resource)
end
@impl true
def run_query(query, resource) do
query = AshSql.Bindings.default_bindings(query, resource, AshPostgres.SqlImplementation)
if AshPostgres.DataLayer.Info.polymorphic?(resource) && no_table?(query) do
raise_table_error!(resource, :read)
else
repo = AshSql.dynamic_repo(resource, AshPostgres.SqlImplementation, query)
with_savepoint(repo, query, fn ->
{:ok,
repo.all(
query,
AshSql.repo_opts(repo, AshPostgres.SqlImplementation, nil, nil, resource)
)
|> AshSql.Query.remap_mapped_fields(query)}
end)
end
rescue
e ->
handle_raised_error(e, __STACKTRACE__, query, resource)
end
defp no_table?(%{from: %{source: {"", _}}}), do: true
defp no_table?(_), do: false
@impl true
def functions(resource) do
config = AshPostgres.DataLayer.Info.repo(resource, :mutate).config()
functions = [
AshPostgres.Functions.Like,
AshPostgres.Functions.ILike,
AshPostgres.Functions.Binding
]
functions =
if "pg_trgm" in (config[:installed_extensions] || []) do
functions ++
[
AshPostgres.Functions.TrigramSimilarity
]
else
functions
end
if "vector" in (config[:installed_extensions] || []) do
functions ++
[
AshPostgres.Functions.VectorCosineDistance,
AshPostgres.Functions.VectorL2Distance
]
else
functions
end
end
@impl true
def run_aggregate_query(original_query, aggregates, resource) do
AshSql.AggregateQuery.run_aggregate_query(
original_query,
aggregates,
resource,
AshPostgres.SqlImplementation
)
end
@impl true
def set_tenant(_resource, query, tenant) do
{:ok, Map.put(Ecto.Query.put_query_prefix(query, to_string(tenant)), :__tenant__, tenant)}
end
@impl true
def run_aggregate_query_with_lateral_join(
query,
aggregates,
root_data,
destination_resource,
path
) do
{can_group, cant_group} =
aggregates
|> Enum.split_with(&AshSql.Aggregate.can_group?(destination_resource, &1, query))
|> case do
{[one], cant_group} -> {[], [one | cant_group]}
{can_group, cant_group} -> {can_group, cant_group}
end
case lateral_join_query(
query,
root_data,
path
) do
{:ok, lateral_join_query} ->
source_resource =
path
|> Enum.at(0)
|> elem(0)
|> Map.get(:resource)
subquery = from(row in subquery(lateral_join_query), as: ^0, select: %{})
subquery =
AshSql.Bindings.default_bindings(
subquery,
source_resource,
AshPostgres.SqlImplementation
)
{global_filter, can_group} =
AshSql.Aggregate.extract_shared_filters(can_group)
original_subquery = subquery
subquery =
case global_filter do
{:ok, global_filter} ->
filter(subquery, global_filter, destination_resource)
:error ->
{:ok, subquery}
end
case subquery do
{:error, error} ->
{:error, error}
{:ok, subquery} ->
query =
Enum.reduce(
can_group,
subquery,
fn agg, subquery ->
has_exists? =
Ash.Filter.find(agg.query && agg.query.filter, fn
%Ash.Query.Exists{} -> true
_ -> false
end)
first_relationship =
Ash.Resource.Info.relationship(
source_resource,
agg.relationship_path |> Enum.at(0)
)
AshSql.Aggregate.add_subquery_aggregate_select(
subquery,
agg.relationship_path |> Enum.drop(1),
agg,
destination_resource,
has_exists?,
first_relationship
)
end
)
result =
case can_group do
[] ->
%{}
_ ->
repo =
AshSql.dynamic_repo(source_resource, AshPostgres.SqlImplementation, query)
repo.one(
query,
AshSql.repo_opts(
repo,
AshPostgres.SqlImplementation,
nil,
nil,
source_resource
)
)
end
{:ok,
AshSql.AggregateQuery.add_single_aggs(
result,
source_resource,
original_subquery,
cant_group,
AshPostgres.SqlImplementation
)}
end
{:error, error} ->
{:error, error}
end
end
@impl true
def run_query_with_lateral_join(
query,
root_data,
_destination_resource,
path
) do
{calculations_require_rewrite, aggregates_require_rewrite, query} =
AshSql.Query.rewrite_nested_selects(query)
case lateral_join_query(
query,
root_data,
path
) do
{:ok, lateral_join_query} ->
source_resource =
path
|> Enum.at(0)
|> elem(0)
|> Map.get(:resource)
repo =
AshSql.dynamic_repo(source_resource, AshPostgres.SqlImplementation, lateral_join_query)
# patching strange behavior that sets `take` to this empty list even though I'm not telling it to
lateral_join_query =
case lateral_join_query do
%{select: %{take: %{0 => {:map, []}}}} -> put_in(lateral_join_query.select.take, %{})
_ -> lateral_join_query
end
results =
repo.all(
lateral_join_query,