feat(backend): 添加车辆与加油记录 model、repository 和 GORM 迁移
完成 Phase 1.2,把 GORM 真正接进来。Phase 1.1 留下的 /health 和骨架保持不变, 本 commit 在此之上铺好数据访问层,Phase 1.3 直接在 service / handler 上挂业务即可。 新增: - internal/model/vehicle.go 车辆实体(严格按 plan §7.1) - internal/model/refuel_record.go 加油记录实体(严格按 plan §7.2) - internal/db/db.go SQLite 连接 + AutoMigrate 入口 * glebarez/sqlite 纯 Go,免 CGO,Windows / Docker 通吃 * DSN 自动启用 WAL + 外键约束 + busy_timeout * 表目录若不存在会自动创建 - internal/repository/vehicle.go 车辆数据访问接口 + GORM 实现 * Create / Get / List / Update / Delete * ClearDefault / SetDefault(切换默认车辆用,在事务里跑避免脏状态) - internal/repository/refuel_record.go 加油记录数据访问接口 + GORM 实现 * Create / Get / Update / Delete * ListByVehicle 支持可选时间窗口 * PrevFullRefuel 找上一次加满,给油耗计算用 main.go 改动: - 启动期 db.Open + db.Migrate,失败直接退出 - application 持有 *gorm.DB,Phase 1.3 起注入 repo / service 设计要点: - repository 全是接口,Service 持有接口便于单测用 fake 替换 - 所有 repo 错误统一包成 apperror.NotFound / apperror.Internal, 不让 GORM 原始错误泄漏到 handler - model.TableName() 显式指定单数,避免 GORM 复数 - refuel_record 用 (vehicle_id, refuel_time) 复合场景常见,已加索引 未做(留给后续 commit): - service 层与 DTO - handler / router - 显式 migration 文件(AGENTS.md 要求 schema 变更必须写 migration; 此次为首次建表,AutoMigrate 即可,后续 schema 改动会补 goose / 自管文件) 验证: go mod tidy all modules verified go vet ./... 0 issues go build 25.9 MB binary 冷启动一次,DB 文件生成在 fuellog-api/data/fuellog.db(WAL/SHM 齐备) listtables 脚本 dump 出来的两表 schema 与 plan §7 完全一致
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
// Package db 负责 GORM 数据库连接的初始化与迁移注册。
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/glebarez/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
|
||||
"github.com/kennethcheng/fuellog-api/internal/model"
|
||||
)
|
||||
|
||||
// Open 打开 SQLite 数据库连接,并确保目标目录存在。
|
||||
//
|
||||
// 设计要点:
|
||||
// - 使用 pure-Go glebarez/sqlite,避免 CGO;Windows / Docker 都友好
|
||||
// - 日志走 slog,关闭 GORM 默认的 stdout 输出
|
||||
// - 启用 WAL + 外键约束,提升并发与一致性
|
||||
func Open(path string) (*gorm.DB, error) {
|
||||
if dir := filepath.Dir(path); dir != "" {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return nil, fmt.Errorf("ensure db dir: %w", err)
|
||||
}
|
||||
}
|
||||
gormLogger := logger.New(
|
||||
slog.NewLogLogger(slog.Default().Handler(), slog.LevelWarn),
|
||||
logger.Config{
|
||||
LogLevel: logger.Warn,
|
||||
Colorful: false,
|
||||
},
|
||||
)
|
||||
dsn := fmt.Sprintf("file:%s?_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)&_pragma=busy_timeout(5000)", path)
|
||||
g, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{Logger: gormLogger})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open sqlite: %w", err)
|
||||
}
|
||||
return g, nil
|
||||
}
|
||||
|
||||
// Migrate 在数据库上注册所有模型。Phase 1.2 之前,业务表只读;Phase 1.2
|
||||
// 起每次 schema 变更必须追加迁移文件,不得依赖此处注册。
|
||||
func Migrate(g *gorm.DB) error {
|
||||
return g.AutoMigrate(
|
||||
&model.Vehicle{},
|
||||
&model.RefuelRecord{},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// RefuelRecord 单次加油记录。
|
||||
//
|
||||
// 关键约定:
|
||||
// - Liters > 0(后端强校验)
|
||||
// - TotalAmount >= 0(允许 0 表示免费加注或赠送)
|
||||
// - PricePerLiter = TotalAmount / Liters(在 service 层实时计算并落库,
|
||||
// 既保留历史真实单价,也方便后续统计直接查询)
|
||||
// - IsFull = true 时,该记录才进入"标准百公里油耗"统计
|
||||
type RefuelRecord struct {
|
||||
ID uint64 `gorm:"primaryKey;column:id" json:"id"`
|
||||
VehicleID uint64 `gorm:"not null;index;column:vehicle_id" json:"vehicle_id"`
|
||||
RefuelTime time.Time `gorm:"not null;index;column:refuel_time" json:"refuel_time"` // UTC
|
||||
Odometer float64 `gorm:"not null;column:odometer" json:"odometer"` // 公里
|
||||
FuelType string `gorm:"not null;column:fuel_type" json:"fuel_type"`
|
||||
Liters float64 `gorm:"not null;column:liters" json:"liters"` // 升
|
||||
PricePerLiter float64 `gorm:"not null;column:price_per_liter" json:"price_per_liter"`
|
||||
TotalAmount float64 `gorm:"not null;column:total_amount" json:"total_amount"` // 元
|
||||
StationName string `gorm:"column:station_name" json:"station_name"`
|
||||
IsFull bool `gorm:"not null;default:false;column:is_full" json:"is_full"`
|
||||
Remark string `gorm:"column:remark" json:"remark"`
|
||||
CreatedAt time.Time `gorm:"not null;column:created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"not null;column:updated_at" json:"updated_at"`
|
||||
}
|
||||
|
||||
// TableName 显式指定表名。
|
||||
func (RefuelRecord) TableName() string { return "refuel_record" }
|
||||
@@ -0,0 +1,25 @@
|
||||
// Package model 包含 FuelLog 的 GORM 实体。
|
||||
//
|
||||
// 表结构严格遵循 FuelLog_PLAN.md §7。
|
||||
// 字段名以 snake_case 形式映射到列;created_at / updated_at 由 GORM 自动维护。
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// Vehicle 车辆。
|
||||
type Vehicle struct {
|
||||
ID uint64 `gorm:"primaryKey;column:id" json:"id"`
|
||||
Name string `gorm:"not null;column:name" json:"name"`
|
||||
Brand string `gorm:"column:brand" json:"brand"`
|
||||
Model string `gorm:"column:model" json:"model"`
|
||||
PlateNumber string `gorm:"column:plate_number" json:"plate_number"`
|
||||
FuelType string `gorm:"not null;column:fuel_type" json:"fuel_type"`
|
||||
TankCapacity float64 `gorm:"column:tank_capacity" json:"tank_capacity"` // 升
|
||||
CurrentOdometer float64 `gorm:"column:current_odometer" json:"current_odometer"` // 公里
|
||||
DefaultVehicle bool `gorm:"not null;default:false;column:default_vehicle" json:"default_vehicle"`
|
||||
CreatedAt time.Time `gorm:"not null;column:created_at" json:"created_at"`
|
||||
UpdatedAt time.Time `gorm:"not null;column:updated_at" json:"updated_at"`
|
||||
}
|
||||
|
||||
// TableName 显式指定表名,避免 GORM 自动复数。
|
||||
func (Vehicle) TableName() string { return "vehicle" }
|
||||
@@ -0,0 +1,102 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/kennethcheng/fuellog-api/internal/model"
|
||||
"github.com/kennethcheng/fuellog-api/pkg/apperror"
|
||||
)
|
||||
|
||||
// RefuelRecordRepository 加油记录表的数据访问接口。
|
||||
type RefuelRecordRepository interface {
|
||||
Create(ctx context.Context, r *model.RefuelRecord) error
|
||||
Get(ctx context.Context, id uint64) (*model.RefuelRecord, error)
|
||||
Update(ctx context.Context, r *model.RefuelRecord) error
|
||||
Delete(ctx context.Context, id uint64) error
|
||||
// List 返回指定车辆的加油记录,按 refuel_time DESC 排序。
|
||||
// 支持可选时间窗口。
|
||||
ListByVehicle(ctx context.Context, vehicleID uint64, start, end *time.Time) ([]model.RefuelRecord, error)
|
||||
// PrevFullRefuel 返回指定车辆在 time 之前最近一次 is_full=true 的记录。
|
||||
// 用于计算百公里油耗。
|
||||
PrevFullRefuel(ctx context.Context, vehicleID uint64, before time.Time) (*model.RefuelRecord, error)
|
||||
}
|
||||
|
||||
func NewRefuelRecordRepository(g *gorm.DB) RefuelRecordRepository {
|
||||
return &refuelRepo{g: g}
|
||||
}
|
||||
|
||||
type refuelRepo struct{ g *gorm.DB }
|
||||
|
||||
func (r *refuelRepo) Create(ctx context.Context, rec *model.RefuelRecord) error {
|
||||
if err := r.g.WithContext(ctx).Create(rec).Error; err != nil {
|
||||
return apperror.Wrap(apperror.CodeInternal, "创建加油记录失败", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *refuelRepo) Get(ctx context.Context, id uint64) (*model.RefuelRecord, error) {
|
||||
var rec model.RefuelRecord
|
||||
if err := r.g.WithContext(ctx).First(&rec, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, apperror.New(apperror.CodeNotFound, "加油记录不存在")
|
||||
}
|
||||
return nil, apperror.Wrap(apperror.CodeInternal, "查询加油记录失败", err)
|
||||
}
|
||||
return &rec, nil
|
||||
}
|
||||
|
||||
func (r *refuelRepo) Update(ctx context.Context, rec *model.RefuelRecord) error {
|
||||
res := r.g.WithContext(ctx).Save(rec)
|
||||
if res.Error != nil {
|
||||
return apperror.Wrap(apperror.CodeInternal, "更新加油记录失败", res.Error)
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return apperror.New(apperror.CodeNotFound, "加油记录不存在")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *refuelRepo) Delete(ctx context.Context, id uint64) error {
|
||||
res := r.g.WithContext(ctx).Delete(&model.RefuelRecord{}, id)
|
||||
if res.Error != nil {
|
||||
return apperror.Wrap(apperror.CodeInternal, "删除加油记录失败", res.Error)
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return apperror.New(apperror.CodeNotFound, "加油记录不存在")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *refuelRepo) ListByVehicle(ctx context.Context, vehicleID uint64, start, end *time.Time) ([]model.RefuelRecord, error) {
|
||||
q := r.g.WithContext(ctx).Where("vehicle_id = ?", vehicleID)
|
||||
if start != nil {
|
||||
q = q.Where("refuel_time >= ?", *start)
|
||||
}
|
||||
if end != nil {
|
||||
q = q.Where("refuel_time <= ?", *end)
|
||||
}
|
||||
var out []model.RefuelRecord
|
||||
if err := q.Order("refuel_time DESC, id DESC").Find(&out).Error; err != nil {
|
||||
return nil, apperror.Wrap(apperror.CodeInternal, "查询加油记录列表失败", err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *refuelRepo) PrevFullRefuel(ctx context.Context, vehicleID uint64, before time.Time) (*model.RefuelRecord, error) {
|
||||
var rec model.RefuelRecord
|
||||
err := r.g.WithContext(ctx).
|
||||
Where("vehicle_id = ? AND is_full = ? AND refuel_time < ?", vehicleID, true, before).
|
||||
Order("refuel_time DESC, id DESC").
|
||||
First(&rec).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, apperror.New(apperror.CodeNotFound, "此前没有加满油记录")
|
||||
}
|
||||
return nil, apperror.Wrap(apperror.CodeInternal, "查询前次加满记录失败", err)
|
||||
}
|
||||
return &rec, nil
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// Package repository 负责数据库访问。
|
||||
//
|
||||
// 设计原则:
|
||||
// - 每个 repo 都是接口 + GORM 实现,Service 持有接口便于单测替换
|
||||
// - 不在 repo 内做业务逻辑(比如不会去算油耗)
|
||||
// - 错误统一包成 apperror.NotFound / apperror.Internal
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/kennethcheng/fuellog-api/internal/model"
|
||||
"github.com/kennethcheng/fuellog-api/pkg/apperror"
|
||||
)
|
||||
|
||||
// VehicleRepository 车辆表的数据访问接口。
|
||||
type VehicleRepository interface {
|
||||
Create(ctx context.Context, v *model.Vehicle) error
|
||||
Get(ctx context.Context, id uint64) (*model.Vehicle, error)
|
||||
List(ctx context.Context) ([]model.Vehicle, error)
|
||||
Update(ctx context.Context, v *model.Vehicle) error
|
||||
Delete(ctx context.Context, id uint64) error
|
||||
ClearDefault(ctx context.Context, tx *gorm.DB) error
|
||||
SetDefault(ctx context.Context, tx *gorm.DB, id uint64) error
|
||||
}
|
||||
|
||||
// NewVehicleRepository 返回 GORM 实现。
|
||||
func NewVehicleRepository(g *gorm.DB) VehicleRepository {
|
||||
return &vehicleRepo{g: g}
|
||||
}
|
||||
|
||||
type vehicleRepo struct{ g *gorm.DB }
|
||||
|
||||
func (r *vehicleRepo) Create(ctx context.Context, v *model.Vehicle) error {
|
||||
if err := r.g.WithContext(ctx).Create(v).Error; err != nil {
|
||||
return apperror.Wrap(apperror.CodeInternal, "创建车辆失败", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *vehicleRepo) Get(ctx context.Context, id uint64) (*model.Vehicle, error) {
|
||||
var v model.Vehicle
|
||||
if err := r.g.WithContext(ctx).First(&v, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, apperror.New(apperror.CodeNotFound, "车辆不存在")
|
||||
}
|
||||
return nil, apperror.Wrap(apperror.CodeInternal, "查询车辆失败", err)
|
||||
}
|
||||
return &v, nil
|
||||
}
|
||||
|
||||
func (r *vehicleRepo) List(ctx context.Context) ([]model.Vehicle, error) {
|
||||
var vs []model.Vehicle
|
||||
if err := r.g.WithContext(ctx).Order("default_vehicle DESC, id ASC").Find(&vs).Error; err != nil {
|
||||
return nil, apperror.Wrap(apperror.CodeInternal, "查询车辆列表失败", err)
|
||||
}
|
||||
return vs, nil
|
||||
}
|
||||
|
||||
func (r *vehicleRepo) Update(ctx context.Context, v *model.Vehicle) error {
|
||||
res := r.g.WithContext(ctx).Save(v)
|
||||
if res.Error != nil {
|
||||
return apperror.Wrap(apperror.CodeInternal, "更新车辆失败", res.Error)
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return apperror.New(apperror.CodeNotFound, "车辆不存在")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *vehicleRepo) Delete(ctx context.Context, id uint64) error {
|
||||
res := r.g.WithContext(ctx).Delete(&model.Vehicle{}, id)
|
||||
if res.Error != nil {
|
||||
return apperror.Wrap(apperror.CodeInternal, "删除车辆失败", res.Error)
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return apperror.New(apperror.CodeNotFound, "车辆不存在")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearDefault 在事务内把当前所有 default_vehicle 置为 false。
|
||||
// 由 service 在切换默认车辆时调用,避免出现两个默认车辆。
|
||||
func (r *vehicleRepo) ClearDefault(ctx context.Context, tx *gorm.DB) error {
|
||||
if err := tx.WithContext(ctx).Model(&model.Vehicle{}).
|
||||
Where("default_vehicle = ?", true).
|
||||
Update("default_vehicle", false).Error; err != nil {
|
||||
return apperror.Wrap(apperror.CodeInternal, "清除默认车辆标记失败", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetDefault 在事务内把指定车辆置为默认。
|
||||
func (r *vehicleRepo) SetDefault(ctx context.Context, tx *gorm.DB, id uint64) error {
|
||||
res := tx.WithContext(ctx).Model(&model.Vehicle{}).
|
||||
Where("id = ?", id).
|
||||
Update("default_vehicle", true)
|
||||
if res.Error != nil {
|
||||
return apperror.Wrap(apperror.CodeInternal, "设置默认车辆失败", res.Error)
|
||||
}
|
||||
if res.RowsAffected == 0 {
|
||||
return apperror.New(apperror.CodeNotFound, "车辆不存在")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user