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 (uffi:def-type vp-type :pointer-void)
35 (uffi:def-type vpp-type (* :pointer-void))
37 (defmacro deref-vp (foreign-object)
38 `(the vp-type (uffi:deref-pointer (the vpp-type ,foreign-object) :pointer-void)))
40 (defvar +unsigned-char-null-pointer+
41 (uffi:make-null-pointer :unsigned-char))
42 (defvar +unsigned-short-null-pointer+
43 (uffi:make-null-pointer :unsigned-short))
44 (defvar +unsigned-int-null-pointer+
45 (uffi:make-null-pointer :unsigned-int))
47 ;; constants - from OCI?
49 (defconstant +var-not-in-list+ 1007)
50 (defconstant +no-data-found+ 1403)
51 (defconstant +null-value-returned+ 1405)
52 (defconstant +field-truncated+ 1406)
54 (eval-when (:compile-toplevel :load-toplevel :execute)
55 (defconstant SQLT-NUMBER 2)
56 (defconstant SQLT-INT 3)
57 (defconstant SQLT-FLT 4)
58 (defconstant SQLT-STR 5)
59 (defconstant SQLT-DATE 12))
61 ;;; Note that despite the suggestive class name (and the way that the
62 ;;; *DEFAULT-DATABASE* variable holds an object of this class), a DB
63 ;;; object is not actually a database but is instead a connection to a
64 ;;; database. Thus, there's no obstacle to having any number of DB
65 ;;; objects referring to the same database.
67 (uffi:def-type pointer-pointer-void '(* :pointer-void))
69 (defclass oracle-database (database) ; was struct db
73 :type pointer-pointer-void
75 "OCI environment handle")
79 :type pointer-pointer-void
85 :type pointer-pointer-void
87 "OCI service context handle")
92 "optional data source name (used only for debugging/printing)")
98 "the \"user\" value given when data source connection was made")
100 :initarg :date-format
102 :initform "YYYY-MM-DD HH24:MI:SS\"+00\"")
106 "Each database connection can be configured with its own date
107 output format. In order to extract date strings from output buffers
108 holding multiple date strings in fixed-width fields, we need to know
109 the length of that format.")
111 :type (or null string)
112 :initarg :server-version
113 :reader server-version
115 "Version string of Oracle server.")
116 (major-server-version
117 :type (or null fixnum)
118 :initarg :major-server-version
119 :reader major-server-version
121 "The major version number of the Oracle server, should be 8, 9, or 10")
123 :type (or null string)
124 :initarg :client-version
125 :reader client-version
127 "Version string of Oracle client.")
128 (major-client-version
129 :type (or null fixnum)
130 :initarg :major-client-version
131 :reader major-client-version
133 "The major version number of the Oracle client, should be 8, 9, or 10")))
136 ;;; Handle the messy case of return code=+oci-error+, querying the
137 ;;; system for subcodes and reporting them as appropriate. ERRHP and
138 ;;; NULLS-OK are as in the OERR function.
140 (defun handle-oci-error (&key database nulls-ok)
142 (with-slots (errhp) database
143 (uffi:with-foreign-objects ((errbuf '(:array :unsigned-char
146 ;; ensure errbuf empty string
147 (setf (uffi:deref-array errbuf '(:array :unsigned-char) 0)
148 (uffi:ensure-char-storable (code-char 0)))
149 (setf (uffi:deref-pointer errcode :long) 0)
151 (uffi:with-cstring (sqlstate nil)
152 (oci-error-get (deref-vp errhp) 1
155 (uffi:char-array-to-pointer errbuf)
156 +errbuf-len+ +oci-htype-error+))
157 (let ((subcode (uffi:deref-pointer errcode :long)))
158 (unless (and nulls-ok (= subcode +null-value-returned+))
159 (error 'sql-database-error
162 :message (uffi:convert-from-foreign-string errbuf)))))))
164 (error 'sql-database-error
166 :message "can't handle NULLS-OK without ERRHP"))
168 (error 'sql-database-error
170 :message "OCI Error (and no ERRHP available to find subcode)"))))
172 ;;; Require an OCI success code.
174 ;;; (The ordinary OCI error reporting mechanisms uses a fair amount of
175 ;;; machinery (environments and other handles). In order to get to
176 ;;; where we can use these mechanisms, we have to be able to allocate
177 ;;; the machinery. The functions for allocating the machinery can
178 ;;; return errors (e.g. out of memory) but shouldn't. Wrapping this function
179 ;;; around function calls to such have-to-succeed functions enforces
183 (declare (type fixnum code))
184 (unless (= code +oci-success+)
185 (error 'sql-database-error
186 :message (format nil "unexpected OCI failure, code=~S" code))))
189 ;;; Enabling this can be handy for low-level debugging.
192 (trace #-oci7 oci-env-create oci-initialize oci-handle-alloc oci-logon
193 oci-error-get oci-stmt-prepare oci-stmt-execute
194 oci-param-get oci-logon oci-attr-get oci-define-by-pos oci-stmt-fetch)
195 (setf debug::*debug-print-length* nil))
198 ;; Return the INDEXth string of the OCI array, represented as Lisp
199 ;; SIMPLE-STRING. SIZE is the size of the fixed-width fields used by
200 ;; Oracle to store strings within the array.
202 (uffi:def-type string-pointer (* :unsigned-char))
204 (defun deref-oci-string (arrayptr string-index size)
205 (declare (type string-pointer arrayptr))
206 (declare (type (mod #.+n-buf-rows+) string-index))
207 (declare (type (and unsigned-byte fixnum) size))
208 (let ((str (uffi:convert-from-foreign-string
210 (+ (uffi:pointer-address arrayptr) (* string-index size))
212 (if (string-equal str "NULL") nil str)))
214 ;; the OCI library, part Z: no-longer used logic to convert from
215 ;; Oracle's binary date representation to Common Lisp's native date
219 (defvar +oci-date-bytes+ 7)
221 ;;; Return the INDEXth date in the OCI array, represented as
222 ;;; a Common Lisp "universal time" (i.e. seconds since 1900).
225 (defun deref-oci-date (arrayptr index)
226 (oci-date->universal-time (uffi:pointer-address
227 (uffi:deref-array arrayptr
228 '(:array :unsigned-char)
229 (* index +oci-date-bytes+)))))
231 (defun oci-date->universal-time (oci-date)
232 (declare (type (alien (* :unsigned-char)) oci-date))
233 (flet (;; a character from OCI-DATE, interpreted as an unsigned byte
235 (declare (type (mod #.+oci-date-bytes+) i))
236 (mod (uffi:deref-array oci-date string-array i) 256)))
237 (let* ((century (* (- (ub 0) 100) 100))
238 (year (+ century (- (ub 1) 100)))
243 (second (1- (ub 6))))
244 (encode-universal-time second minute hour day month year))))
247 (defmethod database-list-tables ((database oracle-database) &key owner)
251 "select user_tables.table_name from user_tables,all_tables where user_tables.table_name=all_tables.table_name and all_tables.owner='~:@(~A~)'"
253 "select table_name from user_tables")))
254 (mapcar #'car (database-query query database nil nil))))
257 (defmethod database-list-views ((database oracle-database) &key owner)
261 "select user_views.view_name from user_views,all_views where user_views.view_name=all_views.view_name and all_views.owner='~:@(~A~)'"
263 "select view_name from user_views")))
265 (database-query query database nil nil))))
267 (defmethod database-list-indexes ((database oracle-database)
272 "select user_indexes.index_name from user_indexes,all_indexes where user_indexes.index_name=all_indexes.index_name and all_indexes.owner='~:@(~A~)'"
274 "select index_name from user_indexes")))
275 (mapcar #'car (database-query query database nil nil))))
277 (defmethod database-list-table-indexes (table (database oracle-database)
282 "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~)'"
284 (format nil "select index_name from user_indexes where table_name='~A'"
286 (mapcar #'car (database-query query database nil nil))))
289 (defmethod database-list-attributes (table (database oracle-database) &key owner)
293 "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~)'"
296 "select column_name from user_tab_columns where table_name='~A'"
298 (mapcar #'car (database-query query database nil nil))))
300 (defmethod database-attribute-type (attribute (table string)
301 (database oracle-database)
306 "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~)'"
307 table attribute owner)
309 "select data_type,data_length,data_scale,nullable from user_tab_columns where table_name='~A' and column_name='~A'"
311 (destructuring-bind (type length scale nullable) (car (database-query query database :auto nil))
312 (values (ensure-keyword type) length scale
313 (if (char-equal #\Y (schar nullable 0)) 1 0)))))
315 ;; Return one row of the table referred to by QC, represented as a
316 ;; list; or if there are no more rows, signal an error if EOF-ERRORP,
317 ;; or return EOF-VALUE otherwise.
319 ;; KLUDGE: This CASE statement is a strong sign that the code would be
320 ;; cleaner if CD were made into an abstract class, we made variant
321 ;; classes for CD-for-column-of-strings, CD-for-column-of-floats,
322 ;; etc., and defined virtual functions to handle operations like
323 ;; get-an-element-from-column. (For a small special purpose module
324 ;; like this, would arguably be overkill, so I'm not going to do it
325 ;; now, but if this code ends up getting more complicated in
326 ;; maintenance, it would become a really good idea.)
328 ;; Arguably this would be a good place to signal END-OF-FILE, but
329 ;; since the ANSI spec specifically says that END-OF-FILE means a
330 ;; STREAM which has no more data, and QC is not a STREAM, we signal
331 ;; DBI-ERROR instead.
333 (uffi:def-type short-array '(:array :short))
334 (uffi:def-type int-pointer '(* :int))
335 (uffi:def-type double-pointer '(* :double))
337 ;;; the result of a database query: a cursor through a table
338 (defstruct (oracle-result-set (:print-function print-query-cursor)
340 (:constructor %make-query-cursor))
341 (db (error "missing DB") ; db conn. this table is associated with
342 :type oracle-database
344 (stmthp (error "missing STMTHP") ; the statement handle used to create
345 ;; :type alien ; this table. owned by the QUERY-CURSOR
346 :read-only t) ; object, deallocated on CLOSE-QUERY
347 (cds) ; (error "missing CDS") ; column descriptors
348 ; :type (simple-array cd 1)
351 0 ; buffered rows: number of rows recv'd
352 :type (integer 0 #.+n-buf-rows+)) ; from the database on the last read
354 0 ; number of buffered rows returned, i.e.
355 :type (integer 0 #.+n-buf-rows+)) ; the index, within the buffered rows,
356 ; of the next row which hasn't already
359 0 ; total number of bytes recv'd from OCI
360 :type unsigned-byte) ; in all reads
361 (oci-end-seen-p nil)) ; Have we seen the end of OCI
362 ; data, i.e. OCI returning
363 ; less data than we requested?
364 ; OCI doesn't seem to like us
365 ; to try to read more data
366 ; from it after that..
369 (defun fetch-row (qc &optional (eof-errorp t) eof-value)
370 ;;(declare (optimize (speed 3)))
371 (cond ((zerop (qc-n-from-oci qc))
373 (error 'sql-database-error :message
374 (format nil "no more rows available in ~S" qc))
376 ((>= (qc-n-to-dbi qc)
378 (refill-qc-buffers qc)
379 (fetch-row qc nil eof-value))
381 (let ((cds (qc-cds qc))
382 (reversed-result nil)
383 (irow (qc-n-to-dbi qc)))
384 (dotimes (icd (length cds))
385 (let* ((cd (aref cds icd))
386 (b (foreign-resource-buffer (cd-buffer cd)))
388 (let* ((arb (foreign-resource-buffer (cd-indicators cd)))
389 (indicator (uffi:deref-array arb '(:array :short) irow)))
390 ;;(declare (type short-array arb))
391 (unless (= indicator -1)
392 (ecase (cd-oci-data-type cd)
394 (deref-oci-string b irow (cd-sizeof cd)))
396 (uffi:deref-array b '(:array :double) irow))
398 (ecase (cd-sizeof cd)
400 (uffi:deref-array b '(:array :int) irow))))
402 (deref-oci-string b irow (cd-sizeof cd))))))))
403 (when (and (eq :string (cd-result-type cd))
405 (not (stringp value)))
406 (setq value (write-to-string value)))
407 (push value reversed-result)))
408 (incf (qc-n-to-dbi qc))
409 (nreverse reversed-result)))))
411 (defun refill-qc-buffers (qc)
412 (with-slots (errhp) (qc-db qc)
413 (setf (qc-n-to-dbi qc) 0)
414 (cond ((qc-oci-end-seen-p qc)
415 (setf (qc-n-from-oci qc) 0))
417 (let ((oci-code (%oci-stmt-fetch
418 (deref-vp (qc-stmthp qc))
421 +oci-fetch-next+ +oci-default+)))
423 (#.+oci-success+ (values))
424 (#.+oci-no-data+ (setf (qc-oci-end-seen-p qc) t)
426 (#.+oci-error+ (handle-oci-error :database (qc-db qc)
428 (uffi:with-foreign-object (rowcount :long)
429 (oci-attr-get (deref-vp (qc-stmthp qc))
432 +unsigned-int-null-pointer+
435 (setf (qc-n-from-oci qc)
436 (- (uffi:deref-pointer rowcount :long)
437 (qc-total-n-from-oci qc)))
438 (when (< (qc-n-from-oci qc) +n-buf-rows+)
439 (setf (qc-oci-end-seen-p qc) t))
440 (setf (qc-total-n-from-oci qc)
441 (uffi:deref-pointer rowcount :long)))))
444 ;; the guts of the SQL function
446 ;; (like the SQL function, but with the QUERY argument hardwired to T, so
447 ;; that the return value is always a cursor instead of a list)
449 ;; Is this a SELECT statement? SELECT statements are handled
450 ;; specially by OCIStmtExecute(). (Non-SELECT statements absolutely
451 ;; require a nonzero iteration count, while the ordinary choice for a
452 ;; SELECT statement is a zero iteration count.
454 ;; SELECT statements are the only statements which return tables. We
455 ;; don't free STMTHP in this case, but instead give it to the new
456 ;; QUERY-CURSOR, and the new QUERY-CURSOR becomes responsible for
457 ;; freeing the STMTHP when it is no longer needed.
459 (defun sql-stmt-exec (sql-stmt-string db result-types field-names)
460 (with-slots (envhp svchp errhp)
462 (let ((stmthp (uffi:allocate-foreign-object :pointer-void)))
463 (uffi:with-foreign-object (stmttype :unsigned-short)
465 (oci-handle-alloc (deref-vp envhp)
467 +oci-htype-stmt+ 0 +null-void-pointer-pointer+)
468 (oci-stmt-prepare (deref-vp stmthp)
470 (uffi:convert-to-cstring sql-stmt-string)
471 (length sql-stmt-string)
472 +oci-ntv-syntax+ +oci-default+ :database db)
473 (oci-attr-get (deref-vp stmthp)
476 +unsigned-int-null-pointer+
480 (let* ((select-p (= (uffi:deref-pointer stmttype :unsigned-short) 1))
481 (iters (if select-p 0 1)))
483 (oci-stmt-execute (deref-vp svchp)
486 iters 0 +null-void-pointer+ +null-void-pointer+ +oci-default+
489 (make-query-cursor db stmthp result-types field-names))
491 (oci-handle-free (deref-vp stmthp) +oci-htype-stmt+)
495 ;; Return a QUERY-CURSOR representing the table returned from the OCI
496 ;; operation done through STMTHP. TYPES is the argument of the same
497 ;; name from the external SQL function, controlling type conversion
498 ;; of the returned arguments.
500 (defun make-query-cursor (db stmthp result-types field-names)
501 (let ((qc (%make-query-cursor :db db
503 :cds (make-query-cursor-cds db stmthp
506 (refill-qc-buffers qc)
510 ;; the hairy part of MAKE-QUERY-CURSOR: Ask OCI for information
511 ;; about table columns, translate the information into a Lisp
512 ;; vector of column descriptors, and return it.
514 ;; Allegro defines several flavors of type conversion, but this
515 ;; implementation only supports the :AUTO flavor.
517 ;; A note of explanation: OCI's internal number format uses 21
518 ;; bytes (42 decimal digits). 2 separate (?) one-byte fields,
519 ;; scale and precision, are used to deduce the nature of these
520 ;; 21 bytes. See pp. 3-10, 3-26, and 6-13 of OCI documentation
523 ;; When calling OCI C code to handle the conversion, we have
524 ;; only two numeric types available to pass the return value:
525 ;; double-float and signed-long. It would be possible to
526 ;; bypass the OCI conversion functions and write Lisp code
527 ;; which reads the 21-byte field directly and decodes
528 ;; it. However this is left as an exercise for the reader. :-)
530 ;; The following table describes the mapping, based on the implicit
531 ;; assumption that C's "signed long" type is a 32-bit integer.
533 ;; Internal Values SQL Type C Return Type
534 ;; =============== ======== =============
535 ;; Precision > 0 SCALE = -127 FLOAT --> double-float
536 ;; Precision > 0 && <=9 SCALE = 0 INTEGER --> signed-long
537 ;; Precision = 0 || > 9 SCALE = 0 BIG INTEGER --> double-float
538 ;; Precision > 0 SCALE > 0 DECIMAL --> double-float
540 ;; (OCI uses 1-based indexing here.)
542 ;; KLUDGE: This should work for all other data types except those
543 ;; which don't actually fit in their fixed-width field (BLOBs and the
544 ;; like). As Winton says, we (Cadabra) don't need to worry much about
545 ;; those, since we can't reason with them, so we don't use them. But
546 ;; for a more general application it'd be good to have a more
547 ;; selective and rigorously correct test here for whether we can
548 ;; actually handle the given DEREF-DTYPE value. -- WHN 20000106
550 ;; Note: The OCI documentation doesn't seem to say whether the COLNAME
551 ;; value returned here is a newly-allocated copy which we're
552 ;; responsible for freeing, or a pointer into some system copy which
553 ;; will be freed when the system itself is shut down. But judging
554 ;; from the way that the result is used in the cdemodsa.c example
555 ;; program, it looks like the latter: we should make our own copy of
556 ;; the value, but not try to free it.
558 ;; WORKAROUND: OCI seems to return ub2 values for the
559 ;; +oci-attr-data-size+ attribute even though its documentation claims
560 ;; that it returns a ub4, and even though the associated "sizep" value
561 ;; is 4, not 2. In order to make the code here work reliably, without
562 ;; having to patch it later if OCI is ever fixed to match its
563 ;; documentation, we pre-zero COLSIZE before making the call into OCI.
565 ;; To exercise the weird OCI behavior (thereby blowing up the code
566 ;; below, beware!) try setting this value into COLSIZE, calling OCI,
567 ;; then looking at the value in COLSIZE. (setf colsize #x12345678)
571 (uffi:def-type byte-pointer (* :byte))
572 (uffi:def-type ulong-pointer (* :unsigned-long))
573 (uffi:def-type void-pointer-pointer (* :void-pointer))
575 (defun make-query-cursor-cds (database stmthp result-types field-names)
576 (declare (optimize (safety 3) #+nil (speed 3))
577 (type oracle-database database)
578 (type pointer-pointer-void stmthp))
579 (with-slots (errhp) database
580 (uffi:with-foreign-objects ((dtype-foreign :unsigned-short)
581 (parmdp :pointer-void)
584 (colname '(* :unsigned-char))
585 (colnamelen :unsigned-long)
586 (colsize :unsigned-long)
587 (colsizesize :unsigned-long)
588 (defnp ':pointer-void))
591 (do ((icolumn 0 (1+ icolumn))
592 (cds-as-reversed-list nil))
593 ((not (eql (oci-param-get (deref-vp stmthp)
597 (1+ icolumn) :database database)
599 (coerce (reverse cds-as-reversed-list) 'simple-vector))
600 ;; Decode type of ICOLUMNth column into a type we're prepared to
602 (oci-attr-get (deref-vp parmdp)
605 +unsigned-int-null-pointer+
608 (let ((dtype (uffi:deref-pointer dtype-foreign :unsigned-short)))
609 (declare (fixnum dtype))
612 (setf buffer (acquire-foreign-resource :unsigned-char
613 (* 32 +n-buf-rows+)))
614 (setf sizeof 32 dtype #.SQLT-STR))
616 (oci-attr-get (deref-vp parmdp)
619 +unsigned-int-null-pointer+
622 (oci-attr-get (deref-vp parmdp)
625 +unsigned-int-null-pointer+
628 (let ((*scale (uffi:deref-pointer scale :byte))
629 (*precision (uffi:deref-pointer precision :byte)))
631 ;;(format t "scale=~d, precision=~d~%" *scale *precision)
633 ((or (and (minusp *scale) (zerop *precision))
634 (and (zerop *scale) (plusp *precision)))
635 (setf buffer (acquire-foreign-resource :int +n-buf-rows+)
636 sizeof 4 ;; sizeof(int)
639 (setf buffer (acquire-foreign-resource :double +n-buf-rows+)
640 sizeof 8 ;; sizeof(double)
641 dtype #.SQLT-FLT)))))
642 ;; Default to SQL-STR
644 (setf (uffi:deref-pointer colsize :unsigned-long) 0)
645 (setf dtype #.SQLT-STR)
646 (oci-attr-get (deref-vp parmdp)
649 +unsigned-int-null-pointer+
652 (let ((colsize-including-null (1+ (uffi:deref-pointer colsize :unsigned-long))))
653 (setf buffer (acquire-foreign-resource
654 :unsigned-char (* +n-buf-rows+ colsize-including-null)))
655 (setf sizeof colsize-including-null))))
656 (let ((retcodes (acquire-foreign-resource :unsigned-short +n-buf-rows+))
657 (indicators (acquire-foreign-resource :short +n-buf-rows+))
660 (oci-attr-get (deref-vp parmdp)
666 (setq colname-string (uffi:convert-from-foreign-string
667 (uffi:deref-pointer colname '(* :unsigned-char))
668 :length (uffi:deref-pointer colnamelen :unsigned-long))))
669 (push (make-cd :name colname-string
674 :indicators indicators
676 ((consp result-types)
677 (nth icolumn result-types))
682 cds-as-reversed-list)
683 (oci-define-by-pos (deref-vp stmthp)
686 (1+ icolumn) ; OCI 1-based indexing again
687 (foreign-resource-buffer buffer)
690 (foreign-resource-buffer indicators)
691 +unsigned-short-null-pointer+
692 (foreign-resource-buffer retcodes)
693 +oci-default+))))))))
695 ;; Release the resources associated with a QUERY-CURSOR.
697 (defun close-query (qc)
698 (oci-handle-free (deref-vp (qc-stmthp qc)) +oci-htype-stmt+)
699 (let ((cds (qc-cds qc)))
700 (dotimes (i (length cds))
701 (release-cd-resources (aref cds i))))
705 ;; Release the resources associated with a column description.
707 (defun release-cd-resources (cd)
708 (free-foreign-resource (cd-buffer cd))
709 (free-foreign-resource (cd-retcodes cd))
710 (free-foreign-resource (cd-indicators cd))
714 (defmethod database-name-from-spec (connection-spec (database-type (eql :oracle)))
715 (check-connection-spec connection-spec database-type (dsn user password))
716 (destructuring-bind (dsn user password) connection-spec
717 (declare (ignore password))
718 (concatenate 'string dsn "/" user)))
721 (defmethod database-connect (connection-spec (database-type (eql :oracle)))
722 (check-connection-spec connection-spec database-type (dsn user password))
723 (destructuring-bind (data-source-name user password)
725 (let ((envhp (uffi:allocate-foreign-object :pointer-void))
726 (errhp (uffi:allocate-foreign-object :pointer-void))
727 (svchp (uffi:allocate-foreign-object :pointer-void))
728 (srvhp (uffi:allocate-foreign-object :pointer-void)))
729 ;; Requests to allocate environments and handles should never
730 ;; fail in normal operation, and they're done too early to
731 ;; handle errors very gracefully (since they're part of the
732 ;; error-handling mechanism themselves) so we just assert they
734 (setf (deref-vp envhp) +null-void-pointer+)
736 (oci-env-create envhp +oci-default+ +null-void-pointer+
737 +null-void-pointer+ +null-void-pointer+
738 +null-void-pointer+ 0 +null-void-pointer-pointer+)
741 (oci-initialize +oci-object+ +null-void-pointer+ +null-void-pointer+
742 +null-void-pointer+ +null-void-pointer-pointer+)
743 (ignore-errors (oci-handle-alloc +null-void-pointer+ envhp
745 +null-void-pointer-pointer+)) ;no testing return
746 (oci-env-init envhp +oci-default+ 0 +null-void-pointer-pointer+))
747 (oci-handle-alloc (deref-vp envhp) errhp
748 +oci-htype-error+ 0 +null-void-pointer-pointer+)
749 (oci-handle-alloc (deref-vp envhp) srvhp
750 +oci-htype-server+ 0 +null-void-pointer-pointer+)
751 (uffi:with-cstring (dblink nil)
752 (oci-server-attach (deref-vp srvhp)
756 (oci-handle-alloc (deref-vp envhp) svchp
757 +oci-htype-svcctx+ 0 +null-void-pointer-pointer+)
758 (oci-attr-set (deref-vp svchp)
760 (deref-vp srvhp) 0 +oci-attr-server+
762 ;; oci-handle-alloc((dvoid *)encvhp, (dvoid **)&stmthp, OCI_HTYPE_STMT, 0, 0);
764 ;; Actually, oci-server-version returns the client version, not the server versions
765 ;; will use "SELECT VERSION FROM V$INSTANCE" to get actual server version.
766 (let (db server-version client-version)
767 (declare (ignorable server-version))
768 (uffi:with-foreign-object (buf '(:array :unsigned-char #.+errbuf-len+))
769 (oci-server-version (deref-vp svchp)
771 (uffi:char-array-to-pointer buf)
772 +errbuf-len+ +oci-htype-svcctx+)
773 (setf client-version (uffi:convert-from-foreign-string buf))
774 ;; This returns the client version, not the server version, so diable it
776 (oci-server-version (deref-vp srvhp)
778 (uffi:char-array-to-pointer buf)
779 +errbuf-len+ +oci-htype-server+)
781 (setf server-version (uffi:convert-from-foreign-string buf)))
782 (setq db (make-instance 'oracle-database
783 :name (database-name-from-spec connection-spec
785 :connection-spec connection-spec
788 :database-type :oracle
790 :dsn data-source-name
792 :client-version client-version
793 :server-version server-version
794 :major-client-version (major-client-version-from-string
796 :major-server-version (major-client-version-from-string
798 (oci-logon (deref-vp envhp)
801 (uffi:convert-to-cstring user) (length user)
802 (uffi:convert-to-cstring password) (length password)
803 (uffi:convert-to-cstring data-source-name) (length data-source-name)
805 ;; :date-format-length (1+ (length date-format)))))
806 (setf (slot-value db 'clsql-sys::state) :open)
807 (database-execute-command
808 (format nil "ALTER SESSION SET NLS_DATE_FORMAT='~A'" (date-format db)) db)
809 (let ((server-version
810 (caar (database-query
811 "SELECT BANNER FROM V$VERSION WHERE BANNER LIKE '%Oracle%'" db nil nil))))
812 (setf (slot-value db 'server-version) server-version
813 (slot-value db 'major-server-version) (major-client-version-from-string
818 (defun major-client-version-from-string (str)
820 ((search " 10g " str)
822 ((search "Oracle9i " str)
824 ((search "Oracle8" str)
827 (defun major-server-version-from-string (str)
828 (when (> (length str) 2)
830 ((string= "10." (subseq str 0 3))
832 ((string= "9." (subseq str 0 2))
834 ((string= "8." (subseq str 0 2))
838 ;; Close a database connection.
840 (defmethod database-disconnect ((database oracle-database))
841 (osucc (oci-logoff (deref-vp (svchp database))
842 (deref-vp (errhp database))))
843 (osucc (oci-handle-free (deref-vp (envhp database)) +oci-htype-env+))
844 ;; Note: It's neither required nor allowed to explicitly deallocate the
845 ;; ERRHP handle here, since it's owned by the ENVHP deallocated above,
846 ;; and was therefore automatically deallocated at the same time.
849 ;;; Do the database operation described in SQL-STMT-STRING on database
850 ;;; DB and, if the command is a SELECT, return a representation of the
851 ;;; resulting table. The representation of the table is controlled by the
853 ;;; * If QUERY is NIL, the table is returned as a list of rows, with
854 ;;; each row represented by a list.
855 ;;; * If QUERY is non-NIL, the result is returned as a QUERY-CURSOR
856 ;;; suitable for FETCH-ROW and CLOSE-QUERY
857 ;;; The TYPES argument controls the type conversion method used
858 ;;; to construct the table. The Allegro version supports several possible
859 ;;; values for this argument, but we only support :AUTO.
861 (defmethod database-query (query-expression (database oracle-database) result-types field-names)
862 (let ((cursor (sql-stmt-exec query-expression database result-types field-names)))
863 ;; (declare (type (or query-cursor null) cursor))
864 (if (null cursor) ; No table was returned.
866 (do ((reversed-result nil))
868 (let* ((eof-value :eof)
869 (row (fetch-row cursor nil eof-value)))
870 (when (eq row eof-value)
873 (return (values (nreverse reversed-result)
874 (loop for cd across (qc-cds cursor)
875 collect (cd-name cd))))
876 (return (nreverse reversed-result))))
877 (push row reversed-result))))))
880 (defmethod database-create-sequence (sequence-name (database oracle-database))
882 (concatenate 'string "CREATE SEQUENCE " (sql-escape sequence-name))
885 (defmethod database-drop-sequence (sequence-name (database oracle-database))
887 (concatenate 'string "DROP SEQUENCE " (sql-escape sequence-name))
890 (defmethod database-sequence-next (sequence-name (database oracle-database))
893 (concatenate 'string "SELECT "
894 (sql-escape sequence-name)
897 database :auto nil)))
899 (defmethod database-set-sequence-position (name position (database oracle-database))
901 (let* ((next (database-sequence-next name database))
902 (incr (- position next)))
903 (database-execute-command
904 (format nil "ALTER SEQUENCE ~A INCREMENT BY ~D" name incr)
906 (database-sequence-next name database)
907 (database-execute-command
908 (format nil "ALTER SEQUENCE ~A INCREMENT BY 1" name)
911 (defmethod database-list-sequences ((database oracle-database) &key owner)
915 "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~)'"
917 "select sequence_name from user_sequences")))
918 (mapcar #'car (database-query query database nil nil))))
920 (defmethod database-execute-command (sql-expression (database oracle-database))
921 (database-query sql-expression database nil nil)
922 (when (database-autocommit database)
923 (oracle-commit database))
927 (defstruct (cd (:constructor make-cd)
928 (:print-function print-cd))
929 "a column descriptor: metadata about the data in a table"
931 ;; name of this column
932 (name (error "missing NAME") :type simple-string :read-only t)
933 ;; the size in bytes of a single element
934 (sizeof (error "missing SIZE") :type fixnum :read-only t)
935 ;; an array of +N-BUF-ROWS+ elements in C representation
936 (buffer (error "Missing BUFFER")
937 :type foreign-resource
939 ;; an array of +N-BUF-ROWS+ OCI return codes in C representation.
940 ;; (There must be one return code for every element of every
941 ;; row in order to be able to represent nullness.)
942 (retcodes (error "Missing RETCODES")
943 :type foreign-resource
945 (indicators (error "Missing INDICATORS")
946 :type foreign-resource
948 ;; the OCI code for the data type of a single element
949 (oci-data-type (error "missing OCI-DATA-TYPE")
952 (result-type (error "missing RESULT-TYPE")
956 (defun print-cd (cd stream depth)
957 (declare (ignore depth))
958 (print-unreadable-object (cd stream :type t)
960 ":NAME ~S :OCI-DATA-TYPE ~S :OCI-DATA-SIZE ~S"
962 (cd-oci-data-type cd)
965 (defun print-query-cursor (qc stream depth)
966 (declare (ignore depth))
967 (print-unreadable-object (qc stream :type t :identity t)
968 (prin1 (qc-db qc) stream)))
971 (defmethod database-query-result-set ((query-expression string)
972 (database oracle-database)
973 &key full-set result-types)
974 (let ((cursor (sql-stmt-exec query-expression database result-types nil)))
976 (values cursor (length (qc-cds cursor)) nil)
977 (values cursor (length (qc-cds cursor))))))
980 (defmethod database-dump-result-set (result-set (database oracle-database))
981 (close-query result-set))
983 (defmethod database-store-next-row (result-set (database oracle-database) list)
984 (let* ((eof-value :eof)
985 (row (fetch-row result-set nil eof-value)))
986 (unless (eq eof-value row)
987 (loop for i from 0 below (length row)
988 do (setf (nth i list) (nth i row)))
991 (defmethod database-start-transaction ((database oracle-database))
993 ;; Not needed with simple transaction
995 (with-slots (svchp errhp) database
996 (oci-trans-start (deref-vp svchp)
1003 (defun oracle-commit (database)
1004 (with-slots (svchp errhp) database
1005 (osucc (oci-trans-commit (deref-vp svchp)
1009 (defmethod database-commit-transaction ((database oracle-database))
1011 (oracle-commit database)
1014 (defmethod database-abort-transaction ((database oracle-database))
1016 (osucc (oci-trans-rollback (deref-vp (svchp database))
1017 (deref-vp (errhp database))
1023 (defmethod db-type-has-bigint? ((type (eql :oracle)))
1026 (defmethod db-type-has-fancy-math? ((db-type (eql :oracle)))
1029 (defmethod db-type-has-boolean-where? ((db-type (eql :oracle)))
1032 (when (clsql-sys:database-type-library-loaded :oracle)
1033 (clsql-sys:initialize-database-type :database-type :oracle))