-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
DB_driver.php
1999 lines (1728 loc) · 45.2 KB
/
DB_driver.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
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2019 - 2022, CodeIgniter Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
* @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
* @copyright Copyright (c) 2019 - 2022, CodeIgniter Foundation (https://codeigniter.com/)
* @license https://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
* @since Version 1.0.0
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Database Driver Class
*
* This is the platform-independent base DB implementation class.
* This class will not be called directly. Rather, the adapter
* class for the specific database will extend and instantiate it.
*
* @package CodeIgniter
* @subpackage Drivers
* @category Database
* @author EllisLab Dev Team
* @link https://codeigniter.com/userguide3/database/
*/
abstract class CI_DB_driver {
/**
* Data Source Name / Connect string
*
* @var string
*/
public $dsn;
/**
* Username
*
* @var string
*/
public $username;
/**
* Password
*
* @var string
*/
public $password;
/**
* Hostname
*
* @var string
*/
public $hostname;
/**
* Database name
*
* @var string
*/
public $database;
/**
* Database driver
*
* @var string
*/
public $dbdriver = 'mysqli';
/**
* Sub-driver
*
* @used-by CI_DB_pdo_driver
* @var string
*/
public $subdriver;
/**
* Table prefix
*
* @var string
*/
public $dbprefix = '';
/**
* Character set
*
* @var string
*/
public $char_set = 'utf8';
/**
* Collation
*
* @var string
*/
public $dbcollat = 'utf8_general_ci';
/**
* Encryption flag/data
*
* @var mixed
*/
public $encrypt = FALSE;
/**
* Swap Prefix
*
* @var string
*/
public $swap_pre = '';
/**
* Database port
*
* @var int
*/
public $port = NULL;
/**
* Persistent connection flag
*
* @var bool
*/
public $pconnect = FALSE;
/**
* Connection ID
*
* @var object|resource
*/
public $conn_id = FALSE;
/**
* Result ID
*
* @var object|resource
*/
public $result_id = FALSE;
/**
* Debug flag
*
* Whether to display error messages.
*
* @var bool
*/
public $db_debug = FALSE;
/**
* Benchmark time
*
* @var int
*/
public $benchmark = 0;
/**
* Executed queries count
*
* @var int
*/
public $query_count = 0;
/**
* Bind marker
*
* Character used to identify values in a prepared statement.
*
* @var string
*/
public $bind_marker = '?';
/**
* Save queries flag
*
* Whether to keep an in-memory history of queries for debugging purposes.
*
* @var bool
*/
public $save_queries = TRUE;
/**
* Queries list
*
* @see CI_DB_driver::$save_queries
* @var string[]
*/
public $queries = array();
/**
* Query times
*
* A list of times that queries took to execute.
*
* @var array
*/
public $query_times = array();
/**
* Data cache
*
* An internal generic value cache.
*
* @var array
*/
public $data_cache = array();
/**
* Transaction enabled flag
*
* @var bool
*/
public $trans_enabled = TRUE;
/**
* Strict transaction mode flag
*
* @var bool
*/
public $trans_strict = TRUE;
/**
* Transaction depth level
*
* @var int
*/
protected $_trans_depth = 0;
/**
* Transaction status flag
*
* Used with transactions to determine if a rollback should occur.
*
* @var bool
*/
protected $_trans_status = TRUE;
/**
* Transaction failure flag
*
* Used with transactions to determine if a transaction has failed.
*
* @var bool
*/
protected $_trans_failure = FALSE;
/**
* Cache On flag
*
* @var bool
*/
public $cache_on = FALSE;
/**
* Cache directory path
*
* @var bool
*/
public $cachedir = '';
/**
* Cache auto-delete flag
*
* @var bool
*/
public $cache_autodel = FALSE;
/**
* DB Cache object
*
* @see CI_DB_cache
* @var object
*/
public $CACHE;
/**
* Protect identifiers flag
*
* @var bool
*/
protected $_protect_identifiers = TRUE;
/**
* List of reserved identifiers
*
* Identifiers that must NOT be escaped.
*
* @var string[]
*/
protected $_reserved_identifiers = array('*');
/**
* Identifier escape character
*
* @var string
*/
protected $_escape_char = '"';
/**
* ESCAPE statement string
*
* @var string
*/
protected $_like_escape_str = " ESCAPE '%s' ";
/**
* ESCAPE character
*
* @var string
*/
protected $_like_escape_chr = '!';
/**
* ORDER BY random keyword
*
* @var array
*/
protected $_random_keyword = array('RAND()', 'RAND(%d)');
/**
* COUNT string
*
* @used-by CI_DB_driver::count_all()
* @used-by CI_DB_query_builder::count_all_results()
*
* @var string
*/
protected $_count_string = 'SELECT COUNT(*) AS ';
// --------------------------------------------------------------------
/**
* Class constructor
*
* @param array $params
* @return void
*/
public function __construct($params)
{
if (is_array($params))
{
foreach ($params as $key => $val)
{
$this->$key = $val;
}
}
log_message('info', 'Database Driver Class Initialized');
}
// --------------------------------------------------------------------
/**
* Initialize Database Settings
*
* @return bool
*/
public function initialize()
{
/* If an established connection is available, then there's
* no need to connect and select the database.
*
* Depending on the database driver, conn_id can be either
* boolean TRUE, a resource or an object.
*/
if ($this->conn_id)
{
return TRUE;
}
// ----------------------------------------------------------------
// Connect to the database and set the connection ID
$this->conn_id = $this->db_connect($this->pconnect);
// No connection resource? Check if there is a failover else throw an error
if ( ! $this->conn_id)
{
// Check if there is a failover set
if ( ! empty($this->failover) && is_array($this->failover))
{
// Go over all the failovers
foreach ($this->failover as $failover)
{
// Replace the current settings with those of the failover
foreach ($failover as $key => $val)
{
$this->$key = $val;
}
// Try to connect
$this->conn_id = $this->db_connect($this->pconnect);
// If a connection is made break the foreach loop
if ($this->conn_id)
{
break;
}
}
}
// We still don't have a connection?
if ( ! $this->conn_id)
{
log_message('error', 'Unable to connect to the database');
if ($this->db_debug)
{
$this->display_error('db_unable_to_connect');
}
return FALSE;
}
}
// Now we set the character set and that's all
return $this->db_set_charset($this->char_set);
}
// --------------------------------------------------------------------
/**
* DB connect
*
* This is just a dummy method that all drivers will override.
*
* @return mixed
*/
public function db_connect()
{
return TRUE;
}
// --------------------------------------------------------------------
/**
* Persistent database connection
*
* @return mixed
*/
public function db_pconnect()
{
return $this->db_connect(TRUE);
}
// --------------------------------------------------------------------
/**
* Reconnect
*
* Keep / reestablish the db connection if no queries have been
* sent for a length of time exceeding the server's idle timeout.
*
* This is just a dummy method to allow drivers without such
* functionality to not declare it, while others will override it.
*
* @return void
*/
public function reconnect()
{
}
// --------------------------------------------------------------------
/**
* Select database
*
* This is just a dummy method to allow drivers without such
* functionality to not declare it, while others will override it.
*
* @return bool
*/
public function db_select()
{
return TRUE;
}
// --------------------------------------------------------------------
/**
* Last error
*
* @return array
*/
public function error()
{
return array('code' => NULL, 'message' => NULL);
}
// --------------------------------------------------------------------
/**
* Set client character set
*
* @param string
* @return bool
*/
public function db_set_charset($charset)
{
if (method_exists($this, '_db_set_charset') && ! $this->_db_set_charset($charset))
{
log_message('error', 'Unable to set database connection charset: '.$charset);
if ($this->db_debug)
{
$this->display_error('db_unable_to_set_charset', $charset);
}
return FALSE;
}
return TRUE;
}
// --------------------------------------------------------------------
/**
* The name of the platform in use (mysql, mssql, etc...)
*
* @return string
*/
public function platform()
{
return $this->dbdriver;
}
// --------------------------------------------------------------------
/**
* Database version number
*
* Returns a string containing the version of the database being used.
* Most drivers will override this method.
*
* @return string
*/
public function version()
{
if (isset($this->data_cache['version']))
{
return $this->data_cache['version'];
}
if (FALSE === ($sql = $this->_version()))
{
return ($this->db_debug) ? $this->display_error('db_unsupported_function') : FALSE;
}
$query = $this->query($sql)->row();
return $this->data_cache['version'] = $query->ver;
}
// --------------------------------------------------------------------
/**
* Version number query string
*
* @return string
*/
protected function _version()
{
return 'SELECT VERSION() AS ver';
}
// --------------------------------------------------------------------
/**
* Execute the query
*
* Accepts an SQL string as input and returns a result object upon
* successful execution of a "read" type query. Returns boolean TRUE
* upon successful execution of a "write" type query. Returns boolean
* FALSE upon failure, and if the $db_debug variable is set to TRUE
* will raise an error.
*
* @param string $sql
* @param array $binds = FALSE An array of binding data
* @param bool $return_object = NULL
* @return mixed
*/
public function query($sql, $binds = FALSE, $return_object = NULL)
{
if ($sql === '')
{
log_message('error', 'Invalid query: '.$sql);
return ($this->db_debug) ? $this->display_error('db_invalid_query') : FALSE;
}
elseif ( ! is_bool($return_object))
{
$return_object = ! $this->is_write_type($sql);
}
// Verify table prefix and replace if necessary
if ($this->dbprefix !== '' && $this->swap_pre !== '' && $this->dbprefix !== $this->swap_pre)
{
$sql = preg_replace('/(\W)'.$this->swap_pre.'(\S+?)/', '\\1'.$this->dbprefix.'\\2', $sql);
}
// Compile binds if needed
if ($binds !== FALSE)
{
$sql = $this->compile_binds($sql, $binds);
}
// Is query caching enabled? If the query is a "read type"
// we will load the caching class and return the previously
// cached query if it exists
if ($this->cache_on === TRUE && $return_object === TRUE && $this->_cache_init())
{
$this->load_rdriver();
if (FALSE !== ($cache = $this->CACHE->read($sql)))
{
return $cache;
}
}
// Save the query for debugging
if ($this->save_queries === TRUE)
{
$this->queries[] = $sql;
}
// Start the Query Timer
$time_start = microtime(TRUE);
// Run the Query
if (FALSE === ($this->result_id = $this->simple_query($sql)))
{
if ($this->save_queries === TRUE)
{
$this->query_times[] = 0;
}
// This will trigger a rollback if transactions are being used
if ($this->_trans_depth !== 0)
{
$this->_trans_status = FALSE;
}
// Grab the error now, as we might run some additional queries before displaying the error
$error = $this->error();
// Log errors
log_message('error', 'Query error: '.$error['message'].' - Invalid query: '.$sql);
if ($this->db_debug)
{
// We call this function in order to roll-back queries
// if transactions are enabled. If we don't call this here
// the error message will trigger an exit, causing the
// transactions to remain in limbo.
while ($this->_trans_depth !== 0)
{
$trans_depth = $this->_trans_depth;
$this->trans_complete();
if ($trans_depth === $this->_trans_depth)
{
log_message('error', 'Database: Failure during an automated transaction commit/rollback!');
break;
}
}
// Display errors
return $this->display_error(array('Error Number: '.$error['code'], $error['message'], $sql));
}
return FALSE;
}
// Stop and aggregate the query time results
$time_end = microtime(TRUE);
$this->benchmark += $time_end - $time_start;
if ($this->save_queries === TRUE)
{
$this->query_times[] = $time_end - $time_start;
}
// Increment the query counter
$this->query_count++;
// Will we have a result object instantiated? If not - we'll simply return TRUE
if ($return_object !== TRUE)
{
// If caching is enabled we'll auto-cleanup any existing files related to this particular URI
if ($this->cache_on === TRUE && $this->cache_autodel === TRUE && $this->_cache_init())
{
$this->CACHE->delete();
}
return TRUE;
}
// Load and instantiate the result driver
$driver = $this->load_rdriver();
$RES = new $driver($this);
// Is query caching enabled? If so, we'll serialize the
// result object and save it to a cache file.
if ($this->cache_on === TRUE && $this->_cache_init())
{
// We'll create a new instance of the result object
// only without the platform specific driver since
// we can't use it with cached data (the query result
// resource ID won't be any good once we've cached the
// result object, so we'll have to compile the data
// and save it)
$CR = new CI_DB_result($this);
$CR->result_object = $RES->result_object();
$CR->result_array = $RES->result_array();
$CR->num_rows = $RES->num_rows();
// Reset these since cached objects can not utilize resource IDs.
$CR->conn_id = NULL;
$CR->result_id = NULL;
$this->CACHE->write($sql, $CR);
}
return $RES;
}
// --------------------------------------------------------------------
/**
* Load the result drivers
*
* @return string the name of the result class
*/
public function load_rdriver()
{
$driver = 'CI_DB_'.$this->dbdriver.'_result';
if ( ! class_exists($driver, FALSE))
{
require_once(BASEPATH.'database/DB_result.php');
require_once(BASEPATH.'database/drivers/'.$this->dbdriver.'/'.$this->dbdriver.'_result.php');
}
return $driver;
}
// --------------------------------------------------------------------
/**
* Simple Query
* This is a simplified version of the query() function. Internally
* we only use it when running transaction commands since they do
* not require all the features of the main query() function.
*
* @param string the sql query
* @return mixed
*/
public function simple_query($sql)
{
if ( ! $this->conn_id)
{
if ( ! $this->initialize())
{
return FALSE;
}
}
return $this->_execute($sql);
}
// --------------------------------------------------------------------
/**
* Disable Transactions
* This permits transactions to be disabled at run-time.
*
* @return void
*/
public function trans_off()
{
$this->trans_enabled = FALSE;
}
// --------------------------------------------------------------------
/**
* Enable/disable Transaction Strict Mode
*
* When strict mode is enabled, if you are running multiple groups of
* transactions, if one group fails all subsequent groups will be
* rolled back.
*
* If strict mode is disabled, each group is treated autonomously,
* meaning a failure of one group will not affect any others
*
* @param bool $mode = TRUE
* @return void
*/
public function trans_strict($mode = TRUE)
{
$this->trans_strict = is_bool($mode) ? $mode : TRUE;
}
// --------------------------------------------------------------------
/**
* Start Transaction
*
* @param bool $test_mode = FALSE
* @return bool
*/
public function trans_start($test_mode = FALSE)
{
if ( ! $this->trans_enabled)
{
return FALSE;
}
return $this->trans_begin($test_mode);
}
// --------------------------------------------------------------------
/**
* Complete Transaction
*
* @return bool
*/
public function trans_complete()
{
if ( ! $this->trans_enabled)
{
return FALSE;
}
// The query() function will set this flag to FALSE in the event that a query failed
if ($this->_trans_status === FALSE OR $this->_trans_failure === TRUE)
{
$this->trans_rollback();
// If we are NOT running in strict mode, we will reset
// the _trans_status flag so that subsequent groups of
// transactions will be permitted.
if ($this->trans_strict === FALSE)
{
$this->_trans_status = TRUE;
}
log_message('debug', 'DB Transaction Failure');
return FALSE;
}
return $this->trans_commit();
}
// --------------------------------------------------------------------
/**
* Lets you retrieve the transaction flag to determine if it has failed
*
* @return bool
*/
public function trans_status()
{
return $this->_trans_status;
}
// --------------------------------------------------------------------
/**
* Returns TRUE if a transaction is currently active
*
* @return bool
*/
public function trans_active()
{
return (bool) $this->_trans_depth;
}
// --------------------------------------------------------------------
/**
* Begin Transaction
*
* @param bool $test_mode
* @return bool
*/
public function trans_begin($test_mode = FALSE)
{
if ( ! $this->trans_enabled)
{
return FALSE;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
elseif ($this->_trans_depth > 0)
{
$this->_trans_depth++;
return TRUE;
}
// Reset the transaction failure flag.
// If the $test_mode flag is set to TRUE transactions will be rolled back
// even if the queries produce a successful result.
$this->_trans_failure = ($test_mode === TRUE);
if ($this->_trans_begin())
{
$this->_trans_status = TRUE;
$this->_trans_depth++;
return TRUE;
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* Commit Transaction
*
* @return bool
*/
public function trans_commit()
{
if ( ! $this->trans_enabled OR $this->_trans_depth === 0)
{
return FALSE;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
elseif ($this->_trans_depth > 1 OR $this->_trans_commit())
{
$this->_trans_depth--;
return TRUE;
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* Rollback Transaction
*
* @return bool
*/
public function trans_rollback()
{
if ( ! $this->trans_enabled OR $this->_trans_depth === 0)
{
return FALSE;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
elseif ($this->_trans_depth > 1 OR $this->_trans_rollback())
{
$this->_trans_depth--;
return TRUE;
}
return FALSE;
}
// --------------------------------------------------------------------
/**
* Compile Bindings
*
* @param string the sql statement
* @param array an array of bind data
* @return string
*/
public function compile_binds($sql, $binds)
{
if (empty($this->bind_marker) OR strpos($sql, $this->bind_marker) === FALSE)
{
return $sql;
}