Files
sqlite3/compile.go

69 lines
1.4 KiB
Go
Raw Normal View History

2023-01-12 13:43:35 +00:00
package sqlite3
import (
"context"
2023-02-23 14:13:32 +00:00
"crypto/rand"
2023-01-12 13:43:35 +00:00
"os"
2023-02-23 14:13:32 +00:00
"runtime"
2023-01-28 12:47:39 +00:00
"strconv"
2023-01-12 13:43:35 +00:00
"sync"
"sync/atomic"
"github.com/tetratelabs/wazero"
2023-01-28 12:47:39 +00:00
"github.com/tetratelabs/wazero/api"
2023-01-12 13:43:35 +00:00
)
2023-03-01 10:34:08 +00:00
// Configure SQLite WASM.
//
// Importing package embed initializes these
// with an appropriate build of SQLite:
//
// import _ "github.com/ncruces/go-sqlite3/embed"
2023-01-12 13:43:35 +00:00
var (
2023-03-01 10:34:08 +00:00
Binary []byte // WASM binary to load.
2023-01-12 13:43:35 +00:00
Path string // Path to load the binary from.
)
2023-01-28 12:47:39 +00:00
var sqlite3 sqlite3Runtime
2023-01-12 13:43:35 +00:00
2023-01-28 12:47:39 +00:00
type sqlite3Runtime struct {
once sync.Once
runtime wazero.Runtime
compiled wazero.CompiledModule
instances atomic.Uint64
err error
}
2023-01-12 13:43:35 +00:00
2023-01-28 12:47:39 +00:00
func (s *sqlite3Runtime) instantiateModule(ctx context.Context) (api.Module, error) {
2023-02-15 16:24:34 +00:00
s.once.Do(func() { s.compileModule(ctx) })
2023-01-28 12:47:39 +00:00
if s.err != nil {
return nil, s.err
}
2023-01-18 01:30:11 +00:00
2023-01-28 12:47:39 +00:00
cfg := wazero.NewModuleConfig().
2023-02-23 14:13:32 +00:00
WithName("sqlite3-" + strconv.FormatUint(s.instances.Add(1), 10)).
WithSysWalltime().WithSysNanotime().WithSysNanosleep().
WithOsyield(runtime.Gosched).
WithRandSource(rand.Reader)
2023-01-28 12:47:39 +00:00
return s.runtime.InstantiateModule(ctx, s.compiled, cfg)
}
2023-02-15 16:24:34 +00:00
func (s *sqlite3Runtime) compileModule(ctx context.Context) {
s.runtime = wazero.NewRuntime(ctx)
2023-02-16 13:52:05 +00:00
vfsInstantiate(ctx, s.runtime)
2023-01-12 13:43:35 +00:00
2023-01-28 12:47:39 +00:00
bin := Binary
if bin == nil && Path != "" {
bin, s.err = os.ReadFile(Path)
if s.err != nil {
return
2023-01-12 13:43:35 +00:00
}
}
2023-02-20 13:38:03 +00:00
if bin == nil {
s.err = binaryErr
return
}
2023-01-12 13:43:35 +00:00
2023-02-15 16:24:34 +00:00
s.compiled, s.err = s.runtime.CompileModule(ctx, bin)
2023-01-12 13:43:35 +00:00
}