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