Automatically generated installer lang files
[moodle.git] / lib / adodb / drivers / adodb-pdo.inc.php
blobcf8e4e2644b18779ee942640def1ac2f5885334f
1 <?php
2 /**
3 * ADOdb base PDO driver
5 * This file is part of ADOdb, a Database Abstraction Layer library for PHP.
7 * @package ADOdb
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();
27 enum pdo_param_type {
28 PDO::PARAM_NULL, 0
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
32 * a pointer to a long
33 PDO::PARAM_INT, 1
35 /* get_col ptr should point to start of the string buffer
36 PDO::PARAM_STR, 2
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
41 PDO::PARAM_LOB, 3
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
48 PDO::PARAM_BOOL, 5
51 /* magic flag to denote a parameter as being input/output
52 PDO::PARAM_INPUT_OUTPUT = 0x80000000
56 function adodb_pdo_type($t)
58 switch($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;
76 var $_genIDSQL;
77 var $_genSeqSQL = "create table %s (id integer)";
78 var $_dropSeqSQL;
79 var $_autocommit = true;
80 var $_lastAffectedRows = 0;
82 var $_errormsg = false;
83 var $_errorno = false;
85 var $dsnType = '';
86 var $stmt = false;
87 var $_driver;
90 * Describe parameters passed directly to the PDO driver
92 * @example $db->pdoOptions = [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION];
94 public $pdoParameters = array();
96 function _UpdatePDO()
98 $d = $this->_driver;
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;
114 $d->_init($this);
117 function Time()
119 if (!empty($this->_driver->_hasdual)) {
120 $sql = "select $this->sysTimeStamp from dual";
122 else {
123 $sql = "select $this->sysTimeStamp";
126 $rs = $this->_Execute($sql);
127 if ($rs && !$rs->EOF) {
128 return $this->UnixTimeStamp(reset($rs->fields));
131 return false;
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){
142 case 'sqlsrv':
143 $argDSN .= ';database='.$argDatabasename;
144 break;
145 case 'mssql':
146 case 'mysql':
147 case 'oci':
148 case 'pgsql':
149 case 'sqlite':
150 case 'firebird':
151 default:
152 $argDSN .= ';dbname='.$argDatabasename;
156 * Configure for persistent connection if required,
157 * by adding the the pdo parameter into any provided
158 * ones
160 if ($persist) {
161 $this->pdoParameters[\PDO::ATTR_PERSISTENT] = true;
164 try {
165 $this->_connectionID = new \PDO($argDSN, $argUsername, $argPassword, $this->pdoParameters);
166 } catch (Exception $e) {
167 $this->_connectionID = false;
168 $this->_errorno = -1;
169 //var_dump($e);
170 $this->_errormsg = 'Connection attempt failed: '.$e->getMessage();
171 return false;
174 if ($this->_connectionID) {
175 switch(ADODB_ASSOC_CASE){
176 case ADODB_ASSOC_CASE_LOWER:
177 $m = PDO::CASE_LOWER;
178 break;
179 case ADODB_ASSOC_CASE_UPPER:
180 $m = PDO::CASE_UPPER;
181 break;
182 default:
183 case ADODB_ASSOC_CASE_NATIVE:
184 $m = PDO::CASE_NATURAL;
185 break;
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) {
194 if ($this->debug) {
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) {
204 case 'mssql':
205 case 'mysql':
206 case 'oci':
207 case 'pgsql':
208 case 'sqlite':
209 case 'sqlsrv':
210 case 'firebird':
211 case 'dblib':
212 include_once(ADODB_DIR.'/drivers/adodb-pdo_'.$this->dsnType.'.inc.php');
213 break;
215 if (class_exists($class)) {
216 $this->_driver = new $class();
218 else {
219 $this->_driver = new ADODB_pdo_base();
222 $this->_driver->_connectionID = $this->_connectionID;
223 $this->_UpdatePDO();
224 $this->_driver->database = $this->database;
225 return true;
227 $this->_driver = new ADODB_pdo_base();
228 return false;
231 function Concat()
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;
257 return $ret;
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
301 * @param bool $upper
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
319 * Array(
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);
331 return false;
334 function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
336 $obj = $stmt[1];
337 if ($type) {
338 $obj->bindParam($name, $var, $type, $maxLen);
340 else {
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);
360 function ErrorMsg()
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();
371 else {
372 return 'No Connection Established';
375 if ($arr) {
376 if (sizeof($arr)<2) {
377 return '';
379 if ((integer)$arr[0]) {
380 return $arr[2];
382 else {
383 return '';
386 else {
387 return '-1';
392 function ErrorNo()
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])) {
403 $err = $arr[0];
405 else {
406 $err = -1;
408 } else {
409 return 0;
412 if ($err == '00000') {
413 return 0; // allows empty check
415 return $err;
419 * @param bool $auto_commit
420 * @return void
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) {
445 return false;
447 if ($this->transOff) {
448 return true;
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) {
465 return false;
467 if ($this->transOff) {
468 return true;
470 if (!$ok) {
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);
480 return $ret;
483 function RollbackTrans()
485 if(method_exists($this->_driver, 'RollbackTrans')) {
486 return $this->_driver->RollbackTrans();
489 if (!$this->hasTransactions) {
490 return false;
492 if ($this->transOff) {
493 return true;
495 if ($this->transCnt) {
496 $this->transCnt -= 1;
498 $this->_autocommit = true;
500 $ret = $this->_connectionID->rollback();
501 $this->SetAutoCommit(true);
502 return $ret;
505 function Prepare($sql)
507 $this->_stmt = $this->_connectionID->prepare($sql);
508 if ($this->_stmt) {
509 return array($sql,$this->_stmt);
512 return false;
515 function PrepareStmt($sql)
517 $stmt = $this->_connectionID->prepare($sql);
518 if (!$stmt) {
519 return false;
521 $obj = new ADOPDOStatement($stmt,$this);
522 return $obj;
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)
556 $ok = false;
557 if (is_array($sql)) {
558 $stmt = $sql[1];
559 } else {
560 $stmt = $this->_connectionID->prepare($sql);
563 if ($stmt) {
564 if ($this->_driver instanceof ADODB_pdo) {
565 $this->_driver->debug = $this->debug;
567 if ($inputarr) {
569 * inputarr must be numeric
571 $inputarr = array_values($inputarr);
572 $ok = $stmt->execute($inputarr);
574 else {
575 $ok = $stmt->execute();
580 $this->_errormsg = false;
581 $this->_errorno = false;
583 if ($ok) {
584 $this->_stmt = $stmt;
585 return $stmt;
588 if ($stmt) {
590 $arr = $stmt->errorinfo();
591 if ((integer)$arr[1]) {
592 $this->_errormsg = $arr[2];
593 $this->_errorno = $arr[1];
596 } else {
597 $this->_errormsg = false;
598 $this->_errorno = false;
600 return false;
603 // returns true or false
604 function _close()
606 $this->_stmt = false;
607 return true;
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);
663 return $ret;
666 function MetaTables($ttype=false,$showSchema=false,$mask=false)
668 return false;
671 function MetaColumns($table,$normalize=true)
673 return false;
677 class ADOPDOStatement {
679 var $databaseType = "pdo";
680 var $dataProvider = "pdo";
681 var $_stmt;
682 var $_connectionID;
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;
695 return $rs;
698 function InParameter(&$var,$name,$maxLen=4000,$type=false)
701 if ($type) {
702 $this->_stmt->bindParam($name,$var,$type,$maxLen);
704 else {
705 $this->_stmt->bindParam($name, $var);
709 function Affected_Rows()
711 return ($this->_stmt) ? $this->_stmt->rowCount() : 0;
714 function ErrorMsg()
716 if ($this->_stmt) {
717 $arr = $this->_stmt->errorInfo();
719 else {
720 $arr = $this->_connectionID->errorInfo();
723 if (is_array($arr)) {
724 if ((integer) $arr[0] && isset($arr[2])) {
725 return $arr[2];
727 else {
728 return '';
730 } else {
731 return '-1';
735 function NumCols()
737 return ($this->_stmt) ? $this->_stmt->columnCount() : 0;
740 function ErrorNo()
742 if ($this->_stmt) {
743 return $this->_stmt->errorCode();
745 else {
746 return $this->_connectionID->errorInfo();
751 /*--------------------------------------------------------------------------------------
752 Class Name: Recordset
753 --------------------------------------------------------------------------------------*/
755 class ADORecordSet_pdo extends ADORecordSet {
757 var $bind = false;
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;
768 switch($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);
782 function Init()
784 if ($this->_inited) {
785 return;
787 $this->_inited = true;
788 if ($this->_queryID) {
789 @$this->_initrs();
791 else {
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
800 } else {
801 $this->EOF = true;
805 function _initrs()
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);
823 if (!$arr) {
824 $o->name = 'bad getColumnMeta()';
825 $o->max_length = -1;
826 $o->type = 'VARCHAR';
827 $o->precision = 0;
828 # $false = false;
829 return $o;
831 //adodb_pr($arr);
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'];
844 else
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);
855 break;
856 case ADODB_ASSOC_CASE_UPPER:
857 $o->name = strtoupper($o->name);
858 break;
860 return $o;
863 function _seek($row)
865 return false;
868 function _fetch()
870 if (!$this->_queryID) {
871 return false;
874 $this->fields = $this->_queryID->fetch($this->fetchMode);
875 return !empty($this->fields);
878 function _close()
880 $this->_queryID = false;
883 function Fields($colname)
885 if ($this->adodbFetchMode != ADODB_FETCH_NUM) {
886 return @$this->fields[$colname];
889 if (!$this->bind) {
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 {}