func (db *Db) FindRefs(name string) []string { var ret []string = []string{sqlx.NameMapper(name)} for _, tbl := range db.Tables { if tbl.Name != name { continue } for _, fld := range tbl.Fields { if len(fld.Ref) <= 0 { continue } res := db.FindRefs(fld.Ref) for _, n := range res { if !util.StringInSlice(n, ret) { ret = append(ret, n) } } } } return ret }
func (db *Db) ApplyRebuilds() error { rNames := make([]string, 0) for _, tbl := range db.Tables { if tbl._rebuildorg != tbl._rebuildnew { rNames = append(rNames, db.FindRefs(tbl.Name)...) //log.Println(">>>>>>>>>>>>>>>>>>>>>>>>>", tbl.Name, tbl._rebuildorg, tbl._rebuildnew) } } if len(rNames) <= 0 { return nil } for { bChange := false for _, tbl := range db.Tables { if util.StringInSlice(sqlx.NameMapper(tbl.Name), rNames) { continue } refs := db.FindRefs(tbl.Name)[1:] //log.Println(">>>>>>>>>>>>>>>>>>>>>>>>>2", tbl.Name, refs) for _, n := range refs { if !util.StringInSlice(sqlx.NameMapper(tbl.Name), rNames) && util.StringInSlice(n, rNames) { rNames = append(rNames, sqlx.NameMapper(tbl.Name)) //log.Println(">>>>>>>>>>>>>>>>>>>>>>>>>3", n) bChange = true } } } if !bChange { break } } log.Println("!!!DB Rebuild Begin!!!", rNames) tx, err := db.Begin() if err != nil { return err } for _, tbl := range db.Tables { if !util.StringInSlice(sqlx.NameMapper(tbl.Name), rNames) { continue } err := db.RebuildTable(tbl.Name, tbl._rebuildorg, tbl._rebuildnew, tx, 0) if err != nil { tx.Rollback() return err } } for _, tbl := range db.Tables { if !util.StringInSlice(sqlx.NameMapper(tbl.Name), rNames) { continue } err := db.RebuildTable(tbl.Name, tbl._rebuildorg, tbl._rebuildnew, tx, 1) if err != nil { tx.Rollback() return err } } for _, tbl := range db.Tables { if !util.StringInSlice(sqlx.NameMapper(tbl.Name), rNames) { continue } err := db.RebuildTable(tbl.Name, tbl._rebuildorg, tbl._rebuildnew, tx, 2) if err != nil { tx.Rollback() return err } for _, fld := range tbl.Fields { if len(fld.Index) > 0 { _, err := db.DB.Exec(fld.Index) if err != nil { tx.Rollback() return err } } } } tx.Commit() db.DB.Exec("VACUUM;") log.Println("!!!DB Rebuild Successful!!!") return nil }