-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeneric.php
More file actions
1362 lines (1218 loc) · 43.7 KB
/
Generic.php
File metadata and controls
1362 lines (1218 loc) · 43.7 KB
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
/**
* DbSimple_Generic: universal database connected by DSN.
* (C) Dk Lab, http://en.dklab.ru
*
* This library 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; either
* version 2.1 of the License, or (at your option) any later version.
* See http://www.gnu.org/copyleft/lesser.html
*
* Use static DbSimple_Generic::connect($dsn) call if you don't know
* database type and parameters, but have its DSN.
*
* Additional keys can be added by appending a URI query string to the
* end of the DSN.
*
* The format of the supplied DSN is in its fullest form:
* phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
*
* Most variations are allowed:
* phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
* phptype://username:password@hostspec/database_name
* phptype://username:password@hostspec
* phptype://username@hostspec
* phptype://hostspec/database
* phptype://hostspec
* phptype(dbsyntax)
* phptype
*
* Parsing code is partially grabbed from PEAR DB class,
* initial author: Tomas V.V.Cox <cox@idecnet.com>.
*
* Contains 3 classes:
* - DbSimple_Generic: database factory class
* - DbSimple_Generic_Database: common database methods
* - DbSimple_Generic_Blob: common BLOB support
* - DbSimple_Generic_LastError: error reporting and tracking
*
* Special result-set fields:
* - ARRAY_KEY* ("*" means "anything")
* - PARENT_KEY
*
* Transforms:
* - GET_ATTRIBUTES
* - CALC_TOTAL
* - GET_TOTAL
* - UNIQ_KEY
*
* Query attributes:
* - BLOB_OBJ
* - CACHE
*
* @author Dmitry Koterov, http://forum.dklab.ru/users/DmitryKoterov/
* @author Konstantin Zhinko, http://forum.dklab.ru/users/KonstantinGinkoTit/
*
* @version 2.x $Id$
*/
/**
* Use this constant as placeholder value to skip optional SQL block [...].
*/
define('DBSIMPLE_SKIP', log(0));
/**
* Names of special columns in result-set which is used
* as array key (or karent key in forest-based resultsets) in
* resulting hash.
*/
define('DBSIMPLE_ARRAY_KEY', 'ARRAY_KEY'); // hash-based resultset support
define('DBSIMPLE_PARENT_KEY', 'PARENT_KEY'); // forrest-based resultset support
/**
* DbSimple factory.
*/
class DbSimple_Generic
{
/**
* DbSimple_Generic connect(mixed $dsn)
*
* Universal static function to connect ANY database using DSN syntax.
* Choose database driver according to DSN. Return new instance
* of this driver.
*/
function& connect($dsn)
{
// Load database driver and create its instance.
$parsed = DbSimple_Generic::parseDSN($dsn);
if (!$parsed) {
$dummy = null;
return $dummy;
}
$class = 'DbSimple_'.ucfirst($parsed['scheme']);
if (!class_exists($class)) {
$file = str_replace('_', '/', $class) . ".php";
// Try to load library file from standard include_path.
if ($f = @fopen($file, "r", true)) {
fclose($f);
require_once($file);
} else {
// Wrong include_path; try to load from current directory.
$base = basename($file);
$dir = dirname(__FILE__);
if (@is_file($path = "$dir/$base")) {
require_once($path);
} else {
trigger_error("Error loading database driver: no file $file in include_path; no file $base in $dir", E_USER_ERROR);
return null;
}
}
}
$object = new $class($parsed);
if (isset($parsed['ident_prefix'])) {
$object->setIdentPrefix($parsed['ident_prefix']);
}
$object->setCachePrefix(md5(serialize($parsed['dsn'])));
if (@fopen('Cache/Lite.php', 'r', true)) {
$tmp_dirs = array(
ini_get('session.save_path'),
getenv("TEMP"),
getenv("TMP"),
getenv("TMPDIR"),
'/tmp'
);
foreach ($tmp_dirs as $dir) {
if (!$dir) continue;
$fp = @fopen($testFile = $dir . '/DbSimple_' . md5(getmypid() . microtime()), 'w');
if ($fp) {
fclose($fp);
unlink($testFile);
require_once 'Cache' . '/Lite.php'; // "." -> no phpEclipse notice
$t = new Cache_Lite(array('cacheDir' => $dir.'/', 'lifeTime' => null, 'automaticSerialization' => true));
$object->_cacher =& $t;
break;
}
}
}
return $object;
}
/**
* array parseDSN(mixed $dsn)
* Parse a data source name.
* See parse_url() for details.
*/
function parseDSN($dsn)
{
if (is_array($dsn)) return $dsn;
$parsed = @parse_url($dsn);
if (!$parsed) return null;
$params = null;
if (!empty($parsed['query'])) {
parse_str($parsed['query'], $params);
$parsed += $params;
}
$parsed['dsn'] = $dsn;
return $parsed;
}
}
/**
* Base class for all databases.
* Can create transactions and new BLOBs, parse DSNs.
*
* Logger is COMMON for multiple transactions.
* Error handler is private for each transaction and database.
*/
class DbSimple_Generic_Database extends DbSimple_Generic_LastError
{
/**
* Public methods.
*/
/**
* object blob($blob_id)
* Create new blob
*/
function blob($blob_id = null)
{
$this->_resetLastError();
return $this->_performNewBlob($blob_id);
}
/**
* void transaction($mode)
* Create new transaction.
*/
function transaction($mode=null)
{
$this->_resetLastError();
$this->_logQuery('-- START TRANSACTION '.$mode);
return $this->_performTransaction($mode);
}
/**
* mixed commit()
* Commit the transaction.
*/
function commit()
{
$this->_resetLastError();
$this->_logQuery('-- COMMIT');
return $this->_performCommit();
}
/**
* mixed rollback()
* Rollback the transaction.
*/
function rollback()
{
$this->_resetLastError();
$this->_logQuery('-- ROLLBACK');
return $this->_performRollback();
}
/**
* mixed select(string $query [, $arg1] [,$arg2] ...)
* Execute query and return the result.
*/
function select($query)
{
$args = func_get_args();
$total = false;
return $this->_query($args, $total);
}
/**
* mixed selectPage(int &$total, string $query [, $arg1] [,$arg2] ...)
* Execute query and return the result.
* Total number of found rows (independent to LIMIT) is returned in $total
* (in most cases second query is performed to calculate $total).
*/
function selectPage(&$total, $query)
{
$args = func_get_args();
array_shift($args);
$total = true;
return $this->_query($args, $total);
}
/**
* hash selectRow(string $query [, $arg1] [,$arg2] ...)
* Return the first row of query result.
* On errors return null and set last error.
* If no one row found, return array()! It is useful while debugging,
* because PHP DOES NOT generates notice on $row['abc'] if $row === null
* or $row === false (but, if $row is empty array, notice is generated).
*/
function selectRow()
{
$args = func_get_args();
$total = false;
$rows = $this->_query($args, $total);
if (!is_array($rows)) return $rows;
if (!count($rows)) return array();
reset($rows);
return current($rows);
}
/**
* array selectCol(string $query [, $arg1] [,$arg2] ...)
* Return the first column of query result as array.
*/
function selectCol()
{
$args = func_get_args();
$total = false;
$rows = $this->_query($args, $total);
if (!is_array($rows)) return $rows;
$this->_shrinkLastArrayDimensionCallback($rows);
return $rows;
}
/**
* scalar selectCell(string $query [, $arg1] [,$arg2] ...)
* Return the first cell of the first column of query result.
* If no one row selected, return null.
*/
function selectCell()
{
$args = func_get_args();
$total = false;
$rows = $this->_query($args, $total);
if (!is_array($rows)) return $rows;
if (!count($rows)) return null;
reset($rows);
$row = current($rows);
if (!is_array($row)) return $row;
reset($row);
return current($row);
}
/**
* mixed query(string $query [, $arg1] [,$arg2] ...)
* Alias for select(). May be used for INSERT or UPDATE queries.
*/
function query()
{
$args = func_get_args();
$total = false;
return $this->_query($args, $total);
}
/**
* string escape(mixed $s, bool $isIdent=false)
* Enclose the string into database quotes correctly escaping
* special characters. If $isIdent is true, value quoted as identifier
* (e.g.: `value` in MySQL, "value" in Firebird, [value] in MSSQL).
*/
function escape($s, $isIdent=false)
{
return $this->_performEscape($s, $isIdent);
}
/**
* callback setLogger(callback $logger)
* Set query logger called before each query is executed.
* Returns previous logger.
*/
function setLogger($logger)
{
$prev = $this->_logger;
$this->_logger = $logger;
return $prev;
}
/**
* callback setCacher(callback $cacher)
* Set cache mechanism called during each query if specified.
* Returns previous handler.
*/
function setCacher($cacher)
{
$prev = $this->_cacher;
$this->_cacher = $cacher;
return $prev;
}
/**
* string setIdentPrefix($prx)
* Set identifier prefix used for $_ placeholder.
*/
function setIdentPrefix($prx)
{
$old = $this->_identPrefix;
if ($prx !== null) $this->_identPrefix = $prx;
return $old;
}
/**
* string setIdentPrefix($prx)
* Set cache prefix used in key caclulation.
*/
function setCachePrefix($prx)
{
$old = $this->_cachePrefix;
if ($prx !== null) $this->_cachePrefix = $prx;
return $old;
}
/**
* array getStatistics()
* Returns various statistical information.
*/
function getStatistics()
{
return $this->_statistics;
}
/**
* Virtual protected methods
*/
function ____________PROTECTED() {} // for phpEclipse outline
/**
* string _performEscape(mixed $s, bool $isIdent=false)
*/
function _performEscape($s, $isIdent)
{
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
}
/**
* object _performNewBlob($id)
*
* Returns new blob object.
*/
function& _performNewBlob($id)
{
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
}
/**
* list _performGetBlobFieldNames($resultResource)
* Get list of all BLOB field names in result-set.
*/
function _performGetBlobFieldNames($result)
{
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
}
/**
* mixed _performTransformQuery(array &$query, string $how)
*
* Transform query different way specified by $how.
* May return some information about performed transform.
*/
function _performTransformQuery(&$queryMain, $how)
{
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
}
/**
* resource _performQuery($arrayQuery)
* Must return:
* - For SELECT queries: ID of result-set (PHP resource).
* - For other queries: query status (scalar).
* - For error queries: null (and call _setLastError()).
*/
function _performQuery($arrayQuery)
{
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
}
/**
* mixed _performFetch($resultResource)
* Fetch ONE NEXT row from result-set.
* Must return:
* - For SELECT queries: all the rows of the query (2d arrray).
* - For INSERT queries: ID of inserted row.
* - For UPDATE queries: number of updated rows.
* - For other queries: query status (scalar).
* - For error queries: null (and call _setLastError()).
*/
function _performFetch($result)
{
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
}
/**
* array _performTotal($arrayQuery)
*/
function _performTotal($arrayQuery)
{
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
}
/**
* mixed _performTransaction($mode)
* Start new transaction.
*/
function _performTransaction($mode=null)
{
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
}
/**
* mixed _performCommit()
* Commit the transaction.
*/
function _performCommit()
{
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
}
/**
* mixed _performRollback()
* Rollback the transaction.
*/
function _performRollback()
{
die("Method must be defined in derived class. Abstract function called at ".__FILE__." line ".__LINE__);
}
/**
* string _performGetPlaceholderIgnoreRe()
* Return regular expression which matches ignored query parts.
* This is needed to skip placeholder replacement inside comments, constants etc.
*/
function _performGetPlaceholderIgnoreRe()
{
return '';
}
/**
* Returns marker for native database placeholder. E.g. in FireBird it is '?',
* in PostgreSQL - '$1', '$2' etc.
*
* @param int $n Number of native placeholder from the beginning of the query (begins from 0!).
* @return string String representation of native placeholder marker (by default - '?').
*/
function _performGetNativePlaceholderMarker($n)
{
return '?';
}
/**
* Private methods.
*/
function ____________PRIVATE() {} // for phpEclipse outline
/**
* array _query($query, &$total)
* See _performQuery().
*/
function _query($query, &$total)
{
$this->_resetLastError();
// Fetch query attributes.
$this->attributes = $this->_transformQuery($query, 'GET_ATTRIBUTES');
// Modify query if needed for total counting.
if ($total) {
$this->_transformQuery($query, 'CALC_TOTAL');
}
$is_cacher_callable = (is_callable($this->_cacher) || (method_exists($this->_cacher, 'get') && method_exists($this->_cacher, 'save')));
$rows = null;
$cache_it = false;
if (!empty($this->attributes['CACHE']) && $is_cacher_callable) {
$hash = $this->_cachePrefix . md5(serialize($query));
// Getting data from cache if possible
$fetchTime = $firstFetchTime = 0;
$qStart = $this->_microtime();
$cacheData = $this->_cache($hash);
$queryTime = $this->_microtime() - $qStart;
$storeTime = isset($cacheData['storeTime']) ? $cacheData['storeTime'] : null;
$invalCache = isset($cacheData['invalCache']) ? $cacheData['invalCache'] : null;
$result = isset($cacheData['result']) ? $cacheData['result'] : null;
$rows = isset($cacheData['rows']) ? $cacheData['rows'] : null;
$cache_params = $this->attributes['CACHE'];
// Calculating cache time to live
$re = '/
(
([0-9]+) #2 - hours
h)? [ \t]*
(
([0-9]+) #4 - minutes
m)? [ \t]*
(
([0-9]+) #6 - seconds
s?)? (,)?
/sx';
$m = null;
preg_match($re, $cache_params, $m);
$ttl = @$m[6] + @$m[4] * 60 + @$m[2] * 3600;
// Cutting out time param - now there are just fields for uniqKey or nothing
$cache_params = trim(preg_replace($re, '', $cache_params, 1));
$uniq_key = null;
// UNIQ_KEY calculation
if (!empty($cache_params)) {
$dummy = null;
// There is no need in query, cos' needle in $this->attributes['CACHE']
$this->_transformQuery($dummy, 'UNIQ_KEY');
$uniq_key = call_user_func_array(array(&$this, 'select'), $dummy);
$uniq_key = md5(serialize($uniq_key));
}
// Check TTL?
$ttl = empty($ttl) ? true : (int)$storeTime > (time() - $ttl);
// Invalidate cache?
if ($ttl && $uniq_key == $invalCache) {
$this->_logQuery($query);
$this->_logQueryStat($queryTime, $fetchTime, $firstFetchTime, $rows);
}
else $cache_it = true;
}
if (null === $rows || true === $cache_it) {
$this->_logQuery($query);
// Run the query (counting time).
$qStart = $this->_microtime();
$result = $this->_performQuery($query);
$fetchTime = $firstFetchTime = 0;
if (is_resource($result) || is_object($result)) {
$rows = array();
// Fetch result row by row.
$fStart = $this->_microtime();
$row = $this->_performFetch($result);
$firstFetchTime = $this->_microtime() - $fStart;
if ($row !== null) {
$rows[] = $row;
while ($row=$this->_performFetch($result)) {
$rows[] = $row;
}
}
$fetchTime = $this->_microtime() - $fStart;
} else {
$rows = $result;
}
$queryTime = $this->_microtime() - $qStart;
// Log query statistics.
$this->_logQueryStat($queryTime, $fetchTime, $firstFetchTime, $rows);
// Prepare BLOB objects if needed.
if (is_array($rows) && !empty($this->attributes['BLOB_OBJ'])) {
$blobFieldNames = $this->_performGetBlobFieldNames($result);
foreach ($blobFieldNames as $name) {
for ($r = count($rows)-1; $r>=0; $r--) {
$rows[$r][$name] =& $this->_performNewBlob($rows[$r][$name]);
}
}
}
// Transform resulting rows.
$result = $this->_transformResult($rows);
// Storing data in cache
if ($cache_it && $is_cacher_callable) {
$this->_cache(
$hash,
array(
'storeTime' => time(),
'invalCache' => $uniq_key,
'result' => $result,
'rows' => $rows
)
);
}
}
// Count total number of rows if needed.
if (is_array($result) && $total) {
$this->_transformQuery($query, 'GET_TOTAL');
$total = call_user_func_array(array(&$this, 'selectCell'), $query);
}
return $result;
}
/**
* mixed _transformQuery(array &$query, string $how)
*
* Transform query different way specified by $how.
* May return some information about performed transform.
*/
function _transformQuery(&$query, $how)
{
// Do overriden transformation.
$result = $this->_performTransformQuery($query, $how);
if ($result === true) return $result;
// Common transformations.
switch ($how) {
case 'GET_ATTRIBUTES':
// Extract query attributes.
$options = array();
$q = $query[0];
$m = null;
while (preg_match('/^ \s* -- [ \t]+ (\w+): ([^\r\n]+) [\r\n]* /sx', $q, $m)) {
$options[$m[1]] = trim($m[2]);
$q = substr($q, strlen($m[0]));
}
return $options;
case 'UNIQ_KEY':
$q = $this->attributes['CACHE'];
$i = 0;
$query = " -- UNIQ_KEY\n";
while(preg_match('/(\w+)\.\w+/sx', $q, $m)) {
if($i > 0)$query .= "\nUNION\n";
$query .= 'SELECT MAX('.$m[0].') AS M, COUNT(*) AS C FROM '.$m[1];
$q = substr($q, strlen($m[0]));
$i++;
}
return true;
}
// No such transform.
$this->_setLastError(-1, "No such transform type: $how", $query);
}
/**
* void _expandPlaceholders(array &$queryAndArgs, bool $useNative=false)
* Replace placeholders by quoted values.
* Modify $queryAndArgs.
*/
function _expandPlaceholders(&$queryAndArgs, $useNative=false)
{
$cacheCode = null;
if ($this->_logger) {
// Serialize is much faster than placeholder expansion. So use caching.
$cacheCode = md5(serialize($queryAndArgs) . '|' . $useNative . '|' . $this->_identPrefix);
if (isset($this->_placeholderCache[$cacheCode])) {
$queryAndArgs = $this->_placeholderCache[$cacheCode];
return;
}
}
if (!is_array($queryAndArgs)) {
$queryAndArgs = array($queryAndArgs);
}
$this->_placeholderNativeArgs = $useNative? array() : null;
$this->_placeholderArgs = array_reverse($queryAndArgs);
$query = array_pop($this->_placeholderArgs); // array_pop is faster than array_shift
// Do all the work.
$this->_placeholderNoValueFound = false;
$query = $this->_expandPlaceholdersFlow($query);
if ($useNative) {
array_unshift($this->_placeholderNativeArgs, $query);
$queryAndArgs = $this->_placeholderNativeArgs;
} else {
$queryAndArgs = array($query);
}
if ($cacheCode) {
$this->_placeholderCache[$cacheCode] = $queryAndArgs;
}
}
/**
* Do real placeholder processing.
* Imply that all interval variables (_placeholder_*) already prepared.
* May be called recurrent!
*/
function _expandPlaceholdersFlow($query)
{
$re = '{
(?>
# Ignored chunks.
(?>
# Comment.
-- [^\r\n]*
)
|
(?>
# DB-specifics.
' . trim($this->_performGetPlaceholderIgnoreRe()) . '
)
)
|
(?>
# Optional blocks
\{
# Use "+" here, not "*"! Else nested blocks are not processed well.
( (?> (?>[^{}]+) | (?R) )* ) #1
\}
)
|
(?>
# Placeholder
(\?) ( [_dsafn\#]? ) #2 #3
)
}sx';
$query = preg_replace_callback(
$re,
array(&$this, '_expandPlaceholdersCallback'),
$query
);
return $query;
}
/**
* string _expandPlaceholdersCallback(list $m)
* Internal function to replace placeholders (see preg_replace_callback).
*/
function _expandPlaceholdersCallback($m)
{
// Placeholder.
if (!empty($m[2])) {
$type = $m[3];
// Idenifier prefix.
if ($type == '_') {
return $this->_identPrefix;
}
// Value-based placeholder.
if (!$this->_placeholderArgs) return 'DBSIMPLE_ERROR_NO_VALUE';
$value = array_pop($this->_placeholderArgs);
// Skip this value?
if ($value === DBSIMPLE_SKIP) {
$this->_placeholderNoValueFound = true;
return '';
}
// First process guaranteed non-native placeholders.
switch ($type) {
case 'a':
if (!$value) $this->_placeholderNoValueFound = true;
if (!is_array($value)) return 'DBSIMPLE_ERROR_VALUE_NOT_ARRAY';
$parts = array();
foreach ($value as $k=>$v) {
$v = $v === null? 'NULL' : $this->escape($v);
if (!is_int($k)) {
$k = $this->escape($k, true);
$parts[] = "$k=$v";
} else {
$parts[] = $v;
}
}
return join(', ', $parts);
case "#":
// Identifier.
if (!is_array($value)) return $this->escape($value, true);
$parts = array();
foreach ($value as $table => $identifier) {
if (!is_string($identifier)) return 'DBSIMPLE_ERROR_ARRAY_VALUE_NOT_STRING';
$parts[] = (!is_int($table)? $this->escape($table, true) . '.' : '') . $this->escape($identifier, true);
}
return join(', ', $parts);
case 'n':
// NULL-based placeholder.
return empty($value)? 'NULL' : intval($value);
}
// Native arguments are not processed.
if ($this->_placeholderNativeArgs !== null) {
$this->_placeholderNativeArgs[] = $value;
return $this->_performGetNativePlaceholderMarker(count($this->_placeholderNativeArgs) - 1);
}
// In non-native mode arguments are quoted.
if ($value === null) return 'NULL';
switch ($type) {
case '':
if (!is_scalar($value)) return 'DBSIMPLE_ERROR_VALUE_NOT_SCALAR';
return $this->escape($value);
case 'd':
return intval($value);
case 'f':
return str_replace(',', '.', floatval($value));
}
// By default - escape as string.
return $this->escape($value);
}
// Optional block.
if (isset($m[1]) && strlen($block=$m[1])) {
$prev = @$this->_placeholderNoValueFound;
$block = $this->_expandPlaceholdersFlow($block);
$block = $this->_placeholderNoValueFound? '' : ' ' . $block . ' ';
$this->_placeholderNoValueFound = $prev; // recurrent-safe
return $block;
}
// Default: skipped part of the string.
return $m[0];
}
/**
* void _setLastError($code, $msg, $query)
* Set last database error context.
* Aditionally expand placeholders.
*/
function _setLastError($code, $msg, $query)
{
if (is_array($query)) {
$this->_expandPlaceholders($query, false);
$query = $query[0];
}
return DbSimple_Generic_LastError::_setLastError($code, $msg, $query);
}
/**
* Return microtime as float value.
*/
function _microtime()
{
$t = explode(" ", microtime());
return $t[0] + $t[1];
}
/**
* Convert SQL field-list to COUNT(...) clause
* (e.g. 'DISTINCT a AS aa, b AS bb' -> 'COUNT(DISTINCT a, b)').
*/
function _fieldList2Count($fields)
{
$m = null;
if (preg_match('/^\s* DISTINCT \s* (.*)/sx', $fields, $m)) {
$fields = $m[1];
$fields = preg_replace('/\s+ AS \s+ .*? (?=,|$)/sx', '', $fields);
return "COUNT(DISTINCT $fields)";
} else {
return 'COUNT(*)';
}
}
/**
* array _transformResult(list $rows)
* Transform resulting rows to various formats.
*/
function _transformResult($rows)
{
// Process ARRAY_KEY feature.
if (is_array($rows) && $rows) {
// Find ARRAY_KEY* AND PARENT_KEY fields in field list.
$pk = null;
$ak = array();
foreach (current($rows) as $fieldName => $dummy) {
if (0 == strncasecmp($fieldName, DBSIMPLE_ARRAY_KEY, strlen(DBSIMPLE_ARRAY_KEY))) {
$ak[] = $fieldName;
} else if (0 == strncasecmp($fieldName, DBSIMPLE_PARENT_KEY, strlen(DBSIMPLE_PARENT_KEY))) {
$pk = $fieldName;
}
}
natsort($ak); // sort ARRAY_KEY* using natural comparision
if ($ak) {
// Tree-based array? Fields: ARRAY_KEY, PARENT_KEY
if ($pk !== null) {
return $this->_transformResultToForest($rows, $ak[0], $pk);
}
// Key-based array? Fields: ARRAY_KEY.
return $this->_transformResultToHash($rows, $ak);
}
}
return $rows;
}
/**
* Converts rowset to key-based array.
*
* @param array $rows Two-dimensional array of resulting rows.
* @param array $ak List of ARRAY_KEY* field names.
* @return array Transformed array.
*/
function _transformResultToHash($rows, $arrayKeys)
{
$arrayKeys = (array)$arrayKeys;
$result = array();
foreach ($rows as $row) {
// Iterate over all of ARRAY_KEY* fields and build array dimensions.
$current =& $result;
foreach ($arrayKeys as $ak) {
$key = $row[$ak];
unset($row[$ak]); // remove ARRAY_KEY* field from result row
if ($key !== null) {
$current =& $current[$key];
} else {
// IF ARRAY_KEY field === null, use array auto-indices.
$tmp = array();
$current[] =& $tmp;
$current =& $tmp;
unset($tmp); // we use $tmp, because don't know the value of auto-index
}
}
$current = $row; // save the row in last dimension
}
return $result;
}
/**
* Converts rowset to the forest.
*
* @param array $rows Two-dimensional array of resulting rows.
* @param string $idName Name of ID field.
* @param string $pidName Name of PARENT_ID field.
* @return array Transformed array (tree).
*/
function _transformResultToForest($rows, $idName, $pidName)
{
$children = array(); // children of each ID
$ids = array();
// Collect who are children of whom.
foreach ($rows as $i=>$r) {
$row =& $rows[$i];
$id = $row[$idName];
if ($id === null) {
// Rows without an ID are totally invalid and makes the result tree to
// be empty (because PARENT_ID = null means "a root of the tree"). So
// skip them totally.
continue;
}
$pid = $row[$pidName];