小程序后端补充数据库兼容层与启动适配

This commit is contained in:
stu2not
2026-04-16 18:19:28 +08:00
parent 2526365af1
commit 9d7c1ce7b4
4 changed files with 110 additions and 50 deletions

View File

@@ -5,9 +5,21 @@ from typing import Optional
from sqlalchemy import text
from app.dao import BaseDAO
from app.db_compat import inserted_primary_key
class ChildDAO(BaseDAO):
def _create_relation(self, user_id: int, child_id: int) -> None:
self.db.execute(
text(
"""
INSERT INTO parent_child_relations (user_id, child_id, relation_type, is_primary, status)
VALUES (:user_id, :child_id, 9, 0, 1)
"""
),
{"user_id": user_id, "child_id": child_id},
)
def create(
self,
user_id: int,
@@ -18,13 +30,14 @@ class ChildDAO(BaseDAO):
result = self.db.execute(
text(
"""
INSERT INTO children (parent_user_id, child_name, child_gender, child_birthday, status)
VALUES (:user_id, :child_name, :child_gender, :child_birthday, 1)
INSERT INTO children (child_name, child_gender, child_birthday, status)
VALUES (:child_name, :child_gender, :child_birthday, 1)
"""
),
{"user_id": user_id, "child_name": child_name, "child_gender": child_gender, "child_birthday": child_birthday},
{"child_name": child_name, "child_gender": child_gender, "child_birthday": child_birthday},
)
child_id = int(result.lastrowid)
child_id = inserted_primary_key(result)
self._create_relation(user_id, child_id)
self.commit()
return child_id
@@ -40,18 +53,21 @@ class ChildDAO(BaseDAO):
def list_by_parent(self, user_id: int, limit: int = 20, cursor: int = None) -> list[Mapping]:
params = {"user_id": user_id, "limit": limit + 1}
where = "parent_user_id = :user_id AND status = 1"
if cursor:
where += " AND child_id < :cursor"
where = "pcr.user_id = :user_id AND pcr.status = 1 AND c.status = 1"
if cursor is not None:
where += " AND c.child_id < :cursor"
params["cursor"] = cursor
rows = (
self.db.execute(
text(
f"""
SELECT * FROM children
SELECT c.*
FROM children AS c
JOIN parent_child_relations AS pcr
ON pcr.child_id = c.child_id
WHERE {where}
ORDER BY child_id DESC
ORDER BY c.child_id DESC
LIMIT :limit
"""
),
@@ -87,9 +103,18 @@ class ChildDAO(BaseDAO):
return (
self.db.execute(
text(
"SELECT 1 FROM children WHERE child_id = :child_id AND parent_user_id = :user_id AND status = 1"
"""
SELECT 1
FROM children AS c
JOIN parent_child_relations AS pcr
ON pcr.child_id = c.child_id
WHERE c.child_id = :child_id
AND pcr.user_id = :user_id
AND c.status = 1
AND pcr.status = 1
"""
),
{"child_id": child_id, "user_id": user_id},
).scalar_one_or_none()
is not None
)
)