r9722: Document the FDML.
[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
66 (defun print-query (query-exp &key titles (formats t) (sizes t) (stream t)
67                               (database *default-database*))
68   "Prints a tabular report of the results returned by the SQL
69 query QUERY-EXP, which may be a symbolic SQL expression or a
70 string, in DATABASE which defaults to *DEFAULT-DATABASE*. The
71 report is printed onto STREAM which has a default value of t
72 which means that *STANDARD-OUTPUT* is used. The TITLE argument,
73 which defaults to nil, allows the specification of a list of
74 strings to use as column titles in the tabular output. SIZES
75 accepts a list of column sizes, one for each column selected by
76 QUERY-EXP, to use in formatting the tabular report. The default
77 value of t means that minimum sizes are computed. FORMATS is a
78 list of format strings to be used for printing each column
79 selected by QUERY-EXP. The default value of FORMATS is t meaning
80 that ~A is used to format all columns or ~VA if column sizes are
81 used."
82   (flet ((compute-sizes (data)
83            (mapcar #'(lambda (x) 
84                        (apply #'max (mapcar #'(lambda (y) 
85                                                 (if (null y) 3 (length y)))
86                                             x)))
87                    (apply #'mapcar (cons #'list data))))
88          (format-record (record control sizes)
89            (format stream "~&~?" control
90                    (if (null sizes) record
91                        (mapcan #'(lambda (s f) (list s f)) sizes record)))))
92     (let* ((query-exp (etypecase query-exp
93                         (string query-exp)
94                         (sql-query (sql-output query-exp database))))
95            (data (query query-exp :database database :result-types nil 
96                         :field-names nil))
97            (sizes (if (or (null sizes) (listp sizes)) sizes 
98                       (compute-sizes (if titles (cons titles data) data))))
99            (formats (if (or (null formats) (not (listp formats)))
100                         (make-list (length (car data)) :initial-element
101                                    (if (null sizes) "~A " "~VA "))
102                         formats))
103            (control-string (format nil "~{~A~}" formats)))
104       (when titles (format-record titles control-string sizes))
105       (dolist (d data (values)) (format-record d control-string sizes)))))
106
107 (defun insert-records (&key (into nil)
108                             (attributes nil)
109                             (values nil)
110                             (av-pairs nil)
111                             (query nil)
112                             (database *default-database*))
113   "Inserts records into the table specified by INTO in DATABASE
114 which defaults to *DEFAULT-DATABASE*. There are five ways of
115 specifying the values inserted into each row. In the first VALUES
116 contains a list of values to insert and ATTRIBUTES, AV-PAIRS and
117 QUERY are nil. This can be used when values are supplied for all
118 attributes in INTO. In the second, ATTRIBUTES is a list of column
119 names, VALUES is a corresponding list of values and AV-PAIRS and
120 QUERY are nil. In the third, ATTRIBUTES, VALUES and QUERY are nil
121 and AV-PAIRS is an alist of (attribute value) pairs. In the
122 fourth, VALUES, AV-PAIRS and ATTRIBUTES are nil and QUERY is a
123 symbolic SQL query expression in which the selected columns also
124 exist in INTO. In the fifth method, VALUES and AV-PAIRS are nil
125 and ATTRIBUTES is a list of column names and QUERY is a symbolic
126 SQL query expression which returns values for the specified
127 columns."
128   (let ((stmt (make-sql-insert :into into :attrs attributes
129                                :vals values :av-pairs av-pairs
130                                :subquery query)))
131     (execute-command stmt :database database)))
132
133 (defun make-sql-insert (&key (into nil)
134                             (attrs nil)
135                             (vals nil)
136                             (av-pairs nil)
137                             (subquery nil))
138   (unless into
139       (error 'sql-user-error :message ":into keyword not supplied"))
140   (let ((insert (make-instance 'sql-insert :into into)))
141     (with-slots (attributes values query)
142       insert
143       (cond ((and vals (not attrs) (not query) (not av-pairs))
144              (setf values vals))
145             ((and vals attrs (not subquery) (not av-pairs))
146              (setf attributes attrs)
147              (setf values vals))
148             ((and av-pairs (not vals) (not attrs) (not subquery))
149              (setf attributes (mapcar #'car av-pairs))
150              (setf values (mapcar #'cadr av-pairs)))
151             ((and subquery (not vals) (not attrs) (not av-pairs))
152              (setf query subquery))
153             ((and subquery attrs (not vals) (not av-pairs))
154              (setf attributes attrs)
155              (setf query subquery))
156             (t
157              (error 'sql-user-error
158                     :message "bad or ambiguous keyword combination.")))
159       insert)))
160     
161 (defun delete-records (&key (from nil)
162                             (where nil)
163                             (database *default-database*))
164   "Deletes records satisfying the SQL expression WHERE from the
165 table specified by FROM in DATABASE specifies a database which
166 defaults to *DEFAULT-DATABASE*."
167   (let ((stmt (make-instance 'sql-delete :from from :where where)))
168     (execute-command stmt :database database)))
169
170 (defun update-records (table &key (attributes nil)
171                             (values nil)
172                             (av-pairs nil)
173                             (where nil)
174                             (database *default-database*))
175   "Updates the attribute values of existing records satsifying
176 the SQL expression WHERE in the table specified by TABLE in
177 DATABASE which defaults to *DEFAULT-DATABASE*. There are three
178 ways of specifying the values to update for each row. In the
179 first, VALUES contains a list of values to use in the update and
180 ATTRIBUTES and AV-PAIRS are nil. This can be used when values are
181 supplied for all attributes in TABLE. In the second, ATTRIBUTES
182 is a list of column names, VALUES is a corresponding list of
183 values and AV-PAIRS is nil. In the third, ATTRIBUTES and VALUES
184 are nil and AV-PAIRS is an alist of (attribute value) pairs."
185   (when av-pairs
186     (setf attributes (mapcar #'car av-pairs)
187           values (mapcar #'cadr av-pairs)))
188   (let ((stmt (make-instance 'sql-update :table table
189                              :attributes attributes
190                              :values values
191                              :where where)))
192     (execute-command stmt :database database)))
193
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 #+nil
297 (defmethod add-storage-class ((self database) (class symbol) &key (sequence t))
298   (let ((tablename (view-table (find-class class))))
299     (unless (tablep tablename)
300       (create-view-from-class class)
301       (when sequence
302         (create-sequence-from-class class)))))
303  
304
305 ;;; Iteration
306
307 (defmacro do-query (((&rest args) query-expression
308                      &key (database '*default-database*) (result-types :auto))
309                     &body body)
310   "Repeatedly executes BODY within a binding of ARGS on the
311 fields of each row selected by the SQL query QUERY-EXPRESSION,
312 which may be a string or a symbolic SQL expression, in DATABASE
313 which defaults to *DEFAULT-DATABASE*. The values returned by the
314 execution of BODY are returned. RESULT-TYPES is a list of symbols
315 which specifies the lisp type for each field returned by
316 QUERY-EXPRESSION. If RESULT-TYPES is nil all results are returned
317 as strings whereas the default value of :auto means that the lisp
318 types are automatically computed for each field."
319   (let ((result-set (gensym "RESULT-SET-"))
320         (qe (gensym "QUERY-EXPRESSION-"))
321         (columns (gensym "COLUMNS-"))
322         (row (gensym "ROW-"))
323         (db (gensym "DB-")))
324     `(let ((,qe ,query-expression))
325       (typecase ,qe
326         (sql-object-query
327          (dolist (,row (query ,qe))
328            (destructuring-bind ,args 
329                ,row
330              ,@body)))
331         (t
332          ;; Functional query 
333          (let ((,db ,database))
334            (multiple-value-bind (,result-set ,columns)
335                (database-query-result-set ,qe ,db
336                                           :full-set nil 
337                                           :result-types ,result-types)
338              (when ,result-set
339                (unwind-protect
340                     (do ((,row (make-list ,columns)))
341                         ((not (database-store-next-row ,result-set ,db ,row))
342                          nil)
343                       (destructuring-bind ,args ,row
344                         ,@body))
345                  (database-dump-result-set ,result-set ,db))))))))))
346
347 (defun map-query (output-type-spec function query-expression
348                   &key (database *default-database*)
349                   (result-types :auto))
350   "Map the function FUNCTION over the attribute values of each
351 row selected by the SQL query QUERY-EXPRESSION, which may be a
352 string or a symbolic SQL expression, in DATABASE which defaults
353 to *DEFAULT-DATABASE*. The results of the function are collected
354 as specified in OUTPUT-TYPE-SPEC and returned like in
355 MAP. RESULT-TYPES is a list of symbols which specifies the lisp
356 type for each field returned by QUERY-EXPRESSION. If RESULT-TYPES
357 is nil all results are returned as strings whereas the default
358 value of :auto means that the lisp types are automatically
359 computed for each field."
360   (typecase query-expression
361     (sql-object-query
362      (map output-type-spec #'(lambda (x) (apply function x))
363           (query query-expression)))
364     (t
365      ;; Functional query 
366      (macrolet ((type-specifier-atom (type)
367                   `(if (atom ,type) ,type (car ,type))))
368        (case (type-specifier-atom output-type-spec)
369          ((nil) 
370           (map-query-for-effect function query-expression database 
371                                 result-types))
372          (list 
373           (map-query-to-list function query-expression database result-types))
374          ((simple-vector simple-string vector string array simple-array
375                          bit-vector simple-bit-vector base-string
376                          simple-base-string)
377           (map-query-to-simple output-type-spec function query-expression 
378                                database result-types))
379          (t
380           (funcall #'map-query 
381                    (cmucl-compat:result-type-or-lose output-type-spec t)
382                    function query-expression :database database 
383                    :result-types result-types)))))))
384   
385 (defun map-query-for-effect (function query-expression database result-types)
386   (multiple-value-bind (result-set columns)
387       (database-query-result-set query-expression database :full-set nil
388                                  :result-types result-types)
389     (let ((flatp (and (= columns 1) 
390                       (typep query-expression 'sql-query)
391                       (slot-value query-expression 'flatp))))
392       (when result-set
393         (unwind-protect
394              (do ((row (make-list columns)))
395                  ((not (database-store-next-row result-set database row))
396                   nil)
397                (if flatp
398                    (apply function row)
399                    (funcall function row)))
400           (database-dump-result-set result-set database))))))
401                      
402 (defun map-query-to-list (function query-expression database result-types)
403   (multiple-value-bind (result-set columns)
404       (database-query-result-set query-expression database :full-set nil
405                                  :result-types result-types)
406     (let ((flatp (and (= columns 1) 
407                       (typep query-expression 'sql-query)
408                       (slot-value query-expression 'flatp))))
409       (when result-set
410         (unwind-protect
411              (let ((result (list nil)))
412                (do ((row (make-list columns))
413                     (current-cons result (cdr current-cons)))
414                    ((not (database-store-next-row result-set database row))
415                     (cdr result))
416                  (rplacd current-cons 
417                          (list (if flatp 
418                                    (apply function row)
419                                    (funcall function (copy-list row)))))))
420           (database-dump-result-set result-set database))))))
421
422 (defun map-query-to-simple (output-type-spec function query-expression database result-types)
423   (multiple-value-bind (result-set columns rows)
424       (database-query-result-set query-expression database :full-set t
425                                  :result-types result-types)
426     (let ((flatp (and (= columns 1) 
427                       (typep query-expression 'sql-query)
428                       (slot-value query-expression 'flatp))))
429       (when result-set
430         (unwind-protect
431              (if rows
432                  ;; We know the row count in advance, so we allocate once
433                  (do ((result
434                        (cmucl-compat:make-sequence-of-type output-type-spec rows))
435                       (row (make-list columns))
436                       (index 0 (1+ index)))
437                      ((not (database-store-next-row result-set database row))
438                       result)
439                    (declare (fixnum index))
440                    (setf (aref result index)
441                          (if flatp 
442                              (apply function row)
443                              (funcall function (copy-list row)))))
444                  ;; Database can't report row count in advance, so we have
445                  ;; to grow and shrink our vector dynamically
446                  (do ((result
447                        (cmucl-compat:make-sequence-of-type output-type-spec 100))
448                       (allocated-length 100)
449                       (row (make-list columns))
450                       (index 0 (1+ index)))
451                      ((not (database-store-next-row result-set database row))
452                       (cmucl-compat:shrink-vector result index))
453                    (declare (fixnum allocated-length index))
454                    (when (>= index allocated-length)
455                      (setq allocated-length (* allocated-length 2)
456                            result (adjust-array result allocated-length)))
457                    (setf (aref result index)
458                          (if flatp 
459                              (apply function row)
460                              (funcall function (copy-list row))))))
461           (database-dump-result-set result-set database))))))
462
463 ;;; Row processing macro from CLSQL
464
465 (defmacro for-each-row (((&rest fields) &key from order-by where distinct limit)
466                         &body body)
467   (let ((d (gensym "DISTINCT-"))
468         (bind-fields (loop for f in fields collect (car f)))
469         (w (gensym "WHERE-"))
470         (o (gensym "ORDER-BY-"))
471         (frm (gensym "FROM-"))
472         (l (gensym "LIMIT-"))
473         (q (gensym "QUERY-")))
474     `(let ((,frm ,from)
475            (,w ,where)
476            (,d ,distinct)
477            (,l ,limit)
478            (,o ,order-by))
479       (let ((,q (query-string ',fields ,frm ,w ,d ,o ,l)))
480         (loop for tuple in (query ,q)
481               collect (destructuring-bind ,bind-fields tuple
482                    ,@body))))))
483
484 (defun query-string (fields from where distinct order-by limit)
485   (concatenate
486    'string
487    (format nil "select ~A~{~A~^,~} from ~{~A~^ and ~}" 
488            (if distinct "distinct " "") (field-names fields)
489            (from-names from))
490    (if where (format nil " where ~{~A~^ ~}"
491                      (where-strings where)) "")
492    (if order-by (format nil " order by ~{~A~^, ~}"
493                         (order-by-strings order-by)))
494    (if limit (format nil " limit ~D" limit) "")))
495
496 (defun lisp->sql-name (field)
497   (typecase field
498     (string field)
499     (symbol (string-upcase (symbol-name field)))
500     (cons (cadr field))
501     (t (format nil "~A" field))))
502
503 (defun field-names (field-forms)
504   "Return a list of field name strings from a fields form"
505   (loop for field-form in field-forms
506         collect
507         (lisp->sql-name
508          (if (cadr field-form)
509              (cadr field-form)
510              (car field-form)))))
511
512 (defun from-names (from)
513   "Return a list of field name strings from a fields form"
514   (loop for table in (if (atom from) (list from) from)
515         collect (lisp->sql-name table)))
516
517
518 (defun where-strings (where)
519   (loop for w in (if (atom (car where)) (list where) where)
520         collect
521         (if (consp w)
522             (format nil "~A ~A ~A" (second w) (first w) (third w))
523             (format nil "~A" w))))
524
525 (defun order-by-strings (order-by)
526   (loop for o in order-by
527         collect
528         (if (atom o)
529             (lisp->sql-name o)
530             (format nil "~A ~A" (lisp->sql-name (car o))
531                     (lisp->sql-name (cadr o))))))
532
533
534 ;;; Large objects support
535
536 (defun create-large-object (&key (database *default-database*))
537   "Creates a new large object in the database and returns the object identifier"
538   (database-create-large-object database))
539
540 (defun write-large-object (object-id data &key (database *default-database*))
541   "Writes data to the large object"
542   (database-write-large-object object-id data database))
543
544 (defun read-large-object (object-id &key (database *default-database*))
545   "Reads the large object content"
546   (database-read-large-object object-id database))
547
548 (defun delete-large-object (object-id &key (database *default-database*))
549   "Deletes the large object in the database"
550   (database-delete-large-object object-id database))
551
552
553 ;;; Prepared statements
554
555 (defun prepare-sql (sql-stmt types &key (database *default-database*) (result-types :auto) field-names)
556   "Prepares a SQL statement for execution. TYPES contains a
557 list of types corresponding to the input parameters. Returns a
558 prepared-statement object.
559
560 A type can be
561   :int
562   :double
563   :null
564   (:string n)
565 "
566   (unless (db-type-has-prepared-stmt? (database-type database))
567     (error 'sql-user-error 
568            :message
569            (format nil
570                    "Database backend type ~:@(~A~) does not support prepared statements."
571                    (database-type database))))
572
573   (database-prepare sql-stmt types database result-types field-names))
574
575 (defun bind-parameter (prepared-stmt position value)
576   "Sets the value of a parameter is in prepared statement."
577   (database-bind-parameter prepared-stmt position value)
578   value)
579
580 (defun run-prepared-sql (prepared-stmt)
581   "Execute the prepared sql statment. All input parameters must be bound."
582   (database-run-prepared prepared-stmt))
583
584 (defun free-prepared-sql (prepared-stmt)
585   "Delete the objects associated with a prepared statement."
586   (database-free-prepared prepared-stmt))