feat(同步命令): 添加忽略表功能并优化表名处理

This commit is contained in:
augushong
2026-01-09 22:09:56 +08:00
parent edeae731f0
commit ec757f2e9f
2 changed files with 43 additions and 1 deletions

View File

@@ -5,6 +5,7 @@ return [
'ignore_tables' => [
'migrations',
'phinxlog',
'debug_log',
],
// 备份中间前缀
'backup_prefix' => 'backup',

View File

@@ -6,8 +6,10 @@ use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\facade\App;
use think\facade\Config;
use app\common\service\scheme\SchemeToDbService;
use app\common\scheme\attribute\Table;
use ReflectionClass;
class Sync extends Command
{
@@ -25,6 +27,9 @@ class Sync extends Command
$service = new SchemeToDbService();
$schemeDir = app()->getAppPath() . 'admin/scheme/';
$ignoreTables = Config::get('scheme.ignore_tables', []);
$connection = Config::get('database.default', 'mysql');
$prefix = Config::get('database.connections.' . $connection . '.prefix', '');
if (!is_dir($schemeDir)) {
$output->writeln("<error>Scheme directory not found: $schemeDir</error>");
@@ -37,6 +42,12 @@ class Sync extends Command
$className = 'app\\admin\\scheme\\' . basename($file, '.php');
if (class_exists($className)) {
$tableName = $this->getTableNameFromScheme($className);
if (!empty($tableName) && $this->isIgnoredTable($tableName, $ignoreTables, $prefix)) {
$output->writeln("Skipping $className (ignored table: $tableName)");
continue;
}
$output->writeln("Syncing $className...");
try {
$backup = $service->sync($className, $skipData);
@@ -50,4 +61,34 @@ class Sync extends Command
}
}
}
protected function getTableNameFromScheme(string $className): string
{
try {
$ref = new ReflectionClass($className);
$tableAttrs = $ref->getAttributes(Table::class);
if (empty($tableAttrs)) {
return '';
}
$tableAttr = $tableAttrs[0]->newInstance();
return (string)($tableAttr->name ?? '');
} catch (\Throwable $e) {
return '';
}
}
protected function isIgnoredTable(string $tableName, array $ignoreTables, string $prefix): bool
{
if (empty($ignoreTables)) {
return false;
}
$shortName = $tableName;
if ($prefix && str_starts_with($tableName, $prefix)) {
$shortName = substr($tableName, strlen($prefix));
}
return in_array($shortName, $ignoreTables, true) || in_array($tableName, $ignoreTables, true);
}
}