r9244: Automated commit for Debian build of clsql upstream-version-2.10.11
[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)
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 *update-records-on-make-instance* nil
25   "When T, UPDATE-RECORDS-FROM-INSTANCE will be automatically called
26 when a new instance of a view-class is created.")
27
28 (defvar *db-deserializing* nil)
29 (defvar *db-initializing* nil)
30
31 (defmethod slot-value-using-class ((class standard-db-class) instance slot-def)
32   (declare (optimize (speed 3)))
33   (unless *db-deserializing*
34     (let* ((slot-name (%svuc-slot-name slot-def))
35            (slot-object (%svuc-slot-object slot-def class))
36            (slot-kind (view-class-slot-db-kind slot-object)))
37       (when (and (eql slot-kind :join)
38                  (not (slot-boundp instance slot-name)))
39         (let ((*db-deserializing* t))
40           (if (view-database instance)
41               (setf (slot-value instance slot-name)
42                     (fault-join-slot class instance slot-object))
43               (setf (slot-value instance slot-name) nil))))))
44   (call-next-method))
45
46 #+ignore ;; not currently used
47 (defmethod (setf slot-value-using-class) (new-value (class standard-db-class)
48                                           instance slot)
49   (declare (ignore new-value instance slot))
50   (call-next-method))
51
52 (defmethod initialize-instance ((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     (when (and *update-records-on-make-instance*
58                (not *db-deserializing*))
59       #+nil (created-object object)
60       (update-records-from-instance object))))
61
62 ;;
63 ;; Build the database tables required to store the given view class
64 ;;
65
66 (defun create-view-from-class (view-class-name
67                                &key (database *default-database*))
68   "Creates a view in DATABASE based on VIEW-CLASS-NAME which defines
69 the view. The argument DATABASE has a default value of
70 *DEFAULT-DATABASE*."
71   (let ((tclass (find-class view-class-name)))
72     (if tclass
73         (let ((*default-database* database))
74           (%install-class tclass database))
75         (error "Class ~s not found." view-class-name)))
76   (values))
77
78 (defmethod %install-class ((self standard-db-class) database &aux schemadef)
79   (dolist (slotdef (ordered-class-slots self))
80     (let ((res (database-generate-column-definition (class-name self)
81                                                     slotdef database)))
82       (when res 
83         (push res schemadef))))
84   (unless schemadef
85     (error "Class ~s has no :base slots" self))
86   (create-table (sql-expression :table (view-table self)) schemadef
87                 :database database
88                 :constraints (database-pkey-constraint self database))
89   (push self (database-view-classes database))
90   t)
91
92 (defmethod database-pkey-constraint ((class standard-db-class) database)
93   (let ((keylist (mapcar #'view-class-slot-column (keyslots-for-class class))))
94     (when keylist 
95       (convert-to-db-default-case
96        (format nil "CONSTRAINT ~APK PRIMARY KEY~A"
97                (database-output-sql (view-table class) database)
98                (database-output-sql keylist database))
99        database))))
100
101 (defmethod database-generate-column-definition (class slotdef database)
102   (declare (ignore database class))
103   (when (member (view-class-slot-db-kind slotdef) '(:base :key))
104     (let ((cdef
105            (list (sql-expression :attribute (view-class-slot-column slotdef))
106                  (specified-type slotdef))))
107       (setf cdef (append cdef (list (view-class-slot-db-type slotdef))))
108       (let ((const (view-class-slot-db-constraints slotdef)))
109         (when const 
110           (setq cdef (append cdef (list const)))))
111       cdef)))
112
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 cl-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 
176       ,@(if (find :metaclass `,cl-options :key #'car)
177             `,cl-options
178             (cons '(:metaclass clsql::standard-db-class) `,cl-options)))
179     (finalize-inheritance (find-class ',class))
180     (find-class ',class)))
181
182 (defun keyslots-for-class (class)
183   (slot-value class 'key-slots))
184
185 (defun key-qualifier-for-instance (obj &key (database *default-database*))
186   (let ((tb (view-table (class-of obj))))
187     (flet ((qfk (k)
188              (sql-operation '==
189                             (sql-expression :attribute
190                                             (view-class-slot-column k)
191                                             :table tb)
192                             (db-value-from-slot
193                              k
194                              (slot-value obj (slot-definition-name k))
195                              database))))
196       (let* ((keys (keyslots-for-class (class-of obj)))
197              (keyxprs (mapcar #'qfk (reverse keys))))
198         (cond
199           ((= (length keyxprs) 0) nil)
200           ((= (length keyxprs) 1) (car keyxprs))
201           ((> (length keyxprs) 1) (apply #'sql-operation 'and keyxprs)))))))
202
203 ;;
204 ;; Function used by 'generate-selection-list'
205 ;;
206
207 (defun generate-attribute-reference (vclass slotdef)
208   (cond
209    ((eq (view-class-slot-db-kind slotdef) :base)
210     (sql-expression :attribute (view-class-slot-column slotdef)
211                     :table (view-table vclass)))
212    ((eq (view-class-slot-db-kind slotdef) :key)
213     (sql-expression :attribute (view-class-slot-column slotdef)
214                     :table (view-table vclass)))
215    (t nil)))
216
217 ;;
218 ;; Function used by 'find-all'
219 ;;
220
221 (defun generate-selection-list (vclass)
222   (let ((sels nil))
223     (dolist (slotdef (ordered-class-slots vclass))
224       (let ((res (generate-attribute-reference vclass slotdef)))
225         (when res
226           (push (cons slotdef res) sels))))
227     (if sels
228         sels
229         (error "No slots of type :base in view-class ~A" (class-name vclass)))))
230
231
232 ;;
233 ;; Called by 'get-slot-values-from-view'
234 ;;
235
236 (declaim (inline delistify))
237 (defun delistify (list)
238   (if (listp list)
239       (car list)
240       list))
241
242 (defvar *update-context* nil)
243
244 (defmethod update-slot-from-db ((instance standard-db-object) slotdef value)
245   (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
246   (let* ((slot-reader (view-class-slot-db-reader slotdef))
247          (slot-name   (slot-definition-name slotdef))
248          (slot-type   (specified-type slotdef))
249          (*update-context* (cons (type-of instance) slot-name)))
250     (cond ((and value (null slot-reader))
251            (setf (slot-value instance slot-name)
252                  (read-sql-value value (delistify slot-type)
253                                  (view-database instance))))
254           ((null value)
255            (update-slot-with-null instance slot-name slotdef))
256           ((typep slot-reader 'string)
257            (setf (slot-value instance slot-name)
258                  (format nil slot-reader value)))
259           ((typep slot-reader 'function)
260            (setf (slot-value instance slot-name)
261                  (apply slot-reader (list value))))
262           (t
263            (error "Slot reader is of an unusual type.")))))
264
265 (defmethod key-value-from-db (slotdef value database) 
266   (declare (optimize (speed 3) #+cmu (extensions:inhibit-warnings 3)))
267   (let ((slot-reader (view-class-slot-db-reader slotdef))
268         (slot-type (specified-type slotdef)))
269     (cond ((and value (null slot-reader))
270            (read-sql-value value (delistify slot-type) database))
271           ((null value)
272            nil)
273           ((typep slot-reader 'string)
274            (format nil slot-reader value))
275           ((typep slot-reader 'function)
276            (apply slot-reader (list value)))
277           (t
278            (error "Slot reader is of an unusual type.")))))
279
280 (defun db-value-from-slot (slotdef val database)
281   (let ((dbwriter (view-class-slot-db-writer slotdef))
282         (dbtype (specified-type slotdef)))
283     (typecase dbwriter
284       (string (format nil dbwriter val))
285       (function (apply dbwriter (list val)))
286       (t
287        (typecase dbtype
288          (cons
289           (database-output-sql-as-type (car dbtype) val database))
290          (t
291           (database-output-sql-as-type dbtype val database)))))))
292
293 (defun check-slot-type (slotdef val)
294   (let* ((slot-type (specified-type slotdef))
295          (basetype (if (listp slot-type) (car slot-type) slot-type)))
296     (when (and slot-type val)
297       (unless (typep val basetype)
298         (error 'clsql-type-error
299                :slotname (slot-definition-name slotdef)
300                :typespec slot-type
301                :value val)))))
302
303 ;;
304 ;; Called by find-all
305 ;;
306
307 (defmethod get-slot-values-from-view (obj slotdeflist values)
308     (flet ((update-slot (slot-def values)
309              (update-slot-from-db obj slot-def values)))
310       (mapc #'update-slot slotdeflist values)
311       obj))
312
313 (defmethod update-record-from-slot ((obj standard-db-object) slot &key
314                                     (database *default-database*))
315   (let* ((database (or (view-database obj) database))
316          (vct (view-table (class-of obj)))
317          (sd (slotdef-for-slot-with-class slot (class-of obj))))
318     (check-slot-type sd (slot-value obj slot))
319     (let* ((att (view-class-slot-column sd))
320            (val (db-value-from-slot sd (slot-value obj slot) database)))
321       (cond ((and vct sd (view-database obj))
322              (update-records (sql-expression :table vct)
323                              :attributes (list (sql-expression :attribute att))
324                              :values (list val)
325                              :where (key-qualifier-for-instance
326                                      obj :database database)
327                              :database database))
328             ((and vct sd (not (view-database obj)))
329              (insert-records :into (sql-expression :table vct)
330                              :attributes (list (sql-expression :attribute att))
331                              :values (list val)
332                              :database database)
333              (setf (slot-value obj 'view-database) database))
334             (t
335              (error "Unable to update record.")))))
336   (values))
337
338 (defmethod update-record-from-slots ((obj standard-db-object) slots &key
339                                      (database *default-database*))
340   (let* ((database (or (view-database obj) database))
341          (vct (view-table (class-of obj)))
342          (sds (slotdefs-for-slots-with-class slots (class-of obj)))
343          (avps (mapcar #'(lambda (s)
344                            (let ((val (slot-value
345                                        obj (slot-definition-name s))))
346                              (check-slot-type s val)
347                              (list (sql-expression
348                                     :attribute (view-class-slot-column s))
349                                    (db-value-from-slot s val database))))
350                        sds)))
351     (cond ((and avps (view-database obj))
352            (update-records (sql-expression :table vct)
353                            :av-pairs avps
354                            :where (key-qualifier-for-instance
355                                    obj :database database)
356                            :database database))
357           ((and avps (not (view-database obj)))
358            (insert-records :into (sql-expression :table vct)
359                            :av-pairs avps
360                            :database database)
361            (setf (slot-value obj 'view-database) database))
362           (t
363            (error "Unable to update records"))))
364   (values))
365
366 (defmethod update-records-from-instance ((obj standard-db-object)
367                                          &key (database *default-database*))
368   (let ((database (or (view-database obj) database)))
369     (labels ((slot-storedp (slot)
370                (and (member (view-class-slot-db-kind slot) '(:base :key))
371                     (slot-boundp obj (slot-definition-name slot))))
372              (slot-value-list (slot)
373                (let ((value (slot-value obj (slot-definition-name slot))))
374                  (check-slot-type slot value)
375                  (list (sql-expression :attribute (view-class-slot-column slot))
376                        (db-value-from-slot slot value database)))))
377       (let* ((view-class (class-of obj))
378              (view-class-table (view-table view-class))
379              (slots (remove-if-not #'slot-storedp 
380                                    (ordered-class-slots view-class)))
381              (record-values (mapcar #'slot-value-list slots)))
382         (unless record-values
383           (error "No settable slots."))
384         (if (view-database obj)
385             (update-records (sql-expression :table view-class-table)
386                             :av-pairs record-values
387                             :where (key-qualifier-for-instance
388                                     obj :database database)
389                             :database database)
390             (progn
391               (insert-records :into (sql-expression :table view-class-table)
392                               :av-pairs record-values
393                               :database database)
394               (setf (slot-value obj 'view-database) database))))))
395   (values))
396
397 (defmethod delete-instance-records ((instance standard-db-object))
398   (let ((vt (sql-expression :table (view-table (class-of instance))))
399         (vd (view-database instance)))
400     (if vd
401         (let ((qualifier (key-qualifier-for-instance instance :database vd)))
402           (delete-records :from vt :where qualifier :database vd)
403           (setf (slot-value instance 'view-database) nil))
404         (error 'clsql-base::clsql-no-database-error :database nil))))
405
406 (defmethod update-instance-from-records ((instance standard-db-object)
407                                          &key (database *default-database*))
408   (let* ((view-class (find-class (class-name (class-of instance))))
409          (view-table (sql-expression :table (view-table view-class)))
410          (vd (or (view-database instance) database))
411          (view-qual (key-qualifier-for-instance instance :database vd))
412          (sels (generate-selection-list view-class))
413          (res (apply #'select (append (mapcar #'cdr sels)
414                                       (list :from  view-table
415                                             :where view-qual)
416                                       (list :result-types nil)))))
417     (when res
418       (get-slot-values-from-view instance (mapcar #'car sels) (car res)))))
419
420 (defmethod update-slot-from-record ((instance standard-db-object)
421                                     slot &key (database *default-database*))
422   (let* ((view-class (find-class (class-name (class-of instance))))
423          (view-table (sql-expression :table (view-table view-class)))
424          (vd (or (view-database instance) database))
425          (view-qual (key-qualifier-for-instance instance :database vd))
426          (slot-def (slotdef-for-slot-with-class slot view-class))
427          (att-ref (generate-attribute-reference view-class slot-def))
428          (res (select att-ref :from  view-table :where view-qual
429                       :result-types nil)))
430     (when res 
431       (get-slot-values-from-view instance (list slot-def) (car res)))))
432
433
434 (defmethod update-slot-with-null ((object standard-db-object)
435                                   slotname
436                                   slotdef)
437   (setf (slot-value object slotname) (slot-value slotdef 'void-value)))
438
439 (defvar +no-slot-value+ '+no-slot-value+)
440
441 (defsql sql-slot-value (:symbol "slot-value") (classname slot &optional (value +no-slot-value+) (database *default-database*))
442   (let* ((class (find-class classname))
443          (sld (slotdef-for-slot-with-class slot class)))
444     (if sld
445         (if (eq value +no-slot-value+)
446             (sql-expression :attribute (view-class-slot-column sld)
447                             :table (view-table class))
448             (db-value-from-slot
449              sld
450              value
451              database))
452         (error "Unknown slot ~A for class ~A" slot classname))))
453
454 (defsql sql-view-class (:symbol "view-class") (classname &optional (database *default-database*))
455         (declare (ignore database))
456         (let* ((class (find-class classname)))
457           (unless (view-table class)
458             (error "No view-table for class ~A"  classname))
459           (sql-expression :table (view-table class))))
460
461 (defmethod database-get-type-specifier (type args database)
462   (declare (ignore type args))
463   (if (clsql-base::in (database-underlying-type database)
464                           :postgresql :postgresql-socket)
465           "VARCHAR"
466           "VARCHAR(255)"))
467
468 (defmethod database-get-type-specifier ((type (eql 'integer)) args database)
469   (declare (ignore database))
470   ;;"INT8")
471   (if args
472       (format nil "INT(~A)" (car args))
473       "INT"))
474
475 (deftype bigint () 
476   "An integer larger than a 32-bit integer, this width may vary by SQL implementation."
477   'integer)
478
479 (defmethod database-get-type-specifier ((type (eql 'bigint)) args database)
480   (declare (ignore args database))
481   "BIGINT")
482               
483 (defmethod database-get-type-specifier ((type (eql 'simple-base-string)) args
484                                         database)
485   (if args
486       (format nil "VARCHAR(~A)" (car args))
487     (if (clsql-base::in (database-underlying-type database) 
488                             :postgresql :postgresql-socket)
489         "VARCHAR"
490       "VARCHAR(255)")))
491
492 (defmethod database-get-type-specifier ((type (eql 'simple-string)) args
493                                         database)
494   (if args
495       (format nil "VARCHAR(~A)" (car args))
496     (if (clsql-base::in (database-underlying-type database) 
497                             :postgresql :postgresql-socket)
498         "VARCHAR"
499       "VARCHAR(255)")))
500
501 (defmethod database-get-type-specifier ((type (eql 'string)) args database)
502   (if args
503       (format nil "VARCHAR(~A)" (car args))
504     (if (clsql-base::in (database-underlying-type database) 
505                             :postgresql :postgresql-socket)
506         "VARCHAR"
507       "VARCHAR(255)")))
508
509 (deftype universal-time () 
510   "A positive integer as returned by GET-UNIVERSAL-TIME."
511   '(integer 1 *))
512
513 (defmethod database-get-type-specifier ((type (eql 'universal-time)) args database)
514   (declare (ignore args database))
515   "BIGINT")
516
517 (defmethod database-get-type-specifier ((type (eql 'wall-time)) args database)
518   (declare (ignore args))
519   (case (database-underlying-type database)
520     ((:postgresql :postgresql-socket)
521      "TIMESTAMP WITHOUT TIME ZONE")
522     (:mysql
523      "DATETIME")
524     (t "TIMESTAMP")))
525
526 (defmethod database-get-type-specifier ((type (eql 'duration)) args database)
527   (declare (ignore database args))
528   "VARCHAR")
529
530 (defmethod database-get-type-specifier ((type (eql 'money)) args database)
531   (declare (ignore database args))
532   "INT8")
533
534 (deftype raw-string (&optional len)
535   "A string which is not trimmed when retrieved from the database"
536   `(string ,len))
537
538 (defmethod database-get-type-specifier ((type (eql 'raw-string)) args database)
539   (declare (ignore database))
540   (if args
541       (format nil "VARCHAR(~A)" (car args))
542       "VARCHAR"))
543
544 (defmethod database-get-type-specifier ((type (eql 'float)) args database)
545   (declare (ignore database))
546   (if args
547       (format nil "FLOAT(~A)" (car args))
548       "FLOAT"))
549
550 (defmethod database-get-type-specifier ((type (eql 'long-float)) args database)
551   (declare (ignore database))
552   (if args
553       (format nil "FLOAT(~A)" (car args))
554       "FLOAT"))
555
556 (defmethod database-get-type-specifier ((type (eql 'boolean)) args database)
557   (declare (ignore args database))
558   "BOOL")
559
560 (defmethod database-output-sql-as-type (type val database)
561   (declare (ignore type database))
562   val)
563
564 (defmethod database-output-sql-as-type ((type (eql 'list)) val database)
565   (declare (ignore database))
566   (progv '(*print-circle* *print-array*) '(t t)
567     (let ((escaped (prin1-to-string val)))
568       (clsql-base::substitute-char-string
569        escaped #\Null " "))))
570
571 (defmethod database-output-sql-as-type ((type (eql 'symbol)) val database)
572   (declare (ignore database))
573   (if (keywordp val)
574       (symbol-name val)
575       (if val
576           (concatenate 'string
577                        (package-name (symbol-package val))
578                        "::"
579                        (symbol-name val))
580           "")))
581
582 (defmethod database-output-sql-as-type ((type (eql 'keyword)) val database)
583   (declare (ignore database))
584   (if val
585       (symbol-name val)
586       ""))
587
588 (defmethod database-output-sql-as-type ((type (eql 'vector)) val database)
589   (declare (ignore database))
590   (progv '(*print-circle* *print-array*) '(t t)
591     (prin1-to-string val)))
592
593 (defmethod database-output-sql-as-type ((type (eql 'array)) val database)
594   (declare (ignore database))
595   (progv '(*print-circle* *print-array*) '(t t)
596     (prin1-to-string val)))
597
598 (defmethod database-output-sql-as-type ((type (eql 'boolean)) val database)
599   (case (database-underlying-type database)
600     (:mysql
601      (if val 1 0))
602     (t
603      (if val "t" "f"))))
604
605 (defmethod database-output-sql-as-type ((type (eql 'string)) val database)
606   (declare (ignore database))
607   val)
608
609 (defmethod database-output-sql-as-type ((type (eql 'simple-string))
610                                         val database)
611   (declare (ignore database))
612   val)
613
614 (defmethod database-output-sql-as-type ((type (eql 'simple-base-string))
615                                         val database)
616   (declare (ignore database))
617   val)
618
619 (defmethod read-sql-value (val type database)
620   (declare (ignore type database))
621   (read-from-string val))
622
623 (defmethod read-sql-value (val (type (eql 'string)) database)
624   (declare (ignore database))
625   val)
626
627 (defmethod read-sql-value (val (type (eql 'simple-string)) database)
628   (declare (ignore database))
629   val)
630
631 (defmethod read-sql-value (val (type (eql 'simple-base-string)) database)
632   (declare (ignore database))
633   val)
634
635 (defmethod read-sql-value (val (type (eql 'raw-string)) database)
636   (declare (ignore database))
637   val)
638
639 (defmethod read-sql-value (val (type (eql 'keyword)) database)
640   (declare (ignore database))
641   (when (< 0 (length val))
642     (intern (symbol-name-default-case val) 
643             (find-package '#:keyword))))
644
645 (defmethod read-sql-value (val (type (eql 'symbol)) database)
646   (declare (ignore database))
647   (when (< 0 (length val))
648     (unless (string= val (clsql-base:symbol-name-default-case "NIL"))
649       (intern (clsql-base:symbol-name-default-case val)
650               (symbol-package *update-context*)))))
651
652 (defmethod read-sql-value (val (type (eql 'integer)) database)
653   (declare (ignore database))
654   (etypecase val
655     (string
656      (unless (string-equal "NIL" val)
657        (parse-integer val)))
658     (number val)))
659
660 (defmethod read-sql-value (val (type (eql 'bigint)) database)
661   (declare (ignore database))
662   (etypecase val
663     (string
664      (unless (string-equal "NIL" val)
665        (parse-integer val)))
666     (number val)))
667
668 (defmethod read-sql-value (val (type (eql 'float)) database)
669   (declare (ignore database))
670   ;; writing 1.0 writes 1, so we we *really* want a float, must do (float ...)
671   (float (read-from-string val))) 
672
673 (defmethod read-sql-value (val (type (eql 'boolean)) database)
674   (case (database-underlying-type database)
675     (:mysql
676      (etypecase val
677        (string (if (string= "0" val) nil t))
678        (integer (if (zerop val) nil t))))
679     (:postgresql
680      (if (eq :odbc (database-type database))
681          (if (string= "0" val) nil t)
682        (equal "t" val)))
683     (t
684      (equal "t" val))))
685
686 (defmethod read-sql-value (val (type (eql 'univeral-time)) database)
687   (declare (ignore database))
688   (unless (eq 'NULL val)
689     (etypecase val
690       (string
691        (parse-integer val))
692       (number val))))
693
694 (defmethod read-sql-value (val (type (eql 'wall-time)) database)
695   (declare (ignore database))
696   (unless (eq 'NULL val)
697     (parse-timestring val)))
698
699 (defmethod read-sql-value (val (type (eql 'duration)) database)
700   (declare (ignore database))
701   (unless (or (eq 'NULL val)
702               (equal "NIL" val))
703     (parse-timestring val)))
704
705 ;; ------------------------------------------------------------
706 ;; Logic for 'faulting in' :join slots
707
708 (defun fault-join-slot-raw (class object slot-def)
709   (let* ((dbi (view-class-slot-db-info slot-def))
710          (jc (gethash :join-class dbi)))
711     (let ((jq (join-qualifier class object slot-def)))
712       (when jq 
713         (select jc :where jq :flatp t :result-types nil)))))
714
715 (defun fault-join-slot (class object slot-def)
716   (let* ((dbi (view-class-slot-db-info slot-def))
717          (ts (gethash :target-slot dbi))
718          (res (fault-join-slot-raw class object slot-def)))
719     (when res
720       (cond
721        ((and ts (gethash :target-slot dbi) (gethash :set dbi))
722         (mapcar (lambda (obj)
723                   (let* ((target-name (gethash :target-slot dbi))
724                          (target-class (find-class target-name)))
725                     (cons 
726                      (car
727                       (fault-join-slot-raw 
728                        target-class
729                        obj
730                        (find target-name (class-slots (class-of obj))
731                              :key #'slot-definition-name)))
732                      obj)))
733                  res))
734         ((and ts (gethash :set dbi))
735          (mapcar (lambda (obj)
736                    (cons obj (slot-value obj ts))) res))
737         ((and ts (not (gethash :set dbi)))
738          (mapcar (lambda (obj) (slot-value obj ts)) res))
739         ((and (not ts) (not (gethash :set dbi)))
740          (car res))
741         ((and (not ts) (gethash :set dbi))
742          res)))))
743
744 (defun join-qualifier (class object slot-def)
745     (declare (ignore class))
746     (let* ((dbi (view-class-slot-db-info slot-def))
747            (jc (find-class (gethash :join-class dbi)))
748            ;;(ts (gethash :target-slot dbi))
749            ;;(tsdef (if ts (slotdef-for-slot-with-class ts jc)))
750            (foreign-keys (gethash :foreign-key dbi))
751            (home-keys (gethash :home-key dbi)))
752       (when (every #'(lambda (slt)
753                        (and (slot-boundp object slt)
754                             (not (null (slot-value object slt)))))
755                    (if (listp home-keys) home-keys (list home-keys)))
756         (let ((jc
757                (mapcar #'(lambda (hk fk)
758                            (let ((fksd (slotdef-for-slot-with-class fk jc)))
759                              (sql-operation '==
760                                             (typecase fk
761                                               (symbol
762                                                (sql-expression
763                                                 :attribute
764                                                 (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)
773                            home-keys
774                            (list home-keys))
775                        (if (listp foreign-keys)
776                            foreign-keys
777                            (list foreign-keys)))))
778           (when jc
779             (if (> (length jc) 1)
780                 (apply #'sql-and jc)
781                 jc))))))
782
783 (defun find-all (view-classes &rest args &key all set-operation distinct from
784                  where group-by having order-by order-by-descending offset limit
785                  refresh flatp result-types (database *default-database*))
786   "Called by SELECT to generate object query results when the
787   View Classes VIEW-CLASSES are passed as arguments to SELECT."
788   (declare (ignore all set-operation group-by having offset limit result-types)
789            (optimize (debug 3) (speed 1)))
790   (remf args :from)
791   (remf args :flatp)
792   (remf args :result-types)
793   (labels ((table-sql-expr (table)
794              (sql-expression :table (view-table table)))
795            (ref-equal (ref1 ref2)
796              (equal (sql ref1)
797                     (sql ref2)))
798            (tables-equal (table-a table-b)
799              (string= (string (slot-value table-a 'name))
800                       (string (slot-value table-b 'name))))
801            (build-object (vals vclass selects)
802              (let* ((class-name (class-name vclass))
803                     (db-vals (butlast vals (- (list-length vals)
804                                               (list-length selects))))
805                     (*db-initializing* t)
806                     (obj (make-instance class-name :view-database database)))
807                ;; use refresh keyword here 
808                (setf obj (get-slot-values-from-view obj (mapcar #'car selects) 
809                                                     db-vals))
810                (when refresh (instance-refreshed obj))
811                obj))
812            (build-objects (vals sclasses sels)
813              (let ((objects (mapcar #'(lambda (sclass sel) 
814                                         (prog1 (build-object vals sclass sel)
815                                           (setf vals (nthcdr (list-length sel)
816                                                              vals))))
817                                     sclasses sels)))
818                (if (and flatp (= (length sclasses) 1))
819                    (car objects)
820                    objects))))
821     (let* ((*db-deserializing* t)
822            (*default-database* (or database
823                                    (error 'clsql-base::clsql-no-database-error :database nil)))
824            (sclasses (mapcar #'find-class view-classes))
825            (sels (mapcar #'generate-selection-list sclasses))
826            (fullsels (apply #'append sels))
827            (sel-tables (collect-table-refs where))
828            (tables (remove-duplicates (append (mapcar #'table-sql-expr sclasses)
829                                               sel-tables)
830                                       :test #'tables-equal))
831            (res nil))
832         (dolist (ob (listify order-by))
833           (when (and ob (not (member ob (mapcar #'cdr fullsels)
834                                      :test #'ref-equal)))
835             (setq fullsels 
836                   (append fullsels (mapcar #'(lambda (att) (cons nil att))
837                                            (listify ob))))))
838         (dolist (ob (listify order-by-descending))
839           (when (and ob (not (member ob (mapcar #'cdr fullsels)
840                                      :test #'ref-equal)))
841             (setq fullsels 
842                   (append fullsels (mapcar #'(lambda (att) (cons nil att))
843                                            (listify ob))))))
844         (dolist (ob (listify distinct))
845           (when (and (typep ob 'sql-ident) 
846                      (not (member ob (mapcar #'cdr fullsels) 
847                                   :test #'ref-equal)))
848             (setq fullsels 
849                   (append fullsels (mapcar #'(lambda (att) (cons nil att))
850                                            (listify ob))))))
851         (setq res 
852               (apply #'select 
853                      (append (mapcar #'cdr fullsels)
854                              (cons :from 
855                                    (list (append (when from (listify from)) 
856                                                  (listify tables)))) 
857                              (list :result-types nil)
858                              args)))
859         (mapcar #'(lambda (r) (build-objects r sclasses sels)) res))))
860
861 (defmethod instance-refreshed ((instance standard-db-object)))
862
863 (defun select (&rest select-all-args) 
864    "The function SELECT selects data from DATABASE, which has a
865 default value of *DEFAULT-DATABASE*, given the constraints
866 specified by the rest of the ARGS. It returns a list of objects
867 as specified by SELECTIONS. By default, the objects will each be
868 represented as lists of attribute values. The argument SELECTIONS
869 consists either of database identifiers, type-modified database
870 identifiers or literal strings. A type-modifed database
871 identifier is an expression such as [foo :string] which means
872 that the values in column foo are returned as Lisp strings.  The
873 FLATP argument, which has a default value of nil, specifies if
874 full bracketed results should be returned for each matched
875 entry. If FLATP is nil, the results are returned as a list of
876 lists. If FLATP is t, the results are returned as elements of a
877 list, only if there is only one result per row. The arguments
878 ALL, SET-OPERATION, DISTINCT, FROM, WHERE, GROUP-BY, HAVING and
879 ORDER-by have the same function as the equivalent SQL expression.
880 The SELECT function is common across both the functional and
881 object-oriented SQL interfaces. If selections refers to View
882 Classes then the select operation becomes object-oriented. This
883 means that SELECT returns a list of View Class instances, and
884 SLOT-VALUE becomes a valid SQL operator for use within the where
885 clause. In the View Class case, a second equivalent select call
886 will return the same View Class instance objects. If REFRESH is
887 true, then existing instances are updated if necessary, and in
888 this case you might need to extend the hook INSTANCE-REFRESHED.
889 The default value of REFRESH is nil. SQL expressions used in the
890 SELECT function are specified using the square bracket syntax,
891 once this syntax has been enabled using
892 ENABLE-SQL-READER-SYNTAX."
893
894   (flet ((select-objects (target-args)
895            (and target-args
896                 (every #'(lambda (arg)
897                            (and (symbolp arg)
898                                 (find-class arg nil)))
899                        target-args))))
900     (multiple-value-bind (target-args qualifier-args)
901         (query-get-selections select-all-args)
902       (if (select-objects target-args)
903           (apply #'find-all target-args qualifier-args)
904         (let* ((expr (apply #'make-query select-all-args))
905                (specified-types
906                 (mapcar #'(lambda (attrib)
907                             (if (typep attrib 'sql-ident-attribute)
908                                 (let ((type (slot-value attrib 'type)))
909                                   (if type
910                                       type
911                                     t))
912                               t))
913                         (slot-value expr 'selections))))
914           (destructuring-bind (&key (flatp nil)
915                                     (result-types :auto)
916                                     (field-names t) 
917                                     (database *default-database*)
918                                &allow-other-keys)
919               qualifier-args
920             (query expr :flatp flatp 
921                    :result-types 
922                    ;; specifying a type for an attribute overrides result-types
923                    (if (some #'(lambda (x) (not (eq t x))) specified-types) 
924                        specified-types
925                      result-types)
926                    :field-names field-names
927                    :database database)))))))
928