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 ;;;; *************************************************************************
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))
37 (declare (ignore result-types))
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 (clsql-base::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)
74 (mapcar #'(lambda (x) (apply #'max (mapcar #'length x)))
75 (apply #'mapcar (cons #'list data))))
76 (format-record (record control sizes)
77 (format stream "~&~?" control
78 (if (null sizes) record
79 (mapcan #'(lambda (s f) (list s f)) sizes record)))))
80 (let* ((query-exp (etypecase query-exp
82 (sql-query (sql-output query-exp database))))
83 (data (query query-exp :database database))
84 (sizes (if (or (null sizes) (listp sizes)) sizes
85 (compute-sizes (if titles (cons titles data) data))))
86 (formats (if (or (null formats) (not (listp formats)))
87 (make-list (length (car data)) :initial-element
88 (if (null sizes) "~A " "~VA "))
90 (control-string (format nil "~{~A~}" formats)))
91 (when titles (format-record titles control-string sizes))
92 (dolist (d data (values)) (format-record d control-string sizes)))))
94 (defun insert-records (&key (into nil)
99 (database *default-database*))
100 "Inserts a set of values into a table. The records created contain
101 values for attributes (or av-pairs). The argument VALUES is a list of
102 values. If ATTRIBUTES is supplied then VALUES must be a corresponding
103 list of values for each of the listed attribute names. If AV-PAIRS is
104 non-nil, then both ATTRIBUTES and VALUES must be nil. If QUERY is
105 non-nil, then neither VALUES nor AV-PAIRS should be. QUERY should be a
106 query expression, and the attribute names in it must also exist in the
107 table INTO. The default value of DATABASE is *DEFAULT-DATABASE*."
108 (let ((stmt (make-sql-insert :into into :attrs attributes
109 :vals values :av-pairs av-pairs
111 (execute-command stmt :database database)))
113 (defun make-sql-insert (&key (into nil)
119 (error 'clsql-sql-syntax-error :reason ":into keyword not supplied"))
120 (let ((insert (make-instance 'sql-insert :into into)))
121 (with-slots (attributes values query)
123 (cond ((and vals (not attrs) (not query) (not av-pairs))
125 ((and vals attrs (not subquery) (not av-pairs))
126 (setf attributes attrs)
128 ((and av-pairs (not vals) (not attrs) (not subquery))
129 (setf attributes (mapcar #'car av-pairs))
130 (setf values (mapcar #'cadr av-pairs)))
131 ((and subquery (not vals) (not attrs) (not av-pairs))
132 (setf query subquery))
133 ((and subquery attrs (not vals) (not av-pairs))
134 (setf attributes attrs)
135 (setf query subquery))
137 (error 'clsql-sql-syntax-error
138 :reason "bad or ambiguous keyword combination.")))
141 (defun delete-records (&key (from nil)
143 (database *default-database*))
144 "Deletes rows from a database table specified by FROM in which the
145 WHERE condition is true. The argument DATABASE specifies a database
146 from which the records are to be removed, and defaults to
148 (let ((stmt (make-instance 'sql-delete :from from :where where)))
149 (execute-command stmt :database database)))
151 (defun update-records (table &key (attributes nil)
155 (database *default-database*))
156 "Changes the values of existing fields in TABLE with columns
157 specified by ATTRIBUTES and VALUES (or AV-PAIRS) where the WHERE
160 (setf attributes (mapcar #'car av-pairs)
161 values (mapcar #'cadr av-pairs)))
162 (let ((stmt (make-instance 'sql-update :table table
163 :attributes attributes
166 (execute-command stmt :database database)))
173 (defmethod database-output-sql ((str string) database)
174 (declare (ignore database)
175 (optimize (speed 3) (safety 1) #+cmu (extensions:inhibit-warnings 3))
176 (type (simple-array * (*)) str))
177 (let ((len (length str)))
178 (declare (type fixnum len))
181 ((and (null (position #\' str))
182 (null (position #\\ str)))
183 (concatenate 'string "'" str "'"))
185 (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
188 ((= i len) (subseq buf 0 (1+ j)))
189 (declare (type integer i j))
190 (let ((char (aref str i)))
191 (cond ((eql char #\')
192 (setf (aref buf j) #\\)
194 (setf (aref buf j) #\'))
196 (setf (aref buf j) #\\)
198 (setf (aref buf j) #\\))
200 (setf (aref buf j) char))))))))))
202 (let ((keyword-package (symbol-package :foo)))
203 (defmethod database-output-sql ((sym symbol) database)
204 (convert-to-db-default-case
205 (if (equal (symbol-package sym) keyword-package)
206 (concatenate 'string "'" (string sym) "'")
210 (defmethod database-output-sql ((tee (eql t)) database)
211 (declare (ignore database))
214 (defmethod database-output-sql ((num number) database)
215 (declare (ignore database))
216 (princ-to-string num))
218 (defmethod database-output-sql ((arg list) database)
221 (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
222 (sql-output val database))
225 (defmethod database-output-sql ((arg vector) database)
226 (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
227 (sql-output val database))
230 (defmethod database-output-sql ((self wall-time) database)
231 (declare (ignore database))
232 (db-timestring self))
234 (defmethod database-output-sql ((self duration) database)
235 (declare (ignore database))
236 (format nil "'~a'" (duration-timestring self)))
238 (defmethod database-output-sql (thing database)
242 (error 'clsql-simple-error
244 "No type conversion to SQL for ~A is defined for DB ~A."
245 :format-arguments (list (type-of thing) (type-of database)))))
248 (defmethod output-sql-hash-key ((arg vector) database)
249 (list 'vector (map 'list (lambda (arg)
250 (or (output-sql-hash-key arg database)
251 (return-from output-sql-hash-key nil)))
254 (defmethod output-sql (expr database)
255 (write-string (database-output-sql expr database) *sql-stream*)
258 (defmethod output-sql ((expr list) database)
260 (write-string +null-string+ *sql-stream*)
262 (write-char #\( *sql-stream*)
263 (do ((item expr (cdr item)))
265 (output-sql (car item) database))
266 (output-sql (car item) database)
267 (write-char #\, *sql-stream*))
268 (write-char #\) *sql-stream*)))
271 (defmethod describe-table ((table sql-create-table)
272 &key (database *default-database*))
273 (database-describe-table
275 (convert-to-db-default-case
276 (symbol-name (slot-value table 'name)) database)))
279 (defmethod add-storage-class ((self database) (class symbol) &key (sequence t))
280 (let ((tablename (view-table (find-class class))))
281 (unless (tablep tablename)
282 (create-view-from-class class)
284 (create-sequence-from-class class)))))
289 (defmacro do-query (((&rest args) query-expression
290 &key (database '*default-database*) (result-types :auto))
292 "Repeatedly executes BODY within a binding of ARGS on the
293 attributes of each record resulting from QUERY-EXPRESSION. The
294 return value is determined by the result of executing BODY. The
295 default value of DATABASE is *DEFAULT-DATABASE*."
296 (let ((result-set (gensym "RESULT-SET-"))
297 (qe (gensym "QUERY-EXPRESSION-"))
298 (columns (gensym "COLUMNS-"))
299 (row (gensym "ROW-"))
301 `(let ((,qe ,query-expression))
304 (dolist (,row (query ,qe))
305 (destructuring-bind ,args
310 (let ((,db ,database))
311 (multiple-value-bind (,result-set ,columns)
312 (database-query-result-set ,qe ,db
314 :result-types ,result-types)
317 (do ((,row (make-list ,columns)))
318 ((not (database-store-next-row ,result-set ,db ,row))
320 (destructuring-bind ,args ,row
322 (database-dump-result-set ,result-set ,db))))))))))
324 (defun map-query (output-type-spec function query-expression
325 &key (database *default-database*)
326 (result-types :auto))
327 "Map the function over all tuples that are returned by the
328 query in QUERY-EXPRESSION. The results of the function are
329 collected as specified in OUTPUT-TYPE-SPEC and returned like in
331 (typecase query-expression
333 (map output-type-spec #'(lambda (x) (apply function x))
334 (query query-expression)))
337 (macrolet ((type-specifier-atom (type)
338 `(if (atom ,type) ,type (car ,type))))
339 (case (type-specifier-atom output-type-spec)
341 (map-query-for-effect function query-expression database
344 (map-query-to-list function query-expression database result-types))
345 ((simple-vector simple-string vector string array simple-array
346 bit-vector simple-bit-vector base-string
348 (map-query-to-simple output-type-spec function query-expression
349 database result-types))
352 (cmucl-compat:result-type-or-lose output-type-spec t)
353 function query-expression :database database
354 :result-types result-types)))))))
356 (defun map-query-for-effect (function query-expression database result-types)
357 (multiple-value-bind (result-set columns)
358 (database-query-result-set query-expression database :full-set nil
359 :result-types result-types)
362 (do ((row (make-list columns)))
363 ((not (database-store-next-row result-set database row))
365 (apply function row))
366 (database-dump-result-set result-set database)))))
368 (defun map-query-to-list (function query-expression database result-types)
369 (multiple-value-bind (result-set columns)
370 (database-query-result-set query-expression database :full-set nil
371 :result-types result-types)
374 (let ((result (list nil)))
375 (do ((row (make-list columns))
376 (current-cons result (cdr current-cons)))
377 ((not (database-store-next-row result-set database row))
379 (rplacd current-cons (list (apply function row)))))
380 (database-dump-result-set result-set database)))))
383 (defun map-query-to-simple (output-type-spec function query-expression database result-types)
384 (multiple-value-bind (result-set columns rows)
385 (database-query-result-set query-expression database :full-set t
386 :result-types result-types)
390 ;; We know the row count in advance, so we allocate once
392 (cmucl-compat:make-sequence-of-type output-type-spec rows))
393 (row (make-list columns))
394 (index 0 (1+ index)))
395 ((not (database-store-next-row result-set database row))
397 (declare (fixnum index))
398 (setf (aref result index)
399 (apply function row)))
400 ;; Database can't report row count in advance, so we have
401 ;; to grow and shrink our vector dynamically
403 (cmucl-compat:make-sequence-of-type output-type-spec 100))
404 (allocated-length 100)
405 (row (make-list columns))
406 (index 0 (1+ index)))
407 ((not (database-store-next-row result-set database row))
408 (cmucl-compat:shrink-vector result index))
409 (declare (fixnum allocated-length index))
410 (when (>= index allocated-length)
411 (setq allocated-length (* allocated-length 2)
412 result (adjust-array result allocated-length)))
413 (setf (aref result index)
414 (apply function row))))
415 (database-dump-result-set result-set database)))))