|
| 1 | +require "mongoid/threaded" |
| 2 | +require "mongoid/errors/transactions_not_supported" |
| 3 | + |
| 4 | +# This method raises an error if the cluster the client is connected to |
| 5 | +# does not support transactions in any case. At the moment this is the case |
| 6 | +# of the standalone topology. |
| 7 | +# |
| 8 | +# Please note that if this method did not raise, it does not guarantee that |
| 9 | +# transactions are available for the cluster. |
| 10 | +# |
| 11 | +# @param [ Mongo::Client ] client Client connected to a cluster to be tested. |
| 12 | +# |
| 13 | +# @raise [ Mongoid::Errors::TransactionsNotSupported ] If the cluster |
| 14 | +# definitely does not support transactions. |
| 15 | +def check_if_transactions_might_be_available!(client) |
| 16 | + if client.cluster.single? |
| 17 | + raise Mongoid::Errors::TransactionsNotSupported |
| 18 | + end |
| 19 | +end |
| 20 | + |
| 21 | +# Starts a transaction that should include all the operations inside |
| 22 | +# the sandboxed console session. This transaction should not be ever committed. |
| 23 | +# When a user end the console session, the client will disconnect, and |
| 24 | +# the transaction will be automatically aborted therefore. |
| 25 | +# |
| 26 | +# @param [ Mongo::Client ] client Client to start the transaction. |
| 27 | +def start_sandbox_transaction(client) |
| 28 | + session = client.start_session |
| 29 | + ::Mongoid::Threaded.set_session(session, client: client) |
| 30 | + session.start_transaction |
| 31 | +end |
| 32 | + |
| 33 | +# Prepares console sandbox mode. This method should be called when |
| 34 | +# a user starts rails console with '--sandbox' flag. |
| 35 | +def start_sandbox |
| 36 | + Mongoid.persistence_context.client.tap do |client| |
| 37 | + check_if_transactions_might_be_available!(client) |
| 38 | + start_sandbox_transaction(client) |
| 39 | + end |
| 40 | +end |
| 41 | + |
0 commit comments