Skip to content

Core version availability

Scoped sessions are available in Core 3.3.0 and later. Use 3.3.1 or later when also using small/swoole-patterns 26.1.1.

Scoped ORM sessions and typed criteria (Core 3.3)

These APIs are available starting with Core 3.3.0.

Transaction and connection ownership

Use OrmSession::transaction() to execute multiple ORM queries on the same driver connection. The ORM commits once when the callback succeeds, rolls back on any exception and always releases the connection. The native connection is never returned to the caller.

use Small\SwooleEntityManager\Database\Session\OrmSession;

$connection = $manager->getConnection();

OrmSession::transaction($connection, function (OrmSession $session) use ($manager): void {
    // Only mapped query builders and entity operations.
    // Commit/rollback and resource disposal are owned by the ORM.
});

Use OrmSession::readOnly() for bounded reads without a transaction. Updates and row locking are rejected on read-only sessions, and a session cannot be used after its callback exits. Never share a session between coroutines.

Mapped criteria, projections and row locking

use Small\SwooleEntityManager\Database\Session\OrmSession;
use Small\SwooleEntityManager\QueryBuilder\RelationalQueryBuilder\Criteria;

OrmSession::transaction($connection, function (OrmSession $session) use ($manager): void {
    $where = Criteria::all(
        Criteria::equal('status', 'pending'),
        Criteria::lessThanOrEqual('availableAt', new DateTimeImmutable('now')->format('Y-m-d H:i:s.u')),
    );

    $row = $session->findOneBy($manager, $where, lock: true, skipLocked: true);
    if ($row === null) {
        return;
    }

    // The callback holds the row lock until the ORM commits.
});

The criterion API supports equality, inequality, less/greater comparisons, IN lists, AND/OR groups, nullable values, mapped column comparisons and NOT EXISTS subqueries. Values are bound automatically; they are never concatenated into generated SQL. The API refuses to overwrite an existing WHERE clause. When building queries manually, use the same ORM mappings.

rows($query) returns scalar projections, first($query) returns the first row or null without mutating the original query, and exists($query) checks whether at least one row matches. first(..., lock: true) requires a transaction; skipLocked: true additionally requires locking. Locking is supported by MySQL and PostgreSQL, not the SwooleDb adapter.

Atomic mutations and optimistic concurrency

OrmSession::transaction($connection, function (OrmSession $session) use ($manager): void {
    $where = Criteria::equal('id', '11111111-1111-4111-8111-111111111111');

    $affected = $session->assign($manager, $where, ['status' => 'running']);
    $session->increment($manager, $where, 'attempts');

    $advanced = $session->compareAndSwap(
        $manager, $where, 'revision', expectedRevision: 4,
        assignments: ['status' => 'completed'],
    );
    if (!$advanced) {
        // Lost race or already updated; do not overwrite concurrent work.
    }
});

The CAS operation always increments the mapped revision atomically, so the affected-row count distinguishes a successful update from an unchanged row. insertIfAbsent($manager, $entity) uses a database uniqueness constraint for idempotency; updateAffectedRows returns the exact affected-row count. insertMapped, updateMapped and deleteMapped execute entity-mapped statements on the current transaction without invoking lifecycle callbacks or committing early. Updates/deletes require an entity hydrated from the database with its original primary-key snapshot.

For manually assigned primary keys on PostgreSQL (including UUIDv7), add #[NoLastInsertId] to the entity class, as required by the existing PostgreSQL persist adapter. Otherwise it expects a database-generated key.

Retry policy

use Small\SwooleEntityManager\Database\Session\TransactionRetryPolicy;

$policy = new TransactionRetryPolicy(maxAttempts: 3);
$result = $policy->runReplaySafe(
    fn () => OrmSession::transaction($connection, $transactionCallback),
);

Use this only when the entire callback is safe to replay and each failed transaction has been rolled back. The retry policy recognizes MySQL deadlock / lock-wait errors and PostgreSQL transaction conflicts, including wrapped SQLSTATE codes. It never retries ambiguous connection/commit failures. Do not perform external effects, send events or invoke non-idempotent handlers inside the replayable callback. Use an outbox or post-commit worker instead.

Compatibility and tests

Existing managers and query-builder APIs remain available. These new operations are optional, and applications can migrate one manager at a time.

Tests cover transaction ownership, escaped sessions, read-only enforcement, criteria binding, MySQL 8.4 and PostgreSQL 16 mapped writes, rollback, CAS and row locking. The Core test suite retains its 100% line-coverage requirement. Cross-table business operations should continue to use small/swoole-entity-manager-strates where an atomic multi-table unit of work is required.