<?php

namespace app\common\utility;

use think\facade\Db;
use think\db\Query;

class DbTool
{
    public static function addColumnIfNotExists($table, $column, $definition,$isUnique=false)
    {

// 增加字段
$sql = <<<SQL
ALTER TABLE {$table}
ADD COLUMN {$column} {$definition};
SQL;
        
        try {
            Db::execute($sql);
            if($isUnique){
                // 再添加唯一索引
                $sql2 = <<<SQL
                CREATE UNIQUE INDEX idx_{$table}_{$column} ON `{$table}`(`{$column}`);
                SQL;
                Db::execute($sql2);
            }
            return true;
        } catch (\Exception $e) {
            // dd('添加字段失败：' . $e->getMessage() . "\nSQL: " . $sql);
            return false;
        }
    }
}