-
Notifications
You must be signed in to change notification settings - Fork 0
/
DB_driver.php
1812 lines (1561 loc) · 39.4 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
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 = '';
/**
* 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;
}
}
}
// --------------------------------------------------------------------
/**
* 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)
{
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;
}
// --------------------------------------------------------------------
/**
* 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))
{
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 (function_exists('logger')) {
logger($sql);
}
if ($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
$this->_trans_status = FALSE;
// Grab the error now, as we might run some additional queries before displaying the error
$error = $this->error();
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.
if ($this->_trans_depth !== 0)
{
do
{
$this->trans_complete();
}
while ($this->_trans_depth !== 0);
}
// 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('DB_result.php');
require_once($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)
{
$this->initialize();
}
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 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 void
*/
public function trans_start($test_mode = FALSE)
{
if ( ! $this->trans_enabled)
{
return;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
if ($this->_trans_depth > 0)
{
$this->_trans_depth += 1;
return;
}
$this->trans_begin($test_mode);
$this->_trans_depth += 1;
}
// --------------------------------------------------------------------
/**
* Complete Transaction
*
* @return bool
*/
public function trans_complete()
{
if ( ! $this->trans_enabled)
{
return FALSE;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
if ($this->_trans_depth > 1)
{
$this->_trans_depth -= 1;
return TRUE;
}
else
{
$this->_trans_depth = 0;
}
// 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;
}
return FALSE;
}
$this->trans_commit();
return TRUE;
}
// --------------------------------------------------------------------
/**
* Lets you retrieve the transaction flag to determine if it has failed
*
* @return bool
*/
public function trans_status()
{
return $this->_trans_status;
}
// --------------------------------------------------------------------
/**
* Compile Bindings
*
* @param string the sql statement
* @param array an array of bind data
* @return string
*/
public function compile_binds($sql, $binds)
{
if (empty($binds) OR empty($this->bind_marker) OR strpos($sql, $this->bind_marker) === FALSE)
{
return $sql;
}
elseif ( ! is_array($binds))
{
$binds = array($binds);
$bind_count = 1;
}
else
{
// Make sure we're using numeric keys
$binds = array_values($binds);
$bind_count = count($binds);
}
// We'll need the marker length later
$ml = strlen($this->bind_marker);
// Make sure not to replace a chunk inside a string that happens to match the bind marker
if ($c = preg_match_all("/'[^']*'/i", $sql, $matches))
{
$c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i',
str_replace($matches[0],
str_replace($this->bind_marker, str_repeat(' ', $ml), $matches[0]),
$sql, $c),
$matches, PREG_OFFSET_CAPTURE);
// Bind values' count must match the count of markers in the query
if ($bind_count !== $c)
{
return $sql;
}
}
elseif (($c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i', $sql, $matches, PREG_OFFSET_CAPTURE)) !== $bind_count)
{
return $sql;
}
do
{
$c--;
$escaped_value = $this->escape($binds[$c]);
if (is_array($escaped_value))
{
$escaped_value = '('.implode(',', $escaped_value).')';
}
$sql = substr_replace($sql, $escaped_value, $matches[0][$c][1], $ml);
}
while ($c !== 0);
return $sql;
}
// --------------------------------------------------------------------
/**
* Determines if a query is a "write" type.
*
* @param string An SQL query string
* @return bool
*/
public function is_write_type($sql)
{
return (bool) preg_match('/^\s*"?(SET|INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|TRUNCATE|LOAD|COPY|ALTER|RENAME|GRANT|REVOKE|LOCK|UNLOCK|REINDEX)\s/i', $sql);
}
// --------------------------------------------------------------------
/**
* Calculate the aggregate query elapsed time
*
* @param int The number of decimal places
* @return string
*/
public function elapsed_time($decimals = 6)
{
return number_format($this->benchmark, $decimals);
}
// --------------------------------------------------------------------
/**
* Returns the total number of queries
*
* @return int
*/
public function total_queries()
{
return $this->query_count;
}
// --------------------------------------------------------------------
/**
* Returns the last query that was executed
*
* @return string
*/
public function last_query()
{
return end($this->queries);
}
// --------------------------------------------------------------------
/**
* "Smart" Escape String
*
* Escapes data based on type
* Sets boolean and null types
*
* @param string
* @return mixed
*/
public function escape($str)
{
if (is_array($str))
{
$str = array_map(array(&$this, 'escape'), $str);
return $str;
}
elseif (is_string($str) OR (is_object($str) && method_exists($str, '__toString')))
{
return "'".$this->escape_str($str)."'";
}
elseif (is_bool($str))
{
return ($str === FALSE) ? 0 : 1;
}
elseif ($str === NULL)
{
return 'NULL';
}
return $str;
}
// --------------------------------------------------------------------
/**
* Escape String
*
* @param string|string[] $str Input string
* @param bool $like Whether or not the string will be used in a LIKE condition
* @return string
*/
public function escape_str($str, $like = FALSE)
{
if (is_array($str))
{
foreach ($str as $key => $val)
{
$str[$key] = $this->escape_str($val, $like);
}
return $str;
}