r9471: 5 May 2004 Kevin Rosenberg <kevin@rosenberg.net>
[clsql.git] / db-oracle / oracle-sql.lisp
index aedff1bab29dc4cb5889f0f75cdb634f0f3e4dca..8ef460229a203916744008f860aa007f7e5b4ed8 100644 (file)
@@ -31,8 +31,11 @@ Setting this constant to a moderate value should make it less
 likely that we'll have to worry about the CMUCL limit."))
 
 
+(uffi:def-type vp-type :pointer-void)
+(uffi:def-type vpp-type (* :pointer-void))
+
 (defmacro deref-vp (foreign-object)
-  `(uffi:deref-pointer ,foreign-object :pointer-void))
+  `(the vp-type (uffi:deref-pointer (the vpp-type ,foreign-object) :pointer-void)))
 
 ;; constants - from OCI?
 
@@ -51,8 +54,8 @@ likely that we'll have to worry about the CMUCL limit."))
 (eval-when (:compile-toplevel :load-toplevel :execute)
   (defconstant SQLT-NUMBER 2)
   (defconstant SQLT-INT 3)
-  (defconstant SQLT-STR 5)
   (defconstant SQLT-FLT 4)
+  (defconstant SQLT-STR 5)
   (defconstant SQLT-DATE 12))
 
 ;;; Note that despite the suggestive class name (and the way that the
@@ -105,7 +108,7 @@ output format.  In order to extract date strings from output buffers
 holding multiple date strings in fixed-width fields, we need to know
 the length of that format.")
    (server-version 
-    :type string
+    :type (or null string)
     :initarg :server-version
     :reader server-version
     :documentation
@@ -117,7 +120,7 @@ the length of that format.")
     :documentation
     "The major version number of the Oracle server, should be 8, 9, or 10")
    (client-version 
-    :type string
+    :type (or null string)
     :initarg :client-version
     :reader client-version
     :documentation
@@ -136,8 +139,7 @@ the length of that format.")
 
 (defun handle-oci-error (&key database nulls-ok)
   (cond (database
-         (with-slots (errhp)
-            database
+         (with-slots (errhp) database
            (uffi:with-foreign-objects ((errbuf '(:array :unsigned-char
                                                 #.+errbuf-len+))
                                       (errcode :long))
@@ -146,9 +148,12 @@ the length of that format.")
                   (uffi:ensure-char-storable (code-char 0)))
 
              (setf (uffi:deref-pointer errcode :long) 0)
-             (oci-error-get (deref-vp errhp) 1
-                           (uffi:make-null-pointer :unsigned-char)
-                           errcode errbuf +errbuf-len+ +oci-htype-error+)
+            (uffi:with-cstring (sqlstate nil)
+              (oci-error-get (deref-vp errhp) 1
+                             sqlstate
+                             errcode
+                             (uffi:char-array-to-pointer errbuf)
+                             +errbuf-len+ +oci-htype-error+))
              (let ((subcode (uffi:deref-pointer errcode :long)))
                (unless (and nulls-ok (= subcode +null-value-returned+))
                  (error 'sql-database-error
@@ -190,36 +195,21 @@ the length of that format.")
   (setf debug::*debug-print-length* nil))
 
 
-;;;; the OCI library, part V: converting from OCI representations to Lisp
-;;;; representations
-
 ;; Return the INDEXth string of the OCI array, represented as Lisp
 ;; SIMPLE-STRING. SIZE is the size of the fixed-width fields used by
 ;; Oracle to store strings within the array.
 
-;; In the wild world of databases, trailing spaces aren't generally
-;; significant, since e.g. "LARRY " and "LARRY    " are the same string
-;; stored in different fixed-width fields. OCI drops trailing spaces
-;; for us in some cases but apparently not for fields of fixed
-;; character width, e.g.
-;;
-;;   (dbi:sql "create table employees (name char(15), job char(15), city
-;;            char(15), rate float)" :db orcl :types :auto)
-;; In order to map the "same string" property above onto Lisp equality,
-;; we drop trailing spaces in all cases:
-
-(uffi:def-type string-array (:array :unsigned-char))
+(uffi:def-type string-pointer (* :unsigned-char))
 
 (defun deref-oci-string (arrayptr string-index size)
-;;  (declare (type string-array arrayptr))
+  (declare (type string-pointer arrayptr))
   (declare (type (mod #.+n-buf-rows+) string-index))
   (declare (type (and unsigned-byte fixnum) size))
-  (let* ((raw (uffi:convert-from-foreign-string 
-              (uffi:make-pointer
-               (+ (uffi:pointer-address arrayptr) (* string-index size))
-               :unsigned-char)))
-        (trimmed (string-trim " " raw)))
-     (if (equal trimmed "NULL") nil trimmed)))
+  (let ((str (uffi:convert-from-foreign-string 
+             (uffi:make-pointer
+              (+ (uffi:pointer-address arrayptr) (* string-index size))
+              :unsigned-char))))
+    (if (string-equal str "NULL") nil str)))
 
 ;; the OCI library, part Z: no-longer used logic to convert from
 ;; Oracle's binary date representation to Common Lisp's native date
@@ -295,30 +285,6 @@ the length of that format.")
                      table))))
     (mapcar #'car (database-query query database nil nil))))
 
-(defmethod list-all-table-columns (table (db oracle-database))
-  (declare (string table))
-  (let* ((sql-stmt (concatenate
-                   'simple-string
-                   "select "
-                   "'',"
-                   "all_tables.OWNER,"
-                   "'',"
-                   "user_tab_columns.COLUMN_NAME,"
-                   "user_tab_columns.DATA_TYPE from user_tab_columns,"
-                   "all_tables where all_tables.table_name = '" table "'"
-                   " and user_tab_columns.table_name = '" table "'"))
-        (preresult (database-query sql-stmt db :auto nil)))
-    ;; PRERESULT is like RESULT except that it has a name instead of
-    ;; type codes in the fifth column of each row. To fix this, we
-    ;; destructively modify PRERESULT.
-    (dolist (preresult-row preresult)
-      (setf (fifth preresult-row)
-           (if (find (fifth preresult-row)
-                     #("NUMBER" "DATE")
-                     :test #'string=)
-               2 ; numeric
-               1))) ; string
-    preresult))
 
 (defmethod database-list-attributes (table (database oracle-database) &key owner)
   (let ((query
@@ -600,20 +566,24 @@ the length of that format.")
 ;; debugging only
             
 
+(uffi:def-type byte-pointer (* :byte))
+(uffi:def-type ulong-pointer (* :unsigned-long))
+(uffi:def-type void-pointer-pointer (* :void-pointer))
+
 (defun make-query-cursor-cds (database stmthp result-types field-names)
   (declare (optimize (safety 3) #+nil (speed 3))
           (type oracle-database database)
           (type pointer-pointer-void stmthp))
   (with-slots (errhp) database
     (uffi:with-foreign-objects ((dtype-foreign :unsigned-short)
-                          (parmdp ':pointer-void)
-                          (precision :byte)
-                          (scale :byte)
-                          (colname '(* :unsigned-char))
-                          (colnamelen :unsigned-long)
-                          (colsize :unsigned-long)
-                          (colsizesize :unsigned-long)
-                          (defnp ':pointer-void))
+                               (parmdp :pointer-void)
+                               (precision :byte)
+                               (scale :byte)
+                               (colname '(* :unsigned-char))
+                               (colnamelen :unsigned-long)
+                               (colsize :unsigned-long)
+                               (colsizesize :unsigned-long)
+                               (defnp ':pointer-void))
       (let ((buffer nil)
            (sizeof nil))
        (do ((icolumn 0 (1+ icolumn))
@@ -634,6 +604,7 @@ the length of that format.")
                        +oci-attr-data-type+
                        (deref-vp errhp))
          (let ((dtype (uffi:deref-pointer dtype-foreign :unsigned-short)))
+           (declare (fixnum dtype))
            (case dtype
              (#.SQLT-DATE
               (setf buffer (acquire-foreign-resource :unsigned-char
@@ -654,9 +625,10 @@ the length of that format.")
                             (deref-vp errhp))
               (let ((*scale (uffi:deref-pointer scale :byte))
                     (*precision (uffi:deref-pointer precision :byte)))
-                ;;(format t "scale=~d, precision=~d~%" *scale *precision)
+                
+                ;; (format t "scale=~d, precision=~d~%" *scale *precision)
                 (cond
-                 ((or (zerop *scale)
+                 ((or (and (zerop *scale) (not (zerop *precision)))
                       (and (minusp *scale) (< *precision 10)))
                   (setf buffer (acquire-foreign-resource :int +n-buf-rows+)
                         sizeof 4                       ;; sizeof(int)
@@ -664,11 +636,11 @@ the length of that format.")
                  (t
                   (setf buffer (acquire-foreign-resource :double +n-buf-rows+)
                         sizeof 8                   ;; sizeof(double)
-                        dtype #.SQLT-FLT))))          )
+                        dtype #.SQLT-FLT)))))
              ;; Default to SQL-STR
-             (t                
-              (setf (uffi:deref-pointer colsize :unsigned-long) 0
-                    dtype #.SQLT-STR)
+             (t
+              (setf (uffi:deref-pointer colsize :unsigned-long) 0)
+              (setf dtype #.SQLT-STR)
               (oci-attr-get (deref-vp parmdp)
                             +oci-dtype-param+ 
                             colsize
@@ -838,7 +810,9 @@ the length of that format.")
        (setf (slot-value db 'clsql-sys::state) :open)
         (database-execute-command
         (format nil "ALTER SESSION SET NLS_DATE_FORMAT='~A'" (date-format db)) db)
-       (let ((server-version (caar (database-query "SELECT BANNER FROM V$VERSION WHERE BANNER LIKE '%Oracle%'" db nil nil))))
+       (let ((server-version
+              (caar (database-query
+                     "SELECT BANNER FROM V$VERSION WHERE BANNER LIKE '%Oracle%'" db nil nil))))
          (setf (slot-value db 'server-version) server-version
                (slot-value db 'major-server-version) (major-client-version-from-string
                                                       server-version)))
@@ -907,18 +881,14 @@ the length of that format.")
          (push row reversed-result))))))
 
 
-(defmethod database-create-sequence
-  (sequence-name (database oracle-database))
+(defmethod database-create-sequence (sequence-name (database oracle-database))
   (execute-command
-   (concatenate 'string "CREATE SEQUENCE "
-               (sql-escape sequence-name))
+   (concatenate 'string "CREATE SEQUENCE " (sql-escape sequence-name))
    :database database))
 
-(defmethod database-drop-sequence
-  (sequence-name (database oracle-database))
+(defmethod database-drop-sequence (sequence-name (database oracle-database))
   (execute-command
-   (concatenate 'string "DROP SEQUENCE "
-               (sql-escape sequence-name))
+   (concatenate 'string "DROP SEQUENCE " (sql-escape sequence-name))
    :database database))
 
 (defmethod database-sequence-next (sequence-name (database oracle-database))
@@ -930,16 +900,17 @@ the length of that format.")
                 )
     database :auto nil)))
 
-(defmethod database-set-sequence-position (name position database)
-  (let* ((next (database-sequence-next name database))
-        (incr (- position next)))
-    (database-execute-command
-     (format nil "ALTER SEQUENCE ~A INCREMENT BY ~D" name incr)
-     database)
-    (database-sequence-next name database)
-    (database-execute-command
-     (format nil "ALTER SEQUENCE ~A INCREMENT BY 1" name)
-     database)))
+(defmethod database-set-sequence-position (name position (database oracle-database))
+  (without-interrupts
+   (let* ((next (database-sequence-next name database))
+         (incr (- position next)))
+     (database-execute-command
+      (format nil "ALTER SEQUENCE ~A INCREMENT BY ~D" name incr)
+      database)
+     (database-sequence-next name database)
+     (database-execute-command
+      (format nil "ALTER SEQUENCE ~A INCREMENT BY 1" name)
+      database))))
 
 (defmethod database-list-sequences ((database oracle-database) &key owner)
   (let ((query
@@ -952,8 +923,8 @@ the length of that format.")
 
 (defmethod database-execute-command (sql-expression (database oracle-database))
   (database-query sql-expression database nil nil)
-  ;; HACK HACK HACK
-  (database-query "commit" database nil nil)
+  (when (database-autocommit database)
+    (oracle-commit database))
   t)
 
 
@@ -1021,54 +992,36 @@ the length of that format.")
          do (setf (nth i list) (nth i row)))
       list)))
 
-(defmethod clsql-sys:database-start-transaction ((database oracle-database))
-  (call-next-method))
+(defmethod database-start-transaction ((database oracle-database))
+  (call-next-method)
+  ;; Not needed with simple transaction
+  #+ignore
+  (with-slots (svchp errhp) database
+    (oci-trans-start (deref-vp svchp)
+                    (deref-vp errhp)
+                    60
+                    +oci-trans-new+))
+  t)
 
-;;(with-slots (svchp errhp) database
-;;    (osucc (oci-trans-start (uffi:deref-pointer svchp)
-;;                         (uffi:deref-pointer errhp)
-;;                         60
-;;                         +oci-trans-new+)))
-;;  t)
-  
 
-(defmethod clsql-sys:database-commit-transaction ((database oracle-database))
-  (call-next-method)
+(defun oracle-commit (database)
   (with-slots (svchp errhp) database
-             (osucc (oci-trans-commit (deref-vp svchp)
-                                      (deref-vp errhp)
-                                      0)))
+    (osucc (oci-trans-commit (deref-vp svchp)
+                            (deref-vp errhp)
+                            0))))
+
+(defmethod database-commit-transaction ((database oracle-database))
+  (call-next-method)
+  (oracle-commit database)
   t)
 
-(defmethod clsql-sys:database-abort-transaction ((database oracle-database))
+(defmethod database-abort-transaction ((database oracle-database))
   (call-next-method)
   (osucc (oci-trans-rollback (deref-vp (svchp database))
                             (deref-vp (errhp database))
                             0))
   t)
 
-(defparameter *constraint-types*
-  '(("NOT-NULL" . "NOT NULL")))
-
-(defmethod database-output-sql ((str string) (database oracle-database))
-  (if (and (null (position #\' str))
-          (null (position #\\ str)))
-      (format nil "'~A'" str)
-    (let* ((l (length str))
-          (buf (make-string (+ l 3))))
-      (setf (aref buf 0) #\')
-      (do ((i 0 (incf i))
-          (j 1 (incf j)))
-         ((= i l) (setf (aref buf j) #\'))
-       (if (= j (- (length buf) 1))
-           (setf buf (adjust-array buf (+ (length buf) 1))))
-       (cond ((eql (aref str i) #\')
-              (setf (aref buf j) #\')
-              (incf j)))
-       (setf (aref buf j) (aref str i)))
-      buf)))
-
-
 ;; Specifications
 
 (defmethod db-type-has-bigint? ((type (eql :oracle)))