func update(engines *xorm.Engine, File *xlsx.Sheet) { var num int = 0 if len(File.Rows) < 1 { fmt.Println("检查更新列表.") return } for _, row := range File.Rows[1:] { var list []*xlsx.Cell for _, cell := range row.Cells { list = append(list, cell) } date := parse(list) if date != nil { n, err := engines.Where("IssuerId = ? and ServerID = ?", date.IssuerId, date.ServerID).MustCols("OnlineNum", "IsRuning", "ServerStyle", "IsStartIPWhile", "OrderBy").Update(date) if n == 0 || err != nil { fmt.Printf("更新:%s出错.\n", fmt.Sprint(*date)) continue } engines.Query(fmt.Sprintf("UPDATE NxServerState SET ServerName=N'%s' where IssuerId = %d and ServerID = %d", date.ServerName, date.IssuerId, date.ServerID)) } num++ } fmt.Printf("一共更新%d条数据\n", num) }
func generateOrgRandsAndSalt(x *xorm.Engine) (err error) { type User struct { ID int64 `xorm:"pk autoincr"` Rands string `xorm:"VARCHAR(10)"` Salt string `xorm:"VARCHAR(10)"` } orgs := make([]*User, 0, 10) if err = x.Where("type=1").And("rands=''").Find(&orgs); err != nil { return fmt.Errorf("select all organizations: %v", err) } sess := x.NewSession() defer sessionRelease(sess) if err = sess.Begin(); err != nil { return err } for _, org := range orgs { org.Rands = base.GetRandomString(10) org.Salt = base.GetRandomString(10) if _, err = sess.Id(org.ID).Update(org); err != nil { return err } } return sess.Commit() }
func Login(w http.ResponseWriter, r *http.Request, urlValues map[string]string, db *xorm.Engine) { //handle the input var input struct { Email string `json:"email" validate:"required"` Password string `json:"password" validate:"required"` } if err := httputil.Bind(r.Body, &input); err != nil { middleware.Send(w, http.StatusBadRequest, map[string]string{"error": err.Error()}) return } user := model.User{} found, err := db.Where("email = ?", input.Email).Get(&user) if err != nil { middleware.Send(w, http.StatusInternalServerError, map[string]string{"error": err.Error()}) return } if found == false || bcrypt.CompareHashAndPassword([]byte(user.PasswordDigest), []byte(input.Password)) != nil { middleware.Send(w, http.StatusUnauthorized, map[string]string{"error": "Incorrect Email / Password"}) return } if newToken, err := auth.Sign(user.Id); err != nil { middleware.Send(w, http.StatusInternalServerError, map[string]string{"error": err.Error()}) } else { // update JWT Token w.Header().Add("Authorization", newToken) //allow CORS w.Header().Set("Access-Control-Expose-Headers", "Authorization") middleware.Send(w, http.StatusOK, map[string]string{"userId": user.Id}) } }
func insert(engines *xorm.Engine, File *xlsx.Sheet) { var num int = 0 if len(File.Rows) < 1 { fmt.Println("检查更新列表.") return } for _, row := range File.Rows[1:] { var list []*xlsx.Cell for _, cell := range row.Cells { list = append(list, cell) } date := parse(list) if date != nil { b, err := engines.Where("IssuerId = ? and ServerID = ?", date.IssuerId, date.ServerID).Get(&NxServerState{}) if b { fmt.Println(*date, " 已存在") continue } n, err := engines.Insert(date) if n == 0 || err != nil { fmt.Printf("插入:%s出错.\n", fmt.Sprint(*date)) continue } engines.Query(fmt.Sprintf("UPDATE NxServerState SET ServerName=N'%s' where IssuerId = %d and ServerID = %d", date.ServerName, date.IssuerId, date.ServerID)) } num++ } fmt.Printf("一共插入%d条数据\n", num) }
func testLowerCase(engine *xorm.Engine, t *testing.T) { err := engine.Sync(&Lowercase{}) _, err = engine.Where("(id) > 0").Delete(&Lowercase{}) if err != nil { t.Error(err) panic(err) } _, err = engine.Insert(&Lowercase{ended: 1}) if err != nil { t.Error(err) panic(err) } ls := make([]Lowercase, 0) err = engine.Find(&ls) if err != nil { t.Error(err) panic(err) } if len(ls) != 1 { err = errors.New("should be 1") t.Error(err) panic(err) } }
//process post alipay return func AlipayReturn(ctx *macaron.Context, x *xorm.Engine) { m, _ := url.ParseQuery(ctx.Req.URL.RawQuery) params := map[string]string{} for k, v := range m { params[k] = v[0] } result := alipay.Return(params) type OrderInfo struct { Result bool OrderId string GoodId string GoodCnt int64 Tel string Name string Addr string Sum float32 } var orderInfo OrderInfo orderInfo.Result = false if result.Status == -1 || result.Status == -5 || result.Status == -3 { ctx.HTML(400, "orderresult", orderInfo) return } o := &Order{Uuid: result.OrderNo} has, err := x.Where("status=?", "等待支付").Get(o) if err != nil || !has { ctx.HTML(400, "orderresult", orderInfo) return } if result.Status != 1 { o.Status = "支付失败" x.Id(o.Id).Cols("status").Update(o) ctx.HTML(400, "orderresult", orderInfo) return } o.Status = "支付成功" _, err = x.Id(o.Id).Cols("status").Update(o) if err != nil { ctx.HTML(400, "orderresult", orderInfo) return } orderInfo.Result = true orderInfo.OrderId = o.CusTel + "_" + strconv.FormatInt(o.Id, 10) orderInfo.GoodId = strconv.FormatInt(o.GoodId, 10) orderInfo.GoodCnt = o.GoodCnt orderInfo.Tel = o.CusTel orderInfo.Name = o.CusName orderInfo.Addr = o.CusAddr orderInfo.Sum = o.Sum ctx.HTML(200, "orderresult", orderInfo) return }
func get(engine *xorm.Engine, t *testing.T) { user := Userinfo{Uid: 2} has, err := engine.Get(&user) if err != nil { t.Error(err) panic(err) } if has { fmt.Println(user) } else { fmt.Println("no record id is 2") } err = engine.Sync(&NoIdUser{}) if err != nil { t.Error(err) panic(err) } userCol := engine.ColumnMapper.Obj2Table("User") _, err = engine.Where("`"+userCol+"` = ?", "xlw").Delete(&NoIdUser{}) if err != nil { t.Error(err) panic(err) } cnt, err := engine.Insert(&NoIdUser{"xlw", 20, 100}) if err != nil { t.Error(err) panic(err) } if cnt != 1 { err = errors.New("insert not returned 1") t.Error(err) panic(err) } noIdUser := new(NoIdUser) has, err = engine.Where("`"+userCol+"` = ?", "xlw").Get(noIdUser) if err != nil { t.Error(err) panic(err) } if !has { err = errors.New("get not returned 1") t.Error(err) panic(err) } fmt.Println(noIdUser) }
func TestNullStructCount(engine *xorm.Engine, t *testing.T) { if true { item := new(NullType) total, err := engine.Where("age IS NOT NULL").Count(item) if err != nil { t.Error(err) panic(err) } fmt.Println(total) } }
func TestNullStructIterate(engine *xorm.Engine, t *testing.T) { if true { err := engine.Where("age IS NOT NULL").OrderBy("age").Iterate(new(NullType), func(i int, bean interface{}) error { nultype := bean.(*NullType) fmt.Println(i, nultype) return nil }) if err != nil { t.Error(err) panic(err) } } }
func TestNullStructDelete(engine *xorm.Engine, t *testing.T) { item := new(NullType) _, err := engine.Id(1).Delete(item) if err != nil { t.Error(err) panic(err) } _, err = engine.Where("id > ?", 1).Delete(item) if err != nil { t.Error(err) panic(err) } }
func getRecordWithUserIdDirect(out interface{}, id, userId string, db *xorm.Engine) (statusCode int, err error) { if _, err := uuid.FromString(id); err != nil { return http.StatusBadRequest, errUuidNotValid } found, err := db.Where("id = ? and user_id = ?", id, userId).Get(out) if err != nil { return http.StatusInternalServerError, err } if found == false { return http.StatusNotFound, errNotFound } return http.StatusOK, nil }
func where(engine *xorm.Engine, t *testing.T) { users := make([]Userinfo, 0) err := engine.Where("(id) > ?", 2).Find(&users) if err != nil { t.Error(err) panic(err) } fmt.Println(users) err = engine.Where("(id) > ?", 2).And("(id) < ?", 10).Find(&users) if err != nil { t.Error(err) panic(err) } fmt.Println(users) }
func cleanUpMigrateRepoInfo(x *xorm.Engine) (err error) { type ( User struct { ID int64 `xorm:"pk autoincr"` LowerName string } Repository struct { ID int64 `xorm:"pk autoincr"` OwnerID int64 LowerName string } ) repos := make([]*Repository, 0, 25) if err = x.Where("is_mirror=?", false).Find(&repos); err != nil { return fmt.Errorf("select all non-mirror repositories: %v", err) } var user *User for _, repo := range repos { user = &User{ID: repo.OwnerID} has, err := x.Get(user) if err != nil { return fmt.Errorf("get owner of repository[%d - %d]: %v", repo.ID, repo.OwnerID, err) } else if !has { continue } configPath := filepath.Join(setting.RepoRootPath, user.LowerName, repo.LowerName+".git/config") // In case repository file is somehow missing. if !com.IsFile(configPath) { continue } cfg, err := ini.Load(configPath) if err != nil { return fmt.Errorf("open config file: %v", err) } cfg.DeleteSection("remote \"origin\"") if err = cfg.SaveToIndent(configPath, "\t"); err != nil { return fmt.Errorf("save config file: %v", err) } } return nil }
func TestNullStructRows(engine *xorm.Engine, t *testing.T) { item := new(NullType) rows, err := engine.Where("id > ?", 1).Rows(item) if err != nil { t.Error(err) panic(err) } defer rows.Close() for rows.Next() { err = rows.Scan(item) if err != nil { t.Error(err) panic(err) } fmt.Println(item) } }
//process post alipay notify func AlipayNotify(ctx *macaron.Context, x *xorm.Engine) { // Read the content bodyString, err := ctx.Req.Body().String() if err != nil { ctx.Resp.Write([]byte("error")) return } result := alipay.Notify(bodyString) if result.Status == -2 { ctx.Resp.Write([]byte("error")) return } o := &Order{Uuid: result.OrderNo} has, err := x.Where("status=?", "等待支付").Get(o) if err != nil || !has { ctx.Resp.Write([]byte("error")) return } if result.Status != 1 { o.Status = "支付失败" x.Id(o.Id).Cols("status").Update(o) ctx.Resp.Write([]byte("error")) return } o.Status = "支付成功" _, err = x.Id(o.Id).Cols("status").Update(o) if err != nil { ctx.Resp.Write([]byte("error")) return } ctx.Resp.Write([]byte("success")) return }
func testCustomType2(engine *xorm.Engine, t *testing.T) { err := engine.CreateTables(&UserCus{}) if err != nil { t.Fatal(err) } engine.Exec("TRUNCATE TABLE " + engine.TableMapper.Obj2Table("UserCus")) _, err = engine.Insert(&UserCus{1, "xlw", Registed}) if err != nil { t.Fatal(err) } user := UserCus{} exist, err := engine.Id(1).Get(&user) if err != nil { t.Fatal(err) } if !exist { t.Fatal("user not exist") } fmt.Println(user) users := make([]UserCus, 0) err = engine.Where("`"+engine.ColumnMapper.Obj2Table("Status")+"` = ?", "Registed").Find(&users) if err != nil { t.Error(err) panic(err) } if len(users) != 1 { t.Error("users should has 1 record.") panic("") } fmt.Println(users) }
func testDeleted(engine *xorm.Engine, t *testing.T) { err := engine.DropTables(&Deleted{}) if err != nil { t.Error(err) panic(err) } err = engine.CreateTables(&Deleted{}) if err != nil { t.Error(err) panic(err) } _, err = engine.InsertOne(&Deleted{Id: 1, Name: "11111"}) if err != nil { t.Error(err) panic(err) } _, err = engine.InsertOne(&Deleted{Id: 2, Name: "22222"}) if err != nil { t.Error(err) panic(err) } _, err = engine.InsertOne(&Deleted{Id: 3, Name: "33333"}) if err != nil { t.Error(err) panic(err) } // Test normal Find() var records1 []Deleted err = engine.Where("`"+engine.ColumnMapper.Obj2Table("Id")+"` > 0").Find(&records1, &Deleted{}) if len(records1) != 3 { t.Fatalf("Find failed: expected=%d, actual=%d, err=%v", 3, len(records1), err) } // Test normal Get() record1 := &Deleted{} has, err := engine.Id(1).Get(record1) if !has { t.Fatalf("Get failed: expected=%v, actual=%v, err=%v", true, has, err) } //fmt.Println("----- get:", record1) // Test Delete() with deleted affected, err := engine.Id(1).Delete(&Deleted{}) if affected != 1 { t.Fatalf("Delete failed: expected=%v, actual=%v, err=%v", 1, affected, err) } has, err = engine.Id(1).Get(&Deleted{}) if has { t.Fatalf("Delete failed. Must not get any records.") } var records2 []Deleted err = engine.Where("`" + engine.ColumnMapper.Obj2Table("Id") + "` > 0").Find(&records2) if len(records2) != 2 { t.Fatalf("Find() failed.") } // Test no rows affected after Delete() again. affected, err = engine.Id(1).Delete(&Deleted{}) if affected != 0 { t.Fatalf("Delete failed. No rows must be affected: expected=%v, actual=%v, err=%v", 0, affected, err) } // Deleted.DeletedAt must not be updated. affected, err = engine.Id(2).Update(&Deleted{Name: "2", DeletedAt: time.Now()}) if affected != 1 { t.Fatalf("Update failed: expected=%v, actual=%v, err=%v", 1, affected, err) } record2 := &Deleted{} has, err = engine.Id(2).Get(record2) if !record2.DeletedAt.IsZero() { t.Fatalf("Update failed: DeletedAt must be zero value. actual=%v", record2.DeletedAt) } // Test find all records whatever `deleted`. var unscopedRecords1 []Deleted err = engine.Unscoped().Where("`"+engine.ColumnMapper.Obj2Table("Id")+"` > 0").Find(&unscopedRecords1, &Deleted{}) if len(unscopedRecords1) != 3 { fmt.Printf("unscopedRecords1 = %v\n", unscopedRecords1) t.Fatalf("Find failed: all records must be selected when engine.Unscoped()") } // Delete() must really delete a record with Unscoped() affected, err = engine.Unscoped().Id(1).Delete(&Deleted{}) if affected != 1 { t.Fatalf("Delete failed") } var unscopedRecords2 []Deleted err = engine.Unscoped().Where("`"+engine.ColumnMapper.Obj2Table("Id")+"` > 0").Find(&unscopedRecords2, &Deleted{}) if len(unscopedRecords2) != 2 { t.Fatalf("Find failed: Only 2 records must be selected when engine.Unscoped()") } var records3 []Deleted err = engine.Where("`"+engine.ColumnMapper.Obj2Table("Id")+"` > 0").And("`"+engine.ColumnMapper.Obj2Table("Id")+"`> 1"). Or("`"+engine.ColumnMapper.Obj2Table("Id")+"` = ?", 3).Find(&records3) if len(records3) != 2 { t.Fatalf("Find failed: expected=%d, actual=%d, err=%v", 2, len(records3), err) } }
func in(engine *xorm.Engine, t *testing.T) { var usrs []Userinfo err := engine.Limit(3).Find(&usrs) if err != nil { t.Error(err) panic(err) } if len(usrs) != 3 { err = errors.New("there are not 3 records") t.Error(err) panic(err) } var ids []int64 var idsStr string for _, u := range usrs { ids = append(ids, u.Uid) idsStr = fmt.Sprintf("%d,", u.Uid) } idsStr = idsStr[:len(idsStr)-1] users := make([]Userinfo, 0) err = engine.In("(id)", ids[0], ids[1], ids[2]).Find(&users) if err != nil { t.Error(err) panic(err) } fmt.Println(users) if len(users) != 3 { err = errors.New("in uses should be " + idsStr + " total 3") t.Error(err) panic(err) } users = make([]Userinfo, 0) err = engine.In("(id)", ids).Find(&users) if err != nil { t.Error(err) panic(err) } fmt.Println(users) if len(users) != 3 { err = errors.New("in uses should be " + idsStr + " total 3") t.Error(err) panic(err) } for _, user := range users { if user.Uid != ids[0] && user.Uid != ids[1] && user.Uid != ids[2] { err = errors.New("in uses should be " + idsStr + " total 3") t.Error(err) panic(err) } } users = make([]Userinfo, 0) var idsInterface []interface{} for _, id := range ids { idsInterface = append(idsInterface, id) } department := engine.ColumnMapper.Obj2Table("Departname") err = engine.Where("`"+department+"` = ?", "dev").In("(id)", idsInterface...).Find(&users) if err != nil { t.Error(err) panic(err) } fmt.Println(users) if len(users) != 3 { err = errors.New("in uses should be " + idsStr + " total 3") t.Error(err) panic(err) } for _, user := range users { if user.Uid != ids[0] && user.Uid != ids[1] && user.Uid != ids[2] { err = errors.New("in uses should be " + idsStr + " total 3") t.Error(err) panic(err) } } dev := engine.ColumnMapper.Obj2Table("Dev") err = engine.In("(id)", 1).In("(id)", 2).In(department, dev).Find(&users) if err != nil { t.Error(err) panic(err) } fmt.Println(users) cnt, err := engine.In("(id)", ids[0]).Update(&Userinfo{Departname: "dev-"}) if err != nil { t.Error(err) panic(err) } if cnt != 1 { err = errors.New("update records not 1") t.Error(err) panic(err) } user := new(Userinfo) has, err := engine.Id(ids[0]).Get(user) if err != nil { t.Error(err) panic(err) } if !has { err = errors.New("get record not 1") t.Error(err) panic(err) } if user.Departname != "dev-" { err = errors.New("update not success") t.Error(err) panic(err) } cnt, err = engine.In("(id)", ids[0]).Update(&Userinfo{Departname: "dev"}) if err != nil { t.Error(err) panic(err) } if cnt != 1 { err = errors.New("update records not 1") t.Error(err) panic(err) } cnt, err = engine.In("(id)", ids[1]).Delete(&Userinfo{}) if err != nil { t.Error(err) panic(err) } if cnt != 1 { err = errors.New("deleted records not 1") t.Error(err) panic(err) } }
func in(engine *xorm.Engine, t *testing.T) { users := make([]Userinfo, 0) err := engine.In("(id)", 7, 8, 9).Find(&users) if err != nil { t.Error(err) panic(err) } fmt.Println(users) if len(users) != 3 { err = errors.New("in uses should be 7,8,9 total 3") t.Error(err) panic(err) } users = make([]Userinfo, 0) err = engine.In("(id)", []int{7, 8, 9}).Find(&users) if err != nil { t.Error(err) panic(err) } fmt.Println(users) if len(users) != 3 { err = errors.New("in uses should be 7,8,9 total 3") t.Error(err) panic(err) } for _, user := range users { if user.Uid != 7 && user.Uid != 8 && user.Uid != 9 { err = errors.New("in uses should be 7,8,9 total 3") t.Error(err) panic(err) } } users = make([]Userinfo, 0) ids := []interface{}{7, 8, 9} department := engine.ColumnMapper.Obj2Table("Departname") err = engine.Where("`"+department+"` = ?", "dev").In("(id)", ids...).Find(&users) if err != nil { t.Error(err) panic(err) } fmt.Println(users) if len(users) != 3 { err = errors.New("in uses should be 7,8,9 total 3") t.Error(err) panic(err) } for _, user := range users { if user.Uid != 7 && user.Uid != 8 && user.Uid != 9 { err = errors.New("in uses should be 7,8,9 total 3") t.Error(err) panic(err) } } dev := engine.ColumnMapper.Obj2Table("Dev") err = engine.In("(id)", 1).In("(id)", 2).In(department, dev).Find(&users) if err != nil { t.Error(err) panic(err) } fmt.Println(users) cnt, err := engine.In("(id)", 4).Update(&Userinfo{Departname: "dev-"}) if err != nil { t.Error(err) panic(err) } if cnt != 1 { err = errors.New("update records not 1") t.Error(err) panic(err) } user := new(Userinfo) has, err := engine.Id(4).Get(user) if err != nil { t.Error(err) panic(err) } if !has { err = errors.New("get record not 1") t.Error(err) panic(err) } if user.Departname != "dev-" { err = errors.New("update not success") t.Error(err) panic(err) } cnt, err = engine.In("(id)", 4).Update(&Userinfo{Departname: "dev"}) if err != nil { t.Error(err) panic(err) } if cnt != 1 { err = errors.New("update records not 1") t.Error(err) panic(err) } cnt, err = engine.In("(id)", 5).Delete(&Userinfo{}) if err != nil { t.Error(err) panic(err) } if cnt != 1 { err = errors.New("deleted records not 1") t.Error(err) panic(err) } }
func TestNullStructUpdate(engine *xorm.Engine, t *testing.T) { if true { // 测试可插入NULL item := new(NullType) item.Age = sql.NullInt64{23, true} item.Height = sql.NullFloat64{0, false} // update to NULL affected, err := engine.Id(2).Cols("height", "is_man").Update(item) if err != nil { t.Error(err) panic(err) } if affected != 1 { err := errors.New("update failed") t.Error(err) panic(err) } } if true { // 测试In update item := new(NullType) affected, err := engine.In("id", 3, 4).Cols("height", "is_man").Update(item) if err != nil { t.Error(err) panic(err) } if affected != 2 { err := errors.New("update failed") t.Error(err) panic(err) } } if true { // 测试where item := new(NullType) item.Name = sql.NullString{"nullname", true} item.IsMan = sql.NullBool{true, true} item.Age = sql.NullInt64{34, true} _, err := engine.Where("age > ?", 34).Update(item) if err != nil { t.Error(err) panic(err) } } if true { // 修改全部时,插入空值 item := &NullType{ Name: sql.NullString{"winxxp", true}, Age: sql.NullInt64{30, true}, Height: sql.NullFloat64{1.72, true}, // IsMan: sql.NullBool{true, true}, } _, err := engine.AllCols().Id(6).Update(item) if err != nil { t.Error(err) panic(err) } fmt.Println(item) } }