r9657: Cleanup and document the FDDL.
[clsql.git] / sql / fddl.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*) (on nil))
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. The keyword
207 argument ON limits the results to indexes on the specified
208 tables. Meaningful values for ON are nil (the default) which
209 means that all tables are considered, a string, symbol or SQL
210 expression representing a table name in DATABASE or a list of
211 such table identifiers."
212   (if (null on) 
213       (database-list-indexes database :owner owner)
214       (let ((tables (typecase on (cons on) (t (list on)))))
215         (reduce #'append 
216                 (mapcar #'(lambda (table) (database-list-table-indexes 
217                                            (database-identifier table database)
218                                            database :owner owner))
219                         tables)))))
220   
221 (defun index-exists-p (name &key (owner nil) (database *default-database*))
222   "Tests for the existence of an SQL index called NAME in DATABASE
223 which defaults to *DEFAULT-DATABASE*. OWNER is nil by default
224 which means that only indexes owned by users are examined. If
225 OWNER is a string denoting a user name, only indexes owned by
226 OWNER are examined. If OWNER is :all then all indexes are
227 examined."
228   (when (member (database-identifier name database)
229                 (list-indexes :owner owner :database database)
230                 :test #'string-equal)
231     t))
232
233 ;; Attributes 
234
235 (defvar *cache-table-queries-default* nil 
236   "Specifies the default behaivour for caching of attribute
237   types. Meaningful values are t, nil and :flush as described for
238   the action argument to CACHE-TABLE-QUERIES.")
239
240 (defun cache-table-queries (table &key (action nil) (database *default-database*))
241   "Controls the caching of attribute type information on the
242 table specified by TABLE in DATABASE which defaults to
243 *DEFAULT-DATABASE*. ACTION specifies the caching behaviour to
244 adopt. If its value is t then attribute type information is
245 cached whereas if its value is nil then attribute type
246 information is not cached. If ACTION is :flush then all existing
247 type information in the cache for TABLE is removed, but caching
248 is still enabled. TABLE may be a string representing a table for
249 which the caching action is to be taken while the caching action
250 is applied to all tables if TABLE is t. Alternativly, when TABLE
251 is :default, the default caching action specified by
252 *CACHE-TABLE-QUERIES-DEFAULT* is applied to all table for which a
253 caching action has not been explicitly set."
254   (with-slots (attribute-cache) database
255     (cond
256       ((stringp table)
257        (multiple-value-bind (val found) (gethash table attribute-cache)
258          (cond
259            ((and found (eq action :flush))
260             (setf (gethash table attribute-cache) (list t nil)))
261            ((and found (eq action t))
262             (setf (gethash table attribute-cache) (list t (second val))))
263            ((and found (null action))
264             (setf (gethash table attribute-cache) (list nil nil)))
265            ((not found)
266             (setf (gethash table attribute-cache) (list action nil))))))
267       ((eq table t)
268        (maphash (lambda (k v)
269                   (cond
270                     ((eq action :flush)
271                      (setf (gethash k attribute-cache) (list t nil)))
272                     ((null action)
273                      (setf (gethash k attribute-cache) (list nil nil)))
274                     ((eq t action)
275                      (setf (gethash k attribute-cache) (list t (second v))))))
276                 attribute-cache))
277       ((eq table :default)
278        (maphash (lambda (k v)
279                   (when (eq (first v) :unspecified)
280                     (cond
281                       ((eq action :flush)
282                        (setf (gethash k attribute-cache) (list t nil)))
283                       ((null action)
284                        (setf (gethash k attribute-cache) (list nil nil)))
285                       ((eq t action)
286                        (setf (gethash k attribute-cache) (list t (second v)))))))
287                 attribute-cache))))
288   (values))
289                   
290
291 (defun list-attributes (name &key (owner nil) (database *default-database*))
292   "Returns a list of strings representing the attributes of table
293 NAME in DATABASE which defaults to *DEFAULT-DATABASE*. OWNER is
294 nil by default which means that only attributes owned by users
295 are listed. If OWNER is a string denoting a user name, only
296 attributes owned by OWNER are listed. If OWNER is :all then all
297 attributes are listed."
298   (database-list-attributes (database-identifier name database) database 
299                             :owner owner))
300
301 (defun attribute-type (attribute table &key (owner nil)
302                                  (database *default-database*))
303   "Returns a keyword representing the vendor-specific field type
304 of the supplied attribute ATTRIBUTE in the table specified by
305 TABLE in DATABASE which defaults to *DEFAULT-DATABASE*. OWNER is
306 nil by default which means that the attribute specified by
307 ATTRIBUTE, if it exists, must be user owned else nil is
308 returned. If OWNER is a string denoting a user name, the
309 attribute, if it exists, must be owned by OWNER else nil is
310 returned, whereas if OWNER is :all then the attribute, if it
311 exists, will be returned regardless of its owner."
312   (database-attribute-type (database-identifier attribute database)
313                            (database-identifier table database)
314                            database
315                            :owner owner))
316
317 (defun list-attribute-types (table &key (owner nil)
318                                    (database *default-database*))
319   "Returns a list containing information about the SQL types of
320 each of the attributes in the table specified by TABLE in
321 DATABASE which has a default value of *DEFAULT-DATABASE*. OWNER
322 is nil by default which means that only attributes owned by users
323 are listed. If OWNER is a string denoting a user name, only
324 attributes owned by OWNER are listed. If OWNER is :all then all
325 attributes are listed. The elements of the returned list are
326 lists where the first element is the name of the attribute, the
327 second element is its SQL type, the third is the type precision,
328 the fourth is the scale of the attribute and the fifth is 1 if
329 the attribute accepts null values and otherwise 0."
330   (with-slots (attribute-cache) database
331     (let ((table-ident (database-identifier table database)))
332       (multiple-value-bind (val found) (gethash table-ident attribute-cache)
333         (if (and found (second val))
334             (second val)
335             (let ((types (mapcar #'(lambda (attribute)
336                                      (cons attribute
337                                            (multiple-value-list
338                                             (database-attribute-type
339                                              (database-identifier attribute 
340                                                                   database)
341                                              table-ident
342                                              database
343                                              :owner owner))))
344                                  (list-attributes table :database database 
345                                                   :owner owner))))
346               (cond
347                 ((and (not found) (eq t *cache-table-queries-default*))
348                  (setf (gethash table-ident attribute-cache) 
349                        (list :unspecified types)))
350                 ((and found (eq t (first val)) 
351                       (setf (gethash table-ident attribute-cache) 
352                             (list t types)))))
353               types))))))
354   
355
356 ;; Sequences 
357
358 (defun create-sequence (name &key (database *default-database*))
359   "Creates a sequence called NAME in DATABASE which defaults to
360 *DEFAULT-DATABASE*."
361   (let ((sequence-name (database-identifier name database)))
362     (database-create-sequence sequence-name database))
363   (values))
364
365 (defun drop-sequence (name &key (if-does-not-exist :error)
366                            (database *default-database*))
367   "Drops the sequence called NAME from DATABASE which defaults to
368 *DEFAULT-DATABASE*. If the sequence does not exist and
369 IF-DOES-NOT-EXIST is :ignore then DROP-SEQUENCE returns nil
370 whereas an error is signalled if IF-DOES-NOT-EXIST is :error."
371   (let ((sequence-name (database-identifier name database)))
372     (ecase if-does-not-exist
373       (:ignore
374        (unless (sequence-exists-p sequence-name :database database)
375          (return-from drop-sequence)))
376       (:error t))
377     (database-drop-sequence sequence-name database))
378   (values))
379
380 (defun list-sequences (&key (owner nil) (database *default-database*))
381   "Returns a list of strings representing sequence names in
382 DATABASE which defaults to *DEFAULT-DATABASE*. OWNER is nil by
383 default which means that only sequences owned by users are
384 listed. If OWNER is a string denoting a user name, only sequences
385 owned by OWNER are listed. If OWNER is :all then all sequences
386 are listed."
387   (database-list-sequences database :owner owner))
388
389 (defun sequence-exists-p (name &key (owner nil)
390                                (database *default-database*))
391   "Tests for the existence of an SQL sequence called NAME in
392 DATABASE which defaults to *DEFAULT-DATABASE*. OWNER is nil by
393 default which means that only sequences owned by users are
394 examined. If OWNER is a string denoting a user name, only
395 sequences owned by OWNER are examined. If OWNER is :all then all
396 sequences are examined."
397   (when (member (database-identifier name database)
398                 (list-sequences :owner owner :database database)
399                 :test #'string-equal)
400     t))
401   
402 (defun sequence-next (name &key (database *default-database*))
403   "Increment and return the next value in the sequence called
404   NAME in DATABASE which defaults to *DEFAULT-DATABASE*."
405   (database-sequence-next (database-identifier name database) database))
406
407 (defun set-sequence-position (name position &key (database *default-database*))
408   "Explicitly set the the position of the sequence called NAME in
409 DATABASE, which defaults to *DEFAULT-DATABSE*, to POSITION which
410 is returned."
411   (database-set-sequence-position (database-identifier name database) 
412                                   position database))
413
414 (defun sequence-last (name &key (database *default-database*))
415   "Return the last value allocated in the sequence called NAME in DATABASE
416   which defaults to *DEFAULT-DATABASE*."
417   (database-sequence-last (database-identifier name database) database))
418