-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
60 lines (48 loc) · 1.01 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"database/sql"
_ "modernc.org/sqlite"
)
func fatalErr(err error) {
if err != nil {
log.Fatalln(err)
}
}
func main() {
// Arg[1] = db path, Arg[2] = query
if len(os.Args) != 3 {
log.Println("Missing arguments! Please provide database's path and a query.")
os.Exit(1)
}
db, err := sql.Open("sqlite", os.Args[1])
fatalErr(err)
defer db.Close()
record, err := db.Query(os.Args[2])
fatalErr(err)
defer record.Close()
columns, err := record.Columns()
fatalErr(err)
row := make([]interface{}, len(columns))
for i := 0; i < len(columns); i++ {
row[i] = new(sql.RawBytes)
}
rowString := make([]string, len(columns))
for record.Next() {
record.Scan(row...)
fatalErr(err)
for i := 0; i < len(columns); i++ {
if col, ok := row[i].(*sql.RawBytes); ok {
rowString[i] = string(*col)
} else {
log.Fatalln("Cannot convert column into string")
}
}
j, err := json.Marshal(&rowString)
fatalErr(err)
fmt.Println(string(j))
}
}