Skip to content

Commit

Permalink
Optionally disable transaction when rebuilding documents
Browse files Browse the repository at this point in the history
  • Loading branch information
Travis Hunter authored and nertzy committed Dec 13, 2021
1 parent e890b7f commit 849e667
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,13 @@ like so:
PgSearch::Multisearch.rebuild(Product, clean_up: false)
```

```rebuild``` runs inside a single transaction. To run outside of a transaction,
you can pass ```transactional: false``` like so:

```ruby
PgSearch::Multisearch.rebuild(Product, transactional: false)
```

Rebuild is also available as a Rake task, for convenience.

$ rake pg_search:multisearch:rebuild[BlogPost]
Expand Down
16 changes: 12 additions & 4 deletions lib/pg_search/multisearch.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
module PgSearch
module Multisearch
class << self
def rebuild(model, deprecated_clean_up = nil, clean_up: true)
def rebuild(model, deprecated_clean_up = nil, clean_up: true, transactional: true)
unless deprecated_clean_up.nil?
ActiveSupport::Deprecation.warn(
"pg_search 3.0 will no longer accept a boolean second argument to PgSearchMultisearch.rebuild, " \
Expand All @@ -14,11 +14,19 @@ def rebuild(model, deprecated_clean_up = nil, clean_up: true)
clean_up = deprecated_clean_up
end

model.transaction do
PgSearch::Document.where(searchable_type: model.base_class.name).delete_all if clean_up
Rebuilder.new(model).rebuild
if transactional
model.transaction { execute(model, clean_up) }
else
execute(model, clean_up)
end
end

private

def execute(model, clean_up)
PgSearch::Document.where(searchable_type: model.base_class.name).delete_all if clean_up
Rebuilder.new(model).rebuild
end
end

class ModelNotMultisearchable < StandardError
Expand Down
9 changes: 9 additions & 0 deletions spec/lib/pg_search/multisearch_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@
expect(model).to have_received(:transaction).once
end

context "when transactional is false" do
it "does not operate inside a transaction" do
allow(model).to receive(:transaction)

described_class.rebuild(model, transactional: false)
expect(model).not_to have_received(:transaction)
end
end

describe "cleaning up search documents for this model" do
before do
connection.execute <<~SQL.squish
Expand Down

0 comments on commit 849e667

Please sign in to comment.