Files
db/schema/dialect/mysql/mysql.go
T
what 21b80bdea4 feat: 完善扫描器、exec 及 schema 相关功能
- exec/scanner: 用 *interface{} 替换 **json.RawMessage 扫描目标,兼容 DuckDB 返回 map[string]interface{} 的场景;新增 toJSONRawMessage 转换函数
- exec/scanner: ScanVal 支持结构体指针,通过 JSON 中间层转换(DuckDB STRUCT 列)
- exec/scanner: 将 *sql.RawBytes 和 *[]byte 的处理从 ScanValContext 移入 scanner.ScanVal
- exec/query_executor: 简化 ScanValContext,移除私有 scan 方法
- exec: 补充 scanner 级别 ScanVal 测试用例
- internal/util/reflect: 重写 SafeSetVarValue,修复非指针 src 及 nil 指针字段的 panic
- internal/util/column_map: 恢复非匿名带标签结构体字段的展开逻辑
- schema: 新增 vector 列类型支持
- engine: 补充 DuckDB 相关配置
- dialect/sqlite3/vtab: 完善虚拟表适配器
- 各方言测试改用 sqlmock 虚拟连接
2026-05-20 17:52:28 +08:00

292 lines
7.6 KiB
Go

package mysql
import (
"strings"
"git.fsdpf.net/go/db"
"git.fsdpf.net/go/db/dialect/mysql"
"git.fsdpf.net/go/db/internal/sb"
"git.fsdpf.net/go/db/schema"
"git.fsdpf.net/go/db/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.Temporary {
temporary = db.L("CREATE TEMPORARY")
}
columns := strings.Join(this.getAddedColumns(bp), ",\n")
sql := this.GenerateSQL("? TABLE IF NOT EXISTS ? (\n?\n)", temporary, db.T(bp.GetTable()), db.L(columns))
charset := bp.Charset
if charset == "" {
charset = "utf8mb4"
}
collation := bp.Collation
if collation == "" {
collation = "utf8mb4_general_ci"
}
sql += this.GenerateSQL(" default charset=? collate=?", charset, collation)
if engine := bp.Engine; engine != "" {
sql += this.GenerateSQL(" engine=?", engine)
}
if comment := bp.Comment; comment != "" {
sql += this.GenerateSQL(" comment=?", comment)
}
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 = commands[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) CompileModifyComment(bp *schema.Blueprint) []string {
return []string{this.GenerateSQL("ALTER TABLE ? COMMENT = ?", db.T(bp.GetTable()), db.V(bp.Comment))}
}
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)"
case "vector":
return this.GenerateSQL("VECTOR(?)", column.Length)
}
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()),
}
})
}