r8859: package renaming
[clsql.git] / base / database.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; $Id: $
5
6 (in-package #:clsql-base-sys)
7
8 (setf (documentation 'database-name 'function)
9       "Returns the name of a database.")
10
11 ;;; Database handling
12
13 (defvar *connect-if-exists* :error
14   "Default value for the if-exists parameter of connect calls.")
15
16 (defvar *connected-databases* nil
17   "List of active database objects.")
18
19 (defun connected-databases ()
20   "Return the list of active database objects."
21   *connected-databases*)
22
23 (defvar *default-database* nil
24   "Specifies the default database to be used.")
25
26 (defun find-database (database &key (errorp t) (db-type nil))
27   "The function FIND-DATABASE, given a string DATABASE, searches
28 amongst the connected databases for one matching the name DATABASE. If
29 there is exactly one such database, it is returned and the second
30 return value count is 1. If more than one databases match and ERRORP
31 is nil, then the most recently connected of the matching databases is
32 returned and count is the number of matches. If no matching database
33 is found and ERRORP is nil, then nil is returned. If none, or more
34 than one, matching databases are found and ERRORP is true, then an
35 error is signalled. If the argument database is a database, it is
36 simply returned."
37   (etypecase database
38     (database
39      (values database 1))
40     (string
41      (let* ((matches (remove-if 
42                       #'(lambda (db)
43                           (not (and (string= (database-name db) database)
44                                     (if db-type
45                                         (equal (database-type db) db-type)
46                                         t))))
47                       (connected-databases)))
48             (count (length matches)))
49        (if (or (not errorp) (= count 1))
50            (values (car matches) count)
51            (cerror "Return nil."
52                    'clsql-simple-error
53                    :format-control "There exists ~A database called ~A."
54                    :format-arguments
55                    (list (if (zerop count) "no" "more than one")
56                          database)))))))
57
58
59 (defun connect (connection-spec
60                 &key (if-exists *connect-if-exists*)
61                 (make-default t)
62                 (pool nil)
63                 (database-type *default-database-type*))
64   "Connects to a database of the given database-type, using the
65 type-specific connection-spec.  The value of if-exists determines what
66 happens if a connection to that database is already established.  A
67 value of :new means create a new connection.  A value of :warn-new
68 means warn the user and create a new connect.  A value of :warn-old
69 means warn the user and use the old connection.  A value of :error
70 means fail, notifying the user.  A value of :old means return the old
71 connection.  If make-default is true, then *default-database* is set
72 to the new connection, otherwise *default-database is not changed. If
73 pool is t the connection will be taken from the general pool, if pool
74 is a conn-pool object the connection will be taken from this pool."
75   (if pool
76       (acquire-from-pool connection-spec database-type pool)
77       (let* ((db-name (database-name-from-spec connection-spec database-type))
78              (old-db (unless (eq if-exists :new)
79                        (find-database db-name :db-type database-type
80                                       :errorp nil)))
81              (result nil))
82         (if old-db
83             (ecase if-exists
84               (:warn-new
85                (setq result
86                      (database-connect connection-spec database-type))
87                (warn 'clsql-exists-warning :old-db old-db :new-db result))
88               (:error
89                (restart-case
90                    (error 'clsql-exists-error :old-db old-db)
91                  (create-new ()
92                    :report "Create a new connection."
93                    (setq result
94                          (database-connect connection-spec database-type)))
95                  (use-old ()
96                    :report "Use the existing connection."
97                    (setq result old-db))))
98               (:warn-old
99                (setq result old-db)
100                (warn 'clsql-exists-warning :old-db old-db :new-db old-db))
101               (:old
102                (setq result old-db)))
103             (setq result
104                   (database-connect connection-spec database-type)))
105         (when result
106           (pushnew result *connected-databases*)
107           (when make-default (setq *default-database* result))
108           result))))
109
110
111 (defun disconnect (&key (database *default-database*) (error nil))
112
113   "Closes the connection to DATABASE and resets *default-database* if
114 that database was disconnected. If database is a database object, then
115 it is used directly. Otherwise, the list of connected databases is
116 searched to find one with DATABASE as its connection
117 specifications. If no such database is found, then if ERROR and
118 DATABASE are both non-nil an error is signaled, otherwise DISCONNECT
119 returns nil. If the database is from a pool it will be released to
120 this pool."
121   (let ((database (find-database database :errorp (and database error))))
122     (when database
123       (if (conn-pool database)
124           (when (release-to-pool database)
125             (setf *connected-databases* (delete database *connected-databases*))
126             (when (eq database *default-database*)
127               (setf *default-database* (car *connected-databases*)))
128             t)
129           (when (database-disconnect database)
130             (setf *connected-databases* (delete database *connected-databases*))
131             (when (eq database *default-database*)
132               (setf *default-database* (car *connected-databases*)))
133             (change-class database 'closed-database)
134             t)))))
135
136
137 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
138
139
140
141
142
143 (defun reconnect (&key (database *default-database*) (error nil) (force t))
144   "Reconnects DATABASE to its underlying RDBMS. If successful, returns
145 t and the variable *default-database* is set to the newly reconnected
146 database. The default value for DATABASE is *default-database*. If
147 DATABASE is a database object, then it is used directly. Otherwise,
148 the list of connected databases is searched to find one with database
149 as its connection specifications (see CONNECT). If no such database is
150 found, then if ERROR and DATABASE are both non-nil an error is
151 signaled, otherwise RECONNECT returns nil. FORCE controls whether an
152 error should be signaled if the existing database connection cannot be
153 closed. When non-nil (this is the default value) the connection is
154 closed without error checking. When FORCE is nil, an error is signaled
155 if the database connection has been lost."
156   ;; TODO: just a placeholder
157   (declare (ignore database error force)))
158
159
160   
161 (defun status (&optional full)
162   "The function STATUS prints status information to the standard
163 output, for the connected databases and initialized database types. If
164 full is T, detailed status information is printed. The default value
165 of full is NIL."
166   (declare (ignore full))
167   ;; TODO: table details if full is true?
168   (flet ((get-data ()
169            (let ((data '()))
170              (dolist (db (connected-databases) data)
171                (push (list (database-name db)
172                            (string (database-type db))
173                            (when (conn-pool db) "T" "NIL")
174                            (format nil "~A" (length (database-list-tables db)))
175                            (format nil "~A" (length (database-list-views db)))
176                            (if (equal db *default-database*) "   *" ""))
177                      data))))
178          (compute-sizes (data)
179            (mapcar #'(lambda (x) (apply #'max (mapcar #'length x)))
180                    (apply #'mapcar (cons #'list data))))
181          (print-separator (size)
182            (format t "~&~A" (make-string size :initial-element #\-))))
183     (let ((data (get-data)))
184       (when data
185         (let* ((titles (list "NAME" "TYPE" "POOLED" "TABLES" "VIEWS" "DEFAULT"))
186                (sizes (compute-sizes (cons titles data)))
187                (total-size (+ (apply #'+ sizes) (* 2 (1- (length titles)))))
188                (control-string (format nil "~~&~~{~{~~~AA  ~}~~}" sizes)))
189           (print-separator total-size)
190           (format t control-string titles)
191           (print-separator total-size)
192           (dolist (d data) (format t control-string d))
193           (print-separator total-size))))
194     (values)))
195
196
197 (defmacro with-database ((db-var connection-spec &rest connect-args) &body body)
198   "Evaluate the body in an environment, where `db-var' is bound to the
199 database connection given by `connection-spec' and `connect-args'.
200 The connection is automatically closed or released to the pool on exit from the body."
201   (let ((result (gensym "result-")))
202     (unless db-var (setf db-var '*default-database*))
203     `(let ((,db-var (connect ,connection-spec ,@connect-args))
204            (,result nil))
205       (unwind-protect
206            (let ((,db-var ,db-var))
207              (setf ,result (progn ,@body)))
208         (disconnect :database ,db-var))
209       ,result)))
210
211
212 (defmacro with-default-database ((database) &rest body)
213   "Perform BODY with DATABASE bound as *default-database*."
214   `(progv '(*default-database*)
215        (list ,database)
216      ,@body))