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