forked from multiprocessio/dsq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
277 lines (226 loc) · 6.26 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
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
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"github.com/multiprocessio/datastation/runner"
"github.com/google/uuid"
)
func resolveContentType(fileExtensionOrContentType string) runner.MimeType {
if strings.Contains(fileExtensionOrContentType, "/") {
return runner.MimeType(fileExtensionOrContentType)
}
return runner.GetMimeType("x."+fileExtensionOrContentType, runner.ContentTypeInfo{})
}
func openTruncate(out string) (*os.File, error) {
base := filepath.Dir(out)
_ = os.Mkdir(base, os.ModePerm)
return os.OpenFile(out, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, os.ModePerm)
}
func evalFileInto(file string, out *os.File) error {
if file == "" {
return fmt.Errorf(`First argument when not used in a pipe should be a file. e.g. 'dsq test.csv "SELECT COUNT(1) FROM {}"'`)
}
mimetype := runner.GetMimeType(file, runner.ContentTypeInfo{})
if mimetype == "" {
return fmt.Errorf("Unknown mimetype for file: %s.", file)
}
return runner.TransformFile(file, runner.ContentTypeInfo{}, out)
}
func getShape(resultFile, panelId string) *runner.Shape {
s, err := runner.ShapeFromFile(resultFile, panelId, 10_000, 100)
if err != nil {
switch t := err.(type) {
case *runner.DSError:
if t.Name == "NotAnArrayOfObjectsError" {
rest := "."
if panelId != "" {
rest = ": " + panelId + "."
}
log.Fatalf("Input is not an array of objects%s", rest)
}
log.Fatal(err)
default:
log.Fatal(err)
}
}
return s
}
var Version = "latest"
var HELP = `dsq (Version ` + Version + `) - commandline SQL engine for data files
Usage: dsq [file...] $query
dsq $file [query]
cat $file | dsq -s $filetype [query]
dsq is a tool for running SQL on one or more data files. It uses
SQLite's SQL dialect. Files as tables are accessible via "{N}" where N
is the 0-based index of the file in the commandline.
The shorthand "{}" is replaced with "{0}".
Examples:
# This simply dumps the CSV as JSON
$ dsq test.csv
# This dumps the first 10 rows of the parquet file as JSON.
$ dsq data.parquet "SELECT * FROM {} LIMIT 10"
# This joins two datasets of differing origin types (CSV and JSON).
$ dsq testdata/join/users.csv testdata/join/ages.json \
"select {0}.name, {1}.age from {0} join {1} on {0}.id = {1}.id"
See the repo for more details: https://github.com/multiprocessio/dsq.`
func main() {
log.SetFlags(0)
runner.Verbose = false
var nonFlagArgs []string
stdin := false
for _, arg := range os.Args[1:] {
if arg == "-v" || arg == "--verbose" {
runner.Verbose = true
continue
}
if arg == "-s" || arg == "--stdin" {
stdin = true
continue
}
if arg == "-h" || arg == "--help" {
log.Println(HELP)
return
}
nonFlagArgs = append(nonFlagArgs, arg)
}
lastNonFlagArg := ""
files := nonFlagArgs
// Empty marker meaning to process from stdin
if stdin {
files = append([]string{""}, files...)
}
if len(nonFlagArgs) > 1 {
lastNonFlagArg = nonFlagArgs[len(nonFlagArgs)-1]
if strings.Contains(lastNonFlagArg, " ") {
files = files[:len(files)-1]
}
}
if len(files) == 0 {
log.Fatal("No input files.")
}
projectTmp, err := ioutil.TempFile("", "dsq-project")
if err != nil {
log.Fatal(err)
}
defer os.Remove(projectTmp.Name())
project := &runner.ProjectState{
Id: projectTmp.Name(),
Pages: []runner.ProjectPage{
{
Panels: nil,
},
},
}
for i := 0; i < len(files); i++ {
file := files[i]
panelId := uuid.New().String()
resultFile := runner.GetPanelResultsFile(project.Id, panelId)
out, err := openTruncate(resultFile)
if err != nil {
log.Fatal(err)
}
readFromStdin := false
if file == "" {
b, err := ioutil.ReadAll(os.Stdin)
if err == nil {
if i == len(files)-1 {
log.Fatal("Expected file extension or mimetype: e.g. cat x.csv | dsq -s csv, or cat x.csv | dsq -s text/csv")
}
mimetype := files[i+1]
if !strings.Contains(mimetype, "/") {
mimetype = string(runner.GetMimeType("x."+mimetype, runner.ContentTypeInfo{}))
}
if mimetype == "" {
log.Fatalf("Unknown mimetype or file extension: %s.", mimetype)
}
i += 1
cti := runner.ContentTypeInfo{Type: string(mimetype)}
err := runner.TransformReader(bytes.NewReader(b), "", cti, out)
if err != nil {
log.Fatal(err)
}
s := getShape(resultFile, "")
project.Pages[0].Panels = append(project.Pages[0].Panels, runner.PanelInfo{
ResultMeta: runner.PanelResult{
Shape: *s,
},
Id: panelId,
Name: uuid.New().String(),
})
readFromStdin = true
}
continue
}
if !readFromStdin {
err := evalFileInto(file, out)
if err != nil {
log.Fatal(err)
}
}
s := getShape(resultFile, file)
project.Pages[0].Panels = append(project.Pages[0].Panels, runner.PanelInfo{
ResultMeta: runner.PanelResult{
Shape: *s,
},
Id: panelId,
Name: uuid.New().String(),
})
out.Close()
}
// No query, just dump transformed file directly out
if lastNonFlagArg == "" {
resultFile := runner.GetPanelResultsFile(project.Id, project.Pages[0].Panels[0].Id)
fd, err := os.Open(resultFile)
if err != nil {
log.Fatal(err)
}
defer fd.Close()
_, err = io.Copy(os.Stdout, fd)
if err != nil {
log.Fatal(err)
}
return
}
connector, tmp, err := runner.MakeTmpSQLiteConnector()
if err != nil {
log.Fatal(err)
}
defer os.Remove(tmp.Name())
project.Connectors = append(project.Connectors, *connector)
query := lastNonFlagArg
query = strings.ReplaceAll(query, "{}", "DM_getPanel(0)")
for i := 0; i < len(project.Pages[0].Panels); i++ {
query = strings.ReplaceAll(query, fmt.Sprintf("{%d}", i), fmt.Sprintf("DM_getPanel(%d)", i))
}
panel := &runner.PanelInfo{
Type: runner.DatabasePanel,
Content: query,
Id: uuid.New().String(),
Name: uuid.New().String(),
DatabasePanelInfo: &runner.DatabasePanelInfo{
Database: runner.DatabasePanelInfoDatabase{
ConnectorId: connector.Id,
},
},
}
err = runner.EvalDatabasePanel(project, 0, panel, nil)
if err != nil {
log.Fatal(err)
}
// Dump the result to stdout
fd, err := os.Open(runner.GetPanelResultsFile(project.Id, panel.Id))
if err != nil {
log.Fatalf("Could not open results file: %s", err)
}
_, err = io.Copy(os.Stdout, fd)
if err != nil {
log.Fatal(err)
}
fmt.Println()
}