From 4557b166bb350464d4d132eb0d46ea91fc19755a Mon Sep 17 00:00:00 2001 From: mst Date: Mon, 16 Dec 2024 16:48:31 +0300 Subject: [PATCH] getAllQuestions function --- functions.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/functions.py b/functions.py index 225d0a1..6844a94 100644 --- a/functions.py +++ b/functions.py @@ -129,6 +129,47 @@ def getQuestion(question_id: int): conn.close() return question +def getAllQuestions(): + conn = connectToDb() + cursor = conn.cursor(dictionary=True) + + app.logger.debug("[CatAsk/functions/getAllQuestions] SELECT'ing all questions with latest answers") + + query = """ + SELECT q.*, a.creation_date AS latest_answer_date + FROM questions q + LEFT JOIN ( + SELECT question_id, MAX(creation_date) AS creation_date + FROM answers + GROUP BY question_id + ) a ON q.id = a.question_id + WHERE q.answered = %s + ORDER BY (a.creation_date IS NULL), a.creation_date DESC, q.pinned DESC, q.creation_date DESC + """ + + cursor.execute(query, (True,)) + questions = cursor.fetchall() + + app.logger.debug("[CatAsk/functions/getAllQuestions] SELECT'ing answers") + + cursor.execute("SELECT * FROM answers ORDER BY creation_date DESC") + answers = cursor.fetchall() + + metadata = generateMetadata() + + combined = [] + for question in questions: + question_answers = [answer for answer in answers if answer['question_id'] == question['id']] + combined.append({ + 'question': question, + 'answers': question_answers + }) + + cursor.close() + conn.close() + + return combined, metadata + def addQuestion(from_who, question, cw, noAntispam=False): if cfg['antispam']['type'] == 'basic':