-
Notifications
You must be signed in to change notification settings - Fork 78
/
fDatabase.php
3625 lines (3122 loc) · 108 KB
/
fDatabase.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
/**
* Provides a common API for different databases - will automatically use any installed extension
*
* This class is implemented to use the UTF-8 character encoding. Please see
* http://flourishlib.com/docs/UTF-8 for more information.
*
* The following databases are supported:
*
* - [http://ibm.com/db2 DB2]
* - [http://microsoft.com/sql/ MSSQL]
* - [http://mysql.com MySQL]
* - [http://oracle.com Oracle]
* - [http://postgresql.org PostgreSQL]
* - [http://sqlite.org SQLite]
*
* The class will automatically use the first of the following extensions it finds:
*
* - DB2
* - [http://php.net/ibm_db2 ibm_db2]
* - [http://php.net/pdo_ibm pdo_ibm]
* - MSSQL
* - [http://msdn.microsoft.com/en-us/library/cc296221.aspx sqlsrv]
* - [http://php.net/pdo_dblib pdo_dblib]
* - [http://php.net/mssql mssql] (or [http://php.net/sybase sybase])
* - MySQL
* - [http://php.net/mysql mysql]
* - [http://php.net/mysqli mysqli]
* - [http://php.net/pdo_mysql pdo_mysql]
* - Oracle
* - [http://php.net/oci8 oci8]
* - [http://php.net/pdo_oci pdo_oci]
* - PostgreSQL
* - [http://php.net/pgsql pgsql]
* - [http://php.net/pdo_pgsql pdo_pgsql]
* - SQLite
* - [http://php.net/pdo_sqlite pdo_sqlite] (for v3.x)
* - [http://php.net/sqlite sqlite] (for v2.x)
*
* The `odbc` and `pdo_odbc` extensions are not supported due to character
* encoding and stability issues on Windows, and functionality on non-Windows
* operating systems.
*
* @copyright Copyright (c) 2007-2012 Will Bond
* @author Will Bond [wb] <will@flourishlib.com>
* @license http://flourishlib.com/license
*
* @package Flourish
* @link http://flourishlib.com/fDatabase
*
* @version 1.0.0b41
* @changes 1.0.0b41 Fixed an array to string conversion notice [wb, 2012-09-21]
* @changes 1.0.0b40 Fixed a bug with notices being triggered when failing to connect to a SQLite database [wb, 2011-06-20]
* @changes 1.0.0b39 Fixed a bug with detecting some MySQL database version numbers [wb, 2011-05-24]
* @changes 1.0.0b38 Backwards Compatibility Break - callbacks registered to the `extracted` hook via ::registerHookCallback() no longer receive the `$strings` parameter, instead all strings are added into the `$values` parameter - added ::getVersion(), fixed a bug with SQLite messaging, fixed a bug with ::__destruct(), improved handling of transactional queries, added ::close(), enhanced class to throw four different exceptions for different connection errors, silenced PHP warnings upon connection error [wb, 2011-05-09]
* @changes 1.0.0b37 Fixed usage of the mysqli extension to only call mysqli_set_charset() if it exists [wb, 2011-03-04]
* @changes 1.0.0b36 Updated ::escape() and methods that use ::escape() to handle float values that don't contain a digit before or after the . [wb, 2011-02-01]
* @changes 1.0.0b35 Updated the class to replace `LIMIT` and `OFFSET` value placeholders in the SQL with their values before translating since most databases that translate `LIMIT` statements need to move or add values together [wb, 2011-01-11]
* @changes 1.0.0b34 Fixed a bug with creating translated prepared statements [wb, 2011-01-09]
* @changes 1.0.0b33 Added code to explicitly set the connection encoding for the mysql and mysqli extensions since some PHP installs don't see to fully respect `SET NAMES` [wb, 2010-12-06]
* @changes 1.0.0b32 Fixed handling auto-incrementing values for Oracle when the trigger was on `INSERT OR UPDATE` instead of just `INSERT` [wb, 2010-12-04]
* @changes 1.0.0b31 Fixed handling auto-incrementing values for MySQL when the `INTO` keyword is left out of an `INSERT` statement [wb, 2010-11-04]
* @changes 1.0.0b30 Fixed the pgsql, mssql and mysql extensions to force a new connection instead of reusing an existing one [wb, 2010-08-17]
* @changes 1.0.0b29 Backwards Compatibility Break - removed ::enableSlowQueryWarnings(), added ability to replicate via ::registerHookCallback() [wb, 2010-08-10]
* @changes 1.0.0b28 Backwards Compatibility Break - removed ODBC support. Added support for the `pdo_ibm` extension. [wb, 2010-07-31]
* @changes 1.0.0b27 Fixed a bug with running multiple copies of a SQL statement with string values through a single ::translatedQuery() call [wb, 2010-07-14]
* @changes 1.0.0b26 Updated the class to use new fCore functionality [wb, 2010-07-05]
* @changes 1.0.0b25 Added IBM DB2 support [wb, 2010-04-13]
* @changes 1.0.0b24 Fixed an auto-incrementing transaction bug with Oracle and debugging issues with all databases [wb, 2010-03-17]
* @changes 1.0.0b23 Resolved another bug with capturing auto-incrementing values for PostgreSQL and Oracle [wb, 2010-03-15]
* @changes 1.0.0b22 Changed ::clearCache() to also clear the cache on the fSQLTranslation [wb, 2010-03-09]
* @changes 1.0.0b21 Added ::execute() for result-less SQL queries, ::prepare() and ::translatedPrepare() to create fStatement objects for prepared statements, support for prepared statements in ::query() and ::unbufferedQuery(), fixed default caching key for ::enableCaching() [wb, 2010-03-02]
* @changes 1.0.0b20 Added a parameter to ::enableCaching() to provide a key token that will allow cached values to be shared between multiple databases with the same schema [wb, 2009-10-28]
* @changes 1.0.0b19 Added support for escaping identifiers (column and table names) to ::escape(), added support for database schemas, rewrote internal SQL string spliting [wb, 2009-10-22]
* @changes 1.0.0b18 Updated the class for the new fResult and fUnbufferedResult APIs, fixed ::unescape() to not touch NULLs [wb, 2009-08-12]
* @changes 1.0.0b17 Added the ability to pass an array of all values as a single parameter to ::escape() instead of one value per parameter [wb, 2009-08-11]
* @changes 1.0.0b16 Fixed PostgreSQL and Oracle from trying to get auto-incrementing values on inserts when explicit values were given [wb, 2009-08-06]
* @changes 1.0.0b15 Fixed a bug where auto-incremented values would not be detected when table names were quoted [wb, 2009-07-15]
* @changes 1.0.0b14 Changed ::determineExtension() and ::determineCharacterSet() to be protected instead of private [wb, 2009-07-08]
* @changes 1.0.0b13 Updated ::escape() to accept arrays of values for insertion into full SQL strings [wb, 2009-07-06]
* @changes 1.0.0b12 Updates to ::unescape() to improve performance [wb, 2009-06-15]
* @changes 1.0.0b11 Changed replacement values in preg_replace() calls to be properly escaped [wb, 2009-06-11]
* @changes 1.0.0b10 Changed date/time/timestamp escaping from `strtotime()` to fDate/fTime/fTimestamp for better localization support [wb, 2009-06-01]
* @changes 1.0.0b9 Fixed a bug with ::escape() where floats that start with a . were encoded as `NULL` [wb, 2009-05-09]
* @changes 1.0.0b8 Added Oracle support, change PostgreSQL code to no longer cause lastval() warnings, added support for arrays of values to ::escape() [wb, 2009-05-03]
* @changes 1.0.0b7 Updated for new fCore API [wb, 2009-02-16]
* @changes 1.0.0b6 Fixed a bug with executing transaction queries when using the mysqli extension [wb, 2009-02-12]
* @changes 1.0.0b5 Changed @ error suppression operator to `error_reporting()` calls [wb, 2009-01-26]
* @changes 1.0.0b4 Added a few error suppression operators back in so that developers don't get errors and exceptions [wb, 2009-01-14]
* @changes 1.0.0b3 Removed some unnecessary error suppresion operators [wb, 2008-12-11]
* @changes 1.0.0b2 Fixed a bug with PostgreSQL when using the PDO extension and executing an INSERT statement [wb, 2008-12-11]
* @changes 1.0.0b The initial implementation [wb, 2007-09-25]
*/
class fDatabase
{
/**
* Composes text using fText if loaded
*
* @param string $message The message to compose
* @param mixed $component A string or number to insert into the message
* @param mixed ...
* @return string The composed and possible translated message
*/
static protected function compose($message)
{
$args = array_slice(func_get_args(), 1);
if (class_exists('fText', FALSE)) {
return call_user_func_array(
array('fText', 'compose'),
array($message, $args)
);
} else {
return vsprintf($message, $args);
}
}
/**
* An fCache object to cache the schema info to
*
* @var fCache
*/
private $cache;
/**
* The cache prefix to use for cache entries
*
* @var string
*/
private $cache_prefix;
/**
* Database connection resource or PDO object
*
* @var mixed
*/
private $connection;
/**
* The database name
*
* @var string
*/
private $database;
/**
* If debugging is enabled
*
* @var boolean
*/
private $debug;
/**
* A temporary error holder for the mssql extension
*
* @var string
*/
private $error;
/**
* The extension to use for the database specified
*
* Options include:
*
* - `'ibm_db2'`
* - `'mssql'`
* - `'mysql'`
* - `'mysqli'`
* - `'oci8'`
* - `'pgsql'`
* - `'sqlite'`
* - `'sqlsrv'`
* - `'pdo'`
*
* @var string
*/
protected $extension;
/**
* Hooks callbacks to be used for accessing and modifying queries
*
* This array will have the structure:
*
* {{{
* array(
* 'unmodified' => array({callbacks}),
* 'extracted' => array({callbacks}),
* 'run' => array({callbacks})
* )
* }}}
*
* @var array
*/
private $hook_callbacks;
/**
* The host the database server is located on
*
* @var string
*/
private $host;
/**
* If a transaction is in progress
*
* @var boolean
*/
private $inside_transaction;
/**
* The password for the user specified
*
* @var string
*/
private $password;
/**
* The port number for the host
*
* @var string
*/
private $port;
/**
* The total number of seconds spent executing queries
*
* @var float
*/
private $query_time;
/**
* A cache of database-specific code
*
* @var array
*/
protected $schema_info;
/**
* The last executed fStatement object
*
* @var fStatement
*/
private $statement;
/**
* The timeout for the database connection
*
* @var integer
*/
private $timeout;
/**
* The fSQLTranslation object for this database
*
* @var object
*/
private $translation;
/**
* The database type: `'db2'`, `'mssql'`, `'mysql'`, `'oracle'`, `'postgresql'`, or `'sqlite'`
*
* @var string
*/
private $type;
/**
* The unbuffered query instance
*
* @var fUnbufferedResult
*/
private $unbuffered_result;
/**
* The user to connect to the database as
*
* @var string
*/
private $username;
/**
* Configures the connection to a database - connection is not made until the first query is executed
*
* Passing `NULL` to any parameter other than `$type` and `$database` will
* cause the default value to be used.
*
* @param string $type The type of the database: `'db2'`, `'mssql'`, `'mysql'`, `'oracle'`, `'postgresql'`, `'sqlite'`
* @param string $database Name of the database. If SQLite the path to the database file.
* @param string $username Database username - not used for SQLite
* @param string $password The password for the username specified - not used for SQLite
* @param string $host Database server host or IP, defaults to localhost - not used for SQLite. MySQL socket connection can be made by entering `'sock:'` followed by the socket path. PostgreSQL socket connection can be made by passing just `'sock:'`.
* @param integer $port The port to connect to, defaults to the standard port for the database type specified - not used for SQLite
* @param integer $timeout The number of seconds to timeout after if a connection can not be made - not used for SQLite
* @return fDatabase
*/
public function __construct($type, $database, $username=NULL, $password=NULL, $host=NULL, $port=NULL, $timeout=NULL)
{
$valid_types = array('db2', 'mssql', 'mysql', 'oracle', 'postgresql', 'sqlite');
if (!in_array($type, $valid_types)) {
throw new fProgrammerException(
'The database type specified, %1$s, is invalid. Must be one of: %2$s.',
$type,
join(', ', $valid_types)
);
}
if (empty($database)) {
throw new fProgrammerException('No database was specified');
}
if ($host === NULL) {
$host = 'localhost';
}
$this->type = $type;
$this->database = $database;
$this->username = $username;
$this->password = $password;
$this->host = $host;
$this->port = $port;
$this->timeout = $timeout;
$this->hook_callbacks = array(
'unmodified' => array(),
'extracted' => array(),
'run' => array()
);
$this->schema_info = array();
$this->determineExtension();
}
/**
* Closes the open database connection
*
* @internal
*
* @return void
*/
public function __destruct()
{
if (!$this->connection) { return; }
fCore::debug('Total query time: ' . $this->query_time . ' seconds', $this->debug);
if ($this->extension == 'ibm_db2') {
db2_close($this->connection);
} elseif ($this->extension == 'mssql') {
mssql_close($this->connection);
} elseif ($this->extension == 'mysql') {
mysql_close($this->connection);
} elseif ($this->extension == 'mysqli') {
// Before 5.2.0 the destructor order would cause mysqli to
// close itself which would make this call trigger a warning
if (fCore::checkVersion('5.2.0')) {
mysqli_close($this->connection);
}
} elseif ($this->extension == 'oci8') {
oci_close($this->connection);
} elseif ($this->extension == 'pgsql') {
pg_close($this->connection);
} elseif ($this->extension == 'sqlite') {
sqlite_close($this->connection);
} elseif ($this->extension == 'sqlsrv') {
sqlsrv_close($this->connection);
} elseif ($this->extension == 'pdo') {
// PDO objects close their own connections when destroyed
}
$this->connection = FALSE;
}
/**
* All requests that hit this method should be requests for callbacks
*
* @internal
*
* @param string $method The method to create a callback for
* @return callback The callback for the method requested
*/
public function __get($method)
{
return array($this, $method);
}
/**
* Checks to see if an SQL error occured
*
* @param fResult|fUnbufferedResult|boolean $result The result object for the query
* @param mixed $extra_info The sqlite extension will pass a string error message, the oci8 extension will pass the statement resource
* @param string $sql The SQL that was executed
* @return void
*/
private function checkForError($result, $extra_info=NULL, $sql=NULL)
{
if ($result === FALSE || $result->getResult() === FALSE) {
if ($this->extension == 'ibm_db2') {
if (is_resource($extra_info)) {
$message = db2_stmt_errormsg($extra_info);
} else {
$message = db2_stmt_errormsg();
}
} elseif ($this->extension == 'mssql') {
$message = $this->error;
$this->error = '';
} elseif ($this->extension == 'mysql') {
$message = mysql_error($this->connection);
} elseif ($this->extension == 'mysqli') {
if (is_object($extra_info)) {
$message = $extra_info->error;
} else {
$message = mysqli_error($this->connection);
}
} elseif ($this->extension == 'oci8') {
$error_info = oci_error($extra_info ? $extra_info : $this->connection);
$message = $error_info['message'];
} elseif ($this->extension == 'pgsql') {
$message = pg_last_error($this->connection);
} elseif ($this->extension == 'sqlite') {
if ($extra_info === NULL) {
$message = sqlite_error_string(sqlite_last_error($this->connection));
} else {
$message = $extra_info;
}
} elseif ($this->extension == 'sqlsrv') {
$error_info = sqlsrv_errors(SQLSRV_ERR_ALL);
$message = $error_info[0]['message'];
} elseif ($this->extension == 'pdo') {
if ($extra_info instanceof PDOStatement) {
$error_info = $extra_info->errorInfo();
} else {
$error_info = $this->connection->errorInfo();
}
if (empty($error_info[2])) {
$error_info[2] = 'Unknown error - this usually indicates a bug in the PDO driver';
}
$message = $error_info[2];
}
$db_type_map = array(
'db2' => 'DB2',
'mssql' => 'MSSQL',
'mysql' => 'MySQL',
'oracle' => 'Oracle',
'postgresql' => 'PostgreSQL',
'sqlite' => 'SQLite'
);
throw new fSQLException(
'%1$s error (%2$s) in %3$s',
$db_type_map[$this->type],
$message,
is_object($result) ? $result->getSQL() : $sql
);
}
}
/**
* Clears all of the schema info out of the object and, if set, the fCache object
*
* @return void
*/
public function clearCache()
{
$this->schema_info = array();
if ($this->cache) {
$this->cache->delete($this->makeCachePrefix() . 'schema_info');
}
if ($this->type == 'mssql') {
$this->determineCharacterSet();
}
if ($this->translation) {
$this->translation->clearCache();
}
}
/**
* Closes the database connection
*
* @return void
*/
public function close()
{
$this->__destruct();
}
/**
* Connects to the database specified, if no connection exists
*
* This method is only intended to force a connection, all operations that
* require a database connection will automatically call this method.
*
* @throws fAuthorizationException When the username and password are not accepted
*
* @return void
*/
public function connect()
{
// Don't try to reconnect if we are already connected
if ($this->connection) { return; }
$connection_error = FALSE;
$authentication_error = FALSE;
$database_error = FALSE;
$errors = NULL;
// Establish a connection to the database
if ($this->extension == 'pdo') {
$username = $this->username;
$password = $this->password;
$options = array();
if ($this->timeout !== NULL && $this->type != 'sqlite' && $this->type != 'mssql') {
$options[PDO::ATTR_TIMEOUT] = $this->timeout;
}
if ($this->type == 'db2') {
if ($this->host === NULL && $this->port === NULL) {
$dsn = 'ibm:DSN:' . $this->database;
} else {
$dsn = 'ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=' . $this->database . ';HOSTNAME=' . $this->host . ';';
$dsn .= 'PORT=' . ($this->port ? $this->port : 60000) . ';';
$dsn .= 'PROTOCOL=TCPIP;UID=' . $username . ';PWD=' . $password . ';';
if ($this->timeout !== NULL) {
$dsn .= 'CONNECTTIMEOUT=' . $this->timeout . ';';
}
$username = NULL;
$password = NULL;
}
} elseif ($this->type == 'mssql') {
$separator = (fCore::checkOS('windows')) ? ',' : ':';
$port = ($this->port) ? $separator . $this->port : '';
$driver = (fCore::checkOs('windows')) ? 'mssql' : 'dblib';
$dsn = $driver . ':host=' . $this->host . $port . ';dbname=' . $this->database;
// This driver does not support timeouts so we fake it here
if ($this->timeout !== NULL) {
fCore::startErrorCapture();
$resource = fsockopen($this->host, $this->port ? $this->port : 1433, $errno, $errstr, $this->timeout);
$errors = fCore::stopErrorCapture();
if ($resource !== FALSE) {
fclose($resource);
}
}
} elseif ($this->type == 'mysql') {
if (substr($this->host, 0, 5) == 'sock:') {
$dsn = 'mysql:unix_socket=' . substr($this->host, 5) . ';dbname=' . $this->database;
} else {
$port = ($this->port) ? ';port=' . $this->port : '';
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->database . $port;
}
} elseif ($this->type == 'oracle') {
$port = ($this->port) ? ':' . $this->port : '';
$dsn = 'oci:dbname=' . $this->host . $port . '/' . $this->database . ';charset=AL32UTF8';
// This driver does not support timeouts so we fake it here
if ($this->timeout !== NULL) {
fCore::startErrorCapture();
$resource = fsockopen($this->host, $this->port ? $this->port : 1521, $errno, $errstr, $this->timeout);
$errors = fCore::stopErrorCapture();
if ($resource !== FALSE) {
fclose($resource);
}
}
} elseif ($this->type == 'postgresql') {
$dsn = 'pgsql:dbname=' . $this->database;
if ($this->host && $this->host != 'sock:') {
$dsn .= ' host=' . $this->host;
}
if ($this->port) {
$dsn .= ' port=' . $this->port;
}
} elseif ($this->type == 'sqlite') {
$dsn = 'sqlite:' . $this->database;
}
try {
if ($errors) {
$this->connection = FALSE;
} else {
$this->connection = new PDO($dsn, $username, $password, $options);
if ($this->type == 'mysql') {
$this->connection->setAttribute(PDO::MYSQL_ATTR_DIRECT_QUERY, 1);
}
}
} catch (PDOException $e) {
$this->connection = FALSE;
$errors = $e->getMessage();
}
}
if ($this->extension == 'sqlite') {
$this->connection = sqlite_open($this->database);
}
if ($this->extension == 'ibm_db2') {
$username = $this->username;
$password = $this->password;
if ($this->host === NULL && $this->port === NULL && $this->timeout === NULL) {
$connection_string = $this->database;
} else {
$connection_string = 'DATABASE=' . $this->database . ';HOSTNAME=' . $this->host . ';';
$connection_string .= 'PORT=' . ($this->port ? $this->port : 60000) . ';';
$connection_string .= 'PROTOCOL=TCPIP;UID=' . $this->username . ';PWD=' . $this->password . ';';
if ($this->timeout !== NULL) {
$connection_string .= 'CONNECTTIMEOUT=' . $this->timeout . ';';
}
$username = NULL;
$password = NULL;
}
$options = array(
'autocommit' => DB2_AUTOCOMMIT_ON,
'DB2_ATTR_CASE' => DB2_CASE_LOWER
);
$this->connection = db2_connect($connection_string, $username, $password, $options);
if ($this->connection === FALSE) {
$errors = db2_conn_errormsg();
}
}
if ($this->extension == 'mssql') {
if ($this->timeout !== NULL) {
$old_timeout = ini_get('mssql.connect_timeout');
ini_set('mssql.connect_timeout', $this->timeout);
}
fCore::startErrorCapture();
$separator = (fCore::checkOS('windows')) ? ',' : ':';
$this->connection = mssql_connect(($this->port) ? $this->host . $separator . $this->port : $this->host, $this->username, $this->password, TRUE);
if ($this->connection !== FALSE && mssql_select_db($this->database, $this->connection) === FALSE) {
$this->connection = FALSE;
}
$errors = fCore::stopErrorCapture();
if ($this->timeout !== NULL) {
ini_set('mssql.connect_timeout', $old_timeout);
}
}
if ($this->extension == 'mysql') {
if ($this->timeout !== NULL) {
$old_timeout = ini_get('mysql.connect_timeout');
ini_set('mysql.connect_timeout', $this->timeout);
}
if (substr($this->host, 0, 5) == 'sock:') {
$host = substr($this->host, 4);
} elseif ($this->port) {
$host = $this->host . ':' . $this->port;
} else {
$host = $this->host;
}
fCore::startErrorCapture();
$this->connection = mysql_connect($host, $this->username, $this->password, TRUE);
$errors = fCore::stopErrorCapture();
if ($this->connection !== FALSE && mysql_select_db($this->database, $this->connection) === FALSE) {
$errors = 'Unknown database';
$this->connection = FALSE;
}
if ($this->connection && function_exists('mysql_set_charset') && !mysql_set_charset('utf8', $this->connection)) {
throw new fConnectivityException(
'There was an error setting the database connection to use UTF-8'
);
}
if ($this->timeout !== NULL) {
ini_set('mysql.connect_timeout', $old_timeout);
}
}
if ($this->extension == 'mysqli') {
$this->connection = mysqli_init();
if ($this->timeout !== NULL) {
mysqli_options($this->connection, MYSQLI_OPT_CONNECT_TIMEOUT, $this->timeout);
}
fCore::startErrorCapture();
if (substr($this->host, 0, 5) == 'sock:') {
$result = mysqli_real_connect($this->connection, 'localhost', $this->username, $this->password, $this->database, $this->port, substr($this->host, 5));
} elseif ($this->port) {
$result = mysqli_real_connect($this->connection, $this->host, $this->username, $this->password, $this->database, $this->port);
} else {
$result = mysqli_real_connect($this->connection, $this->host, $this->username, $this->password, $this->database);
}
if (!$result) {
$this->connection = FALSE;
}
$errors = fCore::stopErrorCapture();
if ($this->connection && function_exists('mysqli_set_charset') && !mysqli_set_charset($this->connection, 'utf8')) {
throw new fConnectivityException(
'There was an error setting the database connection to use UTF-8'
);
}
}
if ($this->extension == 'oci8') {
fCore::startErrorCapture();
$resource = TRUE;
// This driver does not support timeouts so we fake it here
if ($this->timeout !== NULL) {
$resource = fsockopen($this->host, $this->port ? $this->port : 1521, $errno, $errstr, $this->timeout);
if ($resource !== FALSE) {
fclose($resource);
$resource = TRUE;
} else {
$this->connection = FALSE;
}
}
if ($resource) {
$this->connection = oci_connect($this->username, $this->password, $this->host . ($this->port ? ':' . $this->port : '') . '/' . $this->database, 'AL32UTF8');
}
$errors = fCore::stopErrorCapture();
}
if ($this->extension == 'pgsql') {
$connection_string = "dbname='" . addslashes($this->database) . "'";
if ($this->host && $this->host != 'sock:') {
$connection_string .= " host='" . addslashes($this->host) . "'";
}
if ($this->username) {
$connection_string .= " user='" . addslashes($this->username) . "'";
}
if ($this->password) {
$connection_string .= " password='" . addslashes($this->password) . "'";
}
if ($this->port) {
$connection_string .= " port='" . $this->port . "'";
}
if ($this->timeout !== NULL) {
$connection_string .= " connect_timeout='" . $this->timeout . "'";
}
fCore::startErrorCapture();
$this->connection = pg_connect($connection_string, PGSQL_CONNECT_FORCE_NEW);
$errors = fCore::stopErrorCapture();
}
if ($this->extension == 'sqlsrv') {
$options = array(
'Database' => $this->database
);
if ($this->username !== NULL) {
$options['UID'] = $this->username;
}
if ($this->password !== NULL) {
$options['PWD'] = $this->password;
}
if ($this->timeout !== NULL) {
$options['LoginTimeout'] = $this->timeout;
}
$this->connection = sqlsrv_connect($this->host . ',' . $this->port, $options);
if ($this->connection === FALSE) {
$errors = sqlsrv_errors();
}
sqlsrv_configure('WarningsReturnAsErrors', 0);
}
// Ensure the connection was established
if ($this->connection === FALSE) {
$this->handleConnectionErrors($errors);
}
// Make MySQL act more strict and use UTF-8
if ($this->type == 'mysql') {
$this->execute("SET SQL_MODE = 'REAL_AS_FLOAT,PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE'");
$this->execute("SET NAMES 'utf8'");
$this->execute("SET CHARACTER SET utf8");
}
// Make SQLite behave like other DBs for assoc arrays
if ($this->type == 'sqlite') {
$this->execute('PRAGMA short_column_names = 1');
}
// Fix some issues with mssql
if ($this->type == 'mssql') {
if (!isset($this->schema_info['character_set'])) {
$this->determineCharacterSet();
}
$this->execute('SET TEXTSIZE 65536');
$this->execute('SET QUOTED_IDENTIFIER ON');
}
// Make PostgreSQL use UTF-8
if ($this->type == 'postgresql') {
$this->execute("SET NAMES 'UTF8'");
}
// Oracle has different date and timestamp defaults
if ($this->type == 'oracle') {
$this->execute("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
$this->execute("ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS'");
$this->execute("ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH24:MI:SS TZR'");
$this->execute("ALTER SESSION SET NLS_TIME_FORMAT = 'HH24:MI:SS'");
$this->execute("ALTER SESSION SET NLS_TIME_TZ_FORMAT = 'HH24:MI:SS TZR'");
}
}
/**
* Determines the character set of a SQL Server database
*
* @return void
*/
protected function determineCharacterSet()
{
$this->schema_info['character_set'] = 'WINDOWS-1252';
$this->schema_info['character_set'] = $this->query("SELECT 'WINDOWS-' + CONVERT(VARCHAR, COLLATIONPROPERTY(CONVERT(NVARCHAR, DATABASEPROPERTYEX(DB_NAME(), 'Collation')), 'CodePage')) AS charset")->fetchScalar();
if ($this->cache) {
$this->cache->set($this->makeCachePrefix() . 'schema_info', $this->schema_info);
}
}
/**
* Figures out which extension to use for the database type selected
*
* @return void
*/
protected function determineExtension()
{
switch ($this->type) {
case 'db2':
if (extension_loaded('ibm_db2')) {
$this->extension = 'ibm_db2';
} elseif (class_exists('PDO', FALSE) && in_array('ibm', PDO::getAvailableDrivers())) {
$this->extension = 'pdo';
} else {
$type = 'DB2';
$exts = 'ibm_db2, pdo_ibm';
}
break;
case 'mssql':
if (extension_loaded('sqlsrv')) {
$this->extension = 'sqlsrv';
} elseif (extension_loaded('mssql')) {
$this->extension = 'mssql';
} elseif (class_exists('PDO', FALSE) && (in_array('dblib', PDO::getAvailableDrivers()) || in_array('mssql', PDO::getAvailableDrivers()))) {
$this->extension = 'pdo';
} else {
$type = 'MSSQL';
$exts = 'mssql, sqlsrv, pdo_dblib (linux), pdo_mssql (windows)';
}
break;
case 'mysql':
if (extension_loaded('mysqli')) {
$this->extension = 'mysqli';
} elseif (class_exists('PDO', FALSE) && in_array('mysql', PDO::getAvailableDrivers())) {
$this->extension = 'pdo';
} elseif (extension_loaded('mysql')) {
$this->extension = 'mysql';
} else {
$type = 'MySQL';
$exts = 'mysql, pdo_mysql, mysqli';
}
break;
case 'oracle':
if (extension_loaded('oci8')) {
$this->extension = 'oci8';
} elseif (class_exists('PDO', FALSE) && in_array('oci', PDO::getAvailableDrivers())) {
$this->extension = 'pdo';
} else {
$type = 'Oracle';
$exts = 'oci8, pdo_oci';
}
break;
case 'postgresql':
if (extension_loaded('pgsql')) {
$this->extension = 'pgsql';
} elseif (class_exists('PDO', FALSE) && in_array('pgsql', PDO::getAvailableDrivers())) {
$this->extension = 'pdo';
} else {
$type = 'PostgreSQL';
$exts = 'pgsql, pdo_pgsql';
}
break;
case 'sqlite':
$sqlite_version = 0;
if (file_exists($this->database)) {
$database_handle = fopen($this->database, 'r');
$database_version = fread($database_handle, 64);
fclose($database_handle);
if (strpos($database_version, 'SQLite format 3') !== FALSE) {
$sqlite_version = 3;
} elseif (strpos($database_version, '** This file contains an SQLite 2.1 database **') !== FALSE) {
$sqlite_version = 2;
} else {
throw new fConnectivityException(
'The database specified does not appear to be a valid %1$s or %2$s database',
'SQLite v2.1',
'v3'
);
}
}
if ((!$sqlite_version || $sqlite_version == 3) && class_exists('PDO', FALSE) && in_array('sqlite', PDO::getAvailableDrivers())) {
$this->extension = 'pdo';
} elseif ($sqlite_version == 3 && (!class_exists('PDO', FALSE) || !in_array('sqlite', PDO::getAvailableDrivers()))) {
throw new fEnvironmentException(
'The database specified is an %1$s database and the %2$s extension is not installed',
'SQLite v3',
'pdo_sqlite'
);
} elseif ((!$sqlite_version || $sqlite_version == 2) && extension_loaded('sqlite')) {
$this->extension = 'sqlite';
} elseif ($sqlite_version == 2 && !extension_loaded('sqlite')) {
throw new fEnvironmentException(
'The database specified is an %1$s database and the %2$s extension is not installed',
'SQLite v2.1',
'sqlite'
);
} else {
$type = 'SQLite';
$exts = 'pdo_sqlite, sqlite';
}
break;
}
if (!$this->extension) {
throw new fEnvironmentException(
'The server does not have any of the following extensions for %2$s support: %2$s',
$type,
$exts
);
}
}