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