2

I have one database for my laravel application but I need to open two connection to it in Laravel for the following reason.

I have this code:

    $pdo = DB::connection()->getPdo();
    $pdo->setAttribute( PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false );

    $query = $pdo->query( "SOME QUERY PULLING MILLIONS OF ROWS" );

    while ( $row = $query->fetch( PDO::FETCH_ASSOC ) ) {
        // Some function that writes the result to file
        // and updates a row in a table to keep track of the process
    }

I'm using an unbuffered query as I don't have enough memory to ready the entire result set into memory, we are talking millions of rows here. But I need to keep track of how many rows have been processed so I have a function that writes back to a status table every 10K rows processed. Problem is while an unbuffered query is running you cannot write back to MYSQL until its finished.

So what I need to do is make this unbuffered query above run it a new connection but to the same database as the application is using.

So is it possible? How do I spin up a new connection in Laravel to the same database the application is already using without closing the existing connection?

Scott
  • 3,967
  • 9
  • 38
  • 56
  • I think you have seen this already, but http://laravel.com/docs/5.0/database#accessing-connections but maybe ```DB::connection('foo')->select(...)``` can open a new connection for you. With ```DB::disconnect('foo');``` you can disconnect. – wiesson Mar 04 '15 at 09:52
  • @wiesson I'm under the impression this will only work if you have multiple connections configured. I have only one connection 'production'. If I use `DB::connection('production')` then it will just use the connection that is already open rather than use a new one. Please correct me if I am wrong. – Scott Mar 04 '15 at 09:57
  • 1
    I think you are correct, but you could try to define "prodiction2" with the same credentials and establish a connection. This was just my initial thought, I don't know if this is very efficient, but could work for now. – wiesson Mar 04 '15 at 10:01
  • @wiesson thanks I have the same thought process and am in the middle of testing this as we speak. – Scott Mar 04 '15 at 10:05
  • @wiesson OK this works but feels hacky as I'm needlessly creating a duplication of config. Maybe someone has a better solution? – Scott Mar 04 '15 at 10:07

1 Answers1

0

In application config create a new database connection with the same database connection details as your main database and call it something different.

Then in code you can use the second connection like so:

$pdo = DB::connection('connection 2 name here')->getPdo();

This will open a new connection if it isn't already open.

Scott
  • 3,967
  • 9
  • 38
  • 56