Where possible use a reset command against the DB to verify a pooled connection.
[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 ;;;; $Id$
11 ;;;;
12 ;;;; This file, part of CLSQL, is Copyright (c) 2002-2003 by Kevin M. Rosenberg
13 ;;;;
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 ;;;; *************************************************************************
18
19 (in-package #:clsql-sys)
20
21 (defvar *db-pool* (make-hash-table :test #'equal))
22 (defvar *db-pool-lock* (make-process-lock "DB Pool lock"))
23
24 (defclass conn-pool ()
25   ((connection-spec :accessor connection-spec :initarg :connection-spec)
26    (database-type :accessor pool-database-type :initarg :pool-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))
31    (lock :accessor conn-pool-lock
32          :initform (make-process-lock "Connection pool"))))
33
34 (defun acquire-from-conn-pool (pool)
35   "Try to find a working database connection in the pool or create a new
36 one if needed. This performs 1 query against the DB to ensure it's still
37 valid. When possible (postgres, mssql) that query will be a reset
38 command to put the connection back into its default state."
39   (or (with-process-lock ((conn-pool-lock pool) "Acquire from pool")
40         (when (plusp (length (free-connections pool)))
41           (let ((pconn (vector-pop (free-connections pool))))
42             ;; test if connection still valid.
43             ;; (e.g. db reboot -> invalid connection )
44             (handler-case
45                 (case (database-underlying-type pconn)
46                   (:postgresql
47                      (database-execute-command "RESET ALL" pconn))
48                   (:mysql
49                      (database-query "SHOW ERRORS LIMIT 1" pconn nil nil))
50                   (:mssql
51                      ;; rpc escape sequence since this can't be called as a normal sp.
52                      ;;http://msdn.microsoft.com/en-us/library/aa198358%28SQL.80%29.aspx
53                      (database-execute-command "{rpc sp_reset_connection}" pconn))
54                   (T
55                      (database-query "SELECT 1;"  pconn '(integer) nil)))
56               (sql-database-error (e)
57                 ;; we could check for a specific error,
58                 ;; but, it's safer just to disconnect the pooled conn for any error ?
59                 (warn "Database connection ~S had an error when attempted to be acquired from the pool:
60   ~S
61 Disconnecting.~%"
62                       pconn e)
63                 (ignore-errors (database-disconnect pconn))
64                 nil)
65               (:no-error (&rest args)
66                 (declare (ignore args))
67                 pconn)))))
68       (let ((conn (connect (connection-spec pool)
69                            :database-type (pool-database-type pool)
70                            :if-exists :new
71                            :make-default nil)))
72         (with-process-lock ((conn-pool-lock pool) "Acquire from pool")
73           (vector-push-extend conn (all-connections pool))
74           (setf (conn-pool conn) pool))
75         conn)))
76
77 (defun release-to-conn-pool (conn)
78   (let ((pool (conn-pool conn)))
79     (with-process-lock ((conn-pool-lock pool) "Release to pool")
80       (vector-push-extend conn (free-connections pool)))))
81
82 (defun clear-conn-pool (pool)
83   (with-process-lock ((conn-pool-lock pool) "Clear pool")
84     (loop for conn across (all-connections pool)
85           do (setf (conn-pool conn) nil)
86           ;; disconnect may error if remote side closed connection
87           (ignore-errors (disconnect :database conn)))
88     (setf (fill-pointer (free-connections pool)) 0)
89     (setf (fill-pointer (all-connections pool)) 0))
90   nil)
91
92 (defun find-or-create-connection-pool (connection-spec database-type)
93   "Find connection pool in hash table, creates a new connection pool
94 if not found"
95   (with-process-lock (*db-pool-lock* "Find-or-create connection")
96     (let* ((key (list connection-spec database-type))
97            (conn-pool (gethash key *db-pool*)))
98       (unless conn-pool
99         (setq conn-pool (make-instance 'conn-pool
100                                        :connection-spec connection-spec
101                                        :pool-database-type database-type))
102         (setf (gethash key *db-pool*) conn-pool))
103       conn-pool)))
104
105 (defun acquire-from-pool (connection-spec database-type &optional pool)
106   (unless (typep pool 'conn-pool)
107     (setf pool (find-or-create-connection-pool connection-spec database-type)))
108   (acquire-from-conn-pool pool))
109
110 (defun release-to-pool (database)
111   (release-to-conn-pool database))
112
113 (defun disconnect-pooled (&optional clear)
114   "Disconnects all connections in the pool."
115   (with-process-lock (*db-pool-lock* "Disconnect pooled")
116     (maphash
117      #'(lambda (key conn-pool)
118          (declare (ignore key))
119          (clear-conn-pool conn-pool))
120      *db-pool*)
121     (when clear (clrhash *db-pool*)))
122   t)
123
124 ;(defun pool-start-sql-recording (pool &key (types :command))
125 ;  "Start all stream in the pool recording actions of TYPES"
126 ;  (dolist (con (pool-connections pool))
127 ;    (start-sql-recording :type types
128 ;                        :database (connection-database con))))
129
130 ;(defun pool-stop-sql-recording (pool &key (types :command))
131 ;  "Start all stream in the pool recording actions of TYPES"
132 ;  (dolist (con (pool-connections pool))
133 ;    (stop-sql-recording :type types
134 ;                         :database (connection-database con))))
135
136 ;(defmacro with-database-connection (pool &body body)
137 ;  `(let ((connection (obtain-connection ,pool))
138 ;         (results nil))
139 ;    (unwind-protect
140 ;         (with-database ((connection-database connection))
141 ;           (setq results (multiple-value-list (progn ,@body))))
142 ;      (release-connection connection))
143 ;    (values-list results)))