setName('dbal:import') ->setDescription('Import SQL file(s) directly to Database.') ->setDefinition([new InputArgument( 'file', InputArgument::REQUIRED | InputArgument::IS_ARRAY, 'File path(s) of SQL to be executed.' ), ]) ->setHelp(<<getHelper('db')->getConnection(); $fileNames = $input->getArgument('file'); if ($fileNames === null) { return 0; } foreach ((array) $fileNames as $fileName) { $filePath = realpath($fileName); // Phar compatibility. if ($filePath === false) { $filePath = $fileName; } if (! file_exists($filePath)) { throw new InvalidArgumentException( sprintf("SQL file '%s' does not exist.", $filePath) ); } if (! is_readable($filePath)) { throw new InvalidArgumentException( sprintf("SQL file '%s' does not have read permissions.", $filePath) ); } $output->write(sprintf("Processing file '%s'... ", $filePath)); $sql = @file_get_contents($filePath); if ($sql === false) { throw new RuntimeException( sprintf("Unable to read SQL file '%s': %s", $filePath, error_get_last()['message']) ); } if ($conn instanceof PDOConnection) { // PDO Drivers try { $lines = 0; $stmt = $conn->prepare($sql); assert($stmt instanceof PDOStatement); $stmt->execute(); do { // Required due to "MySQL has gone away!" issue $stmt->fetch(); $stmt->closeCursor(); $lines++; } while ($stmt->nextRowset()); $output->write(sprintf('%d statements executed!', $lines) . PHP_EOL); } catch (PDOException $e) { $output->write('error!' . PHP_EOL); throw new RuntimeException($e->getMessage(), $e->getCode(), $e); } } else { // Non-PDO Drivers (ie. OCI8 driver) $stmt = $conn->prepare($sql); $rs = $stmt->execute(); if (! $rs) { $error = $stmt->errorInfo(); $output->write('error!' . PHP_EOL); throw new RuntimeException($error[2], $error[0]); } $output->writeln('OK!' . PHP_EOL); $stmt->closeCursor(); } } return 0; } }