Magento – Force a reconnect to Mysql

databasemodelMySQL

Is there anyway I can force a reconnect to Mysql with Magento? or Replace the connection entirely?

I have an importer which is slow, and is very custom using Magento models. Before you say it… No I don't want t use any off the shelf products. This is super specific. A way of speeding this up would be to pcntl fork during a part of the application to improve import speed. The issue with pcntl_fork is that the db connection will go bad as soon as you fork. So I need to totally reconnect the Mage core connection so that my forked process is new connection. So any mage core model save will automatically be using the new connection rather that the parent pcntl processes connection.

Ideas?

Cheers

Best Answer

Threading can work, DB connection unterminated:

I'm not having the same issue that you are when I switch over $pid -

<?php

require('app/Mage.php');
Mage::app();


$pid = pcntl_fork();

switch($pid) {
    case -1:
        print "Could not fork!\n";
        exit;
    case 0:
        echo "In Child " . Mage::getModel('catalog/product')->getCollection()->getLastItem()->getId() . PHP_EOL;
        break;
    default:
        echo "In Parent " . Mage::getModel('catalog/product')->getCollection()->getFirstItem()->getId() . PHP_EOL;
}

Returns:

> php test.php
In Parent 1
In Child 32

However if I do not, I get a MySQL gone away error:

PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2013 Lost connection to MySQL server during query

Summary:

I think you have an error in your execution code somewhere wherein you are not executing database queries from within the switch over process ID.

Edit

Further investigation:

By declaring a Mage::registry value, and then inspecting the source of the query we can, from within lib/Varien/Db/Adapter/Pdo/Mysql.php, inspect the scope (pid) of the current running process:

test.php:

$pid = pcntl_fork();
Mage::register('pcntl',$pid);

lib/Varien/Db/Adapter/Pdo/Mysql.php:

public function query($sql, $bind = array())
{
    $pid = Mage::registry('pcntl');
    switch($pid){
        case 0:
            echo "In child" . PHP_EOL;
        case 1:
            echo "In parent!" . PHP_EOL;
    }
    //.... stuff

Result:

In child
In parent!
In child
In parent!
In child
In parent!
In child
In parent!
In child
In parent!
In child
In parent!
In child
In parent!
In child
In parent!
In child
In parent!
In child
In parent!
Related Topic