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 6f1637a commit 2c000fe
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,11 +189,13 @@ 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 (($s = fgets($handle)) !== FALSE) {
$size += strlen($s);
if (!strncasecmp($s, 'DELIMITER ', 10)) {
$delimiter = trim(substr($s, 10));

Expand All @@ -201,6 +204,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 @@ -209,6 +215,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 2c000fe

Please sign in to comment.