r9162: case-sensitive changes
[clsql.git] / sql / objects.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;;
4 ;;;; $Id$
5 ;;;;
6 ;;;; The CLSQL Object Oriented Data Definitional Language (OODDL)
7 ;;;; and Object Oriented Data Manipulation Language (OODML).
8 ;;;;
9 ;;;; This file is part of CLSQL.
10 ;;;;
11 ;;;; CLSQL users are granted the rights to distribute and use this software
12 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
13 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
14 ;;;; *************************************************************************
15
16 (in-package #:clsql-sys)
17
18 (defclass standard-db-object ()
19   ((view-database :initform nil :initarg :view-database :reader view-database
20     :db-kind :virtual))
21   (:metaclass standard-db-class)
22   (:documentation "Superclass for all CLSQL View Classes."))
23
24 (defvar *db-deserializing* nil)
25 (defvar *db-initializing* nil)
26
27 (defmethod slot-value-using-class ((class standard-db-class) instance slot-def)
28   (declare (optimize (speed 3)))
29   (unless *db-deserializing*
30     (let* ((slot-name (%svuc-slot-name slot-def))
31            (slot-object (%svuc-slot-object slot-def class))
32            (slot-kind (view-class-slot-db-kind slot-object)))
33       (when (and (eql slot-kind :join)
34                  (not (slot-boundp instance slot-name)))
35         (let ((*db-deserializing* t))
36           (if (view-database instance)
37               (setf (slot-value instance slot-name)
38                     (fault-join-slot class instance slot-object))
39               (setf (slot-value instance slot-name) nil))))))
40   (call-next-method))
41
42 (defmethod (setf slot-value-using-class) (new-value (class standard-db-class)
43                                           instance slot)
44   (declare (ignore new-value instance slot))
45   (call-next-method))
46
47 (defmethod initialize-instance :around ((object standard-db-object)
48                                         &rest all-keys &key &allow-other-keys)
49   (declare (ignore all-keys))
50   (let ((*db-initializing* t))
51     (call-next-method)
52     (unless *db-deserializing*
53       #+nil (created-object object)
54       (update-records-from-instance object))))
55
56 (defun sequence-from-class (view-class-name)
57   (sql-escape
58    (concatenate
59     'string
60     (symbol-name (view-table (find-class view-class-name)))
61     "-SEQ")))
62
63 (defun create-sequence-from-class (view-class-name
64                                    &key (database *default-database*))
65   (create-sequence (sequence-from-class view-class-name) :database database))
66
67 (defun drop-sequence-from-class (view-class-name
68                                  &key (if-does-not-exist :error)
69                                  (database *default-database*))
70   (drop-sequence (sequence-from-class view-class-name)
71                  :if-does-not-exist if-does-not-exist
72                  :database database))
73
74 ;;
75 ;; Build the database tables required to store the given view class
76 ;;
77
78 (defmethod database-pkey-constraint ((class standard-db-class) database)
79   (let ((keylist (mapcar #'view-class-slot-column (keyslots-for-class class))))
80     (when keylist 
81       (convert-to-db-default-case
82        (format nil "CONSTRAINT ~APK PRIMARY KEY~A"
83                (database-output-sql (view-table class) database)
84                (database-output-sql keylist database))
85        database))))
86
87
88 (defun create-view-from-class (view-class-name
89                                &key (database *default-database*))
90   "Creates a view in DATABASE based on VIEW-CLASS-NAME which defines
91 the view. The argument DATABASE has a default value of
92 *DEFAULT-DATABASE*."
93   (let ((tclass (find-class view-class-name)))
94     (if tclass
95         (let ((*default-database* database))
96           (%install-class tclass database))
97         (error "Class ~s not found." view-class-name)))
98   (values))
99
100 (defmethod %install-class ((self standard-db-class) database &aux schemadef)
101   (dolist (slotdef (ordered-class-slots self))
102     (let ((res (database-generate-column-definition (class-name self)
103                                                     slotdef database)))
104       (when res 
105         (push res schemadef))))
106   (unless schemadef
107     (error "Class ~s has no :base slots" self))
108   (create-table (sql-expression :table (view-table self)) schemadef
109                 :database database
110                 :constraints (database-pkey-constraint self database))
111   (push self (database-view-classes database))
112   t)
113
114 ;;
115 ;; Drop the tables which store the given view class
116 ;;
117
118 (defun drop-view-from-class (view-class-name &key (database *default-database*))
119   "Deletes a view or base table from DATABASE based on VIEW-CLASS-NAME
120 which defines that view. The argument DATABASE has a default value of
121 *DEFAULT-DATABASE*."
122   (let ((tclass (find-class view-class-name)))
123     (if tclass
124         (let ((*default-database* database))
125           (%uninstall-class tclass))
126         (error "Class ~s not found." view-class-name)))
127   (values))
128
129 (defun %uninstall-class (self &key (database *default-database*))
130   (drop-table (sql-expression :table (view-table self))
131               :if-does-not-exist :ignore
132               :database database)
133   (setf (database-view-classes database)
134         (remove self (database-view-classes database))))
135
136
137 ;;
138 ;; List all known view classes
139 ;;
140
141 (defun list-classes (&key (test #'identity)
142                      (root-class (find-class 'standard-db-object))
143                      (database *default-database*))
144   "The LIST-CLASSES function collects all the classes below
145 ROOT-CLASS, which defaults to standard-db-object, that are connected
146 to the supplied DATABASE and which satisfy the TEST function. The
147 default for the TEST argument is identity. By default, LIST-CLASSES
148 returns a list of all the classes connected to the default database,
149 *DEFAULT-DATABASE*."
150   (flet ((find-superclass (class) 
151            (member root-class (class-precedence-list class))))
152     (let ((view-classes (and database (database-view-classes database))))
153       (when view-classes
154         (remove-if #'(lambda (c) (or (not (funcall test c))
155                                      (not (find-superclass c))))
156                    view-classes)))))
157
158 ;;
159 ;; Define a new view class
160 ;;
161
162 (defmacro def-view-class (class supers slots &rest options)
163   "Extends the syntax of defclass to allow special slots to be mapped
164 onto the attributes of database views. The macro DEF-VIEW-CLASS
165 creates a class called CLASS which maps onto a database view. Such a
166 class is called a View Class. The macro DEF-VIEW-CLASS extends the
167 syntax of DEFCLASS to allow special base slots to be mapped onto the
168 attributes of database views (presently single tables). When a select
169 query that names a View Class is submitted, then the corresponding
170 database view is queried, and the slots in the resulting View Class
171 instances are filled with attribute values from the database. If
172 SUPERS is nil then STANDARD-DB-OBJECT automatically becomes the
173 superclass of the newly-defined View Class."
174   `(progn
175      (defclass ,class ,supers ,slots ,@options
176                (:metaclass standard-db-class))
177      (finalize-inheritance (find-class ',class))))
178
179 (defun keyslots-for-class (class)
180   (slot-value class 'key-slots))
181
182 (defun key-qualifier-for-instance (obj &key (database *default-database*))
183   (let ((tb (view-table (class-of obj))))
184     (flet ((qfk (k)
185              (sql-operation '==
186                             (sql-expression :attribute
187                                             (view-class-slot-column k)
188                                             :table tb)
189                             (db-value-from-slot
190                              k
191                              (slot-value obj (slot-definition-name k))
192                              database))))
193       (let* ((keys (keyslots-for-class (class-of obj)))
194              (keyxprs (mapcar #'qfk (reverse keys))))
195         (cond
196           ((= (length keyxprs) 0) nil)
197           ((= (length keyxprs) 1) (car keyxprs))
198           ((> (length keyxprs) 1) (apply #'sql-operation 'and keyxprs)))))))
199
200 ;;
201 ;; Function used by 'generate-selection-list'
202 ;;
203
204 (defun generate-attribute-reference (vclass slotdef)
205   (cond
206    ((eq (view-class-slot-db-kind slotdef) :base)
207     (sql-expression :attribute (view-class-slot-column slotdef)
208                     :table (view-table vclass)))
209    ((eq (view-class-slot-db-kind slotdef) :key)
210     (sql-expression :attribute (view-class-slot-column slotdef)
211                     :table (view-table vclass)))
212    (t nil)))
213
214 ;;
215 ;; Function used by 'find-all'
216 ;;
217
218 (defun generate-selection-list (vclass)
219   (let ((sels nil))
220     (dolist (slotdef (ordered-class-slots vclass))
221       (let ((res (generate-attribute-reference vclass slotdef)))
222         (when res
223           (push (cons slotdef res) sels))))
224     (if sels
225         sels
226         (error "No slots of type :base in view-class ~A" (class-name vclass)))))
227
228 ;;
229 ;; Used by 'create-view-from-class'
230 ;;
231
232
233 (defmethod database-generate-column-definition (class slotdef database)
234   (declare (ignore database class))
235   (when (member (view-class-slot-db-kind slotdef) '(:base :key))
236     (let ((cdef
237            (list (sql-expression :attribute (view-class-slot-column slotdef))
238                  (slot-type slotdef))))
239       (setf cdef (append cdef (list (view-class-slot-db-type slotdef))))
240       (let ((const (view-class-slot-db-constraints slotdef)))
241         (when const 
242           (setq cdef (append cdef (list const)))))
243       cdef)))
244
245 ;;
246 ;; Called by 'get-slot-values-from-view'
247 ;;
248
249 (declaim (inline delistify))
250 (defun delistify (list)
251   (if (listp list)
252       (car list)
253       list))
254
255 (defun slot-type (slotdef)
256   (specified-type slotdef))
257
258 (defvar *update-context* nil)
259
260 (defmethod update-slot-from-db ((instance standard-db-object) slotdef value)
261   (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
262   (let* ((slot-reader (view-class-slot-db-reader slotdef))
263          (slot-name   (slot-definition-name slotdef))
264          (slot-type   (slot-type slotdef))
265          (*update-context* (cons (type-of instance) slot-name)))
266     (cond ((and value (null slot-reader))
267            (setf (slot-value instance slot-name)
268                  (read-sql-value value (delistify slot-type)
269                                  (view-database instance))))
270           ((null value)
271            (update-slot-with-null instance slot-name slotdef))
272           ((typep slot-reader 'string)
273            (setf (slot-value instance slot-name)
274                  (format nil slot-reader value)))
275           ((typep slot-reader 'function)
276            (setf (slot-value instance slot-name)
277                  (apply slot-reader (list value))))
278           (t
279            (error "Slot reader is of an unusual type.")))))
280
281 (defmethod key-value-from-db (slotdef value database) 
282   (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
283   (let ((slot-reader (view-class-slot-db-reader slotdef))
284         (slot-type (slot-type slotdef)))
285     (cond ((and value (null slot-reader))
286            (read-sql-value value (delistify slot-type) database))
287           ((null value)
288            nil)
289           ((typep slot-reader 'string)
290            (format nil slot-reader value))
291           ((typep slot-reader 'function)
292            (apply slot-reader (list value)))
293           (t
294            (error "Slot reader is of an unusual type.")))))
295
296 (defun db-value-from-slot (slotdef val database)
297   (let ((dbwriter (view-class-slot-db-writer slotdef))
298         (dbtype (slot-type slotdef)))
299     (typecase dbwriter
300       (string (format nil dbwriter val))
301       (function (apply dbwriter (list val)))
302       (t
303        (typecase dbtype
304          (cons
305           (database-output-sql-as-type (car dbtype) val database))
306          (t
307           (database-output-sql-as-type dbtype val database)))))))
308
309 (defun check-slot-type (slotdef val)
310   (let* ((slot-type (slot-type slotdef))
311          (basetype (if (listp slot-type) (car slot-type) slot-type)))
312     (when (and slot-type val)
313       (unless (typep val basetype)
314         (error 'clsql-type-error
315                :slotname (slot-definition-name slotdef)
316                :typespec slot-type
317                :value val)))))
318
319 ;;
320 ;; Called by find-all
321 ;;
322
323 (defmethod get-slot-values-from-view (obj slotdeflist values)
324     (flet ((update-slot (slot-def values)
325              (update-slot-from-db obj slot-def values)))
326       (mapc #'update-slot slotdeflist values)
327       obj))
328
329 (defgeneric update-record-from-slot (object slot &key database)
330   (:documentation
331    "The generic function UPDATE-RECORD-FROM-SLOT updates an individual
332 data item in the column represented by SLOT. The DATABASE is only used
333 if OBJECT is not yet associated with any database, in which case a
334 record is created in DATABASE. Only SLOT is initialized in this case;
335 other columns in the underlying database receive default values. The
336 argument SLOT is the CLOS slot name; the corresponding column names
337 are derived from the View Class definition."))
338    
339 (defmethod update-record-from-slot ((obj standard-db-object) slot &key
340                                         (database *default-database*))
341   (let* ((vct (view-table (class-of obj)))
342          (sd (slotdef-for-slot-with-class slot (class-of obj))))
343     (check-slot-type sd (slot-value obj slot))
344     (let* ((att (view-class-slot-column sd))
345            (val (db-value-from-slot sd (slot-value obj slot) database)))
346       (cond ((and vct sd (view-database obj))
347              (update-records (sql-expression :table vct)
348                              :attributes (list (sql-expression
349                                                 :attribute att))
350                              :values (list val)
351                              :where (key-qualifier-for-instance
352                                      obj :database database)
353                              :database (view-database obj)))
354             ((and vct sd (not (view-database obj)))
355              (warn "Ignoring (install-instance obj :database database))")
356              t)
357             (t
358              (error "Unable to update record.")))))
359   t)
360
361 (defgeneric update-record-from-slots (object slots &key database)
362   (:documentation 
363    "The generic function UPDATE-RECORD-FROM-SLOTS updates data in the
364 columns represented by SLOTS. The DATABASE is only used if OBJECT is
365 not yet associated with any database, in which case a record is
366 created in DATABASE. Only slots are initialized in this case; other
367 columns in the underlying database receive default values. The
368 argument SLOTS contains the CLOS slot names; the corresponding column
369 names are derived from the view class definition."))
370
371 (defmethod update-record-from-slots ((obj standard-db-object) slots &key
372                                      (database *default-database*))
373   (let* ((vct (view-table (class-of obj)))
374          (sds (slotdefs-for-slots-with-class slots (class-of obj)))
375          (avps (mapcar #'(lambda (s)
376                            (let ((val (slot-value
377                                        obj (slot-definition-name s))))
378                              (check-slot-type s val)
379                              (list (sql-expression
380                                     :attribute (view-class-slot-column s))
381                                    (db-value-from-slot s val database))))
382                        sds)))
383     (cond ((and avps (view-database obj))
384            (update-records (sql-expression :table vct)
385                            :av-pairs avps
386                            :where (key-qualifier-for-instance
387                                    obj :database database)
388                            :database (view-database obj)))
389           ((and avps (not (view-database obj)))
390            (insert-records :into (sql-expression :table vct)
391                            :av-pairs avps
392                            :database database)
393            (setf (slot-value obj 'view-database) database))
394           (t
395            (error "Unable to update records"))))
396   (values))
397
398 (defgeneric update-records-from-instance (object &key database)
399   (:documentation
400    "Using an instance of a view class, update the database table that
401 stores its instance data. If the instance is already associated with a
402 database, that database is used, and database is ignored. If instance
403 is not yet associated with a database, a record is created for
404 instance in the appropriate table of database and the instance becomes
405 associated with that database."))
406
407 (defmethod update-records-from-instance ((obj standard-db-object)
408                                          &key (database *default-database*))
409   (labels ((slot-storedp (slot)
410              (and (member (view-class-slot-db-kind slot) '(:base :key))
411                   (slot-boundp obj (slot-definition-name slot))))
412            (slot-value-list (slot)
413              (let ((value (slot-value obj (slot-definition-name slot))))
414                (check-slot-type slot value)
415                (list (sql-expression :attribute (view-class-slot-column slot))
416                      (db-value-from-slot slot value database)))))
417     (let* ((view-class (class-of obj))
418            (view-class-table (view-table view-class))
419            (slots (remove-if-not #'slot-storedp (ordered-class-slots view-class)))
420            (record-values (mapcar #'slot-value-list slots)))
421       (unless record-values
422         (error "No settable slots."))
423       (if (view-database obj)
424           (update-records (sql-expression :table view-class-table)
425                           :av-pairs record-values
426                           :where (key-qualifier-for-instance
427                                   obj :database database)
428                           :database (view-database obj))
429           (progn
430             (insert-records :into (sql-expression :table view-class-table)
431                             :av-pairs record-values
432                             :database database)
433             (setf (slot-value obj 'view-database) database)))
434       (values))))
435
436 (defgeneric delete-instance-records (instance)
437   (:documentation
438    "Deletes the records represented by INSTANCE from the database
439 associated with it. If instance has no associated database, an error
440 is signalled."))
441
442 (defmethod delete-instance-records ((instance standard-db-object))
443   (let ((vt (sql-expression :table (view-table (class-of instance))))
444         (vd (or (view-database instance) *default-database*)))
445     (when vd
446       (let ((qualifier (key-qualifier-for-instance instance :database vd)))
447         (delete-records :from vt :where qualifier :database vd)
448         (setf (slot-value instance 'view-database) nil))))
449   #+ignore (odcl::deleted-object object))
450
451 (defgeneric update-instance-from-records (instance &key database)
452   (:documentation
453    "Updates the values in the slots of the View Class instance
454 INSTANCE using the data in the database DATABASE which defaults to the
455 database that INSTANCE is associated with, or the value of
456 *DEFAULT-DATABASE*."))
457
458 (defmethod update-instance-from-records ((instance standard-db-object)
459                                          &key (database *default-database*))
460   (let* ((view-class (find-class (class-name (class-of instance))))
461          (view-table (sql-expression :table (view-table view-class)))
462          (vd (or (view-database instance) database))
463          (view-qual (key-qualifier-for-instance instance :database vd))
464          (sels (generate-selection-list view-class))
465          (res (apply #'select (append (mapcar #'cdr sels)
466                                       (list :from  view-table
467                                             :where view-qual)))))
468     (when res
469       (get-slot-values-from-view instance (mapcar #'car sels) (car res)))))
470
471 (defgeneric update-slot-from-record (instance slot &key database)
472   (:documentation
473    "Updates the value in the slot SLOT of the View Class instance
474 INSTANCE using the data in the database DATABASE which defaults to the
475 database that INSTANCE is associated with, or the value of
476 *DEFAULT-DATABASE*."))
477
478 (defmethod update-slot-from-record ((instance standard-db-object)
479                                     slot &key (database *default-database*))
480   (let* ((view-class (find-class (class-name (class-of instance))))
481          (view-table (sql-expression :table (view-table view-class)))
482          (vd (or (view-database instance) database))
483          (view-qual (key-qualifier-for-instance instance :database vd))
484          (slot-def (slotdef-for-slot-with-class slot view-class))
485          (att-ref (generate-attribute-reference view-class slot-def))
486          (res (select att-ref :from  view-table :where view-qual)))
487     (get-slot-values-from-view instance (list slot-def) (car res))))
488
489
490 (defgeneric database-null-value (type)
491   (:documentation "Return an expression of type TYPE which SQL NULL values
492 will be converted into."))
493
494 (defmethod database-null-value ((type t))
495   (cond
496     ((subtypep type 'string) nil)
497     ((subtypep type 'integer) nil)
498     ((subtypep type 'list) nil)
499     ((subtypep type 'boolean) nil)
500     ((eql type t) nil)
501     ((subtypep type 'symbol) nil)
502     ((subtypep type 'keyword) nil)
503     ((subtypep type 'wall-time) nil)
504     ((subtypep type 'duration) nil)
505     ((subtypep type 'money) nil)
506     (t
507      (error "Unable to handle null for type ~A" type))))
508
509 (defgeneric update-slot-with-null (instance slotname slotdef)
510   (:documentation "Called to update a slot when its column has a NULL
511 value.  If nulls are allowed for the column, the slot's value will be
512 nil, otherwise its value will be set to the result of calling
513 DATABASE-NULL-VALUE on the type of the slot."))
514
515 (defmethod update-slot-with-null ((object standard-db-object)
516                                   slotname
517                                   slotdef)
518   (let ((st (slot-type slotdef))
519         (allowed (slot-value slotdef 'nulls-ok)))
520     (if allowed
521         (setf (slot-value object slotname) nil)
522         (setf (slot-value object slotname)
523               (database-null-value st)))))
524
525 (defvar +no-slot-value+ '+no-slot-value+)
526
527 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
528   (let* ((class (find-class classname))
529          (sld (slotdef-for-slot-with-class slot class)))
530     (if sld
531         (if (eq value +no-slot-value+)
532             (sql-expression :attribute (view-class-slot-column sld)
533                             :table (view-table class))
534             (db-value-from-slot
535              sld
536              value
537              database))
538         (error "Unknown slot ~A for class ~A" slot classname))))
539
540 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
541         (declare (ignore database))
542         (let* ((class (find-class classname)))
543           (unless (view-table class)
544             (error "No view-table for class ~A"  classname))
545           (sql-expression :table (view-table class))))
546
547 (defmethod database-get-type-specifier (type args database)
548   (declare (ignore type args))
549   (if (clsql-base-sys::in (database-underlying-type database)
550                           :postgresql :postgresql-socket)
551           "VARCHAR"
552           "VARCHAR(255)"))
553
554 (defmethod database-get-type-specifier ((type (eql 'integer)) args database)
555   (declare (ignore database))
556   ;;"INT8")
557   (if args
558       (format nil "INT(~A)" (car args))
559       "INT"))
560               
561 (defmethod database-get-type-specifier ((type (eql 'simple-base-string)) args
562                                         database)
563   (if args
564       (format nil "VARCHAR(~A)" (car args))
565     (if (clsql-base-sys::in (database-underlying-type database) 
566                             :postgresql :postgresql-socket)
567         "VARCHAR"
568       "VARCHAR(255)")))
569
570 (defmethod database-get-type-specifier ((type (eql 'simple-string)) args
571                                         database)
572   (if args
573       (format nil "VARCHAR(~A)" (car args))
574     (if (clsql-base-sys::in (database-underlying-type database) 
575                             :postgresql :postgresql-socket)
576         "VARCHAR"
577       "VARCHAR(255)")))
578
579 (defmethod database-get-type-specifier ((type (eql 'string)) args database)
580   (if args
581       (format nil "VARCHAR(~A)" (car args))
582     (if (clsql-base-sys::in (database-underlying-type database) 
583                             :postgresql :postgresql-socket)
584         "VARCHAR"
585       "VARCHAR(255)")))
586
587 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database)
588   (declare (ignore args))
589   (case (database-underlying-type database)
590     ((:postgresql :postgresql-socket)
591      "TIMESTAMP WITHOUT TIME ZONE")
592     (:mysql
593      "DATETIME")
594     (t "TIMESTAMP")))
595
596 (defmethod database-get-type-specifier ((type (eql 'duration)) args database)
597   (declare (ignore database args))
598   "VARCHAR")
599
600 (defmethod database-get-type-specifier ((type (eql 'money)) args database)
601   (declare (ignore database args))
602   "INT8")
603
604 (deftype raw-string (&optional len)
605   "A string which is not trimmed when retrieved from the database"
606   `(string ,len))
607
608 (defmethod database-get-type-specifier ((type (eql 'raw-string)) args database)
609   (declare (ignore database))
610   (if args
611       (format nil "VARCHAR(~A)" (car args))
612       "VARCHAR"))
613
614 (defmethod database-get-type-specifier ((type (eql 'float)) args database)
615   (declare (ignore database))
616   (if args
617       (format nil "FLOAT(~A)" (car args))
618       "FLOAT"))
619
620 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database)
621   (declare (ignore database))
622   (if args
623       (format nil "FLOAT(~A)" (car args))
624       "FLOAT"))
625
626 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database)
627   (declare (ignore args database))
628   "BOOL")
629
630 (defmethod database-output-sql-as-type (type val database)
631   (declare (ignore type database))
632   val)
633
634 (defmethod database-output-sql-as-type ((type (eql 'list)) val database)
635   (declare (ignore database))
636   (progv '(*print-circle* *print-array*) '(t t)
637     (let ((escaped (prin1-to-string val)))
638       (clsql-base-sys::substitute-char-string
639        escaped #\Null " "))))
640
641 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database)
642   (declare (ignore database))
643   (if (keywordp val)
644       (symbol-name val)
645       (if val
646           (concatenate 'string
647                        (package-name (symbol-package val))
648                        "::"
649                        (symbol-name val))
650           "")))
651
652 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database)
653   (declare (ignore database))
654   (if val
655       (symbol-name val)
656       ""))
657
658 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database)
659   (declare (ignore database))
660   (progv '(*print-circle* *print-array*) '(t t)
661     (prin1-to-string val)))
662
663 (defmethod database-output-sql-as-type ((type (eql 'array)) val database)
664   (declare (ignore database))
665   (progv '(*print-circle* *print-array*) '(t t)
666     (prin1-to-string val)))
667
668 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database)
669   (declare (ignore database))
670   (if val "t" "f"))
671
672 (defmethod database-output-sql-as-type ((type (eql 'string)) val database)
673   (declare (ignore database))
674   val)
675
676 (defmethod database-output-sql-as-type ((type (eql 'simple-string))
677                                         val database)
678   (declare (ignore database))
679   val)
680
681 (defmethod database-output-sql-as-type ((type (eql 'simple-base-string))
682                                         val database)
683   (declare (ignore database))
684   val)
685
686 (defmethod read-sql-value (val type database)
687   (declare (ignore type database))
688   (read-from-string val))
689
690 (defmethod read-sql-value (val (type (eql 'string)) database)
691   (declare (ignore database))
692   val)
693
694 (defmethod read-sql-value (val (type (eql 'simple-string)) database)
695   (declare (ignore database))
696   val)
697
698 (defmethod read-sql-value (val (type (eql 'simple-base-string)) database)
699   (declare (ignore database))
700   val)
701
702 (defmethod read-sql-value (val (type (eql 'raw-string)) database)
703   (declare (ignore database))
704   val)
705
706 (defmethod read-sql-value (val (type (eql 'keyword)) database)
707   (declare (ignore database))
708   (when (< 0 (length val))
709     (intern (symbol-name-default-case val) 
710             (find-package '#:keyword))))
711
712 (defmethod read-sql-value (val (type (eql 'symbol)) database)
713   (declare (ignore database))
714   (when (< 0 (length val))
715     (unless (string= val (clsql-base-sys:symbol-name-default-case "NIL"))
716       (intern (clsql-base-sys:symbol-name-default-case val)
717               (symbol-package *update-context*)))))
718
719 (defmethod read-sql-value (val (type (eql 'integer)) database)
720   (declare (ignore database))
721   (etypecase val
722     (string
723      (read-from-string val))
724     (number val)))
725
726 (defmethod read-sql-value (val (type (eql 'float)) database)
727   (declare (ignore database))
728   ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
729   (float (read-from-string val))) 
730
731 (defmethod read-sql-value (val (type (eql 'boolean)) database)
732   (declare (ignore database))
733   (equal "t" val))
734
735 (defmethod read-sql-value (val (type (eql 'wall-time)) database)
736   (declare (ignore database))
737   (unless (eq 'NULL val)
738     (parse-timestring val)))
739
740 (defmethod read-sql-value (val (type (eql 'duration)) database)
741   (declare (ignore database))
742   (unless (or (eq 'NULL val)
743               (equal "NIL" val))
744     (parse-timestring val)))
745
746 ;; ------------------------------------------------------------
747 ;; Logic for 'faulting in' :join slots
748
749 (defun fault-join-slot-raw (class object slot-def)
750   (let* ((dbi (view-class-slot-db-info slot-def))
751          (jc (gethash :join-class dbi)))
752     (let ((jq (join-qualifier class object slot-def)))
753       (when jq 
754         (select jc :where jq)))))
755
756 (defun fault-join-slot (class object slot-def)
757   (let* ((dbi (view-class-slot-db-info slot-def))
758          (ts (gethash :target-slot dbi))
759          (res (fault-join-slot-raw class object slot-def)))
760     (when res
761       (cond
762         ((and ts (gethash :set dbi))
763          (mapcar (lambda (obj)
764                    (cons obj (slot-value obj ts))) res))
765         ((and ts (not (gethash :set dbi)))
766          (mapcar (lambda (obj) (slot-value obj ts)) res))
767         ((and (not ts) (not (gethash :set dbi)))
768          (car res))
769         ((and (not ts) (gethash :set dbi))
770          res)))))
771
772 (defun join-qualifier (class object slot-def)
773     (declare (ignore class))
774     (let* ((dbi (view-class-slot-db-info slot-def))
775            (jc (find-class (gethash :join-class dbi)))
776            ;;(ts (gethash :target-slot dbi))
777            ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
778            (foreign-keys (gethash :foreign-key dbi))
779            (home-keys (gethash :home-key dbi)))
780       (when (every #'(lambda (slt)
781                        (and (slot-boundp object slt)
782                             (not (null (slot-value object slt)))))
783                    (if (listp home-keys) home-keys (list home-keys)))
784         (let ((jc
785                (mapcar #'(lambda (hk fk)
786                            (let ((fksd (slotdef-for-slot-with-class fk jc)))
787                              (sql-operation '==
788                                             (typecase fk
789                                               (symbol
790                                                (sql-expression
791                                                 :attribute
792                                                 (view-class-slot-column fksd)
793                                                 :table (view-table jc)))
794                                               (t fk))
795                                             (typecase hk
796                                               (symbol
797                                                (slot-value object hk))
798                                               (t
799                                                hk)))))
800                        (if (listp home-keys)
801                            home-keys
802                            (list home-keys))
803                        (if (listp foreign-keys)
804                            foreign-keys
805                            (list foreign-keys)))))
806           (when jc
807             (if (> (length jc) 1)
808                 (apply #'sql-and jc)
809                 jc))))))
810
811 (defmethod postinitialize ((self t))
812   )
813
814 (defun find-all (view-classes &rest args &key all set-operation distinct from
815                  where group-by having order-by order-by-descending offset limit
816                  (database *default-database*))
817   "tweeze me apart someone pleeze"
818   (declare (ignore all set-operation group-by having
819                    offset limit)
820            (optimize (debug 3) (speed 1)))
821   ;; (cmsg "Args = ~s" args)
822   (remf args :from)
823   (let* ((*db-deserializing* t)
824          (*default-database* (or database
825                                  (error 'clsql-no-database-error nil))))
826     (flet ((table-sql-expr (table)
827              (sql-expression :table (view-table table)))
828            (ref-equal (ref1 ref2)
829              (equal (sql ref1)
830                     (sql ref2)))
831            (tables-equal (table-a table-b)
832              (string= (string (slot-value table-a 'name))
833                       (string (slot-value table-b 'name)))))
834
835       (let* ((sclasses (mapcar #'find-class view-classes))
836              (sels (mapcar #'generate-selection-list sclasses))
837              (fullsels (apply #'append sels))
838              (sel-tables (collect-table-refs where))
839              (tables (remove-duplicates (append (mapcar #'table-sql-expr sclasses) sel-tables)
840                                         :test #'tables-equal))
841              (res nil))
842         (dolist (ob (listify order-by))
843           (when (and ob (not (member ob (mapcar #'cdr fullsels)
844                                      :test #'ref-equal)))
845             (setq fullsels (append fullsels (mapcar #'(lambda (att) (cons nil att))
846                                                     (listify ob))))))
847         (dolist (ob (listify order-by-descending))
848           (when (and ob (not (member ob (mapcar #'cdr fullsels)
849                                      :test #'ref-equal)))
850             (setq fullsels (append fullsels (mapcar #'(lambda (att) (cons nil att))
851                                                     (listify ob))))))
852         (dolist (ob (listify distinct))
853           (when (and (typep ob 'sql-ident) (not (member ob (mapcar #'cdr fullsels)
854                                                         :test #'ref-equal)))
855             (setq fullsels (append fullsels (mapcar #'(lambda (att) (cons nil att))
856                                                     (listify ob))))))
857         ;; (cmsg  "Tables = ~s" tables)
858         ;; (cmsg  "From = ~s" from)
859         (setq res (apply #'select (append (mapcar #'cdr fullsels)
860                                           (cons :from (list (append (when from (listify from)) (listify tables)))) args)))
861         (flet ((build-object (vals)
862                  (flet ((%build-object (vclass selects)
863                           (let ((class-name (class-name vclass))
864                                 (db-vals    (butlast vals (- (list-length vals)
865                                                              (list-length selects)))))
866                             ;; (setf vals (nthcdr (list-length selects) vals))
867                             (%make-fresh-object class-name (mapcar #'car selects) db-vals))))
868                    (let ((objects (mapcar #'%build-object sclasses sels)))
869                      (if (= (length sclasses) 1)
870                          (car objects)
871                          objects)))))
872           (mapcar #'build-object res))))))
873
874 (defun %make-fresh-object (class-name slots values)
875   (let* ((*db-initializing* t)
876          (obj (make-instance class-name
877                              :view-database *default-database*)))
878     (setf obj (get-slot-values-from-view obj slots values))
879     (postinitialize obj)
880     obj))
881
882 (defun select (&rest select-all-args)
883   "Selects data from database given the constraints specified. Returns
884 a list of lists of record values as specified by select-all-args. By
885 default, the records are each represented as lists of attribute
886 values. The selections argument may be either db-identifiers, literal
887 strings or view classes.  If the argument consists solely of view
888 classes, the return value will be instances of objects rather than raw
889 tuples."
890   (flet ((select-objects (target-args)
891            (and target-args
892                 (every #'(lambda (arg)
893                            (and (symbolp arg)
894                                 (find-class arg nil)))
895                        target-args))))
896     (multiple-value-bind (target-args qualifier-args)
897         (query-get-selections select-all-args)
898       ;; (cmsg "Qual args = ~s" qualifier-args)
899       (if (select-objects target-args)
900           (apply #'find-all target-args qualifier-args)
901           (let ((expr (apply #'make-query select-all-args)))
902             (destructuring-bind (&key (flatp nil)
903                                       (database *default-database*)
904                                       &allow-other-keys)
905                 qualifier-args
906               (let ((res (query expr :database database)))
907                 (if (and flatp
908                          (= (length (slot-value expr 'selections)) 1))
909                     (mapcar #'car res)
910                   res))))))))