_getReadAdapter(); $writeAdapter = $this->_getWriteAdapter(); $timeLimit = $this->formatDate(Mage::getModel('core/date')->gmtTimestamp() - $time); // retrieve last active customer log id $lastLogId = $readAdapter->fetchOne( $readAdapter->select() ->from($this->getTable('log/customer'), 'log_id') ->where('login_at < ?', $timeLimit) ->order('log_id DESC') ->limit(1) ); if (!$lastLogId) { return $this; } /** * @author Kirk Madera * * Replaced this query entirely. The purpose of this query is to grab the latest log id * for each customer. This can be done with a group by and max expression, without the * overhead of joins and the exponentially time increase as data increases. */ //// Order by desc log_id before grouping (within-group aggregates query pattern) // $select = $readAdapter->select() // ->from( // array('log_customer_main' => $this->getTable('log/customer')), // array('log_id')) // ->joinLeft( // array('log_customer' => $this->getTable('log/customer')), // 'log_customer_main.customer_id = log_customer.customer_id ' // . 'AND log_customer_main.log_id < log_customer.log_id', // array()) // ->where('log_customer.customer_id IS NULL') // ->where('log_customer_main.log_id < ?', $lastLogId + 1); $select = $readAdapter->select() ->from($this->getTable('log/customer'), array('log_id' => new Zend_Db_Expr('MAX(log_id)'))) ->group('customer_id') ->where('log_id < ?', $lastLogId + 1); $needLogIds = array(); $query = $readAdapter->query($select); while ($row = $query->fetch()) { $needLogIds[$row['log_id']] = 1; } $customerLogId = 0; while (true) { $visitorIds = array(); $select = $readAdapter->select() ->from( $this->getTable('log/customer'), array('log_id', 'visitor_id')) ->where('log_id > ?', $customerLogId) ->where('log_id < ?', $lastLogId + 1) ->order('log_id') ->limit(100); $query = $readAdapter->query($select); $count = 0; while ($row = $query->fetch()) { $count++; $customerLogId = $row['log_id']; if (!isset($needLogIds[$row['log_id']])) { $visitorIds[] = $row['visitor_id']; } } if (!$count) { break; } if ($visitorIds) { $condition = array('visitor_id IN (?)' => $visitorIds); // remove visitors from log/quote $writeAdapter->delete($this->getTable('log/quote_table'), $condition); // remove visitors from log/url $writeAdapter->delete($this->getTable('log/url_table'), $condition); // remove visitors from log/visitor_info $writeAdapter->delete($this->getTable('log/visitor_info'), $condition); // remove visitors from log/visitor $writeAdapter->delete($this->getTable('log/visitor'), $condition); // remove customers from log/customer $writeAdapter->delete($this->getTable('log/customer'), $condition); } if ($customerLogId == $lastLogId) { break; } } return $this; } }