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