Bugfix: make it possible to close the DB connection

This commit is contained in:
Tomek Kurcz 2017-11-28 14:05:40 +01:00
parent 19b9f1baa3
commit 67f6d4dc9e

View file

@ -19,8 +19,16 @@
:remove-session))
(in-package :lack.middleware.session.store.dbi)
(defmacro with-db-connection (connection store &body body)
`(let ((,connection (funcall (dbi-store-connector ,store))))
(unwind-protect
(progn ,@body)
(when (dbi-store-disconnector ,store)
(funcall (dbi-store-disconnector ,store) ,connection)))))
(defstruct (dbi-store (:include store))
(connector nil :type function)
(disconnector nil)
(serializer (lambda (data)
(usb8-array-to-base64-string
(string-to-utf-8-bytes (prin1-to-string (marshal data))))))
@ -31,8 +39,8 @@
(table-name "sessions"))
(defmethod fetch-session ((store dbi-store) sid)
(let* ((conn (funcall (dbi-store-connector store)))
(query (dbi:prepare conn
(with-db-connection conn store
(let* ((query (dbi:prepare conn
(format nil "SELECT session_data FROM ~A WHERE id = ?"
(dbi-store-table-name store))))
(result (dbi:fetch (dbi:execute query sid))))
@ -44,7 +52,7 @@
(getf result :|session_data|)
e)
nil))
nil)))
nil))))
(defun current-timestamp ()
(multiple-value-bind (sec min hour date month year)
@ -54,8 +62,8 @@
hour min sec)))
(defmethod store-session ((store dbi-store) sid session)
(let ((conn (funcall (dbi-store-connector store)))
(serialized-session (funcall (dbi-store-serializer store) session)))
(with-db-connection conn store
(let ((serialized-session (funcall (dbi-store-serializer store) session)))
(dbi:with-transaction conn
(let* ((query (dbi:prepare conn
(format nil "SELECT session_data FROM ~A WHERE id = ?"
@ -80,10 +88,11 @@
(dbi-store-record-timestamps store)
(current-timestamp))
sid
serialized-session)))))))
serialized-session))))))))
(defmethod remove-session ((store dbi-store) sid)
(dbi:do-sql (funcall (dbi-store-connector store))
(with-db-connection conn store
(dbi:do-sql conn
(format nil "DELETE FROM ~A WHERE id = ?"
(dbi-store-table-name store))
sid))
sid)))