github.com/eden-framework/sqlx@v0.0.2/enummeta/sync_enum.go (about)

     1  package enummeta
     2  
     3  import (
     4  	"github.com/eden-framework/enumeration"
     5  	"reflect"
     6  
     7  	"github.com/eden-framework/sqlx"
     8  	"github.com/eden-framework/sqlx/builder"
     9  )
    10  
    11  func SyncEnum(db sqlx.DBExecutor) error {
    12  	metaEnumTable := builder.T((&SqlMetaEnum{}).TableName())
    13  	builder.ScanDefToTable(reflect.ValueOf(&SqlMetaEnum{}), metaEnumTable)
    14  
    15  	dialect := db.Dialect()
    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  				v := reflect.New(col.ColumnType.Type).Interface()
    44  				if enumValue, ok := v.(enumeration.EnumTypeDescriber); ok {
    45  					for value, enum := range enumValue.Enums() {
    46  						sqlMetaEnum := &SqlMetaEnum{
    47  							TName: table.Name,
    48  							CName: col.Name,
    49  							Value: value,
    50  							Type:  enumValue.EnumType(),
    51  						}
    52  
    53  						if len(enum) > 0 {
    54  							sqlMetaEnum.Key = enum[0]
    55  						}
    56  
    57  						if len(enum) > 1 {
    58  							sqlMetaEnum.Label = enum[1]
    59  						}
    60  
    61  						fieldValues := builder.FieldValuesFromStructByNonZero(sqlMetaEnum, "Value")
    62  						cols, values := metaEnumTable.ColumnsAndValuesByFieldValues(fieldValues)
    63  						vals = append(vals, values...)
    64  						columns = cols
    65  					}
    66  				}
    67  			})
    68  		})
    69  
    70  		if len(vals) > 0 {
    71  			stmtForInsert = stmtForInsert.Values(columns, vals...)
    72  
    73  			task = task.With(func(db sqlx.DBExecutor) error {
    74  				_, err := db.ExecExpr(stmtForInsert)
    75  				return err
    76  			})
    77  		}
    78  	}
    79  
    80  	return task.Do()
    81  }