1/* 2** Zabbix 3** Copyright (C) 2001-2021 Zabbix SIA 4** 5** This program is free software; you can redistribute it and/or modify 6** it under the terms of the GNU General Public License as published by 7** the Free Software Foundation; either version 2 of the License, or 8** (at your option) any later version. 9** 10** This program is distributed in the hope that it will be useful, 11** but WITHOUT ANY WARRANTY; without even the implied warranty of 12** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13** GNU General Public License for more details. 14** 15** You should have received a copy of the GNU General Public License 16** along with this program; if not, write to the Free Software 17** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 18**/ 19 20package mysql 21 22import ( 23 "database/sql" 24) 25 26// rows2data scans rows and returns it as an array of key-value pairs. 27// https://github.com/go-sql-driver/mysql/wiki/Examples 28func rows2data(rows *sql.Rows) (result []map[string]string, err error) { 29 defer rows.Close() 30 31 columns, err := rows.Columns() 32 if err != nil { 33 return nil, err 34 } 35 36 values := make([]sql.RawBytes, len(columns)) 37 38 // rows.Scan wants '[]interface{}' as an argument, so we must copy the 39 // references into such a slice 40 // See http://code.google.com/p/go-wiki/wiki/InterfaceSlice for details 41 scanArgs := make([]interface{}, len(values)) 42 for i := range values { 43 scanArgs[i] = &values[i] 44 } 45 46 for rows.Next() { 47 err = rows.Scan(scanArgs...) 48 if err != nil { 49 return nil, err 50 } 51 52 entry := make(map[string]string) 53 54 for i, col := range values { 55 if col == nil { 56 entry[columns[i]] = "" 57 } else { 58 entry[columns[i]] = string(col) 59 } 60 } 61 62 result = append(result, entry) 63 } 64 65 return result, nil 66} 67