refactor(db): 阶段A - driver 抽象 + SQLite 保持工作

- db.Open 改为接受 URL(sqlite:// mysql:// postgres://),返回 (db, dialect, err)
- 向后兼容:不含 scheme 的路径仍按 SQLite 文件处理
- migration 移到 migrations/sqlite/ 子目录,embed 包含三个方言目录
- Migrate 按方言选择子目录 + goose dialect
- Store 加 Dialect 字段,NewStore(db, dialect)
- cmd/server 加 -db-url 和 DATABASE_URL 环境变量(优先级:env > -db-url > -db)
- cmd/init-admin 同步支持 URL
- 新增依赖 pgx/v5、go-sql-driver/mysql
- mysql/postgres migration 目录暂为 SQLite 副本占位,阶段B/C 替换
- 所有测试调用方更新为新签名

验证:现有测试全过(SQLite 回归),SQLite 行为不变

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
ChristandClaude Opus 4.8 committed 2026-07-06 12:35:01 +08:00
1 parent 3f7954af84
commit 0fa5d6617c
39 files changed
+1459 -49

No files matched your search

+13 -3
View File
@@ -18,16 +18,26 @@ import (
)
func main() {
dbPath := flag.String("db", "data/xianyu_data.db", "SQLite 数据库路径")
dbPath := flag.String("db", "data/xianyu_data.db", "SQLite 数据库路径(兼容旧用法)")
dbURL := flag.String("db-url", "", "数据库连接 URL(sqlite:// mysql:// postgres://),优先级高于 -db;也可用 DATABASE_URL 环境变量")
flag.Parse()
// 解析数据库连接:DATABASE_URL > -db-url > -db。
resolved := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if resolved == "" {
resolved = strings.TrimSpace(*dbURL)
}
if resolved == "" {
resolved = *dbPath
}
ctx := context.Background()
database, err := db.Open(ctx, *dbPath)
database, dialect, err := db.Open(ctx, resolved)
if err != nil {
fatalf("打开数据库失败: %v", err)
}
defer database.Close()
store := db.NewStore(database)
store := db.NewStore(database, dialect)
users := store.Users
reader := bufio.NewReader(os.Stdin)
+14 -3
View File
@@ -34,7 +34,8 @@ import (
)
func main() {
dbPath := flag.String("db", "data/xianyu_data.db", "SQLite 数据库路径")
dbPath := flag.String("db", "data/xianyu_data.db", "SQLite 数据库路径(兼容旧用法)")
dbURL := flag.String("db-url", "", "数据库连接 URL(sqlite:// mysql:// postgres://),优先级高于 -db;也可用 DATABASE_URL 环境变量")
addr := flag.String("addr", ":8080", "HTTP 监听地址")
webDir := flag.String("web", "", "前端静态资源目录(含 index.html)")
secure := flag.Bool("secure", false, "HTTPS 模式(Cookie 加 Secure)")
@@ -45,6 +46,15 @@ func main() {
adminPassword := flag.String("admin-password", "", "初始化/重置 admin 密码;也可用 XIANYU_ADMIN_PASSWORD 环境变量")
flag.Parse()
// 解析数据库连接:DATABASE_URL > -db-url > -db(SQLite 路径,向后兼容)。
resolvedDBURL := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if resolvedDBURL == "" {
resolvedDBURL = strings.TrimSpace(*dbURL)
}
if resolvedDBURL == "" {
resolvedDBURL = *dbPath
}
level := slog.LevelInfo
if *verbose {
level = slog.LevelDebug
@@ -55,13 +65,14 @@ func main() {
defer cancel()
// 1) DB。
database, err := db.Open(ctx, *dbPath)
database, dialect, err := db.Open(ctx, resolvedDBURL)
if err != nil {
logger.Error("打开数据库失败", "err", err)
os.Exit(1)
}
logger.Info("数据库已就绪", "dialect", dialect)
store := db.NewStore(database, dialect)
defer database.Close()
store := db.NewStore(database)
if *initAdmin {
if err := ensureAdmin(ctx, store, *adminEmail, *adminPassword); err != nil {
+7
View File
@@ -5,6 +5,8 @@ go 1.26.4
require (
github.com/coder/websocket v1.8.15
github.com/go-chi/chi/v5 v5.3.0
github.com/go-sql-driver/mysql v1.10.0
github.com/jackc/pgx/v5 v5.10.0
github.com/playwright-community/playwright-go v0.5700.1
github.com/pressly/goose/v3 v3.27.1
github.com/sashabaranov/go-openai v1.41.2
@@ -15,11 +17,15 @@ require (
)
require (
filippo.io/edwards25519 v1.2.0 // indirect
github.com/deckarep/golang-set/v2 v2.8.0 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-jose/go-jose/v3 v3.0.4 // indirect
github.com/go-stack/stack v1.8.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/mattn/go-isatty v0.0.21 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
@@ -28,6 +34,7 @@ require (
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.46.0 // indirect
golang.org/x/text v0.36.0 // indirect
modernc.org/libc v1.73.4 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
+15
View File
@@ -1,3 +1,5 @@
filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo=
filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc=
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@@ -11,6 +13,8 @@ github.com/go-chi/chi/v5 v5.3.0 h1:halUjDxhshgXHMrao5bB8eNBXo/rnzwr8m5m36glehM=
github.com/go-chi/chi/v5 v5.3.0/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY=
github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw=
github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/go-stack/stack v1.8.1 h1:ntEHSVwIt7PNXNpgPmVfMrNhLtgjlmnZha2kOpuRiDw=
github.com/go-stack/stack v1.8.1/go.mod h1:dcoOX6HbPZSZptuspn9bctJ+N/CnF5gGygcUP3XYfe4=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
@@ -20,6 +24,14 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs=
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
@@ -41,6 +53,7 @@ github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLy
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
@@ -89,6 +102,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
+4 -4
View File
@@ -22,12 +22,12 @@ func (noopHandler) OnAccountAlert(context.Context, string, string, string, strin
// 用无效 cookie 让账号快速进入重连等待(不会真正连上),验证管理逻辑而非网络。
func TestManagerStartStop(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "test.db")
d, err := db.Open(context.Background(), dbPath)
d, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
defer d.Close()
store := db.NewStore(d)
store := db.NewStore(d, db.DialectSQLite)
store.Users.Create(context.Background(), "admin", "a@e.com", "pw")
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
@@ -76,12 +76,12 @@ func TestManagerStartStop(t *testing.T) {
// TestManagerStopAll 验证 StopAll 停止所有运行中的账号,用于进程优雅退出。
func TestManagerStopAll(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "test.db")
d, err := db.Open(context.Background(), dbPath)
d, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
defer d.Close()
store := db.NewStore(d)
store := db.NewStore(d, db.DialectSQLite)
store.Users.Create(context.Background(), "admin", "a@e.com", "pw")
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
// 三个启用账号。
+2 -2
View File
@@ -14,11 +14,11 @@ import (
func newAuth(t *testing.T) (*Service, func()) {
t.Helper()
dbPath := filepath.Join(t.TempDir(), "test.db")
d, err := db.Open(context.Background(), dbPath)
d, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
store := db.NewStore(d)
store := db.NewStore(d, db.DialectSQLite)
// 初始化 admin。
if ok, _ := store.Users.Create(context.Background(), "admin", "a@e.com", "pw"); !ok {
t.Fatal("create admin")
+2 -2
View File
@@ -41,11 +41,11 @@ func (f testFetcher) FetchOrderDetail(context.Context, string, string, string, s
func newAutomationTestStore(t *testing.T) (*db.Store, func()) {
t.Helper()
database, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "test.db"))
database, _, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "test.db"))
if err != nil {
t.Fatalf("Open: %v", err)
}
store := db.NewStore(database)
store := db.NewStore(database, db.DialectSQLite)
if _, err := store.Users.Create(context.Background(), "admin", "admin@example.com", "pw"); err != nil {
t.Fatalf("create user: %v", err)
}
+104 -21
View File
@@ -1,6 +1,11 @@
// Package db 提供 SQLite 连接管理与迁移。
// 使用 modernc.org/sqlite(纯 Go,免 CGO,跨平台编译友好),WAL 模式 + busy_timeout。
// 迁移用 goose 嵌入式执行,把历史 schema 变更收敛为有序 migration。
// Package db 提供数据库连接管理与迁移。
//
// 支持三种数据库,由连接 URL 的 scheme 决定:
// - sqlite://<path> 纯 Go modernc.org/sqlite,WAL + foreign_keys(默认,本地开发)
// - mysql://<dsn> go-sql-driver/mysql(生产/Docker 外置数据库)
// - postgres://<dsn> jackc/pgx(生产/Docker 外置数据库)
//
// 迁移用 goose 嵌入式执行,按方言分目录:migrations/{sqlite,mysql,postgres}。
// 00001 初始 schema 已把历史上运行时 ALTER TABLE 的列补齐到 CREATE TABLE,
// 并修复 schema 不一致(如 orders.system_shipped 原 CREATE 缺失却被引用)。
package db
@@ -10,48 +15,126 @@ import (
"database/sql"
"embed"
"fmt"
"strings"
"time"
"github.com/pressly/goose/v3"
_ "github.com/go-sql-driver/mysql"
_ "github.com/jackc/pgx/v5/stdlib"
_ "modernc.org/sqlite"
)
//go:embed migrations/*.sql
//go:embed migrations/sqlite/*.sql migrations/mysql/*.sql migrations/postgres/*.sql
var migrationsFS embed.FS
// Open 打开/创建数据库并执行迁移。dbPath 形如 "data/xianyu_data.db"。
func Open(ctx context.Context, dbPath string) (*sql.DB, error) {
// _pragma 通过 DSN 设置;foreign_keys=ON 让 ON DELETE CASCADE 生效。
dsn := fmt.Sprintf("file:%s?_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)&_pragma=busy_timeout(5000)&_pragma=synchronous(NORMAL)", dbPath)
db, err := sql.Open("sqlite", dsn)
// Dialect 标识数据库方言。
type Dialect string
const (
DialectSQLite Dialect = "sqlite"
DialectMySQL Dialect = "mysql"
DialectPostgres Dialect = "postgres"
)
// driverName 内部 driver 名(传给 sql.Open)。
type driverName string
const (
driverSQLite driverName = "sqlite"
driverMySQL driverName = "mysql"
driverPgx driverName = "pgx"
)
// Open 打开/创建数据库并执行迁移。dbURL 形如:
//
// sqlite://data/xianyu_data.db
// mysql://user:pass@tcp(host:3306)/dbname?parseTime=true&loc=Local
// postgres://user:pass@host:5432/dbname?sslmode=disable
//
// 为向后兼容,传入的 dbURL 若不含 "://",则按 SQLite 文件路径处理。
func Open(ctx context.Context, dbURL string) (*sql.DB, Dialect, error) {
driver, dialect, dsn, err := parseDBURL(dbURL)
if err != nil {
return nil, fmt.Errorf("打开数据库: %w", err)
return nil, "", err
}
db, err := sql.Open(string(driver), dsn)
if err != nil {
return nil, "", fmt.Errorf("打开数据库: %w", err)
}
// SQLite 写串行,连接池主要供读并发;设单写多读的合理上限。
db.SetMaxOpenConns(8)
db.SetMaxIdleConns(4)
// 连接池参数按 driver 调整:SQLite 写串行,单写多读;MySQL/PG 可多写并发。
switch driver {
case driverSQLite:
db.SetMaxOpenConns(8)
db.SetMaxIdleConns(4)
default:
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(10)
}
db.SetConnMaxLifetime(time.Hour)
if err := db.PingContext(ctx); err != nil {
_ = db.Close()
return nil, fmt.Errorf("ping 数据库: %w", err)
return nil, "", fmt.Errorf("ping 数据库: %w", err)
}
if err := Migrate(ctx, db); err != nil {
if err := Migrate(ctx, db, dialect); err != nil {
_ = db.Close()
return nil, err
return nil, "", err
}
return db, nil
return db, dialect, nil
}
// Migrate 执行嵌入式 goose 迁移。
func Migrate(ctx context.Context, db *sql.DB) error {
if err := goose.SetDialect("sqlite3"); err != nil {
// parseDBURL 解析连接 URL,返回内部 driver 名、方言、DSN。
func parseDBURL(raw string) (driverName, Dialect, string, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", "", "", fmt.Errorf("数据库连接为空")
}
// 向后兼容:不含 scheme 视为 SQLite 文件路径。
if !strings.Contains(raw, "://") {
dsn := sqliteDSN(raw)
return driverSQLite, DialectSQLite, dsn, nil
}
idx := strings.Index(raw, "://")
scheme := raw[:idx]
rest := raw[idx+3:]
switch scheme {
case "sqlite", "sqlite3":
return driverSQLite, DialectSQLite, sqliteDSN(rest), nil
case "mysql":
return driverMySQL, DialectMySQL, rest, nil
case "postgres", "postgresql", "pgx":
return driverPgx, DialectPostgres, rest, nil
default:
return "", "", "", fmt.Errorf("不支持的数据库 scheme: %s(支持 sqlite/mysql/postgres)", scheme)
}
}
// sqliteDSN 构造 SQLite DSN,开启 WAL/foreign_keys/busy_timeout/synchronous。
func sqliteDSN(path string) string {
return fmt.Sprintf("file:%s?_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)&_pragma=busy_timeout(5000)&_pragma=synchronous(NORMAL)", path)
}
// Migrate 执行嵌入式 goose 迁移,按方言选择子目录。
func Migrate(ctx context.Context, db *sql.DB, dialect Dialect) error {
var gooseDialect string
var subdir string
switch dialect {
case DialectSQLite:
gooseDialect, subdir = "sqlite3", "sqlite"
case DialectMySQL:
gooseDialect, subdir = "mysql", "mysql"
case DialectPostgres:
gooseDialect, subdir = "postgres", "postgres"
default:
return fmt.Errorf("未知方言: %s", dialect)
}
if err := goose.SetDialect(gooseDialect); err != nil {
return fmt.Errorf("设置 goose dialect: %w", err)
}
goose.SetBaseFS(migrationsFS)
if err := goose.Up(db, "migrations"); err != nil {
if err := goose.Up(db, "migrations/"+subdir); err != nil {
return fmt.Errorf("执行迁移: %w", err)
}
return nil
+2 -2
View File
@@ -14,7 +14,7 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
dbPath := filepath.Join(tmp, "test.db")
ctx := context.Background()
db, err := Open(ctx, dbPath)
db, _, err := Open(ctx, dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
@@ -57,7 +57,7 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
if err := db.Close(); err != nil {
t.Fatalf("close: %v", err)
}
db2, err := Open(ctx, dbPath)
db2, _, err := Open(ctx, dbPath)
if err != nil {
t.Fatalf("二次 Open 幂等失败: %v", err)
}
@@ -0,0 +1,358 @@
-- +goose Up
-- +goose StatementBegin
-- 闲鱼管家初始 schema。
-- 把历史上 12+ 处运行时 ALTER TABLE 补齐到 CREATE,并修复 schema 不一致:
-- - orders.system_shipped:原 CREATE 缺失却被 insert_or_update_order 引用 → 补齐
-- - orders.receiver_city:原为运行时补齐 → 补齐
-- - delivery_rules.user_id:原 CREATE 缺失却被 create_delivery_rule 引用 → 补齐
-- - cards.user_id / delay_seconds / image_url:历史 ALTER → 补齐
-- - keywords.item_id / type / image_url:历史 ALTER → 补齐
-- - item_info.multi_quantity_delivery:历史 ALTER → 补齐
-- - default_replies.reply_once / reply_image_url:历史 ALTER → 补齐
-- - users.is_admin:历史 ALTER → 补齐
-- 注:老库导入对齐在 Phase 6 单独脚本处理;本迁移面向全新库。
-- 认证与会话
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
is_active BOOLEAN DEFAULT TRUE,
is_admin BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS sessions (
session_id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
username TEXT NOT NULL,
is_admin INTEGER DEFAULT 0,
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
CREATE TABLE IF NOT EXISTS email_verifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL,
code TEXT NOT NULL,
expires_at TIMESTAMP NOT NULL,
used BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS captcha_codes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
code TEXT NOT NULL,
expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 账号(闲鱼 cookie)
CREATE TABLE IF NOT EXISTS cookies (
id TEXT PRIMARY KEY,
value TEXT NOT NULL,
user_id INTEGER NOT NULL,
auto_confirm INTEGER DEFAULT 1,
remark TEXT DEFAULT '',
pause_duration INTEGER DEFAULT 10,
username TEXT DEFAULT '',
password TEXT DEFAULT '',
show_browser INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_cookies_user_id ON cookies(user_id);
CREATE TABLE IF NOT EXISTS cookie_status (
cookie_id TEXT PRIMARY KEY,
enabled BOOLEAN DEFAULT TRUE,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
-- 关键字回复
CREATE TABLE IF NOT EXISTS keywords (
cookie_id TEXT,
keyword TEXT,
reply TEXT,
item_id TEXT,
type TEXT DEFAULT 'text',
image_url TEXT,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_keywords_cookie_id ON keywords(cookie_id);
-- AI 回复
CREATE TABLE IF NOT EXISTS ai_reply_settings (
cookie_id TEXT PRIMARY KEY,
ai_enabled BOOLEAN DEFAULT FALSE,
model_name TEXT DEFAULT 'qwen-plus',
api_key TEXT,
base_url TEXT DEFAULT 'https://dashscope.aliyuncs.com/compatible-mode/v1',
max_discount_percent INTEGER DEFAULT 10,
max_discount_amount INTEGER DEFAULT 100,
max_bargain_rounds INTEGER DEFAULT 3,
custom_prompts TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS ai_conversations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
chat_id TEXT NOT NULL,
user_id TEXT NOT NULL,
item_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
intent TEXT,
bargain_count INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies (id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS ai_item_cache (
item_id TEXT PRIMARY KEY,
data TEXT NOT NULL,
price REAL,
description TEXT,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 卡券与发货规则
CREATE TABLE IF NOT EXISTS cards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
type TEXT NOT NULL CHECK (type IN ('api', 'text', 'data', 'image')),
api_config TEXT,
text_content TEXT,
data_content TEXT,
image_url TEXT,
description TEXT,
enabled BOOLEAN DEFAULT TRUE,
delay_seconds INTEGER DEFAULT 0,
is_multi_spec BOOLEAN DEFAULT FALSE,
spec_name TEXT,
spec_value TEXT,
user_id INTEGER NOT NULL DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id)
);
CREATE INDEX IF NOT EXISTS idx_cards_user_id ON cards(user_id);
CREATE TABLE IF NOT EXISTS delivery_rules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
keyword TEXT NOT NULL,
card_id INTEGER NOT NULL,
delivery_count INTEGER DEFAULT 1,
enabled BOOLEAN DEFAULT TRUE,
description TEXT,
delivery_times INTEGER DEFAULT 0,
user_id INTEGER NOT NULL DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (card_id) REFERENCES cards(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE INDEX IF NOT EXISTS idx_delivery_rules_user_id ON delivery_rules(user_id);
CREATE INDEX IF NOT EXISTS idx_delivery_rules_card_id ON delivery_rules(card_id);
-- 订单
CREATE TABLE IF NOT EXISTS orders (
order_id TEXT PRIMARY KEY,
item_id TEXT,
buyer_id TEXT,
spec_name TEXT,
spec_value TEXT,
quantity TEXT,
amount TEXT,
order_status TEXT DEFAULT 'unknown',
cookie_id TEXT,
is_bargain INTEGER DEFAULT 0,
receiver_name TEXT DEFAULT '',
receiver_phone TEXT DEFAULT '',
receiver_address TEXT DEFAULT '',
receiver_city TEXT DEFAULT '',
version INTEGER DEFAULT 1,
chat_id TEXT DEFAULT '',
system_shipped INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_orders_cookie_id ON orders(cookie_id);
-- 商品信息
CREATE TABLE IF NOT EXISTS item_info (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
item_id TEXT NOT NULL,
item_title TEXT,
item_description TEXT,
item_category TEXT,
item_price TEXT,
item_detail TEXT,
is_multi_spec BOOLEAN DEFAULT FALSE,
multi_quantity_delivery BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE,
UNIQUE(cookie_id, item_id)
);
-- 默认回复
CREATE TABLE IF NOT EXISTS default_replies (
cookie_id TEXT PRIMARY KEY,
enabled BOOLEAN DEFAULT FALSE,
reply_content TEXT,
reply_image_url TEXT,
reply_once BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
-- WS 原始消息记录
CREATE TABLE IF NOT EXISTS ws_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
direction TEXT NOT NULL DEFAULT 'in',
raw_text TEXT NOT NULL DEFAULT '',
parsed_json TEXT NOT NULL DEFAULT '',
message_kind TEXT NOT NULL DEFAULT '',
parse_status TEXT NOT NULL DEFAULT 'raw',
error TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_ws_messages_cookie_id_created_at ON ws_messages(cookie_id, created_at DESC);
-- 指定商品回复
CREATE TABLE IF NOT EXISTS item_replay (
id INTEGER PRIMARY KEY AUTOINCREMENT,
item_id TEXT NOT NULL,
cookie_id TEXT NOT NULL,
reply_content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_item_replay_cookie_item ON item_replay(cookie_id, item_id);
-- 默认回复记录(防重复)
CREATE TABLE IF NOT EXISTS default_reply_records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
chat_id TEXT NOT NULL,
replied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(cookie_id, chat_id),
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
-- 通知
CREATE TABLE IF NOT EXISTS notification_channels (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
type TEXT NOT NULL CHECK (type IN ('qq','ding_talk','dingtalk','feishu','lark','bark','email','webhook','wechat','telegram')),
config TEXT NOT NULL,
enabled BOOLEAN DEFAULT TRUE,
user_id INTEGER NOT NULL DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE TABLE IF NOT EXISTS message_notifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
channel_id INTEGER NOT NULL,
enabled BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE,
FOREIGN KEY (channel_id) REFERENCES notification_channels(id) ON DELETE CASCADE,
UNIQUE(cookie_id, channel_id)
);
-- 系统设置
CREATE TABLE IF NOT EXISTS system_settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
description TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 用户设置
CREATE TABLE IF NOT EXISTS user_settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
UNIQUE(user_id, key)
);
-- 风控日志
CREATE TABLE IF NOT EXISTS risk_control_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
event_type TEXT NOT NULL DEFAULT 'slider_captcha',
event_description TEXT,
processing_result TEXT,
processing_status TEXT DEFAULT 'processing',
error_message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
-- 默认系统设置(不含管理员口令——由 init-admin CLI 初始化)
INSERT OR IGNORE INTO system_settings (key, value, description) VALUES
('theme_color', 'blue', '主题颜色'),
('registration_enabled', 'true', '是否开启用户注册'),
('show_default_login_info', 'true', '是否显示默认登录信息'),
('login_captcha_enabled', 'true', '登录滑动验证码开关'),
('smtp_server', '', 'SMTP服务器地址'),
('smtp_port', '587', 'SMTP端口'),
('smtp_user', '', 'SMTP登录用户名(发件邮箱)'),
('smtp_password', '', 'SMTP登录密码/授权码'),
('smtp_from', '', '发件人显示名(留空则使用用户名)'),
('smtp_use_tls', 'true', '是否启用TLS'),
('smtp_use_ssl', 'false', '是否启用SSL'),
('qq_reply_secret_key', '', 'QQ回复消息API秘钥(必须显式配置,无默认值)'),
('item_sync_enabled', 'true', '是否启用定时自动同步商品'),
('item_sync_interval', '600', '商品同步间隔时间(秒)'),
('item_sync_max_pages', '5', '每次最多同步的页数');
-- +goose StatementEnd
-- +goose Down
DROP TABLE IF EXISTS risk_control_logs;
DROP TABLE IF EXISTS user_settings;
DROP TABLE IF EXISTS system_settings;
DROP TABLE IF EXISTS message_notifications;
DROP TABLE IF EXISTS notification_channels;
DROP TABLE IF EXISTS default_reply_records;
DROP TABLE IF EXISTS item_replay;
DROP TABLE IF EXISTS default_replies;
DROP TABLE IF EXISTS item_info;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS delivery_rules;
DROP TABLE IF EXISTS cards;
DROP TABLE IF EXISTS ai_item_cache;
DROP TABLE IF EXISTS ai_conversations;
DROP TABLE IF EXISTS ai_reply_settings;
DROP TABLE IF EXISTS keywords;
DROP TABLE IF EXISTS cookie_status;
DROP TABLE IF EXISTS cookies;
DROP TABLE IF EXISTS captcha_codes;
DROP TABLE IF EXISTS email_verifications;
DROP TABLE IF EXISTS sessions;
DROP TABLE IF EXISTS users;
@@ -0,0 +1,15 @@
-- +goose Up
-- +goose StatementBegin
ALTER TABLE cookies ADD COLUMN nickname TEXT DEFAULT '';
ALTER TABLE cookies ADD COLUMN avatar_url TEXT DEFAULT '';
ALTER TABLE cookies ADD COLUMN updated_at TIMESTAMP;
UPDATE cookies
SET updated_at = COALESCE(updated_at, created_at, CURRENT_TIMESTAMP);
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
ALTER TABLE cookies DROP COLUMN updated_at;
ALTER TABLE cookies DROP COLUMN avatar_url;
ALTER TABLE cookies DROP COLUMN nickname;
-- +goose StatementEnd
@@ -0,0 +1,8 @@
-- +goose Up
INSERT OR IGNORE INTO system_settings (key, value, description) VALUES
('ai_api_url', 'https://dashscope.aliyuncs.com/compatible-mode/v1', 'AI OpenAI兼容API地址'),
('ai_api_key', '', 'AI API Key'),
('ai_model', 'qwen-plus', 'AI模型名称');
-- +goose Down
DELETE FROM system_settings WHERE key IN ('ai_api_url', 'ai_api_key', 'ai_model');
@@ -0,0 +1,44 @@
-- +goose Up
-- +goose StatementBegin
ALTER TABLE delivery_rules ADD COLUMN cookie_id TEXT NOT NULL DEFAULT '';
ALTER TABLE delivery_rules ADD COLUMN item_id TEXT NOT NULL DEFAULT '';
CREATE TABLE delivery_rule_variants (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rule_id INTEGER NOT NULL,
spec_name TEXT NOT NULL DEFAULT '',
spec_value TEXT NOT NULL DEFAULT '',
card_id INTEGER NOT NULL,
delivery_count INTEGER NOT NULL DEFAULT 1,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (rule_id) REFERENCES delivery_rules(id) ON DELETE CASCADE,
FOREIGN KEY (card_id) REFERENCES cards(id) ON DELETE RESTRICT,
UNIQUE(rule_id, spec_name, spec_value)
);
CREATE INDEX idx_delivery_rules_cookie_item ON delivery_rules(cookie_id, item_id);
CREATE INDEX idx_delivery_rule_variants_rule ON delivery_rule_variants(rule_id);
CREATE INDEX idx_delivery_rule_variants_card ON delivery_rule_variants(card_id);
-- 旧规则迁移为一条默认或指定规格映射。cards 上的规格字段仅保留兼容读取。
INSERT INTO delivery_rule_variants
(rule_id, spec_name, spec_value, card_id, delivery_count, enabled)
SELECT dr.id,
CASE WHEN COALESCE(c.is_multi_spec, 0) = 1 THEN COALESCE(c.spec_name, '') ELSE '' END,
CASE WHEN COALESCE(c.is_multi_spec, 0) = 1 THEN COALESCE(c.spec_value, '') ELSE '' END,
dr.card_id,
CASE WHEN dr.delivery_count > 0 THEN dr.delivery_count ELSE 1 END,
dr.enabled
FROM delivery_rules dr
JOIN cards c ON c.id = dr.card_id;
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DROP TABLE delivery_rule_variants;
DROP INDEX IF EXISTS idx_delivery_rules_cookie_item;
ALTER TABLE delivery_rules DROP COLUMN item_id;
ALTER TABLE delivery_rules DROP COLUMN cookie_id;
-- +goose StatementEnd
@@ -0,0 +1,22 @@
-- +goose Up
-- +goose StatementBegin
CREATE TABLE IF NOT EXISTS ws_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
direction TEXT NOT NULL DEFAULT 'in',
raw_text TEXT NOT NULL DEFAULT '',
parsed_json TEXT NOT NULL DEFAULT '',
message_kind TEXT NOT NULL DEFAULT '',
parse_status TEXT NOT NULL DEFAULT 'raw',
error TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_ws_messages_cookie_id_created_at ON ws_messages(cookie_id, created_at DESC);
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DROP INDEX IF EXISTS idx_ws_messages_cookie_id_created_at;
DROP TABLE IF EXISTS ws_messages;
-- +goose StatementEnd
@@ -0,0 +1,53 @@
-- +goose Up
-- +goose StatementBegin
CREATE TABLE IF NOT EXISTS item_publish_batches (
id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
default_cookie_id TEXT NOT NULL DEFAULT '',
filename TEXT NOT NULL DEFAULT '',
upload_dir TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'pending',
total_count INTEGER NOT NULL DEFAULT 0,
success_count INTEGER NOT NULL DEFAULT 0,
failed_count INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS item_publish_batch_rows (
id INTEGER PRIMARY KEY AUTOINCREMENT,
batch_id TEXT NOT NULL,
row_no INTEGER NOT NULL,
cookie_id TEXT NOT NULL DEFAULT '',
title TEXT NOT NULL DEFAULT '',
description TEXT NOT NULL DEFAULT '',
price TEXT NOT NULL DEFAULT '',
original_price TEXT NOT NULL DEFAULT '',
quantity INTEGER NOT NULL DEFAULT 1,
postage_mode TEXT NOT NULL DEFAULT 'free',
postage TEXT NOT NULL DEFAULT '',
images_json TEXT NOT NULL DEFAULT '[]',
auto_create_delivery_rule INTEGER NOT NULL DEFAULT 0,
card_group_id INTEGER NOT NULL DEFAULT 0,
delivery_count INTEGER NOT NULL DEFAULT 1,
status TEXT NOT NULL DEFAULT 'pending',
item_id TEXT NOT NULL DEFAULT '',
item_url TEXT NOT NULL DEFAULT '',
error_message TEXT NOT NULL DEFAULT '',
raw_json TEXT NOT NULL DEFAULT '{}',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (batch_id) REFERENCES item_publish_batches(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_item_publish_batches_user ON item_publish_batches(user_id, created_at);
CREATE INDEX IF NOT EXISTS idx_item_publish_batch_rows_batch ON item_publish_batch_rows(batch_id, row_no);
CREATE INDEX IF NOT EXISTS idx_item_publish_batch_rows_status ON item_publish_batch_rows(batch_id, status);
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DROP TABLE IF EXISTS item_publish_batch_rows;
DROP TABLE IF EXISTS item_publish_batches;
-- +goose StatementEnd
@@ -0,0 +1,90 @@
-- +goose Up
-- +goose StatementBegin
-- 自动化中心 schema。
--
-- 设计目标:
-- 1. 不再把“自动发货”写死成唯一业务,付款发货、评价赠品、超时求评价都统一为自动化规则。
-- 2. 触发来源可以是 WS 系统事件、计划任务或后台手动触发;规则和动作统一落在 automation_rules/actions。
-- 3. automation_runs 使用 trigger_key 做持久化防重,避免 WS 重放、服务重启或计划任务重复扫描导致重复发送。
CREATE TABLE IF NOT EXISTS automation_rules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
cookie_id TEXT NOT NULL DEFAULT '',
item_id TEXT NOT NULL DEFAULT '',
name TEXT NOT NULL,
trigger_type TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
priority INTEGER NOT NULL DEFAULT 100,
config_json TEXT NOT NULL DEFAULT '{}',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_automation_rules_user ON automation_rules(user_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_automation_rules_match ON automation_rules(cookie_id, item_id, trigger_type, enabled, priority);
CREATE TABLE IF NOT EXISTS automation_rule_actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rule_id INTEGER NOT NULL,
action_type TEXT NOT NULL,
card_id INTEGER,
delivery_count INTEGER NOT NULL DEFAULT 1,
message_template TEXT NOT NULL DEFAULT '',
delay_seconds INTEGER NOT NULL DEFAULT 0,
config_json TEXT NOT NULL DEFAULT '{}',
enabled INTEGER NOT NULL DEFAULT 1,
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (rule_id) REFERENCES automation_rules(id) ON DELETE CASCADE,
FOREIGN KEY (card_id) REFERENCES cards(id) ON DELETE RESTRICT
);
CREATE INDEX IF NOT EXISTS idx_automation_rule_actions_rule ON automation_rule_actions(rule_id, sort_order, id);
CREATE TABLE IF NOT EXISTS automation_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rule_id INTEGER NOT NULL,
cookie_id TEXT NOT NULL,
item_id TEXT NOT NULL DEFAULT '',
order_id TEXT NOT NULL DEFAULT '',
buyer_id TEXT NOT NULL DEFAULT '',
chat_id TEXT NOT NULL DEFAULT '',
trigger_type TEXT NOT NULL,
trigger_key TEXT NOT NULL,
status TEXT NOT NULL,
sent_count INTEGER NOT NULL DEFAULT 0,
error_message TEXT NOT NULL DEFAULT '',
raw_event_json TEXT NOT NULL DEFAULT '{}',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (rule_id) REFERENCES automation_rules(id) ON DELETE CASCADE,
UNIQUE(rule_id, trigger_key)
);
CREATE INDEX IF NOT EXISTS idx_automation_runs_cookie_order ON automation_runs(cookie_id, order_id, trigger_type);
CREATE INDEX IF NOT EXISTS idx_automation_runs_status ON automation_runs(status, updated_at);
ALTER TABLE orders ADD COLUMN paid_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN shipped_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN completed_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN buyer_reviewed_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN last_review_request_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN review_request_count INTEGER NOT NULL DEFAULT 0;
ALTER TABLE item_publish_batch_rows ADD COLUMN automation_json TEXT NOT NULL DEFAULT '{}';
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DROP TABLE IF EXISTS automation_runs;
DROP TABLE IF EXISTS automation_rule_actions;
DROP TABLE IF EXISTS automation_rules;
ALTER TABLE item_publish_batch_rows DROP COLUMN automation_json;
ALTER TABLE orders DROP COLUMN review_request_count;
ALTER TABLE orders DROP COLUMN last_review_request_at;
ALTER TABLE orders DROP COLUMN buyer_reviewed_at;
ALTER TABLE orders DROP COLUMN completed_at;
ALTER TABLE orders DROP COLUMN shipped_at;
ALTER TABLE orders DROP COLUMN paid_at;
-- +goose StatementEnd
@@ -0,0 +1,51 @@
-- +goose Up
-- +goose StatementBegin
-- 清理被 automation_rules 取代或从未使用的 schema:
-- - delivery_rules + delivery_rule_variants:发货规则旧系统,已被 automation_rules 完全取代(前端只走 automation-rules)。
-- - email_verifications / captcha_codes / ai_item_cache / risk_control_logs:从未有 Go 代码读写。
-- - item_publish_batch_rows.auto_create_delivery_rule / card_group_id / delivery_count:批量铺货改走 automation_json,三列从未读写。
DROP TABLE IF EXISTS delivery_rule_variants;
DROP TABLE IF EXISTS delivery_rules;
DROP TABLE IF EXISTS email_verifications;
DROP TABLE IF EXISTS captcha_codes;
DROP TABLE IF EXISTS ai_item_cache;
DROP TABLE IF EXISTS risk_control_logs;
ALTER TABLE item_publish_batch_rows DROP COLUMN auto_create_delivery_rule;
ALTER TABLE item_publish_batch_rows DROP COLUMN card_group_id;
ALTER TABLE item_publish_batch_rows DROP COLUMN delivery_count;
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
-- 仅重建结构,历史数据不可恢复。
CREATE TABLE IF NOT EXISTS delivery_rules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
keyword TEXT NOT NULL,
card_id INTEGER NOT NULL,
delivery_count INTEGER DEFAULT 1,
enabled BOOLEAN DEFAULT TRUE,
description TEXT,
delivery_times INTEGER DEFAULT 0,
user_id INTEGER NOT NULL DEFAULT 1,
cookie_id TEXT NOT NULL DEFAULT '',
item_id TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS delivery_rule_variants (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rule_id INTEGER NOT NULL,
spec_name TEXT NOT NULL DEFAULT '',
spec_value TEXT NOT NULL DEFAULT '',
card_id INTEGER NOT NULL,
delivery_count INTEGER NOT NULL DEFAULT 1,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE item_publish_batch_rows ADD COLUMN auto_create_delivery_rule INTEGER NOT NULL DEFAULT 0;
ALTER TABLE item_publish_batch_rows ADD COLUMN card_group_id INTEGER NOT NULL DEFAULT 0;
ALTER TABLE item_publish_batch_rows ADD COLUMN delivery_count INTEGER NOT NULL DEFAULT 1;
-- +goose StatementEnd
@@ -0,0 +1,358 @@
-- +goose Up
-- +goose StatementBegin
-- 闲鱼管家初始 schema。
-- 把历史上 12+ 处运行时 ALTER TABLE 补齐到 CREATE,并修复 schema 不一致:
-- - orders.system_shipped:原 CREATE 缺失却被 insert_or_update_order 引用 → 补齐
-- - orders.receiver_city:原为运行时补齐 → 补齐
-- - delivery_rules.user_id:原 CREATE 缺失却被 create_delivery_rule 引用 → 补齐
-- - cards.user_id / delay_seconds / image_url:历史 ALTER → 补齐
-- - keywords.item_id / type / image_url:历史 ALTER → 补齐
-- - item_info.multi_quantity_delivery:历史 ALTER → 补齐
-- - default_replies.reply_once / reply_image_url:历史 ALTER → 补齐
-- - users.is_admin:历史 ALTER → 补齐
-- 注:老库导入对齐在 Phase 6 单独脚本处理;本迁移面向全新库。
-- 认证与会话
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
is_active BOOLEAN DEFAULT TRUE,
is_admin BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS sessions (
session_id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
username TEXT NOT NULL,
is_admin INTEGER DEFAULT 0,
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_sessions_user_id ON sessions(user_id);
CREATE TABLE IF NOT EXISTS email_verifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL,
code TEXT NOT NULL,
expires_at TIMESTAMP NOT NULL,
used BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS captcha_codes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
code TEXT NOT NULL,
expires_at TIMESTAMP NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 账号(闲鱼 cookie)
CREATE TABLE IF NOT EXISTS cookies (
id TEXT PRIMARY KEY,
value TEXT NOT NULL,
user_id INTEGER NOT NULL,
auto_confirm INTEGER DEFAULT 1,
remark TEXT DEFAULT '',
pause_duration INTEGER DEFAULT 10,
username TEXT DEFAULT '',
password TEXT DEFAULT '',
show_browser INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_cookies_user_id ON cookies(user_id);
CREATE TABLE IF NOT EXISTS cookie_status (
cookie_id TEXT PRIMARY KEY,
enabled BOOLEAN DEFAULT TRUE,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
-- 关键字回复
CREATE TABLE IF NOT EXISTS keywords (
cookie_id TEXT,
keyword TEXT,
reply TEXT,
item_id TEXT,
type TEXT DEFAULT 'text',
image_url TEXT,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_keywords_cookie_id ON keywords(cookie_id);
-- AI 回复
CREATE TABLE IF NOT EXISTS ai_reply_settings (
cookie_id TEXT PRIMARY KEY,
ai_enabled BOOLEAN DEFAULT FALSE,
model_name TEXT DEFAULT 'qwen-plus',
api_key TEXT,
base_url TEXT DEFAULT 'https://dashscope.aliyuncs.com/compatible-mode/v1',
max_discount_percent INTEGER DEFAULT 10,
max_discount_amount INTEGER DEFAULT 100,
max_bargain_rounds INTEGER DEFAULT 3,
custom_prompts TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS ai_conversations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
chat_id TEXT NOT NULL,
user_id TEXT NOT NULL,
item_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
intent TEXT,
bargain_count INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies (id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS ai_item_cache (
item_id TEXT PRIMARY KEY,
data TEXT NOT NULL,
price REAL,
description TEXT,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 卡券与发货规则
CREATE TABLE IF NOT EXISTS cards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
type TEXT NOT NULL CHECK (type IN ('api', 'text', 'data', 'image')),
api_config TEXT,
text_content TEXT,
data_content TEXT,
image_url TEXT,
description TEXT,
enabled BOOLEAN DEFAULT TRUE,
delay_seconds INTEGER DEFAULT 0,
is_multi_spec BOOLEAN DEFAULT FALSE,
spec_name TEXT,
spec_value TEXT,
user_id INTEGER NOT NULL DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id)
);
CREATE INDEX IF NOT EXISTS idx_cards_user_id ON cards(user_id);
CREATE TABLE IF NOT EXISTS delivery_rules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
keyword TEXT NOT NULL,
card_id INTEGER NOT NULL,
delivery_count INTEGER DEFAULT 1,
enabled BOOLEAN DEFAULT TRUE,
description TEXT,
delivery_times INTEGER DEFAULT 0,
user_id INTEGER NOT NULL DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (card_id) REFERENCES cards(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE INDEX IF NOT EXISTS idx_delivery_rules_user_id ON delivery_rules(user_id);
CREATE INDEX IF NOT EXISTS idx_delivery_rules_card_id ON delivery_rules(card_id);
-- 订单
CREATE TABLE IF NOT EXISTS orders (
order_id TEXT PRIMARY KEY,
item_id TEXT,
buyer_id TEXT,
spec_name TEXT,
spec_value TEXT,
quantity TEXT,
amount TEXT,
order_status TEXT DEFAULT 'unknown',
cookie_id TEXT,
is_bargain INTEGER DEFAULT 0,
receiver_name TEXT DEFAULT '',
receiver_phone TEXT DEFAULT '',
receiver_address TEXT DEFAULT '',
receiver_city TEXT DEFAULT '',
version INTEGER DEFAULT 1,
chat_id TEXT DEFAULT '',
system_shipped INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_orders_cookie_id ON orders(cookie_id);
-- 商品信息
CREATE TABLE IF NOT EXISTS item_info (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
item_id TEXT NOT NULL,
item_title TEXT,
item_description TEXT,
item_category TEXT,
item_price TEXT,
item_detail TEXT,
is_multi_spec BOOLEAN DEFAULT FALSE,
multi_quantity_delivery BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE,
UNIQUE(cookie_id, item_id)
);
-- 默认回复
CREATE TABLE IF NOT EXISTS default_replies (
cookie_id TEXT PRIMARY KEY,
enabled BOOLEAN DEFAULT FALSE,
reply_content TEXT,
reply_image_url TEXT,
reply_once BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
-- WS 原始消息记录
CREATE TABLE IF NOT EXISTS ws_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
direction TEXT NOT NULL DEFAULT 'in',
raw_text TEXT NOT NULL DEFAULT '',
parsed_json TEXT NOT NULL DEFAULT '',
message_kind TEXT NOT NULL DEFAULT '',
parse_status TEXT NOT NULL DEFAULT 'raw',
error TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_ws_messages_cookie_id_created_at ON ws_messages(cookie_id, created_at DESC);
-- 指定商品回复
CREATE TABLE IF NOT EXISTS item_replay (
id INTEGER PRIMARY KEY AUTOINCREMENT,
item_id TEXT NOT NULL,
cookie_id TEXT NOT NULL,
reply_content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_item_replay_cookie_item ON item_replay(cookie_id, item_id);
-- 默认回复记录(防重复)
CREATE TABLE IF NOT EXISTS default_reply_records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
chat_id TEXT NOT NULL,
replied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(cookie_id, chat_id),
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
-- 通知
CREATE TABLE IF NOT EXISTS notification_channels (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
type TEXT NOT NULL CHECK (type IN ('qq','ding_talk','dingtalk','feishu','lark','bark','email','webhook','wechat','telegram')),
config TEXT NOT NULL,
enabled BOOLEAN DEFAULT TRUE,
user_id INTEGER NOT NULL DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE TABLE IF NOT EXISTS message_notifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
channel_id INTEGER NOT NULL,
enabled BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE,
FOREIGN KEY (channel_id) REFERENCES notification_channels(id) ON DELETE CASCADE,
UNIQUE(cookie_id, channel_id)
);
-- 系统设置
CREATE TABLE IF NOT EXISTS system_settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
description TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 用户设置
CREATE TABLE IF NOT EXISTS user_settings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
UNIQUE(user_id, key)
);
-- 风控日志
CREATE TABLE IF NOT EXISTS risk_control_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
event_type TEXT NOT NULL DEFAULT 'slider_captcha',
event_description TEXT,
processing_result TEXT,
processing_status TEXT DEFAULT 'processing',
error_message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
-- 默认系统设置(不含管理员口令——由 init-admin CLI 初始化)
INSERT OR IGNORE INTO system_settings (key, value, description) VALUES
('theme_color', 'blue', '主题颜色'),
('registration_enabled', 'true', '是否开启用户注册'),
('show_default_login_info', 'true', '是否显示默认登录信息'),
('login_captcha_enabled', 'true', '登录滑动验证码开关'),
('smtp_server', '', 'SMTP服务器地址'),
('smtp_port', '587', 'SMTP端口'),
('smtp_user', '', 'SMTP登录用户名(发件邮箱)'),
('smtp_password', '', 'SMTP登录密码/授权码'),
('smtp_from', '', '发件人显示名(留空则使用用户名)'),
('smtp_use_tls', 'true', '是否启用TLS'),
('smtp_use_ssl', 'false', '是否启用SSL'),
('qq_reply_secret_key', '', 'QQ回复消息API秘钥(必须显式配置,无默认值)'),
('item_sync_enabled', 'true', '是否启用定时自动同步商品'),
('item_sync_interval', '600', '商品同步间隔时间(秒)'),
('item_sync_max_pages', '5', '每次最多同步的页数');
-- +goose StatementEnd
-- +goose Down
DROP TABLE IF EXISTS risk_control_logs;
DROP TABLE IF EXISTS user_settings;
DROP TABLE IF EXISTS system_settings;
DROP TABLE IF EXISTS message_notifications;
DROP TABLE IF EXISTS notification_channels;
DROP TABLE IF EXISTS default_reply_records;
DROP TABLE IF EXISTS item_replay;
DROP TABLE IF EXISTS default_replies;
DROP TABLE IF EXISTS item_info;
DROP TABLE IF EXISTS orders;
DROP TABLE IF EXISTS delivery_rules;
DROP TABLE IF EXISTS cards;
DROP TABLE IF EXISTS ai_item_cache;
DROP TABLE IF EXISTS ai_conversations;
DROP TABLE IF EXISTS ai_reply_settings;
DROP TABLE IF EXISTS keywords;
DROP TABLE IF EXISTS cookie_status;
DROP TABLE IF EXISTS cookies;
DROP TABLE IF EXISTS captcha_codes;
DROP TABLE IF EXISTS email_verifications;
DROP TABLE IF EXISTS sessions;
DROP TABLE IF EXISTS users;
@@ -0,0 +1,15 @@
-- +goose Up
-- +goose StatementBegin
ALTER TABLE cookies ADD COLUMN nickname TEXT DEFAULT '';
ALTER TABLE cookies ADD COLUMN avatar_url TEXT DEFAULT '';
ALTER TABLE cookies ADD COLUMN updated_at TIMESTAMP;
UPDATE cookies
SET updated_at = COALESCE(updated_at, created_at, CURRENT_TIMESTAMP);
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
ALTER TABLE cookies DROP COLUMN updated_at;
ALTER TABLE cookies DROP COLUMN avatar_url;
ALTER TABLE cookies DROP COLUMN nickname;
-- +goose StatementEnd
@@ -0,0 +1,8 @@
-- +goose Up
INSERT OR IGNORE INTO system_settings (key, value, description) VALUES
('ai_api_url', 'https://dashscope.aliyuncs.com/compatible-mode/v1', 'AI OpenAI兼容API地址'),
('ai_api_key', '', 'AI API Key'),
('ai_model', 'qwen-plus', 'AI模型名称');
-- +goose Down
DELETE FROM system_settings WHERE key IN ('ai_api_url', 'ai_api_key', 'ai_model');
@@ -0,0 +1,44 @@
-- +goose Up
-- +goose StatementBegin
ALTER TABLE delivery_rules ADD COLUMN cookie_id TEXT NOT NULL DEFAULT '';
ALTER TABLE delivery_rules ADD COLUMN item_id TEXT NOT NULL DEFAULT '';
CREATE TABLE delivery_rule_variants (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rule_id INTEGER NOT NULL,
spec_name TEXT NOT NULL DEFAULT '',
spec_value TEXT NOT NULL DEFAULT '',
card_id INTEGER NOT NULL,
delivery_count INTEGER NOT NULL DEFAULT 1,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (rule_id) REFERENCES delivery_rules(id) ON DELETE CASCADE,
FOREIGN KEY (card_id) REFERENCES cards(id) ON DELETE RESTRICT,
UNIQUE(rule_id, spec_name, spec_value)
);
CREATE INDEX idx_delivery_rules_cookie_item ON delivery_rules(cookie_id, item_id);
CREATE INDEX idx_delivery_rule_variants_rule ON delivery_rule_variants(rule_id);
CREATE INDEX idx_delivery_rule_variants_card ON delivery_rule_variants(card_id);
-- 旧规则迁移为一条默认或指定规格映射。cards 上的规格字段仅保留兼容读取。
INSERT INTO delivery_rule_variants
(rule_id, spec_name, spec_value, card_id, delivery_count, enabled)
SELECT dr.id,
CASE WHEN COALESCE(c.is_multi_spec, 0) = 1 THEN COALESCE(c.spec_name, '') ELSE '' END,
CASE WHEN COALESCE(c.is_multi_spec, 0) = 1 THEN COALESCE(c.spec_value, '') ELSE '' END,
dr.card_id,
CASE WHEN dr.delivery_count > 0 THEN dr.delivery_count ELSE 1 END,
dr.enabled
FROM delivery_rules dr
JOIN cards c ON c.id = dr.card_id;
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DROP TABLE delivery_rule_variants;
DROP INDEX IF EXISTS idx_delivery_rules_cookie_item;
ALTER TABLE delivery_rules DROP COLUMN item_id;
ALTER TABLE delivery_rules DROP COLUMN cookie_id;
-- +goose StatementEnd
@@ -0,0 +1,22 @@
-- +goose Up
-- +goose StatementBegin
CREATE TABLE IF NOT EXISTS ws_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
cookie_id TEXT NOT NULL,
direction TEXT NOT NULL DEFAULT 'in',
raw_text TEXT NOT NULL DEFAULT '',
parsed_json TEXT NOT NULL DEFAULT '',
message_kind TEXT NOT NULL DEFAULT '',
parse_status TEXT NOT NULL DEFAULT 'raw',
error TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_ws_messages_cookie_id_created_at ON ws_messages(cookie_id, created_at DESC);
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DROP INDEX IF EXISTS idx_ws_messages_cookie_id_created_at;
DROP TABLE IF EXISTS ws_messages;
-- +goose StatementEnd
@@ -0,0 +1,53 @@
-- +goose Up
-- +goose StatementBegin
CREATE TABLE IF NOT EXISTS item_publish_batches (
id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
default_cookie_id TEXT NOT NULL DEFAULT '',
filename TEXT NOT NULL DEFAULT '',
upload_dir TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'pending',
total_count INTEGER NOT NULL DEFAULT 0,
success_count INTEGER NOT NULL DEFAULT 0,
failed_count INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS item_publish_batch_rows (
id INTEGER PRIMARY KEY AUTOINCREMENT,
batch_id TEXT NOT NULL,
row_no INTEGER NOT NULL,
cookie_id TEXT NOT NULL DEFAULT '',
title TEXT NOT NULL DEFAULT '',
description TEXT NOT NULL DEFAULT '',
price TEXT NOT NULL DEFAULT '',
original_price TEXT NOT NULL DEFAULT '',
quantity INTEGER NOT NULL DEFAULT 1,
postage_mode TEXT NOT NULL DEFAULT 'free',
postage TEXT NOT NULL DEFAULT '',
images_json TEXT NOT NULL DEFAULT '[]',
auto_create_delivery_rule INTEGER NOT NULL DEFAULT 0,
card_group_id INTEGER NOT NULL DEFAULT 0,
delivery_count INTEGER NOT NULL DEFAULT 1,
status TEXT NOT NULL DEFAULT 'pending',
item_id TEXT NOT NULL DEFAULT '',
item_url TEXT NOT NULL DEFAULT '',
error_message TEXT NOT NULL DEFAULT '',
raw_json TEXT NOT NULL DEFAULT '{}',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (batch_id) REFERENCES item_publish_batches(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_item_publish_batches_user ON item_publish_batches(user_id, created_at);
CREATE INDEX IF NOT EXISTS idx_item_publish_batch_rows_batch ON item_publish_batch_rows(batch_id, row_no);
CREATE INDEX IF NOT EXISTS idx_item_publish_batch_rows_status ON item_publish_batch_rows(batch_id, status);
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DROP TABLE IF EXISTS item_publish_batch_rows;
DROP TABLE IF EXISTS item_publish_batches;
-- +goose StatementEnd
@@ -0,0 +1,90 @@
-- +goose Up
-- +goose StatementBegin
-- 自动化中心 schema。
--
-- 设计目标:
-- 1. 不再把“自动发货”写死成唯一业务,付款发货、评价赠品、超时求评价都统一为自动化规则。
-- 2. 触发来源可以是 WS 系统事件、计划任务或后台手动触发;规则和动作统一落在 automation_rules/actions。
-- 3. automation_runs 使用 trigger_key 做持久化防重,避免 WS 重放、服务重启或计划任务重复扫描导致重复发送。
CREATE TABLE IF NOT EXISTS automation_rules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
cookie_id TEXT NOT NULL DEFAULT '',
item_id TEXT NOT NULL DEFAULT '',
name TEXT NOT NULL,
trigger_type TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
priority INTEGER NOT NULL DEFAULT 100,
config_json TEXT NOT NULL DEFAULT '{}',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_automation_rules_user ON automation_rules(user_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_automation_rules_match ON automation_rules(cookie_id, item_id, trigger_type, enabled, priority);
CREATE TABLE IF NOT EXISTS automation_rule_actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rule_id INTEGER NOT NULL,
action_type TEXT NOT NULL,
card_id INTEGER,
delivery_count INTEGER NOT NULL DEFAULT 1,
message_template TEXT NOT NULL DEFAULT '',
delay_seconds INTEGER NOT NULL DEFAULT 0,
config_json TEXT NOT NULL DEFAULT '{}',
enabled INTEGER NOT NULL DEFAULT 1,
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (rule_id) REFERENCES automation_rules(id) ON DELETE CASCADE,
FOREIGN KEY (card_id) REFERENCES cards(id) ON DELETE RESTRICT
);
CREATE INDEX IF NOT EXISTS idx_automation_rule_actions_rule ON automation_rule_actions(rule_id, sort_order, id);
CREATE TABLE IF NOT EXISTS automation_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rule_id INTEGER NOT NULL,
cookie_id TEXT NOT NULL,
item_id TEXT NOT NULL DEFAULT '',
order_id TEXT NOT NULL DEFAULT '',
buyer_id TEXT NOT NULL DEFAULT '',
chat_id TEXT NOT NULL DEFAULT '',
trigger_type TEXT NOT NULL,
trigger_key TEXT NOT NULL,
status TEXT NOT NULL,
sent_count INTEGER NOT NULL DEFAULT 0,
error_message TEXT NOT NULL DEFAULT '',
raw_event_json TEXT NOT NULL DEFAULT '{}',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (rule_id) REFERENCES automation_rules(id) ON DELETE CASCADE,
UNIQUE(rule_id, trigger_key)
);
CREATE INDEX IF NOT EXISTS idx_automation_runs_cookie_order ON automation_runs(cookie_id, order_id, trigger_type);
CREATE INDEX IF NOT EXISTS idx_automation_runs_status ON automation_runs(status, updated_at);
ALTER TABLE orders ADD COLUMN paid_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN shipped_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN completed_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN buyer_reviewed_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN last_review_request_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN review_request_count INTEGER NOT NULL DEFAULT 0;
ALTER TABLE item_publish_batch_rows ADD COLUMN automation_json TEXT NOT NULL DEFAULT '{}';
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DROP TABLE IF EXISTS automation_runs;
DROP TABLE IF EXISTS automation_rule_actions;
DROP TABLE IF EXISTS automation_rules;
ALTER TABLE item_publish_batch_rows DROP COLUMN automation_json;
ALTER TABLE orders DROP COLUMN review_request_count;
ALTER TABLE orders DROP COLUMN last_review_request_at;
ALTER TABLE orders DROP COLUMN buyer_reviewed_at;
ALTER TABLE orders DROP COLUMN completed_at;
ALTER TABLE orders DROP COLUMN shipped_at;
ALTER TABLE orders DROP COLUMN paid_at;
-- +goose StatementEnd
@@ -0,0 +1,51 @@
-- +goose Up
-- +goose StatementBegin
-- 清理被 automation_rules 取代或从未使用的 schema:
-- - delivery_rules + delivery_rule_variants:发货规则旧系统,已被 automation_rules 完全取代(前端只走 automation-rules)。
-- - email_verifications / captcha_codes / ai_item_cache / risk_control_logs:从未有 Go 代码读写。
-- - item_publish_batch_rows.auto_create_delivery_rule / card_group_id / delivery_count:批量铺货改走 automation_json,三列从未读写。
DROP TABLE IF EXISTS delivery_rule_variants;
DROP TABLE IF EXISTS delivery_rules;
DROP TABLE IF EXISTS email_verifications;
DROP TABLE IF EXISTS captcha_codes;
DROP TABLE IF EXISTS ai_item_cache;
DROP TABLE IF EXISTS risk_control_logs;
ALTER TABLE item_publish_batch_rows DROP COLUMN auto_create_delivery_rule;
ALTER TABLE item_publish_batch_rows DROP COLUMN card_group_id;
ALTER TABLE item_publish_batch_rows DROP COLUMN delivery_count;
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
-- 仅重建结构,历史数据不可恢复。
CREATE TABLE IF NOT EXISTS delivery_rules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
keyword TEXT NOT NULL,
card_id INTEGER NOT NULL,
delivery_count INTEGER DEFAULT 1,
enabled BOOLEAN DEFAULT TRUE,
description TEXT,
delivery_times INTEGER DEFAULT 0,
user_id INTEGER NOT NULL DEFAULT 1,
cookie_id TEXT NOT NULL DEFAULT '',
item_id TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS delivery_rule_variants (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rule_id INTEGER NOT NULL,
spec_name TEXT NOT NULL DEFAULT '',
spec_value TEXT NOT NULL DEFAULT '',
card_id INTEGER NOT NULL,
delivery_count INTEGER NOT NULL DEFAULT 1,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE item_publish_batch_rows ADD COLUMN auto_create_delivery_rule INTEGER NOT NULL DEFAULT 0;
ALTER TABLE item_publish_batch_rows ADD COLUMN card_group_id INTEGER NOT NULL DEFAULT 0;
ALTER TABLE item_publish_batch_rows ADD COLUMN delivery_count INTEGER NOT NULL DEFAULT 1;
-- +goose StatementEnd
+2 -2
View File
@@ -9,11 +9,11 @@ import (
func newTestDB(t *testing.T) (*Store, func()) {
t.Helper()
dbPath := filepath.Join(t.TempDir(), "test.db")
db, err := Open(context.Background(), dbPath)
db, _, err := Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
s := NewStore(db)
s := NewStore(db, DialectSQLite)
return s, func() { db.Close() }
}
+4 -2
View File
@@ -5,6 +5,7 @@ import "database/sql"
// Store 聚合各 repository,供上层(HTTP server、account supervisor 等)统一持有。
type Store struct {
DB *sql.DB
Dialect Dialect
Users *Users
Sessions *Sessions
Cookies *Cookies
@@ -22,10 +23,11 @@ type Store struct {
PublishBatches *ItemPublishBatches
}
// NewStore 基于 *sql.DB 构造聚合 store。
func NewStore(db *sql.DB) *Store {
// NewStore 基于 *sql.DB 构造聚合 store。dialect 用于业务 SQL 方言分支。
func NewStore(db *sql.DB, dialect Dialect) *Store {
return &Store{
DB: db,
Dialect: dialect,
Users: &Users{DB: db},
Sessions: &Sessions{DB: db},
Cookies: &Cookies{DB: db},
+2 -2
View File
@@ -43,11 +43,11 @@ func (h *recordingHandler) OnAccountAlert(_ context.Context, _, _, _, _ string)
func newAccountForTest(t *testing.T) (*Account, *recordingHandler, *db.Store, func()) {
t.Helper()
dbPath := filepath.Join(t.TempDir(), "test.db")
d, err := db.Open(context.Background(), dbPath)
d, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
store := db.NewStore(d)
store := db.NewStore(d, db.DialectSQLite)
store.Users.Create(context.Background(), "admin", "a@e.com", "pw")
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
store.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID)
+2 -2
View File
@@ -10,11 +10,11 @@ import (
func newReplyStore(t *testing.T) (*db.Store, func()) {
t.Helper()
d, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "test.db"))
d, _, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "test.db"))
if err != nil {
t.Fatalf("Open: %v", err)
}
s := db.NewStore(d)
s := db.NewStore(d, db.DialectSQLite)
s.Users.Create(context.Background(), "admin", "a@e.com", "pw")
admin, _ := s.Users.GetByUsername(context.Background(), "admin")
s.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID)
+2 -2
View File
@@ -14,11 +14,11 @@ import (
func newNotifyStore(t *testing.T) (*db.Store, func()) {
t.Helper()
d, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "test.db"))
d, _, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "test.db"))
if err != nil {
t.Fatalf("Open: %v", err)
}
s := db.NewStore(d)
s := db.NewStore(d, db.DialectSQLite)
s.Users.Create(context.Background(), "admin", "a@e.com", "pw")
admin, _ := s.Users.GetByUsername(context.Background(), "admin")
s.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID)
+2 -2
View File
@@ -19,11 +19,11 @@ import (
func newTestServer(t *testing.T) (*Server, *db.Store, func()) {
t.Helper()
dbPath := filepath.Join(t.TempDir(), "test.db")
d, err := db.Open(context.Background(), dbPath)
d, _, err := db.Open(context.Background(), dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
store := db.NewStore(d)
store := db.NewStore(d, db.DialectSQLite)
store.Users.Create(context.Background(), "admin", "a@e.com", "pw")
store.Users.SetAdmin(context.Background(), "admin")
// 一个账号。