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

codeigniter4 / CodeIgniter4 / 8677009716

13 Apr 2024 11:45PM UTC coverage: 84.44% (-2.2%) from 86.607%
8677009716

push

github

web-flow
Merge pull request #8776 from kenjis/fix-findQualifiedNameFromPath-Cannot-declare-class-v3

fix: Cannot declare class CodeIgniter\Config\Services, because the name is already in use

0 of 3 new or added lines in 1 file covered. (0.0%)

478 existing lines in 72 files now uncovered.

20318 of 24062 relevant lines covered (84.44%)

188.23 hits per line

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

78.26
/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 stdClass;
19

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

141
            return $this->connID;
18✔
142
        }
143

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

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

156
        foreach (sqlsrv_errors() as $error) {
2✔
157
            $errors[] = $error['message']
2✔
158
                . ' SQLSTATE: ' . $error['SQLSTATE'] . ', code: ' . $error['code'];
2✔
159
        }
160

161
        return implode("\n", $errors);
2✔
162
    }
163

164
    /**
165
     * Keep or establish the connection if no queries have been sent for
166
     * a length of time exceeding the server's idle timeout.
167
     */
168
    public function reconnect()
169
    {
170
        $this->close();
×
171
        $this->initialize();
×
172
    }
173

174
    /**
175
     * Close the database connection.
176
     */
177
    protected function _close()
178
    {
179
        sqlsrv_close($this->connID);
1✔
180
    }
181

182
    /**
183
     * Platform-dependant string escape
184
     */
185
    protected function _escapeString(string $str): string
186
    {
187
        return str_replace("'", "''", remove_invisible_characters($str, false));
621✔
188
    }
189

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

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

210
        if ($tableName !== null) {
569✔
211
            return $sql .= ' AND [TABLE_NAME] LIKE ' . $this->escape($tableName);
569✔
212
        }
213

214
        if ($prefixLimit === true && $this->DBPrefix !== '') {
28✔
215
            $sql .= " AND [TABLE_NAME] LIKE '" . $this->escapeLikeString($this->DBPrefix) . "%' "
×
216
                . sprintf($this->likeEscapeStr, $this->likeEscapeChar);
×
217
        }
218

219
        return $sql;
28✔
220
    }
221

222
    /**
223
     * Generates a platform-specific query string so that the column names can be fetched.
224
     */
225
    protected function _listColumns(string $table = ''): string
226
    {
227
        return 'SELECT [COLUMN_NAME] '
8✔
228
            . ' FROM [INFORMATION_SCHEMA].[COLUMNS]'
8✔
229
            . ' WHERE  [TABLE_NAME] = ' . $this->escape($this->DBPrefix . $table)
8✔
230
            . ' AND [TABLE_SCHEMA] = ' . $this->escape($this->schema);
8✔
231
    }
232

233
    /**
234
     * Returns an array of objects with index data
235
     *
236
     * @return array<string, stdClass>
237
     *
238
     * @throws DatabaseException
239
     */
240
    protected function _indexData(string $table): array
241
    {
242
        $sql = 'EXEC sp_helpindex ' . $this->escape($this->schema . '.' . $table);
38✔
243

244
        if (($query = $this->query($sql)) === false) {
38✔
245
            throw new DatabaseException(lang('Database.failGetIndexData'));
×
246
        }
247
        $query = $query->getResultObject();
38✔
248

249
        $retVal = [];
38✔
250

251
        foreach ($query as $row) {
38✔
252
            $obj       = new stdClass();
27✔
253
            $obj->name = $row->index_name;
27✔
254

255
            $_fields     = explode(',', trim($row->index_keys));
27✔
256
            $obj->fields = array_map(static fn ($v) => trim($v), $_fields);
27✔
257

258
            if (str_contains($row->index_description, 'primary key located on')) {
27✔
259
                $obj->type = 'PRIMARY';
25✔
260
            } else {
261
                $obj->type = (str_contains($row->index_description, 'nonclustered, unique')) ? 'UNIQUE' : 'INDEX';
17✔
262
            }
263

264
            $retVal[$obj->name] = $obj;
27✔
265
        }
266

267
        return $retVal;
38✔
268
    }
269

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

296
        if (($query = $this->query($sql)) === false) {
5✔
297
            throw new DatabaseException(lang('Database.failGetForeignKeyData'));
×
298
        }
299

300
        $query   = $query->getResultObject();
5✔
301
        $indexes = [];
5✔
302

303
        foreach ($query as $row) {
5✔
304
            $indexes[$row->constraint_name]['constraint_name']       = $row->constraint_name;
4✔
305
            $indexes[$row->constraint_name]['table_name']            = $row->table_name;
4✔
306
            $indexes[$row->constraint_name]['column_name'][]         = $row->column_name;
4✔
307
            $indexes[$row->constraint_name]['foreign_table_name']    = $row->foreign_table_name;
4✔
308
            $indexes[$row->constraint_name]['foreign_column_name'][] = $row->foreign_column_name;
4✔
309
            $indexes[$row->constraint_name]['on_delete']             = $row->delete_rule;
4✔
310
            $indexes[$row->constraint_name]['on_update']             = $row->update_rule;
4✔
311
            $indexes[$row->constraint_name]['match']                 = $row->match_option;
4✔
312
        }
313

314
        return $this->foreignKeyDataToObjects($indexes);
5✔
315
    }
316

317
    /**
318
     * Disables foreign key checks temporarily.
319
     *
320
     * @return string
321
     */
322
    protected function _disableForeignKeyChecks()
323
    {
324
        return 'EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT ALL"';
574✔
325
    }
326

327
    /**
328
     * Enables foreign key checks temporarily.
329
     *
330
     * @return string
331
     */
332
    protected function _enableForeignKeyChecks()
333
    {
334
        return 'EXEC sp_MSforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL"';
574✔
335
    }
336

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

352
        if (($query = $this->query($sql)) === false) {
12✔
353
            throw new DatabaseException(lang('Database.failGetFieldData'));
×
354
        }
355

356
        $query  = $query->getResultObject();
12✔
357
        $retVal = [];
12✔
358

359
        for ($i = 0, $c = count($query); $i < $c; $i++) {
12✔
360
            $retVal[$i] = new stdClass();
12✔
361

362
            $retVal[$i]->name = $query[$i]->COLUMN_NAME;
12✔
363
            $retVal[$i]->type = $query[$i]->DATA_TYPE;
12✔
364

365
            $retVal[$i]->max_length = $query[$i]->CHARACTER_MAXIMUM_LENGTH > 0
12✔
366
                ? $query[$i]->CHARACTER_MAXIMUM_LENGTH
11✔
367
                : $query[$i]->NUMERIC_PRECISION;
9✔
368

369
            $retVal[$i]->nullable = $query[$i]->IS_NULLABLE !== 'NO';
12✔
370
            $retVal[$i]->default  = $query[$i]->COLUMN_DEFAULT;
12✔
371
        }
372

373
        return $retVal;
12✔
374
    }
375

376
    /**
377
     * Begin Transaction
378
     */
379
    protected function _transBegin(): bool
380
    {
381
        return sqlsrv_begin_transaction($this->connID);
14✔
382
    }
383

384
    /**
385
     * Commit Transaction
386
     */
387
    protected function _transCommit(): bool
388
    {
389
        return sqlsrv_commit($this->connID);
3✔
390
    }
391

392
    /**
393
     * Rollback Transaction
394
     */
395
    protected function _transRollback(): bool
396
    {
397
        return sqlsrv_rollback($this->connID);
14✔
398
    }
399

400
    /**
401
     * Returns the last error code and message.
402
     * Must return this format: ['code' => string|int, 'message' => string]
403
     * intval(code) === 0 means "no error".
404
     *
405
     * @return array<string, int|string>
406
     */
407
    public function error(): array
408
    {
409
        $error = [
29✔
410
            'code'    => '00000',
29✔
411
            'message' => '',
29✔
412
        ];
29✔
413

414
        $sqlsrvErrors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
29✔
415

416
        if (! is_array($sqlsrvErrors)) {
29✔
417
            return $error;
2✔
418
        }
419

420
        $sqlsrvError = array_shift($sqlsrvErrors);
27✔
421
        if (isset($sqlsrvError['SQLSTATE'])) {
27✔
422
            $error['code'] = isset($sqlsrvError['code']) ? $sqlsrvError['SQLSTATE'] . '/' . $sqlsrvError['code'] : $sqlsrvError['SQLSTATE'];
27✔
423
        } elseif (isset($sqlsrvError['code'])) {
×
424
            $error['code'] = $sqlsrvError['code'];
×
425
        }
426

427
        if (isset($sqlsrvError['message'])) {
27✔
428
            $error['message'] = $sqlsrvError['message'];
27✔
429
        }
430

431
        return $error;
27✔
432
    }
433

434
    /**
435
     * Returns the total number of rows affected by this query.
436
     */
437
    public function affectedRows(): int
438
    {
439
        return sqlsrv_rows_affected($this->resultID);
46✔
440
    }
441

442
    /**
443
     * Select a specific database table to use.
444
     *
445
     * @return bool
446
     */
447
    public function setDatabase(?string $databaseName = null)
448
    {
449
        if ($databaseName === null || $databaseName === '') {
×
450
            $databaseName = $this->database;
×
451
        }
452

453
        if (empty($this->connID)) {
×
454
            $this->initialize();
×
455
        }
456

457
        if ($this->execute('USE ' . $this->_escapeString($databaseName))) {
×
458
            $this->database  = $databaseName;
×
459
            $this->dataCache = [];
×
460

461
            return true;
×
462
        }
463

464
        return false;
×
465
    }
466

467
    /**
468
     * Executes the query against the database.
469
     *
470
     * @return false|resource
471
     */
472
    protected function execute(string $sql)
473
    {
474
        $stmt = ($this->scrollable === false || $this->isWriteType($sql)) ?
643✔
475
            sqlsrv_query($this->connID, $sql) :
612✔
476
            sqlsrv_query($this->connID, $sql, [], ['Scrollable' => $this->scrollable]);
643✔
477

478
        if ($stmt === false) {
643✔
479
            $error = $this->error();
27✔
480

481
            log_message('error', $error['message']);
27✔
482

483
            if ($this->DBDebug) {
27✔
484
                throw new DatabaseException($error['message']);
11✔
485
            }
486
        }
487

488
        return $stmt;
643✔
489
    }
490

491
    /**
492
     * Returns the last error encountered by this connection.
493
     *
494
     * @return array<string, int|string>
495
     *
496
     * @deprecated Use `error()` instead.
497
     */
498
    public function getError()
499
    {
UNCOV
500
        $error = [
×
UNCOV
501
            'code'    => '00000',
×
UNCOV
502
            'message' => '',
×
UNCOV
503
        ];
×
504

UNCOV
505
        $sqlsrvErrors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
×
506

UNCOV
507
        if (! is_array($sqlsrvErrors)) {
×
UNCOV
508
            return $error;
×
509
        }
510

UNCOV
511
        $sqlsrvError = array_shift($sqlsrvErrors);
×
UNCOV
512
        if (isset($sqlsrvError['SQLSTATE'])) {
×
UNCOV
513
            $error['code'] = isset($sqlsrvError['code']) ? $sqlsrvError['SQLSTATE'] . '/' . $sqlsrvError['code'] : $sqlsrvError['SQLSTATE'];
×
UNCOV
514
        } elseif (isset($sqlsrvError['code'])) {
×
UNCOV
515
            $error['code'] = $sqlsrvError['code'];
×
516
        }
517

UNCOV
518
        if (isset($sqlsrvError['message'])) {
×
UNCOV
519
            $error['message'] = $sqlsrvError['message'];
×
520
        }
521

UNCOV
522
        return $error;
×
523
    }
524

525
    /**
526
     * The name of the platform in use (MySQLi, mssql, etc)
527
     */
528
    public function getPlatform(): string
529
    {
530
        return $this->DBDriver;
10✔
531
    }
532

533
    /**
534
     * Returns a string containing the version of the database being used.
535
     */
536
    public function getVersion(): string
537
    {
538
        $info = [];
3✔
539
        if (isset($this->dataCache['version'])) {
3✔
540
            return $this->dataCache['version'];
1✔
541
        }
542

543
        if (! $this->connID || ($info = sqlsrv_server_info($this->connID)) === []) {
2✔
544
            $this->initialize();
×
545
        }
546

547
        return isset($info['SQLServerVersion']) ? $this->dataCache['version'] = $info['SQLServerVersion'] : false;
2✔
548
    }
549

550
    /**
551
     * Determines if a query is a "write" type.
552
     *
553
     * Overrides BaseConnection::isWriteType, adding additional read query types.
554
     *
555
     * @param string $sql
556
     */
557
    public function isWriteType($sql): bool
558
    {
559
        if (preg_match('/^\s*"?(EXEC\s*sp_rename)\s/i', $sql)) {
643✔
560
            return true;
3✔
561
        }
562

563
        return parent::isWriteType($sql);
643✔
564
    }
565
}
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