a904c89ba7af437459d289932cc3f3c4bb6fda18
[clsql.git] / sql / sql.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; $Id$
5 ;;;;
6 ;;;; The CLSQL Functional Data Manipulation Language (FDML). 
7 ;;;;
8 ;;;; This file is part of CLSQL.
9 ;;;;
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 ;;;; *************************************************************************
14
15 (in-package #:clsql-sys)
16   
17 ;;; Basic operations on databases
18
19
20 (defmethod database-query-result-set ((expr %sql-expression) database
21                                       &key full-set result-types)
22   (database-query-result-set (sql-output expr database) database
23                              :full-set full-set :result-types result-types))
24
25 (defmethod execute-command ((expr %sql-expression)
26                             &key (database *default-database*))
27   (execute-command (sql-output expr database) :database database)
28   (values))
29
30 (defmethod explain ((expr %sql-expression) &key (database *default-database*))
31   (let ((expression (sql-output expr database)))
32     (format *standard-output* "explain: ~S~%" expression)
33     (execute-command (concatenate 'string "explain " expression))))
34
35
36 (defmethod query ((expr %sql-expression) &key (database *default-database*)
37                   (result-types nil) (flatp nil))
38   (query (sql-output expr database) :database database :flatp flatp
39          :result-types result-types))
40
41 (defun truncate-database (database)
42   (unless (typep database 'database)
43     (clsql-base-sys::signal-no-database-error database))
44   (unless (is-database-open database)
45     (database-reconnect database))
46   (dolist (table (list-tables database))
47     (drop-table table database))
48   (dolist (index (list-indexes database))
49     (drop-index index database))
50   (dolist (seq (list-sequences database))
51     (drop-sequence seq database)))
52
53 (defun print-query (query-exp &key titles (formats t) (sizes t) (stream t)
54                               (database *default-database*))
55   "The PRINT-QUERY function takes a symbolic SQL query expression and
56 formatting information and prints onto STREAM a table containing the
57 results of the query. A list of strings to use as column headings is
58 given by TITLES, which has a default value of NIL. The FORMATS
59 argument is a list of format strings used to print each attribute, and
60 has a default value of T, which means that ~A or ~VA are used if sizes
61 are provided or computed. The field sizes are given by SIZES. It has a
62 default value of T, which specifies that minimum sizes are
63 computed. The output stream is given by STREAM, which has a default
64 value of T. This specifies that *STANDARD-OUTPUT* is used."
65   (flet ((compute-sizes (data)
66            (mapcar #'(lambda (x) (apply #'max (mapcar #'length x)))
67                    (apply #'mapcar (cons #'list data))))
68          (format-record (record control sizes)
69            (format stream "~&~?" control
70                    (if (null sizes) record
71                        (mapcan #'(lambda (s f) (list s f)) sizes record)))))
72     (let* ((query-exp (etypecase query-exp
73                         (string query-exp)
74                         (sql-query (sql-output query-exp))))
75            (data (query query-exp :database database))
76            (sizes (if (or (null sizes) (listp sizes)) sizes 
77                       (compute-sizes (if titles (cons titles data) data))))
78            (formats (if (or (null formats) (not (listp formats)))
79                         (make-list (length (car data)) :initial-element
80                                    (if (null sizes) "~A " "~VA "))
81                         formats))
82            (control-string (format nil "~{~A~}" formats)))
83       (when titles (format-record titles control-string sizes))
84       (dolist (d data (values)) (format-record d control-string sizes)))))
85
86 (defun insert-records (&key (into nil)
87                             (attributes nil)
88                             (values nil)
89                             (av-pairs nil)
90                             (query nil)
91                             (database *default-database*))
92   "Inserts a set of values into a table. The records created contain
93 values for attributes (or av-pairs). The argument VALUES is a list of
94 values. If ATTRIBUTES is supplied then VALUES must be a corresponding
95 list of values for each of the listed attribute names. If AV-PAIRS is
96 non-nil, then both ATTRIBUTES and VALUES must be nil. If QUERY is
97 non-nil, then neither VALUES nor AV-PAIRS should be. QUERY should be a
98 query expression, and the attribute names in it must also exist in the
99 table INTO. The default value of DATABASE is *DEFAULT-DATABASE*."
100   (let ((stmt (make-sql-insert :into into :attrs attributes
101                                :vals values :av-pairs av-pairs
102                                :subquery query)))
103     (execute-command stmt :database database)))
104
105 (defun make-sql-insert (&key (into nil)
106                             (attrs nil)
107                             (vals nil)
108                             (av-pairs nil)
109                             (subquery nil))
110   (unless into
111       (error 'clsql-sql-syntax-error :reason ":into keyword not supplied"))
112   (let ((insert (make-instance 'sql-insert :into into)))
113     (with-slots (attributes values query)
114       insert
115       (cond ((and vals (not attrs) (not query) (not av-pairs))
116              (setf values vals))
117             ((and vals attrs (not subquery) (not av-pairs))
118              (setf attributes attrs)
119              (setf values vals))
120             ((and av-pairs (not vals) (not attrs) (not subquery))
121              (setf attributes (mapcar #'car av-pairs))
122              (setf values (mapcar #'cadr av-pairs)))
123             ((and subquery (not vals) (not attrs) (not av-pairs))
124              (setf query subquery))
125             ((and subquery attrs (not vals) (not av-pairs))
126              (setf attributes attrs)
127              (setf query subquery))
128             (t
129              (error 'clsql-sql-syntax-error
130                     :reason "bad or ambiguous keyword combination.")))
131       insert)))
132     
133 (defun delete-records (&key (from nil)
134                             (where nil)
135                             (database *default-database*))
136   "Deletes rows from a database table specified by FROM in which the
137 WHERE condition is true. The argument DATABASE specifies a database
138 from which the records are to be removed, and defaults to
139 *default-database*."
140   (let ((stmt (make-instance 'sql-delete :from from :where where)))
141     (execute-command stmt :database database)))
142
143 (defun update-records (table &key (attributes nil)
144                             (values nil)
145                             (av-pairs nil)
146                             (where nil)
147                             (database *default-database*))
148   "Changes the values of existing fields in TABLE with columns
149 specified by ATTRIBUTES and VALUES (or AV-PAIRS) where the WHERE
150 condition is true."
151   (when av-pairs
152     (setf attributes (mapcar #'car av-pairs)
153           values (mapcar #'cadr av-pairs)))
154   (let ((stmt (make-instance 'sql-update :table table
155                              :attributes attributes
156                              :values values
157                              :where where)))
158     (execute-command stmt :database database)))
159
160
161 ;; iteration 
162
163 ;; output-sql
164
165 (defmethod database-output-sql ((str string) database)
166   (declare (ignore database)
167            (optimize (speed 3) (safety 1) #+cmu (extensions:inhibit-warnings 3))
168            (type (simple-array * (*)) str))
169   (let ((len (length str)))
170     (declare (type fixnum len))
171     (cond ((= len 0)
172            +empty-string+)
173           ((and (null (position #\' str))
174                 (null (position #\\ str)))
175            (concatenate 'string "'" str "'"))
176           (t
177            (let ((buf (make-string (+ (* len 2) 2) :initial-element #\')))
178              (do* ((i 0 (incf i))
179                    (j 1 (incf j)))
180                   ((= i len) (subseq buf 0 (1+ j)))
181                (declare (type integer i j))
182                (let ((char (aref str i)))
183                  (cond ((eql char #\')
184                         (setf (aref buf j) #\\)
185                         (incf j)
186                         (setf (aref buf j) #\'))
187                        ((eql char #\\)
188                         (setf (aref buf j) #\\)
189                         (incf j)
190                         (setf (aref buf j) #\\))
191                        (t
192                         (setf (aref buf j) char))))))))))
193
194 (let ((keyword-package (symbol-package :foo)))
195   (defmethod database-output-sql ((sym symbol) database)
196     (declare (ignore database))
197     (if (equal (symbol-package sym) keyword-package)
198         (concatenate 'string "'" (string sym) "'")
199         (symbol-name sym))))
200
201 (defmethod database-output-sql ((tee (eql t)) database)
202   (declare (ignore database))
203   "'Y'")
204
205 (defmethod database-output-sql ((num number) database)
206   (declare (ignore database))
207   (princ-to-string num))
208
209 (defmethod database-output-sql ((arg list) database)
210   (if (null arg)
211       "NULL"
212       (format nil "(~{~A~^,~})" (mapcar #'(lambda (val)
213                                             (sql-output val database))
214                                         arg))))
215
216 (defmethod database-output-sql ((arg vector) database)
217   (format nil "~{~A~^,~}" (map 'list #'(lambda (val)
218                                          (sql-output val database))
219                                arg)))
220
221 (defmethod database-output-sql ((self wall-time) database)
222   (declare (ignore database))
223   (db-timestring self))
224
225 (defmethod database-output-sql (thing database)
226   (if (or (null thing)
227           (eq 'null thing))
228       "NULL"
229     (error 'clsql-simple-error
230            :format-control
231            "No type conversion to SQL for ~A is defined for DB ~A."
232            :format-arguments (list (type-of thing) (type-of database)))))
233
234
235 (defmethod output-sql-hash-key ((arg vector) &optional database)
236   (list 'vector (map 'list (lambda (arg)
237                              (or (output-sql-hash-key arg database)
238                                  (return-from output-sql-hash-key nil)))
239                      arg)))
240
241 (defmethod output-sql (expr &optional (database *default-database*))
242   (write-string (database-output-sql expr database) *sql-stream*)
243   (values))
244
245 (defmethod output-sql ((expr list) &optional (database *default-database*))
246   (if (null expr)
247       (write-string +null-string+ *sql-stream*)
248       (progn
249         (write-char #\( *sql-stream*)
250         (do ((item expr (cdr item)))
251             ((null (cdr item))
252              (output-sql (car item) database))
253           (output-sql (car item) database)
254           (write-char #\, *sql-stream*))
255         (write-char #\) *sql-stream*)))
256   t)
257
258 (defmethod describe-table ((table sql-create-table)
259                            &key (database *default-database*))
260   (database-describe-table
261    database
262    (string-downcase (symbol-name (slot-value table 'name)))))
263
264 #+nil
265 (defmethod add-storage-class ((self database) (class symbol) &key (sequence t))
266   (let ((tablename (view-table (find-class class))))
267     (unless (tablep tablename)
268       (create-view-from-class class)
269       (when sequence
270         (create-sequence-from-class class)))))
271