-
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathMysqlDriver.php
More file actions
817 lines (703 loc) · 23.6 KB
/
MysqlDriver.php
File metadata and controls
817 lines (703 loc) · 23.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
<?php
/**
* Part of the Joomla Framework Database Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Database\Mysql;
use Joomla\Database\Exception\ConnectionFailureException;
use Joomla\Database\Pdo\PdoDriver;
use Joomla\Database\UTF8MB4SupportInterface;
/**
* MySQL database driver supporting PDO based connections
*
* @link https://www.php.net/manual/en/ref.pdo-mysql.php
* @since 1.0
*/
class MysqlDriver extends PdoDriver implements UTF8MB4SupportInterface
{
/**
* The name of the database driver.
*
* @var string
* @since 1.0
*/
public $name = 'mysql';
/**
* The character(s) used to quote SQL statement names such as table names or field names, etc.
*
* If a single character string the same character is used for both sides of the quoted name, else the first character will be used for the
* opening quote and the second for the closing quote.
*
* @var string
* @since 1.0
*/
protected $nameQuote = '`';
/**
* The null or zero representation of a timestamp for the database driver.
*
* @var string
* @since 1.0
*/
protected $nullDate = '0000-00-00 00:00:00';
/**
* True if the database engine supports UTF-8 Multibyte (utf8mb4) character encoding.
*
* @var boolean
* @since 1.4.0
*/
protected $utf8mb4 = false;
/**
* True if the database engine is MariaDB.
*
* @var boolean
* @since 2.0.0
*/
protected $mariadb = false;
/**
* The minimum supported database version.
*
* @var string
* @since 1.0
*/
protected static $dbMinimum = '5.6';
/**
* The minimum supported MariaDB database version.
*
* @var string
* @since 2.0.0
*/
protected static $dbMinMariadb = '10.0';
/**
* The default cipher suite for TLS connections.
*
* @var array
* @since 2.0.0
*/
protected static $defaultCipherSuite = [
'AES128-GCM-SHA256',
'AES256-GCM-SHA384',
'AES128-CBC-SHA256',
'AES256-CBC-SHA384',
'DES-CBC3-SHA',
];
/**
* The default charset.
*
* @var string
* @since 2.0.0
*/
public $charset = 'utf8';
/**
* The database server version.
*
* @var string
* @since __DEPLOY_VERSION__
*/
protected $serverVersion;
/**
* Constructor.
*
* @param array $options Array of database options with keys: host, user, password, database, select.
*
* @since 1.0
*/
public function __construct(array $options)
{
/**
* sql_mode to MySql 5.7.8+ default strict mode minus ONLY_FULL_GROUP_BY
*
* @link https://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-8.html#mysqld-5-7-8-sql-mode
*/
$sqlModes = [
'STRICT_TRANS_TABLES',
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_ENGINE_SUBSTITUTION',
];
// Get some basic values from the options.
$options['driver'] = 'mysql';
$options['charset'] = $options['charset'] ?? 'utf8';
$options['sqlModes'] = isset($options['sqlModes']) ? (array) $options['sqlModes'] : $sqlModes;
$this->charset = $options['charset'];
/*
* Pre-populate the UTF-8 Multibyte compatibility flag. Unfortunately PDO won't report the server version unless we're connected to it,
* and we cannot connect to it unless we know if it supports utf8mb4, which requires us knowing the server version. Because of this
* chicken and egg issue, we _assume_ it's supported and we'll just catch any problems at connection time.
*/
$this->utf8mb4 = $options['charset'] === 'utf8mb4';
// Finalize initialisation.
parent::__construct($options);
}
/**
* Connects to the database if needed.
*
* @return void Returns void if the database connected successfully.
*
* @since 1.0
* @throws \RuntimeException
*/
public function connect()
{
if ($this->getConnection()) {
return;
}
// For SSL/TLS connection encryption.
if ($this->options['ssl'] !== [] && $this->options['ssl']['enable'] === true) {
$sslContextIsNull = true;
// If customised, add cipher suite, ca file path, ca path, private key file path and certificate file path to PDO driver options.
foreach (['cipher', 'ca', 'capath', 'key', 'cert'] as $key => $value) {
if ($this->options['ssl'][$value] !== null) {
$this->options['driverOptions'][constant('\PDO::MYSQL_ATTR_SSL_' . strtoupper($value))] = $this->options['ssl'][$value];
$sslContextIsNull = false;
}
}
// PDO, if no cipher, ca, capath, cert and key are set, can't start TLS one-way connection, set a common ciphers suite to force it.
if ($sslContextIsNull === true) {
$this->options['driverOptions'][\PDO::MYSQL_ATTR_SSL_CIPHER] = implode(':', static::$defaultCipherSuite);
}
// If customised, for capable systems (PHP 7.0.14+ and 7.1.4+) verify certificate chain and Common Name to driver options.
if ($this->options['ssl']['verify_server_cert'] !== null && defined('\PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT')) {
$this->options['driverOptions'][\PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT] = $this->options['ssl']['verify_server_cert'];
}
}
try {
// Try to connect to MySQL
parent::connect();
} catch (ConnectionFailureException $e) {
// If the connection failed, but not because of the wrong character set, then bubble up the exception.
if (!$this->utf8mb4) {
throw $e;
}
/*
* Otherwise, try connecting again without using utf8mb4 and see if maybe that was the problem. If the connection succeeds, then we
* will have learned that the client end of the connection does not support utf8mb4.
*/
$this->utf8mb4 = false;
$this->options['charset'] = 'utf8';
parent::connect();
}
$serverVersion = $this->getVersion();
$this->mariadb = stripos($serverVersion, 'mariadb') !== false;
if ($this->utf8mb4) {
// At this point we know the client supports utf8mb4. Now we must check if the server supports utf8mb4 as well.
$this->utf8mb4 = version_compare($serverVersion, '5.5.3', '>=');
if ($this->mariadb && version_compare($serverVersion, '10.0.0', '<')) {
$this->utf8mb4 = false;
}
if (!$this->utf8mb4) {
// Reconnect with the utf8 character set.
parent::disconnect();
$this->options['charset'] = 'utf8';
parent::connect();
}
}
// If needed, set the sql modes.
if ($this->options['sqlModes'] !== []) {
$this->connection->query('SET @@SESSION.sql_mode = \'' . implode(',', $this->options['sqlModes']) . '\';');
}
$this->setOption(\PDO::ATTR_EMULATE_PREPARES, true);
}
/**
* Automatically downgrade a CREATE TABLE or ALTER TABLE query from utf8mb4 (UTF-8 Multibyte) to plain utf8.
*
* Used when the server doesn't support UTF-8 Multibyte.
*
* @param string $query The query to convert
*
* @return string The converted query
*
* @since 1.4.0
*/
public function convertUtf8mb4QueryToUtf8($query)
{
if ($this->hasUTF8mb4Support()) {
return $query;
}
// If it's not an ALTER TABLE or CREATE TABLE command there's nothing to convert
$beginningOfQuery = substr($query, 0, 12);
$beginningOfQuery = strtoupper($beginningOfQuery);
if (!\in_array($beginningOfQuery, ['ALTER TABLE ', 'CREATE TABLE'], true)) {
return $query;
}
// Replace utf8mb4 with utf8
return str_replace('utf8mb4', 'utf8', $query);
}
/**
* Test to see if the MySQL connector is available.
*
* @return boolean True on success, false otherwise.
*
* @since 1.0
*/
public static function isSupported()
{
return class_exists('\\PDO') && \in_array('mysql', \PDO::getAvailableDrivers(), true);
}
/**
* Select a database for use.
*
* @param string $database The name of the database to select for use.
*
* @return boolean
*
* @since 1.0
* @throws \RuntimeException
*/
public function select($database)
{
$this->connect();
$this->setQuery('USE ' . $this->quoteName($database))
->execute();
return true;
}
/**
* Return the query string to alter the database character set.
*
* @param string $dbName The database name
*
* @return string The query that alter the database query string
*
* @since 2.0.0
*/
public function getAlterDbCharacterSet($dbName)
{
$charset = $this->utf8mb4 ? 'utf8mb4' : 'utf8';
return 'ALTER DATABASE ' . $this->quoteName($dbName) . ' CHARACTER SET `' . $charset . '`';
}
/**
* Method to get the database collation in use by sampling a text field of a table in the database.
*
* @return string|boolean The collation in use by the database (string) or boolean false if not supported.
*
* @since 1.0
* @throws \RuntimeException
*/
public function getCollation()
{
$this->connect();
return $this->setQuery('SELECT @@collation_database;')->loadResult();
}
/**
* Method to get the database connection collation in use by sampling a text field of a table in the database.
*
* @return string|boolean The collation in use by the database connection (string) or boolean false if not supported.
*
* @since 1.6.0
* @throws \RuntimeException
*/
public function getConnectionCollation()
{
$this->connect();
return $this->setQuery('SELECT @@collation_connection;')->loadResult();
}
/**
* Method to get the database encryption details (cipher and protocol) in use.
*
* @return string The database encryption details.
*
* @since 2.0.0
* @throws \RuntimeException
*/
public function getConnectionEncryption(): string
{
$this->connect();
$variables = $this->setQuery('SHOW SESSION STATUS WHERE `Variable_name` IN (\'Ssl_version\', \'Ssl_cipher\')')
->loadObjectList('Variable_name');
if (!empty($variables['Ssl_cipher']->Value)) {
return $variables['Ssl_version']->Value . ' (' . $variables['Ssl_cipher']->Value . ')';
}
return '';
}
/**
* Method to test if the database TLS connections encryption are supported.
*
* @return boolean Whether the database supports TLS connections encryption.
*
* @since 2.0.0
*/
public function isConnectionEncryptionSupported(): bool
{
$this->connect();
$variables = $this->setQuery('SHOW SESSION VARIABLES WHERE `Variable_name` IN (\'have_ssl\')')->loadObjectList('Variable_name');
return !empty($variables['have_ssl']->Value) && $variables['have_ssl']->Value === 'YES';
}
/**
* Return the query string to create new Database.
*
* @param \stdClass $options Object used to pass user and database name to database driver. This object must have "db_name" and "db_user" set.
* @param boolean $utf True if the database supports the UTF-8 character set.
*
* @return string The query that creates database
*
* @since 2.0.0
*/
protected function getCreateDatabaseQuery($options, $utf)
{
if ($utf) {
$charset = $this->utf8mb4 ? 'utf8mb4' : 'utf8';
$collation = $charset . '_unicode_ci';
return 'CREATE DATABASE ' . $this->quoteName($options->db_name) . ' CHARACTER SET `' . $charset . '` COLLATE `' . $collation . '`';
}
return 'CREATE DATABASE ' . $this->quoteName($options->db_name);
}
/**
* Shows the table CREATE statement that creates the given tables.
*
* @param array|string $tables A table name or a list of table names.
*
* @return array A list of the create SQL for the tables.
*
* @since 1.0
* @throws \RuntimeException
*/
public function getTableCreate($tables)
{
$this->connect();
// Initialise variables.
$result = [];
// Sanitize input to an array and iterate over the list.
$tables = (array) $tables;
foreach ($tables as $table) {
$row = $this->setQuery('SHOW CREATE TABLE ' . $this->quoteName($table))->loadRow();
// Populate the result array based on the create statements.
$result[$table] = $row[1];
}
return $result;
}
/**
* Retrieves field information about a given table.
*
* @param string $table The name of the database table.
* @param boolean $typeOnly True to only return field types.
*
* @return array An array of fields for the database table.
*
* @since 1.0
* @throws \RuntimeException
*/
public function getTableColumns($table, $typeOnly = true)
{
$this->connect();
$result = [];
// Set the query to get the table fields statement.
$fields = $this->setQuery('SHOW FULL COLUMNS FROM ' . $this->quoteName($table))->loadObjectList();
// If we only want the type as the value add just that to the list.
if ($typeOnly) {
foreach ($fields as $field) {
$result[$field->Field] = preg_replace('/[(0-9)]/', '', $field->Type);
}
} else {
// If we want the whole field data object add that to the list.
foreach ($fields as $field) {
$result[$field->Field] = $field;
}
}
return $result;
}
/**
* Get the details list of keys for a table.
*
* @param string $table The name of the table.
*
* @return array An array of the column specification for the table.
*
* @since 1.0
* @throws \RuntimeException
*/
public function getTableKeys($table)
{
$this->connect();
// Get the details columns information.
return $this->setQuery('SHOW KEYS FROM ' . $this->quoteName($table))->loadObjectList();
}
/**
* Method to get an array of all tables in the database.
*
* @return array An array of all the tables in the database.
*
* @since 1.0
* @throws \RuntimeException
*/
public function getTableList()
{
$this->connect();
// Set the query to get the tables statement and not the views.
return $this->setQuery('SHOW FULL TABLES WHERE table_type="BASE TABLE"')->loadColumn();
}
/**
* Get the version of the database server.
*
* @return string The database server version.
*
* @since 2.0.0
*/
public function getVersion()
{
if (!isset($this->serverVersion)) {
$this->connect();
$this->serverVersion = $this->setQuery('SELECT @@version;')->loadResult();
if (stripos($this->serverVersion, 'mariadb') !== false) {
// MariaDB: Strip off any leading '5.5.5-', if present
$this->serverVersion = preg_replace('/^5\.5\.5-/', '', $this->serverVersion);
}
}
return $this->serverVersion;
}
/**
* Get the minimum supported database version.
*
* @return string
*
* @since 2.0.0
*/
public function getMinimum()
{
return $this->mariadb ? static::$dbMinMariadb : static::$dbMinimum;
}
/**
* Get the null or zero representation of a timestamp for the database driver.
*
* @return string
*
* @since 2.0.0
*/
public function getNullDate()
{
// Check the session sql mode;
if (\in_array('NO_ZERO_DATE', $this->options['sqlModes']) !== false) {
$this->nullDate = '1000-01-01 00:00:00';
}
return $this->nullDate;
}
/**
* Determine whether the database engine support the UTF-8 Multibyte (utf8mb4) character encoding.
*
* @return boolean True if the database engine supports UTF-8 Multibyte.
*
* @since 2.0.0
*/
public function hasUTF8mb4Support()
{
return $this->utf8mb4;
}
/**
* Determine if the database engine is MariaDB.
*
* @return boolean
*
* @since 2.0.0
*/
public function isMariaDb(): bool
{
$this->connect();
return $this->mariadb;
}
/**
* Locks a table in the database.
*
* @param string $table The name of the table to unlock.
*
* @return $this
*
* @since 1.0
* @throws \RuntimeException
*/
public function lockTable($table)
{
$this->setQuery('LOCK TABLES ' . $this->quoteName($table) . ' WRITE')
->execute();
return $this;
}
/**
* Renames a table in the database.
*
* @param string $oldTable The name of the table to be renamed
* @param string $newTable The new name for the table.
* @param string $backup Not used by MySQL.
* @param string $prefix Not used by MySQL.
*
* @return $this
*
* @since 1.0
* @throws \RuntimeException
*/
public function renameTable($oldTable, $newTable, $backup = null, $prefix = null)
{
$this->setQuery('RENAME TABLE ' . $this->quoteName($oldTable) . ' TO ' . $this->quoteName($newTable))
->execute();
return $this;
}
/**
* Inserts a row into a table based on an object's properties.
*
* @param string $table The name of the database table to insert into.
* @param object $object A reference to an object whose public properties match the table fields.
* @param string $key The name of the primary key. If provided the object property is updated.
*
* @return boolean
*
* @since 2.0.0
* @throws \RuntimeException
*/
public function insertObject($table, &$object, $key = null)
{
$fields = [];
$values = [];
$tableColumns = $this->getTableColumns($table);
// Iterate over the object variables to build the query fields and values.
foreach (get_object_vars($object) as $k => $v) {
// Skip columns that don't exist in the table.
if (!array_key_exists($k, $tableColumns)) {
continue;
}
// Only process non-null scalars.
if (\is_array($v) || \is_object($v) || $v === null) {
continue;
}
// Ignore any internal fields.
if ($k[0] === '_') {
continue;
}
// Ignore null datetime fields.
if ($tableColumns[$k] === 'datetime' && empty($v)) {
continue;
}
// Ignore null integer fields.
if (stristr($tableColumns[$k], 'int') !== false && $v === '') {
continue;
}
// Prepare and sanitize the fields and values for the database query.
$fields[] = $this->quoteName($k);
$values[] = $this->quote($v);
}
// Create the base insert statement.
$query = $this->createQuery()
->insert($this->quoteName($table))
->columns($fields)
->values(implode(',', $values));
// Set the query and execute the insert.
$this->setQuery($query)->execute();
// Update the primary key if it exists.
$id = $this->insertid();
if ($key && $id && \is_string($key)) {
$object->$key = $id;
}
return true;
}
/**
* Method to escape a string for usage in an SQL statement.
*
* Oracle escaping reference:
* http://www.orafaq.com/wiki/SQL_FAQ#How_does_one_escape_special_characters_when_writing_SQL_queries.3F
*
* SQLite escaping notes:
* http://www.sqlite.org/faq.html#q14
*
* Method body is as implemented by the Zend Framework
*
* Note: Using query objects with bound variables is preferable to the below.
*
* @param string $text The string to be escaped.
* @param boolean $extra Unused optional parameter to provide extra escaping.
*
* @return string The escaped string.
*
* @since 1.0
*/
public function escape($text, $extra = false)
{
if (\is_int($text)) {
return $text;
}
if (\is_float($text)) {
// Force the dot as a decimal point.
return str_replace(',', '.', (string) $text);
}
$this->connect();
$result = substr($this->connection->quote($text), 1, -1);
if ($extra) {
$result = addcslashes($result, '%_');
}
return $result;
}
/**
* Unlocks tables in the database.
*
* @return $this
*
* @since 1.0
* @throws \RuntimeException
*/
public function unlockTables()
{
$this->setQuery('UNLOCK TABLES')
->execute();
return $this;
}
/**
* Method to commit a transaction.
*
* @param boolean $toSavepoint If true, commit to the last savepoint.
*
* @return void
*
* @since 1.0
* @throws \RuntimeException
*/
public function transactionCommit($toSavepoint = false)
{
$this->connect();
if (!$toSavepoint || $this->transactionDepth <= 1) {
parent::transactionCommit($toSavepoint);
} else {
$this->transactionDepth--;
}
}
/**
* Method to roll back a transaction.
*
* @param boolean $toSavepoint If true, rollback to the last savepoint.
*
* @return void
*
* @since 1.0
* @throws \RuntimeException
*/
public function transactionRollback($toSavepoint = false)
{
$this->connect();
if (!$toSavepoint || $this->transactionDepth <= 1) {
parent::transactionRollback($toSavepoint);
} else {
$savepoint = 'SP_' . ($this->transactionDepth - 1);
$this->setQuery('ROLLBACK TO SAVEPOINT ' . $this->quoteName($savepoint));
if ($this->execute()) {
$this->transactionDepth--;
}
}
}
/**
* Method to initialize a transaction.
*
* @param boolean $asSavepoint If true and a transaction is already active, a savepoint will be created.
*
* @return void
*
* @since 1.0
* @throws \RuntimeException
*/
public function transactionStart($asSavepoint = false)
{
$this->connect();
if (!$asSavepoint || !$this->transactionDepth) {
parent::transactionStart($asSavepoint);
} else {
$savepoint = 'SP_' . $this->transactionDepth;
$this->setQuery('SAVEPOINT ' . $this->quoteName($savepoint));
if ($this->execute()) {
$this->transactionDepth++;
}
}
}
}