1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
6 ;;;; Purpose: Support function for connection pool
7 ;;;; Programmers: Kevin M. Rosenberg, Marc Battyani
8 ;;;; Date Started: Apr 2002
10 ;;;; $Id: pool.cl,v 1.6 2002/05/13 16:55:07 marc.battyani Exp $
12 ;;;; This file, part of CLSQL, is Copyright (c) 2002 by Kevin M. Rosenberg
14 ;;;; CLSQL users are granted the rights to distribute and use this software
15 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
16 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
17 ;;;; *************************************************************************
19 (declaim (optimize (debug 3) (speed 3) (safety 1) (compilation-speed 0)))
20 (in-package :clsql-sys)
22 (defvar *db-pool* (make-hash-table :test #'equal))
24 (defclass conn-pool ()
25 ((connection-spec :accessor connection-spec :initarg :connection-spec)
26 (database-type :accessor database-type :initarg :database-type)
27 (free-connections :accessor free-connections
28 :initform (make-array 5 :fill-pointer 0 :adjustable t))
29 (all-connections :accessor all-connections
30 :initform (make-array 5 :fill-pointer 0 :adjustable t))))
32 (defun acquire-from-conn-pool (pool)
33 (if (zerop (length (free-connections pool)))
34 (let ((conn (connect (connection-spec pool)
35 :database-type (database-type pool) :if-exists :new)))
36 (vector-push-extend conn (all-connections pool))
37 (setf (conn-pool conn) pool)
39 (vector-pop (free-connections pool))))
41 (defun release-to-conn-pool (conn)
42 (vector-push-extend conn (free-connections (conn-pool conn))))
44 (defun clear-conn-pool (pool)
45 (loop for conn across (all-connections pool)
46 do (setf (conn-pool conn) nil)
47 (disconnect :database conn))
48 (setf (fill-pointer (free-connections pool)) 0)
49 (setf (fill-pointer (all-connections pool)) 0))
51 (defun find-or-create-connection-pool (connection-spec database-type)
52 "Find connection pool in hash table, creates a new connection pool if not found"
53 (let* ((key (list connection-spec database-type))
54 (conn-pool (gethash key *db-pool*)))
56 (setq conn-pool (make-instance 'conn-pool
57 :connection-spec connection-spec
58 :database-type database-type))
59 (setf (gethash key *db-pool*) conn-pool))
62 (defun acquire-from-pool (connection-spec database-type &optional pool)
63 (unless (typep pool 'conn-pool)
64 (setf pool (find-or-create-connection-pool connection-spec database-type)))
65 (acquire-from-conn-pool pool))
67 (defun release-to-pool (database)
68 (release-to-conn-pool database))
70 (defun disconnect-pooled (&optional clear)
71 "Disconnects all connections in the pool"
73 #'(lambda (key conn-pool)
74 (declare (ignore key))
75 (clear-conn-pool conn-pool))
77 (when clear (clrhash *db-pool*))