Skip to content

Instantly share code, notes, and snippets.

@yannick
Created September 10, 2024 14:21
Show Gist options
  • Save yannick/187ea0efaa698d2037e961e0d0283bd3 to your computer and use it in GitHub Desktop.
Save yannick/187ea0efaa698d2037e961e0d0283bd3 to your computer and use it in GitHub Desktop.
main.go
package main
import (
"context"
"fmt"
"log"
"github.com/ClickHouse/clickhouse-go/v2"
"github.com/vmihailenco/msgpack/v5"
)
// Example struct that matches the schema of your ClickHouse table
type Example struct {
ID uint32 `msgpack:"id"`
Name string `msgpack:"name"`
Age uint32 `msgpack:"age"`
}
func main() {
// Connect to ClickHouse
conn, err := clickhouse.Open(&clickhouse.Options{
Addr: []string{"localhost:9000"},
Auth: clickhouse.Auth{
Database: "default",
Username: "default",
Password: "",
},
})
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
// Create an example record
exampleRecord := &Example{
ID: 1,
Name: "John Doe",
Age: 30,
}
// Marshal the record to binary MsgPack format
binaryData, err := msgpack.Marshal(exampleRecord)
if err != nil {
log.Fatal(err)
}
// Insert the binary MsgPack data into ClickHouse
query := "INSERT INTO test FORMAT MsgPack"
if err := conn.Exec(ctx, query, binaryData); err != nil {
log.Fatal(err)
}
fmt.Println("Data inserted successfully")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment