-
Notifications
You must be signed in to change notification settings - Fork 1
/
prql.go
80 lines (65 loc) · 1.69 KB
/
prql.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
package prql
import (
"bytes"
"context"
"crypto/sha256"
_ "embed"
"fmt"
"hash"
"strings"
"github.com/segmentio/fasthash/fnv1a"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
)
type Engine interface {
Compile(context.Context, string) (string, error)
}
var _ Engine = (*WasiEngine)(nil)
//go:embed testdata/prql-wasi.wasm
var prqlWasi []byte
type WasiEngine struct {
code wazero.CompiledModule
r wazero.Runtime
h hash.Hash
}
// Compile compiles a prql query to a sql query
func (e *WasiEngine) Compile(ctx context.Context, query string) (string, error) {
if query == "" {
return "", fmt.Errorf("prql query must not be empty")
}
// hash query for concurrent a
h1 := fnv1a.HashString64(query)
name := fmt.Sprintf("id-%x", h1)
in := strings.NewReader(query)
out := new(bytes.Buffer)
// we know our wasi program doesn't write to stderr
// so we skip configuring it
config := wazero.NewModuleConfig().
WithStdout(out).
WithStdin(in).
WithName(name)
mod, err := e.r.InstantiateModule(ctx, e.code, config)
if err != nil {
return "", err
}
mod.Close(ctx)
return strings.TrimSpace(out.String()), nil
}
// Close closes the underlying wazero runtime
func (e *WasiEngine) Close(ctx context.Context) error {
return e.r.Close(ctx)
}
// New instantiates a new wasi runtime and precompiles the embedded wasi file
func New(ctx context.Context) (*WasiEngine, error) {
r := wazero.NewRuntimeWithConfig(ctx, wazero.NewRuntimeConfig())
wasi_snapshot_preview1.MustInstantiate(ctx, r)
code, err := r.CompileModule(ctx, prqlWasi)
if err != nil {
return nil, err
}
return &WasiEngine{
r: r,
code: code,
h: sha256.New(),
}, nil
}