initialize(); if (Settings::get('IAM_DATA_MODE', 'standalone') !== 'standalone') { throw new RuntimeException('共享数据模式禁止初始化数据库;请使用原项目管理真实数据'); } $arguments = getopt('', ['account:', 'password:', 'name:']); $account = Input::account($arguments['account'] ?? 'admin'); $password = Input::password($arguments['password'] ?? Settings::get('IAM_ADMIN_PASSWORD')); $name = Input::text($arguments['name'] ?? '管理员', '名称'); $database = new Database(true); if ($database->driver === 'sqlite') { $lock = fopen(Settings::sqlitePath() . '.init.lock', 'c'); if (!$lock || !flock($lock, LOCK_EX)) { throw new RuntimeException('无法取得初始化锁'); } $tables = $database->all("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'"); } else { $mysqlLock = 'iam-init-' . sha1(Settings::get('IAM_DB_DATABASE')); $result = $database->one('SELECT GET_LOCK(?,10) AS acquired', [$mysqlLock]); if ((int) ($result['acquired'] ?? 0) !== 1) { throw new RuntimeException('无法取得初始化锁'); } $tables = $database->all('SHOW TABLES'); } if ($tables !== []) { throw new RuntimeException('数据库非空,拒绝初始化;现有账号与密码未修改'); } require __DIR__ . '/schema.php'; require __DIR__ . '/seed.php'; if ($database->driver === 'sqlite') { $database->transaction(static function () use ($database, $account, $password, $name): void { identitySchema($database); identitySeed(new IdentityRepository($database), $account, $password, $name); }); } else { // MySQL DDL commits implicitly; all credentials were validated before creating any table. identitySchema($database); $database->transaction(static fn () => identitySeed(new IdentityRepository($database), $account, $password, $name)); } fwrite(STDOUT, "独立数据库初始化完成:{$account}(密码未输出)\n"); } catch (Throwable $error) { // Do not print PDO connection diagnostics, SQL parameters or credential values. $message = $error instanceof app\exception\ApiError || $error instanceof RuntimeException && !$error instanceof PDOException ? $error->getMessage() : '初始化失败,请检查独立数据库及目录权限'; fwrite(STDERR, $message . "\n"); exit(1); } finally { if (is_resource($lock)) { flock($lock, LOCK_UN); fclose($lock); } if ($database && $mysqlLock !== '') { $database->one('SELECT RELEASE_LOCK(?)', [$mysqlLock]); } }