sqlite.php 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  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, Lorenzo Alberton |
  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. // | Authors: Lukas Smith <smith@pooteeweet.org> |
  43. // | Lorenzo Alberton <l.alberton@quipo.it> |
  44. // +----------------------------------------------------------------------+
  45. //
  46. // $Id$
  47. //
  48. require_once 'MDB2/Driver/Manager/Common.php';
  49. /**
  50. * MDB2 SQLite driver for the management modules
  51. *
  52. * @package MDB2
  53. * @category Database
  54. * @author Lukas Smith <smith@pooteeweet.org>
  55. * @author Lorenzo Alberton <l.alberton@quipo.it>
  56. */
  57. class MDB2_Driver_Manager_sqlite extends MDB2_Driver_Manager_Common
  58. {
  59. // {{{ createDatabase()
  60. /**
  61. * create a new database
  62. *
  63. * @param string $name name of the database that should be created
  64. * @param array $options array with charset info
  65. *
  66. * @return mixed MDB2_OK on success, a MDB2 error on failure
  67. * @access public
  68. */
  69. function createDatabase($name, $options = array())
  70. {
  71. $db = $this->getDBInstance();
  72. if (MDB2::isError($db)) {
  73. return $db;
  74. }
  75. $database_file = $db->_getDatabaseFile($name);
  76. if (file_exists($database_file)) {
  77. return $db->raiseError(MDB2_ERROR_ALREADY_EXISTS, null, null,
  78. 'database already exists', __FUNCTION__);
  79. }
  80. $php_errormsg = '';
  81. $handle = @sqlite_open($database_file, $db->dsn['mode'], $php_errormsg);
  82. if (!$handle) {
  83. return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
  84. (isset($php_errormsg) ? $php_errormsg : 'could not create the database file'), __FUNCTION__);
  85. }
  86. if (!empty($options['charset'])) {
  87. $query = 'PRAGMA encoding = ' . $db->quote($options['charset'], 'text');
  88. @sqlite_query($query, $handle);
  89. }
  90. @sqlite_close($handle);
  91. return MDB2_OK;
  92. }
  93. // }}}
  94. // {{{ dropDatabase()
  95. /**
  96. * drop an existing database
  97. *
  98. * @param string $name name of the database that should be dropped
  99. * @return mixed MDB2_OK on success, a MDB2 error on failure
  100. * @access public
  101. */
  102. function dropDatabase($name)
  103. {
  104. $db = $this->getDBInstance();
  105. if (MDB2::isError($db)) {
  106. return $db;
  107. }
  108. $database_file = $db->_getDatabaseFile($name);
  109. if (!@file_exists($database_file)) {
  110. return $db->raiseError(MDB2_ERROR_CANNOT_DROP, null, null,
  111. 'database does not exist', __FUNCTION__);
  112. }
  113. $result = @unlink($database_file);
  114. if (!$result) {
  115. return $db->raiseError(MDB2_ERROR_CANNOT_DROP, null, null,
  116. (isset($php_errormsg) ? $php_errormsg : 'could not remove the database file'), __FUNCTION__);
  117. }
  118. return MDB2_OK;
  119. }
  120. // }}}
  121. // {{{ _getAdvancedFKOptions()
  122. /**
  123. * Return the FOREIGN KEY query section dealing with non-standard options
  124. * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
  125. *
  126. * @param array $definition
  127. * @return string
  128. * @access protected
  129. */
  130. function _getAdvancedFKOptions($definition)
  131. {
  132. $query = '';
  133. if (!empty($definition['match'])) {
  134. $query .= ' MATCH '.$definition['match'];
  135. }
  136. if (!empty($definition['onupdate']) && (strtoupper($definition['onupdate']) != 'NO ACTION')) {
  137. $query .= ' ON UPDATE '.$definition['onupdate'];
  138. }
  139. if (!empty($definition['ondelete']) && (strtoupper($definition['ondelete']) != 'NO ACTION')) {
  140. $query .= ' ON DELETE '.$definition['ondelete'];
  141. }
  142. if (!empty($definition['deferrable'])) {
  143. $query .= ' DEFERRABLE';
  144. } else {
  145. $query .= ' NOT DEFERRABLE';
  146. }
  147. if (!empty($definition['initiallydeferred'])) {
  148. $query .= ' INITIALLY DEFERRED';
  149. } else {
  150. $query .= ' INITIALLY IMMEDIATE';
  151. }
  152. return $query;
  153. }
  154. // }}}
  155. // {{{ _getCreateTableQuery()
  156. /**
  157. * Create a basic SQL query for a new table creation
  158. * @param string $name Name of the database that should be created
  159. * @param array $fields Associative array that contains the definition of each field of the new table
  160. * @param array $options An associative array of table options
  161. * @return mixed string (the SQL query) on success, a MDB2 error on failure
  162. * @see createTable()
  163. */
  164. function _getCreateTableQuery($name, $fields, $options = array())
  165. {
  166. $db = $this->getDBInstance();
  167. if (MDB2::isError($db)) {
  168. return $db;
  169. }
  170. if (!$name) {
  171. return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
  172. 'no valid table name specified', __FUNCTION__);
  173. }
  174. if (empty($fields)) {
  175. return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
  176. 'no fields specified for table "'.$name.'"', __FUNCTION__);
  177. }
  178. $query_fields = $this->getFieldDeclarationList($fields);
  179. if (MDB2::isError($query_fields)) {
  180. return $query_fields;
  181. }
  182. if (!empty($options['primary'])) {
  183. $query_fields.= ', PRIMARY KEY ('.implode(', ', array_keys($options['primary'])).')';
  184. }
  185. if (!empty($options['foreign_keys'])) {
  186. foreach ($options['foreign_keys'] as $fkname => $fkdef) {
  187. if (empty($fkdef)) {
  188. continue;
  189. }
  190. $query_fields.= ', CONSTRAINT '.$fkname.' FOREIGN KEY ('.implode(', ', array_keys($fkdef['fields'])).')';
  191. $query_fields.= ' REFERENCES '.$fkdef['references']['table'].' ('.implode(', ', array_keys($fkdef['references']['fields'])).')';
  192. $query_fields.= $this->_getAdvancedFKOptions($fkdef);
  193. }
  194. }
  195. $name = $db->quoteIdentifier($name, true);
  196. $result = 'CREATE ';
  197. if (!empty($options['temporary'])) {
  198. $result .= $this->_getTemporaryTableQuery();
  199. }
  200. $result .= " TABLE $name ($query_fields)";
  201. return $result;
  202. }
  203. // }}}
  204. // {{{ createTable()
  205. /**
  206. * create a new table
  207. *
  208. * @param string $name Name of the database that should be created
  209. * @param array $fields Associative array that contains the definition
  210. * of each field of the new table
  211. * @param array $options An associative array of table options
  212. *
  213. * @return mixed MDB2_OK on success, a MDB2 error on failure
  214. * @access public
  215. */
  216. function createTable($name, $fields, $options = array())
  217. {
  218. $result = parent::createTable($name, $fields, $options);
  219. if (MDB2::isError($result)) {
  220. return $result;
  221. }
  222. // create triggers to enforce FOREIGN KEY constraints
  223. if (!empty($options['foreign_keys'])) {
  224. $db = $this->getDBInstance();
  225. if (MDB2::isError($db)) {
  226. return $db;
  227. }
  228. foreach ($options['foreign_keys'] as $fkname => $fkdef) {
  229. if (empty($fkdef)) {
  230. continue;
  231. }
  232. //set actions to default if not set
  233. $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']);
  234. $fkdef['ondelete'] = empty($fkdef['ondelete']) ? $db->options['default_fk_action_ondelete'] : strtoupper($fkdef['ondelete']);
  235. $trigger_names = array(
  236. 'insert' => $fkname.'_insert_trg',
  237. 'update' => $fkname.'_update_trg',
  238. 'pk_update' => $fkname.'_pk_update_trg',
  239. 'pk_delete' => $fkname.'_pk_delete_trg',
  240. );
  241. //create the [insert|update] triggers on the FK table
  242. $table_fields = array_keys($fkdef['fields']);
  243. $referenced_fields = array_keys($fkdef['references']['fields']);
  244. $query = 'CREATE TRIGGER %s BEFORE %s ON '.$name
  245. .' FOR EACH ROW BEGIN'
  246. .' SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')'
  247. .' WHERE (SELECT ';
  248. $aliased_fields = array();
  249. foreach ($referenced_fields as $field) {
  250. $aliased_fields[] = $fkdef['references']['table'] .'.'.$field .' AS '.$field;
  251. }
  252. $query .= implode(',', $aliased_fields)
  253. .' FROM '.$fkdef['references']['table']
  254. .' WHERE ';
  255. $conditions = array();
  256. for ($i=0; $i<count($table_fields); $i++) {
  257. $conditions[] = $referenced_fields[$i] .' = NEW.'.$table_fields[$i];
  258. }
  259. $query .= implode(' AND ', $conditions).') IS NULL; END;';
  260. $result = $db->exec(sprintf($query, $trigger_names['insert'], 'INSERT', 'insert'));
  261. if (MDB2::isError($result)) {
  262. return $result;
  263. }
  264. $result = $db->exec(sprintf($query, $trigger_names['update'], 'UPDATE', 'update'));
  265. if (MDB2::isError($result)) {
  266. return $result;
  267. }
  268. //create the ON [UPDATE|DELETE] triggers on the primary table
  269. $restrict_action = 'SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')'
  270. .' WHERE (SELECT ';
  271. $aliased_fields = array();
  272. foreach ($table_fields as $field) {
  273. $aliased_fields[] = $name .'.'.$field .' AS '.$field;
  274. }
  275. $restrict_action .= implode(',', $aliased_fields)
  276. .' FROM '.$name
  277. .' WHERE ';
  278. $conditions = array();
  279. $new_values = array();
  280. $null_values = array();
  281. for ($i=0; $i<count($table_fields); $i++) {
  282. $conditions[] = $table_fields[$i] .' = OLD.'.$referenced_fields[$i];
  283. $new_values[] = $table_fields[$i] .' = NEW.'.$referenced_fields[$i];
  284. $null_values[] = $table_fields[$i] .' = NULL';
  285. }
  286. $conditions2 = array();
  287. for ($i=0; $i<count($referenced_fields); $i++) {
  288. $conditions2[] = 'NEW.'.$referenced_fields[$i] .' <> OLD.'.$referenced_fields[$i];
  289. }
  290. $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL'
  291. .' AND (' .implode(' OR ', $conditions2) .')';
  292. $cascade_action_update = 'UPDATE '.$name.' SET '.implode(', ', $new_values) .' WHERE '.implode(' AND ', $conditions);
  293. $cascade_action_delete = 'DELETE FROM '.$name.' WHERE '.implode(' AND ', $conditions);
  294. $setnull_action = 'UPDATE '.$name.' SET '.implode(', ', $null_values).' WHERE '.implode(' AND ', $conditions);
  295. if ('SET DEFAULT' == $fkdef['onupdate'] || 'SET DEFAULT' == $fkdef['ondelete']) {
  296. $db->loadModule('Reverse', null, true);
  297. $default_values = array();
  298. foreach ($table_fields as $table_field) {
  299. $field_definition = $db->reverse->getTableFieldDefinition($name, $field);
  300. if (MDB2::isError($field_definition)) {
  301. return $field_definition;
  302. }
  303. $default_values[] = $table_field .' = '. $field_definition[0]['default'];
  304. }
  305. $setdefault_action = 'UPDATE '.$name.' SET '.implode(', ', $default_values).' WHERE '.implode(' AND ', $conditions);
  306. }
  307. $query = 'CREATE TRIGGER %s'
  308. .' %s ON '.$fkdef['references']['table']
  309. .' FOR EACH ROW BEGIN ';
  310. if ('CASCADE' == $fkdef['onupdate']) {
  311. $sql_update = sprintf($query, $trigger_names['pk_update'], 'AFTER UPDATE', 'update') . $cascade_action_update. '; END;';
  312. } elseif ('SET NULL' == $fkdef['onupdate']) {
  313. $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setnull_action. '; END;';
  314. } elseif ('SET DEFAULT' == $fkdef['onupdate']) {
  315. $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setdefault_action. '; END;';
  316. } elseif ('NO ACTION' == $fkdef['onupdate']) {
  317. $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'AFTER UPDATE', 'update') . '; END;';
  318. } elseif ('RESTRICT' == $fkdef['onupdate']) {
  319. $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . '; END;';
  320. }
  321. if ('CASCADE' == $fkdef['ondelete']) {
  322. $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete') . $cascade_action_delete. '; END;';
  323. } elseif ('SET NULL' == $fkdef['ondelete']) {
  324. $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setnull_action. '; END;';
  325. } elseif ('SET DEFAULT' == $fkdef['ondelete']) {
  326. $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setdefault_action. '; END;';
  327. } elseif ('NO ACTION' == $fkdef['ondelete']) {
  328. $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete') . '; END;';
  329. } elseif ('RESTRICT' == $fkdef['ondelete']) {
  330. $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . '; END;';
  331. }
  332. if (MDB2::isError($result)) {
  333. return $result;
  334. }
  335. $result = $db->exec($sql_delete);
  336. if (MDB2::isError($result)) {
  337. return $result;
  338. }
  339. $result = $db->exec($sql_update);
  340. if (MDB2::isError($result)) {
  341. return $result;
  342. }
  343. }
  344. }
  345. if (MDB2::isError($result)) {
  346. return $result;
  347. }
  348. return MDB2_OK;
  349. }
  350. // }}}
  351. // {{{ dropTable()
  352. /**
  353. * drop an existing table
  354. *
  355. * @param string $name name of the table that should be dropped
  356. * @return mixed MDB2_OK on success, a MDB2 error on failure
  357. * @access public
  358. */
  359. function dropTable($name)
  360. {
  361. $db = $this->getDBInstance();
  362. if (MDB2::isError($db)) {
  363. return $db;
  364. }
  365. //delete the triggers associated to existing FK constraints
  366. $constraints = $this->listTableConstraints($name);
  367. if (!MDB2::isError($constraints) && !empty($constraints)) {
  368. $db->loadModule('Reverse', null, true);
  369. foreach ($constraints as $constraint) {
  370. $definition = $db->reverse->getTableConstraintDefinition($name, $constraint);
  371. if (!MDB2::isError($definition) && !empty($definition['foreign'])) {
  372. $result = $this->_dropFKTriggers($name, $constraint, $definition['references']['table']);
  373. if (MDB2::isError($result)) {
  374. return $result;
  375. }
  376. }
  377. }
  378. }
  379. $name = $db->quoteIdentifier($name, true);
  380. $result = $db->exec("DROP TABLE $name");
  381. if (MDB2::isError($result)) {
  382. return $result;
  383. }
  384. return MDB2_OK;
  385. }
  386. // }}}
  387. // {{{ vacuum()
  388. /**
  389. * Optimize (vacuum) all the tables in the db (or only the specified table)
  390. * and optionally run ANALYZE.
  391. *
  392. * @param string $table table name (all the tables if empty)
  393. * @param array $options an array with driver-specific options:
  394. * - timeout [int] (in seconds) [mssql-only]
  395. * - analyze [boolean] [pgsql and mysql]
  396. * - full [boolean] [pgsql-only]
  397. * - freeze [boolean] [pgsql-only]
  398. *
  399. * @return mixed MDB2_OK success, a MDB2 error on failure
  400. * @access public
  401. */
  402. function vacuum($table = null, $options = array())
  403. {
  404. $db = $this->getDBInstance();
  405. if (MDB2::isError($db)) {
  406. return $db;
  407. }
  408. $query = 'VACUUM';
  409. if (!empty($table)) {
  410. $query .= ' '.$db->quoteIdentifier($table, true);
  411. }
  412. $result = $db->exec($query);
  413. if (MDB2::isError($result)) {
  414. return $result;
  415. }
  416. return MDB2_OK;
  417. }
  418. // }}}
  419. // {{{ alterTable()
  420. /**
  421. * alter an existing table
  422. *
  423. * @param string $name name of the table that is intended to be changed.
  424. * @param array $changes associative array that contains the details of each type
  425. * of change that is intended to be performed. The types of
  426. * changes that are currently supported are defined as follows:
  427. *
  428. * name
  429. *
  430. * New name for the table.
  431. *
  432. * add
  433. *
  434. * Associative array with the names of fields to be added as
  435. * indexes of the array. The value of each entry of the array
  436. * should be set to another associative array with the properties
  437. * of the fields to be added. The properties of the fields should
  438. * be the same as defined by the MDB2 parser.
  439. *
  440. *
  441. * remove
  442. *
  443. * Associative array with the names of fields to be removed as indexes
  444. * of the array. Currently the values assigned to each entry are ignored.
  445. * An empty array should be used for future compatibility.
  446. *
  447. * rename
  448. *
  449. * Associative array with the names of fields to be renamed as indexes
  450. * of the array. The value of each entry of the array should be set to
  451. * another associative array with the entry named name with the new
  452. * field name and the entry named Declaration that is expected to contain
  453. * the portion of the field declaration already in DBMS specific SQL code
  454. * as it is used in the CREATE TABLE statement.
  455. *
  456. * change
  457. *
  458. * Associative array with the names of the fields to be changed as indexes
  459. * of the array. Keep in mind that if it is intended to change either the
  460. * name of a field and any other properties, the change array entries
  461. * should have the new names of the fields as array indexes.
  462. *
  463. * The value of each entry of the array should be set to another associative
  464. * array with the properties of the fields to that are meant to be changed as
  465. * array entries. These entries should be assigned to the new values of the
  466. * respective properties. The properties of the fields should be the same
  467. * as defined by the MDB2 parser.
  468. *
  469. * Example
  470. * array(
  471. * 'name' => 'userlist',
  472. * 'add' => array(
  473. * 'quota' => array(
  474. * 'type' => 'integer',
  475. * 'unsigned' => 1
  476. * )
  477. * ),
  478. * 'remove' => array(
  479. * 'file_limit' => array(),
  480. * 'time_limit' => array()
  481. * ),
  482. * 'change' => array(
  483. * 'name' => array(
  484. * 'length' => '20',
  485. * 'definition' => array(
  486. * 'type' => 'text',
  487. * 'length' => 20,
  488. * ),
  489. * )
  490. * ),
  491. * 'rename' => array(
  492. * 'sex' => array(
  493. * 'name' => 'gender',
  494. * 'definition' => array(
  495. * 'type' => 'text',
  496. * 'length' => 1,
  497. * 'default' => 'M',
  498. * ),
  499. * )
  500. * )
  501. * )
  502. *
  503. * @param boolean $check indicates whether the function should just check if the DBMS driver
  504. * can perform the requested table alterations if the value is true or
  505. * actually perform them otherwise.
  506. * @access public
  507. *
  508. * @return mixed MDB2_OK on success, a MDB2 error on failure
  509. */
  510. function alterTable($name, $changes, $check, $options = array())
  511. {
  512. $db = $this->getDBInstance();
  513. if (MDB2::isError($db)) {
  514. return $db;
  515. }
  516. foreach ($changes as $change_name => $change) {
  517. switch ($change_name) {
  518. case 'add':
  519. case 'remove':
  520. case 'change':
  521. case 'name':
  522. case 'rename':
  523. break;
  524. default:
  525. return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
  526. 'change type "'.$change_name.'" not yet supported', __FUNCTION__);
  527. }
  528. }
  529. if ($check) {
  530. return MDB2_OK;
  531. }
  532. $db->loadModule('Reverse', null, true);
  533. // actually sqlite 2.x supports no ALTER TABLE at all .. so we emulate it
  534. $fields = $db->manager->listTableFields($name);
  535. if (MDB2::isError($fields)) {
  536. return $fields;
  537. }
  538. $fields = array_flip($fields);
  539. foreach ($fields as $field => $value) {
  540. $definition = $db->reverse->getTableFieldDefinition($name, $field);
  541. if (MDB2::isError($definition)) {
  542. return $definition;
  543. }
  544. $fields[$field] = $definition[0];
  545. }
  546. $indexes = $db->manager->listTableIndexes($name);
  547. if (MDB2::isError($indexes)) {
  548. return $indexes;
  549. }
  550. $indexes = array_flip($indexes);
  551. foreach ($indexes as $index => $value) {
  552. $definition = $db->reverse->getTableIndexDefinition($name, $index);
  553. if (MDB2::isError($definition)) {
  554. return $definition;
  555. }
  556. $indexes[$index] = $definition;
  557. }
  558. $constraints = $db->manager->listTableConstraints($name);
  559. if (MDB2::isError($constraints)) {
  560. return $constraints;
  561. }
  562. if (!array_key_exists('foreign_keys', $options)) {
  563. $options['foreign_keys'] = array();
  564. }
  565. $constraints = array_flip($constraints);
  566. foreach ($constraints as $constraint => $value) {
  567. if (!empty($definition['primary'])) {
  568. if (!array_key_exists('primary', $options)) {
  569. $options['primary'] = $definition['fields'];
  570. //remove from the $constraint array, it's already handled by createTable()
  571. unset($constraints[$constraint]);
  572. }
  573. } else {
  574. $c_definition = $db->reverse->getTableConstraintDefinition($name, $constraint);
  575. if (MDB2::isError($c_definition)) {
  576. return $c_definition;
  577. }
  578. if (!empty($c_definition['foreign'])) {
  579. if (!array_key_exists($constraint, $options['foreign_keys'])) {
  580. $options['foreign_keys'][$constraint] = $c_definition;
  581. }
  582. //remove from the $constraint array, it's already handled by createTable()
  583. unset($constraints[$constraint]);
  584. } else {
  585. $constraints[$constraint] = $c_definition;
  586. }
  587. }
  588. }
  589. $name_new = $name;
  590. $create_order = $select_fields = array_keys($fields);
  591. foreach ($changes as $change_name => $change) {
  592. switch ($change_name) {
  593. case 'add':
  594. foreach ($change as $field_name => $field) {
  595. $fields[$field_name] = $field;
  596. $create_order[] = $field_name;
  597. }
  598. break;
  599. case 'remove':
  600. foreach ($change as $field_name => $field) {
  601. unset($fields[$field_name]);
  602. $select_fields = array_diff($select_fields, array($field_name));
  603. $create_order = array_diff($create_order, array($field_name));
  604. }
  605. break;
  606. case 'change':
  607. foreach ($change as $field_name => $field) {
  608. $fields[$field_name] = $field['definition'];
  609. }
  610. break;
  611. case 'name':
  612. $name_new = $change;
  613. break;
  614. case 'rename':
  615. foreach ($change as $field_name => $field) {
  616. unset($fields[$field_name]);
  617. $fields[$field['name']] = $field['definition'];
  618. $create_order[array_search($field_name, $create_order)] = $field['name'];
  619. }
  620. break;
  621. default:
  622. return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
  623. 'change type "'.$change_name.'" not yet supported', __FUNCTION__);
  624. }
  625. }
  626. $data = null;
  627. if (!empty($select_fields)) {
  628. $query = 'SELECT '.implode(', ', $select_fields).' FROM '.$db->quoteIdentifier($name, true);
  629. $data = $db->queryAll($query, null, MDB2_FETCHMODE_ORDERED);
  630. }
  631. $result = $this->dropTable($name);
  632. if (MDB2::isError($result)) {
  633. return $result;
  634. }
  635. $result = $this->createTable($name_new, $fields, $options);
  636. if (MDB2::isError($result)) {
  637. return $result;
  638. }
  639. foreach ($indexes as $index => $definition) {
  640. $this->createIndex($name_new, $index, $definition);
  641. }
  642. foreach ($constraints as $constraint => $definition) {
  643. $this->createConstraint($name_new, $constraint, $definition);
  644. }
  645. if (!empty($select_fields) && !empty($data)) {
  646. $query = 'INSERT INTO '.$db->quoteIdentifier($name_new, true);
  647. $query.= '('.implode(', ', array_slice(array_keys($fields), 0, count($select_fields))).')';
  648. $query.=' VALUES (?'.str_repeat(', ?', (count($select_fields) - 1)).')';
  649. $stmt = $db->prepare($query, null, MDB2_PREPARE_MANIP);
  650. if (MDB2::isError($stmt)) {
  651. return $stmt;
  652. }
  653. foreach ($data as $row) {
  654. $result = $stmt->execute($row);
  655. if (MDB2::isError($result)) {
  656. return $result;
  657. }
  658. }
  659. }
  660. return MDB2_OK;
  661. }
  662. // }}}
  663. // {{{ listDatabases()
  664. /**
  665. * list all databases
  666. *
  667. * @return mixed array of database names on success, a MDB2 error on failure
  668. * @access public
  669. */
  670. function listDatabases()
  671. {
  672. $db = $this->getDBInstance();
  673. if (MDB2::isError($db)) {
  674. return $db;
  675. }
  676. return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  677. 'list databases is not supported', __FUNCTION__);
  678. }
  679. // }}}
  680. // {{{ listUsers()
  681. /**
  682. * list all users
  683. *
  684. * @return mixed array of user names on success, a MDB2 error on failure
  685. * @access public
  686. */
  687. function listUsers()
  688. {
  689. $db = $this->getDBInstance();
  690. if (MDB2::isError($db)) {
  691. return $db;
  692. }
  693. return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
  694. 'list databases is not supported', __FUNCTION__);
  695. }
  696. // }}}
  697. // {{{ listViews()
  698. /**
  699. * list all views in the current database
  700. *
  701. * @return mixed array of view names on success, a MDB2 error on failure
  702. * @access public
  703. */
  704. function listViews()
  705. {
  706. $db = $this->getDBInstance();
  707. if (MDB2::isError($db)) {
  708. return $db;
  709. }
  710. $query = "SELECT name FROM sqlite_master WHERE type='view' AND sql NOT NULL";
  711. $result = $db->queryCol($query);
  712. if (MDB2::isError($result)) {
  713. return $result;
  714. }
  715. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  716. $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
  717. }
  718. return $result;
  719. }
  720. // }}}
  721. // {{{ listTableViews()
  722. /**
  723. * list the views in the database that reference a given table
  724. *
  725. * @param string table for which all referenced views should be found
  726. * @return mixed array of view names on success, a MDB2 error on failure
  727. * @access public
  728. */
  729. function listTableViews($table)
  730. {
  731. $db = $this->getDBInstance();
  732. if (MDB2::isError($db)) {
  733. return $db;
  734. }
  735. $query = "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
  736. $views = $db->queryAll($query, array('text', 'text'), MDB2_FETCHMODE_ASSOC);
  737. if (MDB2::isError($views)) {
  738. return $views;
  739. }
  740. $result = array();
  741. foreach ($views as $row) {
  742. if (preg_match("/^create view .* \bfrom\b\s+\b{$table}\b /i", $row['sql'])) {
  743. if (!empty($row['name'])) {
  744. $result[$row['name']] = true;
  745. }
  746. }
  747. }
  748. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  749. $result = array_change_key_case($result, $db->options['field_case']);
  750. }
  751. return array_keys($result);
  752. }
  753. // }}}
  754. // {{{ listTables()
  755. /**
  756. * list all tables in the current database
  757. *
  758. * @return mixed array of table names on success, a MDB2 error on failure
  759. * @access public
  760. */
  761. function listTables()
  762. {
  763. $db = $this->getDBInstance();
  764. if (MDB2::isError($db)) {
  765. return $db;
  766. }
  767. $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
  768. $table_names = $db->queryCol($query);
  769. if (MDB2::isError($table_names)) {
  770. return $table_names;
  771. }
  772. $result = array();
  773. foreach ($table_names as $table_name) {
  774. if (!$this->_fixSequenceName($table_name, true)) {
  775. $result[] = $table_name;
  776. }
  777. }
  778. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  779. $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
  780. }
  781. return $result;
  782. }
  783. // }}}
  784. // {{{ listTableFields()
  785. /**
  786. * list all fields in a table in the current database
  787. *
  788. * @param string $table name of table that should be used in method
  789. * @return mixed array of field names on success, a MDB2 error on failure
  790. * @access public
  791. */
  792. function listTableFields($table)
  793. {
  794. $db = $this->getDBInstance();
  795. if (MDB2::isError($db)) {
  796. return $db;
  797. }
  798. $result = $db->loadModule('Reverse', null, true);
  799. if (MDB2::isError($result)) {
  800. return $result;
  801. }
  802. $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
  803. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  804. $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
  805. } else {
  806. $query.= 'name='.$db->quote($table, 'text');
  807. }
  808. $sql = $db->queryOne($query);
  809. if (MDB2::isError($sql)) {
  810. return $sql;
  811. }
  812. $columns = $db->reverse->_getTableColumns($sql);
  813. $fields = array();
  814. foreach ($columns as $column) {
  815. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  816. if ($db->options['field_case'] == CASE_LOWER) {
  817. $column['name'] = strtolower($column['name']);
  818. } else {
  819. $column['name'] = strtoupper($column['name']);
  820. }
  821. } else {
  822. $column = array_change_key_case($column, $db->options['field_case']);
  823. }
  824. $fields[] = $column['name'];
  825. }
  826. return $fields;
  827. }
  828. // }}}
  829. // {{{ listTableTriggers()
  830. /**
  831. * list all triggers in the database that reference a given table
  832. *
  833. * @param string table for which all referenced triggers should be found
  834. * @return mixed array of trigger names on success, a MDB2 error on failure
  835. * @access public
  836. */
  837. function listTableTriggers($table = null)
  838. {
  839. $db = $this->getDBInstance();
  840. if (MDB2::isError($db)) {
  841. return $db;
  842. }
  843. $query = "SELECT name FROM sqlite_master WHERE type='trigger' AND sql NOT NULL";
  844. if (null !== $table) {
  845. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  846. $query.= ' AND LOWER(tbl_name)='.$db->quote(strtolower($table), 'text');
  847. } else {
  848. $query.= ' AND tbl_name='.$db->quote($table, 'text');
  849. }
  850. }
  851. $result = $db->queryCol($query);
  852. if (MDB2::isError($result)) {
  853. return $result;
  854. }
  855. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  856. $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
  857. }
  858. return $result;
  859. }
  860. // }}}
  861. // {{{ createIndex()
  862. /**
  863. * Get the stucture of a field into an array
  864. *
  865. * @param string $table name of the table on which the index is to be created
  866. * @param string $name name of the index to be created
  867. * @param array $definition associative array that defines properties of the index to be created.
  868. * Currently, only one property named FIELDS is supported. This property
  869. * is also an associative with the names of the index fields as array
  870. * indexes. Each entry of this array is set to another type of associative
  871. * array that specifies properties of the index that are specific to
  872. * each field.
  873. *
  874. * Currently, only the sorting property is supported. It should be used
  875. * to define the sorting direction of the index. It may be set to either
  876. * ascending or descending.
  877. *
  878. * Not all DBMS support index sorting direction configuration. The DBMS
  879. * drivers of those that do not support it ignore this property. Use the
  880. * function support() to determine whether the DBMS driver can manage indexes.
  881. * Example
  882. * array(
  883. * 'fields' => array(
  884. * 'user_name' => array(
  885. * 'sorting' => 'ascending'
  886. * ),
  887. * 'last_login' => array()
  888. * )
  889. * )
  890. * @return mixed MDB2_OK on success, a MDB2 error on failure
  891. * @access public
  892. */
  893. function createIndex($table, $name, $definition)
  894. {
  895. $db = $this->getDBInstance();
  896. if (MDB2::isError($db)) {
  897. return $db;
  898. }
  899. $table = $db->quoteIdentifier($table, true);
  900. $name = $db->quoteIdentifier($db->getIndexName($name), true);
  901. $query = "CREATE INDEX $name ON $table";
  902. $fields = array();
  903. foreach ($definition['fields'] as $field_name => $field) {
  904. $field_string = $db->quoteIdentifier($field_name, true);
  905. if (!empty($field['sorting'])) {
  906. switch ($field['sorting']) {
  907. case 'ascending':
  908. $field_string.= ' ASC';
  909. break;
  910. case 'descending':
  911. $field_string.= ' DESC';
  912. break;
  913. }
  914. }
  915. $fields[] = $field_string;
  916. }
  917. $query .= ' ('.implode(', ', $fields) . ')';
  918. $result = $db->exec($query);
  919. if (MDB2::isError($result)) {
  920. return $result;
  921. }
  922. return MDB2_OK;
  923. }
  924. // }}}
  925. // {{{ dropIndex()
  926. /**
  927. * drop existing index
  928. *
  929. * @param string $table name of table that should be used in method
  930. * @param string $name name of the index to be dropped
  931. * @return mixed MDB2_OK on success, a MDB2 error on failure
  932. * @access public
  933. */
  934. function dropIndex($table, $name)
  935. {
  936. $db = $this->getDBInstance();
  937. if (MDB2::isError($db)) {
  938. return $db;
  939. }
  940. $name = $db->getIndexName($name);
  941. $result = $db->exec("DROP INDEX $name");
  942. if (MDB2::isError($result)) {
  943. return $result;
  944. }
  945. return MDB2_OK;
  946. }
  947. // }}}
  948. // {{{ listTableIndexes()
  949. /**
  950. * list all indexes in a table
  951. *
  952. * @param string $table name of table that should be used in method
  953. * @return mixed array of index names on success, a MDB2 error on failure
  954. * @access public
  955. */
  956. function listTableIndexes($table)
  957. {
  958. $db = $this->getDBInstance();
  959. if (MDB2::isError($db)) {
  960. return $db;
  961. }
  962. $table = $db->quote($table, 'text');
  963. $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
  964. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  965. $query.= 'LOWER(tbl_name)='.strtolower($table);
  966. } else {
  967. $query.= "tbl_name=$table";
  968. }
  969. $query.= " AND sql NOT NULL ORDER BY name";
  970. $indexes = $db->queryCol($query, 'text');
  971. if (MDB2::isError($indexes)) {
  972. return $indexes;
  973. }
  974. $result = array();
  975. foreach ($indexes as $sql) {
  976. if (preg_match("/^create index ([^ ]+) on /i", $sql, $tmp)) {
  977. $index = $this->_fixIndexName($tmp[1]);
  978. if (!empty($index)) {
  979. $result[$index] = true;
  980. }
  981. }
  982. }
  983. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  984. $result = array_change_key_case($result, $db->options['field_case']);
  985. }
  986. return array_keys($result);
  987. }
  988. // }}}
  989. // {{{ createConstraint()
  990. /**
  991. * create a constraint on a table
  992. *
  993. * @param string $table name of the table on which the constraint is to be created
  994. * @param string $name name of the constraint to be created
  995. * @param array $definition associative array that defines properties of the constraint to be created.
  996. * Currently, only one property named FIELDS is supported. This property
  997. * is also an associative with the names of the constraint fields as array
  998. * constraints. Each entry of this array is set to another type of associative
  999. * array that specifies properties of the constraint that are specific to
  1000. * each field.
  1001. *
  1002. * Example
  1003. * array(
  1004. * 'fields' => array(
  1005. * 'user_name' => array(),
  1006. * 'last_login' => array()
  1007. * )
  1008. * )
  1009. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1010. * @access public
  1011. */
  1012. function createConstraint($table, $name, $definition)
  1013. {
  1014. $db = $this->getDBInstance();
  1015. if (MDB2::isError($db)) {
  1016. return $db;
  1017. }
  1018. if (!empty($definition['primary'])) {
  1019. return $db->manager->alterTable($table, array(), false, array('primary' => $definition['fields']));
  1020. }
  1021. if (!empty($definition['foreign'])) {
  1022. return $db->manager->alterTable($table, array(), false, array('foreign_keys' => array($name => $definition)));
  1023. }
  1024. $table = $db->quoteIdentifier($table, true);
  1025. $name = $db->getIndexName($name);
  1026. $query = "CREATE UNIQUE INDEX $name ON $table";
  1027. $fields = array();
  1028. foreach ($definition['fields'] as $field_name => $field) {
  1029. $field_string = $field_name;
  1030. if (!empty($field['sorting'])) {
  1031. switch ($field['sorting']) {
  1032. case 'ascending':
  1033. $field_string.= ' ASC';
  1034. break;
  1035. case 'descending':
  1036. $field_string.= ' DESC';
  1037. break;
  1038. }
  1039. }
  1040. $fields[] = $field_string;
  1041. }
  1042. $query .= ' ('.implode(', ', $fields) . ')';
  1043. $result = $db->exec($query);
  1044. if (MDB2::isError($result)) {
  1045. return $result;
  1046. }
  1047. return MDB2_OK;
  1048. }
  1049. // }}}
  1050. // {{{ dropConstraint()
  1051. /**
  1052. * drop existing constraint
  1053. *
  1054. * @param string $table name of table that should be used in method
  1055. * @param string $name name of the constraint to be dropped
  1056. * @param string $primary hint if the constraint is primary
  1057. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1058. * @access public
  1059. */
  1060. function dropConstraint($table, $name, $primary = false)
  1061. {
  1062. if ($primary || $name == 'PRIMARY') {
  1063. return $this->alterTable($table, array(), false, array('primary' => null));
  1064. }
  1065. $db = $this->getDBInstance();
  1066. if (MDB2::isError($db)) {
  1067. return $db;
  1068. }
  1069. //is it a FK constraint? If so, also delete the associated triggers
  1070. $db->loadModule('Reverse', null, true);
  1071. $definition = $db->reverse->getTableConstraintDefinition($table, $name);
  1072. if (!MDB2::isError($definition) && !empty($definition['foreign'])) {
  1073. //first drop the FK enforcing triggers
  1074. $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']);
  1075. if (MDB2::isError($result)) {
  1076. return $result;
  1077. }
  1078. //then drop the constraint itself
  1079. return $this->alterTable($table, array(), false, array('foreign_keys' => array($name => null)));
  1080. }
  1081. $name = $db->getIndexName($name);
  1082. $result = $db->exec("DROP INDEX $name");
  1083. if (MDB2::isError($result)) {
  1084. return $result;
  1085. }
  1086. return MDB2_OK;
  1087. }
  1088. // }}}
  1089. // {{{ _dropFKTriggers()
  1090. /**
  1091. * Drop the triggers created to enforce the FOREIGN KEY constraint on the table
  1092. *
  1093. * @param string $table table name
  1094. * @param string $fkname FOREIGN KEY constraint name
  1095. * @param string $referenced_table referenced table name
  1096. *
  1097. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1098. * @access private
  1099. */
  1100. function _dropFKTriggers($table, $fkname, $referenced_table)
  1101. {
  1102. $db = $this->getDBInstance();
  1103. if (MDB2::isError($db)) {
  1104. return $db;
  1105. }
  1106. $triggers = $this->listTableTriggers($table);
  1107. $triggers2 = $this->listTableTriggers($referenced_table);
  1108. if (!MDB2::isError($triggers2) && !MDB2::isError($triggers)) {
  1109. $triggers = array_merge($triggers, $triggers2);
  1110. $pattern = '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i';
  1111. foreach ($triggers as $trigger) {
  1112. if (preg_match($pattern, $trigger)) {
  1113. $result = $db->exec('DROP TRIGGER '.$trigger);
  1114. if (MDB2::isError($result)) {
  1115. return $result;
  1116. }
  1117. }
  1118. }
  1119. }
  1120. return MDB2_OK;
  1121. }
  1122. // }}}
  1123. // {{{ listTableConstraints()
  1124. /**
  1125. * list all constraints in a table
  1126. *
  1127. * @param string $table name of table that should be used in method
  1128. * @return mixed array of constraint names on success, a MDB2 error on failure
  1129. * @access public
  1130. */
  1131. function listTableConstraints($table)
  1132. {
  1133. $db = $this->getDBInstance();
  1134. if (MDB2::isError($db)) {
  1135. return $db;
  1136. }
  1137. $table = $db->quote($table, 'text');
  1138. $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
  1139. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1140. $query.= 'LOWER(tbl_name)='.strtolower($table);
  1141. } else {
  1142. $query.= "tbl_name=$table";
  1143. }
  1144. $query.= " AND sql NOT NULL ORDER BY name";
  1145. $indexes = $db->queryCol($query, 'text');
  1146. if (MDB2::isError($indexes)) {
  1147. return $indexes;
  1148. }
  1149. $result = array();
  1150. foreach ($indexes as $sql) {
  1151. if (preg_match("/^create unique index ([^ ]+) on /i", $sql, $tmp)) {
  1152. $index = $this->_fixIndexName($tmp[1]);
  1153. if (!empty($index)) {
  1154. $result[$index] = true;
  1155. }
  1156. }
  1157. }
  1158. // also search in table definition for PRIMARY KEYs...
  1159. $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
  1160. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1161. $query.= 'LOWER(name)='.strtolower($table);
  1162. } else {
  1163. $query.= "name=$table";
  1164. }
  1165. $query.= " AND sql NOT NULL ORDER BY name";
  1166. $table_def = $db->queryOne($query, 'text');
  1167. if (MDB2::isError($table_def)) {
  1168. return $table_def;
  1169. }
  1170. if (preg_match("/\bPRIMARY\s+KEY\b/i", $table_def, $tmp)) {
  1171. $result['primary'] = true;
  1172. }
  1173. // ...and for FOREIGN KEYs
  1174. if (preg_match_all("/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN\s+KEY/imsx", $table_def, $tmp)) {
  1175. foreach ($tmp[1] as $fk) {
  1176. $result[$fk] = true;
  1177. }
  1178. }
  1179. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1180. $result = array_change_key_case($result, $db->options['field_case']);
  1181. }
  1182. return array_keys($result);
  1183. }
  1184. // }}}
  1185. // {{{ createSequence()
  1186. /**
  1187. * create sequence
  1188. *
  1189. * @param string $seq_name name of the sequence to be created
  1190. * @param string $start start value of the sequence; default is 1
  1191. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1192. * @access public
  1193. */
  1194. function createSequence($seq_name, $start = 1)
  1195. {
  1196. $db = $this->getDBInstance();
  1197. if (MDB2::isError($db)) {
  1198. return $db;
  1199. }
  1200. $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
  1201. $seqcol_name = $db->quoteIdentifier($db->options['seqcol_name'], true);
  1202. $query = "CREATE TABLE $sequence_name ($seqcol_name INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)";
  1203. $res = $db->exec($query);
  1204. if (MDB2::isError($res)) {
  1205. return $res;
  1206. }
  1207. if ($start == 1) {
  1208. return MDB2_OK;
  1209. }
  1210. $res = $db->exec("INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')');
  1211. if (!MDB2::isError($res)) {
  1212. return MDB2_OK;
  1213. }
  1214. // Handle error
  1215. $result = $db->exec("DROP TABLE $sequence_name");
  1216. if (MDB2::isError($result)) {
  1217. return $db->raiseError($result, null, null,
  1218. 'could not drop inconsistent sequence table', __FUNCTION__);
  1219. }
  1220. return $db->raiseError($res, null, null,
  1221. 'could not create sequence table', __FUNCTION__);
  1222. }
  1223. // }}}
  1224. // {{{ dropSequence()
  1225. /**
  1226. * drop existing sequence
  1227. *
  1228. * @param string $seq_name name of the sequence to be dropped
  1229. * @return mixed MDB2_OK on success, a MDB2 error on failure
  1230. * @access public
  1231. */
  1232. function dropSequence($seq_name)
  1233. {
  1234. $db = $this->getDBInstance();
  1235. if (MDB2::isError($db)) {
  1236. return $db;
  1237. }
  1238. $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
  1239. $result = $db->exec("DROP TABLE $sequence_name");
  1240. if (MDB2::isError($result)) {
  1241. return $result;
  1242. }
  1243. return MDB2_OK;
  1244. }
  1245. // }}}
  1246. // {{{ listSequences()
  1247. /**
  1248. * list all sequences in the current database
  1249. *
  1250. * @return mixed array of sequence names on success, a MDB2 error on failure
  1251. * @access public
  1252. */
  1253. function listSequences()
  1254. {
  1255. $db = $this->getDBInstance();
  1256. if (MDB2::isError($db)) {
  1257. return $db;
  1258. }
  1259. $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
  1260. $table_names = $db->queryCol($query);
  1261. if (MDB2::isError($table_names)) {
  1262. return $table_names;
  1263. }
  1264. $result = array();
  1265. foreach ($table_names as $table_name) {
  1266. if ($sqn = $this->_fixSequenceName($table_name, true)) {
  1267. $result[] = $sqn;
  1268. }
  1269. }
  1270. if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1271. $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
  1272. }
  1273. return $result;
  1274. }
  1275. // }}}
  1276. }
  1277. ?>