diff --git a/cmd/dbverify/main.go b/cmd/dbverify/main.go new file mode 100644 index 0000000..648ca37 --- /dev/null +++ b/cmd/dbverify/main.go @@ -0,0 +1,178 @@ +// dbverify 在 MySQL/Postgres(或 SQLite)上跑迁移 + 核心 CRUD, +// 确认方言适配器在真实实例上工作。 +// +// 用法: +// +// go run ./cmd/dbverify "mysql://user:pass@tcp(host:3306)/db?parseTime=true&loc=Local&multiStatements=true" +// go run ./cmd/dbverify "postgres://user:pass@host:5432/db?sslmode=disable" +// go run ./cmd/dbverify "sqlite://data/verify.db" +// +// MySQL DSN 必须带 multiStatements=true(goose 多语句迁移需要)。 +// 全部 9 步通过即说明三库的 upsert/布尔/自增主键路径均正常。 +package main + +import ( + "context" + "fmt" + "os" + "time" + + "xianyu-go/internal/db" +) + +func main() { + if len(os.Args) < 2 { + fmt.Println("用法: dbverify ") + os.Exit(1) + } + url := os.Args[1] + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + + fmt.Printf("连接 %s ...\n", maskURL(url)) + database, dialect, err := db.Open(ctx, url) + if err != nil { + fmt.Printf("❌ Open 失败: %v\n", err) + os.Exit(1) + } + defer database.Close() + fmt.Printf("✅ 迁移成功,方言=%s\n", dialect) + + store := db.NewStore(database, dialect) + + // 1) 创建用户 + ok, err := store.Users.Create(ctx, "admin", "admin@test.local", "pw123456") + if err != nil || !ok { + fmt.Printf("❌ 创建用户失败: err=%v ok=%v\n", err, ok) + os.Exit(1) + } + store.Users.SetAdmin(ctx, "admin") + adminUser, _ := store.Users.GetByUsername(ctx, "admin") + userID := adminUser.ID + fmt.Printf("✅ 创建用户 admin (id=%d)\n", userID) + + // 2) 保存 cookie(dialectUpsert: ON CONFLICT/ON DUPLICATE KEY) + if err := store.Cookies.Save(ctx, "acc1", "unb=123; _m_h5_tk=tk_1;", userID); err != nil { + fmt.Printf("❌ 保存 cookie 失败: %v\n", err) + os.Exit(1) + } + // 再 Save 一次验证 upsert + if err := store.Cookies.Save(ctx, "acc1", "unb=123; _m_h5_tk=tk_2;", userID); err != nil { + fmt.Printf("❌ 二次保存 cookie 失败: %v\n", err) + os.Exit(1) + } + v, _ := store.Cookies.GetValue(ctx, "acc1") + fmt.Printf("✅ cookie upsert 成功,value=%s\n", v) + + // 3) 系统设置 upsert(dialectUpsert + key 保留字引用) + if err := store.Settings.Set(ctx, "theme_color", "blue"); err != nil { + fmt.Printf("❌ 系统设置 Set 失败: %v\n", err) + os.Exit(1) + } + if err := store.Settings.Set(ctx, "theme_color", "green"); err != nil { + fmt.Printf("❌ 系统设置二次 Set 失败: %v\n", err) + os.Exit(1) + } + fmt.Println("✅ 系统设置 upsert 成功(key 保留字处理 OK)") + + // 4) 订单 upsert(INSERT IGNORE + 动态 UPDATE) + if err := store.Orders.Upsert(ctx, "order-1", db.OrderUpsertOpts{ + ItemID: "item-1", BuyerID: "buyer-1", CookieID: "acc1", OrderStatus: "paid", Amount: "19.90", + }); err != nil { + fmt.Printf("❌ 订单 Upsert 失败: %v\n", err) + os.Exit(1) + } + // 二次 upsert 验证不重复插入 + if err := store.Orders.Upsert(ctx, "order-1", db.OrderUpsertOpts{ + OrderStatus: "shipped", ChatID: "chat-1", + }); err != nil { + fmt.Printf("❌ 订单二次 Upsert 失败: %v\n", err) + os.Exit(1) + } + fmt.Println("✅ 订单 upsert 成功(INSERT IGNORE + UPDATE OK)") + + // 5) 商品信息 upsert(dialectUpsert,UNIQUE(cookie_id, item_id)) + if err := store.Items.Upsert(ctx, &db.ItemInfoRow{ + CookieID: "acc1", ItemID: "item-1", ItemTitle: "测试商品", ItemPrice: "19.90", + }); err != nil { + fmt.Printf("❌ 商品 Upsert 失败: %v\n", err) + os.Exit(1) + } + if err := store.Items.Upsert(ctx, &db.ItemInfoRow{ + CookieID: "acc1", ItemID: "item-1", ItemTitle: "更新后商品", ItemPrice: "29.90", + }); err != nil { + fmt.Printf("❌ 商品二次 Upsert 失败: %v\n", err) + os.Exit(1) + } + fmt.Println("✅ 商品信息 upsert 成功") + + // 6) 卡密创建(boolToInt 布尔写入) + cardID, err := store.Cards.Create(ctx, &db.CardFull{ + Name: "测试卡组", Type: "data", DataContent: "card-1\ncard-2\ncard-3", Enabled: true, UserID: userID, + }) + if err != nil { + fmt.Printf("❌ 创建卡密失败: %v\n", err) + os.Exit(1) + } + fmt.Printf("✅ 创建卡密组 (id=%d)\n", cardID) + + // 7) 卡密批量追加(AppendBatchData) + added, err := store.Cards.AppendBatchData(ctx, cardID, "card-4\ncard-5") + if err != nil { + fmt.Printf("❌ 追加卡密失败: %v\n", err) + os.Exit(1) + } + fmt.Printf("✅ 追加卡密 %d 个\n", added) + + // 8) 通知渠道 + 绑定(dialectUpsert) + chID, err := store.Notifications.CreateChannel(ctx, &db.NotificationChannelRow{ + Name: "测试渠道", Type: "webhook", Config: `{"webhook_url":"http://x"}`, Enabled: true, UserID: userID, + }) + if err != nil { + fmt.Printf("❌ 创建通知渠道失败: %v\n", err) + os.Exit(1) + } + if err := store.Notifications.SetBindings(ctx, "acc1", []int64{chID}); err != nil { + fmt.Printf("❌ 绑定通知渠道失败: %v\n", err) + os.Exit(1) + } + fmt.Printf("✅ 通知渠道 + 绑定 OK (channel=%d)\n", chID) + + // 9) 自动化规则(TryStartRun 用 INSERT IGNORE + UNIQUE 防重) + ruleID, err := store.Automation.Create(ctx, db.AutomationRuleInput{ + UserID: userID, CookieID: "acc1", ItemID: "item-1", Name: "付款发货", + TriggerType: "order_paid", Enabled: true, Priority: 100, + }) + if err != nil { + fmt.Printf("❌ 创建自动化规则失败: %v\n", err) + os.Exit(1) + } + runID, started, err := store.Automation.TryStartRun(ctx, db.AutomationRun{ + RuleID: ruleID, CookieID: "acc1", TriggerType: "order_paid", TriggerKey: "order-1", Status: "running", + }) + if err != nil || !started { + fmt.Printf("❌ TryStartRun 失败: err=%v started=%v\n", err, started) + os.Exit(1) + } + // 重复触发应 started=false + _, started2, err := store.Automation.TryStartRun(ctx, db.AutomationRun{ + RuleID: ruleID, CookieID: "acc1", TriggerType: "order_paid", TriggerKey: "order-1", Status: "running", + }) + if started2 { + fmt.Printf("❌ TryStartRun 重复触发未防重\n") + os.Exit(1) + } + fmt.Printf("✅ 自动化规则 + 防重 OK (rule=%d run=%d)\n", ruleID, runID) + + fmt.Println("\n🎉 全部验证通过") +} + +func maskURL(url string) string { + // 只显示 scheme 和 host,隐藏密码 + for _, p := range []string{"mysql://", "postgres://", "postgresql://"} { + if len(url) > len(p) && url[:len(p)] == p { + return p + "***@" + url[len(p):] + } + } + return url +} diff --git a/internal/db/automation.go b/internal/db/automation.go index 1b647b6..c76fed8 100644 --- a/internal/db/automation.go +++ b/internal/db/automation.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "encoding/json" + "errors" "fmt" ) @@ -168,7 +169,7 @@ func (a *AutomationRules) Create(ctx context.Context, in AutomationRuleInput) (i return 0, err } defer tx.Rollback() - id, err := createAutomationRuleTx(ctx, tx, in) + id, err := createAutomationRuleTx(ctx, tx, a.Dialect, in) if err != nil { return 0, err } @@ -250,12 +251,26 @@ SELECT a.id,a.rule_id,a.action_type,COALESCE(a.card_id,0),COALESCE(c.name,''),a. // TryStartRun 以 UNIQUE(rule_id, trigger_key) 作为持久化防重。 // 返回 started=false 表示该规则对该触发已执行或正在执行,调用方应直接跳过。 func (a *AutomationRules) TryStartRun(ctx context.Context, run AutomationRun) (int64, bool, error) { - res, err := a.DB.ExecContext(ctx, - dialectInsertIgnorePrefix(a.Dialect)+` INTO automation_runs + query := dialectInsertIgnorePrefix(a.Dialect) + ` INTO automation_runs (rule_id,cookie_id,item_id,order_id,buyer_id,chat_id,trigger_type,trigger_key,status,raw_event_json) -VALUES (?,?,?,?,?,?,?,?,?,?)`+dialectInsertIgnore(a.Dialect, []string{"rule_id", "trigger_key"}), - run.RuleID, run.CookieID, run.ItemID, run.OrderID, run.BuyerID, run.ChatID, run.TriggerType, - run.TriggerKey, "running", validJSON(run.RawEventJSON)) +VALUES (?,?,?,?,?,?,?,?,?,?)` + dialectInsertIgnore(a.Dialect, []string{"rule_id", "trigger_key"}) + args := []any{run.RuleID, run.CookieID, run.ItemID, run.OrderID, run.BuyerID, run.ChatID, + run.TriggerType, run.TriggerKey, "running", validJSON(run.RawEventJSON)} + + if a.Dialect == DialectPostgres { + // pgx 不支持 LastInsertId;用 RETURNING id。ON CONFLICT DO NOTHING 冲突时无行返回 → 未启动。 + var id int64 + err := a.DB.QueryRowContext(ctx, query+" RETURNING id", args...).Scan(&id) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return 0, false, nil + } + return 0, false, err + } + return id, true, nil + } + + res, err := a.DB.ExecContext(ctx, query, args...) if err != nil { return 0, false, err } @@ -354,18 +369,17 @@ SELECT order_id,item_id,buyer_id,spec_name,spec_value,quantity,amount,order_stat return out, rows.Err() } -func createAutomationRuleTx(ctx context.Context, tx *sql.Tx, in AutomationRuleInput) (int64, error) { +func createAutomationRuleTx(ctx context.Context, tx *sql.Tx, dialect Dialect, in AutomationRuleInput) (int64, error) { if in.Priority <= 0 { in.Priority = 100 } - res, err := tx.ExecContext(ctx, ` + id, err := insertReturningID(ctx, tx, dialect, ` INSERT INTO automation_rules (user_id,cookie_id,item_id,name,trigger_type,enabled,priority,config_json) VALUES (?,?,?,?,?,?,?,?)`, in.UserID, in.CookieID, in.ItemID, in.Name, in.TriggerType, boolToInt(in.Enabled), in.Priority, validJSON(in.ConfigJSON)) if err != nil { return 0, err } - id, _ := res.LastInsertId() for _, act := range in.Actions { if err := insertAutomationActionTx(ctx, tx, id, act); err != nil { return 0, err diff --git a/internal/db/db.go b/internal/db/db.go index b188960..7916602 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -42,7 +42,8 @@ type driverName string const ( driverSQLite driverName = "sqlite" driverMySQL driverName = "mysql" - driverPgx driverName = "pgx" + // driverPgx 走 pgx_compat driver(见 pgx_compat.go),把 ? 占位符重写成 $N。 + driverPgx driverName = pgxCompatDriverName ) // Open 打开/创建数据库并执行迁移。dbURL 形如: @@ -103,8 +104,16 @@ func parseDBURL(raw string) (driverName, Dialect, string, error) { case "sqlite", "sqlite3": return driverSQLite, DialectSQLite, sqliteDSN(rest), nil case "mysql": - return driverMySQL, DialectMySQL, rest, nil + // MySQL DSN: user:pass@tcp(host:port)/db?params(无 scheme) + // goose 多语句迁移需要 multiStatements=true,缺失会静默只执行首条语句。 + return driverMySQL, DialectMySQL, mysqlDSN(rest), nil case "postgres", "postgresql", "pgx": + // pgx 接受完整 postgres:// URL;也接受 libpq key=value DSN。 + // 若是 URL 形式(含 @),保留 scheme 还原完整 URL; + // 若是 key=value 形式(含 = 且不含 @),原样透传。 + if strings.Contains(rest, "@") { + return driverPgx, DialectPostgres, scheme + "://" + rest, nil + } return driverPgx, DialectPostgres, rest, nil default: return "", "", "", fmt.Errorf("不支持的数据库 scheme: %s(支持 sqlite/mysql/postgres)", scheme) @@ -116,6 +125,19 @@ 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) } +// mysqlDSN 确保 DSN 含 multiStatements=true(goose 多语句迁移需要,缺失会静默只执行首条语句)。 +// 已显式设置则不覆盖;其余参数原样保留。不强制 parseTime——本仓库时间列按 string/int64 扫描。 +func mysqlDSN(dsn string) string { + if strings.Contains(dsn, "multiStatements=") { + return dsn + } + sep := "?" + if strings.Contains(dsn, "?") { + sep = "&" + } + return dsn + sep + "multiStatements=true" +} + // Migrate 执行嵌入式 goose 迁移,按方言选择子目录。 func Migrate(ctx context.Context, db *sql.DB, dialect Dialect) error { var gooseDialect string diff --git a/internal/db/dialect.go b/internal/db/dialect.go index 4faf48a..396024f 100644 --- a/internal/db/dialect.go +++ b/internal/db/dialect.go @@ -1,6 +1,10 @@ package db -import "strings" +import ( + "context" + "database/sql" + "strings" +) // DialectUpsert 生成 UPSERT 子句,处理三种数据库的语法差异。 // @@ -23,8 +27,10 @@ func DialectUpsert(d Dialect, conflictCols []string, updateAssignments map[strin for _, col := range keys { expr := updateAssignments[col] if d == DialectMySQL { - if strings.HasPrefix(expr, "EXCLUDED.") { - field := strings.TrimPrefix(expr, "EXCLUDED.") + // EXCLUDED.col / excluded.col → VALUES(col)(大小写不敏感) + upper := strings.ToUpper(expr) + if strings.HasPrefix(upper, "EXCLUDED.") { + field := expr[len("EXCLUDED."):] // 保留原大小写 expr = "VALUES(" + field + ")" } } @@ -90,3 +96,28 @@ func sortStrings(s []string) { } } } + +// DBTX 是 *sql.DB 与 *sql.Tx 共有的最小执行接口,供 insertReturningID 复用。 +type DBTX interface { + ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) + QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row +} + +// insertReturningID 执行 INSERT 并返回自增主键 id。 +// Postgres 的 pgx driver 不支持 Result.LastInsertId(Postgres 无该概念), +// 改用 `INSERT ... RETURNING id` + QueryRow.Scan;SQLite/MySQL 走 res.LastInsertId()。 +// query 必须是可安全追加 ` RETURNING id` 的单条 INSERT(无尾随分号/ON CONFLICT 亦可)。 +func insertReturningID(ctx context.Context, exec DBTX, dialect Dialect, query string, args ...any) (int64, error) { + if dialect == DialectPostgres { + var id int64 + if err := exec.QueryRowContext(ctx, query+" RETURNING id", args...).Scan(&id); err != nil { + return 0, err + } + return id, nil + } + res, err := exec.ExecContext(ctx, query, args...) + if err != nil { + return 0, err + } + return res.LastInsertId() +} diff --git a/internal/db/extras.go b/internal/db/extras.go index 921cc09..eab0ca2 100644 --- a/internal/db/extras.go +++ b/internal/db/extras.go @@ -44,13 +44,9 @@ func (k *Keywords) Add(ctx context.Context, cookieID, keyword, reply, itemID, kw if kwType == "" { kwType = "text" } - res, err := k.DB.ExecContext(ctx, + return insertReturningID(ctx, k.DB, k.Dialect, `INSERT INTO keywords (cookie_id, keyword, reply, item_id, type, image_url) VALUES (?,?,?,?,?,?)`, cookieID, keyword, reply, nullable(itemID), kwType, nullable(imageURL)) - if err != nil { - return 0, err - } - return res.LastInsertId() } // DeleteByIndex 按索引(0-based,按 rowid 顺序)删除某账号的一个关键字。 @@ -161,13 +157,9 @@ func (n *Notifications) AllChannelsForUser(ctx context.Context, userID int64) ([ // CreateChannel 创建通知渠道。 func (n *Notifications) CreateChannel(ctx context.Context, c *NotificationChannelRow) (int64, error) { - res, err := n.DB.ExecContext(ctx, + return insertReturningID(ctx, n.DB, n.Dialect, `INSERT INTO notification_channels (name, type, config, enabled, user_id) VALUES (?,?,?,?,?)`, c.Name, c.Type, c.Config, boolToInt(c.Enabled), c.UserID) - if err != nil { - return 0, err - } - return res.LastInsertId() } // UpdateChannel 更新通知渠道。 @@ -376,17 +368,31 @@ func (i *Items) Upsert(ctx context.Context, r *ItemInfoRow) error { // UpsertBasic 插入或补全商品基础信息,不覆盖已有的多规格/多数量发货设置。 func (i *Items) UpsertBasic(ctx context.Context, r *ItemInfoRow) error { + // 三种数据库的条件 upsert:非空才覆盖,空值保留旧值。 + // SQLite/Postgres 用 EXCLUDED.col 引用插入值;MySQL 用 VALUES(col)。 + var conflictClause string + switch i.Dialect { + case DialectMySQL: + conflictClause = ` ON DUPLICATE KEY UPDATE + item_title=CASE WHEN VALUES(item_title) IS NOT NULL AND VALUES(item_title) != '' THEN VALUES(item_title) ELSE item_info.item_title END, + item_description=CASE WHEN VALUES(item_description) IS NOT NULL AND VALUES(item_description) != '' THEN VALUES(item_description) ELSE item_info.item_description END, + item_category=CASE WHEN VALUES(item_category) IS NOT NULL AND VALUES(item_category) != '' THEN VALUES(item_category) ELSE item_info.item_category END, + item_price=CASE WHEN VALUES(item_price) IS NOT NULL AND VALUES(item_price) != '' THEN VALUES(item_price) ELSE item_info.item_price END, + item_detail=CASE WHEN VALUES(item_detail) IS NOT NULL AND VALUES(item_detail) != '' THEN VALUES(item_detail) ELSE item_info.item_detail END, + updated_at=CURRENT_TIMESTAMP` + default: + conflictClause = ` ON CONFLICT(cookie_id, item_id) DO UPDATE SET + item_title=CASE WHEN EXCLUDED.item_title IS NOT NULL AND EXCLUDED.item_title != '' THEN EXCLUDED.item_title ELSE item_info.item_title END, + item_description=CASE WHEN EXCLUDED.item_description IS NOT NULL AND EXCLUDED.item_description != '' THEN EXCLUDED.item_description ELSE item_info.item_description END, + item_category=CASE WHEN EXCLUDED.item_category IS NOT NULL AND EXCLUDED.item_category != '' THEN EXCLUDED.item_category ELSE item_info.item_category END, + item_price=CASE WHEN EXCLUDED.item_price IS NOT NULL AND EXCLUDED.item_price != '' THEN EXCLUDED.item_price ELSE item_info.item_price END, + item_detail=CASE WHEN EXCLUDED.item_detail IS NOT NULL AND EXCLUDED.item_detail != '' THEN EXCLUDED.item_detail ELSE item_info.item_detail END, + updated_at=CURRENT_TIMESTAMP` + } _, err := i.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id, item_id, item_title, item_description, item_category, item_price, item_detail, updated_at) - VALUES (?,?,?,?,?,?,?,CURRENT_TIMESTAMP) - ON CONFLICT(cookie_id, item_id) DO UPDATE SET - item_title=CASE WHEN excluded.item_title IS NOT NULL AND excluded.item_title != '' THEN excluded.item_title ELSE item_info.item_title END, - item_description=CASE WHEN excluded.item_description IS NOT NULL AND excluded.item_description != '' THEN excluded.item_description ELSE item_info.item_description END, - item_category=CASE WHEN excluded.item_category IS NOT NULL AND excluded.item_category != '' THEN excluded.item_category ELSE item_info.item_category END, - item_price=CASE WHEN excluded.item_price IS NOT NULL AND excluded.item_price != '' THEN excluded.item_price ELSE item_info.item_price END, - item_detail=CASE WHEN excluded.item_detail IS NOT NULL AND excluded.item_detail != '' THEN excluded.item_detail ELSE item_info.item_detail END, - updated_at=CURRENT_TIMESTAMP`, + VALUES (?,?,?,?,?,?,?,CURRENT_TIMESTAMP)`+conflictClause, r.CookieID, r.ItemID, nullable(r.ItemTitle), nullable(r.ItemDescription), nullable(r.ItemCategory), nullable(r.ItemPrice), nullable(r.ItemDetail)) return err diff --git a/internal/db/migrations/mysql/00001_init.sql b/internal/db/migrations/mysql/00001_init.sql index c68f248..8453af1 100644 --- a/internal/db/migrations/mysql/00001_init.sql +++ b/internal/db/migrations/mysql/00001_init.sql @@ -80,7 +80,7 @@ CREATE TABLE IF NOT EXISTS ai_reply_settings ( ai_enabled TINYINT(1) DEFAULT 0, model_name VARCHAR(255) DEFAULT 'qwen-plus', api_key TEXT, - base_url TEXT DEFAULT 'https://dashscope.aliyuncs.com/compatible-mode/v1', + base_url VARCHAR(512) 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, diff --git a/internal/db/migrations/postgres/00001_init.sql b/internal/db/migrations/postgres/00001_init.sql index a5bb12d..60333c9 100644 --- a/internal/db/migrations/postgres/00001_init.sql +++ b/internal/db/migrations/postgres/00001_init.sql @@ -3,7 +3,9 @@ -- 闲鱼管家初始 schema(PostgreSQL 版)。 -- 与 SQLite 00001 对齐,差异: -- - INTEGER PRIMARY KEY AUTOINCREMENT → BIGSERIAL PRIMARY KEY --- - BOOLEAN 原生支持(无需 boolToInt,但 Go 代码传 0/1 也兼容) +-- - 布尔列用 INTEGER 0/1(与 SQLite/MySQL 一致,Go 代码用 boolToInt 写、int 读) +-- 不用原生 BOOLEAN:pgx 对 BOOLEAN 严格按 bool 类型读写,与全仓库 ? 占位符 + +-- int 扫描的写法不兼容(见 internal/db/pgx_compat.go)。 -- - INSERT OR IGNORE → ON CONFLICT DO NOTHING(业务代码用方言适配器) -- - CURRENT_TIMESTAMP 一致;updated_at 不设 ON UPDATE(业务代码手动 SET) @@ -13,8 +15,8 @@ CREATE TABLE IF NOT EXISTS users ( 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, + is_active INTEGER DEFAULT 1, + is_admin INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); @@ -23,7 +25,7 @@ CREATE TABLE IF NOT EXISTS sessions ( session_id TEXT PRIMARY KEY, user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, username TEXT NOT NULL, - is_admin BOOLEAN DEFAULT FALSE, + is_admin INTEGER DEFAULT 0, expires_at BIGINT NOT NULL, created_at BIGINT NOT NULL ); @@ -42,19 +44,19 @@ CREATE TABLE IF NOT EXISTS cookies ( id TEXT PRIMARY KEY, value TEXT NOT NULL, user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE, - auto_confirm BOOLEAN DEFAULT TRUE, + auto_confirm INTEGER DEFAULT 1, remark TEXT DEFAULT '', pause_duration INTEGER DEFAULT 10, username TEXT DEFAULT '', password TEXT DEFAULT '', - show_browser BOOLEAN DEFAULT FALSE, + show_browser INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); 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 REFERENCES cookies(id) ON DELETE CASCADE, - enabled BOOLEAN DEFAULT TRUE, + enabled INTEGER DEFAULT 1, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); @@ -72,7 +74,7 @@ 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 REFERENCES cookies(id) ON DELETE CASCADE, - ai_enabled BOOLEAN DEFAULT FALSE, + ai_enabled INTEGER DEFAULT 0, model_name TEXT DEFAULT 'qwen-plus', api_key TEXT, base_url TEXT DEFAULT 'https://dashscope.aliyuncs.com/compatible-mode/v1', @@ -107,9 +109,9 @@ CREATE TABLE IF NOT EXISTS cards ( data_content TEXT, image_url TEXT, description TEXT, - enabled BOOLEAN DEFAULT TRUE, + enabled INTEGER DEFAULT 1, delay_seconds INTEGER DEFAULT 0, - is_multi_spec BOOLEAN DEFAULT FALSE, + is_multi_spec INTEGER DEFAULT 0, spec_name TEXT, spec_value TEXT, user_id BIGINT NOT NULL DEFAULT 1 REFERENCES users(id), @@ -123,7 +125,7 @@ CREATE TABLE IF NOT EXISTS delivery_rules ( keyword TEXT NOT NULL, card_id INTEGER NOT NULL REFERENCES cards(id) ON DELETE CASCADE, delivery_count INTEGER DEFAULT 1, - enabled BOOLEAN DEFAULT TRUE, + enabled INTEGER DEFAULT 1, description TEXT, delivery_times INTEGER DEFAULT 0, user_id BIGINT NOT NULL DEFAULT 1 REFERENCES users(id), @@ -167,8 +169,8 @@ CREATE TABLE IF NOT EXISTS item_info ( item_category TEXT, item_price TEXT, item_detail TEXT, - is_multi_spec BOOLEAN DEFAULT FALSE, - multi_quantity_delivery BOOLEAN DEFAULT FALSE, + is_multi_spec INTEGER DEFAULT 0, + multi_quantity_delivery INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE(cookie_id, item_id) @@ -177,10 +179,10 @@ CREATE TABLE IF NOT EXISTS item_info ( -- 默认回复 CREATE TABLE IF NOT EXISTS default_replies ( cookie_id TEXT PRIMARY KEY REFERENCES cookies(id) ON DELETE CASCADE, - enabled BOOLEAN DEFAULT FALSE, + enabled INTEGER DEFAULT 0, reply_content TEXT, reply_image_url TEXT, - reply_once BOOLEAN DEFAULT FALSE, + reply_once INTEGER DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); @@ -225,7 +227,7 @@ CREATE TABLE IF NOT EXISTS notification_channels ( 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, + enabled INTEGER DEFAULT 1, user_id BIGINT NOT NULL DEFAULT 1 REFERENCES users(id), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP @@ -235,7 +237,7 @@ CREATE TABLE IF NOT EXISTS message_notifications ( id BIGSERIAL PRIMARY KEY, cookie_id TEXT NOT NULL REFERENCES cookies(id) ON DELETE CASCADE, channel_id BIGINT NOT NULL REFERENCES notification_channels(id) ON DELETE CASCADE, - enabled BOOLEAN DEFAULT TRUE, + enabled INTEGER DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE(cookie_id, channel_id) diff --git a/internal/db/migrations/postgres/00004_delivery_rule_variants.sql b/internal/db/migrations/postgres/00004_delivery_rule_variants.sql index 75179f2..37a1da6 100644 --- a/internal/db/migrations/postgres/00004_delivery_rule_variants.sql +++ b/internal/db/migrations/postgres/00004_delivery_rule_variants.sql @@ -10,7 +10,7 @@ CREATE TABLE delivery_rule_variants ( spec_value TEXT NOT NULL DEFAULT '', card_id BIGINT NOT NULL REFERENCES cards(id) ON DELETE RESTRICT, delivery_count INTEGER NOT NULL DEFAULT 1, - enabled BOOLEAN NOT NULL DEFAULT TRUE, + enabled INTEGER NOT NULL DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE(rule_id, spec_name, spec_value) @@ -24,8 +24,8 @@ CREATE INDEX IF NOT EXISTS idx_delivery_rule_variants_card ON delivery_rule_vari 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, FALSE) = TRUE THEN COALESCE(c.spec_name, '') ELSE '' END, - CASE WHEN COALESCE(c.is_multi_spec, FALSE) = TRUE THEN COALESCE(c.spec_value, '') ELSE '' END, + 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 diff --git a/internal/db/migrations/postgres/00008_drop_dead_schema.sql b/internal/db/migrations/postgres/00008_drop_dead_schema.sql index 7b28a9e..848fa52 100644 --- a/internal/db/migrations/postgres/00008_drop_dead_schema.sql +++ b/internal/db/migrations/postgres/00008_drop_dead_schema.sql @@ -22,7 +22,7 @@ CREATE TABLE IF NOT EXISTS delivery_rules ( keyword TEXT NOT NULL, card_id BIGINT NOT NULL, delivery_count INTEGER DEFAULT 1, - enabled BOOLEAN DEFAULT TRUE, + enabled INTEGER DEFAULT 1, description TEXT, delivery_times INTEGER DEFAULT 0, user_id BIGINT NOT NULL DEFAULT 1, @@ -38,7 +38,7 @@ CREATE TABLE IF NOT EXISTS delivery_rule_variants ( spec_value TEXT NOT NULL DEFAULT '', card_id BIGINT NOT NULL, delivery_count INTEGER NOT NULL DEFAULT 1, - enabled BOOLEAN NOT NULL DEFAULT TRUE, + enabled INTEGER NOT NULL DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); diff --git a/internal/db/orders_ext.go b/internal/db/orders_ext.go index dfb6500..d79a615 100644 --- a/internal/db/orders_ext.go +++ b/internal/db/orders_ext.go @@ -191,17 +191,13 @@ func (c *Cards) AllForUser(ctx context.Context, userID int64) ([]CardFull, error // Create 创建卡券,返回新 ID。 func (c *Cards) Create(ctx context.Context, cf *CardFull) (int64, error) { - res, err := c.DB.ExecContext(ctx, + return insertReturningID(ctx, c.DB, c.Dialect, `INSERT INTO cards (name, type, api_config, text_content, data_content, image_url, description, enabled, delay_seconds, is_multi_spec, spec_name, spec_value, user_id) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`, cf.Name, cf.Type, nullable(cf.APIConfig), nullable(cf.TextContent), nullable(cf.DataContent), nullable(cf.ImageURL), nullable(cf.Description), boolToInt(cf.Enabled), cf.DelaySeconds, boolToInt(cf.IsMultiSpec), nullable(cf.SpecName), nullable(cf.SpecValue), cf.UserID) - if err != nil { - return 0, err - } - return res.LastInsertId() } // Update 更新卡券。 diff --git a/internal/db/pgx_compat.go b/internal/db/pgx_compat.go new file mode 100644 index 0000000..9337b5f --- /dev/null +++ b/internal/db/pgx_compat.go @@ -0,0 +1,135 @@ +package db + +import ( + "context" + "database/sql" + "database/sql/driver" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/stdlib" +) + +// pgxCompatDriverName 是包裹 pgx 的自定义 driver 名。 +// 注册后 sql.Open(pgxCompatDriverName, dsn) 走 qPgDriver,把 ? 改写成 $N。 +const pgxCompatDriverName = "pgx_compat" + +func init() { + sql.Register(pgxCompatDriverName, &qPgDriver{base: stdlib.GetDefaultDriver()}) +} + +// qPgDriver 包裹 pgx stdlib driver,仅为了把 ? 占位符改写成 $N。 +// 全仓库业务 SQL 都用 ? 写(SQLite/MySQL 原生支持),Postgres 的 pgx +// 只认 $1/$2/...,不重写会报 "syntax error at or near \",\""。 +type qPgDriver struct{ base driver.Driver } + +func (d *qPgDriver) Open(name string) (driver.Conn, error) { + c, err := d.base.Open(name) + if err != nil { + return nil, err + } + return &qConn{Conn: c}, nil +} + +// qConn 包裹 pgx 连接。Exec/Query/Prepare 重写 SQL,其余方法透传给底层 pgx conn。 +// 嵌入 driver.Conn 接口会把 Close/Begin/Prepare(legacy)等方法自动透传; +// 显式实现的可选接口方法(带 Context、Pinger、Validator 等)覆盖/补齐 pgx 行为。 +type qConn struct { + driver.Conn +} + +func (c *qConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { + ex, ok := c.Conn.(driver.ExecerContext) + if !ok { + return nil, driver.ErrSkip + } + return ex.ExecContext(ctx, rewriteQuestionPlaceholders(query), args) +} + +func (c *qConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { + qx, ok := c.Conn.(driver.QueryerContext) + if !ok { + return nil, driver.ErrSkip + } + return qx.QueryContext(ctx, rewriteQuestionPlaceholders(query), args) +} + +func (c *qConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { + px, ok := c.Conn.(driver.ConnPrepareContext) + if !ok { + return nil, driver.ErrSkip + } + return px.PrepareContext(ctx, rewriteQuestionPlaceholders(query)) +} + +func (c *qConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { + bx, ok := c.Conn.(driver.ConnBeginTx) + if !ok { + return nil, driver.ErrSkip + } + return bx.BeginTx(ctx, opts) +} + +func (c *qConn) Ping(ctx context.Context) error { + if p, ok := c.Conn.(driver.Pinger); ok { + return p.Ping(ctx) + } + return nil +} + +func (c *qConn) IsValid() bool { + if v, ok := c.Conn.(driver.Validator); ok { + return v.IsValid() + } + return true +} + +func (c *qConn) CheckNamedValue(nv *driver.NamedValue) error { + if nc, ok := c.Conn.(driver.NamedValueChecker); ok { + return nc.CheckNamedValue(nv) + } + return driver.ErrSkip +} + +func (c *qConn) ResetSession(ctx context.Context) error { + if rs, ok := c.Conn.(driver.SessionResetter); ok { + return rs.ResetSession(ctx) + } + return nil +} + +// rewriteQuestionPlaceholders 把 SQL 里的 ? 改写成 $1, $2, ...(Postgres 占位符)。 +// 跳过单引号字符串字面量('...')和双引号标识符("...")内的 ?; +// '' 转义单引号也正确处理(相邻两个 ' 不改变字面量状态)。 +func rewriteQuestionPlaceholders(query string) string { + var b strings.Builder + b.Grow(len(query) + 16) + n := 0 + inSingle, inDouble := false, false + for i := 0; i < len(query); i++ { + ch := query[i] + switch ch { + case '\'': + if !inDouble { + inSingle = !inSingle + } + b.WriteByte(ch) + case '"': + if !inSingle { + inDouble = !inDouble + } + b.WriteByte(ch) + case '?': + if inSingle || inDouble { + b.WriteByte(ch) + } else { + n++ + b.WriteByte('$') + b.WriteString(strconv.Itoa(n)) + } + default: + b.WriteByte(ch) + } + } + return b.String() +} diff --git a/internal/db/reply.go b/internal/db/reply.go index 5ac2f20..b9958f0 100644 --- a/internal/db/reply.go +++ b/internal/db/reply.go @@ -31,7 +31,10 @@ type ItemReply struct { } // Keywords 关键字操作。 -type Keywords struct{ DB *sql.DB } +type Keywords struct { + DB *sql.DB + Dialect Dialect +} // AllWithType 取某账号所有关键字(含类型/图片)。 func (k *Keywords) AllWithType(ctx context.Context, cookieID string) ([]Keyword, error) { diff --git a/internal/db/store.go b/internal/db/store.go index 6f83075..c79317a 100644 --- a/internal/db/store.go +++ b/internal/db/store.go @@ -35,7 +35,7 @@ func NewStore(db *sql.DB, dialect Dialect) *Store { Cards: &Cards{DB: db, Dialect: dialect}, Automation: &AutomationRules{DB: db, Dialect: dialect}, Orders: &Orders{DB: db, Dialect: dialect}, - Keywords: &Keywords{DB: db}, + Keywords: &Keywords{DB: db, Dialect: dialect}, DefaultReps: &DefaultReplies{DB: db, Dialect: dialect}, ItemReps: &ItemReplies{DB: db, Dialect: dialect}, AIReply: &AIReply{DB: db},