-
Notifications
You must be signed in to change notification settings - Fork 0
/
BDB.inc.php
2195 lines (1767 loc) · 64.7 KB
/
BDB.inc.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
/*
BDB vers: 1.9.10
This class is meant to provide easy access to instantiated BDB database objects
It does this by allowing you to declare a new child class of BDB with any aribtrary name (usually something like "PrimaryDB")
Example usage
class PrimaryDB extends BDB {}
PrimaryDB::Make('MySQL', 'PrimaryDB', $CnxnParams);
BDB::Make('MySQL', 'PrimaryDB', $CnxnParams);
PrimaryDB::Claim('PrimaryDB');
$DB = BDB::Get('PrimaryDB');
$User1Row = $DB->SelectOne('users', '', 'id = 1');
$DelResult = $DB->DeleteEquals('domains', 'id', 443);
TODO
- Add Postgres.
- Allow more values to be passed in that are pushed in through mysqli->options();
- add method to get current version of particular engines library.
- Event Logging - connect, query, disconnect, etc....
- DupKeyUpdate - allow passing comma separated field list - fxn will do the setup.
- Finish Upsert
- BDB_DataObject
- BDB_Record $this->Record->select($fields)->from("module_rows")->where("module_id", "=", $module_id);
*/
class BDB
{
const kSQLDATETIMEFMT = 'Y-m-d H:i:s';
protected static $MyDB = false;
private static $EngineTypes = array();
private static $TypeEngines = array();
private static $BDBs = array();
### -------------------------------------------------------------------------
## don't allow instantiation of this class
private function __construct() {}
public static function Get($inName=false)
{
if (false === $inName) return self::$MyDB;
$nameKey = strtolower($inName);
if (!array_key_exists($nameKey, self::$BDBs)) return false;
return self::$BDBs[$nameKey];
}
public static function DB($name)
{
return self::Get($name);
}
private static function Set($inName, $BDB_Object)
{
$nameKey = strtolower($inName);
self::$BDBs[$nameKey] = $BDB_Object;
}
public static function __callStatic($func, $Args)
{
if (false === static::$MyDB) throw new Exception('No DB Defined');
if ('BDB' === get_called_class()) throw new Exception('BDB not extended');
return call_user_func_array(array(static::$MyDB, $func), $Args);
}
/*
hack for the pass by reference issue:
function executeHook($name, $type='hooks'){
$args = func_get_args();
array_shift($args);
array_shift($args);
//Rather stupid Hack for the call_user_func_array();
$Args = array();
foreach($args as $k => &$arg){
$Args[$k] = &$arg;
}
//End Hack
$hooks = &$this->$type;
if(!isset($hooks[$name])) return false;
$hook = $hooks[$name];
call_user_func_array($hook, $Args);
}
*/
## returns true or a text error.
## noops if there is already a BDB registered with the same name.
public static function Make($inType, $name, $CnxnParams, $Services=array())
{
$type = strtolower($inType);
if (!array_key_exists($type, self::$TypeEngines)) return "Unknown Engine Type: $inType";
if (false === self::Get($name))
{
$bdbClass = 'BDB_'. (self::$EngineTypes[self::$TypeEngines[$type]]); // BDB_MySQL
$NewBDB = new $bdbClass($name, $CnxnParams, $Services);
if ('BDB' != get_called_class()) self::$MyDB = $NewBDB;
self::Set($name, $NewBDB);
}
return true;
}
public static function Claim($name)
{
if ('BDB' == get_called_class()) return false;
$BDB = self::Get($name);
if (false === $BDB) return false;
self::$MyDB = $BDB;
return true;
}
public static function RegisterEngineType($typeID, $typeName)
{
self::$EngineTypes[$typeID] = $typeName;
self::$TypeEngines[strtolower($typeName)] = $typeID;
}
public static function DBList()
{
$DBList = array();
foreach(self::$BDBs as $nameKey => $DB)
{
$DBList[$nameKey] = $DB->GetInfo();
}
return $DBList;
}
public static function DisconnectAll()
{
foreach(self::$BDBs as $DB)
{
if ($DB->IsConnected()) $DB->Disconnect();
}
}
} // BDB
## class that is meant to be extended by db engine specific code
## Create some methods that deal with asking about the result returned from a db operation
## $DBResult
class BDB_Base
{
const kEngineTypeID = 0;
const kEngineTypeName = 'BDB';
const kSQLDATETIMEFMT = BDB::kSQLDATETIMEFMT;
const kCnxnStaleTime = 10;
const kTOKEN_UTCTS = false;
protected $DBParams = array();
public $cnxnName = null;
protected $cnxnRef = null; // cnxn id rsrc or open file pointer or driver object
protected $CnxnOpts = array();
protected $connStartTime = 0;
protected $numQueries = 0;
public $logDBErrors = true;
protected $dbErrLogFileTgt = true;
public $logQueries = false;
protected $QueryLogger = false;
protected $logThisQuery = false;
protected $qLogFileTgt = false;
protected $QueryLog = array();
public $logQueryErrors = true;
protected $QueryErrorAlerter = false;
protected $qErrLogFileTgt = false;
protected $QErrData = array();
protected $ErrorInfo = array();
protected $lastQuery = '';
protected $lastQueryTgtTable = '';
protected $lastQueryWhen = 0; // last UTS-based when last good query ran.
protected $lastQueryTime = 0; // last query took this number of microtime to complete.
protected $Services = array();
protected $defaultBoolTest = 'AND';
protected static $fxnNameDisconnect = false;
protected static $fxnNameSelectDB = false;
protected static $fxnNameEscapeString = false;
protected static $fxnNameFreeResult = false;
protected static $fxnNameQuery = 'null_op';
public function __construct($name=false, $CnxnParams, $Services=array())
{
$this->cnxnName = $name;
$this->SetCnxnParams($CnxnParams);
if (!empty($Services))
{
$this->Services = array_merge($this->Services, $Services);
}
# if (array_key_exists('QueryLogger', $Services))
# {
# $this->SetQueryLogger($Services['QueryLogger']);
# }
#
if (array_key_exists('QueryErrorAlerter', $Services))
{
$this->SetQueryErrorAlerter($Services['QueryErrorAlerter']);
}
} // __construct
protected final function null_op() {}
protected function SetCnxnParams($CnxnParams)
{
foreach($CnxnParams as $key => $val)
{
switch(strtolower($key))
{
case 'logqueries':
$this->logQueries = $this->logThisQuery = (bool)$val;
break;
case 'logerrors':
$this->logQueryErrors = (bool)$val;
break;
case 'errorlogging':
case 'erroralerter':
case 'queryerroralerter':
$result = $this->SetQueryErrorAlerter($val);
if (true !== $result) error_log("attempting to set error log in CnxnParams failed: $result\n". var_export($val, true));
break;
case 'dberroralerter':
$result = $this->SetDBErrorAlerter($val);
if (true !== $result) error_log("attempting to set db error log in CnxnParams failed: $result\n". var_export($val, true));
break;
}
}
return $this;
}
public function GetDBParams() {}
public function SetDBParams($DBParams) {}
public function Connect() {}
public function Disconnect()
{ // simple version of Disconnect.
$cnxnRef = $this->cnxnRef;
$this->cnxnRef = null;
if (is_null($cnxnRef)) return false;
$fxn = static::$fxnNameDisconnect;
return $fxn($cnxnRef);
}
public function IsConnected()
{
return (!is_null($this->cnxnRef));
}
public function SelectDB($dbName)
{
$fxn = static::$fxnNameSelectDB;
return $fxn($this->cnxnRef, $dbName);
}
public function EscapeString($data) { return $data; }
public function Quote($data)
{
if (!is_array($data))
{
$vtype = gettype($data);
if ( ('integer' == $vtype) || ('double' == $vtype) ) return $data;
return "'". $this->EscapeString($data) ."'";
}
$NewData = array();
foreach(array_keys($data) as $k)
{
$v = $data[$k];
$vtype = gettype($v);
if ( ('integer' == $vtype) || ('double' == $vtype) )
$NewData[$k] = $v;
else $NewData[$k] = "'". $this->EscapeString($v) ."'";
}
return $NewData;
}
public function Ping() { return false; }
public function Epoch() {}
public function IsEpoch() {}
public function AsSQLDT($time=false)
{ ## formats a datetime as a UTC/GM time according to the engines preferred datetime format
if (false !== $time)
{
$timeInt = preg_replace('/[^0-9]/', '', $time);
$timeLen = strlen($time);
if (strlen($timeInt) == $timeLen)
{ // we've been passed a timestamp - 20010301090807 or 1029733200
if (14 == $timeLen) $time = gmmktime(substr($time,8,2), substr($time,10,2), substr($time,12,2), substr($time,4,2), substr($time,6,2), substr($time,0,4));
}
else
{
$time = strtotime($time); // this can be a relative time (3 weeks ago)
if (false === $time) return false;
}
} else $time = time();
return gmdate($this::kSQLDATETIMEFMT, $time);
}
public function GetInfo($DBInfo=array())
{
$DBInfo['type'] = $this::kEngineTypeName;
$DBInfo['cnxn_name'] = $this->cnxnName;
$DBInfo['host'] = $this->Host();
$DBInfo['username'] = $this->Username();
$DBInfo['cnxn_started'] = $this->Stats('cnxn_started');
$DBInfo['num_queries'] = $this->Stats('num_queries');
$DBInfo['connected'] = $this->IsConnected();
return $DBInfo;
}
public function Host() {}
public function Username() {}
public function Stats($stat)
{
switch(strtolower($stat))
{
case 'cnxn_started': return $this->connStartTime;
case 'num_queries': return $this->numQueries;
}
}
// tableName/queryPart is passed by reference so it can be corrected
protected function InitQuery(&$queryPart, $Options=array())
{
$this->QueryOptions = $Options; // save these for others to have access to.
## If there has been a previous query and
$testTime = ($this->lastQueryWhen) ? $this->lastQueryWhen : intval($this->connStartTime);
if ( time() > ($testTime + self::kCnxnStaleTime) )
{
if (!$this->Ping(true)) return false;
}
$logThisQuery = ('!' == substr($queryPart, 0,1));
if ($logThisQuery)
{
$queryPart = substr($queryPart, 1);
}
else
{
## This could theoretically turn OFF logging for this single query, even if logging were enabled globally. This is a feature, not a bug.
$logThisQuery = array_key_exists('logquery', $this->QueryOptions) ? boolval($this->QueryOptions['logquery']) : $this->logQueries;
}
$this->logThisQuery = $logThisQuery;
$this->lastQuery = $this->lastQueryTgtTable = '';
return $this;
} // InitQuery
public function LastQuery() { return $this->lastQuery; }
public function LastQueryTime() { return $this->lastQueryTime; }
## these need to be overridden by subclass
public function SelectOne($table, $colList, $where='') { $this->InitQuery($table); return array(); }
public function SelectCell($query) { $this->InitQuery($query); return; }
## shorthand versions
public function SelectKeyList($tableName, $keyField, $where, $orderBy='', $limitInput=0)
{
return $this->SelectList($tableName, '', $keyField, '', $where, $orderBy, $limitInput);
}
## ---------- Query, return result set pointer -------------
## Direct Queries can be directed to log by prefixed a '!' to the query string.
public function Query($query, $Options=array())
{
if (is_null($this->cnxnRef)) return $this->DBError(__function__, 'No db connection');
if (!$this->InitQuery($query, $Options)) return false;
$this->lastQuery = $query;
if ($this->logThisQuery) $this->LogQuery(__function__);
$this->numQueries++;
$fxn = static::$fxnNameResultsQuery;
# try {# } catch
$qtime = -microtime(true);
$QR = $fxn($this->lastQuery, $this->cnxnRef);
$this->lastQueryTime = $qtime + microtime(true);
if (false !== $QR)
{
$this->lastQueryWhen = time();
return $QR;
}
return $this->HandleQueryError(__function__, array('called_fxn' => $fxn));
}
public function DQuery($query, $Options=array())
{ // Direct Query, no fluff
if (is_null($this->cnxnRef)) return $this->DBError(__function__, 'No db connection');
if (!$this->InitQuery($query, $Options)) return false;
$this->lastQuery = $query;
if ($this->logThisQuery) $this->LogQuery(__function__);
$this->numQueries++;
$fxn = static::$fxnNameQuery;
$qtime = -microtime(true);
$QR = $fxn($this->cnxnRef, $query);
$this->lastQueryTime = $qtime + microtime(true);
if (false !== $QR)
{
$this->lastQueryWhen = time();
return $QR;
}
return $this->HandleQueryError(__function__, array('called_fxn' => $fxn));
}
## This should return either a data value or false
public function QuerySimpleResult($queryString) {}
public function SelectList($tableName, $colList, $keyField, $nameField, $where, $orderBy='', $limitInput=0) { return array(); }
public function QueryOne($sqlQuery) { return array(); }
public function QueryList($sqlQuery, $keyField='', $nameField='') { return array(); }
public function Insert($tableName, $DataRecord, $Options=array()) {}
public function Replace($tableName, $DataRecord, $Options=array()) {}
public function Update($tableName, $DataRecord, $where, $Options=array()) {}
public function UpdateOne($tableName, $DataRecord, $where, $Options=array())
{
$Options['limit'] = 1;
return $this->Update($tableName, $DataRecord, $where, $Options);
}
public function Delete($table, $where) {}
public function DeleteOne($table, $where) {}
public function SetTransIsolationLevel() {}
public function FetchAssoc($QR)
{
$fxn = static::$fxnNameFetchAssoc;
return $fxn($QR);
}
public function FetchRow($QR) { return array(); }
public function LastInsertID($param1) { return 0; }
## ---------- Query Result/Set Processing -------------
## return format for FetchResultSet is dependent on the keyfield/namefield parameters.
public function FetchResultSet($QR, $keyField='', $nameField='')
{
$numRows = $this->QueryNumRows($QR);
$ResultData = array();
while ($numRows)
{
$numRows--;
$RowData = $this->FetchRow($QR);
if (!empty($keyField))
{
if (empty($nameField))
{
$theKey = $RowData[$keyField];
unset($RowData[$keyField]);
$ResultData[$theKey] = $RowData;
}
elseif ('*' == $nameField)
{
$ResultData[$RowData[$keyField]] = $RowData;
}
else
{
$ResultData[$RowData[$keyField]] = $RowData[$nameField];
}
}
else
{
$ResultData[] = empty($nameField) ? $RowData : $RowData[$nameField];
}
}
return $ResultData;
}
public function DisposeQuery($QR)
{
if ( !(is_object($QR) || is_resource($QR) )) return false;
$fxn = static::$fxnNameFreeResult;
return $fxn($QR);
}
public function QueryNumRows($QR)
{
if ( !(is_object($QR) || is_resource($QR) )) return 0;
$fxn = static::$fxnNameNumRows;
return $fxn($QR);
}
public function NumAffectedRows($QR)
{
if (is_null($this->cnxnRef)) return false;
$fxn = static::$fxnNameNumAffectedRows;
return $fxn($QR, $this->cnxnRef);
}
## ---------- Transactions -------------
public function BeginTransaction()
{
return $this->DQuery(static::$sqlBeginTrxn);
}
public function Begin() { return $this->BeginTransaction(); }
public function CommitTransaction()
{
return $this->DQuery(static::$sqlCommitTrxn);
}
public function Commit() { return $this->CommitTransaction(); }
public function RollbackTransaction()
{
return $this->DQuery(static::$sqlRollbackTrxn);
}
public function Rollback() { return $this->RollbackTransaction(); }
## Utility functions
public function BuildWhere($TheData)
{
if (empty($TheData)) return '';
if (!is_array($TheData)) return $TheData;
if ('AND' == $this->defaultBoolTest) return $this->PrepareColDataAND($TheData);
return $this->PrepareColDataOR($TheData);
}
## array('Col1'=>'A', 'Col1'=>'A', '#Col3'=>'NOW()', 'Col4|!='=>'3333', '#Col5|>'=>'NOW()', )
## Result: Col1='A', Col2='B', Col3=NOW(), Col4!='3333', Col5 > NOW()
public function PrepareColData($TheData)
{
$Result = array();
if (!is_array($TheData)) return $Result;
$LiteralKeys = array(); // used to resolve multiple passed fields down to one and prefer "#" passed fields in the process
foreach(array_keys($TheData) as $dataKey)
{
$normalKey = strtolower($dataKey);
if (array_key_exists($normalKey, $LiteralKeys)) continue;
// if we've seen this key as a literal key before, do not override with this new non-literal version
$colName = $dataKey;
$useQuotes = true; // !is_numeric($theData);
if ('#' == substr($normalKey, 0, 1))
{ // the key/value passed is to built as literal....
$normalKey = substr($normalKey, 1);
$colName = substr($colName, 1);
$useQuotes = false;
$LiteralKeys[$normalKey] = $colName;
}
if (NULL === $TheData[$dataKey])
{
$Result[$normalKey] = $colName .' = NU'.'LL';
continue;
}
$op = '=';
if (strstr($colName, '|'))
{
list($colName, $op) = explode('|', $colName, 2);
}
$Result[$normalKey] = "$colName $op ". ($useQuotes ? $this->Quote($TheData[$dataKey]) : $TheData[$dataKey]);
}
return $Result;
} // PrepareColData
## array('Col1'=>'A', 'Col1'=>'A', '#Col3'=>'NOW()', 'Col4|!='=>'3333', '#Col5|>'=>'NOW()', )
## Result: Col1='A', Col2='B', Col3=NOW(), Col4!='3333', Col5 > NOW()
protected function PrepareColDataList($TheData)
{
if (!is_array($TheData) || (count($TheData) == 0)) return false;
return implode(', ', $this->PrepareColData($TheData));
}
## Result: (Col1='A') OR (Col2='B')
public function PrepareColDataOR($TheData)
{
if (!is_array($TheData) || (count($TheData) == 0)) return false;
return '('. implode(') OR (', $this->PrepareColData($TheData)) .')';
}
## Result: (Col1='A') AND (Col2='B')
public function PrepareColDataAND($TheData)
{
if (!is_array($TheData) || (count($TheData) == 0)) return false;
return '('. implode(') AND (', $this->PrepareColData($TheData)) .')';
}
## -------- Query Logging --------------
### $this->QueryLogger can be one of three values:
### boolean = false => do nothing
### an object => the LogQuery method of that object is called
### a callable => the fxn is called.
protected function LogQuery($fxn, $query=false)
{ // Explicitly log this query as it will only be called if {logQueries} is set to true
$QLogData = array('fxn' => $fxn, );
$QLogData['query'] = (false === $query) ? $this->lastQuery : $query;
$QLogData['qtime'] = $this->lastQueryTime;
$QLogData['when_ut'] = microtime(true);
$LoggingEventDT = new DateTime();
$QLogData['when_fmt'] = $LoggingEventDT->format('Y-m-d H:i:s'); ## .v'); // Y-m-d\TH:i:s.v
$QLogData['cnxn'] = self::kEngineTypeID .':'. $this->cnxnName;
if (false !== $this->QueryLogger)
{
if (is_object($this->QueryLogger))
{ $this->QueryLogger->LogQuery($QLogData); }
else
{ call_user_func($this->QueryLogger, $QLogData); }
}
return $this;
}
## returns either true or text error message.
public function SetQueryLogger($qryLgr, $tgt=false)
{
if (is_object($qryLgr))
{
if (!is_callable(array($qryLgr, 'LogQuery'))) return get_class($qryLgr) .'::LogQuery() is not a callable method';
$this->QueryLogger = $qryLgr;
}
elseif ( ('error_log' === $qryLgr) || ('error_log_file' === $qryLgr) )
{
$this->QueryLogger = array($this, 'QueryLogger_ErrorLog');
if ( ('error_log_file' === $qryLgr) && (false !== $tgt) )
{
if (!file_exists($tgt)) @touch($tgt); ## try and create the file.
if (!file_exists($tgt)) return "Unable to create query log output file: $tgt";
if (!is_writable($tgt)) return "Query log output file not writable: $tgt";
$this->qLogFileTgt = $tgt;
}
else $this->qLogFileTgt = false;
}
elseif ( (true === $qryLgr) || ('memory' === $qryLgr) )
{
$this->QueryLogger = array($this, 'QueryLogger_Memory');
}
elseif (is_callable($qryLgr))
{
$this->QueryLogger = $qryLgr;
}
else return "Unable to Set QueryLogger to: ". var_export($qryLgr, true);
return true;
}
protected function QueryLogger_ErrorLog($QLogData)
{
$fxn = $QLogData['fxn'];
$query = $QLogData['query'];
if (false === $this->qLogFileTgt)
error_log("$fxn - $query");
else error_log("$fxn - $query\n", 3, $this->qLogFileTgt);
return $this;
}
protected function QueryLogger_Memory($QLogData)
{
$fxn = $QLogData['fxn'];
$query = $QLogData['query'];
$eventDate = $QLogData['when_fmt'];
$this->QueryLog[] = $eventDate ."\t". $fxn ."\t". $query;
return $this;
}
## TODO - max returned.
public function GetQueryLog($max=false)
{
return $this->QueryLog;
}
## -------- Query Error Handling --------------
## Called when the lowest level connection object query method returns a "false"
## will always return a "false"
protected function HandleQueryError($fxn, $AddlData=array())
{
$this->QErrData = array('fxn' => $fxn, );
$this->QErrData['cnxn'] = $this::kEngineTypeName .':'. $this->cnxnName;
$this->QErrData['database'] = $this->defaultDB;
$this->QErrData['target_table'] = $this->lastQueryTgtTable;
$this->QErrData['when_ut'] = microtime(true);
$LoggingEventDT = new DateTime();
$this->QErrData['code'] = $this->ErrorNum();
$this->QErrData['text'] = $this->ErrorStr();
if (!empty($this->QueryOptions)) $this->QErrData['query_options'] = $this->QueryOptions;
$this->QErrData['backtrace'] = $this->GetQueryBT();
$this->QErrData['query'] = $this->lastQuery;
$this->QErrData = array_merge($this->QErrData, $AddlData);
return $this->QueryErrorAlert();
}
## for non-select ops that expect a result block back with a status flag
protected function HandleQueryErrorResult($fxn, $AddlData=array())
{
$Result = array('Status' => false, );
$Result += $this->HandleQueryError($fxn, $AddlData);
return $Result;
}
## Called when there is something wrong with the parameters passed that WILL result in a query error.
## the query was not constructed, so we blank it out then pass on to the normal chain for query error processing/alerting.
protected final function HandleQueryParamsError($fxn, $msg)
{
$this->QErrData = array('fxn' => $fxn, );
$this->QErrData['msg'] = $msg;
$this->QErrData['query'] = $this->lastQuery;
$this->QErrData['backtrace'] = $this->GetQueryBT();
return $this->QueryErrorAlert();
}
## for non-select ops that expect a result block back with a status flag
protected function HandleQueryParamsErrorResult($fxn, $msg)
{
$Result = array('Status' => false, 'ErrorNum' => -1, 'ErrorStr' => $msg);
$Result['err_handled'] = $this->HandleQueryParamsError($fxn, $msg);
return $Result;
}
## A standalone function for handling whatever alerting/logging/{messenger pigeon} is configured when a query error occurs.
protected final function QueryErrorAlert()
{
$logThisError = array_key_exists('logerrors', $this->QueryOptions) ? boolval($this->QueryOptions['logerrors']) : $this->logQueryErrors;
## the caller can explicitly request to NOT have an error alert raised if this specific query results in an error.
if (!$logThisError) return;
## default value
if (true === $this->QueryErrorAlerter) return $this->QueryErrorAlerter_ErrorLog();
if (false !== $this->QueryErrorAlerter)
{
if (is_object($this->QueryErrorAlerter))
{ $this->QueryErrorAlerter->LogQError($this->QErrData); }
else
{ call_user_func($this->QueryErrorAlerter, $this->QErrData); }
}
return false;
}
## returns either true or text error message.
public function SetQueryErrorAlerter($qryErrLgr, $tgt=false)
{
$this->logQueryErrors = true;
if ( is_array($qryErrLgr) && (1 == count($qryErrLgr)) )
{ ## array('error_log_file'=> 'file')
$tgt = current($qryErrLgr);
$qryErrLgr = key($qryErrLgr);
}
if (is_object($qryErrLgr))
{
if (!is_callable(array($qryErrLgr, 'LogQuery'))) return get_class($qryErrLgr) .'::LogQuery() is not a callable method';
$this->QueryErrorAlerter = $qryErrLgr;
}
elseif ( ('error_log' === $qryErrLgr) || ('error_log_file' === $qryErrLgr) )
{
$this->QueryErrorAlerter = true;
$this->qErrLogFileTgt = false; // set to default of php error log as a contigency.
if ( ('error_log_file' === $qryErrLgr) && (false !== $tgt) )
{
if (!file_exists($tgt)) @touch($tgt); ## try and create the file.
if (!file_exists($tgt)) return "Unable to create query log output file: $tgt";
if (!is_writable($tgt)) return "Query log output file not writable: $tgt";
$this->qErrLogFileTgt = $tgt; // Set this variable regardless of the outcomes below.
}
}
elseif (is_callable($qryErrLgr))
{
$this->QueryErrorAlerter = $qryErrLgr;
}
elseif (false === $qryErrLgr)
{
$this->QueryErrorAlerter = false;
$this->logQueryErrors = false;
}
else
{
$this->logQueryErrors = false;
return "Unable to Set QueryErrorAlerter to: ". var_export($qryErrLgr, true);
}
return true;
} // SetQueryErrorAlerter
protected function QueryErrorAlerter_ErrorLog()
{
$fxn = $this->QErrData['fxn'];
$cnxn = $this->QErrData['cnxn'];
$dbName = $this->defaultDB;
$tableName = $this->lastQueryTgtTable;
$dbErr = $this->QErrData['code'] .':'. $this->QErrData['text'];
$errMsg = "DBCnxn: $cnxn: $fxn Execution has failed on $dbName" . (empty($tableName) ? '' : '.'.$tableName) ."\n";
$errMsg .= "Error:$dbErr\nQuery:". $this->lastQuery ."\n". $this->QErrData['backtrace'];
if (false === $this->qErrLogFileTgt)
error_log($errMsg);
else
{
$when_ut_str = strval($this->QErrData['when_ut']);
# error_log('DateTime::createFromFormat: '. $this->QErrData['when_ut']);
$WhenDTObj = DateTime::createFromFormat('U.u', $when_ut_str);
if (false === $WhenDTObj) $WhenDTObj = DateTime::createFromFormat('U', $when_ut_str);
$when = $WhenDTObj->format('Y-m-d h:i:s.v');
error_log($when .' '. $errMsg ."\n", 3, $this->qErrLogFileTgt);
}
return false;
}
## ------------------------------------------------------
## For errors related to events NOT query related
## when detected, caller can retrieve info by called GetDBError()
protected final function DBError($fxn, $msg)
{
$this->ErrorInfo['fxn'] = $fxn;
$this->ErrorInfo['cnxn_name'] = $this->cnxnName;
$this->ErrorInfo['host'] = $this->Host();
$this->ErrorInfo['user'] = $this->username;
$this->ErrorInfo['db'] = $this->defaultDB;
$this->ErrorInfo['msg'] = $msg;
if ($this->logDBErrors)
{
$msg = array();
foreach($this->ErrorInfo as $k => $v) { $msg[] = "$k: $v"; }
$this->MsgDBError(implode(' - ', $msg));
}
return false;
}
public function SetDBErrorAlerter($dbErrLgr, $tgt=false)
{
if (is_writable($dbErrLgr)) $this->dbErrLogFileTgt = $dbErrLgr;
}
protected function MsgDBError($msg)
{
if (true !== $this->dbErrLogFileTgt)
error_log($msg."\n", 3, $this->dbErrLogFileTgt);
else error_log($msg);
}
protected function GetQueryBT()
{
$FullBacktrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
## We want to not spam this BT output with a bunch of irrelevant lines, so strip
## all but the last method where the class is from this family.
$SlimBacktrace = array();
$curClassName = get_class($this);
foreach($FullBacktrace as $stepNum => $StepInfo)
{
if (array_key_exists('class', $StepInfo))
{
$class = $StepInfo['class'];
if ( ('BDB_Base' == $class) || ($class == $curClassName) )
{
$SlimBacktrace = array($StepInfo);
continue;
}
}
$SlimBacktrace[] = $StepInfo;
}
$DebugOut = array();
$SlimBacktrace = array_reverse($SlimBacktrace, false);
foreach($SlimBacktrace as $stepNum => $StepInfo)
{
$stepLine = "$stepNum.\t";
if (array_key_exists('class', $StepInfo))
{
$stepLine .= $StepInfo['class'] . $StepInfo['type'];
}
$stepLine .= $StepInfo['function'] .'::'. $StepInfo['line'] ."\t". $StepInfo['file'];
$DebugOut[] = $stepLine;
}
return implode("\n", $DebugOut);
}
protected function QErrResultInit()
{
$Result = array('Status' => false, 'Query' => $this->lastQuery, );
$Result['ErrorNum'] = $this->ErrorNum();
$Result['ErrorStr'] = $this->ErrorStr();
if (!empty($_SERVER['REMOTE_ADDR'])) $Result['SourceIP'] = $_SERVER['REMOTE_ADDR']; // helps with debugging.
$Result['Error'] = $Result['ErrorNum'] .':'. $Result['ErrorStr'];
return $Result;
}
## Subclasses are free to implement/override these methods
## they can also NOT, but set the appropriate static $fxnName var and these functions will call/return the value.
public function ErrorNum()
{
if (is_null($this->cnxnRef)) return 0;
$fxn = static::$fxnNameErrorNum;
return $fxn($this->cnxnRef)+0;
}
public function ErrorStr()
{
if (is_null($this->cnxnRef)) return '';
$fxn = static::$fxnNameErrorStr;
return $fxn($this->cnxnRef);
}
public function Error()
{
$errNum = $this->ErrorNum();
$errStr = $this->ErrorStr();
return array($errNum, $errStr);
}
public function ErrorMsg($ErrMsg=true)
{
if (true === $ErrMsg) $ErrMsg = $this->Error();
if (false === $ErrMsg) return '';
list($errNum, $errStr) = $ErrMsg;
return "$errNum:$errStr";
}
public function GetQueryError()
{
return $this->QErrData;
}
# A DBError is a failure in a non-query operation, like connect or set database.
public function GetDBError()
{
$ErrInfo = $this->ErrorInfo;
$ErrInfo['cnxn_start_ts'] = $this->connStartTime;
$ErrInfo['num_queries'] = $this->numQueries;
return $ErrInfo;