3 * ADOdb base PDO driver
5 * This file is part of ADOdb, a Database Abstraction Layer library for PHP.
8 * @link https://adodb.org Project's web site and documentation
9 * @link https://github.com/ADOdb/ADOdb Source code and issue tracker
11 * The ADOdb Library is dual-licensed, released under both the BSD 3-Clause
12 * and the GNU Lesser General Public Licence (LGPL) v2.1 or, at your option,
13 * any later version. This means you can use it in proprietary products.
14 * See the LICENSE.md file distributed with this source code for details.
15 * @license BSD-3-Clause
16 * @license LGPL-2.1-or-later
18 * @copyright 2000-2013 John Lim
19 * @copyright 2014 Damien Regad, Mark Newnham and the ADOdb community
22 // security - hide paths
23 if (!defined('ADODB_DIR')) die();
30 /* int as in long (the php native int type).
31 * If you mark a column as an int, PDO expects get_col to return
35 /* get_col ptr should point to start of the string buffer
38 /* get_col: when len is 0 ptr should point to a php_stream *,
39 * otherwise it should behave like a string. Indicate a NULL field
40 * value by setting the ptr to NULL
43 /* get_col: will expect the ptr to point to a new PDOStatement object handle,
44 * but this isn't wired up yet
45 PDO::PARAM_STMT, 4 /* hierarchical result set
47 /* get_col ptr should point to a zend_bool
51 /* magic flag to denote a parameter as being input/output
52 PDO::PARAM_INPUT_OUTPUT = 0x80000000
56 function adodb_pdo_type($t)
59 case 2: return 'VARCHAR';
60 case 3: return 'BLOB';
61 default: return 'NUMERIC';
65 /*----------------------------------------------------------------------------*/
68 class ADODB_pdo
extends ADOConnection
{
69 var $databaseType = "pdo";
70 var $dataProvider = "pdo";
71 var $fmtDate = "'Y-m-d'";
72 var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
73 var $replaceQuote = "''"; // string to use to replace quotes
74 var $hasAffectedRows = true;
75 var $_bindInputArray = true;
77 var $_genSeqSQL = "create table %s (id integer)";
79 var $_autocommit = true;
80 var $_lastAffectedRows = 0;
82 var $_errormsg = false;
83 var $_errorno = false;
90 * Describe parameters passed directly to the PDO driver
92 * @example $db->pdoOptions = [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION];
94 public $pdoParameters = array();
99 $this->fmtDate
= $d->fmtDate
;
100 $this->fmtTimeStamp
= $d->fmtTimeStamp
;
101 $this->replaceQuote
= $d->replaceQuote
;
102 $this->sysDate
= $d->sysDate
;
103 $this->sysTimeStamp
= $d->sysTimeStamp
;
104 $this->random
= $d->random
;
105 $this->concat_operator
= $d->concat_operator
;
106 $this->nameQuote
= $d->nameQuote
;
107 $this->arrayClass
= $d->arrayClass
;
109 $this->hasGenID
= $d->hasGenID
;
110 $this->_genIDSQL
= $d->_genIDSQL
;
111 $this->_genSeqSQL
= $d->_genSeqSQL
;
112 $this->_dropSeqSQL
= $d->_dropSeqSQL
;
119 if (!empty($this->_driver
->_hasdual
)) {
120 $sql = "select $this->sysTimeStamp from dual";
123 $sql = "select $this->sysTimeStamp";
126 $rs = $this->_Execute($sql);
127 if ($rs && !$rs->EOF
) {
128 return $this->UnixTimeStamp(reset($rs->fields
));
134 // returns true or false
135 function _connect($argDSN, $argUsername, $argPassword, $argDatabasename, $persist=false)
137 $at = strpos($argDSN,':');
138 $this->dsnType
= substr($argDSN,0,$at);
140 if ($argDatabasename) {
141 switch($this->dsnType
){
143 $argDSN .= ';database='.$argDatabasename;
152 $argDSN .= ';dbname='.$argDatabasename;
156 * Configure for persistent connection if required,
157 * by adding the the pdo parameter into any provided
161 $this->pdoParameters
[\PDO
::ATTR_PERSISTENT
] = true;
165 $this->_connectionID
= new \
PDO($argDSN, $argUsername, $argPassword, $this->pdoParameters
);
166 } catch (Exception
$e) {
167 $this->_connectionID
= false;
168 $this->_errorno
= -1;
170 $this->_errormsg
= 'Connection attempt failed: '.$e->getMessage();
174 if ($this->_connectionID
) {
175 switch(ADODB_ASSOC_CASE
){
176 case ADODB_ASSOC_CASE_LOWER
:
177 $m = PDO
::CASE_LOWER
;
179 case ADODB_ASSOC_CASE_UPPER
:
180 $m = PDO
::CASE_UPPER
;
183 case ADODB_ASSOC_CASE_NATIVE
:
184 $m = PDO
::CASE_NATURAL
;
188 //$this->_connectionID->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_SILENT );
189 $this->_connectionID
->setAttribute(PDO
::ATTR_CASE
,$m);
191 // Now merge in any provided attributes for PDO
192 foreach ($this->connectionParameters
as $options) {
193 foreach($options as $k=>$v) {
195 ADOconnection
::outp('Setting attribute: ' . $k . ' to ' . $v);
197 $this->_connectionID
->setAttribute($k,$v);
201 $class = 'ADODB_pdo_'.$this->dsnType
;
202 //$this->_connectionID->setAttribute(PDO::ATTR_AUTOCOMMIT,true);
203 switch($this->dsnType
) {
212 include_once(ADODB_DIR
.'/drivers/adodb-pdo_'.$this->dsnType
.'.inc.php');
215 if (class_exists($class)) {
216 $this->_driver
= new $class();
219 $this->_driver
= new ADODB_pdo_base();
222 $this->_driver
->_connectionID
= $this->_connectionID
;
224 $this->_driver
->database
= $this->database
;
227 $this->_driver
= new ADODB_pdo_base();
233 $args = func_get_args();
234 if(method_exists($this->_driver
, 'Concat')) {
235 return call_user_func_array(array($this->_driver
, 'Concat'), $args);
238 return call_user_func_array('parent::Concat', $args);
241 // returns true or false
242 function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
244 return $this->_connect($argDSN, $argUsername, $argPassword, $argDatabasename, true);
247 /*------------------------------------------------------------------------------*/
250 function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
252 $save = $this->_driver
->fetchMode
;
253 $this->_driver
->fetchMode
= $this->fetchMode
;
254 $this->_driver
->debug
= $this->debug
;
255 $ret = $this->_driver
->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
256 $this->_driver
->fetchMode
= $save;
261 function ServerInfo()
263 return $this->_driver
->ServerInfo();
266 function MetaTables($ttype=false,$showSchema=false,$mask=false)
268 return $this->_driver
->MetaTables($ttype,$showSchema,$mask);
271 function MetaColumns($table,$normalize=true)
273 return $this->_driver
->MetaColumns($table,$normalize);
276 public function metaIndexes($table,$normalize=true,$owner=false)
278 if (method_exists($this->_driver
,'metaIndexes'))
279 return $this->_driver
->metaIndexes($table,$normalize,$owner);
283 * Return a list of Primary Keys for a specified table.
285 * @param string $table
286 * @param bool $owner (optional) not used in this driver
288 * @return string[] Array of indexes
290 public function metaPrimaryKeys($table,$owner=false)
292 if (method_exists($this->_driver
,'metaPrimaryKeys'))
293 return $this->_driver
->metaPrimaryKeys($table,$owner);
297 * Returns a list of Foreign Keys for a specified table.
299 * @param string $table
300 * @param bool $owner (optional) not used in this driver
302 * @param bool $associative
304 * @return string[] where keys are tables, and values are foreign keys
306 public function metaForeignKeys($table, $owner=false, $upper=false,$associative=false) {
307 if (method_exists($this->_driver
,'metaForeignKeys'))
308 return $this->_driver
->metaForeignKeys($table,$owner,$upper,$associative);
312 * List procedures or functions in an array.
314 * @param $procedureNamePattern A procedure name pattern; must match the procedure name as it is stored in the database.
315 * @param $catalog A catalog name; must match the catalog name as it is stored in the database.
316 * @param $schemaPattern A schema name pattern.
318 * @return false|array false if not supported, or array of procedures on current database with structure below
320 * [name_of_procedure] => Array(
321 * [type] => PROCEDURE or FUNCTION
322 * [catalog] => Catalog_name
323 * [schema] => Schema_name
324 * [remarks] => explanatory comment on the procedure
328 public function metaProcedures($procedureNamePattern = null, $catalog = null, $schemaPattern = null) {
329 if (method_exists($this->_driver
,'metaProcedures'))
330 return $this->_driver
->metaProcedures($procedureNamePattern,$catalog,$schemaPattern);
334 function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
338 $obj->bindParam($name, $var, $type, $maxLen);
341 $obj->bindParam($name, $var);
345 function OffsetDate($dayFraction,$date=false)
347 return $this->_driver
->OffsetDate($dayFraction,$date);
350 function SelectDB($dbName)
352 return $this->_driver
->SelectDB($dbName);
355 function SQLDate($fmt, $col=false)
357 return $this->_driver
->SQLDate($fmt, $col);
362 if ($this->_errormsg
!== false) {
363 return $this->_errormsg
;
365 if (!empty($this->_stmt
)) {
366 $arr = $this->_stmt
->errorInfo();
368 else if (!empty($this->_connectionID
)) {
369 $arr = $this->_connectionID
->errorInfo();
372 return 'No Connection Established';
376 if (sizeof($arr)<2) {
379 if ((integer)$arr[0]) {
394 if ($this->_errorno
!== false) {
395 return $this->_errorno
;
397 if (!empty($this->_stmt
)) {
398 $err = $this->_stmt
->errorCode();
400 else if (!empty($this->_connectionID
)) {
401 $arr = $this->_connectionID
->errorInfo();
402 if (isset($arr[0])) {
412 if ($err == '00000') {
413 return 0; // allows empty check
419 * @param bool $auto_commit
422 function SetAutoCommit($auto_commit)
424 if(method_exists($this->_driver
, 'SetAutoCommit')) {
425 $this->_driver
->SetAutoCommit($auto_commit);
429 function SetTransactionMode($transaction_mode)
431 if(method_exists($this->_driver
, 'SetTransactionMode')) {
432 return $this->_driver
->SetTransactionMode($transaction_mode);
435 return parent
::SetTransactionMode($transaction_mode);
438 function beginTrans()
440 if(method_exists($this->_driver
, 'beginTrans')) {
441 return $this->_driver
->beginTrans();
444 if (!$this->hasTransactions
) {
447 if ($this->transOff
) {
450 $this->transCnt +
= 1;
451 $this->_autocommit
= false;
452 $this->SetAutoCommit(false);
454 return $this->_connectionID
->beginTransaction();
457 function commitTrans($ok=true)
460 if(method_exists($this->_driver
, 'commitTrans')) {
461 return $this->_driver
->commitTrans($ok);
464 if (!$this->hasTransactions
) {
467 if ($this->transOff
) {
471 return $this->rollbackTrans();
473 if ($this->transCnt
) {
474 $this->transCnt
-= 1;
476 $this->_autocommit
= true;
478 $ret = $this->_connectionID
->commit();
479 $this->SetAutoCommit(true);
483 function RollbackTrans()
485 if(method_exists($this->_driver
, 'RollbackTrans')) {
486 return $this->_driver
->RollbackTrans();
489 if (!$this->hasTransactions
) {
492 if ($this->transOff
) {
495 if ($this->transCnt
) {
496 $this->transCnt
-= 1;
498 $this->_autocommit
= true;
500 $ret = $this->_connectionID
->rollback();
501 $this->SetAutoCommit(true);
505 function Prepare($sql)
507 $this->_stmt
= $this->_connectionID
->prepare($sql);
509 return array($sql,$this->_stmt
);
515 function PrepareStmt($sql)
517 $stmt = $this->_connectionID
->prepare($sql);
521 $obj = new ADOPDOStatement($stmt,$this);
525 public function createSequence($seqname='adodbseq',$startID=1)
527 if(method_exists($this->_driver
, 'createSequence')) {
528 return $this->_driver
->createSequence($seqname, $startID);
531 return parent
::CreateSequence($seqname, $startID);
534 function DropSequence($seqname='adodbseq')
536 if(method_exists($this->_driver
, 'DropSequence')) {
537 return $this->_driver
->DropSequence($seqname);
540 return parent
::DropSequence($seqname);
543 function GenID($seqname='adodbseq',$startID=1)
545 if(method_exists($this->_driver
, 'GenID')) {
546 return $this->_driver
->GenID($seqname, $startID);
549 return parent
::GenID($seqname, $startID);
553 /* returns queryID or false */
554 function _query($sql,$inputarr=false)
557 if (is_array($sql)) {
560 $stmt = $this->_connectionID
->prepare($sql);
564 if ($this->_driver
instanceof ADODB_pdo
) {
565 $this->_driver
->debug
= $this->debug
;
569 * inputarr must be numeric
571 $inputarr = array_values($inputarr);
572 $ok = $stmt->execute($inputarr);
575 $ok = $stmt->execute();
580 $this->_errormsg
= false;
581 $this->_errorno
= false;
584 $this->_stmt
= $stmt;
590 $arr = $stmt->errorinfo();
591 if ((integer)$arr[1]) {
592 $this->_errormsg
= $arr[2];
593 $this->_errorno
= $arr[1];
597 $this->_errormsg
= false;
598 $this->_errorno
= false;
603 // returns true or false
606 $this->_stmt
= false;
610 function _affectedrows()
612 return ($this->_stmt
) ?
$this->_stmt
->rowCount() : 0;
615 protected function _insertID($table = '', $column = '')
617 return ($this->_connectionID
) ?
$this->_connectionID
->lastInsertId() : 0;
621 * Quotes a string to be sent to the database.
623 * If we have an active connection, delegates quoting to the underlying
624 * PDO object PDO::quote(). Otherwise, replace "'" by the value of
625 * $replaceQuote (same behavior as mysqli driver).
627 * @param string $s The string to quote
628 * @param bool $magic_quotes This param is not used since 5.21.0.
629 * It remains for backwards compatibility.
631 * @return string Quoted string
633 function qStr($s, $magic_quotes = false)
635 if ($this->_connectionID
) {
636 return $this->_connectionID
->quote($s);
638 return "'" . str_replace("'", $this->replaceQuote
, $s) . "'";
643 class ADODB_pdo_base
extends ADODB_pdo
{
645 var $sysDate = "'?'";
646 var $sysTimeStamp = "'?'";
649 function _init($parentDriver)
651 $parentDriver->_bindInputArray
= true;
652 #$parentDriver->_connectionID->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);
655 function ServerInfo()
657 return ADOConnection
::ServerInfo();
660 function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
662 $ret = ADOConnection
::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
666 function MetaTables($ttype=false,$showSchema=false,$mask=false)
671 function MetaColumns($table,$normalize=true)
677 class ADOPDOStatement
{
679 var $databaseType = "pdo";
680 var $dataProvider = "pdo";
684 function __construct($stmt,$connection)
686 $this->_stmt
= $stmt;
687 $this->_connectionID
= $connection;
690 function Execute($inputArr=false)
692 $savestmt = $this->_connectionID
->_stmt
;
693 $rs = $this->_connectionID
->Execute(array(false,$this->_stmt
),$inputArr);
694 $this->_connectionID
->_stmt
= $savestmt;
698 function InParameter(&$var,$name,$maxLen=4000,$type=false)
702 $this->_stmt
->bindParam($name,$var,$type,$maxLen);
705 $this->_stmt
->bindParam($name, $var);
709 function Affected_Rows()
711 return ($this->_stmt
) ?
$this->_stmt
->rowCount() : 0;
717 $arr = $this->_stmt
->errorInfo();
720 $arr = $this->_connectionID
->errorInfo();
723 if (is_array($arr)) {
724 if ((integer) $arr[0] && isset($arr[2])) {
737 return ($this->_stmt
) ?
$this->_stmt
->columnCount() : 0;
743 return $this->_stmt
->errorCode();
746 return $this->_connectionID
->errorInfo();
751 /*--------------------------------------------------------------------------------------
752 Class Name: Recordset
753 --------------------------------------------------------------------------------------*/
755 class ADORecordSet_pdo
extends ADORecordSet
{
758 var $databaseType = "pdo";
759 var $dataProvider = "pdo";
761 function __construct($id,$mode=false)
763 if ($mode === false) {
764 global $ADODB_FETCH_MODE;
765 $mode = $ADODB_FETCH_MODE;
767 $this->adodbFetchMode
= $mode;
769 case ADODB_FETCH_NUM
: $mode = PDO
::FETCH_NUM
; break;
770 case ADODB_FETCH_ASSOC
: $mode = PDO
::FETCH_ASSOC
; break;
772 case ADODB_FETCH_BOTH
:
773 default: $mode = PDO
::FETCH_BOTH
; break;
775 $this->fetchMode
= $mode;
777 $this->_queryID
= $id;
778 parent
::__construct($id);
784 if ($this->_inited
) {
787 $this->_inited
= true;
788 if ($this->_queryID
) {
792 $this->_numOfRows
= 0;
793 $this->_numOfFields
= 0;
795 if ($this->_numOfRows
!= 0 && $this->_currentRow
== -1) {
796 $this->_currentRow
= 0;
797 if ($this->EOF
= ($this->_fetch() === false)) {
798 $this->_numOfRows
= 0; // _numOfRows could be -1
807 global $ADODB_COUNTRECS;
809 $this->_numOfRows
= ($ADODB_COUNTRECS) ?
@$this->_queryID
->rowCount() : -1;
810 if (!$this->_numOfRows
) {
811 $this->_numOfRows
= -1;
813 $this->_numOfFields
= $this->_queryID
->columnCount();
816 // returns the field object
817 function FetchField($fieldOffset = -1)
819 $off=$fieldOffset+
1; // offsets begin at 1
821 $o= new ADOFieldObject();
822 $arr = @$this->_queryID
->getColumnMeta($fieldOffset);
824 $o->name
= 'bad getColumnMeta()';
826 $o->type
= 'VARCHAR';
832 $o->name
= $arr['name'];
833 if (isset($arr['sqlsrv:decl_type']) && $arr['sqlsrv:decl_type'] <> "null")
836 * If the database is SQL server, use the native built-ins
838 $o->type
= $arr['sqlsrv:decl_type'];
840 elseif (isset($arr['native_type']) && $arr['native_type'] <> "null")
842 $o->type
= $arr['native_type'];
846 $o->type
= adodb_pdo_type($arr['pdo_type']);
849 $o->max_length
= $arr['len'];
850 $o->precision
= $arr['precision'];
852 switch(ADODB_ASSOC_CASE
) {
853 case ADODB_ASSOC_CASE_LOWER
:
854 $o->name
= strtolower($o->name
);
856 case ADODB_ASSOC_CASE_UPPER
:
857 $o->name
= strtoupper($o->name
);
870 if (!$this->_queryID
) {
874 $this->fields
= $this->_queryID
->fetch($this->fetchMode
);
875 return !empty($this->fields
);
880 $this->_queryID
= false;
883 function Fields($colname)
885 if ($this->adodbFetchMode
!= ADODB_FETCH_NUM
) {
886 return @$this->fields
[$colname];
890 $this->bind
= array();
891 for ($i=0; $i < $this->_numOfFields
; $i++
) {
892 $o = $this->FetchField($i);
893 $this->bind
[strtoupper($o->name
)] = $i;
896 return $this->fields
[$this->bind
[strtoupper($colname)]];
901 class ADORecordSet_array_pdo
extends ADORecordSet_array
{}