Pass encoding argument to pooled connections
[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
21   database rather than returning it to the pool. This is really a heuristic
22 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 (defun acquire-from-pool (connection-spec database-type &optional pool encoding)
37   "Try to find a working database connection in the pool or create a new
38 one if needed. This performs 1 query against the DB to ensure it's still
39 valid. When possible (postgres, mssql) that query will be a reset
40 command to put the connection back into its default state."
41   (unless (typep pool 'conn-pool)
42     (setf pool (find-or-create-connection-pool connection-spec database-type)))
43   (or
44    (loop for pconn = (with-process-lock ((conn-pool-lock pool) "Acquire")
45                        (pop (free-connections pool)))
46          always pconn
47          thereis
48          ;; test if connection still valid.
49          ;; (e.g. db reboot -> invalid connection )
50          (handler-case
51              (progn (database-acquire-from-conn-pool pconn)
52                     pconn)
53            (sql-database-error (e)
54              ;; we could check for a specific error,
55              ;; but, it's safer just to disconnect the pooled conn for any error ?
56              (warn "Database connection ~S had an error while acquiring from the pool:
57   ~S
58 Disconnecting.~%"
59                    pconn e)
60              ;;run database disconnect to give chance for cleanup
61              ;;there, then remove it from the lists of connected
62              ;;databases.
63              (%pool-force-disconnect pconn)
64              (with-process-lock ((conn-pool-lock pool) "remove dead conn")
65                (setf (all-connections pool)
66                      (delete pconn (all-connections pool))))
67              nil)))
68    (let ((conn (connect (connection-spec pool)
69                         :database-type (pool-database-type pool)
70                         :if-exists :new
71                         :make-default nil
72                         :encoding encoding)))
73      (with-process-lock ((conn-pool-lock pool) "new conection")
74        (push conn (all-connections pool))
75        (setf (conn-pool conn) pool))
76      conn)))
77
78 (defun release-to-pool (database)
79   "Release a database connection to the pool. The backend will have a
80 chance to do cleanup."
81   (let ((pool (conn-pool database)))
82     (cond
83       ;;We read the list of free-connections outside the lock. This
84       ;;should be fine as long as that list is never dealt with
85       ;;destructively (push and pop destructively modify the place,
86       ;;not the list). Multiple threads getting to this test at the
87       ;;same time might result in the free-connections getting
88       ;;longer... meh.
89       ((and *db-pool-max-free-connections*
90             (>= (length (free-connections pool))
91                 *db-pool-max-free-connections*))
92        (%pool-force-disconnect database)
93        (with-process-lock ((conn-pool-lock pool) "Remove extra Conn")
94          (setf (all-connections pool)
95                (delete database (all-connections pool)))))
96       (t
97        ;;let it do cleanup
98        (database-release-to-conn-pool database)
99        (with-process-lock ((conn-pool-lock pool) "Release to pool")
100          (push database (free-connections pool)))))))
101
102 (defmethod database-acquire-from-conn-pool (database)
103   (case (database-underlying-type database)
104     (:postgresql
105        (database-execute-command "RESET ALL" database))
106     (:mysql
107        (database-query "SHOW ERRORS LIMIT 1" database nil nil))
108     (:mssql
109        ;; rpc escape sequence since this can't be called as a normal sp.
110        ;;http://msdn.microsoft.com/en-us/library/aa198358%28SQL.80%29.aspx
111        (database-execute-command "{rpc sp_reset_connection}" database))
112     (T
113        (database-query "SELECT 1;"  database '(integer) nil))))
114
115 (defmethod database-release-to-conn-pool (database)
116   (case (database-underlying-type database)
117     (:postgresql
118        (ignore-errors
119          ;;http://www.postgresql.org/docs/current/static/sql-discard.html
120          ;;this was introduced relatively recently, wrap in ignore-errors
121          ;;so that it doesn't choke older versions.
122          (database-execute-command "DISCARD ALL" database)))))
123
124 (defun clear-conn-pool (pool)
125   (with-process-lock ((conn-pool-lock pool) "Clear pool")
126     (mapc #'%pool-force-disconnect (all-connections pool))
127     (setf (all-connections pool) nil
128           (free-connections pool) nil))
129   nil)
130
131 (defun find-or-create-connection-pool (connection-spec database-type)
132   "Find connection pool in hash table, creates a new connection pool
133 if not found"
134   (with-process-lock (*db-pool-lock* "Find-or-create connection")
135     (let* ((key (list connection-spec database-type))
136            (conn-pool (gethash key *db-pool*)))
137       (unless conn-pool
138         (setq conn-pool (make-instance 'conn-pool
139                                        :connection-spec connection-spec
140                                        :pool-database-type database-type))
141         (setf (gethash key *db-pool*) conn-pool))
142       conn-pool)))
143
144 (defun disconnect-pooled (&optional clear)
145   "Disconnects all connections in the pool. When clear, also deletes
146 the pool objects."
147   (with-process-lock (*db-pool-lock* "Disconnect pooled")
148     (maphash
149      #'(lambda (key conn-pool)
150          (declare (ignore key))
151          (clear-conn-pool conn-pool))
152      *db-pool*)
153     (when clear (clrhash *db-pool*)))
154   t)
155
156 (defun %pool-force-disconnect (database)
157   "Force disconnection of a connection from the pool."
158   ;;so it isn't just returned to pool
159   (setf (conn-pool database) nil)
160   ;; disconnect may error if remote side closed connection
161   (ignore-errors (disconnect :database database)))
162
163 ;(defun pool-start-sql-recording (pool &key (types :command))
164 ;  "Start all stream in the pool recording actions of TYPES"
165 ;  (dolist (con (pool-connections pool))
166 ;    (start-sql-recording :type types
167 ;                        :database (connection-database con))))
168
169 ;(defun pool-stop-sql-recording (pool &key (types :command))
170 ;  "Start all stream in the pool recording actions of TYPES"
171 ;  (dolist (con (pool-connections pool))
172 ;    (stop-sql-recording :type types
173 ;                         :database (connection-database con))))
174
175 ;(defmacro with-database-connection (pool &body body)
176 ;  `(let ((connection (obtain-connection ,pool))
177 ;         (results nil))
178 ;    (unwind-protect
179 ;         (with-database ((connection-database connection))
180 ;           (setq results (multiple-value-list (progn ,@body))))
181 ;      (release-connection connection))
182 ;    (values-list results)))