r2006: debian
[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.16 2002/05/11 14:31:10 marc.battyani 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 (defun find-database (database &optional (errorp t))
80   (etypecase database
81     (database
82      ;; Return the database object itself
83      database)
84     (string
85      (or (find database (connected-databases)
86                :key #'database-name
87                :test #'string=)
88          (when errorp
89            (cerror "Return nil."
90                    'clsql-simple-error
91                    :format-control "There exists no database called ~A."
92                    :format-arguments (list database)))))))
93
94 (defun connect (connection-spec
95                 &key (if-exists *connect-if-exists*)
96                 (database-type *default-database-type*)
97                 (pool nil))
98   "Connects to a database of the given database-type, using the type-specific
99 connection-spec.  if-exists is currently ignored.
100 If pool is t the the connection will be taken from the general pool,
101 if pool is a conn-pool object the connection will be taken from this pool.
102 "
103   (if pool
104     (acquire-from-pool connection-spec database-type pool)
105     (let* ((db-name (database-name-from-spec connection-spec database-type))
106            (old-db (unless (eq if-exists :new) (find-database db-name nil)))
107            (result nil))
108       (if old-db
109         (case if-exists
110 ;           (:new
111 ;            (setq result
112 ;              (database-connect connection-spec database-type)))
113           (:warn-new
114            (setq result
115                  (database-connect connection-spec database-type))
116            (warn 'clsql-exists-warning :old-db old-db :new-db result))
117           (:error
118            (restart-case
119                  (error 'clsql-exists-error :old-db old-db)
120                (create-new ()
121                    :report "Create a new connection."
122                  (setq result
123                    (database-connect connection-spec database-type)))
124                (use-old ()
125                    :report "Use the existing connection."
126                  (setq result old-db))))
127           (:warn-old
128            (setq result old-db)
129            (warn 'clsql-exists-warning :old-db old-db :new-db old-db))
130           (:old
131            (setq result old-db)))
132         (setq result
133               (database-connect connection-spec database-type)))
134       (when result
135         (pushnew result *connected-databases*)
136         (setq *default-database* result)
137         result))))
138
139
140 (defun disconnect (&key (database *default-database*))
141   "Closes the connection to database. Resets *default-database* if that
142 database was disconnected and only one other connection exists.
143 if the database is from a pool it will be released to this pool."
144   (if (conn-pool database)
145       (release-to-pool database)
146     (when (database-disconnect database)
147       (setq *connected-databases* (delete database *connected-databases*))
148       (when (eq database *default-database*)
149         (setq *default-database* (car *connected-databases*)))
150       (change-class database 'closed-database)
151       t)))
152
153 ;;; Basic operations on databases
154
155 (defmethod query (query-expression &key (database *default-database*)  
156                   types)
157   "Execute the SQL query expression query-expression on the given database.
158 Returns a list of lists of values of the result of that expression."
159   (database-query query-expression database types))
160
161
162
163 (defmethod execute-command (sql-expression &key (database *default-database*))
164   "Execute the SQL command expression sql-expression on the given database.
165 Returns true on success or nil on failure."
166   (database-execute-command sql-expression database))
167
168
169
170 (defun map-query (output-type-spec function query-expression
171                   &key (database *default-database*)
172                   (types nil))
173   "Map the function over all tuples that are returned by the query in
174 query-expression.  The results of the function are collected as
175 specified in output-type-spec and returned like in MAP."
176   ;; DANGER Will Robinson: Parts of the code for implementing
177   ;; map-query (including the code below and the helper functions
178   ;; called) are highly CMU CL specific.
179   ;; KMR -- these have been replaced with cross-platform instructions above
180   (macrolet ((type-specifier-atom (type)
181                `(if (atom ,type) ,type (car ,type))))
182     (case (type-specifier-atom output-type-spec)
183       ((nil) 
184        (map-query-for-effect function query-expression database types))
185       (list 
186        (map-query-to-list function query-expression database types))
187       ((simple-vector simple-string vector string array simple-array
188         bit-vector simple-bit-vector base-string
189         simple-base-string)
190        (map-query-to-simple output-type-spec function query-expression database types))
191       (t
192        (funcall #'map-query (cmucl-compat:result-type-or-lose output-type-spec t)
193               function query-expression :database database :types types)))))
194
195 (defun map-query-for-effect (function query-expression database types)
196   (multiple-value-bind (result-set columns)
197       (database-query-result-set query-expression database :full-set nil
198                                  :types types)
199     (when result-set
200       (unwind-protect
201            (do ((row (make-list columns)))
202                ((not (database-store-next-row result-set database row))
203                 nil)
204              (apply function row))
205         (database-dump-result-set result-set database)))))
206                      
207 (defun map-query-to-list (function query-expression database types)
208   (multiple-value-bind (result-set columns)
209       (database-query-result-set query-expression database :full-set nil
210                                  :types types)
211     (when result-set
212       (unwind-protect
213            (let ((result (list nil)))
214              (do ((row (make-list columns))
215                   (current-cons result (cdr current-cons)))
216                  ((not (database-store-next-row result-set database row))
217                   (cdr result))
218                (rplacd current-cons (list (apply function row)))))
219         (database-dump-result-set result-set database)))))
220
221
222 (defun map-query-to-simple (output-type-spec function query-expression database types)
223   (multiple-value-bind (result-set columns rows)
224       (database-query-result-set query-expression database :full-set t
225                                  :types types)
226     (when result-set
227       (unwind-protect
228            (if rows
229                ;; We know the row count in advance, so we allocate once
230                (do ((result
231                      (cmucl-compat:make-sequence-of-type output-type-spec rows))
232                     (row (make-list columns))
233                     (index 0 (1+ index)))
234                    ((not (database-store-next-row result-set database row))
235                     result)
236                  (declare (fixnum index))
237                  (setf (aref result index)
238                        (apply function row)))
239                ;; Database can't report row count in advance, so we have
240                ;; to grow and shrink our vector dynamically
241                (do ((result
242                      (cmucl-compat:make-sequence-of-type output-type-spec 100))
243                     (allocated-length 100)
244                     (row (make-list columns))
245                     (index 0 (1+ index)))
246                    ((not (database-store-next-row result-set database row))
247                     (cmucl-compat:shrink-vector result index))
248                  (declare (fixnum allocated-length index))
249                  (when (>= index allocated-length)
250                    (setq allocated-length (* allocated-length 2)
251                          result (adjust-array result allocated-length)))
252                  (setf (aref result index)
253                        (apply function row))))
254         (database-dump-result-set result-set database)))))
255
256 (defmacro do-query (((&rest args) query-expression
257                      &key (database '*default-database*)
258                      (types nil))
259                     &body body)
260   (let ((result-set (gensym))
261         (columns (gensym))
262         (row (gensym))
263         (db (gensym)))
264     `(let ((,db ,database))
265        (multiple-value-bind (,result-set ,columns)
266            (database-query-result-set ,query-expression ,db
267                                       :full-set nil :types ,types)
268          (when ,result-set
269            (unwind-protect
270                 (do ((,row (make-list ,columns)))
271                     ((not (database-store-next-row ,result-set ,db ,row))
272                      nil)
273                   (destructuring-bind ,args ,row
274                     ,@body))
275              (database-dump-result-set ,result-set ,db)))))))
276
277 ;;; Marc Battyani : Large objects support
278
279 (defun create-large-object (&key (database *default-database*))
280   "Creates a new large object in the database and returns the object identifier"
281   (database-create-large-object database))
282
283 (defun write-large-object (object-id data &key (database *default-database*))
284   "Writes data to the large object"
285   (database-write-large-object object-id data database))
286
287 (defun read-large-object (object-id &key (database *default-database*))
288   "Reads the large object content"
289   (database-read-large-object object-id database))
290
291 (defun delete-large-object (object-id &key (database *default-database*))
292   "Deletes the large object in the database"
293   (database-delete-large-object object-id database))