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*)))
317 (defmethod describe-table ((table sql-create-table)
318 &key (database *default-database*))
319 (database-describe-table
321 (convert-to-db-default-case
322 (symbol-name (slot-value table 'name)) database)))
325 (defmethod add-storage-class ((self database) (class symbol) &key (sequence t))
326 (let ((tablename (view-table (find-class class))))
327 (unless (tablep tablename)
328 (create-view-from-class class)
330 (create-sequence-from-class class)))))
335 (defmacro do-query (((&rest args) query-expression
336 &key (database '*default-database*) (result-types :auto))
338 "Repeatedly executes BODY within a binding of ARGS on the
339 fields of each row selected by the SQL query QUERY-EXPRESSION,
340 which may be a string or a symbolic SQL expression, in DATABASE
341 which defaults to *DEFAULT-DATABASE*. The values returned by the
342 execution of BODY are returned. RESULT-TYPES is a list of symbols
343 which specifies the lisp type for each field returned by
344 QUERY-EXPRESSION. If RESULT-TYPES is nil all results are returned
345 as strings whereas the default value of :auto means that the lisp
346 types are automatically computed for each field."
347 (let ((result-set (gensym "RESULT-SET-"))
348 (qe (gensym "QUERY-EXPRESSION-"))
349 (columns (gensym "COLUMNS-"))
350 (row (gensym "ROW-"))
352 `(let ((,qe ,query-expression))
355 (dolist (,row (query ,qe))
356 (destructuring-bind ,args
361 (let ((,db ,database))
362 (multiple-value-bind (,result-set ,columns)
363 (database-query-result-set ,qe ,db
365 :result-types ,result-types)
368 (do ((,row (make-list ,columns)))
369 ((not (database-store-next-row ,result-set ,db ,row))
371 (destructuring-bind ,args ,row
373 (database-dump-result-set ,result-set ,db))))))))))
375 (defun map-query (output-type-spec function query-expression
376 &key (database *default-database*)
377 (result-types :auto))
378 "Map the function FUNCTION over the attribute values of each
379 row selected by the SQL query QUERY-EXPRESSION, which may be a
380 string or a symbolic SQL expression, in DATABASE which defaults
381 to *DEFAULT-DATABASE*. The results of the function are collected
382 as specified in OUTPUT-TYPE-SPEC and returned like in
383 MAP. RESULT-TYPES is a list of symbols which specifies the lisp
384 type for each field returned by QUERY-EXPRESSION. If RESULT-TYPES
385 is nil all results are returned as strings whereas the default
386 value of :auto means that the lisp types are automatically
387 computed for each field."
388 (typecase query-expression
390 (map output-type-spec #'(lambda (x) (apply function x))
391 (query query-expression)))
394 (macrolet ((type-specifier-atom (type)
395 `(if (atom ,type) ,type (car ,type))))
396 (case (type-specifier-atom output-type-spec)
398 (map-query-for-effect function query-expression database
401 (map-query-to-list function query-expression database result-types))
402 ((simple-vector simple-string vector string array simple-array
403 bit-vector simple-bit-vector base-string
405 (map-query-to-simple output-type-spec function query-expression
406 database result-types))
409 (cmucl-compat:result-type-or-lose output-type-spec t)
410 function query-expression :database database
411 :result-types result-types)))))))
413 (defun map-query-for-effect (function query-expression database result-types)
414 (multiple-value-bind (result-set columns)
415 (database-query-result-set query-expression database :full-set nil
416 :result-types result-types)
417 (let ((flatp (and (= columns 1)
418 (typep query-expression 'sql-query)
419 (slot-value query-expression 'flatp))))
422 (do ((row (make-list columns)))
423 ((not (database-store-next-row result-set database row))
427 (funcall function row)))
428 (database-dump-result-set result-set database))))))
430 (defun map-query-to-list (function query-expression database result-types)
431 (multiple-value-bind (result-set columns)
432 (database-query-result-set query-expression database :full-set nil
433 :result-types result-types)
434 (let ((flatp (and (= columns 1)
435 (typep query-expression 'sql-query)
436 (slot-value query-expression 'flatp))))
439 (let ((result (list nil)))
440 (do ((row (make-list columns))
441 (current-cons result (cdr current-cons)))
442 ((not (database-store-next-row result-set database row))
447 (funcall function (copy-list row)))))))
448 (database-dump-result-set result-set database))))))
450 (defun map-query-to-simple (output-type-spec function query-expression database result-types)
451 (multiple-value-bind (result-set columns rows)
452 (database-query-result-set query-expression database :full-set t
453 :result-types result-types)
454 (let ((flatp (and (= columns 1)
455 (typep query-expression 'sql-query)
456 (slot-value query-expression 'flatp))))
460 ;; We know the row count in advance, so we allocate once
462 (cmucl-compat:make-sequence-of-type output-type-spec rows))
463 (row (make-list columns))
464 (index 0 (1+ index)))
465 ((not (database-store-next-row result-set database row))
467 (declare (fixnum index))
468 (setf (aref result index)
471 (funcall function (copy-list row)))))
472 ;; Database can't report row count in advance, so we have
473 ;; to grow and shrink our vector dynamically
475 (cmucl-compat:make-sequence-of-type output-type-spec 100))
476 (allocated-length 100)
477 (row (make-list columns))
478 (index 0 (1+ index)))
479 ((not (database-store-next-row result-set database row))
480 (cmucl-compat:shrink-vector result index))
481 (declare (fixnum allocated-length index))
482 (when (>= index allocated-length)
483 (setq allocated-length (* allocated-length 2)
484 result (adjust-array result allocated-length)))
485 (setf (aref result index)
488 (funcall function (copy-list row))))))
489 (database-dump-result-set result-set database))))))
491 ;;; Row processing macro from CLSQL
493 (defmacro for-each-row (((&rest fields) &key from order-by where distinct limit) &body body)
494 (let ((d (gensym "DISTINCT-"))
495 (bind-fields (loop for f in fields collect (car f)))
496 (w (gensym "WHERE-"))
497 (o (gensym "ORDER-BY-"))
498 (frm (gensym "FROM-"))
499 (l (gensym "LIMIT-"))
500 (q (gensym "QUERY-")))
506 (let ((,q (query-string ',fields ,frm ,w ,d ,o ,l)))
507 (loop for tuple in (query ,q)
508 collect (destructuring-bind ,bind-fields tuple
511 (defun query-string (fields from where distinct order-by limit)
514 (format nil "select ~A~{~A~^,~} from ~{~A~^ and ~}"
515 (if distinct "distinct " "") (field-names fields)
517 (if where (format nil " where ~{~A~^ ~}"
518 (where-strings where)) "")
519 (if order-by (format nil " order by ~{~A~^, ~}"
520 (order-by-strings order-by)))
521 (if limit (format nil " limit ~D" limit) "")))
523 (defun lisp->sql-name (field)
526 (symbol (string-upcase (symbol-name field)))
528 (t (format nil "~A" field))))
530 (defun field-names (field-forms)
531 "Return a list of field name strings from a fields form"
532 (loop for field-form in field-forms
535 (if (cadr field-form)
539 (defun from-names (from)
540 "Return a list of field name strings from a fields form"
541 (loop for table in (if (atom from) (list from) from)
542 collect (lisp->sql-name table)))
545 (defun where-strings (where)
546 (loop for w in (if (atom (car where)) (list where) where)
549 (format nil "~A ~A ~A" (second w) (first w) (third w))
550 (format nil "~A" w))))
552 (defun order-by-strings (order-by)
553 (loop for o in order-by
557 (format nil "~A ~A" (lisp->sql-name (car o))
558 (lisp->sql-name (cadr o))))))
561 ;;; Large objects support
563 (defun create-large-object (&key (database *default-database*))
564 "Creates a new large object in the database and returns the object identifier"
565 (database-create-large-object database))
567 (defun write-large-object (object-id data &key (database *default-database*))
568 "Writes data to the large object"
569 (database-write-large-object object-id data database))
571 (defun read-large-object (object-id &key (database *default-database*))
572 "Reads the large object content"
573 (database-read-large-object object-id database))
575 (defun delete-large-object (object-id &key (database *default-database*))
576 "Deletes the large object in the database"
577 (database-delete-large-object object-id database))
580 ;;; Prepared statements
582 (defun prepare-sql (sql-stmt types &key (database *default-database*) (result-types :auto) field-names)
583 "Prepares a SQL statement for execution. TYPES contains a
584 list of UFFI primitive types corresponding to the input parameters. Returns a
585 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))