Home > OS >  How to insert csv file using one command in clickhouse using golang
How to insert csv file using one command in clickhouse using golang

Time:12-21

Is there a way to insert csv file using this go library https://github.com/ClickHouse/clickhouse-go in one command (without reading csv and iterating through the content.). If there is a way can you provide me with the example. if not how can we convert this system command and write it in golang using os/exec library. cat /home/srijan/employee.csv | clickhouse-client --query="INSERT INTO test1 FORMAT CSV"

CodePudding user response:

It's impossible with that go library. You can use http api https://clickhouse.com/docs/en/interfaces/http/ and any http go client

for example

package main

import (
        "compress/gzip"
        "fmt"
        "io"
        "io/ioutil"
        "net/http"
        "net/url"
        "os"
)

func compress(data io.Reader) io.Reader {
        pr, pw := io.Pipe()
        gw, err := gzip.NewWriterLevel(pw, int(3))
        if err != nil {
                panic(err)
        }

        go func() {
                _, _ = io.Copy(gw, data)
                gw.Close()
                pw.Close()
        }()

        return pr
}

func main() {
        p, err := url.Parse("http://localhost:8123/")
        if err != nil {
                panic(err)
        }
        q := p.Query()

        q.Set("query", "INSERT INTO test1 FORMAT CSV")
        p.RawQuery = q.Encode()
        queryUrl := p.String()

        var req *http.Request


        req, err = http.NewRequest("POST", queryUrl, compress(os.Stdin))
        req.Header.Add("Content-Encoding", "gzip")

        if err != nil {
                panic(err)
        }

        client := &http.Client{
                Transport: &http.Transport{DisableKeepAlives: true},
        }
        resp, err := client.Do(req)
        if err != nil {
                panic(err)
        }
        defer resp.Body.Close()

        body, _ := ioutil.ReadAll(resp.Body)

        if resp.StatusCode != 200 {
                panic(fmt.Errorf("clickhouse response status %d: %s", resp.StatusCode, string(body)))
        }
}
  • Related