1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
5 ;;;; Name: oracle-sql.lisp
9 ;;;; This file is part of CLSQL.
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 ;;;; *************************************************************************
16 (in-package #:clsql-oracle)
18 (defmethod database-initialize-database-type ((database-type (eql :oracle)))
21 ;;;; arbitrary parameters, tunable for performance or other reasons
23 (eval-when (:compile-toplevel :load-toplevel :execute)
24 (defconstant +errbuf-len+ 512
25 "the number of characters that we allocate for an error message buffer")
26 (defconstant +n-buf-rows+ 200
27 "the number of table rows that we buffer at once when reading a table.
28 CMUCL has a compiled-in limit on how much C data can be allocated
29 (through malloc() and friends) at any given time, typically 8 Mb.
30 Setting this constant to a moderate value should make it less
31 likely that we'll have to worry about the CMUCL limit."))
34 (defmacro deref-vp (foreign-object)
35 `(uffi:deref-pointer ,foreign-object :pointer-void))
37 ;; constants - from OCI?
39 (defvar +unsigned-char-null-pointer+
40 (uffi:make-null-pointer :unsigned-char))
41 (defvar +unsigned-short-null-pointer+
42 (uffi:make-null-pointer :unsigned-short))
43 (defvar +unsigned-int-null-pointer+
44 (uffi:make-null-pointer :unsigned-int))
46 (defconstant +var-not-in-list+ 1007)
47 (defconstant +no-data-found+ 1403)
48 (defconstant +null-value-returned+ 1405)
49 (defconstant +field-truncated+ 1406)
51 (eval-when (:compile-toplevel :load-toplevel :execute)
52 (defconstant SQLT-NUMBER 2)
53 (defconstant SQLT-INT 3)
54 (defconstant SQLT-STR 5)
55 (defconstant SQLT-FLT 4)
56 (defconstant SQLT-DATE 12))
58 ;;; Note that despite the suggestive class name (and the way that the
59 ;;; *DEFAULT-DATABASE* variable holds an object of this class), a DB
60 ;;; object is not actually a database but is instead a connection to a
61 ;;; database. Thus, there's no obstacle to having any number of DB
62 ;;; objects referring to the same database.
64 (uffi:def-type pointer-pointer-void '(* :pointer-void))
66 (defclass oracle-database (database) ; was struct db
70 :type pointer-pointer-void
72 "OCI environment handle")
76 :type pointer-pointer-void
82 :type pointer-pointer-void
84 "OCI service context handle")
89 "optional data source name (used only for debugging/printing)")
95 "the \"user\" value given when data source connection was made")
99 :initform "YYYY-MM-DD HH24:MI:SS\"+00\"")
103 "Each database connection can be configured with its own date
104 output format. In order to extract date strings from output buffers
105 holding multiple date strings in fixed-width fields, we need to know
106 the length of that format.")
109 :initarg :server-version
110 :reader server-version
112 "Version string of Oracle server.")
113 (major-server-version
114 :type (or null fixnum)
115 :initarg :major-server-version
116 :reader major-server-version
118 "The major version number of the Oracle server, should be 8, 9, or 10")
121 :initarg :client-version
122 :reader client-version
124 "Version string of Oracle client.")
125 (major-client-version
126 :type (or null fixnum)
127 :initarg :major-client-version
128 :reader major-client-version
130 "The major version number of the Oracle client, should be 8, 9, or 10")))
133 ;;; Handle the messy case of return code=+oci-error+, querying the
134 ;;; system for subcodes and reporting them as appropriate. ERRHP and
135 ;;; NULLS-OK are as in the OERR function.
137 (defun handle-oci-error (&key database nulls-ok)
141 (uffi:with-foreign-objects ((errbuf '(:array :unsigned-char
144 ;; ensure errbuf empty string
145 (setf (uffi:deref-array errbuf '(:array :unsigned-char) 0)
146 (uffi:ensure-char-storable (code-char 0)))
148 (setf (uffi:deref-pointer errcode :long) 0)
149 (uffi:with-cstring (sqlstate nil)
150 (oci-error-get (deref-vp errhp) 1
153 (uffi:char-array-to-pointer errbuf)
154 +errbuf-len+ +oci-htype-error+))
155 (let ((subcode (uffi:deref-pointer errcode :long)))
156 (unless (and nulls-ok (= subcode +null-value-returned+))
157 (error 'sql-database-error
160 :message (uffi:convert-from-foreign-string errbuf)))))))
162 (error 'sql-database-error
164 :message "can't handle NULLS-OK without ERRHP"))
166 (error 'sql-database-error
168 :message "OCI Error (and no ERRHP available to find subcode)"))))
170 ;;; Require an OCI success code.
172 ;;; (The ordinary OCI error reporting mechanisms uses a fair amount of
173 ;;; machinery (environments and other handles). In order to get to
174 ;;; where we can use these mechanisms, we have to be able to allocate
175 ;;; the machinery. The functions for allocating the machinery can
176 ;;; return errors (e.g. out of memory) but shouldn't. Wrapping this function
177 ;;; around function calls to such have-to-succeed functions enforces
181 (declare (type fixnum code))
182 (unless (= code +oci-success+)
183 (error 'sql-database-error
184 :message (format nil "unexpected OCI failure, code=~S" code))))
187 ;;; Enabling this can be handy for low-level debugging.
190 (trace oci-initialize #+oci-8-1-5 oci-env-create oci-handle-alloc oci-logon
191 oci-error-get oci-stmt-prepare oci-stmt-execute
192 oci-param-get oci-logon oci-attr-get oci-define-by-pos oci-stmt-fetch)
193 (setf debug::*debug-print-length* nil))
196 ;;;; the OCI library, part V: converting from OCI representations to Lisp
199 ;; Return the INDEXth string of the OCI array, represented as Lisp
200 ;; SIMPLE-STRING. SIZE is the size of the fixed-width fields used by
201 ;; Oracle to store strings within the array.
203 ;; In the wild world of databases, trailing spaces aren't generally
204 ;; significant, since e.g. "LARRY " and "LARRY " are the same string
205 ;; stored in different fixed-width fields. OCI drops trailing spaces
206 ;; for us in some cases but apparently not for fields of fixed
207 ;; character width, e.g.
209 ;; (dbi:sql "create table employees (name char(15), job char(15), city
210 ;; char(15), rate float)" :db orcl :types :auto)
211 ;; In order to map the "same string" property above onto Lisp equality,
212 ;; we drop trailing spaces in all cases:
214 (uffi:def-type string-pointer (* :unsigned-char))
216 (defun deref-oci-string (arrayptr string-index size)
217 (declare (type string-pointer arrayptr))
218 (declare (type (mod #.+n-buf-rows+) string-index))
219 (declare (type (and unsigned-byte fixnum) size))
220 (let* ((raw (uffi:convert-from-foreign-string
222 (+ (uffi:pointer-address arrayptr) (* string-index size))
224 (trimmed (string-trim " " raw)))
225 (if (equal trimmed "NULL") nil trimmed)))
227 ;; the OCI library, part Z: no-longer used logic to convert from
228 ;; Oracle's binary date representation to Common Lisp's native date
232 (defvar +oci-date-bytes+ 7)
234 ;;; Return the INDEXth date in the OCI array, represented as
235 ;;; a Common Lisp "universal time" (i.e. seconds since 1900).
238 (defun deref-oci-date (arrayptr index)
239 (oci-date->universal-time (uffi:pointer-address
240 (uffi:deref-array arrayptr
241 '(:array :unsigned-char)
242 (* index +oci-date-bytes+)))))
244 (defun oci-date->universal-time (oci-date)
245 (declare (type (alien (* :unsigned-char)) oci-date))
246 (flet (;; a character from OCI-DATE, interpreted as an unsigned byte
248 (declare (type (mod #.+oci-date-bytes+) i))
249 (mod (uffi:deref-array oci-date string-array i) 256)))
250 (let* ((century (* (- (ub 0) 100) 100))
251 (year (+ century (- (ub 1) 100)))
256 (second (1- (ub 6))))
257 (encode-universal-time second minute hour day month year))))
260 (defmethod database-list-tables ((database oracle-database) &key owner)
264 "select user_tables.table_name from user_tables,all_tables where user_tables.table_name=all_tables.table_name and all_tables.owner='~:@(~A~)'"
266 "select table_name from user_tables")))
267 (mapcar #'car (database-query query database nil nil))))
270 (defmethod database-list-views ((database oracle-database) &key owner)
274 "select user_views.view_name from user_views,all_views where user_views.view_name=all_views.view_name and all_views.owner='~:@(~A~)'"
276 "select view_name from user_views")))
278 (database-query query database nil nil))))
280 (defmethod database-list-indexes ((database oracle-database)
285 "select user_indexes.index_name from user_indexes,all_indexes where user_indexes.index_name=all_indexes.index_name and all_indexes.owner='~:@(~A~)'"
287 "select index_name from user_indexes")))
288 (mapcar #'car (database-query query database nil nil))))
290 (defmethod database-list-table-indexes (table (database oracle-database)
295 "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~)'"
297 (format nil "select index_name from user_indexes where table_name='~A'"
299 (mapcar #'car (database-query query database nil nil))))
301 (defmethod list-all-table-columns (table (db oracle-database))
302 (declare (string table))
303 (let* ((sql-stmt (concatenate
309 "user_tab_columns.COLUMN_NAME,"
310 "user_tab_columns.DATA_TYPE from user_tab_columns,"
311 "all_tables where all_tables.table_name = '" table "'"
312 " and user_tab_columns.table_name = '" table "'"))
313 (preresult (database-query sql-stmt db :auto nil)))
314 ;; PRERESULT is like RESULT except that it has a name instead of
315 ;; type codes in the fifth column of each row. To fix this, we
316 ;; destructively modify PRERESULT.
317 (dolist (preresult-row preresult)
318 (setf (fifth preresult-row)
319 (if (find (fifth preresult-row)
326 (defmethod database-list-attributes (table (database oracle-database) &key owner)
330 "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~)'"
333 "select column_name from user_tab_columns where table_name='~A'"
335 (mapcar #'car (database-query query database nil nil))))
337 (defmethod database-attribute-type (attribute (table string)
338 (database oracle-database)
343 "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~)'"
344 table attribute owner)
346 "select data_type,data_length,data_scale,nullable from user_tab_columns where table_name='~A' and column_name='~A'"
348 (destructuring-bind (type length scale nullable) (car (database-query query database :auto nil))
349 (values (ensure-keyword type) length scale
350 (if (char-equal #\Y (schar nullable 0)) 1 0)))))
352 ;; Return one row of the table referred to by QC, represented as a
353 ;; list; or if there are no more rows, signal an error if EOF-ERRORP,
354 ;; or return EOF-VALUE otherwise.
356 ;; KLUDGE: This CASE statement is a strong sign that the code would be
357 ;; cleaner if CD were made into an abstract class, we made variant
358 ;; classes for CD-for-column-of-strings, CD-for-column-of-floats,
359 ;; etc., and defined virtual functions to handle operations like
360 ;; get-an-element-from-column. (For a small special purpose module
361 ;; like this, would arguably be overkill, so I'm not going to do it
362 ;; now, but if this code ends up getting more complicated in
363 ;; maintenance, it would become a really good idea.)
365 ;; Arguably this would be a good place to signal END-OF-FILE, but
366 ;; since the ANSI spec specifically says that END-OF-FILE means a
367 ;; STREAM which has no more data, and QC is not a STREAM, we signal
368 ;; DBI-ERROR instead.
370 (uffi:def-type short-array '(:array :short))
371 (uffi:def-type int-pointer '(* :int))
372 (uffi:def-type double-pointer '(* :double))
374 ;;; the result of a database query: a cursor through a table
375 (defstruct (oracle-result-set (:print-function print-query-cursor)
377 (:constructor %make-query-cursor))
378 (db (error "missing DB") ; db conn. this table is associated with
379 :type oracle-database
381 (stmthp (error "missing STMTHP") ; the statement handle used to create
382 ;; :type alien ; this table. owned by the QUERY-CURSOR
383 :read-only t) ; object, deallocated on CLOSE-QUERY
384 (cds) ; (error "missing CDS") ; column descriptors
385 ; :type (simple-array cd 1)
388 0 ; buffered rows: number of rows recv'd
389 :type (integer 0 #.+n-buf-rows+)) ; from the database on the last read
391 0 ; number of buffered rows returned, i.e.
392 :type (integer 0 #.+n-buf-rows+)) ; the index, within the buffered rows,
393 ; of the next row which hasn't already
396 0 ; total number of bytes recv'd from OCI
397 :type unsigned-byte) ; in all reads
398 (oci-end-seen-p nil)) ; Have we seen the end of OCI
399 ; data, i.e. OCI returning
400 ; less data than we requested?
401 ; OCI doesn't seem to like us
402 ; to try to read more data
403 ; from it after that..
406 (defun fetch-row (qc &optional (eof-errorp t) eof-value)
407 ;;(declare (optimize (speed 3)))
408 (cond ((zerop (qc-n-from-oci qc))
410 (error 'sql-database-error :message
411 (format nil "no more rows available in ~S" qc))
413 ((>= (qc-n-to-dbi qc)
415 (refill-qc-buffers qc)
416 (fetch-row qc nil eof-value))
418 (let ((cds (qc-cds qc))
419 (reversed-result nil)
420 (irow (qc-n-to-dbi qc)))
421 (dotimes (icd (length cds))
422 (let* ((cd (aref cds icd))
423 (b (foreign-resource-buffer (cd-buffer cd)))
425 (let* ((arb (foreign-resource-buffer (cd-indicators cd)))
426 (indicator (uffi:deref-array arb '(:array :short) irow)))
427 ;;(declare (type short-array arb))
428 (unless (= indicator -1)
429 (ecase (cd-oci-data-type cd)
431 (deref-oci-string b irow (cd-sizeof cd)))
433 (uffi:deref-array b '(:array :double) irow))
435 (uffi:deref-array b '(:array :int) irow))
437 (deref-oci-string b irow (cd-sizeof cd))))))))
438 (when (and (eq :string (cd-result-type cd))
440 (not (stringp value)))
441 (setq value (write-to-string value)))
442 (push value reversed-result)))
443 (incf (qc-n-to-dbi qc))
444 (nreverse reversed-result)))))
446 (defun refill-qc-buffers (qc)
447 (with-slots (errhp) (qc-db qc)
448 (setf (qc-n-to-dbi qc) 0)
449 (cond ((qc-oci-end-seen-p qc)
450 (setf (qc-n-from-oci qc) 0))
452 (let ((oci-code (%oci-stmt-fetch
453 (deref-vp (qc-stmthp qc))
456 +oci-fetch-next+ +oci-default+)))
458 (#.+oci-success+ (values))
459 (#.+oci-no-data+ (setf (qc-oci-end-seen-p qc) t)
461 (#.+oci-error+ (handle-oci-error :database (qc-db qc)
463 (uffi:with-foreign-object (rowcount :long)
464 (oci-attr-get (deref-vp (qc-stmthp qc))
467 +unsigned-int-null-pointer+
470 (setf (qc-n-from-oci qc)
471 (- (uffi:deref-pointer rowcount :long)
472 (qc-total-n-from-oci qc)))
473 (when (< (qc-n-from-oci qc) +n-buf-rows+)
474 (setf (qc-oci-end-seen-p qc) t))
475 (setf (qc-total-n-from-oci qc)
476 (uffi:deref-pointer rowcount :long)))))
479 ;; the guts of the SQL function
481 ;; (like the SQL function, but with the QUERY argument hardwired to T, so
482 ;; that the return value is always a cursor instead of a list)
484 ;; Is this a SELECT statement? SELECT statements are handled
485 ;; specially by OCIStmtExecute(). (Non-SELECT statements absolutely
486 ;; require a nonzero iteration count, while the ordinary choice for a
487 ;; SELECT statement is a zero iteration count.
489 ;; SELECT statements are the only statements which return tables. We
490 ;; don't free STMTHP in this case, but instead give it to the new
491 ;; QUERY-CURSOR, and the new QUERY-CURSOR becomes responsible for
492 ;; freeing the STMTHP when it is no longer needed.
494 (defun sql-stmt-exec (sql-stmt-string db result-types field-names)
495 (with-slots (envhp svchp errhp)
497 (let ((stmthp (uffi:allocate-foreign-object :pointer-void)))
498 (uffi:with-foreign-object (stmttype :unsigned-short)
500 (oci-handle-alloc (deref-vp envhp)
502 +oci-htype-stmt+ 0 +null-void-pointer-pointer+)
503 (oci-stmt-prepare (deref-vp stmthp)
505 (uffi:convert-to-cstring sql-stmt-string)
506 (length sql-stmt-string)
507 +oci-ntv-syntax+ +oci-default+ :database db)
508 (oci-attr-get (deref-vp stmthp)
511 +unsigned-int-null-pointer+
515 (let* ((select-p (= (uffi:deref-pointer stmttype :unsigned-short) 1))
516 (iters (if select-p 0 1)))
518 (oci-stmt-execute (deref-vp svchp)
521 iters 0 +null-void-pointer+ +null-void-pointer+ +oci-default+
524 (make-query-cursor db stmthp result-types field-names))
526 (oci-handle-free (deref-vp stmthp) +oci-htype-stmt+)
530 ;; Return a QUERY-CURSOR representing the table returned from the OCI
531 ;; operation done through STMTHP. TYPES is the argument of the same
532 ;; name from the external SQL function, controlling type conversion
533 ;; of the returned arguments.
535 (defun make-query-cursor (db stmthp result-types field-names)
536 (let ((qc (%make-query-cursor :db db
538 :cds (make-query-cursor-cds db stmthp
541 (refill-qc-buffers qc)
545 ;; the hairy part of MAKE-QUERY-CURSOR: Ask OCI for information
546 ;; about table columns, translate the information into a Lisp
547 ;; vector of column descriptors, and return it.
549 ;; Allegro defines several flavors of type conversion, but this
550 ;; implementation only supports the :AUTO flavor.
552 ;; A note of explanation: OCI's internal number format uses 21
553 ;; bytes (42 decimal digits). 2 separate (?) one-byte fields,
554 ;; scale and precision, are used to deduce the nature of these
555 ;; 21 bytes. See pp. 3-10, 3-26, and 6-13 of OCI documentation
558 ;; When calling OCI C code to handle the conversion, we have
559 ;; only two numeric types available to pass the return value:
560 ;; double-float and signed-long. It would be possible to
561 ;; bypass the OCI conversion functions and write Lisp code
562 ;; which reads the 21-byte field directly and decodes
563 ;; it. However this is left as an exercise for the reader. :-)
565 ;; The following table describes the mapping, based on the implicit
566 ;; assumption that C's "signed long" type is a 32-bit integer.
568 ;; Internal Values SQL Type C Return Type
569 ;; =============== ======== =============
570 ;; Precision > 0 SCALE = -127 FLOAT --> double-float
571 ;; Precision > 0 && <=9 SCALE = 0 INTEGER --> signed-long
572 ;; Precision = 0 || > 9 SCALE = 0 BIG INTEGER --> double-float
573 ;; Precision > 0 SCALE > 0 DECIMAL --> double-float
575 ;; (OCI uses 1-based indexing here.)
577 ;; KLUDGE: This should work for all other data types except those
578 ;; which don't actually fit in their fixed-width field (BLOBs and the
579 ;; like). As Winton says, we (Cadabra) don't need to worry much about
580 ;; those, since we can't reason with them, so we don't use them. But
581 ;; for a more general application it'd be good to have a more
582 ;; selective and rigorously correct test here for whether we can
583 ;; actually handle the given DEREF-DTYPE value. -- WHN 20000106
585 ;; Note: The OCI documentation doesn't seem to say whether the COLNAME
586 ;; value returned here is a newly-allocated copy which we're
587 ;; responsible for freeing, or a pointer into some system copy which
588 ;; will be freed when the system itself is shut down. But judging
589 ;; from the way that the result is used in the cdemodsa.c example
590 ;; program, it looks like the latter: we should make our own copy of
591 ;; the value, but not try to free it.
593 ;; WORKAROUND: OCI seems to return ub2 values for the
594 ;; +oci-attr-data-size+ attribute even though its documentation claims
595 ;; that it returns a ub4, and even though the associated "sizep" value
596 ;; is 4, not 2. In order to make the code here work reliably, without
597 ;; having to patch it later if OCI is ever fixed to match its
598 ;; documentation, we pre-zero COLSIZE before making the call into OCI.
600 ;; To exercise the weird OCI behavior (thereby blowing up the code
601 ;; below, beware!) try setting this value into COLSIZE, calling OCI,
602 ;; then looking at the value in COLSIZE. (setf colsize #x12345678)
606 (defun make-query-cursor-cds (database stmthp result-types field-names)
607 (declare (optimize (safety 3) #+nil (speed 3))
608 (type oracle-database database)
609 (type pointer-pointer-void stmthp))
610 (with-slots (errhp) database
611 (uffi:with-foreign-objects ((dtype-foreign :unsigned-short)
612 (parmdp ':pointer-void)
615 (colname '(* :unsigned-char))
616 (colnamelen :unsigned-long)
617 (colsize :unsigned-long)
618 (colsizesize :unsigned-long)
619 (defnp ':pointer-void))
622 (do ((icolumn 0 (1+ icolumn))
623 (cds-as-reversed-list nil))
624 ((not (eql (oci-param-get (deref-vp stmthp)
628 (1+ icolumn) :database database)
630 (coerce (reverse cds-as-reversed-list) 'simple-vector))
631 ;; Decode type of ICOLUMNth column into a type we're prepared to
633 (oci-attr-get (deref-vp parmdp)
636 +unsigned-int-null-pointer+
639 (let ((dtype (uffi:deref-pointer dtype-foreign :unsigned-short)))
642 (setf buffer (acquire-foreign-resource :unsigned-char
643 (* 32 +n-buf-rows+)))
644 (setf sizeof 32 dtype #.SQLT-STR))
646 (oci-attr-get (deref-vp parmdp)
649 +unsigned-int-null-pointer+
652 (oci-attr-get (deref-vp parmdp)
655 +unsigned-int-null-pointer+
658 (let ((*scale (uffi:deref-pointer scale :byte))
659 (*precision (uffi:deref-pointer precision :byte)))
660 ;;(format t "scale=~d, precision=~d~%" *scale *precision)
663 (and (minusp *scale) (< *precision 10)))
664 (setf buffer (acquire-foreign-resource :int +n-buf-rows+)
665 sizeof 4 ;; sizeof(int)
668 (setf buffer (acquire-foreign-resource :double +n-buf-rows+)
669 sizeof 8 ;; sizeof(double)
670 dtype #.SQLT-FLT)))) )
671 ;; Default to SQL-STR
673 (setf (uffi:deref-pointer colsize :unsigned-long) 0
675 (oci-attr-get (deref-vp parmdp)
678 +unsigned-int-null-pointer+
681 (let ((colsize-including-null (1+ (uffi:deref-pointer colsize :unsigned-long))))
682 (setf buffer (acquire-foreign-resource
683 :unsigned-char (* +n-buf-rows+ colsize-including-null)))
684 (setf sizeof colsize-including-null))))
685 (let ((retcodes (acquire-foreign-resource :unsigned-short +n-buf-rows+))
686 (indicators (acquire-foreign-resource :short +n-buf-rows+))
689 (oci-attr-get (deref-vp parmdp)
695 (setq colname-string (uffi:convert-from-foreign-string
696 (uffi:deref-pointer colname '(* :unsigned-char))
697 :length (uffi:deref-pointer colnamelen :unsigned-long))))
698 (push (make-cd :name colname-string
703 :indicators indicators
705 ((consp result-types)
706 (nth icolumn result-types))
711 cds-as-reversed-list)
712 (oci-define-by-pos (deref-vp stmthp)
715 (1+ icolumn) ; OCI 1-based indexing again
716 (foreign-resource-buffer buffer)
719 (foreign-resource-buffer indicators)
720 +unsigned-short-null-pointer+
721 (foreign-resource-buffer retcodes)
722 +oci-default+))))))))
724 ;; Release the resources associated with a QUERY-CURSOR.
726 (defun close-query (qc)
727 (oci-handle-free (deref-vp (qc-stmthp qc)) +oci-htype-stmt+)
728 (let ((cds (qc-cds qc)))
729 (dotimes (i (length cds))
730 (release-cd-resources (aref cds i))))
734 ;; Release the resources associated with a column description.
736 (defun release-cd-resources (cd)
737 (free-foreign-resource (cd-buffer cd))
738 (free-foreign-resource (cd-retcodes cd))
739 (free-foreign-resource (cd-indicators cd))
743 (defmethod database-name-from-spec (connection-spec (database-type (eql :oracle)))
744 (check-connection-spec connection-spec database-type (dsn user password))
745 (destructuring-bind (dsn user password) connection-spec
746 (declare (ignore password))
747 (concatenate 'string dsn "/" user)))
750 (defmethod database-connect (connection-spec (database-type (eql :oracle)))
751 (check-connection-spec connection-spec database-type (dsn user password))
752 (destructuring-bind (data-source-name user password)
754 (let ((envhp (uffi:allocate-foreign-object :pointer-void))
755 (errhp (uffi:allocate-foreign-object :pointer-void))
756 (svchp (uffi:allocate-foreign-object :pointer-void))
757 (srvhp (uffi:allocate-foreign-object :pointer-void)))
758 ;; Requests to allocate environments and handles should never
759 ;; fail in normal operation, and they're done too early to
760 ;; handle errors very gracefully (since they're part of the
761 ;; error-handling mechanism themselves) so we just assert they
763 (setf (deref-vp envhp) +null-void-pointer+)
766 (oci-env-create envhp +oci-default+ +null-void-pointer+
767 +null-void-pointer+ +null-void-pointer+
768 +null-void-pointer+ 0 +null-void-pointer-pointer+)
769 (oci-handle-alloc envhp
772 +null-void-pointer-pointer+))
775 (oci-initialize +oci-object+ +null-void-pointer+ +null-void-pointer+
776 +null-void-pointer+ +null-void-pointer-pointer+)
777 (ignore-errors (oci-handle-alloc +null-void-pointer+ envhp
779 +null-void-pointer-pointer+)) ;no testing return
780 (oci-env-init envhp +oci-default+ 0 +null-void-pointer-pointer+)
781 (oci-handle-alloc (deref-vp envhp) errhp
782 +oci-htype-error+ 0 +null-void-pointer-pointer+)
783 (oci-handle-alloc (deref-vp envhp) srvhp
784 +oci-htype-server+ 0 +null-void-pointer-pointer+)
785 (uffi:with-cstring (dblink nil)
786 (oci-server-attach (deref-vp srvhp)
790 (oci-handle-alloc (deref-vp envhp) svchp
791 +oci-htype-svcctx+ 0 +null-void-pointer-pointer+)
792 (oci-attr-set (deref-vp svchp)
794 (deref-vp srvhp) 0 +oci-attr-server+
796 ;; oci-handle-alloc((dvoid *)encvhp, (dvoid **)&stmthp, OCI_HTYPE_STMT, 0, 0);
799 ;; Actually, oci-server-version returns the client version, not the server versions
800 ;; will use "SELECT VERSION FROM V$INSTANCE" to get actual server version.
801 (let (db server-version client-version)
802 (declare (ignorable server-version))
803 (uffi:with-foreign-object (buf '(:array :unsigned-char #.+errbuf-len+))
804 (oci-server-version (deref-vp svchp)
806 (uffi:char-array-to-pointer buf)
807 +errbuf-len+ +oci-htype-svcctx+)
808 (setf client-version (uffi:convert-from-foreign-string buf))
809 ;; This returns the client version, not the server version, so diable it
811 (oci-server-version (deref-vp srvhp)
813 (uffi:char-array-to-pointer buf)
814 +errbuf-len+ +oci-htype-server+)
816 (setf server-version (uffi:convert-from-foreign-string buf)))
817 (setq db (make-instance 'oracle-database
818 :name (database-name-from-spec connection-spec
820 :connection-spec connection-spec
823 :database-type :oracle
825 :dsn data-source-name
827 :client-version client-version
828 :server-version server-version
829 :major-client-version (major-client-version-from-string
831 :major-server-version (major-client-version-from-string
833 (oci-logon (deref-vp envhp)
836 (uffi:convert-to-cstring user) (length user)
837 (uffi:convert-to-cstring password) (length password)
838 (uffi:convert-to-cstring data-source-name) (length data-source-name)
840 ;; :date-format-length (1+ (length date-format)))))
841 (setf (slot-value db 'clsql-sys::state) :open)
842 (database-execute-command
843 (format nil "ALTER SESSION SET NLS_DATE_FORMAT='~A'" (date-format db)) db)
844 (let ((server-version (caar (database-query "SELECT BANNER FROM V$VERSION WHERE BANNER LIKE '%Oracle%'" db nil nil))))
845 (setf (slot-value db 'server-version) server-version
846 (slot-value db 'major-server-version) (major-client-version-from-string
851 (defun major-client-version-from-string (str)
853 ((search " 10g " str)
855 ((search "Oracle9i " str)
857 ((search "Oracle8" str)
860 (defun major-server-version-from-string (str)
861 (when (> (length str) 2)
863 ((string= "10." (subseq str 0 3))
865 ((string= "9." (subseq str 0 2))
867 ((string= "8." (subseq str 0 2))
871 ;; Close a database connection.
873 (defmethod database-disconnect ((database oracle-database))
874 (osucc (oci-logoff (deref-vp (svchp database))
875 (deref-vp (errhp database))))
876 (osucc (oci-handle-free (deref-vp (envhp database)) +oci-htype-env+))
877 ;; Note: It's neither required nor allowed to explicitly deallocate the
878 ;; ERRHP handle here, since it's owned by the ENVHP deallocated above,
879 ;; and was therefore automatically deallocated at the same time.
882 ;;; Do the database operation described in SQL-STMT-STRING on database
883 ;;; DB and, if the command is a SELECT, return a representation of the
884 ;;; resulting table. The representation of the table is controlled by the
886 ;;; * If QUERY is NIL, the table is returned as a list of rows, with
887 ;;; each row represented by a list.
888 ;;; * If QUERY is non-NIL, the result is returned as a QUERY-CURSOR
889 ;;; suitable for FETCH-ROW and CLOSE-QUERY
890 ;;; The TYPES argument controls the type conversion method used
891 ;;; to construct the table. The Allegro version supports several possible
892 ;;; values for this argument, but we only support :AUTO.
894 (defmethod database-query (query-expression (database oracle-database) result-types field-names)
895 (let ((cursor (sql-stmt-exec query-expression database result-types field-names)))
896 ;; (declare (type (or query-cursor null) cursor))
897 (if (null cursor) ; No table was returned.
899 (do ((reversed-result nil))
901 (let* ((eof-value :eof)
902 (row (fetch-row cursor nil eof-value)))
903 (when (eq row eof-value)
906 (return (values (nreverse reversed-result)
907 (loop for cd across (qc-cds cursor)
908 collect (cd-name cd))))
909 (return (nreverse reversed-result))))
910 (push row reversed-result))))))
913 (defmethod database-create-sequence
914 (sequence-name (database oracle-database))
916 (concatenate 'string "CREATE SEQUENCE "
917 (sql-escape sequence-name))
920 (defmethod database-drop-sequence
921 (sequence-name (database oracle-database))
923 (concatenate 'string "DROP SEQUENCE "
924 (sql-escape sequence-name))
927 (defmethod database-sequence-next (sequence-name (database oracle-database))
930 (concatenate 'string "SELECT "
931 (sql-escape sequence-name)
934 database :auto nil)))
936 (defmethod database-set-sequence-position (name position database)
937 (let* ((next (database-sequence-next name database))
938 (incr (- position next)))
939 (database-execute-command
940 (format nil "ALTER SEQUENCE ~A INCREMENT BY ~D" name incr)
942 (database-sequence-next name database)
943 (database-execute-command
944 (format nil "ALTER SEQUENCE ~A INCREMENT BY 1" name)
947 (defmethod database-list-sequences ((database oracle-database) &key owner)
951 "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~)'"
953 "select sequence_name from user_sequences")))
954 (mapcar #'car (database-query query database nil nil))))
956 (defmethod database-execute-command (sql-expression (database oracle-database))
957 (database-query sql-expression database nil nil)
959 (database-query "commit" database nil nil)
963 (defstruct (cd (:constructor make-cd)
964 (:print-function print-cd))
965 "a column descriptor: metadata about the data in a table"
967 ;; name of this column
968 (name (error "missing NAME") :type simple-string :read-only t)
969 ;; the size in bytes of a single element
970 (sizeof (error "missing SIZE") :type fixnum :read-only t)
971 ;; an array of +N-BUF-ROWS+ elements in C representation
972 (buffer (error "Missing BUFFER")
973 :type foreign-resource
975 ;; an array of +N-BUF-ROWS+ OCI return codes in C representation.
976 ;; (There must be one return code for every element of every
977 ;; row in order to be able to represent nullness.)
978 (retcodes (error "Missing RETCODES")
979 :type foreign-resource
981 (indicators (error "Missing INDICATORS")
982 :type foreign-resource
984 ;; the OCI code for the data type of a single element
985 (oci-data-type (error "missing OCI-DATA-TYPE")
988 (result-type (error "missing RESULT-TYPE")
992 (defun print-cd (cd stream depth)
993 (declare (ignore depth))
994 (print-unreadable-object (cd stream :type t)
996 ":NAME ~S :OCI-DATA-TYPE ~S :OCI-DATA-SIZE ~S"
998 (cd-oci-data-type cd)
1001 (defun print-query-cursor (qc stream depth)
1002 (declare (ignore depth))
1003 (print-unreadable-object (qc stream :type t :identity t)
1004 (prin1 (qc-db qc) stream)))
1007 (defmethod database-query-result-set ((query-expression string)
1008 (database oracle-database)
1009 &key full-set result-types)
1010 (let ((cursor (sql-stmt-exec query-expression database result-types nil)))
1012 (values cursor (length (qc-cds cursor)) nil)
1013 (values cursor (length (qc-cds cursor))))))
1016 (defmethod database-dump-result-set (result-set (database oracle-database))
1017 (close-query result-set))
1019 (defmethod database-store-next-row (result-set (database oracle-database) list)
1020 (let* ((eof-value :eof)
1021 (row (fetch-row result-set nil eof-value)))
1022 (unless (eq eof-value row)
1023 (loop for i from 0 below (length row)
1024 do (setf (nth i list) (nth i row)))
1027 (defmethod clsql-sys:database-start-transaction ((database oracle-database))
1030 ;;(with-slots (svchp errhp) database
1031 ;; (osucc (oci-trans-start (uffi:deref-pointer svchp)
1032 ;; (uffi:deref-pointer errhp)
1034 ;; +oci-trans-new+)))
1038 (defmethod clsql-sys:database-commit-transaction ((database oracle-database))
1040 (with-slots (svchp errhp) database
1041 (osucc (oci-trans-commit (deref-vp svchp)
1046 (defmethod clsql-sys:database-abort-transaction ((database oracle-database))
1048 (osucc (oci-trans-rollback (deref-vp (svchp database))
1049 (deref-vp (errhp database))
1053 (defparameter *constraint-types*
1054 '(("NOT-NULL" . "NOT NULL")))
1056 (defmethod database-output-sql ((str string) (database oracle-database))
1057 (if (and (null (position #\' str))
1058 (null (position #\\ str)))
1059 (format nil "'~A'" str)
1060 (let* ((l (length str))
1061 (buf (make-string (+ l 3))))
1062 (setf (aref buf 0) #\')
1065 ((= i l) (setf (aref buf j) #\'))
1066 (if (= j (- (length buf) 1))
1067 (setf buf (adjust-array buf (+ (length buf) 1))))
1068 (cond ((eql (aref str i) #\')
1069 (setf (aref buf j) #\')
1071 (setf (aref buf j) (aref str i)))
1077 (defmethod db-type-has-bigint? ((type (eql :oracle)))
1080 (defmethod db-type-has-fancy-math? ((db-type (eql :oracle)))
1083 (defmethod db-type-has-boolean-where? ((db-type (eql :oracle)))
1086 (when (clsql-sys:database-type-library-loaded :oracle)
1087 (clsql-sys:initialize-database-type :database-type :oracle))