Automatically exported from code.google.com/p/planningalerts
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

mysql.php 52 KiB

hace 17 años
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416
  1. <?php
  2. // vim: set et ts=4 sw=4 fdm=marker:
  3. // +----------------------------------------------------------------------+
  4. // | PHP versions 4 and 5 |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1998-2006 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.157 2006/08/20 19:38:26 lsmith 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 $escape_quotes = "\\";
  59. var $escape_pattern = "\\";
  60. var $escape_identifier = '`';
  61. var $start_transaction = false;
  62. var $varchar_max_length = 255;
  63. // }}}
  64. // {{{ constructor
  65. /**
  66. * Constructor
  67. */
  68. function __construct()
  69. {
  70. parent::__construct();
  71. $this->phptype = 'mysql';
  72. $this->dbsyntax = 'mysql';
  73. $this->supported['sequences'] = 'emulated';
  74. $this->supported['indexes'] = true;
  75. $this->supported['affected_rows'] = true;
  76. $this->supported['transactions'] = false;
  77. $this->supported['savepoints'] = false;
  78. $this->supported['summary_functions'] = true;
  79. $this->supported['order_by_text'] = true;
  80. $this->supported['current_id'] = 'emulated';
  81. $this->supported['limit_queries'] = true;
  82. $this->supported['LOBs'] = true;
  83. $this->supported['replace'] = true;
  84. $this->supported['sub_selects'] = 'emulated';
  85. $this->supported['auto_increment'] = true;
  86. $this->supported['primary_key'] = true;
  87. $this->supported['result_introspection'] = true;
  88. $this->supported['prepared_statements'] = 'emulated';
  89. $this->supported['identifier_quoting'] = true;
  90. $this->supported['pattern_escaping'] = true;
  91. $this->options['default_table_type'] = '';
  92. }
  93. // }}}
  94. // {{{ errorInfo()
  95. /**
  96. * This method is used to collect information about an error
  97. *
  98. * @param integer $error
  99. * @return array
  100. * @access public
  101. */
  102. function errorInfo($error = null)
  103. {
  104. if ($this->connection) {
  105. $native_code = @mysql_errno($this->connection);
  106. $native_msg = @mysql_error($this->connection);
  107. } else {
  108. $native_code = @mysql_errno();
  109. $native_msg = @mysql_error();
  110. }
  111. if (is_null($error)) {
  112. static $ecode_map;
  113. if (empty($ecode_map)) {
  114. $ecode_map = array(
  115. 1004 => MDB2_ERROR_CANNOT_CREATE,
  116. 1005 => MDB2_ERROR_CANNOT_CREATE,
  117. 1006 => MDB2_ERROR_CANNOT_CREATE,
  118. 1007 => MDB2_ERROR_ALREADY_EXISTS,
  119. 1008 => MDB2_ERROR_CANNOT_DROP,
  120. 1022 => MDB2_ERROR_ALREADY_EXISTS,
  121. 1044 => MDB2_ERROR_ACCESS_VIOLATION,
  122. 1046 => MDB2_ERROR_NODBSELECTED,
  123. 1048 => MDB2_ERROR_CONSTRAINT,
  124. 1049 => MDB2_ERROR_NOSUCHDB,
  125. 1050 => MDB2_ERROR_ALREADY_EXISTS,
  126. 1051 => MDB2_ERROR_NOSUCHTABLE,
  127. 1054 => MDB2_ERROR_NOSUCHFIELD,
  128. 1061 => MDB2_ERROR_ALREADY_EXISTS,
  129. 1062 => MDB2_ERROR_ALREADY_EXISTS,
  130. 1064 => MDB2_ERROR_SYNTAX,
  131. 1091 => MDB2_ERROR_NOT_FOUND,
  132. 1100 => MDB2_ERROR_NOT_LOCKED,
  133. 1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
  134. 1142 => MDB2_ERROR_ACCESS_VIOLATION,
  135. 1146 => MDB2_ERROR_NOSUCHTABLE,
  136. 1216 => MDB2_ERROR_CONSTRAINT,
  137. 1217 => MDB2_ERROR_CONSTRAINT,
  138. );
  139. }
  140. if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) {
  141. $ecode_map[1022] = MDB2_ERROR_CONSTRAINT;
  142. $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL;
  143. $ecode_map[1062] = MDB2_ERROR_CONSTRAINT;
  144. } else {
  145. // Doing this in case mode changes during runtime.
  146. $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS;
  147. $ecode_map[1048] = MDB2_ERROR_CONSTRAINT;
  148. $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS;
  149. }
  150. if (isset($ecode_map[$native_code])) {
  151. $error = $ecode_map[$native_code];
  152. }
  153. }
  154. return array($error, $native_code, $native_msg);
  155. }
  156. // }}}
  157. // {{{ escape()
  158. /**
  159. * Quotes a string so it can be safely used in a query. It will quote
  160. * the text so it can safely be used within a query.
  161. *
  162. * @param string the input string to quote
  163. * @param bool escape wildcards
  164. *
  165. * @return string quoted string
  166. *
  167. * @access public
  168. */
  169. function escape($text, $escape_wildcards = false)
  170. {
  171. if ($escape_wildcards) {
  172. $text = $this->escapePattern($text);
  173. }
  174. $connection = $this->getConnection();
  175. if (PEAR::isError($connection)) {
  176. return $connection;
  177. }
  178. $text = @mysql_real_escape_string($text, $connection);
  179. return $text;
  180. }
  181. // }}}
  182. // {{{
  183. /**
  184. * Start a transaction or set a savepoint.
  185. *
  186. * @param string name of a savepoint to set
  187. * @return mixed MDB2_OK on success, a MDB2 error on failure
  188. *
  189. * @access public
  190. */
  191. function beginTransaction($savepoint = null)
  192. {
  193. $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  194. if (!is_null($savepoint)) {
  195. if (!$this->supports('savepoints')) {
  196. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  197. 'savepoints are not supported', __FUNCTION__);
  198. }
  199. if (!$this->in_transaction) {
  200. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  201. 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
  202. }
  203. $query = 'SAVEPOINT '.$savepoint;
  204. return $this->_doQuery($query, true);
  205. } elseif ($this->in_transaction) {
  206. return MDB2_OK; //nothing to do
  207. }
  208. if (!$this->destructor_registered && $this->opened_persistent) {
  209. $this->destructor_registered = true;
  210. register_shutdown_function('MDB2_closeOpenTransactions');
  211. }
  212. $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 1';
  213. $result =& $this->_doQuery($query, true);
  214. if (PEAR::isError($result)) {
  215. return $result;
  216. }
  217. $this->in_transaction = true;
  218. return MDB2_OK;
  219. }
  220. // }}}
  221. // {{{ commit()
  222. /**
  223. * Commit the database changes done during a transaction that is in
  224. * progress or release a savepoint. This function may only be called when
  225. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  226. * transaction is implicitly started after committing the pending changes.
  227. *
  228. * @param string name of a savepoint to release
  229. * @return mixed MDB2_OK on success, a MDB2 error on failure
  230. *
  231. * @access public
  232. */
  233. function commit($savepoint = null)
  234. {
  235. $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  236. if (!$this->in_transaction) {
  237. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  238. 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
  239. }
  240. if (!is_null($savepoint)) {
  241. if (!$this->supports('savepoints')) {
  242. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  243. 'savepoints are not supported', __FUNCTION__);
  244. }
  245. $server_info = $this->getServerVersion();
  246. if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
  247. return MDB2_OK;
  248. }
  249. $query = 'RELEASE SAVEPOINT '.$savepoint;
  250. return $this->_doQuery($query, true);
  251. }
  252. if (!$this->supports('transactions')) {
  253. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  254. 'transactions are not supported', __FUNCTION__);
  255. }
  256. $result =& $this->_doQuery('COMMIT', true);
  257. if (PEAR::isError($result)) {
  258. return $result;
  259. }
  260. if (!$this->start_transaction) {
  261. $query = 'SET AUTOCOMMIT = 0';
  262. $result =& $this->_doQuery($query, true);
  263. if (PEAR::isError($result)) {
  264. return $result;
  265. }
  266. }
  267. $this->in_transaction = false;
  268. return MDB2_OK;
  269. }
  270. // }}}
  271. // {{{ rollback()
  272. /**
  273. * Cancel any database changes done during a transaction or since a specific
  274. * savepoint that is in progress. This function may only be called when
  275. * auto-committing is disabled, otherwise it will fail. Therefore, a new
  276. * transaction is implicitly started after canceling the pending changes.
  277. *
  278. * @param string name of a savepoint to rollback to
  279. * @return mixed MDB2_OK on success, a MDB2 error on failure
  280. *
  281. * @access public
  282. */
  283. function rollback($savepoint = null)
  284. {
  285. $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
  286. if (!$this->in_transaction) {
  287. return $this->raiseError(MDB2_ERROR_INVALID, null, null,
  288. 'rollback cannot be done changes are auto committed', __FUNCTION__);
  289. }
  290. if (!is_null($savepoint)) {
  291. if (!$this->supports('savepoints')) {
  292. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  293. 'savepoints are not supported', __FUNCTION__);
  294. }
  295. $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
  296. return $this->_doQuery($query, true);
  297. }
  298. $query = 'ROLLBACK';
  299. $result =& $this->_doQuery($query, true);
  300. if (PEAR::isError($result)) {
  301. return $result;
  302. }
  303. if (!$this->start_transaction) {
  304. $query = 'SET AUTOCOMMIT = 0';
  305. $result =& $this->_doQuery($query, true);
  306. if (PEAR::isError($result)) {
  307. return $result;
  308. }
  309. }
  310. $this->in_transaction = false;
  311. return MDB2_OK;
  312. }
  313. // }}}
  314. // {{{ function setTransactionIsolation()
  315. /**
  316. * Set the transacton isolation level.
  317. *
  318. * @param string standard isolation level
  319. * READ UNCOMMITTED (allows dirty reads)
  320. * READ COMMITTED (prevents dirty reads)
  321. * REPEATABLE READ (prevents nonrepeatable reads)
  322. * SERIALIZABLE (prevents phantom reads)
  323. * @return mixed MDB2_OK on success, a MDB2 error on failure
  324. *
  325. * @access public
  326. * @since 2.1.1
  327. */
  328. function setTransactionIsolation($isolation)
  329. {
  330. $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
  331. if (!$this->supports('transactions')) {
  332. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  333. 'transactions are not supported', __FUNCTION__);
  334. }
  335. switch ($isolation) {
  336. case 'READ UNCOMMITTED':
  337. case 'READ COMMITTED':
  338. case 'REPEATABLE READ':
  339. case 'SERIALIZABLE':
  340. break;
  341. default:
  342. return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  343. 'isolation level is not supported: '.$isolation, __FUNCTION__);
  344. }
  345. $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
  346. return $this->_doQuery($query, true);
  347. }
  348. // }}}
  349. // {{{ connect()
  350. /**
  351. * Connect to the database
  352. *
  353. * @return true on success, MDB2 Error Object on failure
  354. */
  355. function connect()
  356. {
  357. if (is_resource($this->connection)) {
  358. if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
  359. && $this->opened_persistent == $this->options['persistent']
  360. ) {
  361. return MDB2_OK;
  362. }
  363. $this->disconnect(false);
  364. }
  365. if (!PEAR::loadExtension($this->phptype)) {
  366. return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  367. 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
  368. }
  369. $params = array();
  370. if ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix') {
  371. $params[0] = ':' . $this->dsn['socket'];
  372. } else {
  373. $params[0] = $this->dsn['hostspec'] ? $this->dsn['hostspec']
  374. : 'localhost';
  375. if ($this->dsn['port']) {
  376. $params[0].= ':' . $this->dsn['port'];
  377. }
  378. }
  379. $params[] = $this->dsn['username'] ? $this->dsn['username'] : null;
  380. $params[] = $this->dsn['password'] ? $this->dsn['password'] : null;
  381. if (!$this->options['persistent']) {
  382. if (isset($this->dsn['new_link'])
  383. && ($this->dsn['new_link'] == 'true' || $this->dsn['new_link'] === true)
  384. ) {
  385. $params[] = true;
  386. } else {
  387. $params[] = false;
  388. }
  389. }
  390. if (version_compare(phpversion(), '4.3.0', '>=')) {
  391. $params[] = isset($this->dsn['client_flags'])
  392. ? $this->dsn['client_flags'] : null;
  393. }
  394. $connect_function = $this->options['persistent'] ? 'mysql_pconnect' : 'mysql_connect';
  395. @ini_set('track_errors', true);
  396. $php_errormsg = '';
  397. $connection = @call_user_func_array($connect_function, $params);
  398. @ini_restore('track_errors');
  399. if (!$connection) {
  400. if (($err = @mysql_error()) != '') {
  401. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  402. $err, __FUNCTION__);
  403. } else {
  404. return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
  405. $php_errormsg, __FUNCTION__);
  406. }
  407. }
  408. if (!empty($this->dsn['charset'])) {
  409. $result = $this->setCharset($this->dsn['charset'], $connection);
  410. if (PEAR::isError($result)) {
  411. return $result;
  412. }
  413. }
  414. $this->connection = $connection;
  415. $this->connected_dsn = $this->dsn;
  416. $this->connected_database_name = '';
  417. $this->opened_persistent = $this->options['persistent'];
  418. $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
  419. $this->supported['transactions'] = $this->options['use_transactions'];
  420. if ($this->options['default_table_type']) {
  421. switch (strtoupper($this->options['default_table_type'])) {
  422. case 'BLACKHOLE':
  423. case 'MEMORY':
  424. case 'ARCHIVE':
  425. case 'CSV':
  426. case 'HEAP':
  427. case 'ISAM':
  428. case 'MERGE':
  429. case 'MRG_ISAM':
  430. case 'ISAM':
  431. case 'MRG_MYISAM':
  432. case 'MYISAM':
  433. $this->supported['transactions'] = false;
  434. $this->warnings[] = $default_table_type.
  435. ' is not a supported default table type';
  436. break;
  437. }
  438. }
  439. $this->supported['sub_selects'] = 'emulated';
  440. $this->supported['prepared_statements'] = 'emulated';
  441. $this->start_transaction = false;
  442. $this->varchar_max_length = 255;
  443. $server_info = $this->getServerVersion();
  444. if (is_array($server_info)) {
  445. if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '4.1.0', '<')) {
  446. $this->supported['sub_selects'] = true;
  447. $this->supported['prepared_statements'] = true;
  448. }
  449. if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '4.0.14', '<')
  450. || !version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '4.1.1', '<')
  451. ) {
  452. $this->supported['savepoints'] = true;
  453. }
  454. if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '4.0.11', '<')) {
  455. $this->start_transaction = true;
  456. }
  457. if (!version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
  458. $this->varchar_max_length = 65535;
  459. }
  460. }
  461. return MDB2_OK;
  462. }
  463. // }}}
  464. // {{{ setCharset()
  465. /**
  466. * Set the charset on the current connection
  467. *
  468. * @param string charset
  469. * @param resource connection handle
  470. *
  471. * @return true on success, MDB2 Error Object on failure
  472. */
  473. function setCharset($charset, $connection = null)
  474. {
  475. if (is_null($connection)) {
  476. $connection = $this->getConnection();
  477. if (PEAR::isError($connection)) {
  478. return $connection;
  479. }
  480. }
  481. $query = "SET character_set_client = '".mysql_real_escape_string($charset, $connection)."'";
  482. $result = @mysql_query($query, $connection);
  483. if (!$result) {
  484. return $this->raiseError(null, null, null,
  485. 'Unable to set client charset: '.$charset, __FUNCTION__);
  486. }
  487. return MDB2_OK;
  488. }
  489. // }}}
  490. // {{{ disconnect()
  491. /**
  492. * Log out and disconnect from the database.
  493. *
  494. * @param boolean $force if the disconnect should be forced even if the
  495. * connection is opened persistently
  496. * @return mixed true on success, false if not connected and error
  497. * object on error
  498. * @access public
  499. */
  500. function disconnect($force = true)
  501. {
  502. if (is_resource($this->connection)) {
  503. if ($this->in_transaction) {
  504. $dsn = $this->dsn;
  505. $database_name = $this->database_name;
  506. $persistent = $this->options['persistent'];
  507. $this->dsn = $this->connected_dsn;
  508. $this->database_name = $this->connected_database_name;
  509. $this->options['persistent'] = $this->opened_persistent;
  510. $this->rollback();
  511. $this->dsn = $dsn;
  512. $this->database_name = $database_name;
  513. $this->options['persistent'] = $persistent;
  514. }
  515. if (!$this->opened_persistent || $force) {
  516. @mysql_close($this->connection);
  517. }
  518. }
  519. return parent::disconnect($force);
  520. }
  521. // }}}
  522. // {{{ _doQuery()
  523. /**
  524. * Execute a query
  525. * @param string $query query
  526. * @param boolean $is_manip if the query is a manipulation query
  527. * @param resource $connection
  528. * @param string $database_name
  529. * @return result or error object
  530. * @access protected
  531. */
  532. function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
  533. {
  534. $this->last_query = $query;
  535. $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
  536. if ($result) {
  537. if (PEAR::isError($result)) {
  538. return $result;
  539. }
  540. $query = $result;
  541. }
  542. if ($this->options['disable_query']) {
  543. $result = $is_manip ? 0 : null;
  544. return $result;
  545. }
  546. if (is_null($connection)) {
  547. $connection = $this->getConnection();
  548. if (PEAR::isError($connection)) {
  549. return $connection;
  550. }
  551. }
  552. if (is_null($database_name)) {
  553. $database_name = $this->database_name;
  554. }
  555. if ($database_name) {
  556. if ($database_name != $this->connected_database_name) {
  557. if (!@mysql_select_db($database_name, $connection)) {
  558. $err = $this->raiseError(null, null, null,
  559. 'Could not select the database: '.$database_name, __FUNCTION__);
  560. return $err;
  561. }
  562. $this->connected_database_name = $database_name;
  563. }
  564. }
  565. $function = $this->options['result_buffering']
  566. ? 'mysql_query' : 'mysql_unbuffered_query';
  567. $result = @$function($query, $connection);
  568. if (!$result) {
  569. $err =& $this->raiseError(null, null, null,
  570. 'Could not execute statement', __FUNCTION__);
  571. return $err;
  572. }
  573. $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
  574. return $result;
  575. }
  576. // }}}
  577. // {{{ _affectedRows()
  578. /**
  579. * Returns the number of rows affected
  580. *
  581. * @param resource $result
  582. * @param resource $connection
  583. * @return mixed MDB2 Error Object or the number of rows affected
  584. * @access private
  585. */
  586. function _affectedRows($connection, $result = null)
  587. {
  588. if (is_null($connection)) {
  589. $connection = $this->getConnection();
  590. if (PEAR::isError($connection)) {
  591. return $connection;
  592. }
  593. }
  594. return @mysql_affected_rows($connection);
  595. }
  596. // }}}
  597. // {{{ _modifyQuery()
  598. /**
  599. * Changes a query string for various DBMS specific reasons
  600. *
  601. * @param string $query query to modify
  602. * @param boolean $is_manip if it is a DML query
  603. * @param integer $limit limit the number of rows
  604. * @param integer $offset start reading from given offset
  605. * @return string modified query
  606. * @access protected
  607. */
  608. function _modifyQuery($query, $is_manip, $limit, $offset)
  609. {
  610. if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
  611. // "DELETE FROM table" gives 0 affected rows in MySQL.
  612. // This little hack lets you know how many rows were deleted.
  613. if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
  614. $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
  615. 'DELETE FROM \1 WHERE 1=1', $query);
  616. }
  617. }
  618. if ($limit > 0
  619. && !preg_match('/LIMIT\s*\d(\s*(,|OFFSET)\s*\d+)?/i', $query)
  620. ) {
  621. $query = rtrim($query);
  622. if (substr($query, -1) == ';') {
  623. $query = substr($query, 0, -1);
  624. }
  625. if ($is_manip) {
  626. return $query . " LIMIT $limit";
  627. } else {
  628. return $query . " LIMIT $offset, $limit";
  629. }
  630. }
  631. return $query;
  632. }
  633. // }}}
  634. // {{{ getServerVersion()
  635. /**
  636. * return version information about the server
  637. *
  638. * @param string $native determines if the raw version string should be returned
  639. * @return mixed array/string with version information or MDB2 error object
  640. * @access public
  641. */
  642. function getServerVersion($native = false)
  643. {
  644. $connection = $this->getConnection();
  645. if (PEAR::isError($connection)) {
  646. return $connection;
  647. }
  648. if ($this->connected_server_info) {
  649. $server_info = $this->connected_server_info;
  650. } else {
  651. $server_info = @mysql_get_server_info($connection);
  652. }
  653. if (!$server_info) {
  654. return $this->raiseError(null, null, null,
  655. 'Could not get server information', __FUNCTION__);
  656. }
  657. // cache server_info
  658. $this->connected_server_info = $server_info;
  659. if (!$native) {
  660. $tmp = explode('.', $server_info, 3);
  661. if (isset($tmp[2]) && strpos($tmp[2], '-')) {
  662. $tmp2 = explode('-', @$tmp[2], 2);
  663. } else {
  664. $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;
  665. $tmp2[1] = null;
  666. }
  667. $server_info = array(
  668. 'major' => isset($tmp[0]) ? $tmp[0] : null,
  669. 'minor' => isset($tmp[1]) ? $tmp[1] : null,
  670. 'patch' => $tmp2[0],
  671. 'extra' => $tmp2[1],
  672. 'native' => $server_info,
  673. );
  674. }
  675. return $server_info;
  676. }
  677. // }}}
  678. // {{{ prepare()
  679. /**
  680. * Prepares a query for multiple execution with execute().
  681. * With some database backends, this is emulated.
  682. * prepare() requires a generic query as string like
  683. * 'INSERT INTO numbers VALUES(?,?)' or
  684. * 'INSERT INTO numbers VALUES(:foo,:bar)'.
  685. * The ? and :[a-zA-Z] and are placeholders which can be set using
  686. * bindParam() and the query can be send off using the execute() method.
  687. *
  688. * @param string $query the query to prepare
  689. * @param mixed $types array that contains the types of the placeholders
  690. * @param mixed $result_types array that contains the types of the columns in
  691. * the result set or MDB2_PREPARE_RESULT, if set to
  692. * MDB2_PREPARE_MANIP the query is handled as a manipulation query
  693. * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
  694. * @return mixed resource handle for the prepared query on success, a MDB2
  695. * error on failure
  696. * @access public
  697. * @see bindParam, execute
  698. */
  699. function &prepare($query, $types = null, $result_types = null, $lobs = array())
  700. {
  701. if ($this->options['emulate_prepared']
  702. || $this->supported['prepared_statements'] !== true
  703. ) {
  704. $obj =& parent::prepare($query, $types, $result_types, $lobs);
  705. return $obj;
  706. }
  707. $is_manip = ($result_types === MDB2_PREPARE_MANIP);
  708. $offset = $this->offset;
  709. $limit = $this->limit;
  710. $this->offset = $this->limit = 0;
  711. $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
  712. $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
  713. if ($result) {
  714. if (PEAR::isError($result)) {
  715. return $result;
  716. }
  717. $query = $result;
  718. }
  719. $placeholder_type_guess = $placeholder_type = null;
  720. $question = '?';
  721. $colon = ':';
  722. $positions = array();
  723. $position = 0;
  724. while ($position < strlen($query)) {
  725. $q_position = strpos($query, $question, $position);
  726. $c_position = strpos($query, $colon, $position);
  727. if ($q_position && $c_position) {
  728. $p_position = min($q_position, $c_position);
  729. } elseif ($q_position) {
  730. $p_position = $q_position;
  731. } elseif ($c_position) {
  732. $p_position = $c_position;
  733. } else {
  734. break;
  735. }
  736. if (is_null($placeholder_type)) {
  737. $placeholder_type_guess = $query[$p_position];
  738. }
  739. if (is_int($quote = strpos($query, "'", $position)) && $quote < $p_position) {
  740. if (!is_int($end_quote = strpos($query, "'", $quote + 1))) {
  741. $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  742. 'query with an unterminated text string specified', __FUNCTION__);
  743. return $err;
  744. }
  745. switch ($this->escape_quotes) {
  746. case '':
  747. case "'":
  748. $position = $end_quote + 1;
  749. break;
  750. default:
  751. if ($end_quote == $quote + 1) {
  752. $position = $end_quote + 1;
  753. } else {
  754. if ($query[$end_quote-1] == $this->escape_quotes) {
  755. $position = $end_quote;
  756. } else {
  757. $position = $end_quote + 1;
  758. }
  759. }
  760. break;
  761. }
  762. } elseif ($query[$position] == $placeholder_type_guess) {
  763. if (is_null($placeholder_type)) {
  764. $placeholder_type = $query[$p_position];
  765. $question = $colon = $placeholder_type;
  766. }
  767. if ($placeholder_type == ':') {
  768. $parameter = preg_replace('/^.{'.($position+1).'}([a-z0-9_]+).*$/si', '\\1', $query);
  769. if ($parameter === '') {
  770. $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  771. 'named parameter with an empty name', __FUNCTION__);
  772. return $err;
  773. } elseif (isset($positions[$parameter])) {
  774. $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
  775. 'named parameter names can only be used once per statement', __FUNCTION__);
  776. return $err;
  777. }
  778. $positions[$parameter] = $p_position;
  779. $query = substr_replace($query, '?', $position, strlen($parameter)+1);
  780. } else {
  781. $positions[] = $p_position;
  782. }
  783. $position = $p_position + 1;
  784. } else {
  785. $position = $p_position;
  786. }
  787. }
  788. $connection = $this->getConnection();
  789. if (PEAR::isError($connection)) {
  790. return $connection;
  791. }
  792. $statement_name = 'MDB2_Statement_'.$this->phptype.'_'.md5(time() + rand());
  793. $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text');
  794. $statement =& $this->_doQuery($query, true, $connection);
  795. if (PEAR::isError($statement)) {
  796. return $statement;
  797. }
  798. $class_name = 'MDB2_Statement_'.$this->phptype;
  799. $obj =& new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
  800. $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
  801. return $obj;
  802. }
  803. // }}}
  804. // {{{ replace()
  805. /**
  806. * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
  807. * query, except that if there is already a row in the table with the same
  808. * key field values, the REPLACE query just updates its values instead of
  809. * inserting a new row.
  810. *
  811. * The REPLACE type of query does not make part of the SQL standards. Since
  812. * practically only MySQL implements it natively, this type of query is
  813. * emulated through this method for other DBMS using standard types of
  814. * queries inside a transaction to assure the atomicity of the operation.
  815. *
  816. * @access public
  817. *
  818. * @param string $table name of the table on which the REPLACE query will
  819. * be executed.
  820. * @param array $fields associative array that describes the fields and the
  821. * values that will be inserted or updated in the specified table. The
  822. * indexes of the array are the names of all the fields of the table. The
  823. * values of the array are also associative arrays that describe the
  824. * values and other properties of the table fields.
  825. *
  826. * Here follows a list of field properties that need to be specified:
  827. *
  828. * value:
  829. * Value to be assigned to the specified field. This value may be
  830. * of specified in database independent type format as this
  831. * function can perform the necessary datatype conversions.
  832. *
  833. * Default:
  834. * this property is required unless the Null property
  835. * is set to 1.
  836. *
  837. * type
  838. * Name of the type of the field. Currently, all types Metabase
  839. * are supported except for clob and blob.
  840. *
  841. * Default: no type conversion
  842. *
  843. * null
  844. * Boolean property that indicates that the value for this field
  845. * should be set to null.
  846. *
  847. * The default value for fields missing in INSERT queries may be
  848. * specified the definition of a table. Often, the default value
  849. * is already null, but since the REPLACE may be emulated using
  850. * an UPDATE query, make sure that all fields of the table are
  851. * listed in this function argument array.
  852. *
  853. * Default: 0
  854. *
  855. * key
  856. * Boolean property that indicates that this field should be
  857. * handled as a primary key or at least as part of the compound
  858. * unique index of the table that will determine the row that will
  859. * updated if it exists or inserted a new row otherwise.
  860. *
  861. * This function will fail if no key field is specified or if the
  862. * value of a key field is set to null because fields that are
  863. * part of unique index they may not be null.
  864. *
  865. * Default: 0
  866. *
  867. * @return mixed MDB2_OK on success, a MDB2 error on failure
  868. */
  869. function replace($table, $fields)
  870. {
  871. $count = count($fields);
  872. $query = $values = '';
  873. $keys = $colnum = 0;
  874. for (reset($fields); $colnum < $count; next($fields), $colnum++) {
  875. $name = key($fields);
  876. if ($colnum > 0) {
  877. $query .= ',';
  878. $values.= ',';
  879. }
  880. $query.= $name;
  881. if (isset($fields[$name]['null']) && $fields[$name]['null']) {
  882. $value = 'NULL';
  883. } else {
  884. $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
  885. $value = $this->quote($fields[$name]['value'], $type);
  886. }
  887. $values.= $value;
  888. if (isset($fields[$name]['key']) && $fields[$name]['key']) {
  889. if ($value === 'NULL') {
  890. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  891. 'key value '.$name.' may not be NULL', __FUNCTION__);
  892. }
  893. $keys++;
  894. }
  895. }
  896. if ($keys == 0) {
  897. return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
  898. 'not specified which fields are keys', __FUNCTION__);
  899. }
  900. $connection = $this->getConnection();
  901. if (PEAR::isError($connection)) {
  902. return $connection;
  903. }
  904. $query = "REPLACE INTO $table ($query) VALUES ($values)";
  905. $result =& $this->_doQuery($query, true, $connection);
  906. if (PEAR::isError($result)) {
  907. return $result;
  908. }
  909. return $this->_affectedRows($connection, $result);
  910. }
  911. // }}}
  912. // {{{ nextID()
  913. /**
  914. * Returns the next free id of a sequence
  915. *
  916. * @param string $seq_name name of the sequence
  917. * @param boolean $ondemand when true the sequence is
  918. * automatic created, if it
  919. * not exists
  920. *
  921. * @return mixed MDB2 Error Object or id
  922. * @access public
  923. */
  924. function nextID($seq_name, $ondemand = true)
  925. {
  926. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  927. $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
  928. $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
  929. $this->expectError(MDB2_ERROR_NOSUCHTABLE);
  930. $result =& $this->_doQuery($query, true);
  931. $this->popExpect();
  932. if (PEAR::isError($result)) {
  933. if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
  934. $this->loadModule('Manager', null, true);
  935. // Since we are creating the sequence on demand
  936. // we know the first id = 1 so initialize the
  937. // sequence at 2
  938. $result = $this->manager->createSequence($seq_name, 2);
  939. if (PEAR::isError($result)) {
  940. return $this->raiseError($result, null, null,
  941. 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
  942. } else {
  943. // First ID of a newly created sequence is 1
  944. return 1;
  945. }
  946. }
  947. return $result;
  948. }
  949. $value = $this->lastInsertID();
  950. if (is_numeric($value)) {
  951. $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
  952. $result =& $this->_doQuery($query, true);
  953. if (PEAR::isError($result)) {
  954. $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
  955. }
  956. }
  957. return $value;
  958. }
  959. // }}}
  960. // {{{ lastInsertID()
  961. /**
  962. * Returns the autoincrement ID if supported or $id or fetches the current
  963. * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
  964. *
  965. * @param string $table name of the table into which a new row was inserted
  966. * @param string $field name of the field into which a new row was inserted
  967. * @return mixed MDB2 Error Object or id
  968. * @access public
  969. */
  970. function lastInsertID($table = null, $field = null)
  971. {
  972. // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
  973. return $this->queryOne('SELECT LAST_INSERT_ID()', 'integer');
  974. }
  975. // }}}
  976. // {{{ currID()
  977. /**
  978. * Returns the current id of a sequence
  979. *
  980. * @param string $seq_name name of the sequence
  981. * @return mixed MDB2 Error Object or id
  982. * @access public
  983. */
  984. function currID($seq_name)
  985. {
  986. $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
  987. $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
  988. $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
  989. return $this->queryOne($query, 'integer');
  990. }
  991. }
  992. /**
  993. * MDB2 MySQL result driver
  994. *
  995. * @package MDB2
  996. * @category Database
  997. * @author Lukas Smith <smith@pooteeweet.org>
  998. */
  999. class MDB2_Result_mysql extends MDB2_Result_Common
  1000. {
  1001. // }}}
  1002. // {{{ fetchRow()
  1003. /**
  1004. * Fetch a row and insert the data into an existing array.
  1005. *
  1006. * @param int $fetchmode how the array data should be indexed
  1007. * @param int $rownum number of the row where the data can be found
  1008. * @return int data array on success, a MDB2 error on failure
  1009. * @access public
  1010. */
  1011. function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
  1012. {
  1013. if (!is_null($rownum)) {
  1014. $seek = $this->seek($rownum);
  1015. if (PEAR::isError($seek)) {
  1016. return $seek;
  1017. }
  1018. }
  1019. if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
  1020. $fetchmode = $this->db->fetchmode;
  1021. }
  1022. if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
  1023. $row = @mysql_fetch_assoc($this->result);
  1024. if (is_array($row)
  1025. && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
  1026. ) {
  1027. $row = array_change_key_case($row, $this->db->options['field_case']);
  1028. }
  1029. } else {
  1030. $row = @mysql_fetch_row($this->result);
  1031. }
  1032. if (!$row) {
  1033. if ($this->result === false) {
  1034. $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1035. 'resultset has already been freed', __FUNCTION__);
  1036. return $err;
  1037. }
  1038. $null = null;
  1039. return $null;
  1040. }
  1041. $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
  1042. if ($mode) {
  1043. $this->db->_fixResultArrayValues($row, $mode);
  1044. }
  1045. if (!empty($this->types)) {
  1046. $row = $this->db->datatype->convertResultRow($this->types, $row, false);
  1047. }
  1048. if (!empty($this->values)) {
  1049. $this->_assignBindColumns($row);
  1050. }
  1051. if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
  1052. $object_class = $this->db->options['fetch_class'];
  1053. if ($object_class == 'stdClass') {
  1054. $row = (object) $row;
  1055. } else {
  1056. $row = &new $object_class($row);
  1057. }
  1058. }
  1059. ++$this->rownum;
  1060. return $row;
  1061. }
  1062. // }}}
  1063. // {{{ _getColumnNames()
  1064. /**
  1065. * Retrieve the names of columns returned by the DBMS in a query result.
  1066. *
  1067. * @return mixed Array variable that holds the names of columns as keys
  1068. * or an MDB2 error on failure.
  1069. * Some DBMS may not return any columns when the result set
  1070. * does not contain any rows.
  1071. * @access private
  1072. */
  1073. function _getColumnNames()
  1074. {
  1075. $columns = array();
  1076. $numcols = $this->numCols();
  1077. if (PEAR::isError($numcols)) {
  1078. return $numcols;
  1079. }
  1080. for ($column = 0; $column < $numcols; $column++) {
  1081. $column_name = @mysql_field_name($this->result, $column);
  1082. $columns[$column_name] = $column;
  1083. }
  1084. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1085. $columns = array_change_key_case($columns, $this->db->options['field_case']);
  1086. }
  1087. return $columns;
  1088. }
  1089. // }}}
  1090. // {{{ numCols()
  1091. /**
  1092. * Count the number of columns returned by the DBMS in a query result.
  1093. *
  1094. * @return mixed integer value with the number of columns, a MDB2 error
  1095. * on failure
  1096. * @access public
  1097. */
  1098. function numCols()
  1099. {
  1100. $cols = @mysql_num_fields($this->result);
  1101. if (is_null($cols)) {
  1102. if ($this->result === false) {
  1103. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1104. 'resultset has already been freed', __FUNCTION__);
  1105. } elseif (is_null($this->result)) {
  1106. return count($this->types);
  1107. }
  1108. return $this->db->raiseError(null, null, null,
  1109. 'Could not get column count', __FUNCTION__);
  1110. }
  1111. return $cols;
  1112. }
  1113. // }}}
  1114. // {{{ free()
  1115. /**
  1116. * Free the internal resources associated with result.
  1117. *
  1118. * @return boolean true on success, false if result is invalid
  1119. * @access public
  1120. */
  1121. function free()
  1122. {
  1123. if (is_resource($this->result) && $this->db->connection) {
  1124. $free = @mysql_free_result($this->result);
  1125. if ($free === false) {
  1126. return $this->db->raiseError(null, null, null,
  1127. 'Could not free result', __FUNCTION__);
  1128. }
  1129. }
  1130. $this->result = false;
  1131. return MDB2_OK;
  1132. }
  1133. }
  1134. /**
  1135. * MDB2 MySQL buffered result driver
  1136. *
  1137. * @package MDB2
  1138. * @category Database
  1139. * @author Lukas Smith <smith@pooteeweet.org>
  1140. */
  1141. class MDB2_BufferedResult_mysql extends MDB2_Result_mysql
  1142. {
  1143. // }}}
  1144. // {{{ seek()
  1145. /**
  1146. * Seek to a specific row in a result set
  1147. *
  1148. * @param int $rownum number of the row where the data can be found
  1149. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1150. * @access public
  1151. */
  1152. function seek($rownum = 0)
  1153. {
  1154. if ($this->rownum != ($rownum - 1) && !@mysql_data_seek($this->result, $rownum)) {
  1155. if ($this->result === false) {
  1156. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1157. 'resultset has already been freed', __FUNCTION__);
  1158. } elseif (is_null($this->result)) {
  1159. return MDB2_OK;
  1160. }
  1161. return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
  1162. 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
  1163. }
  1164. $this->rownum = $rownum - 1;
  1165. return MDB2_OK;
  1166. }
  1167. // }}}
  1168. // {{{ valid()
  1169. /**
  1170. * Check if the end of the result set has been reached
  1171. *
  1172. * @return mixed true or false on sucess, a MDB2 error on failure
  1173. * @access public
  1174. */
  1175. function valid()
  1176. {
  1177. $numrows = $this->numRows();
  1178. if (PEAR::isError($numrows)) {
  1179. return $numrows;
  1180. }
  1181. return $this->rownum < ($numrows - 1);
  1182. }
  1183. // }}}
  1184. // {{{ numRows()
  1185. /**
  1186. * Returns the number of rows in a result object
  1187. *
  1188. * @return mixed MDB2 Error Object or the number of rows
  1189. * @access public
  1190. */
  1191. function numRows()
  1192. {
  1193. $rows = @mysql_num_rows($this->result);
  1194. if (is_null($rows)) {
  1195. if ($this->result === false) {
  1196. return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
  1197. 'resultset has already been freed', __FUNCTION__);
  1198. } elseif (is_null($this->result)) {
  1199. return 0;
  1200. }
  1201. return $this->db->raiseError(null, null, null,
  1202. 'Could not get row count', __FUNCTION__);
  1203. }
  1204. return $rows;
  1205. }
  1206. }
  1207. /**
  1208. * MDB2 MySQL statement driver
  1209. *
  1210. * @package MDB2
  1211. * @category Database
  1212. * @author Lukas Smith <smith@pooteeweet.org>
  1213. */
  1214. class MDB2_Statement_mysql extends MDB2_Statement_Common
  1215. {
  1216. // {{{ _execute()
  1217. /**
  1218. * Execute a prepared query statement helper method.
  1219. *
  1220. * @param mixed $result_class string which specifies which result class to use
  1221. * @param mixed $result_wrap_class string which specifies which class to wrap results in
  1222. * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  1223. * @access private
  1224. */
  1225. function &_execute($result_class = true, $result_wrap_class = false)
  1226. {
  1227. if (is_null($this->statement)) {
  1228. $result =& parent::_execute($result_class, $result_wrap_class);
  1229. return $result;
  1230. }
  1231. $this->db->last_query = $this->query;
  1232. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
  1233. if ($this->db->getOption('disable_query')) {
  1234. $result = $this->is_manip ? 0 : null;
  1235. return $result;
  1236. }
  1237. $connection = $this->db->getConnection();
  1238. if (PEAR::isError($connection)) {
  1239. return $connection;
  1240. }
  1241. $query = 'EXECUTE '.$this->statement;
  1242. if (!empty($this->positions)) {
  1243. $parameters = array();
  1244. foreach ($this->positions as $parameter => $current_position) {
  1245. if (!array_key_exists($parameter, $this->values)) {
  1246. return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
  1247. 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
  1248. }
  1249. $value = $this->values[$parameter];
  1250. $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
  1251. if (is_resource($value) || $type == 'clob' || $type == 'blob') {
  1252. if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
  1253. if ($match[1] == 'file://') {
  1254. $value = $match[2];
  1255. }
  1256. $value = @fopen($value, 'r');
  1257. $close = true;
  1258. }
  1259. if (is_resource($value)) {
  1260. $data = '';
  1261. while (!@feof($value)) {
  1262. $data.= @fread($value, $this->db->options['lob_buffer_length']);
  1263. }
  1264. if ($close) {
  1265. @fclose($value);
  1266. }
  1267. $value = $data;
  1268. }
  1269. }
  1270. $param_query = 'SET @'.$parameter.' = '.$this->db->quote($value, $type);
  1271. $result = $this->db->_doQuery($param_query, true, $connection);
  1272. if (PEAR::isError($result)) {
  1273. return $result;
  1274. }
  1275. }
  1276. $query.= ' USING @'.implode(', @', array_keys($this->positions));
  1277. }
  1278. $result = $this->db->_doQuery($query, $this->is_manip, $connection);
  1279. if (PEAR::isError($result)) {
  1280. return $result;
  1281. }
  1282. if ($this->is_manip) {
  1283. $affected_rows = $this->db->_affectedRows($connection, $result);
  1284. return $affected_rows;
  1285. }
  1286. $result =& $this->db->_wrapResult($result, $this->result_types,
  1287. $result_class, $result_wrap_class, $this->limit, $this->offset);
  1288. $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
  1289. return $result;
  1290. }
  1291. // }}}
  1292. // {{{ free()
  1293. /**
  1294. * Release resources allocated for the specified prepared query.
  1295. *
  1296. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1297. * @access public
  1298. */
  1299. function free()
  1300. {
  1301. if (is_null($this->positions)) {
  1302. return $this->db->raiseError(MDB2_ERROR, null, null,
  1303. 'Prepared statement has already been freed', __FUNCTION__);
  1304. }
  1305. $result = MDB2_OK;
  1306. if (!is_null($this->statement)) {
  1307. $connection = $this->db->getConnection();
  1308. if (PEAR::isError($connection)) {
  1309. return $connection;
  1310. }
  1311. $query = 'DEALLOCATE PREPARE '.$this->statement;
  1312. $result = $this->db->_doQuery($query, true, $connection);
  1313. }
  1314. parent::free();
  1315. return $result;
  1316. }
  1317. }
  1318. ?>