diff --git a/lib/couchbase-orm/relation.rb b/lib/couchbase-orm/relation.rb index 2793e6d1..4b414700 100644 --- a/lib/couchbase-orm/relation.rb +++ b/lib/couchbase-orm/relation.rb @@ -26,14 +26,27 @@ def to_n1ql "select raw meta().id from `#{bucket_name}` where #{where} order by #{order} #{limit}" end - def query - CouchbaseOrm::logger.debug("Query: #{self}") - n1ql_query = to_n1ql + def execute(n1ql_query) result = @model.cluster.query(n1ql_query, Couchbase::Options::Query.new(scan_consistency: :request_plus)) CouchbaseOrm.logger.debug { "Relation query: #{n1ql_query} return #{result.rows.to_a.length} rows" } N1qlProxy.new(result) end + def query + CouchbaseOrm::logger.debug("Query: #{self}") + n1ql_query = to_n1ql + execute(n1ql_query) + end + + def update_all(**cond) + bucket_name = @model.bucket.name + where = build_where + limit = build_limit + update = build_update(**cond) + n1ql_query = "update `#{bucket_name}` set #{update} where #{where} #{limit}" + execute(n1ql_query) + end + def ids query.to_a end @@ -151,6 +164,13 @@ def build_where @model.build_match(key, value) end.join(" AND ") end + + def build_update(**cond) + cond.map do |key,value| + "#{key} = #{@model.quote(value)}" + end.join(", ") + end + end module ClassMethods diff --git a/spec/relation_spec.rb b/spec/relation_spec.rb index 5854ead0..55a6b5c9 100644 --- a/spec/relation_spec.rb +++ b/spec/relation_spec.rb @@ -208,7 +208,6 @@ class RelationModel < CouchbaseOrm::Base end).to eq m2 end - it "should pluck several elements" do _m1 = RelationModel.create!(active: true, age: 10) _m2 = RelationModel.create!(active: true, age: 20) @@ -289,5 +288,17 @@ class RelationModel < CouchbaseOrm::Base _m4 = RelationModel.create!(age: 40) expect(RelationModel.where(age: {_lte: 30, _gt:10})).to match_array([m2, m3]) end + + it "should update_all" do + m1 = RelationModel.create!(age: 10) + m2 = RelationModel.create!(age: 20) + m3 = RelationModel.create!(age: 30) + m4 = RelationModel.create!(age: 40) + RelationModel.where(age: {_lte: 30, _gt:10}).update_all(age: 50) + expect(m1.reload.age).to eq(10) + expect(m2.reload.age).to eq(50) + expect(m3.reload.age).to eq(50) + expect(m4.reload.age).to eq(40) + end end