/** * @return \Magento\Framework\DB\Adapter\AdapterInterface */ protected function getConnection() { if (!$this->connection) { $this->connection = $this->resource->getConnection('sales_write'); } return $this->connection; }
/** * Returns connection * * @return AdapterInterface */ protected function getConnection() { if (!$this->connection) { $this->connection = $this->resource->getConnection($this->connectionName); } return $this->connection; }
/** * Retrieve write connection instance * * @return bool|\Magento\Framework\DB\Adapter\AdapterInterface */ protected function _getWriteConnection() { if (null === $this->_connection) { $this->_connection = $this->_resource->getConnection('write'); } return $this->_connection; }
/** * Load customer log data by customer id * * @param int $customerId * @return array */ protected function loadLogData($customerId) { /** @var \Magento\Framework\DB\Adapter\AdapterInterface $adapter */ $adapter = $this->resource->getConnection('read'); $select = $adapter->select()->from(['cl' => $this->resource->getTableName('customer_log')])->joinLeft(['cv' => $this->resource->getTableName('customer_visitor')], 'cv.customer_id = cl.customer_id', ['last_visit_at'])->where('cl.customer_id = ?', $customerId)->order('cv.visitor_id DESC')->limit(1); return $adapter->fetchRow($select); }
/** * Get connection object * * @return \Magento\Framework\DB\Adapter\AdapterInterface */ public function getConnection() { if (null === $this->connection) { $this->connection = $this->resourceModel->getConnection($this->connectionName); } return $this->connection; }
/** * {@inheritdoc} */ public function buildFilter(\Magento\Framework\Search\Request\FilterInterface $filter) { $adapter = $this->resource->getConnection(Resource::DEFAULT_READ_RESOURCE); /** @var \Magento\Framework\Search\Request\Filter\Term $filter */ $condition = sprintf('%s = %s', $filter->getField(), $adapter->quote($filter->getValue())); return $condition; }
/** * @return void */ protected function setUp() { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->resource = $this->objectManager->get('Magento\\Framework\\App\\Resource'); $this->adapter = $this->resource->getConnection('core_read'); $this->reviewCollection = $this->objectManager->create('Magento\\Review\\Model\\Resource\\Review\\Collection'); $this->reviewResource = $this->objectManager->create('Magento\\Review\\Model\\Resource\\Review'); }
protected function setUp() { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\CatalogSearch\Model\Indexer\Fulltext\Action\Full indexer */ $this->indexer = $this->objectManager->create('Magento\\CatalogSearch\\Model\\Indexer\\Fulltext\\Action\\Full'); $this->resource = $this->objectManager->get('Magento\\Framework\\App\\Resource'); $this->adapter = $this->resource->getConnection('core_read'); }
public function setUp() { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); $this->resource = $this->objectManager->get('Magento\\Framework\\App\\Resource'); $this->connection = $this->resource->getConnection('core_write'); $this->model = $this->objectManager->create('Magento\\Framework\\Mview\\View\\Changelog', ['resource' => $this->resource]); $this->model->setViewId('test_view_id_1'); $this->model->create(); }
public function testGetConnectionInitConnection() { $this->_connectionFactory->expects($this->once())->method('create')->with(self::CONNECTION_NAME)->will($this->returnValue($this->_connection)); $this->_connection->expects($this->once())->method('setCacheAdapter')->with($this->isInstanceOf('Magento\\Framework\\Cache\\FrontendInterface')); $frontendInterface = $this->getMockBuilder('Magento\\Framework\\Cache\\FrontendInterface')->disableOriginalConstructor()->setMethods([])->getMock(); $this->_cache->expects($this->once())->method('getFrontend')->will($this->returnValue($frontendInterface)); $this->assertInstanceOf('Magento\\Framework\\DB\\Adapter\\AdapterInterface', $this->_resorce->getConnection(self::RESOURCE_NAME)); $this->assertInstanceOf('Magento\\Framework\\DB\\Adapter\\AdapterInterface', $this->_resorce->getConnection(self::RESOURCE_NAME)); }
protected function setUp() { $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); /** @var \Magento\Indexer\Model\IndexerRegistry $indexerRegistry */ $indexerRegistry = $this->objectManager->create('\\Magento\\Indexer\\Model\\IndexerRegistry'); $this->indexer = $indexerRegistry->get('catalogsearch_fulltext'); $this->resource = $this->objectManager->get('Magento\\Framework\\App\\Resource'); $this->adapter = $this->resource->getConnection('core_read'); }
/** * Move data from temporary tables to flat * * @param string $flatTable * @param string $flatDropName * @param string $temporaryFlatTableName * @return void */ public function move($flatTable, $flatDropName, $temporaryFlatTableName) { $connection = $this->_resource->getConnection('write'); $renameTables = []; if ($connection->isTableExists($flatTable)) { $renameTables[] = ['oldName' => $flatTable, 'newName' => $flatDropName]; } $renameTables[] = ['oldName' => $temporaryFlatTableName, 'newName' => $flatTable]; $connection->dropTable($flatDropName); $connection->renameTablesBatch($renameTables); $connection->dropTable($flatDropName); }
/** * @param int $n * @return void */ public function generateSequences($n = 10) { $connection = $this->appResource->getConnection('write'); for ($i = 0; $i < $n; $i++) { foreach ($this->entities as $entityName) { $sequenceName = $this->appResource->getTableName(sprintf('sequence_%s_%s', $entityName, $i)); if (!$connection->isTableExists($sequenceName)) { $connection->query($this->ddlSequence->getCreateSequenceDdl($sequenceName)); } } } }
/** * Save image information to DB. * * @param \Magento\Catalog\Model\Product $product * @param array $images * @return void */ protected function storeImage($product, $images) { $baseImage = ''; $i = 1; foreach ($images as $image) { if (empty($image)) { $this->errors[] = $product->getSku(); continue; } if (strpos($image, '_main') !== false) { $baseImage = $image; } $id = $this->galleryAttribute->insertGallery(['attribute_id' => $this->mediaAttribute->getAttributeId(), 'entity_id' => $product->getId(), 'value' => $image]); $this->galleryAttribute->insertGalleryValueInStore(['value_id' => $id, 'store_id' => \Magento\Store\Model\Store::DEFAULT_STORE_ID, 'entity_id' => $product->getId(), 'label' => 'Image', 'position' => $i, 'disables' => 0]); $i++; } if (empty($baseImage)) { $baseImage = $images[0]; } if ($baseImage) { $imageAttribute = $product->getResource()->getAttribute('image'); $smallImageAttribute = $product->getResource()->getAttribute('small_image'); $thumbnailAttribute = $product->getResource()->getAttribute('thumbnail'); $adapter = $this->resource->getConnection('core'); foreach ([$imageAttribute, $smallImageAttribute, $thumbnailAttribute] as $attribute) { $table = $imageAttribute->getBackend()->getTable(); /** @var \Magento\Framework\DB\Adapter\AdapterInterface $adapter*/ $data = [$attribute->getBackend()->getEntityIdField() => $product->getId(), 'attribute_id' => $attribute->getId(), 'value' => $baseImage]; $adapter->insertOnDuplicate($table, $data, ['value']); } } }
/** * {@inheritdoc} */ public function run() { $this->logger->log('Installing Tablerate:'); /** @var \Magento\Framework\DB\Adapter\AdapterInterface $connection */ $connection = $this->resource->getConnection('core'); $fixtureFile = 'OfflineShipping/tablerate.csv'; $fixtureFilePath = $this->fixtureHelper->getPath($fixtureFile); $regions = $this->loadDirectoryRegions(); /** @var \Magento\SampleData\Helper\Csv\Reader $csvReader */ $csvReader = $this->csvReaderFactory->create(['fileName' => $fixtureFilePath, 'mode' => 'r']); foreach ($csvReader as $data) { $regionId = $data['region'] != '*' ? $regions[$data['country']][$data['region']] : 0; try { $connection->insert($this->tablerate->getMainTable(), ['website_id' => $this->storeManager->getWebsiteId(), 'dest_country_id' => $data['country'], 'dest_region_id' => $regionId, 'dest_zip' => $data['zip'], 'condition_name' => 'package_value', 'condition_value' => $data['order_subtotal'], 'price' => $data['price'], 'cost' => 0]); } catch (\Zend_Db_Statement_Exception $e) { if ($e->getCode() == self::ERROR_CODE_DUPLICATE_ENTRY) { // In case if Sample data was already installed we just skip duplicated records installation continue; } else { throw $e; } } $this->logger->logInline('.'); } $this->configWriter->save('carriers/tablerate/active', 1); $this->configWriter->save('carriers/tablerate/condition_name', 'package_value'); $this->cacheTypeList->cleanType('config'); }
/** * @param RequestInterface $request * @param MatchContainer[] $matchQueries * @param ScoreBuilder $scoreBuilder * @param Select $select * @param IndexBuilderInterface $indexBuilder * @return Select * @internal param QueryContainer $queryContainer */ private function addMatchQueries(RequestInterface $request, array $matchQueries, ScoreBuilder $scoreBuilder, Select $select, IndexBuilderInterface $indexBuilder) { if (!$matchQueries) { $select->columns($scoreBuilder->build()); $select = $this->createAroundSelect($select, $scoreBuilder); } elseif (count($matchQueries) === 1) { $matchContainer = reset($matchQueries); $this->matchBuilder->build($scoreBuilder, $select, $matchContainer->getRequest(), $matchContainer->getConditionType()); $select->columns($scoreBuilder->build()); $select = $this->createAroundSelect($select, $scoreBuilder); } elseif (count($matchQueries) > 1) { $select->columns($scoreBuilder->build()); $select = $this->createAroundSelect($select, $scoreBuilder); $subSelect = $select; $select = $this->resource->getConnection(Resource::DEFAULT_READ_RESOURCE)->select(); $tables = array_merge(array_keys($matchQueries), ['main_select.relevance']); $relevance = implode('.relevance + ', $tables); $select->from(['main_select' => $subSelect], [$this->entityMetadata->getEntityId() => 'entity_id', 'relevance' => sprintf('(%s)', $relevance)]); foreach ($matchQueries as $matchName => $matchContainer) { $matchSelect = $indexBuilder->build($request); $matchScoreBuilder = $this->scoreBuilderFactory->create(); $matchSelect = $this->matchBuilder->build($matchScoreBuilder, $matchSelect, $matchContainer->getRequest(), $matchContainer->getConditionType()); $matchSelect->columns($matchScoreBuilder->build()); $select->join([$matchName => $this->createAroundSelect($matchSelect, $scoreBuilder)], $matchName . '.entity_id = main_select.entity_id', []); } } return $select; }
/** * Create sequence with metadata and profile * * @throws \Exception * @throws \Magento\Framework\Exception\AlreadyExistsException * @return void */ public function create() { $metadata = $this->resourceMetadata->loadByEntityTypeAndStore($this->data['entity_type'], $this->data['store_id']); if ($metadata->getSequenceTable() == $this->getSequenceName()) { return; } $this->data['sequence_table'] = $this->getSequenceName(); $this->data['is_active'] = 1; $profile = $this->profileFactory->create(['data' => array_intersect_key($this->data, array_flip(['prefix', 'suffix', 'start_value', 'step', 'max_value', 'warning_value', 'is_active', 'active_profile']))]); $profile->setHasDataChanges(true); $this->data['active_profile'] = $profile; $metadata = $this->metaFactory->create(['data' => array_intersect_key($this->data, array_flip(['entity_type', 'store_id', 'sequence_table', 'active_profile']))]); $metadata->setHasDataChanges(true); try { $this->resourceMetadata->save($metadata); $adapter = $this->appResource->getConnection('write'); if (!$adapter->isTableExists($this->data['sequence_table'])) { $adapter->query($this->ddlSequence->getCreateSequenceDdl($this->data['sequence_table'], $this->data['start_value'])); } } catch (Exception $e) { $this->resourceMetadata->delete($metadata); $this->logger->critical($e); throw $e; } $this->data = array_flip($this->pattern); }
/** * Check attribute lock state * * @param \Magento\Framework\Model\AbstractModel $object * @param null $attributeSet * @throws \Magento\Framework\Exception\LocalizedException * @return void */ public function validate(\Magento\Framework\Model\AbstractModel $object, $attributeSet = null) { $adapter = $this->resource->getConnection('read'); $attrTable = $this->resource->getTableName('catalog_product_super_attribute'); $productTable = $this->resource->getTableName('catalog_product_entity'); $bind = ['attribute_id' => $object->getAttributeId()]; $select = clone $adapter->select(); $select->reset()->from(['main_table' => $attrTable], ['psa_count' => 'COUNT(product_super_attribute_id)'])->join(['entity' => $productTable], 'main_table.product_id = entity.entity_id')->where('main_table.attribute_id = :attribute_id')->group('main_table.attribute_id')->limit(1); if ($attributeSet !== null) { $bind['attribute_set_id'] = $attributeSet; $select->where('entity.attribute_set_id = :attribute_set_id'); } if ($adapter->fetchOne($select, $bind)) { throw new \Magento\Framework\Exception\LocalizedException(__('This attribute is used in configurable products.')); } }
/** * Cleanup old logs so that the database table foggyline_sentinel_log does not get cluttered. * * @return $this */ public function cleanup() { try { /* Here we do a fast cleanup, directly on database, no individual objects */ $connection = $this->resource->getConnection(); $connection->beginTransaction(); $condition = ['created_at < (NOW() - INTERVAL ? HOUR)' => $this->helper->getCleanAfterHours()]; $connection->delete($this->resource->getTableName('foggyline_sentinel_log'), $condition); $connection->commit(); $this->logger->info('Cron job foggyline_sentinel_cleanup executed'); } catch (\Exception $e) { $connection->rollBack(); $this->logger->critical($e); } return $this; }
/** * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry * @param \Magento\Framework\App\Config\ScopeConfigInterface $config * @param \Magento\Framework\Model\Resource\AbstractResource $resource * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection * @param \Magento\UrlRewrite\Helper\UrlRewrite $urlRewriteHelper * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Magento\Framework\App\Resource $appResource * @param \Magento\UrlRewrite\Model\UrlFinderInterface $urlFinder * @param array $data * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct(\Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\App\Config\ScopeConfigInterface $config, \Magento\UrlRewrite\Helper\UrlRewrite $urlRewriteHelper, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\App\Resource $appResource, \Magento\UrlRewrite\Model\UrlFinderInterface $urlFinder, \Magento\Framework\Model\Resource\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, array $data = []) { parent::__construct($context, $registry, $config, $resource, $resourceCollection, $data); $this->urlRewriteHelper = $urlRewriteHelper; $this->connection = $appResource->getConnection(Resource::DEFAULT_WRITE_RESOURCE); $this->urlFinder = $urlFinder; $this->storeManager = $storeManager; }
/** * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory * @param \Psr\Log\LoggerInterface $logger * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy * @param \Magento\Framework\App\Resource $resource */ public function __construct(\Magento\Framework\Data\Collection\EntityFactory $entityFactory, \Psr\Log\LoggerInterface $logger, \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy, \Magento\Framework\App\Resource $resource) { $this->_setIdFieldName('primary_id'); parent::__construct($entityFactory, $logger, $fetchStrategy, $resource->getConnection('review_read')); $this->_summaryTable = $resource->getTableName('review_entity_summary'); $this->_select->from($this->_summaryTable); $this->setItemObjectClass('Magento\\Review\\Model\\Review\\Summary'); }
/** * @param \Magento\Catalog\Helper\Product\Flat\Indexer $productIndexerHelper * @param \Magento\Framework\App\Resource $resource * @param \Magento\Framework\App\Config\ScopeConfigInterface $config * @param \Magento\Framework\StoreManagerInterface $storeManager * @param TableDataInterface $tableData */ public function __construct(\Magento\Catalog\Helper\Product\Flat\Indexer $productIndexerHelper, \Magento\Framework\App\Resource $resource, \Magento\Framework\App\Config\ScopeConfigInterface $config, \Magento\Framework\StoreManagerInterface $storeManager, \Magento\Catalog\Model\Indexer\Product\Flat\TableDataInterface $tableData) { $this->_productIndexerHelper = $productIndexerHelper; $this->_connection = $resource->getConnection('write'); $this->_config = $config; $this->_storeManager = $storeManager; $this->_tableData = $tableData; }
/** * Validate sequence before save * * @throws \Magento\Framework\Exception\AlreadyExistsException * @return void */ protected function validate() { $metadata = $this->resourceMetadata->loadByEntityTypeAndStore($this->data['entity_type'], $this->data['store_id']); $adapter = $this->appResource->getConnection('write'); if ($metadata->getId() && !$adapter->isTableExists($this->getSequenceName())) { throw new \Magento\Framework\Exception\AlreadyExistsException(__('Sequence with this metadata already exists')); } }
/** * @param \Magento\Framework\App\Resource $resource * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Magento\Catalog\Helper\Product\Flat\Indexer $productHelper * @param \Magento\Catalog\Model\Product\Type $productType * @param TableBuilder $tableBuilder * @param FlatTableBuilder $flatTableBuilder */ public function __construct(\Magento\Framework\App\Resource $resource, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Catalog\Helper\Product\Flat\Indexer $productHelper, \Magento\Catalog\Model\Product\Type $productType, TableBuilder $tableBuilder, FlatTableBuilder $flatTableBuilder) { $this->_storeManager = $storeManager; $this->_productIndexerHelper = $productHelper; $this->_productType = $productType; $this->_connection = $resource->getConnection('default'); $this->_tableBuilder = $tableBuilder; $this->_flatTableBuilder = $flatTableBuilder; }
/** * Move data from temporary tables to flat * * @param string $flatTable * @param string $flatDropName * @param string $temporaryFlatTableName * @return void */ public function move($flatTable, $flatDropName, $temporaryFlatTableName) { $connection = $this->_resource->getConnection('write'); if (!$connection->isTableExists($flatTable)) { $connection->dropTable($flatDropName); $connection->renameTablesBatch([['oldName' => $temporaryFlatTableName, 'newName' => $flatTable]]); $connection->dropTable($flatDropName); } else { $describe = $connection->describeTable($flatTable); $columns = $this->_productIndexerHelper->getFlatColumns(); $columns = array_keys(array_intersect_key($describe, $columns)); $select = $connection->select(); $select->from(['tf' => sprintf('%s_tmp_indexer', $flatTable)], $columns); $sql = $select->insertFromSelect($flatTable, $columns); $connection->query($sql); $connection->dropTable(sprintf('%s_tmp_indexer', $flatTable)); } }
/** * @param Config $eavConfig * @param Resource $resource * @param \Magento\Catalog\Helper\Product $productHelper * @param StoreManagerInterface $storeManager * @param CategoryHelper $categoryHelper * @param Converter $converter */ public function __construct(Config $eavConfig, Resource $resource, ProductHelper $productHelper, StoreManagerInterface $storeManager, CategoryHelper $categoryHelper, Converter $converter) { $this->eavConfig = $eavConfig; $this->connection = $resource->getConnection(Resource::DEFAULT_READ_RESOURCE); $this->productHelper = $productHelper; $this->storeManager = $storeManager; $this->categoryHelper = $categoryHelper; $this->converter = $converter; }
/** * Retrieve connection to resource specified by $resourceName. * * @param string $resourceName * @return \Exception|false|\Magento\Framework\DB\Adapter\AdapterInterface|\Zend_Exception */ protected function getConnection($resourceName) { try { $connection = $this->resource->getConnection($resourceName); return $connection; } catch (\Zend_Exception $e) { echo $e->getMessage() . PHP_EOL; return $e; } }
/** * @param Resource $resource * @param \Magento\Framework\DB\Ddl\TriggerFactory $triggerFactory * @param \Magento\Framework\Mview\View\CollectionInterface $viewCollection * @param \Magento\Framework\Mview\ViewInterface $view * @param string $tableName * @param string $columnName */ public function __construct(Resource $resource, \Magento\Framework\DB\Ddl\TriggerFactory $triggerFactory, \Magento\Framework\Mview\View\CollectionInterface $viewCollection, \Magento\Framework\Mview\ViewInterface $view, $tableName, $columnName) { $this->write = $resource->getConnection('core_write'); $this->triggerFactory = $triggerFactory; $this->viewCollection = $viewCollection; $this->view = $view; $this->tableName = $tableName; $this->columnName = $columnName; $this->resource = $resource; }
/** * Populate ACL with roles from external storage * * @param \Magento\Framework\Acl $acl * @return void */ public function populateAcl(\Magento\Framework\Acl $acl) { $roleTableName = $this->_resource->getTableName('authorization_role'); $adapter = $this->_resource->getConnection('core_read'); $select = $adapter->select()->from($roleTableName)->order('tree_level'); foreach ($adapter->fetchAll($select) as $role) { $parent = $role['parent_id'] > 0 ? $role['parent_id'] : null; switch ($role['role_type']) { case RoleGroup::ROLE_TYPE: $acl->addRole($this->_groupFactory->create(['roleId' => $role['role_id']]), $parent); break; case RoleUser::ROLE_TYPE: if (!$acl->hasRole($role['role_id'])) { $acl->addRole($this->_roleFactory->create(['roleId' => $role['role_id']]), $parent); } else { $acl->addRoleParent($role['role_id'], $parent); } break; } } }
/** * Get connection by resource name * * @param string $resourceName * @return \Magento\Framework\DB\Adapter\AdapterInterface|false */ protected function _getConnection($resourceName) { if (isset($this->_connections[$resourceName])) { return $this->_connections[$resourceName]; } $fullResourceName = ($this->_resourcePrefix ? $this->_resourcePrefix . '_' : '') . $resourceName; $connectionInstance = $this->_resources->getConnection($fullResourceName); // cache only active connections to detect inactive ones as soon as they become active if ($connectionInstance) { $this->_connections[$resourceName] = $connectionInstance; } return $connectionInstance; }