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