Skip to content

Transactions and persistence threads

A persistence thread batches insert, update and delete operations for one connection.

$thread = $userManager->getConnection()->createPersistThread();

$thread
    ->pushPersist($user)
    ->pushPersist($project)
    ->pushDelete($obsoleteProject)
    ->flush();

flush() executes queued statements without wrapping them in a transaction.

Commit a transactional batch

$thread = $userManager->getConnection()->createPersistThread();

try {
    $thread
        ->pushPersist($user)
        ->pushPersist($project)
        ->commit();
} catch (Throwable $exception) {
    $thread->rollback();
    throw $exception;
}

For PDO-backed connections, commit() obtains one native driver connection, starts a transaction, executes the batch, commits it and returns the connection to the pool.

The PostgreSQL driver uses native PgSql\Connection, not PDO. In core 2.7.x, PersistThread::commit() falls back to flush() when the native driver does not expose PDO transaction methods. Code requiring a strict PostgreSQL transaction must therefore use a driver path that explicitly guarantees it rather than assuming commit() is atomic.

Entity collections

$users->persist();
$users->delete();

When supported by the connection, collection persistence uses one persistence thread. Small Swoole DB reads the generated identifier after every insert; SQL drivers keep normal batched behavior.

Next chapter: Backups and change detection