-
Notifications
You must be signed in to change notification settings - Fork 0
/
rb.php
18413 lines (16912 loc) · 534 KB
/
rb.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
namespace RedBeanPHP {
/**
* RedBean Logging interface.
* Provides a uniform and convenient logging
* interface throughout RedBeanPHP.
*
* @file RedBean/Logging.php
* @author Gabor de Mooij and the RedBeanPHP Community
* @license BSD/GPLv2
*
* @copyright
* copyright (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community
* This source file is subject to the BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
interface Logger
{
/**
* A logger (for PDO or OCI driver) needs to implement the log method.
* The log method will receive logging data. Note that the number of parameters is 0, this means
* all parameters are optional and the number may vary. This way the logger can be used in a very
* flexible way. Sometimes the logger is used to log a simple error message and in other
* situations sql and bindings are passed.
* The log method should be able to accept all kinds of parameters and data by using
* functions like func_num_args/func_get_args.
*
* @param string $message, ...
*
* @return void
*/
public function log();
}
}
namespace RedBeanPHP\Logger {
use RedBeanPHP\Logger as Logger;
use RedBeanPHP\RedException as RedException;
/**
* Logger. Provides a basic logging function for RedBeanPHP.
*
* @file RedBeanPHP/Logger.php
* @author Gabor de Mooij and the RedBeanPHP Community
* @license BSD/GPLv2
*
* @copyright
* copyright (c) G.J.G.T. (Gabor) de Mooij
* This source file is subject to the BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class RDefault implements Logger
{
/**
* Logger modes
*/
const C_LOGGER_ECHO = 0;
const C_LOGGER_ARRAY = 1;
/**
* @var integer
*/
protected $mode = 0;
/**
* @var array
*/
protected $logs = array();
/**
* Default logger method logging to STDOUT.
* This is the default/reference implementation of a logger.
* This method will write the message value to STDOUT (screen) unless
* you have changed the mode of operation to C_LOGGER_ARRAY.
*
* @param $message (optional) message to log (might also be data or output)
*
* @return void
*/
public function log()
{
if ( func_num_args() < 1 ) return;
foreach ( func_get_args() as $argument ) {
if ( is_array( $argument ) ) {
$log = var_export( $argument, TRUE );
if ( $this->mode === self::C_LOGGER_ECHO ) {
echo $log;
} else {
$this->logs[] = $log;
}
} else {
if ( $this->mode === self::C_LOGGER_ECHO ) {
echo $argument;
} else {
$this->logs[] = $argument;
}
}
if ( $this->mode === self::C_LOGGER_ECHO ) echo "<br>" . PHP_EOL;
}
}
/**
* Returns the internal log array.
* The internal log array is where all log messages are stored.
*
* @return array
*/
public function getLogs()
{
return $this->logs;
}
/**
* Clears the internal log array, removing all
* previously stored entries.
*
* @return self
*/
public function clear()
{
$this->logs = array();
return $this;
}
/**
* Selects a logging mode.
* There are several options available.
*
* * C_LOGGER_ARRAY - log silently, stores entries in internal log array only
* * C_LOGGER_ECHO - also forward log messages directly to STDOUT
*
* @param integer $mode mode of operation for logging object
*
* @return self
*/
public function setMode( $mode )
{
if ($mode !== self::C_LOGGER_ARRAY && $mode !== self::C_LOGGER_ECHO ) {
throw new RedException( 'Invalid mode selected for logger, use C_LOGGER_ARRAY or C_LOGGER_ECHO.' );
}
$this->mode = $mode;
return $this;
}
/**
* Searches for all log entries in internal log array
* for $needle and returns those entries.
* This method will return an array containing all matches for your
* search query.
*
* @param string $needle phrase to look for in internal log array
*
* @return array
*/
public function grep( $needle )
{
$found = array();
foreach( $this->logs as $logEntry ) {
if ( strpos( $logEntry, $needle ) !== FALSE ) $found[] = $logEntry;
}
return $found;
}
}
}
namespace RedBeanPHP\Logger\RDefault {
use RedBeanPHP\Logger as Logger;
use RedBeanPHP\Logger\RDefault as RDefault;
use RedBeanPHP\RedException as RedException;
/**
* Debug logger.
* A special logger for debugging purposes.
* Provides debugging logging functions for RedBeanPHP.
*
* @file RedBeanPHP/Logger/RDefault/Debug.php
* @author Gabor de Mooij and the RedBeanPHP Community
* @license BSD/GPLv2
*
* @copyright
* copyright (c) G.J.G.T. (Gabor) de Mooij
* This source file is subject to the BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class Debug extends RDefault implements Logger
{
/**
* @var integer
*/
protected $strLen = 40;
/**
* @var boolean
*/
protected static $noCLI = FALSE;
/**
* @var boolean
*/
protected $flagUseStringOnlyBinding = FALSE;
/**
* Toggles CLI override. By default debugging functions will
* output differently based on PHP_SAPI values. This function
* allows you to override the PHP_SAPI setting. If you set
* this to TRUE, CLI output will be suppressed in favour of
* HTML output. So, to get HTML on the command line use
* setOverrideCLIOutput( TRUE ).
*
* @param boolean $yesNo CLI-override setting flag
*
* @return void
*/
public static function setOverrideCLIOutput( $yesNo )
{
self::$noCLI = $yesNo;
}
/**
* Writes a query for logging with all bindings / params filled
* in.
*
* @param string $newSql the query
* @param array $newBindings the bindings to process (key-value pairs)
*
* @return string
*/
protected function writeQuery( $newSql, $newBindings )
{
//avoid str_replace collisions: slot1 and slot10 (issue 407).
uksort( $newBindings, function( $a, $b ) {
return ( strlen( $b ) - strlen( $a ) );
} );
$newStr = $newSql;
foreach( $newBindings as $slot => $value ) {
if ( strpos( $slot, ':' ) === 0 ) {
$newStr = str_replace( $slot, $this->fillInValue( $value ), $newStr );
}
}
return $newStr;
}
/**
* Fills in a value of a binding and truncates the
* resulting string if necessary.
*
* @param mixed $value bound value
*
* @return string
*/
protected function fillInValue( $value )
{
if ( is_array( $value ) && count( $value ) == 2 ) {
$paramType = end( $value );
$value = reset( $value );
} else {
$paramType = NULL;
}
if ( is_null( $value ) ) $value = 'NULL';
if ( $this->flagUseStringOnlyBinding ) $paramType = \PDO::PARAM_STR;
if ( $paramType != \PDO::PARAM_INT && $paramType != \PDO::PARAM_STR ) {
if ( \RedBeanPHP\QueryWriter\AQueryWriter::canBeTreatedAsInt( $value ) || $value === 'NULL') {
$paramType = \PDO::PARAM_INT;
} else {
$paramType = \PDO::PARAM_STR;
}
}
if ( strlen( $value ) > ( $this->strLen ) ) {
$value = substr( $value, 0, ( $this->strLen ) ).'... ';
}
if ($paramType === \PDO::PARAM_STR) {
$value = '\''.$value.'\'';
}
return $value;
}
/**
* Depending on the current mode of operation,
* this method will either log and output to STDIN or
* just log.
*
* Depending on the value of constant PHP_SAPI this function
* will format output for console or HTML.
*
* @param string $str string to log or output and log
*
* @return void
*/
protected function output( $str )
{
$this->logs[] = $str;
if ( !$this->mode ) {
$highlight = FALSE;
/* just a quick heuristic to highlight schema changes */
if ( strpos( $str, 'CREATE' ) === 0
|| strpos( $str, 'ALTER' ) === 0
|| strpos( $str, 'DROP' ) === 0) {
$highlight = TRUE;
}
if (PHP_SAPI === 'cli' && !self::$noCLI) {
if ($highlight) echo "\e[91m";
echo $str, PHP_EOL;
echo "\e[39m";
} else {
if ($highlight) {
echo "<b style=\"color:red\">{$str}</b>";
} else {
echo $str;
}
echo '<br />';
}
}
}
/**
* Normalizes the slots in an SQL string.
* Replaces question mark slots with :slot1 :slot2 etc.
*
* @param string $sql sql to normalize
*
* @return string
*/
protected function normalizeSlots( $sql )
{
$newSql = $sql;
$i = 0;
while(strpos($newSql, '?') !== FALSE ){
$pos = strpos( $newSql, '?' );
$slot = ':slot'.$i;
$begin = substr( $newSql, 0, $pos );
$end = substr( $newSql, $pos+1 );
if (PHP_SAPI === 'cli' && !self::$noCLI) {
$newSql = "{$begin}\e[32m{$slot}\e[39m{$end}";
} else {
$newSql = "{$begin}<b style=\"color:green\">$slot</b>{$end}";
}
$i ++;
}
return $newSql;
}
/**
* Normalizes the bindings.
* Replaces numeric binding keys with :slot1 :slot2 etc.
*
* @param array $bindings bindings to normalize
*
* @return array
*/
protected function normalizeBindings( $bindings )
{
$i = 0;
$newBindings = array();
foreach( $bindings as $key => $value ) {
if ( is_numeric($key) ) {
$newKey = ':slot'.$i;
$newBindings[$newKey] = $value;
$i++;
} else {
$newBindings[$key] = $value;
}
}
return $newBindings;
}
/**
* Logger method.
*
* Takes a number of arguments tries to create
* a proper debug log based on the available data.
*
* @return void
*/
public function log()
{
if ( func_num_args() < 1 ) return;
$sql = func_get_arg( 0 );
if ( func_num_args() < 2) {
$bindings = array();
} else {
$bindings = func_get_arg( 1 );
}
if ( !is_array( $bindings ) ) {
return $this->output( $sql );
}
$newSql = $this->normalizeSlots( $sql );
$newBindings = $this->normalizeBindings( $bindings );
$newStr = $this->writeQuery( $newSql, $newBindings );
$this->output( $newStr );
}
/**
* Sets the max string length for the parameter output in
* SQL queries. Set this value to a reasonable number to
* keep you SQL queries readable.
*
* @param integer $len string length
*
* @return self
*/
public function setParamStringLength( $len = 20 )
{
$this->strLen = max(0, $len);
return $this;
}
/**
* Whether to bind all parameters as strings.
* If set to TRUE this will cause all integers to be bound as STRINGS.
* This will NOT affect NULL values.
*
* @param boolean $yesNo pass TRUE to bind all parameters as strings.
*
* @return self
*/
public function setUseStringOnlyBinding( $yesNo = false )
{
$this->flagUseStringOnlyBinding = (boolean) $yesNo;
return $this;
}
}
}
namespace RedBeanPHP {
/**
* Interface for database drivers.
* The Driver API conforms to the ADODB pseudo standard
* for database drivers.
*
* @file RedBeanPHP/Driver.php
* @author Gabor de Mooij and the RedBeanPHP Community
* @license BSD/GPLv2
*
* @copyright
* copyright (c) G.J.G.T. (Gabor) de Mooij and the RedBeanPHP Community
* This source file is subject to the BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
interface Driver
{
/**
* Runs a query and fetches results as a multi dimensional array.
*
* @param string $sql SQL query to execute
* @param array $bindings list of values to bind to SQL snippet
*
* @return array
*/
public function GetAll( $sql, $bindings = array() );
/**
* Runs a query and fetches results as a column.
*
* @param string $sql SQL query to execute
* @param array $bindings list of values to bind to SQL snippet
*
* @return array
*/
public function GetCol( $sql, $bindings = array() );
/**
* Runs a query and returns results as a single cell.
*
* @param string $sql SQL query to execute
* @param array $bindings list of values to bind to SQL snippet
*
* @return mixed
*/
public function GetOne( $sql, $bindings = array() );
/**
* Runs a query and returns results as an associative array
* indexed by the first column.
*
* @param string $sql SQL query to execute
* @param array $bindings list of values to bind to SQL snippet
*
* @return array
*/
public function GetAssocRow( $sql, $bindings = array() );
/**
* Runs a query and returns a flat array containing the values of
* one row.
*
* @param string $sql SQL query to execute
* @param array $bindings list of values to bind to SQL snippet
*
* @return array
*/
public function GetRow( $sql, $bindings = array() );
/**
* Executes SQL code and allows key-value binding.
* This function allows you to provide an array with values to bind
* to query parameters. For instance you can bind values to question
* marks in the query. Each value in the array corresponds to the
* question mark in the query that matches the position of the value in the
* array. You can also bind values using explicit keys, for instance
* array(":key"=>123) will bind the integer 123 to the key :key in the
* SQL. This method has no return value.
*
* @param string $sql SQL query to execute
* @param array $bindings list of values to bind to SQL snippet
*
* @return int Affected Rows
*/
public function Execute( $sql, $bindings = array() );
/**
* Returns the latest insert ID if driver does support this
* feature.
*
* @return integer
*/
public function GetInsertID();
/**
* Returns the number of rows affected by the most recent query
* if the currently selected driver driver supports this feature.
*
* @return integer
*/
public function Affected_Rows();
/**
* Returns a cursor-like object from the database.
*
* @param string $sql SQL query to execute
* @param array $bindings list of values to bind to SQL snippet
*
* @return Cursor
*/
public function GetCursor( $sql, $bindings = array() );
/**
* Toggles debug mode. In debug mode the driver will print all
* SQL to the screen together with some information about the
* results.
*
* This method is for more fine-grained control. Normally
* you should use the facade to start the query debugger for
* you. The facade will manage the object wirings necessary
* to use the debugging functionality.
*
* Usage (through facade):
*
* <code>
* R::debug( TRUE );
* ...rest of program...
* R::debug( FALSE );
* </code>
*
* The example above illustrates how to use the RedBeanPHP
* query debugger through the facade.
*
* @param boolean $trueFalse turn on/off
* @param Logger $logger logger instance
*
* @return void
*/
public function setDebugMode( $tf, $customLogger );
/**
* Commits a transaction.
*
* @return void
*/
public function CommitTrans();
/**
* Starts a transaction.
*
* @return void
*/
public function StartTrans();
/**
* Rolls back a transaction.
*
* @return void
*/
public function FailTrans();
/**
* Resets the internal Query Counter.
*
* @return self
*/
public function resetCounter();
/**
* Returns the number of SQL queries processed.
*
* @return integer
*/
public function getQueryCount();
/**
* Sets initialization code for connection.
*
* @param callable|NULL $code code
*
* @return void
*/
public function setInitCode( $code );
/**
* Returns the version string from the database server.
*
* @return string
*/
public function DatabaseServerVersion();
}
}
namespace RedBeanPHP\Driver {
use RedBeanPHP\Driver as Driver;
use RedBeanPHP\Logger as Logger;
use RedBeanPHP\QueryWriter\AQueryWriter as AQueryWriter;
use RedBeanPHP\RedException as RedException;
use RedBeanPHP\RedException\SQL as SQL;
use RedBeanPHP\Logger\RDefault as RDefault;
use RedBeanPHP\PDOCompatible as PDOCompatible;
use RedBeanPHP\Cursor\PDOCursor as PDOCursor;
/**
* PDO Driver
* This Driver implements the RedBean Driver API.
* for RedBeanPHP. This is the standard / default database driver
* for RedBeanPHP.
*
* @file RedBeanPHP/PDO.php
* @author Gabor de Mooij and the RedBeanPHP Community, Desfrenes
* @license BSD/GPLv2
*
* @copyright
* copyright (c) Desfrenes & Gabor de Mooij and the RedBeanPHP community
* This source file is subject to the BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*/
class RPDO implements Driver
{
/**
* @var integer
*/
protected $max;
/**
* @var string
*/
protected $dsn;
/**
* @var boolean
*/
protected $loggingEnabled = FALSE;
/**
* @var Logger|NULL
*/
protected $logger = NULL;
/**
* @var \PDO|NULL
*/
protected $pdo;
/**
* @var integer
*/
protected $affectedRows;
/**
* @var array
*/
protected $resultArray;
/**
* @var array
*/
protected $connectInfo = array();
/**
* @var boolean
*/
protected $isConnected = FALSE;
/**
* @var bool
*/
protected $flagUseStringOnlyBinding = FALSE;
/**
* @var integer
*/
protected $queryCounter = 0;
/**
* @var string
*/
protected $mysqlCharset = '';
/**
* @var string
*/
protected $mysqlCollate = '';
/**
* @var boolean
*/
protected $stringifyFetches = TRUE;
/**
* @var string|NULL
*/
protected $initSQL = NULL;
/**
* @var callable|NULL
*/
protected $initCode = NULL;
/**
* Binds parameters. This method binds parameters to a PDOStatement for
* Query Execution. This method binds parameters as NULL, INTEGER or STRING
* and supports both named keys and question mark keys.
*
* @param \PDOStatement $statement PDO Statement instance
* @param array $bindings values that need to get bound to the statement
*
* @return void
*/
protected function bindParams( $statement, $bindings )
{
foreach ( $bindings as $key => &$value ) {
$k = is_integer( $key ) ? $key + 1 : $key;
if ( is_array( $value ) && count( $value ) == 2 ) {
$paramType = end( $value );
$value = reset( $value );
} else {
$paramType = NULL;
}
if ( is_null( $value ) ) {
$statement->bindValue( $k, NULL, \PDO::PARAM_NULL );
continue;
}
if ( $paramType != \PDO::PARAM_INT && $paramType != \PDO::PARAM_STR ) {
if ( !$this->flagUseStringOnlyBinding && AQueryWriter::canBeTreatedAsInt( $value ) && abs( $value ) <= $this->max ) {
$paramType = \PDO::PARAM_INT;
} else {
$paramType = \PDO::PARAM_STR;
}
}
$statement->bindParam( $k, $value, $paramType );
}
}
/**
* This method runs the actual SQL query and binds a list of parameters to the query.
* slots. The result of the query will be stored in the protected property
* $rs (always array). The number of rows affected (result of rowcount, if supported by database)
* is stored in protected property $affectedRows. If the debug flag is set
* this function will send debugging output to screen buffer.
*
* @param string $sql the SQL string to be send to database server
* @param array $bindings the values that need to get bound to the query slots
* @param array $options
*
* @return mixed
* @throws SQL
*/
public function runQuery( $sql, $bindings, $options = array() )
{
$this->connect();
if ( $this->loggingEnabled && $this->logger ) {
$this->logger->log( $sql, $bindings );
}
try {
if ( strpos( 'pgsql', $this->dsn ) === 0 ) {
if (defined('\\PDO::PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT')) {
$statement = @$this->pdo->prepare($sql, array(\PDO::PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT => TRUE));
} else {
$statement = $this->pdo->prepare($sql);
}
} else {
$statement = $this->pdo->prepare( $sql );
}
$this->bindParams( $statement, $bindings );
$statement->execute();
$this->queryCounter ++;
$this->affectedRows = $statement->rowCount();
if ( isset( $options['noFetch'] ) && $options['noFetch'] ) {
$this->resultArray = array();
return $statement;
}
if ( $statement->columnCount() ) {
$fetchStyle = ( isset( $options['fetchStyle'] ) ) ? $options['fetchStyle'] : NULL;
if ( is_null( $fetchStyle) ) {
$this->resultArray = $statement->fetchAll();
} else {
$this->resultArray = $statement->fetchAll( $fetchStyle );
}
if ( $this->loggingEnabled && $this->logger ) {
$this->logger->log( 'resultset: ' . count( $this->resultArray ) . ' rows' );
}
} else {
$this->resultArray = array();
}
} catch ( \PDOException $e ) {
//Unfortunately the code field is supposed to be int by default (php)
//So we need a property to convey the SQL State code.
$err = $e->getMessage();
if ( $this->loggingEnabled && $this->logger ) $this->logger->log( 'An error occurred: ' . $err );
$exception = new SQL( $err, 0, $e );
$exception->setSQLState( $e->getCode() );
$exception->setDriverDetails( $e->errorInfo );
throw $exception;
}
}
/**
* Try to fix MySQL character encoding problems.
* MySQL < 5.5.3 does not support proper 4 byte unicode but they
* seem to have added it with version 5.5.3 under a different label: utf8mb4.
* We try to select the best possible charset based on your version data.
*
* @return void
*/
protected function setEncoding()
{
$driver = $this->pdo->getAttribute( \PDO::ATTR_DRIVER_NAME );
if ($driver === 'mysql') {
$charset = $this->hasCap( 'utf8mb4' ) ? 'utf8mb4' : 'utf8';
$collate = $this->hasCap( 'utf8mb4_520' ) ? '_unicode_520_ci' : '_unicode_ci';
$this->pdo->setAttribute(\PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES '. $charset ); //on every re-connect
/* #624 removed space before SET NAMES because it causes trouble with ProxySQL */
$this->pdo->exec('SET NAMES '. $charset); //also for current connection
$this->mysqlCharset = $charset;
$this->mysqlCollate = $charset . $collate;
}
}
/**
* Determine if a database supports a particular feature.
* Currently this function can be used to detect the following features:
*
* - utf8mb4
* - utf8mb4 520
*
* Usage:
*
* <code>
* $this->hasCap( 'utf8mb4_520' );
* </code>
*
* By default, RedBeanPHP uses this method under the hood to make sure
* you use the latest UTF8 encoding possible for your database.
*
* @param string $db_cap identifier of database capability
*
* @return int|false Whether the database feature is supported, FALSE otherwise.
**/
protected function hasCap( $db_cap )
{
$compare = FALSE;
$version = $this->pdo->getAttribute( \PDO::ATTR_SERVER_VERSION );
switch ( strtolower( $db_cap ) ) {
case 'utf8mb4':
//oneliner, to boost code coverage (coverage does not span versions)
if ( version_compare( $version, '5.5.3', '<' ) ) { return FALSE; }
$client_version = $this->pdo->getAttribute(\PDO::ATTR_CLIENT_VERSION );
/*
* libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
* mysqlnd has supported utf8mb4 since 5.0.9.
*/
if ( strpos( $client_version, 'mysqlnd' ) !== FALSE ) {
$client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $client_version );
$compare = version_compare( $client_version, '5.0.9', '>=' );
} else {
$compare = version_compare( $client_version, '5.5.3', '>=' );
}
break;
case 'utf8mb4_520':
$compare = version_compare( $version, '5.6', '>=' );
break;
}
return $compare;
}
/**
* Constructor. You may either specify dsn, user and password or
* just give an existing PDO connection.
*
* Usage:
*
* <code>
* $driver = new RPDO( $dsn, $user, $password );
* </code>
*
* The example above illustrates how to create a driver
* instance from a database connection string (dsn), a username
* and a password. It's also possible to pass a PDO object.
*
* Usage:
*
* <code>
* $driver = new RPDO( $existingConnection );
* </code>
*
* The second example shows how to create an RPDO instance
* from an existing PDO object.
*
* @param string|\PDO $dsn database connection string
* @param string $user optional, username to sign in
* @param string $pass optional, password for connection login
*
* @return void
*/
public function __construct( $dsn, $user = NULL, $pass = NULL, $options = array() )
{
if ( is_object( $dsn ) ) {
$this->pdo = $dsn;
$this->isConnected = TRUE;
$this->setEncoding();
$this->pdo->setAttribute( \PDO::ATTR_ERRMODE,\PDO::ERRMODE_EXCEPTION );
$this->pdo->setAttribute( \PDO::ATTR_DEFAULT_FETCH_MODE,\PDO::FETCH_ASSOC );
// make sure that the dsn at least contains the type
$this->dsn = $this->getDatabaseType();
} else {
$this->dsn = $dsn;
$this->connectInfo = array( 'pass' => $pass, 'user' => $user );
if (is_array($options)) $this->connectInfo['options'] = $options;
}
//PHP 5.3 PDO SQLite has a bug with large numbers:
if ( ( strpos( $this->dsn, 'sqlite' ) === 0 && PHP_MAJOR_VERSION === 5 && PHP_MINOR_VERSION === 3 ) || defined('HHVM_VERSION') || $this->dsn === 'test-sqlite-53' ) {
$this->max = 2147483647; //otherwise you get -2147483648 ?! demonstrated in build #603 on Travis.
} elseif ( strpos( $this->dsn, 'cubrid' ) === 0 ) {
$this->max = 2147483647; //bindParam in pdo_cubrid also fails...
} else {
$this->max = PHP_INT_MAX; //the normal value of course (makes it possible to use large numbers in LIMIT clause)
}
}
/**
* Sets PDO in stringify fetch mode.
* If set to TRUE, this method will make sure all data retrieved from
* the database will be fetched as a string. Default: TRUE.
*
* To set it to FALSE...
*
* Usage:
*
* <code>
* R::getDatabaseAdapter()->getDatabase()->stringifyFetches( FALSE );
* </code>
*
* Important!
* Note, this method only works if you set the value BEFORE the connection
* has been establish. Also, this setting ONLY works with SOME drivers.
* It's up to the driver to honour this setting.
*
* @param boolean $bool
*/
public function stringifyFetches( $bool ) {
$this->stringifyFetches = $bool;
}
/**
* Returns the best possible encoding for MySQL based on version data.
* This method can be used to obtain the best character set parameters
* possible for your database when constructing a table creation query
* containing clauses like: CHARSET=... COLLATE=...
* This is a MySQL-specific method and not part of the driver interface.
*