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 (db-type-has-views? (database-underlying-type database))
52 (dolist (view (list-views :database database))
53 (drop-view view :database database)))
54 (dolist (table (list-tables :database database))
55 (drop-table table :database database))
56 (dolist (index (list-indexes :database database))
57 (drop-index index :database database))
58 (dolist (seq (list-sequences :database database))
59 (drop-sequence seq :database database)))
61 (defun print-query (query-exp &key titles (formats t) (sizes t) (stream t)
62 (database *default-database*))
63 "The PRINT-QUERY function takes a symbolic SQL query expression and
64 formatting information and prints onto STREAM a table containing the
65 results of the query. A list of strings to use as column headings is
66 given by TITLES, which has a default value of NIL. The FORMATS
67 argument is a list of format strings used to print each attribute, and
68 has a default value of T, which means that ~A or ~VA are used if sizes
69 are provided or computed. The field sizes are given by SIZES. It has a
70 default value of T, which specifies that minimum sizes are
71 computed. The output stream is given by STREAM, which has a default
72 value of T. This specifies that *STANDARD-OUTPUT* is used."
73 (flet ((compute-sizes (data)
75 (apply #'max (mapcar #'(lambda (y)
76 (if (null y) 3 (length y)))
78 (apply #'mapcar (cons #'list data))))
79 (format-record (record control sizes)
80 (format stream "~&~?" control
81 (if (null sizes) record
82 (mapcan #'(lambda (s f) (list s f)) sizes record)))))
83 (let* ((query-exp (etypecase query-exp
85 (sql-query (sql-output query-exp database))))
86 (data (query query-exp :database database :result-types nil
88 (sizes (if (or (null sizes) (listp sizes)) sizes
89 (compute-sizes (if titles (cons titles data) data))))
90 (formats (if (or (null formats) (not (listp formats)))
91 (make-list (length (car data)) :initial-element
92 (if (null sizes) "~A " "~VA "))
94 (control-string (format nil "~{~A~}" formats)))
95 (when titles (format-record titles control-string sizes))
96 (dolist (d data (values)) (format-record d control-string sizes)))))
98 (defun insert-records (&key (into nil)
103 (database *default-database*))
104 "Inserts a set of values into a table. The records created contain
105 values for attributes (or av-pairs). The argument VALUES is a list of
106 values. If ATTRIBUTES is supplied then VALUES must be a corresponding
107 list of values for each of the listed attribute names. If AV-PAIRS is
108 non-nil, then both ATTRIBUTES and VALUES must be nil. If QUERY is
109 non-nil, then neither VALUES nor AV-PAIRS should be. QUERY should be a
110 query expression, and the attribute names in it must also exist in the
111 table INTO. The default value of DATABASE is *DEFAULT-DATABASE*."
112 (let ((stmt (make-sql-insert :into into :attrs attributes
113 :vals values :av-pairs av-pairs
115 (execute-command stmt :database database)))
117 (defun make-sql-insert (&key (into nil)
123 (error 'clsql-sql-syntax-error :reason ":into keyword not supplied"))
124 (let ((insert (make-instance 'sql-insert :into into)))
125 (with-slots (attributes values query)
127 (cond ((and vals (not attrs) (not query) (not av-pairs))
129 ((and vals attrs (not subquery) (not av-pairs))
130 (setf attributes attrs)
132 ((and av-pairs (not vals) (not attrs) (not subquery))
133 (setf attributes (mapcar #'car av-pairs))
134 (setf values (mapcar #'cadr av-pairs)))
135 ((and subquery (not vals) (not attrs) (not av-pairs))
136 (setf query subquery))
137 ((and subquery attrs (not vals) (not av-pairs))
138 (setf attributes attrs)
139 (setf query subquery))
141 (error 'clsql-sql-syntax-error
142 :reason "bad or ambiguous keyword combination.")))
145 (defun delete-records (&key (from nil)
147 (database *default-database*))
148 "Deletes rows from a database table specified by FROM in which the
149 WHERE condition is true. The argument DATABASE specifies a database
150 from which the records are to be removed, and defaults to
152 (let ((stmt (make-instance 'sql-delete :from from :where where)))
153 (execute-command stmt :database database)))
155 (defun update-records (table &key (attributes nil)
159 (database *default-database*))
160 "Changes the values of existing fields in TABLE with columns
161 specified by ATTRIBUTES and VALUES (or AV-PAIRS) where the WHERE
164 (setf attributes (mapcar #'car av-pairs)
165 values (mapcar #'cadr av-pairs)))
166 (let ((stmt (make-instance 'sql-update :table table
167 :attributes attributes
170 (execute-command stmt :database database)))
177 (defmethod database-output-sql ((str string) database)
178 (declare (ignore database)
179 (optimize (speed 3) (safety 1) #+cmu (extensions:inhibit-warnings 3))
180 (type (simple-array * (*)) str))
181 (let ((len (length str)))
182 (declare (type fixnum len))
185 ((and (null (position #\' str))
186 (null (position #\\ str)))
187 (concatenate 'string "'" str "'"))
189 (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
192 ((= i len) (subseq buf 0 (1+ j)))
193 (declare (type integer i j))
194 (let ((char (aref str i)))
195 (cond ((eql char #\')
196 (setf (aref buf j) #\\)
198 (setf (aref buf j) #\'))
200 (setf (aref buf j) #\\)
202 (setf (aref buf j) #\\))
204 (setf (aref buf j) char))))))))))
206 (let ((keyword-package (symbol-package :foo)))
207 (defmethod database-output-sql ((sym symbol) database)
208 (convert-to-db-default-case
209 (if (equal (symbol-package sym) keyword-package)
210 (concatenate 'string "'" (string sym) "'")
214 (defmethod database-output-sql ((tee (eql t)) database)
215 (declare (ignore database))
218 (defmethod database-output-sql ((num number) database)
219 (declare (ignore database))
220 (princ-to-string num))
222 (defmethod database-output-sql ((arg list) database)
225 (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
226 (sql-output val database))
229 (defmethod database-output-sql ((arg vector) database)
230 (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
231 (sql-output val database))
234 (defmethod database-output-sql ((self wall-time) database)
235 (declare (ignore database))
236 (db-timestring self))
238 (defmethod database-output-sql ((self duration) database)
239 (declare (ignore database))
240 (format nil "'~a'" (duration-timestring self)))
242 (defmethod database-output-sql (thing database)
246 (error 'clsql-simple-error
248 "No type conversion to SQL for ~A is defined for DB ~A."
249 :format-arguments (list (type-of thing) (type-of database)))))
252 (defmethod output-sql-hash-key ((arg vector) database)
253 (list 'vector (map 'list (lambda (arg)
254 (or (output-sql-hash-key arg database)
255 (return-from output-sql-hash-key nil)))
258 (defmethod output-sql (expr database)
259 (write-string (database-output-sql expr database) *sql-stream*)
262 (defmethod output-sql ((expr list) database)
264 (write-string +null-string+ *sql-stream*)
266 (write-char #\( *sql-stream*)
267 (do ((item expr (cdr item)))
269 (output-sql (car item) database))
270 (output-sql (car item) database)
271 (write-char #\, *sql-stream*))
272 (write-char #\) *sql-stream*)))
275 (defmethod describe-table ((table sql-create-table)
276 &key (database *default-database*))
277 (database-describe-table
279 (convert-to-db-default-case
280 (symbol-name (slot-value table 'name)) database)))
283 (defmethod add-storage-class ((self database) (class symbol) &key (sequence t))
284 (let ((tablename (view-table (find-class class))))
285 (unless (tablep tablename)
286 (create-view-from-class class)
288 (create-sequence-from-class class)))))
293 (defmacro do-query (((&rest args) query-expression
294 &key (database '*default-database*) (result-types :auto))
296 "Repeatedly executes BODY within a binding of ARGS on the
297 attributes of each record resulting from QUERY-EXPRESSION. The
298 return value is determined by the result of executing BODY. The
299 default value of DATABASE is *DEFAULT-DATABASE*."
300 (let ((result-set (gensym "RESULT-SET-"))
301 (qe (gensym "QUERY-EXPRESSION-"))
302 (columns (gensym "COLUMNS-"))
303 (row (gensym "ROW-"))
305 `(let ((,qe ,query-expression))
308 (dolist (,row (query ,qe))
309 (destructuring-bind ,args
314 (let ((,db ,database))
315 (multiple-value-bind (,result-set ,columns)
316 (database-query-result-set ,qe ,db
318 :result-types ,result-types)
321 (do ((,row (make-list ,columns)))
322 ((not (database-store-next-row ,result-set ,db ,row))
324 (destructuring-bind ,args ,row
326 (database-dump-result-set ,result-set ,db))))))))))
328 (defun map-query (output-type-spec function query-expression
329 &key (database *default-database*)
330 (result-types :auto))
331 "Map the function over all tuples that are returned by the
332 query in QUERY-EXPRESSION. The results of the function are
333 collected as specified in OUTPUT-TYPE-SPEC and returned like in
335 (typecase query-expression
337 (map output-type-spec #'(lambda (x) (apply function x))
338 (query query-expression)))
341 (macrolet ((type-specifier-atom (type)
342 `(if (atom ,type) ,type (car ,type))))
343 (case (type-specifier-atom output-type-spec)
345 (map-query-for-effect function query-expression database
348 (map-query-to-list function query-expression database result-types))
349 ((simple-vector simple-string vector string array simple-array
350 bit-vector simple-bit-vector base-string
352 (map-query-to-simple output-type-spec function query-expression
353 database result-types))
356 (cmucl-compat:result-type-or-lose output-type-spec t)
357 function query-expression :database database
358 :result-types result-types)))))))
360 (defun map-query-for-effect (function query-expression database result-types)
361 (multiple-value-bind (result-set columns)
362 (database-query-result-set query-expression database :full-set nil
363 :result-types result-types)
364 (let ((flatp (and (= columns 1)
365 (typecase query-expression
368 (slot-value query-expression 'flatp))))))
371 (do ((row (make-list columns)))
372 ((not (database-store-next-row result-set database row))
376 (funcall function row)))
377 (database-dump-result-set result-set database))))))
379 (defun map-query-to-list (function query-expression database result-types)
380 (multiple-value-bind (result-set columns)
381 (database-query-result-set query-expression database :full-set nil
382 :result-types result-types)
383 (let ((flatp (and (= columns 1)
384 (typecase query-expression
387 (slot-value query-expression 'flatp))))))
390 (let ((result (list nil)))
391 (do ((row (make-list columns))
392 (current-cons result (cdr current-cons)))
393 ((not (database-store-next-row result-set database row))
398 (funcall function (copy-list row)))))))
399 (database-dump-result-set result-set database))))))
401 (defun map-query-to-simple (output-type-spec function query-expression database result-types)
402 (multiple-value-bind (result-set columns rows)
403 (database-query-result-set query-expression database :full-set t
404 :result-types result-types)
405 (let ((flatp (and (= columns 1)
406 (typecase query-expression
409 (slot-value query-expression 'flatp))))))
413 ;; We know the row count in advance, so we allocate once
415 (cmucl-compat:make-sequence-of-type output-type-spec rows))
416 (row (make-list columns))
417 (index 0 (1+ index)))
418 ((not (database-store-next-row result-set database row))
420 (declare (fixnum index))
421 (setf (aref result index)
424 (funcall function (copy-list row)))))
425 ;; Database can't report row count in advance, so we have
426 ;; to grow and shrink our vector dynamically
428 (cmucl-compat:make-sequence-of-type output-type-spec 100))
429 (allocated-length 100)
430 (row (make-list columns))
431 (index 0 (1+ index)))
432 ((not (database-store-next-row result-set database row))
433 (cmucl-compat:shrink-vector result index))
434 (declare (fixnum allocated-length index))
435 (when (>= index allocated-length)
436 (setq allocated-length (* allocated-length 2)
437 result (adjust-array result allocated-length)))
438 (setf (aref result index)
441 (funcall function (copy-list row))))))
442 (database-dump-result-set result-set database))))))
444 ;;; Row processing macro from CLSQL
446 (defmacro for-each-row (((&rest fields) &key from order-by where distinct limit) &body body)
447 (let ((d (gensym "DISTINCT-"))
448 (bind-fields (loop for f in fields collect (car f)))
449 (w (gensym "WHERE-"))
450 (o (gensym "ORDER-BY-"))
451 (frm (gensym "FROM-"))
452 (l (gensym "LIMIT-"))
453 (q (gensym "QUERY-")))
459 (let ((,q (query-string ',fields ,frm ,w ,d ,o ,l)))
460 (loop for tuple in (query ,q)
461 collect (destructuring-bind ,bind-fields tuple
464 (defun query-string (fields from where distinct order-by limit)
467 (format nil "select ~A~{~A~^,~} from ~{~A~^ and ~}"
468 (if distinct "distinct " "") (field-names fields)
470 (if where (format nil " where ~{~A~^ ~}"
471 (where-strings where)) "")
472 (if order-by (format nil " order by ~{~A~^, ~}"
473 (order-by-strings order-by)))
474 (if limit (format nil " limit ~D" limit) "")))
476 (defun lisp->sql-name (field)
479 (symbol (string-upcase (symbol-name field)))
481 (t (format nil "~A" field))))
483 (defun field-names (field-forms)
484 "Return a list of field name strings from a fields form"
485 (loop for field-form in field-forms
488 (if (cadr field-form)
492 (defun from-names (from)
493 "Return a list of field name strings from a fields form"
494 (loop for table in (if (atom from) (list from) from)
495 collect (lisp->sql-name table)))
498 (defun where-strings (where)
499 (loop for w in (if (atom (car where)) (list where) where)
502 (format nil "~A ~A ~A" (second w) (first w) (third w))
503 (format nil "~A" w))))
505 (defun order-by-strings (order-by)
506 (loop for o in order-by
510 (format nil "~A ~A" (lisp->sql-name (car o))
511 (lisp->sql-name (cadr o))))))