Magento Flat Catalog – Get Flat Product Table Name

collection;flat-catalogperformanceskusql

First, I wanted to ask for the fastest way to get a list of all existing SKUs in the shop (Magento 1.9.0.1), but while writing the post, I already managed to write a good deal of the solution.
This is a combination of two ways – one is fast (raw sql, 0.02s), one is reliable (collections, 2s):

$ProductCollection = Mage::getModel('catalog/product')->getCollection();

if ($ProductCollection->getFlatHelper()->isEnabled()) {
    $TableName = 'catalog_product_flat_1';

    $result = Mage::getSingleton('core/resource')
        ->getConnection('core_read')
        ->query("SELECT sku FROM `{$TableName}`");

    $rows = $result->fetchAll();
    $shopSKUs = array();

    foreach ($rows as $row)
        $shopSKUs[] = $row['sku'];

} else {
    $shopSKUs = $ProductCollection
        ->addAttributeToSelect('sku')
        ->getColumnValues('sku');
}

But it will only work if catalog_product_flat_1 is always the correct name of the flat table.

I tried to get the table name, but with no success:

$readConnection = Mage::getSingleton('core/resource')->getConnection('core_read');
$TableName = $readConnection->getTableName('catalog/product_flat');

This results in $TableName being the literal string catalog/product_flat, while

$TableName = Mage::getModel('core/resource')->getTableName('catalog/product_flat');

ends up with $TableName being catalog_product_flat – notice the missing _1.

So, the question it all boils down to is this:
How can I get Magento to give me the correct name of the flat product table?

Background:
I'm currently preparing a pre-import sanity check of CSV product data which will then be imported using Magmi.
The import will be done every few days with new products, so I'd like to have the workflow as foolproof as possible.
I already do check if all given SKUs in the CSV-file are unique, but I also want to check if any of those SKUs already exists in the shop.

Best Answer

Hi you could try with something like this:

public function getFlatTableName($store = null)
{
    if (is_null($store)) {
        $store = $this->getStoreId();
    }
    return $this->getTable('catalog/product_flat') . '_' . $store;
}

There is a nice post here about this topic: http://inchoo.net/magento/flat-tables-in-magento-and-product-collection/

Related Topic