yj
2026-03-31 4becf7b5eba5de2d9889f379eb88aeb6cb16f760
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import pymysql
import logging
 
# 设置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
 
 
class ContentTypeDAO:
    """ContentType数据访问对象"""
 
    @staticmethod
    def save_contenttype(data, db_config):
        """保存ContentType,支持通过ID更新或创建新记录"""
        # 在批量操作中,我们使用已有的连接,不需要获取新连接
        connection = db_config.get_connection()
        if not connection:
            logger.error("数据库连接失败")
            return None, "数据库连接失败"
 
        try:
            with connection.cursor() as cursor:
                contenttype = data.get("id")
                code = data.get("code", "").strip()
                name = data.get("name", "").strip()
 
                if not code or not name:
                    return None, "代码和名称是必需的"
 
                if contenttype:
                    # 如果提供了ID,则更新现有记录
                    # 检查记录是否存在
                    check_sql = "SELECT id FROM content_type WHERE id = %s"
                    cursor.execute(check_sql, (contenttype,))
                    existing_record = cursor.fetchone()
 
                    if existing_record:
                        # 更新记录
                        update_sql = (
                            "UPDATE content_type SET code = %s, name = %s WHERE id = %s"
                        )
                        cursor.execute(update_sql, (code, name, contenttype))
                        record_id = contenttype
                        message = "ContentType更新成功"
                    else:
                        # 如果ID不存在,则返回错误
                        return None, "指定的ID不存在"
                else:
                    # 检查代码是否已存在(当没有提供ID时)
                    check_sql = "SELECT id FROM content_type WHERE code = %s"
                    cursor.execute(check_sql, (code,))
                    existing_record = cursor.fetchone()
 
                    if existing_record:
                        # 更新现有记录
                        update_sql = "UPDATE content_type SET name = %s WHERE code = %s"
                        cursor.execute(update_sql, (name, code))
                        record_id = existing_record["id"]
                        message = "ContentType更新成功"
                    else:
                        # 插入新记录
                        insert_sql = (
                            "INSERT INTO content_type (code, name) VALUES (%s, %s)"
                        )
                        cursor.execute(insert_sql, (code, name))
                        record_id = cursor.lastrowid
                        message = "ContentType保存成功"
 
                logger.info(
                    f"ContentType {'已更新' if contenttype or existing_record else '已保存'},ID: {record_id},代码: {code}"
                )
 
                return {
                    "message": message,
                    "id": record_id,
                    "code": code,
                    "name": name,
                }, None
 
        except pymysql.IntegrityError as e:
            logger.error(f"保存ContentType时数据完整性错误: {e}")
            return None, "代码已存在"
        except Exception as e:
            logger.error(f"保存ContentType操作时出错: {e}")
            return None, "内部服务器错误"
 
    @staticmethod
    def get_contenttype(contenttype=None, code=None, limit=None, db_config=None):
        """获取ContentType"""
        connection = db_config.get_connection()
        if not connection:
            logger.error("数据库连接失败")
            return None, "数据库连接失败"
 
        try:
            with connection.cursor() as cursor:
                if contenttype:
                    # 按ID获取特定记录
                    sql = "SELECT id, code, name, created_at, updated_at FROM content_type WHERE id = %s"
                    cursor.execute(sql, (int(contenttype),))
                elif code:
                    # 按代码获取记录
                    sql = "SELECT id, code, name, created_at, updated_at FROM content_type WHERE code = %s"
                    cursor.execute(sql, (code,))
                else:
                    # 获取所有记录
                    sql = "SELECT id, code, name, created_at, updated_at FROM content_type ORDER BY created_at DESC"
                    if limit:
                        sql += f" LIMIT {limit}"
                    cursor.execute(sql)
 
                results = cursor.fetchall()
 
                logger.info(f"检索到 {len(results)} 条ContentType记录")
 
                return {"data": results, "count": len(results)}, None
 
        except Exception as e:
            logger.error(f"检索ContentType操作时出错: {e}")
            return None, "内部服务器错误"
 
 
class ContentDAO:
    """Content数据访问对象"""
 
    @staticmethod
    def save_content(data, db_config):
        """保存Content,支持通过ID更新或创建新记录"""
        # 在批量操作中,我们使用已有的连接,不需要获取新连接
        connection = db_config.get_connection()
        if not connection:
            logger.error("数据库连接失败")
            return None, "数据库连接失败"
 
        try:
            with connection.cursor() as cursor:
                content_id = data.get("id")
                content_type = data.get("type", None)
                question = data.get("question", "").strip()
                answer = data.get("answer", "").strip()
 
                if content_type is None or not question or not answer:
                    return None, "类型、问题和答案是必需的"
 
                # 验证类型ID是否存在
                check_type_sql = "SELECT id FROM content_type WHERE id = %s"
                cursor.execute(check_type_sql, (content_type,))
                type_exists = cursor.fetchone()
 
                if not type_exists:
                    return None, "指定的类型ID不存在"
 
                if content_id:
                    # 如果提供了ID,则更新现有记录
                    # 检查记录是否存在
                    check_sql = "SELECT id FROM content WHERE id = %s"
                    cursor.execute(check_sql, (content_id,))
                    existing_record = cursor.fetchone()
 
                    if existing_record:
                        # 更新记录
                        update_sql = "UPDATE content SET type = %s, question = %s, answer = %s WHERE id = %s"
                        cursor.execute(
                            update_sql, (content_type, question, answer, content_id)
                        )
                        record_id = content_id
                        message = "Content更新成功"
                    else:
                        # 如果ID不存在,则返回错误
                        return None, "指定的ID不存在"
                else:
                    # 插入新记录
                    insert_sql = "INSERT INTO content (type, question, answer) VALUES (%s, %s, %s)"
                    cursor.execute(insert_sql, (content_type, question, answer))
                    record_id = cursor.lastrowid
                    message = "Content保存成功"
 
                logger.info(
                    f"Content {'已更新' if content_id else '已保存'},ID: {record_id},类型ID: {content_type}"
                )
 
                return {
                    "message": message,
                    "id": record_id,
                    "type": content_type,
                    "question": question,
                    "answer": answer,
                }, None
 
        except Exception as e:
            logger.error(f"保存Content操作时出错: {e}")
            return None, "内部服务器错误"
 
    @staticmethod
    def get_content(content_id=None, content_type=None, limit=None, db_config=None):
        """获取Content"""
        connection = db_config.get_connection()
        if not connection:
            logger.error("数据库连接失败")
            return None, "数据库连接失败"
 
        try:
            with connection.cursor() as cursor:
                if content_id:
                    # 按ID获取特定记录
                    sql = """
                    SELECT c.id, c.type, ct.code, ct.name, c.question, c.answer, c.created_at, c.updated_at
                    FROM content c
                    LEFT JOIN content_type ct ON c.type = ct.id
                    WHERE c.id = %s
                    """
                    cursor.execute(sql, (content_id,))
                elif content_type:
                    # 按类型获取记录
                    sql = """
                    SELECT c.id, c.type, ct.code, ct.name, c.question, c.answer, c.created_at, c.updated_at
                    FROM content c
                    LEFT JOIN content_type ct ON c.type = ct.id
                    WHERE c.type = %s
                    ORDER BY c.created_at
                    """
                    if limit:
                        sql += f" LIMIT {limit}"
                    cursor.execute(sql, (content_type,))
                else:
                    # 获取所有记录
                    sql = """
                    SELECT c.id, c.type, ct.code, ct.name, c.question, c.answer, c.created_at, c.updated_at
                    FROM content c
                    LEFT JOIN content_type ct ON c.type = ct.id
                    ORDER BY c.created_at
                    """
                    if limit:
                        sql += f" LIMIT {limit}"
                    cursor.execute(sql)
 
                results = cursor.fetchall()
 
                logger.info(f"检索到 {len(results)} 条Content记录")
 
                return {"data": results, "count": len(results)}, None
 
        except Exception as e:
            logger.error(f"检索Content操作时出错: {e}")
            return None, "内部服务器错误"
        finally:
            connection.close()
 
    @staticmethod
    def delete_content(content_id, db_config):
        """根据ID删除Content"""
        connection = db_config.get_connection()
        if not connection:
            logger.error("数据库连接失败")
            return None, "数据库连接失败"
 
        try:
            with connection.cursor() as cursor:
                # 检查记录是否存在
                check_sql = "SELECT id FROM content WHERE id = %s"
                cursor.execute(check_sql, (content_id,))
                existing_record = cursor.fetchone()
 
                if not existing_record:
                    return None, "指定的ID不存在"
 
                # 删除记录
                delete_sql = "DELETE FROM content WHERE id = %s"
                cursor.execute(delete_sql, (content_id,))
 
                if cursor.rowcount > 0:
                    connection.commit()
                    logger.info(f"Content已删除,ID: {content_id}")
                    return {"message": "Content删除成功", "id": content_id}, None
                else:
                    connection.rollback()
                    return None, "删除操作失败"
 
        except Exception as e:
            logger.error(f"删除Content操作时出错: {e}")
            try:
                connection.rollback()
            except Exception as rollback_error:
                logger.error(f"回滚操作时出错: {rollback_error}")
            return None, "内部服务器错误"
        finally:
            connection.close()