79bf6cd037bc223b4086fa482df59275bb2d5b01
[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-sys)
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) (field-names t))
37   (declare (ignore result-types field-names))
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     (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) 
75                        (apply #'max (mapcar #'(lambda (y) 
76                                                 (if (null y) 3 (length y)))
77                                             x)))
78                    (apply #'mapcar (cons #'list data))))
79          (format-record (record control sizes)
80            (format stream "~&~?" control
81                    (if (null sizes) record
82                        (mapcan #'(lambda (s f) (list s f)) sizes record)))))
83     (let* ((query-exp (etypecase query-exp
84                         (string query-exp)
85                         (sql-query (sql-output query-exp database))))
86            (data (query query-exp :database database :result-types nil 
87                         :field-names nil))
88            (sizes (if (or (null sizes) (listp sizes)) sizes 
89                       (compute-sizes (if titles (cons titles data) data))))
90            (formats (if (or (null formats) (not (listp formats)))
91                         (make-list (length (car data)) :initial-element
92                                    (if (null sizes) "~A " "~VA "))
93                         formats))
94            (control-string (format nil "~{~A~}" formats)))
95       (when titles (format-record titles control-string sizes))
96       (dolist (d data (values)) (format-record d control-string sizes)))))
97
98 (defun insert-records (&key (into nil)
99                             (attributes nil)
100                             (values nil)
101                             (av-pairs nil)
102                             (query nil)
103                             (database *default-database*))
104   "Inserts a set of values into a table. The records created contain
105 values for attributes (or av-pairs). The argument VALUES is a list of
106 values. If ATTRIBUTES is supplied then VALUES must be a corresponding
107 list of values for each of the listed attribute names. If AV-PAIRS is
108 non-nil, then both ATTRIBUTES and VALUES must be nil. If QUERY is
109 non-nil, then neither VALUES nor AV-PAIRS should be. QUERY should be a
110 query expression, and the attribute names in it must also exist in the
111 table INTO. The default value of DATABASE is *DEFAULT-DATABASE*."
112   (let ((stmt (make-sql-insert :into into :attrs attributes
113                                :vals values :av-pairs av-pairs
114                                :subquery query)))
115     (execute-command stmt :database database)))
116
117 (defun make-sql-insert (&key (into nil)
118                             (attrs nil)
119                             (vals nil)
120                             (av-pairs nil)
121                             (subquery nil))
122   (unless into
123       (error 'sql-user-error :message ":into keyword not supplied"))
124   (let ((insert (make-instance 'sql-insert :into into)))
125     (with-slots (attributes values query)
126       insert
127       (cond ((and vals (not attrs) (not query) (not av-pairs))
128              (setf values vals))
129             ((and vals attrs (not subquery) (not av-pairs))
130              (setf attributes attrs)
131              (setf values vals))
132             ((and av-pairs (not vals) (not attrs) (not subquery))
133              (setf attributes (mapcar #'car av-pairs))
134              (setf values (mapcar #'cadr av-pairs)))
135             ((and subquery (not vals) (not attrs) (not av-pairs))
136              (setf query subquery))
137             ((and subquery attrs (not vals) (not av-pairs))
138              (setf attributes attrs)
139              (setf query subquery))
140             (t
141              (error 'sql-user-error
142                     :message "bad or ambiguous keyword combination.")))
143       insert)))
144     
145 (defun delete-records (&key (from nil)
146                             (where nil)
147                             (database *default-database*))
148   "Deletes rows from a database table specified by FROM in which the
149 WHERE condition is true. The argument DATABASE specifies a database
150 from which the records are to be removed, and defaults to
151 *default-database*."
152   (let ((stmt (make-instance 'sql-delete :from from :where where)))
153     (execute-command stmt :database database)))
154
155 (defun update-records (table &key (attributes nil)
156                             (values nil)
157                             (av-pairs nil)
158                             (where nil)
159                             (database *default-database*))
160   "Changes the values of existing fields in TABLE with columns
161 specified by ATTRIBUTES and VALUES (or AV-PAIRS) where the WHERE
162 condition is true."
163   (when av-pairs
164     (setf attributes (mapcar #'car av-pairs)
165           values (mapcar #'cadr av-pairs)))
166   (let ((stmt (make-instance 'sql-update :table table
167                              :attributes attributes
168                              :values values
169                              :where where)))
170     (execute-command stmt :database database)))
171
172
173 ;; iteration 
174
175 ;; output-sql
176
177 (defmethod database-output-sql ((str string) database)
178   (declare (ignore database)
179            (optimize (speed 3) (safety 1) #+cmu (extensions:inhibit-warnings 3))
180            (type (simple-array * (*)) str))
181   (let ((len (length str)))
182     (declare (type fixnum len))
183     (cond ((= len 0)
184            +empty-string+)
185           ((and (null (position #\' str))
186                 (null (position #\\ str)))
187            (concatenate 'string "'" str "'"))
188           (t
189            (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
190              (do* ((i 0 (incf i))
191                    (j 1 (incf j)))
192                   ((= i len) (subseq buf 0 (1+ j)))
193                (declare (type integer i j))
194                (let ((char (aref str i)))
195                  (cond ((eql char #\')
196                         (setf (aref buf j) #\\)
197                         (incf j)
198                         (setf (aref buf j) #\'))
199                        ((eql char #\\)
200                         (setf (aref buf j) #\\)
201                         (incf j)
202                         (setf (aref buf j) #\\))
203                        (t
204                         (setf (aref buf j) char))))))))))
205
206 (let ((keyword-package (symbol-package :foo)))
207   (defmethod database-output-sql ((sym symbol) database)
208     (convert-to-db-default-case
209      (if (equal (symbol-package sym) keyword-package)
210          (concatenate 'string "'" (string sym) "'")
211          (symbol-name sym))
212      database)))
213
214 (defmethod database-output-sql ((tee (eql t)) database)
215   (declare (ignore database))
216   "'Y'")
217
218 (defmethod database-output-sql ((num number) database)
219   (declare (ignore database))
220   (princ-to-string num))
221
222 (defmethod database-output-sql ((arg list) database)
223   (if (null arg)
224       "NULL"
225       (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
226                                             (sql-output val database))
227                                         arg))))
228
229 (defmethod database-output-sql ((arg vector) database)
230   (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
231                                          (sql-output val database))
232                                arg)))
233
234 (defmethod database-output-sql ((self wall-time) database)
235   (declare (ignore database))
236   (db-timestring self))
237
238 (defmethod database-output-sql ((self duration) database)
239   (declare (ignore database))
240   (format nil "'~a'" (duration-timestring self)))
241
242 (defmethod database-output-sql (thing database)
243   (if (or (null thing)
244           (eq 'null thing))
245       "NULL"
246     (error 'sql-user-error
247            :message
248            (format nil
249                    "No type conversion to SQL for ~A is defined for DB ~A."
250                    (type-of thing) (type-of database)))))
251
252
253 (defmethod output-sql-hash-key ((arg vector) database)
254   (list 'vector (map 'list (lambda (arg)
255                              (or (output-sql-hash-key arg database)
256                                  (return-from output-sql-hash-key nil)))
257                      arg)))
258
259 (defmethod output-sql (expr database)
260   (write-string (database-output-sql expr database) *sql-stream*)
261   (values))
262
263 (defmethod output-sql ((expr list) database)
264   (if (null expr)
265       (write-string +null-string+ *sql-stream*)
266       (progn
267         (write-char #\( *sql-stream*)
268         (do ((item expr (cdr item)))
269             ((null (cdr item))
270              (output-sql (car item) database))
271           (output-sql (car item) database)
272           (write-char #\, *sql-stream*))
273         (write-char #\) *sql-stream*)))
274   t)
275
276 (defmethod describe-table ((table sql-create-table)
277                            &key (database *default-database*))
278   (database-describe-table
279    database
280    (convert-to-db-default-case 
281     (symbol-name (slot-value table 'name)) database)))
282
283 #+nil
284 (defmethod add-storage-class ((self database) (class symbol) &key (sequence t))
285   (let ((tablename (view-table (find-class class))))
286     (unless (tablep tablename)
287       (create-view-from-class class)
288       (when sequence
289         (create-sequence-from-class class)))))
290  
291 ;;; Iteration
292
293
294 (defmacro do-query (((&rest args) query-expression
295                      &key (database '*default-database*) (result-types :auto))
296                     &body body)
297   "Repeatedly executes BODY within a binding of ARGS on the
298 attributes of each record resulting from QUERY-EXPRESSION. The
299 return value is determined by the result of executing BODY. The
300 default value of DATABASE is *DEFAULT-DATABASE*."
301   (let ((result-set (gensym "RESULT-SET-"))
302         (qe (gensym "QUERY-EXPRESSION-"))
303         (columns (gensym "COLUMNS-"))
304         (row (gensym "ROW-"))
305         (db (gensym "DB-")))
306     `(let ((,qe ,query-expression))
307       (typecase ,qe
308         (sql-object-query
309          (dolist (,row (query ,qe))
310            (destructuring-bind ,args 
311                ,row
312              ,@body)))
313         (t
314          ;; Functional query 
315          (let ((,db ,database))
316            (multiple-value-bind (,result-set ,columns)
317                (database-query-result-set ,qe ,db
318                                           :full-set nil 
319                                           :result-types ,result-types)
320              (when ,result-set
321                (unwind-protect
322                     (do ((,row (make-list ,columns)))
323                         ((not (database-store-next-row ,result-set ,db ,row))
324                          nil)
325                       (destructuring-bind ,args ,row
326                         ,@body))
327                  (database-dump-result-set ,result-set ,db))))))))))
328
329 (defun map-query (output-type-spec function query-expression
330                   &key (database *default-database*)
331                   (result-types :auto))
332   "Map the function over all tuples that are returned by the
333 query in QUERY-EXPRESSION. The results of the function are
334 collected as specified in OUTPUT-TYPE-SPEC and returned like in
335 MAP."
336   (typecase query-expression
337     (sql-object-query
338      (map output-type-spec #'(lambda (x) (apply function x))
339           (query query-expression)))
340     (t
341      ;; Functional query 
342      (macrolet ((type-specifier-atom (type)
343                   `(if (atom ,type) ,type (car ,type))))
344        (case (type-specifier-atom output-type-spec)
345          ((nil) 
346           (map-query-for-effect function query-expression database 
347                                 result-types))
348          (list 
349           (map-query-to-list function query-expression database result-types))
350          ((simple-vector simple-string vector string array simple-array
351                          bit-vector simple-bit-vector base-string
352                          simple-base-string)
353           (map-query-to-simple output-type-spec function query-expression 
354                                database result-types))
355          (t
356           (funcall #'map-query 
357                    (cmucl-compat:result-type-or-lose output-type-spec t)
358                    function query-expression :database database 
359                    :result-types result-types)))))))
360   
361 (defun map-query-for-effect (function query-expression database result-types)
362   (multiple-value-bind (result-set columns)
363       (database-query-result-set query-expression database :full-set nil
364                                  :result-types result-types)
365     (let ((flatp (and (= columns 1) 
366                       (typecase query-expression 
367                         (string t) 
368                         (sql-query 
369                          (slot-value query-expression 'flatp))))))
370       (when result-set
371         (unwind-protect
372              (do ((row (make-list columns)))
373                  ((not (database-store-next-row result-set database row))
374                   nil)
375                (if flatp
376                    (apply function row)
377                    (funcall function row)))
378           (database-dump-result-set result-set database))))))
379                      
380 (defun map-query-to-list (function query-expression database result-types)
381   (multiple-value-bind (result-set columns)
382       (database-query-result-set query-expression database :full-set nil
383                                  :result-types result-types)
384     (let ((flatp (and (= columns 1) 
385                       (typecase query-expression 
386                         (string t) 
387                         (sql-query 
388                          (slot-value query-expression 'flatp))))))
389       (when result-set
390         (unwind-protect
391              (let ((result (list nil)))
392                (do ((row (make-list columns))
393                     (current-cons result (cdr current-cons)))
394                    ((not (database-store-next-row result-set database row))
395                     (cdr result))
396                  (rplacd current-cons 
397                          (list (if flatp 
398                                    (apply function row)
399                                    (funcall function (copy-list row)))))))
400           (database-dump-result-set result-set database))))))
401
402 (defun map-query-to-simple (output-type-spec function query-expression database result-types)
403   (multiple-value-bind (result-set columns rows)
404       (database-query-result-set query-expression database :full-set t
405                                  :result-types result-types)
406     (let ((flatp (and (= columns 1) 
407                       (typecase query-expression 
408                         (string t) 
409                         (sql-query
410                          (slot-value query-expression 'flatp))))))
411       (when result-set
412         (unwind-protect
413              (if rows
414                  ;; We know the row count in advance, so we allocate once
415                  (do ((result
416                        (cmucl-compat:make-sequence-of-type output-type-spec rows))
417                       (row (make-list columns))
418                       (index 0 (1+ index)))
419                      ((not (database-store-next-row result-set database row))
420                       result)
421                    (declare (fixnum index))
422                    (setf (aref result index)
423                          (if flatp 
424                              (apply function row)
425                              (funcall function (copy-list row)))))
426                  ;; Database can't report row count in advance, so we have
427                  ;; to grow and shrink our vector dynamically
428                  (do ((result
429                        (cmucl-compat:make-sequence-of-type output-type-spec 100))
430                       (allocated-length 100)
431                       (row (make-list columns))
432                       (index 0 (1+ index)))
433                      ((not (database-store-next-row result-set database row))
434                       (cmucl-compat:shrink-vector result index))
435                    (declare (fixnum allocated-length index))
436                    (when (>= index allocated-length)
437                      (setq allocated-length (* allocated-length 2)
438                            result (adjust-array result allocated-length)))
439                    (setf (aref result index)
440                          (if flatp 
441                              (apply function row)
442                              (funcall function (copy-list row))))))
443           (database-dump-result-set result-set database))))))
444
445 ;;; Row processing macro from CLSQL
446
447 (defmacro for-each-row (((&rest fields) &key from order-by where distinct limit) &body body)
448   (let ((d (gensym "DISTINCT-"))
449         (bind-fields (loop for f in fields collect (car f)))
450         (w (gensym "WHERE-"))
451         (o (gensym "ORDER-BY-"))
452         (frm (gensym "FROM-"))
453         (l (gensym "LIMIT-"))
454         (q (gensym "QUERY-")))
455     `(let ((,frm ,from)
456            (,w ,where)
457            (,d ,distinct)
458            (,l ,limit)
459            (,o ,order-by))
460       (let ((,q (query-string ',fields ,frm ,w ,d ,o ,l)))
461         (loop for tuple in (query ,q)
462               collect (destructuring-bind ,bind-fields tuple
463                    ,@body))))))
464
465 (defun query-string (fields from where distinct order-by limit)
466   (concatenate
467    'string
468    (format nil "select ~A~{~A~^,~} from ~{~A~^ and ~}" 
469            (if distinct "distinct " "") (field-names fields)
470            (from-names from))
471    (if where (format nil " where ~{~A~^ ~}"
472                      (where-strings where)) "")
473    (if order-by (format nil " order by ~{~A~^, ~}"
474                         (order-by-strings order-by)))
475    (if limit (format nil " limit ~D" limit) "")))
476
477 (defun lisp->sql-name (field)
478   (typecase field
479     (string field)
480     (symbol (string-upcase (symbol-name field)))
481     (cons (cadr field))
482     (t (format nil "~A" field))))
483
484 (defun field-names (field-forms)
485   "Return a list of field name strings from a fields form"
486   (loop for field-form in field-forms
487         collect
488         (lisp->sql-name
489          (if (cadr field-form)
490              (cadr field-form)
491              (car field-form)))))
492
493 (defun from-names (from)
494   "Return a list of field name strings from a fields form"
495   (loop for table in (if (atom from) (list from) from)
496         collect (lisp->sql-name table)))
497
498
499 (defun where-strings (where)
500   (loop for w in (if (atom (car where)) (list where) where)
501         collect
502         (if (consp w)
503             (format nil "~A ~A ~A" (second w) (first w) (third w))
504             (format nil "~A" w))))
505
506 (defun order-by-strings (order-by)
507   (loop for o in order-by
508         collect
509         (if (atom o)
510             (lisp->sql-name o)
511             (format nil "~A ~A" (lisp->sql-name (car o))
512                     (lisp->sql-name (cadr o))))))
513
514
515