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

/wp-includes/library/Varien/Db/Adapter/Pdo/Mysql.php

https://bitbucket.org/aukhanev/xdn-wordpress31
PHP | 3586 lines | 3339 code | 47 blank | 200 comment | 34 complexity | 49cec4cf8aa903eb9c4cff6bb26d7934 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 Varien
  22. * @package Varien_Db
  23. * @copyright Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
  24. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  25. */
  26. /**
  27. * Mysql PDO DB adapter
  28. */
  29. class Varien_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Mysql implements Varien_Db_Adapter_Interface
  30. {
  31. const DEBUG_CONNECT = 0;
  32. const DEBUG_TRANSACTION = 1;
  33. const DEBUG_QUERY = 2;
  34. const TIMESTAMP_FORMAT = 'Y-m-d H:i:s';
  35. const DATETIME_FORMAT = 'Y-m-d H:i:s';
  36. const DATE_FORMAT = 'Y-m-d';
  37. const DDL_DESCRIBE = 1;
  38. const DDL_CREATE = 2;
  39. const DDL_INDEX = 3;
  40. const DDL_FOREIGN_KEY = 4;
  41. const DDL_CACHE_PREFIX = 'DB_PDO_MYSQL_DDL';
  42. const DDL_CACHE_TAG = 'DB_PDO_MYSQL_DDL';
  43. const LENGTH_TABLE_NAME = 64;
  44. const LENGTH_INDEX_NAME = 64;
  45. const LENGTH_FOREIGN_NAME = 64;
  46. /**
  47. * Default class name for a DB statement.
  48. *
  49. * @var string
  50. */
  51. protected $_defaultStmtClass = 'Varien_Db_Statement_Pdo_Mysql';
  52. /**
  53. * Current Transaction Level
  54. *
  55. * @var int
  56. */
  57. protected $_transactionLevel = 0;
  58. /**
  59. * Set attribute to connection flag
  60. *
  61. * @var bool
  62. */
  63. protected $_connectionFlagsSet = false;
  64. /**
  65. * Tables DDL cache
  66. *
  67. * @var array
  68. */
  69. protected $_ddlCache = array();
  70. /**
  71. * SQL bind params. Used temporarily by regexp callback.
  72. *
  73. * @var array
  74. */
  75. protected $_bindParams = array();
  76. /**
  77. * Autoincrement for bind value. Used by regexp callback.
  78. *
  79. * @var int
  80. */
  81. protected $_bindIncrement = 0;
  82. /**
  83. * Write SQL debug data to file
  84. *
  85. * @var bool
  86. */
  87. protected $_debug = false;
  88. /**
  89. * Minimum query duration time to be logged
  90. *
  91. * @var float
  92. */
  93. protected $_logQueryTime = 0.05;
  94. /**
  95. * Log all queries (ignored minimum query duration time)
  96. *
  97. * @var bool
  98. */
  99. protected $_logAllQueries = false;
  100. /**
  101. * Add to log call stack data (backtrace)
  102. *
  103. * @var bool
  104. */
  105. protected $_logCallStack = false;
  106. /**
  107. * Path to SQL debug data log
  108. *
  109. * @var string
  110. */
  111. protected $_debugFile = 'var/debug/pdo_mysql.log';
  112. /**
  113. * Io File Adapter
  114. *
  115. * @var Varien_Io_File
  116. */
  117. protected $_debugIoAdapter;
  118. /**
  119. * Debug timer start value
  120. *
  121. * @var float
  122. */
  123. protected $_debugTimer = 0;
  124. /**
  125. * Cache frontend adapter instance
  126. *
  127. * @var Zend_Cache_Core
  128. */
  129. protected $_cacheAdapter;
  130. /**
  131. * DDL cache allowing flag
  132. * @var bool
  133. */
  134. protected $_isDdlCacheAllowed = true;
  135. /**
  136. * MySQL column - Table DDL type pairs
  137. *
  138. * @var array
  139. */
  140. protected $_ddlColumnTypes = array(
  141. Varien_Db_Ddl_Table::TYPE_BOOLEAN => 'bool',
  142. Varien_Db_Ddl_Table::TYPE_SMALLINT => 'smallint',
  143. Varien_Db_Ddl_Table::TYPE_INTEGER => 'int',
  144. Varien_Db_Ddl_Table::TYPE_BIGINT => 'bigint',
  145. Varien_Db_Ddl_Table::TYPE_FLOAT => 'float',
  146. Varien_Db_Ddl_Table::TYPE_DECIMAL => 'decimal',
  147. Varien_Db_Ddl_Table::TYPE_NUMERIC => 'decimal',
  148. Varien_Db_Ddl_Table::TYPE_DATE => 'date',
  149. Varien_Db_Ddl_Table::TYPE_TIMESTAMP => 'timestamp',
  150. Varien_Db_Ddl_Table::TYPE_DATETIME => 'datetime',
  151. Varien_Db_Ddl_Table::TYPE_TEXT => 'text',
  152. Varien_Db_Ddl_Table::TYPE_BLOB => 'blob',
  153. Varien_Db_Ddl_Table::TYPE_VARBINARY => 'blob'
  154. );
  155. /**
  156. * Allowed interval units array
  157. *
  158. * @var array
  159. */
  160. protected $_intervalUnits = array(
  161. self::INTERVAL_YEAR => 'YEAR',
  162. self::INTERVAL_MONTH => 'MONTH',
  163. self::INTERVAL_DAY => 'DAY',
  164. self::INTERVAL_HOUR => 'HOUR',
  165. self::INTERVAL_MINUTE => 'MINUTE',
  166. self::INTERVAL_SECOND => 'SECOND',
  167. );
  168. /**
  169. * Hook callback to modify queries. Mysql specific property, designed only for backwards compatibility.
  170. *
  171. * @var array|null
  172. */
  173. protected $_queryHook = null;
  174. /**
  175. * Begin new DB transaction for connection
  176. *
  177. * @return Varien_Db_Adapter_Pdo_Mysql
  178. */
  179. public function beginTransaction()
  180. {
  181. if ($this->_transactionLevel === 0) {
  182. $this->_debugTimer();
  183. parent::beginTransaction();
  184. $this->_debugStat(self::DEBUG_TRANSACTION, 'BEGIN');
  185. }
  186. ++$this->_transactionLevel;
  187. return $this;
  188. }
  189. /**
  190. * Commit DB transaction
  191. *
  192. * @return Varien_Db_Adapter_Pdo_Mysql
  193. */
  194. public function commit()
  195. {
  196. if ($this->_transactionLevel === 1) {
  197. $this->_debugTimer();
  198. parent::commit();
  199. $this->_debugStat(self::DEBUG_TRANSACTION, 'COMMIT');
  200. }
  201. --$this->_transactionLevel;
  202. return $this;
  203. }
  204. /**
  205. * Rollback DB transaction
  206. *
  207. * @return Varien_Db_Adapter_Pdo_Mysql
  208. */
  209. public function rollback()
  210. {
  211. if ($this->_transactionLevel === 1) {
  212. $this->_debugTimer();
  213. parent::rollback();
  214. $this->_debugStat(self::DEBUG_TRANSACTION, 'ROLLBACK');
  215. }
  216. --$this->_transactionLevel;
  217. return $this;
  218. }
  219. /**
  220. * Get adapter transaction level state. Return 0 if all transactions are complete
  221. *
  222. * @return int
  223. */
  224. public function getTransactionLevel()
  225. {
  226. return $this->_transactionLevel;
  227. }
  228. /**
  229. * Convert date to DB format
  230. *
  231. * @param mixed $date
  232. * @return string
  233. */
  234. public function convertDate($date)
  235. {
  236. return $this->formatDate($date, false);
  237. }
  238. /**
  239. * Convert date and time to DB format
  240. *
  241. * @param mixed $date
  242. * @return string
  243. */
  244. public function convertDateTime($datetime)
  245. {
  246. return $this->formatDate($datetime, true);
  247. }
  248. /**
  249. * Creates a PDO object and connects to the database.
  250. *
  251. * @throws Zend_Db_Adapter_Exception
  252. */
  253. protected function _connect()
  254. {
  255. if ($this->_connection) {
  256. return;
  257. }
  258. if (!extension_loaded('pdo_mysql')) {
  259. throw new Zend_Db_Adapter_Exception('pdo_mysql extension is not installed');
  260. }
  261. if (strpos($this->_config['host'], '/') !== false) {
  262. $this->_config['unix_socket'] = $this->_config['host'];
  263. unset($this->_config['host']);
  264. } else if (strpos($this->_config['host'], ':') !== false) {
  265. list($this->_config['host'], $this->_config['port']) = explode(':', $this->_config['host']);
  266. }
  267. $this->_debugTimer();
  268. parent::_connect();
  269. $this->_debugStat(self::DEBUG_CONNECT, '');
  270. /** @link http://bugs.mysql.com/bug.php?id=18551 */
  271. $this->_connection->query("SET SQL_MODE=''");
  272. if (!$this->_connectionFlagsSet) {
  273. $this->_connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
  274. $this->_connection->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
  275. $this->_connectionFlagsSet = true;
  276. }
  277. }
  278. /**
  279. * Run RAW Query
  280. *
  281. * @param string $sql
  282. * @return Zend_Db_Statement_Interface
  283. * @throws PDOException
  284. */
  285. public function raw_query($sql)
  286. {
  287. $lostConnectionMessage = 'SQLSTATE[HY000]: General error: 2013 Lost connection to MySQL server during query';
  288. $tries = 0;
  289. do {
  290. $retry = false;
  291. try {
  292. $result = $this->query($sql);
  293. } catch (Exception $e) {
  294. // Convert to PDOException to maintain backwards compatibility with usage of MySQL adapter
  295. if ($e instanceof Zend_Db_Statement_Exception) {
  296. $e = $e->getPrevious();
  297. if (!($e instanceof PDOException)) {
  298. $e = new PDOException($e->getMessage(), $e->getCode());
  299. }
  300. }
  301. // Check to reconnect
  302. if ($tries < 10 && $e->getMessage() == $lostConnectionMessage) {
  303. $retry = true;
  304. $tries++;
  305. } else {
  306. throw $e;
  307. }
  308. }
  309. } while ($retry);
  310. return $result;
  311. }
  312. /**
  313. * Run RAW query and Fetch First row
  314. *
  315. * @param string $sql
  316. * @param string|int $field
  317. * @return boolean
  318. */
  319. public function raw_fetchRow($sql, $field = null)
  320. {
  321. $result = $this->raw_query($sql);
  322. if (!$result) {
  323. return false;
  324. }
  325. $row = $result->fetch(PDO::FETCH_ASSOC);
  326. if (!$row) {
  327. return false;
  328. }
  329. if (empty($field)) {
  330. return $row;
  331. } else {
  332. return isset($row[$field]) ? $row[$field] : false;
  333. }
  334. }
  335. /**
  336. * Special handling for PDO query().
  337. * All bind parameter names must begin with ':'.
  338. *
  339. * @param string|Zend_Db_Select $sql The SQL statement with placeholders.
  340. * @param mixed $bind An array of data or data itself to bind to the placeholders.
  341. * @return Zend_Db_Pdo_Statement
  342. * @throws Zend_Db_Adapter_Exception To re-throw PDOException.
  343. */
  344. public function query($sql, $bind = array())
  345. {
  346. $this->_debugTimer();
  347. try {
  348. $this->_prepareQuery($sql, $bind);
  349. $result = parent::query($sql, $bind);
  350. } catch (Exception $e) {
  351. $this->_debugStat(self::DEBUG_QUERY, $sql, $bind);
  352. $this->_debugException($e);
  353. }
  354. $this->_debugStat(self::DEBUG_QUERY, $sql, $bind, $result);
  355. return $result;
  356. }
  357. /**
  358. * Prepares SQL query by moving to bind all special parameters that can be confused with bind placeholders
  359. * (e.g. "foo:bar"). And also changes named bind to positional one, because underlying library has problems
  360. * with named binds.
  361. *
  362. * @param Zend_Db_Select|string $sql
  363. * @param mixed $bind
  364. * @return Varien_Db_Adapter_Pdo_Mysql
  365. */
  366. protected function _prepareQuery(&$sql, &$bind = array())
  367. {
  368. $sql = (string) $sql;
  369. if (!is_array($bind)) {
  370. $bind = array($bind);
  371. }
  372. // Mixed bind is not supported - so remember whether it is named bind, to normalize later if required
  373. $isNamedBind = false;
  374. if ($bind) {
  375. foreach ($bind as $k => $v) {
  376. if (!is_int($k)) {
  377. $isNamedBind = true;
  378. if ($k[0] != ':') {
  379. $bind[":{$k}"] = $v;
  380. unset($bind[$k]);
  381. }
  382. }
  383. }
  384. }
  385. if (strpos($sql, ':') !== false || strpos($sql, '?') !== false) {
  386. $before = count($bind);
  387. $this->_bindParams = $bind; // Used by callback
  388. $sql = preg_replace_callback('#(([\'"])((\\2)|((.*?[^\\\\])\\2)))#',
  389. array($this, 'proccessBindCallback'),
  390. $sql);
  391. Varien_Exception::processPcreError();
  392. $bind = $this->_bindParams;
  393. // If _processBindCallbacks() has added named entries to positional bind - normalize it to positional
  394. if (!$isNamedBind && $before && (count($bind) != $before)) {
  395. $this->_convertMixedBind($sql, $bind);
  396. }
  397. }
  398. // Special query hook
  399. if ($this->_queryHook) {
  400. $object = $this->_queryHook['object'];
  401. $method = $this->_queryHook['method'];
  402. $object->$method($sql, $bind);
  403. }
  404. return $this;
  405. }
  406. /**
  407. * Callback function for preparation of query and bind by regexp.
  408. * Checks query parameters for special symbols and moves such parameters to bind array as named ones.
  409. * This method writes to $_bindParams, where query bind parameters are kept.
  410. * This method requires further normalizing, if bind array is positional.
  411. *
  412. * @param array $matches
  413. * @return string
  414. */
  415. public function proccessBindCallback($matches)
  416. {
  417. if (isset($matches[6]) && (
  418. strpos($matches[6], "'") !== false ||
  419. strpos($matches[6], ':') !== false ||
  420. strpos($matches[6], '?') !== false)
  421. ) {
  422. $bindName = ':_mage_bind_var_' . (++$this->_bindIncrement);
  423. $this->_bindParams[$bindName] = $this->_unQuote($matches[6]);
  424. return ' ' . $bindName;
  425. }
  426. return $matches[0];
  427. }
  428. /**
  429. * Unquote raw string (use for auto-bind)
  430. *
  431. * @param string $string
  432. * @return string
  433. */
  434. protected function _unQuote($string)
  435. {
  436. $translate = array(
  437. "\\000" => "\000",
  438. "\\n" => "\n",
  439. "\\r" => "\r",
  440. "\\\\" => "\\",
  441. "\'" => "'",
  442. "\\\"" => "\"",
  443. "\\032" => "\032"
  444. );
  445. return strtr($string, $translate);
  446. }
  447. /**
  448. * Normalizes mixed positional-named bind to positional bind, and replaces named placeholders in query to
  449. * '?' placeholders.
  450. *
  451. * @param string $sql
  452. * @param array $bind
  453. * @return Varien_Db_Adapter_Pdo_Mysql
  454. */
  455. protected function _convertMixedBind(&$sql, &$bind)
  456. {
  457. $positions = array();
  458. $offset = 0;
  459. // get positions
  460. while (true) {
  461. $pos = strpos($sql, '?', $offset);
  462. if ($pos !== false) {
  463. $positions[] = $pos;
  464. $offset = ++$pos;
  465. } else {
  466. break;
  467. }
  468. }
  469. $bindResult = array();
  470. $map = array();
  471. foreach ($bind as $k => $v) {
  472. // positional
  473. if (is_int($k)) {
  474. if (!isset($positions[$k])) {
  475. continue;
  476. }
  477. $bindResult[$positions[$k]] = $v;
  478. } else {
  479. $offset = 0;
  480. while (true) {
  481. $pos = strpos($sql, $k, $offset);
  482. if ($pos === false) {
  483. break;
  484. } else {
  485. $offset = $pos + strlen($k);
  486. $bindResult[$pos] = $v;
  487. }
  488. }
  489. $map[$k] = '?';
  490. }
  491. }
  492. ksort($bindResult);
  493. $bind = array_values($bindResult);
  494. $sql = strtr($sql, $map);
  495. return $this;
  496. }
  497. /**
  498. * Sets (removes) query hook.
  499. *
  500. * $hook must be either array with 'object' and 'method' entries, or null to remove hook.
  501. * Previous hook is returned.
  502. *
  503. * @param array $hook
  504. * @return mixed
  505. */
  506. public function setQueryHook($hook)
  507. {
  508. $prev = $this->_queryHook;
  509. $this->_queryHook = $hook;
  510. return $prev;
  511. }
  512. /**
  513. * Executes a SQL statement(s)
  514. *
  515. * @param string $sql
  516. * @throws Zend_Db_Exception
  517. * @return Varien_Db_Adapter_Pdo_Mysql
  518. */
  519. public function multiQuery($sql)
  520. {
  521. return $this->multi_query($sql);
  522. }
  523. /**
  524. * Run Multi Query
  525. *
  526. * @param string $sql
  527. * @return array
  528. */
  529. public function multi_query($sql)
  530. {
  531. ##$result = $this->raw_query($sql);
  532. #$this->beginTransaction();
  533. try {
  534. $stmts = $this->_splitMultiQuery($sql);
  535. $result = array();
  536. foreach ($stmts as $stmt) {
  537. $result[] = $this->raw_query($stmt);
  538. }
  539. #$this->commit();
  540. } catch (Exception $e) {
  541. #$this->rollback();
  542. throw $e;
  543. }
  544. $this->resetDdlCache();
  545. return $result;
  546. }
  547. /**
  548. * Split multi statement query
  549. *
  550. * @param $sql string
  551. * @return array
  552. */
  553. protected function _splitMultiQuery($sql)
  554. {
  555. $parts = preg_split('#(;|\'|"|\\\\|//|--|\n|/\*|\*/)#', $sql, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
  556. $q = false;
  557. $c = false;
  558. $stmts = array();
  559. $s = '';
  560. foreach ($parts as $i => $part) {
  561. // strings
  562. if (($part === "'" || $part === '"') && ($i === 0 || $parts[$i-1] !== '\\')) {
  563. if ($q === false) {
  564. $q = $part;
  565. } elseif ($q === $part) {
  566. $q = false;
  567. }
  568. }
  569. // single line comments
  570. if (($part === '//' || $part === '--') && ($i === 0 || $parts[$i-1] === "\n")) {
  571. $c = $part;
  572. } elseif ($part === "\n" && ($c === '//' || $c === '--')) {
  573. $c = false;
  574. }
  575. // multi line comments
  576. if ($part === '/*' && $c === false) {
  577. $c = '/*';
  578. } elseif ($part === '*/' && $c === '/*') {
  579. $c = false;
  580. }
  581. // statements
  582. if ($part === ';' && $q === false && $c === false) {
  583. if (trim($s)!=='') {
  584. $stmts[] = trim($s);
  585. $s = '';
  586. }
  587. } else {
  588. $s .= $part;
  589. }
  590. }
  591. if (trim($s) !== '') {
  592. $stmts[] = trim($s);
  593. }
  594. return $stmts;
  595. }
  596. /**
  597. * Drop the Foreign Key from table
  598. *
  599. * @param string $tableName
  600. * @param string $fkName
  601. * @param string $schemaName
  602. * @return Varien_Db_Adapter_Pdo_Mysql
  603. */
  604. public function dropForeignKey($tableName, $fkName, $schemaName = null)
  605. {
  606. $foreignKeys = $this->getForeignKeys($tableName, $schemaName);
  607. $fkName = strtoupper($fkName);
  608. if (substr($fkName, 0, 3) == 'FK_') {
  609. $fkName = substr($fkName, 3);
  610. }
  611. foreach (array($fkName, 'FK_' . $fkName) as $key) {
  612. if (isset($foreignKeys[$key])) {
  613. $sql = sprintf('ALTER TABLE %s DROP FOREIGN KEY %s',
  614. $this->quoteIdentifier($this->_getTableName($tableName, $schemaName)),
  615. $this->quoteIdentifier($foreignKeys[$key]['FK_NAME'])
  616. );
  617. $this->resetDdlCache($tableName, $schemaName);
  618. $this->raw_query($sql);
  619. }
  620. }
  621. return $this;
  622. }
  623. /**
  624. * Delete index from a table if it exists
  625. *
  626. * @deprecated since 1.4.0.1
  627. * @param string $tableName
  628. * @param string $keyName
  629. * @param string $schemaName
  630. * @return bool|Zend_Db_Statement_Interface
  631. */
  632. public function dropKey($tableName, $keyName, $schemaName = null)
  633. {
  634. return $this->dropIndex($tableName, $keyName, $schemaName);
  635. }
  636. /**
  637. * Prepare table before add constraint foreign key
  638. *
  639. * @param string $tableName
  640. * @param string $columnName
  641. * @param string $refTableName
  642. * @param string $refColumnName
  643. * @param string $onDelete
  644. * @return Varien_Db_Adapter_Pdo_Mysql
  645. */
  646. public function purgeOrphanRecords($tableName, $columnName, $refTableName, $refColumnName,
  647. $onDelete = Varien_Db_Adapter_Interface::FK_ACTION_CASCADE)
  648. {
  649. $onDelete = strtoupper($onDelete);
  650. if ($onDelete == Varien_Db_Adapter_Interface::FK_ACTION_CASCADE
  651. || $onDelete == Varien_Db_Adapter_Interface::FK_ACTION_RESTRICT
  652. ) {
  653. $sql = sprintf("DELETE p.* FROM %s AS p LEFT JOIN %s AS r ON p.%s = r.%s WHERE r.%s IS NULL",
  654. $this->quoteIdentifier($tableName),
  655. $this->quoteIdentifier($refTableName),
  656. $this->quoteIdentifier($columnName),
  657. $this->quoteIdentifier($refColumnName),
  658. $this->quoteIdentifier($refColumnName));
  659. $this->raw_query($sql);
  660. } elseif ($onDelete == Varien_Db_Adapter_Interface::FK_ACTION_SET_NULL) {
  661. $sql = sprintf("UPDATE %s AS p LEFT JOIN %s AS r ON p.%s = r.%s SET p.%s = NULL WHERE r.%s IS NULL",
  662. $this->quoteIdentifier($tableName),
  663. $this->quoteIdentifier($refTableName),
  664. $this->quoteIdentifier($columnName),
  665. $this->quoteIdentifier($refColumnName),
  666. $this->quoteIdentifier($columnName),
  667. $this->quoteIdentifier($refColumnName));
  668. $this->raw_query($sql);
  669. }
  670. return $this;
  671. }
  672. /**
  673. * Add foreign key to table. If FK with same name exist - it will be deleted
  674. *
  675. * @deprecated since 1.4.0.1
  676. * @param string $fkName foreign key name
  677. * @param string $tableName main table name
  678. * @param string $keyName main table field name
  679. * @param string $refTableName refered table name
  680. * @param string $refKeyName refered table field name
  681. * @param string $onUpdate on update statement
  682. * @param string $onDelete on delete statement
  683. * @param bool $purge
  684. * @return mixed
  685. */
  686. public function addConstraint($fkName, $tableName, $columnName,
  687. $refTableName, $refColumnName, $onDelete = Varien_Db_Adapter_Interface::FK_ACTION_CASCADE,
  688. $onUpdate = Varien_Db_Adapter_Interface::FK_ACTION_CASCADE, $purge = false)
  689. {
  690. return $this->addForeignKey($fkName, $tableName, $columnName, $refTableName, $refColumnName,
  691. $onDelete, $onUpdate, $purge);
  692. }
  693. /**
  694. * Check does table column exist
  695. *
  696. * @param string $tableName
  697. * @param string $columnName
  698. * @param string $schemaName
  699. * @return boolean
  700. */
  701. public function tableColumnExists($tableName, $columnName, $schemaName = null)
  702. {
  703. $describe = $this->describeTable($tableName, $schemaName);
  704. foreach ($describe as $column) {
  705. if ($column['COLUMN_NAME'] == $columnName) {
  706. return true;
  707. }
  708. }
  709. return false;
  710. }
  711. /**
  712. * Adds new column to table.
  713. *
  714. * Generally $defintion must be array with column data to keep this call cross-DB compatible.
  715. * Using string as $definition is allowed only for concrete DB adapter.
  716. * Adds primary key if needed
  717. *
  718. * @param string $tableName
  719. * @param string $columnName
  720. * @param array|string $definition string specific or universal array DB Server definition
  721. * @param string $schemaName
  722. * @return int|boolean
  723. * @throws Zend_Db_Exception
  724. */
  725. public function addColumn($tableName, $columnName, $definition, $schemaName = null)
  726. {
  727. if ($this->tableColumnExists($tableName, $columnName, $schemaName)) {
  728. return true;
  729. }
  730. $primaryKey = '';
  731. if (is_array($definition)) {
  732. $definition = array_change_key_case($definition, CASE_UPPER);
  733. if (empty($definition['COMMENT'])) {
  734. throw new Zend_Db_Exception("Impossible to create a column without comment.");
  735. }
  736. if (!empty($definition['PRIMARY'])) {
  737. $primaryKey = sprintf(', ADD PRIMARY KEY (%s)', $this->quoteIdentifier($columnName));
  738. }
  739. $definition = $this->_getColumnDefinition($definition);
  740. }
  741. $sql = sprintf('ALTER TABLE %s ADD COLUMN %s %s %s',
  742. $this->quoteIdentifier($this->_getTableName($tableName, $schemaName)),
  743. $this->quoteIdentifier($columnName),
  744. $definition,
  745. $primaryKey
  746. );
  747. $result = $this->raw_query($sql);
  748. $this->resetDdlCache($tableName, $schemaName);
  749. return $result;
  750. }
  751. /**
  752. * Delete table column
  753. *
  754. * @param string $tableName
  755. * @param string $columnName
  756. * @param string $schemaName
  757. * @return bool
  758. */
  759. public function dropColumn($tableName, $columnName, $schemaName = null)
  760. {
  761. if (!$this->tableColumnExists($tableName, $columnName, $schemaName)) {
  762. return true;
  763. }
  764. $alterDrop = array();
  765. $foreignKeys = $this->getForeignKeys($tableName, $schemaName);
  766. foreach ($foreignKeys as $fkProp) {
  767. if ($fkProp['COLUMN_NAME'] == $columnName) {
  768. $alterDrop[] = 'DROP FOREIGN KEY ' . $this->quoteIdentifier($fkProp['FK_NAME']);
  769. }
  770. }
  771. $alterDrop[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
  772. $sql = sprintf('ALTER TABLE %s %s',
  773. $this->quoteIdentifier($this->_getTableName($tableName, $schemaName)),
  774. implode(', ', $alterDrop));
  775. $result = $this->raw_query($sql);
  776. $this->resetDdlCache($tableName, $schemaName);
  777. return $result;
  778. }
  779. /**
  780. * Change the column name and definition
  781. *
  782. * For change definition of column - use modifyColumn
  783. *
  784. * @param string $tableName
  785. * @param string $oldColumnName
  786. * @param string $newColumnName
  787. * @param array $definition
  788. * @param boolean $flushData flush table statistic
  789. * @param string $schemaName
  790. * @return Varien_Db_Adapter_Pdo_Mysql
  791. * @throws Zend_Db_Exception
  792. */
  793. public function changeColumn($tableName, $oldColumnName, $newColumnName, $definition, $flushData = false,
  794. $schemaName = null)
  795. {
  796. if (!$this->tableColumnExists($tableName, $oldColumnName, $schemaName)) {
  797. throw new Zend_Db_Exception(sprintf('Column "%s" does not exists on table "%s"', $oldColumnName, $tableName));
  798. }
  799. if (is_array($definition)) {
  800. $definition = $this->_getColumnDefinition($definition);
  801. }
  802. $sql = sprintf('ALTER TABLE %s CHANGE COLUMN %s %s %s',
  803. $this->quoteIdentifier($tableName),
  804. $this->quoteIdentifier($oldColumnName),
  805. $this->quoteIdentifier($newColumnName),
  806. $definition);
  807. $result = $this->raw_query($sql);
  808. if ($flushData) {
  809. $this->showTableStatus($tableName, $schemaName);
  810. }
  811. $this->resetDdlCache($tableName, $schemaName);
  812. return $result;
  813. }
  814. /**
  815. * Modify the column definition
  816. *
  817. * @param string $tableName
  818. * @param string $columnName
  819. * @param array|string $definition
  820. * @param boolean $flushData
  821. * @param string $schemaName
  822. * @return Varien_Db_Adapter_Pdo_Mysql
  823. * @throws Zend_Db_Exception
  824. */
  825. public function modifyColumn($tableName, $columnName, $definition, $flushData = false, $schemaName = null)
  826. {
  827. if (!$this->tableColumnExists($tableName, $columnName, $schemaName)) {
  828. throw new Zend_Db_Exception(sprintf('Column "%s" does not exists on table "%s"', $columnName, $tableName));
  829. }
  830. if (is_array($definition)) {
  831. $definition = $this->_getColumnDefinition($definition);
  832. }
  833. $sql = sprintf('ALTER TABLE %s MODIFY COLUMN %s %s',
  834. $this->quoteIdentifier($tableName),
  835. $this->quoteIdentifier($columnName),
  836. $definition);
  837. $this->raw_query($sql);
  838. if ($flushData) {
  839. $this->showTableStatus($tableName, $schemaName);
  840. }
  841. $this->resetDdlCache($tableName, $schemaName);
  842. return $this;
  843. }
  844. /**
  845. * Show table status
  846. *
  847. * @param string $tableName
  848. * @param string $schemaName
  849. * @return array|false
  850. */
  851. public function showTableStatus($tableName, $schemaName = null)
  852. {
  853. $fromDbName = null;
  854. if ($schemaName !== null) {
  855. $fromDbName = ' FROM ' . $this->quoteIdentifier($schemaName);
  856. }
  857. $query = sprintf('SHOW TABLE STATUS%s LIKE %s', $fromDbName, $this->quote($tableName));
  858. return $this->raw_fetchRow($query);
  859. }
  860. /**
  861. * Retrieve table index key list
  862. *
  863. * @deprecated use getIndexList(
  864. * @param string $tableName
  865. * @param string $schemaName
  866. * @return array
  867. */
  868. public function getKeyList($tableName, $schemaName = null)
  869. {
  870. $keyList = array();
  871. $indexList = $this->getIndexList($tableName, $schemaName);
  872. foreach ($indexList as $indexProp) {
  873. $keyList[$indexProp['KEY_NAME']] = $indexProp['COLUMNS_LIST'];
  874. }
  875. return $keyList;
  876. }
  877. /**
  878. * Retrieve Create Table SQL
  879. *
  880. * @param string $tableName
  881. * @param string $schemaName
  882. * @return string
  883. */
  884. public function getCreateTable($tableName, $schemaName = null)
  885. {
  886. $cacheKey = $this->_getTableName($tableName, $schemaName);
  887. $ddl = $this->loadDdlCache($cacheKey, self::DDL_CREATE);
  888. if ($ddl === false) {
  889. $sql = 'SHOW CREATE TABLE ' . $this->quoteIdentifier($tableName);
  890. $ddl = $this->raw_fetchRow($sql, 'Create Table');
  891. $this->saveDdlCache($cacheKey, self::DDL_CREATE, $ddl);
  892. }
  893. return $ddl;
  894. }
  895. /**
  896. * Retrieve the foreign keys descriptions for a table.
  897. *
  898. * The return value is an associative array keyed by the UPPERCASE foreign key,
  899. * as returned by the RDBMS.
  900. *
  901. * The value of each array element is an associative array
  902. * with the following keys:
  903. *
  904. * FK_NAME => string; original foreign key name
  905. * SCHEMA_NAME => string; name of database or schema
  906. * TABLE_NAME => string;
  907. * COLUMN_NAME => string; column name
  908. * REF_SCHEMA_NAME => string; name of reference database or schema
  909. * REF_TABLE_NAME => string; reference table name
  910. * REF_COLUMN_NAME => string; reference column name
  911. * ON_DELETE => string; action type on delete row
  912. * ON_UPDATE => string; action type on update row
  913. *
  914. * @param string $tableName
  915. * @param string $schemaName
  916. * @return array
  917. */
  918. public function getForeignKeys($tableName, $schemaName = null)
  919. {
  920. $cacheKey = $this->_getTableName($tableName, $schemaName);
  921. $ddl = $this->loadDdlCache($cacheKey, self::DDL_FOREIGN_KEY);
  922. if ($ddl === false) {
  923. $ddl = array();
  924. $createSql = $this->getCreateTable($tableName, $schemaName);
  925. // collect CONSTRAINT
  926. $regExp = '#,\s+CONSTRAINT `([^`]*)` FOREIGN KEY \(`([^`]*)`\) '
  927. . 'REFERENCES (`[^`]*\.)?`([^`]*)` \(`([^`]*)`\)'
  928. . '( ON DELETE (RESTRICT|CASCADE|SET NULL|NO ACTION))?'
  929. . '( ON UPDATE (RESTRICT|CASCADE|SET NULL|NO ACTION))?#';
  930. $matches = array();
  931. preg_match_all($regExp, $createSql, $matches, PREG_SET_ORDER);
  932. foreach ($matches as $match) {
  933. $ddl[strtoupper($match[1])] = array(
  934. 'FK_NAME' => $match[1],
  935. 'SCHEMA_NAME' => $schemaName,
  936. 'TABLE_NAME' => $tableName,
  937. 'COLUMN_NAME' => $match[2],
  938. 'REF_SHEMA_NAME' => isset($match[3]) ? $match[3] : $schemaName,
  939. 'REF_TABLE_NAME' => $match[4],
  940. 'REF_COLUMN_NAME' => $match[5],
  941. 'ON_DELETE' => isset($match[6]) ? $match[7] : '',
  942. 'ON_UPDATE' => isset($match[8]) ? $match[9] : ''
  943. );
  944. }
  945. $this->saveDdlCache($cacheKey, self::DDL_FOREIGN_KEY, $ddl);
  946. }
  947. return $ddl;
  948. }
  949. /**
  950. * Retrieve the foreign keys tree for all tables
  951. *
  952. * @return array
  953. */
  954. public function getForeignKeysTree()
  955. {
  956. $tree = array();
  957. foreach ($this->listTables() as $table) {
  958. foreach($this->getForeignKeys($table) as $key) {
  959. $tree[$table][$key['COLUMN_NAME']] = $key;
  960. }
  961. }
  962. return $tree;
  963. }
  964. /**
  965. * Modify tables, used for upgrade process
  966. * Change columns definitions, reset foreign keys, change tables comments and engines.
  967. *
  968. * The value of each array element is an associative array
  969. * with the following keys:
  970. *
  971. * columns => array; list of columns definitions
  972. * comment => string; table comment
  973. * engine => string; table engine
  974. *
  975. * @return Varien_Db_Adapter_Pdo_Mysql
  976. */
  977. public function modifyTables($tables)
  978. {
  979. $foreignKeys = $this->getForeignKeysTree();
  980. foreach ($tables as $table => $tableData) {
  981. if (!$this->isTableExists($table)) {
  982. continue;
  983. }
  984. foreach ($tableData['columns'] as $column =>$columnDefinition) {
  985. if (!$this->tableColumnExists($table, $column)) {
  986. continue;
  987. }
  988. $droppedKeys = array();
  989. foreach($foreignKeys as $keyTable => $columns) {
  990. foreach($columns as $columnName => $keyOptions) {
  991. if ($table == $keyOptions['REF_TABLE_NAME'] && $column == $keyOptions['REF_COLUMN_NAME']) {
  992. $this->dropForeignKey($keyTable, $keyOptions['FK_NAME']);
  993. $droppedKeys[] = $keyOptions;
  994. }
  995. }
  996. }
  997. $this->modifyColumn($table, $column, $columnDefinition);
  998. foreach ($droppedKeys as $options) {
  999. unset($columnDefinition['identity'], $columnDefinition['primary'], $columnDefinition['comment']);
  1000. $onDelete = $options['ON_DELETE'];
  1001. $onUpdate = $options['ON_UPDATE'];
  1002. if ($onDelete == Varien_Db_Adapter_Interface::FK_ACTION_SET_NULL
  1003. || $onUpdate == Varien_Db_Adapter_Interface::FK_ACTION_SET_NULL) {
  1004. $columnDefinition['nullable'] = true;
  1005. }
  1006. $this->modifyColumn($options['TABLE_NAME'], $options['COLUMN_NAME'], $columnDefinition);
  1007. $this->addForeignKey(
  1008. $options['FK_NAME'],
  1009. $options['TABLE_NAME'],
  1010. $options['COLUMN_NAME'],
  1011. $options['REF_TABLE_NAME'],
  1012. $options['REF_COLUMN_NAME'],
  1013. ($onDelete) ? $onDelete : Varien_Db_Adapter_Interface::FK_ACTION_NO_ACTION,
  1014. ($onUpdate) ? $onUpdate : Varien_Db_Adapter_Interface::FK_ACTION_NO_ACTION
  1015. );
  1016. }
  1017. }
  1018. if (!empty($tableData['comment'])) {
  1019. $this->changeTableComment($table, $tableData['comment']);
  1020. }
  1021. if (!empty($tableData['engine'])) {
  1022. $this->changeTableEngine($table, $tableData['engine']);
  1023. }
  1024. }
  1025. return $this;
  1026. }
  1027. /**
  1028. * Retrieve table index information
  1029. *
  1030. * The return value is an associative array keyed by the UPPERCASE index key (except for primary key,
  1031. * that is always stored under 'PRIMARY' key) as returned by the RDBMS.
  1032. *
  1033. * The value of each array element is an associative array
  1034. * with the following keys:
  1035. *
  1036. * SCHEMA_NAME => string; name of database or schema
  1037. * TABLE_NAME => string; name of the table
  1038. * KEY_NAME => string; the original index name
  1039. * COLUMNS_LIST => array; array of index column names
  1040. * INDEX_TYPE => string; lowercase, create index type
  1041. * INDEX_METHOD => string; index method using
  1042. * type => string; see INDEX_TYPE
  1043. * fields => array; see COLUMNS_LIST
  1044. *
  1045. * @param string $tableName
  1046. * @param string $schemaName
  1047. * @return array
  1048. */
  1049. public function getIndexList($tableName, $schemaName = null)
  1050. {
  1051. $cacheKey = $this->_getTableName($tableName, $schemaName);
  1052. $ddl = $this->loadDdlCache($cacheKey, self::DDL_INDEX);
  1053. if ($ddl === false) {
  1054. $ddl = array();
  1055. $sql = sprintf('SHOW INDEX FROM %s',
  1056. $this->quoteIdentifier($this->_getTableName($tableName, $schemaName)));
  1057. foreach ($this->fetchAll($sql) as $row) {
  1058. $fieldKeyName = 'Key_name';
  1059. $fieldNonUnique = 'Non_unique';
  1060. $fieldColumn = 'Column_name';
  1061. $fieldIndexType = 'Index_type';
  1062. if (strtolower($row[$fieldKeyName]) == Varien_Db_Adapter_Interface::INDEX_TYPE_PRIMARY) {
  1063. $indexType = Varien_Db_Adapter_Interface::INDEX_TYPE_PRIMARY;
  1064. } elseif ($row[$fieldNonUnique] == 0) {
  1065. $indexType = Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE;
  1066. } elseif (strtolower($row[$fieldIndexType]) == Varien_Db_Adapter_Interface::INDEX_TYPE_FULLTEXT) {
  1067. $indexType = Varien_Db_Adapter_Interface::INDEX_TYPE_FULLTEXT;
  1068. } else {
  1069. $indexType = Varien_Db_Adapter_Interface::INDEX_TYPE_INDEX;
  1070. }
  1071. $upperKeyName = strtoupper($row[$fieldKeyName]);
  1072. if (isset($ddl[$upperKeyName])) {
  1073. $ddl[$upperKeyName]['fields'][] = $row[$fieldColumn]; // for compatible
  1074. $ddl[$upperKeyName]['COLUMNS_LIST'][] = $row[$fieldColumn];
  1075. } else {
  1076. $ddl[$upperKeyName] = array(
  1077. 'SCHEMA_NAME' => $schemaName,
  1078. 'TABLE_NAME' => $tableName,
  1079. 'KEY_NAME' => $row[$fieldKeyName],
  1080. 'COLUMNS_LIST' => array($row[$fieldColumn]),
  1081. 'INDEX_TYPE' => $indexType,
  1082. 'INDEX_METHOD' => $row[$fieldIndexType],
  1083. 'type' => strtolower($indexType), // for compatibility
  1084. 'fields' => array($row[$fieldColumn]) // for compatibility
  1085. );
  1086. }
  1087. }
  1088. $this->saveDdlCache($cacheKey, self::DDL_INDEX, $ddl);
  1089. }
  1090. return $ddl;
  1091. }
  1092. /**
  1093. * Add Index Key
  1094. *
  1095. * @deprecated since 1.5.0.0
  1096. * @param string $tableName
  1097. * @param string $indexName
  1098. * @param string|array $fields
  1099. * @param string $indexType
  1100. * @param string $schemaName
  1101. * @return Zend_Db_Statement_Interface
  1102. */
  1103. public function addKey($tableName, $indexName, $fields, $indexType = 'index', $schemaName = null)
  1104. {
  1105. return $this->addIndex($tableName, $indexName, $fields, $indexType, $schemaName);
  1106. }
  1107. /**
  1108. * Remove duplicate entry for create key
  1109. *
  1110. * @param string $table
  1111. * @param array $fields
  1112. * @param array $ids
  1113. * @return Varien_Db_Adapter_Pdo_Mysql
  1114. */
  1115. protected function _removeDuplicateEntry($table, $fields, $ids)
  1116. {
  1117. $where = array();
  1118. $i = 0;
  1119. foreach ($fields as $field) {
  1120. $where[] = $this->quoteInto($field . '=?', $ids[$i++]);
  1121. }
  1122. if (!$where) {
  1123. return $this;
  1124. }
  1125. $whereCond = implode(' AND ', $where);
  1126. $sql = sprintf('SELECT COUNT(*) as `cnt` FROM `%s` WHERE %s', $table, $whereCond);
  1127. $cnt = $this->raw_fetchRow($sql, 'cnt');
  1128. if ($cnt > 1) {
  1129. $sql = sprintf('DELETE FROM `%s` WHERE %s LIMIT %d',
  1130. $table,
  1131. $whereCond,
  1132. $cnt - 1
  1133. );
  1134. $this->raw_query($sql);
  1135. }
  1136. return $this;
  1137. }
  1138. /**
  1139. * Creates and returns a new Zend_Db_Select object for this adapter.
  1140. *
  1141. * @return Varien_Db_Select
  1142. */
  1143. public function select()
  1144. {
  1145. return new Varien_Db_Select($this);
  1146. }
  1147. /**
  1148. * Start debug timer
  1149. *
  1150. * @return Varien_Db_Adapter_Pdo_Mysql
  1151. */
  1152. protected function _debugTimer()
  1153. {
  1154. if ($this->_debug) {
  1155. $this->_debugTimer = microtime(true);
  1156. }
  1157. return $this;
  1158. }
  1159. /**
  1160. * Logging debug information
  1161. *
  1162. * @param int $type
  1163. * @param string $sql
  1164. * @param array $bind
  1165. * @param Zend_Db_Statement_Pdo $result
  1166. * @return Varien_Db_Adapter_Pdo_Mysql
  1167. */
  1168. protected function _debugStat($type, $sql, $bind = array(), $result = null)
  1169. {
  1170. if (!$this->_debug) {
  1171. return $this;
  1172. }
  1173. $code = '## ' . getmypid() . ' ## ';
  1174. $nl = "\n";
  1175. $time = sprintf('%.4f', microtime(true) - $this->_debugTimer);
  1176. if (!$this->_logAllQueries && $time < $this->_logQueryTime) {
  1177. return $this;
  1178. }
  1179. switch ($type) {
  1180. case self::DEBUG_CONNECT:
  1181. $code .= 'CONNECT' . $nl;
  1182. break;
  1183. case self::DEBUG_TRANSACTION:
  1184. $code .= 'TRANSACTION ' . $sql . $nl;
  1185. break;
  1186. case self::DEBUG_QUERY:
  1187. $code .= 'QUERY' . $nl;
  1188. $code .= 'SQL: ' . $sql . $nl;
  1189. if ($bind) {
  1190. $code .= 'BIND: ' . var_export($bind, true) . $nl;
  1191. }
  1192. if ($result instanceof Zend_Db_Statement_Pdo) {
  1193. $code .= 'AFF: ' . $result->rowCount() . $nl;
  1194. }
  1195. break;
  1196. }
  1197. $code .= 'TIME: ' . $time . $nl;
  1198. if ($this->_logCallStack) {
  1199. $code .= 'TRACE: ' . Varien_Debug::backtrace(true, false) . $nl;
  1200. }
  1201. $code .= $nl;
  1202. $this->_debugWriteToFile($code);
  1203. return $this;
  1204. }
  1205. /**
  1206. * Write exception and thow
  1207. *
  1208. * @param Exception $e
  1209. * @throws Exception
  1210. */
  1211. protected function _debugException(Exception $e)
  1212. {
  1213. if (!$this->_debug) {
  1214. throw $e;
  1215. }
  1216. $nl = "\n";
  1217. $code = 'EXCEPTION ' . $nl . $e . $nl . $nl;
  1218. $this->_debugWriteToFile($code);
  1219. throw $e;
  1220. }
  1221. /**
  1222. * Debug write to file process
  1223. *
  1224. * @param string $str
  1225. */
  1226. protected function _debugWriteToFile($str)
  1227. {
  1228. $str = '## ' . date('Y-m-d H:i:s') . "\r\n" . $str;
  1229. if (!$this->_debugIoAdapter) {
  1230. $this->_debugIoAdapter = new Varien_Io_File();
  1231. $dir = Mage::getBaseDir() . DS . $this->_debugIoAdapter->dirname($this->_debugFile);
  1232. $this->_debugIoAdapter->checkAndCreateFolder($dir);
  1233. $this->_debugIoAdapter->open(array('path' => $dir));
  1234. $this->_debugFile = basename($this->_debugFile);
  1235. }
  1236. $this->_debugIoAdapter->streamOpen($this->_debugFile, 'a');
  1237. $this->_debugIoAdapter->streamLock();
  1238. $this->_debugIoAdapter->streamWrite($str);
  1239. $this->_debugIoAdapter->streamUnlock();
  1240. $this->_debugIoAdapter->streamClose();
  1241. }
  1242. /**
  1243. * Quotes a value and places into a piece of text at a placeholder.
  1244. *
  1245. * Method revrited for handle empty arrays in value param
  1246. *
  1247. * @param string $text The text with a placeholder.
  1248. * @param mixed $value The value to quote.
  1249. * @param string $type OPTIONAL SQL datatype
  1250. * @param integer $count OPTIONAL count of placeholders to replace
  1251. * @return string An SQL-safe quoted value placed into the orignal text.
  1252. */
  1253. public function quoteInto($text, $value, $type = null, $count = null)
  1254. {
  1255. if (is_array($value) && empty($value)) {
  1256. $value = new Zend_Db_Expr('NULL');
  1257. }
  1258. return parent::quoteInto($text, $value, $type, $count);
  1259. }
  1260. /**
  1261. * Retrieve ddl cache name
  1262. *
  1263. * @param string $tableName
  1264. * @param string $schemaName
  1265. */
  1266. protected function _getTableName($tableName, $schemaName = null)
  1267. {
  1268. return ($schemaName ? $schemaName . '.' : '') . $tableName;
  1269. }
  1270. /**
  1271. * Retrieve Id for cache
  1272. *
  1273. * @param string $tableKey
  1274. * @param int $ddlType
  1275. * @return string
  1276. */
  1277. protected function _getCacheId($tableKey, $ddlType)
  1278. {
  1279. return sprintf('%s_%s_%s', self::DDL_CACHE_PREFIX, $tableKey, $ddlType);
  1280. }
  1281. /**
  1282. * Load DDL data from cache
  1283. * Return false if cache does not exists
  1284. *
  1285. * @param string $tableCacheKey the table cache key
  1286. * @param int $ddlType the DDL constant
  1287. * @return string|array|int|false
  1288. */
  1289. public function loadDdlCache($tableCacheKey, $ddlType)
  1290. {
  1291. if (!$this->_isDdlCacheAllowed) {
  1292. return false;
  1293. }
  1294. if (isset($this->_ddlCache[$ddlType][$tableCacheKey])) {
  1295. return $this->_ddlCache[$ddlType][$tableCacheKey];
  1296. }
  1297. if ($this->_cacheAdapter instanceof Zend_Cache_Core) {
  1298. $cacheId = $this->_getCacheId($tableCacheKey, $ddlType);
  1299. $data = $this->_cacheAdapter->load($cacheId);
  1300. if ($data !== false) {
  1301. $data = unserialize($data);
  1302. $this->_ddlCache[$ddlType][$tableCacheKey] = $data;
  1303. }
  1304. return $data;
  1305. }
  1306. return false;
  1307. }
  1308. /**
  1309. * Save DDL data into cache
  1310. *
  1311. * @param string $tableCacheKey
  1312. * @param int $ddlType
  1313. * @return Varien_Db_Adapter_Pdo_Mysql
  1314. */
  1315. public function saveDdlCache($tableCacheKey, $ddlType, $data)
  1316. {
  1317. if (!$this->_isDdlCacheAllowed) {
  1318. return $this;
  1319. }
  1320. $this->_ddlCache[$ddlType][$tableCacheKey] = $data;
  1321. if ($this->_cacheAdapter instanceof Zend_Cache_Core) {
  1322. $cacheId = $this->_getCacheId($tableCacheKey, $ddlType);
  1323. $data = serialize($data);
  1324. $this->_cacheAdapter->save($data, $cacheId, array(self::DDL_CACHE_TAG));
  1325. }
  1326. return $this;
  1327. }
  1328. /**
  1329. * Reset cached DDL data from cache
  1330. * if table name is null - reset all cached DDL data
  1331. *
  1332. * @param string $tableName
  1333. * @param string $schemaName OPTIONAL
  1334. * @return Varien_Db_Adapter_Pdo_Mysql
  1335. */
  1336. public function resetDdlCache($tableName = null, $schemaName = null)
  1337. {
  1338. if (!$this->_isDdlCacheAllowed) {
  1339. return $this;
  1340. }
  1341. if ($tableName === null) {
  1342. $this->_ddlCache = array();
  1343. if ($this->_cacheAdapter instanceof Zend_Cache_Core) {
  1344. $this->_cacheAdapter->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array(self::DDL_CACHE_TAG));
  1345. }
  1346. } else {
  1347. $cacheKey = $this->_getTableName($tableName, $schemaName);
  1348. $ddlTypes = array(self::DDL_DESCRIBE, self::DDL_CREATE, self::DDL_INDEX, self::DDL_FOREIGN_KEY);
  1349. foreach ($ddlTypes as $ddlType) {
  1350. unset($this->_ddlCache[$ddlType][$cacheKey]);
  1351. }
  1352. if ($this->_cacheAdapter instanceof Zend_Cache_Core) {
  1353. foreach ($ddlTypes as $ddlType) {
  1354. $cacheId = $this->_getCacheId($cacheKey, $ddlType);
  1355. $this->_cacheAdapter->remove($cacheId);
  1356. }
  1357. }
  1358. }
  1359. return $this;
  1360. }
  1361. /**
  1362. * Disallow DDL caching
  1363. * @return Varien_Db_Adapter_Pdo_Mysql
  1364. */
  1365. public function disallowDdlCache()
  1366. {
  1367. $this->_isDdlCacheAllowed = false;
  1368. return $this;
  1369. }
  1370. /**
  1371. * Allow DDL caching
  1372. * @return Varien_Db_Adapter_Pdo_Mysql
  1373. */
  1374. public function allowDdlCache()
  1375. {
  1376. $this->_isDdlCacheAllowed = true;
  1377. return $this;
  1378. }
  1379. /**
  1380. * Returns the column descriptions for a table.
  1381. *
  1382. * The return value is an associative array keyed by the column name,
  1383. * as returned by the RDBMS.
  1384. *
  1385. * The value of each array element is an associative array
  1386. * with the following keys:
  1387. *
  1388. * SCHEMA_NAME => string; name of database or schema
  1389. * TABLE_NAME => string;
  1390. * COLUMN_NAME => string; column name
  1391. * COLUMN_POSITION => number; ordinal position of column in table
  1392. * DATA_TYPE => string; SQL datatype name of column
  1393. * DEFAULT => string; default expression of column, null if none
  1394. * NULLABLE => boolean; true if column can have nulls
  1395. * LENGTH => number; length of CHAR/VARCHAR
  1396. * SCALE => number; scale of NUMERIC/DECIMAL
  1397. * PRECISION => number; precision of NUMERIC/DECIMAL
  1398. * UNSIGNED => boolean; unsigned property of an integer type
  1399. * PRIMARY => boolean; true if column is part of the primary key
  1400. * PRIMARY_POSITION => integer; position of column in primary key
  1401. * IDENTITY => integer; true if column is auto-generated with unique values
  1402. *
  1403. * @param string $tableName
  1404. * @param string $schemaName OPTIONAL
  1405. * @return array
  1406. */
  1407. public function describeTable($tableName, $schemaName = null)
  1408. {
  1409. $cacheKey = $this->_getTableName($tableName, $schemaName);
  1410. $ddl = $this->loadDdlCache($cacheKey, self::DDL_DESCRIBE);
  1411. if ($ddl === false) {
  1412. $ddl = parent::describeTable($tableName, $schemaName);
  1413. /**
  1414. * Remove bug in some MySQL versions, when int-column without default value is described as:
  1415. * having default empty string value
  1416. */
  1417. $affected = array('tinyint', 'smallint', 'mediumint', 'int', 'bigint');
  1418. foreach ($ddl as $key => $columnData) {
  1419. if (($columnData['DEFAULT'] === '') && (array_search($columnData['DATA_TYPE'], $affected) !== FALSE)) {
  1420. $ddl[$key]['DEFAULT'] = null;
  1421. }
  1422. }
  1423. $this->saveDdlCache($cacheKey, self::DDL_DESCRIBE, $ddl);
  1424. }
  1425. return $ddl;
  1426. }
  1427. /**
  1428. * Format described column to definition, ready to be added to ddl table.
  1429. * Return array with keys: name, type, length, options, comment
  1430. *
  1431. * @param array $columnData
  1432. * @return array
  1433. */
  1434. public function getColumnCreateByDescribe($columnData)
  1435. {
  1436. $type = $this->_getColumnTypeByDdl($columnData);
  1437. $options = array();
  1438. if ($columnData['IDENTITY'] === true) {
  1439. $options['identity'] = true;
  1440. }
  1441. if ($columnData['UNSIGNED'] === true) {
  1442. $options['unsigned'] = true;
  1443. }
  1444. if ($columnData['NULLABLE'] === false
  1445. && !($type == Varien_Db_Ddl_Table::TYPE_TEXT && strlen($columnData['DEFAULT']) != 0)
  1446. ) {
  1447. $options['nullable'] = false;
  1448. }
  1449. if ($columnData['PRIMARY'] === true) {
  1450. $options['primary'] = true;
  1451. }
  1452. if (!is_null($columnData['DEFAULT'])
  1453. && $type != Varien_Db_Ddl_Table::TYPE_TEXT
  1454. ) {
  1455. $options['default'] = $this->quote($columnData['DEFAULT']);
  1456. }
  1457. if (strlen($columnData['SCALE']) > 0) {
  1458. $options['scale'] = $columnData['SCALE'];
  1459. }
  1460. if (strlen($columnData['PRECISION']) > 0) {
  1461. $options['precision'] = $columnData['PRECISION'];
  1462. }
  1463. $comment = uc_words($columnData['COLUMN_NAME'], ' ');
  1464. $result = array(
  1465. 'name' => $columnData['COLUMN_NAME'],
  1466. 'type' => $type,
  1467. 'length' => $columnData['LENGTH'],
  1468. 'options' => $options,
  1469. 'comment' => $comment
  1470. );
  1471. return $result;
  1472. }
  1473. /**
  1474. * Create Varien_Db_Ddl_Table object by data from describe table
  1475. *
  1476. * @param $tableName
  1477. * @param $newTableName
  1478. * @return Varien_Db_Ddl_Table
  1479. */
  1480. public function createTableByDdl($tableName, $newTableName)
  1481. {
  1482. $describe = $this->describeTable($tableName);
  1483. $table = $this->newTable($newTableName)
  1484. ->setComment(uc_words($newTableName, ' '));
  1485. foreach ($describe as $columnData) {
  1486. $columnInfo = $this->getColumnCreateByDescribe($columnData);
  1487. $table->addColumn(
  1488. $columnInfo['name'],
  1489. $columnInfo['type'],
  1490. $columnInfo['length'],
  1491. $columnInfo['options'],
  1492. $columnInfo['comment']
  1493. );
  1494. }
  1495. $indexes = $this->getIndexList($tableName);
  1496. foreach ($indexes as $indexData) {
  1497. /**
  1498. * Do not create primary index - it is created with identity column.
  1499. * For reliability check both name and type, because these values can start to differ in future.
  1500. */
  1501. if (($indexData['KEY_NAME'] == 'PRIMARY')
  1502. || ($indexData['INDEX_TYPE'] == Varien_Db_Adapter_Interface::INDEX_TYPE_PRIMARY)
  1503. ) {
  1504. continue;
  1505. }
  1506. $fields = $indexData['COLUMNS_LIST'];
  1507. $options = array('type' => $indexData['INDEX_TYPE']);
  1508. $table->addIndex($this->getIndexName($newTableName, $fields, $indexData['INDEX_TYPE']), $fields, $options);
  1509. }
  1510. $foreignKeys = $this->getForeignKeys($tableName);
  1511. foreach ($foreignKeys as $keyData) {
  1512. $fkName = $this->getForeignKeyName(
  1513. $newTableName, $keyData['COLUMN_NAME'], $keyData['REF_TABLE_NAME'], $keyData['REF_COLUMN_NAME']
  1514. );
  1515. $onDelete = $this->_getDdlAction($keyData['ON_DELETE']);
  1516. $onUpdate = $this->_getDdlAction($keyData['ON_UPDATE']);
  1517. $table->addForeignKey(
  1518. $fkName, $keyData['COLUMN_NAME'], $keyData['REF_TABLE_NAME'],
  1519. $keyData['REF_COLUMN_NAME'], $onDelete, $onUpdate
  1520. );
  1521. }
  1522. // Set additional options
  1523. $tableData = $this->showTableStatus($tableName);
  1524. $table->setOption('type', $tableData['Engine']);
  1525. return $table;
  1526. }
  1527. /**
  1528. * Modify the column definition by data from describe table
  1529. *
  1530. * @param string $tableName
  1531. * @param string $columnName
  1532. * @param array $definition
  1533. * @param boolean $flushData
  1534. * @param string $schemaName
  1535. * @return Varien_Db_Adapter_Pdo_Mysql
  1536. */
  1537. public function modifyColumnByDdl($tableName, $columnName, $definition, $flushData = false, $schemaName = null)
  1538. {
  1539. $definition = array_change_key_case($definition, CASE_UPPER);
  1540. $definition['COLUMN_TYPE'] = $this->_getColumnTypeByDdl($definition);
  1541. if (array_key_exists('DEFAULT', $definition) && is_null($definition['DEFAULT'])) {
  1542. unset($definition['DEFAULT']);
  1543. }
  1544. return $this->modifyColumn($tableName, $columnName, $definition, $flushData, $schemaName);
  1545. }
  1546. /**
  1547. * Retrieve column data type by data from describe table
  1548. *
  1549. * @param array $column
  1550. * @return string
  1551. */
  1552. protected function _getColumnTypeByDdl($column)
  1553. {
  1554. switch ($column['DATA_TYPE']) {
  1555. case 'bool':
  1556. return Varien_Db_Ddl_Table::TYPE_BOOLEAN;
  1557. case 'tinytext':
  1558. case 'char':
  1559. case 'varchar':
  1560. case 'text':
  1561. case 'mediumtext':
  1562. case 'longtext':
  1563. return Varien_Db_Ddl_Table::TYPE_TEXT;
  1564. case 'blob':
  1565. case 'mediumblob':
  1566. case 'longblob':
  1567. return Varien_Db_Ddl_Table::TYPE_BLOB;
  1568. case 'tinyint':
  1569. case 'smallint':
  1570. return Varien_Db_Ddl_Table::TYPE_SMALLINT;
  1571. case 'mediumint':
  1572. case 'int':
  1573. return Varien_Db_Ddl_Table::TYPE_INTEGER;
  1574. case 'bigint':
  1575. return Varien_Db_Ddl_Table::TYPE_BIGINT;
  1576. case 'datetime':
  1577. return Varien_Db_Ddl_Table::TYPE_DATETIME;
  1578. case 'timestamp':
  1579. return Varien_Db_Ddl_Table::TYPE_TIMESTAMP;
  1580. case 'date':
  1581. return Varien_Db_Ddl_Table::TYPE_DATE;
  1582. case 'float':
  1583. return Varien_Db_Ddl_Table::TYPE_FLOAT;
  1584. case 'decimal':
  1585. case 'numeric':
  1586. return Varien_Db_Ddl_Table::TYPE_DECIMAL;
  1587. }
  1588. }
  1589. /**
  1590. * Truncate table
  1591. *
  1592. * @deprecated since 1.4.0.1
  1593. * @param string $tableName
  1594. * @param string $schemaName
  1595. * @return Varien_Db_Adapter_Pdo_Mysql
  1596. */
  1597. public function truncate($tableName, $schemaName = null)
  1598. {
  1599. return $this->truncateTable($tableName, $schemaName);
  1600. }
  1601. /**
  1602. * Change table storage engine
  1603. *
  1604. * @param string $tableName
  1605. * @param string $engine
  1606. * @param string $schemaName
  1607. * @return mixed
  1608. */
  1609. public function changeTableEngine($tableName, $engine, $schemaName = null)
  1610. {
  1611. $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
  1612. $sql = sprintf('ALTER TABLE %s ENGINE=%s', $table, $engine);
  1613. return $this->raw_query($sql);
  1614. }
  1615. /**
  1616. * Change table comment
  1617. *
  1618. * @param string $tableName
  1619. * @param string $comment
  1620. * @param string $schemaName
  1621. * @return mixed
  1622. */
  1623. public function changeTableComment($tableName, $comment, $schemaName = null)
  1624. {
  1625. $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
  1626. $sql = sprintf("ALTER TABLE %s COMMENT='%s'", $table, $comment);
  1627. return $this->raw_query($sql);
  1628. }
  1629. /**
  1630. * Inserts a table row with specified data
  1631. * Special for Zero values to identity column
  1632. *
  1633. * @param string $table
  1634. * @param array $bind
  1635. * @return int The number of affected rows.
  1636. */
  1637. public function insertForce($table, array $bind)
  1638. {
  1639. $this->raw_query("SET @OLD_INSERT_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO'");
  1640. $result = $this->insert($table, $bind);
  1641. $this->raw_query("SET SQL_MODE=IFNULL(@OLD_INSERT_SQL_MODE,'')");
  1642. return $result;
  1643. }
  1644. /**
  1645. * Inserts a table row with specified data.
  1646. *
  1647. * @param mixed $table The table to insert data into.
  1648. * @param array $data Column-value pairs or array of column-value pairs.
  1649. * @param array $fields update fields pairs or values
  1650. * @return int The number of affected rows.
  1651. * @throws Zend_Db_Exception
  1652. */
  1653. public function insertOnDuplicate($table, array $data, array $fields = array())
  1654. {
  1655. // extract and quote col names from the array keys
  1656. $row = reset($data); // get first element from data array
  1657. $bind = array(); // SQL bind array
  1658. $values = array();
  1659. if (is_array($row)) { // Array of column-value pairs
  1660. $cols = array_keys($row);
  1661. foreach ($data as $row) {
  1662. if (array_diff($cols, array_keys($row))) {
  1663. throw new Zend_Db_Exception('Invalid data for insert');
  1664. }
  1665. $values[] = $this->_prepareInsertData($row, $bind);
  1666. }
  1667. unset($row);
  1668. } else { // Column-value pairs
  1669. $cols = array_keys($data);
  1670. $values[] = $this->_prepareInsertData($data, $bind);
  1671. }
  1672. $updateFields = array();
  1673. if (empty($fields)) {
  1674. $fields = $cols;
  1675. }
  1676. // quote column names
  1677. // $cols = array_map(array($this, 'quoteIdentifier'), $cols);
  1678. // prepare ON DUPLICATE KEY conditions
  1679. foreach ($fields as $k => $v) {
  1680. $field = $value = null;
  1681. if (!is_numeric($k)) {
  1682. $field = $this->quoteIdentifier($k);
  1683. if ($v instanceof Zend_Db_Expr) {
  1684. $value = $v->__toString();
  1685. } elseif (is_string($v)) {
  1686. $value = sprintf('VALUES(%s)', $this->quoteIdentifier($v));
  1687. } elseif (is_numeric($v)) {
  1688. $value = $this->quoteInto('?', $v);
  1689. }
  1690. } elseif (is_string($v)) {
  1691. $value = sprintf('VALUES(%s)', $this->quoteIdentifier($v));
  1692. $field = $v;
  1693. }
  1694. if ($field && $value) {
  1695. $updateFields[] = sprintf('%s = %s', $field, $value);
  1696. }
  1697. }
  1698. $insertSql = $this->_getInsertSqlQuery($table, $cols, $values);
  1699. if ($updateFields) {
  1700. $insertSql .= ' ON DUPLICATE KEY UPDATE ' . implode(', ', $updateFields);
  1701. }
  1702. // execute the statement and return the number of affected rows
  1703. $stmt = $this->query($insertSql, array_values($bind));
  1704. $result = $stmt->rowCount();
  1705. return $result;
  1706. }
  1707. /**
  1708. * Inserts a table multiply rows with specified data.
  1709. *
  1710. * @param mixed $table The table to insert data into.
  1711. * @param array $data Column-value pairs or array of Column-value pairs.
  1712. * @return int The number of affected rows.
  1713. * @throws Zend_Db_Exception
  1714. */
  1715. public function insertMultiple($table, array $data)
  1716. {
  1717. $row = reset($data);
  1718. // support insert syntaxes
  1719. if (!is_array($row)) {
  1720. return $this->insert($table, $data);
  1721. }
  1722. // validate data array
  1723. $cols = array_keys($row);
  1724. $insertArray = array();
  1725. foreach ($data as $row) {
  1726. $line = array();
  1727. if (array_diff($cols, array_keys($row))) {
  1728. throw new Zend_Db_Exception('Invalid data for insert');
  1729. }
  1730. foreach ($cols as $field) {
  1731. $line[] = $row[$field];
  1732. }
  1733. $insertArray[] = $line;
  1734. }
  1735. unset($row);
  1736. return $this->insertArray($table, $cols, $insertArray);
  1737. }
  1738. /**
  1739. * Insert array to table based on columns definition
  1740. *
  1741. * @param string $table
  1742. * @param array $columns
  1743. * @param array $data
  1744. * @return int
  1745. * @throws Zend_Db_Exception
  1746. */
  1747. public function insertArray($table, array $columns, array $data)
  1748. {
  1749. $values = array();
  1750. $bind = array();
  1751. $columnsCount = count($columns);
  1752. foreach ($data as $row) {
  1753. if ($columnsCount != count($row)) {
  1754. throw new Zend_Db_Exception('Invalid data for insert');
  1755. }
  1756. $values[] = $this->_prepareInsertData($row, $bind);
  1757. }
  1758. $insertQuery = $this->_getInsertSqlQuery($table, $columns, $values);
  1759. // execute the statement and return the number of affected rows
  1760. $stmt = $this->query($insertQuery, $bind);
  1761. $result = $stmt->rowCount();
  1762. return $result;
  1763. }
  1764. /**
  1765. * Set cache adapter
  1766. *
  1767. * @param Zend_Cache_Backend_Interface $adapter
  1768. * @return Varien_Db_Adapter_Pdo_Mysql
  1769. */
  1770. public function setCacheAdapter($adapter)
  1771. {
  1772. $this->_cacheAdapter = $adapter;
  1773. return $this;
  1774. }
  1775. /**
  1776. * Return new DDL Table object
  1777. *
  1778. * @param string $tableName the table name
  1779. * @param string $schemaName the database/schema name
  1780. * @return Varien_Db_Ddl_Table
  1781. */
  1782. public function newTable($tableName = null, $schemaName = null)
  1783. {
  1784. $table = new Varien_Db_Ddl_Table();
  1785. if ($tableName !== null) {
  1786. $table->setName($tableName);
  1787. }
  1788. if ($schemaName !== null) {
  1789. $table->setSchema($schemaName);
  1790. }
  1791. return $table;
  1792. }
  1793. /**
  1794. * Create table
  1795. *
  1796. * @param Varien_Db_Ddl_Table $table
  1797. * @throws Zend_Db_Exception
  1798. * @return Zend_Db_Pdo_Statement
  1799. */
  1800. public function createTable(Varien_Db_Ddl_Table $table)
  1801. {
  1802. $columns = $table->getColumns();
  1803. foreach ($columns as $columnEntry) {
  1804. if (empty($columnEntry['COMMENT'])) {
  1805. throw new Zend_Db_Exception("Cannot create table without columns comments");
  1806. }
  1807. }
  1808. $sqlFragment = array_merge(
  1809. $this->_getColumnsDefinition($table),
  1810. $this->_getIndexesDefinition($table),
  1811. $this->_getForeignKeysDefinition($table)
  1812. );
  1813. $tableOptions = $this->_getOptionsDefinition($table);
  1814. $sql = sprintf("CREATE TABLE %s (\n%s\n) %s",
  1815. $this->quoteIdentifier($table->getName()),
  1816. implode(",\n", $sqlFragment),
  1817. implode(" ", $tableOptions));
  1818. return $this->query($sql);
  1819. }
  1820. /**
  1821. * Retrieve columns and primary keys definition array for create table
  1822. *
  1823. * @param Varien_Db_Ddl_Table $table
  1824. * @return array
  1825. * @throws Zend_Db_Exception
  1826. */
  1827. protected function _getColumnsDefinition(Varien_Db_Ddl_Table $table)
  1828. {
  1829. $definition = array();
  1830. $primary = array();
  1831. $columns = $table->getColumns();
  1832. if (empty($columns)) {
  1833. throw new Zend_Db_Exception('Table columns are not defined');
  1834. }
  1835. foreach ($columns as $columnData) {
  1836. $columnDefinition = $this->_getColumnDefinition($columnData);
  1837. if ($columnData['PRIMARY']) {
  1838. $primary[$columnData['COLUMN_NAME']] = $columnData['PRIMARY_POSITION'];
  1839. }
  1840. $definition[] = sprintf(' %s %s',
  1841. $this->quoteIdentifier($columnData['COLUMN_NAME']),
  1842. $columnDefinition
  1843. );
  1844. }
  1845. // PRIMARY KEY
  1846. if (!empty($primary)) {
  1847. asort($primary, SORT_NUMERIC);
  1848. $primary = array_map(array($this, 'quoteIdentifier'), array_keys($primary));
  1849. $definition[] = sprintf(' PRIMARY KEY (%s)', implode(', ', $primary));
  1850. }
  1851. return $definition;
  1852. }
  1853. /**
  1854. * Retrieve table indexes definition array for create table
  1855. *
  1856. * @param Varien_Db_Ddl_Table $table
  1857. * @return array
  1858. */
  1859. protected function _getIndexesDefinition(Varien_Db_Ddl_Table $table)
  1860. {
  1861. $definition = array();
  1862. $indexes = $table->getIndexes();
  1863. if (!empty($indexes)) {
  1864. foreach ($indexes as $indexData) {
  1865. if (!empty($indexData['TYPE'])) {
  1866. switch ($indexData['TYPE']) {
  1867. case 'primary':
  1868. $indexType = 'PRIMARY KEY';
  1869. unset($indexData['INDEX_NAME']);
  1870. break;
  1871. default:
  1872. $indexType = strtoupper($indexData['TYPE']);
  1873. break;
  1874. }
  1875. } else {
  1876. $indexType = 'KEY';
  1877. }
  1878. $columns = array();
  1879. foreach ($indexData['COLUMNS'] as $columnData) {
  1880. $column = $this->quoteIdentifier($columnData['NAME']);
  1881. if (!empty($columnData['SIZE'])) {
  1882. $column .= sprintf('(%d)', $columnData['SIZE']);
  1883. }
  1884. $columns[] = $column;
  1885. }
  1886. $indexName = isset($indexData['INDEX_NAME']) ? $this->quoteIdentifier($indexData['INDEX_NAME']) : '';
  1887. $definition[] = sprintf(' %s %s (%s)',
  1888. $indexType,
  1889. $indexName,
  1890. implode(', ', $columns)
  1891. );
  1892. }
  1893. }
  1894. return $definition;
  1895. }
  1896. /**
  1897. * Retrieve table foreign keys definition array for create table
  1898. *
  1899. * @param Varien_Db_Ddl_Table $table
  1900. * @return array
  1901. */
  1902. protected function _getForeignKeysDefinition(Varien_Db_Ddl_Table $table)
  1903. {
  1904. $definition = array();
  1905. $relations = $table->getForeignKeys();
  1906. if (!empty($relations)) {
  1907. foreach ($relations as $fkData) {
  1908. $onDelete = $this->_getDdlAction($fkData['ON_DELETE']);
  1909. $onUpdate = $this->_getDdlAction($fkData['ON_UPDATE']);
  1910. $definition[] = sprintf(' CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s) ON DELETE %s ON UPDATE %s',
  1911. $this->quoteIdentifier($fkData['FK_NAME']),
  1912. $this->quoteIdentifier($fkData['COLUMN_NAME']),
  1913. $this->quoteIdentifier($fkData['REF_TABLE_NAME']),
  1914. $this->quoteIdentifier($fkData['REF_COLUMN_NAME']),
  1915. $onDelete,
  1916. $onUpdate
  1917. );
  1918. }
  1919. }
  1920. return $definition;
  1921. }
  1922. /**
  1923. * Retrieve table options definition array for create table
  1924. *
  1925. * @param Varien_Db_Ddl_Table $table
  1926. * @return array
  1927. * @throws Zend_Db_Exception
  1928. */
  1929. protected function _getOptionsDefinition(Varien_Db_Ddl_Table $table)
  1930. {
  1931. $definition = array();
  1932. $comment = $table->getComment();
  1933. if (empty($comment)) {
  1934. throw new Zend_Db_Exception('Comment for table is required and must be defined');
  1935. }
  1936. $definition[] = $this->quoteInto('COMMENT=?', $comment);
  1937. $tableProps = array(
  1938. 'type' => 'ENGINE=%s',
  1939. 'checksum' => 'CHECKSUM=%d',
  1940. 'auto_increment' => 'AUTO_INCREMENT=%d',
  1941. 'avg_row_length' => 'AVG_ROW_LENGTH=%d',
  1942. 'max_rows' => 'MAX_ROWS=%d',
  1943. 'min_rows' => 'MIN_ROWS=%d',
  1944. 'delay_key_write' => 'DELAY_KEY_WRITE=%d',
  1945. 'row_format' => 'row_format=%s',
  1946. 'charset' => 'charset=%s',
  1947. 'collate' => 'COLLATE=%s'
  1948. );
  1949. foreach ($tableProps as $key => $mask) {
  1950. $v = $table->getOption($key);
  1951. if ($v !== null) {
  1952. $definition[] = sprintf($mask, $v);
  1953. }
  1954. }
  1955. return $definition;
  1956. }
  1957. /**
  1958. * Get column definition from description
  1959. *
  1960. * @param array $options
  1961. * @param null|string $ddlType
  1962. * @return string
  1963. */
  1964. public function getColumnDefinitionFromDescribe($options, $ddlType = null)
  1965. {
  1966. $columnInfo = $this->getColumnCreateByDescribe($options);
  1967. foreach ($columnInfo['options'] as $key => $value) {
  1968. $columnInfo[$key] = $value;
  1969. }
  1970. return $this->_getColumnDefinition($columnInfo, $ddlType);
  1971. }
  1972. /**
  1973. * Retrieve column definition fragment
  1974. *
  1975. * @param array $options
  1976. * @param string $ddlType Table DDL Column type constant
  1977. * @throws Varien_Exception
  1978. * @return string
  1979. * @throws Zend_Db_Exception
  1980. */
  1981. protected function _getColumnDefinition($options, $ddlType = null)
  1982. {
  1983. // convert keys to uppercase
  1984. $options = array_change_key_case($options, CASE_UPPER);
  1985. $cType = null;
  1986. $cUnsigned = false;
  1987. $cNullable = true;
  1988. $cDefault = false;
  1989. $cIdentity = false;
  1990. // detect and validate column type
  1991. if ($ddlType === null) {
  1992. $ddlType = $this->_getDdlType($options);
  1993. }
  1994. if (empty($ddlType) || !isset($this->_ddlColumnTypes[$ddlType])) {
  1995. throw new Zend_Db_Exception('Invalid column definition data');
  1996. }
  1997. // column size
  1998. $cType = $this->_ddlColumnTypes[$ddlType];
  1999. switch ($ddlType) {
  2000. case Varien_Db_Ddl_Table::TYPE_SMALLINT:
  2001. case Varien_Db_Ddl_Table::TYPE_INTEGER:
  2002. case Varien_Db_Ddl_Table::TYPE_BIGINT:
  2003. if (!empty($options['UNSIGNED'])) {
  2004. $cUnsigned = true;
  2005. }
  2006. break;
  2007. case Varien_Db_Ddl_Table::TYPE_DECIMAL:
  2008. case Varien_Db_Ddl_Table::TYPE_NUMERIC:
  2009. $precision = 10;
  2010. $scale = 0;
  2011. $match = array();
  2012. if (!empty($options['LENGTH']) && preg_match('#^\(?(\d+),(\d+)\)?$#', $options['LENGTH'], $match)) {
  2013. $precision = $match[1];
  2014. $scale = $match[2];
  2015. } else {
  2016. if (isset($options['SCALE']) && is_numeric($options['SCALE'])) {
  2017. $scale = $options['SCALE'];
  2018. }
  2019. if (isset($options['PRECISION']) && is_numeric($options['PRECISION'])) {
  2020. $precision = $options['PRECISION'];
  2021. }
  2022. }
  2023. $cType .= sprintf('(%d,%d)', $precision, $scale);
  2024. break;
  2025. case Varien_Db_Ddl_Table::TYPE_TEXT:
  2026. case Varien_Db_Ddl_Table::TYPE_BLOB:
  2027. case Varien_Db_Ddl_Table::TYPE_VARBINARY:
  2028. if (empty($options['LENGTH'])) {
  2029. $length = Varien_Db_Ddl_Table::DEFAULT_TEXT_SIZE;
  2030. } else {
  2031. $length = $this->_parseTextSize($options['LENGTH']);
  2032. }
  2033. if ($length <= 255) {
  2034. $cType = $ddlType == Varien_Db_Ddl_Table::TYPE_TEXT ? 'varchar' : 'varbinary';
  2035. $cType = sprintf('%s(%d)', $cType, $length);
  2036. } else if ($length > 255 && $length <= 65536) {
  2037. $cType = $ddlType == Varien_Db_Ddl_Table::TYPE_TEXT ? 'text' : 'blob';
  2038. } else if ($length > 65536 && $length <= 16777216) {
  2039. $cType = $ddlType == Varien_Db_Ddl_Table::TYPE_TEXT ? 'mediumtext' : 'mediumblob';
  2040. } else {
  2041. $cType = $ddlType == Varien_Db_Ddl_Table::TYPE_TEXT ? 'longtext' : 'longblob';
  2042. }
  2043. break;
  2044. }
  2045. if (array_key_exists('DEFAULT', $options)) {
  2046. $cDefault = $options['DEFAULT'];
  2047. }
  2048. if (array_key_exists('NULLABLE', $options)) {
  2049. $cNullable = (bool)$options['NULLABLE'];
  2050. }
  2051. if (!empty($options['IDENTITY']) || !empty($options['AUTO_INCREMENT'])) {
  2052. $cIdentity = true;
  2053. }
  2054. /* For cases when tables created from createTableByDdl()
  2055. * where default value can be quoted already.
  2056. * We need to avoid "double-quoting" here
  2057. */
  2058. if ( $cDefault !== null && strlen($cDefault)) {
  2059. $cDefault = str_replace("'", '', $cDefault);
  2060. }
  2061. // prepare default value string
  2062. if ($ddlType == Varien_Db_Ddl_Table::TYPE_TIMESTAMP) {
  2063. if ($cDefault === null) {
  2064. $cDefault = new Zend_Db_Expr('NULL');
  2065. } elseif ($cDefault == Varien_Db_Ddl_Table::TIMESTAMP_INIT) {
  2066. $cDefault = new Zend_Db_Expr('CURRENT_TIMESTAMP');
  2067. } else if ($cDefault == Varien_Db_Ddl_Table::TIMESTAMP_UPDATE) {
  2068. $cDefault = new Zend_Db_Expr('0 ON UPDATE CURRENT_TIMESTAMP');
  2069. } else if ($cDefault == Varien_Db_Ddl_Table::TIMESTAMP_INIT_UPDATE) {
  2070. $cDefault = new Zend_Db_Expr('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');
  2071. } else {
  2072. $cDefault = false;
  2073. }
  2074. } else if (is_null($cDefault) && $cNullable) {
  2075. $cDefault = new Zend_Db_Expr('NULL');
  2076. }
  2077. if (empty($options['COMMENT'])) {
  2078. $comment = '';
  2079. } else {
  2080. $comment = $options['COMMENT'];
  2081. }
  2082. return sprintf('%s%s%s%s%s COMMENT %s',
  2083. $cType,
  2084. $cUnsigned ? ' UNSIGNED' : '',
  2085. $cNullable ? ' NULL' : ' NOT NULL',
  2086. $cDefault !== false ? $this->quoteInto(' default ?', $cDefault) : '',
  2087. $cIdentity ? ' auto_increment' : '',
  2088. $this->quote($comment)
  2089. );
  2090. }
  2091. /**
  2092. * Drop table from database
  2093. *
  2094. * @param string $tableName
  2095. * @param string $schemaName
  2096. * @return boolean
  2097. */
  2098. public function dropTable($tableName, $schemaName = null)
  2099. {
  2100. $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
  2101. $query = 'DROP TABLE IF EXISTS ' . $table;
  2102. $this->query($query);
  2103. return true;
  2104. }
  2105. /**
  2106. * Truncate a table
  2107. *
  2108. * @param string $tableName
  2109. * @param string $schemaName
  2110. * @return Varien_Db_Adapter_Pdo_Mysql
  2111. * @throws Zend_Db_Exception
  2112. */
  2113. public function truncateTable($tableName, $schemaName = null)
  2114. {
  2115. if (!$this->isTableExists($tableName, $schemaName)) {
  2116. throw new Zend_Db_Exception(sprintf('Table "%s" is not exists', $tableName));
  2117. }
  2118. $table = $this->quoteIdentifier($this->_getTableName($tableName, $schemaName));
  2119. $query = 'TRUNCATE TABLE ' . $table;
  2120. $this->query($query);
  2121. return $this;
  2122. }
  2123. /**
  2124. * Check is a table exists
  2125. *
  2126. * @param string $tableName
  2127. * @param string $schemaName
  2128. * @return boolean
  2129. */
  2130. public function isTableExists($tableName, $schemaName = null)
  2131. {
  2132. return $this->showTableStatus($tableName, $schemaName) !== false;
  2133. }
  2134. /**
  2135. * Rename table
  2136. *
  2137. * @param string $oldTableName
  2138. * @param string $newTableName
  2139. * @param string $schemaName
  2140. * @return boolean
  2141. * @throws Zend_Db_Exception
  2142. */
  2143. public function renameTable($oldTableName, $newTableName, $schemaName = null)
  2144. {
  2145. if (!$this->isTableExists($oldTableName, $schemaName)) {
  2146. throw new Zend_Db_Exception(sprintf('Table "%s" is not exists', $oldTableName));
  2147. }
  2148. if ($this->isTableExists($newTableName, $schemaName)) {
  2149. throw new Zend_Db_Exception(sprintf('Table "%s" already exists', $newTableName));
  2150. }
  2151. $oldTable = $this->_getTableName($oldTableName, $schemaName);
  2152. $newTable = $this->_getTableName($newTableName, $schemaName);
  2153. $query = sprintf('ALTER TABLE %s RENAME TO %s', $oldTable, $newTable);
  2154. $this->query($query);
  2155. $this->resetDdlCache($oldTableName, $schemaName);
  2156. return true;
  2157. }
  2158. /**
  2159. * Add new index to table name
  2160. *
  2161. * @param string $tableName
  2162. * @param string $indexName
  2163. * @param string|array $fields the table column name or array of ones
  2164. * @param string $indexType the index type
  2165. * @param string $schemaName
  2166. * @return Zend_Db_Statement_Interface
  2167. * @throws Zend_Db_Exception|Exception
  2168. */
  2169. public function addIndex($tableName, $indexName, $fields,
  2170. $indexType = Varien_Db_Adapter_Interface::INDEX_TYPE_INDEX, $schemaName = null)
  2171. {
  2172. $columns = $this->describeTable($tableName, $schemaName);
  2173. $keyList = $this->getIndexList($tableName, $schemaName);
  2174. $query = sprintf('ALTER TABLE %s', $this->quoteIdentifier($this->_getTableName($tableName, $schemaName)));
  2175. if (isset($keyList[strtoupper($indexName)])) {
  2176. if ($keyList[strtoupper($indexName)]['INDEX_TYPE'] == Varien_Db_Adapter_Interface::INDEX_TYPE_PRIMARY) {
  2177. $query .= ' DROP PRIMARY KEY,';
  2178. } else {
  2179. $query .= sprintf(' DROP INDEX %s,', $this->quoteIdentifier($indexName));
  2180. }
  2181. }
  2182. if (!is_array($fields)) {
  2183. $fields = array($fields);
  2184. }
  2185. $fieldSql = array();
  2186. foreach ($fields as $field) {
  2187. if (!isset($columns[$field])) {
  2188. $msg = sprintf('There is no field "%s" that you are trying to create an index on "%s"',
  2189. $field, $tableName);
  2190. throw new Zend_Db_Exception($msg);
  2191. }
  2192. $fieldSql[] = $this->quoteIdentifier($field);
  2193. }
  2194. $fieldSql = implode(',', $fieldSql);
  2195. switch (strtolower($indexType)) {
  2196. case Varien_Db_Adapter_Interface::INDEX_TYPE_PRIMARY:
  2197. $condition = 'PRIMARY KEY';
  2198. break;
  2199. case Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE:
  2200. $condition = 'UNIQUE ' . $this->quoteIdentifier($indexName);
  2201. break;
  2202. case Varien_Db_Adapter_Interface::INDEX_TYPE_FULLTEXT:
  2203. $condition = 'FULLTEXT ' . $this->quoteIdentifier($indexName);
  2204. break;
  2205. default:
  2206. $condition = 'INDEX ' . $this->quoteIdentifier($indexName);
  2207. break;
  2208. }
  2209. $query .= sprintf(' ADD %s (%s)', $condition, $fieldSql);
  2210. $cycle = true;
  2211. while ($cycle === true) {
  2212. try {
  2213. $result = $this->raw_query($query);
  2214. $cycle = false;
  2215. } catch (Exception $e) {
  2216. if (in_array(strtolower($indexType), array('primary', 'unique'))) {
  2217. $match = array();
  2218. if (preg_match('#SQLSTATE\[23000\]: [^:]+: 1062[^\']+\'([\d-\.]+)\'#', $e->getMessage(), $match)) {
  2219. $ids = explode('-', $match[1]);
  2220. $this->_removeDuplicateEntry($tableName, $fields, $ids);
  2221. continue;
  2222. }
  2223. }
  2224. throw $e;
  2225. }
  2226. }
  2227. $this->resetDdlCache($tableName, $schemaName);
  2228. return $result;
  2229. }
  2230. /**
  2231. * Drop the index from table
  2232. *
  2233. * @param string $tableName
  2234. * @param string $keyName
  2235. * @param string $schemaName
  2236. * @return bool|Zend_Db_Statement_Interface
  2237. */
  2238. public function dropIndex($tableName, $keyName, $schemaName = null)
  2239. {
  2240. $indexList = $this->getIndexList($tableName, $schemaName);
  2241. $keyName = strtoupper($keyName);
  2242. if (!isset($indexList[$keyName])) {
  2243. return true;
  2244. }
  2245. if ($keyName == 'PRIMARY') {
  2246. $cond = 'DROP PRIMARY KEY';
  2247. } else {
  2248. $cond = 'DROP KEY ' . $this->quoteIdentifier($indexList[$keyName]['KEY_NAME']);
  2249. }
  2250. $sql = sprintf('ALTER TABLE %s %s',
  2251. $this->quoteIdentifier($this->_getTableName($tableName, $schemaName)),
  2252. $cond);
  2253. $this->resetDdlCache($tableName, $schemaName);
  2254. return $this->raw_query($sql);
  2255. }
  2256. /**
  2257. * Add new Foreign Key to table
  2258. * If Foreign Key with same name is exist - it will be deleted
  2259. *
  2260. * @param string $fkName
  2261. * @param string $tableName
  2262. * @param string $columnName
  2263. * @param string $refTableName
  2264. * @param string $refColumnName
  2265. * @param string $onDelete
  2266. * @param string $onUpdate
  2267. * @param boolean $purge trying remove invalid data
  2268. * @param string $schemaName
  2269. * @param string $refSchemaName
  2270. * @return Varien_Db_Adapter_Pdo_Mysql
  2271. */
  2272. public function addForeignKey($fkName, $tableName, $columnName, $refTableName, $refColumnName,
  2273. $onDelete = Varien_Db_Adapter_Interface::FK_ACTION_CASCADE,
  2274. $onUpdate = Varien_Db_Adapter_Interface::FK_ACTION_CASCADE,
  2275. $purge = false, $schemaName = null, $refSchemaName = null)
  2276. {
  2277. $this->dropForeignKey($tableName, $fkName, $schemaName);
  2278. if ($purge) {
  2279. $this->purgeOrphanRecords($tableName, $columnName, $refTableName, $refColumnName, $onDelete);
  2280. }
  2281. $query = sprintf('ALTER TABLE %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)',
  2282. $this->quoteIdentifier($this->_getTableName($tableName, $schemaName)),
  2283. $this->quoteIdentifier($fkName),
  2284. $this->quoteIdentifier($columnName),
  2285. $this->quoteIdentifier($this->_getTableName($refTableName, $refSchemaName)),
  2286. $this->quoteIdentifier($refColumnName)
  2287. );
  2288. if ($onDelete !== null) {
  2289. $query .= ' ON DELETE ' . strtoupper($onDelete);
  2290. }
  2291. if ($onUpdate !== null) {
  2292. $query .= ' ON UPDATE ' . strtoupper($onUpdate);
  2293. }
  2294. $result = $this->raw_query($query);
  2295. $this->resetDdlCache($tableName);
  2296. return $result;
  2297. }
  2298. /**
  2299. * Format Date to internal database date format
  2300. *
  2301. * @param int|string|Zend_Date $date
  2302. * @param boolean $includeTime
  2303. * @return Zend_Db_Expr
  2304. */
  2305. public function formatDate($date, $includeTime = true)
  2306. {
  2307. $date = Varien_Date::formatDate($date, $includeTime);
  2308. if ($date === null) {
  2309. return new Zend_Db_Expr('NULL');
  2310. }
  2311. return new Zend_Db_Expr($this->quote($date));
  2312. }
  2313. /**
  2314. * Run additional environment before setup
  2315. *
  2316. * @return Varien_Db_Adapter_Pdo_Mysql
  2317. */
  2318. public function startSetup()
  2319. {
  2320. $this->raw_query("SET SQL_MODE=''");
  2321. $this->raw_query("SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0");
  2322. $this->raw_query("SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO'");
  2323. return $this;
  2324. }
  2325. /**
  2326. * Run additional environment after setup
  2327. *
  2328. * @return Varien_Db_Adapter_Pdo_Mysql
  2329. */
  2330. public function endSetup()
  2331. {
  2332. $this->raw_query("SET SQL_MODE=IFNULL(@OLD_SQL_MODE,'')");
  2333. $this->raw_query("SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS=0, 0, 1)");
  2334. return $this;
  2335. }
  2336. /**
  2337. * Build SQL statement for condition
  2338. *
  2339. * If $condition integer or string - exact value will be filtered ('eq' condition)
  2340. *
  2341. * If $condition is array is - one of the following structures is expected:
  2342. * - array("from" => $fromValue, "to" => $toValue)
  2343. * - array("eq" => $equalValue)
  2344. * - array("neq" => $notEqualValue)
  2345. * - array("like" => $likeValue)
  2346. * - array("in" => array($inValues))
  2347. * - array("nin" => array($notInValues))
  2348. * - array("notnull" => $valueIsNotNull)
  2349. * - array("null" => $valueIsNull)
  2350. * - array("gt" => $greaterValue)
  2351. * - array("lt" => $lessValue)
  2352. * - array("gteq" => $greaterOrEqualValue)
  2353. * - array("lteq" => $lessOrEqualValue)
  2354. * - array("finset" => $valueInSet)
  2355. * - array("regexp" => $regularExpression)
  2356. * - array("seq" => $stringValue)
  2357. * - array("sneq" => $stringValue)
  2358. *
  2359. * If non matched - sequential array is expected and OR conditions
  2360. * will be built using above mentioned structure
  2361. *
  2362. * @param string|array $fieldName
  2363. * @param integer|string|array $condition
  2364. * @return string
  2365. */
  2366. public function prepareSqlCondition($fieldName, $condition)
  2367. {
  2368. $conditionKeyMap = array(
  2369. 'eq' => "{{fieldName}} = ?",
  2370. 'neq' => "{{fieldName}} != ?",
  2371. 'like' => "{{fieldName}} LIKE ?",
  2372. 'nlike' => "{{fieldName}} NOT LIKE ?",
  2373. 'in' => "{{fieldName}} IN(?)",
  2374. 'nin' => "{{fieldName}} NOT IN(?)",
  2375. 'is' => "{{fieldName}} IS ?",
  2376. 'notnull' => "{{fieldName}} IS NOT NULL",
  2377. 'null' => "{{fieldName}} IS NULL",
  2378. 'gt' => "{{fieldName}} > ?",
  2379. 'lt' => "{{fieldName}} < ?",
  2380. 'gteq' => "{{fieldName}} >= ?",
  2381. 'lteq' => "{{fieldName}} <= ?",
  2382. 'finset' => "FIND_IN_SET(?, {{fieldName}})",
  2383. 'regexp' => "{{fieldName}} REGEXP ?",
  2384. 'from' => "{{fieldName}} >= ?",
  2385. 'to' => "{{fieldName}} <= ?",
  2386. 'seq' => null,
  2387. 'sneq' => null
  2388. );
  2389. $query = '';
  2390. if (is_array($condition)) {
  2391. if (isset($condition['field_expr'])) {
  2392. $fieldName = str_replace('#?', $this->quoteIdentifier($fieldName), $condition['field_expr']);
  2393. unset($condition['field_expr']);
  2394. }
  2395. $key = key(array_intersect_key($condition, $conditionKeyMap));
  2396. if (isset($condition['from']) || isset($condition['to'])) {
  2397. if (isset($condition['from'])) {
  2398. $from = $this->_prepareSqlDateCondition($condition, 'from');
  2399. $query = $this->_prepareQuotedSqlCondition($conditionKeyMap['from'], $from, $fieldName);
  2400. }
  2401. if (isset($condition['to'])) {
  2402. $query .= empty($query) ? '' : ' AND ';
  2403. $to = $this->_prepareSqlDateCondition($condition, 'to');
  2404. $query = $this->_prepareQuotedSqlCondition($query . $conditionKeyMap['to'], $to, $fieldName);
  2405. }
  2406. } elseif (array_key_exists($key, $conditionKeyMap)) {
  2407. $value = $condition[$key];
  2408. if (($key == 'seq') || ($key == 'sneq')) {
  2409. $key = $this->_transformStringSqlCondition($key, $value);
  2410. }
  2411. $query = $this->_prepareQuotedSqlCondition($conditionKeyMap[$key], $value, $fieldName);
  2412. } else {
  2413. $queries = array();
  2414. foreach ($condition as $orCondition) {
  2415. $queries[] = sprintf('(%s)', $this->prepareSqlCondition($fieldName, $orCondition));
  2416. }
  2417. $query = sprintf('(%s)', implode(' OR ', $queries));
  2418. }
  2419. } else {
  2420. $query = $this->_prepareQuotedSqlCondition($conditionKeyMap['eq'], (string)$condition, $fieldName);
  2421. }
  2422. return $query;
  2423. }
  2424. /**
  2425. * Prepare Sql condition
  2426. *
  2427. * @param $text Condition value
  2428. * @param mixed $value
  2429. * @param string $fieldName
  2430. * @return string
  2431. */
  2432. protected function _prepareQuotedSqlCondition($text, $value, $fieldName)
  2433. {
  2434. $sql = $this->quoteInto($text, $value);
  2435. $sql = str_replace('{{fieldName}}', $fieldName, $sql);
  2436. return $sql;
  2437. }
  2438. /**
  2439. * Transforms sql condition key 'seq' / 'sneq' that is used for comparing string values to its analog:
  2440. * - 'null' / 'notnull' for empty strings
  2441. * - 'eq' / 'neq' for non-empty strings
  2442. *
  2443. * @param string $conditionKey
  2444. * @param mixed $value
  2445. * @return string
  2446. */
  2447. protected function _transformStringSqlCondition($conditionKey, $value)
  2448. {
  2449. $value = (string) $value;
  2450. if ($value == '') {
  2451. return ($conditionKey == 'seq') ? 'null' : 'notnull';
  2452. } else {
  2453. return ($conditionKey == 'seq') ? 'eq' : 'neq';
  2454. }
  2455. }
  2456. /**
  2457. * Prepare value for save in column
  2458. * Return converted to column data type value
  2459. *
  2460. * @param array $column the column describe array
  2461. * @param mixed $value
  2462. * @return mixed
  2463. */
  2464. public function prepareColumnValue(array $column, $value)
  2465. {
  2466. if ($value instanceof Zend_Db_Expr) {
  2467. return $value;
  2468. }
  2469. if ($value instanceof Varien_Db_Statement_Parameter) {
  2470. return $value;
  2471. }
  2472. // return original value if invalid column describe data
  2473. if (!isset($column['DATA_TYPE'])) {
  2474. return $value;
  2475. }
  2476. // return null
  2477. if (is_null($value) && $column['NULLABLE']) {
  2478. return null;
  2479. }
  2480. switch ($column['DATA_TYPE']) {
  2481. case 'smallint':
  2482. case 'int':
  2483. case 'bigint':
  2484. $value = (int)$value;
  2485. break;
  2486. case 'decimal':
  2487. $precision = 10;
  2488. $scale = 0;
  2489. if (isset($column['SCALE'])) {
  2490. $scale = $column['SCALE'];
  2491. }
  2492. if (isset($column['PRECISION'])) {
  2493. $precision = $column['PRECISION'];
  2494. }
  2495. $format = sprintf('%%%d.%dF', $precision - $scale, $scale);
  2496. $value = (float)sprintf($format, $value);
  2497. break;
  2498. case 'float':
  2499. $value = (float)sprintf('%F', $value);
  2500. break;
  2501. case 'date':
  2502. $value = $this->formatDate($value, false);
  2503. break;
  2504. case 'datetime':
  2505. case 'timestamp':
  2506. $value = $this->formatDate($value);
  2507. break;
  2508. case 'varchar':
  2509. case 'mediumtext':
  2510. case 'text':
  2511. case 'longtext':
  2512. $value = (string)$value;
  2513. if ($column['NULLABLE'] && $value == '') {
  2514. $value = null;
  2515. }
  2516. break;
  2517. case 'varbinary':
  2518. case 'mediumblob':
  2519. case 'blob':
  2520. case 'longblob':
  2521. // No special processing for MySQL is needed
  2522. break;
  2523. }
  2524. return $value;
  2525. }
  2526. /**
  2527. * Generate fragment of SQL, that check condition and return true or false value
  2528. *
  2529. * @param Zend_Db_Expr|Zend_Db_Select|string $expression
  2530. * @param string $true true value
  2531. * @param string $false false value
  2532. */
  2533. public function getCheckSql($expression, $true, $false)
  2534. {
  2535. if ($expression instanceof Zend_Db_Expr || $expression instanceof Zend_Db_Select) {
  2536. $expression = sprintf("IF((%s), %s, %s)", $expression, $true, $false);
  2537. } else {
  2538. $expression = sprintf("IF(%s, %s, %s)", $expression, $true, $false);
  2539. }
  2540. return new Zend_Db_Expr($expression);
  2541. }
  2542. /**
  2543. * Returns valid IFNULL expression
  2544. *
  2545. * @param Zend_Db_Expr|Zend_Db_Select|string $expression
  2546. * @param string $value OPTIONAL. Applies when $expression is NULL
  2547. * @return Zend_Db_Expr
  2548. */
  2549. public function getIfNullSql($expression, $value = 0)
  2550. {
  2551. if ($expression instanceof Zend_Db_Expr || $expression instanceof Zend_Db_Select) {
  2552. $expression = sprintf("IFNULL((%s), %s)", $expression, $value);
  2553. } else {
  2554. $expression = sprintf("IFNULL(%s, %s)", $expression, $value);
  2555. }
  2556. return new Zend_Db_Expr($expression);
  2557. }
  2558. /**
  2559. * Generate fragment of SQL, that check value against multiple condition cases
  2560. * and return different result depends on them
  2561. *
  2562. * @param string $valueName Name of value to check
  2563. * @param array $casesResults Cases and results
  2564. * @param string $defaultValue value to use if value doesn't confirm to any cases
  2565. */
  2566. public function getCaseSql($valueName, $casesResults, $defaultValue = null)
  2567. {
  2568. $expression = 'CASE ' . $valueName;
  2569. foreach ($casesResults as $case => $result) {
  2570. $expression .= ' WHEN ' . $case . ' THEN ' . $result;
  2571. }
  2572. if ($defaultValue !== null) {
  2573. $expression .= ' ELSE ' . $defaultValue;
  2574. }
  2575. $expression .= ' END';
  2576. return new Zend_Db_Expr($expression);
  2577. }
  2578. /**
  2579. * Generate fragment of SQL, that combine together (concatenate) the results from data array
  2580. * All arguments in data must be quoted
  2581. *
  2582. * @param array $data
  2583. * @param string $separator concatenate with separator
  2584. * @return Zend_Db_Expr
  2585. */
  2586. public function getConcatSql(array $data, $separator = null)
  2587. {
  2588. $format = empty($separator) ? 'CONCAT(%s)' : "CONCAT_WS('{$separator}', %s)";
  2589. return new Zend_Db_Expr(sprintf($format, implode(', ', $data)));
  2590. }
  2591. /**
  2592. * Generate fragment of SQL that returns length of character string
  2593. * The string argument must be quoted
  2594. *
  2595. * @param string $string
  2596. * @return Zend_Db_Expr
  2597. */
  2598. public function getLengthSql($string)
  2599. {
  2600. return new Zend_Db_Expr(sprintf('LENGTH(%s)', $string));
  2601. }
  2602. /**
  2603. * Generate fragment of SQL, that compare with two or more arguments, and returns the smallest
  2604. * (minimum-valued) argument
  2605. * All arguments in data must be quoted
  2606. *
  2607. * @param array $data
  2608. * @return Zend_Db_Expr
  2609. */
  2610. public function getLeastSql(array $data)
  2611. {
  2612. return new Zend_Db_Expr(sprintf('LEAST(%s)', implode(', ', $data)));
  2613. }
  2614. /**
  2615. * Generate fragment of SQL, that compare with two or more arguments, and returns the largest
  2616. * (maximum-valued) argument
  2617. * All arguments in data must be quoted
  2618. *
  2619. * @param array $data
  2620. * @return Zend_Db_Expr
  2621. */
  2622. public function getGreatestSql(array $data)
  2623. {
  2624. return new Zend_Db_Expr(sprintf('GREATEST(%s)', implode(', ', $data)));
  2625. }
  2626. /**
  2627. * Get Interval Unit SQL fragment
  2628. *
  2629. * @param int $interval
  2630. * @param string $unit
  2631. * @return string
  2632. * @throws Zend_Db_Exception
  2633. */
  2634. protected function _getIntervalUnitSql($interval, $unit)
  2635. {
  2636. if (!isset($this->_intervalUnits[$unit])) {
  2637. throw new Zend_Db_Exception(sprintf('Undefined interval unit "%s" specified', $unit));
  2638. }
  2639. return sprintf('INTERVAL %d %s', $interval, $this->_intervalUnits[$unit]);
  2640. }
  2641. /**
  2642. * Add time values (intervals) to a date value
  2643. *
  2644. * @see INTERVAL_* constants for $unit
  2645. *
  2646. * @param Zend_Db_Expr|string $date quoted field name or SQL statement
  2647. * @param int $interval
  2648. * @param string $unit
  2649. * @return Zend_Db_Expr
  2650. */
  2651. public function getDateAddSql($date, $interval, $unit)
  2652. {
  2653. $expr = sprintf('DATE_ADD(%s, %s)', $date, $this->_getIntervalUnitSql($interval, $unit));
  2654. return new Zend_Db_Expr($expr);
  2655. }
  2656. /**
  2657. * Subtract time values (intervals) to a date value
  2658. *
  2659. * @see INTERVAL_* constants for $expr
  2660. *
  2661. * @param Zend_Db_Expr|string $date quoted field name or SQL statement
  2662. * @param int|string $interval
  2663. * @param string $unit
  2664. * @return Zend_Db_Expr
  2665. */
  2666. public function getDateSubSql($date, $interval, $unit)
  2667. {
  2668. $expr = sprintf('DATE_SUB(%s, %s)', $date, $this->_getIntervalUnitSql($interval, $unit));
  2669. return new Zend_Db_Expr($expr);
  2670. }
  2671. /**
  2672. * Format date as specified
  2673. *
  2674. * Supported format Specifier
  2675. *
  2676. * %H Hour (00..23)
  2677. * %i Minutes, numeric (00..59)
  2678. * %s Seconds (00..59)
  2679. * %d Day of the month, numeric (00..31)
  2680. * %m Month, numeric (00..12)
  2681. * %Y Year, numeric, four digits
  2682. *
  2683. * @param string $date quoted date value or non quoted SQL statement(field)
  2684. * @param string $format
  2685. * @return Zend_Db_Expr
  2686. */
  2687. public function getDateFormatSql($date, $format)
  2688. {
  2689. $expr = sprintf("DATE_FORMAT(%s, '%s')", $date, $format);
  2690. return new Zend_Db_Expr($expr);
  2691. }
  2692. /**
  2693. * Extract the date part of a date or datetime expression
  2694. *
  2695. * @param Zend_Db_Expr|string $date quoted field name or SQL statement
  2696. * @return Zend_Db_Expr
  2697. */
  2698. public function getDatePartSql($date)
  2699. {
  2700. return new Zend_Db_Expr(sprintf('DATE(%s)', $date));
  2701. }
  2702. /**
  2703. * Extract part of a date
  2704. *
  2705. * @see INTERVAL_* constants for $unit
  2706. *
  2707. * @param Zend_Db_Expr|string $date quoted field name or SQL statement
  2708. * @param string $unit
  2709. * @return Zend_Db_Expr
  2710. * @throws Zend_Db_Exception
  2711. */
  2712. public function getDateExtractSql($date, $unit)
  2713. {
  2714. if (!isset($this->_intervalUnits[$unit])) {
  2715. throw new Zend_Db_Exception(sprintf('Undefined interval unit "%s" specified', $unit));
  2716. }
  2717. $expr = sprintf('EXTRACT(%s FROM %s)', $this->_intervalUnits[$unit], $date);
  2718. return new Zend_Db_Expr($expr);
  2719. }
  2720. /**
  2721. * Minus superfluous characters from hash.
  2722. *
  2723. * @param $hash
  2724. * @param $prefix
  2725. * @param $maxCharacters
  2726. * @return string
  2727. */
  2728. protected function _minusSuperfluous($hash, $prefix, $maxCharacters)
  2729. {
  2730. $diff = strlen($hash) + strlen($prefix) - $maxCharacters;
  2731. $superfluous = $diff / 2;
  2732. $odd = $diff % 2;
  2733. $hash = substr($hash, $superfluous, - ($superfluous + $odd));
  2734. return $hash;
  2735. }
  2736. /**
  2737. * Retrieve valid table name
  2738. * Check table name length and allowed symbols
  2739. *
  2740. * @param string $tableName
  2741. * @return string
  2742. */
  2743. public function getTableName($tableName)
  2744. {
  2745. $prefix = 't_';
  2746. if (strlen($tableName) > self::LENGTH_TABLE_NAME) {
  2747. $shortName = Varien_Db_Helper::shortName($tableName);
  2748. if (strlen($shortName) > self::LENGTH_TABLE_NAME) {
  2749. $hash = md5($tableName);
  2750. if (strlen($prefix.$hash) > self::LENGTH_TABLE_NAME) {
  2751. $tableName = $this->_minusSuperfluous($hash, $prefix, self::LENGTH_TABLE_NAME);
  2752. } else {
  2753. $tableName = $prefix . $hash;
  2754. }
  2755. } else {
  2756. $tableName = $shortName;
  2757. }
  2758. }
  2759. return $tableName;
  2760. }
  2761. /**
  2762. * Retrieve valid index name
  2763. * Check index name length and allowed symbols
  2764. *
  2765. * @param string $tableName
  2766. * @param string|array $fields the columns list
  2767. * @param string $indexType
  2768. * @return string
  2769. */
  2770. public function getIndexName($tableName, $fields, $indexType = '')
  2771. {
  2772. if (is_array($fields)) {
  2773. $fields = implode('_', $fields);
  2774. }
  2775. switch (strtolower($indexType)) {
  2776. case Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE:
  2777. $prefix = 'unq_';
  2778. $shortPrefix = 'u_';
  2779. break;
  2780. case Varien_Db_Adapter_Interface::INDEX_TYPE_FULLTEXT:
  2781. $prefix = 'fti_';
  2782. $shortPrefix = 'f_';
  2783. break;
  2784. case Varien_Db_Adapter_Interface::INDEX_TYPE_INDEX:
  2785. default:
  2786. $prefix = 'idx_';
  2787. $shortPrefix = 'i_';
  2788. }
  2789. $hash = $tableName . '_' . $fields;
  2790. if (strlen($hash) + strlen($prefix) > self::LENGTH_INDEX_NAME) {
  2791. $short = Varien_Db_Helper::shortName($prefix . $hash);
  2792. if (strlen($short) > self::LENGTH_INDEX_NAME) {
  2793. $hash = md5($hash);
  2794. if (strlen($hash) + strlen($shortPrefix) > self::LENGTH_INDEX_NAME) {
  2795. $hash = $this->_minusSuperfluous($hash, $shortPrefix, self::LENGTH_INDEX_NAME);
  2796. }
  2797. } else {
  2798. $hash = $short;
  2799. }
  2800. } else {
  2801. $hash = $prefix . $hash;
  2802. }
  2803. return strtoupper($hash);
  2804. }
  2805. /**
  2806. * Retrieve valid foreign key name
  2807. * Check foreign key name length and allowed symbols
  2808. *
  2809. * @param string $priTableName
  2810. * @param string $priColumnName
  2811. * @param string $refTableName
  2812. * @param string $refColumnName
  2813. * @return string
  2814. */
  2815. public function getForeignKeyName($priTableName, $priColumnName, $refTableName, $refColumnName)
  2816. {
  2817. $prefix = 'fk_';
  2818. $hash = sprintf('%s_%s_%s_%s', $priTableName, $priColumnName, $refTableName, $refColumnName);
  2819. if (strlen($prefix.$hash) > self::LENGTH_FOREIGN_NAME) {
  2820. $short = Varien_Db_Helper::shortName($prefix.$hash);
  2821. if (strlen($short) > self::LENGTH_FOREIGN_NAME) {
  2822. $hash = md5($hash);
  2823. if (strlen($prefix.$hash) > self::LENGTH_FOREIGN_NAME) {
  2824. $hash = $this->_minusSuperfluous($hash, $prefix, self::LENGTH_FOREIGN_NAME);
  2825. } else {
  2826. $hash = $prefix . $hash;
  2827. }
  2828. } else {
  2829. $hash = $short;
  2830. }
  2831. } else {
  2832. $hash = $prefix . $hash;
  2833. }
  2834. return strtoupper($hash);
  2835. }
  2836. /**
  2837. * Stop updating indexes
  2838. *
  2839. * @param string $tableName
  2840. * @param string $schemaName
  2841. * @return Varien_Db_Adapter_Pdo_Mysql
  2842. */
  2843. public function disableTableKeys($tableName, $schemaName = null)
  2844. {
  2845. $tableName = $this->_getTableName($tableName, $schemaName);
  2846. $query = sprintf('ALTER TABLE %s DISABLE KEYS', $this->quoteIdentifier($tableName));
  2847. $this->query($query);
  2848. return $this;
  2849. }
  2850. /**
  2851. * Re-create missing indexes
  2852. *
  2853. * @param string $tableName
  2854. * @param string $schemaName
  2855. * @return Varien_Db_Adapter_Pdo_Mysql
  2856. */
  2857. public function enableTableKeys($tableName, $schemaName = null)
  2858. {
  2859. $tableName = $this->_getTableName($tableName, $schemaName);
  2860. $query = sprintf('ALTER TABLE %s ENABLE KEYS', $this->quoteIdentifier($tableName));
  2861. $this->query($query);
  2862. return $this;
  2863. }
  2864. /**
  2865. * Get insert from Select object query
  2866. *
  2867. * @param Varien_Db_Select $select
  2868. * @param string $table insert into table
  2869. * @param array $fields
  2870. * @param int $mode
  2871. * @return string
  2872. */
  2873. public function insertFromSelect(Varien_Db_Select $select, $table, array $fields = array(), $mode = false)
  2874. {
  2875. $query = 'INSERT';
  2876. if ($mode == self::INSERT_IGNORE) {
  2877. $query .= ' IGNORE';
  2878. }
  2879. $query = sprintf('%s INTO %s', $query, $this->quoteIdentifier($table));
  2880. if ($fields) {
  2881. $columns = array_map(array($this, 'quoteIdentifier'), $fields);
  2882. $query = sprintf('%s (%s)', $query, join(', ', $columns));
  2883. }
  2884. $query = sprintf('%s %s', $query, $select->assemble());
  2885. if ($mode == self::INSERT_ON_DUPLICATE) {
  2886. if (!$fields) {
  2887. $describe = $this->describeTable($table);
  2888. foreach ($describe as $column) {
  2889. if ($column['PRIMARY'] === false) {
  2890. $fields[] = $column['COLUMN_NAME'];
  2891. }
  2892. }
  2893. }
  2894. $update = array();
  2895. foreach ($fields as $field) {
  2896. $update[] = sprintf('%1$s = VALUES(%1$s)', $this->quoteIdentifier($field));
  2897. }
  2898. if ($update) {
  2899. $query = sprintf('%s ON DUPLICATE KEY UPDATE %s', $query, join(', ', $update));
  2900. }
  2901. }
  2902. return $query;
  2903. }
  2904. /**
  2905. * Get update table query using select object for join and update
  2906. *
  2907. * @param Varien_Db_Select $select
  2908. * @param string|array $table
  2909. * @return string
  2910. */
  2911. public function updateFromSelect(Varien_Db_Select $select, $table)
  2912. {
  2913. if (!is_array($table)) {
  2914. $table = array($table => $table);
  2915. }
  2916. // get table name and alias
  2917. $keys = array_keys($table);
  2918. $tableAlias = $keys[0];
  2919. $tableName = $table[$keys[0]];
  2920. $query = sprintf('UPDATE %s', $this->quoteTableAs($tableName, $tableAlias));
  2921. // render JOIN conditions (FROM Part)
  2922. $joinConds = array();
  2923. foreach ($select->getPart(Zend_Db_Select::FROM) as $correlationName => $joinProp) {
  2924. if ($joinProp['joinType'] == Zend_Db_Select::FROM) {
  2925. $joinType = strtoupper(Zend_Db_Select::INNER_JOIN);
  2926. } else {
  2927. $joinType = strtoupper($joinProp['joinType']);
  2928. }
  2929. $joinTable = '';
  2930. if ($joinProp['schema'] !== null) {
  2931. $joinTable = sprintf('%s.', $this->quoteIdentifier($joinProp['schema']));
  2932. }
  2933. $joinTable .= $this->quoteTableAs($joinProp['tableName'], $correlationName);
  2934. $join = sprintf(' %s %s', $joinType, $joinTable);
  2935. if (!empty($joinProp['joinCondition'])) {
  2936. $join = sprintf('%s ON %s', $join, $joinProp['joinCondition']);
  2937. }
  2938. $joinConds[] = $join;
  2939. }
  2940. if ($joinConds) {
  2941. $query = sprintf("%s\n%s", $query, implode("\n", $joinConds));
  2942. }
  2943. // render UPDATE SET
  2944. $columns = array();
  2945. foreach ($select->getPart(Zend_Db_Select::COLUMNS) as $columnEntry) {
  2946. list($correlationName, $column, $alias) = $columnEntry;
  2947. if (empty($alias)) {
  2948. $alias = $column;
  2949. }
  2950. if (!$column instanceof Zend_Db_Expr && !empty($correlationName)) {
  2951. $column = $this->quoteIdentifier(array($correlationName, $column));
  2952. }
  2953. $columns[] = sprintf('%s = %s', $this->quoteIdentifier(array($tableAlias, $alias)), $column);
  2954. }
  2955. if (!$columns) {
  2956. throw new Varien_Db_Exception('The columns for UPDATE statement are not defined');
  2957. }
  2958. $query = sprintf("%s\nSET %s", $query, implode(', ', $columns));
  2959. // render WHERE
  2960. $wherePart = $select->getPart(Zend_Db_Select::WHERE);
  2961. if ($wherePart) {
  2962. $query = sprintf("%s\nWHERE %s", $query, implode(' ', $wherePart));
  2963. }
  2964. return $query;
  2965. }
  2966. /**
  2967. * Get delete from select object query
  2968. *
  2969. * @param Varien_Db_Select $select
  2970. * @param string $table the table name or alias used in select
  2971. * @return string|int
  2972. */
  2973. public function deleteFromSelect(Varien_Db_Select $select, $table)
  2974. {
  2975. $select = clone $select;
  2976. $select->reset(Zend_Db_Select::DISTINCT);
  2977. $select->reset(Zend_Db_Select::COLUMNS);
  2978. $query = sprintf('DELETE %s %s', $this->quoteIdentifier($table), $select->assemble());
  2979. return $query;
  2980. }
  2981. /**
  2982. * Calculate checksum for table or for group of tables
  2983. *
  2984. * @param array|string $tableNames array of tables names | table name
  2985. * @param string $schemaName schema name
  2986. * @return arrray
  2987. */
  2988. public function getTablesChecksum($tableNames, $schemaName = null)
  2989. {
  2990. $result = array();
  2991. $tableNames = is_array($tableNames) ? $tableNames : array($tableNames);
  2992. foreach ($tableNames as $tableName) {
  2993. $query = 'CHECKSUM TABLE ' . $this->_getTableName($tableName, $schemaName);
  2994. $checkSumArray = $this->fetchRow($query);
  2995. $result[$tableName] = $checkSumArray['Checksum'];
  2996. }
  2997. return $result;
  2998. }
  2999. /**
  3000. * Check if the database support STRAIGHT JOIN
  3001. *
  3002. * @return boolean
  3003. */
  3004. public function supportStraightJoin()
  3005. {
  3006. return true;
  3007. }
  3008. /**
  3009. * Adds order by random to select object
  3010. * Possible using integer field for optimization
  3011. *
  3012. * @param Varien_Db_Select $select
  3013. * @param string $field
  3014. * @return Varien_Db_Adapter_Pdo_Mysql
  3015. */
  3016. public function orderRand(Varien_Db_Select $select, $field = null)
  3017. {
  3018. if ($field !== null) {
  3019. $expression = new Zend_Db_Expr(sprintf('RAND() * %s', $this->quoteIdentifier($field)));
  3020. $select->columns(array('mage_rand' => $expression));
  3021. $spec = new Zend_Db_Expr('mage_rand');
  3022. } else {
  3023. $spec = new Zend_Db_Expr('RAND()');
  3024. }
  3025. $select->order($spec);
  3026. return $this;
  3027. }
  3028. /**
  3029. * Render SQL FOR UPDATE clause
  3030. *
  3031. * @param string $sql
  3032. * @return string
  3033. */
  3034. public function forUpdate($sql)
  3035. {
  3036. return sprintf('%s FOR UPDATE', $sql);
  3037. }
  3038. /**
  3039. * Prepare insert data
  3040. *
  3041. * @param mixed $row
  3042. * @param array $bind
  3043. * @return string
  3044. */
  3045. protected function _prepareInsertData($row, &$bind)
  3046. {
  3047. if (is_array($row)) {
  3048. $line = array();
  3049. foreach ($row as $value) {
  3050. if ($value instanceof Zend_Db_Expr) {
  3051. $line[] = $value->__toString();
  3052. } else {
  3053. $line[] = '?';
  3054. $bind[] = $value;
  3055. }
  3056. }
  3057. $line = implode(', ', $line);
  3058. } elseif ($row instanceof Zend_Db_Expr) {
  3059. $line = $row->__toString();
  3060. } else {
  3061. $line = '?';
  3062. $bind[] = $row;
  3063. }
  3064. return sprintf('(%s)', $line);
  3065. }
  3066. /**
  3067. * Return insert sql query
  3068. *
  3069. * @param string $tableName
  3070. * @param array $columns
  3071. * @param array $values
  3072. * @return string
  3073. */
  3074. protected function _getInsertSqlQuery($tableName, array $columns, array $values)
  3075. {
  3076. $tableName = $this->quoteIdentifier($tableName, true);
  3077. $columns = array_map(array($this, 'quoteIdentifier'), $columns);
  3078. $columns = implode(',', $columns);
  3079. $values = implode(', ', $values);
  3080. $insertSql = sprintf('INSERT INTO %s (%s) VALUES %s', $tableName, $columns, $values);
  3081. return $insertSql;
  3082. }
  3083. /**
  3084. * Return ddl type
  3085. *
  3086. * @param array $options
  3087. * @return string
  3088. */
  3089. protected function _getDdlType($options)
  3090. {
  3091. $ddlType = null;
  3092. if (isset($options['TYPE'])) {
  3093. $ddlType = $options['TYPE'];
  3094. } elseif (isset($options['COLUMN_TYPE'])) {
  3095. $ddlType = $options['COLUMN_TYPE'];
  3096. }
  3097. return $ddlType;
  3098. }
  3099. /**
  3100. * Return DDL action
  3101. *
  3102. * @param string $action
  3103. * @return string
  3104. */
  3105. protected function _getDdlAction($action)
  3106. {
  3107. switch ($action) {
  3108. case Varien_Db_Adapter_Interface::FK_ACTION_CASCADE:
  3109. return Varien_Db_Ddl_Table::ACTION_CASCADE;
  3110. case Varien_Db_Adapter_Interface::FK_ACTION_SET_NULL:
  3111. return Varien_Db_Ddl_Table::ACTION_SET_NULL;
  3112. case Varien_Db_Adapter_Interface::FK_ACTION_RESTRICT:
  3113. return Varien_Db_Ddl_Table::ACTION_RESTRICT;
  3114. default:
  3115. return Varien_Db_Ddl_Table::ACTION_NO_ACTION;
  3116. }
  3117. }
  3118. /**
  3119. * Prepare sql date condition
  3120. *
  3121. * @param array $condition
  3122. * @param string $key
  3123. * @return string
  3124. */
  3125. protected function _prepareSqlDateCondition($condition, $key)
  3126. {
  3127. if (empty($condition['date'])) {
  3128. if (empty($condition['datetime'])) {
  3129. $result = $condition[$key];
  3130. } else {
  3131. $result = $this->formatDate($condition[$key]);
  3132. }
  3133. } else {
  3134. $result = $this->formatDate($condition[$key]);
  3135. }
  3136. return $result;
  3137. }
  3138. /**
  3139. * Try to find installed primary key name, if not - formate new one.
  3140. *
  3141. * @param string $tableName Table name
  3142. * @param string $schemaName OPTIONAL
  3143. * @return string Primary Key name
  3144. */
  3145. public function getPrimaryKeyName($tableName, $schemaName = null)
  3146. {
  3147. $indexes = $this->getIndexList($tableName, $schemaName);
  3148. if (isset($indexes['PRIMARY'])) {
  3149. return $indexes['PRIMARY']['KEY_NAME'];
  3150. } else {
  3151. return 'PK_' . strtoupper($tableName);
  3152. }
  3153. }
  3154. /**
  3155. * Parse text size
  3156. * Returns max allowed size if value great it
  3157. *
  3158. * @param string|int $size
  3159. * @return int
  3160. */
  3161. protected function _parseTextSize($size)
  3162. {
  3163. $size = trim($size);
  3164. $last = strtolower(substr($size, -1));
  3165. switch ($last) {
  3166. case 'k':
  3167. $size = intval($size) * 1024;
  3168. break;
  3169. case 'm':
  3170. $size = intval($size) * 1024 * 1024;
  3171. break;
  3172. case 'g':
  3173. $size = intval($size) * 1024 * 1024 * 1024;
  3174. break;
  3175. }
  3176. if (empty($size)) {
  3177. return Varien_Db_Ddl_Table::DEFAULT_TEXT_SIZE;
  3178. }
  3179. if ($size >= Varien_Db_Ddl_Table::MAX_TEXT_SIZE) {
  3180. return Varien_Db_Ddl_Table::MAX_TEXT_SIZE;
  3181. }
  3182. return intval($size);
  3183. }
  3184. /**
  3185. * Converts fetched blob into raw binary PHP data.
  3186. * The MySQL drivers do it nice, no processing required.
  3187. *
  3188. * @mixed $value
  3189. * @return mixed
  3190. */
  3191. public function decodeVarbinary($value)
  3192. {
  3193. return $value;
  3194. }
  3195. /**
  3196. * Returns date that fits into TYPE_DATETIME range and is suggested to act as default 'zero' value
  3197. * for a column for current RDBMS. Deprecated and left for compatibility only.
  3198. * In Magento at MySQL there was zero date used for datetime columns. However, zero date it is not supported across
  3199. * different RDBMS. Thus now it is recommended to use same default value equal for all RDBMS - either NULL
  3200. * or specific date supported by all RDBMS.
  3201. *
  3202. * @deprecated after 1.5.1.0
  3203. * @return string
  3204. */
  3205. public function getSuggestedZeroDate()
  3206. {
  3207. return '0000-00-00 00:00:00';
  3208. }
  3209. /**
  3210. * Retrieve Foreign Key name
  3211. *
  3212. * @deprecated after 1.6.0.0
  3213. *
  3214. * @param string $fkName
  3215. * @return string
  3216. */
  3217. protected function _getForeignKeyName($fkName)
  3218. {
  3219. if (substr($fkName, 0, 3) != 'FK_') {
  3220. $fkName = 'FK_' . $fkName;
  3221. }
  3222. return $fkName;
  3223. }
  3224. }