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