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