r9199: fold clsql-base and clsql-base-sys into clsql-base
[clsql.git] / base / database.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; $Id$
5 ;;;;
6 ;;;; Base database functions
7 ;;;;
8 ;;;; This file is part of CLSQL.
9 ;;;;
10 ;;;; CLSQL users are granted the rights to distribute and use this software
11 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
12 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
13 ;;;; *************************************************************************
14
15 (in-package #:clsql-base)
16
17 (setf (documentation 'database-name 'function)
18       "Returns the name of a database.")
19
20 ;;; Database handling
21
22 (defvar *connect-if-exists* :error
23   "Default value for the if-exists parameter of connect calls.")
24
25 (defvar *connected-databases* nil
26   "List of active database objects.")
27
28 (defun connected-databases ()
29   "Return the list of active database objects."
30   *connected-databases*)
31
32 (defvar *default-database* nil
33   "Specifies the default database to be used.")
34
35 (defun is-database-open (database)
36   (eql (database-state database) :open))
37
38 (defun find-database (database &key (errorp t) (db-type nil))
39   "The function FIND-DATABASE, given a string DATABASE, searches
40 amongst the connected databases for one matching the name DATABASE. If
41 there is exactly one such database, it is returned and the second
42 return value count is 1. If more than one databases match and ERRORP
43 is nil, then the most recently connected of the matching databases is
44 returned and count is the number of matches. If no matching database
45 is found and ERRORP is nil, then nil is returned. If none, or more
46 than one, matching databases are found and ERRORP is true, then an
47 error is signalled. If the argument database is a database, it is
48 simply returned."
49   (etypecase database
50     (database
51      (values database 1))
52     (string
53      (let* ((matches (remove-if 
54                       #'(lambda (db)
55                           (not (and (string= (database-name db) database)
56                                     (if db-type
57                                         (equal (database-type db) db-type)
58                                         t))))
59                       (connected-databases)))
60             (count (length matches)))
61        (if (or (not errorp) (= count 1))
62            (values (car matches) count)
63            (cerror "Return nil."
64                    'clsql-simple-error
65                    :format-control "There exists ~A database called ~A."
66                    :format-arguments
67                    (list (if (zerop count) "no" "more than one")
68                          database)))))))
69
70
71 (defun connect (connection-spec
72                 &key (if-exists *connect-if-exists*)
73                 (make-default t)
74                 (pool nil)
75                 (database-type *default-database-type*))
76   "Connects to a database of the given database-type, using the
77 type-specific connection-spec.  The value of if-exists determines what
78 happens if a connection to that database is already established.  A
79 value of :new means create a new connection.  A value of :warn-new
80 means warn the user and create a new connect.  A value of :warn-old
81 means warn the user and use the old connection.  A value of :error
82 means fail, notifying the user.  A value of :old means return the old
83 connection.  If make-default is true, then *default-database* is set
84 to the new connection, otherwise *default-database is not changed. If
85 pool is t the connection will be taken from the general pool, if pool
86 is a conn-pool object the connection will be taken from this pool."
87
88   (unless database-type
89     (error "Must specify a database-type."))
90   
91   (when (stringp connection-spec)
92     (setq connection-spec (string-to-list-connection-spec connection-spec)))
93   
94   (unless (member database-type *loaded-database-types*)
95     (asdf:operate 'asdf:load-op (ensure-keyword
96                                  (concatenate 'string 
97                                               (symbol-name '#:clsql-)
98                                               (symbol-name database-type)))))
99
100   (if pool
101       (acquire-from-pool connection-spec database-type pool)
102       (let* ((db-name (database-name-from-spec connection-spec database-type))
103              (old-db (unless (eq if-exists :new)
104                        (find-database db-name :db-type database-type
105                                       :errorp nil)))
106              (result nil))
107         (if old-db
108             (ecase if-exists
109               (:warn-new
110                (setq result
111                      (database-connect connection-spec database-type))
112                (warn 'clsql-exists-warning :old-db old-db :new-db result))
113               (:error
114                (restart-case
115                    (error 'clsql-exists-error :old-db old-db)
116                  (create-new ()
117                    :report "Create a new connection."
118                    (setq result
119                          (database-connect connection-spec database-type)))
120                  (use-old ()
121                    :report "Use the existing connection."
122                    (setq result old-db))))
123               (:warn-old
124                (setq result old-db)
125                (warn 'clsql-exists-warning :old-db old-db :new-db old-db))
126               (:old
127                (setq result old-db)))
128             (setq result
129                   (database-connect connection-spec database-type)))
130         (when result
131           (setf (slot-value result 'state) :open)
132           (pushnew result *connected-databases*)
133           (when make-default (setq *default-database* result))
134           result))))
135
136
137 (defun disconnect (&key (database *default-database*) (error nil))
138
139   "Closes the connection to DATABASE and resets *default-database* if
140 that database was disconnected. If database is a database object, then
141 it is used directly. Otherwise, the list of connected databases is
142 searched to find one with DATABASE as its connection
143 specifications. If no such database is found, then if ERROR and
144 DATABASE are both non-nil an error is signaled, otherwise DISCONNECT
145 returns nil. If the database is from a pool it will be released to
146 this pool."
147   (let ((database (find-database database :errorp (and database error))))
148     (when database
149       (if (conn-pool database)
150           (when (release-to-pool database)
151             (setf *connected-databases* (delete database *connected-databases*))
152             (when (eq database *default-database*)
153               (setf *default-database* (car *connected-databases*)))
154             t)
155           (when (database-disconnect database)
156             (setf *connected-databases* (delete database *connected-databases*))
157             (when (eq database *default-database*)
158               (setf *default-database* (car *connected-databases*)))
159             (setf (slot-value database 'state) :closed)
160             t)))))
161
162
163 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
164
165
166
167
168
169 (defun reconnect (&key (database *default-database*) (error nil) (force t))
170   "Reconnects DATABASE to its underlying RDBMS. If successful, returns
171 t and the variable *default-database* is set to the newly reconnected
172 database. The default value for DATABASE is *default-database*. If
173 DATABASE is a database object, then it is used directly. Otherwise,
174 the list of connected databases is searched to find one with database
175 as its connection specifications (see CONNECT). If no such database is
176 found, then if ERROR and DATABASE are both non-nil an error is
177 signaled, otherwise RECONNECT returns nil. FORCE controls whether an
178 error should be signaled if the existing database connection cannot be
179 closed. When non-nil (this is the default value) the connection is
180 closed without error checking. When FORCE is nil, an error is signaled
181 if the database connection has been lost."
182   (let ((db (etypecase database
183               (database database)
184               ((or string list)
185                (let ((db (find-database database :errorp nil)))
186                  (when (null db)
187                    (if (and database error)
188                        (error 'clsql-generic-error
189                               :message
190                               (format nil "Unable to find database with connection-spec ~A." database))
191                        (return-from reconnect nil)))
192                  db)))))
193                               
194     (when (is-database-open db)
195       (if force
196           (ignore-errors (disconnect :database db))
197           (disconnect :database db :error nil)))
198     
199     (connect (connection-spec db))))
200
201   
202 (defun status (&optional full)
203   "The function STATUS prints status information to the standard
204 output, for the connected databases and initialized database types. If
205 full is T, detailed status information is printed. The default value
206 of full is NIL."
207   (flet ((get-data ()
208            (let ((data '()))
209              (dolist (db (connected-databases) data)
210                (push 
211                 (append 
212                  (list (if (equal db *default-database*) "*" "")        
213                        (database-name db)
214                        (string-downcase (string (database-type db)))
215                        (cond ((and (command-recording-stream db) 
216                                    (result-recording-stream db)) 
217                               "Both")
218                              ((command-recording-stream db) "Commands")
219                              ((result-recording-stream db) "Results")
220                              (t "nil")))
221                  (when full 
222                    (list 
223                     (if (conn-pool db) "t" "nil")
224                     (format nil "~A" (length (database-list-tables db)))
225                     (format nil "~A" (length (database-list-views db))))))
226                 data))))
227          (compute-sizes (data)
228            (mapcar #'(lambda (x) (apply #'max (mapcar #'length x)))
229                    (apply #'mapcar (cons #'list data))))
230          (print-separator (size)
231            (format t "~&~A" (make-string size :initial-element #\-))))
232     (format t "~&CLSQL STATUS: ~A~%" (iso-timestring (get-time)))
233     (let ((data (get-data)))
234       (when data
235         (let* ((titles (if full 
236                            (list "" "DATABASE" "TYPE" "RECORDING" "POOLED" 
237                                  "TABLES" "VIEWS")
238                            (list "" "DATABASE" "TYPE" "RECORDING")))
239                (sizes (compute-sizes (cons titles data)))
240                (total-size (+ (apply #'+ sizes) (* 2 (1- (length titles)))))
241                (control-string (format nil "~~&~~{~{~~~AA  ~}~~}" sizes)))
242           (print-separator total-size)
243           (format t control-string titles)
244           (print-separator total-size)
245           (dolist (d data) (format t control-string d))
246           (print-separator total-size))))
247     (values)))
248
249 (defun create-database (connection-spec &key database-type)
250   (when (stringp connection-spec)
251     (setq connection-spec (string-to-list-connection-spec connection-spec)))
252   (database-create connection-spec database-type))
253
254 (defun probe-database (connection-spec &key database-type)
255   (when (stringp connection-spec)
256     (setq connection-spec (string-to-list-connection-spec connection-spec)))
257   (database-probe connection-spec database-type))
258
259 (defun destroy-database (connection-spec &key database-type)
260   (when (stringp connection-spec)
261     (setq connection-spec (string-to-list-connection-spec connection-spec)))
262   (database-destroy connection-spec database-type))
263
264 (defun list-databases (connection-spec &key database-type)
265   (when (stringp connection-spec)
266     (setq connection-spec (string-to-list-connection-spec connection-spec)))
267   (database-list connection-spec database-type))
268
269 (defmacro with-database ((db-var connection-spec &rest connect-args) &body body)
270   "Evaluate the body in an environment, where `db-var' is bound to the
271 database connection given by `connection-spec' and `connect-args'.
272 The connection is automatically closed or released to the pool on exit from the body."
273   (let ((result (gensym "result-")))
274     (unless db-var (setf db-var '*default-database*))
275     `(let ((,db-var (connect ,connection-spec ,@connect-args))
276            (,result nil))
277       (unwind-protect
278            (let ((,db-var ,db-var))
279              (setf ,result (progn ,@body)))
280         (disconnect :database ,db-var))
281       ,result)))
282
283
284 (defmacro with-default-database ((database) &rest body)
285   "Perform BODY with DATABASE bound as *default-database*."
286   `(progv '(*default-database*)
287        (list ,database)
288      ,@body))
289