github.com/kunlun-qilian/sqlx/v3@v3.0.0/enummeta/sync_enum.go (about)

     1  package enummeta
     2  
     3  import (
     4  	"github.com/go-courier/enumeration"
     5  	typex "github.com/go-courier/x/types"
     6  	"github.com/kunlun-qilian/sqlx/v3"
     7  	"github.com/kunlun-qilian/sqlx/v3/builder"
     8  )
     9  
    10  func SyncEnum(db sqlx.DBExecutor) error {
    11  	metaEnumTable := builder.T((&SqlMetaEnum{}).TableName())
    12  
    13  	dialect := db.Dialect()
    14  
    15  	builder.ScanDefToTable(metaEnumTable, &SqlMetaEnum{})
    16  
    17  	task := sqlx.NewTasks(db.WithSchema(""))
    18  
    19  	task = task.With(func(db sqlx.DBExecutor) error {
    20  		_, err := db.ExecExpr(dialect.DropTable(metaEnumTable))
    21  		return err
    22  	})
    23  
    24  	exprs := dialect.CreateTableIsNotExists(metaEnumTable)
    25  
    26  	for i := range exprs {
    27  		expr := exprs[i]
    28  		task = task.With(func(db sqlx.DBExecutor) error {
    29  			_, err := db.ExecExpr(expr)
    30  			return err
    31  		})
    32  	}
    33  
    34  	{
    35  		// insert values
    36  		stmtForInsert := builder.Insert().Into(metaEnumTable)
    37  		vals := make([]interface{}, 0)
    38  
    39  		columns := &builder.Columns{}
    40  
    41  		db.D().Tables.Range(func(table *builder.Table, idx int) {
    42  			table.Columns.Range(func(col *builder.Column, idx int) {
    43  				if rv, ok := typex.TryNew(col.ColumnType.Type); ok {
    44  					if enumValue, ok := rv.Interface().(enumeration.Enum); ok {
    45  						for _, enum := range enumValue.ConstValues() {
    46  							sqlMetaEnum := &SqlMetaEnum{
    47  								TName: table.Name,
    48  								CName: col.Name,
    49  								Type:  enum.TypeName(),
    50  								Value: enum.Int(),
    51  								Key:   enum.String(),
    52  								Label: enum.Label(),
    53  							}
    54  							fieldValues := builder.FieldValuesFromStructByNonZero(sqlMetaEnum, "Value")
    55  							cols, values := metaEnumTable.ColumnsAndValuesByFieldValues(fieldValues)
    56  							vals = append(vals, values...)
    57  							columns = cols
    58  						}
    59  					}
    60  				}
    61  			})
    62  		})
    63  
    64  		if len(vals) > 0 {
    65  			stmtForInsert = stmtForInsert.Values(columns, vals...)
    66  
    67  			task = task.With(func(db sqlx.DBExecutor) error {
    68  				_, err := db.ExecExpr(stmtForInsert)
    69  				return err
    70  			})
    71  		}
    72  	}
    73  
    74  	return task.Do()
    75  }