47 lines
2.2 KiB
SQL
47 lines
2.2 KiB
SQL
-- 引入 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 <> '';
|