Skip to content

Commit

Permalink
Helpers::loadFromFile added $onProgress
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Jun 9, 2017
1 parent eda00f8 commit 304e5c6
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/Database/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,9 +177,10 @@ public static function detectType(string $type): string

/**
* Import SQL dump from file - extremely fast.
* @param $onProgress function (int $count, ?float $percent): void
* @return int count of commands
*/
public static function loadFromFile(Connection $connection, $file): int
public static function loadFromFile(Connection $connection, string $file, callable $onProgress = NULL): int
{
@set_time_limit(0); // @ function may be disabled

Expand All @@ -188,12 +189,14 @@ public static function loadFromFile(Connection $connection, $file): int
throw new Nette\FileNotFoundException("Cannot open file '$file'.");
}

$count = 0;
$stat = fstat($handle);
$count = $size = 0;
$delimiter = ';';
$sql = '';
$pdo = $connection->getPdo(); // native query without logging
while (!feof($handle)) {
$s = (string) fgets($handle);
$size += strlen($s);
if (!strncasecmp($s, 'DELIMITER ', 10)) {
$delimiter = trim(substr($s, 10));

Expand All @@ -202,6 +205,9 @@ public static function loadFromFile(Connection $connection, $file): int
$pdo->exec($sql);
$sql = '';
$count++;
if ($onProgress) {
$onProgress($count, isset($stat['size']) ? $size * 100 / $stat['size'] : NULL);
}

} else {
$sql .= $s;
Expand All @@ -210,6 +216,9 @@ public static function loadFromFile(Connection $connection, $file): int
if (rtrim($sql) !== '') {
$pdo->exec($sql);
$count++;
if ($onProgress) {
$onProgress($count, isset($stat['size']) ? 100 : NULL);
}
}
fclose($handle);
return $count;
Expand Down

0 comments on commit 304e5c6

Please sign in to comment.