github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/sqlx/migration/enum.go (about) 1 package migration 2 3 import ( 4 "github.com/machinefi/w3bstream/pkg/depends/kit/enum" 5 "github.com/machinefi/w3bstream/pkg/depends/kit/sqlx" 6 "github.com/machinefi/w3bstream/pkg/depends/kit/sqlx/builder" 7 "github.com/machinefi/w3bstream/pkg/depends/x/typesx" 8 ) 9 10 type SqlMetaEnum struct { 11 TName string `db:"F_table_name,size=64"` 12 CName string `db:"F_column_name,size=64"` 13 Value int `db:"F_value"` 14 Type string `db:"F_type,size=255"` 15 Key string `db:"F_key,size=255"` 16 Label string `db:"F_label,size=255"` 17 } 18 19 func (*SqlMetaEnum) TableName() string { 20 return "t_sql_meta_enum" 21 } 22 23 func (*SqlMetaEnum) UniqueIndexes() builder.Indexes { 24 return builder.Indexes{"I_enum": {"TName", "CName", "Value"}} 25 } 26 27 func SyncEnum(db sqlx.DBExecutor) error { 28 tbl := builder.T((&SqlMetaEnum{}).TableName()).WithSchema(db.D().Schema) 29 30 dialect := db.Dialect() 31 32 builder.ScanDefToTable(tbl, &SqlMetaEnum{}) 33 34 tx := sqlx.NewTasks(db).With( 35 func(db sqlx.DBExecutor) error { 36 _, err := db.Exec(dialect.DropTable(tbl)) 37 return err 38 }, 39 ) 40 41 exprs := dialect.CreateTableIsNotExists(tbl) 42 for i := range exprs { 43 expr := exprs[i] 44 tx = tx.With(func(db sqlx.DBExecutor) error { 45 _, err := db.Exec(expr) 46 return err 47 }) 48 } 49 50 // insert values 51 stmt := builder.Insert().Into(tbl) 52 vals := make([]interface{}, 0) 53 cols := &builder.Columns{} 54 55 db.D().Tables.Range(func(table *builder.Table, idx int) { 56 table.Columns.Range(func(col *builder.Column, idx int) { 57 rv, ok := typesx.TryNew(col.ColumnType.Type) 58 if !ok { 59 return 60 } 61 enumValue, ok := rv.Interface().(enum.Enum) 62 if !ok { 63 return 64 } 65 for _, e := range enumValue.ConstValues() { 66 meta := &SqlMetaEnum{ 67 TName: table.Name, 68 CName: col.Name, 69 Type: e.TypeName(), 70 Value: e.Int(), 71 Key: e.String(), 72 Label: e.Label(), 73 } 74 fvs := builder.FieldValueFromStructByNoneZero(meta, "Value") 75 cs, vs := tbl.ColumnsAndValuesByFieldValues(fvs) 76 vals = append(vals, vs...) 77 cols = cs 78 } 79 }) 80 }) 81 82 if len(vals) > 0 { 83 stmt = stmt.Values(cols, vals...) 84 tx = tx.With(func(db sqlx.DBExecutor) error { 85 _, err := db.Exec(stmt) 86 return err 87 }) 88 } 89 90 return tx.Do() 91 }