/** * SetInc * @param fieldname string * @param value int * @return rows,error */ func (this *Sql) SetInc(field string, value int) (int64, error) { sqlstr := " UPDATE " + this.tableName + " " sqlstr += " SET " field_filted := this.convertValue2String(field) sqlstr += field_filted + " = " + field_filted + " + " + this.convertValue2String(value) sqlstr += " WHERE " sqlstr += this.conditionSql //slimSqlLog("SETINC", sqlstr) var r sql.Result var err error if this.tx != nil { r, err = this.tx.Exec(sqlstr) } else { r, err = this.getDbW().Exec(sqlstr) } if err != nil { slimSqlLog("ERROR", sqlstr) return 0, err } else { num, err := r.RowsAffected() if err != nil { return 0, err } else { return num, nil } } }
func NewOrUpdateUser(db *sql.DB, user *User) error { var err error var res sql.Result if user.Id == "" { res, err = db.Exec("INSERT INTO users(firstName, lastName) VALUES(?,?)", user.FirstName, user.LastName) } else { res, err = db.Exec("UPDATE users SET firstName=?, lastName=? WHERE id=?", user.FirstName, user.LastName, user.Id) } if err != nil { return err } lastId, err := res.LastInsertId() if err != nil { return err } rowCnt, err := res.RowsAffected() if err != nil { return err } if rowCnt != 1 { return errors.New(fmt.Sprintf("Row count (%s) and/or lastId (%s) are wrong.", lastId, rowCnt)) } return nil }
/* ** 执行更新操作 param1 表名 param2 柱头 parma3 条件 param4 参数 return 影响行数,错误 ** */ func (self *MDB) execUpdate(tableName, cols, condition string, args ...interface{}) (int64, error) { tx, err := self.Begin() if err != nil { return 0, err } if condition == "" || len(args) == 0 { return 0, errors.New("条件和参数都不能为空!") } stmt, err := tx.Prepare(fmt.Sprintf("UPDATE %s SET %s WHERE %s", tableName, cols, condition)) if err != nil { return 0, err } var result sql.Result if result, err = stmt.Exec(args...); err != nil { return 0, err } defer stmt.Close() if err = tx.Commit(); err != nil { return 0, err } if affected, err := result.RowsAffected(); err != nil { return 0, err } else { return affected, nil } }
func (this *mysql) Exec(query string, args ...interface{}) (afftectedRows int64, lastInsertId int64, err error) { if this.db == nil { return 0, 0, ErrNotOpen } if this.breaker.Open() { return 0, 0, ErrCircuitOpen } var result sql.Result result, err = this.db.Exec(query, args...) if err != nil { if this.isSystemError(err) { log.Warn("mysql exec breaks: %s", err.Error()) this.breaker.Fail() } return 0, 0, err } afftectedRows, err = result.RowsAffected() if err != nil { if this.isSystemError(err) { log.Warn("mysql exec2 breaks: %s", err.Error()) this.breaker.Fail() } } else { this.breaker.Succeed() } lastInsertId, _ = result.LastInsertId() return }
//Update ... func (vs VictualService) Update(victual *Victual) *Victual { db, err := sql.Open("postgres", "host=localhost port=5432 user=pober dbname=pober sslmode=disable") checkErr(err) defer db.Close() var statement *sql.Stmt statement, err = db.Prepare("UPDATE dc.victual SET description = $1, brand = $2, source = $3, energyCal = $4, energyJoule = $5, fat = $6, saturatedFat = $7, carbohydrates = $8, sugars = $9, protein = $10, salt = $11, fiber = $12, barCode = $13, weightVolumeRatio = $14 WHERE ID = $1") checkErr(err) var result sql.Result result, err = statement.Exec(victual.ID, victual.Description, victual.Brand, victual.Source, victual.EnergyCal, victual.EnergyJoule, victual.Fat, victual.SaturatedFat, victual.Carbohydrates, victual.Sugars, victual.Protein, victual.Salt, victual.Fiber, victual.BarCode, victual.WeightVolumeRatio) checkErr(err) var rowsAffected int64 rowsAffected, err = result.RowsAffected() checkErr(err) statement.Close() if rowsAffected == 1 { return victual } return nil }
func check_result(result sql.Result) { rows, err := result.RowsAffected() check_error(err) if rows == 0 { fmt.Printf("No rows affected by query") } }
func (database *Database) CreateTables(tableConf *TableConf) { db, err := sql.Open(database.Driver, database.dataSource) if err != nil { panic(err) } var result sql.Result var auto_increment_syntax = "INT AUTO INCREMENT " if database.IsPostgres() { auto_increment_syntax = "SERIAL " } fmt.Printf("creating table '%s'... \n", tableConf.Name) query := fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (id %s PRIMARY KEY, %s varchar(255), %s varchar(255), created_at timestamp DEFAULT CURRENT_TIMESTAMP, updated_at timestamp DEFAULT CURRENT_TIMESTAMP)", tableConf.Name, auto_increment_syntax, tableConf.Hash, tableConf.Url) result, err = db.Exec(query) if err != nil { panic(err) } result.RowsAffected() fmt.Printf("creating table 'goahead_statistics'... \n") query = fmt.Sprintf("CREATE TABLE IF NOT EXISTS goahead_statistics (id %s PRIMARY KEY, created_at timestamp DEFAULT CURRENT_TIMESTAMP)", auto_increment_syntax) result, err = db.Exec(query) if err != nil { panic(err) } result.RowsAffected() }
func (d *DBAlias) BatchExec(sqlbuf string, argsv [][]interface{}) (affectedRows int64, err error) { var result sql.Result if argsv == nil || len(argsv) == 0 { result, err = d.db.Exec(sqlbuf) if err == nil { affectedRows, err = result.RowsAffected() } return } else { var stmt *sql.Stmt stmt, err = d.db.Prepare(sqlbuf) if err != nil { return } defer stmt.Close() affectedRows = 0 for i, _ := range argsv { r, err1 := stmt.Exec(argsv[i]...) if err1 != nil { err = err1 return } num, _ := r.RowsAffected() affectedRows += num } } return }
func (this *tableMap) Update2(exec SQLExecutor, where string, data map[string]string, except []string) (rows int64, err error) { dialect := this.dbmap.dialect updSQL := dialect.UpdateSQL(this.schemaName, this.tableName) // L := len(data) setFields := make([]string, L) quote := "" noQuotes := array2dict(except) var i int for key, val := range data { if _, ok := noQuotes[key]; ok { quote = "" } else { quote = "'" } setFields[i] = fmt.Sprintf("%s = %s%s%s", dialect.QuoteField(key), quote, val, quote) i++ } // query := fmt.Sprintf(updSQL, strings.Join(setFields, ", "), setWhere(where)) if exec == nil { exec = this } var res sql.Result if res, err = exec.Exec(query); err == nil { rows, err = res.RowsAffected() } return }
func (this *tableMap) update(vptr reflect.Value, exec SQLExecutor, execVal []reflect.Value) (rows int64, err error) { var ( bind *bindObj res sql.Result ) if err = triggerRun("PreUpdate", vptr, execVal); err != nil { return } if bind, err = this.bindUpdate(); err != nil { return } if err = bind.bindArgs(vptr.Elem()); err != nil { return } if res, err = exec.Exec(bind.query, bind.argValues...); err != nil { return } if rows, err = res.RowsAffected(); err != nil { return } if err = triggerRun("PostUpdate", vptr, execVal); err != nil { return } return }
func (m *Mysql) Exec(query string, param ...interface{}) (rowsAffected int64, lastInsertId int64) { if !m.IsOpen() { panic(errors.New("[mysql555]It is not connected to the host")) } var res sql.Result = nil var err error = nil if m.IsTransaction() { res, err = m.tx.Exec(query, param...) } else { res, err = m.db.Exec(query, param...) } if err != nil { message := err.Error() message = message + "\n" + "[ SQL ] " + query + "\n" + fmt.Sprintf("[ PRM ] %#v\n", param) panic(errors.New(message)) } lastInsertId, err = res.LastInsertId() if err != nil { panic(err) } rowsAffected, err = res.RowsAffected() if err != nil { panic(err) } return }
func fieldMetricTagPut(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result { v := r.URL.Query() var err error var result sql.Result if result, err = db.Exec(`INSERT INTO field.metric_tag(devicePK, typePK, tagPK) SELECT devicePK, typePK, tagPK FROM field.device, field.type, mtr.tag WHERE deviceID = $1 AND typeID = $2 AND tag = $3`, v.Get("deviceID"), v.Get("typeID"), v.Get("tag")); err != nil { if err, ok := err.(*pq.Error); ok && err.Code == errorUniqueViolation { // ignore unique constraint errors return &weft.StatusOK } else { return weft.InternalServerError(err) } } var i int64 if i, err = result.RowsAffected(); err != nil { return weft.InternalServerError(err) } if i != 1 { return weft.BadRequest("Didn't create row, check your query parameters exist") } return &weft.StatusOK }
/* 设置任务状态 */ func (this *TaskDao) SetTasksStatus(tasks []types.CrawlTask, status TaskStatus) (int64, error) { nTasks := len(tasks) var affectedRows int64 = 0 var err = ErrNoTasks if nTasks > 0 { taskIds := []int32{} var result sql.Result var args []interface{} var sqlStr string var now = time.Now() for _, task := range tasks { taskIds = append(taskIds, task.Id) } if status == TASK_FINISH { sqlStr = fmt.Sprintf("update %s set status=%d, last_crawl_time=%d, crawl_times=crawl_times+1, update_time='%s' where id in (?)", TaskTable, status, now.Unix(), now.Format("2006-01-02 15:04:05")) } else { sqlStr = fmt.Sprintf("update %s set status=%d, update_time='%s' where id in (?)", TaskTable, status, now.Format("2006-01-02 15:04:05")) } sqlStr, args, err = sqlx.In(sqlStr, taskIds) if err != nil { log.Errorln("build sql to set task status failed! sql is ", sqlStr) } else { result, err = this.db.Exec(sqlStr, args...) if err != nil { log.Errorln("update tasks status error: ", err) } } affectedRows, _ = result.RowsAffected() } return affectedRows, err }
// ChangeUserPassword ... func ChangeUserPassword(u models.User, oldPassword ...string) (err error) { if len(oldPassword) > 1 { return errors.New("Wrong numbers of params.") } o := GetOrmer() var r sql.Result if len(oldPassword) == 0 { //In some cases, it may no need to check old password, just as Linux change password policies. r, err = o.Raw(`update user set password=?, salt=? where user_id=?`, utils.Encrypt(u.Password, u.Salt), u.Salt, u.UserID).Exec() } else { r, err = o.Raw(`update user set password=?, salt=? where user_id=? and password = ?`, utils.Encrypt(u.Password, u.Salt), u.Salt, u.UserID, utils.Encrypt(oldPassword[0], u.Salt)).Exec() } if err != nil { return err } c, err := r.RowsAffected() if err != nil { return err } if c == 0 { return errors.New("No record has been modified, change password failed.") } return nil }
func (p *TxScope) getAffectedRows(r sql.Result) int64 { if count, err := r.RowsAffected(); err != nil { panic(err) } else { return count } }
func (this *Database) ExecSql(mailbox rpc.Mailbox, msg *rpc.Message) (errcode int32, reply *rpc.Message) { var sqlstr string var callback string var callbackparams share.DBParams if server.Check(server.ParseArgs(msg, &sqlstr, &callback, &callbackparams)) { return 0, nil } sqlconn := db.sql var r sql.Result var err error app := server.GetAppById(mailbox.App) if app == nil { log.LogError(server.ErrAppNotFound) return 0, nil } if r, err = sqlconn.Exec(sqlstr); err != nil { log.LogError("sql:", sqlstr) server.Check(app.Call(nil, callback, callbackparams, 0, err.Error())) return 0, nil } eff, _ := r.RowsAffected() server.Check(app.Call(nil, callback, callbackparams, eff, "")) return 0, nil }
func dataLatencyThresholdPut(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result { v := r.URL.Query() var err error var lower, upper int if lower, err = strconv.Atoi(v.Get("lower")); err != nil { return weft.BadRequest("invalid lower") } if upper, err = strconv.Atoi(v.Get("upper")); err != nil { return weft.BadRequest("invalid upper") } siteID := v.Get("siteID") typeID := v.Get("typeID") var result sql.Result // TODO Change to upsert 9.5 // return if insert succeeds if result, err = db.Exec(`INSERT INTO data.latency_threshold(sitePK, typePK, lower, upper) SELECT sitePK, typePK, $3, $4 FROM data.site, data.type WHERE siteID = $1 AND typeID = $2`, siteID, typeID, lower, upper); err == nil { var i int64 if i, err = result.RowsAffected(); err != nil { return weft.InternalServerError(err) } if i == 1 { return &weft.StatusOK } } // return if update one row if pqErr, ok := err.(*pq.Error); ok && pqErr.Code == errorUniqueViolation { if result, err = db.Exec(`UPDATE data.latency_threshold SET lower=$3, upper=$4 WHERE sitePK = (SELECT sitePK FROM data.site WHERE siteID = $1) AND typePK = (SELECT typePK FROM data.type WHERE typeID = $2)`, siteID, typeID, lower, upper); err == nil { var i int64 if i, err = result.RowsAffected(); err != nil { return weft.InternalServerError(err) } if i == 1 { return &weft.StatusOK } } } if err == nil { err = fmt.Errorf("no rows affected, check your query.") } return weft.InternalServerError(err) }
func checkResult(c *C, r sql.Result, affectedRows int64, insertID int64) { gotRows, err := r.RowsAffected() c.Assert(err, IsNil) c.Assert(gotRows, Equals, affectedRows) gotID, err := r.LastInsertId() c.Assert(err, IsNil) c.Assert(gotID, Equals, insertID) }
func (this *Database) UpdateRow(mailbox rpc.Mailbox, msg *rpc.Message) (errcode int32, reply *rpc.Message) { var tbl string var values map[string]interface{} var condition string var callback string var callbackparams share.DBParams if server.Check(server.ParseArgs(msg, &tbl, &values, &condition, &callback, &callbackparams)) { return 0, nil } sqlconn := db.sql var r sql.Result var err error app := server.GetAppById(mailbox.App) if app == nil { log.LogError(server.ErrAppNotFound) return 0, nil } if condition != "" { condition = fmt.Sprintf("WHERE %s", condition) } args := make([]interface{}, 0, len(values)) var sql bytes.Buffer sql.WriteString("UPDATE `") sql.WriteString(tbl) sql.WriteString("` SET") split := " " for k, v := range values { sql.WriteString(split) split = ", " sql.WriteString("`") sql.WriteString(k) sql.WriteString("`") sql.WriteString("=?") args = append(args, v) } sqlstr := fmt.Sprintf("%s %s", sql.String(), condition) if r, err = sqlconn.Exec(sqlstr, args...); err != nil { log.LogError("sql:", sqlstr) if callback == "_" { log.LogError(err) return 0, nil } server.Check(app.Call(nil, callback, callbackparams, 0, err.Error())) return 0, nil } if callback == "_" { return 0, nil } eff, _ := r.RowsAffected() server.Check(app.Call(nil, callback, callbackparams, eff, "")) return 0, nil }
func (self *Params) Save() (bool, int64, error) { db, query := self.getWriteConnect() defer func() { self.set = self.set[len(self.set):] }() var err error var stmt *sql.Stmt var res sql.Result //var n int64 //if n , err= self.Count();err == nil && n >0 if self.hasRow { sqls, val := query.Update() if OpenSyncUpdate { sqls = strings.Replace(sqls, "?", "%v", -1) sqls = fmt.Sprintf(sqls, val...) SqlSyncHook <- sqls return false, 0, nil } else { if debug_sql { Debug.Println("save update ", sqls, val) } stmt, err = db.Prepare(sqls) if err == nil { defer stmt.Close() } else { return false, 0, err } res, err = stmt.Exec(val...) if err != nil { return false, 0, err } a, b := res.RowsAffected() return false, a, b } } else { sqls, val := query.Insert() if debug_sql { Debug.Println("save insert ", sqls, val) } stmt, err = db.Prepare(sqls) if err == nil { defer stmt.Close() } else { return false, 0, err } res, err = stmt.Exec(val...) if err != nil { return true, 0, err } a, b := res.LastInsertId() self.hasRow = true return true, a, b } }
func Clean(args ...string) (err error) { db, err := eqdb.Load() if err != nil { return } spawns := []Spawndata{ {Npcid: 37082, Spawngroupid: 2096, Chance: 5}, //Arthikus was 50 {Npcid: 35160, Spawngroupid: 4748, Chance: 5}, //Ghoul of TakishHiz was 20 {Npcid: 37121, Spawngroupid: 3271, Chance: 5}, //A sand giant was 50 {Npcid: 37121, Spawngroupid: 3376, Chance: 5}, //A sand giant was 50 {Npcid: 37157, Spawngroupid: 2095, Chance: 5}, //cazel was 50 {Npcid: 22187, Spawngroupid: 788, Chance: 5}, //a griffon was 50 {Npcid: 22187, Spawngroupid: 792, Chance: 5}, //a griffon was 50 {Npcid: 92159, Spawngroupid: 9825, Chance: 5}, //Overseer_Miklek was 34% {Npcid: 110100, Spawngroupid: 16400, Mindelay: 50000, Despawntimer: 100}, //Stormfeather } totalRemoved := int64(0) for _, spawn := range spawns { var result sql.Result if spawn.Chance > 0 { result, err = db.Exec("UPDATE spawnentry SET chance = ? WHERE npcid = ? AND spawngroupid = ?", spawn.Chance, spawn.Npcid, spawn.Spawngroupid) if err != nil { fmt.Println("Err updating spawngroup:", err.Error()) return } var affect int64 affect, err = result.RowsAffected() if err != nil { fmt.Println("Error getting rows affected for", focus, err.Error()) return } totalRemoved += affect } if spawn.Mindelay > 0 && spawn.Despawntimer > 0 { result, err = db.Exec("UPDATE spawngroup SET mindelay = ?, despawn_timer = ? WHERE npcid = ? AND spawngroupid = ?", spawn.Mindelay, spawn.Despawntimer, spawn.Npcid, spawn.Spawngroupid) if err != nil { fmt.Println("Err updating spawngroup:", err.Error()) return } var affect int64 affect, err = result.RowsAffected() if err != nil { fmt.Println("Error getting rows affected for", focus, err.Error()) return } totalRemoved += affect } } fmt.Println("Updated", totalRemoved, " DB entries related to", focus, "in spawnentry and spawngroup successfully.") return }
func checkRowsAffected(res sql.Result, expected int64) error { actual, err := res.RowsAffected() if err != nil { return fmt.Errorf("Could not check rows affected: %v", err) } if actual != expected { return fmt.Errorf("Unexpected result: expected %v, got %v", expected, actual) } return nil }
func mustHaveChanged(res sql.Result) error { n, err := res.RowsAffected() if err != nil { return err } if n == 0 { return ErrNotFound } return nil }
func affectCheck(res sql.Result, expect int64, errMsg error) error { affect, e := res.RowsAffected() if e != nil { return e } if affect != expect { return errMsg } return nil }
func fieldDevicePut(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result { v := r.URL.Query() var err error var latitude, longitude float64 if latitude, err = strconv.ParseFloat(v.Get("latitude"), 64); err != nil { return weft.BadRequest("latitude invalid") } if longitude, err = strconv.ParseFloat(v.Get("longitude"), 64); err != nil { return weft.BadRequest("longitude invalid") } var result sql.Result // TODO - use upsert with PG 9.5? // return if insert succeeds if result, err = db.Exec(`INSERT INTO field.device(deviceID, modelPK, latitude, longitude) SELECT $1, modelPK, $3, $4 FROM field.model WHERE modelID = $2`, v.Get("deviceID"), v.Get("modelID"), latitude, longitude); err == nil { var i int64 if i, err = result.RowsAffected(); err != nil { return weft.InternalServerError(err) } if i == 1 { return &weft.StatusOK } } // return if update one row if pqErr, ok := err.(*pq.Error); ok && pqErr.Code == errorUniqueViolation { if result, err = db.Exec(`UPDATE field.device SET latitude = $2, longitude = $3 WHERE deviceID = $1`, v.Get("deviceID"), latitude, longitude); err == nil { var i int64 if i, err = result.RowsAffected(); err != nil { return weft.InternalServerError(err) } if i == 1 { return &weft.StatusOK } } } if err == nil { err = fmt.Errorf("no rows affected, check your query.") } return weft.InternalServerError(err) }
func resultDoCheck(result sql.Result, callerDescr string, callIndex int) { lastID, err := result.LastInsertId() if err != nil { log.Panic(err) } nAffected, err := result.RowsAffected() if err != nil { log.Panic(err) } log.Printf("Exec result for %s (%d): ID = %d, affected = %d\n", callerDescr, callIndex, lastID, nAffected) }
func dataSitePut(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result { v := r.URL.Query() siteID := v.Get("siteID") var err error var latitude, longitude float64 if latitude, err = strconv.ParseFloat(v.Get("latitude"), 64); err != nil { return weft.BadRequest("latitude invalid") } if longitude, err = strconv.ParseFloat(v.Get("longitude"), 64); err != nil { return weft.BadRequest("longitude invalid") } var result sql.Result // TODO - use upsert with PG 9.5? // return if insert succeeds if result, err = db.Exec(`INSERT INTO data.site(siteID, latitude, longitude) VALUES($1, $2, $3)`, siteID, latitude, longitude); err == nil { var i int64 if i, err = result.RowsAffected(); err != nil { return weft.InternalServerError(err) } if i == 1 { return &weft.StatusOK } } // return if update one row if pqErr, ok := err.(*pq.Error); ok && pqErr.Code == errorUniqueViolation { if result, err = db.Exec(`UPDATE data.site SET latitude=$2, longitude=$3 where siteID=$1`, siteID, latitude, longitude); err == nil { var i int64 if i, err = result.RowsAffected(); err != nil { return weft.InternalServerError(err) } if i == 1 { return &weft.StatusOK } } } if err == nil { err = fmt.Errorf("no rows affected, check your query.") } return weft.InternalServerError(err) }
func updateConvertNilError(res sql.Result, err error) error { if err != nil { return err } n, err := res.RowsAffected() if err != nil { return err } if n < 1 { return ErrNoModify } return nil }
func fieldStatePut(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result { q := r.URL.Query() deviceID := q.Get("deviceID") typeID := q.Get("typeID") var err error var value bool if value, err = strconv.ParseBool(q.Get("value")); err != nil { return weft.BadRequest("invalid value") } var t time.Time if t, err = time.Parse(time.RFC3339, q.Get("time")); err != nil { return weft.BadRequest("invalid time") } var result sql.Result if result, err = db.Exec(`UPDATE field.state SET time = $3, value = $4 WHERE devicePK = (SELECT devicePK from field.device WHERE deviceID = $1) AND typePK = (SELECT typePK from field.state_type WHERE typeID = $2)`, deviceID, typeID, t, value); err != nil { return weft.InternalServerError(err) } // If no rows change either the values are old or it's the first time we've seen this metric. var u int64 if u, err = result.RowsAffected(); err != nil { return weft.InternalServerError(err) } if u == 1 { return &weft.StatusOK } else if result, err = db.Exec(`INSERT INTO field.state(devicePK, typePK, time, value) SELECT devicePK, typePK, $3, $4 FROM field.device, field.state_type WHERE deviceID = $1 AND typeID = $2`, deviceID, typeID, t, value); err == nil { var i int64 if i, err = result.RowsAffected(); err != nil { return weft.InternalServerError(err) } if i == 1 { return &weft.StatusOK } } return weft.InternalServerError(err) }
// expireAttempts finds all attempts whose expiration time has passed // and expires them. It runs on all attempts for all work units in all // work specs in all namespaces (which simplifies the query). Expired // attempts' statuses become "expired", and those attempts cease to be // the active attempt for their corresponding work unit. // // In general this should be called in its own transaction and its error // return ignored: // // _ = withTx(self, func(tx *sql.Tx) error { // return expireAttempts(self, tx) // }) // // Expiry is generally secondary to whatever actual work is going on. // If a result is different because of expiry, pretend the relevant // call was made a second earlier or later. If this fails, then // either there is a concurrency issue (and since the query is // system-global, the other expirer will clean up for us) or there is // an operational error (and the caller will fail afterwards). func expireAttempts(c coordinable, tx *sql.Tx) error { // There are several places this is called with much smaller // scope. For instance, Attempt.Status() needs to invoke // expiry but only actually cares about this very specific // attempt. If there are multiple namespaces, // Worker.RequestAttempts() only cares about this namespace // (though it will run on all work specs). It may help system // performance to try to run this with narrower scope. // // This is probably also an excellent candidate for a stored // procedure. var ( now time.Time cte, query string count int64 result sql.Result err error ) now = c.Coordinate().clock.Now() // Remove expiring attempts from their work unit cte = buildSelect([]string{attemptID}, []string{attemptTable}, []string{attemptIsPending, attemptIsExpired}) // $1 = "now" cte += " FOR UPDATE" query = buildUpdate(workUnitTable, []string{"active_attempt_id=NULL"}, []string{"active_attempt_id IN (" + cte + ")"}) result, err = tx.Exec(query, now) if err != nil { return err } // If this marked nothing as expired, we're done count, err = result.RowsAffected() if err != nil { return err } if count == 0 { return nil } // Mark attempts as expired query = buildUpdate(attemptTable, []string{"expiration_time=$1", "status='expired'"}, []string{attemptIsPending, attemptIsExpired}) _, err = tx.Exec(query, now) return err }