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 DBGetPermissions(dbConn *sql.DB) ([]Permission, error) { slice := []Permission{} //logit.Info.Println("secdb:GetPermissions: called") var rows *sql.Rows var err error queryStr := fmt.Sprintf("select name, description from secperm order by name") rows, err = dbConn.Query(queryStr) if err != nil { return slice, err } defer rows.Close() for rows.Next() { perm := Permission{} perm.Selected = false if err = rows.Scan( &perm.Name, &perm.Description); err != nil { return slice, err } slice = append(slice, perm) } if err = rows.Err(); err != nil { return slice, err } return slice, nil }
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 }
// 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() }
func (s *StoreSqlite) scanUserFromRows(rows *sql.Rows, user *User) error { if rows.Err() != nil { return rows.Err() } if user == nil { return ErrInvalidUser } var params []interface{} columns, err := rows.Columns() if err != nil { return err } for i := range columns { col := columns[i] switch strings.ToLower(col) { case "id": params = append(params, &user.UserID) case "name": params = append(params, &user.Name) case "email": params = append(params, &user.Email) case "key": params = append(params, &user.Key) } } return rows.Scan(params...) }
func scanCards(rows *sql.Rows, r router) ([]Card, error) { cards := []Card{} defer rows.Close() for rows.Next() { var blob []byte var card Card if err := rows.Scan(&blob); err != nil { return cards, err } err := json.Unmarshal(blob, &card) if err != nil { return cards, err } cards = append(cards, card) } if err := rows.Err(); err != nil { return cards, err } for i, _ := range cards { cards[i].Fill(r) } return cards, nil }
func (tca *TCA) getCertificateSets(enrollmentID string) ([]*TCertSet, error) { var sets = []*TCertSet{} var err error var rows *sql.Rows rows, err = tca.retrieveCertificateSets(enrollmentID) if err != nil { return nil, err } defer rows.Close() var enrollID string var timestamp int64 var nonce []byte var kdfKey []byte for rows.Next() { if err = rows.Scan(&enrollID, ×tamp, &nonce, &kdfKey); err != nil { return nil, err } sets = append(sets, &TCertSet{Ts: timestamp, EnrollmentID: enrollID, Key: kdfKey}) } if err = rows.Err(); err != nil { return nil, err } return sets, nil }
func (db *StatsDB) streamRows(result *sql.Rows, out chan Stats) { var err error defer result.Close() LOOP: for result.Next() && result.Err() == nil { var stat Stats var info string stat.Info = make(map[string]string) err = result.Scan(&stat.Id, &stat.System, &stat.SubSystem, &stat.Message, &stat.Context, &stat.ServerTime, &stat.ClientTime, &stat.Error, &info) if err != nil { printf("error scanning database: %v", err) break } dec := json.NewDecoder(bytes.NewBufferString(info)) err = dec.Decode(&stat.Info) if err != nil { printf("error decoding info from record: %v", err) break } select { case out <- stat: case <-time.After(time.Second * 10): break LOOP } } close(out) }
func GetAllContainers(dbConn *sql.DB) ([]Container, error) { var rows *sql.Rows var err error queryStr := fmt.Sprintf("select c.id, c.name, c.clusterid, c.serverid, c.role, c.image, to_char(c.createdt, 'MM-DD-YYYY HH24:MI:SS'), p.id, p.name, s.name from project p, server s , container c where c.projectid = p.id and c.serverid = s.id order by c.name") logit.Info.Println("admindb:GetAllContainers:" + queryStr) rows, err = dbConn.Query(queryStr) if err != nil { return nil, err } defer rows.Close() var clustername string containers := make([]Container, 0) for rows.Next() { container := Container{} if err = rows.Scan(&container.ID, &container.Name, &container.ClusterID, &container.ServerID, &container.Role, &container.Image, &container.CreateDate, &container.ProjectID, &container.ProjectName, &container.ServerName); err != nil { return nil, err } logit.Info.Println("cluster id is [" + container.ClusterID + "]") if container.ClusterID != "-1" { clustername, err = GetClusterName(dbConn, container.ClusterID) if err != nil { logit.Info.Println("admindb:GetAllContainers:error " + err.Error()) return nil, err } container.ClusterName = clustername } containers = append(containers, container) } if err = rows.Err(); err != nil { return nil, err } return containers, nil }
func GetDbListTemplate(queryMap map[string]string, dbCountFunc DbCountFunc, dbRowsFunc DbRowsFunc, dbListFunc DbListFunc) { var rows *sql.Rows var err error err = dbCountFunc(&queryMap) if err != nil { log.Fatal(err) } // get rows rows, err = dbRowsFunc(&queryMap) if err != nil { log.Fatal(err) } defer rows.Close() // create list for rows.Next() { err = dbListFunc(rows) if err != nil { log.Fatal(err) } } err = rows.Err() if err != nil { log.Fatal(err) } }
// GetHealthCheck return the current set of healthcheck metrics that are persisted func GetHealthCheck(dbConn *sql.DB) ([]types.HealthCheck, error) { var rows *sql.Rows var err error rows, err = dbConn.Query( "select ID, ProjectName, ProjectID, ContainerName, ContainerID, " + "ContainerRole, ContainerImage, Status, to_char(UpdateDt, 'MM-DD-YYYY HH24:MI:SS') " + "from healthcheck order by ProjectName, ContainerName") if err != nil { return nil, err } defer rows.Close() var checks []types.HealthCheck checks = make([]types.HealthCheck, 0) for rows.Next() { check := types.HealthCheck{} if err = rows.Scan( &check.ID, &check.ProjectName, &check.ProjectID, &check.ContainerName, &check.ContainerID, &check.ContainerRole, &check.ContainerImage, &check.Status, &check.UpdateDate); err != nil { return nil, err } checks = append(checks, check) } if err = rows.Err(); err != nil { return nil, err } return checks, nil }
func getPushCount(customerId, tenantId string) int { count := 0 var rows *sql.Rows var err error //查询customer下的所有租户调用次数 if tenantId == "*" { rows, err = db.MySQL.Query(GET_CUSTOMER_PUSH_COUNT, customerId) } else { rows, err = db.MySQL.Query(GET_PUSH_COUNT, customerId, tenantId) } if rows != nil { defer rows.Close() } if err != nil { logger.Error(err) return count } if err = rows.Err(); err != nil { logger.Error(err) return count } //取出count for rows.Next() { if err = rows.Scan(&count); err != nil { //logger.Error(err) return count } return count } return count }
func ScanAuthors(rows *sql.Rows) ([]*Author, error) { var err error var vv []*Author var v0 string var v1 string var v2 string for rows.Next() { err = rows.Scan( &v0, &v1, &v2, ) if err != nil { return vv, err } v := &Author{} v.Name = v0 v.Email = v1 v.Username = v2 vv = append(vv, v) } return vv, rows.Err() }
func (l *Lib) List(limit, offset int) (pics []*Pic, err error) { s := "SELECT id,sum,name,added,taken,orient FROM files ORDER BY taken DESC,added DESC" var rows *sql.Rows if limit > 0 { s += " LIMIT ? OFFSET ?" rows, err = l.db.Query(s, limit, offset) } else { rows, err = l.db.Query(s) } if err != nil { return nil, err } defer rows.Close() var added, taken int64 for rows.Next() { p := &Pic{lib: l} err := rows.Scan(&p.id, &p.Sum, &p.Name, &added, &taken, &p.Orient) if err != nil { return nil, err } p.Id = p.id p.Taken = time.Unix(taken, 0) p.Added = time.Unix(added, 0) pics = append(pics, p) } if err := rows.Err(); err != nil { return nil, err } return pics, nil }
// queryInvocations is a common handler for implementing paging over Invocations func queryInvocations(rows *sql.Rows, pageSize int) (result gohst.Invocations, err error) { defer rows.Close() var tmp gohst.Invocation var tags string inc := 0 if pageSize == 0 { inc = -1 } for rows.Next() && inc < pageSize { err = rows.Scan(&tmp.Id, &tmp.ExitCode, &tmp.Timestamp, &tmp.Host, &tmp.User, &tmp.Shell, &tmp.Directory, &tmp.Command, &tags) if err != nil { log.Println(err) return } tmp.Tags = strings.Split(tags[1:len(tags)-1], ", ") result = append(result, tmp) if pageSize > 0 { inc++ } } err = rows.Err() if err != nil { log.Println(err) } return }
func (self *t) qlFetchRow(dst interface{}, rows *sql.Rows) error { dstv := reflect.ValueOf(dst) if dstv.IsNil() || dstv.Kind() != reflect.Ptr { return db.ErrExpectingPointer } item_v := dstv.Elem() columns, err := sqlutil.GetRowColumns(rows) if err != nil { return err } next := rows.Next() if next == false { if err = rows.Err(); err != nil { return err } return db.ErrNoMoreRows } item, err := self.qlFetchResult(item_v.Type(), rows, columns) if err != nil { return err } item_v.Set(reflect.Indirect(item)) return nil }
func (db *StatsDB) streamBuckets(result *sql.Rows, out chan Bucket) { var err error defer result.Close() LOOP: for result.Next() && result.Err() == nil { var bucket Bucket var info string bucket.Info = make(map[string]interface{}) err = result.Scan(&bucket.Id, &bucket.ServerTime, &bucket.Bucket, &info) if err != nil { printf("error scanning database: %v", err) break LOOP } dec := json.NewDecoder(bytes.NewBufferString(info)) err = dec.Decode(&bucket.Info) if err != nil { printf("error decoding info from record: %v", err) break LOOP } select { case out <- bucket: case <-time.After(time.Second * 10): break LOOP } } close(out) }
func GetAllServersByClassByCount(dbConn *sql.DB) ([]Server, error) { //select s.id, s.name, s.serverclass, count(n) from server s left join node n on s.id = n.serverid group by s.id order by s.serverclass, count(n); logit.Info.Println("admindb:GetAllServerByClassByCount:called") var rows *sql.Rows var err error rows, err = dbConn.Query("select s.id, s.name, s.ipaddress, s.dockerbip, s.pgdatapath, s.serverclass, to_char(s.createdt, 'MM-DD-YYYY HH24:MI:SS'), count(n) from server s left join container n on s.id = n.serverid group by s.id order by s.serverclass, count(n)") if err != nil { return nil, err } defer rows.Close() servers := make([]Server, 0) for rows.Next() { server := Server{} if err = rows.Scan(&server.ID, &server.Name, &server.IPAddress, &server.DockerBridgeIP, &server.PGDataPath, &server.ServerClass, &server.CreateDate, &server.NodeCount); err != nil { return nil, err } servers = append(servers, server) } if err = rows.Err(); err != nil { return nil, err } return servers, nil }
// Recursively populate dest with the data from rows, using t as a template to // generate a flat slice of destinations to rows.Scan into. After that, the // values from the flat slice will be recursively copied into dest by doing a // linear search through the slice, matching against the current row's primary // key, appending new values to dest, its children's children, etc. as needed. // // TODO: use iterative or something instead of like 4 different recursive // functions func queryJoinSlice(t reflect.Type, dest interface{}, rows *sql.Rows) error { dests, idIndexes, err := getDests(t) if err != nil { return err } //dump(dests) columns, err := rows.Columns() if err != nil { return err } dv := reflect.ValueOf(dest) //dump(dests) for rows.Next() { if err = rows.Scan(dests...); err != nil { return err } //dump(dests) err = insertIntoTree(dv, dests, idIndexes, columns) if err != nil { return err } if err = rows.Err(); err != nil { return err } } return nil }
func GetAllSettingsMap(dbConn *sql.DB) (map[string]string, error) { logit.Info.Println("admindb:GetAllSettingsMap: called") m := make(map[string]string) var rows *sql.Rows var err error rows, err = dbConn.Query("select name, value, to_char(updatedt, 'MM-DD-YYYY HH24:MI:SS') from settings order by name") if err != nil { return m, err } defer rows.Close() //settings := make([]Setting, 0) for rows.Next() { setting := Setting{} if err = rows.Scan( &setting.Name, &setting.Value, &setting.UpdateDate); err != nil { return m, err } m[setting.Name] = setting.Value //settings = append(settings, setting) } if err = rows.Err(); err != nil { return m, err } return m, nil }
func (c *Connection) getSchemaColumns(schema string, table string) ([]*SchemaColumn, error) { var rows *sql.Rows var err error if rows, err = c.ctrDB.Query(` SELECT COLUMN_NAME, COLLATION_NAME, CHARACTER_SET_NAME, COLUMN_COMMENT, COLUMN_TYPE, COLUMN_KEY FROM COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?`, schema, table); err != nil { return nil, err } defer rows.Close() var cols []*SchemaColumn for rows.Next() { col := &SchemaColumn{} if err = rows.Scan(&col.COLUMN_NAME, &col.COLLATION_NAME, &col.CHARACTER_SET_NAME, &col.COLUMN_COMMENT, &col.COLUMN_TYPE, &col.COLUMN_KEY); err != nil { return nil, err } cols = append(cols, col) } if err = rows.Err(); err != nil { return nil, err } return cols, nil }
func GetContainerUser(dbConn *sql.DB, containername string, usename string) (ContainerUser, error) { var rows *sql.Rows var user ContainerUser var err error queryStr := fmt.Sprintf("select id, passwd, to_char(updatedt, 'MM-DD-YYYY HH24:MI:SS') from containeruser where usename = '%s' and containername = '%s'", usename, containername) logit.Info.Println("admindb:GetContainerUser:" + queryStr) rows, err = dbConn.Query(queryStr) if err != nil { return user, err } defer rows.Close() for rows.Next() { user.Rolname = usename user.Containername = containername if err = rows.Scan(&user.ID, &user.Passwd, &user.UpdateDate); err != nil { return user, err } } if err = rows.Err(); err != nil { return user, err } var unencrypted string unencrypted, err = sec.DecryptPassword(user.Passwd) if err != nil { return user, err } user.Passwd = unencrypted return user, nil }
// 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 }
// Queries the database for sensors and transforms them // to struct format func getSensorsFromDb(sensor_ids []uint64) ([]Sensor, error) { // Select all sensors var rows *sql.Rows var err error if sensor_ids == nil { rows, err = DB.Query("SELECT * FROM sensors LIMIT 50") } else if len(sensor_ids) == 1 { rows, err = DB.Query("SELECT * FROM sensors WHERE id=$1", sensor_ids[0]) } else { sql := "SELECT * FROM sensors WHERE id in (?" + strings.Repeat(",?", len(sensor_ids)-1) + ")" rows, err = DB.Query(sql, sensor_ids) } if err != nil { fmt.Println(err) return nil, err } var sensors []Sensor for rows.Next() { var sensor Sensor err := rows.Scan(&(sensor.Id), &(sensor.Type), &(sensor.Name), &(sensor.CreatedAt), &(sensor.UpdatedAt)) if err != nil { fmt.Println(err) continue } sensors = append(sensors, sensor) } if err := rows.Err(); err != nil { fmt.Println(err) } return sensors, err }
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 rows2MapsArray(rows *sql.Rows) (maps []map[string]interface{}, err error) { cols, err := rows.Columns() if err != nil { return nil, err } vals := make([]interface{}, len(cols)) // values ptrs := make([]interface{}, len(cols)) // Pointers to values for i := range vals { ptrs[i] = &vals[i] // Initialize pointer } maps = []map[string]interface{}{} for rows.Next() { if err := rows.Scan(ptrs...); err != nil { // Scan will fill in 'vals' using 'ptrs' return nil, err } job := map[string]interface{}{} for i, col := range cols { if b, isBytes := vals[i].([]byte); isBytes { job[col] = string(b) // Convert []byte to string. No one wants []byte values. } else { job[col] = vals[i] } } maps = append(maps, job) } if err = rows.Err(); err != nil { return nil, err } return maps, nil }
func TestLongData(t *testing.T) { runTests(t, dsn, func(dbt *DBTest) { var maxAllowedPacketSize int err := dbt.db.QueryRow("select @@max_allowed_packet").Scan(&maxAllowedPacketSize) if err != nil { dbt.Fatal(err) } maxAllowedPacketSize-- // don't get too ambitious if maxAllowedPacketSize > 1<<25 { maxAllowedPacketSize = 1 << 25 } dbt.mustExec("CREATE TABLE test (value LONGBLOB)") in := strings.Repeat(`a`, maxAllowedPacketSize+1) var out string var rows *sql.Rows // Long text data const nonDataQueryLen = 28 // length query w/o value inS := in[:maxAllowedPacketSize-nonDataQueryLen] dbt.mustExec("INSERT INTO test VALUES('" + inS + "')") rows = dbt.mustQuery("SELECT value FROM test") if rows.Next() { rows.Scan(&out) if inS != out { dbt.Fatalf("LONGBLOB: length in: %d, length out: %d", len(inS), len(out)) } if rows.Next() { dbt.Error("LONGBLOB: unexpexted row") } } else { dbt.Fatalf("LONGBLOB: no data") } // Empty table dbt.mustExec("TRUNCATE TABLE test") // Long binary data dbt.mustExec("INSERT INTO test VALUES(?)", in) rows = dbt.mustQuery("SELECT value FROM test WHERE 1=?", 1) if rows.Next() { rows.Scan(&out) if in != out { dbt.Fatalf("LONGBLOB: length in: %d, length out: %d", len(in), len(out)) } if rows.Next() { dbt.Error("LONGBLOB: unexpexted row") } } else { if err = rows.Err(); err != nil { dbt.Fatalf("LONGBLOB: no data (err: %s)", err.Error()) } else { dbt.Fatal("LONGBLOB: no data (err: <nil>)") } } }) }
func readAll(t *testing.T, rows *sql.Rows) [][]string { cols, err := rows.Columns() if err != nil { t.Fatal(err) } var results [][]string results = append(results, cols) 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 ScanUsers(rs *sql.Rows) ([]User, error) { log.Info("ScanUsers Id 000") structs := make([]User, 0, 16) log.Info("ScanUsers Id 111") var err error for rs.Next() { log.Info("ScanUsers Id 3333") var s User // var s = new(User) if err = rs.Scan( &s.Id, &s.Idp_user_id, &s.Name, &s.Last_updated, &s.Status, &s.User_attributes, ); err != nil { continue } if err == nil { log.Info("ScanUsers Id 111") // + string(s.Id)) structs = append(structs, s) } } if err = rs.Err(); err != nil { return nil, err } return structs, nil }
func pagination(ex db.Executor, page int, perPage int) (*[]dashboardEntry, error) { var entries []dashboardEntry var err error var rows *sql.Rows offset := perPage * page if rows, err = ex.Query(paginationSQL, offset, perPage); err != nil { return &entries, err } defer rows.Close() for rows.Next() { var e dashboardEntry err = rows.Scan( &e.Name, &e.ThumbnailID, &e.Slug, &e.CreatedAt, ) if err != nil { log.Fatal(err) } entries = append(entries, e) } if err = rows.Err(); err != nil { log.Fatal(err) } return &entries, err }