PageRenderTime 41ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/app/code/core/Mage/Backup/Model/Mysql4/Db.php

https://github.com/weburnit/magento-lite
PHP | 415 lines | 241 code | 46 blank | 128 comment | 22 complexity | 82c1725174d8bdc0f8cc6fe41a8ce3af MD5 | raw file
  1. <?php
  2. /**
  3. * Magento
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@magentocommerce.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade Magento to newer
  18. * versions in the future. If you wish to customize Magento for your
  19. * needs please refer to http://www.magentocommerce.com for more information.
  20. *
  21. * @category Mage
  22. * @package Mage_Backup
  23. * @copyright Copyright (c) 2010 Magento Inc. (http://www.magentocommerce.com)
  24. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  25. */
  26. /**
  27. * Database backup resource model
  28. *
  29. * @category Mage
  30. * @package Mage_Backup
  31. * @author Magento Core Team <core@magentocommerce.com>
  32. */
  33. class Mage_Backup_Model_Mysql4_Db
  34. {
  35. /**
  36. * Read connection
  37. *
  38. * @var Varien_Db_Adapter_Pdo_Mysql
  39. */
  40. protected $_read;
  41. /**
  42. * tables Foreign key data array
  43. * [tbl_name] = array(create foreign key strings)
  44. *
  45. * @var array
  46. */
  47. protected $_foreignKeys = array();
  48. /**
  49. * Initialize Backup DB resource model
  50. *
  51. */
  52. public function __construct()
  53. {
  54. $this->_read = Mage::getSingleton('core/resource')->getConnection('backup_read');
  55. }
  56. /**
  57. * @deprecated after 1.4.0.0-alpha2
  58. */
  59. public function crear()
  60. {
  61. $this->clear();
  62. }
  63. /**
  64. * Clear data
  65. *
  66. */
  67. public function clear()
  68. {
  69. $this->_foreignKeys = array();
  70. }
  71. /**
  72. * Retrieve table list
  73. *
  74. * @return array
  75. */
  76. public function getTables()
  77. {
  78. return $this->_read->listTables();
  79. }
  80. /**
  81. * Retrieve SQL fragment for drop table
  82. *
  83. * @param string $tableName
  84. * @return string
  85. */
  86. public function getTableDropSql($tableName)
  87. {
  88. $quotedTableName = $this->_read->quoteIdentifier($tableName);
  89. return 'DROP TABLE IF EXISTS ' . $quotedTableName . ';';
  90. }
  91. /**
  92. * Retrieve SQL fragment for create table
  93. *
  94. * @param string $tableName
  95. * @param bool $withForeignKeys
  96. * @return string
  97. */
  98. public function getTableCreateSql($tableName, $withForeignKeys = false)
  99. {
  100. $quotedTableName = $this->_read->quoteIdentifier($tableName);
  101. $sql = 'SHOW CREATE TABLE ' . $quotedTableName;
  102. $row = $this->_read->fetchRow($sql);
  103. if (!$row || !isset($row['Table']) || !isset($row['Create Table'])) {
  104. return false;
  105. }
  106. $regExp = '/,\s+CONSTRAINT `([^`]*)` FOREIGN KEY \(`([^`]*)`\) '
  107. . 'REFERENCES `([^`]*)` \(`([^`]*)`\)'
  108. . '( ON DELETE (RESTRICT|CASCADE|SET NULL|NO ACTION))?'
  109. . '( ON UPDATE (RESTRICT|CASCADE|SET NULL|NO ACTION))?/';
  110. $matches = array();
  111. preg_match_all($regExp, $row['Create Table'], $matches, PREG_SET_ORDER);
  112. foreach ($matches as $match) {
  113. $this->_foreignKeys[$tableName][] = sprintf('ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)%s%s',
  114. $this->_read->quoteIdentifier($match[1]),
  115. $this->_read->quoteIdentifier($match[2]),
  116. $this->_read->quoteIdentifier($match[3]),
  117. $this->_read->quoteIdentifier($match[4]),
  118. isset($match[5]) ? $match[5] : '',
  119. isset($match[7]) ? $match[7] : ''
  120. );
  121. }
  122. if ($withForeignKeys) {
  123. return $row['Create Table'] . ';';
  124. }
  125. else {
  126. return preg_replace($regExp, '', $row['Create Table']) . ';';
  127. }
  128. }
  129. /**
  130. * Retrieve foreign keys for table(s)
  131. *
  132. * @param string|null $tableName
  133. * @return string
  134. */
  135. public function getTableForeignKeysSql($tableName = null)
  136. {
  137. if (is_null($tableName)) {
  138. $sql = '';
  139. foreach ($this->_foreignKeys as $table => $foreignKeys) {
  140. $sql .= sprintf("ALTER TABLE %s\n %s;\n",
  141. $this->_read->quoteIdentifier($table),
  142. join(",\n ", $foreignKeys)
  143. );
  144. }
  145. return $sql;
  146. }
  147. if (isset($this->_foreignKeys[$tableName]) && ($foreignKeys = $this->_foreignKeys[$tableName])) {
  148. }
  149. return false;
  150. }
  151. /**
  152. * Retrieve table status
  153. *
  154. * @param string $tableName
  155. * @return Varien_Object
  156. */
  157. public function getTableStatus($tableName)
  158. {
  159. $sql = $this->_read->quoteInto('SHOW TABLE STATUS LIKE ?', $tableName);
  160. $row = $this->_read->fetchRow($sql);
  161. if ($row) {
  162. $statusObject = new Varien_Object();
  163. $statusObject->setIdFieldName('name');
  164. foreach ($row as $field => $value) {
  165. $statusObject->setData(strtolower($field), $value);
  166. }
  167. $cntRow = $this->_read->fetchRow( $this->_read->select()->from($tableName, 'COUNT(*) as rows'));
  168. $statusObject->setRows($cntRow['rows']);
  169. return $statusObject;
  170. }
  171. return false;
  172. }
  173. /**
  174. * Quote Table Row
  175. *
  176. * @param string $tableName
  177. * @param array $row
  178. * @return string
  179. */
  180. protected function _quoteRow($tableName, array $row)
  181. {
  182. $describe = $this->_read->describeTable($tableName);
  183. $rowData = array();
  184. foreach ($row as $k => $v) {
  185. if (is_null($v)) {
  186. $value = 'NULL';
  187. }
  188. elseif (in_array(strtolower($describe[$k]['DATA_TYPE']), array('bigint','mediumint','smallint','tinyint'))) {
  189. $value = $v;
  190. }
  191. else {
  192. $value = $this->_read->quoteInto('?', $v);
  193. }
  194. $rowData[] = $value;
  195. }
  196. return '('.join(',', $rowData).')';
  197. }
  198. /**
  199. * Retrive table partical data SQL insert
  200. *
  201. * @param string $tableName
  202. * @param int $count
  203. * @param int $offset
  204. * @return string
  205. */
  206. public function getTableDataSql($tableName, $count, $offset = 0)
  207. {
  208. $sql = null;
  209. $quotedTableName = $this->_read->quoteIdentifier($tableName);
  210. $select = $this->_read->select()
  211. ->from($tableName)
  212. ->limit($count, $offset);
  213. $query = $this->_read->query($select);
  214. while ($row = $query->fetch()) {
  215. if (is_null($sql)) {
  216. $sql = 'INSERT INTO ' . $quotedTableName . ' VALUES ';
  217. }
  218. else {
  219. $sql .= ',';
  220. }
  221. $sql .= $this->_quoteRow($tableName, $row);
  222. }
  223. if (!is_null($sql)) {
  224. $sql .= ';' . "\n";
  225. }
  226. return $sql;
  227. }
  228. /**
  229. * Enter description here...
  230. *
  231. * @param unknown_type $tableName
  232. * @param unknown_type $addDropIfExists
  233. * @return unknown
  234. */
  235. public function getTableCreateScript($tableName, $addDropIfExists=false)
  236. {
  237. $script = '';
  238. if ($this->_read) {
  239. $quotedTableName = $this->_read->quoteIdentifier($tableName);
  240. if ($addDropIfExists) {
  241. $script .= 'DROP TABLE IF EXISTS ' . $quotedTableName .";\n";
  242. }
  243. $sql = 'SHOW CREATE TABLE ' . $quotedTableName;
  244. $data = $this->_read->fetchRow($sql);
  245. $script.= isset($data['Create Table']) ? $data['Create Table'].";\n" : '';
  246. }
  247. return $script;
  248. }
  249. /**
  250. * Retrieve table header comment
  251. *
  252. * @return string
  253. */
  254. public function getTableHeader($tableName)
  255. {
  256. $quotedTableName = $this->_read->quoteIdentifier($tableName);
  257. return "\n--\n"
  258. . "-- Table structure for table {$quotedTableName}\n"
  259. . "--\n\n";
  260. }
  261. public function getTableDataDump($tableName, $step=100)
  262. {
  263. $sql = '';
  264. if ($this->_read) {
  265. $quotedTableName = $this->_read->quoteIdentifier($tableName);
  266. $colunms = $this->_read->fetchRow('SELECT * FROM '.$quotedTableName.' LIMIT 1');
  267. if ($colunms) {
  268. $arrSql = array();
  269. $colunms = array_keys($colunms);
  270. $quote = $this->_read->getQuoteIdentifierSymbol();
  271. $sql = 'INSERT INTO ' . $quotedTableName . ' (' .$quote . implode($quote.', '.$quote,$colunms).$quote.')';
  272. $sql.= ' VALUES ';
  273. $startRow = 0;
  274. $select = $this->_read->select();
  275. $select->from($tableName)
  276. ->limit($step, $startRow);
  277. while ($data = $this->_read->fetchAll($select)) {
  278. $dataSql = array();
  279. foreach ($data as $row) {
  280. $dataSql[] = $this->_read->quoteInto('(?)', $row);
  281. }
  282. $arrSql[] = $sql.implode(', ', $dataSql).';';
  283. $startRow += $step;
  284. $select->limit($step, $startRow);
  285. }
  286. $sql = implode("\n", $arrSql)."\n";
  287. }
  288. }
  289. return $sql;
  290. }
  291. /**
  292. * Returns SQL header data
  293. */
  294. public function getHeader()
  295. {
  296. $dbConfig = $this->_read->getConfig();
  297. $versionRow = $this->_read->fetchRow('SHOW VARIABLES LIKE \'version\'');
  298. $hostName = !empty($dbConfig['unix_socket']) ? $dbConfig['unix_socket']
  299. : (!empty($dbConfig['host']) ? $dbConfig['host'] : 'localhost');
  300. $header = "-- Magento DB backup\n"
  301. . "--\n"
  302. . "-- Host: {$hostName} Database: {$dbConfig['dbname']}\n"
  303. . "-- ------------------------------------------------------\n"
  304. . "-- Server version: {$versionRow['Value']}\n\n"
  305. . "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n"
  306. . "/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n"
  307. . "/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n"
  308. . "/*!40101 SET NAMES utf8 */;\n"
  309. . "/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;\n"
  310. . "/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;\n"
  311. . "/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;\n"
  312. . "/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;\n";
  313. return $header;
  314. }
  315. /**
  316. * Returns SQL footer data
  317. */
  318. public function getFooter()
  319. {
  320. $footer = "\n/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;\n"
  321. . "/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; \n"
  322. . "/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;\n"
  323. . "/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n"
  324. . "/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n"
  325. . "/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n"
  326. . "/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;\n"
  327. . "\n-- Dump completed on " . Mage::getSingleton('core/date')->gmtDate() . " GMT";
  328. return $footer;
  329. }
  330. /**
  331. * Retrieve before insert data SQL fragment
  332. *
  333. * @param string $tableName
  334. * @return string
  335. */
  336. public function getTableDataBeforeSql($tableName)
  337. {
  338. $quotedTableName = $this->_read->quoteIdentifier($tableName);
  339. return "\n--\n"
  340. . "-- Dumping data for table {$quotedTableName}\n"
  341. . "--\n\n"
  342. . "LOCK TABLES {$quotedTableName} WRITE;\n"
  343. . "/*!40000 ALTER TABLE {$quotedTableName} DISABLE KEYS */;\n";
  344. }
  345. /**
  346. * Retrieve after insert data SQL fragment
  347. *
  348. * @param string $tableName
  349. * @return string
  350. */
  351. public function getTableDataAfterSql($tableName)
  352. {
  353. $quotedTableName = $this->_read->quoteIdentifier($tableName);
  354. return "/*!40000 ALTER TABLE {$quotedTableName} ENABLE KEYS */;\n"
  355. . "UNLOCK TABLES;\n";
  356. }
  357. public function beginTransaction()
  358. {
  359. $this->_read->beginTransaction();
  360. }
  361. public function commitTransaction()
  362. {
  363. $this->_read->commit();
  364. }
  365. public function rollBackTransaction()
  366. {
  367. $this->_read->rollBack();
  368. }
  369. }