Skip to content

Instantly share code, notes, and snippets.

@smahs
Created August 9, 2015 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smahs/ad464d1631836926f611 to your computer and use it in GitHub Desktop.
Save smahs/ad464d1631836926f611 to your computer and use it in GitHub Desktop.
Returns SQL select query data as [][]string, like dynamic languages. Time and memory complexities are, of course, not optimal.
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
// Connection pool as a singleton
var dbConn *sql.DB
/* Returns an open connection to the database
sql.DB creates new connections as required. */
func Db() (*sql.DB, error) {
// Define or import DB connection string parameters
constr := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s",
Username, Password, Host, Database, SSLmode)
if dbConn == nil {
dbConn, err := sql.Open("postgres", constr)
if err == nil {
return dbConn, nil
} else {
return nil, err
}
} else {
return dbConn, nil
}
}
/*
Somewhat Pythonic, definitely convenient, but slow of course..
Use it if SQL returns a small filtered dataset, or return raw
bytes instead of strings and cast at the receiving function.
The idea to use the number of columns returned by Query
to create a temp array of pointers to placeholder bytes.
And then iterate through the rows, load the bytes to temp,
and cast them to string and append to the return array.
*/
func genericQuery(query string) ([][]string, err) {
data := [][]string{}
db, err := Db()
if err == nil {
rows, err := db.Query(query)
defer rows.Close()
cols, _ := rows.Columns()
if err == nil {
length := len(cols)
values := make([]sql.RawBytes, length)
scanArgs := make([]interface{}, length)
for i := range values {
scanArgs[i] = &values[i]
}
for rows.Next() {
if err := rows.Scan(scanArgs...); err != nil {
return nil, err
}
datum := make([]string, length)
for i, col := range values {
datum[i] = string(col)
}
data = append(data, datum)
}
return data, nil
}
}
return nil, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment