• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

codeigniter4 / CodeIgniter4 / 21568681844

01 Feb 2026 07:16PM UTC coverage: 85.41% (+1.0%) from 84.387%
21568681844

push

github

web-flow
Merge pull request #9916 from codeigniter4/4.7

4.7.0 Merge code

1603 of 1888 new or added lines in 101 files covered. (84.9%)

31 existing lines in 11 files now uncovered.

22163 of 25949 relevant lines covered (85.41%)

205.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

78.42
/system/Database/SQLSRV/Connection.php
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of CodeIgniter 4 framework.
7
 *
8
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace CodeIgniter\Database\SQLSRV;
15

16
use CodeIgniter\Database\BaseConnection;
17
use CodeIgniter\Database\Exceptions\DatabaseException;
18
use CodeIgniter\Database\TableName;
19
use stdClass;
20

21
/**
22
 * Connection for SQLSRV
23
 *
24
 * @extends BaseConnection<resource, resource>
25
 */
26
class Connection extends BaseConnection
27
{
28
    /**
29
     * Database driver
30
     *
31
     * @var string
32
     */
33
    public $DBDriver = 'SQLSRV';
34

35
    /**
36
     * Database name
37
     *
38
     * @var string
39
     */
40
    public $database;
41

42
    /**
43
     * Scrollable flag
44
     *
45
     * Determines what cursor type to use when executing queries.
46
     *
47
     * FALSE or SQLSRV_CURSOR_FORWARD would increase performance,
48
     * but would disable num_rows() (and possibly insert_id())
49
     *
50
     * @var false|string
51
     */
52
    public $scrollable;
53

54
    /**
55
     * Identifier escape character
56
     *
57
     * @var string
58
     */
59
    public $escapeChar = '"';
60

61
    /**
62
     * Database schema
63
     *
64
     * @var string
65
     */
66
    public $schema = 'dbo';
67

68
    /**
69
     * Quoted identifier flag
70
     *
71
     * Whether to use SQL-92 standard quoted identifier
72
     * (double quotes) or brackets for identifier escaping.
73
     *
74
     * @var bool
75
     */
76
    protected $_quoted_identifier = true;
77

78
    /**
79
     * List of reserved identifiers
80
     *
81
     * Identifiers that must NOT be escaped.
82
     *
83
     * @var list<string>
84
     */
85
    protected $_reserved_identifiers = ['*'];
86

87
    /**
88
     * Class constructor
89
     */
90
    public function __construct(array $params)
91
    {
92
        parent::__construct($params);
30✔
93

94
        // This is only supported as of SQLSRV 3.0
95
        if ($this->scrollable === null) {
30✔
96
            $this->scrollable = defined('SQLSRV_CURSOR_CLIENT_BUFFERED') ? SQLSRV_CURSOR_CLIENT_BUFFERED : false;
30✔
97
        }
98
    }
99

100
    /**
101
     * Connect to the database.
102
     *
103
     * @return false|resource
104
     *
105
     * @throws DatabaseException
106
     */
107
    public function connect(bool $persistent = false)
108
    {
109
        $charset = in_array(strtolower($this->charset), ['utf-8', 'utf8'], true) ? 'UTF-8' : SQLSRV_ENC_CHAR;
28✔
110

111
        $connection = [
28✔
112
            'UID'                  => empty($this->username) ? '' : $this->username,
28✔
113
            'PWD'                  => empty($this->password) ? '' : $this->password,
28✔
114
            'Database'             => $this->database,
28✔
115
            'ConnectionPooling'    => $persistent ? 1 : 0,
28✔
116
            'CharacterSet'         => $charset,
28✔
117
            'Encrypt'              => $this->encrypt === true ? 1 : 0,
28✔
118
            'ReturnDatesAsStrings' => 1,
28✔
119
        ];
28✔
120

121
        // If the username and password are both empty, assume this is a
122
        // 'Windows Authentication Mode' connection.
123
        if (empty($connection['UID']) && empty($connection['PWD'])) {
28✔
124
            unset($connection['UID'], $connection['PWD']);
×
125
        }
126

127
        if (! str_contains($this->hostname, ',') && $this->port !== '') {
28✔
128
            $this->hostname .= ', ' . $this->port;
26✔
129
        }
130

131
        sqlsrv_configure('WarningsReturnAsErrors', 0);
28✔
132
        $this->connID = sqlsrv_connect($this->hostname, $connection);
28✔
133

134
        if ($this->connID !== false) {
28✔
135
            // Determine how identifiers are escaped
136
            $query = $this->query('SELECT CASE WHEN (@@OPTIONS | 256) = @@OPTIONS THEN 1 ELSE 0 END AS qi');
28✔
137
            $query = $query->getResultObject();
27✔
138

139
            $this->_quoted_identifier = empty($query) ? false : (bool) $query[0]->qi;
27✔
140
            $this->escapeChar         = ($this->_quoted_identifier) ? '"' : ['[', ']'];
27✔
141

142
            return $this->connID;
27✔
143
        }
144

145
        throw new DatabaseException($this->getAllErrorMessages());
1✔
146
    }
147

148
    /**
149
     * For exception message
150
     *
151
     * @internal
152
     */
153
    public function getAllErrorMessages(): string
154
    {
155
        $errors = [];
34✔
156

157
        foreach (sqlsrv_errors() as $error) {
34✔
158
            $errors[] = sprintf(
34✔
159
                '%s SQLSTATE: %s, code: %s',
34✔
160
                $error['message'],
34✔
161
                $error['SQLSTATE'],
34✔
162
                $error['code'],
34✔
163
            );
34✔
164
        }
165

166
        return implode("\n", $errors);
34✔
167
    }
168

169
    /**
170
     * Close the database connection.
171
     *
172
     * @return void
173
     */
174
    protected function _close()
175
    {
176
        sqlsrv_close($this->connID);
3✔
177
    }
178

179
    /**
180
     * Platform-dependant string escape
181
     */
182
    protected function _escapeString(string $str): string
183
    {
184
        return str_replace("'", "''", remove_invisible_characters($str, false));
734✔
185
    }
186

187
    /**
188
     * Insert ID
189
     */
190
    public function insertID(): int
191
    {
192
        return (int) ($this->query('SELECT SCOPE_IDENTITY() AS insert_id')->getRow()->insert_id ?? 0);
83✔
193
    }
194

195
    /**
196
     * Generates the SQL for listing tables in a platform-dependent manner.
197
     *
198
     * @param string|null $tableName If $tableName is provided will return only this table if exists.
199
     */
200
    protected function _listTables(bool $prefixLimit = false, ?string $tableName = null): string
201
    {
202
        $sql = 'SELECT [TABLE_NAME] AS "name"'
677✔
203
            . ' FROM [INFORMATION_SCHEMA].[TABLES] '
677✔
204
            . ' WHERE '
677✔
205
            . " [TABLE_SCHEMA] = '" . $this->schema . "'    ";
677✔
206

207
        if ($tableName !== null) {
677✔
208
            return $sql .= ' AND [TABLE_NAME] LIKE ' . $this->escape($tableName);
676✔
209
        }
210

211
        if ($prefixLimit && $this->DBPrefix !== '') {
34✔
212
            $sql .= " AND [TABLE_NAME] LIKE '" . $this->escapeLikeString($this->DBPrefix) . "%' "
×
213
                . sprintf($this->likeEscapeStr, $this->likeEscapeChar);
×
214
        }
215

216
        return $sql;
34✔
217
    }
218

219
    /**
220
     * Generates a platform-specific query string so that the column names can be fetched.
221
     *
222
     * @param string|TableName $table
223
     */
224
    protected function _listColumns($table = ''): string
225
    {
226
        if ($table instanceof TableName) {
8✔
227
            $tableName = $this->escape(strtolower($table->getActualTableName()));
2✔
228
        } else {
229
            $tableName = $this->escape($this->DBPrefix . strtolower($table));
6✔
230
        }
231

232
        return 'SELECT [COLUMN_NAME] '
8✔
233
            . ' FROM [INFORMATION_SCHEMA].[COLUMNS]'
8✔
234
            . ' WHERE  [TABLE_NAME] = ' . $tableName
8✔
235
            . ' AND [TABLE_SCHEMA] = ' . $this->escape($this->schema);
8✔
236
    }
237

238
    /**
239
     * Returns an array of objects with index data
240
     *
241
     * @return array<string, stdClass>
242
     *
243
     * @throws DatabaseException
244
     */
245
    protected function _indexData(string $table): array
246
    {
247
        $sql = 'EXEC sp_helpindex ' . $this->escape($this->schema . '.' . $table);
41✔
248

249
        if (($query = $this->query($sql)) === false) {
41✔
250
            throw new DatabaseException(lang('Database.failGetIndexData'));
×
251
        }
252
        $query = $query->getResultObject();
41✔
253

254
        $retVal = [];
41✔
255

256
        foreach ($query as $row) {
41✔
257
            $obj       = new stdClass();
28✔
258
            $obj->name = $row->index_name;
28✔
259

260
            $_fields     = explode(',', trim($row->index_keys));
28✔
261
            $obj->fields = array_map(trim(...), $_fields);
28✔
262

263
            if (str_contains($row->index_description, 'primary key located on')) {
28✔
264
                $obj->type = 'PRIMARY';
25✔
265
            } else {
266
                $obj->type = (str_contains($row->index_description, 'nonclustered, unique')) ? 'UNIQUE' : 'INDEX';
18✔
267
            }
268

269
            $retVal[$obj->name] = $obj;
28✔
270
        }
271

272
        return $retVal;
41✔
273
    }
274

275
    /**
276
     * Returns an array of objects with Foreign key data
277
     * referenced_object_id  parent_object_id
278
     *
279
     * @return array<string, stdClass>
280
     *
281
     * @throws DatabaseException
282
     */
283
    protected function _foreignKeyData(string $table): array
284
    {
285
        $sql = 'SELECT
5✔
286
                f.name as constraint_name,
287
                OBJECT_NAME (f.parent_object_id) as table_name,
288
                COL_NAME(fc.parent_object_id,fc.parent_column_id) column_name,
289
                OBJECT_NAME(f.referenced_object_id) foreign_table_name,
290
                COL_NAME(fc.referenced_object_id,fc.referenced_column_id) foreign_column_name,
291
                rc.delete_rule,
292
                rc.update_rule,
293
                rc.match_option
294
                FROM
295
                sys.foreign_keys AS f
296
                INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
297
                INNER JOIN sys.tables t ON t.OBJECT_ID = fc.referenced_object_id
298
                INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc ON rc.CONSTRAINT_NAME = f.name
299
                WHERE OBJECT_NAME (f.parent_object_id) = ' . $this->escape($table);
5✔
300

301
        if (($query = $this->query($sql)) === false) {
5✔
302
            throw new DatabaseException(lang('Database.failGetForeignKeyData'));
×
303
        }
304

305
        $query   = $query->getResultObject();
5✔
306
        $indexes = [];
5✔
307

308
        foreach ($query as $row) {
5✔
309
            $indexes[$row->constraint_name]['constraint_name']       = $row->constraint_name;
4✔
310
            $indexes[$row->constraint_name]['table_name']            = $row->table_name;
4✔
311
            $indexes[$row->constraint_name]['column_name'][]         = $row->column_name;
4✔
312
            $indexes[$row->constraint_name]['foreign_table_name']    = $row->foreign_table_name;
4✔
313
            $indexes[$row->constraint_name]['foreign_column_name'][] = $row->foreign_column_name;
4✔
314
            $indexes[$row->constraint_name]['on_delete']             = $row->delete_rule;
4✔
315
            $indexes[$row->constraint_name]['on_update']             = $row->update_rule;
4✔
316
            $indexes[$row->constraint_name]['match']                 = $row->match_option;
4✔
317
        }
318

319
        return $this->foreignKeyDataToObjects($indexes);
5✔
320
    }
321

322
    /**
323
     * Disables foreign key checks temporarily.
324
     *
325
     * @return string
326
     */
327
    protected function _disableForeignKeyChecks()
328
    {
329
        return 'EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT ALL"';
682✔
330
    }
331

332
    /**
333
     * Enables foreign key checks temporarily.
334
     *
335
     * @return string
336
     */
337
    protected function _enableForeignKeyChecks()
338
    {
339
        return 'EXEC sp_MSforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL"';
682✔
340
    }
341

342
    /**
343
     * Returns an array of objects with field data
344
     *
345
     * @return list<stdClass>
346
     *
347
     * @throws DatabaseException
348
     */
349
    protected function _fieldData(string $table): array
350
    {
351
        $sql = 'SELECT
13✔
352
                COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION,
353
                COLUMN_DEFAULT, IS_NULLABLE
354
            FROM INFORMATION_SCHEMA.COLUMNS
355
            WHERE TABLE_NAME= ' . $this->escape(($table));
13✔
356

357
        if (($query = $this->query($sql)) === false) {
13✔
358
            throw new DatabaseException(lang('Database.failGetFieldData'));
×
359
        }
360

361
        $query  = $query->getResultObject();
13✔
362
        $retVal = [];
13✔
363

364
        for ($i = 0, $c = count($query); $i < $c; $i++) {
13✔
365
            $retVal[$i] = new stdClass();
13✔
366

367
            $retVal[$i]->name = $query[$i]->COLUMN_NAME;
13✔
368
            $retVal[$i]->type = $query[$i]->DATA_TYPE;
13✔
369

370
            $retVal[$i]->max_length = $query[$i]->CHARACTER_MAXIMUM_LENGTH > 0
13✔
371
                ? $query[$i]->CHARACTER_MAXIMUM_LENGTH
11✔
372
                : (
13✔
373
                    $query[$i]->CHARACTER_MAXIMUM_LENGTH === -1
10✔
374
                    ? 'max'
1✔
375
                    : $query[$i]->NUMERIC_PRECISION
10✔
376
                );
13✔
377

378
            $retVal[$i]->nullable = $query[$i]->IS_NULLABLE !== 'NO';
13✔
379
            $retVal[$i]->default  = $this->normalizeDefault($query[$i]->COLUMN_DEFAULT);
13✔
380
        }
381

382
        return $retVal;
13✔
383
    }
384

385
    /**
386
     * Normalizes SQL Server COLUMN_DEFAULT values.
387
     * Removes wrapping parentheses and handles basic conversions.
388
     */
389
    private function normalizeDefault(?string $default): ?string
390
    {
391
        if ($default === null) {
13✔
392
            return null;
12✔
393
        }
394

395
        $default = trim($default);
2✔
396

397
        // Remove outer parentheses (handles both single and double wrapping)
398
        while (preg_match('/^\((.*)\)$/', $default, $matches)) {
2✔
399
            $default = trim($matches[1]);
2✔
400
        }
401

402
        // Handle NULL literal
403
        if (strcasecmp($default, 'NULL') === 0) {
2✔
404
            return null;
×
405
        }
406

407
        // Handle string literals - remove quotes and unescape
408
        if (preg_match("/^'(.*)'$/s", $default, $matches)) {
2✔
409
            return str_replace("''", "'", $matches[1]);
×
410
        }
411

412
        return $default;
2✔
413
    }
414

415
    /**
416
     * Begin Transaction
417
     */
418
    protected function _transBegin(): bool
419
    {
420
        return sqlsrv_begin_transaction($this->connID);
19✔
421
    }
422

423
    /**
424
     * Commit Transaction
425
     */
426
    protected function _transCommit(): bool
427
    {
428
        return sqlsrv_commit($this->connID);
5✔
429
    }
430

431
    /**
432
     * Rollback Transaction
433
     */
434
    protected function _transRollback(): bool
435
    {
436
        return sqlsrv_rollback($this->connID);
19✔
437
    }
438

439
    /**
440
     * Returns the last error code and message.
441
     * Must return this format: ['code' => string|int, 'message' => string]
442
     * intval(code) === 0 means "no error".
443
     *
444
     * @return array<string, int|string>
445
     */
446
    public function error(): array
447
    {
448
        $error = [
2✔
449
            'code'    => '00000',
2✔
450
            'message' => '',
2✔
451
        ];
2✔
452

453
        $sqlsrvErrors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
2✔
454

455
        if (! is_array($sqlsrvErrors)) {
2✔
456
            return $error;
2✔
457
        }
458

UNCOV
459
        $sqlsrvError = array_shift($sqlsrvErrors);
×
UNCOV
460
        if (isset($sqlsrvError['SQLSTATE'])) {
×
UNCOV
461
            $error['code'] = isset($sqlsrvError['code']) ? $sqlsrvError['SQLSTATE'] . '/' . $sqlsrvError['code'] : $sqlsrvError['SQLSTATE'];
×
462
        } elseif (isset($sqlsrvError['code'])) {
×
463
            $error['code'] = $sqlsrvError['code'];
×
464
        }
465

UNCOV
466
        if (isset($sqlsrvError['message'])) {
×
UNCOV
467
            $error['message'] = $sqlsrvError['message'];
×
468
        }
469

UNCOV
470
        return $error;
×
471
    }
472

473
    /**
474
     * Returns the total number of rows affected by this query.
475
     */
476
    public function affectedRows(): int
477
    {
478
        if ($this->resultID === false) {
50✔
479
            return 0;
1✔
480
        }
481

482
        return sqlsrv_rows_affected($this->resultID);
49✔
483
    }
484

485
    /**
486
     * Select a specific database table to use.
487
     *
488
     * @return bool
489
     */
490
    public function setDatabase(?string $databaseName = null)
491
    {
492
        if ($databaseName === null || $databaseName === '') {
×
493
            $databaseName = $this->database;
×
494
        }
495

496
        if (empty($this->connID)) {
×
497
            $this->initialize();
×
498
        }
499

500
        if ($this->execute('USE ' . $this->_escapeString($databaseName))) {
×
501
            $this->database  = $databaseName;
×
502
            $this->dataCache = [];
×
503

504
            return true;
×
505
        }
506

507
        return false;
×
508
    }
509

510
    /**
511
     * Executes the query against the database.
512
     *
513
     * @return false|resource
514
     */
515
    protected function execute(string $sql)
516
    {
517
        $stmt = ($this->scrollable === false || $this->isWriteType($sql))
764✔
518
            ? sqlsrv_query($this->connID, $sql)
727✔
519
            : sqlsrv_query($this->connID, $sql, [], ['Scrollable' => $this->scrollable]);
763✔
520

521
        if ($stmt === false) {
764✔
522
            $trace = debug_backtrace();
33✔
523
            $first = array_shift($trace);
33✔
524

525
            log_message('error', "{message}\nin {exFile} on line {exLine}.\n{trace}", [
33✔
526
                'message' => $this->getAllErrorMessages(),
33✔
527
                'exFile'  => clean_path($first['file']),
33✔
528
                'exLine'  => $first['line'],
33✔
529
                'trace'   => render_backtrace($trace),
33✔
530
            ]);
33✔
531

532
            if ($this->DBDebug) {
33✔
533
                throw new DatabaseException($this->getAllErrorMessages());
15✔
534
            }
535
        }
536

537
        return $stmt;
764✔
538
    }
539

540
    /**
541
     * Returns the last error encountered by this connection.
542
     *
543
     * @return array<string, int|string>
544
     *
545
     * @deprecated Use `error()` instead.
546
     */
547
    public function getError()
548
    {
549
        $error = [
×
550
            'code'    => '00000',
×
551
            'message' => '',
×
552
        ];
×
553

554
        $sqlsrvErrors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
×
555

556
        if (! is_array($sqlsrvErrors)) {
×
557
            return $error;
×
558
        }
559

560
        $sqlsrvError = array_shift($sqlsrvErrors);
×
561
        if (isset($sqlsrvError['SQLSTATE'])) {
×
562
            $error['code'] = isset($sqlsrvError['code']) ? $sqlsrvError['SQLSTATE'] . '/' . $sqlsrvError['code'] : $sqlsrvError['SQLSTATE'];
×
563
        } elseif (isset($sqlsrvError['code'])) {
×
564
            $error['code'] = $sqlsrvError['code'];
×
565
        }
566

567
        if (isset($sqlsrvError['message'])) {
×
568
            $error['message'] = $sqlsrvError['message'];
×
569
        }
570

571
        return $error;
×
572
    }
573

574
    /**
575
     * The name of the platform in use (MySQLi, mssql, etc)
576
     */
577
    public function getPlatform(): string
578
    {
579
        return $this->DBDriver;
10✔
580
    }
581

582
    /**
583
     * Returns a string containing the version of the database being used.
584
     */
585
    public function getVersion(): string
586
    {
587
        $info = [];
3✔
588
        if (isset($this->dataCache['version'])) {
3✔
589
            return $this->dataCache['version'];
2✔
590
        }
591

592
        if (! $this->connID) {
1✔
593
            $this->initialize();
1✔
594
        }
595

596
        if (($info = sqlsrv_server_info($this->connID)) === []) {
1✔
597
            return '';
×
598
        }
599

600
        return isset($info['SQLServerVersion']) ? $this->dataCache['version'] = $info['SQLServerVersion'] : '';
1✔
601
    }
602

603
    /**
604
     * Determines if a query is a "write" type.
605
     *
606
     * Overrides BaseConnection::isWriteType, adding additional read query types.
607
     *
608
     * @param string $sql
609
     */
610
    public function isWriteType($sql): bool
611
    {
612
        if (preg_match('/^\s*"?(EXEC\s*sp_rename)\s/i', $sql)) {
764✔
613
            return true;
3✔
614
        }
615

616
        return parent::isWriteType($sql);
764✔
617
    }
618
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc