//HandlePanic rolls back the transiction provided and then panics again. func (self *QbsDefaultOrmTransactionPolicy) HandlePanic(tx *qbs.Qbs, err interface{}) (interface{}, error) { log.Printf("got panic, rolling back and returning 500 to client (%v)\n", err) if rerr := tx.Rollback(); rerr != nil { panic(rerr) } return nil, HTTPError(http.StatusInternalServerError, fmt.Sprintf("panic: %v", err)) }
func updateImportInfo(q *qbs.Qbs, path string, pid int, add bool) { // Save package information. info := new(PkgInfo) err := q.WhereEqual("path", path).Find(info) if err == nil { // Check if pid exists in this project. i := strings.Index(info.ImportPid, "$"+strconv.Itoa(pid)+"|") switch { case i == -1 && add: // Add operation and does not contain. info.ImportPid += "$" + strconv.Itoa(pid) + "|" info.ImportedNum++ _, err = q.Save(info) if err != nil { beego.Error("models.updateImportInfo(): add:", path, err) } case i > -1 && !add: // Delete operation and contains. info.ImportPid = strings.Replace(info.ImportPid, "$"+strconv.Itoa(pid)+"|", "", 1) info.ImportedNum-- if err != nil { beego.Error("models.updateImportInfo(): delete:", path, err) } } } // Error means this project does not exist, simply skip. }
func UpdateMultipleUsers(q *qbs.Qbs) (affected int64, err error) { type User struct { Name string } user := new(User) user.Name = "Blue" return q.WhereEqual("name", "Green").Update(user) }
//保存 func (this *Episode) Save(q *qbs.Qbs) bool { _, err := q.Save(this) if err != nil { fmt.Println(err) return false } return true }
func FindUserByCondition(q *qbs.Qbs) (*User, error) { user := new(User) condition1 := qbs.NewCondition("id > ?", 100).Or("id < ?", 50).OrEqual("id", 75) condition2 := qbs.NewCondition("name != ?", "Red").And("name != ?", "Black") condition1.AndCondition(condition2) err := q.Condition(condition1).Find(user) return user, err }
func UpdateOneUser(q *qbs.Qbs, id int64, name string) (affected int64, err error) { user, err := FindUserById(q, id) if err != nil { return 0, err } user.Name = name return q.Save(user) }
//保存 func (p *Person) Save(q *qbs.Qbs) bool { _, err := q.Save(p) if err != nil { fmt.Println(err) return false } return true }
//StartTransaction returns a new qbs object after creating the transaction. func (self *QbsDefaultOrmTransactionPolicy) StartTransaction(q *qbs.Qbs) *qbs.Qbs { if err := q.Begin(); err != nil { if err.Error() == "EOF" { log.Printf("It's likely there is something listening on your server port that isn't the database you expected.") } panic(err) } return q }
//更新 func (p *Person) update(person Person, q *qbs.Qbs) bool { _, err := q.Update(person) if err != nil { fmt.Println(err) return false } return true }
func PrintTable(q *qbs.Qbs) { var users []*User q.FindAll(&users) for _, user := range users { fmt.Printf("%+v,", user) } fmt.Println() }
//保存 func (u *User) Save(q *qbs.Qbs) bool { if u.Password != "" { //u.HashedPassword = EncryptPassword(u.Password) } _, err := q.Save(u) if err != nil { fmt.Println(err) return false } return true }
func (self *testObjUdid) PostQbs(value interface{}, pb PBundle, q *qbs.Qbs) (interface{}, error) { self.testCallCount++ in := value.(*HouseWireUdid) house := &HouseUdid{Id: in.Id, Address: in.Addr, Zip: in.ZipCode} if house.Id == "" { house.Id = UDID() } if _, err := q.Save(house); err != nil { return nil, err } return &HouseWireUdid{Id: house.Id, Addr: house.Address, ZipCode: house.Zip}, nil }
func getGroupPkgInfoWithQ(q *qbs.Qbs, paths []string) []*hv.PkgInfo { pinfos := make([]*hv.PkgInfo, 0, len(paths)) for _, v := range paths { if len(v) > 0 { pinfo := new(hv.PkgInfo) err := q.WhereEqual("import_path", v).Find(pinfo) if err == nil { pinfos = append(pinfos, pinfo) } else { pinfos = append(pinfos, &hv.PkgInfo{ImportPath: v}) } } } return pinfos }
func getGroupPkgInfoByIdWithQ(q *qbs.Qbs, pids []string) []*hv.PkgInfo { pinfos := make([]*hv.PkgInfo, 0, len(pids)) for _, v := range pids { pid, _ := strconv.ParseInt(v, 10, 64) if pid > 0 { pinfo := new(hv.PkgInfo) err := q.WhereEqual("id", pid).Find(pinfo) if err == nil { pinfos = append(pinfos, pinfo) } else { beego.Trace("models.GetGroupPkgInfoById ->", err) } } } return pinfos }
func calRefRanks(q *qbs.Qbs, refPids []string) int64 { refRank := 0 for _, spid := range refPids { pid, _ := strconv.Atoi(spid) if pid == 0 { continue } info := new(hv.PkgInfo) err := q.WhereEqual("id", pid).Find(info) if err == nil { refRank += int(info.Rank) * 10 / 100 } else { beego.Trace("models.calRefRanks ->", err) } } return int64(refRank) }
//分页查询 func GetEpisodes(q *qbs.Qbs, page int, column string, value interface{}, order string, url string) ([]*Episode, *Pagination) { page -= 1 if page < 0 { page = 0 } var episode []*Episode var rows int64 if column == "" { fmt.Println(ItemsPerPage) fmt.Println(page) rows = q.Count("episode") err := q.OrderByDesc(order). Limit(ItemsPerPage).Offset(page * ItemsPerPage).FindAll(&episode) if err != nil { fmt.Println(err) } } else { rows = q.WhereEqual(column, value).Count("episode") err := q.WhereEqual(column, value).OrderByDesc(order). Limit(ItemsPerPage).Offset(page * ItemsPerPage).FindAll(&episode) if err != nil { fmt.Println(err) } } fmt.Println(episode) url = url[:strings.Index(url, "=")+1] pagination := NewPagination(page, int(rows), url) return episode, pagination }
func (self *testObj) PostQbs(value interface{}, pb PBundle, q *qbs.Qbs) (interface{}, error) { self.testCallCount++ in := value.(*HouseWire) house := &House{Address: in.Addr, Zip: in.ZipCode} if _, err := q.Save(house); err != nil { return nil, err } //simulate an error AFTER the save! switch self.failPost { case force_panic: panic("testing panic handling") case force_error: return nil, errors.New("testing error handling") } return &HouseWire{Id: house.Id, Addr: house.Address, ZipCode: house.Zip}, nil }
// checkImport returns true if the package(id) imports given package(path). func checkImport(q *qbs.Qbs, path string, id int64) bool { pinfo := &PkgInfo{ Id: id, } err := q.Find(pinfo) if err != nil { return false } decl := new(PkgDecl) cond := qbs.NewCondition("pid = ?", pinfo.Id).And("tag = ?", "") err = q.Condition(cond).Find(decl) if err != nil { return false } if strings.Index(decl.Imports, path) == -1 { return false } return true }
func main() { var ( q *qbs.Qbs user *User ) q = SetupDb() defer q.Close() profile := &Profile{Homepage: "www.example.com", Interests: "Golang", Id: 1} q.Save(profile) q.Save(&User{Id: 1, FirstName: "John", LastName: "Doe", Age: 25, ProfileId: 1}) //START CODE OMIT user = &User{Id: 1} q.Find(user) fmt.Printf("%+v\n", user) fmt.Printf("%+v\n", user.Profile) //END CODE OMIT }
func getPkgInfoWithQ(path, tag string, q *qbs.Qbs) (*hv.PkgInfo, error) { // Check path length to reduce connect times. if len(path) == 0 { return nil, errors.New("models.getPkgInfoWithQ -> Empty path as not found.") } pinfo := new(hv.PkgInfo) q.WhereEqual("import_path", path).Find(pinfo) proPath := utils.GetProjectPath(path) if utils.IsGoRepoPath(path) { proPath = "code.google.com/p/go" } beego.Trace("models.getPkgInfoWithQ -> proPath:", proPath) ptag := new(PkgTag) cond := qbs.NewCondition("path = ?", proPath).And("tag = ?", tag) err := q.Condition(cond).Find(ptag) if err != nil { pinfo.Ptag = "ptag" return pinfo, errors.New( fmt.Sprintf("models.getPkgInfoWithQ( %s:%s ) -> 'PkgTag': %s", path, tag, err)) } pinfo.Vcs = ptag.Vcs pinfo.Tags = ptag.Tags // Only 'PkgInfo' cannot prove that package exists, // we have to check 'PkgDecl' as well in case it was deleted by mistake. pdecl := new(PkgDecl) cond = qbs.NewCondition("pid = ?", pinfo.Id).And("tag = ?", tag) err = q.Condition(cond).Find(pdecl) if err != nil { // Basically, error means not found, so we set 'pinfo.PkgVer' to 0 // because server uses it to decide whether force update. pinfo.PkgVer = 0 pinfo.Ptag = "ptag" return pinfo, errors.New( fmt.Sprintf("models.getPkgInfoWithQ( %s:%s ) -> 'PkgDecl': %s", path, tag, err)) } docPath := path + utils.TagSuffix("-", tag) if !com.IsExist("." + utils.DocsJsPath + docPath + ".js") { pinfo.PkgVer = 0 pinfo.Ptag = "ptag" return pinfo, errors.New( fmt.Sprintf("models.getPkgInfoWithQ( %s:%s ) -> JS: File not found", path, tag)) } return pinfo, nil }
//HandleResult determines whether or not the transaction provided should be rolled //back or if it should be committed. It rolls back when the result value is //a non-http error, if it is an Error and the status code is >= 400. func (self *QbsDefaultOrmTransactionPolicy) HandleResult(tx *qbs.Qbs, value interface{}, err error) (interface{}, error) { if err != nil { switch e := err.(type) { case *Error: if e.StatusCode >= 400 { rerr := tx.Rollback() if rerr != nil { return nil, rerr } } default: rerr := tx.Rollback() if rerr != nil { return nil, rerr } return nil, HTTPError(http.StatusInternalServerError, fmt.Sprintf("%v", err)) } } else { if cerr := tx.Commit(); cerr != nil { return nil, cerr } } return value, err }
/* * 通过用户编号获得人员信息 * @param userId 用户编号 * @return person */ func (p *Person) findPersonByUserId(userId string, q *qbs.Qbs) *Person { person := new(Person) q.WhereEqual("user_id", userId).Find(person) return person }
//查询验证码是否存在 func FindUserByCode(q *qbs.Qbs, code string) *models.User { user := new(models.User) q.WhereEqual("validate_code", code).Find(user) return user }
func FindUsers(q *qbs.Qbs) ([]*User, error) { var users []*User err := q.Limit(10).Offset(10).FindAll(&users) return users, err }
func FindUserByName(q *qbs.Qbs, n string) (*User, error) { user := new(User) err := q.WhereEqual("name", n).Find(user) return user, err }
func FindUserById(q *qbs.Qbs, id int64) (*User, error) { user := new(User) user.Id = id err := q.Find(user) return user, err }
func CreateUser(q *qbs.Qbs) (*User, error) { user := new(User) user.Name = "Green" _, err := q.Save(user) return user, err }
func FindPostsOmitJoin(q *qbs.Qbs) ([]*Post, error) { var posts []*Post err := q.OmitJoin().OmitFields("Content").Find(&posts) return posts, err }
func FindPostsOmitContentAndCreated(q *qbs.Qbs) ([]*Post, error) { var posts []*Post err := q.OmitFields("Content", "Created").Find(&posts) return posts, err }
func DeleteUser(q *qbs.Qbs, id int64) (affected int64, err error) { user := new(User) user.Id = id return q.Delete(user) }