Suite of new tests for connection pool operations.
[clsql.git] / sql / pool.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          pool.lisp
6 ;;;; Purpose:       Support function for connection pool
7 ;;;; Programmers:   Kevin M. Rosenberg, Marc Battyani
8 ;;;; Date Started:  Apr 2002
9 ;;;;
10 ;;;; This file, part of CLSQL, is Copyright (c) 2002-2010 by Kevin M. Rosenberg
11 ;;;;
12 ;;;; CLSQL users are granted the rights to distribute and use this software
13 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
14 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
15 ;;;; *************************************************************************
16
17 (in-package #:clsql-sys)
18
19 (defparameter *db-pool-max-free-connections* 4
20   "Threshold of free-connections in the pool before we disconnect a database
21   rather than returning it to the pool.  NIL for no limit.  This is really a
22   heuristic that should, on avg keep the free connections about this size.")
23
24 (defvar *db-pool* (make-hash-table :test #'equal))
25 (defvar *db-pool-lock* (make-process-lock "DB Pool lock"))
26
27 (defclass conn-pool ()
28   ((connection-spec :accessor connection-spec :initarg :connection-spec)
29    (database-type :accessor pool-database-type :initarg :pool-database-type)
30    (free-connections :accessor free-connections :initform nil)
31    (all-connections :accessor all-connections :initform nil)
32    (lock :accessor conn-pool-lock
33          :initform (make-process-lock "Connection pool"))))
34
35
36
37
38 (defun acquire-from-pool (connection-spec database-type &optional pool encoding)
39   "Try to find a working database connection in the pool or create a new
40 one if needed. This performs 1 query against the DB to ensure it's still
41 valid. When possible (postgres, mssql) that query will be a reset
42 command to put the connection back into its default state."
43   (unless (typep pool 'conn-pool)
44     (setf pool (find-or-create-connection-pool connection-spec database-type)))
45   (or
46    (loop for pconn = (with-process-lock ((conn-pool-lock pool) "Acquire")
47                        (pop (free-connections pool)))
48          always pconn
49          thereis
50          ;; test if connection still valid.
51          ;; (e.g. db reboot -> invalid connection )
52          (handler-case
53              (progn (database-acquire-from-conn-pool pconn)
54                     pconn)
55            (sql-database-error (e)
56              ;; we could check for a specific error,
57              ;; but, it's safer just to disconnect the pooled conn for any error ?
58              (warn "Database connection ~S had an error while acquiring from the pool:
59   ~S
60 Disconnecting.~%"
61                    pconn e)
62              ;;run database disconnect to give chance for cleanup
63              ;;there, then remove it from the lists of connected
64              ;;databases.
65              (%pool-force-disconnect pconn)
66              (with-process-lock ((conn-pool-lock pool) "remove dead conn")
67                (setf (all-connections pool)
68                      (delete pconn (all-connections pool))))
69              nil)))
70    (let ((conn (connect (connection-spec pool)
71                         :database-type (pool-database-type pool)
72                         :if-exists :new
73                         :make-default nil
74                         :encoding encoding)))
75      (with-process-lock ((conn-pool-lock pool) "new conection")
76        (push conn (all-connections pool))
77        (setf (conn-pool conn) pool))
78      conn)))
79
80 (defun release-to-pool (database &optional (pool (conn-pool database)))
81   "Release a database connection to the pool. The backend will have a
82 chance to do cleanup."
83   (unless (conn-pool database) (setf (conn-pool database) pool))
84   (cond
85     ;;We read the list of free-connections outside the lock. This
86     ;;should be fine as long as that list is never dealt with
87     ;;destructively (push and pop destructively modify the place,
88     ;;not the list). Multiple threads getting to this test at the
89     ;;same time might result in the free-connections getting
90     ;;longer... meh.
91     ((or (and *db-pool-max-free-connections*
92               (>= (length (free-connections pool))
93                   *db-pool-max-free-connections*)))
94      (%pool-force-disconnect database)
95      (with-process-lock ((conn-pool-lock pool) "Remove extra Conn")
96        (setf (all-connections pool)
97              (delete database (all-connections pool)))))
98     (t
99      ;;let it do cleanup
100      (database-release-to-conn-pool database)
101      (with-process-lock ((conn-pool-lock pool) "Release to pool")
102        (push database (free-connections pool))))))
103
104 (defmethod database-acquire-from-conn-pool (database)
105   (case (database-underlying-type database)
106     (:postgresql
107        (database-execute-command "RESET ALL" database))
108     (:mysql
109        (database-query "SHOW ERRORS LIMIT 1" database nil nil))
110     (:mssql
111        ;; rpc escape sequence since this can't be called as a normal sp.
112        ;;http://msdn.microsoft.com/en-us/library/aa198358%28SQL.80%29.aspx
113        (database-execute-command "{rpc sp_reset_connection}" database))
114     (T
115        (database-query "SELECT 1;"  database '(integer) nil))))
116
117 (defmethod database-release-to-conn-pool (database)
118   (case (database-underlying-type database)
119     (:postgresql
120        (ignore-errors
121          ;;http://www.postgresql.org/docs/current/static/sql-discard.html
122          ;;this was introduced relatively recently, wrap in ignore-errors
123          ;;so that it doesn't choke older versions.
124          (database-execute-command "DISCARD ALL" database)))))
125
126 (defun clear-conn-pool (pool)
127   "Be careful this function will disconnect connections without regard
128 to whether another thread is actively using them."
129   (with-process-lock ((conn-pool-lock pool) "Clear pool")
130     (mapc #'%pool-force-disconnect (all-connections pool))
131     (setf (all-connections pool) nil
132           (free-connections pool) nil))
133   nil)
134
135 (defun find-or-create-connection-pool (connection-spec database-type)
136   "Find connection pool in hash table, creates a new connection pool
137 if not found"
138   (with-process-lock (*db-pool-lock* "Find-or-create connection")
139     (let* ((key (list connection-spec database-type))
140            (conn-pool (gethash key *db-pool*)))
141       (unless conn-pool
142         (setq conn-pool (make-instance 'conn-pool
143                                        :connection-spec connection-spec
144                                        :pool-database-type database-type))
145         (setf (gethash key *db-pool*) conn-pool))
146       conn-pool)))
147
148 (defun disconnect-pooled (&optional clear)
149   "Disconnects all connections in the pool. When clear, also deletes
150 the pool objects."
151   (with-process-lock (*db-pool-lock* "Disconnect pooled")
152     (maphash
153      #'(lambda (key conn-pool)
154          (declare (ignore key))
155          (clear-conn-pool conn-pool))
156      *db-pool*)
157     (when clear (clrhash *db-pool*)))
158   t)
159
160 (defun %pool-force-disconnect (database)
161   "Force disconnection of a connection from the pool."
162   ;;so it isn't just returned to pool
163   (setf (conn-pool database) nil)
164   ;; disconnect may error if remote side closed connection
165   (ignore-errors (disconnect :database database)))
166
167 ;(defun pool-start-sql-recording (pool &key (types :command))
168 ;  "Start all stream in the pool recording actions of TYPES"
169 ;  (dolist (con (pool-connections pool))
170 ;    (start-sql-recording :type types
171 ;                        :database (connection-database con))))
172
173 ;(defun pool-stop-sql-recording (pool &key (types :command))
174 ;  "Start all stream in the pool recording actions of TYPES"
175 ;  (dolist (con (pool-connections pool))
176 ;    (stop-sql-recording :type types
177 ;                         :database (connection-database con))))
178
179 ;(defmacro with-database-connection (pool &body body)
180 ;  `(let ((connection (obtain-connection ,pool))
181 ;         (results nil))
182 ;    (unwind-protect
183 ;         (with-database ((connection-database connection))
184 ;           (setq results (multiple-value-list (progn ,@body))))
185 ;      (release-connection connection))
186 ;    (values-list results)))