r9114: fixes for list-indexes
[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 (defgeneric delete-instance-records (instance)
438   (:documentation
439    "Deletes the records represented by INSTANCE from the database
440 associated with it. If instance has no associated database, an error
441 is signalled."))
442
443 (defmethod delete-instance-records ((object standard-db-object))
444   (let ((vt (sql-expression :table (view-table (class-of object))))
445         (qualifier (key-qualifier-for-instance object :database *default-database*)))
446     (delete-records :from vt :where qualifier :database *default-database*)
447     #+ignore (odcl::deleted-object object)))
448
449 (defgeneric update-instance-from-db (instance)
450   (:documentation
451    "Updates the values in the slots of the View Class instance
452 INSTANCE using the data in the database DATABASE which defaults to the
453 database that INSTANCE is associated with, or the value of
454 *DEFAULT-DATABASE*."))
455
456 (defmethod update-instance-from-db ((object standard-db-object))
457   (let* ((view-class (find-class (class-name (class-of object))))
458          (view-table (sql-expression :table (view-table view-class)))
459          (view-qual  (key-qualifier-for-instance object :database *default-database*))
460          (sels       (generate-selection-list view-class))
461          (res (apply #'select (append (mapcar #'cdr sels) (list :from  view-table
462                                                                 :where view-qual)))))
463     (when res
464       (get-slot-values-from-view object (mapcar #'car sels) (car res))
465       res)))
466
467
468 (defgeneric database-null-value (type)
469   (:documentation "Return an expression of type TYPE which SQL NULL values
470 will be converted into."))
471
472 (defmethod database-null-value ((type t))
473   (cond
474     ((subtypep type 'string) nil)
475     ((subtypep type 'integer) nil)
476     ((subtypep type 'list) nil)
477     ((subtypep type 'boolean) nil)
478     ((eql type t) nil)
479     ((subtypep type 'symbol) nil)
480     ((subtypep type 'keyword) nil)
481     ((subtypep type 'wall-time) nil)
482     ((subtypep type 'duration) nil)
483     ((subtypep type 'money) nil)
484     (t
485      (error "Unable to handle null for type ~A" type))))
486
487 (defgeneric update-slot-with-null (instance slotname slotdef)
488   (:documentation "Called to update a slot when its column has a NULL
489 value.  If nulls are allowed for the column, the slot's value will be
490 nil, otherwise its value will be set to the result of calling
491 DATABASE-NULL-VALUE on the type of the slot."))
492
493 (defmethod update-slot-with-null ((object standard-db-object)
494                                   slotname
495                                   slotdef)
496   (let ((st (slot-definition-type slotdef))
497         (allowed (slot-value slotdef 'nulls-ok)))
498     (if allowed
499         (setf (slot-value object slotname) nil)
500         (setf (slot-value object slotname)
501               (database-null-value st)))))
502
503 (defvar +no-slot-value+ '+no-slot-value+)
504
505 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
506   (let* ((class (find-class classname))
507          (sld (slotdef-for-slot-with-class slot class)))
508     (if sld
509         (if (eq value +no-slot-value+)
510             (sql-expression :attribute (view-class-slot-column sld)
511                             :table (view-table class))
512             (db-value-from-slot
513              sld
514              value
515              database))
516         (error "Unknown slot ~A for class ~A" slot classname))))
517
518 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
519         (declare (ignore database))
520         (let* ((class (find-class classname)))
521           (unless (view-table class)
522             (error "No view-table for class ~A"  classname))
523           (sql-expression :table (view-table class))))
524
525 (defmethod database-get-type-specifier (type args database)
526   (declare (ignore type args))
527   (if (member (database-type database) '(:postgresql :postgresql-socket))
528           "VARCHAR"
529           "VARCHAR(255)"))
530
531 (defmethod database-get-type-specifier ((type (eql 'integer)) args database)
532   (declare (ignore database))
533   ;;"INT8")
534   (if args
535       (format nil "INT(~A)" (car args))
536       "INT"))
537
538 (defmethod database-get-type-specifier ((type (eql 'simple-base-string)) args
539                                         database)
540   (if args
541       (format nil "VARCHAR(~A)" (car args))
542       (if (member (database-type database) '(:postgresql :postgresql-socket))
543           "VARCHAR"
544           "VARCHAR(255)")))
545
546 (defmethod database-get-type-specifier ((type (eql 'simple-string)) args
547                                         database)
548   (if args
549       (format nil "VARCHAR(~A)" (car args))
550       (if (member (database-type database) '(:postgresql :postgresql-socket))
551           "VARCHAR"
552           "VARCHAR(255)")))
553
554 (defmethod database-get-type-specifier ((type (eql 'string)) args database)
555   (if args
556       (format nil "VARCHAR(~A)" (car args))
557       (if (member (database-type database) '(:postgresql :postgresql-socket))
558           "VARCHAR"
559           "VARCHAR(255)")))
560
561 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database)
562   (declare (ignore args))
563   (case (database-type database)
564     (:postgresql
565      "TIMESTAMP WITHOUT TIME ZONE")
566     (:postgresql-socket
567      "TIMESTAMP WITHOUT TIME ZONE")
568     (:mysql
569      "DATETIME")
570     (t "TIMESTAMP")))
571
572 (defmethod database-get-type-specifier ((type (eql 'duration)) args database)
573   (declare (ignore database args))
574   "VARCHAR")
575
576 (defmethod database-get-type-specifier ((type (eql 'money)) args database)
577   (declare (ignore database args))
578   "INT8")
579
580 (deftype raw-string (&optional len)
581   "A string which is not trimmed when retrieved from the database"
582   `(string ,len))
583
584 (defmethod database-get-type-specifier ((type (eql 'raw-string)) args database)
585   (declare (ignore database))
586   (if args
587       (format nil "VARCHAR(~A)" (car args))
588       "VARCHAR"))
589
590 (defmethod database-get-type-specifier ((type (eql '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 'long-float)) args database)
597   (declare (ignore database))
598   (if args
599       (format nil "FLOAT(~A)" (car args))
600       "FLOAT"))
601
602 (defmethod database-get-type-specifier ((type (eql 't)) args database)
603   (declare (ignore args database))
604   "BOOL")
605
606 (defmethod database-output-sql-as-type (type val database)
607   (declare (ignore type database))
608   val)
609
610 (defmethod database-output-sql-as-type ((type (eql 'list)) val database)
611   (declare (ignore database))
612   (progv '(*print-circle* *print-array*) '(t t)
613     (let ((escaped (prin1-to-string val)))
614       (clsql-base-sys::substitute-char-string
615        escaped #\Null " "))))
616
617 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database)
618   (declare (ignore database))
619   (if val
620       (symbol-name val))
621   "")
622
623 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database)
624   (declare (ignore database))
625   (if val
626       (symbol-name val)
627       ""))
628
629 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database)
630   (declare (ignore database))
631   (progv '(*print-circle* *print-array*) '(t t)
632     (prin1-to-string val)))
633
634 (defmethod database-output-sql-as-type ((type (eql 'array)) val database)
635   (declare (ignore database))
636   (progv '(*print-circle* *print-array*) '(t t)
637     (prin1-to-string val)))
638
639 (defmethod database-output-sql-as-type ((type (eql 't)) val database)
640   (declare (ignore database))
641   (if val "t" "f"))
642
643 (defmethod database-output-sql-as-type ((type (eql 'string)) val database)
644   (declare (ignore database))
645   val)
646
647 (defmethod database-output-sql-as-type ((type (eql 'simple-string))
648                                         val database)
649   (declare (ignore database))
650   val)
651
652 (defmethod database-output-sql-as-type ((type (eql 'simple-base-string))
653                                         val database)
654   (declare (ignore database))
655   val)
656
657 (defmethod read-sql-value (val type database)
658   (declare (ignore type database))
659   (read-from-string val))
660
661 (defmethod read-sql-value (val (type (eql 'string)) database)
662   (declare (ignore database))
663   val)
664
665 (defmethod read-sql-value (val (type (eql 'simple-string)) database)
666   (declare (ignore database))
667   val)
668
669 (defmethod read-sql-value (val (type (eql 'simple-base-string)) database)
670   (declare (ignore database))
671   val)
672
673 (defmethod read-sql-value (val (type (eql 'raw-string)) database)
674   (declare (ignore database))
675   val)
676
677 (defmethod read-sql-value (val (type (eql 'keyword)) database)
678   (declare (ignore database))
679   (when (< 0 (length val))
680     (intern (string-upcase val) "KEYWORD")))
681
682 (defmethod read-sql-value (val (type (eql 'symbol)) database)
683   (declare (ignore database))
684   (when (< 0 (length val))
685     (unless (string= val "NIL")
686       (intern (string-upcase val)
687               (symbol-package *update-context*)))))
688
689 (defmethod read-sql-value (val (type (eql 'integer)) database)
690   (declare (ignore database))
691   (etypecase val
692     (string
693      (read-from-string val))
694     (number val)))
695
696 (defmethod read-sql-value (val (type (eql 'float)) database)
697   (declare (ignore database))
698   ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
699   (float (read-from-string val))) 
700
701 (defmethod read-sql-value (val (type (eql 't)) database)
702   (declare (ignore database))
703   (equal "t" val))
704
705 (defmethod read-sql-value (val (type (eql 'wall-time)) database)
706   (declare (ignore database))
707   (unless (eq 'NULL val)
708     (parse-timestring val)))
709
710 (defmethod read-sql-value (val (type (eql 'duration)) database)
711   (declare (ignore database))
712   (unless (or (eq 'NULL val)
713               (equal "NIL" val))
714     (parse-timestring val)))
715
716 (defmethod read-sql-value (val (type (eql 'money)) database)
717   (unless (eq 'NULL val)
718     (make-instance 'money :units (read-sql-value val 'integer database))))
719
720 ;; ------------------------------------------------------------
721 ;; Logic for 'faulting in' :join slots
722
723 (defun fault-join-slot-raw (class object slot-def)
724   (let* ((dbi (view-class-slot-db-info slot-def))
725          (jc (gethash :join-class dbi)))
726     (let ((jq (join-qualifier class object slot-def)))
727       (when jq
728         (select jc :where jq)))))
729
730 (defun fault-join-slot (class object slot-def)
731   (let* ((dbi (view-class-slot-db-info slot-def))
732          (ts (gethash :target-slot dbi))
733          (res (fault-join-slot-raw class object slot-def)))
734     (when res
735       (cond
736         ((and ts (gethash :set dbi))
737          (mapcar (lambda (obj)
738                    (cons obj (slot-value obj ts))) res))
739         ((and ts (not (gethash :set dbi)))
740          (mapcar (lambda (obj) (slot-value obj ts)) res))
741         ((and (not ts) (not (gethash :set dbi)))
742          (car res))
743         ((and (not ts) (gethash :set dbi))
744          res)))))
745
746 (defun join-qualifier (class object slot-def)
747     (declare (ignore class))
748     (let* ((dbi (view-class-slot-db-info slot-def))
749            (jc (find-class (gethash :join-class dbi)))
750            ;;(ts (gethash :target-slot dbi))
751            ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
752            (foreign-keys (gethash :foreign-key dbi))
753            (home-keys (gethash :home-key dbi)))
754       (when (every #'(lambda (slt)
755                        (and (slot-boundp object slt)
756                             (not (null (slot-value object slt)))))
757                    (if (listp home-keys) home-keys (list home-keys)))
758         (let ((jc (mapcar #'(lambda (hk fk)
759                                    (let ((fksd (slotdef-for-slot-with-class fk jc)))
760                                      (sql-operation '==
761                                                     (typecase fk
762                                                       (symbol
763                                                        (sql-expression
764                                                         :attribute (view-class-slot-column fksd)
765                                                         :table (view-table jc)))
766                                                       (t fk))
767                                                     (typecase hk
768                                                       (symbol
769                                                        (slot-value object hk))
770                                                       (t
771                                                        hk)))))
772                                (if (listp home-keys) home-keys (list home-keys))
773                                (if (listp foreign-keys) foreign-keys (list foreign-keys)))))
774           (when jc
775             (if (> (length jc) 1)
776                 (apply #'sql-and jc)
777               jc))))))
778
779 (defmethod postinitialize ((self t))
780   )
781
782 (defun find-all (view-classes &rest args &key all set-operation distinct from
783                  where group-by having order-by order-by-descending offset limit
784                  (database *default-database*))
785   "tweeze me apart someone pleeze"
786   (declare (ignore all set-operation group-by having
787                    offset limit)
788            (optimize (debug 3) (speed 1)))
789   ;; (cmsg "Args = ~s" args)
790   (remf args :from)
791   (let* ((*db-deserializing* t)
792          (*default-database* (or database
793                                  (error 'clsql-no-database-error nil))))
794     (flet ((table-sql-expr (table)
795              (sql-expression :table (view-table table)))
796            (ref-equal (ref1 ref2)
797              (equal (sql ref1)
798                     (sql ref2)))
799            (tables-equal (table-a table-b)
800              (string= (string (slot-value table-a 'name))
801                       (string (slot-value table-b 'name)))))
802
803       (let* ((sclasses (mapcar #'find-class view-classes))
804              (sels (mapcar #'generate-selection-list sclasses))
805              (fullsels (apply #'append sels))
806              (sel-tables (collect-table-refs where))
807              (tables (remove-duplicates (append (mapcar #'table-sql-expr sclasses) sel-tables)
808                                         :test #'tables-equal))
809              (res nil))
810         (dolist (ob (listify order-by))
811           (when (and ob (not (member ob (mapcar #'cdr fullsels)
812                                      :test #'ref-equal)))
813             (setq fullsels (append fullsels (mapcar #'(lambda (att) (cons nil att))
814                                                     (listify ob))))))
815         (dolist (ob (listify order-by-descending))
816           (when (and ob (not (member ob (mapcar #'cdr fullsels)
817                                      :test #'ref-equal)))
818             (setq fullsels (append fullsels (mapcar #'(lambda (att) (cons nil att))
819                                                     (listify ob))))))
820         (dolist (ob (listify distinct))
821           (when (and (typep ob 'sql-ident) (not (member ob (mapcar #'cdr fullsels)
822                                                         :test #'ref-equal)))
823             (setq fullsels (append fullsels (mapcar #'(lambda (att) (cons nil att))
824                                                     (listify ob))))))
825         ;; (cmsg  "Tables = ~s" tables)
826         ;; (cmsg  "From = ~s" from)
827         (setq res (apply #'select (append (mapcar #'cdr fullsels)
828                                           (cons :from (list (append (when from (listify from)) (listify tables)))) args)))
829         (flet ((build-object (vals)
830                  (flet ((%build-object (vclass selects)
831                           (let ((class-name (class-name vclass))
832                                 (db-vals    (butlast vals (- (list-length vals)
833                                                              (list-length selects)))))
834                             ;; (setf vals (nthcdr (list-length selects) vals))
835                             (%make-fresh-object class-name (mapcar #'car selects) db-vals))))
836                    (let ((objects (mapcar #'%build-object sclasses sels)))
837                      (if (= (length sclasses) 1)
838                          (car objects)
839                          objects)))))
840           (mapcar #'build-object res))))))
841
842 (defun %make-fresh-object (class-name slots values)
843   (let* ((*db-initializing* t)
844          (obj (make-instance class-name
845                              :stored t)))
846     (setf obj (get-slot-values-from-view obj slots values))
847     (postinitialize obj)
848     obj))
849
850 (defun select (&rest select-all-args)
851   "Selects data from database given the constraints specified. Returns
852 a list of lists of record values as specified by select-all-args. By
853 default, the records are each represented as lists of attribute
854 values. The selections argument may be either db-identifiers, literal
855 strings or view classes.  If the argument consists solely of view
856 classes, the return value will be instances of objects rather than raw
857 tuples."
858   (flet ((select-objects (target-args)
859            (and target-args
860                 (every #'(lambda (arg)
861                            (and (symbolp arg)
862                                 (find-class arg nil)))
863                        target-args))))
864     (multiple-value-bind (target-args qualifier-args)
865         (query-get-selections select-all-args)
866       ;; (cmsg "Qual args = ~s" qualifier-args)
867       (if (select-objects target-args)
868           (apply #'find-all target-args qualifier-args)
869           (let ((expr (apply #'make-query select-all-args)))
870             (destructuring-bind (&key (flatp nil)
871                                       (database *default-database*)
872                                       &allow-other-keys)
873                 qualifier-args
874               (let ((res (query expr :database database)))
875                 (if (and flatp
876                          (= (length (slot-value expr 'selections)) 1))
877                     (mapcar #'car res)
878                   res))))))))