aa14204640
Task 3 计划的 RefundSum→比较→CreateRefund 两段式裸读写在并发下会超退(两个请求都读到 reserved=0、都通过、都插入)。仿 store/order.go::MarkAttemptPaid 的模式,把锁订单行 (clause.Locking FOR UPDATE,MySQL 真锁/SQLite 由 glebarez 静默丢弃)+ 求和 + 校验 + 插入 收进单个 s.db.Transaction。SQLite 侧真正的串行化靠 DSN _txlock=immediate(BEGIN IMMEDIATE 在事务开始就抢写锁)+ busy_timeout,补进 testdb.go 与 main.go 的 sqlite DSN 构造。
45 lines
1.7 KiB
Go
45 lines
1.7 KiB
Go
package model
|
|
|
|
import (
|
|
"fmt"
|
|
"sync/atomic"
|
|
"testing"
|
|
|
|
"github.com/glebarez/sqlite"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
)
|
|
|
|
var testDBCounter int64
|
|
|
|
// OpenTestDB opens an in-memory SQLite DB with the v2 schema migrated.
|
|
// Shared by all package tests (pay has no prior DB test harness — this is it).
|
|
// Each call gets a uniquely named in-memory DB (cache=shared is still needed
|
|
// so GORM's connection pool sees the same migrated schema across connections),
|
|
// so concurrent/parallel tests in the same package don't share state.
|
|
func OpenTestDB(t *testing.T) *gorm.DB {
|
|
t.Helper()
|
|
n := atomic.AddInt64(&testDBCounter, 1)
|
|
// _txlock=immediate: BEGIN IMMEDIATE 让每个事务一开始就抢库级写锁(而非默认
|
|
// BEGIN DEFERRED 推迟到首条写语句才抢),使并发事务在读阶段就串行化——守卫类
|
|
// 事务(锁行/求和/校验/插入,见 RefundStore.CreateRefundGuarded)依赖此语义,
|
|
// 呼应 pangolin 的 SQLite DSN 约定(server/internal/db/db.go)。
|
|
// _pragma=busy_timeout(5000): 抢不到写锁时等待重试而非立即 SQLITE_BUSY 报错。
|
|
dsn := fmt.Sprintf("file:testdb_%d?mode=memory&cache=shared&_txlock=immediate&_pragma=busy_timeout(5000)", n)
|
|
db, err := gorm.Open(sqlite.Open(dsn),
|
|
&gorm.Config{Logger: logger.Default.LogMode(logger.Silent), TranslateError: true})
|
|
if err != nil {
|
|
t.Fatalf("open test db: %v", err)
|
|
}
|
|
if err := db.AutoMigrate(&OrderV2{}, &Attempt{}, &Account{}, &Refund{}, &WebhookDelivery{},
|
|
&Product{}, &ProductPrice{}); err != nil {
|
|
t.Fatalf("migrate: %v", err)
|
|
}
|
|
if err := UpgradeWebhookDeliveryIndex(db); err != nil {
|
|
t.Fatalf("upgrade webhook_deliveries uq_delivery index: %v", err)
|
|
}
|
|
sqlDB, _ := db.DB()
|
|
t.Cleanup(func() { _ = sqlDB.Close() })
|
|
return db
|
|
}
|