本文整理汇总了Golang中github.com/jmoiron/sqlx.Rows类的典型用法代码示例。如果您正苦于以下问题:Golang Rows类的具体用法?Golang Rows怎么用?Golang Rows使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Rows类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: sqlGetRow
func sqlGetRow(rows *sqlx.Rows, bytesToStrings, idTo_id bool) (*map[string]interface{}, error) {
results := make(map[string]interface{})
err := rows.MapScan(results)
if err != nil {
log.Println(err)
} else {
if idTo_id {
// Convert "id" column to "_id" for mongo
if _, ok := results["id"]; ok {
// Mangle id, because mongo is persnickity
results["_id"] = results["id"]
delete(results, "id")
}
}
if bytesToStrings {
// Convert byte arrays to strings
for k, v := range results {
if _, ok := v.([]byte); ok {
// Damn. Byte. Arrays. Sqlx.
results[k] = string(v.([]byte))
}
}
}
}
return &results, err
}
示例2: DropAndCreateTable
// DropAndCreateTable удаляет таблицу, если она уже существует и создает заново
func DropAndCreateTable(schema string, tableName string, db *sqlx.DB) (bool, error) {
var err error
var rows *sqlx.Rows
// Проверяем нет ли такой таблицы в базе
rows, err = db.Queryx("SELECT to_regclass('" + tableName + "');")
if err != nil {
//fmt.Println("Error on check table '"+tableName+"':", err)
return false, err
}
defer rows.Close()
// И если есть удаляем
rowsCount := 0
for rows.Next() {
rowsCount++
}
if rowsCount > 0 {
_, err = db.Exec("DROP TABLE IF EXISTS " + tableName + ";")
if err != nil {
//fmt.Println("Error on drop table '"+tableName+"':", err)
return false, err
}
}
// Создаем таблицу
_, err = db.Exec(schema)
if err != nil {
//fmt.Println("Error on create table '"+tableName+"':", err)
return false, err
}
return true, nil
}
示例3: flattenUuidRows
func flattenUuidRows(rows *sqlx.Rows) (uuids []string, err error) {
for rows.Next() {
var uuid string
err = rows.Scan(&uuid)
if err != nil {
return
}
uuids = append(uuids, uuid)
}
return
}
示例4: loadResult
func loadResult(rows *sqlx.Rows) ([]TestEntity, error) {
result := []TestEntity{}
for rows.Next() {
row := TestEntity{}
err := rows.StructScan(&row)
if err != nil {
return nil, err
}
result = append(result, row)
}
return result, nil
}
示例5: EncodeStructCustom
func EncodeStructCustom(rows *sqlx.Rows, w http.ResponseWriter) {
sa := make([]Custom, 0)
t := Custom{}
for rows.Next() {
rows.StructScan(&t)
sa = append(sa, t)
}
enc := json.NewEncoder(w)
enc.Encode(sa)
}
示例6: decodeRows
func (tx *Transaction) decodeRows(s *schema.Schema, rows *sqlx.Rows, list []*schema.Resource) ([]*schema.Resource, error) {
for rows.Next() {
resourceData := map[string]interface{}{}
data := map[string]interface{}{}
rows.MapScan(data)
var resource *schema.Resource
tx.decode(s, s.GetDbTableName(), data, resourceData)
resource, err := schema.NewResource(s, resourceData)
if err != nil {
return nil, fmt.Errorf("Failed to decode rows")
}
list = append(list, resource)
}
return list, nil
}
示例7: parseOrders
// Orders need to be joined to extract usefull info, therefore they have to be parsed by hand
func (d Datastore) parseOrders(model interface{}, id interface{}) error {
var rows *sqlx.Rows
var e error
query := "select o.id, o.user_id, o.place_id, o.start, o.end_time, p.name as place_name, u.username, u.firstname, u.lastname from orders o left join users u on u.id = o.user_id left join places p on p.id = o.place_id"
/* query := "select o.id, o.user_id, o.place_id, o.date + o.order_start as start, o.date + o.order_end as end, p.name as place_name, u.username, u.firstname, u.lastname from orders o left join users u on u.id = o.user_id left join places p on p.id = o.place_id"
*/if id != nil {
query += " where o.id = $1"
rows, e = d.Db.Queryx(query, id)
} else {
rows, e = d.Db.Queryx(query)
}
/*query = "SELECT * FROM orders o, users u, places p where u.id = o.user_id and p.id = o.place_id"*/
if e != nil {
log.Println(e)
}
for rows.Next() {
var id int64
var place_id, user_id sql.NullInt64
var username, firstname, lastname, place_name sql.NullString
var start, end pq.NullTime
if err := rows.Scan(&id, &user_id, &place_id, &start, &end, &place_name, &username, &firstname, &lastname); err != nil {
log.Println(err)
}
order := Order{Id: id, UserId: user_id.Int64, PlaceId: place_id.Int64, Start: start.Time, End: end.Time, PlaceName: place_name.String, Username: username.String, Firstname: firstname.String, Lastname: lastname.String}
if user_id.Valid == false || (lastname.String == "" && firstname.String == "") {
order.Title = fmt.Sprintf("%v", place_name.String)
} else {
order.Title = fmt.Sprintf("%v: %v, %v", place_name.String, lastname.String, firstname.String)
}
*model.(*[]Order) = append(*model.(*[]Order), order)
}
e = rows.Err()
return e
}
示例8: GetBoardPostsByID
// GetBoardPostsByID returns the filtered posts for a board by the ID of the board
func (ps *PostService) GetBoardPostsByID(boardID, page int) (posts []*model.Post, err error) {
var rows *sqlx.Rows
rows, err = ps.db.Queryx(queries.Get("get_board_posts_by_id"), boardID, page*50)
if err != nil {
return
}
for rows.Next() {
var post model.Post
err = rows.StructScan(&post)
if err != nil {
return
}
posts = append(posts, &post)
}
return
}
示例9: GetUserPosts
// GetUserPosts returns all posts owned by a certain user
func (ps *PostService) GetUserPosts(userID, page int) (posts []*model.Post, err error) {
var rows *sqlx.Rows
rows, err = ps.db.Queryx(queries.Get("get_user_posts"), userID, page*50)
if err != nil {
return
}
for rows.Next() {
var post model.Post
err = rows.StructScan(&post)
if err != nil {
return
}
posts = append(posts, &post)
}
return
}
示例10: GetInactiveUserInfo
// GetInactiveUserInfo returns a list of users who have not been active for the specified time interval
func (db *dbw) GetInactiveUserInfo(fid int, interval time.Duration) (users []peerInfo, err error) {
query := `SELECT user_id, ip FROM files_users
WHERE time < (UNIX_TIMESTAMP() - ?)
AND active = 1
AND file_id = ?;`
result := peerInfo{}
checkInterval := int(interval / time.Second)
var rows *sqlx.Rows
if rows, err = db.Queryx(query, checkInterval, fid); err == nil && err != sql.ErrNoRows {
for rows.Next() {
if err = rows.StructScan(&result); err == nil {
users = append(users, result)
}
}
}
return
}
示例11: GetPostComments
// GetPostComments returns all root level comments along with their children for a Post`
func (cs *CommentService) GetPostComments(postID int) (comments []*model.Comment, err error) {
var rows *sqlx.Rows
rows, err = cs.db.Queryx(queries.Get("get_post_comments"), postID)
if err != nil {
return
}
var pgcr []types.PGComment
for rows.Next() {
var pgc types.PGComment
err = rows.StructScan(&pgc)
if err != nil {
return
}
pgcr = append(pgcr, pgc)
}
comments = types.AssembleCommentTree(pgcr)
return
}
示例12: GetUserComments
// GetUserComments returns all of a users past comments
func (cs *CommentService) GetUserComments(userID int) (comments []*model.Comment, err error) {
var rows *sqlx.Rows
rows, err = cs.db.Queryx(queries.Get("get_user_comments"), userID)
if err != nil {
return
}
var pgcr []types.PGComment
for rows.Next() {
var pgc types.PGComment
err = rows.StructScan(&pgc)
if err != nil {
return
}
log.Printf("%+v", pgc)
pgcr = append(pgcr, pgc)
}
comments = types.AssembleCommentTree(pgcr)
return
}
示例13: mapEvents
func mapEvents(r *sqlx.Rows) ([]event, error) {
events := make([]event, 0)
for r.Next() {
var temp string = ""
e := event{}
err := r.Scan(&e.ID, &temp, &e.Title, &e.Description, &e.Font)
if err != nil {
return nil, err
}
e.Date, err = stringToTime(temp)
events = append(events, e)
}
/*doesn't work
e := event{}
err := e.mapRow(r)
if err != nil {
return nil, err
}
events = append(events, e)
*/
return events, nil
}
示例14: queryScalar
// QueryScan executes the query in builder and loads the resulting data into
// one or more destinations.
//
// Returns ErrNotFound if no value was found, and it was therefore not set.
func queryScalar(execer *Execer, destinations ...interface{}) error {
fullSQL, args, blob, err := cacheOrSQL(execer)
if err != nil {
return err
}
if blob != nil {
err = json.Unmarshal(blob, &destinations)
if err == nil {
return nil
}
// log it and fallthrough to let the query continue
logger.Warn("queryScalar.2: Could not unmarshal cache data. Continuing with query")
}
defer logExecutionTime(time.Now(), fullSQL, args)
// Run the query:
var rows *sqlx.Rows
if args == nil {
rows, err = execer.database.Queryx(fullSQL)
} else {
rows, err = execer.database.Queryx(fullSQL, args...)
}
if err != nil {
return logSQLError(err, "QueryScalar.load_value.query", fullSQL, args)
}
defer rows.Close()
if rows.Next() {
err = rows.Scan(destinations...)
if err != nil {
return logSQLError(err, "QueryScalar.load_value.scan", fullSQL, args)
}
setCache(execer, destinations, dtStruct)
return nil
}
if err := rows.Err(); err != nil {
return logSQLError(err, "QueryScalar.load_value.rows_err", fullSQL, args)
}
return dat.ErrNotFound
}
示例15: ScanOne
// ScanOne returns the instance, if any, returned from sql query
func ScanOne(instance interface{}, rows *sqlx.Rows) error {
defer rows.Close()
for rows.Next() {
if err := rows.StructScan(instance); err != nil {
return err
}
}
return nil
}