mirror of
https://github.com/Xevion/tcp-chat.git
synced 2025-12-06 15:16:43 -06:00
improve message recording, use try/finally cur cursor closing, on-demand cursor creation
This commit is contained in:
28
server/db.py
28
server/db.py
@@ -1,6 +1,6 @@
|
|||||||
|
import logging
|
||||||
import sqlite3
|
import sqlite3
|
||||||
from typing import List
|
from typing import List
|
||||||
import logging
|
|
||||||
|
|
||||||
import constants
|
import constants
|
||||||
|
|
||||||
@@ -10,7 +10,6 @@ conn = sqlite3.connect(constants.DATABASE)
|
|||||||
logger.debug(f"Connected to '{constants.DATABASE}'")
|
logger.debug(f"Connected to '{constants.DATABASE}'")
|
||||||
|
|
||||||
logger.debug("Constructing 'message' table.")
|
logger.debug("Constructing 'message' table.")
|
||||||
cur = conn.cursor()
|
|
||||||
conn.execute('''CREATE TABLE IF NOT EXISTS message
|
conn.execute('''CREATE TABLE IF NOT EXISTS message
|
||||||
(id INTEGER PRIMARY KEY,
|
(id INTEGER PRIMARY KEY,
|
||||||
nickname TEXT NOT NULL,
|
nickname TEXT NOT NULL,
|
||||||
@@ -21,14 +20,33 @@ conn.execute('''CREATE TABLE IF NOT EXISTS message
|
|||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
def add_message(nickname: str, hash: str, color: str, message: str, timestamp: int):
|
def add_message(nickname: str, user_hash: str, color: str, message: str, timestamp: int) -> int:
|
||||||
|
"""
|
||||||
|
Insert a message into the database. Returns the message ID.
|
||||||
|
|
||||||
|
:param nickname: A non-unique identifier for the user.
|
||||||
|
:param user_hash: A unique hash (usually) denoting the sender's identity.
|
||||||
|
:param color: The color of the user who sent the message.
|
||||||
|
:param message: The string content of the message echoed to all clients.
|
||||||
|
:param timestamp: The epoch time of the sent message.
|
||||||
|
:return: The unique integer primary key chosen for the message, i.e. it's ID.
|
||||||
|
"""
|
||||||
|
cur = conn.cursor()
|
||||||
|
try:
|
||||||
cur.execute('''INSERT INTO message (nickname, connection_hash, color, message, timestamp)
|
cur.execute('''INSERT INTO message (nickname, connection_hash, color, message, timestamp)
|
||||||
VALUES (?, ?, ?, ?, ?)''', [nickname, hash, color, message, timestamp])
|
VALUES (?, ?, ?, ?, ?)''', [nickname, user_hash, color, message, timestamp])
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
logger.debug(f'Message {cur.lastrowid} recorded.')
|
||||||
|
return cur.lastrowid
|
||||||
|
finally:
|
||||||
|
cur.close()
|
||||||
|
|
||||||
|
|
||||||
def get_messages(columns: List[str] = None):
|
def get_messages(columns: List[str] = None):
|
||||||
|
cur = conn.cursor()
|
||||||
|
try:
|
||||||
if columns is None:
|
if columns is None:
|
||||||
cur.execute('''SELECT * FROM message''')
|
cur.execute('''SELECT * FROM message''')
|
||||||
return cur.fetchall()
|
return cur.fetchall()
|
||||||
|
finally:
|
||||||
|
cur.close()
|
||||||
|
|||||||
Reference in New Issue
Block a user