codeBOKER commited on
Commit
3f0ddc3
·
verified ·
1 Parent(s): e98438e

Update database.py

Browse files
Files changed (1) hide show
  1. database.py +8 -0
database.py CHANGED
@@ -14,6 +14,10 @@ class DatabaseManager:
14
  self.supabase: Optional[AsyncClient] = None
15
  self.logger = logging.getLogger(__name__)
16
 
 
 
 
 
17
  async def connect(self):
18
  """Initialize the async client"""
19
  if not self.supabase:
@@ -21,6 +25,7 @@ class DatabaseManager:
21
 
22
  async def create_or_update_user(self, telegram_id: int, username: str = None,
23
  first_name: str = None, last_name: str = None):
 
24
  try:
25
  existing_user = await self.supabase.table("users").select("id").eq("telegram_id", telegram_id).execute()
26
 
@@ -44,6 +49,7 @@ class DatabaseManager:
44
  return None
45
 
46
  async def save_message(self, telegram_id: int, message_text: str, message_type: str):
 
47
  try:
48
  await self.create_or_update_user(telegram_id)
49
 
@@ -63,6 +69,7 @@ class DatabaseManager:
63
  return None
64
 
65
  async def get_conversation_history(self, telegram_id: int, limit: int = 10) -> List[Dict]:
 
66
  try:
67
  result = await (self.supabase.table("messages")
68
  .select("message_text, message_type, created_at")
@@ -76,6 +83,7 @@ class DatabaseManager:
76
  return []
77
 
78
  async def _ensure_active_session(self, telegram_id: int):
 
79
  try:
80
  active = await (self.supabase.table("conversation_sessions")
81
  .select("id")
 
14
  self.supabase: Optional[AsyncClient] = None
15
  self.logger = logging.getLogger(__name__)
16
 
17
+ async def _ensure_connection(self):
18
+ if self.supabase is None:
19
+ await self.connect()
20
+
21
  async def connect(self):
22
  """Initialize the async client"""
23
  if not self.supabase:
 
25
 
26
  async def create_or_update_user(self, telegram_id: int, username: str = None,
27
  first_name: str = None, last_name: str = None):
28
+ await self._ensure_connection()
29
  try:
30
  existing_user = await self.supabase.table("users").select("id").eq("telegram_id", telegram_id).execute()
31
 
 
49
  return None
50
 
51
  async def save_message(self, telegram_id: int, message_text: str, message_type: str):
52
+ await self._ensure_connection()
53
  try:
54
  await self.create_or_update_user(telegram_id)
55
 
 
69
  return None
70
 
71
  async def get_conversation_history(self, telegram_id: int, limit: int = 10) -> List[Dict]:
72
+ await self._ensure_connection()
73
  try:
74
  result = await (self.supabase.table("messages")
75
  .select("message_text, message_type, created_at")
 
83
  return []
84
 
85
  async def _ensure_active_session(self, telegram_id: int):
86
+ await self._ensure_connection()
87
  try:
88
  active = await (self.supabase.table("conversation_sessions")
89
  .select("id")