Completed
Pull Request — master (#3070)
by Sergei
64:44
created

SQLSrvStatement::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 11
ccs 0
cts 0
cp 0
rs 10
cc 2
nc 2
nop 3
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\DBAL\Driver\SQLSrv;
6
7
use Doctrine\DBAL\Driver\Statement;
8
use Doctrine\DBAL\Driver\StatementIterator;
9
use Doctrine\DBAL\FetchMode;
10
use Doctrine\DBAL\ParameterType;
11
use IteratorAggregate;
12
use function assert;
13
use function is_int;
14
use function sqlsrv_execute;
15
use function sqlsrv_fetch;
16
use function sqlsrv_fetch_array;
17
use function sqlsrv_get_field;
18
use function sqlsrv_next_result;
19
use function sqlsrv_num_fields;
20
use function SQLSRV_PHPTYPE_STREAM;
21
use function SQLSRV_PHPTYPE_STRING;
22
use function sqlsrv_prepare;
23
use function sqlsrv_rows_affected;
24
use function SQLSRV_SQLTYPE_VARBINARY;
25
use function stripos;
26
use const SQLSRV_ENC_BINARY;
27
use const SQLSRV_FETCH_ASSOC;
28
use const SQLSRV_FETCH_BOTH;
29
use const SQLSRV_FETCH_NUMERIC;
30
use const SQLSRV_PARAM_IN;
31
32
/**
33
 * SQL Server Statement.
34
 */
35
final class SQLSrvStatement implements IteratorAggregate, Statement
36
{
37
    /**
38
     * The SQLSRV Resource.
39
     *
40
     * @var resource
41
     */
42
    private $conn;
43
44
    /**
45
     * The SQL statement to execute.
46
     *
47
     * @var string
48
     */
49
    private $sql;
50
51
    /**
52
     * The SQLSRV statement resource.
53
     *
54
     * @var resource|null
55
     */
56
    private $stmt;
57
58
    /**
59
     * References to the variables bound as statement parameters.
60
     *
61
     * @var mixed
62
     */
63
    private $variables = [];
64
65
    /**
66
     * Bound parameter types.
67
     *
68
     * @var int[]
69
     */
70
    private $types = [];
71
72
    /**
73
     * Translations.
74
     *
75
     * @var int[]
76
     */
77
    private static $fetchMap = [
78
        FetchMode::MIXED       => SQLSRV_FETCH_BOTH,
79
        FetchMode::ASSOCIATIVE => SQLSRV_FETCH_ASSOC,
80
        FetchMode::NUMERIC     => SQLSRV_FETCH_NUMERIC,
81
    ];
82
83
    /**
84
     * The fetch style.
85
     *
86
     * @var int
87
     */
88
    private $defaultFetchMode = FetchMode::MIXED;
89
90
    /**
91
     * The last insert ID.
92
     *
93
     * @var LastInsertId|null
94
     */
95
    private $lastInsertId;
96
97
    /**
98
     * Indicates whether the statement is in the state when fetching results is possible
99
     *
100
     * @var bool
101
     */
102
    private $result = false;
103
104
    /**
105
     * Append to any INSERT query to retrieve the last insert id.
106
     */
107
    private const LAST_INSERT_ID_SQL = ';SELECT SCOPE_IDENTITY() AS LastInsertId;';
108
109
    /**
110
     * @param resource $conn
111
     */
112
    public function __construct($conn, string $sql, ?LastInsertId $lastInsertId = null)
113
    {
114
        $this->conn = $conn;
115
        $this->sql  = $sql;
116
117
        if (stripos($sql, 'INSERT INTO ') !== 0) {
118
            return;
119
        }
120
121
        $this->sql         .= self::LAST_INSERT_ID_SQL;
122
        $this->lastInsertId = $lastInsertId;
123
    }
124
125
    /**
126
     * {@inheritdoc}
127
     */
128
    public function bindValue($param, $value, int $type = ParameterType::STRING) : void
129
    {
130
        assert(is_int($param));
131 324
132
        $this->variables[$param] = $value;
133 324
        $this->types[$param]     = $type;
134 324
    }
135
136 324
    /**
137 317
     * {@inheritdoc}
138
     */
139
    public function bindParam($param, &$variable, int $type = ParameterType::STRING, ?int $length = null) : void
140 92
    {
141 92
        assert(is_int($param));
142 92
143
        $this->variables[$param] =& $variable;
144
        $this->types[$param]     = $type;
145
146
        // unset the statement resource if it exists as the new one will need to be bound to the new variable
147 114
        $this->stmt = null;
148
    }
149 114
150
    public function closeCursor() : void
151 114
    {
152 114
        // not having the result means there's nothing to close
153 114
        if ($this->stmt === null || ! $this->result) {
154
            return;
155
        }
156
157
        // emulate it by fetching and discarding rows, similarly to what PDO does in this case
158 24
        // @link http://php.net/manual/en/pdostatement.closecursor.php
159
        // @link https://github.com/php/php-src/blob/php-7.0.11/ext/pdo/pdo_stmt.c#L2075
160 24
        // deliberately do not consider multiple result sets, since doctrine/dbal doesn't support them
161
        while (sqlsrv_fetch($this->stmt) !== false) {
162 24
        }
163 24
164
        $this->result = false;
165
    }
166 24
167 24
    public function columnCount() : int
168
    {
169
        if ($this->stmt === null) {
170
            return 0;
171
        }
172 19
173
        return sqlsrv_num_fields($this->stmt) ?: 0;
174
    }
175 19
176 3
    /**
177
     * {@inheritdoc}
178
     */
179
    public function execute(?array $params = null) : void
180
    {
181
        if ($params) {
182
            foreach ($params as $key => $val) {
183 16
                if (is_int($key)) {
184
                    $this->bindValue($key + 1, $val);
185
                } else {
186 16
                    $this->bindValue($key, $val);
187 16
                }
188
            }
189
        }
190
191
        if (! $this->stmt) {
192 4
            $this->stmt = $this->prepare();
193
        }
194 4
195
        if (! sqlsrv_execute($this->stmt)) {
196
            throw SQLSrvException::fromSqlSrvErrors();
197
        }
198 4
199
        if ($this->lastInsertId) {
200
            sqlsrv_next_result($this->stmt);
201
            sqlsrv_fetch($this->stmt);
202
            $this->lastInsertId->setId(sqlsrv_get_field($this->stmt, 0));
203
        }
204 317
205
        $this->result = true;
206 317
    }
207 83
208 83
    public function setFetchMode(int $fetchMode) : void
209 83
    {
210
        $this->defaultFetchMode = $fetchMode;
211
    }
212
213
    /**
214
     * {@inheritdoc}
215
     */
216 317
    public function getIterator()
217 317
    {
218
        return new StatementIterator($this);
219
    }
220 316
221
    /**
222
     * {@inheritdoc}
223
     *
224 316
     * @throws SQLSrvException
225 92
     */
226 92
    public function fetch(?int $fetchMode = null)
227 92
    {
228
        // do not try fetching from the statement if it's not expected to contain result
229
        // in order to prevent exceptional situation
230 316
        if ($this->stmt === null || ! $this->result) {
231 316
            return false;
232
        }
233
234
        $fetchMode = $fetchMode ?: $this->defaultFetchMode;
235
236 317
        if ($fetchMode === FetchMode::COLUMN) {
237
            return $this->fetchColumn();
238 317
        }
239
240 317
        if (isset(self::$fetchMap[$fetchMode])) {
241 2
            return sqlsrv_fetch_array($this->stmt, self::$fetchMap[$fetchMode]) ?: false;
242
        }
243
244 317
        throw new SQLSrvException('Fetch mode is not supported.');
245 317
    }
246
247
    /**
248
     * {@inheritdoc}
249
     */
250
    public function fetchAll(?int $fetchMode = null) : array
251
    {
252
        $rows = [];
253
254 1
        switch ($fetchMode) {
255
            case FetchMode::COLUMN:
256 1
                while (($row = $this->fetchColumn()) !== false) {
257
                    $rows[] = $row;
258
                }
259
260
                break;
261
262
            default:
263
                while (($row = $this->fetch($fetchMode)) !== false) {
264 308
                    $rows[] = $row;
265
                }
266
        }
267
268 308
        return $rows;
269 9
    }
270
271
    /**
272 299
     * {@inheritdoc}
273
     */
274 299
    public function fetchColumn()
275 1
    {
276
        $row = $this->fetch(FetchMode::NUMERIC);
277
278 299
        if ($row === false) {
279 295
            return false;
280
        }
281
282 4
        return $row[0];
283 4
    }
284 4
285
    public function rowCount() : int
286 4
    {
287 1
        if ($this->stmt === null) {
288 1
            return 0;
289
        }
290
291 4
        return sqlsrv_rows_affected($this->stmt) ?: 0;
292
    }
293
294
    /**
295
     * Prepares SQL Server statement resource
296
     *
297
     * @return resource
298
     *
299
     * @throws SQLSrvException
300 120
     */
301
    private function prepare()
302 120
    {
303
        $params = [];
304 120
305
        foreach ($this->variables as $column => &$variable) {
306 1
            switch ($this->types[$column]) {
307 1
                case ParameterType::LARGE_OBJECT:
308
                    $params[$column - 1] = [
309 1
                        &$variable,
310
                        SQLSRV_PARAM_IN,
311
                        SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY),
312 10
                        SQLSRV_SQLTYPE_VARBINARY('max'),
313 10
                    ];
314
                    break;
315 10
316
                case ParameterType::BINARY:
317
                    $params[$column - 1] = [
318 109
                        &$variable,
319 101
                        SQLSRV_PARAM_IN,
320
                        SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_BINARY),
321
                    ];
322
                    break;
323 120
324
                default:
325
                    $params[$column - 1] =& $variable;
326
                    break;
327
            }
328
        }
329 198
330
        $stmt = sqlsrv_prepare($this->conn, $this->sql, $params);
331 198
332
        if (! $stmt) {
0 ignored issues
show
introduced by
$stmt is of type false|resource, thus it always evaluated to false.
Loading history...
333 198
            throw SQLSrvException::fromSqlSrvErrors();
334 16
        }
335
336
        return $stmt;
337 192
    }
338
}
339