r9450: 22 May 2004 Kevin Rosenberg
[clsql.git] / sql / table.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; $Id$
5 ;;;;
6 ;;;; The CLSQL Functional Data Definition Language (FDDL)
7 ;;;; including functions for schema manipulation. Currently supported
8 ;;;; SQL objects include tables, views, indexes, attributes and
9 ;;;; sequences.
10 ;;;;
11 ;;;; This file is part of CLSQL.
12 ;;;;
13 ;;;; CLSQL users are granted the rights to distribute and use this software
14 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
15 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
16 ;;;; *************************************************************************
17
18 (in-package #:clsql-sys)
19
20
21 ;; Utilities
22
23 (defun database-identifier (name database)
24   (sql-escape (etypecase name
25                 ;; honor case of strings
26                 (string name
27                         #+nil (convert-to-db-default-case name database))
28                 (sql-ident (sql-output name database))
29                 (symbol (sql-output name database)))))
30
31
32 ;; Tables 
33
34 (defun create-table (name description &key (database *default-database*)
35                           (constraints nil) (transactions t))
36   "Creates a table called NAME, which may be a string, symbol or
37 SQL table identifier, in DATABASE which defaults to
38 *DEFAULT-DATABASE*. DESCRIPTION is a list whose elements are
39 lists containing the attribute names, types, and other
40 constraints such as not-null or primary-key for each column in
41 the table.  CONSTRAINTS is a string representing an SQL table
42 constraint expression or a list of such strings. With MySQL
43 databases, if TRANSACTIONS is t an InnoDB table is created which
44 supports transactions."
45   (let* ((table-name (etypecase name 
46                        (symbol (sql-expression :attribute name))
47                        (string (sql-expression :attribute name))
48                        (sql-ident name)))
49          (stmt (make-instance 'sql-create-table
50                               :name table-name
51                               :columns description
52                               :modifiers constraints
53                               :transactions transactions)))
54     (execute-command stmt :database database)))
55
56 (defun drop-table (name &key (if-does-not-exist :error)
57                              (database *default-database*))
58   "Drops the table called NAME from DATABASE which defaults to
59 *DEFAULT-DATABASE*. If the table does not exist and
60 IF-DOES-NOT-EXIST is :ignore then DROP-TABLE returns nil whereas
61 an error is signalled if IF-DOES-NOT-EXIST is :error."
62   (let ((table-name (database-identifier name database)))
63     (ecase if-does-not-exist
64       (:ignore
65        (unless (table-exists-p table-name :database database)
66          (return-from drop-table nil)))
67       (:error
68        t))
69     
70     ;; Fixme: move to clsql-oracle
71     (let ((expr (concatenate 'string "DROP TABLE " table-name)))
72       (when (and (find-package 'clsql-oracle)
73                  (eq :oracle (database-type database))
74                  (eql 10 (slot-value database 
75                                      (intern (symbol-name '#:major-server-version)
76                                              (symbol-name '#:clsql-oracle)))))
77         (setq expr (concatenate 'string expr " PURGE")))
78
79       (execute-command expr :database database))))
80
81 (defun list-tables (&key (owner nil) (database *default-database*))
82   "Returns a list of strings representing table names in DATABASE
83 which defaults to *DEFAULT-DATABASE*. OWNER is nil by default
84 which means that only tables owned by users are listed. If OWNER
85 is a string denoting a user name, only tables owned by OWNER are
86 listed. If OWNER is :all then all tables are listed."
87   (database-list-tables database :owner owner))
88
89 (defun table-exists-p (name &key (owner nil) (database *default-database*))
90   "Tests for the existence of an SQL table called NAME in DATABASE
91 which defaults to *DEFAULT-DATABASE*. OWNER is nil by default
92 which means that only tables owned by users are examined. If
93 OWNER is a string denoting a user name, only tables owned by
94 OWNER are examined. If OWNER is :all then all tables are
95 examined."
96   (when (member (database-identifier name database)
97                 (list-tables :owner owner :database database)
98                 :test #'string-equal)
99     t))
100
101
102 ;; Views 
103
104 (defun create-view (name &key as column-list (with-check-option nil)
105                          (database *default-database*))
106   "Creates a view called NAME in DATABASE which defaults to
107 *DEFAULT-DATABASE*. The view is created using the query AS and
108 the columns of the view may be specified using the COLUMN-LIST
109 parameter. The WITH-CHECK-OPTION is nil by default but if it has
110 a non-nil value, then all insert/update commands on the view are
111 checked to ensure that the new data satisfy the query AS."
112   (let* ((view-name (etypecase name 
113                       (symbol (sql-expression :attribute name))
114                       (string (sql-expression :attribute (make-symbol name)))
115                       (sql-ident name)))
116          (stmt (make-instance 'sql-create-view
117                               :name view-name
118                               :column-list column-list
119                               :query as
120                               :with-check-option with-check-option)))
121     (execute-command stmt :database database)))
122
123 (defun drop-view (name &key (if-does-not-exist :error)
124                        (database *default-database*))
125   "Drops the view called NAME from DATABASE which defaults to
126 *DEFAULT-DATABASE*. If the view does not exist and
127 IF-DOES-NOT-EXIST is :ignore then DROP-VIEW returns nil whereas
128 an error is signalled if IF-DOES-NOT-EXIST is :error."
129   (let ((view-name (database-identifier name database)))
130     (ecase if-does-not-exist
131       (:ignore
132        (unless (view-exists-p view-name :database database)
133          (return-from drop-view)))
134       (:error
135        t))
136     (let ((expr (concatenate 'string "DROP VIEW " view-name)))
137       (execute-command expr :database database))))
138
139 (defun list-views (&key (owner nil) (database *default-database*))
140   "Returns a list of strings representing view names in DATABASE
141 which defaults to *DEFAULT-DATABASE*. OWNER is nil by default
142 which means that only views owned by users are listed. If OWNER
143 is a string denoting a user name, only views owned by OWNER are
144 listed. If OWNER is :all then all views are listed."
145   (database-list-views database :owner owner))
146
147 (defun view-exists-p (name &key (owner nil) (database *default-database*))
148   "Tests for the existence of an SQL view called NAME in DATABASE
149 which defaults to *DEFAULT-DATABASE*. OWNER is nil by default
150 which means that only views owned by users are examined. If OWNER
151 is a string denoting a user name, only views owned by OWNER are
152 examined. If OWNER is :all then all views are examined."
153   (when (member (database-identifier name database)
154                 (list-views :owner owner :database database)
155                 :test #'string-equal)
156     t))
157
158
159 ;; Indexes 
160
161 (defun create-index (name &key on (unique nil) attributes
162                           (database *default-database*))
163   "Creates an index called NAME on the table specified by ON in
164 DATABASE which default to *DEFAULT-DATABASE*. The table
165 attributes to use in constructing the index NAME are specified by
166 ATTRIBUTES. The UNIQUE argument is nil by default but if it has a
167 non-nil value then the indexed attributes must have unique
168 values."
169   (let* ((index-name (database-identifier name database))
170          (table-name (database-identifier on database))
171          (attributes (mapcar #'(lambda (a) (database-identifier a database)) (listify attributes)))
172          (stmt (format nil "CREATE ~A INDEX ~A ON ~A (~{~A~^, ~})"
173                        (if unique "UNIQUE" "")
174                        index-name table-name attributes)))
175     (execute-command stmt :database database)))
176
177 (defun drop-index (name &key (if-does-not-exist :error)
178                         (on nil)
179                         (database *default-database*))
180   "Drops the index called NAME in DATABASE which defaults to
181 *DEFAULT-DATABASE*. If the index does not exist and
182 IF-DOES-NOT-EXIST is :ignore then DROP-INDEX returns nil whereas
183 an error is signalled if IF-DOES-NOT-EXIST is :error. The
184 argument ON allows the optional specification of a table to drop
185 the index from."
186   (let ((index-name (database-identifier name database)))
187     (ecase if-does-not-exist
188       (:ignore
189        (unless (index-exists-p index-name :database database)
190          (return-from drop-index)))
191       (:error t))
192     (unless (db-type-use-column-on-drop-index? 
193              (database-underlying-type database))
194       (setq on nil))
195     (execute-command (format nil "DROP INDEX ~A~A" index-name
196                              (if (null on) ""
197                                  (concatenate 'string " ON "
198                                               (database-identifier on database))))
199                      :database database)))
200
201 (defun list-indexes (&key (owner nil) (database *default-database*))
202   "Returns a list of strings representing index names in DATABASE
203 which defaults to *DEFAULT-DATABASE*. OWNER is nil by default
204 which means that only indexes owned by users are listed. If OWNER
205 is a string denoting a user name, only indexes owned by OWNER are
206 listed. If OWNER is :all then all indexes are listed."
207   (database-list-indexes database :owner owner))
208
209 (defun list-table-indexes (table &key (owner nil)
210                                       (database *default-database*))
211   "Returns a list of strings representing index names on the
212 table specified by TABLE in DATABASE which defaults to
213 *DEFAULT-DATABASE*. OWNER is nil by default which means that only
214 indexes owned by users are listed. If OWNER is a string denoting
215 a user name, only indexes owned by OWNER are listed. If OWNER
216 is :all then all indexes are listed."
217   (database-list-table-indexes (database-identifier table database)
218                                database :owner owner))
219   
220 (defun index-exists-p (name &key (owner nil) (database *default-database*))
221   "Tests for the existence of an SQL index called NAME in DATABASE
222 which defaults to *DEFAULT-DATABASE*. OWNER is nil by default
223 which means that only indexes owned by users are examined. If
224 OWNER is a string denoting a user name, only indexes owned by
225 OWNER are examined. If OWNER is :all then all indexes are
226 examined."
227   (when (member (database-identifier name database)
228                 (list-indexes :owner owner :database database)
229                 :test #'string-equal)
230     t))
231
232 ;; Attributes 
233
234 (defvar *cache-table-queries-default* nil 
235   "Specifies the default behaivour for caching of attribute
236   types. Meaningful values are t, nil and :flush as described for
237   the action argument to CACHE-TABLE-QUERIES.")
238
239 (defun cache-table-queries (table &key (action nil) (database *default-database*))
240   "Controls the caching of attribute type information on the
241 table specified by TABLE in DATABASE which defaults to
242 *DEFAULT-DATABASE*. ACTION specifies the caching behaviour to
243 adopt. If its value is t then attribute type information is
244 cached whereas if its value is nil then attribute type
245 information is not cached. If ACTION is :flush then all existing
246 type information in the cache for TABLE is removed, but caching
247 is still enabled. TABLE may be a string representing a table for
248 which the caching action is to be taken while the caching action
249 is applied to all tables if TABLE is t. Alternativly, when TABLE
250 is :default, the default caching action specified by
251 *CACHE-TABLE-QUERIES-DEFAULT* is applied to all table for which a
252 caching action has not been explicitly set."
253   (with-slots (attribute-cache) database
254     (cond
255       ((stringp table)
256        (multiple-value-bind (val found) (gethash table attribute-cache)
257          (cond
258            ((and found (eq action :flush))
259             (setf (gethash table attribute-cache) (list t nil)))
260            ((and found (eq action t))
261             (setf (gethash table attribute-cache) (list t (second val))))
262            ((and found (null action))
263             (setf (gethash table attribute-cache) (list nil nil)))
264            ((not found)
265             (setf (gethash table attribute-cache) (list action nil))))))
266       ((eq table t)
267        (maphash (lambda (k v)
268                   (cond
269                     ((eq action :flush)
270                      (setf (gethash k attribute-cache) (list t nil)))
271                     ((null action)
272                      (setf (gethash k attribute-cache) (list nil nil)))
273                     ((eq t action)
274                      (setf (gethash k attribute-cache) (list t (second v))))))
275                 attribute-cache))
276       ((eq table :default)
277        (maphash (lambda (k v)
278                   (when (eq (first v) :unspecified)
279                     (cond
280                       ((eq action :flush)
281                        (setf (gethash k attribute-cache) (list t nil)))
282                       ((null action)
283                        (setf (gethash k attribute-cache) (list nil nil)))
284                       ((eq t action)
285                        (setf (gethash k attribute-cache) (list t (second v)))))))
286                 attribute-cache))))
287   (values))
288                   
289
290 (defun list-attributes (name &key (owner nil) (database *default-database*))
291   "Returns a list of strings representing the attributes of table
292 NAME in DATABASE which defaults to *DEFAULT-DATABASE*. OWNER is
293 nil by default which means that only attributes owned by users
294 are listed. If OWNER is a string denoting a user name, only
295 attributes owned by OWNER are listed. If OWNER is :all then all
296 attributes are listed."
297   (database-list-attributes (database-identifier name database) database 
298                             :owner owner))
299
300 (defun attribute-type (attribute table &key (owner nil)
301                                  (database *default-database*))
302   "Returns a string representing the field type of the supplied
303 attribute ATTRIBUTE in the table specified by TABLE in DATABASE
304 which defaults to *DEFAULT-DATABASE*. OWNER is nil by default
305 which means that the attribute specified by ATTRIBUTE, if it
306 exists, must be user owned else nil is returned. If OWNER is a
307 string denoting a user name, the attribute, if it exists, must be
308 owned by OWNER else nil is returned, whereas if OWNER is :all
309 then the attribute, if it exists, will be returned regardless of
310 its owner."
311   (database-attribute-type (database-identifier attribute database)
312                            (database-identifier table database)
313                            database
314                            :owner owner))
315
316 (defun list-attribute-types (table &key (owner nil)
317                                    (database *default-database*))
318   "Returns a list containing information about the SQL types of
319 each of the attributes in the table specified by TABLE in
320 DATABASE which has a default value of *DEFAULT-DATABASE*. OWNER
321 is nil by default which means that only attributes owned by users
322 are listed. If OWNER is a string denoting a user name, only
323 attributes owned by OWNER are listed. If OWNER is :all then all
324 attributes are listed. The elements of the returned list are
325 lists where the first element is the name of the attribute, the
326 second element is its SQL type, the third is the type precision,
327 the fourth is the scale of the attribute and the fifth is 1 if
328 the attribute accepts null values and otherwise 0."
329   (with-slots (attribute-cache) database
330     (let ((table-ident (database-identifier table database)))
331       (multiple-value-bind (val found) (gethash table-ident attribute-cache)
332         (if (and found (second val))
333             (second val)
334             (let ((types (mapcar #'(lambda (attribute)
335                                      (cons attribute
336                                            (multiple-value-list
337                                             (database-attribute-type
338                                              (database-identifier attribute 
339                                                                   database)
340                                              table-ident
341                                              database
342                                              :owner owner))))
343                                  (list-attributes table :database database 
344                                                   :owner owner))))
345               (cond
346                 ((and (not found) (eq t *cache-table-queries-default*))
347                  (setf (gethash table-ident attribute-cache) 
348                        (list :unspecified types)))
349                 ((and found (eq t (first val)) 
350                       (setf (gethash table-ident attribute-cache) 
351                             (list t types)))))
352               types))))))
353   
354
355 ;; Sequences 
356
357 (defun create-sequence (name &key (database *default-database*))
358   "Creates a sequence called NAME in DATABASE which defaults to
359 *DEFAULT-DATABASE*."
360   (let ((sequence-name (database-identifier name database)))
361     (database-create-sequence sequence-name database))
362   (values))
363
364 (defun drop-sequence (name &key (if-does-not-exist :error)
365                            (database *default-database*))
366   "Drops the sequence called NAME from DATABASE which defaults to
367 *DEFAULT-DATABASE*. If the sequence does not exist and
368 IF-DOES-NOT-EXIST is :ignore then DROP-SEQUENCE returns nil
369 whereas an error is signalled if IF-DOES-NOT-EXIST is :error."
370   (let ((sequence-name (database-identifier name database)))
371     (ecase if-does-not-exist
372       (:ignore
373        (unless (sequence-exists-p sequence-name :database database)
374          (return-from drop-sequence)))
375       (:error t))
376     (database-drop-sequence sequence-name database))
377   (values))
378
379 (defun list-sequences (&key (owner nil) (database *default-database*))
380   "Returns a list of strings representing sequence names in
381 DATABASE which defaults to *DEFAULT-DATABASE*. OWNER is nil by
382 default which means that only sequences owned by users are
383 listed. If OWNER is a string denoting a user name, only sequences
384 owned by OWNER are listed. If OWNER is :all then all sequences
385 are listed."
386   (database-list-sequences database :owner owner))
387
388 (defun sequence-exists-p (name &key (owner nil)
389                                (database *default-database*))
390   "Tests for the existence of an SQL sequence called NAME in
391 DATABASE which defaults to *DEFAULT-DATABASE*. OWNER is nil by
392 default which means that only sequences owned by users are
393 examined. If OWNER is a string denoting a user name, only
394 sequences owned by OWNER are examined. If OWNER is :all then all
395 sequences are examined."
396   (when (member (database-identifier name database)
397                 (list-sequences :owner owner :database database)
398                 :test #'string-equal)
399     t))
400   
401 (defun sequence-next (name &key (database *default-database*))
402   "Return the next value in the sequence called NAME in DATABASE
403   which defaults to *DEFAULT-DATABASE*."
404   (database-sequence-next (database-identifier name database) database))
405
406 (defun set-sequence-position (name position &key (database *default-database*))
407   "Explicitly set the the position of the sequence called NAME in
408 DATABASE, which defaults to *DEFAULT-DATABSE*, to POSITION."
409   (database-set-sequence-position (database-identifier name database) 
410                                   position database))
411
412 (defun sequence-last (name &key (database *default-database*))
413   "Return the last value of the sequence called NAME in DATABASE
414   which defaults to *DEFAULT-DATABASE*."
415   (database-sequence-last (database-identifier name database) database))
416