fix: enforce account data boundaries and real-data integrity
This commit is contained in:
+181
-28
@@ -219,24 +219,43 @@ class ReviewDatabase:
|
||||
|
||||
CREATE TABLE IF NOT EXISTS screener_strategies (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
regimes TEXT NOT NULL,
|
||||
formula TEXT NOT NULL,
|
||||
builtin INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
updated_at TEXT NOT NULL,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS screener_runs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER,
|
||||
trade_date TEXT NOT NULL,
|
||||
regime TEXT NOT NULL,
|
||||
strategy_name TEXT NOT NULL,
|
||||
formula TEXT NOT NULL,
|
||||
result TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
created_at TEXT NOT NULL,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS mentor_messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
mentor_id TEXT NOT NULL,
|
||||
trade_date TEXT NOT NULL,
|
||||
role TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
meta TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_mentor_messages_conversation
|
||||
ON mentor_messages(user_id, mentor_id, trade_date, id DESC);
|
||||
"""
|
||||
)
|
||||
user_columns = {
|
||||
@@ -309,6 +328,38 @@ class ReviewDatabase:
|
||||
ON review_notes(user_id, trade_date DESC, id DESC)
|
||||
"""
|
||||
)
|
||||
strategy_columns = {
|
||||
str(row["name"]) for row in connection.execute("PRAGMA table_info(screener_strategies)")
|
||||
}
|
||||
if "user_id" not in strategy_columns:
|
||||
connection.execute("ALTER TABLE screener_strategies ADD COLUMN user_id INTEGER")
|
||||
run_columns = {
|
||||
str(row["name"]) for row in connection.execute("PRAGMA table_info(screener_runs)")
|
||||
}
|
||||
if "user_id" not in run_columns:
|
||||
connection.execute("ALTER TABLE screener_runs ADD COLUMN user_id INTEGER")
|
||||
if first_user and first_user["id"]:
|
||||
first_user_id = int(first_user["id"])
|
||||
connection.execute(
|
||||
"UPDATE screener_strategies SET user_id = ? WHERE builtin = 0 AND user_id IS NULL",
|
||||
(first_user_id,),
|
||||
)
|
||||
connection.execute(
|
||||
"UPDATE screener_runs SET user_id = ? WHERE user_id IS NULL",
|
||||
(first_user_id,),
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_screener_strategies_user
|
||||
ON screener_strategies(user_id, builtin, updated_at DESC)
|
||||
"""
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_screener_runs_user_date
|
||||
ON screener_runs(user_id, trade_date DESC, id DESC)
|
||||
"""
|
||||
)
|
||||
|
||||
def count_users(self) -> int:
|
||||
with self.connect() as connection:
|
||||
@@ -658,6 +709,33 @@ class ReviewDatabase:
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
|
||||
def get_latest_data_snapshot(
|
||||
self,
|
||||
kind: str,
|
||||
cache_key_prefix: str,
|
||||
maximum_cache_key: str,
|
||||
exclude_source: str = "",
|
||||
) -> dict[str, Any] | None:
|
||||
source_clause = " AND source != ?" if exclude_source else ""
|
||||
parameters: list[Any] = [kind, f"{cache_key_prefix}%", maximum_cache_key]
|
||||
if exclude_source:
|
||||
parameters.append(exclude_source)
|
||||
with self.connect() as connection:
|
||||
row = connection.execute(
|
||||
f"""
|
||||
SELECT payload FROM data_snapshots
|
||||
WHERE kind = ? AND cache_key LIKE ? AND cache_key <= ?{source_clause}
|
||||
ORDER BY cache_key DESC LIMIT 1
|
||||
""",
|
||||
parameters,
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
try:
|
||||
return json.loads(row["payload"])
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
|
||||
def save_data_snapshot(
|
||||
self, kind: str, cache_key: str, source: str, payload: dict[str, Any]
|
||||
) -> None:
|
||||
@@ -1073,7 +1151,7 @@ class ReviewDatabase:
|
||||
return result
|
||||
|
||||
def save_screener_strategy(
|
||||
self, name: str, description: str, regimes: list[str], formula: dict[str, Any],
|
||||
self, user_id: int | None, name: str, description: str, regimes: list[str], formula: dict[str, Any],
|
||||
builtin: bool = False, strategy_id: int | None = None,
|
||||
) -> int:
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
@@ -1081,31 +1159,50 @@ class ReviewDatabase:
|
||||
formula_json = json.dumps(formula, ensure_ascii=False, separators=(",", ":"))
|
||||
with self.connect() as connection:
|
||||
if strategy_id:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
UPDATE screener_strategies SET name=?, description=?, regimes=?, formula=?,
|
||||
builtin=?, updated_at=? WHERE id=?
|
||||
""",
|
||||
(name, description, regimes_json, formula_json, int(builtin), now, strategy_id),
|
||||
)
|
||||
if builtin:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
UPDATE screener_strategies SET name=?, description=?, regimes=?, formula=?,
|
||||
builtin=1, user_id=NULL, updated_at=? WHERE id=? AND builtin=1
|
||||
""",
|
||||
(name, description, regimes_json, formula_json, now, strategy_id),
|
||||
)
|
||||
else:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
UPDATE screener_strategies SET name=?, description=?, regimes=?, formula=?,
|
||||
updated_at=? WHERE id=? AND builtin=0 AND user_id=?
|
||||
""",
|
||||
(name, description, regimes_json, formula_json, now, strategy_id, int(user_id or 0)),
|
||||
)
|
||||
if cursor.rowcount == 0:
|
||||
raise ValueError("选股策略不存在。")
|
||||
return strategy_id
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO screener_strategies
|
||||
(name, description, regimes, formula, builtin, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
(user_id, name, description, regimes, formula, builtin, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(name, description, regimes_json, formula_json, int(builtin), now, now),
|
||||
(None if builtin else int(user_id or 0), name, description, regimes_json, formula_json, int(builtin), now, now),
|
||||
)
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
def list_screener_strategies(self) -> list[dict[str, Any]]:
|
||||
def list_screener_strategies(self, user_id: int | None = None) -> list[dict[str, Any]]:
|
||||
with self.connect() as connection:
|
||||
rows = connection.execute(
|
||||
"SELECT * FROM screener_strategies ORDER BY builtin DESC, updated_at DESC, id"
|
||||
).fetchall()
|
||||
if user_id is None:
|
||||
rows = connection.execute(
|
||||
"SELECT * FROM screener_strategies WHERE builtin = 1 ORDER BY updated_at DESC, id"
|
||||
).fetchall()
|
||||
else:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT * FROM screener_strategies
|
||||
WHERE builtin = 1 OR user_id = ?
|
||||
ORDER BY builtin DESC, updated_at DESC, id
|
||||
""",
|
||||
(int(user_id),),
|
||||
).fetchall()
|
||||
result = []
|
||||
for row in rows:
|
||||
item = dict(row)
|
||||
@@ -1115,24 +1212,26 @@ class ReviewDatabase:
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
def delete_screener_strategy(self, strategy_id: int) -> bool:
|
||||
def delete_screener_strategy(self, user_id: int, strategy_id: int) -> bool:
|
||||
with self.connect() as connection:
|
||||
row = connection.execute(
|
||||
"SELECT builtin FROM screener_strategies WHERE id = ?",
|
||||
"SELECT builtin, user_id FROM screener_strategies WHERE id = ?",
|
||||
(strategy_id,),
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise ValueError("选股策略不存在。")
|
||||
if bool(row["builtin"]):
|
||||
raise ValueError("内置策略不能删除。")
|
||||
if int(row["user_id"] or 0) != int(user_id):
|
||||
raise ValueError("无权删除其他账号的策略。")
|
||||
cursor = connection.execute(
|
||||
"DELETE FROM screener_strategies WHERE id = ? AND builtin = 0",
|
||||
(strategy_id,),
|
||||
"DELETE FROM screener_strategies WHERE id = ? AND builtin = 0 AND user_id = ?",
|
||||
(strategy_id, int(user_id)),
|
||||
)
|
||||
return cursor.rowcount > 0
|
||||
|
||||
def save_screener_run(
|
||||
self, trade_date: str, regime: str, strategy_name: str,
|
||||
self, user_id: int, trade_date: str, regime: str, strategy_name: str,
|
||||
formula: dict[str, Any], result: dict[str, Any],
|
||||
) -> int:
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
@@ -1140,23 +1239,23 @@ class ReviewDatabase:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO screener_runs
|
||||
(trade_date, regime, strategy_name, formula, result, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
(user_id, trade_date, regime, strategy_name, formula, result, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(trade_date, regime, strategy_name,
|
||||
(int(user_id), trade_date, regime, strategy_name,
|
||||
json.dumps(formula, ensure_ascii=False, separators=(",", ":")),
|
||||
json.dumps(result, ensure_ascii=False, separators=(",", ":")), now),
|
||||
)
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
def latest_screener_run(self, trade_date: str) -> dict[str, Any] | None:
|
||||
def latest_screener_run(self, user_id: int, trade_date: str) -> dict[str, Any] | None:
|
||||
with self.connect() as connection:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT id, trade_date, regime, strategy_name, result, created_at
|
||||
FROM screener_runs WHERE trade_date <= ? ORDER BY id DESC LIMIT 1
|
||||
FROM screener_runs WHERE user_id = ? AND trade_date <= ? ORDER BY id DESC LIMIT 1
|
||||
""",
|
||||
(trade_date,),
|
||||
(int(user_id), trade_date),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
@@ -1168,6 +1267,60 @@ class ReviewDatabase:
|
||||
result["meta"]["created_at"] = row["created_at"]
|
||||
return result
|
||||
|
||||
def save_mentor_exchange(
|
||||
self,
|
||||
user_id: int,
|
||||
mentor_id: str,
|
||||
trade_date: str,
|
||||
question: str,
|
||||
answer: str,
|
||||
meta: str = "",
|
||||
) -> None:
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self.connect() as connection:
|
||||
connection.executemany(
|
||||
"""
|
||||
INSERT INTO mentor_messages
|
||||
(user_id, mentor_id, trade_date, role, content, meta, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
[
|
||||
(int(user_id), mentor_id, trade_date, "user", question, "", now),
|
||||
(int(user_id), mentor_id, trade_date, "assistant", answer, meta, now),
|
||||
],
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
DELETE FROM mentor_messages
|
||||
WHERE user_id = ? AND id NOT IN (
|
||||
SELECT id FROM mentor_messages WHERE user_id = ? ORDER BY id DESC LIMIT 500
|
||||
)
|
||||
""",
|
||||
(int(user_id), int(user_id)),
|
||||
)
|
||||
|
||||
def list_mentor_messages(
|
||||
self, user_id: int, mentor_id: str, trade_date: str, limit: int = 100
|
||||
) -> list[dict[str, Any]]:
|
||||
with self.connect() as connection:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT role, content, meta, created_at FROM mentor_messages
|
||||
WHERE user_id = ? AND mentor_id = ? AND trade_date = ?
|
||||
ORDER BY id DESC LIMIT ?
|
||||
""",
|
||||
(int(user_id), mentor_id, trade_date, max(1, min(500, int(limit)))),
|
||||
).fetchall()
|
||||
return [dict(row) for row in reversed(rows)]
|
||||
|
||||
def delete_mentor_messages(self, user_id: int, mentor_id: str, trade_date: str) -> int:
|
||||
with self.connect() as connection:
|
||||
cursor = connection.execute(
|
||||
"DELETE FROM mentor_messages WHERE user_id = ? AND mentor_id = ? AND trade_date = ?",
|
||||
(int(user_id), mentor_id, trade_date),
|
||||
)
|
||||
return int(cursor.rowcount)
|
||||
|
||||
def start_sync(self, trade_date: str, source: str) -> int:
|
||||
started_at = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self.connect() as connection:
|
||||
|
||||
Reference in New Issue
Block a user