Merge branch '17994-filter-by-storage-classes' into main
authorTom Clegg <tom@curii.com>
Mon, 30 Aug 2021 17:27:03 +0000 (13:27 -0400)
committerTom Clegg <tom@curii.com>
Mon, 30 Aug 2021 17:27:03 +0000 (13:27 -0400)
closes #17994

Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tom@curii.com>

doc/api/methods.html.textile.liquid
services/api/lib/record_filters.rb
services/api/test/functional/arvados/v1/collections_controller_test.rb
services/api/test/functional/arvados/v1/filters_test.rb

index 670a9e0da3d96ed16f8de9e053ae5a746cf0aa31..e051ab66fa7afa18d8e52b09741c292f5e1faa9c 100644 (file)
@@ -100,12 +100,16 @@ The following operators are available.
 
 table(table table-bordered table-condensed).
 |_. Operator|_. Operand type|_. Description|_. Example|
-|@=@, @!=@|string, number, timestamp, or null|Equality comparison|@["tail_uuid","=","xyzzy-j7d0g-fffffffffffffff"]@ @["tail_uuid","!=",null]@|
+|@=@, @!=@, @<>@|string, number, timestamp, JSON-encoded array, JSON-encoded object, or null|Equality comparison|@["tail_uuid","=","xyzzy-j7d0g-fffffffffffffff"]@
+@["tail_uuid","!=",null]@
+@["storage_classes_desired","=","[\"default\"]"]@|
 |@<@, @<=@, @>=@, @>@|string, number, or timestamp|Ordering comparison|@["script_version",">","123"]@|
 |@like@, @ilike@|string|SQL pattern match.  Single character match is @_@ and wildcard is @%@. The @ilike@ operator is case-insensitive|@["script_version","like","d00220fb%"]@|
 |@in@, @not in@|array of strings|Set membership|@["script_version","in",["main","d00220fb38d4b85ca8fc28a8151702a2b9d1dec5"]]@|
 |@is_a@|string|Arvados object type|@["head_uuid","is_a","arvados#collection"]@|
-|@exists@|string|Test if a subproperty is present.|@["properties","exists","my_subproperty"]@|
+|@exists@|string|Presence of subproperty|@["properties","exists","my_subproperty"]@|
+|@contains@|string, array of strings|Presence of one or more keys or array elements|@["storage_classes_desired", "contains", ["foo", "bar"]]@ (matches both @["foo", "bar"]@ and @["foo", "bar", "baz"]@)
+(note @[..., "contains", "foo"]@ is also accepted, and is equivalent to @[..., "contains", ["foo"]]@)|
 
 h4(#substringsearchfilter). Filtering using substring search
 
@@ -128,7 +132,7 @@ table(table table-bordered table-condensed).
 |@like@, @ilike@|string|SQL pattern match, single character match is @_@ and wildcard is @%@, ilike is case-insensitive|@["properties.my_subproperty", "like", "d00220fb%"]@|
 |@in@, @not in@|array of strings|Set membership|@["properties.my_subproperty", "in", ["fizz", "buzz"]]@|
 |@exists@|boolean|Test if a subproperty is present or not (determined by operand).|@["properties.my_subproperty", "exists", true]@|
-|@contains@|string, number|Filter where subproperty has a value either by exact match or value is element of subproperty list.|@["foo", "contains", "bar"]@ will find both @{"foo": "bar"}@ and @{"foo": ["bar", "baz"]}@.|
+|@contains@|string, number|Filter where subproperty has a value either by exact match or value is element of subproperty list.|@["properties.foo", "contains", "bar"]@ will find both @{"foo": "bar"}@ and @{"foo": ["bar", "baz"]}@.|
 
 Note that exclusion filters @!=@ and @not in@ will return records for which the property is not defined at all.  To restrict filtering to records on which the subproperty is defined, combine with an @exists@ filter.
 
index f8898d63c90de2169fc8d18b53d40f68171ae945..409e48a6f090a3b348cd5d551bf35a91427e42a9 100644 (file)
@@ -47,9 +47,10 @@ module RecordFilters
         raise ArgumentError.new("Invalid operator '#{operator}' (#{operator.class}) in filter")
       end
 
+      operator = operator.downcase
       cond_out = []
 
-      if attrs_in == 'any' && (operator.casecmp('ilike').zero? || operator.casecmp('like').zero?) && (operand.is_a? String) && operand.match('^[%].*[%]$')
+      if attrs_in == 'any' && (operator == 'ilike' || operator == 'like') && (operand.is_a? String) && operand.match('^[%].*[%]$')
         # Trigram index search
         cond_out << model_class.full_text_trgm + " #{operator} ?"
         param_out << operand
@@ -85,9 +86,9 @@ module RecordFilters
           end
 
           # jsonb search
-          case operator.downcase
+          case operator
           when '=', '!='
-            not_in = if operator.downcase == "!=" then "NOT " else "" end
+            not_in = if operator == "!=" then "NOT " else "" end
             cond_out << "#{not_in}(#{attr_table_name}.#{attr} @> ?::jsonb)"
             param_out << SafeJSON.dump({proppath => operand})
           when 'in'
@@ -134,7 +135,7 @@ module RecordFilters
           else
             raise ArgumentError.new("Invalid operator for subproperty search '#{operator}'")
           end
-        elsif operator.downcase == "exists"
+        elsif operator == "exists"
           if col.type != :jsonb
             raise ArgumentError.new("Invalid attribute '#{attr}' for operator '#{operator}' in filter")
           end
@@ -142,11 +143,12 @@ module RecordFilters
           cond_out << "jsonb_exists(#{attr_table_name}.#{attr}, ?)"
           param_out << operand
         else
-          if !attr_model_class.searchable_columns(operator).index attr
+          if !attr_model_class.searchable_columns(operator).index(attr) &&
+             !(col.andand.type == :jsonb && ['contains', '=', '<>', '!='].index(operator))
             raise ArgumentError.new("Invalid attribute '#{attr}' in filter")
           end
 
-          case operator.downcase
+          case operator
           when '=', '<', '<=', '>', '>=', '!=', 'like', 'ilike'
             attr_type = attr_model_class.attribute_column(attr).type
             operator = '<>' if operator == '!='
@@ -227,6 +229,26 @@ module RecordFilters
               end
             end
             cond_out << cond.join(' OR ')
+          when 'contains'
+            if col.andand.type != :jsonb
+              raise ArgumentError.new("Invalid attribute '#{attr}' for '#{operator}' operator")
+            end
+            if operand == []
+              raise ArgumentError.new("Invalid operand '#{operand.inspect}' for '#{operator}' operator")
+            end
+            operand = [operand] unless operand.is_a? Array
+            operand.each do |op|
+              if !op.is_a?(String)
+                raise ArgumentError.new("Invalid element #{operand.inspect} in operand for #{operator.inspect} operator (operand must be a string or array of strings)")
+              end
+            end
+            # We use jsonb_exists_all(a,b) instead of "a ?& b" because
+            # the pg gem thinks "?" is a bind var. And we use string
+            # interpolation instead of param_out because the pg gem
+            # flattens param_out / doesn't support passing arrays as
+            # bind vars.
+            q = operand.map { |s| ActiveRecord::Base.connection.quote(s) }.join(',')
+            cond_out << "jsonb_exists_all(#{attr_table_name}.#{attr}, array[#{q}])"
           else
             raise ArgumentError.new("Invalid operator '#{operator}'")
           end
index 1ca2dd1dc109857e6987fdaa32caad2b04a52f8b..5b77a544e0bbf6d565e79305e572726a833e6543 100644 (file)
@@ -1455,4 +1455,18 @@ EOS
     assert_response :success
     assert_equal col.version, json_response['version'], 'Trashing a collection should not create a new version'
   end
+
+  ["storage_classes_desired", "storage_classes_confirmed"].each do |attr|
+    test "filter collections by #{attr}" do
+      authorize_with(:active)
+      get :index, params: {
+            filters: [[attr, "=", '["default"]']]
+          }
+      assert_response :success
+      assert_not_equal 0, json_response["items"].length
+      json_response["items"].each do |c|
+        assert_equal ["default"], c[attr]
+      end
+    end
+  end
 end
index bcb18078674ffd27bb124772b4478ebecfff9a76..dd8eeaa7bead1e260d46e5da4142707792edd42a 100644 (file)
@@ -247,4 +247,51 @@ class Arvados::V1::FiltersTest < ActionController::TestCase
     assert_includes(found, collections(:replication_desired_2_unconfirmed).uuid)
     assert_includes(found, collections(:replication_desired_2_confirmed_2).uuid)
   end
+
+  [
+    [1, "foo"],
+    [1, ["foo"]],
+    [1, ["bar"]],
+    [1, ["bar", "foo"]],
+    [0, ["foo", "qux"]],
+    [0, ["qux"]],
+    [nil, []],
+    [nil, [[]]],
+    [nil, [["bogus"]]],
+    [nil, [{"foo" => "bar"}]],
+    [nil, {"foo" => "bar"}],
+  ].each do |results, operand|
+    test "storage_classes_desired contains #{operand.inspect}" do
+      @controller = Arvados::V1::CollectionsController.new
+      authorize_with(:active)
+      c = Collection.create!(
+        manifest_text: "",
+        storage_classes_desired: ["foo", "bar", "baz"])
+      get :index, params: {
+            filters: [["storage_classes_desired", "contains", operand]],
+          }
+      if results.nil?
+        assert_response 422
+        next
+      end
+      assert_response :success
+      assert_equal results, json_response["items"].length
+      if results > 0
+        assert_equal c.uuid, json_response["items"][0]["uuid"]
+      end
+    end
+  end
+
+  test "collections properties contains top level key" do
+    @controller = Arvados::V1::CollectionsController.new
+    authorize_with(:active)
+    get :index, params: {
+          filters: [["properties", "contains", "prop1"]],
+        }
+    assert_response :success
+    assert_not_empty json_response["items"]
+    json_response["items"].each do |c|
+      assert c["properties"].has_key?("prop1")
+    end
+  end
 end