From ddfb4217d9c285536234bbd20f96e44a12577a6e Mon Sep 17 00:00:00 2001 From: lubosdz Date: Sun, 11 Sep 2022 22:26:47 +0200 Subject: [PATCH] Support importing SQL file --- src/Ifsnop/Mysqldump/Mysqldump.php | 40 ++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/Ifsnop/Mysqldump/Mysqldump.php b/src/Ifsnop/Mysqldump/Mysqldump.php index 8d1e4e37..82470e57 100644 --- a/src/Ifsnop/Mysqldump/Mysqldump.php +++ b/src/Ifsnop/Mysqldump/Mysqldump.php @@ -276,6 +276,46 @@ public function getTableLimit($tableName) return $limit; } + /** + * Import supplied SQL file + * @param string $path Absolute path to imported *.sql file + */ + public function restore($path) + { + if(!$path || !is_file($path)){ + throw new Exception("File {$path} does not exist."); + } + + $handle = fopen($path , 'rb'); + + if(!$handle){ + throw new Exception("Failed reading file {$path}. Check access permissions."); + } + + if(!$this->dbHandler){ + $this->connect(); + } + + $buffer = ''; + while ( !feof($handle) ) { + $line = trim(fgets($handle)); + + if (substr($line, 0, 2) == '--' || !$line) { + continue; // skip comments + } + + $buffer .= $line; + + // if it has a semicolon at the end, it's the end of the query + if (';' == substr(rtrim($line), -1, 1)) { + $this->dbHandler->exec($buffer); + $buffer = ''; + } + } + + fclose($handle); + } + /** * Parse DSN string and extract dbname value * Several examples of a DSN string