Skip to content

Commit 19010b9

Browse files
committed
Explorer: added autoCommit()
1 parent 5bb9d26 commit 19010b9

1 file changed

Lines changed: 32 additions & 2 deletions

File tree

src/Database/Explorer.php

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ class Explorer
4444
private TypeConverter $typeConverter;
4545
private ?SqlLiteral $lastQuery = null;
4646
private int $transactionDepth = 0;
47+
private bool $autoCommit = true;
4748
private ?Cache $cache = null;
4849
private ?Conventions $conventions = null;
4950
private ?Structure $structure = null;
@@ -77,6 +78,7 @@ public static function createFromParameters(
7778
$args = array_diff_key($params, array_flip(self::TypeConverterOptions));
7879
$explorer = new self(new $class(...$args));
7980
array_map(fn($opt) => isset($params[$opt]) && ($explorer->typeConverter->$opt = (bool) $params[$opt]), self::TypeConverterOptions);
81+
$this->autoCommit = (bool) ($params['autoCommit'] ?? true);
8082
return $explorer;
8183
}
8284

@@ -129,6 +131,9 @@ public function connect(): void
129131
throw ConnectionException::from($e);
130132
}
131133

134+
if (!$this->autoCommit) {
135+
$this->beginTransaction();
136+
}
132137
Arrays::invoke($this->onConnect, $this);
133138
}
134139

@@ -259,7 +264,9 @@ public function commit(): void
259264

260265
} elseif (--$this->transactionDepth === 0) {
261266
$this->logOperation($this->getConnection()->commit(...), new SqlLiteral('COMMIT'));
262-
267+
if (!$this->autoCommit) {
268+
$this->beginTransaction();
269+
}
263270
} else {
264271
$this->releaseSavepoint($this->transactionDepth);
265272
}
@@ -277,7 +284,9 @@ public function rollBack(): void
277284

278285
} elseif (--$this->transactionDepth === 0) {
279286
$this->logOperation($this->getConnection()->rollBack(...), new SqlLiteral('ROLLBACK'));
280-
287+
if (!$this->autoCommit) {
288+
$this->beginTransaction();
289+
}
281290
} else {
282291
$this->rollbackToSavepoint($this->transactionDepth);
283292
}
@@ -301,6 +310,27 @@ public function transaction(callable $callback): mixed
301310
}
302311

303312

313+
public function setAutoCommit(bool $state): void
314+
{
315+
if ($this->autoCommit === $state) {
316+
return;
317+
}
318+
319+
while ($this->transactionDepth > 0) {
320+
if (--$this->transactionDepth === 0) {
321+
$this->query('::commit');
322+
} else {
323+
$this->releaseSavepoint($this->transactionDepth);
324+
}
325+
}
326+
327+
$this->autoCommit = $state;
328+
if (!$state && $this->connection) {
329+
$$this->beginTransaction();
330+
}
331+
}
332+
333+
304334
public function createSavepoint(int $level): void
305335
{
306336
$this->query('SAVEPOINT LEVEL' . $level); // TODO: to driver, logOperation

0 commit comments

Comments
 (0)