|
8 | 8 | use DateTimeInterface; |
9 | 9 | use PDO; |
10 | 10 | use PDOException; |
| 11 | +use PDOStatement; |
| 12 | +use Tempest\Database\Config\DatabaseDialect; |
11 | 13 | use Tempest\Database\Connection\Connection; |
12 | 14 | use Tempest\Database\Exceptions\QueryException; |
13 | 15 | use Tempest\Database\Transactions\TransactionManager; |
14 | 16 | use Throwable; |
15 | 17 |
|
16 | | -final readonly class GenericDatabase implements Database |
| 18 | +final class GenericDatabase implements Database |
17 | 19 | { |
| 20 | + private PDOStatement|null $lastStatement = null; |
| 21 | + private Query|null $lastQuery = null; |
| 22 | + |
18 | 23 | public function __construct( |
19 | | - private(set) Connection $connection, |
20 | | - private(set) TransactionManager $transactionManager, |
| 24 | + private(set) readonly Connection $connection, |
| 25 | + private(set) readonly TransactionManager $transactionManager, |
| 26 | + private(set) readonly DatabaseDialect $dialect, |
21 | 27 | ) {} |
22 | 28 |
|
23 | 29 | public function execute(Query $query): void |
24 | 30 | { |
25 | 31 | $bindings = $this->resolveBindings($query); |
26 | 32 |
|
27 | 33 | try { |
28 | | - $this->connection |
29 | | - ->prepare($query->toSql()) |
30 | | - ->execute($bindings); |
| 34 | + $statement = $this->connection->prepare($query->toSql()); |
| 35 | + |
| 36 | + $statement->execute($bindings); |
| 37 | + |
| 38 | + $this->lastStatement = $statement; |
| 39 | + $this->lastQuery = $query; |
31 | 40 | } catch (PDOException $pdoException) { |
32 | 41 | throw new QueryException($query, $bindings, $pdoException); |
33 | 42 | } |
34 | 43 | } |
35 | 44 |
|
36 | | - public function getLastInsertId(): Id |
| 45 | + public function getLastInsertId(): Id|null |
37 | 46 | { |
38 | | - return new Id($this->connection->lastInsertId()); |
| 47 | + $sql = $this->lastQuery->toSql(); |
| 48 | + |
| 49 | + if (! str_starts_with($sql, 'INSERT')) { |
| 50 | + return null; |
| 51 | + } |
| 52 | + |
| 53 | + if ($this->dialect === DatabaseDialect::POSTGRESQL) { |
| 54 | + $data = $this->lastStatement->fetch(PDO::FETCH_ASSOC); |
| 55 | + $lastInsertId = $data['id'] ?? null; |
| 56 | + } else { |
| 57 | + $lastInsertId = $this->connection->lastInsertId(); |
| 58 | + } |
| 59 | + |
| 60 | + return new Id($lastInsertId); |
39 | 61 | } |
40 | 62 |
|
41 | 63 | public function fetch(Query $query): array |
|
0 commit comments