-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
qq.go
368 lines (337 loc) · 6.77 KB
/
qq.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package qq
import (
"bufio"
"database/sql"
"encoding/csv"
"fmt"
"io"
"regexp"
"strings"
"unicode"
xenc "golang.org/x/text/encoding"
"github.com/mattn/go-runewidth"
_ "github.com/mattn/go-sqlite3"
"github.com/najeira/ltsv"
)
const (
Comma = ","
)
// QQ is the most basic structure of qq
type QQ struct {
db *sql.DB
Opt *Option
}
// Option is a structure that qq command can receive
type Option struct {
NoHeader bool
OutHeader bool
InputCSV bool
InputTSV bool
InputLTSV bool
InputPat string
Encoding xenc.Encoding
}
var renum = regexp.MustCompile(`^[+-]?[1-9][0-9]*(\.[0-9]+)?(e-?[0-9]+)?$`)
func readLines(r io.Reader) ([]string, error) {
var lines []string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
if strings.TrimSpace(line) == "" {
continue
}
lines = append(lines, line)
}
return lines, scanner.Err()
}
func (qq *QQ) lines2rows(lines []string) [][]string {
cr := []rune(lines[0])
w := 0
rows := make([][]string, len(lines))
i := 0
skip_white:
for ; i < len(cr); i++ {
for _, line := range lines {
if !unicode.IsSpace(rune(line[i])) {
break skip_white
}
}
w++
}
li := i
for ; i < len(cr); i++ {
r := cr[i]
w += runewidth.RuneWidth(r)
last := i == len(cr)-1
if i == 0 || (!unicode.IsSpace(r) && !last) {
continue
}
if last {
for ri := range rows {
fv := strings.TrimSpace(string(([]rune(lines[ri]))[li:]))
if ri == 0 && fv == "" && !qq.Opt.NoHeader {
fv = fmt.Sprintf("______f%d", ri+1)
}
rows[ri] = append(rows[ri], fv)
}
} else {
part := false
for _, line := range lines {
pr := []rune(runewidth.Truncate(line, w, ""))
if !unicode.IsSpace(pr[len(pr)-1]) {
part = true
break
}
}
if !part {
for ri := range rows {
lr := []rune(lines[ri])
ib := i
if ib >= len(lr) {
ib = len(lr) - 1
}
fv := strings.TrimSpace(string(lr[li:ib]))
if ri == 0 && fv == "" && !qq.Opt.NoHeader {
fv = fmt.Sprintf("______f%d", ri+1)
}
rows[ri] = append(rows[ri], fv)
}
for ; i < len(cr); i++ {
cw := runewidth.RuneWidth(r)
for _, line := range lines {
pr := []rune(runewidth.Truncate(line, w+cw, ""))
if !unicode.IsSpace(pr[len(pr)-1]) {
part = true
break
}
}
if part {
break
}
w += cw
}
li = i
}
}
}
return rows
}
// NewQQ creates new connection to sqlite3
func NewQQ(opt *Option) (*QQ, error) {
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
return nil, err
}
return &QQ{db, opt}, nil
}
const (
sqliteINTEGER = "INTEGER"
sqliteTEXT = "TEXT"
sqliteREAL = "REAL"
)
type column struct {
Name string
Type string
}
func newColumn(name string) *column {
return &column{
Name: name,
Type: sqliteINTEGER,
}
}
func (qq *QQ) columnsAndRows(r io.Reader) (cn []*column, rows [][]string, err error) {
if qq.Opt.Encoding != nil {
r = qq.Opt.Encoding.NewDecoder().Reader(r)
}
if qq.Opt.InputCSV {
rows, err = csv.NewReader(r).ReadAll()
if err != nil {
return nil, nil, err
}
} else if qq.Opt.InputTSV {
csv := csv.NewReader(r)
csv.Comma = '\t'
rows, err = csv.ReadAll()
if err != nil {
return nil, nil, err
}
} else if qq.Opt.InputLTSV {
rawRows, err := ltsv.NewReader(r).ReadAll()
if err != nil {
return nil, nil, err
}
keys := make(map[string]struct{})
for _, rowMap := range rawRows {
for k := range rowMap {
keys[k] = struct{}{}
}
}
for k := range keys {
cn = append(cn, newColumn(k))
}
for _, rowMap := range rawRows {
row := make([]string, len(cn))
for i, v := range cn {
row[i] = rowMap[v.Name]
}
rows = append(rows, row)
}
} else if qq.Opt.InputPat != "" {
lines, err := readLines(r)
if err != nil {
return nil, nil, err
}
if len(lines) == 0 {
return nil, nil, nil
}
re, err := regexp.Compile(qq.Opt.InputPat)
if err != nil {
return nil, nil, err
}
for _, line := range lines {
rows = append(rows, re.Split(line, -1))
}
} else {
lines, err := readLines(r)
if err != nil {
return nil, nil, err
}
if len(lines) == 0 {
return nil, nil, nil
}
rows = qq.lines2rows(lines)
}
if !qq.Opt.InputLTSV {
if qq.Opt.NoHeader {
for i := 0; i < len(rows[0]); i++ {
cn = append(cn, newColumn(fmt.Sprintf(`f%d`, i+1)))
}
} else {
for _, v := range rows[0] {
cn = append(cn, newColumn(v))
}
}
}
if !qq.Opt.NoHeader && !qq.Opt.InputLTSV {
rows = rows[1:]
}
for _, row := range rows {
for i, col := range row {
if col == "" {
continue
}
colDef := cn[i]
if colDef.Type == sqliteTEXT {
continue
}
if matches := renum.FindStringSubmatch(col); len(matches) > 0 {
if matches[1] != "" || matches[2] != "" {
colDef.Type = sqliteREAL
}
} else {
colDef.Type = sqliteTEXT
}
}
}
return cn, rows, nil
}
// Import from csv/tsv files or stdin
func (qq *QQ) Import(r io.Reader, name string) error {
cn, rows, err := qq.columnsAndRows(r)
if err != nil || len(rows) == 0 {
return err
}
s := `create table '` + strings.Replace(name, `'`, `''`, -1) + `'(`
for i, n := range cn {
if i > 0 {
s += Comma
}
s += fmt.Sprintf(`'%s' %s`, strings.Replace(n.Name, `'`, `''`, -1), n.Type)
}
s += `)`
_, err = qq.db.Exec(s)
if err != nil {
return err
}
s = `insert into '` + strings.Replace(name, `'`, `''`, -1) + `'(`
for i, n := range cn {
if i > 0 {
s += Comma
}
s += `'` + strings.Replace(n.Name, `'`, `''`, -1) + `'`
}
s += `) values`
d := ``
for _, row := range rows {
if d != `` {
d += `,`
}
d += `(`
for i, col := range row {
if i >= len(cn) {
break
}
if i > 0 {
d += Comma
}
if renum.MatchString(col) {
d += col
} else {
d += `'` + strings.Replace(col, `'`, `''`, -1) + `'`
}
}
d += `)`
}
_, err = qq.db.Exec(s + d)
if err != nil {
return err
}
return nil
}
// Query runs a query and formatize result set
func (qq *QQ) Query(query string) ([][]string, error) {
qrows, err := qq.db.Query(query)
if err != nil {
return nil, err
}
defer qrows.Close()
cols, err := qrows.Columns()
if err != nil {
return nil, err
}
if len(cols) == 0 {
return nil, nil
}
rows := [][]string{}
if qq.Opt.OutHeader {
rows = append(rows, cols)
}
values := make([]interface{}, len(cols))
ptrs := make([]interface{}, len(cols))
for i := range cols {
ptrs[i] = &values[i]
}
for qrows.Next() {
err = qrows.Scan(ptrs...)
if err != nil {
return nil, err
}
cells := []string{}
for _, val := range values {
b, ok := val.([]byte)
var v string
if ok {
v = string(b)
} else {
v = fmt.Sprint(val)
}
cells = append(cells, v)
}
rows = append(rows, cells)
}
return rows, nil
}
// Close database connection
func (qq *QQ) Close() error {
return qq.db.Close()
}