Created
December 27, 2017 08:27
-
-
Save saeid-ir/3bb83586ab6fcca1ef8b72697e3004f4 to your computer and use it in GitHub Desktop.
Interface scanner for pq driver for postgres
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Scanner | |
import ( | |
"database/sql" | |
"reflect" | |
) | |
// Costume scanner type | |
type Scanner struct { | |
*sql.DB | |
} | |
// New return the costume scanner instance | |
func New(db *sql.DB) *Scanner { | |
return &Scanner{db} | |
} | |
// row2mapInterface get rows and fields name and return array of interface | |
func row2mapInterface(rows *sql.Rows, fields []string) (resultsMap map[string]interface{}, err error) { | |
resultsMap = make(map[string]interface{}, len(fields)) | |
scanResultContainers := make([]interface{}, len(fields)) | |
for i := 0; i < len(fields); i++ { | |
var scanResultContainer interface{} | |
scanResultContainers[i] = &scanResultContainer | |
} | |
if err := rows.Scan(scanResultContainers...); err != nil { | |
return nil, err | |
} | |
for ii, key := range fields { | |
resultsMap[key] = reflect.Indirect(reflect.ValueOf(scanResultContainers[ii])).Interface() | |
} | |
return | |
} | |
// rows2Interfaces return the the entire query result as interface with the given query rows | |
func rows2Interfaces(rows *sql.Rows) (resultsSlice []map[string]interface{}, err error) { | |
fields, err := rows.Columns() | |
if err != nil { | |
return nil, err | |
} | |
for rows.Next() { | |
result, err := row2mapInterface(rows, fields) | |
if err != nil { | |
return nil, err | |
} | |
resultsSlice = append(resultsSlice, result) | |
} | |
return resultsSlice, nil | |
} | |
// QueryInterface return the query result as interface | |
func (scanner *Scanner) QueryInterface(sqlStr string, args ...interface{}) ([]map[string]interface{}, error) { | |
var rows *sql.Rows | |
var err error | |
if len(args) > 0 { | |
rows, err = scanner.Query(sqlStr, args) | |
} else { | |
rows, err = scanner.Query(sqlStr) | |
} | |
if err != nil { | |
return nil, err | |
} | |
return rows2Interfaces(rows) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment