r9359: Fixes for PRINT-QUERY and sql concatenation operator (||).
[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 'clsql-sql-syntax-error :reason ":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 'clsql-sql-syntax-error
142                     :reason "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 'clsql-simple-error
247            :format-control
248            "No type conversion to SQL for ~A is defined for DB ~A."
249            :format-arguments (list (type-of thing) (type-of database)))))
250
251
252 (defmethod output-sql-hash-key ((arg vector) database)
253   (list 'vector (map 'list (lambda (arg)
254                              (or (output-sql-hash-key arg database)
255                                  (return-from output-sql-hash-key nil)))
256                      arg)))
257
258 (defmethod output-sql (expr database)
259   (write-string (database-output-sql expr database) *sql-stream*)
260   (values))
261
262 (defmethod output-sql ((expr list) database)
263   (if (null expr)
264       (write-string +null-string+ *sql-stream*)
265       (progn
266         (write-char #\( *sql-stream*)
267         (do ((item expr (cdr item)))
268             ((null (cdr item))
269              (output-sql (car item) database))
270           (output-sql (car item) database)
271           (write-char #\, *sql-stream*))
272         (write-char #\) *sql-stream*)))
273   t)
274
275 (defmethod describe-table ((table sql-create-table)
276                            &key (database *default-database*))
277   (database-describe-table
278    database
279    (convert-to-db-default-case 
280     (symbol-name (slot-value table 'name)) database)))
281
282 #+nil
283 (defmethod add-storage-class ((self database) (class symbol) &key (sequence t))
284   (let ((tablename (view-table (find-class class))))
285     (unless (tablep tablename)
286       (create-view-from-class class)
287       (when sequence
288         (create-sequence-from-class class)))))
289  
290 ;;; Iteration
291
292
293 (defmacro do-query (((&rest args) query-expression
294                      &key (database '*default-database*) (result-types :auto))
295                     &body body)
296   "Repeatedly executes BODY within a binding of ARGS on the
297 attributes of each record resulting from QUERY-EXPRESSION. The
298 return value is determined by the result of executing BODY. The
299 default value of DATABASE is *DEFAULT-DATABASE*."
300   (let ((result-set (gensym "RESULT-SET-"))
301         (qe (gensym "QUERY-EXPRESSION-"))
302         (columns (gensym "COLUMNS-"))
303         (row (gensym "ROW-"))
304         (db (gensym "DB-")))
305     `(let ((,qe ,query-expression))
306       (typecase ,qe
307         (sql-object-query
308          (dolist (,row (query ,qe))
309            (destructuring-bind ,args 
310                ,row
311              ,@body)))
312         (t
313          ;; Functional query 
314          (let ((,db ,database))
315            (multiple-value-bind (,result-set ,columns)
316                (database-query-result-set ,qe ,db
317                                           :full-set nil 
318                                           :result-types ,result-types)
319              (when ,result-set
320                (unwind-protect
321                     (do ((,row (make-list ,columns)))
322                         ((not (database-store-next-row ,result-set ,db ,row))
323                          nil)
324                       (destructuring-bind ,args ,row
325                         ,@body))
326                  (database-dump-result-set ,result-set ,db))))))))))
327
328 (defun map-query (output-type-spec function query-expression
329                   &key (database *default-database*)
330                   (result-types :auto))
331   "Map the function over all tuples that are returned by the
332 query in QUERY-EXPRESSION. The results of the function are
333 collected as specified in OUTPUT-TYPE-SPEC and returned like in
334 MAP."
335   (typecase query-expression
336     (sql-object-query
337      (map output-type-spec #'(lambda (x) (apply function x))
338           (query query-expression)))
339     (t
340      ;; Functional query 
341      (macrolet ((type-specifier-atom (type)
342                   `(if (atom ,type) ,type (car ,type))))
343        (case (type-specifier-atom output-type-spec)
344          ((nil) 
345           (map-query-for-effect function query-expression database 
346                                 result-types))
347          (list 
348           (map-query-to-list function query-expression database result-types))
349          ((simple-vector simple-string vector string array simple-array
350                          bit-vector simple-bit-vector base-string
351                          simple-base-string)
352           (map-query-to-simple output-type-spec function query-expression 
353                                database result-types))
354          (t
355           (funcall #'map-query 
356                    (cmucl-compat:result-type-or-lose output-type-spec t)
357                    function query-expression :database database 
358                    :result-types result-types)))))))
359   
360 (defun map-query-for-effect (function query-expression database result-types)
361   (multiple-value-bind (result-set columns)
362       (database-query-result-set query-expression database :full-set nil
363                                  :result-types result-types)
364     (when result-set
365       (unwind-protect
366            (do ((row (make-list columns)))
367                ((not (database-store-next-row result-set database row))
368                 nil)
369              (apply function row))
370         (database-dump-result-set result-set database)))))
371                      
372 (defun map-query-to-list (function query-expression database result-types)
373   (multiple-value-bind (result-set columns)
374       (database-query-result-set query-expression database :full-set nil
375                                  :result-types result-types)
376     (when result-set
377       (unwind-protect
378            (let ((result (list nil)))
379              (do ((row (make-list columns))
380                   (current-cons result (cdr current-cons)))
381                  ((not (database-store-next-row result-set database row))
382                   (cdr result))
383                (rplacd current-cons (list (apply function row)))))
384         (database-dump-result-set result-set database)))))
385
386
387 (defun map-query-to-simple (output-type-spec function query-expression database result-types)
388   (multiple-value-bind (result-set columns rows)
389       (database-query-result-set query-expression database :full-set t
390                                  :result-types result-types)
391     (when result-set
392       (unwind-protect
393            (if rows
394                ;; We know the row count in advance, so we allocate once
395                (do ((result
396                      (cmucl-compat:make-sequence-of-type output-type-spec rows))
397                     (row (make-list columns))
398                     (index 0 (1+ index)))
399                    ((not (database-store-next-row result-set database row))
400                     result)
401                  (declare (fixnum index))
402                  (setf (aref result index)
403                        (apply function row)))
404                ;; Database can't report row count in advance, so we have
405                ;; to grow and shrink our vector dynamically
406                (do ((result
407                      (cmucl-compat:make-sequence-of-type output-type-spec 100))
408                     (allocated-length 100)
409                     (row (make-list columns))
410                     (index 0 (1+ index)))
411                    ((not (database-store-next-row result-set database row))
412                     (cmucl-compat:shrink-vector result index))
413                  (declare (fixnum allocated-length index))
414                  (when (>= index allocated-length)
415                    (setq allocated-length (* allocated-length 2)
416                          result (adjust-array result allocated-length)))
417                  (setf (aref result index)
418                        (apply function row))))
419         (database-dump-result-set result-set database)))))
420
421 ;;; Row processing macro from CLSQL
422
423 (defmacro for-each-row (((&rest fields) &key from order-by where distinct limit) &body body)
424   (let ((d (gensym "DISTINCT-"))
425         (bind-fields (loop for f in fields collect (car f)))
426         (w (gensym "WHERE-"))
427         (o (gensym "ORDER-BY-"))
428         (frm (gensym "FROM-"))
429         (l (gensym "LIMIT-"))
430         (q (gensym "QUERY-")))
431     `(let ((,frm ,from)
432            (,w ,where)
433            (,d ,distinct)
434            (,l ,limit)
435            (,o ,order-by))
436       (let ((,q (query-string ',fields ,frm ,w ,d ,o ,l)))
437         (loop for tuple in (query ,q)
438               collect (destructuring-bind ,bind-fields tuple
439                    ,@body))))))
440
441 (defun query-string (fields from where distinct order-by limit)
442   (concatenate
443    'string
444    (format nil "select ~A~{~A~^,~} from ~{~A~^ and ~}" 
445            (if distinct "distinct " "") (field-names fields)
446            (from-names from))
447    (if where (format nil " where ~{~A~^ ~}"
448                      (where-strings where)) "")
449    (if order-by (format nil " order by ~{~A~^, ~}"
450                         (order-by-strings order-by)))
451    (if limit (format nil " limit ~D" limit) "")))
452
453 (defun lisp->sql-name (field)
454   (typecase field
455     (string field)
456     (symbol (string-upcase (symbol-name field)))
457     (cons (cadr field))
458     (t (format nil "~A" field))))
459
460 (defun field-names (field-forms)
461   "Return a list of field name strings from a fields form"
462   (loop for field-form in field-forms
463         collect
464         (lisp->sql-name
465          (if (cadr field-form)
466              (cadr field-form)
467              (car field-form)))))
468
469 (defun from-names (from)
470   "Return a list of field name strings from a fields form"
471   (loop for table in (if (atom from) (list from) from)
472         collect (lisp->sql-name table)))
473
474
475 (defun where-strings (where)
476   (loop for w in (if (atom (car where)) (list where) where)
477         collect
478         (if (consp w)
479             (format nil "~A ~A ~A" (second w) (first w) (third w))
480             (format nil "~A" w))))
481
482 (defun order-by-strings (order-by)
483   (loop for o in order-by
484         collect
485         (if (atom o)
486             (lisp->sql-name o)
487             (format nil "~A ~A" (lisp->sql-name (car o))
488                     (lisp->sql-name (cadr o))))))
489
490
491