forked from ManageIQ/manageiq
-
Notifications
You must be signed in to change notification settings - Fork 1
/
miq_expression.rb
1593 lines (1431 loc) · 56 KB
/
miq_expression.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
class MiqExpression
# bit array of the types of nodes available/desired
MODE_NONE = 0
MODE_RUBY = 1
MODE_SQL = 2
MODE_BOTH = MODE_RUBY | MODE_SQL
include Vmdb::Logging
attr_accessor :exp, :context_type, :preprocess_options
config = YAML.load(ERB.new(File.read(Rails.root.join("config/miq_expression.yml"))).result) # rubocop:disable Security/YAMLLoad
BASE_TABLES = config[:base_tables]
INCLUDE_TABLES = config[:include_tables]
EXCLUDE_COLUMNS = config[:exclude_columns]
EXCLUDE_ID_COLUMNS = config[:exclude_id_columns]
EXCLUDE_EXCEPTIONS = config[:exclude_exceptions]
TAG_CLASSES = config[:tag_classes]
EXCLUDE_FROM_RELATS = config[:exclude_from_relats]
FORMAT_SUB_TYPES = config[:format_sub_types]
FORMAT_BYTE_SUFFIXES = FORMAT_SUB_TYPES[:bytes][:units].to_h.invert
BYTE_FORMAT_WHITELIST = Hash[FORMAT_BYTE_SUFFIXES.keys.collect(&:to_s).zip(FORMAT_BYTE_SUFFIXES.keys)]
NUM_OPERATORS = config[:num_operators].freeze
STRING_OPERATORS = config[:string_operators]
SET_OPERATORS = config[:set_operators]
REGKEY_OPERATORS = config[:regkey_operators]
BOOLEAN_OPERATORS = config[:boolean_operators]
DATE_TIME_OPERATORS = config[:date_time_operators]
DEPRECATED_OPERATORS = config[:deprecated_operators]
UNQUOTABLE_OPERATORS = (STRING_OPERATORS + DEPRECATED_OPERATORS - ['=', 'IS NULL', 'IS NOT NULL', 'IS EMPTY', 'IS NOT EMPTY']).freeze
def initialize(exp, ctype = nil)
@exp = exp
@context_type = ctype
@col_details = nil
@ruby = nil
end
def valid?(component = exp)
operator = component.keys.first
case operator.downcase
when "and", "or"
component[operator].all?(&method(:valid?))
when "not", "!"
valid?(component[operator])
when "find"
validate_set = Set.new(%w[checkall checkany checkcount search])
validate_keys = component[operator].keys.select { |k| validate_set.include?(k) }
validate_keys.all? { |k| valid?(component[operator][k]) }
else
if component[operator].key?("field")
field = Field.parse(component[operator]["field"])
return false if field && !field.valid?
end
if Field.is_field?(component[operator]["value"])
field = Field.parse(component[operator]["value"])
return false unless field && field.valid?
end
true
end
end
def set_tagged_target(model, associations = [])
each_atom(exp) do |atom|
next unless atom.key?("tag")
tag = Tag.parse(atom["tag"])
tag.model = model
tag.associations = associations
atom["tag"] = tag.to_s
end
end
def self.proto?
return @proto if defined?(@proto)
@proto = ::Settings.product.proto
end
def self.to_human(exp)
if exp.kind_of?(self)
exp.to_human
elsif exp.kind_of?(Hash)
case exp["mode"]
when "tag_expr"
exp["expr"]
when "tag"
tag = [exp["ns"], exp["tag"]].join("/")
if exp["include"] == "none"
"Not Tagged With #{tag}"
else
"Tagged With #{tag}"
end
when "script"
if exp["expr"] == "true"
"Always True"
else
exp["expr"]
end
else
new(exp).to_human
end
else
exp.inspect
end
end
def to_human
self.class._to_human(exp)
end
def self._to_human(exp, options = {})
return exp unless exp.kind_of?(Hash) || exp.kind_of?(Array)
keys = exp.keys
keys.delete(:token)
operator = keys.first
case operator.downcase
when "like", "not like", "starts with", "ends with", "includes", "includes any", "includes all", "includes only", "limited to", "regular expression", "regular expression matches", "regular expression does not match", "equal", "=", "<", ">", ">=", "<=", "!=", "before", "after"
operands = operands2humanvalue(exp[operator], options)
clause = operands.join(" #{normalize_operator(operator)} ")
when "and", "or"
clause = "( " + exp[operator].collect { |operand| _to_human(operand) }.join(" #{normalize_operator(operator)} ") + " )"
when "not", "!"
clause = normalize_operator(operator) + " ( " + _to_human(exp[operator]) + " )"
when "is null", "is not null", "is empty", "is not empty"
clause = operands2humanvalue(exp[operator], options).first + " " + operator
when "contains"
operands = operands2humanvalue(exp[operator], options)
clause = operands.join(" #{normalize_operator(operator)} ")
when "find"
# FIND Vm.users-name = 'Administrator' CHECKALL Vm.users-enabled = 1
check = nil
check = "checkall" if exp[operator].include?("checkall")
check = "checkany" if exp[operator].include?("checkany")
check = "checkcount" if exp[operator].include?("checkcount")
raise _("expression malformed, must contain one of 'checkall', 'checkany', 'checkcount'") unless check
check =~ /^check(.*)$/
mode = $1.upcase
clause = "FIND" + " " + _to_human(exp[operator]["search"]) + " CHECK " + mode + " " + _to_human(exp[operator][check], :include_table => false).strip
when "key exists"
clause = "KEY EXISTS #{exp[operator]['regkey']}"
when "value exists"
clause = "VALUE EXISTS #{exp[operator]['regkey']} : #{exp[operator]['regval']}"
when "is"
operands = operands2humanvalue(exp[operator], options)
clause = "#{operands.first} #{operator} #{operands.last}"
when "between dates", "between times"
col_name = exp[operator]["field"]
col_type = Target.parse(col_name).column_type
col_human, _value = operands2humanvalue(exp[operator], options)
vals_human = exp[operator]["value"].collect { |v| quote_human(v, col_type) }
clause = "#{col_human} #{operator} #{vals_human.first} AND #{vals_human.last}"
when "from"
col_name = exp[operator]["field"]
col_type = Target.parse(col_name).column_type
col_human, _value = operands2humanvalue(exp[operator], options)
vals_human = exp[operator]["value"].collect { |v| quote_human(v, col_type) }
clause = "#{col_human} #{operator} #{vals_human.first} THROUGH #{vals_human.last}"
end
# puts "clause: #{clause}"
clause
end
# @param timezone [String] (default: "UTC")
# @param prune_sql [boolean] (default: false) remove expressions that are sql friendly
#
# when prune_sql is true, then the sql friendly expression was used to filter the
# records already. no reason to do that again in ruby
def to_ruby(timezone = nil, prune_sql: false)
timezone ||= "UTC".freeze
cached_args = prune_sql ? "#{timezone}P" : timezone
# clear out the cache if the args changed
if @chached_args != cached_args
@ruby = nil
@chached_args = cached_args
end
if @ruby == true
nil
elsif @ruby
@ruby.dup
elsif valid?
pexp = preprocess_exp!(exp.deep_clone)
pexp, _ = prune_exp(pexp, MODE_RUBY) if prune_sql
@ruby = self.class._to_ruby(pexp, context_type, timezone) || true
@ruby == true ? nil : @ruby.dup
else
""
end
end
def self._to_ruby(exp, context_type, tz)
return exp unless exp.kind_of?(Hash)
operator = exp.keys.first
op_args = exp[operator]
col_name = op_args["field"] if op_args.kind_of?(Hash)
operator = operator.downcase
case operator
when "equal", "=", "<", ">", ">=", "<=", "!="
operands = operands2rubyvalue(operator, op_args, context_type)
clause = operands.join(" #{normalize_ruby_operator(operator)} ")
when "before"
col_type = Target.parse(col_name).column_type if col_name
col_ruby, _value = operands2rubyvalue(operator, {"field" => col_name}, context_type)
val = op_args["value"]
clause = ruby_for_date_compare(col_ruby, col_type, tz, "<", val)
when "after"
col_type = Target.parse(col_name).column_type if col_name
col_ruby, _value = operands2rubyvalue(operator, {"field" => col_name}, context_type)
val = op_args["value"]
clause = ruby_for_date_compare(col_ruby, col_type, tz, nil, nil, ">", val)
when "includes all"
operands = operands2rubyvalue(operator, op_args, context_type)
clause = "(#{operands[0]} & #{operands[1]}) == #{operands[1]}"
when "includes any"
operands = operands2rubyvalue(operator, op_args, context_type)
clause = "(#{operands[1]} - #{operands[0]}) != #{operands[1]}"
when "includes only", "limited to"
operands = operands2rubyvalue(operator, op_args, context_type)
clause = "(#{operands[0]} - #{operands[1]}) == []"
when "like", "not like", "starts with", "ends with", "includes"
operands = operands2rubyvalue(operator, op_args, context_type)
operands[1] =
case operator
when "starts with"
"/^" + re_escape(operands[1].to_s) + "/"
when "ends with"
"/" + re_escape(operands[1].to_s) + "$/"
else
"/" + re_escape(operands[1].to_s) + "/"
end
clause = operands.join(" #{normalize_ruby_operator(operator)} ")
clause = "!(" + clause + ")" if operator == "not like"
when "regular expression matches", "regular expression does not match"
operands = operands2rubyvalue(operator, op_args, context_type)
# If it looks like a regular expression, sanitize from forward
# slashes and interpolation
#
# Regular expressions with a single option are also supported,
# e.g. "/abc/i"
#
# Otherwise sanitize the whole string and add the delimiters
#
# TODO: support regexes with more than one option
if operands[1].starts_with?("/") && operands[1].ends_with?("/")
operands[1][1..-2] = sanitize_regular_expression(operands[1][1..-2])
elsif operands[1].starts_with?("/") && operands[1][-2] == "/"
operands[1][1..-3] = sanitize_regular_expression(operands[1][1..-3])
else
operands[1] = "/" + sanitize_regular_expression(operands[1].to_s) + "/"
end
clause = operands.join(" #{normalize_ruby_operator(operator)} ")
when "and", "or"
clause = "(" + op_args.collect { |operand| _to_ruby(operand, context_type, tz) }.join(" #{normalize_ruby_operator(operator)} ") + ")"
when "not", "!"
clause = normalize_ruby_operator(operator) + "(" + _to_ruby(op_args, context_type, tz) + ")"
when "is null", "is not null", "is empty", "is not empty"
operands = operands2rubyvalue(operator, op_args, context_type)
clause = operands.join(" #{normalize_ruby_operator(operator)} ")
when "contains"
op_args["tag"] ||= col_name
operands = if context_type != "hash"
target = Target.parse(op_args["tag"])
["<exist ref=#{target.model.to_s.downcase}>#{target.tag_path_with(op_args["value"])}</exist>"]
elsif context_type == "hash"
# This is only for supporting reporting "display filters"
# In the report object the tag value is actually the description and not the raw tag name.
# So we have to trick it by replacing the value with the description.
description = MiqExpression.get_entry_details(op_args["tag"]).inject("") do |s, t|
break(t.first) if t.last == op_args["value"]
s
end
val = op_args["tag"].split(".").last.split("-").join(".")
fld = "<value type=string>#{val}</value>"
[fld, quote(description, :string)]
end
clause = operands.join(" #{normalize_operator(operator)} ")
when "find"
# FIND Vm.users-name = 'Administrator' CHECKALL Vm.users-enabled = 1
check = nil
check = "checkall" if op_args.include?("checkall")
check = "checkany" if op_args.include?("checkany")
if op_args.include?("checkcount")
check = "checkcount"
op = op_args[check].keys.first
op_args[check][op]["field"] = "<count>"
end
raise _("expression malformed, must contain one of 'checkall', 'checkany', 'checkcount'") unless check
check =~ /^check(.*)$/
mode = $1.downcase
clause = "<find><search>" + _to_ruby(op_args["search"], context_type, tz) + "</search>" \
"<check mode=#{mode}>" + _to_ruby(op_args[check], context_type, tz) + "</check></find>"
when "key exists"
clause, = operands2rubyvalue(operator, op_args, context_type)
when "value exists"
clause, = operands2rubyvalue(operator, op_args, context_type)
when "is"
col_ruby, _value = operands2rubyvalue(operator, {"field" => col_name}, context_type)
col_type = Target.parse(col_name).column_type
value = op_args["value"]
clause = if col_type == :date && !RelativeDatetime.relative?(value)
ruby_for_date_compare(col_ruby, col_type, tz, "==", value)
else
ruby_for_date_compare(col_ruby, col_type, tz, ">=", value, "<=", value)
end
when "from"
col_ruby, _value = operands2rubyvalue(operator, {"field" => col_name}, context_type)
col_type = Target.parse(col_name).column_type
start_val, end_val = op_args["value"]
clause = ruby_for_date_compare(col_ruby, col_type, tz, ">=", start_val, "<=", end_val)
else
raise _("operator '%{operator_name}' is not supported") % {:operator_name => operator.upcase}
end
# puts "clause: #{clause}"
clause
end
def to_sql(tz = nil)
tz ||= "UTC"
pexp = preprocess_exp!(exp.deep_clone)
pexp, seen = prune_exp(pexp, MODE_SQL)
attrs = {:supported_by_sql => (seen == MODE_SQL)}
sql = to_arel(pexp, tz).to_sql if pexp.present?
incl = includes_for_sql if sql.present?
[sql, incl, attrs]
end
def preprocess_exp!(exp)
exp.delete(:token)
operator = exp.keys.first
operator_values = exp[operator]
case operator.downcase
when "and", "or"
operator_values.each { |atom| preprocess_exp!(atom) }
when "not", "!"
preprocess_exp!(operator_values)
exp
else # field
convert_size_in_units_to_integer(exp) if %w[= != <= >= > <].include?(operator)
end
exp
end
# @param operator [String] operator (i.e.: AND, OR, NOT)
# @param children [Array[Hash]] array of child nodes
# @param unary [boolean] true if we are dealing with a unary operator (i.e.: not)
# unary:true (i.e.: NOT), don't collapse single child nodes
# unary:false (i.e.: AND, OR), drop binary operators with a single node
def operator_hash(operator, children, unary: false)
case children&.size
when nil, 0
nil
when 1
unary ? {operator => children} : children.first
else
{operator => children}
end
end
# prune child nodes (OR, NOT, AND) using prune_exp
# This method simplifies the aggregate of the modes seen in the children
#
# @param children [Array<Hash>] child nodes
# @param mode [MODE_SQL|MODE_RUBY] which nodes we want to keep
#
# @return
# [Array] children that can be used in the given mode
# [MODE_SQL|MODE_RUBY|MODE_BOTH]: mode summary for the children
#
# filtered_children:
#
# children | mode=sql | mode=ruby |
# -------------|------------|--------------|
# sql1, sql2 | sql1, sql2 | |
# sql1, ruby1 | sql1 | ruby1 |
# ruby1, ruby2 | | ruby1, ruby1 |
#
def prune_exp_children(children, mode, swap:)
seen = MODE_NONE
filtered_children = []
children.each do |child|
child_exp, child_seen = prune_exp(child, mode, :swap => swap)
seen |= child_seen
filtered_children << child_exp if child_exp
end
[filtered_children, seen]
end
private :prune_exp_children
# Cut up an expression into 2 expressions that can be applied sequentially:
# orig_exp == (exp mode sql) AND (exp mode=ruby)
#
# the sql expression is applied in the db
#
# @param exp [Hash] ast for miq_expression
# @param mode [MODE_RUBY|MODE_SQL] whether we are pruning for a sql or ruby generation
# @param swap [boolean] true if we are in a NOT clause and applying Demorgan's law
#
# @returns [Hash, mode]
# Hash: expression that works for the given mode
# [MODE_SQL|MODE_RUBY|MODE_BOTH]: mode summary for the children
#
# NOTE on Compound nodes:
#
# exp |==>| output (mode=sql) |and| output (mode=ruby)
# ----------------|---|-------------------|---|-----------------
# sql1 AND sql2 |==>| sql1 AND sql2 |AND|
# sql1 AND ruby1 |==>| sql1 |AND| ruby1
# ruby1 AND ruby2 |==>| |AND| ruby1 AND ruby2
#
# The AND case uses all nodes that match the input mode
#
# exp |==>| output (mode=sql) |and| output (mode=ruby)
# ---------------|---|-------------------|---|-----------------
# sql1 OR sql2 |==>| sql1 OR sql2 |AND|
# sql1 OR ruby1 |==>| |AND| sql1 OR ruby1
# ruby1 OR ruby2 |==>| |AND| ruby1 OR ruby2
#
# The OR case uses all nodes that match the input mode with one exception:
# mixed mode expressions are completely applied in ruby to keep the same logical result.
#
#
# exp |==>| exp (mode=sql) |and| exp (mode=ruby)
# -------------------|---|----------------|---|-----------------
# !(sql OR sql) |==>| !(sql OR sql) |AND|
# !(sql OR ruby) |==>| !(sql) |AND| !(ruby)
# !(ruby1 OR ruby2) |==>| |AND| !(ruby1 OR ruby2)
#
# exp |==>| exp (mode=sql) |and| exp (mode=ruby)
# -------------------|---|----------------|---|-----------------
# !(sql AND sql) |==>| !(sql AND sql) |AND|
# !(sql AND ruby) |==>| |AND| !(sql AND ruby)
# !(ruby1 AND ruby2) |==>| |AND| !(ruby1 AND ruby2)
#
# Inside a NOT, the OR acts like the AND, and the AND acts like the OR
# so follow the AND logic if we are not swapping (and vice versa)
#
def prune_exp(exp, mode, swap: false)
operator = exp.keys.first
down_operator = operator.downcase
case down_operator
when "and", "or"
children, seen = prune_exp_children(exp[operator], mode, :swap => swap)
if (down_operator == "and") != swap || seen != MODE_BOTH
[operator_hash(operator, children), seen]
else
[mode == MODE_RUBY ? exp : nil, seen]
end
when "not", "!"
children, seen = prune_exp(exp[operator], mode, :swap => !swap)
[operator_hash(operator, children, :unary => true), seen]
else
if sql_supports_atom?(exp)
[mode == MODE_SQL ? exp : nil, MODE_SQL]
else
[mode == MODE_RUBY ? exp : nil, MODE_RUBY]
end
end
end
def sql_supports_atom?(exp)
operator = exp.keys.first
case operator.downcase
when "contains"
if exp[operator].key?("tag")
Tag.parse(exp[operator]["tag"]).reflection_supported_by_sql?
elsif exp[operator].key?("field")
Field.parse(exp[operator]["field"]).attribute_supported_by_sql?
else
false
end
when "includes"
# Support includes operator using "LIKE" only if first operand is in main table
if exp[operator].key?("field") && (!exp[operator]["field"].include?(".") || (exp[operator]["field"].include?(".") && exp[operator]["field"].split(".").length == 2))
field_in_sql?(exp[operator]["field"])
else
# TODO: Support includes operator for sub-sub-tables
false
end
when "includes any", "includes all", "includes only"
# Support this only from the main model (for now)
if exp[operator].keys.include?("field") && exp[operator]["field"].split(".").length == 1
model, field = exp[operator]["field"].split("-")
method = "miq_expression_#{operator.downcase.tr(' ', '_')}_#{field}_arel"
model.constantize.respond_to?(method)
else
false
end
when "find", "regular expression matches", "regular expression does not match", "key exists", "value exists"
false
else
# => false if operand is a tag
return false if exp[operator].keys.include?("tag")
# => false if operand is a registry
return false if exp[operator].keys.include?("regkey")
# => TODO: support count of child relationship
return false if exp[operator].key?("count")
field_in_sql?(exp[operator]["field"]) && value_in_sql?(exp[operator]["value"])
end
end
def value_in_sql?(value)
!Field.is_field?(value) || Field.parse(value).attribute_supported_by_sql?
end
def field_in_sql?(field)
return false unless attribute_supported_by_sql?(field)
# => false if excluded by special case defined in preprocess options
return false if field_excluded_by_preprocess_options?(field)
true
end
def attribute_supported_by_sql?(field)
return false unless col_details[field]
col_details[field][:sql_support]
end
# private attribute_supported_by_sql? -- tests only
def field_excluded_by_preprocess_options?(field)
col_details[field][:excluded_by_preprocess_options]
end
private :field_excluded_by_preprocess_options?
def col_details
@col_details ||= self.class.get_cols_from_expression(exp, preprocess_options)
end
private :col_details
def includes_for_sql
col_details.values.each_with_object({}) { |v, result| result.deep_merge!(v[:include]) }
end
def self.get_cols_from_expression(exp, options = {})
result = {}
if exp.kind_of?(Hash)
if exp.key?("field")
result[exp["field"]] = get_col_info(exp["field"], options) unless exp["field"] == "<count>"
elsif exp.key?("count")
result[exp["count"]] = get_col_info(exp["count"], options)
elsif exp.key?("tag")
# ignore
else
exp.each_value { |v| result.merge!(get_cols_from_expression(v, options)) }
end
elsif exp.kind_of?(Array)
exp.each { |v| result.merge!(get_cols_from_expression(v, options)) }
end
result
end
def self.get_col_info(field, options = {})
f = Target.parse(field)
{
:include => f.includes,
:data_type => f.column_type,
:format_sub_type => f.sub_type,
:sql_support => f.attribute_supported_by_sql?,
:excluded_by_preprocess_options => f.exclude_col_by_preprocess_options?(options),
:tag => f.tag?
}
end
def lenient_evaluate(obj, timezone = nil, prune_sql: false)
ruby_exp = to_ruby(timezone, :prune_sql => prune_sql)
ruby_exp.nil? || Condition.subst_matches?(ruby_exp, obj)
end
def evaluate(obj, tz = nil)
ruby_exp = to_ruby(tz)
Condition.subst_matches?(ruby_exp, obj)
end
def self.evaluate_atoms(exp, obj)
exp = copy_hash(exp.exp) if exp.kind_of?(self)
exp["result"] = new(exp).evaluate(obj)
operators = exp.keys
operators.each do |k|
if %w[and or].include?(k.to_s.downcase) # and/or atom is an array of atoms
exp[k].each do |atom|
evaluate_atoms(atom, obj)
end
elsif %w[not !].include?(k.to_s.downcase) # not atom is a hash expression
evaluate_atoms(exp[k], obj)
else
next
end
end
exp
end
def self.operands2humanvalue(ops, options = {})
# puts "Enter: operands2humanvalue: ops: #{ops.inspect}"
ret = []
if ops["tag"]
v = nil
ret.push(ops["alias"] || value2human(ops["tag"], options))
MiqExpression.get_entry_details(ops["tag"]).each do |t|
v = "'" + t.first + "'" if t.last == ops["value"]
end
if ops["value"] == :user_input
v = "<user input>"
else
v ||= ops["value"].kind_of?(String) ? "'" + ops["value"] + "'" : ops["value"]
end
ret.push(v)
elsif ops["field"]
ops["value"] ||= ''
if ops["field"] == "<count>"
ret.push(nil)
ret.push(ops["value"])
else
ret.push(ops["alias"] || value2human(ops["field"], options))
if ops["value"] == :user_input
ret.push("<user input>")
else
col_type = Target.parse(ops["field"]).column_type
ret.push(quote_human(ops["value"], col_type))
end
end
elsif ops["count"]
ret.push("COUNT OF " + (ops["alias"] || value2human(ops["count"], options)).strip)
if ops["value"] == :user_input
ret.push("<user input>")
else
ret.push(ops["value"])
end
elsif ops["regkey"]
ops["value"] ||= ''
ret.push(ops["regkey"] + " : " + ops["regval"])
ret.push(ops["value"].kind_of?(String) ? "'" + ops["value"] + "'" : ops["value"])
elsif ops["value"]
ret.push(nil)
ret.push(ops["value"])
end
ret
end
def self.value2human(val, options = {})
options = {
:include_model => true,
:include_table => true
}.merge(options)
tables, col = val.split("-")
first = true
val_is_a_tag = false
ret = ""
if options[:include_table] == true
friendly = tables.split(".").collect do |t|
if t.downcase == "managed"
val_is_a_tag = true
"#{Tenant.root_tenant.name} Tags"
elsif t.downcase == "user_tag"
"My Tags"
elsif first
first = nil
next unless options[:include_model] == true
Dictionary.gettext(t, :type => :model, :notfound => :titleize)
else
Dictionary.gettext(t, :type => :table, :notfound => :titleize)
end
end.compact
ret = friendly.join(".")
ret << " : " unless ret.blank? || col.blank?
end
if val_is_a_tag
if col
classification = options[:classification] || Classification.lookup_by_name(col)
ret << (classification ? classification.description : col)
end
else
model = tables.blank? ? nil : tables.split(".").last.singularize.camelize
dict_col = model.nil? ? col : [model, col].join(".")
column_human = if col
if col.starts_with?(CustomAttributeMixin::CUSTOM_ATTRIBUTES_PREFIX)
CustomAttributeMixin.to_human(col)
else
Dictionary.gettext(dict_col, :type => :column, :notfound => :titleize)
end
end
ret << column_human if col
end
ret = " #{ret}" unless ret.include?(":")
ret
end
def self.quote_by(operator, value, column_type = nil)
if UNQUOTABLE_OPERATORS.map(&:downcase).include?(operator)
value
else
quote(value, column_type)
end
end
def self.operands2rubyvalue(operator, ops, context_type)
if ops["field"]
if ops["field"] == "<count>"
["<count>", quote(ops["value"], :integer)]
else
target = Target.parse(ops["field"])
col_type = target.column_type || :string
[if context_type == "hash"
"<value type=#{col_type}>#{ops["field"].split(".").last.split("-").join(".")}</value>"
else
"<value ref=#{target.model.to_s.downcase}, type=#{col_type}>#{target.tag_path_with}</value>"
end, quote_by(operator, ops["value"], col_type)]
end
elsif ops["count"]
target = Target.parse(ops["count"])
["<count ref=#{target.model.to_s.downcase}>#{target.tag_path_with}</count>", quote(ops["value"], target.column_type)]
elsif ops["regkey"]
if operator == "key exists"
["<registry key_exists=1, type=boolean>#{ops["regkey"].strip}</registry> == 'true'", nil]
elsif operator == "value exists"
["<registry value_exists=1, type=boolean>#{ops["regkey"].strip} : #{ops["regval"]}</registry> == 'true'", nil]
else
["<registry>#{ops["regkey"].strip} : #{ops["regval"]}</registry>", quote_by(operator, ops["value"], :string)]
end
end
end
def self.quote(val, typ)
if Field.is_field?(val)
target = Target.parse(val)
value = target.tag_path_with
col_type = target.column_type || :string
reference_attribute = target ? "ref=#{target.model.to_s.downcase}, " : " "
return "<value #{reference_attribute}type=#{col_type}>#{value}</value>"
end
case typ&.to_sym
when :string, :text, :boolean, nil
# escape any embedded single quotes, etc. - needs to be able to handle even values with trailing backslash
val.to_s.inspect
when :date
return "nil" if val.blank? # treat nil value as empty string
"Date.new(#{val.year},#{val.month},#{val.day})"
when :datetime
return "nil" if val.blank? # treat nil value as empty string
val = val.utc
"Time.utc(#{val.year},#{val.month},#{val.day},#{val.hour},#{val.min},#{val.sec})"
when :integer, :decimal, :fixnum
val.to_s.to_i_with_method
when :float
val.to_s.to_f_with_method
when :numeric_set
val = val.split(",") if val.kind_of?(String)
v_arr = Array.wrap(val).flat_map { |v| quote_numeric_set_atom(v) }.compact.uniq.sort
"[#{v_arr.join(",")}]"
when :string_set
val = val.split(",") if val.kind_of?(String)
v_arr = Array.wrap(val).flat_map { |v| "'#{v.to_s.strip}'" }.uniq.sort
"[#{v_arr.join(",")}]"
else
val
end
end
private_class_method def self.quote_numeric_set_atom(val)
val = val.to_s unless val.kind_of?(Numeric) || val.kind_of?(Range)
if val.kind_of?(String)
val = val.strip
val =
if val.include?("..") # Parse Ranges
b, e = val.split("..", 2).map do |i|
if integer?(i)
i.to_i_with_method
elsif numeric?(i)
i.to_f_with_method
end
end
Range.new(b, e) if b && e
elsif integer?(val) # Parse Integers
val.to_i_with_method
elsif numeric?(val) # Parse Floats
val.to_f_with_method
end
end
val.kind_of?(Range) ? val.to_a : val
end
def self.quote_human(val, typ)
case typ&.to_sym
when :integer, :decimal, :fixnum, :float
return val.to_i unless val.to_s.number_with_method? || typ == :float
if val =~ /^([0-9.,]+)\.([a-z]+)$/
val, sfx = $1, $2
if sfx.ends_with?("bytes") && FORMAT_BYTE_SUFFIXES.key?(sfx.to_sym)
"#{val} #{FORMAT_BYTE_SUFFIXES[sfx.to_sym]}"
else
"#{val} #{sfx.titleize}"
end
else
val
end
when :string, :date, :datetime, nil
"\"#{val}\""
else
quote(val, typ)
end
end
# TODO: update this to use the more nuanced
# .sanitize_regular_expression after performing Regexp.escape. The
# extra substitution is required because, although the result from
# Regexp.escape is fine to pass to Regexp.new, it is not when eval'd
# as we do:
#
# ```ruby
# regexp_string = Regexp.escape("/") # => "/"
# # ...
# eval("/" + regexp_string + "/")
# ```
def self.re_escape(s)
Regexp.escape(s).gsub("/", '\/')
end
# Escape any unescaped forward slashes and/or interpolation
def self.sanitize_regular_expression(string)
string.gsub(%r{\\*/}, "\\/").gsub(/\\*#/, "\\#")
end
def self.escape_virtual_custom_attribute(attribute)
if attribute.include?(CustomAttributeMixin::CUSTOM_ATTRIBUTES_PREFIX)
uri_parser = URI::RFC2396_Parser.new
[uri_parser.escape(attribute, /[^A-Za-z0-9:\-_]/), true]
else
[attribute, false]
end
end
def self.normalize_ruby_operator(str)
case str
when "equal", "="
"=="
when "not"
"!"
when "like", "not like", "starts with", "ends with", "includes", "regular expression matches"
"=~"
when "regular expression does not match"
"!~"
when "is null", "is empty"
"=="
when "is not null", "is not empty"
"!="
when "before"
"<"
when "after"
">"
else
str
end
end
def self.normalize_operator(str)
str = str.upcase
case str
when "EQUAL"
"="
when "!"
"NOT"
when "EXIST"
"CONTAINS"
else
str
end
end
def self.base_tables
BASE_TABLES
end
def self.model_details(model, opts = {:typ => "all", :include_model => true, :include_tags => false, :include_my_tags => false, :include_id_columns => false})
@classifications = nil
model = model.to_s
opts = {:typ => "all", :include_model => true}.merge(opts)
if opts[:typ] == "tag"
tags_for_model = if TAG_CLASSES.include?(model)
tag_details(model, opts)
else
[]
end
result = []
TAG_CLASSES.invert.each do |name, tc|
next if tc.constantize.base_class == model.constantize.base_class
path = [model, name].join(".")
result.concat(tag_details(path, opts))
end
@classifications = nil
return tags_for_model.concat(result.sort_by!(&:to_s))
end
relats = get_relats(model)
result = []
unless opts[:typ] == "count" || opts[:typ] == "find"
@column_cache ||= {}
key = "#{model}_#{opts[:interval]}_#{opts[:include_model] || false}"
@column_cache[key] = nil if model == "ChargebackVm"
@column_cache[key] ||= get_column_details(relats[:columns], model, model, opts).sort_by!(&:to_s)
result.concat(@column_cache[key])
unless opts[:disallow_loading_virtual_custom_attributes]
custom_details = _custom_details_for(model, opts)
result.concat(custom_details.sort_by(&:to_s)) unless custom_details.empty?
end
result.concat(tag_details(model, opts)) if opts[:include_tags] == true && TAG_CLASSES.include?(model)
end
model_details = _model_details(relats, opts)
model_details.sort_by!(&:to_s)
result.concat(model_details)
@classifications = nil
result
end
def self._custom_details_for(model, options)
klass = model.safe_constantize
return [] unless klass < CustomAttributeMixin
custom_attributes_details = []
klass.custom_keys.each do |custom_key|
custom_detail_column = [options[:model_for_column] || model, CustomAttributeMixin.column_name(custom_key)].join("-")
custom_detail_name = CustomAttributeMixin.to_human(custom_key)
if options[:include_model]
model_name = Dictionary.gettext(model, :type => :model, :notfound => :titleize)
custom_detail_name = [model_name, custom_detail_name].join(" : ")
end
custom_attributes_details.push([custom_detail_name, custom_detail_column])
end
custom_attributes_details
end
def self._model_details(relats, opts)
result = []
relats[:reflections].each do |_assoc, ref|
parent = ref[:parent]
case opts[:typ]
when "count"
result.push(get_table_details(parent[:class_path], parent[:assoc_path])) if parent[:multivalue]
when "find"
result.concat(get_column_details(ref[:columns], parent[:class_path], parent[:assoc_path], opts)) if parent[:multivalue]
else
result.concat(get_column_details(ref[:columns], parent[:class_path], parent[:assoc_path], opts))
if opts[:include_tags] == true && TAG_CLASSES.include?(parent[:assoc_class])
result.concat(tag_details(parent[:class_path], opts))
end
end
result.concat(_model_details(ref, opts))
end
result
end
def self.tag_details(path, opts)
result = []
if opts[:no_cache]
@classifications = nil
end
@classifications ||= categories
@classifications.each do |name, cat|
prefix = path.nil? ? "managed" : [path, "managed"].join(".")
field = [prefix, name].join("-")
result.push([value2human(field, opts.merge(:classification => cat)), field])
end
if opts[:include_my_tags] && opts[:userid] && ::Tag.exists?(["name like ?", "/user/#{opts[:userid]}/%"])
prefix = path.nil? ? "user_tag" : [path, "user_tag"].join(".")
field = [prefix, opts[:userid]].join("_")
result.push([value2human(field, opts), field])
end