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