mysql.php 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700
  1. <?php
  2. // vim: set et ts=4 sw=4 fdm=marker:
  3. // +----------------------------------------------------------------------+
  4. // | PHP versions 4 and 5 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
  7. // | Stig. S. Bakken, Lukas Smith |
  8. // | All rights reserved. |
  9. // +----------------------------------------------------------------------+
  10. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
  11. // | API as well as database abstraction for PHP applications. |
  12. // | This LICENSE is in the BSD license style. |
  13. // | |
  14. // | Redistribution and use in source and binary forms, with or without |
  15. // | modification, are permitted provided that the following conditions |
  16. // | are met: |
  17. // | |
  18. // | Redistributions of source code must retain the above copyright |
  19. // | notice, this list of conditions and the following disclaimer. |
  20. // | |
  21. // | Redistributions in binary form must reproduce the above copyright |
  22. // | notice, this list of conditions and the following disclaimer in the |
  23. // | documentation and/or other materials provided with the distribution. |
  24. // | |
  25. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
  26. // | Lukas Smith nor the names of his contributors may be used to endorse |
  27. // | or promote products derived from this software without specific prior|
  28. // | written permission. |
  29. // | |
  30. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
  31. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
  32. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
  33. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
  34. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
  35. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  36. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  37. // | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
  38. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
  39. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  40. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
  41. // | POSSIBILITY OF SUCH DAMAGE. |
  42. // +----------------------------------------------------------------------+
  43. // | Author: Lukas Smith <smith@pooteeweet.org> |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id: mysql.php,v 1.214 2008/11/16 21:45:08 quipo Exp $
  47. //
  48. /**
  49. * MDB2 MySQL driver
  50. *
  51. * @package MDB2
  52. * @category Database
  53. * @author Lukas Smith <smith@pooteeweet.org>
  54. */
  55. class MDB2_Driver_mysql extends MDB2_Driver_Common
  56. {
  57. // {{{ properties
  58. var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => '\\', 'escape_pattern' => '\\');
  59. var $identifier_quoting = array('start' => '`', 'end' => '`', 'escape' => '`');
  60. var $sql_comments = array(
  61. array('start' => '-- ', 'end' => "\n", 'escape' => false),
  62. array('start' => '#', 'end' => "\n", 'escape' => false),
  63. array('start' => '/*', 'end' => '*/', 'escape' => false),
  64. );
  65. var $server_capabilities_checked = false;
  66. var $start_transaction = false;
  67. var $varchar_max_length = 255;
  68. // }}}
  69. // {{{ constructor
  70. /**
  71. * Constructor
  72. */
  73. function __construct()
  74. {
  75. parent::__construct();
  76. $this->phptype = 'mysql';
  77. $this->dbsyntax = 'mysql';
  78. $this->supported['sequences'] = 'emulated';
  79. $this->supported['indexes'] = true;
  80. $this->supported['affected_rows'] = true;
  81. $this->supported['transactions'] = false;
  82. $this->supported['savepoints'] = false;
  83. $this->supported['summary_functions'] = true;
  84. $this->supported['order_by_text'] = true;
  85. $this->supported['current_id'] = 'emulated';
  86. $this->supported['limit_queries'] = true;
  87. $this->supported['LOBs'] = true;
  88. $this->supported['replace'] = true;
  89. $this->supported['sub_selects'] = 'emulated';
  90. $this->supported['triggers'] = false;
  91. $this->supported['auto_increment'] = true;
  92. $this->supported['primary_key'] = true;
  93. $this->supported['result_introspection'] = true;
  94. $this->supported['prepared_statements'] = 'emulated';
  95. $this->supported['identifier_quoting'] = true;
  96. $this->supported['pattern_escaping'] = true;
  97. $this->supported['new_link'] = true;
  98. $this->options['DBA_username'] = false;
  99. $this->options['DBA_password'] = false;
  100. $this->options['default_table_type'] = '';
  101. $this->options['max_identifiers_length'] = 64;
  102. $this->_reCheckSupportedOptions();
  103. }
  104. // }}}
  105. // {{{ _reCheckSupportedOptions()
  106. /**
  107. * If the user changes certain options, other capabilities may depend
  108. * on the new settings, so we need to check them (again).
  109. *
  110. * @access private
  111. */
  112. function _reCheckSupportedOptions()
  113. {
  114. $this->supported['transactions'] = $this->options['use_transactions'];
  115. $this->supported['savepoints'] = $this->options['use_transactions'];
  116. if ($this->options['default_table_type']) {
  117. switch (strtoupper($this->options['default_table_type'])) {
  118. case 'BLACKHOLE':
  119. case 'MEMORY':
  120. case 'ARCHIVE':
  121. case 'CSV':
  122. case 'HEAP':
  123. case 'ISAM':
  124. case 'MERGE':
  125. case 'MRG_ISAM':
  126. case 'ISAM':
  127. case 'MRG_MYISAM':
  128. case 'MYISAM':
  129. $this->supported['savepoints'] = false;
  130. $this->supported['transactions'] = false;
  131. $this->warnings[] = $this->options['default_table_type'] .
  132. ' is not a supported default table type';
  133. break;
  134. }
  135. }
  136. }
  137. // }}}
  138. // {{{ function setOption($option, $value)
  139. /**
  140. * set the option for the db class
  141. *
  142. * @param string option name
  143. * @param mixed value for the option
  144. *
  145. * @return mixed MDB2_OK or MDB2 Error Object
  146. *
  147. * @access public
  148. */
  149. function setOption($option, $value)
  150. {
  151. $res = parent::setOption($option, $value);
  152. $this->_reCheckSupportedOptions();
  153. }
  154. // }}}
  155. // {{{ errorInfo()
  156. /**
  157. * This method is used to collect information about an error
  158. *
  159. * @param integer $error
  160. * @return array
  161. * @access public
  162. */
  163. function errorInfo($error = null)
  164. {
  165. if ($this->connection) {
  166. $native_code = @mysql_errno($this->connection);
  167. $native_msg = @mysql_error($this->connection);
  168. } else {
  169. $native_code = @mysql_errno();
  170. $native_msg = @mysql_error();
  171. }
  172. if (is_null($error)) {
  173. static $ecode_map;
  174. if (empty($ecode_map)) {
  175. $ecode_map = array(
  176. 1000 => MDB2_ERROR_INVALID, //hashchk
  177. 1001 => MDB2_ERROR_INVALID, //isamchk
  178. 1004 => MDB2_ERROR_CANNOT_CREATE,
  179. 1005 => MDB2_ERROR_CANNOT_CREATE,
  180. 1006 => MDB2_ERROR_CANNOT_CREATE,
  181. 1007 => MDB2_ERROR_ALREADY_EXISTS,
  182. 1008 => MDB2_ERROR_CANNOT_DROP,
  183. 1009 => MDB2_ERROR_CANNOT_DROP,
  184. 1010 => MDB2_ERROR_CANNOT_DROP,
  185. 1011 => MDB2_ERROR_CANNOT_DELETE,
  186. 1022 => MDB2_ERROR_ALREADY_EXISTS,
  187. 1029 => MDB2_ERROR_NOT_FOUND,
  188. 1032 => MDB2_ERROR_NOT_FOUND,
  189. 1044 => MDB2_ERROR_ACCESS_VIOLATION,
  190. 1045 => MDB2_ERROR_ACCESS_VIOLATION,
  191. 1046 => MDB2_ERROR_NODBSELECTED,
  192. 1048 => MDB2_ERROR_CONSTRAINT,
  193. 1049 => MDB2_ERROR_NOSUCHDB,
  194. 1050 => MDB2_ERROR_ALREADY_EXISTS,
  195. 1051 => MDB2_ERROR_NOSUCHTABLE,
  196. 1054 => MDB2_ERROR_NOSUCHFIELD,
  197. 1060 => MDB2_ERROR_ALREADY_EXISTS,
  198. 1061 => MDB2_ERROR_ALREADY_EXISTS,
  199. 1062 => MDB2_ERROR_ALREADY_EXISTS,
  200. 1064 => MDB2_ERROR_SYNTAX,
  201. 1067 => MDB2_ERROR_INVALID,
  202. 1072 => MDB2_ERROR_NOT_FOUND,
  203. 1086 => MDB2_ERROR_ALREADY_EXISTS,
  204. 1091 => MDB2_ERROR_NOT_FOUND,
  205. 1100 => MDB2_ERROR_NOT_LOCKED,
  206. 1109 => MDB2_ERROR_NOT_FOUND,
  207. 1125 => MDB2_ERROR_ALREADY_EXISTS,
  208. 1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  209. 1138 => MDB2_ERROR_INVALID,
  210. 1142 => MDB2_ERROR_ACCESS_VIOLATION,
  211. 1143 => MDB2_ERROR_ACCESS_VIOLATION,
  212. 1146 => MDB2_ERROR_NOSUCHTABLE,
  213. 1149 => MDB2_ERROR_SYNTAX,
  214. 1169 => MDB2_ERROR_CONSTRAINT,
  215. 1176 => MDB2_ERROR_NOT_FOUND,
  216. 1177 => MDB2_ERROR_NOSUCHTABLE,
  217. 1213 => MDB2_ERROR_DEADLOCK,
  218. 1216 => MDB2_ERROR_CONSTRAINT,
  219. 1217 => MDB2_ERROR_CONSTRAINT,
  220. 1227 => MDB2_ERROR_ACCESS_VIOLATION,
  221. 1235 => MDB2_ERROR_CANNOT_CREATE,
  222. 1299 => MDB2_ERROR_INVALID_DATE,
  223. 1300 => MDB2_ERROR_INVALID,
  224. 1304 => MDB2_ERROR_ALREADY_EXISTS,
  225. 1305 => MDB2_ERROR_NOT_FOUND,
  226. 1306 => MDB2_ERROR_CANNOT_DROP,
  227. 1307 => MDB2_ERROR_CANNOT_CREATE,
  228. 1334 => MDB2_ERROR_CANNOT_ALTER,
  229. 1339 => MDB2_ERROR_NOT_FOUND,
  230. 1356 => MDB2_ERROR_INVALID,
  231. 1359 => MDB2_ERROR_ALREADY_EXISTS,
  232. 1360 => MDB2_ERROR_NOT_FOUND,
  233. 1363 => MDB2_ERROR_NOT_FOUND,
  234. 1365 => MDB2_ERROR_DIVZERO,
  235. 1451 => MDB2_ERROR_CONSTRAINT,
  236. 1452 => MDB2_ERROR_CONSTRAINT,
  237. 1542 => MDB2_ERROR_CANNOT_DROP,
  238. 1546 => MDB2_ERROR_CONSTRAINT,
  239. 1582 => MDB2_ERROR_CONSTRAINT,
  240. 2003 => MDB2_ERROR_CONNECT_FAILED,
  241. 2019 => MDB2_ERROR_INVALID,
  242. );
  243. }
  244. if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) {
  245. $ecode_map[1022] = MDB2_ERROR_CONSTRAINT;
  246. $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL;
  247. $ecode_map[1062] = MDB2_ERROR_CONSTRAINT;
  248. } else {
  249. // Doing this in case mode changes during runtime.
  250. $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS;
  251. $ecode_map[1048] = MDB2_ERROR_CONSTRAINT;
  252. $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS;
  253. }
  254. if (isset($ecode_map[$native_code])) {
  255. $error = $ecode_map[$native_code];
  256. }
  257. }
  258. return array($error, $native_code, $native_msg);
  259. }
  260. // }}}
  261. // {{{ escape()
  262. /**
  263. * Quotes a string so it can be safely used in a query. It will quote
  264. * the text so it can safely be used within a query.
  265. *
  266. * @param string the input string to quote
  267. * @param bool escape wildcards
  268. *
  269. * @return string quoted string
  270. *
  271. * @access public
  272. */
  273. function escape($text, $escape_wildcards = false)
  274. {
  275. if ($escape_wildcards) {
  276. $text = $this->escapePattern($text);
  277. }
  278. $connection = $this->getConnection();
  279. if (PEAR::isError($connection)) {
  280. return $connection;
  281. }
  282. $text = @mysql_real_escape_string($text, $connection);
  283. return $text;
  284. }
  285. // }}}
  286. // {{{ beginTransaction()
  287. /**
  288. * Start a transaction or set a savepoint.
  289. *
  290. * @param string name of a savepoint to set
  291. * @return mixed MDB2_OK on success, a MDB2 error on failure
  292. *
  293. * @access public
  294. */
  295. function beginTransaction($savepoint = null)
  296. {
  297. $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  298. $this->_getServerCapabilities();
  299. if (!is_null($savepoint)) {
  300. if (!$this->supports('savepoints')) {
  301. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  302. 'savepoints are not supported', __FUNCTION__);
  303. }
  304. if (!$this->in_transaction) {
  305. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  306. 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
  307. }
  308. $query = 'SAVEPOINT '.$savepoint;
  309. return $this->_doQuery($query, true);
  310. } elseif ($this->in_transaction) {
  311. return MDB2_OK; //nothing to do
  312. }
  313. if (!$this->destructor_registered && $this->opened_persistent) {
  314. $this->destructor_registered = true;
  315. register_shutdown_function('MDB2_closeOpenTransactions');
  316. }
  317. $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 0';
  318. $result =& $this->_doQuery($query, true);
  319. if (PEAR::isError($result)) {
  320. return $result;
  321. }
  322. $this->in_transaction = true;
  323. return MDB2_OK;
  324. }
  325. // }}}
  326. // {{{ commit()
  327. /**
  328. * Commit the database changes done during a transaction that is in
  329. * progress or release a savepoint. This function may only be called when
  330. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  331. * transaction is implicitly started after committing the pending changes.
  332. *
  333. * @param string name of a savepoint to release
  334. * @return mixed MDB2_OK on success, a MDB2 error on failure
  335. *
  336. * @access public
  337. */
  338. function commit($savepoint = null)
  339. {
  340. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  341. if (!$this->in_transaction) {
  342. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  343. 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
  344. }
  345. if (!is_null($savepoint)) {
  346. if (!$this->supports('savepoints')) {
  347. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  348. 'savepoints are not supported', __FUNCTION__);
  349. }
  350. $server_info = $this->getServerVersion();
  351. if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
  352. return MDB2_OK;
  353. }
  354. $query = 'RELEASE SAVEPOINT '.$savepoint;
  355. return $this->_doQuery($query, true);
  356. }
  357. if (!$this->supports('transactions')) {
  358. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  359. 'transactions are not supported', __FUNCTION__);
  360. }
  361. $result =& $this->_doQuery('COMMIT', true);
  362. if (PEAR::isError($result)) {
  363. return $result;
  364. }
  365. if (!$this->start_transaction) {
  366. $query = 'SET AUTOCOMMIT = 1';
  367. $result =& $this->_doQuery($query, true);
  368. if (PEAR::isError($result)) {
  369. return $result;
  370. }
  371. }
  372. $this->in_transaction = false;
  373. return MDB2_OK;
  374. }
  375. // }}}
  376. // {{{ rollback()
  377. /**
  378. * Cancel any database changes done during a transaction or since a specific
  379. * savepoint that is in progress. This function may only be called when
  380. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  381. * transaction is implicitly started after canceling the pending changes.
  382. *
  383. * @param string name of a savepoint to rollback to
  384. * @return mixed MDB2_OK on success, a MDB2 error on failure
  385. *
  386. * @access public
  387. */
  388. function rollback($savepoint = null)
  389. {
  390. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  391. if (!$this->in_transaction) {
  392. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  393. 'rollback cannot be done changes are auto committed', __FUNCTION__);
  394. }
  395. if (!is_null($savepoint)) {
  396. if (!$this->supports('savepoints')) {
  397. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  398. 'savepoints are not supported', __FUNCTION__);
  399. }
  400. $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
  401. return $this->_doQuery($query, true);
  402. }
  403. $query = 'ROLLBACK';
  404. $result =& $this->_doQuery($query, true);
  405. if (PEAR::isError($result)) {
  406. return $result;
  407. }
  408. if (!$this->start_transaction) {
  409. $query = 'SET AUTOCOMMIT = 1';
  410. $result =& $this->_doQuery($query, true);
  411. if (PEAR::isError($result)) {
  412. return $result;
  413. }
  414. }
  415. $this->in_transaction = false;
  416. return MDB2_OK;
  417. }
  418. // }}}
  419. // {{{ function setTransactionIsolation()
  420. /**
  421. * Set the transacton isolation level.
  422. *
  423. * @param string standard isolation level
  424. * READ UNCOMMITTED (allows dirty reads)
  425. * READ COMMITTED (prevents dirty reads)
  426. * REPEATABLE READ (prevents nonrepeatable reads)
  427. * SERIALIZABLE (prevents phantom reads)
  428. * @return mixed MDB2_OK on success, a MDB2 error on failure
  429. *
  430. * @access public
  431. * @since 2.1.1
  432. */
  433. static function setTransactionIsolation($isolation, $options = array())
  434. {
  435. $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  436. if (!$this->supports('transactions')) {
  437. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  438. 'transactions are not supported', __FUNCTION__);
  439. }
  440. switch ($isolation) {
  441. case 'READ UNCOMMITTED':
  442. case 'READ COMMITTED':
  443. case 'REPEATABLE READ':
  444. case 'SERIALIZABLE':
  445. break;
  446. default:
  447. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  448. 'isolation level is not supported: '.$isolation, __FUNCTION__);
  449. }
  450. $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
  451. return $this->_doQuery($query, true);
  452. }
  453. // }}}
  454. // {{{ _doConnect()
  455. /**
  456. * do the grunt work of the connect
  457. *
  458. * @return connection on success or MDB2 Error Object on failure
  459. * @access protected
  460. */
  461. function _doConnect($username, $password, $persistent = false)
  462. {
  463. if (!PEAR::loadExtension($this->phptype)) {
  464. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  465. 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
  466. }
  467. $params = array();
  468. if ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix') {
  469. $params[0] = ':' . $this->dsn['socket'];
  470. } else {
  471. $params[0] = $this->dsn['hostspec'] ? $this->dsn['hostspec']
  472. : 'localhost';
  473. if ($this->dsn['port']) {
  474. $params[0].= ':' . $this->dsn['port'];
  475. }
  476. }
  477. $params[] = $username ? $username : null;
  478. $params[] = $password ? $password : null;
  479. if (!$persistent) {
  480. if ($this->_isNewLinkSet()) {
  481. $params[] = true;
  482. } else {
  483. $params[] = false;
  484. }
  485. }
  486. if (version_compare(phpversion(), '4.3.0', '>=')) {
  487. $params[] = isset($this->dsn['client_flags'])
  488. ? $this->dsn['client_flags'] : null;
  489. }
  490. $connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect';
  491. $connection = @call_user_func_array($connect_function, $params);
  492. if (!$connection) {
  493. if (($err = @mysql_error()) != '') {
  494. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  495. $err, __FUNCTION__);
  496. } else {
  497. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  498. 'unable to establish a connection', __FUNCTION__);
  499. }
  500. }
  501. if (!empty($this->dsn['charset'])) {
  502. $result = $this->setCharset($this->dsn['charset'], $connection);
  503. if (PEAR::isError($result)) {
  504. $this->disconnect(false);
  505. return $result;
  506. }
  507. }
  508. return $connection;
  509. }
  510. // }}}
  511. // {{{ connect()
  512. /**
  513. * Connect to the database
  514. *
  515. * @return MDB2_OK on success, MDB2 Error Object on failure
  516. * @access public
  517. */
  518. function connect()
  519. {
  520. if (is_resource($this->connection)) {
  521. //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
  522. if (MDB2::areEquals($this->connected_dsn, $this->dsn)
  523. && $this->opened_persistent == $this->options['persistent']
  524. ) {
  525. return MDB2_OK;
  526. }
  527. $this->disconnect(false);
  528. }
  529. $connection = $this->_doConnect(
  530. $this->dsn['username'],
  531. $this->dsn['password'],
  532. $this->options['persistent']
  533. );
  534. if (PEAR::isError($connection)) {
  535. return $connection;
  536. }
  537. $this->connection = $connection;
  538. $this->connected_dsn = $this->dsn;
  539. $this->connected_database_name = '';
  540. $this->opened_persistent = $this->options['persistent'];
  541. $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
  542. if ($this->database_name) {
  543. if ($this->database_name != $this->connected_database_name) {
  544. if (!@mysql_select_db($this->database_name, $connection)) {
  545. $err = $this->raiseError(null, null, null,
  546. 'Could not select the database: '.$this->database_name, __FUNCTION__);
  547. return $err;
  548. }
  549. $this->connected_database_name = $this->database_name;
  550. }
  551. }
  552. $this->_getServerCapabilities();
  553. return MDB2_OK;
  554. }
  555. // }}}
  556. // {{{ setCharset()
  557. /**
  558. * Set the charset on the current connection
  559. *
  560. * @param string charset (or array(charset, collation))
  561. * @param resource connection handle
  562. *
  563. * @return true on success, MDB2 Error Object on failure
  564. */
  565. function setCharset($charset, $connection = null)
  566. {
  567. if (is_null($connection)) {
  568. $connection = $this->getConnection();
  569. if (PEAR::isError($connection)) {
  570. return $connection;
  571. }
  572. }
  573. $collation = null;
  574. if (is_array($charset) && 2 == count($charset)) {
  575. $collation = array_pop($charset);
  576. $charset = array_pop($charset);
  577. }
  578. $client_info = mysql_get_client_info();
  579. if (function_exists('mysql_set_charset') && version_compare($client_info, '5.0.6')) {
  580. if (!$result = mysql_set_charset($charset, $connection)) {
  581. $err =& $this->raiseError(null, null, null,
  582. 'Could not set client character set', __FUNCTION__);
  583. return $err;
  584. }
  585. return $result;
  586. }
  587. $query = "SET NAMES '".mysql_real_escape_string($charset, $connection)."'";
  588. if (!is_null($collation)) {
  589. $query .= " COLLATE '".mysqli_real_escape_string($connection, $collation)."'";
  590. }
  591. return $this->_doQuery($query, true, $connection);
  592. }
  593. // }}}
  594. // {{{ databaseExists()
  595. /**
  596. * check if given database name is exists?
  597. *
  598. * @param string $name name of the database that should be checked
  599. *
  600. * @return mixed true/false on success, a MDB2 error on failure
  601. * @access public
  602. */
  603. function databaseExists($name)
  604. {
  605. $connection = $this->_doConnect($this->dsn['username'],
  606. $this->dsn['password'],
  607. $this->options['persistent']);
  608. if (PEAR::isError($connection)) {
  609. return $connection;
  610. }
  611. $result = @mysql_select_db($name, $connection);
  612. @mysql_close($connection);
  613. return $result;
  614. }
  615. // }}}
  616. // {{{ disconnect()
  617. /**
  618. * Log out and disconnect from the database.
  619. *
  620. * @param boolean $force if the disconnect should be forced even if the
  621. * connection is opened persistently
  622. * @return mixed true on success, false if not connected and error
  623. * object on error
  624. * @access public
  625. */
  626. function disconnect($force = true)
  627. {
  628. if (is_resource($this->connection)) {
  629. if ($this->in_transaction) {
  630. $dsn = $this->dsn;
  631. $database_name = $this->database_name;
  632. $persistent = $this->options['persistent'];
  633. $this->dsn = $this->connected_dsn;
  634. $this->database_name = $this->connected_database_name;
  635. $this->options['persistent'] = $this->opened_persistent;
  636. $this->rollback();
  637. $this->dsn = $dsn;
  638. $this->database_name = $database_name;
  639. $this->options['persistent'] = $persistent;
  640. }
  641. if (!$this->opened_persistent || $force) {
  642. $ok = @mysql_close($this->connection);
  643. if (!$ok) {
  644. return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
  645. null, null, null, __FUNCTION__);
  646. }
  647. }
  648. } else {
  649. return false;
  650. }
  651. return parent::disconnect($force);
  652. }
  653. // }}}
  654. // {{{ standaloneQuery()
  655. /**
  656. * execute a query as DBA
  657. *
  658. * @param string $query the SQL query
  659. * @param mixed $types array that contains the types of the columns in
  660. * the result set
  661. * @param boolean $is_manip if the query is a manipulation query
  662. * @return mixed MDB2_OK on success, a MDB2 error on failure
  663. * @access public
  664. */
  665. function &standaloneQuery($query, $types = null, $is_manip = false)
  666. {
  667. $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
  668. $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
  669. $connection = $this->_doConnect($user, $pass, $this->options['persistent']);
  670. if (PEAR::isError($connection)) {
  671. return $connection;
  672. }
  673. $offset = $this->offset;
  674. $limit = $this->limit;
  675. $this->offset = $this->limit = 0;
  676. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  677. $result =& $this->_doQuery($query, $is_manip, $connection, $this->database_name);
  678. if (!PEAR::isError($result)) {
  679. $result = $this->_affectedRows($connection, $result);
  680. }
  681. @mysql_close($connection);
  682. return $result;
  683. }
  684. // }}}
  685. // {{{ _doQuery()
  686. /**
  687. * Execute a query
  688. * @param string $query query
  689. * @param boolean $is_manip if the query is a manipulation query
  690. * @param resource $connection
  691. * @param string $database_name
  692. * @return result or error object
  693. * @access protected
  694. */
  695. function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  696. {
  697. $this->last_query = $query;
  698. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  699. if ($result) {
  700. if (PEAR::isError($result)) {
  701. return $result;
  702. }
  703. $query = $result;
  704. }
  705. if ($this->options['disable_query']) {
  706. $result = $is_manip ? 0 : null;
  707. return $result;
  708. }
  709. if (is_null($connection)) {
  710. $connection = $this->getConnection();
  711. if (PEAR::isError($connection)) {
  712. return $connection;
  713. }
  714. }
  715. if (is_null($database_name)) {
  716. $database_name = $this->database_name;
  717. }
  718. if ($database_name) {
  719. if ($database_name != $this->connected_database_name) {
  720. if (!@mysql_select_db($database_name, $connection)) {
  721. $err = $this->raiseError(null, null, null,
  722. 'Could not select the database: '.$database_name, __FUNCTION__);
  723. return $err;
  724. }
  725. $this->connected_database_name = $database_name;
  726. }
  727. }
  728. $function = $this->options['result_buffering']
  729. ? 'mysql_query' : 'mysql_unbuffered_query';
  730. $result = @$function($query, $connection);
  731. if (!$result) {
  732. $err =$this->raiseError(null, null, null,
  733. 'Could not execute statement', __FUNCTION__);
  734. return $err;
  735. }
  736. $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
  737. return $result;
  738. }
  739. // }}}
  740. // {{{ _affectedRows()
  741. /**
  742. * Returns the number of rows affected
  743. *
  744. * @param resource $result
  745. * @param resource $connection
  746. * @return mixed MDB2 Error Object or the number of rows affected
  747. * @access private
  748. */
  749. function _affectedRows($connection, $result = null)
  750. {
  751. if (is_null($connection)) {
  752. $connection = $this->getConnection();
  753. if (PEAR::isError($connection)) {
  754. return $connection;
  755. }
  756. }
  757. return @mysql_affected_rows($connection);
  758. }
  759. // }}}
  760. // {{{ _modifyQuery()
  761. /**
  762. * Changes a query string for various DBMS specific reasons
  763. *
  764. * @param string $query query to modify
  765. * @param boolean $is_manip if it is a DML query
  766. * @param integer $limit limit the number of rows
  767. * @param integer $offset start reading from given offset
  768. * @return string modified query
  769. * @access protected
  770. */
  771. function _modifyQuery($query, $is_manip, $limit, $offset)
  772. {
  773. if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
  774. // "DELETE FROM table" gives 0 affected rows in MySQL.
  775. // This little hack lets you know how many rows were deleted.
  776. if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
  777. $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  778. 'DELETE FROM \1 WHERE 1=1', $query);
  779. }
  780. }
  781. if ($limit > 0
  782. && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
  783. ) {
  784. $query = rtrim($query);
  785. if (substr($query, -1) == ';') {
  786. $query = substr($query, 0, -1);
  787. }
  788. // LIMIT doesn't always come last in the query
  789. // @see http://dev.mysql.com/doc/refman/5.0/en/select.html
  790. $after = '';
  791. if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', $query, $matches)) {
  792. $after = $matches[0];
  793. $query = preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', '', $query);
  794. } elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i', $query, $matches)) {
  795. $after = $matches[0];
  796. $query = preg_replace('/(\s+FOR\s+UPDATE\s*)$/im', '', $query);
  797. } elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', $query, $matches)) {
  798. $after = $matches[0];
  799. $query = preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', '', $query);
  800. }
  801. if ($is_manip) {
  802. return $query . " LIMIT $limit" . $after;
  803. } else {
  804. return $query . " LIMIT $offset, $limit" . $after;
  805. }
  806. }
  807. return $query;
  808. }
  809. // }}}
  810. // {{{ getServerVersion()
  811. /**
  812. * return version information about the server
  813. *
  814. * @param bool $native determines if the raw version string should be returned
  815. * @return mixed array/string with version information or MDB2 error object
  816. * @access public
  817. */
  818. function getServerVersion($native = false)
  819. {
  820. $connection = $this->getConnection();
  821. if (PEAR::isError($connection)) {
  822. return $connection;
  823. }
  824. if ($this->connected_server_info) {
  825. $server_info = $this->connected_server_info;
  826. } else {
  827. $server_info = @mysql_get_server_info($connection);
  828. }
  829. if (!$server_info) {
  830. return $this->raiseError(null, null, null,
  831. 'Could not get server information', __FUNCTION__);
  832. }
  833. // cache server_info
  834. $this->connected_server_info = $server_info;
  835. if (!$native) {
  836. $tmp = explode('.', $server_info, 3);
  837. if (isset($tmp[2]) && strpos($tmp[2], '-')) {
  838. $tmp2 = explode('-', @$tmp[2], 2);
  839. } else {
  840. $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;
  841. $tmp2[1] = null;
  842. }
  843. $server_info = array(
  844. 'major' => isset($tmp[0]) ? $tmp[0] : null,
  845. 'minor' => isset($tmp[1]) ? $tmp[1] : null,
  846. 'patch' => $tmp2[0],
  847. 'extra' => $tmp2[1],
  848. 'native' => $server_info,
  849. );
  850. }
  851. return $server_info;
  852. }
  853. // }}}
  854. // {{{ _getServerCapabilities()
  855. /**
  856. * Fetch some information about the server capabilities
  857. * (transactions, subselects, prepared statements, etc).
  858. *
  859. * @access private
  860. */
  861. function _getServerCapabilities()
  862. {
  863. if (!$this->server_capabilities_checked) {
  864. $this->server_capabilities_checked = true;
  865. //set defaults
  866. $this->supported['sub_selects'] = 'emulated';
  867. $this->supported['prepared_statements'] = 'emulated';
  868. $this->supported['triggers'] = false;
  869. $this->start_transaction = false;
  870. $this->varchar_max_length = 255;
  871. $server_info = $this->getServerVersion();
  872. if (is_array($server_info)) {
  873. $server_version = $server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'];
  874. if (!version_compare($server_version, '4.1.0', '<')) {
  875. $this->supported['sub_selects'] = true;
  876. $this->supported['prepared_statements'] = true;
  877. }
  878. // SAVEPOINTs were introduced in MySQL 4.0.14 and 4.1.1 (InnoDB)
  879. if (version_compare($server_version, '4.1.0', '>=')) {
  880. if (version_compare($server_version, '4.1.1', '<')) {
  881. $this->supported['savepoints'] = false;
  882. }
  883. } elseif (version_compare($server_version, '4.0.14', '<')) {
  884. $this->supported['savepoints'] = false;
  885. }
  886. if (!version_compare($server_version, '4.0.11', '<')) {
  887. $this->start_transaction = true;
  888. }
  889. if (!version_compare($server_version, '5.0.3', '<')) {
  890. $this->varchar_max_length = 65532;
  891. }
  892. if (!version_compare($server_version, '5.0.2', '<')) {
  893. $this->supported['triggers'] = true;
  894. }
  895. }
  896. }
  897. }
  898. // }}}
  899. // {{{ function _skipUserDefinedVariable($query, $position)
  900. /**
  901. * Utility method, used by prepare() to avoid misinterpreting MySQL user
  902. * defined variables (SELECT @x:=5) for placeholders.
  903. * Check if the placeholder is a false positive, i.e. if it is an user defined
  904. * variable instead. If so, skip it and advance the position, otherwise
  905. * return the current position, which is valid
  906. *
  907. * @param string $query
  908. * @param integer $position current string cursor position
  909. * @return integer $new_position
  910. * @access protected
  911. */
  912. function _skipUserDefinedVariable($query, $position)
  913. {
  914. $found = strpos(strrev(substr($query, 0, $position)), '@');
  915. if ($found === false) {
  916. return $position;
  917. }
  918. $pos = strlen($query) - strlen(substr($query, $position)) - $found - 1;
  919. $substring = substr($query, $pos, $position - $pos + 2);
  920. if (preg_match('/^@\w+\s*:=$/', $substring)) {
  921. return $position + 1; //found an user defined variable: skip it
  922. }
  923. return $position;
  924. }
  925. // }}}
  926. // {{{ prepare()
  927. /**
  928. * Prepares a query for multiple execution with execute().
  929. * With some database backends, this is emulated.
  930. * prepare() requires a generic query as string like
  931. * 'INSERT INTO numbers VALUES(?,?)' or
  932. * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  933. * The ? and :name and are placeholders which can be set using
  934. * bindParam() and the query can be sent off using the execute() method.
  935. * The allowed format for :name can be set with the 'bindname_format' option.
  936. *
  937. * @param string $query the query to prepare
  938. * @param mixed $types array that contains the types of the placeholders
  939. * @param mixed $result_types array that contains the types of the columns in
  940. * the result set or MDB2_PREPARE_RESULT, if set to
  941. * MDB2_PREPARE_MANIP the query is handled as a manipulation query
  942. * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
  943. * @return mixed resource handle for the prepared query on success, a MDB2
  944. * error on failure
  945. * @access public
  946. * @see bindParam, execute
  947. */
  948. function &prepare($query, $types = null, $result_types = null, $lobs = array())
  949. {
  950. if ($this->options['emulate_prepared']
  951. || $this->supported['prepared_statements'] !== true
  952. ) {
  953. $obj =& parent::prepare($query, $types, $result_types, $lobs);
  954. return $obj;
  955. }
  956. $is_manip = ($result_types === MDB2_PREPARE_MANIP);
  957. $offset = $this->offset;
  958. $limit = $this->limit;
  959. $this->offset = $this->limit = 0;
  960. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  961. $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
  962. if ($result) {
  963. if (PEAR::isError($result)) {
  964. return $result;
  965. }
  966. $query = $result;
  967. }
  968. $placeholder_type_guess = $placeholder_type = null;
  969. $question = '?';
  970. $colon = ':';
  971. $positions = array();
  972. $position = 0;
  973. while ($position < strlen($query)) {
  974. $q_position = strpos($query, $question, $position);
  975. $c_position = strpos($query, $colon, $position);
  976. if ($q_position && $c_position) {
  977. $p_position = min($q_position, $c_position);
  978. } elseif ($q_position) {
  979. $p_position = $q_position;
  980. } elseif ($c_position) {
  981. $p_position = $c_position;
  982. } else {
  983. break;
  984. }
  985. if (is_null($placeholder_type)) {
  986. $placeholder_type_guess = $query[$p_position];
  987. }
  988. $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
  989. if (PEAR::isError($new_pos)) {
  990. return $new_pos;
  991. }
  992. if ($new_pos != $position) {
  993. $position = $new_pos;
  994. continue; //evaluate again starting from the new position
  995. }
  996. //make sure this is not part of an user defined variable
  997. $new_pos = $this->_skipUserDefinedVariable($query, $position);
  998. if ($new_pos != $position) {
  999. $position = $new_pos;
  1000. continue; //evaluate again starting from the new position
  1001. }
  1002. if ($query[$position] == $placeholder_type_guess) {
  1003. if (is_null($placeholder_type)) {
  1004. $placeholder_type = $query[$p_position];
  1005. $question = $colon = $placeholder_type;
  1006. }
  1007. if ($placeholder_type == ':') {
  1008. $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
  1009. $parameter = preg_replace($regexp, '\\1', $query);
  1010. if ($parameter === '') {
  1011. $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  1012. 'named parameter name must match "bindname_format" option', __FUNCTION__);
  1013. return $err;
  1014. }
  1015. $positions[$p_position] = $parameter;
  1016. $query = substr_replace($query, '?', $position, strlen($parameter)+1);
  1017. } else {
  1018. $positions[$p_position] = count($positions);
  1019. }
  1020. $position = $p_position + 1;
  1021. } else {
  1022. $position = $p_position;
  1023. }
  1024. }
  1025. $connection = $this->getConnection();
  1026. if (PEAR::isError($connection)) {
  1027. return $connection;
  1028. }
  1029. static $prep_statement_counter = 1;
  1030. $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
  1031. $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
  1032. $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text');
  1033. $statement =& $this->_doQuery($query, true, $connection);
  1034. if (PEAR::isError($statement)) {
  1035. return $statement;
  1036. }
  1037. $class_name = 'MDB2_Statement_'.$this->phptype;
  1038. $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  1039. $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  1040. return $obj;
  1041. }
  1042. // }}}
  1043. // {{{ replace()
  1044. /**
  1045. * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  1046. * query, except that if there is already a row in the table with the same
  1047. * key field values, the old row is deleted before the new row is inserted.
  1048. *
  1049. * The REPLACE type of query does not make part of the SQL standards. Since
  1050. * practically only MySQL implements it natively, this type of query is
  1051. * emulated through this method for other DBMS using standard types of
  1052. * queries inside a transaction to assure the atomicity of the operation.
  1053. *
  1054. * @access public
  1055. *
  1056. * @param string $table name of the table on which the REPLACE query will
  1057. * be executed.
  1058. * @param array $fields associative array that describes the fields and the
  1059. * values that will be inserted or updated in the specified table. The
  1060. * indexes of the array are the names of all the fields of the table. The
  1061. * values of the array are also associative arrays that describe the
  1062. * values and other properties of the table fields.
  1063. *
  1064. * Here follows a list of field properties that need to be specified:
  1065. *
  1066. * value:
  1067. * Value to be assigned to the specified field. This value may be
  1068. * of specified in database independent type format as this
  1069. * function can perform the necessary datatype conversions.
  1070. *
  1071. * Default:
  1072. * this property is required unless the Null property
  1073. * is set to 1.
  1074. *
  1075. * type
  1076. * Name of the type of the field. Currently, all types Metabase
  1077. * are supported except for clob and blob.
  1078. *
  1079. * Default: no type conversion
  1080. *
  1081. * null
  1082. * Boolean property that indicates that the value for this field
  1083. * should be set to null.
  1084. *
  1085. * The default value for fields missing in INSERT queries may be
  1086. * specified the definition of a table. Often, the default value
  1087. * is already null, but since the REPLACE may be emulated using
  1088. * an UPDATE query, make sure that all fields of the table are
  1089. * listed in this function argument array.
  1090. *
  1091. * Default: 0
  1092. *
  1093. * key
  1094. * Boolean property that indicates that this field should be
  1095. * handled as a primary key or at least as part of the compound
  1096. * unique index of the table that will determine the row that will
  1097. * updated if it exists or inserted a new row otherwise.
  1098. *
  1099. * This function will fail if no key field is specified or if the
  1100. * value of a key field is set to null because fields that are
  1101. * part of unique index they may not be null.
  1102. *
  1103. * Default: 0
  1104. *
  1105. * @see http://dev.mysql.com/doc/refman/5.0/en/replace.html
  1106. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1107. */
  1108. function replace($table, $fields)
  1109. {
  1110. $count = count($fields);
  1111. $query = $values = '';
  1112. $keys = $colnum = 0;
  1113. for (reset($fields); $colnum < $count; next($fields), $colnum++) {
  1114. $name = key($fields);
  1115. if ($colnum > 0) {
  1116. $query .= ',';
  1117. $values.= ',';
  1118. }
  1119. $query.= $this->quoteIdentifier($name, true);
  1120. if (isset($fields[$name]['null']) && $fields[$name]['null']) {
  1121. $value = 'NULL';
  1122. } else {
  1123. $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
  1124. $value = $this->quote($fields[$name]['value'], $type);
  1125. if (PEAR::isError($value)) {
  1126. return $value;
  1127. }
  1128. }
  1129. $values.= $value;
  1130. if (isset($fields[$name]['key']) && $fields[$name]['key']) {
  1131. if ($value === 'NULL') {
  1132. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  1133. 'key value '.$name.' may not be NULL', __FUNCTION__);
  1134. }
  1135. $keys++;
  1136. }
  1137. }
  1138. if ($keys == 0) {
  1139. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  1140. 'not specified which fields are keys', __FUNCTION__);
  1141. }
  1142. $connection = $this->getConnection();
  1143. if (PEAR::isError($connection)) {
  1144. return $connection;
  1145. }
  1146. $table = $this->quoteIdentifier($table, true);
  1147. $query = "REPLACE INTO $table ($query) VALUES ($values)";
  1148. $result =& $this->_doQuery($query, true, $connection);
  1149. if (PEAR::isError($result)) {
  1150. return $result;
  1151. }
  1152. return $this->_affectedRows($connection, $result);
  1153. }
  1154. // }}}
  1155. // {{{ nextID()
  1156. /**
  1157. * Returns the next free id of a sequence
  1158. *
  1159. * @param string $seq_name name of the sequence
  1160. * @param boolean $ondemand when true the sequence is
  1161. * automatic created, if it
  1162. * not exists
  1163. *
  1164. * @return mixed MDB2 Error Object or id
  1165. * @access public
  1166. */
  1167. function nextID($seq_name, $ondemand = true)
  1168. {
  1169. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  1170. $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
  1171. $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  1172. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  1173. $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  1174. $result =& $this->_doQuery($query, true);
  1175. $this->popExpect();
  1176. $this->popErrorHandling();
  1177. if (PEAR::isError($result)) {
  1178. if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
  1179. $this->loadModule('Manager', null, true);
  1180. $result = $this->manager->createSequence($seq_name);
  1181. if (PEAR::isError($result)) {
  1182. return $this->raiseError($result, null, null,
  1183. 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
  1184. } else {
  1185. return $this->nextID($seq_name, false);
  1186. }
  1187. }
  1188. return $result;
  1189. }
  1190. $value = $this->lastInsertID();
  1191. if (is_numeric($value)) {
  1192. $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  1193. $result =& $this->_doQuery($query, true);
  1194. if (PEAR::isError($result)) {
  1195. $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
  1196. }
  1197. }
  1198. return $value;
  1199. }
  1200. // }}}
  1201. // {{{ lastInsertID()
  1202. /**
  1203. * Returns the autoincrement ID if supported or $id or fetches the current
  1204. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  1205. *
  1206. * @param string $table name of the table into which a new row was inserted
  1207. * @param string $field name of the field into which a new row was inserted
  1208. * @return mixed MDB2 Error Object or id
  1209. * @access public
  1210. */
  1211. function lastInsertID($table = null, $field = null)
  1212. {
  1213. // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
  1214. return $this->queryOne('SELECT LAST_INSERT_ID()', 'integer');
  1215. }
  1216. // }}}
  1217. // {{{ currID()
  1218. /**
  1219. * Returns the current id of a sequence
  1220. *
  1221. * @param string $seq_name name of the sequence
  1222. * @return mixed MDB2 Error Object or id
  1223. * @access public
  1224. */
  1225. function currID($seq_name)
  1226. {
  1227. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  1228. $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
  1229. $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  1230. return $this->queryOne($query, 'integer');
  1231. }
  1232. }
  1233. /**
  1234. * MDB2 MySQL result driver
  1235. *
  1236. * @package MDB2
  1237. * @category Database
  1238. * @author Lukas Smith <smith@pooteeweet.org>
  1239. */
  1240. class MDB2_Result_mysql extends MDB2_Result_Common
  1241. {
  1242. // }}}
  1243. // {{{ fetchRow()
  1244. /**
  1245. * Fetch a row and insert the data into an existing array.
  1246. *
  1247. * @param int $fetchmode how the array data should be indexed
  1248. * @param int $rownum number of the row where the data can be found
  1249. * @return int data array on success, a MDB2 error on failure
  1250. * @access public
  1251. */
  1252. function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  1253. {
  1254. if (!is_null($rownum)) {
  1255. $seek = $this->seek($rownum);
  1256. if (PEAR::isError($seek)) {
  1257. return $seek;
  1258. }
  1259. }
  1260. if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  1261. $fetchmode = $this->db->fetchmode;
  1262. }
  1263. if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
  1264. $row = @mysql_fetch_assoc($this->result);
  1265. if (is_array($row)
  1266. && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
  1267. ) {
  1268. $row = array_change_key_case($row, $this->db->options['field_case']);
  1269. }
  1270. } else {
  1271. $row = @mysql_fetch_row($this->result);
  1272. }
  1273. if (!$row) {
  1274. if ($this->result === false) {
  1275. $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1276. 'resultset has already been freed', __FUNCTION__);
  1277. return $err;
  1278. }
  1279. $null = null;
  1280. return $null;
  1281. }
  1282. $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  1283. $rtrim = false;
  1284. if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
  1285. if (empty($this->types)) {
  1286. $mode += MDB2_PORTABILITY_RTRIM;
  1287. } else {
  1288. $rtrim = true;
  1289. }
  1290. }
  1291. if ($mode) {
  1292. $this->db->_fixResultArrayValues($row, $mode);
  1293. }
  1294. if (!empty($this->types)) {
  1295. $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
  1296. }
  1297. if (!empty($this->values)) {
  1298. $this->_assignBindColumns($row);
  1299. }
  1300. if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  1301. $object_class = $this->db->options['fetch_class'];
  1302. if ($object_class == 'stdClass') {
  1303. $row = (object) $row;
  1304. } else {
  1305. $row = new $object_class($row);
  1306. }
  1307. }
  1308. ++$this->rownum;
  1309. return $row;
  1310. }
  1311. // }}}
  1312. // {{{ _getColumnNames()
  1313. /**
  1314. * Retrieve the names of columns returned by the DBMS in a query result.
  1315. *
  1316. * @return mixed Array variable that holds the names of columns as keys
  1317. * or an MDB2 error on failure.
  1318. * Some DBMS may not return any columns when the result set
  1319. * does not contain any rows.
  1320. * @access private
  1321. */
  1322. function _getColumnNames()
  1323. {
  1324. $columns = array();
  1325. $numcols = $this->numCols();
  1326. if (PEAR::isError($numcols)) {
  1327. return $numcols;
  1328. }
  1329. for ($column = 0; $column < $numcols; $column++) {
  1330. $column_name = @mysql_field_name($this->result, $column);
  1331. $columns[$column_name] = $column;
  1332. }
  1333. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1334. $columns = array_change_key_case($columns, $this->db->options['field_case']);
  1335. }
  1336. return $columns;
  1337. }
  1338. // }}}
  1339. // {{{ numCols()
  1340. /**
  1341. * Count the number of columns returned by the DBMS in a query result.
  1342. *
  1343. * @return mixed integer value with the number of columns, a MDB2 error
  1344. * on failure
  1345. * @access public
  1346. */
  1347. function numCols()
  1348. {
  1349. $cols = @mysql_num_fields($this->result);
  1350. if (is_null($cols)) {
  1351. if ($this->result === false) {
  1352. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1353. 'resultset has already been freed', __FUNCTION__);
  1354. } elseif (is_null($this->result)) {
  1355. return count($this->types);
  1356. }
  1357. return $this->db->raiseError(null, null, null,
  1358. 'Could not get column count', __FUNCTION__);
  1359. }
  1360. return $cols;
  1361. }
  1362. // }}}
  1363. // {{{ free()
  1364. /**
  1365. * Free the internal resources associated with result.
  1366. *
  1367. * @return boolean true on success, false if result is invalid
  1368. * @access public
  1369. */
  1370. function free()
  1371. {
  1372. if (is_resource($this->result) && $this->db->connection) {
  1373. $free = @mysql_free_result($this->result);
  1374. if ($free === false) {
  1375. return $this->db->raiseError(null, null, null,
  1376. 'Could not free result', __FUNCTION__);
  1377. }
  1378. }
  1379. $this->result = false;
  1380. return MDB2_OK;
  1381. }
  1382. }
  1383. /**
  1384. * MDB2 MySQL buffered result driver
  1385. *
  1386. * @package MDB2
  1387. * @category Database
  1388. * @author Lukas Smith <smith@pooteeweet.org>
  1389. */
  1390. class MDB2_BufferedResult_mysql extends MDB2_Result_mysql
  1391. {
  1392. // }}}
  1393. // {{{ seek()
  1394. /**
  1395. * Seek to a specific row in a result set
  1396. *
  1397. * @param int $rownum number of the row where the data can be found
  1398. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1399. * @access public
  1400. */
  1401. function seek($rownum = 0)
  1402. {
  1403. if ($this->rownum != ($rownum - 1) && !@mysql_data_seek($this->result, $rownum)) {
  1404. if ($this->result === false) {
  1405. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1406. 'resultset has already been freed', __FUNCTION__);
  1407. } elseif (is_null($this->result)) {
  1408. return MDB2_OK;
  1409. }
  1410. return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
  1411. 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
  1412. }
  1413. $this->rownum = $rownum - 1;
  1414. return MDB2_OK;
  1415. }
  1416. // }}}
  1417. // {{{ valid()
  1418. /**
  1419. * Check if the end of the result set has been reached
  1420. *
  1421. * @return mixed true or false on sucess, a MDB2 error on failure
  1422. * @access public
  1423. */
  1424. function valid()
  1425. {
  1426. $numrows = $this->numRows();
  1427. if (PEAR::isError($numrows)) {
  1428. return $numrows;
  1429. }
  1430. return $this->rownum < ($numrows - 1);
  1431. }
  1432. // }}}
  1433. // {{{ numRows()
  1434. /**
  1435. * Returns the number of rows in a result object
  1436. *
  1437. * @return mixed MDB2 Error Object or the number of rows
  1438. * @access public
  1439. */
  1440. function numRows()
  1441. {
  1442. $rows = @mysql_num_rows($this->result);
  1443. if (false === $rows) {
  1444. if (false === $this->result) {
  1445. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1446. 'resultset has already been freed', __FUNCTION__);
  1447. } elseif (is_null($this->result)) {
  1448. return 0;
  1449. }
  1450. return $this->db->raiseError(null, null, null,
  1451. 'Could not get row count', __FUNCTION__);
  1452. }
  1453. return $rows;
  1454. }
  1455. }
  1456. /**
  1457. * MDB2 MySQL statement driver
  1458. *
  1459. * @package MDB2
  1460. * @category Database
  1461. * @author Lukas Smith <smith@pooteeweet.org>
  1462. */
  1463. class MDB2_Statement_mysql extends MDB2_Statement_Common
  1464. {
  1465. // {{{ _execute()
  1466. /**
  1467. * Execute a prepared query statement helper method.
  1468. *
  1469. * @param mixed $result_class string which specifies which result class to use
  1470. * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1471. *
  1472. * @return mixed MDB2_Result or integer (affected rows) on success,
  1473. * a MDB2 error on failure
  1474. * @access private
  1475. */
  1476. function &_execute($result_class = true, $result_wrap_class = false)
  1477. {
  1478. if (is_null($this->statement)) {
  1479. $result =& parent::_execute($result_class, $result_wrap_class);
  1480. return $result;
  1481. }
  1482. $this->db->last_query = $this->query;
  1483. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
  1484. if ($this->db->getOption('disable_query')) {
  1485. $result = $this->is_manip ? 0 : null;
  1486. return $result;
  1487. }
  1488. $connection = $this->db->getConnection();
  1489. if (PEAR::isError($connection)) {
  1490. return $connection;
  1491. }
  1492. $query = 'EXECUTE '.$this->statement;
  1493. if (!empty($this->positions)) {
  1494. $parameters = array();
  1495. foreach ($this->positions as $parameter) {
  1496. if (!array_key_exists($parameter, $this->values)) {
  1497. return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  1498. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  1499. }
  1500. $value = $this->values[$parameter];
  1501. $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
  1502. if (is_resource($value) || $type == 'clob' || $type == 'blob' && $this->db->options['lob_allow_url_include']) {
  1503. if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
  1504. if ($match[1] == 'file://') {
  1505. $value = $match[2];
  1506. }
  1507. $value = @fopen($value, 'r');
  1508. $close = true;
  1509. }
  1510. if (is_resource($value)) {
  1511. $data = '';
  1512. while (!@feof($value)) {
  1513. $data.= @fread($value, $this->db->options['lob_buffer_length']);
  1514. }
  1515. if ($close) {
  1516. @fclose($value);
  1517. }
  1518. $value = $data;
  1519. }
  1520. }
  1521. $quoted = $this->db->quote($value, $type);
  1522. if (PEAR::isError($quoted)) {
  1523. return $quoted;
  1524. }
  1525. $param_query = 'SET @'.$parameter.' = '.$quoted;
  1526. $result = $this->db->_doQuery($param_query, true, $connection);
  1527. if (PEAR::isError($result)) {
  1528. return $result;
  1529. }
  1530. }
  1531. $query.= ' USING @'.implode(', @', array_values($this->positions));
  1532. }
  1533. $result = $this->db->_doQuery($query, $this->is_manip, $connection);
  1534. if (PEAR::isError($result)) {
  1535. return $result;
  1536. }
  1537. if ($this->is_manip) {
  1538. $affected_rows = $this->db->_affectedRows($connection, $result);
  1539. return $affected_rows;
  1540. }
  1541. $result =& $this->db->_wrapResult($result, $this->result_types,
  1542. $result_class, $result_wrap_class, $this->limit, $this->offset);
  1543. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
  1544. return $result;
  1545. }
  1546. // }}}
  1547. // {{{ free()
  1548. /**
  1549. * Release resources allocated for the specified prepared query.
  1550. *
  1551. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1552. * @access public
  1553. */
  1554. function free()
  1555. {
  1556. if (is_null($this->positions)) {
  1557. return $this->db->raiseError(MDB2_ERROR, null, null,
  1558. 'Prepared statement has already been freed', __FUNCTION__);
  1559. }
  1560. $result = MDB2_OK;
  1561. if (!is_null($this->statement)) {
  1562. $connection = $this->db->getConnection();
  1563. if (PEAR::isError($connection)) {
  1564. return $connection;
  1565. }
  1566. $query = 'DEALLOCATE PREPARE '.$this->statement;
  1567. $result = $this->db->_doQuery($query, true, $connection);
  1568. }
  1569. parent::free();
  1570. return $result;
  1571. }
  1572. }
  1573. ?>