sky/internal/platform/store/pg.go
root 6ed55254a0 chore: initial import of sky project
Go + PostgreSQL + Valkey backend (cmd/internal/migrations),
uni-app mobile frontend, PC web (web/), admin console (admin/),
Android WebView container (android_project/).
Build artifacts, node_modules, local env and debug screenshots excluded.
2026-11-09 22:22:44 +08:00

59 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package store
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// NewPG 建立 PG 连接池。
// 关键约束:PoolSize 必须受控,见 ARCHITECTURE-V4.md §5.4
//
// 总连接数 = 副本数 × PoolSize ≤ 数据库可承受上限(经 PgBouncer 后)
func NewPG(ctx context.Context, dsn string, maxConns int32) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, fmt.Errorf("解析 PG DSN 失败: %w", err)
}
cfg.MaxConns = maxConns
cfg.MinConns = 2
cfg.MaxConnLifetime = time.Hour
cfg.MaxConnIdleTime = 30 * time.Minute
cfg.HealthCheckPeriod = 30 * time.Second
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("创建 PG 连接池失败: %w", err)
}
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := pool.Ping(pingCtx); err != nil {
pool.Close()
return nil, fmt.Errorf("连接 PG 失败: %w", err)
}
return pool, nil
}
// Tx 在一个事务内执行 fn,返回错误或 panic 时自动回滚
func Tx(ctx context.Context, pool *pgxpool.Pool, fn func(tx pgx.Tx) error) error {
tx, err := pool.Begin(ctx)
if err != nil {
return err
}
defer func() {
if p := recover(); p != nil {
_ = tx.Rollback(ctx)
panic(p)
}
}()
if err := fn(tx); err != nil {
_ = tx.Rollback(ctx)
return err
}
return tx.Commit(ctx)
}