Completed
Push — master ( 1eba78...18908c )
by Sergei
62:05 queued 10s
created

SQLSrvStatement   A

Complexity

Total Complexity 39

Size/Duplication

Total Lines 314
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 104
dl 0
loc 314
rs 9.28
c 0
b 0
f 0
wmc 39

13 Methods

Rating   Name   Duplication   Size   Complexity  
A rowCount() 0 13 3
A setFetchMode() 0 3 1
A fetch() 0 19 5
B execute() 0 27 7
A fetchColumn() 0 9 2
A bindParam() 0 9 1
A bindValue() 0 6 1
A columnCount() 0 13 3
A prepare() 0 36 5
A fetchAll() 0 19 4
A closeCursor() 0 15 4
A getIterator() 0 3 1
A __construct() 0 11 2
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
132
        $this->variables[$param] = $value;
133
        $this->types[$param]     = $type;
134
    }
135
136
    /**
137
     * {@inheritdoc}
138
     */
139
    public function bindParam($param, &$variable, int $type = ParameterType::STRING, ?int $length = null) : void
140
    {
141
        assert(is_int($param));
142
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
        $this->stmt = null;
148
    }
149
150
    public function closeCursor() : void
151
    {
152
        // not having the result means there's nothing to close
153
        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
        // @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
        // deliberately do not consider multiple result sets, since doctrine/dbal doesn't support them
161
        while (sqlsrv_fetch($this->stmt) !== false) {
162
        }
163
164
        $this->result = false;
165
    }
166
167
    public function columnCount() : int
168
    {
169
        if ($this->stmt === null) {
170
            return 0;
171
        }
172
173
        $count = sqlsrv_num_fields($this->stmt);
174
175
        if ($count !== false) {
176
            return $count;
177
        }
178
179
        return 0;
180
    }
181
182
    /**
183
     * {@inheritdoc}
184
     */
185
    public function execute(?array $params = null) : void
186
    {
187
        if ($params !== null) {
188
            foreach ($params as $key => $val) {
189
                if (is_int($key)) {
190
                    $this->bindValue($key + 1, $val);
191
                } else {
192
                    $this->bindValue($key, $val);
193
                }
194
            }
195
        }
196
197
        if ($this->stmt === null) {
198
            $this->stmt = $this->prepare();
199
        }
200
201
        if (! sqlsrv_execute($this->stmt)) {
202
            throw SQLSrvException::fromSqlSrvErrors();
203
        }
204
205
        if ($this->lastInsertId !== null) {
206
            sqlsrv_next_result($this->stmt);
207
            sqlsrv_fetch($this->stmt);
208
            $this->lastInsertId->setId(sqlsrv_get_field($this->stmt, 0));
209
        }
210
211
        $this->result = true;
212
    }
213
214
    public function setFetchMode(int $fetchMode) : void
215
    {
216
        $this->defaultFetchMode = $fetchMode;
217
    }
218
219
    /**
220
     * {@inheritdoc}
221
     */
222
    public function getIterator()
223
    {
224
        return new StatementIterator($this);
225
    }
226
227
    /**
228
     * {@inheritdoc}
229
     *
230
     * @throws SQLSrvException
231
     */
232
    public function fetch(?int $fetchMode = null)
233
    {
234
        // do not try fetching from the statement if it's not expected to contain result
235
        // in order to prevent exceptional situation
236
        if ($this->stmt === null || ! $this->result) {
237
            return false;
238
        }
239
240
        $fetchMode = $fetchMode ?? $this->defaultFetchMode;
241
242
        if ($fetchMode === FetchMode::COLUMN) {
243
            return $this->fetchColumn();
244
        }
245
246
        if (isset(self::$fetchMap[$fetchMode])) {
247
            return sqlsrv_fetch_array($this->stmt, self::$fetchMap[$fetchMode]) ?? false;
248
        }
249
250
        throw new SQLSrvException('Fetch mode is not supported.');
251
    }
252
253
    /**
254
     * {@inheritdoc}
255
     */
256
    public function fetchAll(?int $fetchMode = null) : array
257
    {
258
        $rows = [];
259
260
        switch ($fetchMode) {
261
            case FetchMode::COLUMN:
262
                while (($row = $this->fetchColumn()) !== false) {
263
                    $rows[] = $row;
264
                }
265
266
                break;
267
268
            default:
269
                while (($row = $this->fetch($fetchMode)) !== false) {
270
                    $rows[] = $row;
271
                }
272
        }
273
274
        return $rows;
275
    }
276
277
    /**
278
     * {@inheritdoc}
279
     */
280
    public function fetchColumn()
281
    {
282
        $row = $this->fetch(FetchMode::NUMERIC);
283
284
        if ($row === false) {
285
            return false;
286
        }
287
288
        return $row[0];
289
    }
290
291
    public function rowCount() : int
292
    {
293
        if ($this->stmt === null) {
294
            return 0;
295
        }
296
297
        $count = sqlsrv_rows_affected($this->stmt);
298
299
        if ($count !== false) {
300
            return $count;
301
        }
302
303
        return 0;
304
    }
305
306
    /**
307
     * Prepares SQL Server statement resource
308
     *
309
     * @return resource
310
     *
311
     * @throws SQLSrvException
312
     */
313
    private function prepare()
314
    {
315
        $params = [];
316
317
        foreach ($this->variables as $column => &$variable) {
318
            switch ($this->types[$column]) {
319
                case ParameterType::LARGE_OBJECT:
320
                    $params[$column - 1] = [
321
                        &$variable,
322
                        SQLSRV_PARAM_IN,
323
                        SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY),
324
                        SQLSRV_SQLTYPE_VARBINARY('max'),
325
                    ];
326
                    break;
327
328
                case ParameterType::BINARY:
329
                    $params[$column - 1] = [
330
                        &$variable,
331
                        SQLSRV_PARAM_IN,
332
                        SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_BINARY),
333
                    ];
334
                    break;
335
336
                default:
337
                    $params[$column - 1] =& $variable;
338
                    break;
339
            }
340
        }
341
342
        $stmt = sqlsrv_prepare($this->conn, $this->sql, $params);
343
344
        if ($stmt === false) {
345
            throw SQLSrvException::fromSqlSrvErrors();
346
        }
347
348
        return $stmt;
349
    }
350
}
351