-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathDataObject.php
executable file
·5998 lines (4963 loc) · 196 KB
/
DataObject.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
/**
* Object Based Database Query Builder and data store
*
* For PHP versions 5 and 7
*
*
* Copyright (c) 2016 Alan Knowles
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category Database
* @package PDO_DataObject
* @author Alan Knowles <[email protected]>
* @copyright 2016 Alan Knowles
* @license https://www.gnu.org/licenses/lgpl-3.0.en.html LGPL 3
* @version 1.0
* @link https://github.com/roojs/PDO_DataObject
*/
class PDO_DataObject
{
/**
* The Version - use this to check feature changes
*
* @access private
* @var string
*/
public $_PDO_DataObject_version = "@version@";
/* ---------------- ---------------- Constants -------------------------------- */
/**
* these are constants for the get_table array
* user to determine what type of escaping is required around the object vars.
*/
const INT = 1; // does not require ''
const STR = 2; // requires ''
const DATE = 4; // is date
const TIME = 8; // is time
const BOOL = 16; // is boolean
const TXT = 32; // is long text
const BLOB = 64; // is blob type
const NOTNULL = 128; // not null col.
const MYSQLTIMESTAMP = 256; // mysql timestamps (ignored by update/insert)
/**
* Used for clarity in methods like delete() and count() to specify that the method should
* build the condition only out of the whereAdd's and not the object parameters.
* use WHERE_ONLY now.. whereadd's only the for easier conversion.
*/
const WHEREADD_ONLY = true;
const WHERE_ONLY = true;
/**
* Used for clarity in delete() - behaves like old DataObjects, uses all object properties
* rather than only primary keys to enable delete.
*/
const DANGER_USE_ALL_PROPS = -1;
/**
* optional modes for find()
* FOR_UPDATE => SELECT ... FOR UPDATE
* IN_SHARE_MODE => SELECT ... LOCK IN SHARE MODE
*/
const FOR_UPDATE = "FOR UPDATE";
const IN_SHARE_MODE = "LOCK IN SHARE MODE";
/**
* used by config[portability]
*/
const PORTABILITY_LOWERCASE = 1; // from Pear DB compatibility options..
/**
*
* Theses are the standard error codes -
*
*/
const ERROR_INVALIDARGS = 'InvalidArgs'; // wrong args to function
const ERROR_NODATA = 'NoData'; // no data available
const ERROR_INVALIDCONFIG = 'InvalidConfig'; // something wrong with the config
const ERROR_NOCLASS = 'NoClass'; // no class exists
const ERROR_SET = 'Set'; // set() caused errors when calling set*** methods.
const ERROR_QUERY = 'Query'; // if query throws an error....
const ERROR_CONNECT = 'Connect'; // if connect throws an error....
/* ---------------- ---------------- static -------------------------------- */
/**
* Configuration - use PDO_DataObject::config() to access this.
*
* @access private
* @static
* @var array
*/
private static $config = array(
// connection related
'database' => false,
// the default database dsn (not PDO standard = see @$_database for details)
// it's similar format to PEAR::DB..
'databases' => array(),
// map of database nick-names to connection dsn's
'tables' => array(),
// map of tables names to database 'nick-names'
// schema (INI files)
'schema_location' => false,
// unless you are using 'proxy' then schema_location is required.
// possible values:
// String = directory, or list of directories (with path Seperator..)
// eg. if your database schema is in /var/www/mysite/Myproejct/DataObject/mydb.ini
// then schema_location = /var/www/mysite/Myproejct/DataObject/
// you can use path seperator if there are multiple paths. and combined
// Array = map of database names to exact location(s).
// eg.
// mydb => /var/www/mysite/Myproejct/DataObject/mydb.ini
// value can be an array of absolute paths, or PATH_SEPERATED
// class - factory + load derived classes
'class_prefix' => 'DataObjects_',
// Prefix Mapping of table name to PHP Class
// to use multiple prefixes seperate them with PATH_SEPERATOR
// for 'loading' it will try them all in sequence.. - first found wins.
// for the generator it will only use the first..
'class_location' => '',
// directory where the Table classes are..
// you can also use the format
// /home/me/Projects/myapplication/DataObjects_%s.php (%s==table)
// /home/me/Projects/myapplication/DataObjects_%2$s%1$s.php (%1$s==table) (%2$s==database nickname)
// and %s gets replaced with the tablename.
// to use multiple search paths use the PATH_SEPERATOR
'proxy' => false,
// NOT RECOMMENDED - it's very slow!!!!
// normally we use pre-created 'ini' files, but if you use proxy, it will generate the
// the database schema on the fly..
// true - calls PDO_DataObject_Generator-> ???
// full - generates dataobjects when you call factory...
// YourClass::somemethod... --- calls some other method to generate proxy..
'portability' => 0,
// similar to DB's portability setting,
// currently it only lowercases the tablename when you call tableName(), and
// flatten's ini files ..
'transactions' => true,
// some databases, like sqlite do not support transactions, so if you have code that
// uses transactions, and you want DataObjects to ignore the BEGIN/COMMIT/ROLLBACK etc..
// then set this to false, otherwise you will get errors.
'quote_identifiers' => false,
// Quote table and column names when building queries
'enable_null_strings' => false,
// This is only for BC support -
// previously you could use 'null' as a string to represent a NULL, or even null
// however this behaviour is very problematic.
//
// if you want or needto use NULL in your database:
// use PDO_DataObject::sqlValue('NULL');
// BC - not recommended for new code...
// values true means 'NULL' as a string is supported
// values 'full' means both 'NULL' and guessing with isset() is supported
'enable_dangerous_delete' => false,
// This is only for BC support -
// previously you could use delete(), and it would use all of the object properties
// to build a query to delete the data. Since a single typo can wipe out a large part of your
// database.. this is disabled by default now.
// deleting this way can still be done by calling delete with PDO_DataObject::DANGER_USE_ALL_PROPS.
'table_alias' => array(),
// NEW ------------ peformance
'fetch_into' => false,
// use PDO's fetch_INTO for performance... - not sure what other effects this may have..
// ----- behavior
'debug' => 0,
// debuging - only relivant on initialization - modifying it after, may be ignored.
'PDO' => 'PDO',
// what class to use as PDO - we use PDO_Dummy for the unittests
// -------- Error handling --------
);
private static $debug = 0; // set by config() and debugLevel()
/**
* Connections [md5] => PDO
* note - we overload PDO with some values
* $pdo->database (as there is no support for it..!)
*/
private static $connections = array(); // md5 map of connections to DSN
// use databaseStructure to set these...
// mapping of database(??realname??) to ini file results
private static $ini = array();
// mapping of database to links file (foreign keys really)
private static $links = array();
// cache of sequence keys ??- used by autoincrement?? -- need to check..
private static $sequence = array();
// factory cache's it's input / output results.. (can be reset with reset()
private static $factory_cache = array();
/**
* calling set() may throw an exception.
* -> you can catch PDO_DataObject_Exception_Set , and check this value to see what failed.
*
* @var array the errors (key == the object key, value == the error messages/return from set****)
*
*/
public static $set_errors = false;
/* ---------------- ---------------- non-static -------------------------------- */
/**
* The Database table (used by table extends)
*
* @access semi-private (not recommened - by you can modify it...)
* @var string
*/
public $__table = ''; // database table
/**
* The Database nick-name (usually matches the real database name, but may not..)
* created in __connection
* Note - this used to be called _database - however it's not guarenteed to be the real database name,
* for that use PDO()->dsn[database_name]
*
* @access private (ish) - extended classes can overide this
* @var string
*/
public $_database_nickname = false;
/* ---------------- ---------------- connecting to the database -------------------------------- */
/**
* The Database connection id (md5 sum of databasedsn)
*
* @access private (ish) - extended classes can overide this
* @var string
*/
private $_database_dsn_md5 = '';
/**
* The PDOStatement Result object. accesable by result() ????
* created in _query()
*
* @access private
* @var PDOStatement|StdClass|false
*/
private $_result = false;
/**
* The Number of rows returned from a query
* false = nothing fetched yet.
* 0...9999..... number of rows returned by find/query etc.
* true = sqlite - not able to find number of results.
*
* @access public
* @var int|boolean
*/
public $N = false; // Number of rows returned from a query
/**
* The QUERY rules
* This replaces alot of the private variables
* used to build a query, it is unset after find() is run.
*
*
* @access private
* @var array
*/
private $_query = array(
'condition' => '', // the WHERE condition
'group_by' => '', // the GROUP BY condition
'order_by' => '', // the ORDER BY condition
'having' => '', // the HAVING condition
'useindex' => '', // the USE INDEX condition
'limit_start' => '', // the LIMIT condition
'limit_count' => '', // the LIMIT condition
'data_select' => false, // the columns to be SELECTed (false == '*') the default.
'derive_table' => '', // derived table name (BETA)
'derive_select' => '', // derived table select (BETA),
'unions' => array(), // unions
'locking' => false,
);
/**
* The JOIN condition - this get's modified by extended classes alot
*
*
* @access public
* @var string
*/
public $_join = '';
/**
* array of links.. - if relivant.
* NOTE - not sure if we should leave this defined here?? only defined if created by PDO_DataObject_Links
* Not generally recommended -- JOIN or using the generator is a better method of
* cross referencing related objects.
*
* @access private
* @var boolean | array
*/
public $_link_loaded = false;
/**
* Constructor
* This is not normally used. it's better to use factory to load extended dataObjects.
*
* Can be used to create on-the fly DataObjects. not heavily tested yet though...
* Should be used with config[proxy] = true
*
* Normally you would extend this class an fill it up with methods that relate to actions on that table
*
* usage:
* ```
* $a = new PDO_DataObject('person');
* $a = new PDO_DataObject('mydatabase/person');
* $a = new PDO_DataObject(['mydatabase','person']);
* ```
*
* @param string|array either tablename or databasename/tablename or array(database,tablename)
* @category create
*/
function __construct($cfg = false)
{
if ($cfg === false) {
return;
}
if (self::$debug) {
$this->debug(json_encode(func_get_args()), __FUNCTION__,1);
}
if (!is_array($cfg)) {
$cfg = explode('/', $cfg);
}
$this->__table = count($cfg) > 1 ? $cfg[1] : $cfg[0];
if (count($cfg) > 1) {
$this->_database_nickname = $cfg[0];
} else if (isset(self::$config['tables'][$this->__table])) {
$this->_database_nickname = self::$config['tables'][$this->__table];
}
// should error out if database is not set.. or know..
$ds = $this->databaseStructure();
if (!isset($ds[$this->__table])) {
$this->raise("Could not find INI values for database={$this->_database_nickname} and table={$this->__table}",
self::ERROR_INVALIDARGS );
}
// should this trigger a tableStructure..
// if you are using it this way then using 'proxy' = true is probably required..
}
/**
* connects to the database and returns the [PDO](//www.php.net/PDO) object
*
* Basedon the objects table and database settings it will connect to the database
* as set by the configuratino, and return the PDO object.
*
* the PDO object has `$PDO->dsn` set to and array, of which
* `$PDO->dsn['database_name']` should contain the real database name.
*
* @category results
* @access public
* @return PDO Object the connection
*/
final function PDO()
{
$config = self::config();
// We can use a fake PDO class when testing..
$PDO = $config['PDO'];
// is it already connected ?
if ($this->_database_dsn_md5 && !empty(self::$connections[$this->_database_dsn_md5])) {
$con = self::$connections[$this->_database_dsn_md5];
// connection is an error...?? assumes pear error???
if (!is_a($con, $PDO)) {
return $this->raise( "Error with cached connection", self::ERROR_INVALIDCONFIG, $con);
}
if (empty($this->_database_nickname)) {
$this->_database = $con->dsn['nickname'];
// note
// sqlite -- database == basename of database...
// ibase -- last 4 characters (substring basename, 0, -4 )
}
if (self::$debug) {
$this->debug("Using Cached connection",__FUNCTION__,4); // occurs quite a lot...
}
// theoretically we have a md5, it's listed in connections and it's not an error.
// so everything is ok!
return $con;
}
$tn = $this->tableName();
if (!$this->_database_nickname && strlen($tn)) {
$this->_database_nickname = isset(self::$config['tables'][$tn]) ? self::$config['tables'][$tn] : false;
}
if (self::$debug && $this->_database_nickname) {
$this->debug("Checking for database specific ini ('{$this->_database_nickname}') : config[databases][$this->_database_nickname] in options",__FUNCTION__);
}
if ($this->_database_nickname && !empty(self::$config['databases'][$this->_database_nickname])) {
$dsn = self::$config['databases'][$this->_database_nickname];
} else if (false !== self::$config['database']) {
$dsn = self::$config['database'];
}
// if we still do not know the database - look through the available ones, and see if we can find the table..
// it ignores the issue that multiple databases may have the same tables in them...!?!?
if (!$dsn && !empty(self::$config['databases'])) {
foreach(self::$config['databases'] as $db=>$connect_dsn) {
$s = $this->databaseStructure($db);
if (isset($s[$this->tableName()])) {
$dsn = $connect_dsn;
$this->_database_nickname = $db;
break;
}
}
}
// if still no database...
if (!$dsn) {
return $this->raise(
"No database name / dsn found anywhere",
self::ERROR_INVALIDCONFIG
);
}
$md5 = md5($dsn); // we used to support array of dsn? - not sure why... as you should use a proxy here...
$this->_database_dsn_md5 = $md5;
// we now have the dsn +
if (!empty(self::$connections[$md5])) {
if (self::$debug) {
$this->debug("USING CACHED CONNECTION", __FUNCTION__,3);
}
if (!$this->_database_nickname) {
$this->_database_nickname = self::$connections[$md5]->dsn['nickname'];
}
return self::$connections[$md5];
}
$dsn_ar = parse_url($dsn);
// create a pdo dsn....
switch($dsn_ar['scheme'] ) {
case 'sqlite':
case 'sqlite2':
$pdo_dsn = $dsn_ar['scheme'] . ':' .$dsn_ar['path']; // urldec917ode perhaps?
$dsn_ar['database_name'] = basename($dsn_ar['path']);
break;
case 'sqlsrv':
$pdo_dsn =
$dsn_ar['scheme'] . ':' .
'Database=' . substr($dsn_ar['path'],1) .
(empty($dsn_ar['host']) ? '': ';Server=' . $dsn_ar['host']) .
(empty($dsn_ar['port']) ? '' : ',' . $dsn_ar['port']);
$dsn_ar['database_name'] = substr($dsn_ar['path'],1);
break;
case 'oci':
$pdo_dsn = $dsn_ar['scheme'] . ':';
$dsn_ar['database_name'] = empty($dsn_ar['path']) ? $dsn_ar['host'] : substr($dsn_ar['path'],1);
switch(true) {
// oracle instant client..
case (!empty($dsn_ar['host']) && !empty($dsn_ar['port'])):
$pdo_dsn .= 'dbname=//' . $dsn_ar['host']. ':'. $dsn_ar['port'] . $dsn_ar['path'];
break;
// this is from the comments on pdo page...?
case (!empty($dsn_ar['host']) && !empty($dsn_ar['path'])):
$pdo_dsn .= 'dbname=' . $dsn_ar['host'] . $dsn_ar['path'];
break;
default:
$pdo_dsn .= 'dbname=' . $dsn_ar['database_name'] ;
break;
}
break;
// others go here...
default:
// by default we need to validate a little bit..
if (empty($dsn_ar['host']) || empty($dsn_ar['path']) || strlen($dsn_ar['path']) < 2) {
return $this->raise("Invalid syntax of DSN : {$dsn}\n". print_r($dsn_ar,true), self::ERROR_INVALIDCONFIG);
}
$pdo_dsn =
$dsn_ar['scheme'] . ':' .
'dbname=' . substr($dsn_ar['path'],1) .
(empty($dsn_ar['host']) ? '': ';host=' . $dsn_ar['host']) .
(empty($dsn_ar['port']) ? '' : ';port=' . $dsn_ar['port']);
$dsn_ar['database_name'] = substr($dsn_ar['path'],1);
break;
}
if (!empty($dsn_ar['query'])) {
$pdo_dsn .= ';' . str_replace('&', ';', $dsn_ar['query']); // could just str_replace..
}
$opts = array();
if (!empty($dsn_ar['fragment'])) {
// options.. |MYSQL_ATTR_INIT_COMMAND=....|
$pdo_rc = new ReflectionClass( "PDO" );
foreach(explode('|', $dsn_ar['fragment']) as $opt) {
list($k,$v) = explode('=', $opt);
$opts[$pdo_rc->getConstant($k)] = $v;
}
}
if (self::$debug) {
$this->debug("NEW CONNECTION TO DATABASE :" .$dsn_ar['database_name'], __FUNCTION__,3);
/* actualy make a connection */
$this->debug(print_r($dsn,true) . ' ' . $pdo_dsn . ' ' . $this->_database_dsn_md5, __FUNCTION__,3);
}
$username = isset($dsn_ar['user']) ? urldecode( $dsn_ar['user'] ): '';
$password = isset($dsn_ar['pass']) ? urldecode( $dsn_ar['pass'] ): '';
// might throw an eror..
try {
self::$connections[$md5] = new $PDO($pdo_dsn, $username, $password, $opts );
self::$connections[$md5]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // just in case?
} catch (PDOException $ex) {
$this->debug( (string) $ex , __FUNCTION__,5);
return $this->raise("Connect failed, turn on debugging to 5 see why", self::ERROR_CONNECT, $ex );
}
if (self::$debug) {
$this->debug(print_r(self::$connections,true), __FUNCTION__,5);
}
$dsn_ar['nickname'] = empty($this->_database_nickname) ?
$dsn_ar['database_name'] : $this->_database_nickname;
self::$connections[$md5]->dsn = $dsn_ar;
if (empty($this->_database_nickname)) {
$this->_database_nickname = $dsn_ar['nickname'] ;
}
// Oracle need to optimize for portibility - not sure exactly what this does though :)
return self::$connections[$md5];
}
/**
* Set/get the global configuration...
*
* Usage:
*
* Fetch the current config.
* ```php
* $cfg = PDO_DataObject::config();
* ```
*
* SET a configuration value. (returns old value.)
* ```php
* $old = PDO_DataObject::config('schema_location', '');
* ```
*
* GET a specific value ** does not do this directly to stop errors...
* ```php
* $somevar = PDO_DataObject::config()['schema_location'];
* ```
*
* SET multiple values (returns 'old' configuration)
* ```php
* $old_array = PDO_DataObject::config( array( 'schema_location' => '' ));
* ```
*
*
*
* # Configuration Options:
*
* ### Connection related
*
* | Option | Type | Default | Description |
* | --- | --- | --- | --- |
* | database | string | false | <span>the default database dsn (not PDO standard = see #$_database for details) \
* it's similar format to PEAR::DB.. </span> |
* | databases | array | array() | map of database nick-names to connection dsn's
* | tables | array | array() | map of tables names to database 'nick-names'
*
* ### Schema location
*
* | Option | Type | Default | Description |
* | --- | --- | --- | --- |
* | schema_location | mixed | false | \
* unless you are using 'proxy' then schema_location is required.
* | | string | | directory, or list of directories (with path Seperator..) \
* eg. if your database schema is in /var/www/mysite/Myproejct/DataObject/mydb.ini <BR/>\
* then schema_location = /var/www/mysite/Myproejct/DataObject/ <BR/>\
* you can use path seperator if there are multiple paths. and combined |
* | | array | | map of database names to exact location(s). <BR/>\
* eg. <BR/>\
* mydb => /var/www/mysite/Myproejct/DataObject/mydb.ini <BR/>\
* value can be an array of absolute paths, or PATH_SEPERATED <BR/> |
*
*
* ### Class factory loading and extended class naming
* | Option | Type | Default | Description |
* | --- | --- | --- | --- |
* | class_prefix | string | 'DataObjects_' | \
* Prefix Mapping of table name to PHP Class <br/>\
* to use multiple prefixes seperate them with PATH_SEPERATOR <br/>\
* for 'loading' it will try them all in sequence.. - first found wins. <br/>\
* for the generator it will only use the first.. |
* | class_location | string | '' | \
* directory where the Table classes are.. <br/>\
* you can also use formating <br/>\
* /home/me/Projects/myapplication/DataObjects_%s.php (%s==table) <br/>\
* /home/me/Projects/myapplication/DataObjects_%2$s%1$s.php (%1$s==table) (%2$s==database nickname) <br/>\
* and %s gets replaced with the tablename. <br/>\
* to use multiple search paths use the PATH_SEPERATOR <br/>
* | proxy | mixed | false | \
* NOT RECOMMENDED for normal usage, it's very slow!!!! <br/>\
* normally we use pre-created 'ini' files, but if you use proxy, it will generate the the database schema on the fly.. |
* | | | true | calls PDO_DataObject_Generator for schema |
* | | | 'full'| generates dataobjects when you call factory... |
* | | | 'YourClass::somemethod' | calls some other method to generate proxy.. |
*
*
* ### SQL Generation
* | Option | Type | Default | Description |
* | --- | --- | --- | --- |
* | portability | Number | 0 | similar to DB's portability setting <br/>\
* currently it only lowercases the tablename when you call tableName(), and \
* flatten's ini files .. |
* | transactions | boolean | true | some databases, like sqlite do not support transactions, so if you have code that \
* uses transactions, and you want DataObjects to ignore the BEGIN/COMMIT/ROLLBACK etc.. \
* then set this to false, otherwise you will get errors. |
* | quote_identifiers | boolean | false | Quote table and column names when building queries |
* | enable_null_strings | mixed | false | This is only for BC support - <br/>\
* previously you could use 'null' as a string to represent a NULL, or even null <br/>\
* however this behaviour is very problematic. <br/>\
* <br/>\
* if you want or needto use NULL in your database: <br/>\
* use PDO_DataObject::sqlValue('NULL'); <br/>\
* <br/>\
* BC - not recommended for new code... <br/>\
* values true means 'NULL' as a string is supported <br/>\
* values 'full' means both 'NULL' and guessing with isset() is supported |
* | table alias | array | [] | map of 'new names' to 'current names' <br/>\
* if you are renaming tables, for example from 'Person' to 'core_person' \
* and have updated the factory methods, but not the database.<br/>\
* This can be used as ``` 'core_person' => 'Person' ``` ensure operations \
* use the correct database name when quering the database. <br/>\
* note it does not affect RAW queries) when using ``` $do->query() ``` |
*
*
* ### Performance and debugging
* | Option | Type | Default | Description |
* | --- | --- | --- | --- |
* | fetch_into | boolean | false | use PDO's fetch_INTO for performance... - not sure what other effects this may have.. |
* | debug | mixed | 0 | debuging see #pdo-dataobject-debugLevel |
* | PDO | string | 'PDO' | what class to use as PDO - PDO_Dummy is used for the unittests |
*
*
*
* @category config
* @param array|string (optional) either a key value array, or the key to set.
* @param mixed (optional) the value to set when using key/value format
* @static
* @access public
* @return array the current config array
*/
static function config($cfg_in = array(), $value=false)
{
if (!func_num_args()) {
return self::$config;
}
if (!is_array($cfg_in) && func_num_args() < 2) {
// one arg = not an array..
(new PDO_DataObject())->raise("Invalid Call to config should be string+anther value or array",
self::ERROR_INVALIDARGS);
}
$old = self::$config;
$cfg = $cfg_in;
if (func_num_args() > 1) {
// two args..
if (!is_string($cfg_in)) {
(new PDO_DataObject())->raise("Invalid Call to config should be string+anther value or array",
self::ERROR_INVALIDARGS);
}
$k = $cfg_in;
$cfg = array();
$cfg[$k] = $value;
}
foreach ($cfg as $k=>$v) {
if (!isset(self::$config[$k])) {
(new PDO_DataObject())->raise("Invalid Configuration setting : $k",
self::ERROR_INVALIDCONFIG);
}
self::$config[$k] = $v;
}
if (isset($cfg['debug'])) {
self::$debug = $cfg['debug'];
}
return is_array($cfg_in) ? $old : $old[$cfg_in];
}
/* ---------------- ---------------- database portability methods -------------------------------- */
/**
* similar to escape - but for identifiers, like column names.
*
* When use use the [configuration option](#pdo-dataobject/config) 'quote_identifiers' = true, then
* This is called when building the query to ensure the database columns are quoted.
*
* If you are using a database that uses keywords like 'where' as a column name, then you should use
* this setting, and call this method if you are building the where conditions manually.
*
* @category build
* @param string $identifier identifier to wrap
* @result string wrapped string
*
*/
final function quoteIdentifier($str)
{
$pdo = $this->PDO();
switch($pdo->getAttribute(PDO::ATTR_DRIVER_NAME)) {
case 'mysql':
return '`' . str_replace('`', '``', $str) . '`';
case 'mssql':
case 'sybase':
return '[' . str_replace(']', ']]', $str) . ']';
default: // pretty much most databases....
return '"' . str_replace('"', '""', $str) . '"'; // not sure if this works..
// some don't suppor it -> msql
// odbc?? - do we deal with this?
}
}
/**
* modifies an sql query, filling in the limit's as defined in _query[limit_start / limit_count]
*
* This is used internally to modify the SELECT query to apply rules about limiting the resultsets.
* You should not need to use this normally - it's just publicly available as it's pretty harmless...
*
* @author Benedict Reuthlinger (MSSQL)
* @category build
* @param string $sql the query to modify
* @param bool $manip is the query a manipluation?
* @return string the modified string
*
*/
final function modifyLimitQuery($sql, $manip=false)
{
$start = $this->_query['limit_start'];
$count = $this->_query['limit_count'];
if ($start === '' && $count === '') {
return $sql;
}
$count = (int)$count;
$start = (int)$start;
$drv = $this->PDO()->getAttribute(PDO::ATTR_DRIVER_NAME);
switch($drv) {
case 'mysql':
if ($manip && $start) {
$this->raise("Mysql may not support offset in modification queries",
self::ERROR_INVALIDARGS); // from PEAR DB?
}
$start = empty($start) ? '': ($start .',');
return "$sql LIMIT $start $count";
case 'sqlite':
case 'sqlite2':
case 'pgsql':
return "$sql LIMIT $count OFFSET $start";
case 'oci':
if ($manip) {
$this->raise("Oracle may not support offset in modification queries",
self::ERROR_INVALIDARGS); // from PEAR DB?
}
// from http://stackoverflow.com/questions/2912144/alternatives-to-limit-and-offset-for-paging-in-oracle
// note, it adds an extra column _pdo_rnum.... but we should be able to ingore it.
return "SELECT * FROM (
SELECT
rownum _pdo_rnum, pdo_do.*
FROM (
{$sql}
) _pdo_do
WHERE rownum <= {$start}+{$count}
)
WHERE rnum >= {$start}
";
case 'mssql':
case 'sqlsrv':
if ($manip) {
$this->raise("Limit-Query:Mssql may not support offset,count in modification queries",
self::ERROR_INVALIDARGS); // from PEAR DB?
}
$order_by = $this->_query['order_by'];
if (empty($order_by)) {
$this->raise("Limit-Query: Mssql may not support offset,count without ORDER BY",
self::ERROR_INVALIDARGS); // from PEAR DB?
}
if (!is_numeric($start)) {
$start = 0;
}
if (!is_numeric($count)) {
$this->raise("Limit-Query: Mssql: \$count has NO numeric Value!",
self::ERROR_INVALIDARGS); // from PEAR DB?
}
return $sql . ' OFFSET ' . $start . ' ROWS FETCH NEXT ' . $count . ' ROWS ONLY';
default:
$this->raise("The Database $drv, does not support limit queries - if you know how this can be added, please send a patch.",
self::ERROR_INVALIDARGS); // from PEAR DB?
}
}
/* ============================================================= */
/* Major Public Methods */
/* (designed to be optionally then called with parent::method()) */
/* ============================================================= */
/**
* Get a result using key, value.
*
* Usage:
* ```
* $object->get(1234);
*
* $object->get("email",'[email protected]');
* ```
* Returns Number of rows located (usually 1) for success,
* and puts all the table columns into this classes variables
*
*
* if no `$value` is entered, it is assumed that `$key` is a value
* and get will then use the first key in keys()
* to obtain the key.
*
* @category fetch
* @param mixed $k column (or primary key value)
* @param mixed $v (optional) value
* @throws PDO_DataObject_Exception
* @access public
* @return int No. of rows
*/
final function get($k = null, $v = null)
{
$keys = array();
if ($v === null) {
$v = $k;
$keys = $this->keys();
if (!$keys) {
return $this->raise("No Keys available for table '{$this->tableName()}'", self::ERROR_INVALIDCONFIG);
}
$k = $keys[0];
}
if (self::$debug) {
$this->debug('('.var_export($k,true) . ', ' . var_export($v,true) . ') keys= ' .print_r($keys,true), __FUNCTION__);
}
if ($v === null) {
return $this->raise("No Value specified for get", self::ERROR_INVALIDARGS);
}