Files
upstream-sqlc/internal/goldeneye/clickhouse/local.go
upstream-mirror 0f4df23290
Some checks failed
kotlin / test (push) Has been skipped
python / test (push) Has been skipped
typescript / test (push) Has been skipped
go / build darwin/amd64 (push) Has been cancelled
go / build linux/amd64 (push) Has been cancelled
go / build windows/amd64 (push) Has been cancelled
go / build darwin/arm64 (push) Has been cancelled
go / build linux/arm64 (push) Has been cancelled
go / build windows/arm64 (push) Has been cancelled
go / test (push) Has been cancelled
go / vuln_check (push) Has been cancelled
snapshot of https://github.com/sqlc-dev/sqlc.git (main, 2026-09-16; blobs > 131072B omitted)
2026-09-16 02:17:34 +05:00

83 lines
2.0 KiB
Go

package clickhouse
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
)
// local runs SQL through an ephemeral `clickhouse local` process.
type local struct {
binary string
}
// resultSet is one JSON-format result printed by clickhouse local. Only
// statements that return rows print one; DDL and INSERT print nothing.
type resultSet struct {
Meta []resultColumn `json:"meta"`
Data []map[string]json.RawMessage `json:"data"`
Rows int `json:"rows"`
}
type resultColumn struct {
Name string `json:"name"`
Type string `json:"type"`
}
// run executes a multi-statement script in a fresh process with fresh
// storage and returns the result sets in statement order. Any statement
// failing fails the whole run with ClickHouse's own error message.
func (l local) run(ctx context.Context, script string) ([]resultSet, error) {
dir, err := os.MkdirTemp("", "sqlc-goldeneye-clickhouse-*")
if err != nil {
return nil, err
}
defer os.RemoveAll(dir)
queries := filepath.Join(dir, "queries.sql")
if err := os.WriteFile(queries, []byte(script), 0o600); err != nil {
return nil, err
}
// stdin must not be inherited: clickhouse local reads it as table data
// and blocks until it is closed.
cmd := exec.CommandContext(ctx, l.binary, "local",
"--multiquery",
"--queries-file", queries,
"--output-format", "JSON",
"--path", filepath.Join(dir, "data"),
)
cmd.Stdin = nil
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
msg := strings.TrimSpace(stderr.String())
if msg == "" {
msg = err.Error()
}
return nil, errors.New(msg)
}
var results []resultSet
dec := json.NewDecoder(&stdout)
for {
var rs resultSet
err := dec.Decode(&rs)
if errors.Is(err, io.EOF) {
return results, nil
}
if err != nil {
return nil, fmt.Errorf("decoding clickhouse local output: %w", err)
}
results = append(results, rs)
}
}