Quick Start with GORM ClickHouse
masterTo connect to ClickHouse using GORM, use clickhouse.Open(dsn) with a valid DSN string. You can perform standard GORM operations like AutoMigrate, Create, and Find.
This driver also supports setting ClickHouse-specific table options and cluster options during migration using db.Set with the following keys:
gorm:table_options: Used to specify the ClickHouse engine (e.g.,ENGINE=Distributed(...)).gorm:table_cluster_options: Used to specify cluster-specific settings (e.g.,on cluster default).
package main
import (
"gorm.io/driver/clickhouse"
"gorm.io/gorm"
)
type User struct {
Name string
Age int
}
func main() {
dsn := "clickhouse://gorm:gorm@localhost:9942/gorm?dial_timeout=10s&read_timeout=20s"
db, err := gorm.Open(clickhouse.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Auto Migrate
db.AutoMigrate(&User{})
// Set table options (e.g. Distributed engine)
db.Set("gorm:table_options", "ENGINE=Distributed(cluster, default, hits)").AutoMigrate(&User{})
// Set table cluster options
db.Set("gorm:table_cluster_options", "on cluster default").AutoMigrate(&User{})
// Insert
db.Create(&User{Name: "Angeliz", Age: 18})
// Select
db.Find(&User{}, "name = ?", "Angeliz")
// Batch Insert
users := []User{
{Age: 12, Name: "Bruce Lee"},
{Age: 13, Name: "Feynman"},
{Age: 14, Name: "Angeliz"},
}
db.Create(&users)
}