Skip to content

Commit

Permalink
支持是否一次性导入
Browse files Browse the repository at this point in the history
  • Loading branch information
limingxinleo committed Jul 15, 2024
1 parent 77f8529 commit 098718a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 6 deletions.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
},
"require": {
"php": ">=8.1",
"ext-pdo": "*",
"hyperf/database": "^3.0",
"hyperf/db-connection": "^3.0"
},
Expand Down
51 changes: 45 additions & 6 deletions src/Importer.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

use Fan\SqlImport\Exception\NotFoundException;
use Hyperf\Database\Connectors\ConnectionFactory;
use PDO;
use Psr\Container\ContainerInterface;
use Throwable;

Expand All @@ -26,26 +27,59 @@ public function __construct(protected ContainerInterface $container)
$this->factory = $this->container->get(ConnectionFactory::class);
}

public function import(array $config, string $sql): Result
/**
* @param bool $once 是否一次性导入
*/
public function import(array $config, string $sql, bool $once = true): Result
{
$connection = $this->factory->make($config);
$pdo = $connection->getPdo();
if ($once) {
return new Result($this->importSql($pdo, $sql));
}

$res = $connection->getPdo()->exec($sql);
if ($res === false) {
return new Result(false);
$sqls = explode("\n", $sql);
$sql = '';
$result = new Result(true);
foreach ($sqls as $line) {
try {
if (str_starts_with($line, '--') || $line == '') {
continue;
}

// Add this line to the current segment
$sql .= $line;

// If it has a semicolon at the end, it's the end of the query
if (str_ends_with(trim($line), ';')) {
$pdo->exec($sql);
$sql = '';
}
} catch (Throwable $exception) {
$result->isSuccess = false;
$result->failedSqls[] = new FailedSql($sql, $exception->getMessage());
$sql = '';
}
}

return new Result(true);
return $result;
}

public function importPath(array $config, string $path): Result
/**
* @param bool $once 是否一次性导入
*/
public function importPath(array $config, string $path, bool $once = false): Result
{
// if file cannot be found throw errror
if (! file_exists($path)) {
throw new NotFoundException(sprintf('File %s not found.', $path));
}

$pdo = $this->factory->make($config)->getPdo();
if ($once) {
return new Result($this->importSql($pdo, file_get_contents($path)));
}

$fp = fopen($path, 'r');
$sql = '';
$result = new Result(true);
Expand All @@ -72,4 +106,9 @@ public function importPath(array $config, string $path): Result
fclose($fp);
return $result;
}

protected function importSql(PDO $pdo, string $sql): bool
{
return $pdo->exec($sql) !== false;
}
}

0 comments on commit 098718a

Please sign in to comment.