monitoring/app/storage/clickhouse/client.go
Egor Matveev 4f11e508db
All checks were successful
Deploy Dev / Build (pull_request) Successful in 56s
Deploy Dev / Push (pull_request) Successful in 35s
Deploy Dev / Deploy dev (pull_request) Successful in 12s
fix
2025-06-13 02:35:18 +03:00

80 lines
1.6 KiB
Go

package storage
import (
"context"
"fmt"
"log"
"os"
"github.com/ClickHouse/clickhouse-go/v2"
"github.com/ClickHouse/clickhouse-go/v2/lib/driver"
)
var Connection driver.Conn
func Connect() error {
conn, err := connect()
if err != nil {
return err
}
Connection = *conn
return nil
}
func Close() {
Connection.Close()
}
func connect() (*driver.Conn, error) {
var (
ctx = context.Background()
conn, err = clickhouse.Open(&clickhouse.Options{
Addr: []string{"clickhouse:9000"},
Auth: clickhouse.Auth{
Database: "monitoring",
Username: "default",
Password: os.Getenv("CLICKHOUSE_PASSWORD"),
},
TLS: nil,
})
)
if err != nil {
return nil, err
}
if err := conn.Ping(ctx); err != nil {
if exception, ok := err.(*clickhouse.Exception); ok {
fmt.Printf("Exception [%d] %s \n%s\n", exception.Code, exception.Message, exception.StackTrace)
}
return nil, err
}
return &conn, nil
}
func Migrate() error {
rows, err := Connection.Query(context.TODO(), "SELECT 1")
if err != nil {
log.Fatal("Query failed:", err)
}
rows, err = Connection.Query(
context.TODO(),
`CREATE TABLE IF NOT EXISTS endpoints (
timestamp DateTime,
service_name LowCardinality(String),
endpoint LowCardinality(String),
status_code UInt16,
response_time_ms UInt32,
request_method LowCardinality(String),
)
ENGINE = MergeTree
PARTITION BY toYYYYMM(timestamp)
ORDER BY (service_name, endpoint, request_method, timestamp);`,
)
if err != nil {
log.Fatal(err)
return err
}
defer rows.Close()
return nil
}