/**
  * Clean unused relation products
  *
  * @param int $storeId
  * @return Enterprise_Catalog_Model_Index_Action_Product_Flat_Refresh
  */
 protected function _cleanRelationProducts($storeId)
 {
     if (!$this->_productHelper->getFlatHelper()->isAddChildData()) {
         return $this;
     }
     foreach ($this->_getProductTypeInstances() as $typeInstance) {
         if (!$typeInstance->isComposite()) {
             continue;
         }
         $relation = $typeInstance->getRelationInfo();
         if ($relation && $relation->getTable() && $relation->getParentFieldName() && $relation->getChildFieldName()) {
             $select = $this->_connection->select()->distinct(true)->from($this->_productHelper->getTable($relation->getTable()), "{$relation->getParentFieldName()}");
             $joinLeftCond = array("e.entity_id = t.{$relation->getParentFieldName()}", "e.child_id = t.{$relation->getChildFieldName()}");
             if ($relation->getWhere() !== null) {
                 $select->where($relation->getWhere());
                 $joinLeftCond[] = $relation->getWhere();
             }
             $entitySelect = new Zend_Db_Expr($select->__toString());
             $select = $this->_connection->select()->from(array('e' => $this->_productHelper->getFlatTableName($storeId)), null)->joinLeft(array('t' => $this->_productHelper->getTable($relation->getTable())), implode(' AND ', $joinLeftCond), array())->where('e.is_child = ?', 1)->where('e.entity_id IN(?)', $entitySelect)->where("t.{$relation->getChildFieldName()} IS NULL");
             $sql = $select->deleteFromSelect('e');
             $this->_connection->query($sql);
         }
     }
     return $this;
 }
 /**
  * Delete non stores categories
  *
  * @param Mage_Core_Model_Store $store
  * @return void
  */
 protected function _deleteNonStoreCategories($store)
 {
     $rootId = Mage_Catalog_Model_Category::TREE_ROOT_ID;
     $rootIdExpr = $this->_connection->quote((string) $rootId);
     $rootCatIdExpr = $this->_connection->quote("{$rootId}/{$store->getRootCategoryId()}");
     $catIdExpr = $this->_connection->quote("{$rootId}/{$store->getRootCategoryId()}/%");
     $select = $this->_connection->select()->from(array('cf' => $this->_getMainStoreTable($store->getId())))->joinLeft(array('ce' => $this->_productHelper->getTable('catalog/category')), 'cf.path = ce.path', array())->where("cf.path = {$rootIdExpr} OR cf.path = {$rootCatIdExpr} OR cf.path like {$catIdExpr}")->where('ce.entity_id IS NULL');
     $sql = $select->deleteFromSelect('cf');
     $this->_connection->query($sql);
 }