This repository has been archived by the owner on Apr 17, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 158
/
query.rb
1162 lines (1004 loc) · 32 KB
/
query.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
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
# TODO: break this up into classes for each primary option, eg:
#
# - DataMapper::Query::Fields
# - DataMapper::Query::Links
# - DataMapper::Query::Offset
# - DataMapper::Query::Limit
# - DataMapper::Query::Order
#
# TODO: move assertions, validations, transformations, and equality
# checking into each class and clean up Query
module DataMapper
# Query class represents a query which will be run against the data-store.
# Generally Query objects can be found inside Collection objects.
#
class Query
include Extlib::Assertions
OPTIONS = [ :fields, :links, :conditions, :offset, :limit, :order, :unique, :add_reversed, :reload ].to_set.freeze
##
# Returns the repository query should be
# executed in
#
# Set in cases like the following:
#
# @example
#
# Document.all(:repository => :medline)
#
#
# @return [Repository]
# the Repository to retrieve results from
#
# @api semipublic
attr_reader :repository
##
# Returns model (class) that is used
# to instantiate objects from query result
# returned by adapter
#
# @return [Model]
# the Model to retrieve results from
#
# @api semipublic
attr_reader :model
##
# Returns the fields
#
# Set in cases like the following:
#
# @example
#
# Document.all(:fields => [:title, :vernacular_title, :abstract])
#
# @return [PropertySet]
# the properties in the Model that will be retrieved
#
# @api semipublic
attr_reader :fields
##
# Returns the links (associations) query fetches
#
# @return [Array<DataMapper::Associations::Relationship>]
# the relationships that will be used to scope the results
#
# @api semipublic
attr_reader :links
##
# Returns the conditions of the query
#
# In the following example:
#
# @example
#
# Team.all(:wins.gt => 30, :conference => 'East')
#
# Conditions are "greater than" operator for "wins"
# field and exact match operator for "conference"
# field:
#
# [[:gt, #<Property:Team:wins>, 30], [:eql, #<Property:Team:conference>, 'East']]
#
# @return [Array]
# the conditions that will be used to scope the results
#
# @api semipublic
attr_reader :conditions
##
# Returns the offset query uses
#
# Set in cases like the following:
#
# @example
#
# Document.all(:offset => page.offset)
#
# @return [Integer]
# the offset of the results
#
# @api semipublic
attr_reader :offset
##
# Returns the limit query uses
#
# Set in cases like the following:
#
# @example
#
# Document.all(:limit => 10)
#
# @return [Integer, NilClass]
# the maximum number of results
#
# @api semipublic
attr_reader :limit
##
# Returns the order
#
# Set in cases like the following:
#
# @example
#
# Document.all(:order => [:created_at.desc, :length.desc])
#
# query order is a set of two ordering rules, descending on
# "created_at" field and descending again on "length" field
#
# @return [Array]
# the order of results
#
# @api semipublic
attr_reader :order
##
# Returns the original options
#
# @return [Hash]
# the original options
#
# @api private
attr_reader :options
# TODO: move these checks inside assert_valid_conditions and blow
# up if invalid conditions used
#def valid?
# !conditions.any? do |operator, property, bind_value|
# next if operator.kind_of?(Array)
#
# case bind_value
# when Array
# bind_value.empty?
# when Range
# operator != :eql && operator != :in && operator != :not
# end
# end
#end
##
# Indicates if each result should be returned in reverse order
#
# Set in cases like the following:
#
# @example
#
# Document.all(:limit => 5).reverse
#
# Note that :add_reversed option may be used in conditions directly,
# but this is rarely the case
#
# @return [TrueClass, FalseClass]
# true if the results should be reversed, false if not
#
# @api private
def add_reversed?
@add_reversed
end
##
# Indicates if the Query results should replace the results in the Identity Map
#
# TODO: needs example
#
# @return [TrueClass, FalseClass]
# true if the results should be reloaded, false if not
#
# @api semipublic
def reload?
@reload
end
##
# Indicates if the Query results should be unique
#
# TODO: needs example
#
# @return [TrueClass, FalseClass]
# true if the results should be unique, false if not
#
# @api semipublic
def unique?
@unique
end
##
# Indicates if the Query has raw conditions
#
# @return [TrueClass, FalseClass]
# true if the query has raw conditions, false if not
#
# @api semipublic
def raw?
@raw
end
##
# Returns a new Query with a reversed order
#
# @example
#
# Document.all(:limit => 5).reverse
#
# Will execute a single query with correct order
#
# @return [Query]
# new Query with reversed order
#
# @api semipublic
def reverse
dup.reverse!
end
##
# Reverses the sort order of the Query
#
# @example
#
# Document.all(:limit => 5).reverse
#
# Will execute a single query with original order
# and then reverse collection in the Ruby space
#
# @return [Query]
# self
#
# @api semipublic
def reverse!
# reverse the sort order
@order.map! { |o| o.reverse! }
# copy the order to the options
@options = @options.merge(:order => @order.map { |o| o.dup }).freeze
self
end
##
# Updates the Query with another Query or conditions
#
# Pretty unrealistic example:
#
# @example
#
# Journal.all(:limit => 2).query.limit # => 2
# Journal.all(:limit => 2).query.update(:limit => 3).limit # => 3
#
# @param [Query, Hash] other
# other Query or conditions
#
# @return [Query]
# self
#
# @api semipublic
def update(other)
assert_kind_of 'other', other, self.class, Hash
options = case other
when self.class
if self.eql?(other)
return self
end
assert_valid_other(other)
@options.merge(other.options)
when Hash
if other.empty?
return self
end
@options.merge(other)
end
initialize(repository, model, options)
self
end
##
# Similar to Query#update, but acts on a duplicate.
#
# @param [Query, Hash] other
# other query to merge with
#
# @return [Query]
# updated duplicate of original query
#
# @api semipublic
def merge(other)
dup.update(other)
end
# Builds and returns new query that merges
# original with one given, and slices the result
# with respect to :limit and :offset options
#
# This method is used by Collection to
# concatenate options from multiple chained
# calls in cases like the following:
#
# @example
#
# author.books.all(:year => 2009).all(:published => false)
#
# @api semipublic
def relative(options)
assert_kind_of 'options', options, Hash
options = options.dup
repository = options.delete(:repository) || self.repository
if repository.kind_of?(Symbol)
repository = DataMapper.repository(repository)
end
if options.key?(:offset) && (options.key?(:limit) || self.limit)
offset = options.delete(:offset)
limit = options.delete(:limit) || self.limit - offset
self.class.new(repository, model, @options.merge(options)).slice!(offset, limit)
else
self.class.new(repository, model, @options.merge(options))
end
end
##
# Takes an Enumerable of records, and destructively filters it.
# First finds all matching conditions, then sorts it,
# then does offset & limit
#
# @param [Enumerable] records
# The set of records to be filtered
#
# @return [Enumerable]
# Whats left of the given array after the filtering
#
# @api semipublic
def filter_records(records)
records = records.uniq if unique?
records = match_records(records)
records = sort_records(records)
records = limit_records(records)
records
end
##
# Filter a set of records by the conditions
#
# @param [Enumerable] records
# The set of records to be filtered
#
# @return [Enumerable]
# Whats left of the given array after the matching
#
# @api semipublic
def match_records(records)
records.select do |record|
conditions.matches?(record)
end
end
##
# Sorts a list of Records by the order
#
# @param [Enumerable] records
# A list of Resources to sort
#
# @return [Enumerable]
# The sorted records
#
# @api semipublic
def sort_records(records)
sort_order = order.map { |direction| [ direction.target, direction.operator == :asc ] }
records.sort_by do |record|
sort_order.map do |(property, ascending)|
Sort.new(record_value(record, property), ascending)
end
end
end
##
# Limits a set of records by the offset and/or limit
#
# @param [Enumerable] records
# A list of Recrods to sort
#
# @return [Enumerable]
# The offset & limited records
#
# @api semipublic
def limit_records(records)
size = records.size
if offset > size - 1
[]
elsif (limit && limit != size) || offset > 0
records[offset, limit || size] || []
else
records.dup
end
end
##
# Compares another Query for equivalency
#
# @param [Query] other
# the other Query to compare with
#
# @return [TrueClass, FalseClass]
# true if they are equivalent, false if not
#
# @api semipublic
def ==(other)
if equal?(other)
return true
end
unless [ :repository, :model, :fields, :links, :conditions, :order, :offset, :limit, :reload?, :unique?, :add_reversed? ].all? { |m| other.respond_to?(m) }
return false
end
cmp?(other, :==)
end
##
# Compares another Query for equality
#
# @param [Query] other
# the other Query to compare with
#
# @return [TrueClass, FalseClass]
# true if they are equal, false if not
#
# @api semipublic
def eql?(other)
if equal?(other)
return true
end
unless other.class.equal?(self.class)
return false
end
cmp?(other, :eql?)
end
# Slices collection by adding limit and offset to the
# query, so a single query is executed
#
# @example
#
# Journal.all(:limit => 10).slice(3, 5)
#
# will execute query with the following limit and offset
# (when repository uses DataObjects adapter, and thus
# queries use SQL):
#
# LIMIT 5 OFFSET 3
#
# @api semipublic
def slice(*args)
dup.slice!(*args)
end
alias [] slice
# Slices collection by adding limit and offset to the
# query, so a single query is executed
#
# @example
#
# Journal.all(:limit => 10).slice!(3, 5)
#
# will execute query with the following limit
# (when repository uses DataObjects adapter, and thus
# queries use SQL):
#
# LIMIT 10
#
# and then takes a slice of collection in the Ruby space
#
# @api semipublic
def slice!(*args)
offset, limit = extract_slice_arguments(*args)
if self.limit || self.offset > 0
offset, limit = get_relative_position(offset, limit)
end
update(:offset => offset, :limit => limit)
end
# Returns detailed human readable
# string representation of the query
#
# @return [String] detailed string representation of the query
#
# @api semipublic
def inspect
attrs = [
[ :repository, repository.name ],
[ :model, model ],
[ :fields, fields ],
[ :links, links ],
[ :conditions, conditions ],
[ :order, order ],
[ :limit, limit ],
[ :offset, offset ],
[ :reload, reload? ],
[ :unique, unique? ],
]
"#<#{self.class.name} #{attrs.map { |k, v| "@#{k}=#{v.inspect}" }.join(' ')}>"
end
##
# Get the properties used in the conditions
#
# @return [Set<Property>]
# Set of Property objects used in the conditions
#
# @api private
def condition_properties
properties = Set.new
operands = conditions.operands.dup
while operand = operands.pop
case operand
when Conditions::AbstractOperation then operands.concat(operand.operands)
when Conditions::AbstractComparison then properties << operand.property
end
end
properties
end
private
##
# Initializes a Query instance
#
# @example
#
# JournalIssue.all(:links => [:journal, :country, :medium], :repository => :medline)
#
# initialized a query with repository defined with name :medline,
# model JournalIssue and options { :links => [:journal, :country, :medium] }
#
# @param [Repository] repository
# the Repository to retrieve results from
# @param [Model] model
# the Model to retrieve results from
# @param [Hash] options
# the conditions and scope
#
# @api semipublic
def initialize(repository, model, options = {})
assert_kind_of 'repository', repository, Repository
assert_kind_of 'model', model, Model
@repository = repository
@model = model
@options = options.dup.freeze
repository_name = repository.name
@properties = @model.properties(repository_name)
@relationships = @model.relationships(repository_name)
assert_valid_options(@options)
@fields = @options.fetch :fields, @properties.defaults
@links = @options.fetch :links, []
@conditions = Conditions::Operation.new(:and) # AND all the conditions together
@offset = @options.fetch :offset, 0
@limit = @options.fetch :limit, nil
@order = @options.fetch :order, @model.default_order(repository_name)
@unique = @options.fetch :unique, false
@add_reversed = @options.fetch :add_reversed, false
@reload = @options.fetch :reload, false
@raw = false
@links = @links.dup
# treat all non-options as conditions
@options.except(*OPTIONS).each { |kv| append_condition(*kv) }
# parse @options[:conditions] differently
case conditions = @options[:conditions]
when Conditions::AbstractOperation
@conditions << conditions
when Hash
conditions.each { |kv| append_condition(*kv) }
when Array
statement, *bind_values = *conditions
@conditions << [ statement, bind_values ]
@raw = true
end
normalize_order
normalize_fields
normalize_links
end
##
# Copying contructor, called for Query#dup
#
# @api semipublic
def initialize_copy(original)
initialize(original.repository, original.model, original.options)
end
##
# Validate the options
#
# @param [#each] options
# the options to validate
#
# @raise [ArgumentError]
# if any pairs in +options+ are invalid options
#
# @api private
def assert_valid_options(options)
assert_kind_of 'options', options, Hash
options.each do |attribute, value|
case attribute
when :fields then assert_valid_fields(value, options[:unique])
when :links then assert_valid_links(value)
when :conditions then assert_valid_conditions(value)
when :offset then assert_valid_offset(value, options[:limit])
when :limit then assert_valid_limit(value)
when :order then assert_valid_order(value, options[:fields])
when :unique, :add_reversed, :reload then assert_valid_boolean("options[:#{attribute}]", value)
else
assert_valid_conditions(attribute => value)
end
end
end
# Verifies that value of :fields option
# refers to existing properties
#
# @api private
def assert_valid_fields(fields, unique)
assert_kind_of 'options[:fields]', fields, Array
if fields.empty? && unique == false
raise ArgumentError, '+options[:fields]+ should not be empty if +options[:unique]+ is false'
end
fields.each do |field|
case field
when Symbol, String
unless @properties.named?(field)
raise ArgumentError, "+options[:fields]+ entry #{field.inspect} does not map to a property in #{model}"
end
when Property
unless field.model == model && @properties.include?(field)
raise ArgumentError, "+options[:field]+ entry #{field.name.inspect} does not map to a property in #{model}"
end
else
raise ArgumentError, "+options[:fields]+ entry #{field.inspect} of an unsupported object #{field.class}"
end
end
end
# Verifies that value of :links option
# refers to existing associations
#
# @api private
def assert_valid_links(links)
assert_kind_of 'options[:links]', links, Array
if links.empty?
raise ArgumentError, '+options[:links]+ should not be empty'
end
links.each do |link|
case link
when Symbol, String
unless @relationships.key?(link.to_sym)
raise ArgumentError, "+options[:links]+ entry #{link.inspect} does not map to a relationship in #{model}"
end
when Associations::Relationship
# TODO: figure out how to validate links from other models
#unless @relationships.value?(link)
# raise ArgumentError, "+options[:links]+ entry #{link.name.inspect} does not map to a relationship in #{model}"
#end
else
raise ArgumentError, "+options[:links]+ entry #{link.inspect} of an unsupported object #{link.class}"
end
end
end
# Verifies that value of :conditions option
# refers to existing properties
#
# @api private
def assert_valid_conditions(conditions)
assert_kind_of 'options[:conditions]', conditions, Conditions::AbstractOperation, Hash, Array
case conditions
when Hash
conditions.each do |subject, bind_value|
case subject
when Symbol, String
unless subject.to_s.include?('.') || @properties.named?(subject) || @relationships.key?(subject)
raise ArgumentError, "condition #{subject.inspect} does not map to a property or relationship in #{model}"
end
when Operator
unless (Conditions::Comparison.slugs | [ :not ]).include?(subject.operator)
raise ArgumentError, "condition #{subject.inspect} used an invalid operator #{subject.operator}"
end
assert_valid_conditions(subject.target => bind_value)
if subject.operator == :not && bind_value.kind_of?(Array) && bind_value.empty?
raise ArgumentError, "Cannot use 'not' operator with a bind value that is an empty Array for #{subject.inspect}"
end
when Path
assert_valid_links(subject.relationships)
when Associations::Relationship, Property
# TODO: validate that it belongs to the current model, or to any
# model in the links
#unless @properties.include?(subject)
# raise ArgumentError, "condition #{subject.name.inspect} does not map to a property in #{model}"
#end
else
raise ArgumentError, "condition #{subject.inspect} of an unsupported object #{subject.class}"
end
end
when Array
if conditions.empty?
raise ArgumentError, '+options[:conditions]+ should not be empty'
end
unless conditions.first.kind_of?(String) && !conditions.first.blank?
raise ArgumentError, '+options[:conditions]+ should have a statement for the first entry'
end
end
end
# Verifies that query offset is non-negative and only used together with limit
# @api private
def assert_valid_offset(offset, limit)
assert_kind_of 'options[:offset]', offset, Integer
unless offset >= 0
raise ArgumentError, "+options[:offset]+ must be greater than or equal to 0, but was #{offset.inspect}"
end
if offset > 0 && limit.nil?
raise ArgumentError, '+options[:offset]+ cannot be greater than 0 if limit is not specified'
end
end
# Verifies that query limit equals to or greater than 1
# @api private
def assert_valid_limit(limit)
assert_kind_of 'options[:limit]', limit, Integer
unless limit >= 1
raise ArgumentError, "+options[:limit]+ must be greater than or equal to 1, but was #{limit.inspect}"
end
end
# Verifies that :order option uses proper operator and refers
# to existing property
#
# @api private
def assert_valid_order(order, fields)
assert_kind_of 'options[:order]', order, Array
if order.empty? && fields && fields.any? { |p| !p.kind_of?(Operator) }
raise ArgumentError, '+options[:order]+ should not be empty if +options[:fields] contains a non-operator'
end
order.each do |order_entry|
case order_entry
when Operator
unless order_entry.operator == :asc || order_entry.operator == :desc
raise ArgumentError, "+options[:order]+ entry #{order_entry.inspect} used an invalid operator #{order_entry.operator}"
end
assert_valid_order([ order_entry.target ], fields)
when Symbol, String
unless @properties.named?(order_entry)
raise ArgumentError, "+options[:order]+ entry #{order_entry.inspect} does not map to a property in #{model}"
end
when Property
unless order_entry.model == model && @properties.include?(order_entry)
raise ArgumentError, "+options[:order]+ entry #{order_entry.name.inspect} does not map to a property in #{model}"
end
when Direction
unless order_entry.property.model == model && @properties.include?(order_entry.property)
raise ArgumentError, "+options[:order]+ entry #{order_entry.property.name.inspect} does not map to a property in #{model}"
end
else
raise ArgumentError, "+options[:order]+ entry #{order_entry.inspect} of an unsupported object #{order_entry.class}"
end
end
end
# Used to verify value of boolean properties in conditions
# @api private
def assert_valid_boolean(name, value)
if value != true && value != false
raise ArgumentError, "+#{name}+ should be true or false, but was #{value.inspect}"
end
end
# Verifies that associations given in conditions belong
# to the same repository as query's model
#
# @api private
def assert_valid_other(other)
unless other.repository == repository
raise ArgumentError, "+other+ #{self.class} must be for the #{repository.name} repository, not #{other.repository.name}"
end
unless other.model == model
raise ArgumentError, "+other+ #{self.class} must be for the #{model.name} model, not #{other.model.name}"
end
end
##
# Normalize order elements to Query::Direction instances
#
# TODO: needs example
#
# @api private
def normalize_order
# TODO: should Query::Path objects be permitted? If so, then it
# should probably be normalized to a Direction object
@order = @order.map do |order|
case order
when Operator
target = order.target
property = target.kind_of?(Property) ? target : @properties[target]
Direction.new(property, order.operator)
when Symbol, String
Direction.new(@properties[order])
when Property
Direction.new(order)
when Direction
order.dup
end
end
end
##
# Normalize fields to Property instances
#
# TODO: needs example
#
# @api private
def normalize_fields
@fields = @fields.map do |field|
case field
when Symbol, String
@properties[field]
when Property, Operator
field
end
end
end
##
# Normalize links to Query::Path
#
# Normalization means links given as symbols are replaced with
# relationships they refer to, intermediate links are "followed"
# and duplicates are removed
#
# This method, even though is not a bang method, modifies
# receiver's links attribute
#
# @api private
def normalize_links
@links.map! do |link|
relationship = case link
when Symbol, String then @relationships[link]
when Associations::Relationship then link
end
(links = relationship.links).any? ? links : relationship
end
@links.flatten!
@links.uniq!
end
##
# Append conditions to this Query
#
# TODO: needs example
#
# @param [Symbol, String, Property, Path, Operator] subject
# the subject to match
# @param [Object] bind_value
# the value to match on
# @param [Symbol] operator
# the operator to match with
#
# @api private
def append_condition(subject, bind_value, operator = :eql)
subject = case subject
when Symbol
return append_condition(subject.to_s, bind_value, operator)
when String
if subject.include?('.')
query_path = model
subject.split('.').each { |m| query_path = query_path.send(m) }
return append_condition(query_path, bind_value, operator)
else
return append_condition(@properties[subject] || @relationships[subject], bind_value, operator)
end
when Operator
return append_condition(subject.target, bind_value, subject.operator)
when Path
@links.concat(subject.relationships)
subject
when Associations::Relationship
# TODO: when the bind_value is a Collection, and it is not loaded
# then use a subquery to scope the results rather than lazy loading
# it just to retrieve the Resource key
# TODO: handle compound keys. Consider pushing this into the adapter
source_key = subject.source_key.first
target_key = subject.target_key.first
if (source_values = Array(bind_value).map { |resource| target_key.get!(resource) }.compact).any?
append_condition(source_key, source_values, operator)
end
return @conditions
when Property
subject
end
# TODO: push this logic into Conditions objects
bind_value = normalize_bind_value(subject, bind_value)
negated = operator == :not