func rowsToStrings(rows *sql.Rows) [][]string { cols, err := rows.Columns() if err != nil { panic(err) } pretty := [][]string{cols} results := make([]interface{}, len(cols)) for i := range results { results[i] = new(interface{}) } for rows.Next() { if err := rows.Scan(results[:]...); err != nil { panic(err) } cur := make([]string, len(cols)) for i := range results { val := *results[i].(*interface{}) var str string if val == nil { str = "NULL" } else { switch v := val.(type) { case []byte: str = string(v) default: str = fmt.Sprintf("%v", v) } } cur[i] = str } pretty = append(pretty, cur) } return pretty }
func readAll(t *testing.T, rows *sql.Rows) resultSlice { defer rows.Close() cols, err := rows.Columns() if err != nil { t.Fatal(err) } colStrs := make([]*string, len(cols)) for i := range cols { colStrs[i] = &cols[i] } results := resultSlice{colStrs} for rows.Next() { strs := make([]*string, len(cols)) vals := make([]interface{}, len(cols)) for i := range vals { vals[i] = &strs[i] } if err := rows.Scan(vals...); err != nil { t.Fatal(err) } results = append(results, strs) } if err := rows.Err(); err != nil { t.Fatal(err) } return results }
func AllAgents(db *sql.DB, simid []byte, proto string) (ags []AgentInfo, err error) { s := `SELECT AgentId,Kind,Spec,Prototype,ParentId,EnterTime,ExitTime,Lifetime FROM Agents WHERE Agents.SimId = ?` var rows *sql.Rows if proto != "" { s += ` AND Agents.Prototype = ?` rows, err = db.Query(s, simid, proto) } else { rows, err = db.Query(s, simid) } if err != nil { return nil, err } for rows.Next() { ai := AgentInfo{} var exit sql.NullInt64 if err := rows.Scan(&ai.Id, &ai.Kind, &ai.Impl, &ai.Proto, &ai.Parent, &ai.Enter, &exit, &ai.Lifetime); err != nil { return nil, err } if !exit.Valid { exit.Int64 = -1 } ai.Exit = int(exit.Int64) ags = append(ags, ai) } if err := rows.Err(); err != nil { return nil, err } return ags, nil }
func Test_Query(t *testing.T) { conn, err := sql.Open("mysql", TestConnParam) unitest.NotError(t, err) defer conn.Close() var res *sql.Rows res, err = conn.Query("SELECT * FROM test ORDER BY id ASC") unitest.NotError(t, err) defer res.Close() i := 0 for res.Next() { var ( id int64 value string ) err := res.Scan(&id, &value) unitest.NotError(t, err) unitest.Pass(t, id == int64(i)) unitest.Pass(t, value == strconv.Itoa(i)) i++ } unitest.Pass(t, i == 10) }
func (scan *Scan) One(rows *sql.Rows) error { for rows.Next() { return scan.Scan(rows, meta.DirectValueOf(scan.To)) } return errors.New("No matching rows found.") }
func (persister *Persister) GetServiceAgentList(cond string) ([]ServiceAgent, error) { var rows *sql.Rows var err error if cond == "" { rows, err = persister.Db.Query("SELECT service_host,docker_host,docker_port,is_active,perf_factor,ping_interval_secs,last_ping,exec_command,exec_args,portbinding_min,portbinding_max,portbindings FROM serviceagents") } else { rows, err = persister.Db.Query("SELECT service_host,docker_host,docker_port,is_active,perf_factor,ping_interval_secs,last_ping,exec_command,exec_args,portbinding_min,portbinding_max,portbindings FROM serviceagents where " + cond) } if err != nil { return nil, err } defer rows.Close() var serviceagents []ServiceAgent i := 0 for rows.Next() { serviceagent := ServiceAgent{} var timevalue interface{} rows.Scan(&serviceagent.ServiceHost, &serviceagent.DockerHost, &serviceagent.DockerPort, &serviceagent.IsActive, &serviceagent.PerfFactor, &serviceagent.KeepAlive, &timevalue, &serviceagent.ExecCommand, &serviceagent.ExecArgs, &serviceagent.Portbind_min, &serviceagent.Portbind_max, &serviceagent.Portbindings) switch timevalue.(type) { case string: serviceagent.LastPing, err = time.Parse("2006-01-02 15:04:05 ", timevalue.(string)) case time.Time: serviceagent.LastPing = timevalue.(time.Time) } if err != nil { log.Println("error reading row ", err) } serviceagents = append(serviceagents, serviceagent) i = i + 1 } return serviceagents, nil }
func GetResultsTwo(rows *sql.Rows) [][]string { var ( results [][]string //result [][]string id string types string title string message string i int ) results = make([][]string, 1) i = 0 for rows.Next() { err := rows.Scan(&id, &types, &title, &message) if err != nil { //fmt.Println(err) } messages := []string{id, types, title, message} fmt.Println(messages) for index, element := range messages { results[i][index] = element } i++ } return results }
func sqlToMaps(ctx *Ctx, sqlString string, sqlParams ...interface{}) (ret []map[string]interface{}, err error) { ret = []map[string]interface{}{} var rows *sql.Rows rows, err = ctx.db.Query(sqlString, sqlParams...) defer rows.Close() if err != nil { return } columns, err := rows.Columns() if err != nil { return } count := len(columns) values := make([]interface{}, count) valuePtrs := make([]interface{}, count) for i := 0; i < count; i++ { valuePtrs[i] = &values[i] } for rows.Next() { retRow := map[string]interface{}{} rows.Scan(valuePtrs...) for i, col := range columns { val := values[i] switch val.(type) { case []uint8: retRow[col] = string(val.([]uint8)) default: retRow[col] = val } } ret = append(ret, retRow) } return }
func sexDomain(dom string) (sexAnswer bool, err error) { var stmt *sql.Stmt stmt, err = db.Prepare(`SELECT dom FROM domains WHERE dom = $1 AND sex = true LIMIT 1`) if err != nil { fmt.Printf("db.Prepare error: %v\n", err) return false, err } var rows *sql.Rows rows, err = stmt.Query(dom) if err != nil { fmt.Printf("stmt.Query error: %v\n", err) return false, err } defer stmt.Close() if rows.Next() { var domain string err = rows.Scan(&domain) if err != nil { fmt.Printf("rows.Scan error: %v\n", err) return false, err } if configuration.Debug == "Yes" { fmt.Println("domain => \"" + domain + "\"") } return true, err } return false, nil }
func (m *mysql) AuditLog(from, to, limit, offset int64, reverse bool) ([]*proto.ChangeLog, error) { var r *sql.Rows var err error if from == 0 && to == 0 { q := "readLog" if reverse { q += "Desc" } r, err = st[q].Query(limit, offset) } else { q := "readBetween" if reverse { q += "Desc" } r, err = st[q].Query(from, to, limit, offset) } if err != nil { return nil, err } defer r.Close() var logs []*proto.ChangeLog for r.Next() { var id int log := &proto.ChangeLog{ Change: &proto.Change{ ChangeSet: &proto2.ChangeSet{}, }, } if err := r.Scan( &id, &log.Action, &log.Change.Id, &log.Change.Path, &log.Change.Author, &log.Change.Comment, &log.Change.Timestamp, &log.Change.ChangeSet.Timestamp, &log.Change.ChangeSet.Checksum, &log.Change.ChangeSet.Data, &log.Change.ChangeSet.Source, ); err != nil { if err == sql.ErrNoRows { return nil, errors.New("not found") } return nil, err } logs = append(logs, log) } if r.Err() != nil { return nil, err } return logs, nil }
func bmPreparedQuery(b *testing.B) { stmt, err := db.Prepare("SELECT number, str FROM test") if err != nil { panic(err) } var num int64 var str string var i int64 var rows *sql.Rows for rep := 0; rep < 10000; rep++ { rows, err = stmt.Query() if err != nil { panic(err) } i = 0 for rows.Next() { rows.Scan(&num, &str) if num != i { panic(fmt.Sprintf("Result didn't match: %d!=%d", num, i)) } i++ } if i != 100 { panic(fmt.Sprintf("Rows count doesn't match: %d!=100", i)) } } stmt.Close() }
func displayResult(rows *sql.Rows) { cols, cols_err := rows.Columns() if cols_err != nil { log.Fatalln(cols_err) } rawResult := make([][]byte, len(cols)) result := make([]string, len(cols)) dest := make([]interface{}, len(cols)) for i, _ := range cols { dest[i] = &rawResult[i] } for rows.Next() { rows.Scan(dest...) for i, raw := range rawResult { result[i] = string(raw) } for j, v := range result { fmt.Printf("%s", v) if j != len(result)-1 { fmt.Printf(", ") } } fmt.Printf("\n") } }
// getCardsWithWhereQuery returns all of the cards that match a certain WHERE query. func getCardsWithWhereQuery(query string, params ...interface{}) []Card { var cards []Card var err error sqlQ := "select cardbody, cardtype, cardblanks, classic, id, createdon, rating, raters, approved, createdby from %s " + query var rows *sql.Rows if len(params) == 0 { rows = database.GetByQuery(sqlQ) } else { rows = database.GetByQuery(sqlQ, params...) } defer rows.Close() var card Card for rows.Next() { err = rows.Scan(&card.CardBody, &card.CardType, &card.CardBlanks, &card.Classic, &card.ID, &card.CreatedOn, &card.Rating, &card.Raters, &card.Approved, &card.CreatedBy) if err != nil { log.Fatal(err) } cards = append(cards, card) } err = rows.Err() if err != nil { log.Fatal(err) } return cards }
// Query if given upload is expired - an upload thus not having any records which are currently active func (tx *Transaction) QueryExpiredUpload(id string) (result bool, err error) { err = tx.do(func(tx *sql.Tx) (err error) { var rows *sql.Rows rows, err = tx.Query(` SELECT "u"."id" AS "id" FROM "uploads" AS "u" WHERE "u"."id" = $1 GROUP BY "u"."id" HAVING MAX("u"."expiration") < NOW()`, id) if err != nil { return } defer rows.Close() if rows.Next() { result = true } return }) return }
// Query all expired uploads - uploads thus not having any records which are currently active func (tx *Transaction) QueryExpiredUploads() (result []string, err error) { err = tx.do(func(tx *sql.Tx) (err error) { var rows *sql.Rows rows, err = tx.Query(` SELECT "u"."id" AS "id" FROM "uploads" AS "u" GROUP BY "u"."id" HAVING MAX("u"."expiration") < NOW()`) if err != nil { return } defer rows.Close() for rows.Next() { var id string err = rows.Scan(&id) if err != nil { return } result = append(result, id) } return }) return }
// sqlRowsToStrings turns 'rows' into a list of rows, each of which // is a list of column values. // 'rows' should be closed by the caller. // If 'format' is not nil, the values with column name // found in the map are run through the corresponding callback. // It returns the header row followed by all data rows. // If both the header row and list of rows are empty, it means no row // information was returned (eg: statement was not a query). func sqlRowsToStrings(rows *sql.Rows, format fmtMap) ([]string, [][]string, error) { cols, err := rows.Columns() if err != nil { return nil, nil, fmt.Errorf("rows.Columns() error: %s", err) } if len(cols) == 0 { return nil, nil, nil } vals := make([]interface{}, len(cols)) for i := range vals { vals[i] = new(interface{}) } allRows := [][]string{} for rows.Next() { rowStrings := make([]string, len(cols)) if err := rows.Scan(vals...); err != nil { return nil, nil, fmt.Errorf("scan error: %s", err) } for i, v := range vals { if f, ok := format[cols[i]]; ok { rowStrings[i] = f(*v.(*interface{})) } else { rowStrings[i] = formatVal(*v.(*interface{})) } } allRows = append(allRows, rowStrings) } return cols, allRows, nil }
func (gkDbCon *GkDbConDef) getNextChatArchivesId() (int32, *gkerr.GkErrDef) { var stmt *sql.Stmt var err error stmt, err = gkDbCon.sqlDb.Prepare("select nextval('chat_archives_seq')") if err != nil { return 0, gkerr.GenGkErr("sql.Prepare"+getDatabaseErrorMessage(err), err, ERROR_ID_PREPARE) } defer stmt.Close() var rows *sql.Rows rows, err = stmt.Query() if err != nil { return 0, gkerr.GenGkErr("stmt.Query"+getDatabaseErrorMessage(err), err, ERROR_ID_QUERY) } defer rows.Close() var id int32 if rows.Next() { err = rows.Scan(&id) if err != nil { return 0, gkerr.GenGkErr("rows.Scan"+getDatabaseErrorMessage(err), err, ERROR_ID_ROWS_SCAN) } } else { return 0, gkerr.GenGkErr("select users", nil, ERROR_ID_NO_ROWS_FOUND) } return id, nil }
// sql_ := fmt.Sprintf(`SELECT "Json" %s where `+p.wheresql, p.getFrom()) // var rows *sql.Rows // if rows, p.Err = p._query(sql_, p.whereargs...); p.NotErr() { // defer rows.Close() // for rows.Next() { // var v []byte // rows.Scan(&v) // obj := reflect.New(p.model.Type).Interface() // json.Unmarshal(v, obj) // slicev = reflect.Append(slicev, reflect.ValueOf(obj).Elem()) // } // resultv.Elem().Set(slicev.Slice(0, slicev.Len())) // } // return p //} func (p *Scope) PageJson(lst T, page, perPage int) (pager db.Paging) { p.checkModel(lst) pf := filter.NewPageFilter(page, perPage) p.Limit(pf.Skip(), perPage) pager.Total = p.Count(lst) // log.Println(pager.Total) resultv := reflect.ValueOf(lst) if resultv.Kind() != reflect.Ptr || resultv.Elem().Kind() != reflect.Slice { panic("out argument must be a slice address") } slicev := resultv.Elem() wsa := p.buildWhere() pas := p.buildPage() sql_ := fmt.Sprintf(`SELECT "Json" %s `+wsa.Sql+" "+pas.Sql, p.getFrom()) var rows *sql.Rows if rows, p.Err = p._query(sql_, wsa.Args...); p.NotErr() { defer rows.Close() for rows.Next() { var v []byte rows.Scan(&v) obj := reflect.New(p.model.Type).Interface() json.Unmarshal(v, obj) slicev = reflect.Append(slicev, reflect.ValueOf(obj).Elem()) } resultv.Elem().Set(slicev.Slice(0, slicev.Len())) } pager.Items = lst // log.Println(lst) return }
func (gkDbCon *GkDbConDef) getMaxChatId() (int32, *gkerr.GkErrDef) { var stmt *sql.Stmt var maxId int32 = 0 var err error stmt, err = gkDbCon.sqlDb.Prepare("select max(id) from chat_archives") if err != nil { return 0, gkerr.GenGkErr("sql.Prepare"+getDatabaseErrorMessage(err), err, ERROR_ID_PREPARE) } defer stmt.Close() var rows *sql.Rows rows, err = stmt.Query() if err != nil { return 0, gkerr.GenGkErr("stmt.Query"+getDatabaseErrorMessage(err), err, ERROR_ID_QUERY) } defer rows.Close() if rows.Next() { err = rows.Scan(&maxId) if err != nil { return 0, gkerr.GenGkErr("rows.Scan"+getDatabaseErrorMessage(err), err, ERROR_ID_ROWS_SCAN) } } return maxId, nil }
func sqlToStringsMaps(ctx *Ctx, sqlString string, sqlParams ...interface{}) (ret []map[string]string, err error) { ret = []map[string]string{} var rows *sql.Rows rows, err = ctx.db.Query(sqlString, sqlParams...) defer rows.Close() if err != nil { return } columns, err := rows.Columns() if err != nil { return } count := len(columns) values := make([]sql.NullString, count) // Без NullString невозможно определить, когда NULL valuePtrs := make([]interface{}, count) for i := 0; i < count; i++ { valuePtrs[i] = &values[i] } for rows.Next() { retRow := map[string]string{} rows.Scan(valuePtrs...) for i, col := range columns { retRow[col] = values[i].String } ret = append(ret, retRow) } return }
func (p *Scope) AllJson(lst T) *Scope { p.checkModel(lst) p.Select(p.orm.mapper("Json")) p.From(p.model.Name) resultv := reflect.ValueOf(lst) if resultv.Kind() != reflect.Ptr || resultv.Elem().Kind() != reflect.Slice { panic("out argument must be a slice address") } slicev := resultv.Elem() sa := p.builder.SqlSelect() var rows *sql.Rows if rows, p.Err = p._query2(sa); p.NotErr() { defer rows.Close() for rows.Next() { var v []byte rows.Scan(&v) obj := reflect.New(p.model.Type).Interface() json.Unmarshal(v, obj) slicev = reflect.Append(slicev, reflect.ValueOf(obj).Elem()) } resultv.Elem().Set(slicev.Slice(0, slicev.Len())) } return p }
func dataSiteProto(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result { var err error var rows *sql.Rows if rows, err = dbR.Query(`SELECT siteID, latitude, longitude FROM data.site`); err != nil { return weft.InternalServerError(err) } var ts mtrpb.DataSiteResult for rows.Next() { var t mtrpb.DataSite if err = rows.Scan(&t.SiteID, &t.Latitude, &t.Longitude); err != nil { return weft.InternalServerError(err) } ts.Result = append(ts.Result, &t) } var by []byte if by, err = proto.Marshal(&ts); err != nil { return weft.InternalServerError(err) } b.Write(by) return &weft.StatusOK }
func validate_result_of_sp(dbt *DBTest, rows *sql.Rows) { // final OK packet , indicate last INSERT effected rows // https://dev.mysql.com/doc/internals/en/multi-resultset.html if res, ok := rows.Sibling(); false == ok { dbt.Fatal("there should be a last ok packet.") } else if nil == res { dbt.Fatal("last packet of CALL should return a Result.") } else { if affcted, err := res.RowsAffected(); nil != err { dbt.Fatal("should not return err when RowsAffected") } else if 1 != affcted { dbt.Fatal("Last INSERT STMT in SP should affected one row. ") } if insertId, err := res.LastInsertId(); nil != err { dbt.Fatal("should not return err when LastInsertId") } else if 0 != insertId { dbt.Fatalf("Last INSERT STMT in SP should not return LAST_INSERT_ID:%d ", insertId) } if true == rows.Next() { dbt.Fatal("last packet has no rows, but just affected rows and last insert id") } } }
func validate_multi_second_select(dbt *DBTest, rows *sql.Rows) { if _, ok := rows.Sibling(); false == ok { dbt.Fatal("rows should have a another sibling.") } if false == rows.Next() { dbt.Fatalf("should be one row exists.\n") } if err := rows.Scan(&id, &fv, &id2); err != nil { dbt.Fatalf("should not get error :%s\n", err.Error()) } if 323890472 != id { dbt.Fatalf("expect 323890472, but got %d\n", id) } if math.Abs(42342.43-float64(fv)) > 0.01 { dbt.Fatalf("expect 42342.432, but not got %+v\n", fv) } if rows.Next() { dbt.Fatal("rows should not have more than one row.") } if 298723987 != id2 { dbt.Fatalf("expect 298723987, but got %d\n", id2) } }
func fieldModelProto(r *http.Request, h http.Header, b *bytes.Buffer) *weft.Result { var err error var rows *sql.Rows if rows, err = dbR.Query(`SELECT modelID FROM field.model`); err != nil { return weft.InternalServerError(err) } var fmr mtrpb.FieldModelResult for rows.Next() { var t mtrpb.FieldModel if err = rows.Scan(&t.ModelID); err != nil { return weft.InternalServerError(err) } fmr.Result = append(fmr.Result, &t) } var by []byte if by, err = proto.Marshal(&fmr); err != nil { return weft.InternalServerError(err) } b.Write(by) return &weft.StatusOK }
// scan a single row of data into a struct. func (data *structData) scanRow(rows *sql.Rows, dst interface{}, columns []string) error { // check if there is data waiting if !rows.Next() { if err := rows.Err(); err != nil { return err } return sql.ErrNoRows } // get a list of targets targets, err := Targets(dst, columns) if err != nil { return err } // perform the scan if err := rows.Scan(targets...); err != nil { return err } // post-process and copy the target values into the struct if err := WriteTargets(dst, columns, targets); err != nil { return err } return rows.Err() }
/* Copies *sql.Rows into the slice of maps or structs given by the pointer dst. */ func (self *T) FetchRow(dst interface{}, rows *sql.Rows) error { dstv := reflect.ValueOf(dst) if dstv.IsNil() || dstv.Kind() != reflect.Ptr { return db.ErrExpectingPointer } itemv := dstv.Elem() columns, err := getRowColumns(rows) if err != nil { return err } next := rows.Next() if next == false { return db.ErrNoMoreRows } item, err := self.fetchResult(itemv.Type(), rows, columns) if err != nil { return err } itemv.Set(reflect.Indirect(item)) return nil }
//Parse an executed query func (dbw *Sqlite3) Parse(rows *sql.Rows) (results Results, err error) { // here im not sure what im getting from the db as it can be anything from the results //therefore i wish i can just put everything in a bucket, and think later. tc, tn := dbw.TotalCount(rows) // multiFields := make([]interface{}, tc) multiFieldsPtrs := make([]interface{}, tc) for i := 0; i < tc; i++ { var multiFields interface{} multiFieldsPtrs[i] = &multiFields } headers := make(map[string]interface{}) headers["fields"] = tn results = append(results, headers) for rows.Next() { err = rows.Scan(multiFieldsPtrs...) checkErrors(err) tempMap := make(map[string]interface{}) for idx, label := range tn { row := *(multiFieldsPtrs[idx].(*interface{})) // if sizeOf(row) < 1 { // skip = true // break // } tempMap[label] = row } results = append(results, tempMap) } return }
func populateTechSupports(rows *sql.Rows, ch chan []TechSupport) { var t TechSupport var ts []TechSupport for rows.Next() { err := rows.Scan( &t.ID, &t.VehicleMake, &t.VehicleModel, &t.VehicleYear, &t.PurchaseDate, &t.PurchasedFrom, &t.DealerName, &t.ProductCode, &t.DateCode, &t.Issue, &t.Contact.ID, &t.BrandID, ) if err != nil { ch <- ts } ts = append(ts, t) } defer rows.Close() ch <- ts return }
// ListSecrets returns an iterator function that walks through all secrets in the database. // The iterator takes an integer argument, which is the maximum number of results to return per iteration. // If a key name is specified, the results are limited to secrets shared with that key. func (p *DB) ListSecrets(key *string) func(int) ([]secrets.Secret, error) { pos := 0 return func(n int) (res []secrets.Secret, err error) { if err := p.refresh(); err != nil { return nil, err } var rows *sql.Rows if key != nil { rows, err = p.conn.Table("secrets").Select( "secrets.id, secrets.name, secrets.message, secrets.nonce, secrets.pubkey, secrets.key_id").Joins( "left join keys on secrets.key_id = keys.id").Where( "keys.name = ?", *key).Order("id asc").Limit(n).Offset(pos).Rows() } else { rows, err = p.conn.Table("secrets").Select("id, name, message, nonce, pubkey, key_id").Order("id asc").Limit(n).Offset(pos).Rows() } for rows.Next() { out := new(secrets.Secret) err = rows.Scan(&out.ID, &out.Name, &out.Message, &out.Nonce, &out.Pubkey, &out.KeyID) if err != nil { return } res = append(res, *out) } err = rows.Close() pos += len(res) return } }