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