-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDb.php
2574 lines (2232 loc) · 68.5 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
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
/**
* @file Db.php
* @author Gabriele Tozzi <[email protected]>
* @package DoPhp
* @brief Simple class for database connection handling
*/
namespace dophp;
/**
* Simple class for database connection handling
*/
class Db {
/** MySQL DB Type */
const TYPE_MYSQL = 'mysql';
/** Microsoft SQL Server DB TYPE */
const TYPE_MSSQL = 'mssql';
/** PostgreSQL Server DB TYPE */
const TYPE_PGSQL = 'pgsql';
/** Debug object (if enabled) */
public $debug = false;
/**
* If true, enables FreeTDS/ODBC/MSSQL fix
* Forces casting of all binded parameters to VARCHAR in run()
*
* @see http://stackoverflow.com/a/3853811/4210714
*/
public $vcharfix = false;
/** PDO instance */
protected $_pdo;
/** Database type, one of:
* - null: Uninited/unknown
* - mysql: MySQL server
* - mssql: Microsoft SQL Server
*/
protected $_type = null;
/** Tells lastInsertId() PDO's driver support */
protected $_hasLid = true;
/** Wiritten for debug only, do not use for different purposes */
public $lastQuery = null;
/** Wiritten for debug only, do not use for different purposes */
public $lastParams = null;
/** PK column names cache for insert() */
private $__pkCache = [];
/**
* Starts a PDO connection to DB
*
* @param $dsn string: DSN, PDO valid
* @param $user string: Username to access DBMS (if not included in DSN)
* @param $pass string: Password to access DBMS (if not included in DSN)
* @param $vcharfix bool: See Db::vcharfix docs
*/
public function __construct($dsn, $user=null, $pass=null, $vcharfix=false) {
$this->vcharfix = $vcharfix;
$this->_pdo = new \PDO($dsn, $user, $pass);
$this->_pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->_pdo->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_ASSOC);
$driver = $this->_pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
switch( $driver ) {
case 'mysql':
$this->_type = self::TYPE_MYSQL;
$this->_pdo->exec('SET sql_mode = \'TRADITIONAL,STRICT_ALL_TABLES,NO_AUTO_VALUE_ON_ZERO,NO_ZERO_DATE,NO_ZERO_IN_DATE,ANSI_QUOTES\'');
$this->_pdo->exec('SET NAMES utf8mb4');
break;
case 'odbc':
$this->_hasLid = false;
case 'sqlsrv':
case 'mssql':
case 'sybase':
case 'dblib':
$this->_type = self::TYPE_MSSQL;
$this->_pdo->exec('SET ARITHABORT ON');
$this->_pdo->exec('SET DATEFORMAT ymd');
break;
case 'pgsql':
$this->_type = self::TYPE_PGSQL;
break;
default:
throw new \dophp\NotImplementedException("Unknown DBMS \"$driver\"");
}
}
/**
* Prepares this object to be serialized
*
* @warning This makes the object serializable, but unusable after
* unserialization
* @return array: list of properties to include in serialized object
*/
public function __sleep() {
$vars = get_object_vars($this);
unset($vars['_pdo']);
unset($vars['__pkCache']);
return array_keys($vars);
}
/**
* When waking up, try to get the actual PDO from the running db
*/
public function __wakeup() {
$curDb = \DoPhp::db();
if( ! $curDb )
return;
$this->_pdo = $curDb->_pdo;
$this->__pkCache = [];
}
/**
* Returns database type
*/
public function type() {
return $this->_type;
}
/**
* Prepares a statement, executes it with given parameters and returns it
*
* @param $query mixed: The query to be executed or SelectQuery
* @param $params mixed: Array containing the parameters or single parameter
* @param $vcharfix boolean: like $this->vcharfix, ovverides it when used
* @return \PDOStatement
* @throws StatementExecuteError
*/
public function run($query, $params=array(), $vcharfix=null) {
if( $this->debug && $this->debug instanceof debug\Request && $this->debug->isEnabled() )
$dbgquery = new debug\DbQuery();
else
$dbgquery = null;
if( ! is_array($params) )
$params = array($params);
if( $vcharfix === null )
$vcharfix = $this->vcharfix;
if( $query instanceof SelectQuery )
$query = $query->asSql($this->_type);
// Modify the query to cast all params to varchar
if( $vcharfix )
$query = preg_replace('/(\?|:[a-z]+)/', 'CAST($0 AS VARCHAR)', $query);
foreach($params as & $p)
if( gettype($p) == 'boolean' ) {
// PDO would convert false into null otherwise
if( $p === true )
$p = 1;
elseif( $p === false )
$p = 0;
}
elseif( $p instanceof Date )
$p = $p->format('Y-m-d');
elseif( $p instanceof Time )
$p = $p->format('H:i:s');
elseif( $p instanceof \DateTime )
$p = $p->format('Y-m-d H:i:s');
unset($p);
if( $dbgquery )
$dbgquery->built($query, $params);
$this->lastQuery = $query;
$this->lastParams = $params;
// Using emulated prepares for historic reasons and coherency between DBMSes
$st = $this->_pdo->prepare($query, [ \PDO::ATTR_EMULATE_PREPARES => true ]);
if( $dbgquery )
$dbgquery->prepared();
if( ! $st->execute($params) )
throw new StatementExecuteError($st);
if( $dbgquery ) {
$dbgquery->executed();
$this->debug->add($dbgquery);
}
return $st;
}
/**
* Like Db::run(), but returns a Result instead
*
* @see run()
* @param $query mixed: The Query string or SelectQuery
* @param $params array: Associative array of params
* @param $types array: Associative array name => type of requested return
* types. Omitted ones will be guessed from PDO data.
* Each type must be on of Table::DATA_TYPE_* constants
* @return Result
*/
public function xrun($query, $params=[], $types=[]) {
$st = $this->run($query, $params);
return new Result($st, $query, $params, $types);
}
/**
* Runs an INSERT statement from an associative array and returns ID of the
* last auto_increment value
*
* @param $noPkCache bool: disables local PK cache for PgSQL
* @see self::buildInsUpdQuery
*/
public function insert($table, $params, $noPkCache=false) {
// PgSQL's PDO::lastInsertId() fails badly when trying to call it after
// a non-generated insert. Also, looks like there is no PgSQL equivalent
// for SCOPE_IDENTITY() or LAST_INSERT_ID(). Looks like i need to work
// around this problem and inspect the table's PK structure before
// running the query. Using a small local cache to speed up multiple
// inserts in a row, may be disabled in very special circumstances where
// the table is altered in between
if( $this->_type == self::TYPE_PGSQL && ( $noPkCache || ! array_key_exists($table, $this->__pkCache) ) ) {
$q = '
SELECT a.attname AS col
FROM pg_index AS i
JOIN pg_attribute AS a
ON i.indrelid = a.attrelid
AND a.attnum = any( i.indkey )
WHERE i.indrelid = ' . $this->quote($table) . '::regclass
AND i.indisprimary
';
$this->__pkCache[$table] = [];
foreach( $this->run($q)->fetchAll() as $r )
$this->__pkCache[$table][] = $r['col'];
}
$rcols = $this->_type == self::TYPE_PGSQL ? $this->__pkCache[$table] : null;
list($q,$p) = $this->buildInsUpdQuery('ins', $table, $params, null, $rcols);
// Retrieve the ID by running a scope_identity query
if( ! $this->_hasLid )
$q .= '; SELECT SCOPE_IDENTITY() AS ' . $this->quoteObj('id');
$st = $this->xrun($q, $p);
if( $this->_type == self::TYPE_PGSQL ) {
if( $rcols ) {
$r = $st->fetch();
if( count($rcols) == 1 )
return $r[$rcols[0]];
return $r;
} else
return null;
} elseif( $this->_hasLid )
return $this->lastInsertId();
else {
$r = $st->fetch();
if( ! $r )
throw new DbException('Failed to retrieve id');
return $r['id'];
}
}
/**
* Runs an UPDATE statement from an associative array
*
* @see self::buildInsUpdQuery
* @see self::buildParams
* @return int: Number of affected rows
*/
public function update($table, $params, $where) {
list($s,$ps) = $this->buildInsUpdQuery('upd', $table, $params);
list($w,$pw) = self::buildParams($where, ' AND ', $this->_type);
$q = "$s WHERE $w";
$p = array_merge($ps, $pw);
return $this->run($q, $p)->rowCount();
}
/**
* Runs a DELETE statement
*
* @see self::buildParams
* @return int: Number of affected rows
*/
public function delete($table, $where) {
list($w,$p) = self::buildParams($where, ' AND ', $this->_type);
$q = 'DELETE FROM '.$this->quoteObj($table)." WHERE $w";
return $this->run($q, $p)->rowCount();
}
/**
* Runs an INSERT ON DUPLICATE KEY UPDATE statement from an associative array
*
* @see self::buildInsUpdQuery
*/
public function insertOrUpdate($table, $params, $ccols=null) {
list($q,$p) = $this->buildInsUpdQuery('insupd', $table, $params, $ccols);
$this->run($q, $p);
// Does not return LAST_INSERT_ID because it is not updated on UPDATE
}
/**
* Runs FOUND_ROWS() and returns result
*
* @return int: Number of found rows
*/
public function foundRows() {
switch( $this->_type ) {
case Db::TYPE_MYSQL:
$q = 'SELECT FOUND_ROWS() AS '.$this->quoteObj('fr');
break;
case Db::TYPE_MSSQL:
$q = 'SELECT @@ROWCOUNT AS '.$this->quoteObj('fr');
break;
case Db::TYPE_PGSQL:
$q = 'SELECT count(*) OVER() AS '.$this->quoteObj('fr');
break;
default:
throw new NotImplementedException("Not Implemented DBMS {$this->_type}");
}
$res = $this->run($q)->fetch();
return $res['fr'] !== null ? (int)$res['fr'] : null;
}
/**
* Begins a transaction
*
* @see \PDO::beginTransaction()
* @param $useExisting bool: If true, will not try to open a new transaction
* when there is already an active transaction
* @return true when transaction has been started, false instead
*/
public function beginTransaction($useExisting = false) {
if( $useExisting && $this->inTransaction() )
return false;
if( ! $this->_pdo->beginTransaction() )
throw new DbException('Error opening transaction');
return true;
}
/**
* Checks if a transaction is currently active within the driver
*
* @see \PDO::inTransaction()
*/
public function inTransaction() {
return $this->_pdo->inTransaction();
}
/**
* Commits a transaction
*
* @see \PDO::commit()
*/
public function commit() {
if( ! $this->_pdo->commit() )
throw new DbException('Commit error');
}
/**
* Rolls back a transaction
*
* @see \PDO::rollBack()
*/
public function rollBack() {
if( ! $this->_pdo->rollBack() )
throw new DbException('Rollback error');
}
/**
* Returns last insert ID
*
* @see \PDO::lastInsertId()
* @return string: The ID of the last inserted row or null if not available
*/
public function lastInsertId() {
$lid = $this->_pdo->lastInsertId();
if( is_int($lid) )
return $lid;
if( is_numeric($lid) )
return (int)$lid;
return $lid;
}
/**
* Quotes a parameter
*
* @see \PDO::quote
* @param $param string: The string to be quoted
* @param $ptype int: The parameter type, as PDO constant
* @return string: The quoted string
*/
public function quote($param, $ptype = \PDO::PARAM_STR) {
$quoted = $this->_pdo->quote($param, $ptype);
if( $quoted === false )
throw new DbQuoteException('Error during quoting');
return $quoted;
}
/**
* Quotes a schema object (table, column, ...)
*
* @param $name string: The unquoted object name
* @param $ignoreDot boolean: if true, the entire $name is enclosed in quotes,
* otherwise is split at the dot character and quoted
* separately
* @return string: The quoted object name
*/
public function quoteObj($name, $ignoreDot=false) {
return self::quoteObjFor($name, $this->_type, $ignoreDot);
}
/**
* Quotes a schema object (table, column, ...)
*
* @param $name string: The unquoted object name
* @param $type string: The DBMS type (ansi, mysql, mssql, pgsql)
* @param $ignoreDot boolean: if true, the entire $name is enclosed in quotes,
* otherwise is split at the dot character
* and quoted separately (default)
* @return string: The quoted object name
*/
public static function quoteObjFor($name, $type, $ignoreDot=false) {
$split = $ignoreDot ? [ $name ] : explode('.', $name);
foreach ($split as &$part) {
switch( $type ) {
case self::TYPE_MYSQL:
$part = "`".str_replace('`', '``', $part)."`";
break;
case self::TYPE_MSSQL:
$part = "[$part]";
break;
case self::TYPE_PGSQL:
case 'ansi':
$part = "\"$part\"";
break;
default:
throw new NotImplementedException("Type \"$type\" not implemented");
}
}
unset($part);
return implode('.', $split);
}
/**
* Converts a string using SQL-99 "\"" quoting into a string using
* DBMS' native quoting
*
* @deprecated
* @see self::quoteObj
*/
public function quoteConv($query) {
$spat = '/"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"/';
$reppat = $this->quoteObj('$1');
return preg_replace($spat, $reppat, $query);
}
/**
* Builds a partial query suitable for insert or update in the format
* "SET col1 = val1, col2 = val2, ..."
* The "insupd" type builds and INSERT query with an
* "ON DUPLICATE KEY UPDATE" condition for all the values
*
* @param $type string: The query type (ins, upd, insupd)
* @param $table string: The name of the table
* @param $ccols array: When type is 'insupd' and DBMS is PostgreSQL,
* this is the list of constraint columns. Ignored otherwise
* @param $rcols array: When DBMS is PostgreSQL, this is the list of columns
* in the RETURNING clause of the query
* @see self::buildParams
* @return array [query string, params]
*/
public function buildInsUpdQuery($type, $table, $params, $ccols=null, $rcols=null) {
switch( $type ) {
case 'insupd':
if( $this->_type == self::TYPE_PGSQL && ! $ccols )
throw new \InvalidArgumentException('$ccols must be specified for PostgreSQL');
// no break is intended
case 'ins':
$q = 'INSERT INTO';
$ins = true;
break;
case 'upd':
$q = 'UPDATE';
$ins = false;
break;
default:
throw new NotImplementedException("Unknown type $type");
}
$q .= ' ' . $this->quoteObj($table);
if( $ins ) {
list($cols, $p) = self::processParams($params, $this->_type);
if( ! count($cols) )
$q .= ' DEFAULT VALUES ';
else {
$q .= '(' . implode(',', array_keys($cols)) . ')';
$q .= ' VALUES (' . implode(',', array_values($cols)) . ')';
}
if( $type == 'insupd' ) {
$updates = array();
foreach( $cols as $k => $v )
if( $this->_type == self::TYPE_PGSQL )
$updates[] = "$k=excluded.$k";
else
$updates[] = "$k=VALUES($k)";
if( $this->_type == self::TYPE_PGSQL ) {
$con = implode(', ', array_map(function($c){ return $this->quoteObj($c); }, $ccols));
$cq = " ON CONFLICT ($con) DO UPDATE SET ";
} else
$cq = ' ON DUPLICATE KEY UPDATE ';
$q .= $cq . implode(', ', $updates);
}
} else {
list($sql, $p) = self::buildParams($params, ', ', $this->_type);
$q .= " SET $sql";
}
if( $rcols ) {
$q .= " RETURNING ";
$q .= implode(', ', array_map(function($c){ return $this->quoteObj($c); }, $rcols));
}
return array($q, $p);
}
/**
* Utility function to build an IN() clause
*
* @param $params array: list of paramaters
* @param $emptyok bool: If true, accepts an empty params array instead of
* throwing and exception
* @return string: The in statement, or empty string if no params
* @throws \InvalidArgumentException
*/
public static function buildInStatement($params, $emptyok=false) {
if( ! $params ) {
if( $emptyok )
return '';
throw new \InvalidArgumentException('Empty list of params received and emptyok is not set');
}
return 'IN(' . implode(',', array_fill(0, count($params), '?')) . ')';
}
/**
* Processes an associative array of parameters into an array of SQL-ready
* elements
*
* @param $params array: Associative array with parameters. Key is the name
* of the column. If the data is an array, 2nd key is
* the custom sql funcion to use. By example:
* 'password' => [ '123456', 'SHA1(?)' ]
* If also 1st key is an array, then multiple arguments
* will be bound to the custom sql function, By example:
* 'password' => [['12345', '45678'], 'AES_ENCRYPT(?,?)'],
* @params $type string: The DBMS type, used for quoting (see Db::QuoteObjFor())
* @return array [ sql array, params array ]
* sql array format: [ column (quoted) => parameter placeholder ]
* params array format: [ parameter placeholder => value ]
*/
public static function processParams($params, $type=self::TYPE_MYSQL) {
if( ! $params )
return array([], []);
$cols = array();
$vals = array();
foreach( $params as $k => $v ) {
$sqlCol = self::quoteObjFor($k, $type);
if( is_array($v) ) {
if( count($v) != 2 || ! array_key_exists(0,$v) || ! array_key_exists(1,$v) )
throw new \InvalidArgumentException('Invalid number of array components');
if( is_array($v[0]) ) {
$f = $v[1];
foreach( $v[0] as $n => $vv ) {
$kk = $k . $n;
$f = preg_replace('/\?/', ":$kk", $f, 1);
if( $vv !== null )
$vals[$kk] = $vv;
}
$sqlPar = $f;
} else {
$sqlPar = str_replace('?', ":$k", $v[1]);
if( $v[0] !== null )
$vals[$k] = $v[0];
}
} else {
$sqlPar = ":$k";
$vals[$k] = $v;
}
$cols[$sqlCol] = $sqlPar;
}
// SQL Server driver fix
if( $type == self::TYPE_MSSQL ) {
foreach( $vals as &$v )
if( $v instanceof \DateTime )
$v = $v->format('Ymd H:i:s.v');
unset($v);
}
return array($cols, $vals);
}
/**
* Formats an associative array of parameters into a query string and an
* associative array ready to be passed to pdo
*
* @deprecated
* @see self::processParams
* @param $glue string: The string to join the arguments, usually ', ' or ' AND '
* @return array [query string, params array]
*/
public static function buildParams($params, $glue=', ', $type=self::TYPE_MYSQL) {
list($cols, $vals) = self::processParams($params, $type);
$sql = '';
foreach( $cols as $c => $p )
$sql .= (strlen($sql) ? $glue : '') . "$c = $p";
return array($sql, $vals);
}
/**
* Builds a "limit" statement
*
* @param $limit mixed: If True, returns only first element,
* if int, returns first $limit elements
* @param $skip integer: Number of records to skip
* @return string: the LIMIT statement
*/
public static function buildLimit($limit=null, $skip=0) {
if( $skip || $limit )
$lim = 'LIMIT ';
else
$lim = '';
if( $skip )
$lim .= (int)$skip . ',';
if( $limit === true )
$lim .= '1';
elseif( $limit )
$lim = (int)$limit;
return $lim;
}
/**
* Builds an "order by" statement
*
* @param $order array: Names of the columns to order by
* @return string: the ORDER BY statement
*/
public static function buildOrderBy($order=null) {
if( ! $order )
return '';
$ord = 'ORDER BY ';
$ord .= implode(', ', $order);
return $ord;
}
/**
* Returns a dophp\Table instance (invokes Table::__construct)
*
* @param $name string: The table name
* @return \dophp\Table
* @throws \Exception on invalid name
* @see \dophp\Table::__construct
*/
public function table($name) {
return new Table($this, $name);
}
/**
* Returns true when current DBMS supports schemas
*/
public function hasSchemaSupport(): bool {
switch( $this->_type ) {
case self::TYPE_MYSQL:
return false;
case self::TYPE_PGSQL:
case self::TYPE_MSSQL:
return true;
}
throw new \dophp\NotImplementedException("Unknown Type \"$this->_type\"");
}
/**
* Returns default schema name for current DBMS
*
* @return string: schema name or null when schemas are not supported
*/
public function getDefaultSchemaName(): ?string {
switch( $this->_type ) {
case self::TYPE_MYSQL:
return null;
case self::TYPE_PGSQL:
return 'public';
case self::TYPE_MSSQL:
return 'dbo';
}
throw new \dophp\NotImplementedException("Unknown Type \"$this->_type\"");
}
}
/**
* Exception thrown when statement execution fails
*/
class StatementExecuteError extends \Exception {
/** The PDOStatement::errorCode() result */
public $errorCode;
/** The PDOStatement::errorInfo() result */
public $errorInfo;
/** The PDOStatement */
public $statement;
/** The Query */
public $query;
/** The params */
public $params;
public function __construct( $statement ) {
$this->statement = $statement;
$this->errorCode = $this->statement->errorCode();
$this->errorInfo = $this->statement->errorInfo();
parent::__construct("{$this->errorInfo[0]} [{$this->errorInfo[1]}]: {$this->errorInfo[2]}");
}
}
/**
* Small utility class to hold a Result's column info
*/
class ResultCol {
/** The column name */
public $name;
/** The column data type, one of Table::DATA_TYPE_* constants */
public $type;
/**
* Set the properties
*/
public function __construct($name, $type) {
$this->name = $name;
$this->type = $type;
}
/**
* Disallow modifying attributes
*
* @throws \Exception
*/
public function __set($name, $value) {
throw new \LogicException('Readonly class');
}
}
/**
* Represents a query result, it can be iterated, but onlyce once
*/
class Result implements \Iterator {
/** The initial key value */
const INIT_KEY = -1;
/** The PDO statement used to run the query */
protected $_st;
/** The query SQL */
protected $_query;
/** The query params */
protected $_params;
/** The explicit column types */
protected $_types;
/** The column info cache, array of ResultCol objects */
protected $_cols = [];
/** Next result to be returned */
protected $_current = null;
/** Next key to be returned (-1 = to be started) */
protected $_key = self::INIT_KEY;
/**
* Creates the result object from the given PDO statament
*
* @param $st \PDOStatement: The executed PDO statement
* @param $query string: The query string for the statement
* @param $params array: The used query parameters
* @param $types array: The requested explicit return types
*/
public function __construct( \PDOStatement $st, $query, $params, $types ) {
$this->_st = $st;
$this->_query = $query;
$this->_params = $params;
$this->_types = $types;
}
/**
* Returns the column type, with caching
*
* @see Table::getType()
* @param $idx int: The column index
* @return ResultCol
*/
public function getColumnInfo( $idx ) {
if( ! array_key_exists($idx, $this->_cols) ) {
// Cached value not found, generate it
$meta = $this->_st->getColumnMeta( $idx );
if( ! $meta )
throw new \InvalidArgumentException("No meta for column $idx");
if( isset($this->_types[$meta['name']]) ) {
$type = $this->_types[$meta['name']];
} elseif( isset($meta['sqlsrv:decl_type']) && $meta['sqlsrv:decl_type'] ) {
// Apparently the sqlsrv driver uses a different key for types
$declType = explode(' ', $meta['sqlsrv:decl_type'], 2)[0];
$type = Table::getType($declType, $meta['len']);
} elseif( ! isset($meta['native_type']) ) {
// Apparently JSON fields have no native_type
throw new \InvalidArgumentException("Missing native_type form column $idx, must declare type explicitly");
} else
$type = Table::getType($meta['native_type'], $meta['len']);
$this->_cols[$idx] = new ResultCol($meta['name'], $type);
}
// Return from cache
return $this->_cols[$idx];
}
/**
* Returns next result
*
* @param $column string: The column name; if given, only returns this column's value
* (or null if no result is found)
* @return array: The associative result, with properyl typed data
* (or false/null when no column is found)
*/
public function fetch(string $column=null) {
$this->_key++;
$raw = $this->_st->fetch( \PDO::FETCH_NUM );
if( $raw === false )
return $column ? null : false;
$res = [];
foreach( $raw as $idx => $val ) {
$col = $this->getColumnInfo($idx);
$res[$col->name] = Table::castVal($val, $col->type);
}
return $column ? $res[$column] : $res;
}
/**
* Returns all the results as array or arrays
*
* @return array: Array of arrays, see fetch()
*/
public function fetchAll() {
$ret = [];
foreach( $this as $k => $v )
$ret[$k] = $v;
return $ret;
}
/**
* Returns all the results as array or arrays, using the given col as key
*
* @param $col string: Name of the column to use as key
* @return array: Like fetchAll(), but using given col as key
*/
public function fetchAllBy($col) {
$ret = [];
foreach( $this as $v )
$ret[$v[$col]] = $v;
return $ret;
}
/**
* Returns all the results as array, with only values.
* Available only when the query has a single column
*
* @return array: List of col's values
*/
public function fetchAllVals() {
$ret = [];
$first = true;
foreach( $this as $k => $v ) {
if( $first ) {
$first = false;
// Get column info on first loop
if( count($v) < 1 )
throw new \LogicException('Columns not found');
elseif( count($v) > 1 )
throw new \LogicException('The query returned multiple columns');
$cname = $this->getColumnInfo(0)->name;
}
$ret[$k] = $v[$cname];
}
return $ret;
}
/**
* @see \Iterator::revind()
*/
public function rewind() {
if( $this->_key != self::INIT_KEY )
throw new \LogicException('The result has already been fetched');
$this->next();
}
/**
* @see \Iterator::valid()
*/
public function valid() {
return $this->_current ? true : false;
}
/**
* @see \Iterator::current()
*/
public function current() {
return $this->_current;
}
/**
* @see \Iterator::key()
*/
public function key() {
return $this->_key;
}
/**
* @see \Iterator::next()
*/
public function next() {
$this->_current = $this->fetch();
}
public function rowCount(): int {
return $this->_st->rowCount();
}
}
/**
* Represents a table on the database for easy automated access
*/
class Table {
// Column types
const DATA_TYPE_INTEGER = 'integer';
const DATA_TYPE_BOOLEAN = 'boolean';
const DATA_TYPE_DOUBLE = 'double';
const DATA_TYPE_DECIMAL = 'Decimal';
const DATA_TYPE_STRING = 'string';
const DATA_TYPE_DATE = 'Date';
const DATA_TYPE_DATETIME = 'DateTime';
const DATA_TYPE_TIME = 'Time';
const DATA_TYPE_JSON = 'JSON';
const DATA_TYPE_NULL = 'null'; // Rare always null columns
/** Database table schema, may be overridden in sub-class or passed by constructor */
protected $_schema = null;
/** Database table name, may be overridden in sub-class or passed by constructor */
protected $_name = null;
/** Database object instance, passed by constructor */
protected $_db = null;