Completed
Push — ezp-31088-refactor-content-mod... ( ab3ba3 )
by
unknown
13:24 queued 33s
created

SqliteGateway::getLastInsertedId()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @copyright Copyright (C) eZ Systems AS. All rights reserved.
5
 * @license For full copyright and license information view LICENSE file distributed with this source code.
6
 */
7
declare(strict_types=1);
8
9
namespace eZ\Publish\Core\Persistence\Legacy\SharedGateway\DatabasePlatform;
10
11
use Doctrine\DBAL\Connection;
12
use Doctrine\DBAL\FetchMode;
13
use eZ\Publish\Core\Base\Exceptions\DatabaseException;
14
use eZ\Publish\Core\Persistence\Legacy\SharedGateway\Gateway;
15
16
final class SqliteGateway implements Gateway
17
{
18
    /** @var \Doctrine\DBAL\Connection */
19
    private $connection;
20
21
    /** @var \Doctrine\DBAL\Platforms\AbstractPlatform */
22
    private $databasePlatform;
23
24
    /** @var int[] */
25
    private $lastInsertedIds = [];
26
27
    /**
28
     * @throws \Doctrine\DBAL\DBALException
29
     */
30
    public function __construct(Connection $connection)
31
    {
32
        $this->connection = $connection;
33
        $this->databasePlatform = $connection->getDatabasePlatform();
34
    }
35
36
    public function getColumnNextIntegerValue(
37
        string $tableName,
38
        string $columnName,
39
        string $sequenceName
40
    ): ?int {
41
        $query = $this->connection->createQueryBuilder();
42
        $query
43
            ->select($this->databasePlatform->getMaxExpression($columnName))
44
            ->from($tableName);
45
46
        $lastId = (int)$query->execute()->fetch(FetchMode::COLUMN);
47
48
        $this->lastInsertedIds[$sequenceName] = $lastId + 1;
49
50
        return $this->lastInsertedIds[$sequenceName];
51
    }
52
53
    /**
54
     * @throws \eZ\Publish\Core\Base\Exceptions\DatabaseException if the sequence has no last value
55
     */
56
    public function getLastInsertedId(string $sequenceName): int
57
    {
58
        if (!isset($this->lastInsertedIds[$sequenceName])) {
59
            throw new DatabaseException(
60
                "Sequence '{$sequenceName}' is not yet defined in this session",
61
                // error code 7 for fatal error - taken from an existing driver implementation
62
                7
63
            );
64
        }
65
66
        return $this->lastInsertedIds[$sequenceName];
67
    }
68
}
69