r1697: *** empty log message ***
[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.9 2002/03/29 08:12:16 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 (defun reload-database-types ()
39   "Reloads any foreign code for the loaded database types after a dump."
40   (mapc #'database-type-load-foreign *loaded-database-types*))
41
42
43 (defvar *default-database-type* nil
44   "Specifies the default type of database.  Currently only :mysql is
45 supported.")
46
47 (defvar *initialized-database-types* nil
48   "Contains a list of database types which have been initialized by calls
49 to initialize-database-type.")
50
51 (defun initialize-database-type (&key (database-type *default-database-type*))
52   "Initialize the given database-type, if it is not already
53 initialized, as indicated by `*initialized-database-types*'."
54   (if (member database-type *initialized-database-types*)
55       t
56       (when (database-initialize-database-type database-type)
57         (push database-type *initialized-database-types*)
58         t)))
59
60
61 ;;; Database handling
62
63 (defvar *connect-if-exists* :error
64   "Default value for the if-exists parameter of connect calls.")
65
66 (defvar *connected-databases* nil
67   "List of active database objects.")
68
69 (defun connected-databases ()
70   "Return the list of active database objects."
71   *connected-databases*)
72
73 (defvar *default-database* nil
74   "Specifies the default database to be used.")
75
76
77
78 (defun find-database (database &optional (errorp t))
79   (etypecase database
80     (database
81      ;; Return the database object itself
82      database)
83     (string
84      (or (find database (connected-databases)
85                :key #'database-name
86                :test #'string=)
87          (when errorp
88            (cerror "Return nil."
89                    'clsql-simple-error
90                    :format-control "There exists no database called ~A."
91                    :format-arguments (list database)))))))
92
93 (defun connect (connection-spec
94                 &key (if-exists *connect-if-exists*)
95                 (database-type *default-database-type*))
96   "Connects to a database of the given database-type, using the type-specific
97 connection-spec.  if-exists is currently ignored."
98   (let* ((db-name (database-name-from-spec connection-spec database-type))
99          (old-db (find-database db-name nil))
100          (result nil))
101     (if old-db
102         (case if-exists
103           (:new
104            (setq result
105                  (database-connect connection-spec database-type)))
106           (:warn-new
107            (setq result
108                  (database-connect connection-spec database-type))
109            (warn 'clsql-exists-warning :old-db old-db :new-db result))
110           (:error
111            (restart-case
112                (error 'clsql-exists-error :old-db old-db)
113              (create-new ()
114                :report "Create a new connection."
115                (setq result
116                      (database-connect connection-spec database-type)))
117              (use-old ()
118                :report "Use the existing connection."
119                (setq result old-db))))
120           (:warn-old
121            (setq result old-db)
122            (warn 'clsql-exists-warning :old-db old-db :new-db old-db))
123           (:old
124            (setq result old-db)))
125         (setq result
126               (database-connect connection-spec database-type)))
127     (when result
128       (pushnew result *connected-databases*)
129       (setq *default-database* result)
130       result)))
131
132
133
134 (defun disconnect (&key (database *default-database*))
135   "Closes the connection to database. Resets *default-database* if that
136 database was disconnected and only one other connection exists."
137   (when (database-disconnect database)
138     (setq *connected-databases* (delete database *connected-databases*))
139     (when (eq database *default-database*)
140       (setq *default-database* (car *connected-databases*)))
141     (change-class database 'closed-database)
142     t))
143
144
145
146 ;;; Basic operations on databases
147
148 (defmethod query (query-expression &key (database *default-database*)  
149                   types)
150   "Execute the SQL query expression query-expression on the given database.
151 Returns a list of lists of values of the result of that expression."
152   (database-query query-expression database types))
153
154
155
156 (defmethod execute-command (sql-expression &key (database *default-database*))
157   "Execute the SQL command expression sql-expression on the given database.
158 Returns true on success or nil on failure."
159   (database-execute-command sql-expression database))
160
161
162
163 (defun map-query (output-type-spec function query-expression
164                   &key (database *default-database*)
165                   (types nil))
166   "Map the function over all tuples that are returned by the query in
167 query-expression.  The results of the function are collected as
168 specified in output-type-spec and returned like in MAP."
169   ;; DANGER Will Robinson: Parts of the code for implementing
170   ;; map-query (including the code below and the helper functions
171   ;; called) are highly CMU CL specific.
172   ;; KMR -- these have been replaced with cross-platform instructions above
173   (macrolet ((type-specifier-atom (type)
174                `(if (atom ,type) ,type (car ,type))))
175     (case (type-specifier-atom output-type-spec)
176       ((nil) 
177        (map-query-for-effect function query-expression database types))
178       (list 
179        (map-query-to-list function query-expression database types))
180       ((simple-vector simple-string vector string array simple-array
181         bit-vector simple-bit-vector base-string
182         simple-base-string)
183        (map-query-to-simple output-type-spec function query-expression database types))
184       (t
185        (funcall #'map-query (cmucl-compat:result-type-or-lose output-type-spec t)
186               function query-expression :database database :types types)))))
187
188 (defun map-query-for-effect (function query-expression database types)
189   (multiple-value-bind (result-set columns)
190       (database-query-result-set query-expression database :full-set nil
191                                  :types types)
192     (when result-set
193       (unwind-protect
194            (do ((row (make-list columns)))
195                ((not (database-store-next-row result-set database row))
196                 nil)
197              (apply function row))
198         (database-dump-result-set result-set database)))))
199                      
200 (defun map-query-to-list (function query-expression database types)
201   (multiple-value-bind (result-set columns)
202       (database-query-result-set query-expression database :full-set nil
203                                  :types types)
204     (when result-set
205       (unwind-protect
206            (let ((result (list nil)))
207              (do ((row (make-list columns))
208                   (current-cons result (cdr current-cons)))
209                  ((not (database-store-next-row result-set database row))
210                   (cdr result))
211                (rplacd current-cons (list (apply function row)))))
212         (database-dump-result-set result-set database)))))
213
214
215 (defun map-query-to-simple (output-type-spec function query-expression database types)
216   (multiple-value-bind (result-set columns rows)
217       (database-query-result-set query-expression database :full-set t
218                                  :types types)
219     (when result-set
220       (unwind-protect
221            (if rows
222                ;; We know the row count in advance, so we allocate once
223                (do ((result
224                      (cmucl-compat:make-sequence-of-type output-type-spec rows))
225                     (row (make-list columns))
226                     (index 0 (1+ index)))
227                    ((not (database-store-next-row result-set database row))
228                     result)
229                  (declare (fixnum index))
230                  (setf (aref result index)
231                        (apply function row)))
232                ;; Database can't report row count in advance, so we have
233                ;; to grow and shrink our vector dynamically
234                (do ((result
235                      (cmucl-compat:make-sequence-of-type output-type-spec 100))
236                     (allocated-length 100)
237                     (row (make-list columns))
238                     (index 0 (1+ index)))
239                    ((not (database-store-next-row result-set database row))
240                     (cmucl-compat:shrink-vector result index))
241                  (declare (fixnum allocated-length index))
242                  (when (>= index allocated-length)
243                    (setq allocated-length (* allocated-length 2)
244                          result (adjust-array result allocated-length)))
245                  (setf (aref result index)
246                        (apply function row))))
247         (database-dump-result-set result-set database)))))
248
249 (defmacro do-query (((&rest args) query-expression
250                      &key (database '*default-database*)
251                      (types nil))
252                     &body body)
253   (let ((result-set (gensym))
254         (columns (gensym))
255         (row (gensym))
256         (db (gensym)))
257     `(let ((,db ,database))
258        (multiple-value-bind (,result-set ,columns)
259            (database-query-result-set ,query-expression ,db
260                                       :full-set nil :types ,types)
261          (when ,result-set
262            (unwind-protect
263                 (do ((,row (make-list ,columns)))
264                     ((not (database-store-next-row ,result-set ,db ,row))
265                      nil)
266                   (destructuring-bind ,args ,row
267                     ,@body))
268              (database-dump-result-set ,result-set ,db)))))))
269
270
271