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 GetResult(rows *sql.Rows) ([]interface{}, []string) { if rows == nil { panic("rows is null") } columns, err := rows.Columns() if err != nil { panic(err.Error()) } values := make([]interface{}, len(columns)) scan_args := make([]interface{}, len(columns)) for i := range values { scan_args[i] = &values[i] } var ret []interface{} for rows.Next() { err = rows.Scan(scan_args...) if err != nil { panic(err.Error()) } row := ResultRow{} for i, col_name := range columns { row[col_name] = values[i] } ret = append(ret, row) } return ret, columns }
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 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") } }
// Converts sql.Rows into QueryResults. func NewQueryResults(rows *sql.Rows, rowLimit int) *QueryResults { columns, err := rows.Columns() if err != nil { return &QueryResults{Error: err} } data := make([][]string, 0) row := 1 for rows.Next() && row < rowLimit { stringValues := make([]string, len(columns)+1) stringValues[0] = strconv.Itoa(row) pointers := make([]interface{}, len(columns)) for i := 0; i < len(columns); i++ { pointers[i] = &stringValues[i+1] } if err := rows.Scan(pointers...); err != nil { return &QueryResults{Error: err} } data = append(data, stringValues) row += 1 } return &QueryResults{ Columns: append([]string{"Row"}, columns...), Data: data, } }
func GetKotobaFromRows(rows *sql.Rows) *[]Kotoba { // get data from rows var kotobaArray []Kotoba columns, err := rows.Columns() values := make([]sql.RawBytes, len(columns)) scanArgs := make([]interface{}, len(values)) for i := range values { scanArgs[i] = &values[i] } //var kotoba Kotoba for rows.Next() { err = rows.Scan(scanArgs...) if err != nil { panic(err.Error()) } var kotoba Kotoba kotoba.Id = GetIntValue(values[0]) kotoba.User_id = GetIntValue(values[1]) kotoba.Goi = GetStringValue(values[2]) kotoba.Hatsuon = GetStringValue(values[3]) kotoba.Hatsuon_ = GetStringValue(values[4]) kotoba.Imi = GetStringValue(values[5]) kotoba.Imi_ = GetStringValue(values[6]) kotoba.Level = GetIntValue(values[7]) kotoba.Review = GetStringValue(values[8]) kotoba.Unlocked = GetStringValue(values[9]) //fmt.Println(kotoba) kotobaArray = append(kotobaArray, kotoba) } return &kotobaArray }
// Show writes the sql.Rows given to the destination in tablewriter basic format. func (prettyCsvOutput *PrettyCSVOutput) Show(rows *sql.Rows) { cols, colsErr := rows.Columns() if colsErr != nil { log.Fatalln(colsErr) } if prettyCsvOutput.options.WriteHeader { prettyCsvOutput.writer.SetHeader(cols) prettyCsvOutput.writer.SetHeaderLine(true) prettyCsvOutput.writer.SetAutoFormatHeaders(false) } 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) } prettyCsvOutput.writer.Append(result) } prettyCsvOutput.writer.Render() rows.Close() }
func DisplayResults(rows *sql.Rows) error { defer rows.Close() columns, err := rows.Columns() if err != nil { return err } var ( w = tabwriter.NewWriter(os.Stdout, 10, 1, 3, ' ', 0) num = len(columns) format = fmt.Sprintf("%s\n", getNumTabs(num)) values = make([]interface{}, num) strs = make([]string, num) ) for i := 0; i < num; i++ { values[i] = &strs[i] } fmt.Fprintf(w, format, toInterface(columns)...) for rows.Next() { if err := rows.Scan(values...); err != nil { return err } fmt.Fprintf(w, format, toInterface(strs)...) } return w.Flush() }
func ParseResults(r *sql.Rows) ResultSet { cols, _ := r.Columns() var newMapSlice = ResultSet{} var counter int = 0 for r.Next() { counter = counter + 1 var newRow = make(Result) var scanargs = make([]interface{}, len(cols)) var scanvals = make([]interface{}, len(cols)) for i := range scanargs { scanargs[i] = &scanvals[i] } r.Scan(scanargs...) for i, columnname := range cols { if scanvals[i] != nil { if reflect.TypeOf(scanvals[i]).String() == "[]uint8" { newRow[columnname] = string(scanvals[i].([]byte)) } else { newRow[columnname] = scanvals[i] } } } newMapSlice = append(newMapSlice, newRow) } return newMapSlice }
func GetResult(rows *sql.Rows) ([]interface{}, []string) { if rows == nil { panic("rows is null") } columns, err := rows.Columns() if err != nil { panic(err.Error()) // proper error handling instead of panic in your app } values := make([]interface{}, len(columns)) scan_args := make([]interface{}, len(columns)) for i := range values { scan_args[i] = &values[i] } var ret []interface{} for rows.Next() { err = rows.Scan(scan_args...) if err != nil { panic(err.Error()) // proper error handling instead of panic in your app } //TODO //row := makeRow(columns, scan_args...) //row := make(ResultRow, len(columns)) //var row ResultRow row := ResultRow{} for i, col_name := range columns { row[col_name] = values[i] } ret = append(ret, row) } return ret, columns }
func (m *Mysql) RowsToMap(rows *sql.Rows) (map[string]interface{}, error) { result := make(map[string]interface{}) fields, err := rows.Columns() if err != nil { loger.Print(err.Error()) return nil, err } var containers []interface{} for i := 0; i < len(fields); i++ { var container interface{} containers = append(containers, &container) } if err := rows.Scan(containers...); err != nil { return nil, err } for index, field := range fields { rawValue := reflect.Indirect(reflect.ValueOf(containers[index])) if rawValue.Interface() != nil { result[field] = rawValue.Interface() } } return result, nil }
func CreateMapsFromRows(rows *sql.Rows, types ...interface{}) (RecordMapList, error) { var err error columnNames, err := rows.Columns() if err != nil { return nil, err } // create interface var values []interface{} var reflectValues []reflect.Value var results RecordMapList values, reflectValues = sqlutils.CreateReflectValuesFromTypes(types) for rows.Next() { var result = RecordMap{} if err = rows.Scan(values...); err != nil { return nil, err } for i, name := range columnNames { result[name] = reflectValues[i].Elem().Interface() } results = append(results, result) } return results, nil }
func getResultMap(query *sql.Rows) (res map[int]map[string]string) { cols, err := query.Columns() if err != nil { log.Fatal(err) } scanArgs := make([]interface{}, len(cols)) vals := make([][]byte, len(cols)) for i, _ := range cols { scanArgs[i] = &vals[i] } //最后得到的map results := make(map[int]map[string]string) i := 0 for query.Next() { err := query.Scan(scanArgs...) if err != nil { log.Fatal(err) } row := make(map[string]string) //每行数据 for k, v := range vals { //每行数据是放在values里面,现在把它挪到row里 key := cols[k] row[key] = string(v) } results[i] = row //装入结果集中 i++ } return results }
func QueryResult(rows *sql.Rows) map[int]map[string]string { var result = make(map[int]map[string]string) columns, _ := rows.Columns() values := make([]sql.RawBytes, len(columns)) scanargs := make([]interface{}, len(values)) for i := range values { scanargs[i] = &values[i] } var n = 1 for rows.Next() { result[n] = make(map[string]string) err := rows.Scan(scanargs...) if err != nil { fmt.Println(err) } for i, v := range values { result[n][columns[i]] = string(v) } n++ } return result }
func displayResult(rows *sql.Rows, outputHeader *bool, sep rune) { cols, cols_err := rows.Columns() if cols_err != nil { log.Fatalln(cols_err) } out := csvWriter{csv.NewWriter(os.Stdout)} out.Comma = sep if *outputHeader { out.put(cols) } 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) } out.put(result) } out.Flush() }
// 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 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 GetNewsFromRow(rows *sql.Rows) *[]News { // get data from rows var newsArray []News columns, err := rows.Columns() values := make([]sql.RawBytes, len(columns)) scanArgs := make([]interface{}, len(values)) for i := range values { scanArgs[i] = &values[i] } //var news News for rows.Next() { err = rows.Scan(scanArgs...) if err != nil { panic(err.Error()) } var news News news.Id = GetIntValue(values[0]) news.Title = GetStringValue(values[1]) news.Date = GetStringValue(values[2]) date, _ := time.Parse("2006-01-02 15:04:05", news.Date) news.Date = FormatTime(date) news.Description = GetStringValue(values[3]) newsArray = append(newsArray, news) } fmt.Println() return &newsArray }
func scanTerm(term *data.Term, rows *sql.Rows) error { cols, err := rows.Columns() if err != nil { return err } if len(cols) < 5 { err = rows.Scan( &term.Term, &term.Automated, &term.Author, &term.UpdateTime, ) } else { err = rows.Scan( &term.Term, &term.Automated, &term.Author, &term.UpdateTime, &term.Count, ) } return err }
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 GetMaps(rows *sql.Rows) ([]map[string]interface{}, error) { var maps []map[string]interface{} cols, err := rows.Columns() if err != nil { return nil, err } values := make([]interface{}, len(cols)) scanArgs := make([]interface{}, len(cols)) for x := 0; x < len(cols); x++ { scanArgs[x] = &values[x] } for rows.Next() { m := make(map[string]interface{}) err := rows.Scan(scanArgs...) if err == nil { for n, c := range cols { m[strings.ToLower(c)] = values[n] } maps = append(maps, m) } } return maps, nil }
// 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 bindComponent(name string, rs *sql.Rows, ctype componentType, manager *Manager) (*Component, error) { var id int64 cols, err := rs.Columns() if err != nil { return nil, err } ifaces := make([]interface{}, len(cols)) ifaceptrs := make([]interface{}, len(cols)) for i := 0; i < len(ifaces); i++ { ifaceptrs[i] = &ifaces[i] } err = rs.Scan(ifaceptrs...) if err != nil { return nil, err } cv := reflect.New(ctype.typ).Elem() for i, field := range cols { if field == "entity_id" { id = ifaces[i].(int64) continue } f := cv.FieldByName(field) if !f.IsValid() { return nil, fmt.Errorf("Field %s is invalid for %s", field, name) } iv := reflect.ValueOf(ifaces[i]) switch iv.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: f.SetInt(iv.Int()) default: f.Set(iv) } } return &Component{entity: id, name: name, isNew: false, manager: manager, data: cv.Addr().Interface()}, nil }
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 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 (scan *Scan) ScanToStruct(rows *sql.Rows, record reflect.Value) error { columns, err := rows.Columns() if err != nil { return err } values := make([]interface{}, len(columns)) for i, column := range columns { var field reflect.Value fieldName := scan.SQLColumnDict[column] if scan.ToPointers { field = record.Elem().FieldByName(fieldName) } else { field = record.FieldByName(fieldName) } if field.IsValid() { values[i] = field.Addr().Interface() } else { values[i] = &values[i] } } return rows.Scan(values...) }
//转换为字典数组 //参考:http://my.oschina.net/nowayout/blog/143278 func ConvRowsToMapForJson(rows *sql.Rows) (rowsMap []map[string]interface{}) { rowsMap = [](map[string]interface{}){} //数据切片 var tmpInt int = 0 //序列 columns, _ := rows.Columns() //列名 //定义数组,数组的类型为[]byte var values []interface{} = make([]interface{}, len(columns)) var rawBytes [][]byte = make([][]byte, len(values)) for v := range values { values[v] = &rawBytes[v] } for rows.Next() { rows.Scan(values...) if len(rowsMap) == tmpInt { rowsMap = append(rowsMap, make(map[string]interface{})) } for i, v := range columns { rowsMap[tmpInt][v] = string(rawBytes[i]) //fmt.Println(v + "===>" + string(rawBytes[i])) } tmpInt++ } return rowsMap }
func Scan2Struct(rows *sql.Rows, stru interface{}) error { beanVal := reflect.ValueOf(stru) if beanVal.Kind() != reflect.Ptr { return errors.New("Scan2Bean bean not a pointer") } beanVal = beanVal.Elem() cols, err := rows.Columns() if err != nil { return err } dest := make([]interface{}, len(cols)) for i, col := range cols { fldName := convertColName2FldName(col) fldVal := beanVal.FieldByName(fldName) if fldVal.Kind() != reflect.Struct && fldVal.Kind() != reflect.Ptr { dest[i] = fldVal.Addr().Interface() } else if fldVal.Type().String() == "time.Time" { dest[i] = &ReflectScanner{Value: &fldVal} // dest[i] = &TypeTestScanner{} } else { panic(fmt.Sprintf("Scan2Bean %v %v not support", fldName, fldVal.Type().String())) } } return rows.Scan(dest...) }
func TestSelectAlias(t *testing.T) { dbmap := initDbMap() defer dropAndClose(dbmap) p1 := &IgnoredColumnExported{Id: 1, External: 2, Created: 3} _insert(dbmap, p1) var p2 IgnoredColumnExported err := dbmap.SelectOne(&p2, "select * from ignored_column_exported_test where Id=1") if err != nil { t.Error(err) } if p2.Id != 1 || p2.Created != 3 || p2.External != 0 { t.Error("Expected ignorred field defaults to not set") } err = dbmap.SelectOne(&p2, "SELECT *, 1 AS external FROM ignored_column_exported_test") if err != nil { t.Error(err) } if p2.External != 1 { t.Error("Expected select as can map to exported field.") } var rows *sql.Rows var cols []string rows, err = dbmap.Db.Query("SELECT * FROM ignored_column_exported_test") cols, err = rows.Columns() if err != nil || len(cols) != 2 { t.Error("Expected ignored column not created") } }