Ejemplo n.º 1
0
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
}
Ejemplo n.º 2
0
/* **
执行更新操作
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
	}
}
Ejemplo n.º 3
0
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
}
Ejemplo n.º 4
0
// 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
}
Ejemplo n.º 5
0
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
}
Ejemplo n.º 6
0
// task.ID will be ignored.
func CreateTask(task icarus.TaskData) (ID int, err error) {
	InitStorage()
	var res sql.Result
	res, err = db.Exec("INSERT INTO task (handle) VALUES (?)", task.Handle)
	if err != nil {
		log.Warnf("storage.CreateTask(): Failed to insert task %v: %s.", task, err.Error())
		return
	}
	newID, err := res.LastInsertId()
	if err != nil {
		log.Warnf("storage.CreateTask(): Failed to get ID for task %v: %s.", task, err.Error())
	}
	ID = int(newID)

	_, err = db.Exec("INSERT INTO user (userid, password, task_id) VALUES (?, ?, ?)", task.User.UserID, task.User.Password, ID)
	if err != nil {
		log.Warnf("storage.CreateTask(): Failed to insert user for task %v: %s.", task, err.Error())
		return
	}

	for _, c := range task.Courses {
		_, err = db.Exec("INSERT INTO course (name, desc, token, task_id) VALUES (?, ?, ?, ?)", c.Name, c.Desc, c.Token, ID)
		if err != nil {
			log.Warnf("storage.CreateTask(): Failed to insert course %v for task %v: %s.", c, task, err.Error())
			return
		}
	}

	return
}
Ejemplo n.º 7
0
func (p *TxScope) getAffectedRows(r sql.Result) int64 {
	if count, err := r.RowsAffected(); err != nil {
		panic(err)
	} else {
		return count
	}
}
Ejemplo n.º 8
0
func (a *Account) Save() error {
	db, err := connect()
	if err != nil {
		return err
	}
	defer db.Close()

	stmt, err := db.Prepare("insert or replace into T_ACCOUNTS (ID, NAME, EMAIL, PASSWORD, SALT, ROLE, LAST_AUTH) values (?,?,?,?,?,?,?)")
	if err != nil {
		return err
	}
	defer stmt.Close()

	var result sql.Result
	if a.Id < 1 {
		result, err = stmt.Exec(nil, a.Name, a.Email, a.Password, a.Salt, a.Role, a.LastAuth)
	} else {
		result, err = stmt.Exec(a.Id, a.Name, a.Email, a.Password, a.Salt, a.Role, a.LastAuth)
	}
	if err != nil {
		return err
	}

	id, err := result.LastInsertId()
	if err != nil {
		return err
	}
	a.Id = int(id)

	return nil
}
Ejemplo n.º 9
0
func (self *MysqlDriver) Create(container string, query driver.Query) (id interface{}, requestError error) {
	fmt.Println("mysql driver create:", container, query)
	// Create mysql insert string from given query
	var (
		queryFields []string
		queryValues []string
	)
	for k, v := range query {
		fmt.Println("key/value:", k, v)
		// TODO: check for sql injection
		queryFields = append(queryFields, k)
		queryValues = append(queryValues, fmt.Sprintf("'%s'", v))
	}
	fmt.Println("fields:", queryFields)
	fmt.Println("values:", queryValues)
	var result sql.Result
	if result, requestError = self.db.Exec(fmt.Sprintf("INSERT INTO `users`(%s) VALUES(%s)", strings.Join(queryFields, ","), strings.Join(queryValues, ","))); requestError != nil {
		// Failure
		return
	} else {
		// Success
		if id, requestError = result.LastInsertId(); requestError != nil {
			// Failure
			return
		}
	}
	// Success
	fmt.Println("success?:", id, requestError)
	return
}
Ejemplo n.º 10
0
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
}
Ejemplo n.º 11
0
func (this *Config) Insert() error {
	this.Recordtime = getNow()
	var (
		err error
		id  int64
		res sql.Result
	)
	if this.Cat != nil {
		tran := this.Cat.NewTransaction(DBTITLE, "Config.Insert")
		defer func() {
			if err != nil {
				tran.SetStatus(err)
			} else {
				tran.SetStatus("0")
			}
			tran.Complete()
		}()
	}
	o := orm.NewOrm()
	res, err = o.Raw("INSERT INTO config(channelCode,`key`,value,recordTime)VALUES(?,?,?,?)", this.ChannelCode, this.Key, this.Value, this.Recordtime).Exec()
	if err != nil {
		return err
	}
	id, err = res.LastInsertId()
	if err != nil {
		return err
	}
	this.Id = id
	return nil
}
Ejemplo n.º 12
0
func registerMembers() (err error) {
	members := []Member{
		{Name: "ミク", Birthday: "10/19", Bloodtype: "AB", Hobby: "ショッピング"},
		{Name: "マホ", Birthday: "1/8", Bloodtype: "AB", Hobby: "漫画"},
		{Name: "コヒメ", Birthday: "11/24", Bloodtype: "O", Hobby: "ゲーム"},
	}

	stmt, err := Db.Prepare(`
		INSERT INTO member (name, birthday, blood_type, hobby) 
		VALUES (?, ?, ?, ?)
	`)
	if err != nil {
		return
	}
	defer stmt.Close()

	for _, m := range members {
		var ret sql.Result
		ret, err = stmt.Exec(m.Name, m.Birthday, m.Bloodtype, m.Hobby)
		if err != nil {
			return
		}

		var id int64
		id, err = ret.LastInsertId()
		if err != nil {
			return
		}
		m.Id = int(id)
		fmt.Printf("Inserted. ID = %d, Name = %s\n", m.Id, m.Name)
	}

	return
}
Ejemplo n.º 13
0
func (dbSeq *SequenceDB) NextSequence() (sequence uint64, err error) {
	var stmt *sql.Stmt
	stmt, err = dbSeq.db.Prepare(`REPLACE INTO sequence(stub) VALUES ("sequence")`)
	if err != nil {
		log.Printf("sequence db prepare error. %v", err)
		return 0, err
	}
	defer stmt.Close()

	var res sql.Result
	res, err = stmt.Exec()
	if err != nil {
		log.Printf("sequence db replace into error. %v", err)
		return 0, err
	}

	// 兼容LastInsertId方法的返回值
	var lastID int64
	lastID, err = res.LastInsertId()
	if err != nil {
		log.Printf("sequence db get LastInsertId error. %v", err)
		return 0, err
	} else {
		sequence = uint64(lastID)
		// mysql sequence will start at 1, we actually want it to be
		// started at 0. :)
		sequence -= 1
		return sequence, nil
	}
}
Ejemplo n.º 14
0
/*
	设置任务状态
*/
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
}
Ejemplo n.º 15
0
/**
 * Insert / convert ""/'' maybe a bug.
 * @param map of data
 * @return id,err
 */
func (this *Sql) Add(data map[string]interface{}) (int64, error) {
	var columns []string
	var values []string
	for k, v := range data {
		columns = append(columns, k)
		tmp_v := this.convertValue2String(v)
		values = append(values, "\""+tmp_v+"\"")
	}
	sqlstr := " INSERT INTO `" + this.tableName + "` " + " (" + strings.Join(columns, ",") + ") VALUES (" + strings.Join(values, ",") + ") "
	//slimSqlLog("Insert", 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 {
		id, err := r.LastInsertId()
		if err != nil {
			return 0, err
		} else {
			return id, nil
		}
	}
}
Ejemplo n.º 16
0
// Execute an sql 'exec' that returns 'insert ids' (api is stupid)
func (self *sql) exec(query string, columns []string, values ...[]interface{}) (*rowset, error) {
	var output gsql.Result = nil
	var err error = nil

	// Pass params over
	if len(values) > 0 {
		output, err = self.db.Exec(query, values[0]...)
	} else {
		output, err = self.db.Exec(query)
	}
	if err != nil {
		return nil, utils.Fail(1, "Error perfroming explicit SQL query \"%s\": %s", query, err.Error())
	}

	// Process output
	var rtn = newRowset(nil).(*rowset)
	var id, id_err = output.LastInsertId()
	if id_err == nil {
		var record = map[string]interface{}{}
		for _, c := range columns {
			record[c] = id
		}
		rtn.Values.PushBack(record)
	}

	return rtn, err
}
Ejemplo n.º 17
0
//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
}
Ejemplo n.º 18
0
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
}
Ejemplo n.º 19
0
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()
}
Ejemplo n.º 20
0
func check_result(result sql.Result) {
	rows, err := result.RowsAffected()
	check_error(err)
	if rows == 0 {
		fmt.Printf("No rows affected by query")
	}
}
Ejemplo n.º 21
0
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
}
Ejemplo n.º 22
0
Archivo: db.go Proyecto: colefan/myorm
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

}
Ejemplo n.º 23
0
func InsertPost(title []byte, slug string, markdown []byte, html []byte, featured bool, isPage bool, published bool, image []byte, created_at time.Time, created_by int64) (int64, error) {

	status := "draft"
	if published {
		status = "published"
	}
	writeDB, err := readDB.Begin()
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	var result sql.Result
	if published {
		result, err = writeDB.Exec(stmtInsertPost, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), title, slug, markdown, html, featured, isPage, status, image, created_by, created_at, created_by, created_at, created_by, created_at, created_by)
	} else {
		result, err = writeDB.Exec(stmtInsertPost, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), title, slug, markdown, html, featured, isPage, status, image, created_by, created_at, created_by, created_at, created_by, nil, nil)
	}
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	postId, err := result.LastInsertId()
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	return postId, writeDB.Commit()
}
Ejemplo n.º 24
0
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
}
Ejemplo n.º 25
0
/**
 * 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
		}
	}
}
Ejemplo n.º 26
0
// POST /api/users
func (mgr *Manager) AddUser(w http.ResponseWriter, r *http.Request, rnd render.Render) {
	req := make(map[string]string)
	err := json.NewDecoder(r.Body).Decode(&req)
	if err != nil || len(req["name"]) < 3 || len(req["password"]) < 3 {
		w.WriteHeader(400)
		return
	}
	passwd, err := bcrypt.GenerateFromPassword([]byte(req["password"]), 11)
	if err != nil {
		log.Error("bcrypt.GenerateFromPassword: "******"insert into users (name, password) values(?,?)", req["name"], passwd)
	if err == nil {
		id, err = result.LastInsertId()
	}
	if err != nil {
		mgr.showError(err, w)
		return
	}
	rnd.JSON(200, map[string]interface{}{"name": req["name"], "id": id})
}
Ejemplo n.º 27
0
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)
}
Ejemplo n.º 28
0
func (u *User) userRowFromSqlResult(tx *sqlx.Tx, sqlResult sql.Result) (*UserRow, error) {
	userId, err := sqlResult.LastInsertId()
	if err != nil {
		return nil, err
	}

	return u.GetById(tx, userId)
}
Ejemplo n.º 29
0
func (sq *SavedQuery) savedQueryRowFromSqlResult(tx *sqlx.Tx, sqlResult sql.Result) (*SavedQueryRow, error) {
	savedQueryId, err := sqlResult.LastInsertId()
	if err != nil {
		return nil, err
	}

	return sq.GetByID(tx, savedQueryId)
}
Ejemplo n.º 30
-2
// Insert 向指定table插入数据
func (this *builder) Insert(table string, model interface{}) int {
	query := "insert into `" + table + "`"
	value := reflect.ValueOf(model).Elem()
	data := make(map[string]interface{})
	mapStructToMap(value, data)
	keys := " ("
	values := " ("
	params := make([]interface{}, 0, 0)
	for k, v := range data {
		keys += "`" + k + "`,"
		values += "?,"
		params = append(params, v)
	}
	query += keys[:len(keys)-1] + ") values"
	query += values[:len(values)-1] + ")"
	var result sql.Result
	var err error
	this.reset()
	result, err = this.db.Exec(query, params...)
	if err != nil {
		return -1
	}
	var id int64
	id, err = result.LastInsertId()
	if err != nil {
		return -1
	}
	return int(id)
}