Skip to content

Commit

Permalink
Added bulk insert, update and delete
Browse files Browse the repository at this point in the history
  • Loading branch information
Gabriel Naiman committed Sep 26, 2016
1 parent 64435b4 commit 937565b
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
12 changes: 12 additions & 0 deletions lib/rasti/db/collection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ def insert(attributes)
end
end

def bulk_insert(attributes, options={})
dataset.multi_insert attributes, options
end

def update(primary_key, attributes)
db.transaction do
collection_attributes, relations_primary_keys = split_related_attributes attributes
Expand All @@ -81,10 +85,18 @@ def update(primary_key, attributes)
end
end

def bulk_update(attributes, &block)
build_query(&block).instance_eval { dataset.update attributes }
end

def delete(primary_key)
dataset.where(self.class.primary_key => primary_key).delete
end

def bulk_delete(&block)
build_query(&block).instance_eval { dataset.delete }
end

def find(primary_key)
query { |q| q.where(self.class.primary_key => primary_key).first }
end
Expand Down
29 changes: 26 additions & 3 deletions spec/collection_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,15 @@
db[:categories_posts].where(category_id: category_id).map(:post_id).must_equal [1,2]
end

it 'Insert batch'
it 'Bulk insert' do
users_attrs = 1.upto(2).map { |i| {name: "User #{i}"} }

ids = users.bulk_insert users_attrs, return: :primary_key

ids.must_equal [1,2]
db[:users][id: 1][:name].must_equal 'User 1'
db[:users][id: 2][:name].must_equal 'User 2'
end

it 'Update' do
id = db[:users].insert name: 'User 1'
Expand Down Expand Up @@ -87,7 +95,16 @@
db[:categories_posts].where(category_id: 2).map(:post_id).must_equal [2,3]
end

it 'Update batch'
it 'Bulk update' do
user_id = db[:users].insert name: 'User 1'
1.upto(3) { |i| db[:posts].insert user_id: user_id, title: "Post #{i}", body: '...' }

posts.bulk_update(body: 'Updated ...') { where id: [1,2] }

db[:posts][id: 1][:body].must_equal 'Updated ...'
db[:posts][id: 2][:body].must_equal 'Updated ...'
db[:posts][id: 3][:body].must_equal '...'
end

it 'Delete' do
id = db[:users].insert name: 'User 1'
Expand All @@ -99,7 +116,13 @@
db[:users].count.must_equal 0
end

it 'Delete batch'
it 'Bulk delete' do
1.upto(3) { |i| db[:users].insert name: "User #{i}" }

users.bulk_delete { where id: [1,2] }

db[:users].map(:id).must_equal [3]
end

end

Expand Down

0 comments on commit 937565b

Please sign in to comment.