summaryrefslogtreecommitdiff
path: root/vendor/doctrine/dbal/src/Driver/SQLSrv/Connection.php
blob: 71050f17a3e55eff7392b77b09ecc86c192ee464 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<?php

declare(strict_types=1);

namespace Doctrine\DBAL\Driver\SQLSrv;

use Doctrine\DBAL\Driver\Connection as ConnectionInterface;
use Doctrine\DBAL\Driver\Exception\NoIdentityValue;
use Doctrine\DBAL\Driver\SQLSrv\Exception\Error;

use function sqlsrv_begin_transaction;
use function sqlsrv_commit;
use function sqlsrv_query;
use function sqlsrv_rollback;
use function sqlsrv_rows_affected;
use function sqlsrv_server_info;
use function str_replace;

final class Connection implements ConnectionInterface
{
    /**
     * @internal The connection can be only instantiated by its driver.
     *
     * @param resource $connection
     */
    public function __construct(private readonly mixed $connection)
    {
    }

    public function getServerVersion(): string
    {
        $serverInfo = sqlsrv_server_info($this->connection);

        return $serverInfo['SQLServerVersion'];
    }

    public function prepare(string $sql): Statement
    {
        return new Statement($this->connection, $sql);
    }

    public function query(string $sql): Result
    {
        return $this->prepare($sql)->execute();
    }

    public function quote(string $value): string
    {
        return "'" . str_replace("'", "''", $value) . "'";
    }

    public function exec(string $sql): int
    {
        $stmt = sqlsrv_query($this->connection, $sql);

        if ($stmt === false) {
            throw Error::new();
        }

        $rowsAffected = sqlsrv_rows_affected($stmt);

        if ($rowsAffected === false) {
            throw Error::new();
        }

        return $rowsAffected;
    }

    public function lastInsertId(): int|string
    {
        $result = $this->query('SELECT @@IDENTITY');

        $lastInsertId = $result->fetchOne();

        if ($lastInsertId === null) {
            throw NoIdentityValue::new();
        }

        return $lastInsertId;
    }

    public function beginTransaction(): void
    {
        if (! sqlsrv_begin_transaction($this->connection)) {
            throw Error::new();
        }
    }

    public function commit(): void
    {
        if (! sqlsrv_commit($this->connection)) {
            throw Error::new();
        }
    }

    public function rollBack(): void
    {
        if (! sqlsrv_rollback($this->connection)) {
            throw Error::new();
        }
    }

    /** @return resource */
    public function getNativeConnection()
    {
        return $this->connection;
    }
}