Skip to content

Commit

Permalink
feat(logging): add loggers count control and add cursor close
Browse files Browse the repository at this point in the history
  • Loading branch information
fu050409 committed Mar 1, 2024
1 parent ba08583 commit 52806cc
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/diceutils/logging.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from diceutils.exceptions import TooManyLoggersError
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Any, Literal, Tuple, Union
Expand Down Expand Up @@ -32,6 +33,7 @@ def _create_table(self):
"""
)
self.conn.commit()
cursor.close()

def _insert(
self, cursor: sqlite3.Cursor, data: Tuple[str, str, str, str, str, str, str]
Expand All @@ -55,11 +57,30 @@ def add(
data: str,
message_sequence: str,
) -> None:
count = self.count(session_id)
if (
count == MAX_LOGGERS_PER_SESSION and int(id) >= MAX_LOGGERS_PER_SESSION
) or count > MAX_LOGGERS_PER_SESSION:
raise TooManyLoggersError(
f"Too many loggers, expected less than {MAX_LOGGERS_PER_SESSION}, "
f"but given index is '{id}'."
)
cursor = self.conn.cursor()
self._insert(
cursor, (session_id, id, user_id, user_role, date, data, message_sequence)
)
self.conn.commit()
cursor.close()

def count(self, session_id: str) -> int:
cursor = self.conn.cursor()
cursor.execute(
"SELECT COUNT(DISTINCT id) AS unique_ids FROM log WHERE session_id = ?;",
(session_id,),
)
count = cursor.fetchone()[0]
cursor.close()
return count

def loadall(self) -> Dict[str, Dict[str, List[Dict[str, Any]]]]:
cursor = self.conn.cursor()
Expand All @@ -81,6 +102,7 @@ def loadall(self) -> Dict[str, Dict[str, List[Dict[str, Any]]]]:
}
)

cursor.close()
return datas

def load(self, session_id: str, id: str) -> List[Dict[str, Any]]:
Expand All @@ -103,6 +125,7 @@ def load(self, session_id: str, id: str) -> List[Dict[str, Any]]:
}
)

cursor.close()
return datas

def remove(self, session_id: str, id: str, message_sequence: str):
Expand All @@ -112,13 +135,15 @@ def remove(self, session_id: str, id: str, message_sequence: str):
(session_id, id, message_sequence),
)
self.conn.commit()
cursor.close()

def clear(self, session_id: str, id: str) -> None:
cursor = self.conn.cursor()
cursor.execute(
"DELETE FROM log WHERE session_id = ? AND id = ?", (session_id, id)
)
self.conn.commit()
cursor.close()

def close(self):
self.conn.close()
Expand All @@ -144,6 +169,13 @@ def load(self, session_id: str, id: Union[int, str]) -> List[Dict[str, Any]]:
def loadall(self) -> Dict[str, Dict[str, List[Dict[str, Any]]]]:
return self.log_manager.loadall()

def next_id(self, session_id: str):
return (
count
if (count := self.log_manager.count(session_id)) <= MAX_LOGGERS_PER_SESSION
else None
)

def add(
self,
session_id: str,
Expand Down

0 comments on commit 52806cc

Please sign in to comment.