PageRenderTime 66ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/common/libraries/plugin/pear/MDB2/Driver/Manager/mysqli.php

https://bitbucket.org/renaatdemuynck/chamilo
PHP | 1643 lines | 982 code | 161 blank | 500 comment | 181 complexity | 3f09d48c98249ffafa736120c8552d2e MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1, LGPL-3.0, GPL-3.0, MIT, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. // +----------------------------------------------------------------------+
  3. // | PHP versions 4 and 5 |
  4. // +----------------------------------------------------------------------+
  5. // | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
  6. // | Stig. S. Bakken, Lukas Smith |
  7. // | All rights reserved. |
  8. // +----------------------------------------------------------------------+
  9. // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
  10. // | API as well as database abstraction for PHP applications. |
  11. // | This LICENSE is in the BSD license style. |
  12. // | |
  13. // | Redistribution and use in source and binary forms, with or without |
  14. // | modification, are permitted provided that the following conditions |
  15. // | are met: |
  16. // | |
  17. // | Redistributions of source code must retain the above copyright |
  18. // | notice, this list of conditions and the following disclaimer. |
  19. // | |
  20. // | Redistributions in binary form must reproduce the above copyright |
  21. // | notice, this list of conditions and the following disclaimer in the |
  22. // | documentation and/or other materials provided with the distribution. |
  23. // | |
  24. // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
  25. // | Lukas Smith nor the names of his contributors may be used to endorse |
  26. // | or promote products derived from this software without specific prior|
  27. // | written permission. |
  28. // | |
  29. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
  30. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
  31. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
  32. // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
  33. // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
  34. // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
  35. // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
  36. // | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
  37. // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
  38. // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
  39. // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
  40. // | POSSIBILITY OF SUCH DAMAGE. |
  41. // +----------------------------------------------------------------------+
  42. // | Author: Lukas Smith <smith@pooteeweet.org> |
  43. // +----------------------------------------------------------------------+
  44. //
  45. // $Id: mysqli.php 137 2009-11-09 13:24:37Z vanpouckesven $
  46. //
  47. require_once 'MDB2/Driver/Manager/Common.php';
  48. /**
  49. * MDB2 MySQLi driver for the management modules
  50. *
  51. * @package MDB2
  52. * @category Database
  53. * @author Lukas Smith <smith@pooteeweet.org>
  54. */
  55. class MDB2_Driver_Manager_mysqli extends MDB2_Driver_Manager_Common
  56. {
  57. // }}}
  58. // {{{ createDatabase()
  59. /**
  60. * create a new database
  61. *
  62. * @param string $name name of the database that should be created
  63. * @param array $options array with charset, collation info
  64. *
  65. * @return mixed MDB2_OK on success, a MDB2 error on failure
  66. * @access public
  67. */
  68. function createDatabase($name, $options = array())
  69. {
  70. $db = & $this->getDBInstance();
  71. if (PEAR :: isError($db))
  72. {
  73. return $db;
  74. }
  75. $name = $db->quoteIdentifier($name, true);
  76. $query = 'CREATE DATABASE ' . $name;
  77. if (! empty($options['charset']))
  78. {
  79. $query .= ' DEFAULT CHARACTER SET ' . $db->quote($options['charset'], 'text');
  80. }
  81. if (! empty($options['collation']))
  82. {
  83. $query .= ' COLLATE ' . $db->quote($options['collation'], 'text');
  84. }
  85. return $db->standaloneQuery($query, null, true);
  86. }
  87. // }}}
  88. // {{{ alterDatabase()
  89. /**
  90. * alter an existing database
  91. *
  92. * @param string $name name of the database that is intended to be changed
  93. * @param array $options array with charset, collation info
  94. *
  95. * @return mixed MDB2_OK on success, a MDB2 error on failure
  96. * @access public
  97. */
  98. function alterDatabase($name, $options = array())
  99. {
  100. $db = & $this->getDBInstance();
  101. if (PEAR :: isError($db))
  102. {
  103. return $db;
  104. }
  105. $query = 'ALTER DATABASE ' . $db->quoteIdentifier($name, true);
  106. if (! empty($options['charset']))
  107. {
  108. $query .= ' DEFAULT CHARACTER SET ' . $db->quote($options['charset'], 'text');
  109. }
  110. if (! empty($options['collation']))
  111. {
  112. $query .= ' COLLATE ' . $db->quote($options['collation'], 'text');
  113. }
  114. return $db->standaloneQuery($query, null, true);
  115. }
  116. // }}}
  117. // {{{ dropDatabase()
  118. /**
  119. * drop an existing database
  120. *
  121. * @param string $name name of the database that should be dropped
  122. * @return mixed MDB2_OK on success, a MDB2 error on failure
  123. * @access public
  124. */
  125. function dropDatabase($name)
  126. {
  127. $db = & $this->getDBInstance();
  128. if (PEAR :: isError($db))
  129. {
  130. return $db;
  131. }
  132. $name = $db->quoteIdentifier($name, true);
  133. $query = "DROP DATABASE $name";
  134. return $db->standaloneQuery($query, null, true);
  135. }
  136. // }}}
  137. // {{{ _getAdvancedFKOptions()
  138. /**
  139. * Return the FOREIGN KEY query section dealing with non-standard options
  140. * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
  141. *
  142. * @param array $definition
  143. * @return string
  144. * @access protected
  145. */
  146. function _getAdvancedFKOptions($definition)
  147. {
  148. $query = '';
  149. if (! empty($definition['match']))
  150. {
  151. $query .= ' MATCH ' . $definition['match'];
  152. }
  153. if (! empty($definition['onupdate']))
  154. {
  155. $query .= ' ON UPDATE ' . $definition['onupdate'];
  156. }
  157. if (! empty($definition['ondelete']))
  158. {
  159. $query .= ' ON DELETE ' . $definition['ondelete'];
  160. }
  161. return $query;
  162. }
  163. // }}}
  164. // {{{ createTable()
  165. /**
  166. * create a new table
  167. *
  168. * @param string $name Name of the database that should be created
  169. * @param array $fields Associative array that contains the definition of each field of the new table
  170. * The indexes of the array entries are the names of the fields of the table an
  171. * the array entry values are associative arrays like those that are meant to be
  172. * passed with the field definitions to get[Type]Declaration() functions.
  173. * array(
  174. * 'id' => array(
  175. * 'type' => 'integer',
  176. * 'unsigned' => 1
  177. * 'notnull' => 1
  178. * 'default' => 0
  179. * ),
  180. * 'name' => array(
  181. * 'type' => 'text',
  182. * 'length' => 12
  183. * ),
  184. * 'password' => array(
  185. * 'type' => 'text',
  186. * 'length' => 12
  187. * )
  188. * );
  189. * @param array $options An associative array of table options:
  190. * array(
  191. * 'comment' => 'Foo',
  192. * 'charset' => 'utf8',
  193. * 'collate' => 'utf8_unicode_ci',
  194. * 'type' => 'innodb',
  195. * );
  196. *
  197. * @return mixed MDB2_OK on success, a MDB2 error on failure
  198. * @access public
  199. */
  200. function createTable($name, $fields, $options = array())
  201. {
  202. $db = & $this->getDBInstance();
  203. if (PEAR :: isError($db))
  204. {
  205. return $db;
  206. }
  207. // if we have an AUTO_INCREMENT column and a PK on more than one field,
  208. // we have to handle it differently...
  209. $autoincrement = null;
  210. if (empty($options['primary']))
  211. {
  212. $pk_fields = array();
  213. foreach ($fields as $fieldname => $def)
  214. {
  215. if (! empty($def['primary']))
  216. {
  217. $pk_fields[$fieldname] = true;
  218. }
  219. if (! empty($def['autoincrement']))
  220. {
  221. $autoincrement = $fieldname;
  222. }
  223. }
  224. if (! is_null($autoincrement) && count($pk_fields) > 1)
  225. {
  226. $options['primary'] = $pk_fields;
  227. }
  228. else
  229. {
  230. // the PK constraint is on max one field => OK
  231. $autoincrement = null;
  232. }
  233. }
  234. $query = $this->_getCreateTableQuery($name, $fields, $options);
  235. if (PEAR :: isError($query))
  236. {
  237. return $query;
  238. }
  239. if (! is_null($autoincrement))
  240. {
  241. // we have to remove the PK clause added by _getIntegerDeclaration()
  242. $query = str_replace('AUTO_INCREMENT PRIMARY KEY', 'AUTO_INCREMENT', $query);
  243. }
  244. $options_strings = array();
  245. if (! empty($options['comment']))
  246. {
  247. $options_strings['comment'] = 'COMMENT = ' . $db->quote($options['comment'], 'text');
  248. }
  249. if (! empty($options['charset']))
  250. {
  251. $options_strings['charset'] = 'DEFAULT CHARACTER SET ' . $options['charset'];
  252. if (! empty($options['collate']))
  253. {
  254. $options_strings['charset'] .= ' COLLATE ' . $options['collate'];
  255. }
  256. }
  257. $type = false;
  258. if (! empty($options['type']))
  259. {
  260. $type = $options['type'];
  261. }
  262. elseif ($db->options['default_table_type'])
  263. {
  264. $type = $db->options['default_table_type'];
  265. }
  266. if ($type)
  267. {
  268. $options_strings[] = "ENGINE = $type";
  269. }
  270. if (! empty($options_strings))
  271. {
  272. $query .= ' ' . implode(' ', $options_strings);
  273. }
  274. $result = $db->exec($query);
  275. if (PEAR :: isError($result))
  276. {
  277. return $result;
  278. }
  279. return MDB2_OK;
  280. }
  281. // }}}
  282. // {{{ dropTable()
  283. /**
  284. * drop an existing table
  285. *
  286. * @param string $name name of the table that should be dropped
  287. * @return mixed MDB2_OK on success, a MDB2 error on failure
  288. * @access public
  289. */
  290. function dropTable($name)
  291. {
  292. $db = & $this->getDBInstance();
  293. if (PEAR :: isError($db))
  294. {
  295. return $db;
  296. }
  297. //delete the triggers associated to existing FK constraints
  298. $constraints = $this->listTableConstraints($name);
  299. if (! PEAR :: isError($constraints) && ! empty($constraints))
  300. {
  301. $db->loadModule('Reverse', null, true);
  302. foreach ($constraints as $constraint)
  303. {
  304. $definition = $db->reverse->getTableConstraintDefinition($name, $constraint);
  305. if (! PEAR :: isError($definition) && ! empty($definition['foreign']))
  306. {
  307. $result = $this->_dropFKTriggers($name, $constraint, $definition['references']['table']);
  308. if (PEAR :: isError($result))
  309. {
  310. return $result;
  311. }
  312. }
  313. }
  314. }
  315. return parent :: dropTable($name);
  316. }
  317. // }}}
  318. // {{{ truncateTable()
  319. /**
  320. * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,
  321. * it falls back to a DELETE FROM TABLE query)
  322. *
  323. * @param string $name name of the table that should be truncated
  324. * @return mixed MDB2_OK on success, a MDB2 error on failure
  325. * @access public
  326. */
  327. function truncateTable($name)
  328. {
  329. $db = & $this->getDBInstance();
  330. if (PEAR :: isError($db))
  331. {
  332. return $db;
  333. }
  334. $name = $db->quoteIdentifier($name, true);
  335. return $db->exec("TRUNCATE TABLE $name");
  336. }
  337. // }}}
  338. // {{{ vacuum()
  339. /**
  340. * Optimize (vacuum) all the tables in the db (or only the specified table)
  341. * and optionally run ANALYZE.
  342. *
  343. * @param string $table table name (all the tables if empty)
  344. * @param array $options an array with driver-specific options:
  345. * - timeout [int] (in seconds) [mssql-only]
  346. * - analyze [boolean] [pgsql and mysql]
  347. * - full [boolean] [pgsql-only]
  348. * - freeze [boolean] [pgsql-only]
  349. *
  350. * @return mixed MDB2_OK success, a MDB2 error on failure
  351. * @access public
  352. */
  353. function vacuum($table = null, $options = array())
  354. {
  355. $db = & $this->getDBInstance();
  356. if (PEAR :: isError($db))
  357. {
  358. return $db;
  359. }
  360. if (empty($table))
  361. {
  362. $table = $this->listTables();
  363. if (PEAR :: isError($table))
  364. {
  365. return $table;
  366. }
  367. }
  368. if (is_array($table))
  369. {
  370. foreach (array_keys($table) as $k)
  371. {
  372. $table[$k] = $db->quoteIdentifier($table[$k], true);
  373. }
  374. $table = implode(', ', $table);
  375. }
  376. else
  377. {
  378. $table = $db->quoteIdentifier($table, true);
  379. }
  380. $result = $db->exec('OPTIMIZE TABLE ' . $table);
  381. if (PEAR :: isError($result))
  382. {
  383. return $result;
  384. }
  385. if (! empty($options['analyze']))
  386. {
  387. return $db->exec('ANALYZE TABLE ' . $table);
  388. }
  389. return MDB2_OK;
  390. }
  391. // }}}
  392. // {{{ alterTable()
  393. /**
  394. * alter an existing table
  395. *
  396. * @param string $name name of the table that is intended to be changed.
  397. * @param array $changes associative array that contains the details of each type
  398. * of change that is intended to be performed. The types of
  399. * changes that are currently supported are defined as follows:
  400. *
  401. * name
  402. *
  403. * New name for the table.
  404. *
  405. * add
  406. *
  407. * Associative array with the names of fields to be added as
  408. * indexes of the array. The value of each entry of the array
  409. * should be set to another associative array with the properties
  410. * of the fields to be added. The properties of the fields should
  411. * be the same as defined by the MDB2 parser.
  412. *
  413. *
  414. * remove
  415. *
  416. * Associative array with the names of fields to be removed as indexes
  417. * of the array. Currently the values assigned to each entry are ignored.
  418. * An empty array should be used for future compatibility.
  419. *
  420. * rename
  421. *
  422. * Associative array with the names of fields to be renamed as indexes
  423. * of the array. The value of each entry of the array should be set to
  424. * another associative array with the entry named name with the new
  425. * field name and the entry named Declaration that is expected to contain
  426. * the portion of the field declaration already in DBMS specific SQL code
  427. * as it is used in the CREATE TABLE statement.
  428. *
  429. * change
  430. *
  431. * Associative array with the names of the fields to be changed as indexes
  432. * of the array. Keep in mind that if it is intended to change either the
  433. * name of a field and any other properties, the change array entries
  434. * should have the new names of the fields as array indexes.
  435. *
  436. * The value of each entry of the array should be set to another associative
  437. * array with the properties of the fields to that are meant to be changed as
  438. * array entries. These entries should be assigned to the new values of the
  439. * respective properties. The properties of the fields should be the same
  440. * as defined by the MDB2 parser.
  441. *
  442. * Example
  443. * array(
  444. * 'name' => 'userlist',
  445. * 'add' => array(
  446. * 'quota' => array(
  447. * 'type' => 'integer',
  448. * 'unsigned' => 1
  449. * )
  450. * ),
  451. * 'remove' => array(
  452. * 'file_limit' => array(),
  453. * 'time_limit' => array()
  454. * ),
  455. * 'change' => array(
  456. * 'name' => array(
  457. * 'length' => '20',
  458. * 'definition' => array(
  459. * 'type' => 'text',
  460. * 'length' => 20,
  461. * ),
  462. * )
  463. * ),
  464. * 'rename' => array(
  465. * 'sex' => array(
  466. * 'name' => 'gender',
  467. * 'definition' => array(
  468. * 'type' => 'text',
  469. * 'length' => 1,
  470. * 'default' => 'M',
  471. * ),
  472. * )
  473. * )
  474. * )
  475. *
  476. * @param boolean $check indicates whether the function should just check if the DBMS driver
  477. * can perform the requested table alterations if the value is true or
  478. * actually perform them otherwise.
  479. * @access public
  480. *
  481. * @return mixed MDB2_OK on success, a MDB2 error on failure
  482. */
  483. function alterTable($name, $changes, $check)
  484. {
  485. $db = & $this->getDBInstance();
  486. if (PEAR :: isError($db))
  487. {
  488. return $db;
  489. }
  490. foreach ($changes as $change_name => $change)
  491. {
  492. switch ($change_name)
  493. {
  494. case 'add' :
  495. case 'remove' :
  496. case 'change' :
  497. case 'rename' :
  498. case 'name' :
  499. break;
  500. default :
  501. return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null, 'change type "' . $change_name . '" not yet supported', __FUNCTION__);
  502. }
  503. }
  504. if ($check)
  505. {
  506. return MDB2_OK;
  507. }
  508. $query = '';
  509. if (! empty($changes['name']))
  510. {
  511. $change_name = $db->quoteIdentifier($changes['name'], true);
  512. $query .= 'RENAME TO ' . $change_name;
  513. }
  514. if (! empty($changes['add']) && is_array($changes['add']))
  515. {
  516. foreach ($changes['add'] as $field_name => $field)
  517. {
  518. if ($query)
  519. {
  520. $query .= ', ';
  521. }
  522. $query .= 'ADD ' . $db->getDeclaration($field['type'], $field_name, $field);
  523. }
  524. }
  525. if (! empty($changes['remove']) && is_array($changes['remove']))
  526. {
  527. foreach ($changes['remove'] as $field_name => $field)
  528. {
  529. if ($query)
  530. {
  531. $query .= ', ';
  532. }
  533. $field_name = $db->quoteIdentifier($field_name, true);
  534. $query .= 'DROP ' . $field_name;
  535. }
  536. }
  537. $rename = array();
  538. if (! empty($changes['rename']) && is_array($changes['rename']))
  539. {
  540. foreach ($changes['rename'] as $field_name => $field)
  541. {
  542. $rename[$field['name']] = $field_name;
  543. }
  544. }
  545. if (! empty($changes['change']) && is_array($changes['change']))
  546. {
  547. foreach ($changes['change'] as $field_name => $field)
  548. {
  549. if ($query)
  550. {
  551. $query .= ', ';
  552. }
  553. if (isset($rename[$field_name]))
  554. {
  555. $old_field_name = $rename[$field_name];
  556. unset($rename[$field_name]);
  557. }
  558. else
  559. {
  560. $old_field_name = $field_name;
  561. }
  562. $old_field_name = $db->quoteIdentifier($old_field_name, true);
  563. $query .= "CHANGE $old_field_name " . $db->getDeclaration($field['definition']['type'], $field_name, $field['definition']);
  564. }
  565. }
  566. if (! empty($rename) && is_array($rename))
  567. {
  568. foreach ($rename as $rename_name => $renamed_field)
  569. {
  570. if ($query)
  571. {
  572. $query .= ', ';
  573. }
  574. $field = $changes['rename'][$renamed_field];
  575. $renamed_field = $db->quoteIdentifier($renamed_field, true);
  576. $query .= 'CHANGE ' . $renamed_field . ' ' . $db->getDeclaration($field['definition']['type'], $field['name'], $field['definition']);
  577. }
  578. }
  579. if (! $query)
  580. {
  581. return MDB2_OK;
  582. }
  583. $name = $db->quoteIdentifier($name, true);
  584. return $db->exec("ALTER TABLE $name $query");
  585. }
  586. // }}}
  587. // {{{ listDatabases()
  588. /**
  589. * list all databases
  590. *
  591. * @return mixed array of database names on success, a MDB2 error on failure
  592. * @access public
  593. */
  594. function listDatabases()
  595. {
  596. $db = & $this->getDBInstance();
  597. if (PEAR :: isError($db))
  598. {
  599. return $db;
  600. }
  601. $result = $db->queryCol('SHOW DATABASES');
  602. if (PEAR :: isError($result))
  603. {
  604. return $result;
  605. }
  606. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE)
  607. {
  608. $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
  609. }
  610. return $result;
  611. }
  612. // }}}
  613. // {{{ listUsers()
  614. /**
  615. * list all users
  616. *
  617. * @return mixed array of user names on success, a MDB2 error on failure
  618. * @access public
  619. */
  620. function listUsers()
  621. {
  622. $db = & $this->getDBInstance();
  623. if (PEAR :: isError($db))
  624. {
  625. return $db;
  626. }
  627. return $db->queryCol('SELECT DISTINCT USER FROM mysql.USER');
  628. }
  629. // }}}
  630. // {{{ listFunctions()
  631. /**
  632. * list all functions in the current database
  633. *
  634. * @return mixed array of function names on success, a MDB2 error on failure
  635. * @access public
  636. */
  637. function listFunctions()
  638. {
  639. $db = & $this->getDBInstance();
  640. if (PEAR :: isError($db))
  641. {
  642. return $db;
  643. }
  644. $query = "SELECT name FROM mysql.proc";
  645. /*
  646. SELECT ROUTINE_NAME
  647. FROM INFORMATION_SCHEMA.ROUTINES
  648. WHERE ROUTINE_TYPE = 'FUNCTION'
  649. */
  650. $result = $db->queryCol($query);
  651. if (PEAR :: isError($result))
  652. {
  653. return $result;
  654. }
  655. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE)
  656. {
  657. $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
  658. }
  659. return $result;
  660. }
  661. // }}}
  662. // {{{ listTableTriggers()
  663. /**
  664. * list all triggers in the database that reference a given table
  665. *
  666. * @param string table for which all referenced triggers should be found
  667. * @return mixed array of trigger names on success, a MDB2 error on failure
  668. * @access public
  669. */
  670. function listTableTriggers($table = null)
  671. {
  672. $db = & $this->getDBInstance();
  673. if (PEAR :: isError($db))
  674. {
  675. return $db;
  676. }
  677. $query = 'SHOW TRIGGERS';
  678. if (! is_null($table))
  679. {
  680. $table = $db->quote($table, 'text');
  681. $query .= " LIKE $table";
  682. }
  683. $result = $db->queryCol($query);
  684. if (PEAR :: isError($result))
  685. {
  686. return $result;
  687. }
  688. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE)
  689. {
  690. $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
  691. }
  692. return $result;
  693. }
  694. // }}}
  695. // {{{ listTables()
  696. /**
  697. * list all tables in the current database
  698. *
  699. * @param string database, the current is default
  700. * @return mixed array of table names on success, a MDB2 error on failure
  701. * @access public
  702. */
  703. function listTables($database = null)
  704. {
  705. $db = & $this->getDBInstance();
  706. if (PEAR :: isError($db))
  707. {
  708. return $db;
  709. }
  710. $query = "SHOW /*!50002 FULL*/ TABLES";
  711. if (! is_null($database))
  712. {
  713. $query .= " FROM $database";
  714. }
  715. $query .= "/*!50002 WHERE Table_type = 'BASE TABLE'*/";
  716. $table_names = $db->queryAll($query, null, MDB2_FETCHMODE_ORDERED);
  717. if (PEAR :: isError($table_names))
  718. {
  719. return $table_names;
  720. }
  721. $result = array();
  722. foreach ($table_names as $table)
  723. {
  724. if (! $this->_fixSequenceName($table[0], true))
  725. {
  726. $result[] = $table[0];
  727. }
  728. }
  729. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE)
  730. {
  731. $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
  732. }
  733. return $result;
  734. }
  735. // }}}
  736. // {{{ listViews()
  737. /**
  738. * list all views in the current database
  739. *
  740. * @param string database, the current is default
  741. * @return mixed array of view names on success, a MDB2 error on failure
  742. * @access public
  743. */
  744. function listViews($database = null)
  745. {
  746. $db = & $this->getDBInstance();
  747. if (PEAR :: isError($db))
  748. {
  749. return $db;
  750. }
  751. $query = 'SHOW FULL TABLES';
  752. if (! is_null($database))
  753. {
  754. $query .= " FROM $database";
  755. }
  756. $query .= " WHERE Table_type = 'VIEW'";
  757. $result = $db->queryCol($query);
  758. if (PEAR :: isError($result))
  759. {
  760. return $result;
  761. }
  762. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE)
  763. {
  764. $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
  765. }
  766. return $result;
  767. }
  768. // }}}
  769. // {{{ listTableFields()
  770. /**
  771. * list all fields in a table in the current database
  772. *
  773. * @param string $table name of table that should be used in method
  774. * @return mixed array of field names on success, a MDB2 error on failure
  775. * @access public
  776. */
  777. function listTableFields($table)
  778. {
  779. $db = & $this->getDBInstance();
  780. if (PEAR :: isError($db))
  781. {
  782. return $db;
  783. }
  784. $table = $db->quoteIdentifier($table, true);
  785. $result = $db->queryCol("SHOW COLUMNS FROM $table");
  786. if (PEAR :: isError($result))
  787. {
  788. return $result;
  789. }
  790. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE)
  791. {
  792. $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
  793. }
  794. return $result;
  795. }
  796. // }}}
  797. // {{{ createIndex()
  798. /**
  799. * Get the stucture of a field into an array
  800. *
  801. * @author Leoncx
  802. * @param string $table name of the table on which the index is to be created
  803. * @param string $name name of the index to be created
  804. * @param array $definition associative array that defines properties of the index to be created.
  805. * Currently, only one property named FIELDS is supported. This property
  806. * is also an associative with the names of the index fields as array
  807. * indexes. Each entry of this array is set to another type of associative
  808. * array that specifies properties of the index that are specific to
  809. * each field.
  810. *
  811. * Currently, only the sorting property is supported. It should be used
  812. * to define the sorting direction of the index. It may be set to either
  813. * ascending or descending.
  814. *
  815. * Not all DBMS support index sorting direction configuration. The DBMS
  816. * drivers of those that do not support it ignore this property. Use the
  817. * function supports() to determine whether the DBMS driver can manage indexes.
  818. *
  819. * Example
  820. * array(
  821. * 'fields' => array(
  822. * 'user_name' => array(
  823. * 'sorting' => 'ascending'
  824. * 'length' => 10
  825. * ),
  826. * 'last_login' => array()
  827. * )
  828. * )
  829. *
  830. * @return mixed MDB2_OK on success, a MDB2 error on failure
  831. * @access public
  832. */
  833. function createIndex($table, $name, $definition)
  834. {
  835. $db = & $this->getDBInstance();
  836. if (PEAR :: isError($db))
  837. {
  838. return $db;
  839. }
  840. $table = $db->quoteIdentifier($table, true);
  841. $name = $db->quoteIdentifier($db->getIndexName($name), true);
  842. $query = "CREATE INDEX $name ON $table";
  843. $fields = array();
  844. foreach ($definition['fields'] as $field => $fieldinfo)
  845. {
  846. if (! empty($fieldinfo['length']))
  847. {
  848. $fields[] = $db->quoteIdentifier($field, true) . '(' . $fieldinfo['length'] . ')';
  849. }
  850. else
  851. {
  852. $fields[] = $db->quoteIdentifier($field, true);
  853. }
  854. }
  855. $query .= ' (' . implode(', ', $fields) . ')';
  856. return $db->exec($query);
  857. }
  858. // }}}
  859. // {{{ dropIndex()
  860. /**
  861. * drop existing index
  862. *
  863. * @param string $table name of table that should be used in method
  864. * @param string $name name of the index to be dropped
  865. * @return mixed MDB2_OK on success, a MDB2 error on failure
  866. * @access public
  867. */
  868. function dropIndex($table, $name)
  869. {
  870. $db = & $this->getDBInstance();
  871. if (PEAR :: isError($db))
  872. {
  873. return $db;
  874. }
  875. $table = $db->quoteIdentifier($table, true);
  876. $name = $db->quoteIdentifier($db->getIndexName($name), true);
  877. return $db->exec("DROP INDEX $name ON $table");
  878. }
  879. // }}}
  880. // {{{ listTableIndexes()
  881. /**
  882. * list all indexes in a table
  883. *
  884. * @param string $table name of table that should be used in method
  885. * @return mixed array of index names on success, a MDB2 error on failure
  886. * @access public
  887. */
  888. function listTableIndexes($table)
  889. {
  890. $db = & $this->getDBInstance();
  891. if (PEAR :: isError($db))
  892. {
  893. return $db;
  894. }
  895. $key_name = 'Key_name';
  896. $non_unique = 'Non_unique';
  897. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE)
  898. {
  899. if ($db->options['field_case'] == CASE_LOWER)
  900. {
  901. $key_name = strtolower($key_name);
  902. $non_unique = strtolower($non_unique);
  903. }
  904. else
  905. {
  906. $key_name = strtoupper($key_name);
  907. $non_unique = strtoupper($non_unique);
  908. }
  909. }
  910. $table = $db->quoteIdentifier($table, true);
  911. $query = "SHOW INDEX FROM $table";
  912. $indexes = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
  913. if (PEAR :: isError($indexes))
  914. {
  915. return $indexes;
  916. }
  917. $result = array();
  918. foreach ($indexes as $index_data)
  919. {
  920. if ($index_data[$non_unique] && ($index = $this->_fixIndexName($index_data[$key_name])))
  921. {
  922. $result[$index] = true;
  923. }
  924. }
  925. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE)
  926. {
  927. $result = array_change_key_case($result, $db->options['field_case']);
  928. }
  929. return array_keys($result);
  930. }
  931. // }}}
  932. // {{{ createConstraint()
  933. /**
  934. * create a constraint on a table
  935. *
  936. * @param string $table name of the table on which the constraint is to be created
  937. * @param string $name name of the constraint to be created
  938. * @param array $definition associative array that defines properties of the constraint to be created.
  939. * Currently, only one property named FIELDS is supported. This property
  940. * is also an associative with the names of the constraint fields as array
  941. * constraints. Each entry of this array is set to another type of associative
  942. * array that specifies properties of the constraint that are specific to
  943. * each field.
  944. *
  945. * Example
  946. * array(
  947. * 'fields' => array(
  948. * 'user_name' => array(),
  949. * 'last_login' => array()
  950. * )
  951. * )
  952. * @return mixed MDB2_OK on success, a MDB2 error on failure
  953. * @access public
  954. */
  955. function createConstraint($table, $name, $definition)
  956. {
  957. $db = & $this->getDBInstance();
  958. if (PEAR :: isError($db))
  959. {
  960. return $db;
  961. }
  962. $type = '';
  963. $idx_name = $db->quoteIdentifier($db->getIndexName($name), true);
  964. if (! empty($definition['primary']))
  965. {
  966. $type = 'PRIMARY';
  967. $idx_name = 'KEY';
  968. }
  969. elseif (! empty($definition['unique']))
  970. {
  971. $type = 'UNIQUE';
  972. }
  973. elseif (! empty($definition['foreign']))
  974. {
  975. $type = 'CONSTRAINT';
  976. }
  977. if (empty($type))
  978. {
  979. return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, 'invalid definition, could not create constraint', __FUNCTION__);
  980. }
  981. $table_quoted = $db->quoteIdentifier($table, true);
  982. $query = "ALTER TABLE $table_quoted ADD $type $idx_name";
  983. if (! empty($definition['foreign']))
  984. {
  985. $query .= ' FOREIGN KEY';
  986. }
  987. $fields = array();
  988. foreach ($definition['fields'] as $field => $fieldinfo)
  989. {
  990. $quoted = $db->quoteIdentifier($field, true);
  991. if (! empty($fieldinfo['length']))
  992. {
  993. $quoted .= '(' . $fieldinfo['length'] . ')';
  994. }
  995. $fields[] = $quoted;
  996. }
  997. $query .= ' (' . implode(', ', $fields) . ')';
  998. if (! empty($definition['foreign']))
  999. {
  1000. $query .= ' REFERENCES ' . $db->quoteIdentifier($definition['references']['table'], true);
  1001. $referenced_fields = array();
  1002. foreach (array_keys($definition['references']['fields']) as $field)
  1003. {
  1004. $referenced_fields[] = $db->quoteIdentifier($field, true);
  1005. }
  1006. $query .= ' (' . implode(', ', $referenced_fields) . ')';
  1007. $query .= $this->_getAdvancedFKOptions($definition);
  1008. // add index on FK column(s) or we can't add a FK constraint
  1009. // @see http://forums.mysql.com/read.php?22,19755,226009
  1010. $result = $this->createIndex($table, $name . '_fkidx', $definition);
  1011. if (PEAR :: isError($result))
  1012. {
  1013. return $result;
  1014. }
  1015. }
  1016. $res = $db->exec($query);
  1017. if (PEAR :: isError($res))
  1018. {
  1019. return $res;
  1020. }
  1021. if (! empty($definition['foreign']))
  1022. {
  1023. return $this->_createFKTriggers($table, array($name => $definition));
  1024. }
  1025. return MDB2_OK;
  1026. }
  1027. // }}}
  1028. // {{{ dropConstraint()
  1029. /**
  1030. * drop existing constraint
  1031. *
  1032. * @param string $table name of table that should be used in method
  1033. * @param string $name name of the constraint to be dropped
  1034. * @param string $primary hint if the constraint is primary
  1035. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1036. * @access public
  1037. */
  1038. function dropConstraint($table, $name, $primary = false)
  1039. {
  1040. $db = & $this->getDBInstance();
  1041. if (PEAR :: isError($db))
  1042. {
  1043. return $db;
  1044. }
  1045. if ($primary || strtolower($name) == 'primary')
  1046. {
  1047. $query = 'ALTER TABLE ' . $db->quoteIdentifier($table, true) . ' DROP PRIMARY KEY';
  1048. return $db->exec($query);
  1049. }
  1050. //is it a FK constraint? If so, also delete the associated triggers
  1051. $db->loadModule('Reverse', null, true);
  1052. $definition = $db->reverse->getTableConstraintDefinition($table, $name);
  1053. if (! PEAR :: isError($definition) && ! empty($definition['foreign']))
  1054. {
  1055. //first drop the FK enforcing triggers
  1056. $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']);
  1057. if (PEAR :: isError($result))
  1058. {
  1059. return $result;
  1060. }
  1061. //then drop the constraint itself
  1062. $table = $db->quoteIdentifier($table, true);
  1063. $name = $db->quoteIdentifier($db->getIndexName($name), true);
  1064. $query = "ALTER TABLE $table DROP FOREIGN KEY $name";
  1065. return $db->exec($query);
  1066. }
  1067. $table = $db->quoteIdentifier($table, true);
  1068. $name = $db->quoteIdentifier($db->getIndexName($name), true);
  1069. $query = "ALTER TABLE $table DROP INDEX $name";
  1070. return $db->exec($query);
  1071. }
  1072. // }}}
  1073. // {{{ _createFKTriggers()
  1074. /**
  1075. * Create triggers to enforce the FOREIGN KEY constraint on the table
  1076. *
  1077. * NB: since there's no RAISE_APPLICATION_ERROR facility in mysql,
  1078. * we call a non-existent procedure to raise the FK violation message.
  1079. * @see http://forums.mysql.com/read.php?99,55108,71877#msg-71877
  1080. *
  1081. * @param string $table table name
  1082. * @param array $foreign_keys FOREIGN KEY definitions
  1083. *
  1084. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1085. * @access private
  1086. */
  1087. function _createFKTriggers($table, $foreign_keys)
  1088. {
  1089. $db = & $this->getDBInstance();
  1090. if (PEAR :: isError($db))
  1091. {
  1092. return $db;
  1093. }
  1094. // create triggers to enforce FOREIGN KEY constraints
  1095. if ($db->supports('triggers') && ! empty($foreign_keys))
  1096. {
  1097. $table_quoted = $db->quoteIdentifier($table, true);
  1098. foreach ($foreign_keys as $fkname => $fkdef)
  1099. {
  1100. if (empty($fkdef))
  1101. {
  1102. continue;
  1103. }
  1104. //set actions to default if not set
  1105. $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']);
  1106. $fkdef['ondelete'] = empty($fkdef['ondelete']) ? $db->options['default_fk_action_ondelete'] : strtoupper($fkdef['ondelete']);
  1107. $trigger_names = array('insert' => $fkname . '_insert_trg', 'update' => $fkname . '_update_trg',
  1108. 'pk_update' => $fkname . '_pk_update_trg', 'pk_delete' => $fkname . '_pk_delete_trg');
  1109. $table_fields = array_keys($fkdef['fields']);
  1110. $referenced_fields = array_keys($fkdef['references']['fields']);
  1111. //create the ON [UPDATE|DELETE] triggers on the primary table
  1112. $restrict_action = ' IF (SELECT ';
  1113. $aliased_fields = array();
  1114. foreach ($table_fields as $field)
  1115. {
  1116. $aliased_fields[] = $table_quoted . '.' . $field . ' AS ' . $field;
  1117. }
  1118. $restrict_action .= implode(',', $aliased_fields) . ' FROM ' . $table_quoted . ' WHERE ';
  1119. $conditions = array();
  1120. $new_values = array();
  1121. $null_values = array();
  1122. for($i = 0; $i < count($table_fields); $i ++)
  1123. {
  1124. $conditions[] = $table_fields[$i] . ' = OLD.' . $referenced_fields[$i];
  1125. $new_values[] = $table_fields[$i] . ' = NEW.' . $referenced_fields[$i];
  1126. $null_values[] = $table_fields[$i] . ' = NULL';
  1127. }
  1128. $conditions2 = array();
  1129. for($i = 0; $i < count($referenced_fields); $i ++)
  1130. {
  1131. $conditions2[] = 'NEW.' . $referenced_fields[$i] . ' <> OLD.' . $referenced_fields[$i];
  1132. }
  1133. $restrict_action .= implode(' AND ', $conditions) . ') IS NOT NULL' . ' AND (' . implode(' OR ', $conditions2) . ')' . ' THEN CALL %s_ON_TABLE_' . $table . '_VIOLATES_FOREIGN_KEY_CONSTRAINT();' . ' END IF;';
  1134. $cascade_action_update = 'UPDATE ' . $table_quoted . ' SET ' . implode(', ', $new_values) . ' WHERE ' . implode(' AND ', $conditions) . ';';
  1135. $cascade_action_delete = 'DELETE FROM ' . $table_quoted . ' WHERE ' . implode(' AND ', $conditions) . ';';
  1136. $setnull_action = 'UPDATE ' . $table_quoted . ' SET ' . implode(', ', $null_values) . ' WHERE ' . implode(' AND ', $conditions) . ';';
  1137. if ('SET DEFAULT' == $fkdef['onupdate'] || 'SET DEFAULT' == $fkdef['ondelete'])
  1138. {
  1139. $db->loadModule('Reverse', null, true);
  1140. $default_values = array();
  1141. foreach ($table_fields as $table_field)
  1142. {
  1143. $field_definition = $db->reverse->getTableFieldDefinition($table, $field);
  1144. if (PEAR :: isError($field_definition))
  1145. {
  1146. return $field_definition;
  1147. }
  1148. $default_values[] = $table_field . ' = ' . $field_definition[0]['default'];
  1149. }
  1150. $setdefault_action = 'UPDATE ' . $table_quoted . ' SET ' . implode(', ', $default_values) . ' WHERE ' . implode(' AND ', $conditions) . ';';
  1151. }
  1152. $query = 'CREATE TRIGGER %s' . ' %s ON ' . $fkdef['references']['table'] . ' FOR EACH ROW BEGIN ' . ' SET FOREIGN_KEY_CHECKS = 0; '; //only really needed for ON UPDATE CASCADE
  1153. if ('CASCADE' == $fkdef['onupdate'])
  1154. {
  1155. $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $cascade_action_update;
  1156. }
  1157. elseif ('SET NULL' == $fkdef['onupdate'])
  1158. {
  1159. $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setnull_action;
  1160. }
  1161. elseif ('SET DEFAULT' == $fkdef['onupdate'])
  1162. {
  1163. $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setdefault_action;
  1164. }
  1165. elseif ('NO ACTION' == $fkdef['onupdate'])
  1166. {
  1167. $sql_update = sprintf($query . $restrict_action, $trigger_names['pk_update'], 'AFTER UPDATE', 'update');
  1168. }
  1169. elseif ('RESTRICT' == $fkdef['onupdate'])
  1170. {
  1171. $sql_update = sprintf($query . $restrict_action, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update');
  1172. }
  1173. if ('CASCADE' == $fkdef['ondelete'])
  1174. {
  1175. $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $cascade_action_delete;
  1176. }
  1177. elseif ('SET NULL' == $fkdef['ondelete'])
  1178. {
  1179. $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setnull_action;
  1180. }
  1181. elseif ('SET DEFAULT' == $fkdef['ondelete'])
  1182. {
  1183. $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setdefault_action;
  1184. }
  1185. elseif ('NO ACTION' == $fkdef['ondelete'])
  1186. {
  1187. $sql_delete = sprintf($query . $restrict_action, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete');
  1188. }
  1189. elseif ('RESTRICT' == $fkdef['ondelete'])
  1190. {
  1191. $sql_delete = sprintf($query . $restrict_action, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete');
  1192. }
  1193. $sql_update .= ' SET FOREIGN_KEY_CHECKS = 1; END;';
  1194. $sql_delete .= ' SET FOREIGN_KEY_CHECKS = 1; END;';
  1195. $db->pushErrorHandling(PEAR_ERROR_RETURN);
  1196. $db->expectError(MDB2_ERROR_CANNOT_CREATE);
  1197. $result = $db->exec($sql_delete);
  1198. $expected_errmsg = 'This MySQL version doesn\'t support multiple triggers with the same action time and event for one table';
  1199. $db->popExpect();
  1200. $db->popErrorHandling();
  1201. if (PEAR :: isError($result))
  1202. {
  1203. if ($result->getCode() != MDB2_ERROR_CANNOT_CREATE)
  1204. {
  1205. return $result;
  1206. }
  1207. $db->warnings[] = $expected_errmsg;
  1208. }
  1209. $db->pushErrorHandling(PEAR_ERROR_RETURN);
  1210. $db->expectError(MDB2_ERROR_CANNOT_CREATE);
  1211. $result = $db->exec($sql_update);
  1212. $db->popExpect();
  1213. $db->popErrorHandling();
  1214. if (PEAR :: isError($result) && $result->getCode() != MDB2_ERROR_CANNOT_CREATE)
  1215. {
  1216. if ($result->getCode() != MDB2_ERROR_CANNOT_CREATE)
  1217. {
  1218. return $result;
  1219. }
  1220. $db->warnings[] = $expected_errmsg;
  1221. }
  1222. }
  1223. }
  1224. return MDB2_OK;
  1225. }
  1226. // }}}
  1227. // {{{ _dropFKTriggers()
  1228. /**
  1229. * Drop the triggers created to enforce the FOREIGN KEY constraint on the table
  1230. *
  1231. * @param string $table table name
  1232. * @param string $fkname FOREIGN KEY constraint name
  1233. * @param string $referenced_table referenced table name
  1234. *
  1235. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1236. * @access private
  1237. */
  1238. function _dropFKTriggers($table, $fkname, $referenced_table)
  1239. {
  1240. $db = & $this->getDBInstance();
  1241. if (PEAR :: isError($db))
  1242. {
  1243. return $db;
  1244. }
  1245. $triggers = $this->listTableTriggers($table);
  1246. $triggers2 = $this->listTableTriggers($referenced_table);
  1247. if (! PEAR :: isError($triggers2) && ! PEAR :: isError($triggers))
  1248. {
  1249. $triggers = array_merge($triggers, $triggers2);
  1250. $pattern = '/^' . $fkname . '(_pk)?_(insert|update|delete)_trg$/i';
  1251. foreach ($triggers as $trigger)
  1252. {
  1253. if (preg_match($pattern, $trigger))
  1254. {
  1255. $result = $db->exec('DROP TRIGGER ' . $trigger);
  1256. if (PEAR :: isError($result))
  1257. {
  1258. return $result;
  1259. }
  1260. }
  1261. }
  1262. }
  1263. return MDB2_OK;
  1264. }
  1265. // }}}
  1266. // {{{ listTableConstraints()
  1267. /**
  1268. * list all constraints in a table
  1269. *
  1270. * @param string $table name of table that should be used in method
  1271. * @return mixed array of constraint names on success, a MDB2 error on failure
  1272. * @access public
  1273. */
  1274. function listTableConstraints($table)
  1275. {
  1276. $db = & $this->getDBInstance();
  1277. if (PEAR :: isError($db))
  1278. {
  1279. return $db;
  1280. }
  1281. $key_name = 'Key_name';
  1282. $non_unique = 'Non_unique';
  1283. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE)
  1284. {
  1285. if ($db->options['field_case'] == CASE_LOWER)
  1286. {
  1287. $key_name = strtolower($key_name);
  1288. $non_unique = strtolower($non_unique);
  1289. }
  1290. else
  1291. {
  1292. $key_name = strtoupper($key_name);
  1293. $non_unique = strtoupper($non_unique);
  1294. }
  1295. }
  1296. $query = 'SHOW INDEX FROM ' . $db->quoteIdentifier($table, true);
  1297. $indexes = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
  1298. if (PEAR :: isError($indexes))
  1299. {
  1300. return $indexes;
  1301. }
  1302. $result = array();
  1303. foreach ($indexes as $index_data)
  1304. {
  1305. if (! $index_d

Large files files are truncated, but you can click here to view the full file