Writer.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. /**
  51. * Writes an XML schema file
  52. *
  53. * @category Database
  54. * @package MDB2_Schema
  55. * @author Lukas Smith <smith@pooteeweet.org>
  56. * @license BSD http://www.opensource.org/licenses/bsd-license.php
  57. * @link http://pear.php.net/packages/MDB2_Schema
  58. */
  59. class MDB2_Schema_Writer
  60. {
  61. // {{{ properties
  62. var $valid_types = array();
  63. // }}}
  64. // {{{ constructor
  65. /**
  66. * PHP 5 constructor
  67. *
  68. * @param array $valid_types information of all valid fields
  69. * types
  70. *
  71. * @return void
  72. *
  73. * @access public
  74. * @static
  75. */
  76. function __construct($valid_types = array())
  77. {
  78. $this->valid_types = $valid_types;
  79. }
  80. // }}}
  81. // {{{ raiseError()
  82. /**
  83. * This method is used to communicate an error and invoke error
  84. * callbacks etc. Basically a wrapper for PEAR::raiseError
  85. * without the message string.
  86. *
  87. * @param int|PEAR_Error $code integer error code or and PEAR_Error
  88. * instance
  89. * @param int $mode error mode, see PEAR_Error docs error
  90. * level (E_USER_NOTICE etc). If error mode
  91. * is PEAR_ERROR_CALLBACK, this is the
  92. * callback function, either as a function
  93. * name, or as an array of an object and
  94. * method name. For other error modes this
  95. * parameter is ignored.
  96. * @param string $options Extra debug information. Defaults to the
  97. * last query and native error code.
  98. * @param string $userinfo User-friendly error message
  99. *
  100. * @return object a PEAR error object
  101. * @access public
  102. * @see PEAR_Error
  103. */
  104. function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
  105. {
  106. $error = MDB2_Schema::raiseError($code, $mode, $options, $userinfo);
  107. return $error;
  108. }
  109. // }}}
  110. // {{{ _escapeSpecialChars()
  111. /**
  112. * add escapecharacters to all special characters in a string
  113. *
  114. * @param string $string string that should be escaped
  115. *
  116. * @return string escaped string
  117. * @access protected
  118. */
  119. function _escapeSpecialChars($string)
  120. {
  121. if (!is_string($string)) {
  122. $string = strval($string);
  123. }
  124. $escaped = '';
  125. for ($char = 0, $count = strlen($string); $char < $count; $char++) {
  126. switch ($string[$char]) {
  127. case '&':
  128. $escaped .= '&amp;';
  129. break;
  130. case '>':
  131. $escaped .= '&gt;';
  132. break;
  133. case '<':
  134. $escaped .= '&lt;';
  135. break;
  136. case '"':
  137. $escaped .= '&quot;';
  138. break;
  139. case '\'':
  140. $escaped .= '&apos;';
  141. break;
  142. default:
  143. $code = ord($string[$char]);
  144. if ($code < 32 || $code > 127) {
  145. $escaped .= "&#$code;";
  146. } else {
  147. $escaped .= $string[$char];
  148. }
  149. break;
  150. }
  151. }
  152. return $escaped;
  153. }
  154. // }}}
  155. // {{{ _dumpBoolean()
  156. /**
  157. * dump the structure of a sequence
  158. *
  159. * @param string $boolean boolean value or variable definition
  160. *
  161. * @return string with xml boolea definition
  162. * @access private
  163. */
  164. function _dumpBoolean($boolean)
  165. {
  166. if (is_string($boolean)) {
  167. if ($boolean !== 'true' || $boolean !== 'false'
  168. || preg_match('/<variable>.*</variable>/', $boolean)
  169. ) {
  170. return $boolean;
  171. }
  172. }
  173. return $boolean ? 'true' : 'false';
  174. }
  175. // }}}
  176. // {{{ dumpSequence()
  177. /**
  178. * dump the structure of a sequence
  179. *
  180. * @param string $sequence_definition sequence definition
  181. * @param string $sequence_name sequence name
  182. * @param string $eol end of line characters
  183. * @param integer $dump determines what data to dump
  184. * MDB2_SCHEMA_DUMP_ALL : the entire db
  185. * MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db
  186. * MDB2_SCHEMA_DUMP_CONTENT : only the content of the db
  187. *
  188. * @return mixed string xml sequence definition on success, or a error object
  189. * @access public
  190. */
  191. function dumpSequence($sequence_definition, $sequence_name, $eol, $dump = MDB2_SCHEMA_DUMP_ALL)
  192. {
  193. $buffer = "$eol <sequence>$eol <name>$sequence_name</name>$eol";
  194. if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT) {
  195. if (!empty($sequence_definition['start'])) {
  196. $start = $sequence_definition['start'];
  197. $buffer .= " <start>$start</start>$eol";
  198. }
  199. }
  200. if (!empty($sequence_definition['on'])) {
  201. $buffer .= " <on>$eol";
  202. $buffer .= " <table>".$sequence_definition['on']['table'];
  203. $buffer .= "</table>$eol <field>".$sequence_definition['on']['field'];
  204. $buffer .= "</field>$eol </on>$eol";
  205. }
  206. $buffer .= " </sequence>$eol";
  207. return $buffer;
  208. }
  209. // }}}
  210. // {{{ dumpDatabase()
  211. /**
  212. * Dump a previously parsed database structure in the Metabase schema
  213. * XML based format suitable for the Metabase parser. This function
  214. * may optionally dump the database definition with initialization
  215. * commands that specify the data that is currently present in the tables.
  216. *
  217. * @param array $database_definition unknown
  218. * @param array $arguments associative array that takes pairs of tag
  219. * names and values that define dump options.
  220. * array (
  221. * 'output_mode' => String
  222. * 'file' : dump into a file
  223. * default: dump using a function
  224. * 'output' => String
  225. * depending on the 'Output_Mode'
  226. * name of the file
  227. * name of the function
  228. * 'end_of_line' => String
  229. * end of line delimiter that should be used
  230. * default: "\n"
  231. * );
  232. * @param integer $dump determines what data to dump
  233. * MDB2_SCHEMA_DUMP_ALL : the entire db
  234. * MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db
  235. * MDB2_SCHEMA_DUMP_CONTENT : only the content of the db
  236. *
  237. * @return mixed MDB2_OK on success, or a error object
  238. * @access public
  239. */
  240. function dumpDatabase($database_definition, $arguments, $dump = MDB2_SCHEMA_DUMP_ALL)
  241. {
  242. if (!empty($arguments['output'])) {
  243. if (!empty($arguments['output_mode']) && $arguments['output_mode'] == 'file') {
  244. $fp = fopen($arguments['output'], 'w');
  245. if ($fp === false) {
  246. return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null,
  247. 'it was not possible to open output file');
  248. }
  249. $output = false;
  250. } elseif (is_callable($arguments['output'])) {
  251. $output = $arguments['output'];
  252. } else {
  253. return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null,
  254. 'no valid output function specified');
  255. }
  256. } else {
  257. return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null,
  258. 'no output method specified');
  259. }
  260. $eol = isset($arguments['end_of_line']) ? $arguments['end_of_line'] : "\n";
  261. $sequences = array();
  262. if (!empty($database_definition['sequences'])
  263. && is_array($database_definition['sequences'])
  264. ) {
  265. foreach ($database_definition['sequences'] as $sequence_name => $sequence) {
  266. $table = !empty($sequence['on']) ? $sequence['on']['table'] :'';
  267. $sequences[$table][] = $sequence_name;
  268. }
  269. }
  270. $buffer = '<?xml version="1.0" encoding="ISO-8859-1" ?>'.$eol;
  271. $buffer .= "<database>$eol$eol <name>".$database_definition['name']."</name>";
  272. $buffer .= "$eol <create>".$this->_dumpBoolean($database_definition['create'])."</create>";
  273. $buffer .= "$eol <overwrite>".$this->_dumpBoolean($database_definition['overwrite'])."</overwrite>$eol";
  274. $buffer .= "$eol <charset>".$database_definition['charset']."</charset>$eol";
  275. if ($output) {
  276. call_user_func($output, $buffer);
  277. } else {
  278. fwrite($fp, $buffer);
  279. }
  280. if (!empty($database_definition['tables']) && is_array($database_definition['tables'])) {
  281. foreach ($database_definition['tables'] as $table_name => $table) {
  282. $buffer = "$eol <table>$eol$eol <name>$table_name</name>$eol";
  283. if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_STRUCTURE) {
  284. $buffer .= "$eol <declaration>$eol";
  285. if (!empty($table['fields']) && is_array($table['fields'])) {
  286. foreach ($table['fields'] as $field_name => $field) {
  287. if (empty($field['type'])) {
  288. return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null,
  289. 'it was not specified the type of the field "'.
  290. $field_name.'" of the table "'.$table_name.'"');
  291. }
  292. if (!empty($this->valid_types) && !array_key_exists($field['type'], $this->valid_types)) {
  293. return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
  294. 'type "'.$field['type'].'" is not yet supported');
  295. }
  296. $buffer .= "$eol <field>$eol <name>$field_name</name>$eol <type>";
  297. $buffer .= $field['type']."</type>$eol";
  298. if (!empty($field['fixed']) && $field['type'] === 'text') {
  299. $buffer .= " <fixed>".$this->_dumpBoolean($field['fixed'])."</fixed>$eol";
  300. }
  301. if (array_key_exists('default', $field)
  302. && $field['type'] !== 'clob' && $field['type'] !== 'blob'
  303. ) {
  304. $buffer .= ' <default>'.$this->_escapeSpecialChars($field['default'])."</default>$eol";
  305. }
  306. if (!empty($field['notnull'])) {
  307. $buffer .= " <notnull>".$this->_dumpBoolean($field['notnull'])."</notnull>$eol";
  308. } else {
  309. $buffer .= " <notnull>false</notnull>$eol";
  310. }
  311. if (!empty($field['autoincrement'])) {
  312. $buffer .= " <autoincrement>" . $field['autoincrement'] ."</autoincrement>$eol";
  313. }
  314. if (!empty($field['unsigned'])) {
  315. $buffer .= " <unsigned>".$this->_dumpBoolean($field['unsigned'])."</unsigned>$eol";
  316. }
  317. if (!empty($field['length'])) {
  318. $buffer .= ' <length>'.$field['length']."</length>$eol";
  319. }
  320. $buffer .= " </field>$eol";
  321. }
  322. }
  323. if (!empty($table['indexes']) && is_array($table['indexes'])) {
  324. foreach ($table['indexes'] as $index_name => $index) {
  325. if (strtolower($index_name) === 'primary') {
  326. $index_name = $table_name . '_pKey';
  327. }
  328. $buffer .= "$eol <index>$eol <name>$index_name</name>$eol";
  329. if (!empty($index['unique'])) {
  330. $buffer .= " <unique>".$this->_dumpBoolean($index['unique'])."</unique>$eol";
  331. }
  332. if (!empty($index['primary'])) {
  333. $buffer .= " <primary>".$this->_dumpBoolean($index['primary'])."</primary>$eol";
  334. }
  335. foreach ($index['fields'] as $field_name => $field) {
  336. $buffer .= " <field>$eol <name>$field_name</name>$eol";
  337. if (!empty($field) && is_array($field)) {
  338. $buffer .= ' <sorting>'.$field['sorting']."</sorting>$eol";
  339. }
  340. $buffer .= " </field>$eol";
  341. }
  342. $buffer .= " </index>$eol";
  343. }
  344. }
  345. if (!empty($table['constraints']) && is_array($table['constraints'])) {
  346. foreach ($table['constraints'] as $constraint_name => $constraint) {
  347. $buffer .= "$eol <foreign>$eol <name>$constraint_name</name>$eol";
  348. if (empty($constraint['fields']) || !is_array($constraint['fields'])) {
  349. return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null,
  350. 'it was not specified a field for the foreign key "'.
  351. $constraint_name.'" of the table "'.$table_name.'"');
  352. }
  353. if (!is_array($constraint['references']) || empty($constraint['references']['table'])) {
  354. return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null,
  355. 'it was not specified the referenced table of the foreign key "'.
  356. $constraint_name.'" of the table "'.$table_name.'"');
  357. }
  358. if (!empty($constraint['match'])) {
  359. $buffer .= " <match>".$constraint['match']."</match>$eol";
  360. }
  361. if (!empty($constraint['ondelete'])) {
  362. $buffer .= " <ondelete>".$constraint['ondelete']."</ondelete>$eol";
  363. }
  364. if (!empty($constraint['onupdate'])) {
  365. $buffer .= " <onupdate>".$constraint['onupdate']."</onupdate>$eol";
  366. }
  367. if (!empty($constraint['deferrable'])) {
  368. $buffer .= " <deferrable>".$constraint['deferrable']."</deferrable>$eol";
  369. }
  370. if (!empty($constraint['initiallydeferred'])) {
  371. $buffer .= " <initiallydeferred>".$constraint['initiallydeferred']."</initiallydeferred>$eol";
  372. }
  373. foreach ($constraint['fields'] as $field_name => $field) {
  374. $buffer .= " <field>$field_name</field>$eol";
  375. }
  376. $buffer .= " <references>$eol <table>".$constraint['references']['table']."</table>$eol";
  377. foreach ($constraint['references']['fields'] as $field_name => $field) {
  378. $buffer .= " <field>$field_name</field>$eol";
  379. }
  380. $buffer .= " </references>$eol";
  381. $buffer .= " </foreign>$eol";
  382. }
  383. }
  384. $buffer .= "$eol </declaration>$eol";
  385. }
  386. if ($output) {
  387. call_user_func($output, $buffer);
  388. } else {
  389. fwrite($fp, $buffer);
  390. }
  391. $buffer = '';
  392. if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT) {
  393. if (!empty($table['initialization']) && is_array($table['initialization'])) {
  394. $buffer = "$eol <initialization>$eol";
  395. foreach ($table['initialization'] as $instruction) {
  396. switch ($instruction['type']) {
  397. case 'insert':
  398. $buffer .= "$eol <insert>$eol";
  399. foreach ($instruction['data']['field'] as $field) {
  400. $field_name = $field['name'];
  401. $buffer .= "$eol <field>$eol <name>$field_name</name>$eol";
  402. $buffer .= $this->writeExpression($field['group'], 5, $arguments);
  403. $buffer .= " </field>$eol";
  404. }
  405. $buffer .= "$eol </insert>$eol";
  406. break;
  407. case 'update':
  408. $buffer .= "$eol <update>$eol";
  409. foreach ($instruction['data']['field'] as $field) {
  410. $field_name = $field['name'];
  411. $buffer .= "$eol <field>$eol <name>$field_name</name>$eol";
  412. $buffer .= $this->writeExpression($field['group'], 5, $arguments);
  413. $buffer .= " </field>$eol";
  414. }
  415. if (!empty($instruction['data']['where'])
  416. && is_array($instruction['data']['where'])
  417. ) {
  418. $buffer .= " <where>$eol";
  419. $buffer .= $this->writeExpression($instruction['data']['where'], 5, $arguments);
  420. $buffer .= " </where>$eol";
  421. }
  422. $buffer .= "$eol </update>$eol";
  423. break;
  424. case 'delete':
  425. $buffer .= "$eol <delete>$eol$eol";
  426. if (!empty($instruction['data']['where'])
  427. && is_array($instruction['data']['where'])
  428. ) {
  429. $buffer .= " <where>$eol";
  430. $buffer .= $this->writeExpression($instruction['data']['where'], 5, $arguments);
  431. $buffer .= " </where>$eol";
  432. }
  433. $buffer .= "$eol </delete>$eol";
  434. break;
  435. }
  436. }
  437. $buffer .= "$eol </initialization>$eol";
  438. }
  439. }
  440. $buffer .= "$eol </table>$eol";
  441. if ($output) {
  442. call_user_func($output, $buffer);
  443. } else {
  444. fwrite($fp, $buffer);
  445. }
  446. if (isset($sequences[$table_name])) {
  447. foreach ($sequences[$table_name] as $sequence) {
  448. $result = $this->dumpSequence($database_definition['sequences'][$sequence],
  449. $sequence, $eol, $dump);
  450. if (PEAR::isError($result)) {
  451. return $result;
  452. }
  453. if ($output) {
  454. call_user_func($output, $result);
  455. } else {
  456. fwrite($fp, $result);
  457. }
  458. }
  459. }
  460. }
  461. }
  462. if (isset($sequences[''])) {
  463. foreach ($sequences[''] as $sequence) {
  464. $result = $this->dumpSequence($database_definition['sequences'][$sequence],
  465. $sequence, $eol, $dump);
  466. if (PEAR::isError($result)) {
  467. return $result;
  468. }
  469. if ($output) {
  470. call_user_func($output, $result);
  471. } else {
  472. fwrite($fp, $result);
  473. }
  474. }
  475. }
  476. $buffer = "$eol</database>$eol";
  477. if ($output) {
  478. call_user_func($output, $buffer);
  479. } else {
  480. fwrite($fp, $buffer);
  481. fclose($fp);
  482. }
  483. return MDB2_OK;
  484. }
  485. // }}}
  486. // {{{ writeExpression()
  487. /**
  488. * Dumps the structure of an element. Elements can be value, column,
  489. * function or expression.
  490. *
  491. * @param array $element multi dimensional array that represents the parsed element
  492. * of a DML instruction.
  493. * @param integer $offset base indentation width
  494. * @param array $arguments associative array that takes pairs of tag
  495. * names and values that define dump options.
  496. *
  497. * @return string
  498. *
  499. * @access public
  500. * @see MDB2_Schema_Writer::dumpDatabase()
  501. */
  502. function writeExpression($element, $offset = 0, $arguments = null)
  503. {
  504. $eol = isset($arguments['end_of_line']) ? $arguments['end_of_line'] : "\n";
  505. $str = '';
  506. $indent = str_repeat(' ', $offset);
  507. $noffset = $offset + 1;
  508. switch ($element['type']) {
  509. case 'value':
  510. $str .= "$indent<value>".$this->_escapeSpecialChars($element['data'])."</value>$eol";
  511. break;
  512. case 'column':
  513. $str .= "$indent<column>".$this->_escapeSpecialChars($element['data'])."</column>$eol";
  514. break;
  515. case 'function':
  516. $str .= "$indent<function>$eol$indent <name>".$this->_escapeSpecialChars($element['data']['name'])."</name>$eol";
  517. if (!empty($element['data']['arguments'])
  518. && is_array($element['data']['arguments'])
  519. ) {
  520. foreach ($element['data']['arguments'] as $v) {
  521. $str .= $this->writeExpression($v, $noffset, $arguments);
  522. }
  523. }
  524. $str .= "$indent</function>$eol";
  525. break;
  526. case 'expression':
  527. $str .= "$indent<expression>$eol";
  528. $str .= $this->writeExpression($element['data']['operants'][0], $noffset, $arguments);
  529. $str .= "$indent <operator>".$element['data']['operator']."</operator>$eol";
  530. $str .= $this->writeExpression($element['data']['operants'][1], $noffset, $arguments);
  531. $str .= "$indent</expression>$eol";
  532. break;
  533. }
  534. return $str;
  535. }
  536. // }}}
  537. }