Closed zinzinday closed 9 years ago
@cebe transaction is possible on the client side, when we started to write Yii2, it had declared similar feature
can you point to some docs about that? I could not find any...
I do not see anything about transactions in the linked docs...
hmm, maybe I misunderstood
The list is copy from SQL layer, the question mark indicates that there was no information on whether such feature is provided by mongo or not. And as far as I know there is no such feature in mongodb. If you find it, point us to the docs and we can try implement it.
Hm, maybe only Two Phase Commits http://docs.mongodb.org/manual/tutorial/perform-two-phase-commits/ but it not easy, i think
It's very important update.
Adding some examples in case anyone else runs into issues. I got hung up while trying to add the session to the $options
parameter in the yii\mongodb\Collection
methods.
With Yi2 Mongodb Extension
$client = Yii::$app->mongodb;
$session = $client->manager->startSession();
$session->startTransaction();
try {
$client->createCommand()
->addInsert(['key' => 'value'])
->setWriteConcern(['session' => $session])
->executeBatch('COLLECTION');
// Uncomment to prevent transaction
// throw new \Exception('Force fail. Stop transaction.');
$session->commitTransaction();
} catch (\Exception $error) {
$session->abortTransaction();
print_r($error->getMessage());
}
Without Yii2 Mongodb Exension
$client = Yii::$app->mongodb->manager;
$session = $client->startSession();
$session->startTransaction();
try {
$bulk = new \MongoDB\Driver\BulkWrite;
$bulk->insert(['key' => 'value']);
$client->executeBulkWrite('DB.COLLECTION', $bulk, ['session' => $session]);
// Uncomment to prevent transaction
/// throw new \Exception('Force fail. Stop transaction.');
$session->commitTransaction();
} catch (\Exception $error) {
$session->abortTransaction();
print_r($error->getMessage());
}
$client = Yii::$app->mongodb; $session = $client->manager->startSession();
Manger is null here. Whats the issue?
If I remember correctly and depending on your environment, you may need to install ext-mongodb
to add the core API functionality, along with the MongoDB Driver. Make sure the mongodb.so
extension exists in your PHP.ini file.
Also, I believe transactions are only available with Replicas(at least with Mongo Atlas) and MongoDB 4.2.
because mongodb does not support transactions.