r1798: Initial support for pooled connections
[clsql.git] / sql / sql.cl
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          sql.cl
6 ;;;; Purpose:       High-level SQL interface
7 ;;;; Programmers:   Kevin M. Rosenberg based on
8 ;;;;                 Original code by Pierre R. Mai 
9 ;;;; Date Started:  Feb 2002
10 ;;;;
11 ;;;; $Id: sql.cl,v 1.13 2002/04/27 20:58:11 kevin Exp $
12 ;;;;
13 ;;;; This file, part of CLSQL, is Copyright (c) 2002 by Kevin M. Rosenberg
14 ;;;; and Copyright (c) 1999-2001 by Pierre R. Mai
15 ;;;;
16 ;;;; CLSQL users are granted the rights to distribute and use this software
17 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
18 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
19 ;;;; *************************************************************************
20
21 (declaim (optimize (debug 3) (speed 3) (safety 1) (compilation-speed 0)))
22 (in-package :clsql-sys)
23
24 ;;; Modified by KMR 
25 ;;; - to use CMUCL-COMPAT library 
26 ;;; - fix format strings in error messages 
27 ;;; - use field types
28
29
30 ;;; Simple implementation of SQL along the lines of Harlequin's Common SQL
31
32
33 ;;; Database Types
34
35 (defvar *loaded-database-types* nil
36   "Contains a list of database types which have been defined/loaded.")
37
38 (defmethod database-type-load-foreign :after (database-type)
39   (when (database-type-library-loaded database-type)
40      (pushnew database-type *loaded-database-types*)))
41
42 (defun reload-database-types ()
43   "Reloads any foreign code for the loaded database types after a dump."
44   (mapc #'database-type-load-foreign *loaded-database-types*))
45
46 (defvar *default-database-type* nil
47   "Specifies the default type of database.  Currently only :mysql is
48 supported.")
49
50 (defvar *initialized-database-types* nil
51   "Contains a list of database types which have been initialized by calls
52 to initialize-database-type.")
53
54 (defun initialize-database-type (&key (database-type *default-database-type*))
55   "Initialize the given database-type, if it is not already
56 initialized, as indicated by `*initialized-database-types*'."
57   (if (member database-type *initialized-database-types*)
58       t
59       (when (database-initialize-database-type database-type)
60         (push database-type *initialized-database-types*)
61         t)))
62
63
64 ;;; Database handling
65
66 (defvar *connect-if-exists* :error
67   "Default value for the if-exists parameter of connect calls.")
68
69 (defvar *connected-databases* nil
70   "List of active database objects.")
71
72 (defun connected-databases ()
73   "Return the list of active database objects."
74   *connected-databases*)
75
76 (defvar *default-database* nil
77   "Specifies the default database to be used.")
78
79
80
81 (defun find-database (database &optional (errorp t))
82   (etypecase database
83     (database
84      ;; Return the database object itself
85      database)
86     (string
87      (or (find database (connected-databases)
88                :key #'database-name
89                :test #'string=)
90          (when errorp
91            (cerror "Return nil."
92                    'clsql-simple-error
93                    :format-control "There exists no database called ~A."
94                    :format-arguments (list database)))))))
95
96 (defun connect (connection-spec
97                 &key (if-exists *connect-if-exists*)
98                 (database-type *default-database-type*)
99                 (pool nil))
100   "Connects to a database of the given database-type, using the type-specific
101 connection-spec.  if-exists is currently ignored."
102   (let* ((db-name (database-name-from-spec connection-spec database-type))
103          (old-db (find-database db-name nil))
104          (result nil))
105     (if pool
106         (setq result (acquire-from-pool connection-spec database-type))
107       (if old-db
108           (case if-exists
109             (:new
110              (setq result
111                (database-connect connection-spec database-type)))
112             (:warn-new
113              (setq result
114                (database-connect connection-spec database-type))
115              (warn 'clsql-exists-warning :old-db old-db :new-db result))
116             (:error
117              (restart-case
118                  (error 'clsql-exists-error :old-db old-db)
119                (create-new ()
120                    :report "Create a new connection."
121                  (setq result
122                    (database-connect connection-spec database-type)))
123                (use-old ()
124                    :report "Use the existing connection."
125                  (setq result old-db))))
126             (:warn-old
127              (setq result old-db)
128              (warn 'clsql-exists-warning :old-db old-db :new-db old-db))
129             (:old
130              (setq result old-db)))
131         (setq result
132           (database-connect connection-spec database-type))))
133     (when result
134       (pushnew result *connected-databases*)
135       (setq *default-database* result)
136       result)))
137
138
139 (defun disconnect (&key (database *default-database*)
140                    (pool nil))
141   "Closes the connection to database. Resets *default-database* if that
142 database was disconnected and only one other connection exists."
143   (if pool
144       (release-to-pool database)
145     (when (database-disconnect database)
146       (setq *connected-databases* (delete database *connected-databases*))
147       (when (eq database *default-database*)
148         (setq *default-database* (car *connected-databases*)))
149       (change-class database 'closed-database)
150       t)))
151
152 ;;; Basic operations on databases
153
154 (defmethod query (query-expression &key (database *default-database*)  
155                   types)
156   "Execute the SQL query expression query-expression on the given database.
157 Returns a list of lists of values of the result of that expression."
158   (database-query query-expression database types))
159
160
161
162 (defmethod execute-command (sql-expression &key (database *default-database*))
163   "Execute the SQL command expression sql-expression on the given database.
164 Returns true on success or nil on failure."
165   (database-execute-command sql-expression database))
166
167
168
169 (defun map-query (output-type-spec function query-expression
170                   &key (database *default-database*)
171                   (types nil))
172   "Map the function over all tuples that are returned by the query in
173 query-expression.  The results of the function are collected as
174 specified in output-type-spec and returned like in MAP."
175   ;; DANGER Will Robinson: Parts of the code for implementing
176   ;; map-query (including the code below and the helper functions
177   ;; called) are highly CMU CL specific.
178   ;; KMR -- these have been replaced with cross-platform instructions above
179   (macrolet ((type-specifier-atom (type)
180                `(if (atom ,type) ,type (car ,type))))
181     (case (type-specifier-atom output-type-spec)
182       ((nil) 
183        (map-query-for-effect function query-expression database types))
184       (list 
185        (map-query-to-list function query-expression database types))
186       ((simple-vector simple-string vector string array simple-array
187         bit-vector simple-bit-vector base-string
188         simple-base-string)
189        (map-query-to-simple output-type-spec function query-expression database types))
190       (t
191        (funcall #'map-query (cmucl-compat:result-type-or-lose output-type-spec t)
192               function query-expression :database database :types types)))))
193
194 (defun map-query-for-effect (function query-expression database types)
195   (multiple-value-bind (result-set columns)
196       (database-query-result-set query-expression database :full-set nil
197                                  :types types)
198     (when result-set
199       (unwind-protect
200            (do ((row (make-list columns)))
201                ((not (database-store-next-row result-set database row))
202                 nil)
203              (apply function row))
204         (database-dump-result-set result-set database)))))
205                      
206 (defun map-query-to-list (function query-expression database types)
207   (multiple-value-bind (result-set columns)
208       (database-query-result-set query-expression database :full-set nil
209                                  :types types)
210     (when result-set
211       (unwind-protect
212            (let ((result (list nil)))
213              (do ((row (make-list columns))
214                   (current-cons result (cdr current-cons)))
215                  ((not (database-store-next-row result-set database row))
216                   (cdr result))
217                (rplacd current-cons (list (apply function row)))))
218         (database-dump-result-set result-set database)))))
219
220
221 (defun map-query-to-simple (output-type-spec function query-expression database types)
222   (multiple-value-bind (result-set columns rows)
223       (database-query-result-set query-expression database :full-set t
224                                  :types types)
225     (when result-set
226       (unwind-protect
227            (if rows
228                ;; We know the row count in advance, so we allocate once
229                (do ((result
230                      (cmucl-compat:make-sequence-of-type output-type-spec rows))
231                     (row (make-list columns))
232                     (index 0 (1+ index)))
233                    ((not (database-store-next-row result-set database row))
234                     result)
235                  (declare (fixnum index))
236                  (setf (aref result index)
237                        (apply function row)))
238                ;; Database can't report row count in advance, so we have
239                ;; to grow and shrink our vector dynamically
240                (do ((result
241                      (cmucl-compat:make-sequence-of-type output-type-spec 100))
242                     (allocated-length 100)
243                     (row (make-list columns))
244                     (index 0 (1+ index)))
245                    ((not (database-store-next-row result-set database row))
246                     (cmucl-compat:shrink-vector result index))
247                  (declare (fixnum allocated-length index))
248                  (when (>= index allocated-length)
249                    (setq allocated-length (* allocated-length 2)
250                          result (adjust-array result allocated-length)))
251                  (setf (aref result index)
252                        (apply function row))))
253         (database-dump-result-set result-set database)))))
254
255 (defmacro do-query (((&rest args) query-expression
256                      &key (database '*default-database*)
257                      (types nil))
258                     &body body)
259   (let ((result-set (gensym))
260         (columns (gensym))
261         (row (gensym))
262         (db (gensym)))
263     `(let ((,db ,database))
264        (multiple-value-bind (,result-set ,columns)
265            (database-query-result-set ,query-expression ,db
266                                       :full-set nil :types ,types)
267          (when ,result-set
268            (unwind-protect
269                 (do ((,row (make-list ,columns)))
270                     ((not (database-store-next-row ,result-set ,db ,row))
271                      nil)
272                   (destructuring-bind ,args ,row
273                     ,@body))
274              (database-dump-result-set ,result-set ,db)))))))
275
276 ;;; Marc Battyani : Large objects support
277
278 (defun create-large-object (&key (database *default-database*))
279   "Creates a new large object in the database and returns the object identifier"
280   (database-create-large-object database))
281
282 (defun write-large-object (object-id data &key (database *default-database*))
283   "Writes data to the large object"
284   (database-write-large-object object-id data database))
285
286 (defun read-large-object (object-id &key (database *default-database*))
287   "Reads the large object content"
288   (database-read-large-object object-id database))
289
290 (defun delete-large-object (object-id &key (database *default-database*))
291   "Deletes the large object in the database"
292   (database-delete-large-object object-id database))