-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
DatabaseDriver.php
2016 lines (1749 loc) · 43.9 KB
/
DatabaseDriver.php
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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Part of the Joomla Framework Database Package
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Database;
use Joomla\Database\Event\ConnectionEvent;
use Joomla\Database\Exception\ConnectionFailureException;
use Joomla\Database\Exception\ExecutionFailureException;
use Joomla\Database\Exception\PrepareStatementFailureException;
use Joomla\Event\DispatcherAwareInterface;
use Joomla\Event\DispatcherAwareTrait;
use Joomla\Event\EventInterface;
/**
* Joomla Framework Database Driver Class
*
* @since 1.0
*/
abstract class DatabaseDriver implements DatabaseInterface, DispatcherAwareInterface
{
use DispatcherAwareTrait;
/**
* The name of the database.
*
* @var string
* @since 1.0
*/
private $database;
/**
* The name of the database driver.
*
* @var string
* @since 1.0
*/
protected $name;
/**
* The type of the database server family supported by this driver.
*
* @var string
* @since 1.4.0
*/
public $serverType;
/**
* The database connection resource.
*
* @var resource
* @since 1.0
*/
protected $connection;
/**
* Holds the list of available db connectors.
*
* @var array
* @since 1.0
*/
protected static $connectors = [];
/**
* The number of SQL statements executed by the database driver.
*
* @var integer
* @since 1.0
*/
protected $count = 0;
/**
* The database connection cursor from the last query.
*
* @var resource
* @since 1.0
*/
protected $cursor;
/**
* Contains the current query execution status
*
* @var boolean
* @since 2.0.0
*/
protected $executed = false;
/**
* The affected row limit for the current SQL statement.
*
* @var integer
* @since 1.0
*/
protected $limit = 0;
/**
* 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;
/**
* The affected row offset to apply for the current SQL statement.
*
* @var integer
* @since 1.0
*/
protected $offset = 0;
/**
* Passed in upon instantiation and saved.
*
* @var array
* @since 1.0
*/
protected $options;
/**
* The current SQL statement to execute.
*
* @var mixed
* @since 1.0
*/
protected $sql;
/**
* The prepared statement.
*
* @var StatementInterface
* @since 2.0.0
*/
protected $statement;
/**
* The common database table prefix.
*
* @var string
* @since 1.0
*/
protected $tablePrefix;
/**
* True if the database engine supports UTF-8 character encoding.
*
* @var boolean
* @since 1.0
*/
protected $utf = true;
/**
* The database error number.
*
* @var integer
* @since 1.0
*/
protected $errorNum = 0;
/**
* The database error message.
*
* @var string
* @since 1.0
*/
protected $errorMsg;
/**
* DatabaseDriver instances container.
*
* @var DatabaseDriver[]
* @since 1.0
* @deprecated 3.0 Singleton storage will no longer be supported.
*/
protected static $instances = [];
/**
* The minimum supported database version.
*
* @var string
* @since 1.0
*/
protected static $dbMinimum;
/**
* The depth of the current transaction.
*
* @var integer
* @since 1.0
*/
protected $transactionDepth = 0;
/**
* DatabaseFactory object
*
* @var DatabaseFactory
* @since 2.0.0
*/
protected $factory;
/**
* Query monitor object
*
* @var QueryMonitorInterface
* @since 2.0.0
*/
protected $monitor;
/**
* Get a list of available database connectors.
*
* The list will only be populated with connectors that the class exists for and the environment supports its use.
* This gives us the ability to have a multitude of connector classes that are self-aware as to whether or not they
* are able to be used on a given system.
*
* @return array An array of available database connectors.
*
* @since 1.0
*/
public static function getConnectors()
{
if (empty(self::$connectors))
{
// Get an iterator and loop trough the driver classes.
$dir = __DIR__;
$iterator = new \DirectoryIterator($dir);
/** @var $file \DirectoryIterator */
foreach ($iterator as $file)
{
// Only load for php files.
if (!$file->isDir())
{
continue;
}
$baseName = $file->getBasename();
// Derive the class name from the type.
/** @var $class DatabaseDriver */
$class = __NAMESPACE__ . '\\' . ucfirst(strtolower($baseName)) . '\\' . ucfirst(strtolower($baseName)) . 'Driver';
// If the class doesn't exist, or if it's not supported on this system, move on to the next type.
if (!class_exists($class) || !$class::isSupported())
{
continue;
}
// Everything looks good, add it to the list.
self::$connectors[] = $baseName;
}
}
return self::$connectors;
}
/**
* Method to return a DatabaseDriver instance based on the given options.
*
* There are three global options and then the rest are specific to the database driver.
*
* - The 'driver' option defines which DatabaseDriver class is used for the connection -- the default is 'mysqli'.
* - The 'database' option determines which database is to be used for the connection.
* - The 'select' option determines whether the connector should automatically select the chosen database.
*
* Instances are unique to the given options and new objects are only created when a unique options array is
* passed into the method. This ensures that we don't end up with unnecessary database connection resources.
*
* @param array $options Parameters to be passed to the database driver.
*
* @return DatabaseDriver
*
* @since 1.0
* @throws \RuntimeException
* @deprecated 3.0 Use DatabaseFactory::getDriver() instead
*/
public static function getInstance(array $options = [])
{
trigger_deprecation(
'joomla/database',
'2.0.0',
'%s() is deprecated and will be removed in 3.0, use %s::getDriver() instead.',
__METHOD__,
DatabaseFactory::class
);
// Sanitize the database connector options.
$options['driver'] = isset($options['driver']) ? preg_replace('/[^A-Z0-9_\.-]/i', '', $options['driver']) : 'mysqli';
$options['database'] = $options['database'] ?? null;
$options['select'] = $options['select'] ?? true;
$options['factory'] = $options['factory'] ?? new DatabaseFactory;
$options['monitor'] = $options['monitor'] ?? null;
// Get the options signature for the database connector.
$signature = md5(serialize($options));
// If we already have a database connector instance for these options then just use that.
if (empty(self::$instances[$signature]))
{
// Set the new connector to the global instances based on signature.
self::$instances[$signature] = $options['factory']->getDriver($options['driver'], $options);
}
return self::$instances[$signature];
}
/**
* Splits a string of multiple queries into an array of individual queries.
*
* @param string $sql Input SQL string with which to split into individual queries.
*
* @return array
*
* @since 1.0
*/
public static function splitSql($sql)
{
$start = 0;
$open = false;
$comment = false;
$endString = '';
$end = \strlen($sql);
$queries = [];
$query = '';
for ($i = 0; $i < $end; $i++)
{
$current = substr($sql, $i, 1);
$current2 = substr($sql, $i, 2);
$current3 = substr($sql, $i, 3);
$lenEndString = \strlen($endString);
$testEnd = substr($sql, $i, $lenEndString);
if ($current === '"' || $current === "'" || $current2 === '--'
|| ($current2 === '/*' && $current3 !== '/*!' && $current3 !== '/*+')
|| ($current === '#' && $current3 !== '#__')
|| ($comment && $testEnd === $endString))
{
// Check if quoted with previous backslash
$n = 2;
while (substr($sql, $i - $n + 1, 1) === '\\' && $n < $i)
{
$n++;
}
// Not quoted
if ($n % 2 === 0)
{
if ($open)
{
if ($testEnd === $endString)
{
if ($comment)
{
$comment = false;
if ($lenEndString > 1)
{
$i += ($lenEndString - 1);
$current = substr($sql, $i, 1);
}
$start = $i + 1;
}
$open = false;
$endString = '';
}
}
else
{
$open = true;
if ($current2 === '--')
{
$endString = "\n";
$comment = true;
}
elseif ($current2 === '/*')
{
$endString = '*/';
$comment = true;
}
elseif ($current === '#')
{
$endString = "\n";
$comment = true;
}
else
{
$endString = $current;
}
if ($comment && $start < $i)
{
$query .= substr($sql, $start, $i - $start);
}
}
}
}
if ($comment)
{
$start = $i + 1;
}
if (($current === ';' && !$open) || $i === $end - 1)
{
if ($start <= $i)
{
$query .= substr($sql, $start, $i - $start + 1);
}
$query = trim($query);
if ($query)
{
if (($i === $end - 1) && ($current !== ';'))
{
$query .= ';';
}
$queries[] = $query;
}
$query = '';
$start = $i + 1;
}
$endComment = false;
}
return $queries;
}
/**
* Magic method to access properties of the database driver.
*
* @param string $name The name of the property.
*
* @return mixed A value if the property name is valid, null otherwise.
*
* @since 1.4.0
* @deprecated 3.0 This is a B/C proxy since $this->name was previously public
*/
public function __get($name)
{
switch ($name)
{
case 'name':
trigger_deprecation(
'joomla/database',
'1.4.0',
'Accessing the name property of %s is deprecated, use the getName() method instead.',
self::class
);
return $this->getName();
default:
$trace = debug_backtrace();
trigger_error(
sprintf(
'Undefined property via __get(): %1$s in %2$s on line %3$s',
$name,
$trace[0]['file'],
$trace[0]['line']
),
\E_USER_NOTICE
);
}
}
/**
* Constructor.
*
* @param array $options List of options used to configure the connection
*
* @since 1.0
*/
public function __construct(array $options)
{
// Initialise object variables.
$this->database = $options['database'] ?? '';
$this->tablePrefix = $options['prefix'] ?? '';
$this->count = 0;
$this->errorNum = 0;
// Set class options.
$this->options = $options;
// Register the DatabaseFactory
$this->factory = $options['factory'] ?? new DatabaseFactory;
// Register the query monitor if available
$this->monitor = $options['monitor'] ?? null;
}
/**
* Destructor.
*
* @since 2.0.0
*/
public function __destruct()
{
$this->disconnect();
}
/**
* Alter database's character set.
*
* @param string $dbName The database name that will be altered
*
* @return boolean|resource
*
* @since 2.0.0
* @throws \RuntimeException
*/
public function alterDbCharacterSet($dbName)
{
if ($dbName === null)
{
throw new \RuntimeException('Database name must not be null.');
}
$this->setQuery($this->getAlterDbCharacterSet($dbName));
return $this->execute();
}
/**
* Create a new database using information from $options object.
*
* @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 boolean|resource
*
* @since 2.0.0
* @throws \RuntimeException
*/
public function createDatabase($options, $utf = true)
{
if ($options === null)
{
throw new \RuntimeException('$options object must not be null.');
}
if (empty($options->db_name))
{
throw new \RuntimeException('$options object must have db_name set.');
}
if (empty($options->db_user))
{
throw new \RuntimeException('$options object must have db_user set.');
}
$this->setQuery($this->getCreateDatabaseQuery($options, $utf));
return $this->execute();
}
/**
* Disconnects the database.
*
* @return void
*
* @since 2.0.0
*/
public function disconnect()
{
$this->freeResult();
$this->connection = null;
$this->dispatchEvent(new ConnectionEvent(DatabaseEvents::POST_DISCONNECT, $this));
}
/**
* Dispatch an event.
*
* @param EventInterface $event The event to dispatch
*
* @return void
*
* @since 2.0.0
*/
protected function dispatchEvent(EventInterface $event)
{
try
{
$this->getDispatcher()->dispatch($event->getName(), $event);
}
catch (\UnexpectedValueException $exception)
{
// Don't error if a dispatcher hasn't been set
}
}
/**
* Drops a table from the database.
*
* @param string $table The name of the database table to drop.
* @param boolean $ifExists Optionally specify that the table must exist before it is dropped.
*
* @return $this
*
* @since 2.0.0
* @throws \RuntimeException
*/
public function dropTable($table, $ifExists = true)
{
$this->connect();
$this->setQuery('DROP TABLE ' . ($ifExists ? 'IF EXISTS ' : '') . $this->quoteName($table))
->execute();
return $this;
}
/**
* Execute the SQL statement.
*
* @return boolean
*
* @since 2.0.0
* @throws \RuntimeException
*/
public function execute()
{
$this->connect();
// Increment the query counter.
$this->count++;
// Get list of bound parameters
$bounded =& $this->sql->getBounded();
// If there is a monitor registered, let it know we are starting this query
if ($this->monitor)
{
// Take a local copy so that we don't modify the original query and cause issues later
$sql = $this->replacePrefix((string) $this->sql);
$this->monitor->startQuery($sql, $bounded);
}
// Execute the query.
$this->executed = false;
// Bind the variables
foreach ($bounded as $key => $obj)
{
$this->statement->bindParam($key, $obj->value, $obj->dataType);
}
try
{
$this->executed = $this->statement->execute();
// If there is a monitor registered, let it know we have finished this query
if ($this->monitor)
{
$this->monitor->stopQuery();
}
return true;
}
catch (ExecutionFailureException $exception)
{
// If there is a monitor registered, let it know we have finished this query
if ($this->monitor)
{
$this->monitor->stopQuery();
}
// Check if the server was disconnected.
if (!$this->connected())
{
try
{
// Attempt to reconnect.
$this->connection = null;
$this->connect();
}
catch (ConnectionFailureException $e)
{
// If connect fails, ignore that exception and throw the normal exception.
throw $exception;
}
// Since we were able to reconnect, run the query again.
return $this->execute();
}
// Throw the normal query exception.
throw $exception;
}
}
/**
* Method to fetch a row from the result set cursor as an array.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 1.0
*/
protected function fetchArray()
{
if ($this->statement)
{
return $this->statement->fetch(FetchMode::NUMERIC);
}
}
/**
* Method to fetch a row from the result set cursor as an associative array.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 1.0
*/
protected function fetchAssoc()
{
if ($this->statement)
{
return $this->statement->fetch(FetchMode::ASSOCIATIVE);
}
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* Note, the fetch mode should be configured before calling this method using `StatementInterface::setFetchMode()`.
*
* @return mixed Either the next row from the result set or false if there are no more rows.
*
* @since 1.0
*/
protected function fetchObject()
{
if ($this->statement)
{
return $this->statement->fetch();
}
}
/**
* Method to free up the memory used for the result set.
*
* @return void
*
* @since 1.0
*/
protected function freeResult()
{
$this->executed = false;
if ($this->statement)
{
$this->statement->closeCursor();
}
}
/**
* Get the number of affected rows for the previous executed SQL statement.
*
* @return integer The number of affected rows in the previous operation
*
* @since 2.0.0
*/
public function getAffectedRows()
{
$this->connect();
if ($this->statement)
{
return $this->statement->rowCount();
}
return 0;
}
/**
* Method that provides access to the underlying database connection.
*
* @return resource The underlying database connection resource.
*
* @since 1.0
*/
public function getConnection()
{
return $this->connection;
}
/**
* Get the total number of SQL statements executed by the database driver.
*
* @return integer
*
* @since 1.0
*/
public function getCount()
{
return $this->count;
}
/**
* 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 1.6.0
*/
protected function getAlterDbCharacterSet($dbName)
{
return 'ALTER DATABASE ' . $this->quoteName($dbName) . ' CHARACTER SET ' . $this->quote('UTF8');
}
/**
* 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)
{
return 'CREATE DATABASE ' . $this->quoteName($options->db_name);
}
/**
* Gets the name of the database used by this connection.
*
* @return string
*
* @since 1.0
*/
protected function getDatabase()
{
return $this->database;
}
/**
* Returns a PHP date() function compliant date format for the database driver.
*
* @return string
*
* @since 1.0
*/
public function getDateFormat()
{
return 'Y-m-d H:i:s';
}
/**
* Get the minimum supported database version.
*
* @return string
*
* @since 1.0
*/
public function getMinimum()
{
return static::$dbMinimum;
}
/**
* Get the name of the database driver.
*
* If $this->name is not set it will try guessing the driver name from the class name.
*
* @return string
*
* @since 1.4.0
*/
public function getName()
{
if (empty($this->name))
{
$reflect = new \ReflectionClass($this);
$this->name = strtolower(str_replace('Driver', '', $reflect->getShortName()));
}
return $this->name;
}
/**
* Get the number of returned rows for the previous executed SQL statement.
*
* @return integer The number of returned rows.
*
* @since 2.0.0
*/
public function getNumRows()
{
$this->connect();
if ($this->statement)
{
return $this->statement->rowCount();
}
return 0;
}
/**
* Get the server family type.
*
* If $this->serverType is not set it will attempt guessing the server family type from the driver name. If this is not possible the driver
* name will be returned instead.
*
* @return string
*
* @since 1.4.0
*/
public function getServerType()
{
if (empty($this->serverType))
{
$name = $this->getName();
if (stristr($name, 'mysql') !== false)
{
$this->serverType = 'mysql';
}
elseif (stristr($name, 'postgre') !== false)
{
$this->serverType = 'postgresql';
}
elseif (stristr($name, 'pgsql') !== false)
{
$this->serverType = 'postgresql';
}
elseif (stristr($name, 'oracle') !== false)
{
$this->serverType = 'oracle';
}
elseif (stristr($name, 'sqlite') !== false)
{
$this->serverType = 'sqlite';
}
elseif (stristr($name, 'sqlsrv') !== false)
{
$this->serverType = 'mssql';
}
elseif (stristr($name, 'sqlazure') !== false)
{
$this->serverType = 'mssql';
}
elseif (stristr($name, 'mssql') !== false)
{
$this->serverType = 'mssql';
}
else
{
$this->serverType = $name;
}
}
return $this->serverType;
}
/**
* Get the null or zero representation of a timestamp for the database driver.
*
* @return string
*
* @since 1.0
*/
public function getNullDate()
{
return $this->nullDate;
}
/**
* Get the common table prefix for the database driver.
*