Schema.php 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798
  1. <?php /* vim: se et ts=4 sw=4 sts=4 fdm=marker tw=80: */
  2. /**
  3. * Copyright (c) 1998-2010 Manuel Lemos, Tomas V.V.Cox,
  4. * Stig. S. Bakken, Lukas Smith, Igor Feghali
  5. * All rights reserved.
  6. *
  7. * MDB2_Schema enables users to maintain RDBMS independant schema files
  8. * in XML that can be used to manipulate both data and database schemas
  9. * This LICENSE is in the BSD license style.
  10. *
  11. * Redistribution and use in source and binary forms, with or without
  12. * modification, are permitted provided that the following conditions
  13. * are met:
  14. *
  15. * Redistributions of source code must retain the above copyright
  16. * notice, this list of conditions and the following disclaimer.
  17. *
  18. * Redistributions in binary form must reproduce the above copyright
  19. * notice, this list of conditions and the following disclaimer in the
  20. * documentation and/or other materials provided with the distribution.
  21. *
  22. * Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,
  23. * Lukas Smith, Igor Feghali nor the names of his contributors may be
  24. * used to endorse or promote products derived from this software
  25. * without specific prior written permission.
  26. *
  27. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  28. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  29. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  30. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  31. * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  32. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  33. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  34. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  35. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  36. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
  37. * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  38. * POSSIBILITY OF SUCH DAMAGE.
  39. *
  40. * PHP version 5
  41. *
  42. * @category Database
  43. * @package MDB2_Schema
  44. * @author Lukas Smith <smith@pooteeweet.org>
  45. * @author Igor Feghali <ifeghali@php.net>
  46. * @license BSD http://www.opensource.org/licenses/bsd-license.php
  47. * @version SVN: $Id$
  48. * @link http://pear.php.net/packages/MDB2_Schema
  49. */
  50. require_once 'MDB2.php';
  51. define('MDB2_SCHEMA_DUMP_ALL', 0);
  52. define('MDB2_SCHEMA_DUMP_STRUCTURE', 1);
  53. define('MDB2_SCHEMA_DUMP_CONTENT', 2);
  54. /**
  55. * If you add an error code here, make sure you also add a textual
  56. * version of it in MDB2_Schema::errorMessage().
  57. */
  58. define('MDB2_SCHEMA_ERROR', -1);
  59. define('MDB2_SCHEMA_ERROR_PARSE', -2);
  60. define('MDB2_SCHEMA_ERROR_VALIDATE', -3);
  61. define('MDB2_SCHEMA_ERROR_UNSUPPORTED', -4); // Driver does not support this function
  62. define('MDB2_SCHEMA_ERROR_INVALID', -5); // Invalid attribute value
  63. define('MDB2_SCHEMA_ERROR_WRITER', -6);
  64. /**
  65. * The database manager is a class that provides a set of database
  66. * management services like installing, altering and dumping the data
  67. * structures of databases.
  68. *
  69. * @category Database
  70. * @package MDB2_Schema
  71. * @author Lukas Smith <smith@pooteeweet.org>
  72. * @license BSD http://www.opensource.org/licenses/bsd-license.php
  73. * @link http://pear.php.net/packages/MDB2_Schema
  74. */
  75. class MDB2_Schema extends PEAR
  76. {
  77. // {{{ properties
  78. var $db;
  79. var $warnings = array();
  80. var $options = array(
  81. 'fail_on_invalid_names' => true,
  82. 'dtd_file' => false,
  83. 'valid_types' => array(),
  84. 'force_defaults' => true,
  85. 'parser' => 'MDB2_Schema_Parser',
  86. 'writer' => 'MDB2_Schema_Writer',
  87. 'validate' => 'MDB2_Schema_Validate',
  88. 'drop_obsolete_objects' => false
  89. );
  90. // }}}
  91. // {{{ apiVersion()
  92. /**
  93. * Return the MDB2 API version
  94. *
  95. * @return string the MDB2 API version number
  96. * @access public
  97. */
  98. function apiVersion()
  99. {
  100. return '0.4.3';
  101. }
  102. // }}}
  103. // {{{ arrayMergeClobber()
  104. /**
  105. * Clobbers two arrays together
  106. *
  107. * @param array $a1 array that should be clobbered
  108. * @param array $a2 array that should be clobbered
  109. *
  110. * @return array|false array on success and false on error
  111. *
  112. * @access public
  113. * @author kc@hireability.com
  114. */
  115. function arrayMergeClobber($a1, $a2)
  116. {
  117. if (!is_array($a1) || !is_array($a2)) {
  118. return false;
  119. }
  120. foreach ($a2 as $key => $val) {
  121. if (is_array($val) && array_key_exists($key, $a1) && is_array($a1[$key])) {
  122. $a1[$key] = MDB2_Schema::arrayMergeClobber($a1[$key], $val);
  123. } else {
  124. $a1[$key] = $val;
  125. }
  126. }
  127. return $a1;
  128. }
  129. // }}}
  130. // {{{ resetWarnings()
  131. /**
  132. * reset the warning array
  133. *
  134. * @access public
  135. * @return void
  136. */
  137. function resetWarnings()
  138. {
  139. $this->warnings = array();
  140. }
  141. // }}}
  142. // {{{ getWarnings()
  143. /**
  144. * Get all warnings in reverse order
  145. *
  146. * This means that the last warning is the first element in the array
  147. *
  148. * @return array with warnings
  149. * @access public
  150. * @see resetWarnings()
  151. */
  152. function getWarnings()
  153. {
  154. return array_reverse($this->warnings);
  155. }
  156. // }}}
  157. // {{{ setOption()
  158. /**
  159. * Sets the option for the db class
  160. *
  161. * @param string $option option name
  162. * @param mixed $value value for the option
  163. *
  164. * @return bool|MDB2_Error MDB2_OK or error object
  165. * @access public
  166. */
  167. function setOption($option, $value)
  168. {
  169. if (isset($this->options[$option])) {
  170. if (is_null($value)) {
  171. return $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
  172. 'may not set an option to value null');
  173. }
  174. $this->options[$option] = $value;
  175. return MDB2_OK;
  176. }
  177. return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
  178. "unknown option $option");
  179. }
  180. // }}}
  181. // {{{ getOption()
  182. /**
  183. * returns the value of an option
  184. *
  185. * @param string $option option name
  186. *
  187. * @return mixed the option value or error object
  188. * @access public
  189. */
  190. function getOption($option)
  191. {
  192. if (isset($this->options[$option])) {
  193. return $this->options[$option];
  194. }
  195. return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED,
  196. null, null, "unknown option $option");
  197. }
  198. // }}}
  199. // {{{ factory()
  200. /**
  201. * Create a new MDB2 object for the specified database type
  202. * type
  203. *
  204. * @param string|array|MDB2_Driver_Common &$db 'data source name', see the
  205. * MDB2::parseDSN method for a description of the dsn format.
  206. * Can also be specified as an array of the
  207. * format returned by @see MDB2::parseDSN.
  208. * Finally you can also pass an existing db object to be used.
  209. * @param array $options An associative array of option names and their values.
  210. *
  211. * @return bool|MDB2_Error MDB2_OK or error object
  212. * @access public
  213. * @see MDB2::parseDSN
  214. */
  215. static function &factory(&$db, $options = array())
  216. {
  217. $obj = new MDB2_Schema();
  218. $result = $obj->connect($db, $options);
  219. if (PEAR::isError($result)) {
  220. return $result;
  221. }
  222. return $obj;
  223. }
  224. // }}}
  225. // {{{ connect()
  226. /**
  227. * Create a new MDB2 connection object and connect to the specified
  228. * database
  229. *
  230. * @param string|array|MDB2_Driver_Common &$db 'data source name', see the
  231. * MDB2::parseDSN method for a description of the dsn format.
  232. * Can also be specified as an array of the
  233. * format returned by MDB2::parseDSN.
  234. * Finally you can also pass an existing db object to be used.
  235. * @param array $options An associative array of option names and their values.
  236. *
  237. * @return bool|MDB2_Error MDB2_OK or error object
  238. * @access public
  239. * @see MDB2::parseDSN
  240. */
  241. function connect(&$db, $options = array())
  242. {
  243. $db_options = array();
  244. if (is_array($options)) {
  245. foreach ($options as $option => $value) {
  246. if (array_key_exists($option, $this->options)) {
  247. $result = $this->setOption($option, $value);
  248. if (PEAR::isError($result)) {
  249. return $result;
  250. }
  251. } else {
  252. $db_options[$option] = $value;
  253. }
  254. }
  255. }
  256. $this->disconnect();
  257. if (!MDB2::isConnection($db)) {
  258. $db = MDB2::factory($db, $db_options);
  259. }
  260. if (PEAR::isError($db)) {
  261. return $db;
  262. }
  263. $this->db = $db;
  264. $this->db->loadModule('Datatype');
  265. $this->db->loadModule('Manager');
  266. $this->db->loadModule('Reverse');
  267. $this->db->loadModule('Function');
  268. if (empty($this->options['valid_types'])) {
  269. $this->options['valid_types'] = $this->db->datatype->getValidTypes();
  270. }
  271. return MDB2_OK;
  272. }
  273. // }}}
  274. // {{{ disconnect()
  275. /**
  276. * Log out and disconnect from the database.
  277. *
  278. * @access public
  279. * @return void
  280. */
  281. function disconnect()
  282. {
  283. if (MDB2::isConnection($this->db)) {
  284. $this->db->disconnect();
  285. unset($this->db);
  286. }
  287. }
  288. // }}}
  289. // {{{ parseDatabaseDefinition()
  290. /**
  291. * Parse a database definition from a file or an array
  292. *
  293. * @param string|array $schema the database schema array or file name
  294. * @param bool $skip_unreadable if non readable files should be skipped
  295. * @param array $variables associative array that the defines the text string values
  296. * that are meant to be used to replace the variables that are
  297. * used in the schema description.
  298. * @param bool $fail_on_invalid_names make function fail on invalid names
  299. * @param array $structure database structure definition
  300. *
  301. * @access public
  302. * @return array
  303. */
  304. function parseDatabaseDefinition($schema, $skip_unreadable = false, $variables = array(),
  305. $fail_on_invalid_names = true, $structure = false)
  306. {
  307. $database_definition = false;
  308. if (is_string($schema)) {
  309. // if $schema is not readable then we just skip it
  310. // and simply copy the $current_schema file to that file name
  311. if (is_readable($schema)) {
  312. $database_definition = $this->parseDatabaseDefinitionFile($schema, $variables, $fail_on_invalid_names, $structure);
  313. }
  314. } elseif (is_array($schema)) {
  315. $database_definition = $schema;
  316. }
  317. if (!$database_definition && !$skip_unreadable) {
  318. $database_definition = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
  319. 'invalid data type of schema or unreadable data source');
  320. }
  321. return $database_definition;
  322. }
  323. // }}}
  324. // {{{ parseDatabaseDefinitionFile()
  325. /**
  326. * Parse a database definition file by creating a schema format
  327. * parser object and passing the file contents as parser input data stream.
  328. *
  329. * @param string $input_file the database schema file.
  330. * @param array $variables associative array that the defines the text string values
  331. * that are meant to be used to replace the variables that are
  332. * used in the schema description.
  333. * @param bool $fail_on_invalid_names make function fail on invalid names
  334. * @param array $structure database structure definition
  335. *
  336. * @access public
  337. * @return array
  338. */
  339. function parseDatabaseDefinitionFile($input_file, $variables = array(),
  340. $fail_on_invalid_names = true, $structure = false)
  341. {
  342. $dtd_file = $this->options['dtd_file'];
  343. if ($dtd_file) {
  344. include_once 'XML/DTD/XmlValidator.php';
  345. $dtd = new XML_DTD_XmlValidator;
  346. if (!$dtd->isValid($dtd_file, $input_file)) {
  347. return $this->raiseError(MDB2_SCHEMA_ERROR_PARSE, null, null, $dtd->getMessage());
  348. }
  349. }
  350. $class_name = $this->options['parser'];
  351. $result = MDB2::loadClass($class_name, $this->db->getOption('debug'));
  352. if (PEAR::isError($result)) {
  353. return $result;
  354. }
  355. $max_identifiers_length = null;
  356. if (isset($this->db->options['max_identifiers_length'])) {
  357. $max_identifiers_length = $this->db->options['max_identifiers_length'];
  358. }
  359. $parser = new $class_name($variables, $fail_on_invalid_names, $structure,
  360. $this->options['valid_types'], $this->options['force_defaults'],
  361. $max_identifiers_length
  362. );
  363. $result = $parser->setInputFile($input_file);
  364. if (PEAR::isError($result)) {
  365. return $result;
  366. }
  367. $result = $parser->parse();
  368. if (PEAR::isError($result)) {
  369. return $result;
  370. }
  371. if (PEAR::isError($parser->error)) {
  372. return $parser->error;
  373. }
  374. return $parser->database_definition;
  375. }
  376. // }}}
  377. // {{{ getDefinitionFromDatabase()
  378. /**
  379. * Attempt to reverse engineer a schema structure from an existing MDB2
  380. * This method can be used if no xml schema file exists yet.
  381. * The resulting xml schema file may need some manual adjustments.
  382. *
  383. * @return array|MDB2_Error array with definition or error object
  384. * @access public
  385. */
  386. function getDefinitionFromDatabase()
  387. {
  388. $database = $this->db->database_name;
  389. if (empty($database)) {
  390. return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
  391. 'it was not specified a valid database name');
  392. }
  393. $class_name = $this->options['validate'];
  394. $result = MDB2::loadClass($class_name, $this->db->getOption('debug'));
  395. if (PEAR::isError($result)) {
  396. return $result;
  397. }
  398. $max_identifiers_length = null;
  399. if (isset($this->db->options['max_identifiers_length'])) {
  400. $max_identifiers_length = $this->db->options['max_identifiers_length'];
  401. }
  402. $val = new $class_name(
  403. $this->options['fail_on_invalid_names'],
  404. $this->options['valid_types'],
  405. $this->options['force_defaults'],
  406. $max_identifiers_length
  407. );
  408. $database_definition = array(
  409. 'name' => $database,
  410. 'create' => true,
  411. 'overwrite' => false,
  412. 'charset' => 'utf8',
  413. 'description' => '',
  414. 'comments' => '',
  415. 'tables' => array(),
  416. 'sequences' => array(),
  417. );
  418. $tables = $this->db->manager->listTables();
  419. if (PEAR::isError($tables)) {
  420. return $tables;
  421. }
  422. foreach ($tables as $table_name) {
  423. $fields = $this->db->manager->listTableFields($table_name);
  424. if (PEAR::isError($fields)) {
  425. return $fields;
  426. }
  427. $database_definition['tables'][$table_name] = array(
  428. 'was' => '',
  429. 'description' => '',
  430. 'comments' => '',
  431. 'fields' => array(),
  432. 'indexes' => array(),
  433. 'constraints' => array(),
  434. 'initialization' => array()
  435. );
  436. $table_definition = $database_definition['tables'][$table_name];
  437. foreach ($fields as $field_name) {
  438. $definition = $this->db->reverse->getTableFieldDefinition($table_name, $field_name);
  439. if (PEAR::isError($definition)) {
  440. return $definition;
  441. }
  442. if (!empty($definition[0]['autoincrement'])) {
  443. $definition[0]['default'] = '0';
  444. }
  445. $table_definition['fields'][$field_name] = $definition[0];
  446. $field_choices = count($definition);
  447. if ($field_choices > 1) {
  448. $warning = "There are $field_choices type choices in the table $table_name field $field_name (#1 is the default): ";
  449. $field_choice_cnt = 1;
  450. $table_definition['fields'][$field_name]['choices'] = array();
  451. foreach ($definition as $field_choice) {
  452. $table_definition['fields'][$field_name]['choices'][] = $field_choice;
  453. $warning .= 'choice #'.($field_choice_cnt).': '.serialize($field_choice);
  454. $field_choice_cnt++;
  455. }
  456. $this->warnings[] = $warning;
  457. }
  458. /**
  459. * The first parameter is used to verify if there are duplicated
  460. * fields which we can guarantee that won't happen when reverse engineering
  461. */
  462. $result = $val->validateField(array(), $table_definition['fields'][$field_name], $field_name);
  463. if (PEAR::isError($result)) {
  464. return $result;
  465. }
  466. }
  467. $keys = array();
  468. $indexes = $this->db->manager->listTableIndexes($table_name);
  469. if (PEAR::isError($indexes)) {
  470. return $indexes;
  471. }
  472. if (is_array($indexes)) {
  473. foreach ($indexes as $index_name) {
  474. $this->db->expectError(MDB2_ERROR_NOT_FOUND);
  475. $definition = $this->db->reverse->getTableIndexDefinition($table_name, $index_name);
  476. $this->db->popExpect();
  477. if (PEAR::isError($definition)) {
  478. if (PEAR::isError($definition, MDB2_ERROR_NOT_FOUND)) {
  479. continue;
  480. }
  481. return $definition;
  482. }
  483. $keys[$index_name] = $definition;
  484. }
  485. }
  486. $constraints = $this->db->manager->listTableConstraints($table_name);
  487. if (PEAR::isError($constraints)) {
  488. return $constraints;
  489. }
  490. if (is_array($constraints)) {
  491. foreach ($constraints as $constraint_name) {
  492. $this->db->expectError(MDB2_ERROR_NOT_FOUND);
  493. $definition = $this->db->reverse->getTableConstraintDefinition($table_name, $constraint_name);
  494. $this->db->popExpect();
  495. if (PEAR::isError($definition)) {
  496. if (PEAR::isError($definition, MDB2_ERROR_NOT_FOUND)) {
  497. continue;
  498. }
  499. return $definition;
  500. }
  501. $keys[$constraint_name] = $definition;
  502. }
  503. }
  504. foreach ($keys as $key_name => $definition) {
  505. if (array_key_exists('foreign', $definition)
  506. && $definition['foreign']
  507. ) {
  508. /**
  509. * The first parameter is used to verify if there are duplicated
  510. * foreign keys which we can guarantee that won't happen when reverse engineering
  511. */
  512. $result = $val->validateConstraint(array(), $definition, $key_name);
  513. if (PEAR::isError($result)) {
  514. return $result;
  515. }
  516. foreach ($definition['fields'] as $field_name => $field) {
  517. /**
  518. * The first parameter is used to verify if there are duplicated
  519. * referencing fields which we can guarantee that won't happen when reverse engineering
  520. */
  521. $result = $val->validateConstraintField(array(), $field_name);
  522. if (PEAR::isError($result)) {
  523. return $result;
  524. }
  525. $definition['fields'][$field_name] = '';
  526. }
  527. foreach ($definition['references']['fields'] as $field_name => $field) {
  528. /**
  529. * The first parameter is used to verify if there are duplicated
  530. * referenced fields which we can guarantee that won't happen when reverse engineering
  531. */
  532. $result = $val->validateConstraintReferencedField(array(), $field_name);
  533. if (PEAR::isError($result)) {
  534. return $result;
  535. }
  536. $definition['references']['fields'][$field_name] = '';
  537. }
  538. $table_definition['constraints'][$key_name] = $definition;
  539. } else {
  540. /**
  541. * The first parameter is used to verify if there are duplicated
  542. * indices which we can guarantee that won't happen when reverse engineering
  543. */
  544. $result = $val->validateIndex(array(), $definition, $key_name);
  545. if (PEAR::isError($result)) {
  546. return $result;
  547. }
  548. foreach ($definition['fields'] as $field_name => $field) {
  549. /**
  550. * The first parameter is used to verify if there are duplicated
  551. * index fields which we can guarantee that won't happen when reverse engineering
  552. */
  553. $result = $val->validateIndexField(array(), $field, $field_name);
  554. if (PEAR::isError($result)) {
  555. return $result;
  556. }
  557. $definition['fields'][$field_name] = $field;
  558. }
  559. $table_definition['indexes'][$key_name] = $definition;
  560. }
  561. }
  562. /**
  563. * The first parameter is used to verify if there are duplicated
  564. * tables which we can guarantee that won't happen when reverse engineering
  565. */
  566. $result = $val->validateTable(array(), $table_definition, $table_name);
  567. if (PEAR::isError($result)) {
  568. return $result;
  569. }
  570. $database_definition['tables'][$table_name]=$table_definition;
  571. }
  572. $sequences = $this->db->manager->listSequences();
  573. if (PEAR::isError($sequences)) {
  574. return $sequences;
  575. }
  576. if (is_array($sequences)) {
  577. foreach ($sequences as $sequence_name) {
  578. $definition = $this->db->reverse->getSequenceDefinition($sequence_name);
  579. if (PEAR::isError($definition)) {
  580. return $definition;
  581. }
  582. if (isset($database_definition['tables'][$sequence_name])
  583. && isset($database_definition['tables'][$sequence_name]['indexes'])
  584. ) {
  585. foreach ($database_definition['tables'][$sequence_name]['indexes'] as $index) {
  586. if (isset($index['primary']) && $index['primary']
  587. && count($index['fields'] == 1)
  588. ) {
  589. $definition['on'] = array(
  590. 'table' => $sequence_name,
  591. 'field' => key($index['fields']),
  592. );
  593. break;
  594. }
  595. }
  596. }
  597. /**
  598. * The first parameter is used to verify if there are duplicated
  599. * sequences which we can guarantee that won't happen when reverse engineering
  600. */
  601. $result = $val->validateSequence(array(), $definition, $sequence_name);
  602. if (PEAR::isError($result)) {
  603. return $result;
  604. }
  605. $database_definition['sequences'][$sequence_name] = $definition;
  606. }
  607. }
  608. $result = $val->validateDatabase($database_definition);
  609. if (PEAR::isError($result)) {
  610. return $result;
  611. }
  612. return $database_definition;
  613. }
  614. // }}}
  615. // {{{ createTableIndexes()
  616. /**
  617. * A method to create indexes for an existing table
  618. *
  619. * @param string $table_name Name of the table
  620. * @param array $indexes An array of indexes to be created
  621. * @param boolean $overwrite If the table/index should be overwritten if it already exists
  622. *
  623. * @return mixed MDB2_Error if there is an error creating an index, MDB2_OK otherwise
  624. * @access public
  625. */
  626. function createTableIndexes($table_name, $indexes, $overwrite = false)
  627. {
  628. if (!$this->db->supports('indexes')) {
  629. $this->db->debug('Indexes are not supported', __FUNCTION__);
  630. return MDB2_OK;
  631. }
  632. $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
  633. foreach ($indexes as $index_name => $index) {
  634. // Does the index already exist, and if so, should it be overwritten?
  635. $create_index = true;
  636. $this->db->expectError($errorcodes);
  637. if (!empty($index['primary']) || !empty($index['unique'])) {
  638. $current_indexes = $this->db->manager->listTableConstraints($table_name);
  639. } else {
  640. $current_indexes = $this->db->manager->listTableIndexes($table_name);
  641. }
  642. $this->db->popExpect();
  643. if (PEAR::isError($current_indexes)) {
  644. if (!MDB2::isError($current_indexes, $errorcodes)) {
  645. return $current_indexes;
  646. }
  647. } elseif (is_array($current_indexes) && in_array($index_name, $current_indexes)) {
  648. if (!$overwrite) {
  649. $this->db->debug('Index already exists: '.$index_name, __FUNCTION__);
  650. $create_index = false;
  651. } else {
  652. $this->db->debug('Preparing to overwrite index: '.$index_name, __FUNCTION__);
  653. $this->db->expectError(MDB2_ERROR_NOT_FOUND);
  654. if (!empty($index['primary']) || !empty($index['unique'])) {
  655. $result = $this->db->manager->dropConstraint($table_name, $index_name);
  656. } else {
  657. $result = $this->db->manager->dropIndex($table_name, $index_name);
  658. }
  659. $this->db->popExpect();
  660. if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_NOT_FOUND)) {
  661. return $result;
  662. }
  663. }
  664. }
  665. // Check if primary is being used and if it's supported
  666. if (!empty($index['primary']) && !$this->db->supports('primary_key')) {
  667. // Primary not supported so we fallback to UNIQUE and making the field NOT NULL
  668. $index['unique'] = true;
  669. $changes = array();
  670. foreach ($index['fields'] as $field => $empty) {
  671. $field_info = $this->db->reverse->getTableFieldDefinition($table_name, $field);
  672. if (PEAR::isError($field_info)) {
  673. return $field_info;
  674. }
  675. if (!$field_info[0]['notnull']) {
  676. $changes['change'][$field] = $field_info[0];
  677. $changes['change'][$field]['notnull'] = true;
  678. }
  679. }
  680. if (!empty($changes)) {
  681. $this->db->manager->alterTable($table_name, $changes, false);
  682. }
  683. }
  684. // Should the index be created?
  685. if ($create_index) {
  686. if (!empty($index['primary']) || !empty($index['unique'])) {
  687. $result = $this->db->manager->createConstraint($table_name, $index_name, $index);
  688. } else {
  689. $result = $this->db->manager->createIndex($table_name, $index_name, $index);
  690. }
  691. if (PEAR::isError($result)) {
  692. return $result;
  693. }
  694. }
  695. }
  696. return MDB2_OK;
  697. }
  698. // }}}
  699. // {{{ createTableConstraints()
  700. /**
  701. * A method to create foreign keys for an existing table
  702. *
  703. * @param string $table_name Name of the table
  704. * @param array $constraints An array of foreign keys to be created
  705. * @param boolean $overwrite If the foreign key should be overwritten if it already exists
  706. *
  707. * @return mixed MDB2_Error if there is an error creating a foreign key, MDB2_OK otherwise
  708. * @access public
  709. */
  710. function createTableConstraints($table_name, $constraints, $overwrite = false)
  711. {
  712. if (!$this->db->supports('indexes')) {
  713. $this->db->debug('Indexes are not supported', __FUNCTION__);
  714. return MDB2_OK;
  715. }
  716. $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
  717. foreach ($constraints as $constraint_name => $constraint) {
  718. // Does the foreign key already exist, and if so, should it be overwritten?
  719. $create_constraint = true;
  720. $this->db->expectError($errorcodes);
  721. $current_constraints = $this->db->manager->listTableConstraints($table_name);
  722. $this->db->popExpect();
  723. if (PEAR::isError($current_constraints)) {
  724. if (!MDB2::isError($current_constraints, $errorcodes)) {
  725. return $current_constraints;
  726. }
  727. } elseif (is_array($current_constraints) && in_array($constraint_name, $current_constraints)) {
  728. if (!$overwrite) {
  729. $this->db->debug('Foreign key already exists: '.$constraint_name, __FUNCTION__);
  730. $create_constraint = false;
  731. } else {
  732. $this->db->debug('Preparing to overwrite foreign key: '.$constraint_name, __FUNCTION__);
  733. $result = $this->db->manager->dropConstraint($table_name, $constraint_name);
  734. if (PEAR::isError($result)) {
  735. return $result;
  736. }
  737. }
  738. }
  739. // Should the foreign key be created?
  740. if ($create_constraint) {
  741. $result = $this->db->manager->createConstraint($table_name, $constraint_name, $constraint);
  742. if (PEAR::isError($result)) {
  743. return $result;
  744. }
  745. }
  746. }
  747. return MDB2_OK;
  748. }
  749. // }}}
  750. // {{{ createTable()
  751. /**
  752. * Create a table and inititialize the table if data is available
  753. *
  754. * @param string $table_name name of the table to be created
  755. * @param array $table multi dimensional array that contains the
  756. * structure and optional data of the table
  757. * @param bool $overwrite if the table/index should be overwritten if it already exists
  758. * @param array $options an array of options to be passed to the database specific driver
  759. * version of MDB2_Driver_Manager_Common::createTable().
  760. *
  761. * @return bool|MDB2_Error MDB2_OK or error object
  762. * @access public
  763. */
  764. function createTable($table_name, $table, $overwrite = false, $options = array())
  765. {
  766. $create = true;
  767. $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
  768. $this->db->expectError($errorcodes);
  769. $tables = $this->db->manager->listTables();
  770. $this->db->popExpect();
  771. if (PEAR::isError($tables)) {
  772. if (!MDB2::isError($tables, $errorcodes)) {
  773. return $tables;
  774. }
  775. } elseif (is_array($tables) && in_array($table_name, $tables)) {
  776. if (!$overwrite) {
  777. $create = false;
  778. $this->db->debug('Table already exists: '.$table_name, __FUNCTION__);
  779. } else {
  780. $result = $this->db->manager->dropTable($table_name);
  781. if (PEAR::isError($result)) {
  782. return $result;
  783. }
  784. $this->db->debug('Overwritting table: '.$table_name, __FUNCTION__);
  785. }
  786. }
  787. if ($create) {
  788. $result = $this->db->manager->createTable($table_name, $table['fields'], $options);
  789. if (PEAR::isError($result)) {
  790. return $result;
  791. }
  792. }
  793. if (!empty($table['initialization']) && is_array($table['initialization'])) {
  794. $result = $this->initializeTable($table_name, $table);
  795. if (PEAR::isError($result)) {
  796. return $result;
  797. }
  798. }
  799. if (!empty($table['indexes']) && is_array($table['indexes'])) {
  800. $result = $this->createTableIndexes($table_name, $table['indexes'], $overwrite);
  801. if (PEAR::isError($result)) {
  802. return $result;
  803. }
  804. }
  805. if (!empty($table['constraints']) && is_array($table['constraints'])) {
  806. $result = $this->createTableConstraints($table_name, $table['constraints'], $overwrite);
  807. if (PEAR::isError($result)) {
  808. return $result;
  809. }
  810. }
  811. return MDB2_OK;
  812. }
  813. // }}}
  814. // {{{ initializeTable()
  815. /**
  816. * Inititialize the table with data
  817. *
  818. * @param string $table_name name of the table
  819. * @param array $table multi dimensional array that contains the
  820. * structure and optional data of the table
  821. *
  822. * @return bool|MDB2_Error MDB2_OK or error object
  823. * @access public
  824. */
  825. function initializeTable($table_name, $table)
  826. {
  827. $query_insertselect = 'INSERT INTO %s (%s) (SELECT %s FROM %s %s)';
  828. $query_insert = 'INSERT INTO %s (%s) VALUES (%s)';
  829. $query_update = 'UPDATE %s SET %s %s';
  830. $query_delete = 'DELETE FROM %s %s';
  831. $table_name = $this->db->quoteIdentifier($table_name, true);
  832. $result = MDB2_OK;
  833. $support_transactions = $this->db->supports('transactions');
  834. foreach ($table['initialization'] as $instruction) {
  835. $query = '';
  836. switch ($instruction['type']) {
  837. case 'insert':
  838. if (!isset($instruction['data']['select'])) {
  839. $data = $this->getInstructionFields($instruction['data'], $table['fields']);
  840. if (!empty($data)) {
  841. $fields = implode(', ', array_keys($data));
  842. $values = implode(', ', array_values($data));
  843. $query = sprintf($query_insert, $table_name, $fields, $values);
  844. }
  845. } else {
  846. $data = $this->getInstructionFields($instruction['data']['select'], $table['fields']);
  847. $where = $this->getInstructionWhere($instruction['data']['select'], $table['fields']);
  848. $select_table_name = $this->db->quoteIdentifier($instruction['data']['select']['table'], true);
  849. if (!empty($data)) {
  850. $fields = implode(', ', array_keys($data));
  851. $values = implode(', ', array_values($data));
  852. $query = sprintf($query_insertselect, $table_name, $fields, $values, $select_table_name, $where);
  853. }
  854. }
  855. break;
  856. case 'update':
  857. $data = $this->getInstructionFields($instruction['data'], $table['fields']);
  858. $where = $this->getInstructionWhere($instruction['data'], $table['fields']);
  859. if (!empty($data)) {
  860. array_walk($data, array($this, 'buildFieldValue'));
  861. $fields_values = implode(', ', $data);
  862. $query = sprintf($query_update, $table_name, $fields_values, $where);
  863. }
  864. break;
  865. case 'delete':
  866. $where = $this->getInstructionWhere($instruction['data'], $table['fields']);
  867. $query = sprintf($query_delete, $table_name, $where);
  868. break;
  869. }
  870. if ($query) {
  871. if ($support_transactions && PEAR::isError($res = $this->db->beginNestedTransaction())) {
  872. return $res;
  873. }
  874. $result = $this->db->exec($query);
  875. if (PEAR::isError($result)) {
  876. return $result;
  877. }
  878. if ($support_transactions && PEAR::isError($res = $this->db->completeNestedTransaction())) {
  879. return $res;
  880. }
  881. }
  882. }
  883. return $result;
  884. }
  885. // }}}
  886. // {{{ buildFieldValue()
  887. /**
  888. * Appends the contents of second argument + '=' to the beginning of first
  889. * argument.
  890. *
  891. * Used with array_walk() in initializeTable() for UPDATEs.
  892. *
  893. * @param string &$element value of array's element
  894. * @param string $key key of array's element
  895. *
  896. * @return void
  897. *
  898. * @access public
  899. * @see MDB2_Schema::initializeTable()
  900. */
  901. function buildFieldValue(&$element, $key)
  902. {
  903. $element = $key."=$element";
  904. }
  905. // }}}
  906. // {{{ getExpression()
  907. /**
  908. * Generates a string that represents a value that would be associated
  909. * with a column in a DML instruction.
  910. *
  911. * @param array $element multi dimensional array that contains the
  912. * structure of the current DML instruction.
  913. * @param array $fields_definition multi dimensional array that contains the
  914. * definition for current table's fields
  915. * @param string $type type of given field
  916. *
  917. * @return string
  918. *
  919. * @access public
  920. * @see MDB2_Schema::getInstructionFields(), MDB2_Schema::getInstructionWhere()
  921. */
  922. function getExpression($element, $fields_definition = array(), $type = null)
  923. {
  924. $str = '';
  925. switch ($element['type']) {
  926. case 'null':
  927. $str .= 'NULL';
  928. break;
  929. case 'value':
  930. $str .= $this->db->quote($element['data'], $type);
  931. break;
  932. case 'column':
  933. $str .= $this->db->quoteIdentifier($element['data'], true);
  934. break;
  935. case 'function':
  936. $arguments = array();
  937. if (!empty($element['data']['arguments'])
  938. && is_array($element['data']['arguments'])
  939. ) {
  940. foreach ($element['data']['arguments'] as $v) {
  941. $arguments[] = $this->getExpression($v, $fields_definition);
  942. }
  943. }
  944. if (method_exists($this->db->function, $element['data']['name'])) {
  945. $user_func = array(&$this->db->function, $element['data']['name']);
  946. $str .= call_user_func_array($user_func, $arguments);
  947. } else {
  948. $str .= $element['data']['name'].'(';
  949. $str .= implode(', ', $arguments);
  950. $str .= ')';
  951. }
  952. break;
  953. case 'expression':
  954. $type0 = $type1 = null;
  955. if ($element['data']['operants'][0]['type'] == 'column'
  956. && array_key_exists($element['data']['operants'][0]['data'], $fields_definition)
  957. ) {
  958. $type0 = $fields_definition[$element['data']['operants'][0]['data']]['type'];
  959. }
  960. if ($element['data']['operants'][1]['type'] == 'column'
  961. && array_key_exists($element['data']['operants'][1]['data'], $fields_definition)
  962. ) {
  963. $type1 = $fields_definition[$element['data']['operants'][1]['data']]['type'];
  964. }
  965. $str .= '(';
  966. $str .= $this->getExpression($element['data']['operants'][0], $fields_definition, $type1);
  967. $str .= $this->getOperator($element['data']['operator']);
  968. $str .= $this->getExpression($element['data']['operants'][1], $fields_definition, $type0);
  969. $str .= ')';
  970. break;
  971. }
  972. return $str;
  973. }
  974. // }}}
  975. // {{{ getOperator()
  976. /**
  977. * Returns the matching SQL operator
  978. *
  979. * @param string $op parsed descriptive operator
  980. *
  981. * @return string matching SQL operator
  982. *
  983. * @access public
  984. * @static
  985. * @see MDB2_Schema::getExpression()
  986. */
  987. function getOperator($op)
  988. {
  989. switch ($op) {
  990. case 'PLUS':
  991. return ' + ';
  992. case 'MINUS':
  993. return ' - ';
  994. case 'TIMES':
  995. return ' * ';
  996. case 'DIVIDED':
  997. return ' / ';
  998. case 'EQUAL':
  999. return ' = ';
  1000. case 'NOT EQUAL':
  1001. return ' != ';
  1002. case 'LESS THAN':
  1003. return ' < ';
  1004. case 'GREATER THAN':
  1005. return ' > ';
  1006. case 'LESS THAN OR EQUAL':
  1007. return ' <= ';
  1008. case 'GREATER THAN OR EQUAL':
  1009. return ' >= ';
  1010. default:
  1011. return ' '.$op.' ';
  1012. }
  1013. }
  1014. // }}}
  1015. // {{{ getInstructionFields()
  1016. /**
  1017. * Walks the parsed DML instruction array, field by field,
  1018. * storing them and their processed values inside a new array.
  1019. *
  1020. * @param array $instruction multi dimensional array that contains the
  1021. * structure of the current DML instruction.
  1022. * @param array $fields_definition multi dimensional array that contains the
  1023. * definition for current table's fields
  1024. *
  1025. * @return array array of strings in the form 'field_name' => 'value'
  1026. *
  1027. * @access public
  1028. * @static
  1029. * @see MDB2_Schema::initializeTable()
  1030. */
  1031. function getInstructionFields($instruction, $fields_definition = array())
  1032. {
  1033. $fields = array();
  1034. if (!empty($instruction['field']) && is_array($instruction['field'])) {
  1035. foreach ($instruction['field'] as $field) {
  1036. $field_name = $this->db->quoteIdentifier($field['name'], true);
  1037. $fields[$field_name] = $this->getExpression($field['group'], $fields_definition);
  1038. }
  1039. }
  1040. return $fields;
  1041. }
  1042. // }}}
  1043. // {{{ getInstructionWhere()
  1044. /**
  1045. * Translates the parsed WHERE expression of a DML instruction
  1046. * (array structure) to a SQL WHERE clause (string).
  1047. *
  1048. * @param array $instruction multi dimensional array that contains the
  1049. * structure of the current DML instruction.
  1050. * @param array $fields_definition multi dimensional array that contains the
  1051. * definition for current table's fields.
  1052. *
  1053. * @return string SQL WHERE clause
  1054. *
  1055. * @access public
  1056. * @static
  1057. * @see MDB2_Schema::initializeTable()
  1058. */
  1059. function getInstructionWhere($instruction, $fields_definition = array())
  1060. {
  1061. $where = '';
  1062. if (!empty($instruction['where'])) {
  1063. $where = 'WHERE '.$this->getExpression($instruction['where'], $fields_definition);
  1064. }
  1065. return $where;
  1066. }
  1067. // }}}
  1068. // {{{ createSequence()
  1069. /**
  1070. * Create a sequence
  1071. *
  1072. * @param string $sequence_name name of the sequence to be created
  1073. * @param array $sequence multi dimensional array that contains the
  1074. * structure and optional data of the table
  1075. * @param bool $overwrite if the sequence should be overwritten if it already exists
  1076. *
  1077. * @return bool|MDB2_Error MDB2_OK or error object
  1078. * @access public
  1079. */
  1080. function createSequence($sequence_name, $sequence, $overwrite = false)
  1081. {
  1082. if (!$this->db->supports('sequences')) {
  1083. $this->db->debug('Sequences are not supported', __FUNCTION__);
  1084. return MDB2_OK;
  1085. }
  1086. $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
  1087. $this->db->expectError($errorcodes);
  1088. $sequences = $this->db->manager->listSequences();
  1089. $this->db->popExpect();
  1090. if (PEAR::isError($sequences)) {
  1091. if (!MDB2::isError($sequences, $errorcodes)) {
  1092. return $sequences;
  1093. }
  1094. } elseif (is_array($sequence) && in_array($sequence_name, $sequences)) {
  1095. if (!$overwrite) {
  1096. $this->db->debug('Sequence already exists: '.$sequence_name, __FUNCTION__);
  1097. return MDB2_OK;
  1098. }
  1099. $result = $this->db->manager->dropSequence($sequence_name);
  1100. if (PEAR::isError($result)) {
  1101. return $result;
  1102. }
  1103. $this->db->debug('Overwritting sequence: '.$sequence_name, __FUNCTION__);
  1104. }
  1105. $start = 1;
  1106. $field = '';
  1107. if (!empty($sequence['on'])) {
  1108. $table = $sequence['on']['table'];
  1109. $field = $sequence['on']['field'];
  1110. $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
  1111. $this->db->expectError($errorcodes);
  1112. $tables = $this->db->manager->listTables();
  1113. $this->db->popExpect();
  1114. if (PEAR::isError($tables) && !MDB2::isError($tables, $errorcodes)) {
  1115. return $tables;
  1116. }
  1117. if (!PEAR::isError($tables) && is_array($tables) && in_array($table, $tables)) {
  1118. if ($this->db->supports('summary_functions')) {
  1119. $query = "SELECT MAX($field) FROM ".$this->db->quoteIdentifier($table, true);
  1120. } else {
  1121. $query = "SELECT $field FROM ".$this->db->quoteIdentifier($table, true)." ORDER BY $field DESC";
  1122. }
  1123. $start = $this->db->queryOne($query, 'integer');
  1124. if (PEAR::isError($start)) {
  1125. return $start;
  1126. }
  1127. ++$start;
  1128. } else {
  1129. $this->warnings[] = 'Could not sync sequence: '.$sequence_name;
  1130. }
  1131. } elseif (!empty($sequence['start']) && is_numeric($sequence['start'])) {
  1132. $start = $sequence['start'];
  1133. $table = '';
  1134. }
  1135. $result = $this->db->manager->createSequence($sequence_name, $start);
  1136. if (PEAR::isError($result)) {
  1137. return $result;
  1138. }
  1139. return MDB2_OK;
  1140. }
  1141. // }}}
  1142. // {{{ createDatabase()
  1143. /**
  1144. * Create a database space within which may be created database objects
  1145. * like tables, indexes and sequences. The implementation of this function
  1146. * is highly DBMS specific and may require special permissions to run
  1147. * successfully. Consult the documentation or the DBMS drivers that you
  1148. * use to be aware of eventual configuration requirements.
  1149. *
  1150. * @param array $database_definition multi dimensional array that contains the current definition
  1151. * @param array $options an array of options to be passed to the
  1152. * database specific driver version of
  1153. * MDB2_Driver_Manager_Common::createTable().
  1154. *
  1155. * @return bool|MDB2_Error MDB2_OK or error object
  1156. * @access public
  1157. */
  1158. function createDatabase($database_definition, $options = array())
  1159. {
  1160. if (!isset($database_definition['name']) || !$database_definition['name']) {
  1161. return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
  1162. 'no valid database name specified');
  1163. }
  1164. $create = (isset($database_definition['create']) && $database_definition['create']);
  1165. $overwrite = (isset($database_definition['overwrite']) && $database_definition['overwrite']);
  1166. /**
  1167. *
  1168. * We need to clean up database name before any query to prevent
  1169. * database driver from using a inexistent database
  1170. *
  1171. */
  1172. $previous_database_name = $this->db->setDatabase('');
  1173. // Lower / Upper case the db name if the portability deems so.
  1174. if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
  1175. $func = $this->db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper';
  1176. $db_name = $func($database_definition['name']);
  1177. } else {
  1178. $db_name = $database_definition['name'];
  1179. }
  1180. if ($create) {
  1181. $dbExists = $this->db->databaseExists($db_name);
  1182. if (PEAR::isError($dbExists)) {
  1183. return $dbExists;
  1184. }
  1185. if ($dbExists && $overwrite) {
  1186. $this->db->expectError(MDB2_ERROR_CANNOT_DROP);
  1187. $result = $this->db->manager->dropDatabase($db_name);
  1188. $this->db->popExpect();
  1189. if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_CANNOT_DROP)) {
  1190. return $result;
  1191. }
  1192. $dbExists = false;
  1193. $this->db->debug('Overwritting database: ' . $db_name, __FUNCTION__);
  1194. }
  1195. $dbOptions = array();
  1196. if (array_key_exists('charset', $database_definition)
  1197. && !empty($database_definition['charset'])) {
  1198. $dbOptions['charset'] = $database_definition['charset'];
  1199. }
  1200. if ($dbExists) {
  1201. $this->db->debug('Database already exists: ' . $db_name, __FUNCTION__);
  1202. if (!empty($dbOptions)) {
  1203. $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NO_PERMISSION);
  1204. $this->db->expectError($errorcodes);
  1205. $result = $this->db->manager->alterDatabase($db_name, $dbOptions);
  1206. $this->db->popExpect();
  1207. if (PEAR::isError($result) && !MDB2::isError($result, $errorcodes)) {
  1208. return $result;
  1209. }
  1210. }
  1211. $create = false;
  1212. } else {
  1213. $this->db->expectError(MDB2_ERROR_UNSUPPORTED);
  1214. $result = $this->db->manager->createDatabase($db_name, $dbOptions);
  1215. $this->db->popExpect();
  1216. if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_UNSUPPORTED)) {
  1217. return $result;
  1218. }
  1219. $this->db->debug('Creating database: ' . $db_name, __FUNCTION__);
  1220. }
  1221. }
  1222. $this->db->setDatabase($db_name);
  1223. if (($support_transactions = $this->db->supports('transactions'))
  1224. && PEAR::isError($result = $this->db->beginNestedTransaction())
  1225. ) {
  1226. return $result;
  1227. }
  1228. $created_objects = 0;
  1229. if (isset($database_definition['tables'])
  1230. && is_array($database_definition['tables'])
  1231. ) {
  1232. foreach ($database_definition['tables'] as $table_name => $table) {
  1233. $result = $this->createTable($table_name, $table, $overwrite, $options);
  1234. if (PEAR::isError($result)) {
  1235. break;
  1236. }
  1237. $created_objects++;
  1238. }
  1239. }
  1240. if (!PEAR::isError($result)
  1241. && isset($database_definition['sequences'])
  1242. && is_array($database_definition['sequences'])
  1243. ) {
  1244. foreach ($database_definition['sequences'] as $sequence_name => $sequence) {
  1245. $result = $this->createSequence($sequence_name, $sequence, false, $overwrite);
  1246. if (PEAR::isError($result)) {
  1247. break;
  1248. }
  1249. $created_objects++;
  1250. }
  1251. }
  1252. if ($support_transactions) {
  1253. $res = $this->db->completeNestedTransaction();
  1254. if (PEAR::isError($res)) {
  1255. $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
  1256. 'Could not end transaction ('.
  1257. $res->getMessage().' ('.$res->getUserinfo().'))');
  1258. }
  1259. } elseif (PEAR::isError($result) && $created_objects) {
  1260. $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
  1261. 'the database was only partially created ('.
  1262. $result->getMessage().' ('.$result->getUserinfo().'))');
  1263. }
  1264. $this->db->setDatabase($previous_database_name);
  1265. if (PEAR::isError($result) && $create
  1266. && PEAR::isError($result2 = $this->db->manager->dropDatabase($db_name))
  1267. ) {
  1268. if (!MDB2::isError($result2, MDB2_ERROR_UNSUPPORTED)) {
  1269. return $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
  1270. 'Could not drop the created database after unsuccessful creation attempt ('.
  1271. $result2->getMessage().' ('.$result2->getUserinfo().'))');
  1272. }
  1273. }
  1274. return $result;
  1275. }
  1276. // }}}
  1277. // {{{ compareDefinitions()
  1278. /**
  1279. * Compare a previous definition with the currently parsed definition
  1280. *
  1281. * @param array $current_definition multi dimensional array that contains the current definition
  1282. * @param array $previous_definition multi dimensional array that contains the previous definition
  1283. *
  1284. * @return array|MDB2_Error array of changes on success, or a error object
  1285. * @access public
  1286. */
  1287. function compareDefinitions($current_definition, $previous_definition)
  1288. {
  1289. $changes = array();
  1290. if (!empty($current_definition['tables']) && is_array($current_definition['tables'])) {
  1291. $changes['tables'] = $defined_tables = array();
  1292. foreach ($current_definition['tables'] as $table_name => $table) {
  1293. $previous_tables = array();
  1294. if (!empty($previous_definition) && is_array($previous_definition)) {
  1295. $previous_tables = $previous_definition['tables'];
  1296. }
  1297. $change = $this->compareTableDefinitions($table_name, $table, $previous_tables, $defined_tables);
  1298. if (PEAR::isError($change)) {
  1299. return $change;
  1300. }
  1301. if (!empty($change)) {
  1302. $changes['tables'] = MDB2_Schema::arrayMergeClobber($changes['tables'], $change);
  1303. }
  1304. }
  1305. }
  1306. if (!empty($previous_definition['tables'])
  1307. && is_array($previous_definition['tables'])
  1308. ) {
  1309. foreach ($previous_definition['tables'] as $table_name => $table) {
  1310. if (empty($defined_tables[$table_name])) {
  1311. $changes['tables']['remove'][$table_name] = true;
  1312. }
  1313. }
  1314. }
  1315. if (!empty($current_definition['sequences']) && is_array($current_definition['sequences'])) {
  1316. $changes['sequences'] = $defined_sequences = array();
  1317. foreach ($current_definition['sequences'] as $sequence_name => $sequence) {
  1318. $previous_sequences = array();
  1319. if (!empty($previous_definition) && is_array($previous_definition)) {
  1320. $previous_sequences = $previous_definition['sequences'];
  1321. }
  1322. $change = $this->compareSequenceDefinitions($sequence_name,
  1323. $sequence,
  1324. $previous_sequences,
  1325. $defined_sequences);
  1326. if (PEAR::isError($change)) {
  1327. return $change;
  1328. }
  1329. if (!empty($change)) {
  1330. $changes['sequences'] = MDB2_Schema::arrayMergeClobber($changes['sequences'], $change);
  1331. }
  1332. }
  1333. }
  1334. if (!empty($previous_definition['sequences'])
  1335. && is_array($previous_definition['sequences'])
  1336. ) {
  1337. foreach ($previous_definition['sequences'] as $sequence_name => $sequence) {
  1338. if (empty($defined_sequences[$sequence_name])) {
  1339. $changes['sequences']['remove'][$sequence_name] = true;
  1340. }
  1341. }
  1342. }
  1343. return $changes;
  1344. }
  1345. // }}}
  1346. // {{{ compareTableFieldsDefinitions()
  1347. /**
  1348. * Compare a previous definition with the currently parsed definition
  1349. *
  1350. * @param string $table_name name of the table
  1351. * @param array $current_definition multi dimensional array that contains the current definition
  1352. * @param array $previous_definition multi dimensional array that contains the previous definition
  1353. *
  1354. * @return array|MDB2_Error array of changes on success, or a error object
  1355. * @access public
  1356. */
  1357. function compareTableFieldsDefinitions($table_name, $current_definition,
  1358. $previous_definition)
  1359. {
  1360. $changes = $defined_fields = array();
  1361. if (is_array($current_definition)) {
  1362. foreach ($current_definition as $field_name => $field) {
  1363. $was_field_name = $field['was'];
  1364. if (!empty($previous_definition[$field_name])
  1365. && (
  1366. (isset($previous_definition[$field_name]['was'])
  1367. && $previous_definition[$field_name]['was'] == $was_field_name)
  1368. || !isset($previous_definition[$was_field_name])
  1369. )) {
  1370. $was_field_name = $field_name;
  1371. }
  1372. if (!empty($previous_definition[$was_field_name])) {
  1373. if ($was_field_name != $field_name) {
  1374. $changes['rename'][$was_field_name] = array('name' => $field_name, 'definition' => $field);
  1375. }
  1376. if (!empty($defined_fields[$was_field_name])) {
  1377. return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
  1378. 'the field "'.$was_field_name.
  1379. '" was specified for more than one field of table');
  1380. }
  1381. $defined_fields[$was_field_name] = true;
  1382. $change = $this->db->compareDefinition($field, $previous_definition[$was_field_name]);
  1383. if (PEAR::isError($change)) {
  1384. return $change;
  1385. }
  1386. if (!empty($change)) {
  1387. if (array_key_exists('default', $change)
  1388. && $change['default']
  1389. && !array_key_exists('default', $field)) {
  1390. $field['default'] = null;
  1391. }
  1392. $change['definition'] = $field;
  1393. $changes['change'][$field_name] = $change;
  1394. }
  1395. } else {
  1396. if ($field_name != $was_field_name) {
  1397. return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
  1398. 'it was specified a previous field name ("'.
  1399. $was_field_name.'") for field "'.$field_name.'" of table "'.
  1400. $table_name.'" that does not exist');
  1401. }
  1402. $changes['add'][$field_name] = $field;
  1403. }
  1404. }
  1405. }
  1406. if (isset($previous_definition) && is_array($previous_definition)) {
  1407. foreach ($previous_definition as $field_previous_name => $field_previous) {
  1408. if (empty($defined_fields[$field_previous_name])) {
  1409. $changes['remove'][$field_previous_name] = true;
  1410. }
  1411. }
  1412. }
  1413. return $changes;
  1414. }
  1415. // }}}
  1416. // {{{ compareTableIndexesDefinitions()
  1417. /**
  1418. * Compare a previous definition with the currently parsed definition
  1419. *
  1420. * @param string $table_name name of the table
  1421. * @param array $current_definition multi dimensional array that contains the current definition
  1422. * @param array $previous_definition multi dimensional array that contains the previous definition
  1423. *
  1424. * @return array|MDB2_Error array of changes on success, or a error object
  1425. * @access public
  1426. */
  1427. function compareTableIndexesDefinitions($table_name, $current_definition,
  1428. $previous_definition)
  1429. {
  1430. $changes = $defined_indexes = array();
  1431. if (is_array($current_definition)) {
  1432. foreach ($current_definition as $index_name => $index) {
  1433. $was_index_name = $index['was'];
  1434. if (!empty($previous_definition[$index_name])
  1435. && isset($previous_definition[$index_name]['was'])
  1436. && $previous_definition[$index_name]['was'] == $was_index_name
  1437. ) {
  1438. $was_index_name = $index_name;
  1439. }
  1440. if (!empty($previous_definition[$was_index_name])) {
  1441. $change = array();
  1442. if ($was_index_name != $index_name) {
  1443. $change['name'] = $was_index_name;
  1444. }
  1445. if (!empty($defined_indexes[$was_index_name])) {
  1446. return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
  1447. 'the index "'.$was_index_name.'" was specified for'.
  1448. ' more than one index of table "'.$table_name.'"');
  1449. }
  1450. $defined_indexes[$was_index_name] = true;
  1451. $previous_unique = array_key_exists('unique', $previous_definition[$was_index_name])
  1452. ? $previous_definition[$was_index_name]['unique'] : false;
  1453. $unique = array_key_exists('unique', $index) ? $index['unique'] : false;
  1454. if ($previous_unique != $unique) {
  1455. $change['unique'] = $unique;
  1456. }
  1457. $previous_primary = array_key_exists('primary', $previous_definition[$was_index_name])
  1458. ? $previous_definition[$was_index_name]['primary'] : false;
  1459. $primary = array_key_exists('primary', $index) ? $index['primary'] : false;
  1460. if ($previous_primary != $primary) {
  1461. $change['primary'] = $primary;
  1462. }
  1463. $defined_fields = array();
  1464. $previous_fields = $previous_definition[$was_index_name]['fields'];
  1465. if (!empty($index['fields']) && is_array($index['fields'])) {
  1466. foreach ($index['fields'] as $field_name => $field) {
  1467. if (!empty($previous_fields[$field_name])) {
  1468. $defined_fields[$field_name] = true;
  1469. $previous_sorting = array_key_exists('sorting', $previous_fields[$field_name])
  1470. ? $previous_fields[$field_name]['sorting'] : '';
  1471. $sorting = array_key_exists('sorting', $field) ? $field['sorting'] : '';
  1472. if ($previous_sorting != $sorting) {
  1473. $change['change'] = true;
  1474. }
  1475. } else {
  1476. $change['change'] = true;
  1477. }
  1478. }
  1479. }
  1480. if (isset($previous_fields) && is_array($previous_fields)) {
  1481. foreach ($previous_fields as $field_name => $field) {
  1482. if (empty($defined_fields[$field_name])) {
  1483. $change['change'] = true;
  1484. }
  1485. }
  1486. }
  1487. if (!empty($change)) {
  1488. $changes['change'][$index_name] = $current_definition[$index_name];
  1489. }
  1490. } else {
  1491. if ($index_name != $was_index_name) {
  1492. return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
  1493. 'it was specified a previous index name ("'.$was_index_name.
  1494. ') for index "'.$index_name.'" of table "'.$table_name.'" that does not exist');
  1495. }
  1496. $changes['add'][$index_name] = $current_definition[$index_name];
  1497. }
  1498. }
  1499. }
  1500. foreach ($previous_definition as $index_previous_name => $index_previous) {
  1501. if (empty($defined_indexes[$index_previous_name])) {
  1502. $changes['remove'][$index_previous_name] = $index_previous;
  1503. }
  1504. }
  1505. return $changes;
  1506. }
  1507. // }}}
  1508. // {{{ compareTableDefinitions()
  1509. /**
  1510. * Compare a previous definition with the currently parsed definition
  1511. *
  1512. * @param string $table_name name of the table
  1513. * @param array $current_definition multi dimensional array that contains the current definition
  1514. * @param array $previous_definition multi dimensional array that contains the previous definition
  1515. * @param array &$defined_tables table names in the schema
  1516. *
  1517. * @return array|MDB2_Error array of changes on success, or a error object
  1518. * @access public
  1519. */
  1520. function compareTableDefinitions($table_name, $current_definition,
  1521. $previous_definition, &$defined_tables)
  1522. {
  1523. $changes = array();
  1524. if (is_array($current_definition)) {
  1525. $was_table_name = $table_name;
  1526. if (!empty($current_definition['was'])) {
  1527. $was_table_name = $current_definition['was'];
  1528. }
  1529. if (!empty($previous_definition[$was_table_name])) {
  1530. $changes['change'][$was_table_name] = array();
  1531. if ($was_table_name != $table_name) {
  1532. $changes['change'][$was_table_name] = array('name' => $table_name);
  1533. }
  1534. if (!empty($defined_tables[$was_table_name])) {
  1535. return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
  1536. 'the table "'.$was_table_name.
  1537. '" was specified for more than one table of the database');
  1538. }
  1539. $defined_tables[$was_table_name] = true;
  1540. if (!empty($current_definition['fields']) && is_array($current_definition['fields'])) {
  1541. $previous_fields = array();
  1542. if (isset($previous_definition[$was_table_name]['fields'])
  1543. && is_array($previous_definition[$was_table_name]['fields'])) {
  1544. $previous_fields = $previous_definition[$was_table_name]['fields'];
  1545. }
  1546. $change = $this->compareTableFieldsDefinitions($table_name,
  1547. $current_definition['fields'],
  1548. $previous_fields);
  1549. if (PEAR::isError($change)) {
  1550. return $change;
  1551. }
  1552. if (!empty($change)) {
  1553. $changes['change'][$was_table_name] =
  1554. MDB2_Schema::arrayMergeClobber($changes['change'][$was_table_name], $change);
  1555. }
  1556. }
  1557. if (!empty($current_definition['indexes']) && is_array($current_definition['indexes'])) {
  1558. $previous_indexes = array();
  1559. if (isset($previous_definition[$was_table_name]['indexes'])
  1560. && is_array($previous_definition[$was_table_name]['indexes'])) {
  1561. $previous_indexes = $previous_definition[$was_table_name]['indexes'];
  1562. }
  1563. $change = $this->compareTableIndexesDefinitions($table_name,
  1564. $current_definition['indexes'],
  1565. $previous_indexes);
  1566. if (PEAR::isError($change)) {
  1567. return $change;
  1568. }
  1569. if (!empty($change)) {
  1570. $changes['change'][$was_table_name]['indexes'] = $change;
  1571. }
  1572. }
  1573. if (empty($changes['change'][$was_table_name])) {
  1574. unset($changes['change'][$was_table_name]);
  1575. }
  1576. if (empty($changes['change'])) {
  1577. unset($changes['change']);
  1578. }
  1579. } else {
  1580. if ($table_name != $was_table_name) {
  1581. return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
  1582. 'it was specified a previous table name ("'.$was_table_name.
  1583. '") for table "'.$table_name.'" that does not exist');
  1584. }
  1585. $changes['add'][$table_name] = true;
  1586. }
  1587. }
  1588. return $changes;
  1589. }
  1590. // }}}
  1591. // {{{ compareSequenceDefinitions()
  1592. /**
  1593. * Compare a previous definition with the currently parsed definition
  1594. *
  1595. * @param string $sequence_name name of the sequence
  1596. * @param array $current_definition multi dimensional array that contains the current definition
  1597. * @param array $previous_definition multi dimensional array that contains the previous definition
  1598. * @param array &$defined_sequences names in the schema
  1599. *
  1600. * @return array|MDB2_Error array of changes on success, or a error object
  1601. * @access public
  1602. */
  1603. function compareSequenceDefinitions($sequence_name, $current_definition,
  1604. $previous_definition, &$defined_sequences)
  1605. {
  1606. $changes = array();
  1607. if (is_array($current_definition)) {
  1608. $was_sequence_name = $sequence_name;
  1609. if (!empty($previous_definition[$sequence_name])
  1610. && isset($previous_definition[$sequence_name]['was'])
  1611. && $previous_definition[$sequence_name]['was'] == $was_sequence_name
  1612. ) {
  1613. $was_sequence_name = $sequence_name;
  1614. } elseif (!empty($current_definition['was'])) {
  1615. $was_sequence_name = $current_definition['was'];
  1616. }
  1617. if (!empty($previous_definition[$was_sequence_name])) {
  1618. if ($was_sequence_name != $sequence_name) {
  1619. $changes['change'][$was_sequence_name]['name'] = $sequence_name;
  1620. }
  1621. if (!empty($defined_sequences[$was_sequence_name])) {
  1622. return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
  1623. 'the sequence "'.$was_sequence_name.'" was specified as base'.
  1624. ' of more than of sequence of the database');
  1625. }
  1626. $defined_sequences[$was_sequence_name] = true;
  1627. $change = array();
  1628. if (!empty($current_definition['start'])
  1629. && isset($previous_definition[$was_sequence_name]['start'])
  1630. && $current_definition['start'] != $previous_definition[$was_sequence_name]['start']
  1631. ) {
  1632. $change['start'] = $previous_definition[$sequence_name]['start'];
  1633. }
  1634. if (isset($current_definition['on']['table'])
  1635. && isset($previous_definition[$was_sequence_name]['on']['table'])
  1636. && $current_definition['on']['table'] != $previous_definition[$was_sequence_name]['on']['table']
  1637. && isset($current_definition['on']['field'])
  1638. && isset($previous_definition[$was_sequence_name]['on']['field'])
  1639. && $current_definition['on']['field'] != $previous_definition[$was_sequence_name]['on']['field']
  1640. ) {
  1641. $change['on'] = $current_definition['on'];
  1642. }
  1643. if (!empty($change)) {
  1644. $changes['change'][$was_sequence_name][$sequence_name] = $change;
  1645. }
  1646. } else {
  1647. if ($sequence_name != $was_sequence_name) {
  1648. return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
  1649. 'it was specified a previous sequence name ("'.$was_sequence_name.
  1650. '") for sequence "'.$sequence_name.'" that does not exist');
  1651. }
  1652. $changes['add'][$sequence_name] = true;
  1653. }
  1654. }
  1655. return $changes;
  1656. }
  1657. // }}}
  1658. // {{{ verifyAlterDatabase()
  1659. /**
  1660. * Verify that the changes requested are supported
  1661. *
  1662. * @param array $changes associative array that contains the definition of the changes
  1663. * that are meant to be applied to the database structure.
  1664. *
  1665. * @return bool|MDB2_Error MDB2_OK or error object
  1666. * @access public
  1667. */
  1668. function verifyAlterDatabase($changes)
  1669. {
  1670. if (!empty($changes['tables']['change']) && is_array($changes['tables']['change'])) {
  1671. foreach ($changes['tables']['change'] as $table_name => $table) {
  1672. if (!empty($table['indexes']) && is_array($table['indexes'])) {
  1673. if (!$this->db->supports('indexes')) {
  1674. return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
  1675. 'indexes are not supported');
  1676. }
  1677. $table_changes = count($table['indexes']);
  1678. if (!empty($table['indexes']['add'])) {
  1679. $table_changes--;
  1680. }
  1681. if (!empty($table['indexes']['remove'])) {
  1682. $table_changes--;
  1683. }
  1684. if (!empty($table['indexes']['change'])) {
  1685. $table_changes--;
  1686. }
  1687. if ($table_changes) {
  1688. return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
  1689. 'index alteration not yet supported: '.implode(', ', array_keys($table['indexes'])));
  1690. }
  1691. }
  1692. unset($table['indexes']);
  1693. $result = $this->db->manager->alterTable($table_name, $table, true);
  1694. if (PEAR::isError($result)) {
  1695. return $result;
  1696. }
  1697. }
  1698. }
  1699. if (!empty($changes['sequences']) && is_array($changes['sequences'])) {
  1700. if (!$this->db->supports('sequences')) {
  1701. return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
  1702. 'sequences are not supported');
  1703. }
  1704. $sequence_changes = count($changes['sequences']);
  1705. if (!empty($changes['sequences']['add'])) {
  1706. $sequence_changes--;
  1707. }
  1708. if (!empty($changes['sequences']['remove'])) {
  1709. $sequence_changes--;
  1710. }
  1711. if (!empty($changes['sequences']['change'])) {
  1712. $sequence_changes--;
  1713. }
  1714. if ($sequence_changes) {
  1715. return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
  1716. 'sequence alteration not yet supported: '.implode(', ', array_keys($changes['sequences'])));
  1717. }
  1718. }
  1719. return MDB2_OK;
  1720. }
  1721. // }}}
  1722. // {{{ alterDatabaseIndexes()
  1723. /**
  1724. * Execute the necessary actions to implement the requested changes
  1725. * in the indexes inside a database structure.
  1726. *
  1727. * @param string $table_name name of the table
  1728. * @param array $changes associative array that contains the definition of the changes
  1729. * that are meant to be applied to the database structure.
  1730. *
  1731. * @return bool|MDB2_Error MDB2_OK or error object
  1732. * @access public
  1733. */
  1734. function alterDatabaseIndexes($table_name, $changes)
  1735. {
  1736. $alterations = 0;
  1737. if (empty($changes)) {
  1738. return $alterations;
  1739. }
  1740. if (!empty($changes['remove']) && is_array($changes['remove'])) {
  1741. foreach ($changes['remove'] as $index_name => $index) {
  1742. $this->db->expectError(MDB2_ERROR_NOT_FOUND);
  1743. if (!empty($index['primary']) || !empty($index['unique'])) {
  1744. $result = $this->db->manager->dropConstraint($table_name, $index_name, !empty($index['primary']));
  1745. } else {
  1746. $result = $this->db->manager->dropIndex($table_name, $index_name);
  1747. }
  1748. $this->db->popExpect();
  1749. if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_NOT_FOUND)) {
  1750. return $result;
  1751. }
  1752. $alterations++;
  1753. }
  1754. }
  1755. if (!empty($changes['change']) && is_array($changes['change'])) {
  1756. foreach ($changes['change'] as $index_name => $index) {
  1757. /**
  1758. * Drop existing index/constraint first.
  1759. * Since $changes doesn't tell us whether it's an index or a constraint before the change,
  1760. * we have to find out and call the appropriate method.
  1761. */
  1762. if (in_array($index_name, $this->db->manager->listTableIndexes($table_name))) {
  1763. $result = $this->db->manager->dropIndex($table_name, $index_name);
  1764. } elseif (in_array($index_name, $this->db->manager->listTableConstraints($table_name))) {
  1765. $result = $this->db->manager->dropConstraint($table_name, $index_name);
  1766. }
  1767. if (!empty($result) && PEAR::isError($result)) {
  1768. return $result;
  1769. }
  1770. if (!empty($index['primary']) || !empty($index['unique'])) {
  1771. $result = $this->db->manager->createConstraint($table_name, $index_name, $index);
  1772. } else {
  1773. $result = $this->db->manager->createIndex($table_name, $index_name, $index);
  1774. }
  1775. if (PEAR::isError($result)) {
  1776. return $result;
  1777. }
  1778. $alterations++;
  1779. }
  1780. }
  1781. if (!empty($changes['add']) && is_array($changes['add'])) {
  1782. foreach ($changes['add'] as $index_name => $index) {
  1783. if (!empty($index['primary']) || !empty($index['unique'])) {
  1784. $result = $this->db->manager->createConstraint($table_name, $index_name, $index);
  1785. } else {
  1786. $result = $this->db->manager->createIndex($table_name, $index_name, $index);
  1787. }
  1788. if (PEAR::isError($result)) {
  1789. return $result;
  1790. }
  1791. $alterations++;
  1792. }
  1793. }
  1794. return $alterations;
  1795. }
  1796. // }}}
  1797. // {{{ alterDatabaseTables()
  1798. /**
  1799. * Execute the necessary actions to implement the requested changes
  1800. * in the tables inside a database structure.
  1801. *
  1802. * @param array $current_definition multi dimensional array that contains the current definition
  1803. * @param array $previous_definition multi dimensional array that contains the previous definition
  1804. * @param array $changes associative array that contains the definition of the changes
  1805. * that are meant to be applied to the database structure.
  1806. *
  1807. * @return bool|MDB2_Error MDB2_OK or error object
  1808. * @access public
  1809. */
  1810. function alterDatabaseTables($current_definition, $previous_definition, $changes)
  1811. {
  1812. /* FIXME: tables marked to be added are initialized by createTable(), others don't */
  1813. $alterations = 0;
  1814. if (empty($changes)) {
  1815. return $alterations;
  1816. }
  1817. if (!empty($changes['add']) && is_array($changes['add'])) {
  1818. foreach ($changes['add'] as $table_name => $table) {
  1819. $result = $this->createTable($table_name, $current_definition[$table_name]);
  1820. if (PEAR::isError($result)) {
  1821. return $result;
  1822. }
  1823. $alterations++;
  1824. }
  1825. }
  1826. if ($this->options['drop_obsolete_objects']
  1827. && !empty($changes['remove'])
  1828. && is_array($changes['remove'])
  1829. ) {
  1830. foreach ($changes['remove'] as $table_name => $table) {
  1831. $result = $this->db->manager->dropTable($table_name);
  1832. if (PEAR::isError($result)) {
  1833. return $result;
  1834. }
  1835. $alterations++;
  1836. }
  1837. }
  1838. if (!empty($changes['change']) && is_array($changes['change'])) {
  1839. foreach ($changes['change'] as $table_name => $table) {
  1840. $indexes = array();
  1841. if (!empty($table['indexes'])) {
  1842. $indexes = $table['indexes'];
  1843. unset($table['indexes']);
  1844. }
  1845. if (!empty($indexes['remove'])) {
  1846. $result = $this->alterDatabaseIndexes($table_name, array('remove' => $indexes['remove']));
  1847. if (PEAR::isError($result)) {
  1848. return $result;
  1849. }
  1850. unset($indexes['remove']);
  1851. $alterations += $result;
  1852. }
  1853. $result = $this->db->manager->alterTable($table_name, $table, false);
  1854. if (PEAR::isError($result)) {
  1855. return $result;
  1856. }
  1857. $alterations++;
  1858. // table may be renamed at this point
  1859. if (!empty($table['name'])) {
  1860. $table_name = $table['name'];
  1861. }
  1862. if (!empty($indexes)) {
  1863. $result = $this->alterDatabaseIndexes($table_name, $indexes);
  1864. if (PEAR::isError($result)) {
  1865. return $result;
  1866. }
  1867. $alterations += $result;
  1868. }
  1869. }
  1870. }
  1871. return $alterations;
  1872. }
  1873. // }}}
  1874. // {{{ alterDatabaseSequences()
  1875. /**
  1876. * Execute the necessary actions to implement the requested changes
  1877. * in the sequences inside a database structure.
  1878. *
  1879. * @param array $current_definition multi dimensional array that contains the current definition
  1880. * @param array $previous_definition multi dimensional array that contains the previous definition
  1881. * @param array $changes associative array that contains the definition of the changes
  1882. * that are meant to be applied to the database structure.
  1883. *
  1884. * @return bool|MDB2_Error MDB2_OK or error object
  1885. * @access public
  1886. */
  1887. function alterDatabaseSequences($current_definition, $previous_definition, $changes)
  1888. {
  1889. $alterations = 0;
  1890. if (empty($changes)) {
  1891. return $alterations;
  1892. }
  1893. if (!empty($changes['add']) && is_array($changes['add'])) {
  1894. foreach ($changes['add'] as $sequence_name => $sequence) {
  1895. $result = $this->createSequence($sequence_name, $current_definition[$sequence_name]);
  1896. if (PEAR::isError($result)) {
  1897. return $result;
  1898. }
  1899. $alterations++;
  1900. }
  1901. }
  1902. if ($this->options['drop_obsolete_objects']
  1903. && !empty($changes['remove'])
  1904. && is_array($changes['remove'])
  1905. ) {
  1906. foreach ($changes['remove'] as $sequence_name => $sequence) {
  1907. $result = $this->db->manager->dropSequence($sequence_name);
  1908. if (PEAR::isError($result)) {
  1909. return $result;
  1910. }
  1911. $alterations++;
  1912. }
  1913. }
  1914. if (!empty($changes['change']) && is_array($changes['change'])) {
  1915. foreach ($changes['change'] as $sequence_name => $sequence) {
  1916. $result = $this->db->manager->dropSequence($previous_definition[$sequence_name]['was']);
  1917. if (PEAR::isError($result)) {
  1918. return $result;
  1919. }
  1920. $result = $this->createSequence($sequence_name, $sequence);
  1921. if (PEAR::isError($result)) {
  1922. return $result;
  1923. }
  1924. $alterations++;
  1925. }
  1926. }
  1927. return $alterations;
  1928. }
  1929. // }}}
  1930. // {{{ alterDatabase()
  1931. /**
  1932. * Execute the necessary actions to implement the requested changes
  1933. * in a database structure.
  1934. *
  1935. * @param array $current_definition multi dimensional array that contains the current definition
  1936. * @param array $previous_definition multi dimensional array that contains the previous definition
  1937. * @param array $changes associative array that contains the definition of the changes
  1938. * that are meant to be applied to the database structure.
  1939. *
  1940. * @return bool|MDB2_Error MDB2_OK or error object
  1941. * @access public
  1942. */
  1943. function alterDatabase($current_definition, $previous_definition, $changes)
  1944. {
  1945. $alterations = 0;
  1946. if (empty($changes)) {
  1947. return $alterations;
  1948. }
  1949. $result = $this->verifyAlterDatabase($changes);
  1950. if (PEAR::isError($result)) {
  1951. return $result;
  1952. }
  1953. if (!empty($current_definition['name'])) {
  1954. $previous_database_name = $this->db->setDatabase($current_definition['name']);
  1955. }
  1956. if (($support_transactions = $this->db->supports('transactions'))
  1957. && PEAR::isError($result = $this->db->beginNestedTransaction())
  1958. ) {
  1959. return $result;
  1960. }
  1961. if (!empty($changes['tables']) && !empty($current_definition['tables'])) {
  1962. $current_tables = isset($current_definition['tables']) ? $current_definition['tables'] : array();
  1963. $previous_tables = isset($previous_definition['tables']) ? $previous_definition['tables'] : array();
  1964. $result = $this->alterDatabaseTables($current_tables, $previous_tables, $changes['tables']);
  1965. if (is_numeric($result)) {
  1966. $alterations += $result;
  1967. }
  1968. }
  1969. if (!PEAR::isError($result) && !empty($changes['sequences'])) {
  1970. $current_sequences = isset($current_definition['sequences']) ? $current_definition['sequences'] : array();
  1971. $previous_sequences = isset($previous_definition['sequences']) ? $previous_definition['sequences'] : array();
  1972. $result = $this->alterDatabaseSequences($current_sequences, $previous_sequences, $changes['sequences']);
  1973. if (is_numeric($result)) {
  1974. $alterations += $result;
  1975. }
  1976. }
  1977. if ($support_transactions) {
  1978. $res = $this->db->completeNestedTransaction();
  1979. if (PEAR::isError($res)) {
  1980. $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
  1981. 'Could not end transaction ('.
  1982. $res->getMessage().' ('.$res->getUserinfo().'))');
  1983. }
  1984. } elseif (PEAR::isError($result) && $alterations) {
  1985. $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
  1986. 'the requested database alterations were only partially implemented ('.
  1987. $result->getMessage().' ('.$result->getUserinfo().'))');
  1988. }
  1989. if (isset($previous_database_name)) {
  1990. $this->db->setDatabase($previous_database_name);
  1991. }
  1992. return $result;
  1993. }
  1994. // }}}
  1995. // {{{ dumpDatabaseChanges()
  1996. /**
  1997. * Dump the changes between two database definitions.
  1998. *
  1999. * @param array $changes associative array that specifies the list of database
  2000. * definitions changes as returned by the _compareDefinitions
  2001. * manager class function.
  2002. *
  2003. * @return bool|MDB2_Error MDB2_OK or error object
  2004. * @access public
  2005. */
  2006. function dumpDatabaseChanges($changes)
  2007. {
  2008. if (!empty($changes['tables'])) {
  2009. if (!empty($changes['tables']['add']) && is_array($changes['tables']['add'])) {
  2010. foreach ($changes['tables']['add'] as $table_name => $table) {
  2011. $this->db->debug("$table_name:", __FUNCTION__);
  2012. $this->db->debug("\tAdded table '$table_name'", __FUNCTION__);
  2013. }
  2014. }
  2015. if (!empty($changes['tables']['remove']) && is_array($changes['tables']['remove'])) {
  2016. if ($this->options['drop_obsolete_objects']) {
  2017. foreach ($changes['tables']['remove'] as $table_name => $table) {
  2018. $this->db->debug("$table_name:", __FUNCTION__);
  2019. $this->db->debug("\tRemoved table '$table_name'", __FUNCTION__);
  2020. }
  2021. } else {
  2022. foreach ($changes['tables']['remove'] as $table_name => $table) {
  2023. $this->db->debug("\tObsolete table '$table_name' left as is", __FUNCTION__);
  2024. }
  2025. }
  2026. }
  2027. if (!empty($changes['tables']['change']) && is_array($changes['tables']['change'])) {
  2028. foreach ($changes['tables']['change'] as $table_name => $table) {
  2029. if (array_key_exists('name', $table)) {
  2030. $this->db->debug("\tRenamed table '$table_name' to '".$table['name']."'", __FUNCTION__);
  2031. }
  2032. if (!empty($table['add']) && is_array($table['add'])) {
  2033. foreach ($table['add'] as $field_name => $field) {
  2034. $this->db->debug("\tAdded field '".$field_name."'", __FUNCTION__);
  2035. }
  2036. }
  2037. if (!empty($table['remove']) && is_array($table['remove'])) {
  2038. foreach ($table['remove'] as $field_name => $field) {
  2039. $this->db->debug("\tRemoved field '".$field_name."'", __FUNCTION__);
  2040. }
  2041. }
  2042. if (!empty($table['rename']) && is_array($table['rename'])) {
  2043. foreach ($table['rename'] as $field_name => $field) {
  2044. $this->db->debug("\tRenamed field '".$field_name."' to '".$field['name']."'", __FUNCTION__);
  2045. }
  2046. }
  2047. if (!empty($table['change']) && is_array($table['change'])) {
  2048. foreach ($table['change'] as $field_name => $field) {
  2049. $field = $field['definition'];
  2050. if (array_key_exists('type', $field)) {
  2051. $this->db->debug("\tChanged field '$field_name' type to '".$field['type']."'", __FUNCTION__);
  2052. }
  2053. if (array_key_exists('unsigned', $field)) {
  2054. $this->db->debug("\tChanged field '$field_name' type to '".
  2055. (!empty($field['unsigned']) && $field['unsigned'] ? '' : 'not ')."unsigned'",
  2056. __FUNCTION__);
  2057. }
  2058. if (array_key_exists('length', $field)) {
  2059. $this->db->debug("\tChanged field '$field_name' length to '".
  2060. (!empty($field['length']) ? $field['length']: 'no length')."'", __FUNCTION__);
  2061. }
  2062. if (array_key_exists('default', $field)) {
  2063. $this->db->debug("\tChanged field '$field_name' default to ".
  2064. (isset($field['default']) ? "'".$field['default']."'" : 'NULL'), __FUNCTION__);
  2065. }
  2066. if (array_key_exists('notnull', $field)) {
  2067. $this->db->debug("\tChanged field '$field_name' notnull to ".
  2068. (!empty($field['notnull']) && $field['notnull'] ? 'true' : 'false'),
  2069. __FUNCTION__);
  2070. }
  2071. }
  2072. }
  2073. if (!empty($table['indexes']) && is_array($table['indexes'])) {
  2074. if (!empty($table['indexes']['add']) && is_array($table['indexes']['add'])) {
  2075. foreach ($table['indexes']['add'] as $index_name => $index) {
  2076. $this->db->debug("\tAdded index '".$index_name.
  2077. "' of table '$table_name'", __FUNCTION__);
  2078. }
  2079. }
  2080. if (!empty($table['indexes']['remove']) && is_array($table['indexes']['remove'])) {
  2081. foreach ($table['indexes']['remove'] as $index_name => $index) {
  2082. $this->db->debug("\tRemoved index '".$index_name.
  2083. "' of table '$table_name'", __FUNCTION__);
  2084. }
  2085. }
  2086. if (!empty($table['indexes']['change']) && is_array($table['indexes']['change'])) {
  2087. foreach ($table['indexes']['change'] as $index_name => $index) {
  2088. if (array_key_exists('name', $index)) {
  2089. $this->db->debug("\tRenamed index '".$index_name."' to '".$index['name'].
  2090. "' on table '$table_name'", __FUNCTION__);
  2091. }
  2092. if (array_key_exists('unique', $index)) {
  2093. $this->db->debug("\tChanged index '".$index_name."' unique to '".
  2094. !empty($index['unique'])."' on table '$table_name'", __FUNCTION__);
  2095. }
  2096. if (array_key_exists('primary', $index)) {
  2097. $this->db->debug("\tChanged index '".$index_name."' primary to '".
  2098. !empty($index['primary'])."' on table '$table_name'", __FUNCTION__);
  2099. }
  2100. if (array_key_exists('change', $index)) {
  2101. $this->db->debug("\tChanged index '".$index_name.
  2102. "' on table '$table_name'", __FUNCTION__);
  2103. }
  2104. }
  2105. }
  2106. }
  2107. }
  2108. }
  2109. }
  2110. if (!empty($changes['sequences'])) {
  2111. if (!empty($changes['sequences']['add']) && is_array($changes['sequences']['add'])) {
  2112. foreach ($changes['sequences']['add'] as $sequence_name => $sequence) {
  2113. $this->db->debug("$sequence_name:", __FUNCTION__);
  2114. $this->db->debug("\tAdded sequence '$sequence_name'", __FUNCTION__);
  2115. }
  2116. }
  2117. if (!empty($changes['sequences']['remove']) && is_array($changes['sequences']['remove'])) {
  2118. if ($this->options['drop_obsolete_objects']) {
  2119. foreach ($changes['sequences']['remove'] as $sequence_name => $sequence) {
  2120. $this->db->debug("$sequence_name:", __FUNCTION__);
  2121. $this->db->debug("\tRemoved sequence '$sequence_name'", __FUNCTION__);
  2122. }
  2123. } else {
  2124. foreach ($changes['sequences']['remove'] as $sequence_name => $sequence) {
  2125. $this->db->debug("\tObsolete sequence '$sequence_name' left as is", __FUNCTION__);
  2126. }
  2127. }
  2128. }
  2129. if (!empty($changes['sequences']['change']) && is_array($changes['sequences']['change'])) {
  2130. foreach ($changes['sequences']['change'] as $sequence_name => $sequence) {
  2131. if (array_key_exists('name', $sequence)) {
  2132. $this->db->debug("\tRenamed sequence '$sequence_name' to '".
  2133. $sequence['name']."'", __FUNCTION__);
  2134. }
  2135. if (!empty($sequence['change']) && is_array($sequence['change'])) {
  2136. foreach ($sequence['change'] as $sequence_name => $sequence) {
  2137. if (array_key_exists('start', $sequence)) {
  2138. $this->db->debug("\tChanged sequence '$sequence_name' start to '".
  2139. $sequence['start']."'", __FUNCTION__);
  2140. }
  2141. }
  2142. }
  2143. }
  2144. }
  2145. }
  2146. return MDB2_OK;
  2147. }
  2148. // }}}
  2149. // {{{ dumpDatabase()
  2150. /**
  2151. * Dump a previously parsed database structure in the Metabase schema
  2152. * XML based format suitable for the Metabase parser. This function
  2153. * may optionally dump the database definition with initialization
  2154. * commands that specify the data that is currently present in the tables.
  2155. *
  2156. * @param array $database_definition multi dimensional array that contains the current definition
  2157. * @param array $arguments associative array that takes pairs of tag
  2158. * names and values that define dump options.
  2159. * <pre>array (
  2160. * 'output_mode' => String
  2161. * 'file' : dump into a file
  2162. * default: dump using a function
  2163. * 'output' => String
  2164. * depending on the 'Output_Mode'
  2165. * name of the file
  2166. * name of the function
  2167. * 'end_of_line' => String
  2168. * end of line delimiter that should be used
  2169. * default: "\n"
  2170. * );</pre>
  2171. * @param int $dump Int that determines what data to dump
  2172. * + MDB2_SCHEMA_DUMP_ALL : the entire db
  2173. * + MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db
  2174. * + MDB2_SCHEMA_DUMP_CONTENT : only the content of the db
  2175. *
  2176. * @return bool|MDB2_Error MDB2_OK or error object
  2177. * @access public
  2178. */
  2179. function dumpDatabase($database_definition, $arguments, $dump = MDB2_SCHEMA_DUMP_ALL)
  2180. {
  2181. $class_name = $this->options['writer'];
  2182. $result = MDB2::loadClass($class_name, $this->db->getOption('debug'));
  2183. if (PEAR::isError($result)) {
  2184. return $result;
  2185. }
  2186. // get initialization data
  2187. if (isset($database_definition['tables']) && is_array($database_definition['tables'])
  2188. && $dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT
  2189. ) {
  2190. foreach ($database_definition['tables'] as $table_name => $table) {
  2191. $fields = array();
  2192. $fieldsq = array();
  2193. foreach ($table['fields'] as $field_name => $field) {
  2194. $fields[$field_name] = $field['type'];
  2195. $fieldsq[] = $this->db->quoteIdentifier($field_name, true);
  2196. }
  2197. $query = 'SELECT '.implode(', ', $fieldsq).' FROM ';
  2198. $query .= $this->db->quoteIdentifier($table_name, true);
  2199. $data = $this->db->queryAll($query, $fields, MDB2_FETCHMODE_ASSOC);
  2200. if (PEAR::isError($data)) {
  2201. return $data;
  2202. }
  2203. if (!empty($data)) {
  2204. $initialization = array();
  2205. $lob_buffer_length = $this->db->getOption('lob_buffer_length');
  2206. foreach ($data as $row) {
  2207. $rows = array();
  2208. foreach ($row as $key => $lob) {
  2209. if (is_resource($lob)) {
  2210. $value = '';
  2211. while (!feof($lob)) {
  2212. $value .= fread($lob, $lob_buffer_length);
  2213. }
  2214. $row[$key] = $value;
  2215. }
  2216. $rows[] = array('name' => $key, 'group' => array('type' => 'value', 'data' => $row[$key]));
  2217. }
  2218. $initialization[] = array('type' => 'insert', 'data' => array('field' => $rows));
  2219. }
  2220. $database_definition['tables'][$table_name]['initialization'] = $initialization;
  2221. }
  2222. }
  2223. }
  2224. $writer = new $class_name($this->options['valid_types']);
  2225. return $writer->dumpDatabase($database_definition, $arguments, $dump);
  2226. }
  2227. // }}}
  2228. // {{{ writeInitialization()
  2229. /**
  2230. * Write initialization and sequences
  2231. *
  2232. * @param string|array $data data file or data array
  2233. * @param string|array $structure structure file or array
  2234. * @param array $variables associative array that is passed to the argument
  2235. * of the same name to the parseDatabaseDefinitionFile function. (there third
  2236. * param)
  2237. *
  2238. * @return bool|MDB2_Error MDB2_OK or error object
  2239. * @access public
  2240. */
  2241. function writeInitialization($data, $structure = false, $variables = array())
  2242. {
  2243. if ($structure) {
  2244. $structure = $this->parseDatabaseDefinition($structure, false, $variables);
  2245. if (PEAR::isError($structure)) {
  2246. return $structure;
  2247. }
  2248. }
  2249. $data = $this->parseDatabaseDefinition($data, false, $variables, false, $structure);
  2250. if (PEAR::isError($data)) {
  2251. return $data;
  2252. }
  2253. $previous_database_name = null;
  2254. if (!empty($data['name'])) {
  2255. $previous_database_name = $this->db->setDatabase($data['name']);
  2256. } elseif (!empty($structure['name'])) {
  2257. $previous_database_name = $this->db->setDatabase($structure['name']);
  2258. }
  2259. if (!empty($data['tables']) && is_array($data['tables'])) {
  2260. foreach ($data['tables'] as $table_name => $table) {
  2261. if (empty($table['initialization'])) {
  2262. continue;
  2263. }
  2264. $result = $this->initializeTable($table_name, $table);
  2265. if (PEAR::isError($result)) {
  2266. return $result;
  2267. }
  2268. }
  2269. }
  2270. if (!empty($structure['sequences']) && is_array($structure['sequences'])) {
  2271. foreach ($structure['sequences'] as $sequence_name => $sequence) {
  2272. if (isset($data['sequences'][$sequence_name])
  2273. || !isset($sequence['on']['table'])
  2274. || !isset($data['tables'][$sequence['on']['table']])
  2275. ) {
  2276. continue;
  2277. }
  2278. $result = $this->createSequence($sequence_name, $sequence, true);
  2279. if (PEAR::isError($result)) {
  2280. return $result;
  2281. }
  2282. }
  2283. }
  2284. if (!empty($data['sequences']) && is_array($data['sequences'])) {
  2285. foreach ($data['sequences'] as $sequence_name => $sequence) {
  2286. $result = $this->createSequence($sequence_name, $sequence, true);
  2287. if (PEAR::isError($result)) {
  2288. return $result;
  2289. }
  2290. }
  2291. }
  2292. if (isset($previous_database_name)) {
  2293. $this->db->setDatabase($previous_database_name);
  2294. }
  2295. return MDB2_OK;
  2296. }
  2297. // }}}
  2298. // {{{ updateDatabase()
  2299. /**
  2300. * Compare the correspondent files of two versions of a database schema
  2301. * definition: the previously installed and the one that defines the schema
  2302. * that is meant to update the database.
  2303. * If the specified previous definition file does not exist, this function
  2304. * will create the database from the definition specified in the current
  2305. * schema file.
  2306. * If both files exist, the function assumes that the database was previously
  2307. * installed based on the previous schema file and will update it by just
  2308. * applying the changes.
  2309. * If this function succeeds, the contents of the current schema file are
  2310. * copied to replace the previous schema file contents. Any subsequent schema
  2311. * changes should only be done on the file specified by the $current_schema_file
  2312. * to let this function make a consistent evaluation of the exact changes that
  2313. * need to be applied.
  2314. *
  2315. * @param string|array $current_schema filename or array of the updated database schema definition.
  2316. * @param string|array $previous_schema filename or array of the previously installed database schema definition.
  2317. * @param array $variables associative array that is passed to the argument of the same
  2318. * name to the parseDatabaseDefinitionFile function. (there third param)
  2319. * @param bool $disable_query determines if the disable_query option should be set to true
  2320. * for the alterDatabase() or createDatabase() call
  2321. * @param bool $overwrite_old_schema_file Overwrite?
  2322. *
  2323. * @return bool|MDB2_Error MDB2_OK or error object
  2324. * @access public
  2325. */
  2326. function updateDatabase($current_schema, $previous_schema = false,
  2327. $variables = array(), $disable_query = false,
  2328. $overwrite_old_schema_file = false)
  2329. {
  2330. $current_definition = $this->parseDatabaseDefinition($current_schema, false, $variables,
  2331. $this->options['fail_on_invalid_names']);
  2332. if (PEAR::isError($current_definition)) {
  2333. return $current_definition;
  2334. }
  2335. $previous_definition = false;
  2336. if ($previous_schema) {
  2337. $previous_definition = $this->parseDatabaseDefinition($previous_schema, true, $variables,
  2338. $this->options['fail_on_invalid_names']);
  2339. if (PEAR::isError($previous_definition)) {
  2340. return $previous_definition;
  2341. }
  2342. }
  2343. if ($previous_definition) {
  2344. $dbExists = $this->db->databaseExists($current_definition['name']);
  2345. if (PEAR::isError($dbExists)) {
  2346. return $dbExists;
  2347. }
  2348. if (!$dbExists) {
  2349. return $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
  2350. 'database to update does not exist: '.$current_definition['name']);
  2351. }
  2352. $changes = $this->compareDefinitions($current_definition, $previous_definition);
  2353. if (PEAR::isError($changes)) {
  2354. return $changes;
  2355. }
  2356. if (is_array($changes)) {
  2357. $this->db->setOption('disable_query', $disable_query);
  2358. $result = $this->alterDatabase($current_definition, $previous_definition, $changes);
  2359. $this->db->setOption('disable_query', false);
  2360. if (PEAR::isError($result)) {
  2361. return $result;
  2362. }
  2363. $copy = true;
  2364. if ($this->db->options['debug']) {
  2365. $result = $this->dumpDatabaseChanges($changes);
  2366. if (PEAR::isError($result)) {
  2367. return $result;
  2368. }
  2369. }
  2370. }
  2371. } else {
  2372. $this->db->setOption('disable_query', $disable_query);
  2373. $result = $this->createDatabase($current_definition);
  2374. $this->db->setOption('disable_query', false);
  2375. if (PEAR::isError($result)) {
  2376. return $result;
  2377. }
  2378. }
  2379. if ($overwrite_old_schema_file
  2380. && !$disable_query
  2381. && is_string($previous_schema) && is_string($current_schema)
  2382. && !copy($current_schema, $previous_schema)) {
  2383. return $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
  2384. 'Could not copy the new database definition file to the current file');
  2385. }
  2386. return MDB2_OK;
  2387. }
  2388. // }}}
  2389. // {{{ errorMessage()
  2390. /**
  2391. * Return a textual error message for a MDB2 error code
  2392. *
  2393. * @param int|array $value integer error code, <code>null</code> to get the
  2394. * current error code-message map,
  2395. * or an array with a new error code-message map
  2396. *
  2397. * @return string error message, or false if the error code was not recognized
  2398. * @access public
  2399. */
  2400. function errorMessage($value = null)
  2401. {
  2402. static $errorMessages;
  2403. if (is_array($value)) {
  2404. $errorMessages = $value;
  2405. return MDB2_OK;
  2406. } elseif (!isset($errorMessages)) {
  2407. $errorMessages = array(
  2408. MDB2_SCHEMA_ERROR => 'unknown error',
  2409. MDB2_SCHEMA_ERROR_PARSE => 'schema parse error',
  2410. MDB2_SCHEMA_ERROR_VALIDATE => 'schema validation error',
  2411. MDB2_SCHEMA_ERROR_INVALID => 'invalid',
  2412. MDB2_SCHEMA_ERROR_UNSUPPORTED => 'not supported',
  2413. MDB2_SCHEMA_ERROR_WRITER => 'schema writer error',
  2414. );
  2415. }
  2416. if (is_null($value)) {
  2417. return $errorMessages;
  2418. }
  2419. if (PEAR::isError($value)) {
  2420. $value = $value->getCode();
  2421. }
  2422. return !empty($errorMessages[$value]) ?
  2423. $errorMessages[$value] : $errorMessages[MDB2_SCHEMA_ERROR];
  2424. }
  2425. // }}}
  2426. // {{{ raiseError()
  2427. /**
  2428. * This method is used to communicate an error and invoke error
  2429. * callbacks etc. Basically a wrapper for PEAR::raiseError
  2430. * without the message string.
  2431. *
  2432. * @param int|PEAR_Error $code integer error code or and PEAR_Error instance
  2433. * @param int $mode error mode, see PEAR_Error docs
  2434. * error level (E_USER_NOTICE etc). If error mode is
  2435. * PEAR_ERROR_CALLBACK, this is the callback function,
  2436. * either as a function name, or as an array of an
  2437. * object and method name. For other error modes this
  2438. * parameter is ignored.
  2439. * @param array $options Options, depending on the mode, @see PEAR::setErrorHandling
  2440. * @param string $userinfo Extra debug information. Defaults to the last
  2441. * query and native error code.
  2442. *
  2443. * @return object a PEAR error object
  2444. * @access public
  2445. * @see PEAR_Error
  2446. */
  2447. static function &raiseError($code = null, $mode = null, $options = null, $userinfo = null, $dummy1 = null, $dummy2 = null, $dummy3 = false)
  2448. {
  2449. $err = PEAR::raiseError(null, $code, $mode, $options,
  2450. $userinfo, 'MDB2_Schema_Error', true);
  2451. return $err;
  2452. }
  2453. // }}}
  2454. // {{{ isError()
  2455. /**
  2456. * Tell whether a value is an MDB2_Schema error.
  2457. *
  2458. * @param mixed $data the value to test
  2459. * @param int $code if $data is an error object, return true only if $code is
  2460. * a string and $db->getMessage() == $code or
  2461. * $code is an integer and $db->getCode() == $code
  2462. *
  2463. * @return bool true if parameter is an error
  2464. * @access public
  2465. */
  2466. static function isError($data, $code = null)
  2467. {
  2468. if (is_a($data, 'MDB2_Schema_Error')) {
  2469. if (is_null($code)) {
  2470. return true;
  2471. } elseif (is_string($code)) {
  2472. return $data->getMessage() === $code;
  2473. } else {
  2474. $code = (array)$code;
  2475. return in_array($data->getCode(), $code);
  2476. }
  2477. }
  2478. return false;
  2479. }
  2480. // }}}
  2481. }
  2482. /**
  2483. * MDB2_Schema_Error implements a class for reporting portable database error
  2484. * messages.
  2485. *
  2486. * @category Database
  2487. * @package MDB2_Schema
  2488. * @author Stig Bakken <ssb@fast.no>
  2489. * @license BSD http://www.opensource.org/licenses/bsd-license.php
  2490. * @link http://pear.php.net/packages/MDB2_Schema
  2491. */
  2492. class MDB2_Schema_Error extends PEAR_Error
  2493. {
  2494. /**
  2495. * MDB2_Schema_Error constructor.
  2496. *
  2497. * @param mixed $code error code, or string with error message.
  2498. * @param int $mode what 'error mode' to operate in
  2499. * @param int $level what error level to use for $mode & PEAR_ERROR_TRIGGER
  2500. * @param mixed $debuginfo additional debug info, such as the last query
  2501. *
  2502. * @access public
  2503. */
  2504. function MDB2_Schema_Error($code = MDB2_SCHEMA_ERROR, $mode = PEAR_ERROR_RETURN,
  2505. $level = E_USER_NOTICE, $debuginfo = null)
  2506. {
  2507. $this->PEAR_Error('MDB2_Schema Error: ' . MDB2_Schema::errorMessage($code), $code,
  2508. $mode, $level, $debuginfo);
  2509. }
  2510. }