1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
6 ;;;; The CLSQL Functional Data Manipulation Language (FDML).
8 ;;;; This file is part of CLSQL.
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 ;;;; *************************************************************************
15 (in-package #:clsql-sys)
17 ;;; Basic operations on databases
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))
24 (defmethod execute-command ((expr %sql-expression)
25 &key (database *default-database*))
26 (execute-command (sql-output expr database) :database database)
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))
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) )
44 (list :database database))))
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)))
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
79 (flet ((compute-sizes (data)
81 (apply #'max (mapcar #'(lambda (y)
82 (if (null y) 3 (length y)))
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
91 (sql-query (sql-output query-exp database))))
92 (data (query query-exp :database database :result-types 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 "))
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)))))
104 (defun insert-records (&key (into 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
125 (let ((stmt (make-sql-insert :into into :attrs attributes
126 :vals values :av-pairs av-pairs
128 (execute-command stmt :database database)))
130 (defun make-sql-insert (&key (into nil)
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)
140 (cond ((and vals (not attrs) (not query) (not av-pairs))
142 ((and vals attrs (not subquery) (not av-pairs))
143 (setf attributes attrs)
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))
154 (error 'sql-user-error
155 :message "bad or ambiguous keyword combination.")))
158 (defun delete-records (&key (from 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)))
167 (defun update-records (table &key (attributes 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."
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
190 (execute-command stmt :database database)))
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))
205 ((and (null (position #\' str))
206 (null (position #\\ str)))
207 (concatenate 'string "'" str "'"))
209 (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
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) #\\)
218 (setf (aref buf j) #\'))
220 (setf (aref buf j) #\\)
222 (setf (aref buf j) #\\))
224 (setf (aref buf j) char))))))))))
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) "'")
234 (defmethod database-output-sql ((tee (eql t)) database)
235 (declare (ignore database))
238 (defmethod database-output-sql ((num number) database)
239 (declare (ignore database))
240 (princ-to-string num))
242 (defmethod database-output-sql ((arg list) database)
245 (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
246 (sql-output val database))
249 (defmethod database-output-sql ((arg vector) database)
250 (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
251 (sql-output val database))
254 (defmethod database-output-sql ((self wall-time) database)
255 (declare (ignore database))
256 (db-timestring self))
258 (defmethod database-output-sql ((self duration) database)
259 (declare (ignore database))
260 (format nil "'~a'" (duration-timestring self)))
262 (defmethod database-output-sql (thing database)
266 (error 'sql-user-error
269 "No type conversion to SQL for ~A is defined for DB ~A."
270 (type-of thing) (type-of database)))))
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)))
279 (defmethod output-sql (expr database)
280 (write-string (database-output-sql expr database) *sql-stream*)
283 (defmethod output-sql ((expr list) database)
285 (write-string +null-string+ *sql-stream*)
287 (write-char #\( *sql-stream*)
288 (do ((item expr (cdr item)))
290 (output-sql (car item) database))
291 (output-sql (car item) database)
292 (write-char #\, *sql-stream*))
293 (write-char #\) *sql-stream*)))
296 (defmethod describe-table ((table sql-create-table)
297 &key (database *default-database*))
298 (database-describe-table
300 (convert-to-db-default-case
301 (symbol-name (slot-value table 'name)) database)))
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)
309 (create-sequence-from-class class)))))
314 (defmacro do-query (((&rest args) query-expression
315 &key (database '*default-database*) (result-types :auto))
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-"))
331 `(let ((,qe ,query-expression))
334 (dolist (,row (query ,qe))
335 (destructuring-bind ,args
340 (let ((,db ,database))
341 (multiple-value-bind (,result-set ,columns)
342 (database-query-result-set ,qe ,db
344 :result-types ,result-types)
347 (do ((,row (make-list ,columns)))
348 ((not (database-store-next-row ,result-set ,db ,row))
350 (destructuring-bind ,args ,row
352 (database-dump-result-set ,result-set ,db))))))))))
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
369 (map output-type-spec #'(lambda (x) (apply function x))
370 (query query-expression)))
373 (macrolet ((type-specifier-atom (type)
374 `(if (atom ,type) ,type (car ,type))))
375 (case (type-specifier-atom output-type-spec)
377 (map-query-for-effect function query-expression database
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
384 (map-query-to-simple output-type-spec function query-expression
385 database result-types))
388 (cmucl-compat:result-type-or-lose output-type-spec t)
389 function query-expression :database database
390 :result-types result-types)))))))
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
400 (slot-value query-expression 'flatp))))))
403 (do ((row (make-list columns)))
404 ((not (database-store-next-row result-set database row))
408 (funcall function row)))
409 (database-dump-result-set result-set database))))))
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
419 (slot-value query-expression 'flatp))))))
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))
430 (funcall function (copy-list row)))))))
431 (database-dump-result-set result-set database))))))
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
441 (slot-value query-expression 'flatp))))))
445 ;; We know the row count in advance, so we allocate once
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))
452 (declare (fixnum index))
453 (setf (aref result index)
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
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)
473 (funcall function (copy-list row))))))
474 (database-dump-result-set result-set database))))))
476 ;;; Row processing macro from CLSQL
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-")))
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
496 (defun query-string (fields from where distinct order-by limit)
499 (format nil "select ~A~{~A~^,~} from ~{~A~^ and ~}"
500 (if distinct "distinct " "") (field-names fields)
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) "")))
508 (defun lisp->sql-name (field)
511 (symbol (string-upcase (symbol-name field)))
513 (t (format nil "~A" field))))
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
520 (if (cadr field-form)
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)))
530 (defun where-strings (where)
531 (loop for w in (if (atom (car where)) (list where) where)
534 (format nil "~A ~A ~A" (second w) (first w) (third w))
535 (format nil "~A" w))))
537 (defun order-by-strings (order-by)
538 (loop for o in order-by
542 (format nil "~A ~A" (lisp->sql-name (car o))
543 (lisp->sql-name (cadr o))))))