2024-10-11 16:45:22 -04:00
|
|
|
(in-package #:live-chat-db)
|
|
|
|
|
|
|
|
(defvar *db* nil
|
|
|
|
"Database connection object.")
|
|
|
|
|
2024-10-12 19:53:34 -04:00
|
|
|
(defvar *db-lock* (bt:make-lock)
|
|
|
|
"Lock to ensure thread-safe access to database.")
|
|
|
|
|
|
|
|
(defmacro with-database (conn &body body)
|
2024-10-11 16:45:22 -04:00
|
|
|
"Open the SQLite database."
|
2024-10-12 19:53:34 -04:00
|
|
|
`(let ((*db* ,conn))
|
|
|
|
(bt:with-lock-held (*db-lock*)
|
|
|
|
,@body)))
|
2024-10-11 16:45:22 -04:00
|
|
|
|
2024-10-12 19:53:34 -04:00
|
|
|
(defun db ()
|
|
|
|
(dbi:connect-cached
|
|
|
|
:sqlite3 :database-name
|
|
|
|
(asdf:system-relative-pathname :live-chat "chat.db")))
|
2024-10-11 16:45:22 -04:00
|
|
|
|
|
|
|
(defun create-messages-table ()
|
|
|
|
"Create the messages table if it doesn't exist."
|
2024-10-12 19:53:34 -04:00
|
|
|
(with-database (db)
|
|
|
|
(let ((query (dbi:prepare
|
|
|
|
*db*
|
|
|
|
"CREATE TABLE IF NOT EXISTS messages (id
|
|
|
|
INTEGER PRIMARY KEY AUTOINCREMENT,content TEXT NOT NULL)")))
|
|
|
|
(dbi:execute query (list)))))
|
2024-10-11 16:45:22 -04:00
|
|
|
|
|
|
|
(defun insert-message (message)
|
|
|
|
"Insert a new message into the database."
|
2024-10-12 19:53:34 -04:00
|
|
|
(with-database (db)
|
|
|
|
(let ((query (dbi:prepare
|
|
|
|
*db*
|
|
|
|
"INSERT INTO messages (content) VALUES (?)")))
|
|
|
|
(dbi:execute query (list message))
|
|
|
|
message)))
|
2024-10-11 16:45:22 -04:00
|
|
|
|
|
|
|
(defun fetch-messages ()
|
|
|
|
"Fetch all messages from the database."
|
2024-10-12 19:53:34 -04:00
|
|
|
(with-database (db)
|
|
|
|
(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|))))
|
|
|
|
(reverse results))))
|
2024-10-11 16:45:22 -04:00
|
|
|
|
|
|
|
(defun clear-messages ()
|
|
|
|
"Clear all messages from the database."
|
2024-10-12 19:53:34 -04:00
|
|
|
(with-database (db)
|
|
|
|
(let ((query (dbi:prepare *db* "DELETE FROM messages")))
|
|
|
|
(dbi:execute query (list)))))
|