ProjectInit.php 3.7 KB
<?php
/**
 * Created by PhpStorm.
 * User: zhl
 * Date: 2023/4/12
 * Time: 15:33
 */
namespace App\Console\Commands;

use App\Models\Project;
use App\Services\ProjectServer;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * Class ProjectInitDatabase
 * @package App\Console\Commands
 */
class ProjectInit extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'project:init';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '项目数据库初始化';

    protected $connect = null;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @return bool
     */
    public function handle()
    {
        #TODO 通过项目ID获取项目部署数据库配置, 创建数据库, 同步数据表
        $project_id = 102;
        $project = Project::getProjectById($project_id);
        if (empty($project) || empty($project->mysqlConfig()))
            return true;
        $this->initDatabase($project);

        return true;
    }

    /**
     * @param Project $project
     * @return bool
     */
    public function initDatabase($project)
    {
        $create_flag = $this->createDatabase($project);

        if (!$create_flag) {
            // 创建数据库失败 添加通知以及再次处理
        }
        // 设置 database.connections.custom_mysql 数据
        ProjectServer::useProject($project->id);

        // TODO 创建对应库 初始化数据表
        $this->initTable();
        return true;
    }

    /**
     * @return bool
     */
    public function initTable()
    {
        $database_name = DB::connection('custom_tmp_mysql')->getDatabaseName();

        $table = Schema::connection('custom_tmp_mysql')->getAllTables();
        $table = array_column($table, 'Tables_in_' . $database_name);
        foreach ($table as $v) {
            $has_table = Schema::connection('custom_mysql')->hasTable($v);
            if ($has_table)
                continue;

            $connection = DB::connection('custom_tmp_mysql');
            $sql = $connection->getDoctrineSchemaManager()
                ->getDatabasePlatform()
                ->getCreateTableSQL($connection->getDoctrineSchemaManager()->listTableDetails($v));

            DB::connection('custom_mysql')->select($sql[0]);
        }
        return true;
    }

    /**
     * 创建数据库
     * 链接mysql 查询数据库是否存在 创建数据库
     * @param Project $project
     * @return bool|\mysqli_result|null
     */
    public function createDatabase($project)
    {
        # 该方法需要:composer require parity-bit/laravel-db-commands
//        $result = Artisan::call('db:create', [
//            '--database' => $database_name,
//        ]);
//
//        return $result;

        if ($this->connect)
            return $this->connect;

        //连接到 MySQL 服务器
        $servername = $project->mysqlConfig()->host;
        $username = $project->mysqlConfig()->user;
        $password = $project->mysqlConfig()->password;
        $conn = new \mysqli($servername, $username, $password);
        //检查连接是否成功
        if ($conn->connect_error) {
            die("连接失败: " . $conn->connect_error);
        }
        $this->connect = $conn;
//        $result = $conn->query('SHOW DATABASES LIKE \'' . $database_name . '\';');
//        if ($result)
//            return true;
        $result = $conn->query('CREATE DATABASE ' . $project->databaseName() . ';');
        return $result;
    }
}