Import SQL file in Doctrine / PDO

I recently needed to programmatically import SQL files containing database dumps into a database managed by Doctrine ORM. There didn’t seem to be a built in way to do that, possibly due to our older Doctrine / Symfony versions. I created a solution based on this StackOverflow answer that just made use of the underlying PDO connection, and thus would also be useful for regular PDO situations. The solution runs the SQL row by row in a transaction, so it will automatically roll back on failure.

The code for the import looks something like:

$db = $em->getConnection()->getWrappedConnection();
foreach($files as $file){
        $sql = trim(file_get_contents($file));
            $count = 0;
                $querySet = $db->prepare($sql);
            }catch(Exception $e){
                throw $e;
            echo "{$file}: {$count}\n";
            throw new Exception("File {$file} appears to be empty.");
        throw new Exception("File '{$file}' not found.");

where $em is a Doctrine entity manager (or $db can be your PDO object directly) and $files is an array of file path strings pointing at SQL files.

This worked well for us even with multi-megabyte SQL dumps and can easily be modified for use in a Symfony command or service, as I did.