about summary refs log tree commit diff
path: root/src/db_handler.py
blob: 471154aaeeca383e5824cb2959fd45921789e769 (plain)
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
import logging
from dataclasses import dataclass

import sqlite3


logger = logging.getLogger(__name__) # Set the logger name, to the name of the module


class DBHandler:
    def con_factory(self) -> sqlite3.Connection:
        con = sqlite3.connect("blog.node5.net.db")
        return con

    def get_comments(self, url: str) -> list[dict]:
        with self.con_factory() as con:
            cur = con.cursor()
            comments_sql = '''
SELECT id, nickname, comment, page_url, visitor_url, (CASE WHEN show_contact THEN contact ELSE NULL END) as contact_info, created_at
FROM comment WHERE approved AND public AND page_url = ? ORDER BY created_at DESC;
'''
            cur.execute(comments_sql, (url,))
            comments = cur.fetchall()
            headers = list(map(lambda attr : attr[0], cur.description))
            comments_sql = comments_sql.replace('?', f"'{url}'")
            return comments, headers, comments_sql


    def post_comment(self, comment: str, page_url: str, visitor_url: str=None, nickname: str=None, contact: str=None,
                     show_contact: bool=True, public: bool=True):
        with self.con_factory() as con:
            cur = con.cursor()
            cur.execute(
                '''
                INSERT INTO comment (comment, page_url, visitor_url, nickname, contact, show_contact, public)
                VALUES (?, ?, ?, ?, ?, ?, ?);
                ''',
                (comment, page_url, visitor_url, nickname, contact, show_contact, public)
            )