package mysql import ( "strings" "git.fsdpf.net/go/db/v2" "git.fsdpf.net/go/db/v2/dialect/mysql" "git.fsdpf.net/go/db/v2/internal/sb" "git.fsdpf.net/go/db/v2/schema" "git.fsdpf.net/go/db/v2/sqlgen" ) type Mysql struct { db *db.Database esg sqlgen.ExpressionSQLGenerator } var mysqlDefaultModifiers = []string{ "Unsigned", "Charset", "Collate", "VirtualAs", "StoredAs", "Nullable", "Default", "Increment", "Comment", "After", "First", } var mysqlSerials = []string{ "bigInteger", "integer", "mediumInteger", "smallInteger", "tinyInteger", } func (this Mysql) GetColumnListing(table string) ([]string, error) { cols := []string{} err := this.db.From(db.S("information_schema").Table("columns")).Where( db.C("table_name").Eq(table), db.C("table_schema").Eq(db.L("database()")), ).Pluck(&cols, "column_name") return cols, err } func (this Mysql) TableExists(table string) (bool, error) { result, err := this.db.From(db.S("information_schema").Table("tables")).Where(db.Ex{ "table_name": table, "table_type": "BASE TABLE", "table_schema": db.L("database()"), }).Count() return result > 0, err } // 创建表 func (this Mysql) CompileCreate(bp *schema.Blueprint) []string { temporary := db.L("CREATE") if bp.IsTemporary() { temporary = db.L("CREATE TEMPORARY") } columns := strings.Join(this.getAddedColumns(bp), ",\n") sql := this.GenerateSQL("? TABLE ? (\n?\n)", temporary, db.T(bp.GetTable()), db.L(columns)) charset := bp.GetCharset() if charset == "" { charset = "utf8mb4" } collation := bp.GetCollation() if collation == "" { collation = "utf8mb4_general_ci" } sql += this.GenerateSQL(" default charset=? collate=?", charset, collation) if engine := bp.GetEngine(); engine != "" { sql += this.GenerateSQL(" engine=?", engine) } return []string{sql} } // 添加字段 func (this Mysql) CompileAdd(bp *schema.Blueprint) []string { columns := strings.Join(schema.PrefixArray("ADD COLUMN", this.getAddedColumns(bp)), ",\n") sql := this.GenerateSQL("ALTER TABLE ?\n?", db.T(bp.GetTable()), db.L(columns)) return []string{sql} } // 修改字段 func (this Mysql) CompileChange(bp *schema.Blueprint) []string { columns := strings.Join(schema.PrefixArray("CHANGE COLUMN", this.getChangedColumns(bp)), ",\n") sql := this.GenerateSQL("ALTER TABLE ?\n?", db.T(bp.GetTable()), db.L(columns)) return []string{sql} } // 删除列 func (this Mysql) CompileDropColumn(bp *schema.Blueprint) []string { columns := []string{} for _, item := range bp.GetCommands() { if item.Type != "dropColumn" { continue } for _, col := range item.Columns { columns = append(columns, this.GenerateSQL("DROP COLUMN ?", db.C(col))) } } sql := this.GenerateSQL("ALTER TABLE ?\n?", db.T(bp.GetTable()), db.L(strings.Join(columns, ",\n"))) return []string{sql} } // 删除表 func (this Mysql) CompileDrop(bp *schema.Blueprint) []string { return []string{this.GenerateSQL("DROP TABLE ?", db.T(bp.GetTable()))} } // 删除表, 先判断再删除 func (this Mysql) CompileDropIfExists(bp *schema.Blueprint) []string { return []string{this.GenerateSQL("DROP TABLE IF EXISTS ?", db.T(bp.GetTable()))} } // 表重命名 func (this Mysql) CompileRename(bp *schema.Blueprint) []string { toName := "" commands := bp.GetCommands() if len(commands) == 0 { panic("new table undefined") } toName = bp.GetCommands()[0].To if toName == "" { panic("new table undefined") } return []string{this.GenerateSQL("RENAME TABLE ? TO ?", db.T(bp.GetTable()), db.T(toName))} } func (this Mysql) addModifiers(sql string, bp *schema.Blueprint, column *schema.ColumnDefinition) string { for _, modifier := range mysqlDefaultModifiers { sql += this.GetColumnModifier(modifier, bp, column) } return sql } func (this Mysql) GetColumnType(column *schema.ColumnDefinition) string { switch column.Type { case "char": return this.GenerateSQL("char(?)", column.Length) case "string": return this.GenerateSQL("varchar(?)", column.Length) case "text": return "text" case "integer": return this.GenerateSQL("int(?)", column.Length) case "bigInteger": return "bigint(20)" case "tinyInteger": return "tinyint(1)" case "smallInteger": return "smallint(4)" case "decimal": return this.GenerateSQL("decimal(?,?)", column.Total, column.Places) case "boolean": return "tinyint(1)" case "enum": return this.GenerateSQL("enum?", column.Allowed) case "json": return "json" case "binary": return "binary" case "datetime": return "datetime" case "timestamp": return "timestamp" case "date": return "date" case "time": return "time" case "year": return "year" case "uuid": return "char(36)" } panic("Unsupported data type: " + column.Type) } func (this Mysql) GetColumnModifier(modifier string, bp *schema.Blueprint, column *schema.ColumnDefinition) string { switch modifier { case "Unsigned": if column.IsUnsigned() { return " UNSIGNED" } case "Charset": if v := column.GetCharset(); v != "" { return this.GenerateSQL(" CHARACTER SET ?", v) } case "Collate": if v := column.GetCollaction(); v != "" { return this.GenerateSQL(" COLLATE ?", v) } case "VirtualAs": if v := column.GetVirtualAs(); v != "" { return this.GenerateSQL(" GENERATED ALWAYS AS (?) VIRTUAL", db.L(v)) } case "StoredAs": if v := column.GetStoredAs(); v != "" { return this.GenerateSQL(" GENERATED ALWAYS AS (?) STORED", db.L(v)) } case "Nullable": if column.GetVirtualAs() == "" && column.GetStoredAs() == "" { if column.IsNullable() { return " NULL" } return " NOT NULL" } case "Default": v := column.GetDefault() if v == nil { if column.IsUseCurrent() { return " DEFAULT CURRENT_TIMESTAMP" } return "" } if column.IsUseCurrent() { return this.GenerateSQL(" DEFAULT CURRENT_TIMESTAMP ?", v) } return this.GenerateSQL(" DEFAULT ?", v) case "Increment": if column.IsAutoIncrement() { return " AUTO_INCREMENT PRIMARY KEY" } case "Comment": if v := column.GetComment(); v != "" { return this.GenerateSQL(" COMMENT ?", v) } case "After": if v := column.GetAfter(); v != "" { return this.GenerateSQL(" AFTER ?", v) } case "First": if column.IsFirst() { return " FIRST" } } return "" } // 获取新增表结构字段 func (this Mysql) getAddedColumns(bp *schema.Blueprint) (columns []string) { for _, column := range bp.GetAddedColumns() { sql := this.GenerateSQL("? ?", db.C(column.Name), db.L(this.GetColumnType(column))) columns = append(columns, this.addModifiers(sql, bp, column)) } return } // 获取修改表结构字段 func (this Mysql) getChangedColumns(bp *schema.Blueprint) (columns []string) { for _, column := range bp.GetChangedColumns() { name := column.Name rename := column.Name if column.GetRename() != "" { rename = column.GetRename() } sql := this.GenerateSQL("? ? ?", db.C(name), db.C(rename), db.L(this.GetColumnType(column))) columns = append(columns, this.addModifiers(sql, bp, column)) } return } // 生成SQL func (this Mysql) GenerateSQL(sql string, args ...any) string { sb := sb.NewSQLBuilder(false) this.esg.Generate(sb, db.L(sql, args...)) result, _, _ := sb.ToSQL() return result } func init() { schema.RegisterDialect("mysql", func(db *db.Database) schema.Schema { return &Mysql{ db: db, esg: sqlgen.NewExpressionSQLGenerator("mysql", mysql.DialectOptions()), } }) }