37 lines
1.0 KiB
Go
37 lines
1.0 KiB
Go
// 本包承载国家、区域和历史用户区域重算的 MySQL 持久化。
|
|
package region
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
)
|
|
|
|
// Repository 是国家/区域数据在 MySQL 上的存储实现。
|
|
type Repository struct {
|
|
// db 由父级 MySQL repository 持有,本包只复用连接池。
|
|
db *sql.DB
|
|
}
|
|
|
|
// New 基于共享 MySQL 连接池创建国家/区域存储对象。
|
|
func New(db *sql.DB) *Repository {
|
|
return &Repository{db: db}
|
|
}
|
|
|
|
// queryer 抽象普通连接和事务连接,区域 helper 会同时用于读查询和带锁事务。
|
|
type queryer interface {
|
|
QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
|
|
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
|
|
}
|
|
|
|
func queryRows(ctx context.Context, q queryer, query string, args ...any) (*sql.Rows, error) {
|
|
switch typed := q.(type) {
|
|
case *sql.DB:
|
|
return typed.QueryContext(ctx, query, args...)
|
|
case *sql.Tx:
|
|
return typed.QueryContext(ctx, query, args...)
|
|
default:
|
|
return nil, fmt.Errorf("unsupported queryer %T", q)
|
|
}
|
|
}
|