r9427: 22 May 2004 Kevin Rosenberg
[clsql.git] / db-oracle / oracle-sql.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          oracle-sql.lisp
6 ;;;;
7 ;;;; $Id$
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-oracle)
17
18 (defmethod database-initialize-database-type
19     ((database-type (eql :oracle)))
20   t)
21
22 ;;;; arbitrary parameters, tunable for performance or other reasons
23
24 (eval-when (:compile-toplevel :load-toplevel :execute)
25   (defconstant +errbuf-len+ 512
26     "the number of characters that we allocate for an error message buffer")
27   (defconstant +n-buf-rows+ 200
28     "the number of table rows that we buffer at once when reading a table.
29 CMUCL has a compiled-in limit on how much C data can be allocated
30 (through malloc() and friends) at any given time, typically 8 Mb.
31 Setting this constant to a moderate value should make it less
32 likely that we'll have to worry about the CMUCL limit."))
33
34
35 (defmacro deref-vp (foreign-object)
36   `(uffi:deref-pointer ,foreign-object :pointer-void))
37
38 ;; constants - from OCI?
39
40 (defconstant +var-not-in-list+       1007)
41 (defconstant +no-data-found+         1403)
42 (defconstant +null-value-returned+   1405)
43 (defconstant +field-truncated+       1406)
44
45 (eval-when (:compile-toplevel :load-toplevel :execute)
46   (defconstant SQLT-NUMBER 2)
47   (defconstant SQLT-INT 3)
48   (defconstant SQLT-STR 5)
49   (defconstant SQLT-FLT 4)
50   (defconstant SQLT-DATE 12))
51
52 ;;; Note that despite the suggestive class name (and the way that the
53 ;;; *DEFAULT-DATABASE* variable holds an object of this class), a DB
54 ;;; object is not actually a database but is instead a connection to a
55 ;;; database. Thus, there's no obstacle to having any number of DB
56 ;;; objects referring to the same database.
57
58 (uffi:def-type pointer-pointer-void '(* :pointer-void))
59
60 (defclass oracle-database (database)    ; was struct db
61   ((envhp
62     :reader envhp
63     :initarg :envhp
64     :type pointer-pointer-void
65     :documentation
66     "OCI environment handle")
67    (errhp
68     :reader errhp
69     :initarg :errhp
70     :type pointer-pointer-void
71     :documentation
72     "OCI error handle")
73    (svchp
74     :reader svchp
75     :initarg :svchp
76     :type pointer-pointer-void
77     :documentation
78     "OCI service context handle")
79    (data-source-name
80     :initarg :dsn
81     :initform nil
82     :documentation
83     "optional data source name (used only for debugging/printing)")
84    (user
85     :initarg :user
86     :reader user
87     :type string
88     :documentation
89     "the \"user\" value given when data source connection was made")
90    (date-format
91     :initarg :date-format
92     :reader date-format
93     :initform "YYYY-MM-DD HH24:MI:SS\"+00\"")
94    (date-format-length
95     :type number
96     :documentation
97     "Each database connection can be configured with its own date
98 output format.  In order to extract date strings from output buffers
99 holding multiple date strings in fixed-width fields, we need to know
100 the length of that format.")
101    (server-version 
102     :type string
103     :initarg :server-version
104     :reader server-version
105     :documentation
106     "Version string of Oracle server.")
107    (major-version-number
108     :type (or null fixnum)
109     :initarg :major-version-number
110     :reader major-version-number
111     :documentation
112     "The major version number of Oracle, should be 8, 9, or 10")))
113
114
115 ;;; Handle the messy case of return code=+oci-error+, querying the
116 ;;; system for subcodes and reporting them as appropriate. ERRHP and
117 ;;; NULLS-OK are as in the OERR function.
118
119 (defun handle-oci-error (&key database nulls-ok)
120   (cond (database
121          (with-slots (errhp)
122              database
123            (uffi:with-foreign-objects ((errbuf '(:array :unsigned-char
124                                                  #.+errbuf-len+))
125                                        (errcode :long))
126              ;; ensure errbuf empty string
127              (setf (uffi:deref-array errbuf '(:array :unsigned-char) 0)
128                    (uffi:ensure-char-storable (code-char 0)))
129
130              (setf (uffi:deref-pointer errcode :long) 0)
131              (oci-error-get (deref-vp errhp) 1
132                             (uffi:make-null-pointer :unsigned-char)
133                             errcode errbuf +errbuf-len+ +oci-htype-error+)
134              (let ((subcode (uffi:deref-pointer errcode :long)))
135                (unless (and nulls-ok (= subcode +null-value-returned+))
136                  (error 'sql-database-error
137                         :database database
138                         :error-id subcode
139                         :message (uffi:convert-from-foreign-string errbuf)))))))
140         (nulls-ok
141          (error 'sql-database-error
142                 :database database
143                 :message "can't handle NULLS-OK without ERRHP"))
144         (t 
145          (error 'sql-database-error
146                 :database database
147                 :message "OCI Error (and no ERRHP available to find subcode)"))))
148
149 ;;; Require an OCI success code.
150 ;;;
151 ;;; (The ordinary OCI error reporting mechanisms uses a fair amount of
152 ;;; machinery (environments and other handles). In order to get to
153 ;;; where we can use these mechanisms, we have to be able to allocate
154 ;;; the machinery. The functions for allocating the machinery can
155 ;;; return errors (e.g. out of memory) but shouldn't. Wrapping this function
156 ;;; around function calls to such have-to-succeed functions enforces
157 ;;; this condition.)
158
159 (defun osucc (code)
160   (declare (type fixnum code))
161   (unless (= code +oci-success+)
162     (error 'sql-database-error
163            :message (format nil "unexpected OCI failure, code=~S" code))))
164
165
166 ;;; Enabling this can be handy for low-level debugging.
167 #+nil
168 (progn
169   (trace oci-initialize #+oci-8-1-5 oci-env-create oci-handle-alloc oci-logon
170          oci-error-get oci-stmt-prepare oci-stmt-execute
171          oci-param-get oci-logon oci-attr-get oci-define-by-pos oci-stmt-fetch)
172   (setf debug::*debug-print-length* nil))
173
174
175 ;;;; the OCI library, part V: converting from OCI representations to Lisp
176 ;;;; representations
177
178 ;; Return the INDEXth string of the OCI array, represented as Lisp
179 ;; SIMPLE-STRING. SIZE is the size of the fixed-width fields used by
180 ;; Oracle to store strings within the array.
181
182 ;; In the wild world of databases, trailing spaces aren't generally
183 ;; significant, since e.g. "LARRY " and "LARRY    " are the same string
184 ;; stored in different fixed-width fields. OCI drops trailing spaces
185 ;; for us in some cases but apparently not for fields of fixed
186 ;; character width, e.g.
187 ;;
188 ;;   (dbi:sql "create table employees (name char(15), job char(15), city
189 ;;            char(15), rate float)" :db orcl :types :auto)
190 ;; In order to map the "same string" property above onto Lisp equality,
191 ;; we drop trailing spaces in all cases:
192
193 (uffi:def-type string-array (:array :unsigned-char))
194
195 (defun deref-oci-string (arrayptr string-index size)
196   (declare (type string-array arrayptr))
197   (declare (type (mod #.+n-buf-rows+) string-index))
198   (declare (type (and unsigned-byte fixnum) size))
199   (let* ((raw (uffi:convert-from-foreign-string 
200                (uffi:make-pointer
201                 (+ (uffi:pointer-address arrayptr) (* string-index size))
202                 :unsigned-char)))
203          (trimmed (string-trim " " raw)))
204      (if (equal trimmed "NULL") nil trimmed)))
205
206 ;; the OCI library, part Z: no-longer used logic to convert from
207 ;; Oracle's binary date representation to Common Lisp's native date
208 ;; representation
209
210 #+nil
211 (defvar +oci-date-bytes+ 7)
212
213 ;;; Return the INDEXth date in the OCI array, represented as
214 ;;; a Common Lisp "universal time" (i.e. seconds since 1900).
215
216 #+nil
217 (defun deref-oci-date (arrayptr index)
218   (oci-date->universal-time (uffi:pointer-address 
219                              (uffi:deref-array arrayptr
220                                                '(:array :unsigned-char)
221                                                (* index +oci-date-bytes+)))))
222 #+nil
223 (defun oci-date->universal-time (oci-date)
224   (declare (type (alien (* :unsigned-char)) oci-date))
225   (flet (;; a character from OCI-DATE, interpreted as an unsigned byte
226          (ub (i)
227            (declare (type (mod #.+oci-date-bytes+) i))
228            (mod (uffi:deref-array oci-date string-array i) 256)))
229     (let* ((century (* (- (ub 0) 100) 100))
230            (year    (+ century (- (ub 1) 100)))
231            (month   (ub 2))
232            (day     (ub 3))
233            (hour    (1- (ub 4)))
234            (minute  (1- (ub 5)))
235            (second  (1- (ub 6))))
236       (encode-universal-time second minute hour day month year))))
237
238
239 (defmethod database-list-tables ((database oracle-database) &key owner)
240   (let ((query
241           (if owner
242               (format nil
243                       "select user_tables.table_name from user_tables,all_tables where user_tables.table_name=all_tables.table_name and all_tables.owner='~:@(~A~)'"
244                       owner)
245               "select table_name from user_tables")))
246     (mapcar #'car (database-query query database nil nil))))
247
248
249 (defmethod database-list-views ((database oracle-database) &key owner)
250   (let ((query
251           (if owner
252               (format nil
253                       "select user_views.view_name from user_views,all_views where user_views.view_name=all_views.view_name and all_views.owner='~:@(~A~)'"
254                       owner)
255               "select view_name from user_views")))
256     (mapcar #'car
257           (database-query query database nil nil))))
258
259 (defmethod database-list-indexes ((database oracle-database)
260                                   &key (owner nil))
261   (let ((query
262           (if owner
263               (format nil
264                       "select user_indexes.index_name from user_indexes,all_indexes where user_indexes.index_name=all_indexes.index_name and all_indexes.owner='~:@(~A~)'"
265                       owner)
266               "select index_name from user_indexes")))
267     (mapcar #'car (database-query query database nil nil))))
268
269 (defmethod database-list-table-indexes (table (database oracle-database)
270                                         &key (owner nil))
271   (let ((query
272           (if owner
273               (format nil
274                       "select user_indexes.index_name from user_indexes,all_indexes where user_indexes.table_name='~A' and user_indexes.index_name=all_indexes.index_name and all_indexes.owner='~:@(~A~)'"
275                       table owner)
276               (format nil "select index_name from user_indexes where table_name='~A'"
277                       table))))
278     (mapcar #'car (database-query query database nil nil))))
279
280 (defmethod list-all-table-columns (table (db oracle-database))
281   (declare (string table))
282   (let* ((sql-stmt (concatenate
283                     'simple-string
284                     "select "
285                     "'',"
286                     "all_tables.OWNER,"
287                     "'',"
288                     "user_tab_columns.COLUMN_NAME,"
289                     "user_tab_columns.DATA_TYPE from user_tab_columns,"
290                     "all_tables where all_tables.table_name = '" table "'"
291                     " and user_tab_columns.table_name = '" table "'"))
292          (preresult (database-query sql-stmt db :auto nil)))
293     ;; PRERESULT is like RESULT except that it has a name instead of
294     ;; type codes in the fifth column of each row. To fix this, we
295     ;; destructively modify PRERESULT.
296     (dolist (preresult-row preresult)
297       (setf (fifth preresult-row)
298             (if (find (fifth preresult-row)
299                       #("NUMBER" "DATE")
300                       :test #'string=)
301                 2 ; numeric
302                 1))) ; string
303     preresult))
304
305 (defmethod database-list-attributes (table (database oracle-database) &key owner)
306   (let ((query
307           (if owner
308               (format nil
309                       "select user_tab_columns.column_name from user_tab_columns,all_tables where user_tab_columns.table_name='~A' and all_tables.table_name=user_tab_columns.table_name and all_tables.owner='~:@(~A~)'"
310                       table owner)
311               (format nil
312                       "select column_name from user_tab_columns where table_name='~A'"
313                       table))))
314     (mapcar #'car (database-query query database nil nil))))
315
316 (defmethod database-attribute-type (attribute (table string)
317                                          (database oracle-database)
318                                          &key (owner nil))
319   (let ((query   
320          (if owner
321              (format nil
322                      "select data_type,data_length,data_scale,nullable from user_tab_columns,all_tables where user_tab_columns.table_name='~A' and column_name='~A' and all_tables.table_name=user_tab_columns.table_name and all_tables.owner='~:@(~A~)'"
323                      table attribute owner)
324              (format nil
325                      "select data_type,data_length,data_scale,nullable from user_tab_columns where table_name='~A' and column_name='~A'"
326                      table attribute))))
327     (destructuring-bind (type length scale nullable) (car (database-query query database :auto nil))
328       (values (ensure-keyword type) length scale 
329               (if (char-equal #\Y (schar nullable 0)) 1 0)))))
330     
331 ;; Return one row of the table referred to by QC, represented as a
332 ;; list; or if there are no more rows, signal an error if EOF-ERRORP,
333 ;; or return EOF-VALUE otherwise.
334
335 ;; KLUDGE: This CASE statement is a strong sign that the code would be
336 ;; cleaner if CD were made into an abstract class, we made variant
337 ;; classes for CD-for-column-of-strings, CD-for-column-of-floats,
338 ;; etc., and defined virtual functions to handle operations like
339 ;; get-an-element-from-column. (For a small special purpose module
340 ;; like this, would arguably be overkill, so I'm not going to do it
341 ;; now, but if this code ends up getting more complicated in
342 ;; maintenance, it would become a really good idea.)
343
344 ;; Arguably this would be a good place to signal END-OF-FILE, but
345 ;; since the ANSI spec specifically says that END-OF-FILE means a
346 ;; STREAM which has no more data, and QC is not a STREAM, we signal
347 ;; DBI-ERROR instead.
348
349 (uffi:def-type short-array '(:array :short))
350 (uffi:def-type int-pointer '(* :int))
351 (uffi:def-type double-pointer '(* :double))
352
353 ;;; the result of a database query: a cursor through a table
354 (defstruct (oracle-result-set (:print-function print-query-cursor)
355                               (:conc-name qc-)
356                               (:constructor %make-query-cursor))
357   (db (error "missing DB")   ; db conn. this table is associated with
358     :type oracle-database
359     :read-only t)
360   (stmthp (error "missing STMTHP")      ; the statement handle used to create
361 ;;  :type alien                 ; this table. owned by the QUERY-CURSOR
362     :read-only t)                       ; object, deallocated on CLOSE-QUERY
363   (cds) ;  (error "missing CDS")            ; column descriptors
364 ;    :type (simple-array cd 1)
365                                         ;    :read-only t)
366   (n-from-oci 
367    0                         ; buffered rows: number of rows recv'd
368    :type (integer 0 #.+n-buf-rows+))   ; from the database on the last read
369   (n-to-dbi
370    0                           ; number of buffered rows returned, i.e.
371    :type (integer 0 #.+n-buf-rows+))   ; the index, within the buffered rows,
372                                         ; of the next row which hasn't already
373                                         ; been returned
374   (total-n-from-oci
375    0                   ; total number of bytes recv'd from OCI
376    :type unsigned-byte)                ; in all reads
377   (oci-end-seen-p nil))                 ; Have we seen the end of OCI
378                                         ; data, i.e. OCI returning
379                                         ; less data than we requested?
380                                         ; OCI doesn't seem to like us
381                                         ; to try to read more data
382                                         ; from it after that..
383
384
385 (defun fetch-row (qc &optional (eof-errorp t) eof-value)
386   ;;(declare (optimize (speed 3)))
387   (cond ((zerop (qc-n-from-oci qc))
388          (if eof-errorp
389              (error 'sql-database-error :message
390                     (format nil "no more rows available in ~S" qc))
391            eof-value))
392         ((>= (qc-n-to-dbi qc)
393              (qc-n-from-oci qc))
394          (refill-qc-buffers qc)
395          (fetch-row qc nil eof-value))
396         (t
397          (let ((cds (qc-cds qc))
398                (reversed-result nil)
399                (irow (qc-n-to-dbi qc)))
400            (dotimes (icd (length cds))
401              (let* ((cd (aref cds icd))
402                     (b (foreign-resource-buffer (cd-buffer cd)))
403                     (value
404                      (let* ((arb (foreign-resource-buffer (cd-indicators cd)))
405                             (indicator (uffi:deref-array arb '(:array :short) irow)))
406                        (declare (type short-array arb))
407                        (unless (= indicator -1)
408                          (ecase (cd-oci-data-type cd)
409                            (#.SQLT-STR  
410                             (deref-oci-string b irow (cd-sizeof cd)))
411                            (#.SQLT-FLT  
412                             (uffi:deref-array b '(:array :double) irow))
413                            (#.SQLT-INT  
414                             (uffi:deref-array b '(:array :int) irow))
415                            (#.SQLT-DATE 
416                             (deref-oci-string b irow (cd-sizeof cd))))))))
417                (when (and (eq :string (cd-result-type cd))
418                           value
419                           (not (stringp value)))
420                    (setq value (write-to-string value)))
421                (push value reversed-result)))
422            (incf (qc-n-to-dbi qc))
423            (nreverse reversed-result)))))
424
425 (defun refill-qc-buffers (qc)
426   (with-slots (errhp) (qc-db qc)
427     (setf (qc-n-to-dbi qc) 0)
428     (cond ((qc-oci-end-seen-p qc)
429            (setf (qc-n-from-oci qc) 0))
430           (t
431            (let ((oci-code (%oci-stmt-fetch 
432                             (deref-vp (qc-stmthp qc))
433                             (deref-vp errhp)
434                             +n-buf-rows+
435                             +oci-fetch-next+ +oci-default+)))
436              (ecase oci-code
437                (#.+oci-success+ (values))
438                (#.+oci-no-data+ (setf (qc-oci-end-seen-p qc) t)
439                                 (values))
440                (#.+oci-error+ (handle-oci-error :database (qc-db qc)
441                                                 :nulls-ok t))))
442            (uffi:with-foreign-object (rowcount :long)
443              (oci-attr-get (deref-vp (qc-stmthp qc))
444                            +oci-htype-stmt+
445                            rowcount 
446                            (uffi:make-null-pointer :unsigned-long)
447                            +oci-attr-row-count+ 
448                            (deref-vp errhp))
449              (setf (qc-n-from-oci qc)
450                    (- (uffi:deref-pointer rowcount :long)
451                       (qc-total-n-from-oci qc)))
452              (when (< (qc-n-from-oci qc) +n-buf-rows+)
453                (setf (qc-oci-end-seen-p qc) t))
454              (setf (qc-total-n-from-oci qc)
455                    (uffi:deref-pointer rowcount :long)))))
456     (values)))
457
458 ;; the guts of the SQL function
459 ;;
460 ;; (like the SQL function, but with the QUERY argument hardwired to T, so
461 ;; that the return value is always a cursor instead of a list)
462
463 ;; Is this a SELECT statement?  SELECT statements are handled
464 ;; specially by OCIStmtExecute().  (Non-SELECT statements absolutely
465 ;; require a nonzero iteration count, while the ordinary choice for a
466 ;; SELECT statement is a zero iteration count.
467
468 ;; SELECT statements are the only statements which return tables.  We
469 ;; don't free STMTHP in this case, but instead give it to the new
470 ;; QUERY-CURSOR, and the new QUERY-CURSOR becomes responsible for
471 ;; freeing the STMTHP when it is no longer needed.
472
473 (defun sql-stmt-exec (sql-stmt-string db result-types field-names)
474   (with-slots (envhp svchp errhp)
475     db
476     (let ((stmthp (uffi:allocate-foreign-object :pointer-void)))
477       (uffi:with-foreign-object (stmttype :unsigned-short)
478         
479         (oci-handle-alloc (deref-vp envhp)
480                           stmthp
481                           +oci-htype-stmt+ 0 +null-void-pointer-pointer+)
482         (oci-stmt-prepare (deref-vp stmthp)
483                           (deref-vp errhp)
484                           (uffi:convert-to-cstring sql-stmt-string)
485                           (length sql-stmt-string)
486                           +oci-ntv-syntax+ +oci-default+ :database db)
487         (oci-attr-get (deref-vp stmthp) 
488                       +oci-htype-stmt+ 
489                       stmttype
490                       (uffi:make-null-pointer :unsigned-int)
491                       +oci-attr-stmt-type+ 
492                       (deref-vp errhp)
493                       :database db)
494         (let* ((select-p (= (uffi:deref-pointer stmttype :unsigned-short) 1)) 
495                (iters (if select-p 0 1)))
496           
497           (oci-stmt-execute (deref-vp svchp)
498                             (deref-vp stmthp)
499                             (deref-vp errhp)
500                             iters 0 +null-void-pointer+ +null-void-pointer+ +oci-default+
501                             :database db)
502           (cond (select-p
503                  (make-query-cursor db stmthp result-types field-names))
504                 (t
505                  (oci-handle-free (deref-vp stmthp) +oci-htype-stmt+)
506                  nil)))))))
507
508
509 ;; Return a QUERY-CURSOR representing the table returned from the OCI
510 ;; operation done through STMTHP.  TYPES is the argument of the same
511 ;; name from the external SQL function, controlling type conversion
512 ;; of the returned arguments.
513
514 (defun make-query-cursor (db stmthp result-types field-names)
515   (let ((qc (%make-query-cursor :db db
516                                 :stmthp stmthp
517                                 :cds (make-query-cursor-cds db stmthp 
518                                                             result-types
519                                                             field-names))))
520     (refill-qc-buffers qc)
521     qc))
522
523
524 ;; the hairy part of MAKE-QUERY-CURSOR: Ask OCI for information
525 ;; about table columns, translate the information into a Lisp
526 ;; vector of column descriptors, and return it.
527
528 ;; Allegro defines several flavors of type conversion, but this
529 ;; implementation only supports the :AUTO flavor.
530
531 ;; A note of explanation: OCI's internal number format uses 21
532 ;; bytes (42 decimal digits). 2 separate (?) one-byte fields,
533 ;; scale and precision, are used to deduce the nature of these
534 ;; 21 bytes. See pp. 3-10, 3-26, and 6-13 of OCI documentation
535 ;; for more details.
536
537 ;; When calling OCI C code to handle the conversion, we have
538 ;; only two numeric types available to pass the return value:
539 ;; double-float and signed-long. It would be possible to
540 ;; bypass the OCI conversion functions and write Lisp code
541 ;; which reads the 21-byte field directly and decodes
542 ;; it. However this is left as an exercise for the reader. :-)
543
544 ;; The following table describes the mapping, based on the implicit
545 ;; assumption that C's "signed long" type is a 32-bit integer.
546 ;;
547 ;;   Internal Values                     SQL Type        C Return Type
548 ;;   ===============                     ========        =============
549 ;;   Precision > 0        SCALE = -127   FLOAT       --> double-float
550 ;;   Precision > 0 && <=9 SCALE = 0      INTEGER     --> signed-long
551 ;;   Precision = 0 || > 9 SCALE = 0      BIG INTEGER --> double-float
552 ;;   Precision > 0        SCALE > 0      DECIMAL     --> double-float
553
554 ;; (OCI uses 1-based indexing here.)
555
556 ;; KLUDGE: This should work for all other data types except those
557 ;; which don't actually fit in their fixed-width field (BLOBs and the
558 ;; like). As Winton says, we (Cadabra) don't need to worry much about
559 ;; those, since we can't reason with them, so we don't use them. But
560 ;; for a more general application it'd be good to have a more
561 ;; selective and rigorously correct test here for whether we can
562 ;; actually handle the given DEREF-DTYPE value. -- WHN 20000106
563
564 ;; Note: The OCI documentation doesn't seem to say whether the COLNAME
565 ;; value returned here is a newly-allocated copy which we're
566 ;; responsible for freeing, or a pointer into some system copy which
567 ;; will be freed when the system itself is shut down.  But judging
568 ;; from the way that the result is used in the cdemodsa.c example
569 ;; program, it looks like the latter: we should make our own copy of
570 ;; the value, but not try to free it.
571
572 ;; WORKAROUND: OCI seems to return ub2 values for the
573 ;; +oci-attr-data-size+ attribute even though its documentation claims
574 ;; that it returns a ub4, and even though the associated "sizep" value
575 ;; is 4, not 2.  In order to make the code here work reliably, without
576 ;; having to patch it later if OCI is ever fixed to match its
577 ;; documentation, we pre-zero COLSIZE before making the call into OCI.
578
579 ;; To exercise the weird OCI behavior (thereby blowing up the code
580 ;; below, beware!) try setting this value into COLSIZE, calling OCI,
581 ;; then looking at the value in COLSIZE.  (setf colsize #x12345678)
582 ;; debugging only
583             
584
585 (defun make-query-cursor-cds (database stmthp result-types field-names)
586   (declare (optimize (safety 3) #+nil (speed 3))
587            (type oracle-database database)
588            (type pointer-pointer-void stmthp))
589   (with-slots (errhp) database
590     (uffi:with-foreign-objects ((dtype-foreign :unsigned-short)
591                            (parmdp ':pointer-void)
592                            (precision :byte)
593                            (scale :byte)
594                            (colname '(* :unsigned-char))
595                            (colnamelen :unsigned-long)
596                            (colsize :unsigned-long)
597                            (colsizesize :unsigned-long)
598                            (defnp ':pointer-void))
599       (let ((buffer nil)
600             (sizeof nil))
601         (do ((icolumn 0 (1+ icolumn))
602              (cds-as-reversed-list nil))
603             ((not (eql (oci-param-get (deref-vp stmthp) 
604                                       +oci-htype-stmt+
605                                       (deref-vp errhp)
606                                       parmdp
607                                       (1+ icolumn) :database database)
608                        +oci-success+))
609              (coerce (reverse cds-as-reversed-list) 'simple-vector))
610           ;; Decode type of ICOLUMNth column into a type we're prepared to
611           ;; handle in Lisp.
612           (oci-attr-get (deref-vp parmdp)
613                         +oci-dtype-param+ 
614                         dtype-foreign
615                         (uffi:make-null-pointer :unsigned-int)
616                         +oci-attr-data-type+
617                         (deref-vp errhp))
618           (let ((dtype (uffi:deref-pointer dtype-foreign :unsigned-short)))
619             (case dtype
620               (#.SQLT-DATE
621                (setf buffer (acquire-foreign-resource :unsigned-char
622                                                       (* 32 +n-buf-rows+)))
623                (setf sizeof 32 dtype #.SQLT-STR))
624               (#.SQLT-NUMBER
625                (oci-attr-get (deref-vp parmdp)
626                              +oci-dtype-param+
627                              precision
628                              (uffi:make-null-pointer :unsigned-int)
629                              +oci-attr-precision+
630                              (deref-vp errhp))
631                (oci-attr-get (deref-vp parmdp)
632                              +oci-dtype-param+
633                              scale
634                              (uffi:make-null-pointer :unsigned-int)
635                              +oci-attr-scale+
636                              (deref-vp errhp))
637                (let ((*scale (uffi:deref-pointer scale :byte))
638                      (*precision (uffi:deref-pointer precision :byte)))
639                  ;;(format t "scale=~d, precision=~d~%" *scale *precision)
640                  (cond
641                   ((or (zerop *scale)
642                        (and (minusp *scale) (< *precision 10)))
643                    (setf buffer (acquire-foreign-resource :int +n-buf-rows+)
644                          sizeof 4                       ;; sizeof(int)
645                          dtype #.SQLT-INT))
646                   (t
647                    (setf buffer (acquire-foreign-resource :double +n-buf-rows+)
648                          sizeof 8                   ;; sizeof(double)
649                          dtype #.SQLT-FLT))))          )
650               ;; Default to SQL-STR
651               (t                
652                (setf (uffi:deref-pointer colsize :unsigned-long) 0
653                      dtype #.SQLT-STR)
654                (oci-attr-get (deref-vp parmdp)
655                              +oci-dtype-param+ 
656                              colsize
657                              (uffi:make-null-pointer :unsigned-int) ;;  (uffi:pointer-address colsizesize) 
658                              +oci-attr-data-size+
659                              (deref-vp errhp))
660                (let ((colsize-including-null (1+ (uffi:deref-pointer colsize :unsigned-long))))
661                  (setf buffer (acquire-foreign-resource
662                                :unsigned-char (* +n-buf-rows+ colsize-including-null)))
663                  (setf sizeof colsize-including-null))))
664             (let ((retcodes (acquire-foreign-resource :unsigned-short +n-buf-rows+))
665                   (indicators (acquire-foreign-resource :short +n-buf-rows+))
666                   (colname-string ""))
667               (when field-names
668                 (oci-attr-get (deref-vp parmdp)
669                               +oci-dtype-param+
670                               colname
671                               colnamelen
672                               +oci-attr-name+
673                               (deref-vp errhp))
674                 (setq colname-string (uffi:convert-from-foreign-string
675                                       (uffi:deref-pointer colname '(* :unsigned-char))
676                                       :length (uffi:deref-pointer colnamelen :unsigned-long))))
677               (push (make-cd :name colname-string
678                              :sizeof sizeof
679                              :buffer buffer
680                              :oci-data-type dtype
681                              :retcodes retcodes
682                              :indicators indicators
683                              :result-type (cond
684                                            ((consp result-types)
685                                             (nth icolumn result-types))
686                                            ((null result-types)
687                                             :string)
688                                            (t
689                                             result-types)))
690                     cds-as-reversed-list)
691               (oci-define-by-pos (deref-vp stmthp)
692                                  defnp
693                                  (deref-vp errhp)
694                                  (1+ icolumn) ; OCI 1-based indexing again
695                                  (uffi:with-cast-pointer (vp (foreign-resource-buffer buffer) :void)
696                                    vp)
697                                  sizeof
698                                  dtype
699                                  (uffi:with-cast-pointer (vp (foreign-resource-buffer indicators) :void)
700                                    vp)
701                                  (uffi:make-null-pointer :unsigned-short)
702                                  (uffi:with-cast-pointer (vp (foreign-resource-buffer retcodes) :unsigned-short)
703                                    vp)
704                                  +oci-default+))))))))
705   
706 ;; Release the resources associated with a QUERY-CURSOR.
707
708 (defun close-query (qc)
709   (oci-handle-free (deref-vp (qc-stmthp qc)) +oci-htype-stmt+)
710   (let ((cds (qc-cds qc)))
711     (dotimes (i (length cds))
712       (release-cd-resources (aref cds i))))
713   (values))
714
715
716 ;; Release the resources associated with a column description.
717
718 (defun release-cd-resources (cd)
719   (free-foreign-resource (cd-buffer cd))
720   (free-foreign-resource (cd-retcodes cd))
721   (free-foreign-resource (cd-indicators cd))
722   (values))
723
724
725 (defmethod database-name-from-spec (connection-spec (database-type (eql :oracle)))
726   (check-connection-spec connection-spec database-type (dsn user password))
727   (destructuring-bind (dsn user password) connection-spec
728     (declare (ignore password))
729     (concatenate 'string  dsn "/" user)))
730
731
732 (defmethod database-connect (connection-spec (database-type (eql :oracle)))
733   (check-connection-spec connection-spec database-type (dsn user password))
734   (destructuring-bind (data-source-name user password)
735       connection-spec
736     (let ((envhp (uffi:allocate-foreign-object :pointer-void))
737           (errhp (uffi:allocate-foreign-object :pointer-void))
738           (svchp (uffi:allocate-foreign-object :pointer-void))
739           (srvhp (uffi:allocate-foreign-object :pointer-void)))
740       ;; Requests to allocate environments and handles should never
741       ;; fail in normal operation, and they're done too early to
742       ;; handle errors very gracefully (since they're part of the
743       ;; error-handling mechanism themselves) so we just assert they
744       ;; work.
745       (setf (deref-vp envhp) +null-void-pointer+)
746       #+oci-8-1-5
747       (progn
748         (oci-env-create envhp +oci-default+  +null-void-pointer+
749                         +null-void-pointer+  +null-void-pointer+ 
750                         +null-void-pointer+ 0 +null-void-pointer-pointer+)
751         (oci-handle-alloc envhp
752                           (deref-vp errhp)
753                           +oci-htype-error+ 0 
754                           +null-void-pointer-pointer+))
755       #-oci-8-1-5
756       (progn
757         (oci-initialize +oci-object+ +null-void-pointer+ +null-void-pointer+
758                         +null-void-pointer+ +null-void-pointer-pointer+)
759         (ignore-errors (oci-handle-alloc +null-void-pointer+ envhp
760                                          +oci-htype-env+ 0
761                                          +null-void-pointer-pointer+)) ;no testing return
762         (oci-env-init envhp +oci-default+ 0 +null-void-pointer-pointer+)
763         (oci-handle-alloc (deref-vp envhp) errhp
764                           +oci-htype-error+ 0 +null-void-pointer-pointer+)
765         (oci-handle-alloc (deref-vp envhp) srvhp
766                           +oci-htype-server+ 0 +null-void-pointer-pointer+)
767         (uffi:with-cstring (dblink nil)
768           (oci-server-attach (deref-vp srvhp)
769                              (deref-vp errhp)
770                              dblink
771                              0 +oci-default+))
772         (oci-handle-alloc (deref-vp envhp) svchp
773                           +oci-htype-svcctx+ 0 +null-void-pointer-pointer+)
774         (oci-attr-set (deref-vp svchp)
775                       +oci-htype-svcctx+
776                       (deref-vp srvhp) 0 +oci-attr-server+ 
777                       (deref-vp errhp))
778         ;; oci-handle-alloc((dvoid *)encvhp, (dvoid **)&stmthp, OCI_HTYPE_STMT, 0, 0);
779         ;;#+nil
780         )
781       (let (db server-version)
782         (uffi:with-foreign-object (buf '(:array :unsigned-char #.+errbuf-len+))
783           (oci-server-version (deref-vp svchp)
784                               (deref-vp errhp)
785                               (uffi:char-array-to-pointer buf)
786                               +errbuf-len+ +oci-htype-svcctx+)
787           (setf server-version (uffi:convert-from-foreign-string buf)))
788         (setq db (make-instance 'oracle-database
789                                 :name (database-name-from-spec connection-spec
790                                                                database-type)
791                                 :envhp envhp
792                                 :errhp errhp
793                                 :database-type :oracle
794                                 :svchp svchp
795                                 :dsn data-source-name
796                                 :user user
797                                 :server-version server-version
798                                 :major-version-number (major-version-from-string
799                                                        server-version)))
800
801         (oci-logon (deref-vp envhp)
802                    (deref-vp errhp) 
803                    svchp
804                    (uffi:convert-to-cstring user) (length user)
805                    (uffi:convert-to-cstring password) (length password)
806                    (uffi:convert-to-cstring data-source-name) (length data-source-name)
807                    :database db)
808         ;; :date-format-length (1+ (length date-format)))))
809         (setf (slot-value db 'clsql-sys::state) :open)
810         (database-execute-command
811          (format nil "alter session set NLS_DATE_FORMAT='~A'" (date-format db)) db)
812         db))))
813
814
815 (defun major-version-from-string (str)
816   (cond 
817     ((search " 10g " str)
818      10)
819     ((search "Oracle9i  " str)
820      10)))
821
822
823 ;; Close a database connection.
824
825 (defmethod database-disconnect ((database oracle-database))
826   (osucc (oci-logoff (deref-vp (svchp database))
827                      (deref-vp (errhp database))))
828   (osucc (oci-handle-free (deref-vp (envhp database)) +oci-htype-env+))
829   ;; Note: It's neither required nor allowed to explicitly deallocate the
830   ;; ERRHP handle here, since it's owned by the ENVHP deallocated above,
831   ;; and was therefore automatically deallocated at the same time.
832   t)
833
834 ;;; Do the database operation described in SQL-STMT-STRING on database
835 ;;; DB and, if the command is a SELECT, return a representation of the
836 ;;; resulting table. The representation of the table is controlled by the
837 ;;; QUERY argument:
838 ;;;   * If QUERY is NIL, the table is returned as a list of rows, with
839 ;;;     each row represented by a list.
840 ;;;   * If QUERY is non-NIL, the result is returned as a QUERY-CURSOR
841 ;;;     suitable for FETCH-ROW and CLOSE-QUERY
842 ;;; The TYPES argument controls the type conversion method used
843 ;;; to construct the table. The Allegro version supports several possible
844 ;;; values for this argument, but we only support :AUTO.
845
846 (defmethod database-query (query-expression (database oracle-database) result-types field-names)
847   (let ((cursor (sql-stmt-exec query-expression database result-types field-names)))
848     ;; (declare (type (or query-cursor null) cursor))
849     (if (null cursor) ; No table was returned.
850         (values)
851       (do ((reversed-result nil))
852           (nil)
853         (let* ((eof-value :eof)
854                (row (fetch-row cursor nil eof-value)))
855           (when (eq row eof-value)
856             (close-query cursor)
857             (if field-names
858                 (return (values (nreverse reversed-result)
859                                 (loop for cd across (qc-cds cursor)
860                                     collect (cd-name cd))))
861               (return (nreverse reversed-result))))
862           (push row reversed-result))))))
863
864
865 (defmethod database-create-sequence
866   (sequence-name (database oracle-database))
867   (execute-command
868    (concatenate 'string "CREATE SEQUENCE "
869                 (sql-escape sequence-name))
870    :database database))
871
872 (defmethod database-drop-sequence
873   (sequence-name (database oracle-database))
874   (execute-command
875    (concatenate 'string "DROP SEQUENCE "
876                 (sql-escape sequence-name))
877    :database database))
878
879 (defmethod database-sequence-next (sequence-name (database oracle-database))
880   (caar
881    (database-query
882     (concatenate 'string "SELECT "
883                  (sql-escape sequence-name)
884                  ".NEXTVAL FROM dual"
885                  )
886     database :auto nil)))
887
888 (defmethod database-set-sequence-position (name position database)
889   (let* ((next (database-sequence-next name database))
890          (incr (- position next)))
891     (database-execute-command
892      (format nil "ALTER SEQUENCE ~A INCREMENT BY ~D" name incr)
893      database)
894     (database-sequence-next name database)
895     (database-execute-command
896      (format nil "ALTER SEQUENCE ~A INCREMENT BY 1" name)
897      database)))
898
899 (defmethod database-list-sequences ((database oracle-database) &key owner)
900   (let ((query
901          (if owner
902              (format nil
903                      "select user_sequences.sequence_name from user_sequences,all_sequences where user_sequences.sequence_name=all_sequences.sequence_name and all_sequences.sequence_owner='~:@(~A~)'"
904                      owner)
905              "select sequence_name from user_sequences")))
906     (mapcar #'car (database-query query database nil nil))))
907
908 (defmethod database-execute-command (sql-expression (database oracle-database))
909   (database-query sql-expression database nil nil)
910   ;; HACK HACK HACK
911   (database-query "commit" database nil nil)
912   t)
913
914
915 (defstruct (cd (:constructor make-cd)
916                (:print-function print-cd))
917   "a column descriptor: metadata about the data in a table"
918
919   ;; name of this column
920   (name (error "missing NAME") :type simple-string :read-only t)
921   ;; the size in bytes of a single element
922   (sizeof (error "missing SIZE") :type fixnum :read-only t)
923   ;; an array of +N-BUF-ROWS+ elements in C representation
924   (buffer (error "Missing BUFFER")
925           :type foreign-resource
926           :read-only t)
927   ;; an array of +N-BUF-ROWS+ OCI return codes in C representation.
928   ;; (There must be one return code for every element of every
929   ;; row in order to be able to represent nullness.)
930   (retcodes (error "Missing RETCODES")
931             :type foreign-resource
932             :read-only t)
933   (indicators (error "Missing INDICATORS")
934               :type foreign-resource
935               :read-only t)
936   ;; the OCI code for the data type of a single element
937   (oci-data-type (error "missing OCI-DATA-TYPE")
938                  :type fixnum
939                  :read-only t)
940   (result-type (error "missing RESULT-TYPE")
941                :read-only t))
942
943
944 (defun print-cd (cd stream depth)
945   (declare (ignore depth))
946   (print-unreadable-object (cd stream :type t)
947     (format stream
948             ":NAME ~S :OCI-DATA-TYPE ~S :OCI-DATA-SIZE ~S"
949             (cd-name cd)
950             (cd-oci-data-type cd)
951             (cd-sizeof cd))))
952
953 (defun print-query-cursor (qc stream depth)
954   (declare (ignore depth))
955   (print-unreadable-object (qc stream :type t :identity t)
956     (prin1 (qc-db qc) stream)))
957
958
959 (defmethod database-query-result-set ((query-expression string)
960                                       (database oracle-database) 
961                                       &key full-set result-types)
962   (let ((cursor (sql-stmt-exec query-expression database result-types nil)))
963     (if full-set
964         (values cursor (length (qc-cds cursor)) nil)
965         (values cursor (length (qc-cds cursor))))))
966
967
968 (defmethod database-dump-result-set (result-set (database oracle-database))
969   (close-query result-set)) 
970
971 (defmethod database-store-next-row (result-set (database oracle-database) list)
972   (let* ((eof-value :eof)
973          (row (fetch-row result-set nil eof-value)))
974     (unless (eq eof-value row)
975       (loop for i from 0 below (length row)
976           do (setf (nth i list) (nth i row)))
977       list)))
978
979 (defmethod clsql-sys:database-start-transaction ((database oracle-database))
980   (call-next-method))
981
982 ;;(with-slots (svchp errhp) database
983 ;;    (osucc (oci-trans-start (uffi:deref-pointer svchp)
984 ;;                          (uffi:deref-pointer errhp)
985 ;;                          60
986 ;;                          +oci-trans-new+)))
987 ;;  t)
988   
989
990 (defmethod clsql-sys:database-commit-transaction ((database oracle-database))
991   (call-next-method)
992   (with-slots (svchp errhp) database
993               (osucc (oci-trans-commit (deref-vp svchp)
994                                        (deref-vp errhp)
995                                        0)))
996   t)
997
998 (defmethod clsql-sys:database-abort-transaction ((database oracle-database))
999   (call-next-method)
1000   (osucc (oci-trans-rollback (deref-vp (svchp database))
1001                              (deref-vp (errhp database))
1002                              0))
1003   t)
1004
1005 (defparameter *constraint-types*
1006   '(("NOT-NULL" . "NOT NULL")))
1007
1008 (defmethod database-output-sql ((str string) (database oracle-database))
1009   (if (and (null (position #\' str))
1010            (null (position #\\ str)))
1011       (format nil "'~A'" str)
1012     (let* ((l (length str))
1013            (buf (make-string (+ l 3))))
1014       (setf (aref buf 0) #\')
1015       (do ((i 0 (incf i))
1016            (j 1 (incf j)))
1017           ((= i l) (setf (aref buf j) #\'))
1018         (if (= j (- (length buf) 1))
1019             (setf buf (adjust-array buf (+ (length buf) 1))))
1020         (cond ((eql (aref str i) #\')
1021                (setf (aref buf j) #\')
1022                (incf j)))
1023         (setf (aref buf j) (aref str i)))
1024       buf)))
1025
1026
1027 ;; Specifications
1028
1029 (defmethod db-type-has-bigint? ((type (eql :oracle)))
1030   nil)
1031
1032 (defmethod db-type-has-fancy-math? ((db-type (eql :oracle)))
1033   t)
1034
1035 (defmethod db-type-has-boolean-where? ((db-type (eql :oracle)))
1036   nil)
1037
1038 (when (clsql-sys:database-type-library-loaded :oracle)
1039   (clsql-sys:initialize-database-type :database-type :oracle))