chore: initial commit of HouseholdBudgetBook (backend, frontend, desktop)

This commit is contained in:
mapleferry committed 2026-11-29 21:29:06 +08:00
commit 4a5db3f1f9
167 files changed
+21732

No files matched your search

+89
View File
@@ -0,0 +1,89 @@
package db
import (
"database/sql"
"embed"
"fmt"
"io/fs"
"sort"
"strconv"
"strings"
)
//go:embed migrations/*.sql
var migrationFiles embed.FS
func RunMigrations(db *sql.DB) error {
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS migrations (
version INTEGER PRIMARY KEY,
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
)`); err != nil {
return fmt.Errorf("create migrations table: %w", err)
}
entries, err := fs.ReadDir(migrationFiles, "migrations")
if err != nil {
return fmt.Errorf("read migration dir: %w", err)
}
type migration struct {
version int
name string
content string
}
var migrations []migration
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
continue
}
parts := strings.SplitN(entry.Name(), "_", 2)
version, err := strconv.Atoi(parts[0])
if err != nil {
return fmt.Errorf("parse migration version from %s: %w", entry.Name(), err)
}
data, err := migrationFiles.ReadFile("migrations/" + entry.Name())
if err != nil {
return fmt.Errorf("read migration %s: %w", entry.Name(), err)
}
migrations = append(migrations, migration{version: version, name: entry.Name(), content: string(data)})
}
sort.Slice(migrations, func(i, j int) bool {
return migrations[i].version < migrations[j].version
})
var currentVersion int
err = db.QueryRow("SELECT COALESCE(MAX(version), 0) FROM migrations").Scan(&currentVersion)
if err != nil {
return fmt.Errorf("query current migration version: %w", err)
}
for _, m := range migrations {
if m.version <= currentVersion {
continue
}
tx, err := db.Begin()
if err != nil {
return fmt.Errorf("begin migration %d: %w", m.version, err)
}
if _, err := tx.Exec(m.content); err != nil {
tx.Rollback()
return fmt.Errorf("execute migration %d (%s): %w", m.version, m.name, err)
}
if _, err := tx.Exec("INSERT INTO migrations (version) VALUES (?)", m.version); err != nil {
tx.Rollback()
return fmt.Errorf("record migration %d: %w", m.version, err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit migration %d: %w", m.version, err)
}
}
return nil
}
+50
View File
@@ -0,0 +1,50 @@
CREATE TABLE IF NOT EXISTS members (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
relation TEXT NOT NULL DEFAULT '',
birthday TEXT DEFAULT '',
phone TEXT DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
type TEXT NOT NULL CHECK (type IN ('income', 'expense')),
parent_id INTEGER REFERENCES categories(id) ON DELETE SET NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
is_active INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_categories_parent ON categories(parent_id);
CREATE INDEX IF NOT EXISTS idx_categories_type ON categories(type);
CREATE TABLE IF NOT EXISTS accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
type TEXT NOT NULL DEFAULT 'other',
balance INTEGER NOT NULL DEFAULT 0,
is_active INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT NOT NULL CHECK (type IN ('income', 'expense')),
amount INTEGER NOT NULL CHECK (amount >= 0),
category_id INTEGER NOT NULL REFERENCES categories(id),
account_id INTEGER REFERENCES accounts(id) ON DELETE SET NULL,
member_id INTEGER REFERENCES members(id) ON DELETE SET NULL,
date TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_transactions_date ON transactions(date);
CREATE INDEX IF NOT EXISTS idx_transactions_category ON transactions(category_id);
CREATE INDEX IF NOT EXISTS idx_transactions_type_date ON transactions(type, date);
CREATE INDEX IF NOT EXISTS idx_transactions_account ON transactions(account_id);
CREATE INDEX IF NOT EXISTS idx_transactions_member ON transactions(member_id);
@@ -0,0 +1,4 @@
ALTER TABLE accounts ADD COLUMN bank_name TEXT NOT NULL DEFAULT '';
ALTER TABLE accounts ADD COLUMN card_number TEXT NOT NULL DEFAULT '';
ALTER TABLE accounts ADD COLUMN branch_name TEXT NOT NULL DEFAULT '';
ALTER TABLE accounts ADD COLUMN note TEXT NOT NULL DEFAULT '';
+25
View File
@@ -0,0 +1,25 @@
CREATE TABLE IF NOT EXISTS budgets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
year INTEGER NOT NULL,
month INTEGER,
category_id INTEGER REFERENCES categories(id) ON DELETE CASCADE,
amount INTEGER NOT NULL DEFAULT 0 CHECK (amount >= 0),
note TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_budgets_year_month ON budgets(year, month);
CREATE INDEX IF NOT EXISTS idx_budgets_category ON budgets(category_id);
CREATE UNIQUE INDEX IF NOT EXISTS ux_budgets_annual_total
ON budgets(year)
WHERE month IS NULL AND category_id IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS ux_budgets_annual_category
ON budgets(year, category_id)
WHERE month IS NULL AND category_id IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS ux_budgets_monthly_total
ON budgets(year, month)
WHERE month IS NOT NULL AND category_id IS NULL;
CREATE UNIQUE INDEX IF NOT EXISTS ux_budgets_monthly_category
ON budgets(year, month, category_id)
WHERE month IS NOT NULL AND category_id IS NOT NULL;
@@ -0,0 +1,65 @@
CREATE TABLE IF NOT EXISTS assets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
type TEXT NOT NULL DEFAULT 'other',
value INTEGER NOT NULL DEFAULT 0 CHECK (value >= 0),
note TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_assets_type ON assets(type);
CREATE TABLE IF NOT EXISTS liabilities (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
type TEXT NOT NULL DEFAULT 'other',
principal INTEGER NOT NULL DEFAULT 0 CHECK (principal >= 0),
interest_rate REAL NOT NULL DEFAULT 0,
monthly_payment INTEGER NOT NULL DEFAULT 0 CHECK (monthly_payment >= 0),
remaining_terms INTEGER NOT NULL DEFAULT 0 CHECK (remaining_terms >= 0),
note TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_liabilities_type ON liabilities(type);
CREATE TABLE IF NOT EXISTS asset_snapshots (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
total_asset INTEGER NOT NULL DEFAULT 0,
total_debt INTEGER NOT NULL DEFAULT 0,
net_worth INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE(date)
);
CREATE TABLE IF NOT EXISTS policies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
type TEXT NOT NULL DEFAULT 'other',
insured_person TEXT NOT NULL DEFAULT '',
premium INTEGER NOT NULL DEFAULT 0 CHECK (premium >= 0),
coverage_amount INTEGER NOT NULL DEFAULT 0 CHECK (coverage_amount >= 0),
start_date TEXT NOT NULL DEFAULT '',
end_date TEXT NOT NULL DEFAULT '',
beneficiary TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'active',
note TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_policies_end_date ON policies(end_date);
CREATE INDEX IF NOT EXISTS idx_policies_status ON policies(status);
CREATE TABLE IF NOT EXISTS lifecycle_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
year INTEGER NOT NULL,
member_id INTEGER REFERENCES members(id) ON DELETE SET NULL,
event TEXT NOT NULL,
estimated_cost INTEGER NOT NULL DEFAULT 0 CHECK (estimated_cost >= 0),
note TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_lifecycle_year ON lifecycle_events(year);
CREATE INDEX IF NOT EXISTS idx_lifecycle_member ON lifecycle_events(member_id);
@@ -0,0 +1,6 @@
UPDATE accounts SET type = 'debit_card' WHERE type = 'bank_card';
ALTER TABLE transactions ADD COLUMN source_key TEXT NOT NULL DEFAULT '';
CREATE UNIQUE INDEX IF NOT EXISTS ux_transactions_source_key
ON transactions(source_key)
WHERE source_key <> '';
@@ -0,0 +1,16 @@
CREATE TABLE IF NOT EXISTS import_batches (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT NOT NULL,
bank_name TEXT NOT NULL DEFAULT '',
card_type TEXT NOT NULL DEFAULT '',
account_id INTEGER REFERENCES accounts(id) ON DELETE SET NULL,
imported_count INTEGER NOT NULL DEFAULT 0,
skipped_count INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
ALTER TABLE transactions ADD COLUMN counterparty TEXT NOT NULL DEFAULT '';
ALTER TABLE transactions ADD COLUMN import_batch_id INTEGER REFERENCES import_batches(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_transactions_import_batch ON transactions(import_batch_id);
CREATE INDEX IF NOT EXISTS idx_transactions_counterparty ON transactions(counterparty);
@@ -0,0 +1,26 @@
ALTER TABLE categories ADD COLUMN keywords TEXT NOT NULL DEFAULT '';
-- Backfill keywords for default categories so the import classifier matches the legacy hard-coded rules.
UPDATE categories SET keywords = '工资' WHERE name = '工资薪酬' AND type = 'income';
UPDATE categories SET keywords = '奖金' WHERE name = '奖金福利' AND type = 'income';
UPDATE categories SET keywords = '利息,结息,理财' WHERE name = '银行理财' AND type = 'income';
UPDATE categories SET keywords = '股票,基金,分红' WHERE name = '股票基金' AND type = 'income';
UPDATE categories SET keywords = '房贷,按揭' WHERE name = '房贷' AND type = 'expense';
UPDATE categories SET keywords = '车贷' WHERE name = '车贷' AND type = 'expense';
UPDATE categories SET keywords = '水费,电费,燃气,煤气' WHERE name = '水电燃气' AND type = 'expense';
UPDATE categories SET keywords = '学费,培训' WHERE name = '学费' AND type = 'expense';
UPDATE categories SET keywords = '保费,保险' WHERE name = '保费' AND type = 'expense';
UPDATE categories SET keywords = '餐,面,饭,美团,饿了么' WHERE name = '餐饮' AND type = 'expense';
UPDATE categories SET keywords = '铁路,滴滴,骑行,出行,地铁,公交,加油' WHERE name = '交通' AND type = 'expense';
UPDATE categories SET keywords = '话费,流量,宽带' WHERE name = '通讯' AND type = 'expense';
UPDATE categories SET keywords = '超市,天猫,京东,日用品' WHERE name = '日用品' AND type = 'expense';
UPDATE categories SET keywords = '聚餐,礼物' WHERE name = '社交' AND type = 'expense';
UPDATE categories SET keywords = '医院,药店,诊所' WHERE name = '医疗' AND type = 'expense';
UPDATE categories SET keywords = '酒店,机票,旅游,景点' WHERE name = '旅行' AND type = 'expense';
UPDATE categories SET keywords = '健身,瑜伽,游泳' WHERE name = '健身' AND type = 'expense';
UPDATE categories SET keywords = '美容,美发,化妆品' WHERE name = '美容' AND type = 'expense';
UPDATE categories SET keywords = '电影,游戏,KTV' WHERE name = '娱乐' AND type = 'expense';
UPDATE categories SET keywords = '服装,鞋,帽' WHERE name = '服装' AND type = 'expense';
@@ -0,0 +1,46 @@
-- 引入 transfer 交易类型,支持账户间转账(不参与收入/支出统计)。
-- SQLite 不支持修改 CHECK 约束或列约束,需要重建 transactions 表。
-- 同时把 category_id 改为 NULLABLE:transfer 类型不归属任何分类。
CREATE TABLE transactions_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT NOT NULL CHECK (type IN ('income', 'expense', 'transfer')),
amount INTEGER NOT NULL CHECK (amount >= 0),
category_id INTEGER REFERENCES categories(id),
account_id INTEGER REFERENCES accounts(id) ON DELETE SET NULL,
to_account_id INTEGER REFERENCES accounts(id) ON DELETE SET NULL,
member_id INTEGER REFERENCES members(id) ON DELETE SET NULL,
date TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
counterparty TEXT NOT NULL DEFAULT '',
source_key TEXT NOT NULL DEFAULT '',
import_batch_id INTEGER REFERENCES import_batches(id) ON DELETE SET NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
INSERT INTO transactions_new (
id, type, amount, category_id, account_id, member_id,
date, description, counterparty, source_key, import_batch_id,
created_at, updated_at
)
SELECT
id, type, amount, category_id, account_id, member_id,
date, description, counterparty, source_key, import_batch_id,
created_at, updated_at
FROM transactions;
DROP TABLE transactions;
ALTER TABLE transactions_new RENAME TO transactions;
CREATE INDEX idx_transactions_date ON transactions(date);
CREATE INDEX idx_transactions_category ON transactions(category_id);
CREATE INDEX idx_transactions_type_date ON transactions(type, date);
CREATE INDEX idx_transactions_account ON transactions(account_id);
CREATE INDEX idx_transactions_to_account ON transactions(to_account_id);
CREATE INDEX idx_transactions_member ON transactions(member_id);
CREATE INDEX idx_transactions_import_batch ON transactions(import_batch_id);
CREATE INDEX idx_transactions_counterparty ON transactions(counterparty);
CREATE UNIQUE INDEX ux_transactions_source_key
ON transactions(source_key)
WHERE source_key <> '';
@@ -0,0 +1,5 @@
-- 资产可绑定到账户:当 account_id 不为 NULL 时,资产的 value 由该账户的 current_balance 实时派生。
-- 兼容旧数据:原有手工资产保持 account_id IS NULL,行为不变。
ALTER TABLE assets ADD COLUMN account_id INTEGER REFERENCES accounts(id) ON DELETE SET NULL;
CREATE INDEX IF NOT EXISTS idx_assets_account_id ON assets(account_id);
@@ -0,0 +1,2 @@
-- 每个账户最多绑定一条资产,避免净值重复计入。
CREATE UNIQUE INDEX IF NOT EXISTS idx_assets_account_id_unique ON assets(account_id) WHERE account_id IS NOT NULL;
@@ -0,0 +1,9 @@
ALTER TABLE policies ADD COLUMN payment_frequency TEXT NOT NULL DEFAULT 'annual';
ALTER TABLE policies ADD COLUMN next_payment_date TEXT NOT NULL DEFAULT '';
ALTER TABLE policies ADD COLUMN payment_term_end TEXT NOT NULL DEFAULT '';
-- 旧数据此前将 end_date 同时用于“到期”和“续费提醒”,迁移后保留兼容的首次提醒日期。
UPDATE policies SET next_payment_date = end_date
WHERE next_payment_date = '' AND end_date <> '' AND status = 'active';
CREATE INDEX IF NOT EXISTS idx_policies_next_payment_date ON policies(next_payment_date);
@@ -0,0 +1,24 @@
CREATE TABLE IF NOT EXISTS policy_payments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
policy_id INTEGER NOT NULL REFERENCES policies(id) ON DELETE CASCADE,
due_date TEXT NOT NULL,
amount INTEGER NOT NULL DEFAULT 0 CHECK (amount >= 0),
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','paid','skipped')),
paid_date TEXT NOT NULL DEFAULT '',
note TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_policy_payments_policy_due ON policy_payments(policy_id, due_date);
CREATE TABLE IF NOT EXISTS account_reconciliations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account_id INTEGER NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
system_balance INTEGER NOT NULL,
actual_balance INTEGER NOT NULL,
difference INTEGER NOT NULL,
transaction_id INTEGER REFERENCES transactions(id) ON DELETE SET NULL,
note TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_account_reconciliations_account ON account_reconciliations(account_id, created_at);
+144
View File
@@ -0,0 +1,144 @@
package db
import (
"database/sql"
"fmt"
)
func Seed(db *sql.DB) error {
if err := seedAccounts(db); err != nil {
return err
}
if err := seedCategories(db); err != nil {
return err
}
return nil
}
func seedAccounts(db *sql.DB) error {
var count int
if err := db.QueryRow("SELECT COUNT(*) FROM accounts").Scan(&count); err != nil {
return fmt.Errorf("check accounts: %w", err)
}
if count > 0 {
return nil
}
accounts := []struct {
name string
typ string
}{
{"支付宝", "alipay"},
{"微信", "wechat"},
{"储蓄卡", "debit_card"},
{"信用卡", "credit_card"},
{"现金", "cash"},
}
tx, err := db.Begin()
if err != nil {
return fmt.Errorf("begin seed accounts: %w", err)
}
defer tx.Rollback()
for _, a := range accounts {
if _, err := tx.Exec("INSERT INTO accounts (name, type) VALUES (?, ?)", a.name, a.typ); err != nil {
return fmt.Errorf("seed account %s: %w", a.name, err)
}
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit seed accounts: %w", err)
}
return nil
}
func seedCategories(db *sql.DB) error {
var count int
if err := db.QueryRow("SELECT COUNT(*) FROM categories").Scan(&count); err != nil {
return fmt.Errorf("check categories: %w", err)
}
if count > 0 {
return nil
}
tx, err := db.Begin()
if err != nil {
return fmt.Errorf("begin seed categories: %w", err)
}
defer tx.Rollback()
// Insert top-level categories first, capturing their IDs
top := []struct {
name string
typ string
order int
}{
{"固定收入", "income", 1},
{"不固定收入", "income", 2},
{"固定支出", "expense", 1},
{"不固定必须支出", "expense", 2},
{"可有可无", "expense", 3},
}
parentIDs := make(map[string]int64)
for _, t := range top {
result, err := tx.Exec(
"INSERT INTO categories (name, type, sort_order) VALUES (?, ?, ?)",
t.name, t.typ, t.order,
)
if err != nil {
return fmt.Errorf("seed category %s: %w", t.name, err)
}
id, _ := result.LastInsertId()
parentIDs[t.name] = id
}
children := []struct {
name string
typ string
parent string
order int
keywords string
}{
// Income children
{"工资薪酬", "income", "固定收入", 1, "工资"},
{"奖金福利", "income", "固定收入", 2, "奖金"},
{"银行理财", "income", "不固定收入", 1, "利息,结息,理财"},
{"股票基金", "income", "不固定收入", 2, "股票,基金,分红"},
{"其他", "income", "不固定收入", 3, ""},
// Expense children - 固定支出
{"房贷", "expense", "固定支出", 1, "房贷,按揭"},
{"车贷", "expense", "固定支出", 2, "车贷"},
{"水电燃气", "expense", "固定支出", 3, "水费,电费,燃气,煤气"},
{"学费", "expense", "固定支出", 4, "学费,培训"},
{"保费", "expense", "固定支出", 5, "保费,保险"},
// Expense children - 不固定必须支出
{"餐饮", "expense", "不固定必须支出", 1, "餐,面,饭,美团,饿了么"},
{"交通", "expense", "不固定必须支出", 2, "铁路,滴滴,骑行,出行,地铁,公交,加油"},
{"通讯", "expense", "不固定必须支出", 3, "话费,流量,宽带"},
{"日用品", "expense", "不固定必须支出", 4, "超市,天猫,京东,日用品"},
{"社交", "expense", "不固定必须支出", 5, "聚餐,礼物"},
{"医疗", "expense", "不固定必须支出", 6, "医院,药店,诊所"},
// Expense children - 可有可无
{"旅行", "expense", "可有可无", 1, "酒店,机票,旅游,景点"},
{"健身", "expense", "可有可无", 2, "健身,瑜伽,游泳"},
{"美容", "expense", "可有可无", 3, "美容,美发,化妆品"},
{"娱乐", "expense", "可有可无", 4, "电影,游戏,KTV"},
{"服装", "expense", "可有可无", 5, "服装,鞋,帽"},
}
for _, c := range children {
pid := parentIDs[c.parent]
if _, err := tx.Exec(
"INSERT INTO categories (name, type, parent_id, sort_order, keywords) VALUES (?, ?, ?, ?, ?)",
c.name, c.typ, pid, c.order, c.keywords,
); err != nil {
return fmt.Errorf("seed category %s: %w", c.name, err)
}
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit seed categories: %w", err)
}
return nil
}
+37
View File
@@ -0,0 +1,37 @@
package db
import (
"database/sql"
"fmt"
"os"
"path/filepath"
_ "modernc.org/sqlite"
)
const sqlitePoolSize = 4
func Open(dbPath string) (*sql.DB, error) {
dir := filepath.Dir(dbPath)
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, fmt.Errorf("create db directory: %w", err)
}
dsn := dbPath + "?_pragma=journal_mode(WAL)&_pragma=foreign_keys(ON)&_pragma=busy_timeout(5000)"
conn, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, fmt.Errorf("open database: %w", err)
}
conn.SetMaxOpenConns(sqlitePoolSize)
conn.SetMaxIdleConns(sqlitePoolSize)
conn.SetConnMaxLifetime(0)
conn.SetConnMaxIdleTime(0)
if err := conn.Ping(); err != nil {
conn.Close()
return nil, fmt.Errorf("ping database: %w", err)
}
return conn, nil
}
+140
View File
@@ -0,0 +1,140 @@
package db
import (
"context"
"errors"
"path/filepath"
"sync"
"testing"
)
func TestOpenConfiguresBoundedWALPool(t *testing.T) {
conn, err := Open(filepath.Join(t.TempDir(), "book.db"))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if got := conn.Stats().MaxOpenConnections; got != 4 {
t.Fatalf("MaxOpenConnections=%d, want 4", got)
}
}
func TestOpenAppliesPragmasToEveryPooledConnection(t *testing.T) {
conn, err := Open(filepath.Join(t.TempDir(), "book.db"))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
for range sqlitePoolSize {
pooled, err := conn.Conn(context.Background())
if err != nil {
t.Fatal(err)
}
// 故意延迟到测试结束再释放,确保同时占满 4 个不同连接。
defer pooled.Close()
var journalMode string
var foreignKeys, busyTimeout int
if err := pooled.QueryRowContext(context.Background(), "PRAGMA journal_mode").Scan(&journalMode); err != nil {
t.Fatal(err)
}
if err := pooled.QueryRowContext(context.Background(), "PRAGMA foreign_keys").Scan(&foreignKeys); err != nil {
t.Fatal(err)
}
if err := pooled.QueryRowContext(context.Background(), "PRAGMA busy_timeout").Scan(&busyTimeout); err != nil {
t.Fatal(err)
}
if journalMode != "wal" || foreignKeys != 1 || busyTimeout != 5000 {
t.Fatalf("pragmas=(%s,%d,%d), want (wal,1,5000)", journalMode, foreignKeys, busyTimeout)
}
}
}
func TestOpenAllowsWriteDuringReadTransaction(t *testing.T) {
conn, err := Open(filepath.Join(t.TempDir(), "book.db"))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if _, err := conn.Exec("CREATE TABLE sample(id INTEGER PRIMARY KEY)"); err != nil {
t.Fatal(err)
}
readTx, err := conn.BeginTx(context.Background(), nil)
if err != nil {
t.Fatal(err)
}
defer readTx.Rollback()
var count int
if err := readTx.QueryRow("SELECT COUNT(*) FROM sample").Scan(&count); err != nil {
t.Fatal(err)
}
if _, err := conn.Exec("INSERT INTO sample(id) VALUES (1)"); err != nil {
t.Fatalf("write while read transaction is open: %v", err)
}
}
func TestRunMigrationsWithForeignKeysEnabled(t *testing.T) {
conn, err := Open(filepath.Join(t.TempDir(), "book.db"))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if err := RunMigrations(conn); err != nil {
t.Fatalf("run migrations: %v", err)
}
rows, err := conn.Query("PRAGMA foreign_key_check")
if err != nil {
t.Fatal(err)
}
defer rows.Close()
if rows.Next() {
t.Fatal("freshly migrated database contains foreign key violations")
}
if err := rows.Err(); err != nil {
t.Fatal(err)
}
}
func TestOpenAllowsConcurrentReads(t *testing.T) {
conn, err := Open(filepath.Join(t.TempDir(), "book.db"))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if _, err := conn.Exec(`CREATE TABLE sample(id INTEGER PRIMARY KEY); INSERT INTO sample(id) VALUES (1)`); err != nil {
t.Fatal(err)
}
const workers = 8
const readsPerWorker = 20
errs := make(chan error, workers)
var wg sync.WaitGroup
for range workers {
wg.Add(1)
go func() {
defer wg.Done()
for range readsPerWorker {
var count int
if err := conn.QueryRowContext(context.Background(), "SELECT COUNT(*) FROM sample").Scan(&count); err != nil {
errs <- err
return
}
if count != 1 {
errs <- errors.New("unexpected sample count")
return
}
}
}()
}
wg.Wait()
close(errs)
for err := range errs {
t.Fatal(err)
}
}