sqlite3.php 52 KB

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