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
19 ((database-type (eql :oracle)))
22 ;;;; arbitrary parameters, tunable for performance or other reasons
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."))
35 (defmacro deref-vp (foreign-object)
36 `(uffi:deref-pointer ,foreign-object :pointer-void))
38 ;; constants - from OCI?
40 (defconstant +var-not-in-list+ 1007)
41 (defconstant +no-data-found+ 1403)
42 (defconstant +null-value-returned+ 1405)
43 (defconstant +field-truncated+ 1406)
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))
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.
58 (uffi:def-type pointer-pointer-void '(* :pointer-void))
60 (defclass oracle-database (database) ; was struct db
64 :type pointer-pointer-void
66 "OCI environment handle")
70 :type pointer-pointer-void
76 :type pointer-pointer-void
78 "OCI service context handle")
83 "optional data source name (used only for debugging/printing)")
89 "the \"user\" value given when data source connection was made")
93 :initform "YYYY-MM-DD HH24:MI:SS\"+00\"")
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.")
103 :initarg :server-version
104 :reader server-version
106 "Version string of Oracle server.")
107 (major-server-version
108 :type (or null fixnum)
109 :initarg :major-server-version
110 :reader major-server-version
112 "The major version number of the Oracle server, should be 8, 9, or 10")
115 :initarg :client-version
116 :reader client-version
118 "Version string of Oracle client.")
119 (major-client-version
120 :type (or null fixnum)
121 :initarg :major-client-version
122 :reader major-client-version
124 "The major version number of the Oracle client, should be 8, 9, or 10")))
127 ;;; Handle the messy case of return code=+oci-error+, querying the
128 ;;; system for subcodes and reporting them as appropriate. ERRHP and
129 ;;; NULLS-OK are as in the OERR function.
131 (defun handle-oci-error (&key database nulls-ok)
135 (uffi:with-foreign-objects ((errbuf '(:array :unsigned-char
138 ;; ensure errbuf empty string
139 (setf (uffi:deref-array errbuf '(:array :unsigned-char) 0)
140 (uffi:ensure-char-storable (code-char 0)))
142 (setf (uffi:deref-pointer errcode :long) 0)
143 (oci-error-get (deref-vp errhp) 1
144 (uffi:make-null-pointer :unsigned-char)
145 errcode errbuf +errbuf-len+ +oci-htype-error+)
146 (let ((subcode (uffi:deref-pointer errcode :long)))
147 (unless (and nulls-ok (= subcode +null-value-returned+))
148 (error 'sql-database-error
151 :message (uffi:convert-from-foreign-string errbuf)))))))
153 (error 'sql-database-error
155 :message "can't handle NULLS-OK without ERRHP"))
157 (error 'sql-database-error
159 :message "OCI Error (and no ERRHP available to find subcode)"))))
161 ;;; Require an OCI success code.
163 ;;; (The ordinary OCI error reporting mechanisms uses a fair amount of
164 ;;; machinery (environments and other handles). In order to get to
165 ;;; where we can use these mechanisms, we have to be able to allocate
166 ;;; the machinery. The functions for allocating the machinery can
167 ;;; return errors (e.g. out of memory) but shouldn't. Wrapping this function
168 ;;; around function calls to such have-to-succeed functions enforces
172 (declare (type fixnum code))
173 (unless (= code +oci-success+)
174 (error 'sql-database-error
175 :message (format nil "unexpected OCI failure, code=~S" code))))
178 ;;; Enabling this can be handy for low-level debugging.
181 (trace oci-initialize #+oci-8-1-5 oci-env-create oci-handle-alloc oci-logon
182 oci-error-get oci-stmt-prepare oci-stmt-execute
183 oci-param-get oci-logon oci-attr-get oci-define-by-pos oci-stmt-fetch)
184 (setf debug::*debug-print-length* nil))
187 ;;;; the OCI library, part V: converting from OCI representations to Lisp
190 ;; Return the INDEXth string of the OCI array, represented as Lisp
191 ;; SIMPLE-STRING. SIZE is the size of the fixed-width fields used by
192 ;; Oracle to store strings within the array.
194 ;; In the wild world of databases, trailing spaces aren't generally
195 ;; significant, since e.g. "LARRY " and "LARRY " are the same string
196 ;; stored in different fixed-width fields. OCI drops trailing spaces
197 ;; for us in some cases but apparently not for fields of fixed
198 ;; character width, e.g.
200 ;; (dbi:sql "create table employees (name char(15), job char(15), city
201 ;; char(15), rate float)" :db orcl :types :auto)
202 ;; In order to map the "same string" property above onto Lisp equality,
203 ;; we drop trailing spaces in all cases:
205 (uffi:def-type string-array (:array :unsigned-char))
207 (defun deref-oci-string (arrayptr string-index size)
208 (declare (type string-array arrayptr))
209 (declare (type (mod #.+n-buf-rows+) string-index))
210 (declare (type (and unsigned-byte fixnum) size))
211 (let* ((raw (uffi:convert-from-foreign-string
213 (+ (uffi:pointer-address arrayptr) (* string-index size))
215 (trimmed (string-trim " " raw)))
216 (if (equal trimmed "NULL") nil trimmed)))
218 ;; the OCI library, part Z: no-longer used logic to convert from
219 ;; Oracle's binary date representation to Common Lisp's native date
223 (defvar +oci-date-bytes+ 7)
225 ;;; Return the INDEXth date in the OCI array, represented as
226 ;;; a Common Lisp "universal time" (i.e. seconds since 1900).
229 (defun deref-oci-date (arrayptr index)
230 (oci-date->universal-time (uffi:pointer-address
231 (uffi:deref-array arrayptr
232 '(:array :unsigned-char)
233 (* index +oci-date-bytes+)))))
235 (defun oci-date->universal-time (oci-date)
236 (declare (type (alien (* :unsigned-char)) oci-date))
237 (flet (;; a character from OCI-DATE, interpreted as an unsigned byte
239 (declare (type (mod #.+oci-date-bytes+) i))
240 (mod (uffi:deref-array oci-date string-array i) 256)))
241 (let* ((century (* (- (ub 0) 100) 100))
242 (year (+ century (- (ub 1) 100)))
247 (second (1- (ub 6))))
248 (encode-universal-time second minute hour day month year))))
251 (defmethod database-list-tables ((database oracle-database) &key owner)
255 "select user_tables.table_name from user_tables,all_tables where user_tables.table_name=all_tables.table_name and all_tables.owner='~:@(~A~)'"
257 "select table_name from user_tables")))
258 (mapcar #'car (database-query query database nil nil))))
261 (defmethod database-list-views ((database oracle-database) &key owner)
265 "select user_views.view_name from user_views,all_views where user_views.view_name=all_views.view_name and all_views.owner='~:@(~A~)'"
267 "select view_name from user_views")))
269 (database-query query database nil nil))))
271 (defmethod database-list-indexes ((database oracle-database)
276 "select user_indexes.index_name from user_indexes,all_indexes where user_indexes.index_name=all_indexes.index_name and all_indexes.owner='~:@(~A~)'"
278 "select index_name from user_indexes")))
279 (mapcar #'car (database-query query database nil nil))))
281 (defmethod database-list-table-indexes (table (database oracle-database)
286 "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~)'"
288 (format nil "select index_name from user_indexes where table_name='~A'"
290 (mapcar #'car (database-query query database nil nil))))
292 (defmethod list-all-table-columns (table (db oracle-database))
293 (declare (string table))
294 (let* ((sql-stmt (concatenate
300 "user_tab_columns.COLUMN_NAME,"
301 "user_tab_columns.DATA_TYPE from user_tab_columns,"
302 "all_tables where all_tables.table_name = '" table "'"
303 " and user_tab_columns.table_name = '" table "'"))
304 (preresult (database-query sql-stmt db :auto nil)))
305 ;; PRERESULT is like RESULT except that it has a name instead of
306 ;; type codes in the fifth column of each row. To fix this, we
307 ;; destructively modify PRERESULT.
308 (dolist (preresult-row preresult)
309 (setf (fifth preresult-row)
310 (if (find (fifth preresult-row)
317 (defmethod database-list-attributes (table (database oracle-database) &key owner)
321 "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~)'"
324 "select column_name from user_tab_columns where table_name='~A'"
326 (mapcar #'car (database-query query database nil nil))))
328 (defmethod database-attribute-type (attribute (table string)
329 (database oracle-database)
334 "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~)'"
335 table attribute owner)
337 "select data_type,data_length,data_scale,nullable from user_tab_columns where table_name='~A' and column_name='~A'"
339 (destructuring-bind (type length scale nullable) (car (database-query query database :auto nil))
340 (values (ensure-keyword type) length scale
341 (if (char-equal #\Y (schar nullable 0)) 1 0)))))
343 ;; Return one row of the table referred to by QC, represented as a
344 ;; list; or if there are no more rows, signal an error if EOF-ERRORP,
345 ;; or return EOF-VALUE otherwise.
347 ;; KLUDGE: This CASE statement is a strong sign that the code would be
348 ;; cleaner if CD were made into an abstract class, we made variant
349 ;; classes for CD-for-column-of-strings, CD-for-column-of-floats,
350 ;; etc., and defined virtual functions to handle operations like
351 ;; get-an-element-from-column. (For a small special purpose module
352 ;; like this, would arguably be overkill, so I'm not going to do it
353 ;; now, but if this code ends up getting more complicated in
354 ;; maintenance, it would become a really good idea.)
356 ;; Arguably this would be a good place to signal END-OF-FILE, but
357 ;; since the ANSI spec specifically says that END-OF-FILE means a
358 ;; STREAM which has no more data, and QC is not a STREAM, we signal
359 ;; DBI-ERROR instead.
361 (uffi:def-type short-array '(:array :short))
362 (uffi:def-type int-pointer '(* :int))
363 (uffi:def-type double-pointer '(* :double))
365 ;;; the result of a database query: a cursor through a table
366 (defstruct (oracle-result-set (:print-function print-query-cursor)
368 (:constructor %make-query-cursor))
369 (db (error "missing DB") ; db conn. this table is associated with
370 :type oracle-database
372 (stmthp (error "missing STMTHP") ; the statement handle used to create
373 ;; :type alien ; this table. owned by the QUERY-CURSOR
374 :read-only t) ; object, deallocated on CLOSE-QUERY
375 (cds) ; (error "missing CDS") ; column descriptors
376 ; :type (simple-array cd 1)
379 0 ; buffered rows: number of rows recv'd
380 :type (integer 0 #.+n-buf-rows+)) ; from the database on the last read
382 0 ; number of buffered rows returned, i.e.
383 :type (integer 0 #.+n-buf-rows+)) ; the index, within the buffered rows,
384 ; of the next row which hasn't already
387 0 ; total number of bytes recv'd from OCI
388 :type unsigned-byte) ; in all reads
389 (oci-end-seen-p nil)) ; Have we seen the end of OCI
390 ; data, i.e. OCI returning
391 ; less data than we requested?
392 ; OCI doesn't seem to like us
393 ; to try to read more data
394 ; from it after that..
397 (defun fetch-row (qc &optional (eof-errorp t) eof-value)
398 ;;(declare (optimize (speed 3)))
399 (cond ((zerop (qc-n-from-oci qc))
401 (error 'sql-database-error :message
402 (format nil "no more rows available in ~S" qc))
404 ((>= (qc-n-to-dbi qc)
406 (refill-qc-buffers qc)
407 (fetch-row qc nil eof-value))
409 (let ((cds (qc-cds qc))
410 (reversed-result nil)
411 (irow (qc-n-to-dbi qc)))
412 (dotimes (icd (length cds))
413 (let* ((cd (aref cds icd))
414 (b (foreign-resource-buffer (cd-buffer cd)))
416 (let* ((arb (foreign-resource-buffer (cd-indicators cd)))
417 (indicator (uffi:deref-array arb '(:array :short) irow)))
418 (declare (type short-array arb))
419 (unless (= indicator -1)
420 (ecase (cd-oci-data-type cd)
422 (deref-oci-string b irow (cd-sizeof cd)))
424 (uffi:deref-array b '(:array :double) irow))
426 (uffi:deref-array b '(:array :int) irow))
428 (deref-oci-string b irow (cd-sizeof cd))))))))
429 (when (and (eq :string (cd-result-type cd))
431 (not (stringp value)))
432 (setq value (write-to-string value)))
433 (push value reversed-result)))
434 (incf (qc-n-to-dbi qc))
435 (nreverse reversed-result)))))
437 (defun refill-qc-buffers (qc)
438 (with-slots (errhp) (qc-db qc)
439 (setf (qc-n-to-dbi qc) 0)
440 (cond ((qc-oci-end-seen-p qc)
441 (setf (qc-n-from-oci qc) 0))
443 (let ((oci-code (%oci-stmt-fetch
444 (deref-vp (qc-stmthp qc))
447 +oci-fetch-next+ +oci-default+)))
449 (#.+oci-success+ (values))
450 (#.+oci-no-data+ (setf (qc-oci-end-seen-p qc) t)
452 (#.+oci-error+ (handle-oci-error :database (qc-db qc)
454 (uffi:with-foreign-object (rowcount :long)
455 (oci-attr-get (deref-vp (qc-stmthp qc))
458 (uffi:make-null-pointer :unsigned-long)
461 (setf (qc-n-from-oci qc)
462 (- (uffi:deref-pointer rowcount :long)
463 (qc-total-n-from-oci qc)))
464 (when (< (qc-n-from-oci qc) +n-buf-rows+)
465 (setf (qc-oci-end-seen-p qc) t))
466 (setf (qc-total-n-from-oci qc)
467 (uffi:deref-pointer rowcount :long)))))
470 ;; the guts of the SQL function
472 ;; (like the SQL function, but with the QUERY argument hardwired to T, so
473 ;; that the return value is always a cursor instead of a list)
475 ;; Is this a SELECT statement? SELECT statements are handled
476 ;; specially by OCIStmtExecute(). (Non-SELECT statements absolutely
477 ;; require a nonzero iteration count, while the ordinary choice for a
478 ;; SELECT statement is a zero iteration count.
480 ;; SELECT statements are the only statements which return tables. We
481 ;; don't free STMTHP in this case, but instead give it to the new
482 ;; QUERY-CURSOR, and the new QUERY-CURSOR becomes responsible for
483 ;; freeing the STMTHP when it is no longer needed.
485 (defun sql-stmt-exec (sql-stmt-string db result-types field-names)
486 (with-slots (envhp svchp errhp)
488 (let ((stmthp (uffi:allocate-foreign-object :pointer-void)))
489 (uffi:with-foreign-object (stmttype :unsigned-short)
491 (oci-handle-alloc (deref-vp envhp)
493 +oci-htype-stmt+ 0 +null-void-pointer-pointer+)
494 (oci-stmt-prepare (deref-vp stmthp)
496 (uffi:convert-to-cstring sql-stmt-string)
497 (length sql-stmt-string)
498 +oci-ntv-syntax+ +oci-default+ :database db)
499 (oci-attr-get (deref-vp stmthp)
502 (uffi:make-null-pointer :unsigned-int)
506 (let* ((select-p (= (uffi:deref-pointer stmttype :unsigned-short) 1))
507 (iters (if select-p 0 1)))
509 (oci-stmt-execute (deref-vp svchp)
512 iters 0 +null-void-pointer+ +null-void-pointer+ +oci-default+
515 (make-query-cursor db stmthp result-types field-names))
517 (oci-handle-free (deref-vp stmthp) +oci-htype-stmt+)
521 ;; Return a QUERY-CURSOR representing the table returned from the OCI
522 ;; operation done through STMTHP. TYPES is the argument of the same
523 ;; name from the external SQL function, controlling type conversion
524 ;; of the returned arguments.
526 (defun make-query-cursor (db stmthp result-types field-names)
527 (let ((qc (%make-query-cursor :db db
529 :cds (make-query-cursor-cds db stmthp
532 (refill-qc-buffers qc)
536 ;; the hairy part of MAKE-QUERY-CURSOR: Ask OCI for information
537 ;; about table columns, translate the information into a Lisp
538 ;; vector of column descriptors, and return it.
540 ;; Allegro defines several flavors of type conversion, but this
541 ;; implementation only supports the :AUTO flavor.
543 ;; A note of explanation: OCI's internal number format uses 21
544 ;; bytes (42 decimal digits). 2 separate (?) one-byte fields,
545 ;; scale and precision, are used to deduce the nature of these
546 ;; 21 bytes. See pp. 3-10, 3-26, and 6-13 of OCI documentation
549 ;; When calling OCI C code to handle the conversion, we have
550 ;; only two numeric types available to pass the return value:
551 ;; double-float and signed-long. It would be possible to
552 ;; bypass the OCI conversion functions and write Lisp code
553 ;; which reads the 21-byte field directly and decodes
554 ;; it. However this is left as an exercise for the reader. :-)
556 ;; The following table describes the mapping, based on the implicit
557 ;; assumption that C's "signed long" type is a 32-bit integer.
559 ;; Internal Values SQL Type C Return Type
560 ;; =============== ======== =============
561 ;; Precision > 0 SCALE = -127 FLOAT --> double-float
562 ;; Precision > 0 && <=9 SCALE = 0 INTEGER --> signed-long
563 ;; Precision = 0 || > 9 SCALE = 0 BIG INTEGER --> double-float
564 ;; Precision > 0 SCALE > 0 DECIMAL --> double-float
566 ;; (OCI uses 1-based indexing here.)
568 ;; KLUDGE: This should work for all other data types except those
569 ;; which don't actually fit in their fixed-width field (BLOBs and the
570 ;; like). As Winton says, we (Cadabra) don't need to worry much about
571 ;; those, since we can't reason with them, so we don't use them. But
572 ;; for a more general application it'd be good to have a more
573 ;; selective and rigorously correct test here for whether we can
574 ;; actually handle the given DEREF-DTYPE value. -- WHN 20000106
576 ;; Note: The OCI documentation doesn't seem to say whether the COLNAME
577 ;; value returned here is a newly-allocated copy which we're
578 ;; responsible for freeing, or a pointer into some system copy which
579 ;; will be freed when the system itself is shut down. But judging
580 ;; from the way that the result is used in the cdemodsa.c example
581 ;; program, it looks like the latter: we should make our own copy of
582 ;; the value, but not try to free it.
584 ;; WORKAROUND: OCI seems to return ub2 values for the
585 ;; +oci-attr-data-size+ attribute even though its documentation claims
586 ;; that it returns a ub4, and even though the associated "sizep" value
587 ;; is 4, not 2. In order to make the code here work reliably, without
588 ;; having to patch it later if OCI is ever fixed to match its
589 ;; documentation, we pre-zero COLSIZE before making the call into OCI.
591 ;; To exercise the weird OCI behavior (thereby blowing up the code
592 ;; below, beware!) try setting this value into COLSIZE, calling OCI,
593 ;; then looking at the value in COLSIZE. (setf colsize #x12345678)
597 (defun make-query-cursor-cds (database stmthp result-types field-names)
598 (declare (optimize (safety 3) #+nil (speed 3))
599 (type oracle-database database)
600 (type pointer-pointer-void stmthp))
601 (with-slots (errhp) database
602 (uffi:with-foreign-objects ((dtype-foreign :unsigned-short)
603 (parmdp ':pointer-void)
606 (colname '(* :unsigned-char))
607 (colnamelen :unsigned-long)
608 (colsize :unsigned-long)
609 (colsizesize :unsigned-long)
610 (defnp ':pointer-void))
613 (do ((icolumn 0 (1+ icolumn))
614 (cds-as-reversed-list nil))
615 ((not (eql (oci-param-get (deref-vp stmthp)
619 (1+ icolumn) :database database)
621 (coerce (reverse cds-as-reversed-list) 'simple-vector))
622 ;; Decode type of ICOLUMNth column into a type we're prepared to
624 (oci-attr-get (deref-vp parmdp)
627 (uffi:make-null-pointer :unsigned-int)
630 (let ((dtype (uffi:deref-pointer dtype-foreign :unsigned-short)))
633 (setf buffer (acquire-foreign-resource :unsigned-char
634 (* 32 +n-buf-rows+)))
635 (setf sizeof 32 dtype #.SQLT-STR))
637 (oci-attr-get (deref-vp parmdp)
640 (uffi:make-null-pointer :unsigned-int)
643 (oci-attr-get (deref-vp parmdp)
646 (uffi:make-null-pointer :unsigned-int)
649 (let ((*scale (uffi:deref-pointer scale :byte))
650 (*precision (uffi:deref-pointer precision :byte)))
651 ;;(format t "scale=~d, precision=~d~%" *scale *precision)
654 (and (minusp *scale) (< *precision 10)))
655 (setf buffer (acquire-foreign-resource :int +n-buf-rows+)
656 sizeof 4 ;; sizeof(int)
659 (setf buffer (acquire-foreign-resource :double +n-buf-rows+)
660 sizeof 8 ;; sizeof(double)
661 dtype #.SQLT-FLT)))) )
662 ;; Default to SQL-STR
664 (setf (uffi:deref-pointer colsize :unsigned-long) 0
666 (oci-attr-get (deref-vp parmdp)
669 (uffi:make-null-pointer :unsigned-int) ;; (uffi:pointer-address colsizesize)
672 (let ((colsize-including-null (1+ (uffi:deref-pointer colsize :unsigned-long))))
673 (setf buffer (acquire-foreign-resource
674 :unsigned-char (* +n-buf-rows+ colsize-including-null)))
675 (setf sizeof colsize-including-null))))
676 (let ((retcodes (acquire-foreign-resource :unsigned-short +n-buf-rows+))
677 (indicators (acquire-foreign-resource :short +n-buf-rows+))
680 (oci-attr-get (deref-vp parmdp)
686 (setq colname-string (uffi:convert-from-foreign-string
687 (uffi:deref-pointer colname '(* :unsigned-char))
688 :length (uffi:deref-pointer colnamelen :unsigned-long))))
689 (push (make-cd :name colname-string
694 :indicators indicators
696 ((consp result-types)
697 (nth icolumn result-types))
702 cds-as-reversed-list)
703 (oci-define-by-pos (deref-vp stmthp)
706 (1+ icolumn) ; OCI 1-based indexing again
707 (uffi:with-cast-pointer (vp (foreign-resource-buffer buffer) :void)
711 (uffi:with-cast-pointer (vp (foreign-resource-buffer indicators) :void)
713 (uffi:make-null-pointer :unsigned-short)
714 (uffi:with-cast-pointer (vp (foreign-resource-buffer retcodes) :unsigned-short)
716 +oci-default+))))))))
718 ;; Release the resources associated with a QUERY-CURSOR.
720 (defun close-query (qc)
721 (oci-handle-free (deref-vp (qc-stmthp qc)) +oci-htype-stmt+)
722 (let ((cds (qc-cds qc)))
723 (dotimes (i (length cds))
724 (release-cd-resources (aref cds i))))
728 ;; Release the resources associated with a column description.
730 (defun release-cd-resources (cd)
731 (free-foreign-resource (cd-buffer cd))
732 (free-foreign-resource (cd-retcodes cd))
733 (free-foreign-resource (cd-indicators cd))
737 (defmethod database-name-from-spec (connection-spec (database-type (eql :oracle)))
738 (check-connection-spec connection-spec database-type (dsn user password))
739 (destructuring-bind (dsn user password) connection-spec
740 (declare (ignore password))
741 (concatenate 'string dsn "/" user)))
744 (defmethod database-connect (connection-spec (database-type (eql :oracle)))
745 (check-connection-spec connection-spec database-type (dsn user password))
746 (destructuring-bind (data-source-name user password)
748 (let ((envhp (uffi:allocate-foreign-object :pointer-void))
749 (errhp (uffi:allocate-foreign-object :pointer-void))
750 (svchp (uffi:allocate-foreign-object :pointer-void))
751 (srvhp (uffi:allocate-foreign-object :pointer-void)))
752 ;; Requests to allocate environments and handles should never
753 ;; fail in normal operation, and they're done too early to
754 ;; handle errors very gracefully (since they're part of the
755 ;; error-handling mechanism themselves) so we just assert they
757 (setf (deref-vp envhp) +null-void-pointer+)
760 (oci-env-create envhp +oci-default+ +null-void-pointer+
761 +null-void-pointer+ +null-void-pointer+
762 +null-void-pointer+ 0 +null-void-pointer-pointer+)
763 (oci-handle-alloc envhp
766 +null-void-pointer-pointer+))
769 (oci-initialize +oci-object+ +null-void-pointer+ +null-void-pointer+
770 +null-void-pointer+ +null-void-pointer-pointer+)
771 (ignore-errors (oci-handle-alloc +null-void-pointer+ envhp
773 +null-void-pointer-pointer+)) ;no testing return
774 (oci-env-init envhp +oci-default+ 0 +null-void-pointer-pointer+)
775 (oci-handle-alloc (deref-vp envhp) errhp
776 +oci-htype-error+ 0 +null-void-pointer-pointer+)
777 (oci-handle-alloc (deref-vp envhp) srvhp
778 +oci-htype-server+ 0 +null-void-pointer-pointer+)
779 (uffi:with-cstring (dblink nil)
780 (oci-server-attach (deref-vp srvhp)
784 (oci-handle-alloc (deref-vp envhp) svchp
785 +oci-htype-svcctx+ 0 +null-void-pointer-pointer+)
786 (oci-attr-set (deref-vp svchp)
788 (deref-vp srvhp) 0 +oci-attr-server+
790 ;; oci-handle-alloc((dvoid *)encvhp, (dvoid **)&stmthp, OCI_HTYPE_STMT, 0, 0);
793 ;; Actually, oci-server-version returns the client version, not the server versions
794 ;; will use "SELECT VERSION FROM V$INSTANCE" to get actual server version.
795 (let (db client-version)
796 (uffi:with-foreign-object (buf '(:array :unsigned-char #.+errbuf-len+))
797 (oci-server-version (deref-vp svchp)
799 (uffi:char-array-to-pointer buf)
800 +errbuf-len+ +oci-htype-svcctx+)
801 (setf client-version (uffi:convert-from-foreign-string buf)))
802 (setq db (make-instance 'oracle-database
803 :name (database-name-from-spec connection-spec
807 :database-type :oracle
809 :dsn data-source-name
811 :client-version client-version
812 :major-client-version (major-client-version-from-string
814 (oci-logon (deref-vp envhp)
817 (uffi:convert-to-cstring user) (length user)
818 (uffi:convert-to-cstring password) (length password)
819 (uffi:convert-to-cstring data-source-name) (length data-source-name)
821 ;; :date-format-length (1+ (length date-format)))))
822 (setf (slot-value db 'clsql-sys::state) :open)
823 (database-execute-command
824 (format nil "ALTER SESSION SET NLS_DATE_FORMAT='~A'" (date-format db)) db)
825 (let ((server-version (caar (database-query "SELECT VERSION FROM V$INSTANCE" db nil nil))))
826 (setf (slot-value db 'server-version) server-version
827 (slot-value db 'major-server-version) (major-server-version-from-string
832 (defun major-client-version-from-string (str)
834 ((search " 10g " str)
836 ((search "Oracle9i " str)
838 ((search "Oracle8" str)
841 (defun major-server-version-from-string (str)
842 (when (> (length str) 2)
844 ((string= "10." (subseq str 0 3))
846 ((string= "9." (subseq str 0 2))
848 ((string= "8." (subseq str 0 2))
852 ;; Close a database connection.
854 (defmethod database-disconnect ((database oracle-database))
855 (osucc (oci-logoff (deref-vp (svchp database))
856 (deref-vp (errhp database))))
857 (osucc (oci-handle-free (deref-vp (envhp database)) +oci-htype-env+))
858 ;; Note: It's neither required nor allowed to explicitly deallocate the
859 ;; ERRHP handle here, since it's owned by the ENVHP deallocated above,
860 ;; and was therefore automatically deallocated at the same time.
863 ;;; Do the database operation described in SQL-STMT-STRING on database
864 ;;; DB and, if the command is a SELECT, return a representation of the
865 ;;; resulting table. The representation of the table is controlled by the
867 ;;; * If QUERY is NIL, the table is returned as a list of rows, with
868 ;;; each row represented by a list.
869 ;;; * If QUERY is non-NIL, the result is returned as a QUERY-CURSOR
870 ;;; suitable for FETCH-ROW and CLOSE-QUERY
871 ;;; The TYPES argument controls the type conversion method used
872 ;;; to construct the table. The Allegro version supports several possible
873 ;;; values for this argument, but we only support :AUTO.
875 (defmethod database-query (query-expression (database oracle-database) result-types field-names)
876 (let ((cursor (sql-stmt-exec query-expression database result-types field-names)))
877 ;; (declare (type (or query-cursor null) cursor))
878 (if (null cursor) ; No table was returned.
880 (do ((reversed-result nil))
882 (let* ((eof-value :eof)
883 (row (fetch-row cursor nil eof-value)))
884 (when (eq row eof-value)
887 (return (values (nreverse reversed-result)
888 (loop for cd across (qc-cds cursor)
889 collect (cd-name cd))))
890 (return (nreverse reversed-result))))
891 (push row reversed-result))))))
894 (defmethod database-create-sequence
895 (sequence-name (database oracle-database))
897 (concatenate 'string "CREATE SEQUENCE "
898 (sql-escape sequence-name))
901 (defmethod database-drop-sequence
902 (sequence-name (database oracle-database))
904 (concatenate 'string "DROP SEQUENCE "
905 (sql-escape sequence-name))
908 (defmethod database-sequence-next (sequence-name (database oracle-database))
911 (concatenate 'string "SELECT "
912 (sql-escape sequence-name)
915 database :auto nil)))
917 (defmethod database-set-sequence-position (name position database)
918 (let* ((next (database-sequence-next name database))
919 (incr (- position next)))
920 (database-execute-command
921 (format nil "ALTER SEQUENCE ~A INCREMENT BY ~D" name incr)
923 (database-sequence-next name database)
924 (database-execute-command
925 (format nil "ALTER SEQUENCE ~A INCREMENT BY 1" name)
928 (defmethod database-list-sequences ((database oracle-database) &key owner)
932 "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~)'"
934 "select sequence_name from user_sequences")))
935 (mapcar #'car (database-query query database nil nil))))
937 (defmethod database-execute-command (sql-expression (database oracle-database))
938 (database-query sql-expression database nil nil)
940 (database-query "commit" database nil nil)
944 (defstruct (cd (:constructor make-cd)
945 (:print-function print-cd))
946 "a column descriptor: metadata about the data in a table"
948 ;; name of this column
949 (name (error "missing NAME") :type simple-string :read-only t)
950 ;; the size in bytes of a single element
951 (sizeof (error "missing SIZE") :type fixnum :read-only t)
952 ;; an array of +N-BUF-ROWS+ elements in C representation
953 (buffer (error "Missing BUFFER")
954 :type foreign-resource
956 ;; an array of +N-BUF-ROWS+ OCI return codes in C representation.
957 ;; (There must be one return code for every element of every
958 ;; row in order to be able to represent nullness.)
959 (retcodes (error "Missing RETCODES")
960 :type foreign-resource
962 (indicators (error "Missing INDICATORS")
963 :type foreign-resource
965 ;; the OCI code for the data type of a single element
966 (oci-data-type (error "missing OCI-DATA-TYPE")
969 (result-type (error "missing RESULT-TYPE")
973 (defun print-cd (cd stream depth)
974 (declare (ignore depth))
975 (print-unreadable-object (cd stream :type t)
977 ":NAME ~S :OCI-DATA-TYPE ~S :OCI-DATA-SIZE ~S"
979 (cd-oci-data-type cd)
982 (defun print-query-cursor (qc stream depth)
983 (declare (ignore depth))
984 (print-unreadable-object (qc stream :type t :identity t)
985 (prin1 (qc-db qc) stream)))
988 (defmethod database-query-result-set ((query-expression string)
989 (database oracle-database)
990 &key full-set result-types)
991 (let ((cursor (sql-stmt-exec query-expression database result-types nil)))
993 (values cursor (length (qc-cds cursor)) nil)
994 (values cursor (length (qc-cds cursor))))))
997 (defmethod database-dump-result-set (result-set (database oracle-database))
998 (close-query result-set))
1000 (defmethod database-store-next-row (result-set (database oracle-database) list)
1001 (let* ((eof-value :eof)
1002 (row (fetch-row result-set nil eof-value)))
1003 (unless (eq eof-value row)
1004 (loop for i from 0 below (length row)
1005 do (setf (nth i list) (nth i row)))
1008 (defmethod clsql-sys:database-start-transaction ((database oracle-database))
1011 ;;(with-slots (svchp errhp) database
1012 ;; (osucc (oci-trans-start (uffi:deref-pointer svchp)
1013 ;; (uffi:deref-pointer errhp)
1015 ;; +oci-trans-new+)))
1019 (defmethod clsql-sys:database-commit-transaction ((database oracle-database))
1021 (with-slots (svchp errhp) database
1022 (osucc (oci-trans-commit (deref-vp svchp)
1027 (defmethod clsql-sys:database-abort-transaction ((database oracle-database))
1029 (osucc (oci-trans-rollback (deref-vp (svchp database))
1030 (deref-vp (errhp database))
1034 (defparameter *constraint-types*
1035 '(("NOT-NULL" . "NOT NULL")))
1037 (defmethod database-output-sql ((str string) (database oracle-database))
1038 (if (and (null (position #\' str))
1039 (null (position #\\ str)))
1040 (format nil "'~A'" str)
1041 (let* ((l (length str))
1042 (buf (make-string (+ l 3))))
1043 (setf (aref buf 0) #\')
1046 ((= i l) (setf (aref buf j) #\'))
1047 (if (= j (- (length buf) 1))
1048 (setf buf (adjust-array buf (+ (length buf) 1))))
1049 (cond ((eql (aref str i) #\')
1050 (setf (aref buf j) #\')
1052 (setf (aref buf j) (aref str i)))
1058 (defmethod db-type-has-bigint? ((type (eql :oracle)))
1061 (defmethod db-type-has-fancy-math? ((db-type (eql :oracle)))
1064 (defmethod db-type-has-boolean-where? ((db-type (eql :oracle)))
1067 (when (clsql-sys:database-type-library-loaded :oracle)
1068 (clsql-sys:initialize-database-type :database-type :oracle))