Failed Conditions
Push — master ( ac0e13...24dbc4 )
by Sergei
22s queued 15s
created

src/Driver/SQLSrv/SQLSrvStatement.php (1 issue)

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

339
        if (! array_key_exists($columnIndex, /** @scrutinizer ignore-type */ $row)) {
Loading history...
340
            throw InvalidColumnIndex::new($columnIndex, count($row));
341
        }
342
343
        return $row[$columnIndex];
344
    }
345
346
    public function rowCount() : int
347
    {
348
        if ($this->stmt === null) {
349
            return 0;
350
        }
351
352
        $count = sqlsrv_rows_affected($this->stmt);
353
354
        if ($count !== false) {
355
            return $count;
356
        }
357
358
        return 0;
359
    }
360
361
    /**
362
     * Prepares SQL Server statement resource
363
     *
364
     * @return resource
365
     *
366
     * @throws SQLSrvException
367
     */
368
    private function prepare()
369
    {
370
        $params = [];
371
372
        foreach ($this->variables as $column => &$variable) {
373
            switch ($this->types[$column]) {
374
                case ParameterType::LARGE_OBJECT:
375
                    $params[$column - 1] = [
376
                        &$variable,
377
                        SQLSRV_PARAM_IN,
378
                        SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY),
379
                        SQLSRV_SQLTYPE_VARBINARY('max'),
380
                    ];
381
                    break;
382
383
                case ParameterType::BINARY:
384
                    $params[$column - 1] = [
385
                        &$variable,
386
                        SQLSRV_PARAM_IN,
387
                        SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_BINARY),
388
                    ];
389
                    break;
390
391
                default:
392
                    $params[$column - 1] =& $variable;
393
                    break;
394
            }
395
        }
396
397
        $stmt = sqlsrv_prepare($this->conn, $this->sql, $params);
398
399
        if ($stmt === false) {
400
            throw SQLSrvException::fromSqlSrvErrors();
401
        }
402
403
        return $stmt;
404
    }
405
}
406