Skip to content

Instantly share code, notes, and snippets.

@zkat
Last active September 27, 2015 09:18
Show Gist options
  • Select an option

  • Save zkat/1247190 to your computer and use it in GitHub Desktop.

Select an option

Save zkat/1247190 to your computer and use it in GitHub Desktop.
pomo connection reuse
;;;
;;; Connection pooling
;;;
(defparameter *connection-pool-lock* (bt:make-lock))
(defparameter *max-pooled-connections* 50)
(defvar *connection-pool* (make-queue *max-pooled-connections*))
(defun get-connection ()
(or (bt:with-lock-held (*connection-pool-lock*)
(unless (queue-empty-p *connection-pool*)
(dequeue *connection-pool*)))
(apply #'connect (list *db-name* *db-user* *db-password* *db-host*))))
(defun done-with-connection (connection)
(bt:with-lock-held (*connection-pool-lock*)
(if (queue-full-p *connection-pool*)
(disconnect connection)
(enqueue connection *connection-pool*))))
(defun clear-pooled-connections ()
(bt:with-lock-held (*connection-pool-lock*)
(loop until (queue-empty-p *connection-pool*)
for connection = (dequeue *connection-pool*)
when (connected-p connection)
do (disconnect connection))))
(defmacro with-db ((&key (reusep t)) &body body)
`(let* ((reusing-connection-p (and *database* ,reusep))
(*database* (or (when reusing-connection-p *database*)
(get-connection))))
(unwind-protect (progn ,@body)
(unless reusing-connection-p
(done-with-connection *database*)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment