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 ((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))
31 (defmethod execute-command ((expr %sql-expression)
32 &key (database *default-database*))
33 (execute-command (sql-output expr database) :database database)
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))))
44 (record-sql-result result database)
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))
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) )
63 (list :database database))))
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))))
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
100 (flet ((compute-sizes (data)
101 (mapcar #'(lambda (x)
102 (apply #'max (mapcar #'(lambda (y)
103 (if (null y) 3 (length y)))
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
112 (sql-query (sql-output query-exp database))))
113 (data (query query-exp :database database :result-types 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 "))
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)))))
125 (defun insert-records (&key (into 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
146 (let ((stmt (make-sql-insert :into into :attrs attributes
147 :vals values :av-pairs av-pairs
149 (execute-command stmt :database database)))
151 (defun make-sql-insert (&key (into nil)
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)
161 (cond ((and vals (not attrs) (not query) (not av-pairs))
163 ((and vals attrs (not subquery) (not av-pairs))
164 (setf attributes attrs)
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))
175 (error 'sql-user-error
176 :message "bad or ambiguous keyword combination.")))
179 (defun delete-records (&key (from 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)))
188 (defun update-records (table &key (attributes 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."
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
211 (execute-command stmt :database database)))
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))
226 ((and (null (position #\' str))
227 (null (position #\\ str)))
228 (concatenate 'string "'" str "'"))
230 (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
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) #\\)
239 (setf (aref buf j) #\'))
241 (setf (aref buf j) #\\)
243 (setf (aref buf j) #\\))
245 (setf (aref buf j) char))))))))))
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) "'")
255 (defmethod database-output-sql ((tee (eql t)) database)
256 (declare (ignore database))
259 (defmethod database-output-sql ((num number) database)
260 (declare (ignore database))
261 (princ-to-string num))
263 (defmethod database-output-sql ((arg list) database)
266 (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
267 (sql-output val database))
270 (defmethod database-output-sql ((arg vector) database)
271 (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
272 (sql-output val database))
275 (defmethod database-output-sql ((self wall-time) database)
276 (declare (ignore database))
277 (db-timestring self))
279 (defmethod database-output-sql ((self duration) database)
280 (declare (ignore database))
281 (format nil "'~a'" (duration-timestring self)))
283 (defmethod database-output-sql (thing database)
287 (error 'sql-user-error
290 "No type conversion to SQL for ~A is defined for DB ~A."
291 (type-of thing) (type-of database)))))
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)))
300 (defmethod output-sql (expr database)
301 (write-string (database-output-sql expr database) *sql-stream*)
304 (defmethod output-sql ((expr list) database)
306 (write-string +null-string+ *sql-stream*)
308 (write-char #\( *sql-stream*)
309 (do ((item expr (cdr item)))
311 (output-sql (car item) database))
312 (output-sql (car item) database)
313 (write-char #\, *sql-stream*))
314 (write-char #\) *sql-stream*)))
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)
323 (create-sequence-from-class class)))))
328 (defmacro do-query (((&rest args) query-expression
329 &key (database '*default-database*) (result-types :auto))
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-"))
345 `(let ((,qe ,query-expression))
348 (dolist (,row (query ,qe))
349 (destructuring-bind ,args
354 (let ((,db ,database))
355 (multiple-value-bind (,result-set ,columns)
356 (database-query-result-set ,qe ,db
358 :result-types ,result-types)
361 (do ((,row (make-list ,columns)))
362 ((not (database-store-next-row ,result-set ,db ,row))
364 (destructuring-bind ,args ,row
366 (database-dump-result-set ,result-set ,db))))))))))
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
383 (map output-type-spec #'(lambda (x) (apply function x))
384 (query query-expression)))
387 (macrolet ((type-specifier-atom (type)
388 `(if (atom ,type) ,type (car ,type))))
389 (case (type-specifier-atom output-type-spec)
391 (map-query-for-effect function query-expression database
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
398 (map-query-to-simple output-type-spec function query-expression
399 database result-types))
402 (cmucl-compat:result-type-or-lose output-type-spec t)
403 function query-expression :database database
404 :result-types result-types)))))))
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))))
415 (do ((row (make-list columns)))
416 ((not (database-store-next-row result-set database row))
420 (funcall function row)))
421 (database-dump-result-set result-set database))))))
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))))
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))
440 (funcall function (copy-list row)))))))
441 (database-dump-result-set result-set database))))))
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))))
453 ;; We know the row count in advance, so we allocate once
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))
460 (declare (fixnum index))
461 (setf (aref result index)
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
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)
481 (funcall function (copy-list row))))))
482 (database-dump-result-set result-set database))))))
484 ;;; Row processing macro from CLSQL
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-")))
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
504 (defun query-string (fields from where distinct order-by limit)
507 (format nil "select ~A~{~A~^,~} from ~{~A~^ and ~}"
508 (if distinct "distinct " "") (field-names fields)
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) "")))
516 (defun lisp->sql-name (field)
519 (symbol (string-upcase (symbol-name field)))
521 (t (format nil "~A" field))))
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
528 (if (cadr field-form)
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)))
538 (defun where-strings (where)
539 (loop for w in (if (atom (car where)) (list where) where)
542 (format nil "~A ~A ~A" (second w) (first w) (third w))
543 (format nil "~A" w))))
545 (defun order-by-strings (order-by)
546 (loop for o in order-by
550 (format nil "~A ~A" (lisp->sql-name (car o))
551 (lisp->sql-name (cadr o))))))
554 ;;; Large objects support
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))
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))
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))
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))
573 ;;; Prepared statements
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.
586 (unless (db-type-has-prepared-stmt? (database-type database))
587 (error 'sql-user-error
590 "Database backend type ~:@(~A~) does not support prepared statements."
591 (database-type database))))
593 (database-prepare sql-stmt types database result-types field-names))
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)
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))
604 (defun free-prepared-sql (prepared-stmt)
605 "Delete the objects associated with a prepared statement."
606 (database-free-prepared prepared-stmt))