-
Notifications
You must be signed in to change notification settings - Fork 111
/
export.go
73 lines (64 loc) · 2.17 KB
/
export.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
package server
import (
"fmt"
"io"
"net/http"
"os"
"path"
"github.com/rilldata/rill/runtime/drivers"
"github.com/rilldata/rill/runtime/server/auth"
)
// ExportTable exports a table or view as a flat file and triggers a HTTP download of it.
// It's mounted as a REST API only, and is not available over gRPC.
//
// TODO: This is a temporary hack that only supports DuckDB.
// We should add a generic workflow for data export that also supports possibly very large tables.
func (s *Server) ExportTable(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
if !auth.GetClaims(req.Context()).CanInstance(pathParams["instance_id"], auth.ReadOLAP) {
http.Error(w, "action not allowed", http.StatusUnauthorized)
return
}
var exportString string
switch pathParams["format"] {
case "csv":
exportString = "FORMAT CSV, HEADER"
case "parquet":
exportString = "FORMAT PARQUET"
default:
http.Error(w, fmt.Sprintf("unknown format: %s", pathParams), http.StatusBadRequest)
}
if pathParams["instance_id"] == "" || pathParams["table_name"] == "" {
http.Error(w, "missing params", http.StatusBadRequest)
return
}
fileName := fmt.Sprintf("%s.%s", pathParams["table_name"], pathParams["format"])
filePath := path.Join(os.TempDir(), fileName)
defer os.Remove(filePath)
// select * from the table and write to the temp file (DuckDB only)
olap, err := s.runtime.OLAP(req.Context(), pathParams["instance_id"])
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = olap.Exec(req.Context(), &drivers.Statement{
Query: fmt.Sprintf("COPY (SELECT * FROM %q) TO '%s' (%s)", pathParams["table_name"], filePath, exportString),
})
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// set the header to trigger download
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName))
w.Header().Set("Content-Type", req.Header.Get("Content-Type"))
// read and stream the file
file, err := os.Open(filePath)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
_, err = io.Copy(w, file)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}