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