Files
go-sms-V2/internal/repository/clickhouse/clickhouse.go
T
Tory 01c8874831
ci / test (push) Canceled after 0s
ci / web-test (push) Canceled after 0s
ci / build (push) Canceled after 0s
ci / deploy-dev (push) Canceled after 0s
S4-D3: 明细按天分区热5天+ClickHouse冷热切换——S4泳道收官(冷查16ms<1s验收✅): ①分区=迁移v22 PARTITION BY RANGE(id)(雪花时间位当天零点边界,主键即分区键零唯一键改造;热5天+未来3天缓冲+pmax兜底;MySQL守卫sqlite跳过)+archive/partition.go EnsurePartitions幂等滚动(REORGANIZE pmax拆分;过期分区归档校验后才DROP)+真机9分区存量无损;②归档=archive域(CH表toDate分区/ArchiveJob 1h:CH当日分区重写幂等→分批2000迁出→count校验相等才DROP MySQL分区或DELETE兜底=零丢失方向;consumer装配启动即首轮)+metrics archive_rows/errors;③冷查=GET /record/history(CH查询/task_no MySQL转译回填/D26契约直连)真机16ms+mobile筛选✓,导出挂账D29下载中心;④settle-check热窗感知=月中对账DetailPartial=true明细↔汇总退化两方基线(日汇总↔结算单,reconcile头注预声明落地)+settle.Service时钟注入nowFn+测试相对时间/period动态;⑤真机5连坑全修存档:MySQL8.0 information_schema非分区表也返回NULL行(判据加PARTITION_NAME IS NOT NULL)/parseTime下DATE() Scan []string带RFC3339尾巴(DISTINCT时刻Scan []time.Time+Go去重双方言)/CH24.3无DROP PARTITION IF EXISTS(先查system.parts)/CH count()返回UInt64(*int64不支持+count错误不可吞)/CH绑定time.Time UTC歧义(预格式化墙钟串)——techContext存档;⑥门禁=build/vet/lint 0/-race 41包全绿/迁移v16..v22两遍幂等(v15断言随窗口右移移除);archive单测5件+settle热窗外基线用例;验收单s4-d3-partition-archive.md+CHANGELOG+memory-bank(S4收官快照/S5下一步/挂账清单)
2026-11-16 12:11:31 +08:00

123 lines
3.7 KiB
Go

// Package clickhouse ClickHouse 存储层(Day 14):
// 历史明细/统计的批量写入(native 协议,阶段 5 历史库依赖)。
package clickhouse
import (
"context"
"fmt"
"time"
ch "github.com/ClickHouse/clickhouse-go/v2"
)
// Config 连接配置(对应 config.ClickHouse)。
type Config struct {
Addrs []string
Database string
Username string
Password string
DialTimeout time.Duration
}
// Conn 存储连接抽象(测试可注入 mock)。
type Conn interface {
Ping(ctx context.Context) error
// BatchInsert 批量插入:INSERT INTO table (columns...) VALUES 每行一行。
// 空行返回 nil;类型由调用方保证与表结构一致。
BatchInsert(ctx context.Context, table string, columns []string, rows [][]any) error
// Query 只读查询(S4·D3 冷查;游标语义 Next/Scan/Close,args 走原生 bind)。
Query(ctx context.Context, query string, args ...any) (Rows, error)
// Exec DDL/管理语句(建表/DROP PARTITION;args 走原生 bind)。
Exec(ctx context.Context, query string, args ...any) error
Close() error
}
// Rows 查询游标抽象(驱动行集满足该接口即可)。
type Rows interface {
Next() bool
Scan(dest ...any) error
Close() error
}
// Open 建立 native 协议连接(lazy,首次命令时建立)。
func Open(cfg Config) (Conn, error) {
if len(cfg.Addrs) == 0 {
return nil, fmt.Errorf("clickhouse: addrs 不能为空")
}
if cfg.DialTimeout <= 0 {
cfg.DialTimeout = 10 * time.Second
}
conn, err := ch.Open(&ch.Options{
Addr: cfg.Addrs,
Auth: ch.Auth{Database: cfg.Database, Username: cfg.Username, Password: cfg.Password},
DialTimeout: cfg.DialTimeout,
Compression: &ch.Compression{Method: ch.CompressionLZ4},
})
if err != nil {
return nil, fmt.Errorf("clickhouse: 打开连接失败: %w", err)
}
return &nativeConn{conn: conn}, nil
}
// nativeConn clickhouse-go 实现。
type nativeConn struct{ conn ch.Conn }
func (c *nativeConn) Ping(ctx context.Context) error { return c.conn.Ping(ctx) }
func (c *nativeConn) Close() error { return c.conn.Close() }
// Query 只读查询透传(*ch.Rows 实现 Rows 接口)。
func (c *nativeConn) Query(ctx context.Context, query string, args ...any) (Rows, error) {
rows, err := c.conn.Query(ctx, query, args...)
if err != nil {
return nil, fmt.Errorf("clickhouse: 查询失败: %w", err)
}
return rows, nil
}
// Exec DDL/管理语句透传。
func (c *nativeConn) Exec(ctx context.Context, query string, args ...any) error {
if err := c.conn.Exec(ctx, query, args...); err != nil {
return fmt.Errorf("clickhouse: 执行失败: %w", err)
}
return nil
}
func (c *nativeConn) BatchInsert(ctx context.Context, table string, columns []string, rows [][]any) error {
if table == "" || len(columns) == 0 {
return fmt.Errorf("clickhouse: table/columns 不能为空")
}
if len(rows) == 0 {
return nil
}
batch, err := c.conn.PrepareBatch(ctx, insertSQL(table, columns))
if err != nil {
return fmt.Errorf("clickhouse: 准备批次失败: %w", err)
}
for _, row := range rows {
if len(row) != len(columns) {
return fmt.Errorf("clickhouse: 行列数 %d 与列定义 %d 不一致", len(row), len(columns))
}
if err := batch.Append(row...); err != nil {
return fmt.Errorf("clickhouse: Append 失败: %w", err)
}
}
if err := batch.Send(); err != nil {
return fmt.Errorf("clickhouse: 批次发送失败: %w", err)
}
return nil
}
// insertSQL 构造 INSERT 语句(表名/列名由调用方白名单控制,防注入)。
func insertSQL(table string, columns []string) string {
// S1-B:标识符反引号化——模块名含连字符(go-sms_*)的表名裸拼会语法错误。
sql := "INSERT INTO `" + table + "` ("
for i, c := range columns {
if i > 0 {
sql += ","
}
sql += "`" + c + "`"
}
return sql + ")"
}