0d60e97022abfae8cfdcdfa7ffb66fdf97f569a3
[clsql.git] / tests / datasets.lisp
1 ;;;; Proposed new file in clsql-tests to enable abstracting datasets for reuse.
2 ;;;;
3 ;;;; The core is def-datset and with-dataset that respectively define a set,
4 ;;;; and enable one for a dynamic scope. Datasets will normally be setup and
5 ;;;; torn down in the scope of one test, which may impose a computation
6 ;;;; overhead, but enables simpler tests by not worrying about side-effects
7 ;;;; between tests.
8 ;;;;
9 ;;;; In general datasets should be database agnostic, but because the code
10 ;;;; is only run in the scope of a test, if a test is excluded for a backend
11 ;;;; or some other reason then it is never run hence doesn't cause problems.
12
13 (in-package #:clsql-tests)
14
15 (defparameter *dataset-debug-on-error* nil
16   "If we get an error while loading or cleaning up the dataset,
17 should we debug (T) or just print and quit.")
18
19 (defun generic-error (e)
20   (when (and *dataset-debug-on-error*
21              *debugger-hook*)
22     (invoke-debugger e))
23   (princ e *error-output*)
24   (throw 'quit-dataset e))
25
26 (defmacro def-dataset (name &body body)
27   "Define a dataset"
28   ;;probably just shove this into a param, perhaps a marginal
29   ;; bit of processing first.
30   `(defparameter ,name ',body))
31
32 (defmacro with-dataset (name &body body)
33   "Use a dataset in a dynamic scope, e.g. a single test.
34 1. Before the body:
35   * :setup is run
36   * :data is loaded
37 2. Body
38 3. :cleanup always happens"
39   `(catch 'quit-dataset
40      (unwind-protect
41           (progn 
42             (restart-case (%dataset-init ,name)
43               (retry-dataset-init ()
44                 :report ,(format nil "Retry dataset('~a) init: (with any dataset changes)"
45                                 (symbol-name name))
46                 (%dataset-init ,name))
47               (skip-this-test ()
48                 :report "FAIL and run the next test"
49                 (throw 'quit-dataset :data-set-failure)))
50             ,@body)
51        (%dataset-cleanup ,name))))
52
53
54 (defun %dataset-dispatch (arg)
55   "For use with def-dataset and with-dataset, tries to DWIM."
56   (etypecase arg
57     (string (clsql-sys:execute-command arg))  ;treat it as a sql command.
58     ((or function symbol) (funcall arg))       ;run functions
59     (list
60        (case (first arg)
61          ((function lambda) (%dataset-dispatch (eval arg))) ;#' forms, lambdas
62          (progn (mapc #'%dataset-dispatch (rest arg)))    ; (progn "asdf" "ff")
63          (ignore-errors (ignore-errors (mapc #'%dataset-dispatch (rest arg))))
64          (t (mapc #'%dataset-dispatch arg)))    ;otherwise implicit progn
65        )))
66
67 (defun %dataset-init (name)
68   "Run initialization code and fill database for given dataset."
69       (handler-bind
70           ((error #'generic-error))
71         ;;find items that looks like '(:setup ...),
72         ;; dispatch the rest.
73         (let ((setup (rest (find :setup name :key #'first)))
74               (sqldata (rest (find :sqldata name :key #'first)))
75               (objdata (rest (find :objdata name :key #'first))))
76           (when setup
77             (%dataset-dispatch setup))
78           (when sqldata
79             ;;run raw sql insert statements
80             (destructuring-bind (table-name columns &rest values-list) sqldata
81               (dolist (v values-list)
82                 (clsql-sys:execute-command
83                  (format nil
84                          "INSERT INTO ~a (~a) VALUES (~a)"
85                          table-name columns v)))))
86           (when objdata
87             ;;presumed to be view-class objects, force them to insert.
88             (dolist (o objdata)
89               (setf (slot-value o 'clsql-sys::view-database) nil)
90               (clsql-sys:update-records-from-instance o))))))
91
92 (defun %dataset-cleanup (name)
93   "Run cleanup code associated with the given dataset."
94   (restart-case 
95       (handler-bind ((error #'generic-error))
96         (let ((cleanup (rest (find :cleanup name :key #'first))))
97           (when cleanup
98             (%dataset-dispatch cleanup))))
99     (retry-dataset-cleanup ()
100       :report "Retry dataset cleanup (with any dataset changes)"
101       (%dataset-cleanup name))
102     (skip-cleanup () nil)))
103
104
105 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
106 ;;; Example Test Code
107
108 ;;incomplete example taken from test-init
109 ;; (def-dataset *employees*
110 ;;   (:setup "CREATE TABLE employee
111 ;; (
112 ;;   emplid integer NOT NULL,
113 ;;   groupid integer NOT NULL,
114 ;;   first_name character varying(30),
115 ;;   last_name character varying(30),
116 ;;   email character varying(100),
117 ;;   ecompanyid integer,
118 ;;   managerid integer,
119 ;;   height double,
120 ;;   married boolean,
121 ;;   birthday timestamp without time zone,
122 ;;   bd_utime bigint,
123 ;;   CONSTRAINT employeepk PRIMARY KEY (emplid, groupid),
124 ;;   CONSTRAINT employee_emplid_key UNIQUE (emplid)
125 ;; )
126 ;; ")
127 ;;   ;;alternatively setup can still be done as
128 ;;   ;;(:setup #'(lambda () (create-view-from-class ...)))
129 ;;   (:sqldata "employees" "emplid,groupid,married,height,first_name,last_name"
130 ;;          "1,1,false,1.5,'Napolean', 'Bonaparte'"
131 ;;          (format nil "1,1,true,~a,'Vladimir','Lenin'" (1+ (random 1.00))))
132 ;;   (:cleanup "DROP TABLE EMPLOYEES"))
133