func (u *User) SignUp(db *gorp.DbMap, s SmsSender, firstname, lastname, phone, password string) error { u.FirstName = firstname u.LastName = lastname u.Phone = phone u.HashedPassword, _ = bcrypt.GenerateFromPassword( []byte(password), bcrypt.DefaultCost) _, err := db.Update(u) if err != nil { return err } conf, err := generateConfirmation(db, u.Id) if err != nil { return err } message := fmt.Sprintf("You code %d. Session %d.", conf.Code, conf.Id) err = s.Send(phone, message) if err != nil { return err } return nil }
func Edit(db *gorp.DbMap, w WikiPage) (WikiPage, bool) { if w.Id == 0 { db.Insert(&w) } else { wOld, ok := GetBySlug(db, w.Title) if !ok { return WikiPage{}, false } textOld := string(wOld.Body) textNew := string(w.Body) d := diffmatchpatch.New() b := d.DiffMain(textNew, textOld, false) dl := d.DiffToDelta(b) delta := WikiDelta{ ItemId: w.Id, PrevDelta: w.PrevDelta, Delta: []byte(dl), } db.Insert(&delta) w.PrevDelta = delta.Id db.Update(&w) } return w, true }
func insertOrUpdateContact(dbmap *gorp.DbMap, user, contactid, contactname, group string) error { var contacts []Contact _, err := dbmap.Select(&contacts, "SELECT * FROM contacts WHERE User=? AND ContactId=?", user, contactid) if err != nil { return err } if len(contacts) == 0 { contact := Contact{ User: user, ContactId: contactid, ContactName: contactname, Group: group, } err = dbmap.Insert(&contact) if err != nil { return err } } else if len(contacts) == 1 { contact := contacts[0] contact.ContactName = contactname contact.Group = group _, err = dbmap.Update(&contact) if err != nil { return err } } else { return errors.New("You have more than one contacts") } return nil }
func (u *User) NewPassword(db *gorp.DbMap, password string) error { u.HashedPassword, _ = bcrypt.GenerateFromPassword( []byte(password), bcrypt.DefaultCost) u.Updated = time.Now().UnixNano() _, err := db.Update(u) return err }
func hostState(msg Message, gameId string, playerId int, gs GameService, ws *websocket.Conn, db *gorp.DbMap, log *log.Logger) error { log.Printf("Got state change request from host: %v", msg["state"]) game, _, err := gs.GetGame(db, gameId, playerId) if err != nil { log.Printf("%#v", err) return err } // TODO: check to make sure this is a valid state game.State = msg["state"].(string) var board *TicTacToe_Board if game.State == "start" { board = &TicTacToe_Board{Game: gameId} log.Printf("Setting up starting objects") // we are starting a game, so insert a new board err = board.setBoard([]int{0, 0, 0, 0, 0, 0, 0, 0, 0}) if err != nil { log.Printf("Unable to set game board: %#v", err) return err } log.Printf("Inserting board: %#v", board) err = db.Insert(board) if err != nil { log.Printf("Couldn't insert board: %#v", err) return err } } else { board, err = getBoard(gameId, db) if err != nil { log.Printf("Unable to get board: %#v", err) return err } } log.Printf("Updating game state to %#v", game.State) count, err := db.Update(game) if err != nil || count == 0 { log.Printf("Unable to change game state: %v", err) return err } niceBoard, err := board.getBoard() if err != nil { log.Printf("Error getting board: %#v", board) return err } log.Printf("Sending state %v to all players", msg["state"]) gs.Broadcast(gameId, Message{ "type": "update", "board": niceBoard, "state": "start", }) log.Printf("Updating UI") ws.WriteJSON(Message{ "type": "update", "board": niceBoard, "state": "start", }) return nil }
func Update(db *gorp.DbMap, c ChangeLog) error { old, err := Get(db, c.Id) if err != nil { return err } old.Updated = time.Now().UTC().UnixNano() old.Body = c.Body old.Title = c.Title _, err = db.Update(&old) return err }
// Currently there's no way to only update specific columns, update maps struct fields to table :( // https://github.com/coopernurse/gorp/issues/92 func ProductsUpdate(product models.Product, db *gorp.DbMap, params martini.Params, render render.Render) { id, _ := strconv.ParseInt(params["id"], 0, 64) product.Id = id _, err := db.Update(&product) if err == nil { render.JSON(200, product) } else { render.JSON(422, err.Error()) } }
func Update(db *gorp.DbMap, u User) error { t := time.Now().UnixNano() ou, err := Get(db, u.Id) if err != nil { return err } ou.FirstName = u.FirstName ou.LastName = u.LastName ou.Patronymic = u.Patronymic ou.Updated = t _, err = db.Update(&ou) return err }
func UpdateNew(db *gorp.DbMap, n New) error { oldnew, err := GetNew(db, n.Id) if err != nil { return err } n.Created = oldnew.Created n.Version = oldnew.Version n.Slug = oldnew.Slug t := time.Now().UTC().UnixNano() n.Updated = t _, err = db.Update(&n) return err }
func (network *Network) Persist(db *gorp.DbMap) error { if len(network.UUID) == 0 { obj := GetNetwork(map[string]interface{}{"dbmap": db}, map[string]interface{}{"name": network.Name}) if obj == nil { uuid, _ := uuid.NewV4() network.UUID = uuid.String() db.Insert(network) } else { network.UUID = obj.UUID db.Update(network) } } else { db.Update(network) } for _, address := range network.Addresses { if len(address.DeviceUUID) == 0 { address.DeviceUUID = network.UUID } if address.DeviceAddressID == 0 { db.Insert(address) } else { db.Update(address) } } for _, option := range network.Options { option.DeviceUUID = network.UUID if option.DeviceOptionID == 0 { db.Insert(option) } else { db.Update(option) } } for _, physical := range network.Physicals { if len(physical.NetworkUUID) == 0 { physical.NetworkUUID = network.UUID } if physical.NetworkPhysicalID == 0 { db.Insert(physical) } else { db.Update(physical) } } return nil }
func (jail *Jail) Persist(db *gorp.DbMap) error { insert := false if len(jail.UUID) == 0 { insert = true count := 0 db.Select(&count, "select count(UUID) from Jail where Name = ?", jail.Name) if count > 0 { return fmt.Errorf("Jail with name %s already exists", jail.Name) } } if err := jail.Validate(); err != nil { return err } if insert { db.Insert(jail) } else { db.Update(jail) } for _, device := range jail.NetworkDevices { device.VmUUID = jail.UUID if err := device.Persist(db, jail); err != nil { return err } } for _, mount := range jail.Mounts { if mount.MountPointID == 0 { mount.JailUUID = jail.UUID db.Insert(mount) } else { db.Update(mount) } } for _, option := range jail.Options { if option.OptionID == 0 { option.JailUUID = jail.UUID db.Insert(option) } else { db.Update(option) } } for _, route := range jail.Routes { if route.RouteID == 0 { route.VmUUID = jail.UUID db.Insert(route) } else { db.Update(route) } } return nil }
func VisitPage(Db *gorp.DbMap, fullurl string, body []byte, code int) error { res := SitePage{} var err error fullurl = n(fullurl) u, _ := url.Parse(fullurl) if !IsExistSite(Db, fullurl) { _, err = AddSite(Db, fullurl) if err != nil { return err } } if !IsExistPage(Db, fullurl) { res.Url = u.RequestURI() res.Error = int64(code) res.Body = gz.Gz(string(body)) res.Visited = time.Now().UnixNano() site, err := GetSite(Db, fullurl) if err != nil { return err } res.SiteId = site.Id err = Db.Insert(&res) if err != nil { return err } return nil } else { res, err = GetPage(Db, fullurl) if err != nil { return err } } res.Error = int64(code) res.Body = gz.Gz(string(body)) res.Visited = time.Now().UnixNano() _, err = Db.Update(&res) return err }
func (gs *GameServiceImpl) ConnectToGame(db *gorp.DbMap, gameId string, playerObj interface{}) (*Game, *Player, error) { obj, err := db.Get(Game{}, gameId) if err != nil { return nil, nil, err } if obj == nil { return nil, nil, errors.New("Player not saved to session") } game := obj.(*Game) var player *Player if playerObj == nil { // no, it's a new player player = &Player{ Game: game.Id, } // save to db so we can find them if they disconnect err = db.Insert(player) if err != nil { return nil, nil, err } } else { // player is rejoining playerObj, err := db.Get(Player{}, playerObj) if err != nil { return nil, nil, err } player = playerObj.(*Player) // TODO: this would screw with any games they are currently already in? if player.Game != game.Id { player.Game = game.Id count, err := db.Update(player) if count == 0 { return nil, nil, errors.New("Player update effected 0 rows") } if err != nil { return nil, nil, err } log.Printf("Joining player id is: %#v", player.Id) } else { log.Printf("Returning player id is: %#v", player.Id) } } return game, player, nil }
func (u *User) Confirm(db *gorp.DbMap, code int64, userid int64) error { var uc = UserConfirmation{} err := db.SelectOne(&uc, "select * from UserConfirmation where UserId = ? and Code = ?"+ " and Tried = 0 and Created > ?", userid, code, time.Now().Truncate(5* time.Minute).UnixNano()) if err != nil { return err } if uc.Id == 0 { return errors.New("Confirmation not found") } u.Registered = true _, err = db.Update(u) if err != nil { return err } return nil }
func PutGoods(r render.Render, dbmap *gorp.DbMap, params martini.Params, res http.ResponseWriter, g GoodInfo, e binding.Errors) { id := params["id"] //get userinfo _, err := goods.GetGoodsById(id, dbmap) if err != nil { r.JSON(http.StatusConflict, map[string]string{"message": "DB ERROR"}) } //insert new user info to db; _, err = dbmap.Update(&g) if err != nil { glog.V(1).Infof("[DEBUG:] Update Goods %v fail:%v", g, err) r.JSON(http.StatusConflict, map[string]string{"message": "DB ERROR"}) return } r.JSON(200, map[string]string{"message": "SUCCESS"}) }
func UpdateTask(r render.Render, params martini.Params, taskPayload Task, db *gorp.DbMap) { id, err := strconv.Atoi(params["id"]) if err != nil { r.JSON(400, map[string]string{"message": "id must be an integer"}) return } taskPayload.Id = id count, err := db.Update(&taskPayload) if count == 0 { r.JSON(404, map[string]string{"message": "task not found"}) return } if err != nil { log.Printf("Failed updating task %v: %v", id, err) r.JSON(500, map[string]string{"message": "Failed to update task"}) return } r.JSON(200, taskPayload) }
func (r Rate) Vote(Db *gorp.DbMap, v string, u int64) (Rate, error) { var el int64 if r.Id == 0 { return Rate{}, errors.New("Rate not found") } r = r.GetRate(Db, r.ItemType, r.ItemId) id, err := Db.SelectInt("select RateId from Vote where RateId = ? and"+ " UserId = ?", r.Id, u) if err != nil { return Rate{}, err } if id != 0 { return Rate{}, errors.New("You have already voted") } switch v { case "a": el = -1 r.Against++ Db.Exec("update Rate set Against = Against+1 where Id = ?", r) break case "b": el = 1 r.Behind++ Db.Exec("update Rate set Behind = Behind+1 where Id = ?", r) break default: return Rate{}, errors.New("Vote election undefined") } r.Rate = WilsonSum(r.Behind-r.Against, r.Against+r.Behind) vote := Vote{ RateId: r.Id, Value: el, UserId: u, } Db.Update(&r) Db.Insert(&vote) return r, nil }
func playerMove(msg Message, gameId string, playerId int, gs GameService, ws *websocket.Conn, db *gorp.DbMap, log *log.Logger) error { log.Printf("Sending move to host") turn := TicTacToe_Turn{} err := db.SelectOne(&turn, "select * from tictactoe_turn where game=? and player=?", gameId, playerId) if err != nil { log.Printf("Unable to get turn in move: %#v", err) return err } // the player move comes as an integer from [0-8] representing the location of the move // TODO: assert this is the case before saving turn.Move = int(msg["move"].(float64)) _, err = db.Update(&turn) if err != nil { log.Printf("Failed to update moving player: %#v", err) return err } // send notice to the host that we've moved so it can attempt to resolve the current round gs.SendHost(gameId, msg) return nil }
func main() { var ( dbMap *gorp.DbMap user *User iUser interface{} ) dbMap = SetupDb() //START CODE OMIT dbMap.Insert(&User{Id: 1, FirstName: "John", LastName: "Doe"}) PrintTable(dbMap) iUser, _ = dbMap.Get(User{}, 1) user = iUser.(*User) user.FirstName = "James" dbMap.Update(user) PrintTable(dbMap) dbMap.Delete(user) PrintTable(dbMap) //END CODE OMIT }
func (device *NetworkDevice) Persist(db *gorp.DbMap, vm VirtualMachine.VirtualMachine) error { insert := false device.Network.Persist(db) device.NetworkUUID = device.Network.UUID if len(device.UUID) == 0 { insert = true uuid, _ := uuid.NewV4() device.UUID = uuid.String() } if insert { db.Insert(device) } else { db.Update(device) } for _, address := range device.Addresses { if len(address.DeviceUUID) == 0 { address.DeviceUUID = device.UUID } if address.DeviceAddressID == 0 { db.Insert(address) } else { db.Update(address) } } for _, option := range device.Options { option.DeviceUUID = device.UUID if option.DeviceOptionID == 0 { db.Insert(option) } else { db.Update(option) } } return nil }
func hostMove(msg Message, gameId string, playerId int, gs GameService, ws *websocket.Conn, db *gorp.DbMap, log *log.Logger) error { log.Printf("Checking player move") var players []*Player _, err := db.Select(&players, "select * from players where game=?", gameId) if err != nil { log.Printf("Failed to select players during move for game %v", gameId) return err } resolveRound := true for _, p := range players { if p.Role == Host { continue } turn := TicTacToe_Turn{} err = db.SelectOne(&turn, "select * from tictactoe_turn where game=? and player=?", gameId, p.Id) if err != nil { log.Printf("Couldn't get turn %#v", err) return err } if turn.Move == -1 { resolveRound = false } } if !resolveRound { log.Printf("Round cannot be resolved") return nil // not an error, just nothing to do } board, err := getBoard(gameId, db) if err != nil { log.Printf("Couldn't get board: %#v", err) return err } // all players have set their moves, update the board thisRound := []int{0, 0, 0, 0, 0, 0, 0, 0, 0} for _, p := range players { if p.Role == Host { continue } turn := TicTacToe_Turn{} err = db.SelectOne(&turn, "select * from tictactoe_turn where game=? and player=?", gameId, p.Id) if err != nil { log.Printf("Couldn't get turn %#v", err) return err } if thisRound[turn.Move] == 0 { thisRound[turn.Move] = p.Id } else { thisRound[turn.Move] = 0 // two players went in the same spot } } niceBoard, err := board.getBoard() if err != nil { log.Printf("Error getting board: %#v", err) return err } for i, v := range niceBoard { if v == 0 { niceBoard[i] = thisRound[i] } } board.setBoard(niceBoard) count, err := db.Update(board) if err != nil || count == 0 { log.Printf("Unable to save board after move: %v", err) return err } for _, p := range players { if p.Role == Host { continue } turn := TicTacToe_Turn{} err = db.SelectOne(&turn, "select * from tictactoe_turn where game=? and player=?", gameId, p.Id) if err != nil { log.Printf("Couldn't get turn %#v", err) return err } turn.Move = -1 log.Printf("Resetting player %v turn", p.Id) count, err := db.Update(&turn) if count == 0 || err != nil { log.Printf("Failed to update player turn: %#v -- %#v", err, p.Id) return err } } gs.Broadcast(gameId, Message{ "type": "update", "board": niceBoard, "state": "start", }) ws.WriteJSON(Message{ "type": "update", "board": niceBoard, "state": "start", }) return nil }
func PostOrder(r render.Render, params martini.Params, dbmap *gorp.DbMap, res http.ResponseWriter, o Order, e binding.Errors) { if e != nil { //r.JSON(http.StatusBadRequest, map[string]string{"message": e[0].Message}) res.WriteHeader(http.StatusBadRequest) res.Header().Set("Content-Type", "application/text") res.Write([]byte(e[0].Message)) return } alipaytype := params["type"] //check user exists yet or not? var count int64 //count,err := dbmap.SelectInt("SELECT count(*) FROM ORDERS WHERE O_ID=?",o.Id) row, err := dbmap.Db.Query("SELECT count(*) FROM ORDERS WHERE O_ID=?", o.Id) if err != nil { glog.V(1).Infof("[DEBUG:] Search order by id:%v fail:%v", o.Id, err) //r.JSON(http.StatusConflict, map[string]string{"message": "DB ERROR"}) res.WriteHeader(http.StatusInternalServerError) res.Header().Set("Content-Type", "application/text") res.Write([]byte("DB ERROR")) return } defer row.Close() row.Next() err = row.Scan(&count) if err != nil { glog.V(2).Infof("Scan fail:", err.Error()) } //glog.V(2).Infof("Count = %v", count) if count > 0 { glog.V(1).Infof("Customer with tel:%v exists yet", o.Id) //r.JSON(http.StatusConflict, map[string]string{"message": "Order with same Id exists"}) res.WriteHeader(http.StatusInternalServerError) res.Header().Set("Content-Type", "application/text") res.Write([]byte("Order with same Id exists")) return } o.Status = 2 o.CreateTime = NullTime{Time: time.Now(), Valid: true} fee, err := goods.GetGoodFeeById(o.GoodId.String, dbmap) if err != nil { o.Status = 9 _, err2 := dbmap.Update(&o) if err2 != nil { glog.V(1).Infof("[DEBUG:] Update Order %v to invalid fail:%v", o, err2) } //r.JSON(http.StatusBadRequest, map[string]string{"message": "DB ERROR"}) res.WriteHeader(http.StatusBadRequest) res.Header().Set("Content-Type", "application/text") res.Write([]byte("Invalid Good ID")) return } o.Sum = fee * float32(o.GoodCnt) //insert new user info to db; err = dbmap.Insert(&o) if err != nil { glog.V(1).Infof("[DEBUG:] Insert Order %v fail:%v", o, err) //r.JSON(http.StatusConflict, map[string]string{"message": "DB ERROR"}) res.WriteHeader(http.StatusInternalServerError) res.Header().Set("Content-Type", "application/text") res.Write([]byte("Order Insert DB Fail")) return } //after saved to db,we call alipay and submit to alipay outhtml, outscript := alipay.Form(o, alipaytype) ob := map[string]string{"html": outhtml, "script": outscript} ob["self"] = "admin" res.Header().Set("Content-Type", "application/json") js, _ := json.Marshal(ob) //r.JSON(200, outscript) res.WriteHeader(http.StatusOK) res.Header().Set("Content-Type", "application/text") res.Write([]byte(js)) }
func UpdateGeoObject(db *gorp.DbMap, o *GeoObject) error { _, err := db.Update(o) return err }
func UpdatePage(db *gorp.DbMap, p *Page) error { _, err := db.Update(p) p.Updated = time.Now().UnixNano() return err }
func (p *StoreProduct) Update(db *gorp.DbMap) error { p.Updated = time.Now().UnixNano() _, err := db.Update(p) return err }