Search code examples
phptransactionsneo4jneo4jphp

How to handle transactions in neo4jphp?


For relational databases like mysql, transaction handling in PHP is just like.

Begin transaction
...
Insert queries
...
Update queries
...
if error in any query then
Rollback transaction
...
at end, if no error in any query then
Commit transaction

How to handle transactions in ?

I have tried same like but there was failure. Even after rollback changes were saved.

I was doing like this.

//$client = Neo4jClient
$transaction = $client->beginTransaction();
...
//Insert queries
...
//Update queries
...
//if error in any query then
$transaction->rollback();
...
// at end, if no error in any query then
$transaction->commit();

Solution

  • Check following code.

    //$client = Neo4jClient
    $transaction = $client->beginTransaction();
    
    $dataCypherQuery = new Query($client, $dataQuery, $params);
    

    Instead of getting resultset from query, we need to add statement into transaction.

    // $dataResult = $dataCypherQuery->getResultSet(); // don't do this for transaction
    

    Important : Pass query object to transaction's add statements method.

    $dataResult = $transaction->addStatements($dataCypherQuery);
    

    We can pass true as parameter indicating transaction commit.

    //$dataResult = $transaction->addStatements($dataCypherQuery, true);
    

    If there is an error, changes are automatically rolled back. You can check $dataResult variable for validity, result should be returning something.

    if (0 == $dataResult->count()) {
        $transaction->rollback();
    }
    

    At end, if no error in any query then

    $transaction->commit();
    

    For more info see Cypher-Transactions