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