2 ;;; $Id: oracle-sql.lisp,v 1.1 2002/04/01 05:27:55 kevin Exp $
4 ;;; MaiSQL --- Common Lisp Interface Layer to SQL Databases
5 ;;; This is copyrighted software. See documentation for terms.
7 ;;; oracle-sql.lisp --- SQL-Interface implementation for Oracle
9 ;;; derived from postgresql.lisp
11 (in-package :MAISQL-ORACLE)
13 (defmethod database-initialize-database-type
14 ((database-type (eql :oracle)))
17 ;;;; KLUDGE: The original prototype of this code was implemented using
18 ;;;; lots of special variables holding MAKE-ALIEN values. When I was
19 ;;;; first converting it to use WITH-ALIEN variables, I was confused
20 ;;;; about the behavior of MAKE-ALIEN and WITH-ALIEN; I thought that
21 ;;;; (MAKE-ALIEN TYPEFOO) returned the same type of object as is bound
22 ;;;; to the name BAR by (WITH-ALIEN ((BAR TYPEFOO)) ..). In fact the
23 ;;;; value returned by MAKE-ALIEN has an extra level of indirection
24 ;;;; relative to the value bound by WITH-ALIEN, i.e. (DEREF
25 ;;;; (MAKE-ALIEN TYPEFOO)) has the same type as the value bound to the
26 ;;;; name BAR by (WITH-ALIEN ((BAR TYPEFOO)) ..). Laboring under my
27 ;;;; misunderstanding, I was unable to use ordinary scalars bound by
28 ;;;; WITH-ALIEN, and I ended up giving up and deciding to work around
29 ;;;; this apparent bug in CMUCL by using 1-element arrays instead.
30 ;;;; This "workaround" for my misunderstanding is obviously unnecessary
31 ;;;; and confusing, but still remains in the code. -- WHN 20000106
34 ;;;; arbitrary parameters, tunable for performance or other reasons
36 ;;; the number of table rows that we buffer at once when reading a table
38 ;;; CMUCL has a compiled-in limit on how much C data can be allocated
39 ;;; (through malloc() and friends) at any given time, typically 8 Mb.
40 ;;; Setting this constant to a moderate value should make it less
41 ;;; likely that we'll have to worry about the CMUCL limit.
42 (defconstant +n-buf-rows+ 200)
43 ;;; the number of characters that we allocate for an error message buffer
44 (defconstant +errbuf-len+ 512)
46 ;;; utilities for mucking around with C-level stuff
48 ;; Return the address of ALIEN-OBJECT (like the C operator "&").
50 ;; The INDICES argument is useful to give the ALIEN-OBJECT the
51 ;; expected number of zero indices, especially when we have a bunch of
52 ;; 1-element arrays running around due to the workaround for the CMUCL
53 ;; 18b WITH-ALIEN scalar bug.
55 (defmacro c-& (alien-object &rest indices)
56 `(addr (deref ,alien-object ,@indices)))
58 ;; constants - from OCI?
60 (defconstant +var-not-in-list+ 1007)
61 (defconstant +no-data-found+ 1403)
62 (defconstant +null-value-returned+ 1405)
63 (defconstant +field-truncated+ 1406)
65 (defconstant SQLT-INT 3)
66 (defconstant SQLT-STR 5)
67 (defconstant SQLT-FLT 4)
68 (defconstant SQLT-DATE 12)
70 ;;; Note that despite the suggestive class name (and the way that the
71 ;;; *DEFAULT-DATABASE* variable holds an object of this class), a DB
72 ;;; object is not actually a database but is instead a connection to a
73 ;;; database. Thus, there's no obstacle to having any number of DB
74 ;;; objects referring to the same database.
76 (defclass oracle-database (database) ; was struct db
80 :type (alien (* (* t)))
82 "OCI environment handle")
86 :type (alien (* (* t)))
92 :type (alien (* (* t)))
94 "OCI service context handle")
99 "optional data source name (used only for debugging/printing)")
105 "the \"user\" value given when data source connection was made")
107 :initarg :date-format
109 :initform "YYYY-MM-DD HH24:MI:SS\"+00\"")
113 "Each database connection can be configured with its own date
114 output format. In order to extract date strings from output buffers
115 holding multiple date strings in fixed-width fields, we need to know
116 the length of that format.")))
119 ;;; Handle the messy case of return code=+oci-error+, querying the
120 ;;; system for subcodes and reporting them as appropriate. ERRHP and
121 ;;; NULLS-OK are as in the OERR function.
123 (defun handle-oci-error (&key database nulls-ok)
127 (with-alien ((errbuf (array char #.+errbuf-len+))
128 (errcode (array long 1)))
129 (setf (deref errbuf 0) 0) ; i.e. init to empty string
130 (setf (deref errcode 0) 0)
131 (oci-error-get (deref errhp) 1 "" (c-& errcode 0) (c-& errbuf 0) +errbuf-len+ +oci-htype-error+)
132 (let ((subcode (deref errcode 0)))
133 (unless (and nulls-ok (= subcode +null-value-returned+))
134 (error 'maisql-sql-error
137 :error (cast (c-& errbuf 0) c-string)))))))
139 (error 'maisql-sql-error
141 :error "can't handle NULLS-OK without ERRHP"))
143 (error 'maisql-sql-error
145 :error "OCI Error (and no ERRHP available to find subcode)"))))
147 ;;; Require an OCI success code.
149 ;;; (The ordinary OCI error reporting mechanisms uses a fair amount of
150 ;;; machinery (environments and other handles). In order to get to
151 ;;; where we can use these mechanisms, we have to be able to allocate
152 ;;; the machinery. The functions for allocating the machinery can
153 ;;; return errors (e.g. out of memory) but shouldn't. Wrapping this function
154 ;;; around function calls to such have-to-succeed functions enforces
158 (declare (type fixnum code))
159 (unless (= code +oci-success+)
161 :format-control "unexpected OCI failure, code=~S"
162 :format-arguments (list code))))
165 ;;; Enabling this can be handy for low-level debugging.
168 (trace oci-initialize #+oci-8-1-5 oci-env-create oci-handle-alloc oci-logon
169 oci-error-get oci-stmt-prepare oci-stmt-execute
170 oci-param-get oci-logon oci-attr-get oci-define-by-pos oci-stmt-fetch)
171 (setf debug::*debug-print-length* nil))
174 ;;;; the OCI library, part V: converting from OCI representations to Lisp
177 ;; Return the INDEXth string of the OCI array, represented as Lisp
178 ;; SIMPLE-STRING. SIZE is the size of the fixed-width fields used by
179 ;; Oracle to store strings within the array.
181 ;; In the wild world of databases, trailing spaces aren't generally
182 ;; significant, since e.g. "LARRY " and "LARRY " are the same string
183 ;; stored in different fixed-width fields. OCI drops trailing spaces
184 ;; for us in some cases but apparently not for fields of fixed
185 ;; character width, e.g.
187 ;; (dbi:sql "create table employees (name char(15), job char(15), city
188 ;; char(15), rate float)" :db orcl :types :auto)
189 ;; In order to map the "same string" property above onto Lisp equality,
190 ;; we drop trailing spaces in all cases:
192 (defun deref-oci-string (arrayptr string-index size)
193 (declare (type (alien (* char)) arrayptr))
194 (declare (type (mod #.+n-buf-rows+) string-index))
195 (declare (type (and unsigned-byte fixnum) size))
196 (let* ((raw (cast (addr (deref arrayptr (* string-index size))) c-string))
197 (trimmed (string-trim " " raw)))
198 (if (equal trimmed "NULL") nil trimmed)))
200 ;; the OCI library, part Z: no-longer used logic to convert from
201 ;; Oracle's binary date representation to Common Lisp's native date
205 (defvar +oci-date-bytes+ 7)
207 ;;; Return the INDEXth date in the OCI array, represented as
208 ;;; a Common Lisp "universal time" (i.e. seconds since 1900).
211 (defun deref-oci-date (arrayptr index)
212 (oci-date->universal-time (addr (deref arrayptr
213 (* index +oci-date-bytes+)))))
215 (defun oci-date->universal-time (oci-date)
216 (declare (type (alien (* char)) oci-date))
217 (flet (;; a character from OCI-DATE, interpreted as an unsigned byte
219 (declare (type (mod #.+oci-date-bytes+) i))
220 (mod (deref oci-date i) 256)))
221 (let* ((century (* (- (ub 0) 100) 100))
222 (year (+ century (- (ub 1) 100)))
227 (second (1- (ub 6))))
228 (encode-universal-time second minute hour day month year))))
230 ;; Return (VALUES ALL-TABLES COLUMN-NAMES), where ALL-TABLES is a
231 ;; table containing one row for each table available in DB, and
232 ;; COLUMN-NAMES is a list of header names for the columns in
235 ;; The Allegro version also accepted a HSTMT argument.
237 ;(defmethod database-list-tables ((db oracle-database))
238 ; (sql:query "select '',OWNER,TABLE_NAME,TABLE_TYPE,'' from all_catalog"))
241 (defmethod list-all-user-database-tables ((db oracle-database))
243 (setf db sql:*default-database*))
244 (values (database-query "select TABLE_NAME from all_catalog
245 where owner <> 'PUBLIC' and owner <> 'SYSTEM' and owner <> 'SYS'"
249 (defmethod database-list-tables ((database oracle-database)
250 &key (system-tables nil))
252 (select [table_name] :from [all_catalog])
253 (select [table_name] :from [all_catalog]
254 :where [and [<> [owner] "PUBLIC"]
255 [<> [owner] "SYSTEM"]
259 ;; Return a list of all columns in TABLE.
261 ;; The Allegro version of this also returned a second value.
263 (defmethod list-all-table-columns (table (db oracle-database))
264 (declare (type string table))
266 (setf db (default-database)))
267 (let* ((sql-stmt (concatenate
273 "user_tab_columns.COLUMN_NAME,"
274 "user_tab_columns.DATA_TYPE from user_tab_columns,"
275 "all_tables where all_tables.table_name = '" table "'"
276 " and user_tab_columns.table_name = '" table "'"))
277 (preresult (sql sql-stmt :db db :types :auto)))
278 ;; PRERESULT is like RESULT except that it has a name instead of
279 ;; type codes in the fifth column of each row. To fix this, we
280 ;; destructively modify PRERESULT.
281 (dolist (preresult-row preresult)
282 (setf (fifth preresult-row)
283 (if (find (fifth preresult-row)
290 (defmethod database-list-attributes (table (database oracle-database))
291 (let* ((relname (etypecase table
294 (symbol-name (slot-value table 'sql-sys::name))))
296 (select [user_tab_columns column_name]
297 :from [user_tab_columns]
298 :where [= [user_tab_columns table_name] relname]
303 ;; Return one row of the table referred to by QC, represented as a
304 ;; list; or if there are no more rows, signal an error if EOF-ERRORP,
305 ;; or return EOF-VALUE otherwise.
307 ;; KLUDGE: This CASE statement is a strong sign that the code would be
308 ;; cleaner if CD were made into an abstract class, we made variant
309 ;; classes for CD-for-column-of-strings, CD-for-column-of-floats,
310 ;; etc., and defined virtual functions to handle operations like
311 ;; get-an-element-from-column. (For a small special purpose module
312 ;; like this, would arguably be overkill, so I'm not going to do it
313 ;; now, but if this code ends up getting more complicated in
314 ;; maintenance, it would become a really good idea.)
316 ;; Arguably this would be a good place to signal END-OF-FILE, but
317 ;; since the ANSI spec specifically says that END-OF-FILE means a
318 ;; STREAM which has no more data, and QC is not a STREAM, we signal
319 ;; DBI-ERROR instead.
321 (defun fetch-row (qc &optional (eof-errorp t) eof-value)
322 (declare (optimize (speed 3)))
323 (cond ((zerop (qc-n-from-oci qc))
325 (dbi-error "no more rows available in ~S" qc)
327 ((>= (qc-n-to-dbi qc)
329 (refill-qc-buffers qc)
330 (fetch-row qc nil eof-value))
332 (let ((cds (qc-cds qc))
333 (reversed-result nil)
334 (irow (qc-n-to-dbi qc)))
335 (dotimes (icd (length cds))
336 (let* ((cd (aref cds icd))
337 (b (alien-resource-buffer (cd-buffer cd)))
339 (let ((arb (alien-resource-buffer (cd-indicators cd))))
340 (declare (type (alien (* (alien:signed 16))) arb))
341 (unless (= (deref arb irow) -1)
342 (ecase (cd-oci-data-type cd)
343 (#.SQLT-STR (deref-oci-string b irow (cd-sizeof cd)))
344 (#.SQLT-FLT (deref (the (alien (* double)) b) irow))
345 (#.SQLT-INT (deref (the (alien (* int)) b) irow))
346 (#.SQLT-DATE (deref-oci-string b irow (cd-sizeof cd))))))))
347 (push value reversed-result)))
348 (incf (qc-n-to-dbi qc))
349 (nreverse reversed-result)))))
351 (defun refill-qc-buffers (qc)
354 (setf (qc-n-to-dbi qc) 0)
355 (cond ((qc-oci-end-seen-p qc)
356 (setf (qc-n-from-oci qc) 0))
358 (let ((oci-code (%oci-stmt-fetch (deref (qc-stmthp qc))
361 +oci-fetch-next+ +oci-default+)))
363 (#.+oci-success+ (values))
364 (#.+oci-no-data+ (setf (qc-oci-end-seen-p qc) t)
366 (#.+oci-error+ (handle-oci-error :database (qc-db qc)
368 (with-alien ((rowcount (array unsigned-long 1)))
369 (oci-attr-get (deref (qc-stmthp qc)) +oci-htype-stmt+
370 (c-& rowcount 0) nil +oci-attr-row-count+
372 (setf (qc-n-from-oci qc)
373 (- (deref rowcount 0) (qc-total-n-from-oci qc)))
374 (when (< (qc-n-from-oci qc) +n-buf-rows+)
375 (setf (qc-oci-end-seen-p qc) t))
376 (setf (qc-total-n-from-oci qc)
377 (deref rowcount 0)))))
380 ;; the guts of the SQL function
382 ;; (like the SQL function, but with the QUERY argument hardwired to T, so
383 ;; that the return value is always a cursor instead of a list)
385 ;; Is this a SELECT statement? SELECT statements are handled
386 ;; specially by OCIStmtExecute(). (Non-SELECT statements absolutely
387 ;; require a nonzero iteration count, while the ordinary choice for a
388 ;; SELECT statement is a zero iteration count.
390 ;; SELECT statements are the only statements which return tables. We
391 ;; don't free STMTHP in this case, but instead give it to the new
392 ;; QUERY-CURSOR, and the new QUERY-CURSOR becomes responsible for
393 ;; freeing the STMTHP when it is no longer needed.
395 (defun sql-stmt-exec (sql-stmt-string db &key types)
396 (with-slots (envhp svchp errhp)
398 (let ((stmthp (make-alien (* t))))
399 (with-alien ((stmttype (array unsigned-short 1)))
401 (oci-handle-alloc (deref envhp) (c-& stmthp) +oci-htype-stmt+ 0 nil)
402 (oci-stmt-prepare (deref stmthp) (deref errhp)
403 sql-stmt-string (length sql-stmt-string)
404 +oci-ntv-syntax+ +oci-default+ :database db)
405 (oci-attr-get (deref stmthp) +oci-htype-stmt+
406 (c-& stmttype 0) nil +oci-attr-stmt-type+
407 (deref errhp) :database db)
408 (let* ((select-p (= (deref stmttype 0) 1))
409 (iters (if select-p 0 1)))
411 (oci-stmt-execute (deref svchp) (deref stmthp) (deref errhp)
412 iters 0 nil nil +oci-default+ :database db)
414 (make-query-cursor db stmthp types))
416 (oci-handle-free (deref stmthp) +oci-htype-stmt+)
420 ;; Return a QUERY-CURSOR representing the table returned from the OCI
421 ;; operation done through STMTHP. TYPES is the argument of the same
422 ;; name from the external SQL function, controlling type conversion
423 ;; of the returned arguments.
425 (defun make-query-cursor (db stmthp types)
426 (let ((qc (%make-query-cursor :db db
428 :cds (make-query-cursor-cds db stmthp types))))
429 (refill-qc-buffers qc)
433 ;; the hairy part of MAKE-QUERY-CURSOR: Ask OCI for information
434 ;; about table columns, translate the information into a Lisp
435 ;; vector of column descriptors, and return it.
437 ;; Allegro defines several flavors of type conversion, but this
438 ;; implementation only supports the :AUTO flavor.
440 ;; A note of explanation: OCI's internal number format uses 21
441 ;; bytes (42 decimal digits). 2 separate (?) one-byte fields,
442 ;; scale and precision, are used to deduce the nature of these
443 ;; 21 bytes. See pp. 3-10, 3-26, and 6-13 of OCI documentation
446 ;; When calling OCI C code to handle the conversion, we have
447 ;; only two numeric types available to pass the return value:
448 ;; double-float and signed-long. It would be possible to
449 ;; bypass the OCI conversion functions and write Lisp code
450 ;; which reads the 21-byte field directly and decodes
451 ;; it. However this is left as an exercise for the reader. :-)
453 ;; The following table describes the mapping, based on the implicit
454 ;; assumption that C's "signed long" type is a 32-bit integer.
456 ;; Internal Values SQL Type C Return Type
457 ;; =============== ======== =============
458 ;; Precision > 0 SCALE = -127 FLOAT --> double-float
459 ;; Precision > 0 && <=9 SCALE = 0 INTEGER --> signed-long
460 ;; Precision = 0 || > 9 SCALE = 0 BIG INTEGER --> double-float
461 ;; Precision > 0 SCALE > 0 DECIMAL --> double-float
463 ;; (OCI uses 1-based indexing here.)
465 ;; KLUDGE: This should work for all other data types except those
466 ;; which don't actually fit in their fixed-width field (BLOBs and the
467 ;; like). As Winton says, we (Cadabra) don't need to worry much about
468 ;; those, since we can't reason with them, so we don't use them. But
469 ;; for a more general application it'd be good to have a more
470 ;; selective and rigorously correct test here for whether we can
471 ;; actually handle the given DEREF-DTYPE value. -- WHN 20000106
473 ;; Note: The OCI documentation doesn't seem to say whether the COLNAME
474 ;; value returned here is a newly-allocated copy which we're
475 ;; responsible for freeing, or a pointer into some system copy which
476 ;; will be freed when the system itself is shut down. But judging
477 ;; from the way that the result is used in the cdemodsa.c example
478 ;; program, it looks like the latter: we should make our own copy of
479 ;; the value, but not try to free it.
481 ;; WORKAROUND: OCI seems to return ub2 values for the
482 ;; +oci-attr-data-size+ attribute even though its documentation claims
483 ;; that it returns a ub4, and even though the associated "sizep" value
484 ;; is 4, not 2. In order to make the code here work reliably, without
485 ;; having to patch it later if OCI is ever fixed to match its
486 ;; documentation, we pre-zero COLSIZE before making the call into OCI.
488 ;; To exercise the weird OCI behavior (thereby blowing up the code
489 ;; below, beware!) try setting this value into COLSIZE, calling OCI,
490 ;; then looking at the value in COLSIZE. (setf colsize #x12345678)
494 (defun make-query-cursor-cds (database stmthp types)
495 (declare (optimize (speed 3))
496 (type oracle-database database)
497 (type (alien (* (* t))) stmthp))
500 (unless (eq types :auto)
501 (error "unsupported TYPES value"))
502 (with-alien ((dtype unsigned-short 1)
504 (precision (unsigned 8))
507 (colnamelen unsigned-long)
508 (colsize unsigned-long)
509 (colsizesize unsigned-long)
513 (do ((icolumn 0 (1+ icolumn))
514 (cds-as-reversed-list nil))
515 ((not (eql (oci-param-get (deref stmthp) +oci-htype-stmt+
516 (deref errhp) (addr parmdp)
517 (1+ icolumn) :database database)
519 (coerce (reverse cds-as-reversed-list) 'simple-vector))
520 ;; Decode type of ICOLUMNth column into a type we're prepared to
522 (oci-attr-get parmdp +oci-dtype-param+ (addr dtype)
523 nil +oci-attr-data-type+ (deref errhp))
526 (setf buffer (acquire-alien-resource char (* 32 +n-buf-rows+)))
527 (setf sizeof 32 dtype #.SQLT-STR))
529 ;;(oci-attr-get parmdp +oci-dtype-param+
530 ;;(addr precision) nil +oci-attr-precision+
532 (oci-attr-get parmdp +oci-dtype-param+
533 (addr scale) nil +oci-attr-scale+
537 (setf buffer (acquire-alien-resource signed +n-buf-rows+)
538 sizeof 4 ;; sizeof(int)
541 (setf buffer (acquire-alien-resource double-float +n-buf-rows+)
542 sizeof 8 ;; sizeof(double)
544 (t ; Default to SQL-STR
547 (oci-attr-get parmdp +oci-dtype-param+ (addr colsize)
548 (addr colsizesize) +oci-attr-data-size+
550 (let ((colsize-including-null (1+ colsize)))
551 (setf buffer (acquire-alien-resource char (* +n-buf-rows+ colsize-including-null)))
552 (setf sizeof colsize-including-null))))
553 (let ((retcodes (acquire-alien-resource short +n-buf-rows+))
554 (indicators (acquire-alien-resource short +n-buf-rows+)))
555 (push (make-cd :name "col" ;(subseq colname 0 colnamelen)
560 :indicators indicators)
561 cds-as-reversed-list)
562 (oci-define-by-pos (deref stmthp)
565 (1+ icolumn) ; OCI 1-based indexing again
566 (alien-resource-buffer buffer)
569 (alien-resource-buffer indicators)
571 (alien-resource-buffer retcodes)
574 ;; Release the resources associated with a QUERY-CURSOR.
576 (defun close-query (qc)
577 (oci-handle-free (deref (qc-stmthp qc)) +oci-htype-stmt+)
578 (let ((cds (qc-cds qc)))
579 (dotimes (i (length cds))
580 (release-cd-resources (aref cds i))))
584 ;; Release the resources associated with a column description.
586 (defun release-cd-resources (cd)
587 (free-alien-resource (cd-buffer cd))
588 (free-alien-resource (cd-retcodes cd))
589 (free-alien-resource (cd-indicators cd))
593 (defmethod print-object ((db oracle-database) stream)
594 (print-unreadable-object (db stream :type t :identity t)
595 (format stream "\"/~a/~a\""
596 (slot-value db 'data-source-name)
597 (slot-value db 'user))))
600 (defmethod database-name-from-spec (connection-spec (database-type (eql :oracle)))
601 (check-connection-spec connection-spec database-type (user password dsn))
602 (destructuring-bind (user password dsn)
604 (declare (ignore password))
605 (concatenate 'string "/" dsn "/" user)))
608 (defmethod database-connect (connection-spec (database-type (eql :oracle)))
609 (check-connection-spec connection-spec database-type (user password dsn))
610 (destructuring-bind (user password data-source-name)
612 (let ((envhp (make-alien (* t)))
613 (errhp (make-alien (* t)))
614 (svchp (make-alien (* t)))
615 (srvhp (make-alien (* t))))
616 ;; Requests to allocate environments and handles should never
617 ;; fail in normal operation, and they're done too early to
618 ;; handle errors very gracefully (since they're part of the
619 ;; error-handling mechanism themselves) so we just assert they
621 (setf (deref envhp) nil)
624 (oci-env-create (c-& envhp) +oci-default+ nil nil nil nil 0 nil)
625 (oci-handle-alloc (deref envhp) (c-& errhp) +oci-htype-error+ 0 nil))
628 (oci-initialize +oci-object+ nil nil nil nil)
629 (ignore-errors (oci-handle-alloc nil (c-& envhp) +oci-htype-env+ 0 nil)) ;no testing return
630 (oci-env-init (c-& envhp) +oci-default+ 0 nil)
631 (oci-handle-alloc (deref envhp) (c-& errhp) +oci-htype-error+ 0 nil)
632 (oci-handle-alloc (deref envhp) (c-& srvhp) +oci-htype-server+ 0 nil)
633 ;;(osucc (oci-server-attach srvhp errhp nil 0 +oci-default+))
634 (oci-handle-alloc (deref envhp) (c-& svchp) +oci-htype-svcctx+ 0 nil)
635 ;; oci-handle-alloc((dvoid *)encvhp, (dvoid **)&stmthp, OCI_HTYPE_STMT, 0, 0);
637 (oci-attr-set (deref svchp) +oci-htype-svcctx+ (deref srvhp) 0 +oci-attr-server+ errhp)
641 (format t "Logging in as user '~A' to database ~A~%"
642 user password data-source-name)
643 (oci-logon (deref envhp) (deref errhp) (c-& svchp)
645 password (length password)
646 data-source-name (length data-source-name))
647 (let ((db (make-instance 'oracle-database
648 :name (database-name-from-spec connection-spec
654 :dsn data-source-name
656 ;; :date-format-length (1+ (length date-format)))))
658 (format nil "alter session set NLS_DATE_FORMAT='~A'"
659 (date-format db)) :database db)
663 ;; Close a database connection.
665 (defmethod database-disconnect ((database oracle-database))
666 (osucc (oci-logoff (deref (svchp database)) (deref (errhp database))))
667 (osucc (oci-handle-free (deref (envhp database)) +oci-htype-env+))
668 ;; Note: It's neither required nor allowed to explicitly deallocate the
669 ;; ERRHP handle here, since it's owned by the ENVHP deallocated above,
670 ;; and was therefore automatically deallocated at the same time.
673 ;;; Do the database operation described in SQL-STMT-STRING on database
674 ;;; DB and, if the command is a SELECT, return a representation of the
675 ;;; resulting table. The representation of the table is controlled by the
677 ;;; * If QUERY is NIL, the table is returned as a list of rows, with
678 ;;; each row represented by a list.
679 ;;; * If QUERY is non-NIL, the result is returned as a QUERY-CURSOR
680 ;;; suitable for FETCH-ROW and CLOSE-QUERY
681 ;;; The TYPES argument controls the type conversion method used
682 ;;; to construct the table. The Allegro version supports several possible
683 ;;; values for this argument, but we only support :AUTO.
685 (defmethod database-query (query-expression (database oracle-database))
686 (let ((cursor (sql-stmt-exec query-expression database :types :auto)))
687 (declare (type (or query-cursor null) cursor))
688 (if (null cursor) ; No table was returned.
690 (do ((reversed-result nil))
692 (let* ((eof-value :eof)
693 (row (fetch-row cursor nil eof-value)))
694 (when (eq row eof-value)
696 (return (nreverse reversed-result)))
697 (push row reversed-result))))))
700 (defmethod database-create-sequence
701 (sequence-name (database oracle-database))
703 (concatenate 'string "CREATE SEQUENCE "
704 (sql-escape sequence-name))
707 (defmethod database-drop-sequence
708 (sequence-name (database oracle-database))
710 (concatenate 'string "DROP SEQUENCE "
711 (sql-escape sequence-name))
714 (defmethod database-sequence-next (sequence-name (database oracle-database))
717 (concatenate 'string "SELECT "
718 (sql-escape sequence-name)
720 ) :database database)))
723 (defmethod database-execute-command
724 (sql-expression (database oracle-database))
725 (database-query sql-expression database)
727 (database-query "commit" database)
731 ;;; a column descriptor: metadata about the data in a table
732 (defstruct (cd (:constructor make-cd)
733 (:print-function print-cd))
734 ;; name of this column
735 (name (error "missing NAME") :type simple-string :read-only t)
736 ;; the size in bytes of a single element
737 (sizeof (error "missing SIZE") :type fixnum :read-only t)
738 ;; an array of +N-BUF-ROWS+ elements in C representation
739 (buffer (error "Missing BUFFER")
742 ;; an array of +N-BUF-ROWS+ OCI return codes in C representation.
743 ;; (There must be one return code for every element of every
744 ;; row in order to be able to represent nullness.)
745 (retcodes (error "Missing RETCODES")
748 (indicators (error "Missing INDICATORS")
751 ;; the OCI code for the data type of a single element
752 (oci-data-type (error "missing OCI-DATA-TYPE")
757 (defun print-cd (cd stream depth)
758 (declare (ignore depth))
759 (print-unreadable-object (cd stream :type t)
761 ":NAME ~S :OCI-DATA-TYPE ~S :OCI-DATA-SIZE ~S"
763 (cd-oci-data-type cd)
766 ;;; the result of a database query: a cursor through a table
767 (defstruct (oracle-result-set (:print-function print-query-cursor)
769 (:constructor %make-query-cursor))
770 (db (error "missing DB") ; db conn. this table is associated with
773 (stmthp (error "missing STMTHP") ; the statement handle used to create
774 :type alien ; this table. owned by the QUERY-CURSOR
775 :read-only t) ; object, deallocated on CLOSE-QUERY
776 (cds) ; (error "missing CDS") ; column descriptors
777 ; :type (simple-array cd 1)
779 (n-from-oci 0 ; buffered rows: number of rows recv'd
780 :type (integer 0 #.+n-buf-rows+)) ; from the database on the last read
781 (n-to-dbi 0 ; number of buffered rows returned, i.e.
782 :type (integer 0 #.+n-buf-rows+)) ; the index, within the buffered rows,
783 ; of the next row which hasn't already
785 (total-n-from-oci 0 ; total number of bytes recv'd from OCI
786 :type unsigned-byte) ; in all reads
787 (oci-end-seen-p nil)) ; Have we seen the end of OCI
788 ; data, i.e. OCI returning
789 ; less data than we requested?
790 ; OCI doesn't seem to like us
791 ; to try to read more data
792 ; from it after that..
794 (defun print-query-cursor (qc stream depth)
795 (declare (ignore depth))
796 (print-unreadable-object (qc stream :type t :identity t)
797 (prin1 (qc-db qc) stream)))
800 (defmethod database-query-result-set (query-expression (database oracle-database) &optional full-set)
803 (defmethod database-dump-result-set (result-set (database oracle-database))
806 (defmethod database-store-next-row (result-set (database oracle-database) list)
809 (defmethod sql-sys::database-start-transaction ((database oracle-database))
812 ;;(with-slots (svchp errhp) database
813 ;; (osucc (oci-trans-start (deref svchp)
816 ;; +oci-trans-new+)))
820 (defmethod sql-sys::database-commit-transaction ((database oracle-database))
822 (with-slots (svchp errhp) database
823 (osucc (oci-trans-commit (deref svchp)
828 (defmethod sql-sys::database-abort-transaction ((database oracle-database))
830 (osucc (oci-trans-rollback (deref (svchp database))
831 (deref (errhp database))
835 (defparameter *constraint-types*
836 '(("NOT-NULL" . "NOT NULL")))
838 (defmethod database-output-sql ((str string) (database oracle-database))
839 (if (and (null (position #\' str))
840 (null (position #\\ str)))
841 (format nil "'~A'" str)
842 (let* ((l (length str))
843 (buf (make-string (+ l 3))))
844 (setf (aref buf 0) #\')
847 ((= i l) (setf (aref buf j) #\'))
848 (if (= j (- (length buf) 1))
849 (setf buf (adjust-array buf (+ (length buf) 1))))
850 (cond ((eql (aref str i) #\')
851 (setf (aref buf j) #\')
853 (setf (aref buf j) (aref str i)))