forked from datamapper/dm-core
/
query.rb
1444 lines (1255 loc) · 40.6 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::Conditions
# - DataMapper::Query::Offset
# - DataMapper::Query::Limit
# - DataMapper::Query::Order
#
# TODO: move assertions, validations, transformations, and equality
# checking into each class and clean up Query
#
# TODO: add a way to "register" these classes with the Query object
# so that new reserved options can be added in the future. Each
# class will need to implement a "slug" method or something similar
# so that their option namespace can be reserved.
# TODO: move condition transformations into a Query::Conditions
# helper class that knows how to transform the primitives, and
# calls #comparison_for(repository, model) on objects (or some
# other convention that we establish)
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 DataMapper::Assertions
extend Equalizer
OPTIONS = [ :fields, :links, :conditions, :offset, :limit, :order, :unique, :add_reversed, :reload ].to_set.freeze
equalize :repository, :model, :sorted_fields, :links, :conditions, :order, :offset, :limit, :reload?, :unique?, :add_reversed?
# Extract conditions to match a Resource or Collection
#
# @param [Array, Collection, Resource] source
# the source to extract the values from
# @param [ProperySet] source_key
# the key to extract the value from the resource
# @param [ProperySet] target_key
# the key to match the resource with
#
# @return [AbstractComparison, AbstractOperation]
# the conditions to match the resources with
#
# @api private
def self.target_conditions(source, source_key, target_key)
target_key_size = target_key.size
source_values = []
if source.nil?
source_values << [ nil ] * target_key_size
else
Array(source).each do |resource|
next unless source_key.loaded?(resource)
source_value = source_key.get!(resource)
next unless target_key.valid?(source_value)
source_values << source_value
end
end
source_values.uniq!
if target_key_size == 1
target_key = target_key.first
source_values.flatten!
if source_values.size == 1
Conditions::EqualToComparison.new(target_key, source_values.first)
else
Conditions::InclusionComparison.new(target_key, source_values)
end
else
or_operation = Conditions::OrOperation.new
source_values.each do |source_value|
and_operation = Conditions::AndOperation.new
target_key.zip(source_value) do |property, value|
and_operation << Conditions::EqualToComparison.new(property, value)
end
or_operation << and_operation
end
or_operation
end
end
# @param [Repository] repository
# the default repository to scope the query within
# @param [Model] model
# the default model for the query
# @param [#query, Enumerable] source
# the source to generate the query with
#
# @return [Query]
# the query to match the resources with
#
# @api private
def self.target_query(repository, model, source)
if source.respond_to?(:query)
source.query
elsif source.kind_of?(Enumerable)
key = model.key(repository.name)
conditions = Query.target_conditions(source, key, key)
repository.new_query(model, :conditions => conditions)
else
raise ArgumentError, "+source+ must respond to #query or be an Enumerable, but was #{source.class}"
end
end
# 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 private
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".
#
# @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, nil]
# 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
# 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 [Boolean]
# 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 [Boolean]
# 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 [Boolean]
# true if the results should be unique, false if not
#
# @api semipublic
def unique?
@unique
end
# Indicates if the Query has raw conditions
#
# @return [Boolean]
# true if the query has raw conditions, false if not
#
# @api semipublic
def raw?
@raw
end
# Indicates if the Query is valid
#
# @return [Boolean]
# true if the query is valid
#
# @api semipublic
def valid?
conditions.valid?
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! { |direction| direction.dup.reverse! }
# copy the order to the options
@options = @options.merge(:order => @order).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)
other_options = if kind_of?(other.class)
return self if self.eql?(other)
assert_valid_other(other)
other.options
else
other = other.to_hash
return self if other.empty?
other
end
@options = @options.merge(other_options).freeze
assert_valid_options(@options)
normalize = DataMapper::Ext::Hash.only(other_options, *OPTIONS - [ :conditions ]).map do |attribute, value|
instance_variable_set("@#{attribute}", DataMapper::Ext.try_dup(value))
attribute
end
merge_conditions([ DataMapper::Ext::Hash.except(other_options, *OPTIONS), other_options[:conditions] ])
normalize_options(normalize | [ :links, :unique ])
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)
options = options.to_hash
offset = nil
limit = self.limit
if options.key?(:offset) && (options.key?(:limit) || limit)
options = options.dup
offset = options.delete(:offset)
limit = options.delete(:limit) || limit - offset
end
query = merge(options)
query = query.slice!(offset, limit) if offset
query
end
# Return the union with another query
#
# @param [Query] other
# the other query
#
# @return [Query]
# the union of the query and other
#
# @api semipublic
def union(other)
return dup if self == other
set_operation(:union, other)
end
alias_method :|, :union
alias_method :+, :union
# Return the intersection with another query
#
# @param [Query] other
# the other query
#
# @return [Query]
# the intersection of the query and other
#
# @api semipublic
def intersection(other)
return dup if self == other
set_operation(:intersection, other)
end
alias_method :&, :intersection
# Return the difference with another query
#
# @param [Query] other
# the other query
#
# @return [Query]
# the difference of the query and other
#
# @api semipublic
def difference(other)
set_operation(:difference, other)
end
alias_method :-, :difference
# Clear conditions
#
# @return [self]
#
# @api semipublic
def clear
@conditions = Conditions::Operation.new(:null)
self
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) if conditions
records = sort_records(records) if order
records = limit_records(records) if limit || offset > 0
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)
conditions = self.conditions
records.select { |record| conditions.matches?(record) }
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 records to sort
#
# @return [Enumerable]
# The offset & limited records
#
# @api semipublic
def limit_records(records)
offset = self.offset
limit = self.limit
size = records.size
if offset > size - 1
[]
elsif (limit && limit != size) || offset > 0
records[offset, limit || size] || []
else
records.dup
end
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_method :[], :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 { |key, value| "@#{key}=#{value.inspect}" }.join(' ')}>"
end
# Get the properties used in the conditions
#
# @return [Set<Property>]
# Set of properties used in the conditions
#
# @api private
def condition_properties
properties = Set.new
each_comparison do |comparison|
next unless comparison.respond_to?(:subject)
subject = comparison.subject
properties << subject if subject.kind_of?(Property)
end
properties
end
# Return a list of fields in predictable order
#
# @return [Array<Property>]
# list of fields sorted in deterministic order
#
# @api private
def sorted_fields
fields.sort_by { |property| property.hash }
end
# Transform Query into subquery conditions
#
# @return [AndOperation]
# a subquery for the Query
#
# @api private
def to_subquery
collection = model.all(merge(:fields => model_key))
Conditions::Operation.new(:and, Conditions::Comparison.new(:in, self_relationship, collection))
end
# Hash representation of a Query
#
# @return [Hash]
# Hash representation of a Query
#
# @api private
def to_hash
{
:repository => repository.name,
:model => model.name,
:fields => fields,
:links => links,
:conditions => conditions,
:offset => offset,
:limit => limit,
:order => order,
:unique => unique?,
:add_reversed => add_reversed?,
:reload => reload?,
}
end
# Extract options from a Query
#
# @param [Query] query
# the query to extract options from
#
# @return [Hash]
# the options to use to initialize the new query
#
# @api private
def to_relative_hash
DataMapper::Ext::Hash.only(to_hash, :fields, :order, :unique, :add_reversed, :reload)
end
private
# Initializes a Query instance
#
# @example
#
# JournalIssue.all(:repository => :medline, :created_on.gte => Date.today - 7)
#
# initialized a query with repository defined with name :medline,
# model JournalIssue and options { :created_on.gte => Date.today - 7 }
#
# @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.key?(:links) ? @options[:links].dup : []
@conditions = Conditions::Operation.new(:null)
@offset = @options.fetch :offset, 0
@limit = @options.fetch :limit, nil
@order = @options.fetch :order, @model.default_order(repository_name)
@unique = @options.fetch :unique, true
@add_reversed = @options.fetch :add_reversed, false
@reload = @options.fetch :reload, false
@raw = false
merge_conditions([ DataMapper::Ext::Hash.except(@options, *OPTIONS), @options[:conditions] ])
normalize_options
end
# Copying contructor, called for Query#dup
#
# @api semipublic
def initialize_copy(*)
@fields = @fields.dup
@links = @links.dup
@conditions = @conditions.dup
@order = DataMapper::Ext.try_dup(@order)
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)
options = options.to_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)
fields = fields.to_ary
model = self.model
valid_properties = model.properties
model.descendants.each do |descendant|
valid_properties += descendant.properties
end
fields.each do |field|
case field
when Symbol, String
unless valid_properties.named?(field)
raise ArgumentError, "+options[:fields]+ entry #{field.inspect} does not map to a property in #{model}"
end
when Property
unless valid_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)
links = links.to_ary
if links.empty?
raise ArgumentError, '+options[:links]+ should not be empty'
end
links.each do |link|
case link
when Symbol, String
unless @relationships.named?(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, Conditions::AbstractComparison, Hash, Array
case conditions
when Hash
conditions.each do |subject, bind_value|
case subject
when Symbol, ::String
original = subject
subject = subject.to_s
name = subject[0, subject.index('.') || subject.length]
unless @properties.named?(name) || @relationships.named?(name)
raise ArgumentError, "condition #{original.inspect} does not map to a property or relationship in #{model}"
end
when Property
unless @properties.include?(subject)
raise ArgumentError, "condition #{subject.name.inspect} does not map to a property in #{model}, but belongs to #{subject.model}"
end
when Operator
operator = subject.operator
unless Conditions::Comparison.slugs.include?(operator) || operator == :not
raise ArgumentError, "condition #{subject.inspect} used an invalid operator #{operator}"
end
assert_valid_conditions(subject.target => bind_value)
when Path
assert_valid_links(subject.relationships)
when Associations::Relationship
# TODO: validate that it belongs to the current model
#unless subject.source_model.equal?(model)
# raise ArgumentError, "condition #{subject.name.inspect} is not a valid relationship for #{model}, it's source model was #{subject.source_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
first_condition = conditions.first
unless first_condition.kind_of?(String) && !DataMapper::Ext.blank?(first_condition)
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)
offset = offset.to_int
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 the limit is equal to or greater than 0
#
# @raise [ArgumentError]
# raised if the limit is not an Integer or less than 0
#
# @api private
def assert_valid_limit(limit)
limit = limit.to_int
unless limit >= 0
raise ArgumentError, "+options[:limit]+ must be greater than or equal to 0, 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)
return if order.nil?
order = Array(order)
if order.empty? && fields && fields.any? { |property| !property.kind_of?(Operator) }
raise ArgumentError, '+options[:order]+ should not be empty if +options[:fields] contains a non-operator'
end
model = self.model
order.each do |order_entry|
case order_entry
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, Path
# Allow any arbitrary property, since it may map to a model
# that has been included via the :links option
when Operator, Direction
operator = order_entry.operator
unless operator == :asc || operator == :desc
raise ArgumentError, "+options[:order]+ entry #{order_entry.inspect} used an invalid operator #{operator}"
end
assert_valid_order([ order_entry.target ], fields)
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)
other_repository = other.repository
repository = self.repository
other_class = other.class
unless other_repository == repository
raise ArgumentError, "+other+ #{other_class} must be for the #{repository.name} repository, not #{other_repository.name}"
end
other_model = other.model
model = self.model
unless other_model >= model
raise ArgumentError, "+other+ #{other_class} must be for the #{model.name} model, not #{other_model.name}"
end
end