PageRenderTime 25ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/core/xpdo/om/mysql/xpdogenerator.class.php

https://github.com/esche/revolution
PHP | 216 lines | 187 code | 2 blank | 27 comment | 25 complexity | a360e0ef70e3f3ecbb60464c82f4cf9d MD5 | raw file
  1. <?php
  2. /*
  3. * Copyright 2006-2010 by Jason Coward <xpdo@opengeek.com>
  4. *
  5. * This file is part of xPDO.
  6. *
  7. * xPDO is free software; you can redistribute it and/or modify it under the
  8. * terms of the GNU General Public License as published by the Free Software
  9. * Foundation; either version 2 of the License, or (at your option) any later
  10. * version.
  11. *
  12. * xPDO is distributed in the hope that it will be useful, but WITHOUT ANY
  13. * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  14. * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along with
  17. * xPDO; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
  18. * Suite 330, Boston, MA 02111-1307 USA
  19. */
  20. /**
  21. * MySQL classes for generating xPDOObject classes and maps from an xPDO schema.
  22. *
  23. * @package xpdo
  24. * @subpackage om.mysql
  25. */
  26. /**
  27. * Include the parent {@link xPDOGenerator} class.
  28. */
  29. include_once (strtr(realpath(dirname(__FILE__)), '\\', '/') . '/../xpdogenerator.class.php');
  30. /**
  31. * An extension for generating {@link xPDOObject} class and map files for MySQL.
  32. *
  33. * A MySQL-specific extension to an {@link xPDOManager} instance that can
  34. * generate class stub and meta-data map files from a provided XML schema of a
  35. * database structure.
  36. *
  37. * @package xpdo
  38. * @subpackage om.mysql
  39. */
  40. class xPDOGenerator_mysql extends xPDOGenerator {
  41. public function compile($path = '') {
  42. return false;
  43. }
  44. public function getIndex($index) {
  45. switch ($index) {
  46. case 'PRI':
  47. $index= 'pk';
  48. break;
  49. case 'UNI':
  50. $index= 'unique';
  51. break;
  52. case 'MUL':
  53. $index= 'index';
  54. break;
  55. default:
  56. break;
  57. }
  58. if (!empty ($index)) {
  59. $index= ' index="' . $index . '"';
  60. }
  61. return $index;
  62. }
  63. /**
  64. * Write an xPDO XML Schema from your database.
  65. *
  66. * @param string $schemaFile The name (including path) of the schemaFile you
  67. * want to write.
  68. * @param string $package Name of the package to generate the classes in.
  69. * @param string $baseClass The class which all classes in the package will
  70. * extend; by default this is set to {@link xPDOObject} and any
  71. * auto_increment fields with the column name 'id' will extend {@link
  72. * xPDOSimpleObject} automatically.
  73. * @param string $tablePrefix The table prefix for the current connection,
  74. * which will be removed from all of the generated class and table names.
  75. * Specify a prefix when creating a new {@link xPDO} instance to recreate
  76. * the tables with the same prefix, but still use the generic class names.
  77. * @param boolean $restrictPrefix Only reverse-engineer tables that have the
  78. * specified tablePrefix; if tablePrefix is empty, this is ignored.
  79. * @return boolean True on success, false on failure.
  80. */
  81. public function writeSchema($schemaFile, $package= '', $baseClass= '', $tablePrefix= '', $restrictPrefix= false) {
  82. if (empty ($package))
  83. $package= $this->manager->xpdo->package;
  84. if (empty ($baseClass))
  85. $baseClass= 'xPDOObject';
  86. if (empty ($tablePrefix))
  87. $tablePrefix= $this->manager->xpdo->config[xPDO::OPT_TABLE_PREFIX];
  88. $xmlContent = array();
  89. $xmlContent[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
  90. $xmlContent[] = "<model package=\"{$package}\" baseClass=\"{$baseClass}\" platform=\"mysql\" defaultEngine=\"MyISAM\">";
  91. //read list of tables
  92. $dbname= $this->manager->xpdo->config['dbname'];
  93. $tableLike= ($tablePrefix && $restrictPrefix) ? " LIKE '{$tablePrefix}%'" : '';
  94. $tablesStmt= $this->manager->xpdo->prepare("SHOW TABLES FROM {$dbname}{$tableLike}");
  95. $tablesStmt->execute();
  96. $tables= $tablesStmt->fetchAll(PDO::FETCH_NUM);
  97. if ($this->manager->xpdo->getDebug() === true) $this->manager->xpdo->log(xPDO::LOG_LEVEL_DEBUG, print_r($tables, true));
  98. foreach ($tables as $table) {
  99. $xmlObject= array();
  100. $xmlFields= array();
  101. $xmlIndices= array();
  102. if (!$tableName= $this->getTableName($table[0], $tablePrefix, $restrictPrefix)) {
  103. continue;
  104. }
  105. $class= $this->getClassName($tableName);
  106. $extends= $baseClass;
  107. $fieldsStmt= $this->manager->xpdo->query('SHOW COLUMNS FROM ' . $this->manager->xpdo->escape($table[0]));
  108. if ($fieldsStmt) {
  109. $fields= $fieldsStmt->fetchAll(PDO::FETCH_ASSOC);
  110. if ($this->manager->xpdo->getDebug() === true) $this->manager->xpdo->log(xPDO::LOG_LEVEL_DEBUG, print_r($fields, true));
  111. if (!empty($fields)) {
  112. foreach ($fields as $field) {
  113. $Field= '';
  114. $Type= '';
  115. $Null= '';
  116. $Key= '';
  117. $Default= '';
  118. $Extra= '';
  119. extract($field, EXTR_OVERWRITE);
  120. $Type= xPDO :: escSplit(' ', $Type, "'", 2);
  121. $precisionPos= strpos($Type[0], '(');
  122. $dbType= $precisionPos? substr($Type[0], 0, $precisionPos): $Type[0];
  123. $dbType= strtolower($dbType);
  124. $Precision= $precisionPos? substr($Type[0], $precisionPos + 1, strrpos($Type[0], ')') - ($precisionPos + 1)): '';
  125. if (!empty ($Precision)) {
  126. $Precision= ' precision="' . trim($Precision) . '"';
  127. }
  128. $attributes= '';
  129. if (isset ($Type[1]) && !empty ($Type[1])) {
  130. $attributes= ' attributes="' . trim($Type[1]) . '"';
  131. }
  132. $PhpType= $this->manager->getPhpType($dbType);
  133. $Null= ' null="' . (($Null === 'NO') ? 'false' : 'true') . '"';
  134. $Key= $this->getIndex($Key);
  135. $Default= $this->getDefault($Default);
  136. if (!empty ($Extra)) {
  137. if ($Extra === 'auto_increment') {
  138. if ($baseClass === 'xPDOObject' && $Field === 'id') {
  139. $extends= 'xPDOSimpleObject';
  140. continue;
  141. } else {
  142. $Extra= ' generated="native"';
  143. }
  144. } else {
  145. $Extra= ' extra="' . strtolower($Extra) . '"';
  146. }
  147. $Extra= ' ' . $Extra;
  148. }
  149. $xmlFields[] = "\t\t<field key=\"{$Field}\" dbtype=\"{$dbType}\"{$Precision}{$attributes} phptype=\"{$PhpType}\"{$Null}{$Default}{$Key}{$Extra} />";
  150. }
  151. } else {
  152. $this->manager->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'No columns were found in table ' . $table[0]);
  153. }
  154. } else {
  155. $this->manager->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'Error retrieving columns for table ' . $table[0]);
  156. }
  157. $indexesStmt= $this->manager->xpdo->query('SHOW INDEXES FROM ' . $this->manager->xpdo->escape($table[0]));
  158. if ($indexesStmt) {
  159. $indexes= $indexesStmt->fetchAll(PDO::FETCH_ASSOC);
  160. if ($this->manager->xpdo->getDebug() === true) $this->manager->xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Indices for table {$table[0]}: " . print_r($indexes, true));
  161. if (!empty($indexes)) {
  162. $indices = array();
  163. foreach ($indexes as $index) {
  164. if (!array_key_exists($index['Key_name'], $indices)) $indices[$index['Key_name']] = array();
  165. $indices[$index['Key_name']][$index['Seq_in_index']] = $index;
  166. }
  167. foreach ($indices as $index) {
  168. $xmlIndexCols = array();
  169. if ($this->manager->xpdo->getDebug() === true) $this->manager->xpdo->log(xPDO::LOG_LEVEL_DEBUG, "Details of index: " . print_r($index, true));
  170. foreach ($index as $columnSeq => $column) {
  171. if ($columnSeq == 1) {
  172. $primary = $column['Key_name'] == 'PRIMARY' ? 'true' : 'false';
  173. $unique = empty($column['Non_unique']) ? 'true' : 'false';
  174. $packed = empty($column['Packed']) ? 'false' : 'true';
  175. $type = $column['Index_type'];
  176. }
  177. $null = $column['Null'] == 'YES' ? 'true' : 'false';
  178. $xmlIndexCols[]= "\t\t\t<column key=\"{$column['Column_name']}\" collation=\"{$column['Collation']}\" null=\"{$null}\" />";
  179. }
  180. $xmlIndices[]= "\t\t<index alias=\"{$column['Key_name']}\" name=\"{$column['Key_name']}\" primary=\"{$primary}\" unique=\"{$unique}\">";
  181. $xmlIndices[]= implode("\n", $xmlIndexCols);
  182. $xmlIndices[]= "\t\t</index>";
  183. }
  184. } else {
  185. $this->manager->xpdo->log(xPDO::LOG_LEVEL_WARN, 'No indexes were found in table ' . $table[0]);
  186. }
  187. } else {
  188. $this->manager->xpdo->log(xPDO::LOG_LEVEL_ERROR, 'Error getting indexes for table ' . $table[0]);
  189. }
  190. $xmlObject[] = "\t<object class=\"{$class}\" table=\"{$tableName}\" extends=\"{$extends}\">";
  191. $xmlObject[] = implode("\n", $xmlFields);
  192. if (!empty($xmlIndices)) {
  193. $xmlObject[] = '';
  194. $xmlObject[] = implode("\n", $xmlIndices);
  195. }
  196. $xmlObject[] = "\t</object>";
  197. $xmlContent[] = implode("\n", $xmlObject);
  198. }
  199. $xmlContent[] = "</model>";
  200. if ($this->manager->xpdo->getDebug() === true) {
  201. $this->manager->xpdo->log(xPDO::LOG_LEVEL_DEBUG, implode("\n", $xmlContent));
  202. }
  203. $file= fopen($schemaFile, 'wb');
  204. $written= fwrite($file, implode("\n", $xmlContent));
  205. fclose($file);
  206. return true;
  207. }
  208. }