-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
216 lines (181 loc) · 4.45 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package main
import (
"bytes"
"errors"
"fmt"
"os"
"strings"
"container/list"
"database/sql"
"github.com/babashka/pod-babashka-go-sqlite3/babashka"
_ "github.com/mattn/go-sqlite3" // Import go-sqlite3 library
"github.com/russolsen/transit"
)
func debug(v interface{}) {
fmt.Fprintf(os.Stderr, "debug: %+q\n", v)
}
func encodeRows(rows *sql.Rows) ([]interface{}, error) {
cols, err := rows.Columns()
columns := make([]transit.Keyword, len(cols))
for i, col := range cols {
columns[i] = transit.Keyword(col)
}
if err != nil {
return nil, err
}
var data []interface{}
values := make([]interface{}, len(columns))
scanArgs := make([]interface{}, len(values))
for i := range values {
scanArgs[i] = &values[i]
}
for rows.Next() {
results := make(map[transit.Keyword]interface{})
if err = rows.Scan(scanArgs...); err != nil {
debug(err)
return nil, err
}
for i, val := range values {
col := columns[i]
results[col] = val
}
// debug(results)
// debug(fmt.Sprintf("%T", results))
data = append(data, results)
}
return data, nil
}
type ExecResult = map[transit.Keyword]int64
func encodeResult(result sql.Result) (ExecResult, error) {
rowsAffected, err := result.RowsAffected()
if err != nil {
return nil, err
}
lastInsertedId, err := result.LastInsertId()
if err != nil {
return nil, err
}
res := ExecResult{
transit.Keyword("rows-affected"): rowsAffected,
transit.Keyword("last-inserted-id"): lastInsertedId,
}
return res, nil
}
func listToSlice(l *list.List) []interface{} {
slice := make([]interface{}, l.Len())
cnt := 0
for e := l.Front(); e != nil; e = e.Next() {
slice[cnt] = e.Value
cnt++
}
return slice
}
func parseQuery(args string) (string, string, []interface{}, error) {
reader := strings.NewReader(args)
decoder := transit.NewDecoder(reader)
value, err := decoder.Decode()
if err != nil {
return "", "", nil, err
}
argSlice := listToSlice(value.(*list.List))
db, ok := argSlice[0].(string)
if !ok {
return "", "", nil, errors.New("the sqlite connection must be a string")
}
switch queryArgs := argSlice[1].(type) {
case string:
return db, queryArgs, make([]interface{}, 0), nil
case []interface{}:
return db, queryArgs[0].(string), queryArgs[1:], nil
default:
return "", "", nil, errors.New("unexpected query type, expected a string or a vector")
}
}
func makeArgs(query []string) []interface{} {
args := make([]interface{}, len(query)-1)
for i := range query[1:] {
args[i] = query[i+1]
}
return args
}
func respond(message *babashka.Message, response interface{}) {
buf := bytes.NewBufferString("")
encoder := transit.NewEncoder(buf, false)
if err := encoder.Encode(response); err != nil {
babashka.WriteErrorResponse(message, err)
} else {
babashka.WriteInvokeResponse(message, string(buf.String()))
}
}
func processMessage(message *babashka.Message) {
switch message.Op {
case "describe":
babashka.WriteDescribeResponse(
&babashka.DescribeResponse{
Format: "transit+json",
Namespaces: []babashka.Namespace{
{
Name: "pod.babashka.go-sqlite3",
Vars: []babashka.Var{
{
Name: "execute!",
},
{
Name: "query",
},
},
},
},
})
case "invoke":
db, query, args, err := parseQuery(message.Args)
if err != nil {
babashka.WriteErrorResponse(message, err)
return
}
conn, err := sql.Open("sqlite3", db)
if err != nil {
babashka.WriteErrorResponse(message, err)
return
}
defer conn.Close()
switch message.Var {
case "pod.babashka.go-sqlite3/execute!":
res, err := conn.Exec(query, args...)
if err != nil {
babashka.WriteErrorResponse(message, err)
return
}
if json, err := encodeResult(res); err != nil {
babashka.WriteErrorResponse(message, err)
} else {
respond(message, json)
}
case "pod.babashka.go-sqlite3/query":
res, err := conn.Query(query, args...)
if err != nil {
babashka.WriteErrorResponse(message, err)
return
}
if json, err := encodeRows(res); err != nil {
babashka.WriteErrorResponse(message, err)
} else {
respond(message, json)
}
default:
babashka.WriteErrorResponse(message, fmt.Errorf("Unknown var %s", message.Var))
}
default:
babashka.WriteErrorResponse(message, fmt.Errorf("Unknown op %s", message.Op))
}
}
func main() {
for {
message, err := babashka.ReadMessage()
if err != nil {
babashka.WriteErrorResponse(message, err)
continue
}
processMessage(message)
}
}