Beispiel #1
0
 public function testRebuildInvokesDdlOperationsIfTheyAreAllowed()
 {
     $model = $this->_getModelMock(array('_createTable', '_getWriteAdapter', '_populateFlatTables'));
     // Pretend that no transactions have been started
     $this->_dbAdapterMock->expects($this->any())->method('getTransactionLevel')->will($this->returnValue(0));
     $model->expects($this->any())->method('_getWriteAdapter')->will($this->returnValue($this->_dbAdapterMock));
     $model->expects($this->atLeastOnce())->method('_createTable');
     $store = $this->getMock('Mage_Core_Model_Store', array(), array(), '', false);
     $store->expects($this->any())->method('getId')->will($this->returnValue(1));
     $model->rebuild(array($store));
 }
 private function clearRemovedFilters($currentFilters, $receivedFilters)
 {
     $calculatedFiltersIds = $this->getFiltersForDeleting($currentFilters, $receivedFilters);
     if (count($calculatedFiltersIds) <= 0) {
         return;
     }
     $this->connectionWrite->delete($this->tableName, '`id` IN (' . implode(',', $calculatedFiltersIds) . ')');
 }
 /**
  * Run the jobs that are in the queue
  *
  * @param mixed  $limit Limit of jobs to run
  * @return  int  Number of jobs run
  */
 public function run($limit = NULL)
 {
     // Cleanup crashed jobs
     $pids = $this->_db->fetchCol("SELECT pid FROM {$this->_table} WHERE pid IS NOT NULL GROUP BY pid");
     foreach ($pids as $pid) {
         // Old pid is no longer running, release it's reserved tasks
         if (is_numeric($pid) && !file_exists("/proc/{$pid}/status")) {
             Mage::log("A crashed job queue process was detected for pid {$pid}", Zend_Log::NOTICE, self::ERROR_LOG);
             $this->_db->update($this->_table, array('pid' => new Zend_Db_Expr('NULL')), array('pid = ?' => $pid));
         }
     }
     // Reserve all new jobs since last run
     $pid = getmypid();
     $limit = $limit ? "LIMIT {$limit}" : '';
     $batchSize = $this->_db->query("UPDATE {$this->_db->quoteIdentifier($this->_table, true)} SET pid = {$pid} WHERE pid IS NULL ORDER BY job_id {$limit}")->rowCount();
     // Run all reserved jobs
     $result = $this->_db->query($this->_db->select()->from($this->_table, '*')->where('pid = ?', $pid)->order(array('job_id')));
     while ($row = $result->fetch()) {
         $where = $this->_db->quoteInto('job_id = ?', $row['job_id']);
         $data = substr($row['data'], 0, 1) == '{' ? json_decode($row['data'], TRUE) : ($data = unserialize($row['data']));
         // Check retries
         if ($row['retries'] >= $row['max_retries']) {
             $this->_db->delete($this->_table, $where);
             Mage::log("{$row['pid']}: Mage::getSingleton({$row['class']})->{$row['method']}(" . json_encode($data) . ")\n" . $row['error_log'], Zend_Log::ERR, self::ERROR_LOG);
             continue;
         }
         // Run job!
         try {
             $model = Mage::getSingleton($row['class']);
             $method = $row['method'];
             $model->{$method}(new Varien_Object($data));
             $this->_db->delete($this->_table, $where);
             Mage::log("{$row['pid']}: Mage::getSingleton({$row['class']})->{$row['method']}(" . json_encode($data) . ")", Zend_Log::INFO, self::SUCCESS_LOG);
         } catch (Exception $e) {
             // Increment retries and log error information
             $error = date('c') . " ERROR: " . get_class($e) . ": '{$e->getMessage()}' in {$e->getFile()}:{$e->getLine()}\n" . "Stack trace:\n" . $e->getTraceAsString();
             $bind = array('pid' => new Zend_Db_Expr('NULL'), 'retries' => new Zend_Db_Expr('retries + 1'), 'error_log' => new Zend_Db_Expr('SUBSTR(CONCAT(error_log,' . $this->_db->quote($error) . ',"\\n\\n"),1,20000)'));
             $this->_db->update($this->_table, $bind, $where);
         }
     }
     return $batchSize;
 }
Beispiel #4
0
 /**
  * Returns whether table exists
  *
  * @param string $table
  * @return bool
  */
 protected function _tableExists($table)
 {
     $rows = $this->_adapter->fetchAll('SHOW TABLES');
     foreach ($rows as $row) {
         $tableFound = strtolower(current($row));
         if ($table == $tableFound) {
             return true;
         }
     }
     return false;
 }
Beispiel #5
0
 /**
  * Test incomplete Roll Back in a nested transaction
  */
 public function testSequentialTransactionsSuccess()
 {
     $this->_adapter->expects($this->exactly(4))->method('_connect');
     $this->_adapter->expects($this->exactly(2))->method('_beginTransaction');
     $this->_adapter->expects($this->once())->method('_rollBack');
     $this->_adapter->expects($this->once())->method('_commit');
     $this->_adapter->beginTransaction();
     $this->_adapter->beginTransaction();
     $this->_adapter->beginTransaction();
     $this->_adapter->rollBack();
     $this->_adapter->rollBack();
     $this->_adapter->rollBack();
     $this->_adapter->beginTransaction();
     $this->_adapter->commit();
 }
Beispiel #6
0
 public function refund(Varien_Object $payment, $amount)
 {
     // fetch order and transaction info
     $order = $payment->getOrder();
     $row = $this->_mysqlr->fetchRow('SELECT * FROM `' . $this->_table . '` WHERE `order_id` = ' . intval($order->entity_id), array(), Zend_Db::FETCH_ASSOC);
     $transaction_id = $row['transaction_id'];
     // fetch payment info
     $mollie = $this->_api->_getMollieAPI();
     $mollie_payment = $mollie->payments->get($transaction_id);
     // attempt a refund
     try {
         $mollie->payments->refund($mollie_payment, $amount);
     } catch (Exception $e) {
         Mage::throwException('Impossible to create a refund for this transaction. Details: ' . $e->getMessage() . '<br />');
     }
     return $this;
 }
 /**
  * Save attribute
  *
  * @param Varien_Object $object
  * @param string $attributeCode
  * @return Mage_Eav_Model_Entity_Abstract
  */
 public function saveAttribute(Varien_Object $object, $attributeCode)
 {
     $attribute = $this->getAttribute($attributeCode);
     $backend = $attribute->getBackend();
     $table = $backend->getTable();
     $entity = $attribute->getEntity();
     $entityIdField = $entity->getEntityIdField();
     $row = array('entity_type_id' => $entity->getTypeId(), 'attribute_id' => $attribute->getId(), $entityIdField => $object->getData($entityIdField));
     $newValue = $object->getData($attributeCode);
     if ($attribute->isValueEmpty($newValue)) {
         $newValue = null;
     }
     $whereArr = array();
     foreach ($row as $field => $value) {
         $whereArr[] = $this->_read->quoteInto("{$field}=?", $value);
     }
     $where = '(' . join(') AND (', $whereArr) . ')';
     $this->_getWriteAdapter()->beginTransaction();
     try {
         $select = $this->_getWriteAdapter()->select()->from($table, 'value_id')->where($where);
         $origValueId = $this->_getWriteAdapter()->fetchOne($select);
         if ($origValueId === false && !is_null($newValue)) {
             $this->_insertAttribute($object, $attribute, $newValue);
             $backend->setValueId($this->_getWriteAdapter()->lastInsertId());
         } elseif ($origValueId !== false && !is_null($newValue)) {
             $this->_updateAttribute($object, $attribute, $origValueId, $newValue);
         } elseif ($origValueId !== false && is_null($newValue)) {
             $this->_getWriteAdapter()->delete($table, $where);
         }
         $this->_getWriteAdapter()->commit();
     } catch (Exception $e) {
         $this->_getWriteAdapter()->rollback();
         throw $e;
     }
     $this->_processAttributeValues();
     return $this;
 }
 protected function getLikeExistItem($newItem, $ignoreTitle = true, $attributeSet = NULL)
 {
     $whereSql = '';
     foreach ($newItem as $key => $value) {
         if ($ignoreTitle && $key == 'title') {
             continue;
         }
         if ($whereSql == '') {
             $whereSql .= ' ';
         } else {
             $whereSql .= ' AND ';
         }
         $whereSql .= ' `' . $key . '` ';
         is_null($value) && ($whereSql .= ' IS NULL ');
         is_string($value) && ($whereSql .= ' = ' . $this->mySqlReadConnection->quote($value) . ' ');
         (is_integer($value) || is_float($value)) && ($whereSql .= ' = ' . $value . ' ');
     }
     $dbSelect = $this->mySqlReadConnection->select()->from($this->tableNameNew, '*');
     $whereSql != '' && $dbSelect->where($whereSql);
     $row = $this->mySqlReadConnection->fetchRow($dbSelect);
     if ($row === false) {
         return NULL;
     }
     if (!is_null($attributeSet)) {
         $templateId = (int) $row['id'];
         $templateType = (int) $attributeSet['template_type'];
         $attributeSetId = (int) $attributeSet['attribute_set_id'];
         $tasTable = Mage::getResourceModel('M2ePro/TemplatesAttributeSets')->getMainTable();
         $dbSelect = $this->mySqlReadConnection->select()->from($tasTable, '*')->where('template_type = ?', $templateType)->where('template_id = ?', $templateId);
         $rowsAttributesSets = $this->mySqlReadConnection->fetchAll($dbSelect);
         if ($rowsAttributesSets === false || count($rowsAttributesSets) != 1) {
             return NULL;
         }
         $rowAttributeSet = $rowsAttributesSets[0];
         if ((int) $rowAttributeSet['attribute_set_id'] != $attributeSetId) {
             return NULL;
         }
     }
     return $row;
 }
Beispiel #9
0
 public function getValues($type)
 {
     $dbSelect = $this->mySqlReadConnection->select()->from($this->tableName, '*')->where('`type` = ?', (string) $type);
     return $this->mySqlReadConnection->fetchAll($dbSelect);
 }
 /**
  * Special handling for PDO query().
  * All bind parameter names must begin with ':'.
  *
  * @param string|Zend_Db_Select $sql  The SQL statement with placeholders.
  * @param mixed                 $bind An array of data or data itself to bind to the placeholders.
  *
  * @return Varien_Db_Statement_Pdo_Mysql
  * @throws Zend_Db_Adapter_Exception To re-throw PDOException.
  */
 public function query($sql, $bind = array())
 {
     if (false === $this->enableDbQuoteOptimization()) {
         return parent::query($sql, $bind);
     }
     if (is_array($bind) && count($bind) > 0) {
         foreach ($bind as $k => $v) {
             $bind[$k] = $this->castToNumeric($v);
         }
     }
     return parent::query($sql, $bind);
 }
 public static function setLogQueryTime($value = true)
 {
     if ($value === true) {
         self::$_logAllQueries = true;
         return;
     }
     self::$_logAllQueries = false;
     self::$_logQueryTime = $value;
 }
Beispiel #12
0
 /**
  * Adjust transaction level with "transparent" counter
  *
  * @return int
  */
 public function getTransactionLevel()
 {
     return parent::getTransactionLevel() - $this->_levelAdjustment;
 }
Beispiel #13
0
 public function rollBackTransaction()
 {
     $this->_read->rollBack();
 }
Beispiel #14
0
 private function _saveSettings($settings)
 {
     foreach ($settings as $key => $value) {
         $this->_resource->query("insert into {$this->_table} (`scope`, `scope_id`, `key`, `{$value['type']}_value`, `type`)\n                    values (?,?,?,?,?)", array($this->_scope, $this->_scopeId, $key, $value['value'], $value['type']));
     }
 }
 /**
  * @param Varien_Db_Adapter_Pdo_Mysql $adapter
  * @param Unirgy_StoreLocator_Model_Mysql4_Location $resource
  */
 protected function clearOldLocations($adapter, $resource)
 {
     $overwrite = $this->_shouldOverwrite();
     if ($overwrite && !$this->_tablesCleared) {
         $adapter->delete($resource->getMainTable());
         $this->_tablesCleared = true;
     }
 }
 /**
  * @param Varien_Db_Adapter_Pdo_Mysql $db
  * @return Varien_Db_Select
  */
 protected function _getFilterableAttributeSelect($db)
 {
     return $db->select()->from(array('a' => $this->getTable('eav/attribute')), null)->joinInner(array('t' => $this->getTable('eav/entity_type')), "`t`.`entity_type_id` = `a`.`entity_type_id` AND `t`.`entity_type_code` = 'catalog_product'", null)->joinInner(array('ca' => $this->getTable('catalog/eav_attribute')), "`ca`.`attribute_id` = `a`.`attribute_id`", null)->where("`ca`.`is_filterable` <> 0");
 }
 private function _deleteSettings($websiteId, $storeId)
 {
     $this->_connection->query("DELETE FROM {$this->_table} WHERE `website_id`={$websiteId} and `store_id`={$storeId}");
     return $this;
 }
if (isset($_COOKIE['magento_debug_mysql']) && $_COOKIE['magento_debug_mysql'] == 'value') {
    $debugMysql = true;
}
if (isset($_COOKIE['magento_debug_mysql']) && $_COOKIE['magento_debug_mysql'] == 'all') {
    $debugMysql = true;
}
if ($debugMysql) {
    require_once 'libs/Varien/Db/Adapter/Pdo/Mysql.php';
    if (isset($_COOKIE['magento_debug_mysql_trace']) && $_COOKIE['magento_debug_mysql_trace'] == 'yes') {
        Varien_Db_Adapter_Pdo_Mysql::setLogCallStack();
    }
    if ($_COOKIE['magento_debug_mysql'] == 'all') {
        Varien_Db_Adapter_Pdo_Mysql::setLogQueryTime();
    }
    if ($_COOKIE['magento_debug_mysql'] == 'value' && isset($_COOKIE['magento_debug_mysql'])) {
        Varien_Db_Adapter_Pdo_Mysql::setLogQueryTime((double) $_COOKIE['magento_debug_mysql']);
    }
}
// Blocks debug
if (isset($_COOKIE['magento_debug_blocks']) && $_COOKIE['magento_debug_blocks'] == 'yes') {
    require_once 'libs/Mage/Core/Block/Template.php';
}
if (isset($_GET['magento_debug'])) {
    if ($_GET['magento_debug'] == 'message' && isset($_POST['message'])) {
        $file = MagentoDebugger::getDebuggerVarDir() . '/ajax-console.log';
        file_put_contents($file, $_POST['message'] . "\n", FILE_APPEND);
        return;
    }
    if ($_GET['magento_debug'] == 'model' && isset($_GET['magento_debug_model_method'])) {
        $modelMethodName = $_GET['magento_debug_model_method'];
        header('Content-Type: text/plain');
Beispiel #19
0
 /**
  * Safely quotes a value for an SQL statement.
  *
  * If an array is passed as the value, the array values are quote
  * and then returned as a comma-separated string.
  *
  * @param mixed $value The value to quote.
  * @param null $type OPTIONAL the SQL datatype name, or constant, or null.
  * @return mixed|string An SQL-safe quoted value (or string of separated values).
  */
 public function quote($value, $type = null)
 {
     $this->_connect();
     if ($type !== null && array_key_exists($type = strtoupper($type), $this->_numericDataTypes) && $this->_numericDataTypes[$type] == Zend_Db::FLOAT_TYPE) {
         $value = $this->_convertFloat($value);
         $quoteValue = sprintf('%F', $value);
         return $quoteValue;
     } elseif (is_float($value)) {
         return $this->_quote($value);
     }
     return parent::quote($value, $type);
 }
Beispiel #20
0
 /**
  * Run sql code
  *
  * @param $command
  * @return Mage_Backup_Model_Resource_Db
  */
 public function runCommand($command)
 {
     $this->_write->query($command);
     return $this;
 }
Beispiel #21
0
 public function endSetup()
 {
     $this->_conn->multi_query("\nSET SQL_MODE=IFNULL(@OLD_SQL_MODE,'');\nSET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS=0, 0, 1);\n");
     return $this;
 }
Beispiel #22
0
 /**
  * @param Varien_Db_Adapter_Pdo_Mysql $connection
  * @param $tableName
  * @param array $fields
  * @param bool $onDuplicate
  * @return string
  */
 public function insert($connection, $tableName, $fields = array(), $onDuplicate = true)
 {
     $sql = "INSERT INTO `{$tableName}` ";
     $sql .= "(`" . implode('`,`', array_keys($fields)) . "`) ";
     $sql .= "VALUES (" . implode(',', $fields) . ") ";
     if ($onDuplicate && $fields) {
         $sql .= " ON DUPLICATE KEY UPDATE";
         $updateFields = array();
         foreach ($fields as $key => $field) {
             $key = $connection->quoteIdentifier($key);
             $updateFields[] = "{$key}=VALUES({$key})";
         }
         $sql .= " " . implode(', ', $updateFields);
     }
     return $sql;
 }
 /**
  * Generate Cron Status Information
  *
  * @return array
  * @throws Exception
  */
 protected function _generateCronStatusData()
 {
     $systemReport = array();
     if (!$this->_readConnection) {
         throw new Exception('Cant\'t connect to DB. Cron schedule status can\'t be retrieved.');
     }
     // Cron status by status code
     $data = array();
     try {
         $info = $this->_readConnection->fetchAll("\n                SELECT COUNT( * ) AS `cnt` , `status`\n                FROM `{$this->_getTableName('cron/schedule')}`\n                GROUP BY `status`\n                ORDER BY `status`\n            ");
         if ($info) {
             foreach ($info as $_data) {
                 $data[] = array($_data['status'], $_data['cnt']);
             }
         }
         $systemReport['Cron Schedules by status code'] = array('header' => array('Status Code', 'Count'), 'data' => $data);
     } catch (Exception $e) {
         $this->_log($e);
     }
     // Cron status by job code
     $data = array();
     try {
         $info = $this->_readConnection->fetchAll("\n                SELECT COUNT( * ) AS `cnt` , `job_code`\n                FROM `{$this->_getTableName('cron/schedule')}`\n                GROUP BY `job_code`\n                ORDER BY `job_code`\n            ");
         if ($info) {
             foreach ($info as $_data) {
                 $data[] = array($_data['job_code'], $_data['cnt']);
             }
         }
         $systemReport['Cron Schedules by job code'] = array('header' => array('Job Code', 'Count'), 'data' => $data);
     } catch (Exception $e) {
         $this->_log($e);
     }
     return $systemReport;
 }
Beispiel #24
0
 /**
  * Truncate table with <code>$name</code>
  *
  * @param string $name
  * @param Varien_Db_Adapter_Pdo_Mysql $connection
  * @return AW_Advancedreports_Helper_Tools_Aggregator
  */
 private function _dropFlatTable($name, $connection)
 {
     if ($this->_tableExists($name)) {
         try {
             $connection->exec(new Zend_Db_Expr("DROP TABLE IF EXISTS `{$name}`"));
         } catch (Exception $e) {
             Mage::logException($e);
         }
     }
     return $this;
 }
Beispiel #25
0
 /**
  * Test result for bigint
  *
  * @dataProvider bigintResultProvider
  */
 public function testPrepareColumnValueForBigint($value, $expectedResult)
 {
     $result = $this->_adapter->prepareColumnValue(array('DATA_TYPE' => 'bigint'), $value);
     $this->assertEquals($expectedResult, $result);
 }