diff --git a/database.py b/database.py index 3b2e357..c9211e9 100644 --- a/database.py +++ b/database.py @@ -121,8 +121,8 @@ class BasicDatabase: def context_get_messages(self, bot_id: int, chat_id: int) -> list[dict]: self.cursor.execute(""" SELECT role, text, image FROM contexts - WHERE bot_id = ? AND chat_id = ? AND message_id IS NOT NULL - ORDER BY message_id + WHERE bot_id = ? AND chat_id = ? + ORDER BY id """, bot_id, chat_id) return self._to_dict(self.cursor.fetchall()) @@ -133,8 +133,8 @@ class BasicDatabase: def context_get_last_assistant_message_id(self, bot_id: int, chat_id: int) -> Optional[int]: return self.cursor.execute(""" SELECT message_id FROM contexts - WHERE bot_id = ? AND chat_id = ? AND role = 'assistant' AND message_id IS NOT NULL - ORDER BY message_id DESC + WHERE bot_id = ? AND chat_id = ? AND role = 'assistant' + ORDER BY id DESC LIMIT 1 """, bot_id, chat_id).fetchval() @@ -167,16 +167,12 @@ class BasicDatabase: def _context_trim(self, bot_id: int, chat_id: int, max_messages: int): current_count = self.context_get_count(bot_id, chat_id) while current_count >= max_messages: - oldest_message_id = self.cursor.execute(""" - SELECT message_id FROM contexts - WHERE bot_id = ? AND chat_id = ? AND message_id IS NOT NULL - ORDER BY message_id ASC - LIMIT 1 - """, bot_id, chat_id).fetchval() + oldest_message_id = self.cursor.execute( + "SELECT id FROM contexts WHERE bot_id = ? AND chat_id = ? ORDER BY id LIMIT 1", + bot_id, chat_id).fetchval() if oldest_message_id: - self.cursor.execute("DELETE FROM contexts WHERE bot_id = ? AND chat_id = ? AND message_id = ?", - bot_id, chat_id, oldest_message_id) + self.cursor.execute("DELETE FROM contexts WHERE id = ?", oldest_message_id) current_count -= 1 else: break diff --git a/tg/tg_database.py b/tg/tg_database.py index 3762028..c060608 100644 --- a/tg/tg_database.py +++ b/tg/tg_database.py @@ -44,12 +44,14 @@ class TgDatabase(database.BasicDatabase): self.cursor.execute(""" CREATE TABLE IF NOT EXISTS contexts ( + id BIGINT NOT NULL auto_increment, bot_id BIGINT NOT NULL, chat_id BIGINT NOT NULL, message_id BIGINT, role VARCHAR(16) NOT NULL, text VARCHAR(4000), image MEDIUMBLOB, + PRIMARY KEY (id), CONSTRAINT fk_contexts_chats FOREIGN KEY (bot_id, chat_id) REFERENCES chats (bot_id, chat_id) ON UPDATE CASCADE ON DELETE CASCADE) """) diff --git a/vk/vk_database.py b/vk/vk_database.py index 96543f3..c06d59e 100644 --- a/vk/vk_database.py +++ b/vk/vk_database.py @@ -47,12 +47,14 @@ class VkDatabase(database.BasicDatabase): self.cursor.execute(""" CREATE TABLE IF NOT EXISTS contexts ( + id BIGINT NOT NULL auto_increment, bot_id BIGINT NOT NULL, chat_id BIGINT NOT NULL, message_id BIGINT, role VARCHAR(16) NOT NULL, text VARCHAR(4000), image MEDIUMBLOB, + PRIMARY KEY (id), CONSTRAINT fk_contexts_chats FOREIGN KEY (bot_id, chat_id) REFERENCES chats (bot_id, chat_id) ON UPDATE CASCADE ON DELETE CASCADE) """)