示例#1
0
func Update(executor Executor, val interface{}) *Result {
	pkName := sqlutils.GetPrimaryKeyColumnName(val)
	if pkName == nil {
		panic("primary key column is not defined.")
	}

	sql, values := sqlutils.BuildUpdateClause(val)

	var id = sqlutils.GetPrimaryKeyValue(val)
	values = append(values, id)

	// sql += fmt.Sprintf(" WHERE %s = $%d", *pkName, len(values))
	sql += " WHERE " + *pkName + " = $" + strconv.Itoa(len(values))

	stmt, err := executor.Prepare(sql)
	if err != nil {
		return NewErrorResult(err, sql)
	}

	defer stmt.Close()

	res, err := stmt.Exec(values...)
	if err != nil {
		return NewErrorResult(err, sql)
	}

	result := NewResult(sql)
	result.Result = res
	return result
}
示例#2
0
// id, err := Create(db pointer, struct pointer)
func Create(executor Executor, val interface{}, driver int) *Result {
	var err error

	if err = sqlutils.CheckRequired(val); err != nil {
		return NewErrorResult(err, "")
	}

	var sqlStr, args = sqlutils.BuildInsertClause(val, GetHolderTypeByDriver(driver))

	result := NewResult(sqlStr)

	// get the autoincrement id from result
	if driver == DriverPg {
		if col := sqlutils.GetPrimaryKeyColumnName(val); col != nil {
			sqlStr = sqlStr + " RETURNING " + *col
		}
		row := executor.QueryRow(sqlStr, args...)
		id, err := GetPgReturningIdFromRows(row)
		if err != nil {
			return NewErrorResult(err, sqlStr)
		}

		// if the struct supports the primary key interface, we can set the value faster.
		result.Id = id
		sqlutils.SetPrimaryKeyValue(val, result.Id)
	} else if driver == DriverMysql || driver == DriverSqlite {
		res, err := executor.Exec(sqlStr, args...)
		if err != nil {
			return NewErrorResult(err, sqlStr)
		}
		result.Id, err = res.LastInsertId()
		if err != nil {
			return NewErrorResult(err, sqlStr)
		}
		sqlutils.SetPrimaryKeyValue(val, result.Id)
	} else {
		panic("Unsupported driver type")
	}
	return result
}
示例#3
0
// Delete from DB connection object or a transaction object (pointer)
func Delete(executor Executor, val PtrRecord) *Result {
	pkName := sqlutils.GetPrimaryKeyColumnName(val)

	if pkName == nil {
		return NewErrorResult(errors.New("PrimaryKey column is not defined."), "")
	}

	sqlStr := "DELETE FROM " + sqlutils.GetTableName(val) + " WHERE " + *pkName + " = $1"

	var id = sqlutils.GetPrimaryKeyValue(val)
	var err error
	var res sql.Result

	res, err = executor.Exec(sqlStr, id)
	if err != nil {
		return NewErrorResult(err, sqlStr)
	}

	var r = NewResult(sqlStr)
	r.Result = res
	r.Id = id
	return r
}