-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.php
794 lines (711 loc) · 18 KB
/
db.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
<?php
/* Copyright 2009-2013 Mo McRoberts.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @include uses('db');
* @source http://github.com/nexgenta/eregansu/blob/master/lib/db.php
*/
require_once(PLATFORM_LIB . 'uri.php');
/***********************************************************************
*
* Interfaces
*
**********************************************************************/
/* The interface that all types of database class must conform to */
interface IDatabase
{
public function query($query);
}
/* Transactional databases */
interface ITransactional
{
/* Begin a transaction */
public function begin();
/* Roll-back an in-progress transaction */
public function rollback();
/* Commit (complete) a transaction */
public function commit();
/* Perform the callback $function within a transaction, up to
* $maxRetries attempts.
*/
public function perform($function, $data = null, $maxRetries = 10);
}
/* SQL Databases */
interface ISQLDatabase extends IDatabase
{
public function queryArray($query, $params);
public function insertInto($table, $values);
public function value($query);
public function valueArray($query, $params);
public function row($query);
public function rowArray($query, $params);
public function rows($query);
public function rowsArray($query, $params);
public function exec($query);
public function execArray($query, $params);
public function alias($name, $table = null);
public function quoteObject($name);
public function quoteObjectRef(&$name);
public function quoteRef(&$value);
public function quote($value);
public function rowCount();
public function now();
}
/* Document-oriented content stores */
interface IContentStore extends IDatabase
{
/* Create */
public function insert($values);
public function insertId();
/* Read */
public function fetch($what);
/* Update */
public function update($what, $values);
/* Delete */
public function delete($what);
}
/* Directory services (e.g., LDAP) */
interface IDirectoryService extends IDatabase
{
public function insertAt($dn, $object);
}
interface IDataSet extends Iterator, Countable
{
}
/* Deprecated */
interface IDBCore extends ISQLDatabase, ITransactional
{
}
/* Deprecated */
interface DataSet extends IDataSet
{
}
/***********************************************************************
*
* Exceptions
*
**********************************************************************/
/**
* Class encapsulating database-related exceptions.
*
* @synopsis throw new DBException($code, $message, $dbQuery);
*/
class DBException extends Exception
{
/**
* Error code relating to the exception condition.
*
* The \P{$code} property contains an error code relating to the exception
* condition, usually as supplied by the database system itself.
*
* @type string
* @note \C{DBException} overrides the visibility of \x{Exception::$code}
* to make it \k{public}.
*/
public $code;
/**
* Human-readable error message relating to the exception condition.
*
* The \P{$errMsg} property contains a human-readable error message
* relating to the exception condition, usually as supplied by the
* database system itself.
*
* Unlike the message produced by converting the instance to a string,
* \P{$errMsg} does not contain the query which was being executed when
* the exception occurred.
*/
public $errMsg;
/**
* Text of the database query being performed when the exception condition
* occurred.
*
* The \P{$query} property contains the text of the database query being
* performed when the exception condition ocurred, or \k{null} if no
* query was in progress at the time.
*/
public $query;
/**
* The \C{DBException} constructor is responsible for initialising a new
* database exception object.
*
* The constructor will automatically populate the \C{DBException}
* instance's properties and generate a complete exception message which is
* passed along with \p{$errCode} to \link{http://www.php.net/manual/en/exception.construct.php|Exception::__construct}.
*/
public function __construct($errCode, $errMsg, $query)
{
$this->errMsg = $errMsg;
$this->query = $query;
if(strlen($query))
{
parent::__construct($errMsg . ' while executing: ' . $query, $errCode);
}
else
{
parent::__construct($errMsg, $errCode);
}
}
}
/* Database errors relating to connection and configuration (rather than
* malformed queries, data integrity, and so on. These exceptions may be
* caught and considered transient in some circumstances, but should not
* generally cause an automatic immediate retry.
*/
class DBSystemException extends DBException
{
}
/* Database errors relating to connections and authentication */
class DBNetworkException extends DBSystemException
{
}
/* Database errors relating to transient scenarios which caused the transaction
* to be rolled back.
*/
class DBRollbackException extends DBException
{
}
/***********************************************************************
*
* Classes
*
**********************************************************************/
/* Abstract base class used to establish connections to databases. e.g.:
*
* $db = Database::connect('mysql://localhost/example');
*/
abstract class Database implements IDatabase
{
protected static $stderr;
public $maxReconnectAttempts = 0;
public $reconnectDelay = 1;
public $dbms = 'unknown';
protected $params;
protected $schema;
protected $dbName;
protected $schemaName;
public static function connect($uri)
{
if(!is_object($uri))
{
$uri = new URI($uri);
}
$inst = URI::handlerForScheme($uri->scheme, 'Database', false, $uri);
if(!is_object($inst))
{
/* Try a search engine instead -- at some future point this will
* become unnecessary
*/
$inst = URI::handlerForScheme($uri->scheme, 'SearchEngine', false, $uri);
}
if(!is_object($inst))
{
throw new DBException(0, 'Unsupported database connection scheme "' . $uri->scheme . '"', null);
}
return $inst;
}
public function __construct($params)
{
$this->params = $params;
if(!isset($this->params->dbName))
{
$p = $this->params->path;
while(substr($p, 0, 1) == '/')
{
$p = substr($p, 1);
}
$x = explode('/', $p);
$this->params->dbName = $x[0];
}
if(isset($this->params->options['autoconnect']))
{
$this->params->options['autoconnect'] = parse_bool($this->params->options['autoconnect']);
}
else
{
$this->params->options['autoconnect'] = true;
}
if(isset($this->params->options['autoreconnect']))
{
$this->params->options['autoreconnect'] = parse_bool($this->params->options['autoconnect']);
}
else
{
$this->params->options['autoreconnect'] = php_sapi_name() == 'cli' ? true : false;
}
if(isset($this->params->options['reconnectquietly']))
{
$this->params->options['reconnectquietly'] = parse_bool($this->params->options['autoconnect']);
}
else
{
$this->params->options['reconnectquietly'] = php_sapi_name() == 'cli' ? false : true;
}
if(isset($this->params->options['prefix']))
{
$this->prefix = $this->params->options['prefix'];
}
if(isset($this->params->options['suffix']))
{
$this->suffix = $this->params->options['suffix'];
}
if($this->params->options['autoconnect'])
{
$this->autoconnect();
}
if(isset($this->params->options['maxreconnectattempts']))
{
$this->maxReconnectAttempts = $this->params->options['maxreconnectattempts'];
}
if(isset($this->params->options['reconnectdelay']))
{
$this->reconnectDelay = $this->params->options['reconnectdelay'];
}
}
public function &__get($name)
{
$nothing = null;
if($name == 'schema')
{
if(!$this->schema)
{
require_once(dirname(__FILE__) . '/dbschema.php');
$this->schema = DBSchema::schemaForConnection($this);
}
return $this->schema;
}
if($name == 'dbName')
{
if(isset($this->dbName))
{
return $this->dbName;
}
return $this->params->dbName;
}
if($name == 'schemaName')
{
return $this->schemaName;
}
return $nothing;
}
protected function log()
{
if(!self::$stderr) self::$stderr = fopen('php://stderr', 'w');
$args = func_get_args();
fwrite(self::$stderr, '[' . strftime('%Y-%m-%d %H:%M:%S %z') . '] ' . implode(' ', $args) . "\n");
}
abstract protected function raiseError($query, $allowReconnect = true);
protected function reportError($errcode, $errmsg, $sqlString, $class = 'DBException')
{
throw new $class($errcode, $errmsg, $sqlString);
}
protected function reconnect()
{
$dbname = @$this->params['dbname'];
if(!strlen($dbname)) $dbname = '(None)';
if(!$this->params->options['reconnectquietly'])
{
$this->log('Lost connection to database', $dbname, ', attempting to reconnect...');
}
for($c = 0; !$this->maxReconnectAttempts || ($c < $this->maxReconnectAttempts); $c++)
{
try
{
if($this->autoconnect())
{
if(!$this->params->options['reconnectquietly'])
{
$this->log('Connection to database', $dbname, 're-established after', $c, 'attempts');
}
return true;
}
}
catch(DBNetworkException $e)
{
}
if($this->reconnectDelay)
{
sleep($this->reconnectDelay);
}
if($c && (($c < 100 && !($c % 10)) || !($c % 100)))
{
if(!$this->params->options['reconnectquietly'])
{
$this->log('Unable to connect to database', $dbname, 'after', $c, 'attempts, still trying...');
}
}
}
throw new DBNetworkException(0, 'Failed to reconnect to database ' . $dbname . ' after ' . $this->maxReconnectAttempts);
}
}
/* Abstract base class implementing ISQLDatabase */
abstract class SQLDatabase extends Database implements ISQLDatabase, ITransactional
{
protected $rsClass;
public $prefix = '';
public $suffix = '';
protected $transactionDepth;
protected $aliases = array();
/**** IDatabase support ****/
/* For compatibility, the arguments can be either way around. New
* code should use insertInto() instead.
*/
public function insert($table, $kv = null)
{
if($kv === null)
{
throw new DBException(0, 'Destination relation not specified in SQLDatabase::insert()', null);
}
if(is_array($table) && !is_array($kv))
{
return $this->insertInto($kv, $table);
}
return $this->insertInto($table, $kv);
}
public function update($table, $kv, $clause = null)
{
$sql = 'UPDATE ' . $this->quoteTable($table) . ' SET ';
$keys = array_keys($kv);
foreach($keys as $k)
{
if(substr($k, 0, 1) == '@')
{
$v = $kv[$k];
$sql .= substr($k, 1) . ' = ' . $v . ', ';
}
else
{
$sql .= $this->quoteObject($k) . ' = ' . $this->quote($kv[$k]) . ', ';
}
}
$sql = substr($sql, 0, -2);
if(is_string($clause) && strlen($clause))
{
$sql .= ' WHERE ' . $clause;
}
else if(is_array($clause) && count($clause))
{
$sql .= ' WHERE ';
foreach($clause as $key => $value)
{
$sql .= $this->quoteObject($key) . ' = ' . $this->quote($value) . ' AND ';
}
$sql = substr($sql, 0, -4);
}
return $this->execute($sql, false);
}
public function fetch($what)
{
$params = func_get_args();
array_shift($params);
return $this->rowArray($query, $params);
}
/**** ISQLDatabase support ****/
/* Execute any (parametized) query, expecting a boolean result */
public function exec($query)
{
$params = func_get_args();
array_shift($params);
if($this->vexec($query, $params))
{
return true;
}
return false;
}
/* Execute any (parametized) query, expecting a boolean result */
public function execArray($query, $params)
{
if(!is_array($params)) $params = array();
$query = preg_replace('/\{([^}]+)\}/e', "\$this->quoteTable(\"\\1\")", $query);
$sql = preg_replace('/\?/e', "\$this->quote(array_shift(\$params))", $query);
return $this->execute($sql, false) ? true : false;
}
/* $rs = $inst->query('SELECT * FROM {sometable} WHERE "field" = ? AND "otherfield" = ?', $something, 27); */
public function query($query)
{
$params = func_get_args();
array_shift($params);
if(($r = $this->vquery($query, $params)))
{
return new $this->rsClass($this, $r, $query, $params);
}
return null;
}
public function queryArray($query, $params)
{
if(($r = $this->vquery($query, $params)))
{
return new $this->rsClass($this, $r, $query, $params);
}
return null;
}
public function row($query)
{
$params = func_get_args();
array_shift($params);
return $this->rowArray($query, $params);
}
public function rowArray($query, $params)
{
$row = null;
if(($r = $this->vquery($query, $params)))
{
$rs = new $this->rsClass($this, $r, $query, $params);
$row = $rs->next();
$rs = null;
}
return $row;
}
public function rows($query)
{
$params = func_get_args();
array_shift($params);
return $this->rowsArray($query, $params);
}
public function rowsArray($query, $params)
{
$rows = null;
if(($r = $this->vquery($query, $params)))
{
$rows = array();
$rs = new $this->rsClass($this, $r, $query, $params);
while(($row = $rs->next()))
{
$rows[] = $row;
}
$rs = null;
}
return $rows;
}
public function value($query)
{
$params = func_get_args();
array_shift($params);
return $this->valueArray($query, $params);
}
public function valueArray($query, $params)
{
$row = null;
if(($r = $this->vquery($query, $params)))
{
$rs = new $this->rsClass($this, $r, $query, $params);
$row = $rs->next();
$rs = null;
if($row)
{
foreach($row as $v)
{
return $v;
}
}
}
return null;
}
public function insertInto($table, $kv)
{
$keys = array_keys($kv);
$klist = array();
foreach($keys as $k)
{
if(substr($k, 0, 1) == '@')
{
$values[] = $kv[$k];
$klist[] = $this->quoteObject(substr($k, 1));
}
else
{
$klist[] = $this->quoteObject($k);
$values[] = $this->quote($kv[$k]);
}
}
$sql = 'INSERT INTO ' . $this->quoteTable($table) . ' (' . implode(',', $klist) . ') VALUES (' . implode(',', $values) . ')';
return $this->execute($sql, false);
}
public function alias($name, $table = null)
{
if(is_array($name))
{
foreach($name as $alias => $table)
{
$this->aliases[$alias] = $table;
}
}
else if(strlen($table))
{
$this->aliases[$name] = $table;
}
else
{
unset($this->aliases[$name]);
}
}
public function quoteTable($name)
{
if(isset($this->aliases[$name])) $name = $this->aliases[$name];
$name = $this->prefix . $name . $this->suffix;
$this->quoteObjectRef($name);
return $name;
}
public function quoteObject($name)
{
$this->quoteObjectRef($name);
return $name;
}
public function quote($value)
{
$this->quoteRef($value);
return $value;
}
public function quoteObjectRef(&$name)
{
$name = '"' . $name . '"';
}
public function now()
{
return $this->quote(strftime('%Y-%m-%d %H:%M:%S'));
}
public function rowCount()
{
return null;
}
/**** ITransactional support ****/
public function begin()
{
$this->execute('START TRANSACTION', false);
$this->transactionDepth++;
}
public function rollback()
{
$this->execute('ROLLBACK', false);
if($this->transactionDepth)
{
$this->transactionDepth--;
}
}
/* Invoke $function within a transaction which will be automatically re-tried
* if necessary.
*/
public function perform($function, $data = null, $maxRetries = 10)
{
$count = 0;
while($maxRetries < 0 || $count < $maxRetries)
{
try
{
$this->begin();
if(call_user_func($function, $this, $data))
{
if($this->commit())
{
return true;
}
continue;
}
$this->rollback();
return false;
}
catch(DBRollbackException $e)
{
$count++;
}
}
throw new DBRollbackException(0, 'Repeatedly failed to perform transaction (retried ' . $maxRetries . ' times)');
}
/* Execute any (parametized) query, expecting a resultset */
public /*internal*/ function vquery($query, $params)
{
if(!is_array($params)) $params = array();
$query = preg_replace('/\{([^}]+)\}/e', "\$this->quoteTable(\"\\1\")", $query);
$sql = preg_replace('/\?/e', "\$this->quote(array_shift(\$params))", $query);
return $this->execute($sql, true);
}
/* Deprecated */
public function vexec($query, $params)
{
if(!is_array($params)) $params = array();
$query = preg_replace('/\{([^}]+)\}/e', "\$this->quoteTable(\"\\1\")", $query);
$sql = preg_replace('/\?/e', "\$this->quote(array_shift(\$params))", $query);
return $this->execute($sql, false) ? true : false;
}
}
abstract class ContentStore extends Database implements IContentStore
{
}
abstract class DirectoryService extends Database implements IDirectoryService
{
}
/* Deprecated */
abstract class DBCore extends SQLDatabase
{
}
/* while(($row = $rs->next())) { ... } */
class DBDataSet implements IDataSet
{
public $fields = array();
public $EOF = true;
public $db;
public $total = 0;
protected $resource;
protected $count = 0;
protected $fetched = false;
public function __construct($db, $resource, $query = null, $params = null)
{
$this->db = $db;
$this->resource = $resource;
$this->EOF = false;
}
public function next()
{
if($this->EOF) return null;
if(!$this->row())
{
$this->EOF = true;
return false;
}
$this->count++;
return $this->fields;
}
public function rewind()
{
throw new DBException(0, 'Dataset cannot be rewound', null);
}
public function current()
{
if(!$this->fetched)
{
$this->next();
}
return $this->fields;
}
public function key()
{
if(!$this->fetched)
{
$this->next();
}
return $this->count;
}
public function valid()
{
if(!$this->fetched)
{
$this->next();
}
return !$this->EOF;
}
public function count()
{
return $this->count;
}
}