Skip to content

Commit

Permalink
Add update_all method
Browse files Browse the repository at this point in the history
  • Loading branch information
simkim committed Nov 3, 2022
1 parent 8c7d3af commit 099df50
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
26 changes: 23 additions & 3 deletions lib/couchbase-orm/relation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
13 changes: 12 additions & 1 deletion spec/relation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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

0 comments on commit 099df50

Please sign in to comment.