0397bd031ca01984702a667bd031bba537fd824c
[clsql.git] / sql / sql.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; $Id$
5 ;;;;
6 ;;;; The CLSQL Functional Data Manipulation Language (FDML). 
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)
16   
17 ;;; Basic operations on databases
18
19 (defmethod database-query-result-set ((expr %sql-expression) database
20                                       &key full-set result-types)
21   (database-query-result-set (sql-output expr database) database
22                              :full-set full-set :result-types result-types))
23
24 (defmethod execute-command ((expr %sql-expression)
25                             &key (database *default-database*))
26   (execute-command (sql-output expr database) :database database)
27   (values))
28
29
30 (defmethod query ((expr %sql-expression) &key (database *default-database*)
31                   (result-types :auto) (flatp nil) (field-names t))
32   (query (sql-output expr database) :database database :flatp flatp
33          :result-types result-types :field-names field-names))
34
35 (defmethod query ((expr sql-object-query) &key (database *default-database*)
36                                                (result-types :auto) (flatp nil))
37   (declare (ignore result-types))
38   (apply #'select (append (slot-value expr 'objects)
39                           (slot-value expr 'exp) 
40                           (when (slot-value expr 'refresh) 
41                             (list :refresh (sql-output expr database)))
42                           (when (or flatp (slot-value expr 'flatp) )
43                             (list :flatp t))
44                           (list :database database))))
45
46 (defun truncate-database (&key (database *default-database*))
47   (unless (typep database 'database)
48     (clsql-base::signal-no-database-error database))
49   (unless (is-database-open database)
50     (database-reconnect database))
51   (when (db-type-has-views? (database-underlying-type database))
52     (dolist (view (list-views :database database))
53       (drop-view view :database database)))
54   (dolist (table (list-tables :database database))
55     (drop-table table :database database))
56   (dolist (index (list-indexes :database database))
57     (drop-index index :database database))
58   (dolist (seq (list-sequences :database database))
59     (drop-sequence seq :database database)))
60
61 (defun print-query (query-exp &key titles (formats t) (sizes t) (stream t)
62                               (database *default-database*))
63   "The PRINT-QUERY function takes a symbolic SQL query expression and
64 formatting information and prints onto STREAM a table containing the
65 results of the query. A list of strings to use as column headings is
66 given by TITLES, which has a default value of NIL. The FORMATS
67 argument is a list of format strings used to print each attribute, and
68 has a default value of T, which means that ~A or ~VA are used if sizes
69 are provided or computed. The field sizes are given by SIZES. It has a
70 default value of T, which specifies that minimum sizes are
71 computed. The output stream is given by STREAM, which has a default
72 value of T. This specifies that *STANDARD-OUTPUT* is used."
73   (flet ((compute-sizes (data)
74            (mapcar #'(lambda (x) (apply #'max (mapcar #'length x)))
75                    (apply #'mapcar (cons #'list data))))
76          (format-record (record control sizes)
77            (format stream "~&~?" control
78                    (if (null sizes) record
79                        (mapcan #'(lambda (s f) (list s f)) sizes record)))))
80     (let* ((query-exp (etypecase query-exp
81                         (string query-exp)
82                         (sql-query (sql-output query-exp database))))
83            (data (query query-exp :database database))
84            (sizes (if (or (null sizes) (listp sizes)) sizes 
85                       (compute-sizes (if titles (cons titles data) data))))
86            (formats (if (or (null formats) (not (listp formats)))
87                         (make-list (length (car data)) :initial-element
88                                    (if (null sizes) "~A " "~VA "))
89                         formats))
90            (control-string (format nil "~{~A~}" formats)))
91       (when titles (format-record titles control-string sizes))
92       (dolist (d data (values)) (format-record d control-string sizes)))))
93
94 (defun insert-records (&key (into nil)
95                             (attributes nil)
96                             (values nil)
97                             (av-pairs nil)
98                             (query nil)
99                             (database *default-database*))
100   "Inserts a set of values into a table. The records created contain
101 values for attributes (or av-pairs). The argument VALUES is a list of
102 values. If ATTRIBUTES is supplied then VALUES must be a corresponding
103 list of values for each of the listed attribute names. If AV-PAIRS is
104 non-nil, then both ATTRIBUTES and VALUES must be nil. If QUERY is
105 non-nil, then neither VALUES nor AV-PAIRS should be. QUERY should be a
106 query expression, and the attribute names in it must also exist in the
107 table INTO. The default value of DATABASE is *DEFAULT-DATABASE*."
108   (let ((stmt (make-sql-insert :into into :attrs attributes
109                                :vals values :av-pairs av-pairs
110                                :subquery query)))
111     (execute-command stmt :database database)))
112
113 (defun make-sql-insert (&key (into nil)
114                             (attrs nil)
115                             (vals nil)
116                             (av-pairs nil)
117                             (subquery nil))
118   (unless into
119       (error 'clsql-sql-syntax-error :reason ":into keyword not supplied"))
120   (let ((insert (make-instance 'sql-insert :into into)))
121     (with-slots (attributes values query)
122       insert
123       (cond ((and vals (not attrs) (not query) (not av-pairs))
124              (setf values vals))
125             ((and vals attrs (not subquery) (not av-pairs))
126              (setf attributes attrs)
127              (setf values vals))
128             ((and av-pairs (not vals) (not attrs) (not subquery))
129              (setf attributes (mapcar #'car av-pairs))
130              (setf values (mapcar #'cadr av-pairs)))
131             ((and subquery (not vals) (not attrs) (not av-pairs))
132              (setf query subquery))
133             ((and subquery attrs (not vals) (not av-pairs))
134              (setf attributes attrs)
135              (setf query subquery))
136             (t
137              (error 'clsql-sql-syntax-error
138                     :reason "bad or ambiguous keyword combination.")))
139       insert)))
140     
141 (defun delete-records (&key (from nil)
142                             (where nil)
143                             (database *default-database*))
144   "Deletes rows from a database table specified by FROM in which the
145 WHERE condition is true. The argument DATABASE specifies a database
146 from which the records are to be removed, and defaults to
147 *default-database*."
148   (let ((stmt (make-instance 'sql-delete :from from :where where)))
149     (execute-command stmt :database database)))
150
151 (defun update-records (table &key (attributes nil)
152                             (values nil)
153                             (av-pairs nil)
154                             (where nil)
155                             (database *default-database*))
156   "Changes the values of existing fields in TABLE with columns
157 specified by ATTRIBUTES and VALUES (or AV-PAIRS) where the WHERE
158 condition is true."
159   (when av-pairs
160     (setf attributes (mapcar #'car av-pairs)
161           values (mapcar #'cadr av-pairs)))
162   (let ((stmt (make-instance 'sql-update :table table
163                              :attributes attributes
164                              :values values
165                              :where where)))
166     (execute-command stmt :database database)))
167
168
169 ;; iteration 
170
171 ;; output-sql
172
173 (defmethod database-output-sql ((str string) database)
174   (declare (ignore database)
175            (optimize (speed 3) (safety 1) #+cmu (extensions:inhibit-warnings 3))
176            (type (simple-array * (*)) str))
177   (let ((len (length str)))
178     (declare (type fixnum len))
179     (cond ((= len 0)
180            +empty-string+)
181           ((and (null (position #\' str))
182                 (null (position #\\ str)))
183            (concatenate 'string "'" str "'"))
184           (t
185            (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
186              (do* ((i 0 (incf i))
187                    (j 1 (incf j)))
188                   ((= i len) (subseq buf 0 (1+ j)))
189                (declare (type integer i j))
190                (let ((char (aref str i)))
191                  (cond ((eql char #\')
192                         (setf (aref buf j) #\\)
193                         (incf j)
194                         (setf (aref buf j) #\'))
195                        ((eql char #\\)
196                         (setf (aref buf j) #\\)
197                         (incf j)
198                         (setf (aref buf j) #\\))
199                        (t
200                         (setf (aref buf j) char))))))))))
201
202 (let ((keyword-package (symbol-package :foo)))
203   (defmethod database-output-sql ((sym symbol) database)
204     (convert-to-db-default-case
205      (if (equal (symbol-package sym) keyword-package)
206          (concatenate 'string "'" (string sym) "'")
207          (symbol-name sym))
208      database)))
209
210 (defmethod database-output-sql ((tee (eql t)) database)
211   (declare (ignore database))
212   "'Y'")
213
214 (defmethod database-output-sql ((num number) database)
215   (declare (ignore database))
216   (princ-to-string num))
217
218 (defmethod database-output-sql ((arg list) database)
219   (if (null arg)
220       "NULL"
221       (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
222                                             (sql-output val database))
223                                         arg))))
224
225 (defmethod database-output-sql ((arg vector) database)
226   (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
227                                          (sql-output val database))
228                                arg)))
229
230 (defmethod database-output-sql ((self wall-time) database)
231   (declare (ignore database))
232   (db-timestring self))
233
234 (defmethod database-output-sql ((self duration) database)
235   (declare (ignore database))
236   (format nil "'~a'" (duration-timestring self)))
237
238 (defmethod database-output-sql (thing database)
239   (if (or (null thing)
240           (eq 'null thing))
241       "NULL"
242     (error 'clsql-simple-error
243            :format-control
244            "No type conversion to SQL for ~A is defined for DB ~A."
245            :format-arguments (list (type-of thing) (type-of database)))))
246
247
248 (defmethod output-sql-hash-key ((arg vector) database)
249   (list 'vector (map 'list (lambda (arg)
250                              (or (output-sql-hash-key arg database)
251                                  (return-from output-sql-hash-key nil)))
252                      arg)))
253
254 (defmethod output-sql (expr database)
255   (write-string (database-output-sql expr database) *sql-stream*)
256   (values))
257
258 (defmethod output-sql ((expr list) database)
259   (if (null expr)
260       (write-string +null-string+ *sql-stream*)
261       (progn
262         (write-char #\( *sql-stream*)
263         (do ((item expr (cdr item)))
264             ((null (cdr item))
265              (output-sql (car item) database))
266           (output-sql (car item) database)
267           (write-char #\, *sql-stream*))
268         (write-char #\) *sql-stream*)))
269   t)
270
271 (defmethod describe-table ((table sql-create-table)
272                            &key (database *default-database*))
273   (database-describe-table
274    database
275    (convert-to-db-default-case 
276     (symbol-name (slot-value table 'name)) database)))
277
278 #+nil
279 (defmethod add-storage-class ((self database) (class symbol) &key (sequence t))
280   (let ((tablename (view-table (find-class class))))
281     (unless (tablep tablename)
282       (create-view-from-class class)
283       (when sequence
284         (create-sequence-from-class class)))))
285  
286 ;;; Iteration
287
288
289 (defmacro do-query (((&rest args) query-expression
290                      &key (database '*default-database*) (result-types :auto))
291                     &body body)
292   "Repeatedly executes BODY within a binding of ARGS on the
293 attributes of each record resulting from QUERY-EXPRESSION. The
294 return value is determined by the result of executing BODY. The
295 default value of DATABASE is *DEFAULT-DATABASE*."
296   (let ((result-set (gensym "RESULT-SET-"))
297         (qe (gensym "QUERY-EXPRESSION-"))
298         (columns (gensym "COLUMNS-"))
299         (row (gensym "ROW-"))
300         (db (gensym "DB-")))
301     `(let ((,qe ,query-expression))
302       (typecase ,qe
303         (sql-object-query
304          (dolist (,row (query ,qe))
305            (destructuring-bind ,args 
306                ,row
307              ,@body)))
308         (t
309          ;; Functional query 
310          (let ((,db ,database))
311            (multiple-value-bind (,result-set ,columns)
312                (database-query-result-set ,qe ,db
313                                           :full-set nil 
314                                           :result-types ,result-types)
315              (when ,result-set
316                (unwind-protect
317                     (do ((,row (make-list ,columns)))
318                         ((not (database-store-next-row ,result-set ,db ,row))
319                          nil)
320                       (destructuring-bind ,args ,row
321                         ,@body))
322                  (database-dump-result-set ,result-set ,db))))))))))
323
324 (defun map-query (output-type-spec function query-expression
325                   &key (database *default-database*)
326                   (result-types :auto))
327   "Map the function over all tuples that are returned by the
328 query in QUERY-EXPRESSION. The results of the function are
329 collected as specified in OUTPUT-TYPE-SPEC and returned like in
330 MAP."
331   (typecase query-expression
332     (sql-object-query
333      (map output-type-spec #'(lambda (x) (apply function x))
334           (query query-expression)))
335     (t
336      ;; Functional query 
337      (macrolet ((type-specifier-atom (type)
338                   `(if (atom ,type) ,type (car ,type))))
339        (case (type-specifier-atom output-type-spec)
340          ((nil) 
341           (map-query-for-effect function query-expression database 
342                                 result-types))
343          (list 
344           (map-query-to-list function query-expression database result-types))
345          ((simple-vector simple-string vector string array simple-array
346                          bit-vector simple-bit-vector base-string
347                          simple-base-string)
348           (map-query-to-simple output-type-spec function query-expression 
349                                database result-types))
350          (t
351           (funcall #'map-query 
352                    (cmucl-compat:result-type-or-lose output-type-spec t)
353                    function query-expression :database database 
354                    :result-types result-types)))))))
355   
356 (defun map-query-for-effect (function query-expression database result-types)
357   (multiple-value-bind (result-set columns)
358       (database-query-result-set query-expression database :full-set nil
359                                  :result-types result-types)
360     (when result-set
361       (unwind-protect
362            (do ((row (make-list columns)))
363                ((not (database-store-next-row result-set database row))
364                 nil)
365              (apply function row))
366         (database-dump-result-set result-set database)))))
367                      
368 (defun map-query-to-list (function query-expression database result-types)
369   (multiple-value-bind (result-set columns)
370       (database-query-result-set query-expression database :full-set nil
371                                  :result-types result-types)
372     (when result-set
373       (unwind-protect
374            (let ((result (list nil)))
375              (do ((row (make-list columns))
376                   (current-cons result (cdr current-cons)))
377                  ((not (database-store-next-row result-set database row))
378                   (cdr result))
379                (rplacd current-cons (list (apply function row)))))
380         (database-dump-result-set result-set database)))))
381
382
383 (defun map-query-to-simple (output-type-spec function query-expression database result-types)
384   (multiple-value-bind (result-set columns rows)
385       (database-query-result-set query-expression database :full-set t
386                                  :result-types result-types)
387     (when result-set
388       (unwind-protect
389            (if rows
390                ;; We know the row count in advance, so we allocate once
391                (do ((result
392                      (cmucl-compat:make-sequence-of-type output-type-spec rows))
393                     (row (make-list columns))
394                     (index 0 (1+ index)))
395                    ((not (database-store-next-row result-set database row))
396                     result)
397                  (declare (fixnum index))
398                  (setf (aref result index)
399                        (apply function row)))
400                ;; Database can't report row count in advance, so we have
401                ;; to grow and shrink our vector dynamically
402                (do ((result
403                      (cmucl-compat:make-sequence-of-type output-type-spec 100))
404                     (allocated-length 100)
405                     (row (make-list columns))
406                     (index 0 (1+ index)))
407                    ((not (database-store-next-row result-set database row))
408                     (cmucl-compat:shrink-vector result index))
409                  (declare (fixnum allocated-length index))
410                  (when (>= index allocated-length)
411                    (setq allocated-length (* allocated-length 2)
412                          result (adjust-array result allocated-length)))
413                  (setf (aref result index)
414                        (apply function row))))
415         (database-dump-result-set result-set database)))))