r9019: odbc updates
[clsql.git] / db-odbc / odbc-api.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: odbc -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:     odbc-api.lisp
6 ;;;; Purpose:  Low-level ODBC API using UFFI
7 ;;;; Authors:  Kevin M. Rosenberg and Paul Meurer
8 ;;;;
9 ;;;; $Id: odbc-package.lisp 7061 2003-09-07 06:34:45Z kevin $
10 ;;;;
11 ;;;; This file, part of CLSQL, is Copyright (c) 2004 by Kevin M. Rosenberg
12 ;;;; and Copyright (C) Paul Meurer 1999 - 2001. All rights reserved.
13 ;;;;
14 ;;;; CLSQL users are granted the rights to distribute and use this software
15 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
16 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
17 ;;;; *************************************************************************
18
19 (in-package #:odbc)
20
21 (defvar *null* nil
22   "Lisp representation of SQL Null value, default = nil.
23 May be locally bound to something else if a certain type is necessary.")
24  
25
26 (defvar *binary-format* :unsigned-byte-vector)
27 (defvar *time-conversion-function* (lambda (universal-time &optional fraction)
28                                      (declare (ignore fraction))
29                                      universal-time)
30    "Bound to a function that converts from a Lisp universal time fixnum (and a fractional
31 as possible second argument) to the desired representation of date/time/timestamp.")
32
33 (defvar +null-ptr+ (make-null-pointer :byte))
34 (defvar *info-output* nil
35   "Stream to send SUCCESS_WITH_INFO messages.")
36
37 (defmacro %put-str (ptr string &optional max-length)
38   (let ((size (gensym)))
39     `(let ((,size (length ,string)))
40        (when (and ,max-length (> ,size ,max-length))
41          (error "string \"~a\" of length ~d is longer than max-length: ~d"
42                 ,string ,size ,max-length))
43       (with-cast-pointer (char-ptr ,ptr :byte)
44         (dotimes (i ,size)
45           (setf (deref-array char-ptr '(:array :byte) i) 
46                 (char-code (char ,string i))))
47         (setf (deref-array char-ptr '(:array :byte) ,size) 0)))))
48
49 (defun %cstring-into-vector (ptr vector offset size-in-bytes)
50   (dotimes (i size-in-bytes)
51     (setf (schar vector offset)
52       (ensure-char-character
53        (deref-array ptr '(:array :unsigned-char) i)))
54     (incf offset))
55   offset)
56   
57 (defun handle-error (henv hdbc hstmt)
58   (let ((sql-state (allocate-foreign-string 256))
59         (error-message (allocate-foreign-string $SQL_MAX_MESSAGE_LENGTH)))
60     (with-foreign-objects ((error-code :long)
61                            (msg-length :short))
62       (SQLError henv hdbc hstmt sql-state
63                 error-code error-message
64                 $SQL_MAX_MESSAGE_LENGTH msg-length)
65       (values
66        (prog1
67            (convert-from-foreign-string error-message)
68          (free-foreign-object error-message))
69        (prog1 
70            (convert-from-foreign-string sql-state)
71          (free-foreign-object error-message))
72        (deref-pointer msg-length :short) 
73        (deref-pointer error-code :long)))))
74
75 (defun sql-state (henv hdbc hstmt)
76   (let ((sql-state (allocate-foreign-string 256))
77         (error-message (allocate-foreign-string $SQL_MAX_MESSAGE_LENGTH)))
78     (with-foreign-objects ((error-code :long)
79                            (msg-length :short))
80       (SQLError henv hdbc hstmt sql-state error-code
81                 error-message $SQL_MAX_MESSAGE_LENGTH msg-length)
82       (free-foreign-object error-message)
83       (prog1
84           (convert-from-foreign-string sql-state) 
85         (free-foreign-object sql-state)))
86     ;; test this: return a keyword for efficiency
87     ;;(%cstring-to-keyword sql-state)
88     ))
89
90 (defmacro with-error-handling ((&key henv hdbc hstmt (print-info t))
91                                    odbc-call &body body)
92   (let ((result-code (gensym "RC-")))
93     `(let ((,result-code ,odbc-call))
94        (case ,result-code
95          (#.$SQL_SUCCESS
96           (progn ,result-code ,@body))
97          (#.$SQL_SUCCESS_WITH_INFO
98           (when ,print-info
99             (multiple-value-bind (error-message sql-state)
100                 (handle-error (or ,henv +null-ptr+)
101                               (or ,hdbc +null-ptr+)
102                               (or ,hstmt +null-ptr+))
103               (when *info-output*
104                 (format *info-output* "[ODBC info ~A] ~A state: ~A"
105                         ,result-code error-message
106                         sql-state))))
107           (progn ,result-code ,@body))
108          (#.$SQL_INVALID_HANDLE
109           (error
110            'clsql-base-sys:clsql-odbc-error
111            :odbc-message "Invalid handle"))
112          (#.$SQL_STILL_EXECUTING
113           (error
114            'clsql-base-sys:clsql-odbc-error
115            :odbc-message "Still executing"))
116          (#.$SQL_ERROR
117           (multiple-value-bind (error-message sql-state)
118               (handle-error (or ,henv +null-ptr+)
119                             (or ,hdbc +null-ptr+)
120                             (or ,hstmt +null-ptr+))
121             (error
122              'clsql-base-sys:clsql-odbc-error
123              :odbc-message error-message
124              :sql-state sql-state)))
125          (otherwise
126           (progn ,result-code ,@body))))))
127
128 (defun %new-environment-handle ()
129   (let ((henv
130          (with-foreign-object (phenv 'sql-handle)
131            (with-error-handling
132                ()
133              (SQLAllocEnv phenv)
134              (deref-pointer phenv 'sql-handle)))))
135     (%set-attr-odbc-version henv $SQL_OV_ODBC2)
136     henv))
137
138
139 (defun %sql-free-environment (henv)
140   (with-error-handling 
141     (:henv henv)
142     (SQLFreeEnv henv)))
143
144 (defun %new-db-connection-handle (henv)
145   (with-foreign-object (phdbc 'sql-handle)
146     (with-error-handling
147       (:henv henv)
148       (SQLAllocConnect henv phdbc)
149       (deref-pointer phdbc 'sql-handle))))
150
151 (defun %free-statement (hstmt option)
152   (with-error-handling 
153       (:hstmt hstmt)
154       (SQLFreeStmt 
155        hstmt 
156        (ecase option
157          (:drop $SQL_DROP)
158          (:close $SQL_CLOSE)
159          (:unbind $SQL_UNBIND)
160          (:reset $SQL_RESET_PARAMS)))))
161
162 (defmacro with-statement-handle ((hstmt hdbc) &body body)
163   `(let ((,hstmt (%new-statement-handle ,hdbc)))
164      (unwind-protect
165        (progn ,@body)
166        (%free-statement ,hstmt :drop))))
167
168 ;; functional interface
169
170 (defun %sql-connect (hdbc server uid pwd)
171   (with-cstrings ((server-ptr server)
172                   (uid-ptr uid)
173                   (pwd-ptr pwd))
174     (with-error-handling 
175         (:hdbc hdbc)
176       (SQLConnect hdbc server-ptr $SQL_NTS uid-ptr 
177                   $SQL_NTS pwd-ptr $SQL_NTS))))
178
179
180 (defun %disconnect (hdbc)
181   (with-error-handling 
182     (:hdbc hdbc)
183     (SQLDisconnect hdbc)))
184
185 (defun %commit (henv hdbc)
186   (with-error-handling 
187     (:henv henv :hdbc hdbc)
188     (SQLTransact 
189      henv hdbc $SQL_COMMIT)))
190
191 (defun %rollback (henv hdbc)
192   (with-error-handling 
193     (:henv henv :hdbc hdbc)
194     (SQLTransact 
195      henv hdbc $SQL_ROLLBACK)))
196
197 ; col-nr is zero-based in Lisp
198 ; col-nr = :bookmark retrieves a bookmark.
199 (defun %bind-column (hstmt column-nr c-type data-ptr precision out-len-ptr)
200   (with-error-handling
201     (:hstmt hstmt)
202     (SQLBindCol hstmt
203                 (if (eq column-nr :bookmark) 0 (1+ column-nr))
204                 c-type data-ptr precision out-len-ptr)))
205
206 ; parameter-nr is zero-based in Lisp
207 (defun %sql-bind-parameter (hstmt parameter-nr parameter-type c-type
208                                       sql-type precision scale data-ptr
209                                       max-value out-len-ptr)
210   (with-error-handling
211     (:hstmt hstmt)
212     (SQLBindParameter hstmt (1+ parameter-nr)
213                       parameter-type ;$SQL_PARAM_INPUT 
214                       c-type ;$SQL_C_CHAR
215                       sql-type ;$SQL_VARCHAR
216                       precision ;(1- (length str))
217                       scale ;0
218                       data-ptr
219                       max-value
220                       out-len-ptr ;#.+null-ptr+
221                       )))
222
223 (defun %sql-fetch (hstmt)
224   (with-error-handling 
225       (:hstmt hstmt)
226       (SQLFetch hstmt)))
227
228 (defun %new-statement-handle (hdbc)
229   (with-foreign-object (hstmt-ptr 'sql-handle)
230     (with-error-handling 
231       (:hdbc hdbc)
232       (SQLAllocStmt hdbc hstmt-ptr) 
233       (deref-pointer hstmt-ptr 'sql-handle))))
234
235 (defun %sql-get-info (hdbc info-type)
236   (ecase info-type
237     ;; those return string
238     ((#.$SQL_ACCESSIBLE_PROCEDURES
239       #.$SQL_ACCESSIBLE_TABLES
240       #.$SQL_COLUMN_ALIAS
241       #.$SQL_DATA_SOURCE_NAME
242       #.$SQL_DATA_SOURCE_READ_ONLY
243       #.$SQL_DBMS_NAME
244       #.$SQL_DBMS_VER
245       #.$SQL_DRIVER_NAME
246       #.$SQL_DRIVER_ODBC_VER
247       #.$SQL_DRIVER_VER
248       #.$SQL_EXPRESSIONS_IN_ORDERBY
249       #.$SQL_IDENTIFIER_QUOTE_CHAR
250       #.$SQL_KEYWORDS
251       #.$SQL_LIKE_ESCAPE_CLAUSE
252       #.$SQL_MAX_ROW_SIZE_INCLUDES_LONG
253       #.$SQL_MULT_RESULT_SETS
254       #.$SQL_MULTIPLE_ACTIVE_TXN
255       #.$SQL_NEED_LONG_DATA_LEN
256       #.$SQL_ODBC_SQL_OPT_IEF
257       #.$SQL_ODBC_VER
258       #.$SQL_ORDER_BY_COLUMNS_IN_SELECT
259       #.$SQL_OUTER_JOINS
260       #.$SQL_OWNER_TERM
261       #.$SQL_PROCEDURE_TERM
262       #.$SQL_PROCEDURES
263       #.$SQL_QUALIFIER_NAME_SEPARATOR
264       #.$SQL_QUALIFIER_TERM
265       #.$SQL_ROW_UPDATES
266       #.$SQL_SEARCH_PATTERN_ESCAPE
267       #.$SQL_SERVER_NAME
268       #.$SQL_SPECIAL_CHARACTERS
269       #.$SQL_TABLE_TERM
270       #.$SQL_USER_NAME)
271      (let ((info-ptr (allocate-foreign-string 1024))) 
272        (with-foreign-object (info-length-ptr :short)
273          (with-error-handling 
274              (:hdbc hdbc)
275              (SQLGetInfo hdbc info-type info-ptr 1023 info-length-ptr)
276            (prog1
277                (convert-from-foreign-string info-ptr)
278              (free-foreign-object info-ptr))))))
279     ;; those returning a word
280     ((#.$SQL_ACTIVE_CONNECTIONS
281       #.$SQL_ACTIVE_STATEMENTS
282       #.$SQL_CONCAT_NULL_BEHAVIOR
283       #.$SQL_CORRELATION_NAME
284       #.$SQL_CURSOR_COMMIT_BEHAVIOR
285       #.$SQL_CURSOR_ROLLBACK_BEHAVIOR
286       #.$SQL_MAX_COLUMN_NAME_LEN
287       #.$SQL_MAX_COLUMNS_IN_GROUP_BY
288       #.$SQL_MAX_COLUMNS_IN_INDEX
289       #.$SQL_MAX_COLUMNS_IN_ORDER_BY
290       #.$SQL_MAX_COLUMNS_IN_SELECT
291       #.$SQL_MAX_COLUMNS_IN_TABLE
292       #.$SQL_MAX_CURSOR_NAME_LEN
293       #.$SQL_MAX_OWNER_NAME_LEN
294       #.$SQL_MAX_PROCEDURE_NAME_LEN
295       #.$SQL_MAX_QUALIFIER_NAME_LEN
296       #.$SQL_MAX_TABLE_NAME_LEN
297       #.$SQL_MAX_TABLES_IN_SELECT
298       #.$SQL_MAX_USER_NAME_LEN
299       #.$SQL_NON_NULLABLE_COLUMNS
300       #.$SQL_NULL_COLLATION
301       #.$SQL_ODBC_API_CONFORMANCE
302       #.$SQL_ODBC_SAG_CLI_CONFORMANCE
303       #.$SQL_ODBC_SQL_CONFORMANCE
304       #.$SQL_QUALIFIER_LOCATION
305       #.$SQL_QUOTED_IDENTIFIER_CASE
306       #.$SQL_TXN_CAPABLE)
307      (with-foreign-objects ((info-ptr :short)
308                             (info-length-ptr :short))
309        (with-error-handling 
310         (:hdbc hdbc)
311          (SQLGetInfo hdbc
312                      info-type
313                      info-ptr
314                      255
315                      info-length-ptr)
316          (deref-pointer info-ptr :short)))
317      )
318     ;; those returning a long bitmask
319     ((#.$SQL_ALTER_TABLE 
320       #.$SQL_BOOKMARK_PERSISTENCE
321       #.$SQL_CONVERT_BIGINT
322       #.$SQL_CONVERT_BINARY
323       #.$SQL_CONVERT_BIT
324       #.$SQL_CONVERT_CHAR
325       #.$SQL_CONVERT_DATE
326       #.$SQL_CONVERT_DECIMAL
327       #.$SQL_CONVERT_DOUBLE
328       #.$SQL_CONVERT_FLOAT
329       #.$SQL_CONVERT_INTEGER
330       #.$SQL_CONVERT_LONGVARCHAR
331       #.$SQL_CONVERT_NUMERIC
332       #.$SQL_CONVERT_REAL
333       #.$SQL_CONVERT_SMALLINT
334       #.$SQL_CONVERT_TIME
335       #.$SQL_CONVERT_TIMESTAMP
336       #.$SQL_CONVERT_TINYINT
337       #.$SQL_CONVERT_VARBINARY
338       #.$SQL_CONVERT_VARCHAR
339       #.$SQL_CONVERT_LONGVARBINARY
340       #.$SQL_CONVERT_FUNCTIONS
341       #.$SQL_FETCH_DIRECTION
342       #.$SQL_FILE_USAGE
343       #.$SQL_GETDATA_EXTENSIONS
344       #.$SQL_LOCK_TYPES
345       #.$SQL_MAX_INDEX_SIZE
346       #.$SQL_MAX_ROW_SIZE
347       #.$SQL_MAX_STATEMENT_LEN
348       #.$SQL_NUMERIC_FUNCTIONS
349       #.$SQL_OWNER_USAGE
350       #.$SQL_POS_OPERATIONS
351       #.$SQL_POSITIONED_STATEMENTS
352       #.$SQL_QUALIFIER_USAGE
353       #.$SQL_SCROLL_CONCURRENCY
354       #.$SQL_SCROLL_OPTIONS
355       #.$SQL_STATIC_SENSITIVITY
356       #.$SQL_STRING_FUNCTIONS
357       #.$SQL_SUBQUERIES
358       #.$SQL_SYSTEM_FUNCTIONS
359       #.$SQL_TIMEDATE_ADD_INTERVALS
360       #.$SQL_TIMEDATE_DIFF_INTERVALS
361       #.$SQL_TIMEDATE_FUNCTIONS
362       #.$SQL_TXN_ISOLATION_OPTION
363       #.$SQL_UNION)
364      (with-foreign-objects ((info-ptr :long)
365                             (info-length-ptr :short))
366        (with-error-handling 
367          (:hdbc hdbc)
368          (SQLGetInfo hdbc
369                      info-type
370                      info-ptr
371                      255
372                      info-length-ptr)
373          (deref-pointer info-ptr :long)))
374      )
375     ;; those returning a long integer
376     ((#.$SQL_DEFAULT_TXN_ISOLATION
377       #.$SQL_DRIVER_HDBC
378       #.$SQL_DRIVER_HENV
379       #.$SQL_DRIVER_HLIB
380       #.$SQL_DRIVER_HSTMT
381       #.$SQL_GROUP_BY
382       #.$SQL_IDENTIFIER_CASE
383       #.$SQL_MAX_BINARY_LITERAL_LEN
384       #.$SQL_MAX_CHAR_LITERAL_LEN
385       #.$SQL_ACTIVE_ENVIRONMENTS
386       )
387      (with-foreign-objects ((info-ptr :long)
388                             (info-length-ptr :short))
389        (with-error-handling 
390          (:hdbc hdbc)
391          (SQLGetInfo hdbc info-type info-ptr 255 info-length-ptr)
392          (deref-pointer info-ptr :long))))))
393      
394 (defun %sql-exec-direct (sql hstmt henv hdbc)
395   (with-cstring (sql-ptr sql)
396     (with-error-handling
397       (:hstmt hstmt :henv henv :hdbc hdbc)
398       (SQLExecDirect hstmt sql-ptr $SQL_NTS))))
399
400 (defun %sql-cancel (hstmt)
401   (with-error-handling
402     (:hstmt hstmt)
403     (SQLCancel hstmt)))
404
405 (defun %sql-execute (hstmt)
406   (with-error-handling
407     (:hstmt hstmt)
408     (SQLExecute hstmt)))
409
410 (defun result-columns-count (hstmt)
411   (with-foreign-objects ((columns-nr-ptr :short))
412     (with-error-handling (:hstmt hstmt)
413                          (SQLNumResultCols hstmt columns-nr-ptr)
414       (deref-pointer columns-nr-ptr :short))))
415
416 (defun result-rows-count (hstmt)
417   (with-foreign-objects ((row-count-ptr :long))
418     (with-error-handling (:hstmt hstmt)
419                          (SQLRowCount hstmt row-count-ptr)
420       (deref-pointer row-count-ptr :long))))
421
422 ;; column counting is 1-based
423 (defun %describe-column (hstmt column-nr)
424   (let ((column-name-ptr (allocate-foreign-string 256)))
425     (with-foreign-objects ((column-name-length-ptr :short)
426                            (column-sql-type-ptr :short)
427                            (column-precision-ptr :long)
428                            (column-scale-ptr :short)
429                            (column-nullable-p-ptr :short))
430       (with-error-handling (:hstmt hstmt)
431           (SQLDescribeCol hstmt column-nr column-name-ptr 256
432                           column-name-length-ptr
433                           column-sql-type-ptr
434                           column-precision-ptr
435                           column-scale-ptr
436                           column-nullable-p-ptr)
437         (let ((column-name (convert-from-foreign-string column-name-ptr)))
438           (free-foreign-object column-name-ptr)
439           (values
440            column-name
441            (deref-pointer column-sql-type-ptr :short)
442            (deref-pointer column-precision-ptr :long)
443            (deref-pointer column-scale-ptr :short)
444            (deref-pointer column-nullable-p-ptr :short)))))))
445     
446 ;; parameter counting is 1-based
447 (defun %describe-parameter (hstmt parameter-nr)
448   (with-foreign-objects ((column-sql-type-ptr :short)
449                          (column-precision-ptr :long)
450                          (column-scale-ptr :short)
451                          (column-nullable-p-ptr :short))
452     (with-error-handling 
453       (:hstmt hstmt)
454       (SQLDescribeParam hstmt parameter-nr
455                         column-sql-type-ptr
456                         column-precision-ptr
457                         column-scale-ptr
458                         column-nullable-p-ptr)
459       (values
460        (deref-pointer column-sql-type-ptr :short)
461        (deref-pointer column-precision-ptr :long)
462        (deref-pointer column-scale-ptr :short)
463        (deref-pointer column-nullable-p-ptr :short)))))
464
465 (defun %column-attributes (hstmt column-nr descriptor-type)
466   (let ((descriptor-info-ptr (allocate-foreign-string 256)))
467     (with-foreign-objects ((descriptor-length-ptr :short)
468                            (numeric-descriptor-ptr :long))
469       (with-error-handling
470           (:hstmt hstmt) 
471           (SQLColAttributes hstmt column-nr descriptor-type descriptor-info-ptr
472                             256 descriptor-length-ptr
473                             numeric-descriptor-ptr)
474         (values
475          (prog1
476              (convert-from-foreign-string descriptor-info-ptr)
477            (free-foreign-object descriptor-info-ptr))
478          (deref-pointer numeric-descriptor-ptr :long))))))
479   
480 (defun %prepare-describe-columns (hstmt table-qualifier table-owner 
481                                    table-name column-name)
482   (with-cstrings ((table-qualifier-ptr table-qualifier)
483                   (table-owner-ptr table-owner) 
484                   (table-name-ptr table-name)
485                   (column-name-ptr column-name))
486     (with-error-handling
487         (:hstmt hstmt) 
488       (SQLColumns hstmt
489                   table-qualifier-ptr (length table-qualifier)
490                   table-owner-ptr (length table-owner)
491                   table-name-ptr (length table-name)
492                   column-name-ptr (length column-name)))))
493
494 (defun %describe-columns (hdbc table-qualifier table-owner 
495                           table-name column-name)
496   (with-statement-handle (hstmt hdbc)
497     (%prepare-describe-columns hstmt table-qualifier table-owner 
498                                table-name column-name)
499     (fetch-all-rows hstmt)))
500
501 (defun %sql-data-sources (henv &key (direction :first))
502   (let ((name-ptr (allocate-foreign-string (1+ $SQL_MAX_DSN_LENGTH)))
503         (description-ptr (allocate-foreign-string 1024)))
504     (with-foreign-objects ((name-length-ptr :short)
505                            (description-length-ptr :short))
506       (let ((res (with-error-handling
507                      (:henv henv)
508                      (SQLDataSources henv
509                                      (ecase direction
510                                        (:first $SQL_FETCH_FIRST)
511                                        (:next $SQL_FETCH_NEXT))
512                                      name-ptr
513                                      (1+ $SQL_MAX_DSN_LENGTH)
514                                      name-length-ptr
515                                      description-ptr
516                                      1024
517                                      description-length-ptr))))
518         (unless (= res $SQL_NO_DATA_FOUND)
519           (values 
520            (prog1 
521                (convert-from-foreign-string name-ptr)
522              (free-foreign-object name-ptr))
523            (prog1
524                (convert-from-foreign-string description-ptr)
525              (free-foreign-object description-ptr))))))))
526
527 (defun sql-to-c-type (sql-type)
528   (ecase sql-type
529     ((#.$SQL_CHAR #.$SQL_VARCHAR #.$SQL_LONGVARCHAR 
530       #.$SQL_NUMERIC #.$SQL_DECIMAL #.$SQL_BIGINT -8 -9) $SQL_C_CHAR)
531     (#.$SQL_INTEGER $SQL_C_SLONG)
532     (#.$SQL_SMALLINT $SQL_C_SSHORT)
533     (#.$SQL_DOUBLE $SQL_C_DOUBLE)
534     (#.$SQL_FLOAT $SQL_C_DOUBLE)
535     (#.$SQL_REAL $SQL_C_FLOAT)
536     (#.$SQL_DATE $SQL_C_DATE)
537     (#.$SQL_TIME $SQL_C_TIME)
538     (#.$SQL_TIMESTAMP $SQL_C_TIMESTAMP)
539     ((#.$SQL_BINARY #.$SQL_VARBINARY #.$SQL_LONGVARBINARY) $SQL_C_BINARY)
540     (#.$SQL_TINYINT $SQL_C_STINYINT)
541     (#.$SQL_BIT $SQL_C_BIT)))
542
543 (def-type byte-pointer-type '(* :byte))
544 (def-type short-pointer-type '(* :short))
545 (def-type int-pointer-type '(* :int))
546 (def-type long-pointer-type '(* :long))
547 (def-type float-pointer-type '(* :float))
548 (def-type double-pointer-type '(* :double))
549 (def-type string-pointer-type '(* :unsigned-char))
550
551 (defun get-cast-byte (ptr)
552   (locally (declare (type byte-pointer-type ptr))
553     (deref-pointer ptr :byte)))
554
555 (defun get-cast-short (ptr)
556   (locally (declare (type short-pointer-type ptr))
557     (deref-pointer ptr :short)))
558
559 (defun get-cast-int (ptr)
560   (locally (declare (type int-pointer-type ptr))
561     (deref-pointer ptr :int)))
562
563 (defun get-cast-long (ptr)
564   (locally (declare (type long-pointer-type ptr))
565     (deref-pointer ptr :long)))
566
567 (defun get-cast-single-float (ptr)
568   (locally (declare (type float-pointer-type ptr))
569     (deref-pointer ptr :float)))
570
571 (defun get-cast-double-float (ptr)
572   (locally (declare (type double-pointer-type ptr))
573     (deref-pointer ptr :double)))
574
575 (defun get-cast-foreign-string (ptr)
576   (locally (declare (type string-pointer-type ptr))
577     (convert-from-foreign-string ptr)))
578
579 (defun get-cast-binary (ptr len format)
580   "FORMAT is one of :unsigned-byte-vector, :bit-vector (:string, :hex-string)"
581   (with-cast-pointer (casted ptr :byte)
582     (ecase format
583       (:unsigned-byte-vector
584        (let ((vector (make-array len :element-type '(unsigned-byte 8))))
585          (dotimes (i len)
586            (setf (aref vector i)
587                  (deref-array casted '(:array :byte) i)))
588          vector))
589       (:bit-vector
590        (let ((vector (make-array (ash len 3) :element-type 'bit)))
591          (dotimes (i len)
592            (let ((byte (deref-array casted '(:array :byte) i)))
593              (dotimes (j 8)
594                (setf (bit vector (+ (ash i 3) j))
595                      (logand (ash byte (- j 7)) 1)))))
596          vector)))))
597
598
599 (defun read-data (data-ptr c-type sql-type out-len-ptr result-type)
600   (declare (type long-ptr-type out-len-ptr))
601   (let* ((out-len (deref-pointer out-len-ptr :long))
602          (value
603           (cond ((= out-len $SQL_NULL_DATA)
604                  *null*)
605                 (t
606                  (case sql-type
607                    ;; SQL extended datatypes
608                    (#.$SQL_TINYINT  (get-cast-byte data-ptr))
609                    (#.$SQL_C_STINYINT (get-cast-byte data-ptr)) ;; ?
610                    (#.$SQL_C_SSHORT (get-cast-short data-ptr)) ;; ?
611                    (#.$SQL_SMALLINT (get-cast-short data-ptr)) ;; ??
612                    (#.$SQL_INTEGER (get-cast-int data-ptr))
613                    (#.$SQL_BIGINT (read-from-string
614                                    (get-cast-foreign-string data-ptr)))
615                    (#.$SQL_TINYINT (get-cast-byte data-ptr))
616                    (#.$SQL_DECIMAL 
617                     (let ((*read-base* 10))
618                       (read-from-string (get-cast-foreign-string data-ptr))))
619                    (t 
620                     (case c-type
621                       (#.$SQL_C_DATE
622                        (funcall *time-conversion-function* (date-to-universal-time data-ptr)))
623                       (#.$SQL_C_TIME
624                        (multiple-value-bind (universal-time frac) (time-to-universal-time data-ptr)
625                          (funcall *time-conversion-function* universal-time frac)))
626                       (#.$SQL_C_TIMESTAMP
627                        (multiple-value-bind (universal-time frac) (timestamp-to-universal-time data-ptr)
628                          (funcall *time-conversion-function* universal-time frac)))
629                       (#.$SQL_INTEGER
630                        (get-cast-int data-ptr))
631                       (#.$SQL_C_FLOAT
632                        (get-cast-single-float data-ptr))
633                       (#.$SQL_C_DOUBLE
634                        (get-cast-double-float data-ptr))
635                       (#.$SQL_C_SLONG
636                        (get-cast-long data-ptr))
637                       #+lispworks
638                       (#.$SQL_C_BIT     ; encountered only in Access
639                        (get-cast-byte data-ptr))
640                       (#.$SQL_C_BINARY
641                        (get-cast-binary data-ptr out-len *binary-format*))
642                       ((#.$SQL_C_SSHORT #.$SQL_C_STINYINT) ; LMH short ints
643                        (get-cast-short data-ptr)) ; LMH
644                       #+ignore
645                       (#.$SQL_C_CHAR
646                        (code-char (get-cast-short data-ptr)))
647                       (t
648                        (get-cast-foreign-string data-ptr)))))))))
649     
650     ;; FIXME: this could be better optimized for types which use READ-FROM-STRING above
651     
652     (if (and (or (eq result-type t) (eq result-type :string))
653              (not (stringp value)))
654         (write-to-string value)
655       value)))
656
657 ;; which value is appropriate?
658 (defparameter +max-precision+  4001)
659
660 (defvar *break-on-unknown-data-type* t)
661
662 ;; C. Stacy's idea to factor this out
663 ;; "Make it easy to add new datatypes by making new subroutine %ALLOCATE-BINDINGS,
664 ;; so that I don't have to remember to make changes in more than one place.
665 ;; Just keep it in synch with READ-DATA."
666 (defun %allocate-bindings (sql-type precision)
667   (let* ((c-type (sql-to-c-type sql-type))
668          (size (if (zerop precision)
669                    +max-precision+ ;; if the precision cannot be determined
670                  (min precision +max-precision+)))
671          (long-p (= size +max-precision+))
672          (data-ptr
673           (case c-type ;; add more?
674             (#.$SQL_C_SLONG (uffi:allocate-foreign-object :long))
675             (#.$SQL_C_DATE (allocate-foreign-object 'sql-c-date))
676             (#.$SQL_C_TIME (allocate-foreign-object 'sql-c-time))
677             (#.$SQL_C_TIMESTAMP (allocate-foreign-object 'sql-c-timestamp))
678             (#.$SQL_C_FLOAT (uffi:allocate-foreign-object :float))
679             (#.$SQL_C_DOUBLE (uffi:allocate-foreign-object :double))
680             (#.$SQL_C_BIT (uffi:allocate-foreign-object :byte))
681             (#.$SQL_C_STINYINT (uffi:allocate-foreign-object :short))
682             (#.$SQL_C_SSHORT (uffi:allocate-foreign-object :short))
683             (#.$SQL_C_CHAR (uffi:allocate-foreign-string (1+ size)))
684             (#.$SQL_C_BINARY (uffi:allocate-foreign-string (1+ (* 2 size))))
685             (t 
686                 ;; Maybe should signal a restartable condition for this?
687                 (when *break-on-unknown-data-type*
688                   (break "SQL type is ~A, precision ~D, size ~D, C type is ~A" 
689                          sql-type precision size c-type))
690                 (uffi:allocate-foreign-object :byte (1+ size)))))
691          (out-len-ptr (uffi:allocate-foreign-object :long)))
692     (values c-type data-ptr out-len-ptr size long-p)))
693
694 (defun fetch-all-rows (hstmt &key free-option flatp)
695   (let ((column-count (result-columns-count hstmt)))
696     (unless (zerop column-count)
697       (let ((names (make-array column-count))
698             (sql-types (make-array column-count :element-type 'fixnum))
699             (c-types (make-array column-count :element-type 'fixnum))
700             (precisions (make-array column-count :element-type 'fixnum))
701             (data-ptrs (make-array column-count :initial-element nil))
702             (out-len-ptrs (make-array column-count :initial-element nil))
703             (scales (make-array column-count :element-type 'fixnum))
704             (nullables-p (make-array column-count :element-type 'fixnum)))
705         (unwind-protect
706           (values
707            (progn
708              (dotimes (col-nr column-count)
709                ;; get column information
710                (multiple-value-bind (name sql-type precision scale nullable-p)
711                                     (%describe-column hstmt (1+ col-nr))
712                  ;; allocate space to bind result rows to
713                  (multiple-value-bind (c-type data-ptr out-len-ptr)
714                      (%allocate-bindings sql-type precision)
715                    (%bind-column hstmt col-nr c-type data-ptr (1+ precision) out-len-ptr)
716                    (setf (svref names col-nr) name
717                          (aref sql-types col-nr) sql-type
718                          (aref c-types col-nr) (sql-to-c-type sql-type)
719                          (aref precisions col-nr) (if (zerop precision) 0 precision)
720                          (aref scales col-nr) scale
721                          (aref nullables-p col-nr) nullable-p
722                          (aref data-ptrs col-nr) data-ptr
723                          (aref out-len-ptrs col-nr) out-len-ptr))))
724              ;; the main loop
725              (prog1
726                (cond (flatp 
727                       (when (> column-count 1)
728                         (error "If more than one column is to be fetched, flatp has to be nil."))
729                       (loop until (= (%sql-fetch hstmt) $SQL_NO_DATA_FOUND)
730                             collect
731                             (read-data (aref data-ptrs 0) 
732                                        (aref c-types 0)
733                                        (aref sql-types 0)
734                                        (aref out-len-ptrs 0)
735                                        t)))
736                      (t
737                       (loop until (= (%sql-fetch hstmt) $SQL_NO_DATA_FOUND)
738                             collect
739                             (loop for col-nr from 0 to (1- column-count)
740                                   collect
741                                   (read-data (aref data-ptrs col-nr) 
742                                              (aref c-types col-nr)
743                                              (aref sql-types col-nr)
744                                              (aref out-len-ptrs col-nr)
745                                              t)))))))
746            names)
747           ;; dispose of memory etc
748           (when free-option (%free-statement hstmt free-option))
749           (dotimes (col-nr column-count)
750             (let ((data-ptr (aref data-ptrs col-nr))
751                   (out-len-ptr (aref out-len-ptrs col-nr)))
752               (when data-ptr (free-foreign-object data-ptr)) ; we *did* allocate them
753               (when out-len-ptr (free-foreign-object out-len-ptr)))))))))
754
755 ;; to do: factor out common parts, put the sceleton (the obligatory macro part)
756 ;; of %do-fetch into sql package (has been done)
757
758 (defun %sql-prepare (hstmt sql)
759   (with-cstring (sql-ptr sql)
760     (with-error-handling (:hstmt hstmt)
761       (SQLPrepare hstmt sql-ptr $SQL_NTS))))
762
763 ;; depending on option, we return a long int or a string; string not implemented
764 (defun get-connection-option (hdbc option)
765   (with-foreign-object (param-ptr :long)
766     (with-error-handling (:hdbc hdbc)
767                          (SQLGetConnectOption hdbc option param-ptr)
768       (deref-pointer param-ptr :long))))
769
770 (defun set-connection-option (hdbc option param)
771   (with-error-handling (:hdbc hdbc)
772     (SQLSetConnectOption hdbc option param)))
773
774 (defun disable-autocommit (hdbc)
775   (set-connection-option hdbc $SQL_AUTOCOMMIT $SQL_AUTOCOMMIT_OFF))
776
777 (defun enable-autocommit (hdbc)
778   (set-connection-option hdbc $SQL_AUTOCOMMIT $SQL_AUTOCOMMIT_ON))
779
780 (defun %sql-set-pos (hstmt row option lock)
781   (with-error-handling 
782     (:hstmt hstmt)
783     (SQLSetPos hstmt row option lock)))
784
785 (defun %sql-extended-fetch (hstmt fetch-type row)
786   (with-foreign-objects ((row-count-ptr :unsigned-long)
787                          (row-status-ptr :short))
788     (with-error-handling (:hstmt hstmt)
789       (SQLExtendedFetch hstmt fetch-type row row-count-ptr
790                         row-status-ptr)
791       (values (deref-pointer row-count-ptr :unsigned-long)
792               (deref-pointer row-status-ptr :short)))))
793
794 ; column-nr is zero-based
795 (defun %sql-get-data (hstmt column-nr c-type data-ptr precision out-len-ptr)
796   (with-error-handling
797     (:hstmt hstmt :print-info nil)
798     (SQLGetData hstmt (if (eq column-nr :bookmark) 0 (1+ column-nr))
799                 c-type data-ptr precision out-len-ptr)))
800
801 (defun %sql-param-data (hstmt param-ptr)
802   (with-error-handling (:hstmt hstmt :print-info t) ;; nil
803       (SQLParamData hstmt param-ptr)))
804
805 (defun %sql-put-data (hstmt data-ptr size)
806   (with-error-handling
807     (:hstmt hstmt :print-info t) ;; nil
808     (SQLPutData hstmt data-ptr size)))
809
810 (defconstant $sql-data-truncated (intern "01004" :keyword))
811
812 (defun read-data-in-chunks (hstmt column-nr data-ptr c-type sql-type 
813                                       out-len-ptr result-type)
814   (declare (type long-ptr-type out-len-ptr))
815   (let* ((res (%sql-get-data hstmt column-nr c-type data-ptr 
816                              +max-precision+ out-len-ptr))
817          (out-len (deref-pointer out-len-ptr :long))
818          (offset 0))
819     (case out-len
820       (#.$SQL_NULL_DATA
821        (return-from read-data-in-chunks *null*))
822       (#.$SQL_NO_TOTAL ;; don't know how long it is going to be
823        (let ((str (make-array 0 :element-type 'character :adjustable t)))
824          (loop do (if (= c-type #.$SQL_CHAR)
825                       (let ((data-length (foreign-string-length data-ptr)))
826                         (adjust-array str (+ offset data-length)
827                                       :initial-element #\?)
828                         (setf offset (%cstring-into-vector
829                                       data-ptr str 
830                                       offset 
831                                       data-length)))
832                     (error "wrong type. preliminary."))
833                while (and (= res $SQL_SUCCESS_WITH_INFO)
834                           (equal (sql-state +null-ptr+ +null-ptr+ hstmt)
835                                  "01004"))
836                do (setf res (%sql-get-data hstmt column-nr c-type data-ptr 
837                                            +max-precision+ out-len-ptr)))
838          (setf str (coerce str 'string))
839          (if (= sql-type $SQL_DECIMAL)
840              (let ((*read-base* 10))
841                (read-from-string str))
842            str)))
843       (otherwise
844        (let ((str (make-string out-len)))
845          (loop do (if (= c-type #.$SQL_CHAR)
846                       (setf offset (%cstring-into-vector ;string
847                                     data-ptr str 
848                                     offset 
849                                     (min out-len (1- +max-precision+))))
850                     (error "wrong type. preliminary."))
851                while 
852                (and (= res $SQL_SUCCESS_WITH_INFO)
853                     #+ingore(eq (sql-state +null-ptr+ +null-ptr+ hstmt)
854                                 $sql-data-truncated)
855                     (equal (sql-state +null-ptr+ +null-ptr+ hstmt)
856                            "01004"))
857                do (setf res (%sql-get-data hstmt column-nr c-type data-ptr 
858                                            +max-precision+ out-len-ptr)
859                         out-len (deref-pointer out-len-ptr :long)))
860          (if (= sql-type $SQL_DECIMAL)
861              (let ((*read-base* 10))
862                (read-from-string str))
863            str))))))
864
865 (def-type c-timestamp-ptr-type '(* (:struct sql-c-timestamp)))
866 (def-type c-time-ptr-type '(* (:struct sql-c-time)))
867 (def-type c-date-ptr-type '(* (:struct sql-c-date)))
868
869 (defun timestamp-to-universal-time (ptr)
870   (declare (type c-timestamp-ptr-type ptr))
871   (values
872    (encode-universal-time 
873     (get-slot-value ptr 'sql-c-timestamp 'second)
874     (get-slot-value ptr 'sql-c-timestamp 'minute)
875     (get-slot-value ptr 'sql-c-timestamp 'hour)
876     (get-slot-value ptr 'sql-c-timestamp 'day)
877     (get-slot-value ptr 'sql-c-timestamp 'month)
878     (get-slot-value ptr 'sql-c-timestamp 'year))
879    (get-slot-value ptr 'sql-c-timestamp 'fraction)))
880
881 (defun universal-time-to-timestamp (time &optional (fraction 0))
882   (multiple-value-bind (sec min hour day month year)
883       (decode-universal-time time)
884     (let ((ptr (allocate-foreign-object 'sql-c-timestamp)))
885       (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
886             (get-slot-value ptr 'sql-c-timestamp 'minute) min
887             (get-slot-value ptr 'sql-c-timestamp 'hour) hour
888             (get-slot-value ptr 'sql-c-timestamp 'day) day
889             (get-slot-value ptr 'sql-c-timestamp 'month) month
890             (get-slot-value ptr 'sql-c-timestamp 'year) year
891             (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
892       ptr)))
893
894 (defun %put-timestamp (ptr time &optional (fraction 0))
895   (declare (type c-timestamp-ptr-type ptr))
896   (multiple-value-bind (sec min hour day month year)
897       (decode-universal-time time)
898     (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
899           (get-slot-value ptr 'sql-c-timestamp 'minute) min
900           (get-slot-value ptr 'sql-c-timestamp 'hour) hour
901           (get-slot-value ptr 'sql-c-timestamp 'day) day
902           (get-slot-value ptr 'sql-c-timestamp 'month) month
903           (get-slot-value ptr 'sql-c-timestamp 'year) year
904           (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
905       ptr))
906
907 (defun date-to-universal-time (ptr)
908   (declare (type c-date-ptr-type ptr))
909   (encode-universal-time
910    0 0 0
911    (get-slot-value ptr 'sql-c-timestamp 'day)
912    (get-slot-value ptr 'sql-c-timestamp 'month)
913    (get-slot-value ptr 'sql-c-timestamp 'year)))
914
915 (defun time-to-universal-time (ptr)
916   (declare (type c-time-ptr-type ptr))
917   (encode-universal-time 
918    (get-slot-value ptr 'sql-c-timestamp 'second)
919    (get-slot-value ptr 'sql-c-timestamp 'minute)
920    (get-slot-value ptr 'sql-c-timestamp 'hour)
921    1 1 0))
922
923
924 ;;; Added by KMR
925
926 (defun %set-attr-odbc-version (henv version)
927   (with-error-handling (:henv henv)
928       (SQLSetEnvAttr henv $SQL_ATTR_ODBC_VERSION 
929                      (make-pointer version :void) 0)))
930
931 (defun %list-tables (hstmt)
932   (with-error-handling (:hstmt hstmt)
933     (SQLTables hstmt +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0)))