-
Notifications
You must be signed in to change notification settings - Fork 535
/
Copy pathactive_relation_resource.rb
850 lines (697 loc) · 36.4 KB
/
active_relation_resource.rb
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
module JSONAPI
class ActiveRelationResource < BasicResource
root_resource
class << self
# Finds Resources using the `filters`. Pagination and sort options are used when provided
#
# @param filters [Hash] the filters hash
# @option options [Hash] :context The context of the request, set in the controller
# @option options [Hash] :sort_criteria The `sort criteria`
# @option options [Hash] :include_directives The `include_directives`
#
# @return [Array<Resource>] the Resource instances matching the filters, sorting and pagination rules.
def find(filters, options = {})
sort_criteria = options.fetch(:sort_criteria) { [] }
join_manager = ActiveRelation::JoinManager.new(resource_klass: self,
filters: filters,
sort_criteria: sort_criteria)
paginator = options[:paginator]
records = apply_request_settings_to_records(records: records(options),
sort_criteria: sort_criteria,filters: filters,
join_manager: join_manager,
paginator: paginator,
options: options)
resources_for(records, options[:context])
end
# Counts Resources found using the `filters`
#
# @param filters [Hash] the filters hash
# @option options [Hash] :context The context of the request, set in the controller
#
# @return [Integer] the count
def count(filters, options = {})
join_manager = ActiveRelation::JoinManager.new(resource_klass: self,
filters: filters)
records = apply_request_settings_to_records(records: records(options),
filters: filters,
join_manager: join_manager,
options: options)
count_records(records)
end
# Returns the single Resource identified by `key`
#
# @param key the primary key of the resource to find
# @option options [Hash] :context The context of the request, set in the controller
def find_by_key(key, options = {})
record = find_record_by_key(key, options)
resource_for(record, options[:context])
end
# Returns an array of Resources identified by the `keys` array
#
# @param keys [Array<key>] Array of primary keys to find resources for
# @option options [Hash] :context The context of the request, set in the controller
def find_by_keys(keys, options = {})
records = find_records_by_keys(keys, options)
resources_for(records, options[:context])
end
# Returns an array of Resources identified by the `keys` array. The resources are not filtered as this
# will have been done in a prior step
#
# @param keys [Array<key>] Array of primary keys to find resources for
# @option options [Hash] :context The context of the request, set in the controller
def find_to_populate_by_keys(keys, options = {})
records = records_for_populate(options).where(_primary_key => keys)
resources_for(records, options[:context])
end
# Finds Resource fragments using the `filters`. Pagination and sort options are used when provided.
# Retrieving the ResourceIdentities and attributes does not instantiate a model instance.
# Note: This is incompatible with Polymorphic resources (which are going to come from two separate tables)
#
# @param filters [Hash] the filters hash
# @option options [Hash] :context The context of the request, set in the controller
# @option options [Hash] :sort_criteria The `sort criteria`
# @option options [Hash] :include_directives The `include_directives`
# @option options [Hash] :attributes Additional fields to be retrieved.
# @option options [Boolean] :cache Return the resources' cache field
#
# @return [Hash{ResourceIdentity => {identity: => ResourceIdentity, cache: cache_field, attributes: => {name => value}}}]
# the ResourceInstances matching the filters, sorting, and pagination rules along with any request
# additional_field values
def find_fragments(filters, options = {})
include_directives = options[:include_directives] ? options[:include_directives].include_directives : {}
resource_klass = self
linkage_relationships = to_one_relationships_for_linkage(include_directives)
sort_criteria = options.fetch(:sort_criteria) { [] }
join_manager = ActiveRelation::JoinManager.new(resource_klass: resource_klass,
source_relationship: nil,
relationships: linkage_relationships,
sort_criteria: sort_criteria,
filters: filters)
paginator = options[:paginator]
records = apply_request_settings_to_records(records: records(options),
filters: filters,
sort_criteria: sort_criteria,
paginator: paginator,
join_manager: join_manager,
options: options)
# This alias is going to be resolve down to the model's table name and will not actually be an alias
resource_table_alias = resource_klass._table_name
pluck_fields = [Arel.sql("#{concat_table_field(resource_table_alias, resource_klass._primary_key)} AS #{resource_table_alias}_#{resource_klass._primary_key}")]
cache_field = attribute_to_model_field(:_cache_field) if options[:cache]
if cache_field
pluck_fields << Arel.sql("#{concat_table_field(resource_table_alias, cache_field[:name])} AS #{resource_table_alias}_#{cache_field[:name]}")
end
linkage_fields = []
linkage_relationships.each do |name|
linkage_relationship = resource_klass._relationship(name)
if linkage_relationship.polymorphic? && linkage_relationship.belongs_to?
linkage_relationship.resource_types.each do |resource_type|
klass = resource_klass_for(resource_type)
linkage_fields << {relationship_name: name, resource_klass: klass}
linkage_table_alias = join_manager.join_details_by_polymorphic_relationship(linkage_relationship, resource_type)[:alias]
primary_key = klass._primary_key
pluck_fields << Arel.sql("#{concat_table_field(linkage_table_alias, primary_key)} AS #{linkage_table_alias}_#{primary_key}")
end
else
klass = linkage_relationship.resource_klass
linkage_fields << {relationship_name: name, resource_klass: klass}
linkage_table_alias = join_manager.join_details_by_relationship(linkage_relationship)[:alias]
primary_key = klass._primary_key
pluck_fields << Arel.sql("#{concat_table_field(linkage_table_alias, primary_key)} AS #{linkage_table_alias}_#{primary_key}")
end
end
model_fields = {}
attributes = options[:attributes]
attributes.try(:each) do |attribute|
model_field = resource_klass.attribute_to_model_field(attribute)
model_fields[attribute] = model_field
pluck_fields << Arel.sql("#{concat_table_field(resource_table_alias, model_field[:name])} AS #{resource_table_alias}_#{model_field[:name]}")
end
sort_fields = options.dig(:_relation_helper_options, :sort_fields)
sort_fields.try(:each) do |field|
pluck_fields << Arel.sql(field)
end
fragments = {}
rows = records.pluck(*pluck_fields)
rows.each do |row|
rid = JSONAPI::ResourceIdentity.new(resource_klass, pluck_fields.length == 1 ? row : row[0])
fragments[rid] ||= JSONAPI::ResourceFragment.new(rid)
attributes_offset = 1
if cache_field
fragments[rid].cache = cast_to_attribute_type(row[1], cache_field[:type])
attributes_offset+= 1
end
linkage_fields.each do |linkage_field_details|
fragments[rid].initialize_related(linkage_field_details[:relationship_name])
related_id = row[attributes_offset]
if related_id
related_rid = JSONAPI::ResourceIdentity.new(linkage_field_details[:resource_klass], related_id)
fragments[rid].add_related_identity(linkage_field_details[:relationship_name], related_rid)
end
attributes_offset+= 1
end
model_fields.each_with_index do |k, idx|
fragments[rid].attributes[k[0]]= cast_to_attribute_type(row[idx + attributes_offset], k[1][:type])
end
end
if JSONAPI.configuration.warn_on_performance_issues && (rows.length > fragments.length)
warn "Performance issue detected: `#{self.name.to_s}.records` returned non-normalized results in `#{self.name.to_s}.find_fragments`."
end
fragments
end
# Finds Resource Fragments related to the source resources through the specified relationship
#
# @param source_rids [Array<ResourceIdentity>] The resources to find related ResourcesIdentities for
# @param relationship_name [String | Symbol] The name of the relationship
# @option options [Hash] :context The context of the request, set in the controller
# @option options [Hash] :attributes Additional fields to be retrieved.
# @option options [Boolean] :cache Return the resources' cache field
#
# @return [Hash{ResourceIdentity => {identity: => ResourceIdentity, cache: cache_field, attributes: => {name => value}, related: {relationship_name: [] }}}]
# the ResourceInstances matching the filters, sorting, and pagination rules along with any request
# additional_field values
def find_related_fragments(source_rids, relationship_name, options = {})
relationship = _relationship(relationship_name)
if relationship.polymorphic? # && relationship.foreign_key_on == :self
find_related_polymorphic_fragments(source_rids, relationship, options, false)
else
find_related_monomorphic_fragments(source_rids, relationship, options, false)
end
end
def find_included_fragments(source_rids, relationship_name, options)
relationship = _relationship(relationship_name)
if relationship.polymorphic? # && relationship.foreign_key_on == :self
find_related_polymorphic_fragments(source_rids, relationship, options, true)
else
find_related_monomorphic_fragments(source_rids, relationship, options, true)
end
end
# Counts Resources related to the source resource through the specified relationship
#
# @param source_rid [ResourceIdentity] Source resource identifier
# @param relationship_name [String | Symbol] The name of the relationship
# @option options [Hash] :context The context of the request, set in the controller
#
# @return [Integer] the count
def count_related(source_rid, relationship_name, options = {})
relationship = _relationship(relationship_name)
related_klass = relationship.resource_klass
filters = options.fetch(:filters, {})
# Joins in this case are related to the related_klass
join_manager = ActiveRelation::JoinManager.new(resource_klass: self,
source_relationship: relationship,
filters: filters)
records = apply_request_settings_to_records(records: records(options),
resource_klass: related_klass,
primary_keys: source_rid.id,
join_manager: join_manager,
filters: filters,
options: options)
related_alias = join_manager.join_details_by_relationship(relationship)[:alias]
records = records.select(Arel.sql("#{concat_table_field(related_alias, related_klass._primary_key)}"))
count_records(records)
end
# This resource class (ActiveRelationResource) uses an `ActiveRecord::Relation` as the starting point for
# retrieving models. From this relation filters, sorts and joins are applied as needed.
# Depending on which phase of the request processing different `records` methods will be called, giving the user
# the opportunity to override them differently for performance and security reasons.
# begin `records`methods
# Base for the `records` methods that follow and is not directly used for accessing model data by this class.
# Overriding this method gives a single place to affect the `ActiveRecord::Relation` used for the resource.
#
# @option options [Hash] :context The context of the request, set in the controller
#
# @return [ActiveRecord::Relation]
def records_base(_options = {})
_model_class.all
end
# The `ActiveRecord::Relation` used for finding user requested models. This may be overridden to enforce
# permissions checks on the request.
#
# @option options [Hash] :context The context of the request, set in the controller
#
# @return [ActiveRecord::Relation]
def records(options = {})
records_base(options)
end
# The `ActiveRecord::Relation` used for populating the ResourceSet. Only resources that have been previously
# identified through the `records` method will be accessed. Thus it should not be necessary to reapply permissions
# checks. However if the model needs to include other models adding `includes` is appropriate
#
# @option options [Hash] :context The context of the request, set in the controller
#
# @return [ActiveRecord::Relation]
def records_for_populate(options = {})
records_base(options)
end
# The `ActiveRecord::Relation` used for the finding related resources. Only resources that have been previously
# identified through the `records` method will be accessed and used as the basis to find related resources. Thus
# it should not be necessary to reapply permissions checks.
#
# @option options [Hash] :context The context of the request, set in the controller
#
# @return [ActiveRecord::Relation]
def records_for_source_to_related(options = {})
records_base(options)
end
# end `records` methods
def apply_join(records:, relationship:, resource_type:, join_type:, options:)
if relationship.polymorphic? && relationship.belongs_to?
case join_type
when :inner
records = records.joins(resource_type.to_s.singularize.to_sym)
when :left
records = records.joins_left(resource_type.to_s.singularize.to_sym)
end
else
relation_name = relationship.relation_name(options)
case join_type
when :inner
records = records.joins(relation_name)
when :left
records = records.joins_left(relation_name)
end
end
records
end
def relationship_records(relationship:, join_type: :inner, resource_type: nil, options: {})
records = relationship.parent_resource.records_for_source_to_related(options)
strategy = relationship.options[:apply_join]
if strategy
records = call_method_or_proc(strategy, records, relationship, resource_type, join_type, options)
else
records = apply_join(records: records,
relationship: relationship,
resource_type: resource_type,
join_type: join_type,
options: options)
end
records
end
def join_relationship(records:, relationship:, resource_type: nil, join_type: :inner, options: {})
relationship_records = relationship_records(relationship: relationship,
join_type: join_type,
resource_type: resource_type,
options: options)
records.merge(relationship_records)
end
protected
def to_one_relationships_for_linkage(include_related)
include_related ||= {}
relationships = []
_relationships.each do |name, relationship|
if relationship.is_a?(JSONAPI::Relationship::ToOne) && !include_related.has_key?(name) && relationship.include_optional_linkage_data?
relationships << name
end
end
relationships
end
def find_record_by_key(key, options = {})
record = apply_request_settings_to_records(records: records(options), primary_keys: key, options: options).first
fail JSONAPI::Exceptions::RecordNotFound.new(key) if record.nil?
record
end
def find_records_by_keys(keys, options = {})
apply_request_settings_to_records(records: records(options), primary_keys: keys, options: options)
end
def find_related_monomorphic_fragments(source_rids, relationship, options, connect_source_identity)
filters = options.fetch(:filters, {})
source_ids = source_rids.collect {|rid| rid.id}
include_directives = options[:include_directives] ? options[:include_directives].include_directives : {}
resource_klass = relationship.resource_klass
linkage_relationships = resource_klass.to_one_relationships_for_linkage(include_directives)
sort_criteria = []
options[:sort_criteria].try(:each) do |sort|
field = sort[:field].to_s == 'id' ? resource_klass._primary_key : sort[:field]
sort_criteria << { field: field, direction: sort[:direction] }
end
join_manager = ActiveRelation::JoinManager.new(resource_klass: self,
source_relationship: relationship,
relationships: linkage_relationships,
sort_criteria: sort_criteria,
filters: filters)
paginator = options[:paginator] if source_rids.count == 1
records = apply_request_settings_to_records(records: records_for_source_to_related(options),
resource_klass: resource_klass,
sort_criteria: sort_criteria,
primary_keys: source_ids,
paginator: paginator,
filters: filters,
join_manager: join_manager,
options: options)
resource_table_alias = join_manager.join_details_by_relationship(relationship)[:alias]
pluck_fields = [
Arel.sql("#{_table_name}.#{_primary_key} AS source_id"),
Arel.sql("#{concat_table_field(resource_table_alias, resource_klass._primary_key)} AS #{resource_table_alias}_#{resource_klass._primary_key}")
]
cache_field = resource_klass.attribute_to_model_field(:_cache_field) if options[:cache]
if cache_field
pluck_fields << Arel.sql("#{concat_table_field(resource_table_alias, cache_field[:name])} AS #{resource_table_alias}_#{cache_field[:name]}")
end
linkage_fields = []
linkage_relationships.each do |name|
linkage_relationship = resource_klass._relationship(name)
if linkage_relationship.polymorphic? && linkage_relationship.belongs_to?
linkage_relationship.resource_types.each do |resource_type|
klass = resource_klass_for(resource_type)
linkage_fields << {relationship_name: name, resource_klass: klass}
linkage_table_alias = join_manager.join_details_by_polymorphic_relationship(linkage_relationship, resource_type)[:alias]
primary_key = klass._primary_key
pluck_fields << Arel.sql("#{concat_table_field(linkage_table_alias, primary_key)} AS #{linkage_table_alias}_#{primary_key}")
end
else
klass = linkage_relationship.resource_klass
linkage_fields << {relationship_name: name, resource_klass: klass}
linkage_table_alias = join_manager.join_details_by_relationship(linkage_relationship)[:alias]
primary_key = klass._primary_key
pluck_fields << Arel.sql("#{concat_table_field(linkage_table_alias, primary_key)} AS #{linkage_table_alias}_#{primary_key}")
end
end
model_fields = {}
attributes = options[:attributes]
attributes.try(:each) do |attribute|
model_field = resource_klass.attribute_to_model_field(attribute)
model_fields[attribute] = model_field
pluck_fields << Arel.sql("#{concat_table_field(resource_table_alias, model_field[:name])} AS #{resource_table_alias}_#{model_field[:name]}")
end
sort_fields = options.dig(:_relation_helper_options, :sort_fields)
sort_fields.try(:each) do |field|
pluck_fields << Arel.sql(field)
end
fragments = {}
rows = records.distinct.pluck(*pluck_fields)
rows.each do |row|
rid = JSONAPI::ResourceIdentity.new(resource_klass, row[1])
fragments[rid] ||= JSONAPI::ResourceFragment.new(rid)
attributes_offset = 2
if cache_field
fragments[rid].cache = cast_to_attribute_type(row[attributes_offset], cache_field[:type])
attributes_offset+= 1
end
model_fields.each_with_index do |k, idx|
fragments[rid].add_attribute(k[0], cast_to_attribute_type(row[idx + attributes_offset], k[1][:type]))
attributes_offset+= 1
end
source_rid = JSONAPI::ResourceIdentity.new(self, row[0])
fragments[rid].add_related_from(source_rid)
linkage_fields.each do |linkage_field|
fragments[rid].initialize_related(linkage_field[:relationship_name])
related_id = row[attributes_offset]
if related_id
related_rid = JSONAPI::ResourceIdentity.new(linkage_field[:resource_klass], related_id)
fragments[rid].add_related_identity(linkage_field[:relationship_name], related_rid)
end
attributes_offset+= 1
end
if connect_source_identity
related_relationship = resource_klass._relationships[relationship.inverse_relationship]
if related_relationship
fragments[rid].add_related_identity(related_relationship.name, source_rid)
end
end
end
fragments
end
# Gets resource identities where the related resource is polymorphic and the resource type and id
# are stored on the primary resources. Cache fields will always be on the related resources.
def find_related_polymorphic_fragments(source_rids, relationship, options, connect_source_identity)
filters = options.fetch(:filters, {})
source_ids = source_rids.collect {|rid| rid.id}
resource_klass = relationship.resource_klass
include_directives = options[:include_directives] ? options[:include_directives].include_directives : {}
linkage_relationships = []
resource_types = relationship.resource_types
resource_types.each do |resource_type|
related_resource_klass = resource_klass_for(resource_type)
relationships = related_resource_klass.to_one_relationships_for_linkage(include_directives)
relationships.each do |r|
linkage_relationships << "##{resource_type}.#{r}"
end
end
join_manager = ActiveRelation::JoinManager.new(resource_klass: self,
source_relationship: relationship,
relationships: linkage_relationships,
filters: filters)
paginator = options[:paginator] if source_rids.count == 1
# Note: We will sort by the source table. Without using unions we can't sort on a polymorphic relationship
# in any manner that makes sense
records = apply_request_settings_to_records(records: records_for_source_to_related(options),
resource_klass: resource_klass,
sort_primary: true,
primary_keys: source_ids,
paginator: paginator,
filters: filters,
join_manager: join_manager,
options: options)
primary_key = concat_table_field(_table_name, _primary_key)
related_key = concat_table_field(_table_name, relationship.foreign_key)
related_type = concat_table_field(_table_name, relationship.polymorphic_type)
pluck_fields = [
Arel.sql("#{primary_key} AS #{_table_name}_#{_primary_key}"),
Arel.sql("#{related_key} AS #{_table_name}_#{relationship.foreign_key}"),
Arel.sql("#{related_type} AS #{_table_name}_#{relationship.polymorphic_type}")
]
# Get the additional fields from each relation. There's a limitation that the fields must exist in each relation
relation_positions = {}
relation_index = pluck_fields.length
attributes = options.fetch(:attributes, [])
# Add resource specific fields
if resource_types.nil? || resource_types.length == 0
# :nocov:
warn "No resource types found for polymorphic relationship."
# :nocov:
else
resource_types.try(:each) do |type|
related_klass = resource_klass_for(type.to_s)
cache_field = related_klass.attribute_to_model_field(:_cache_field) if options[:cache]
table_alias = join_manager.source_join_details(type)[:alias]
cache_offset = relation_index
if cache_field
pluck_fields << Arel.sql("#{concat_table_field(table_alias, cache_field[:name])} AS cache_#{type}_#{cache_field[:name]}")
relation_index+= 1
end
model_fields = {}
field_offset = relation_index
attributes.try(:each) do |attribute|
model_field = related_klass.attribute_to_model_field(attribute)
model_fields[attribute] = model_field
pluck_fields << Arel.sql("#{concat_table_field(table_alias, model_field[:name])} AS #{table_alias}_#{model_field[:name]}")
relation_index+= 1
end
model_offset = relation_index
model_fields.each do |_k, v|
pluck_fields << Arel.sql("#{concat_table_field(table_alias, v[:name])}")
relation_index+= 1
end
relation_positions[type] = {relation_klass: related_klass,
cache_field: cache_field,
cache_offset: cache_offset,
model_fields: model_fields,
model_offset: model_offset,
field_offset: field_offset}
end
end
# Add to_one linkage fields
linkage_fields = []
linkage_offset = relation_index
linkage_relationships.each do |linkage_relationship_path|
path = JSONAPI::Path.new(resource_klass: self,
path_string: "#{relationship.name}#{linkage_relationship_path}",
ensure_default_field: false)
linkage_relationship = path.segments[-1].relationship
if linkage_relationship.polymorphic? && linkage_relationship.belongs_to?
linkage_relationship.resource_types.each do |resource_type|
klass = resource_klass_for(resource_type)
linkage_fields << {relationship: linkage_relationship, resource_klass: klass}
linkage_table_alias = join_manager.join_details_by_polymorphic_relationship(linkage_relationship, resource_type)[:alias]
primary_key = klass._primary_key
pluck_fields << Arel.sql("#{concat_table_field(linkage_table_alias, primary_key)} AS #{linkage_table_alias}_#{primary_key}")
end
else
klass = linkage_relationship.resource_klass
linkage_fields << {relationship: linkage_relationship, resource_klass: klass}
linkage_table_alias = join_manager.join_details_by_relationship(linkage_relationship)[:alias]
primary_key = klass._primary_key
pluck_fields << Arel.sql("#{concat_table_field(linkage_table_alias, primary_key)} AS #{linkage_table_alias}_#{primary_key}")
end
end
rows = records.distinct.pluck(*pluck_fields)
related_fragments = {}
rows.each do |row|
unless row[1].nil? || row[2].nil?
related_klass = resource_klass_for(row[2])
rid = JSONAPI::ResourceIdentity.new(related_klass, row[1])
related_fragments[rid] ||= JSONAPI::ResourceFragment.new(rid)
source_rid = JSONAPI::ResourceIdentity.new(self, row[0])
related_fragments[rid].add_related_from(source_rid)
if connect_source_identity
related_relationship = related_klass._relationships[relationship.inverse_relationship]
if related_relationship
related_fragments[rid].add_related_identity(related_relationship.name, source_rid)
end
end
relation_position = relation_positions[row[2].downcase.pluralize]
model_fields = relation_position[:model_fields]
cache_field = relation_position[:cache_field]
cache_offset = relation_position[:cache_offset]
field_offset = relation_position[:field_offset]
if cache_field
related_fragments[rid].cache = cast_to_attribute_type(row[cache_offset], cache_field[:type])
end
if attributes.length > 0
model_fields.each_with_index do |k, idx|
related_fragments[rid].add_attribute(k[0], cast_to_attribute_type(row[idx + field_offset], k[1][:type]))
end
end
linkage_fields.each_with_index do |linkage_field_details, idx|
relationship = linkage_field_details[:relationship]
related_fragments[rid].initialize_related(relationship.name)
related_id = row[linkage_offset + idx]
if related_id
related_rid = JSONAPI::ResourceIdentity.new(linkage_field_details[:resource_klass], related_id)
related_fragments[rid].add_related_identity(relationship.name, related_rid)
end
end
end
end
related_fragments
end
def apply_request_settings_to_records(records:,
join_manager: ActiveRelation::JoinManager.new(resource_klass: self),
resource_klass: self,
filters: {},
primary_keys: nil,
sort_criteria: nil,
sort_primary: nil,
paginator: nil,
options: {})
options[:_relation_helper_options] = { join_manager: join_manager, sort_fields: [] }
records = resource_klass.apply_joins(records, join_manager, options)
if primary_keys
records = records.where(_primary_key => primary_keys)
end
unless filters.empty?
records = resource_klass.filter_records(records, filters, options)
end
if sort_primary
records = records.order(_primary_key => :asc)
else
order_options = resource_klass.construct_order_options(sort_criteria)
records = resource_klass.sort_records(records, order_options, options)
end
if paginator
records = resource_klass.apply_pagination(records, paginator, order_options)
end
records
end
def apply_joins(records, join_manager, options)
join_manager.join(records, options)
end
def apply_pagination(records, paginator, order_options)
records = paginator.apply(records, order_options) if paginator
records
end
def apply_sort(records, order_options, options)
if order_options.any?
order_options.each_pair do |field, direction|
records = apply_single_sort(records, field, direction, options)
end
end
records
end
def apply_single_sort(records, field, direction, options)
context = options[:context]
strategy = _allowed_sort.fetch(field.to_sym, {})[:apply]
options[:_relation_helper_options] ||= {}
options[:_relation_helper_options][:sort_fields] ||= []
if strategy
records = call_method_or_proc(strategy, records, direction, context)
else
join_manager = options.dig(:_relation_helper_options, :join_manager)
sort_field = join_manager ? get_aliased_field(field, join_manager) : field
options[:_relation_helper_options][:sort_fields].push("#{sort_field}")
records = records.order(Arel.sql("#{sort_field} #{direction}"))
end
records
end
# Assumes ActiveRecord's counting. Override if you need a different counting method
def count_records(records)
if Rails::VERSION::MAJOR >= 5 && ActiveRecord::VERSION::MINOR >= 1
records.count(:all)
else
records.count
end
end
def filter_records(records, filters, options)
if _polymorphic
_polymorphic_resource_klasses.each do |klass|
records = klass.apply_filters(records, filters, options)
end
else
records = apply_filters(records, filters, options)
end
records
end
def construct_order_options(sort_params)
if _polymorphic
warn "Sorting is not supported on polymorphic relationships"
else
super(sort_params)
end
end
def sort_records(records, order_options, options)
apply_sort(records, order_options, options)
end
def concat_table_field(table, field, quoted = false)
if table.blank? || field.to_s.include?('.')
# :nocov:
if quoted
"\"#{field.to_s}\""
else
field.to_s
end
# :nocov:
else
if quoted
# :nocov:
"\"#{table.to_s}\".\"#{field.to_s}\""
# :nocov:
else
"#{table.to_s}.#{field.to_s}"
end
end
end
def apply_filters(records, filters, options = {})
if filters
filters.each do |filter, value|
records = apply_filter(records, filter, value, options)
end
end
records
end
def get_aliased_field(path_with_field, join_manager)
path = JSONAPI::Path.new(resource_klass: self, path_string: path_with_field)
relationship_segment = path.segments[-2]
field_segment = path.segments[-1]
if relationship_segment
join_details = join_manager.join_details[path.last_relationship]
table_alias = join_details[:alias]
else
table_alias = self._table_name
end
concat_table_field(table_alias, field_segment.delegated_field_name)
end
def apply_filter(records, filter, value, options = {})
strategy = _allowed_filters.fetch(filter.to_sym, Hash.new)[:apply]
if strategy
records = call_method_or_proc(strategy, records, value, options)
else
join_manager = options.dig(:_relation_helper_options, :join_manager)
field = join_manager ? get_aliased_field(filter, join_manager) : filter
records = records.where(Arel.sql(field) => value)
end
records
end
end
end
end