(in-package #:live-chat-db) (defvar *db* nil "Database connection object.") (defun open-database () "Open the SQLite database." (setf *db* (dbi:connect-cached :sqlite3 :database-name (asdf:system-relative-pathname :live-chat "chat.db")))) (defun close-database () "Close the SQLite database." (when *db* (dbi:disconnect *db*))) (defun create-messages-table () "Create the messages table if it doesn't exist." (open-database) (let ((query (dbi:prepare *db* "CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT NOT NULL)"))) (dbi:execute query (list))) (close-database)) (defun insert-message (message) "Insert a new message into the database." (open-database) (let ((query (dbi:prepare *db* "INSERT INTO messages (content) VALUES (?)"))) (dbi:execute query (list message)) (close-database) message)) (defun fetch-messages () "Fetch all messages from the database." (open-database) (let* ((query (dbi:prepare *db* "SELECT content FROM messages ORDER BY id")) (query (dbi:execute query (list))) (results (loop for row = (dbi:fetch query) while row collect (getf row :|content|)))) (close-database) (reverse results))) (defun clear-messages () "Clear all messages from the database." (let ((query (dbi:prepare *db* "DELETE FROM messages"))) (dbi:execute query (list))))