|
| 1 | +package drivers |
| 2 | + |
| 3 | +import ( |
| 4 | + "database/sql" |
| 5 | + _ "github.com/go-sql-driver/mysql" |
| 6 | + "errors" |
| 7 | +) |
| 8 | + |
| 9 | +type base struct { |
| 10 | + Type string |
| 11 | + dsn string |
| 12 | + db *sql.DB |
| 13 | +} |
| 14 | + |
| 15 | +func (b *base) Open() error { |
| 16 | + db, err := sql.Open(b.Type, b.dsn) |
| 17 | + if err != nil { |
| 18 | + return err |
| 19 | + } |
| 20 | + b.db = db |
| 21 | + return nil |
| 22 | +} |
| 23 | + |
| 24 | +func (b base) Query(q string) ([]map[string]interface{}) { |
| 25 | + if b.db == nil { |
| 26 | + panic(errors.New("need call Open() before Query()")) |
| 27 | + } |
| 28 | + |
| 29 | + rows, err := b.db.Query(q) |
| 30 | + |
| 31 | + columns, err := rows.Columns() |
| 32 | + if err != nil { |
| 33 | + panic(err.Error()) |
| 34 | + } |
| 35 | + |
| 36 | + // Make a slice for the values |
| 37 | + values := make([]sql.RawBytes, len(columns)) |
| 38 | + |
| 39 | + // rows.Scan wants '[]interface{}' as an argument, so we must copy the |
| 40 | + // references into such a slice |
| 41 | + // See http://code.google.com/p/go-wiki/wiki/InterfaceSlice for details |
| 42 | + scanArgs := make([]interface{}, len(values)) |
| 43 | + for i := range values { |
| 44 | + scanArgs[i] = &values[i] |
| 45 | + } |
| 46 | + |
| 47 | + //result |
| 48 | + var rs = make([]map[string]interface{}, 1) |
| 49 | + |
| 50 | + // Fetch rows |
| 51 | + for rows.Next() { |
| 52 | + // get RawBytes from data |
| 53 | + err = rows.Scan(scanArgs...) |
| 54 | + if err != nil { |
| 55 | + panic(err.Error()) // proper error handling instead of panic in your app |
| 56 | + } |
| 57 | + |
| 58 | + // Now do something with the data. |
| 59 | + // Here we just print each column as a string. |
| 60 | + var row = map[string]interface{}{} |
| 61 | + for i, col := range values { |
| 62 | + if col == nil { |
| 63 | + row[columns[i]] = nil |
| 64 | + } else { |
| 65 | + row[columns[i]] = string(col) |
| 66 | + } |
| 67 | + |
| 68 | + } |
| 69 | + rs = append(rs, row) |
| 70 | + } |
| 71 | + |
| 72 | + return rs |
| 73 | +} |
| 74 | + |
| 75 | +func (b *base) Close() { |
| 76 | + if b.db == nil { |
| 77 | + panic(errors.New("need call Open() before Close()")) |
| 78 | + } |
| 79 | + b.db.Close() |
| 80 | +} |
| 81 | + |
| 82 | +func newBase(t string, dsn string) *base { |
| 83 | + return &base{t, dsn, nil} |
| 84 | +} |
0 commit comments