fixed bad SQL_C_SBIGINT call that must have been a bad merge
[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                    (#.$SQL_DECIMAL
677                     (let ((*read-base* 10))
678                       (read-from-string (get-cast-foreign-string data-ptr))))
679                    (#.$SQL_BIT (get-cast-byte data-ptr))
680                    (t
681                     (case c-type
682                       ((#.$SQL_C_DATE #.$SQL_C_TYPE_DATE)
683                        (funcall *time-conversion-function* (date-to-universal-time data-ptr)))
684                       ((#.$SQL_C_TIME #.$SQL_C_TYPE_TIME)
685                        (multiple-value-bind (universal-time frac) (time-to-universal-time data-ptr)
686                          (funcall *time-conversion-function* universal-time frac)))
687                       ((#.$SQL_C_TIMESTAMP #.$SQL_C_TYPE_TIMESTAMP)
688                        (multiple-value-bind (universal-time frac) (timestamp-to-universal-time data-ptr)
689                          (funcall *time-conversion-function* universal-time frac)))
690                       (#.$SQL_INTEGER
691                        (get-cast-int data-ptr))
692                       (#.$SQL_C_FLOAT
693                        (get-cast-single-float data-ptr))
694                       (#.$SQL_C_DOUBLE
695                        (get-cast-double-float data-ptr))
696                       (#.$SQL_C_SLONG
697                        (get-cast-long data-ptr))
698                       #+lispworks
699                       (#.$SQL_C_BIT     ; encountered only in Access
700                        (get-cast-byte data-ptr))
701                       (#.$SQL_C_BINARY
702                        (get-cast-binary data-ptr out-len *binary-format*))
703                       ((#.$SQL_C_SSHORT #.$SQL_C_STINYINT) ; LMH short ints
704                        (get-cast-short data-ptr)) ; LMH
705                       (#.$SQL_C_SBIGINT (get-cast-big data-ptr))
706                       #+ignore
707                       (#.$SQL_C_CHAR
708                        (code-char (get-cast-short data-ptr)))
709                       (t
710                        (get-cast-foreign-string data-ptr)))))))))
711
712     ;; FIXME: this could be better optimized for types which use READ-FROM-STRING above
713
714     (if (and (or (eq result-type t) (eq result-type :string))
715              value
716              (not (stringp value)))
717         (write-to-string value)
718       value)))
719
720 ;; which value is appropriate?
721 (defparameter +max-precision+  4001)
722
723 (defvar *break-on-unknown-data-type* t)
724
725 ;; C. Stacy's idea to factor this out
726 ;; "Make it easy to add new datatypes by making new subroutine %ALLOCATE-BINDINGS,
727 ;; so that I don't have to remember to make changes in more than one place.
728 ;; Just keep it in synch with READ-DATA."
729 (defun %allocate-bindings (sql-type precision)
730   (let* ((c-type (sql-to-c-type sql-type))
731          (size (if (zerop precision)
732                    +max-precision+ ;; if the precision cannot be determined
733                  (min precision +max-precision+)))
734          (long-p (= size +max-precision+))
735          (data-ptr
736           (case c-type ;; add more?
737             (#.$SQL_C_SLONG (uffi:allocate-foreign-object #.$ODBC-LONG-TYPE))
738             ((#.$SQL_C_DATE #.$SQL_C_TYPE_DATE) (allocate-foreign-object 'sql-c-date))
739             ((#.$SQL_C_TIME #.$SQL_C_TYPE_TIME) (allocate-foreign-object 'sql-c-time))
740             ((#.$SQL_C_TIMESTAMP #.$SQL_C_TYPE_TIMESTAMP) (allocate-foreign-object 'sql-c-timestamp))
741             (#.$SQL_C_FLOAT (uffi:allocate-foreign-object :float))
742             (#.$SQL_C_DOUBLE (uffi:allocate-foreign-object :double))
743             (#.$SQL_C_BIT (uffi:allocate-foreign-object :byte))
744             (#.$SQL_C_STINYINT (uffi:allocate-foreign-object :byte))
745             (#.$SQL_C_SBIGINT (uffi:allocate-foreign-object #.$ODBC-BIG-TYPE))
746             (#.$SQL_C_SSHORT (uffi:allocate-foreign-object :short))
747             (#.$SQL_C_CHAR (uffi:allocate-foreign-string (1+ size)))
748             (#.$SQL_C_BINARY (uffi:allocate-foreign-string (1+ (* 2 size))))
749             (t
750                 ;; Maybe should signal a restartable condition for this?
751                 (when *break-on-unknown-data-type*
752                   (break "SQL type is ~A, precision ~D, size ~D, C type is ~A"
753                          sql-type precision size c-type))
754                 (uffi:allocate-foreign-object :byte (1+ size)))))
755          (out-len-ptr (uffi:allocate-foreign-object #.$ODBC-LONG-TYPE)))
756     (values c-type data-ptr out-len-ptr size long-p)))
757
758 (defun fetch-all-rows (hstmt &key free-option flatp)
759   (let ((column-count (result-columns-count hstmt)))
760     (unless (zerop column-count)
761       (let ((names (make-array column-count))
762             (sql-types (make-array column-count :element-type 'fixnum))
763             (c-types (make-array column-count :element-type 'fixnum))
764             (precisions (make-array column-count :element-type 'fixnum))
765             (data-ptrs (make-array column-count :initial-element nil))
766             (out-len-ptrs (make-array column-count :initial-element nil))
767             (scales (make-array column-count :element-type 'fixnum))
768             (nullables-p (make-array column-count :element-type 'fixnum)))
769         (unwind-protect
770           (values
771            (progn
772              (dotimes (col-nr column-count)
773                ;; get column information
774                (multiple-value-bind (name sql-type precision scale nullable-p)
775                                     (%describe-column hstmt (1+ col-nr))
776                  ;; allocate space to bind result rows to
777                  (multiple-value-bind (c-type data-ptr out-len-ptr)
778                      (%allocate-bindings sql-type precision)
779                    (%bind-column hstmt col-nr c-type data-ptr (1+ precision) out-len-ptr)
780                    (setf (svref names col-nr) name
781                          (aref sql-types col-nr) sql-type
782                          (aref c-types col-nr) (sql-to-c-type sql-type)
783                          (aref precisions col-nr) (if (zerop precision) 0 precision)
784                          (aref scales col-nr) scale
785                          (aref nullables-p col-nr) nullable-p
786                          (aref data-ptrs col-nr) data-ptr
787                          (aref out-len-ptrs col-nr) out-len-ptr))))
788              ;; the main loop
789              (prog1
790                (cond (flatp
791                       (when (> column-count 1)
792                         (error 'clsql:sql-database-error
793                                :message "If more than one column is to be fetched, flatp has to be nil."))
794                       (loop until (= (%sql-fetch hstmt) $SQL_NO_DATA_FOUND)
795                             collect
796                             (read-data (aref data-ptrs 0)
797                                        (aref c-types 0)
798                                        (aref sql-types 0)
799                                        (aref out-len-ptrs 0)
800                                        t)))
801                      (t
802                       (loop until (= (%sql-fetch hstmt) $SQL_NO_DATA_FOUND)
803                             collect
804                             (loop for col-nr from 0 to (1- column-count)
805                                   collect
806                                   (read-data (aref data-ptrs col-nr)
807                                              (aref c-types col-nr)
808                                              (aref sql-types col-nr)
809                                              (aref out-len-ptrs col-nr)
810                                              t)))))))
811            names)
812           ;; dispose of memory etc
813           (when free-option (%free-statement hstmt free-option))
814           (dotimes (col-nr column-count)
815             (let ((data-ptr (aref data-ptrs col-nr))
816                   (out-len-ptr (aref out-len-ptrs col-nr)))
817               (when data-ptr (free-foreign-object data-ptr)) ; we *did* allocate them
818               (when out-len-ptr (free-foreign-object out-len-ptr)))))))))
819
820 ;; to do: factor out common parts, put the sceleton (the obligatory macro part)
821 ;; of %do-fetch into sql package (has been done)
822
823 (defun %sql-prepare (hstmt sql)
824   (with-cstring (sql-ptr sql)
825     (with-error-handling (:hstmt hstmt)
826       (SQLPrepare hstmt sql-ptr $SQL_NTS))))
827
828 ;; depending on option, we return a long int or a string; string not implemented
829 (defun get-connection-option (hdbc option)
830   (with-foreign-object (param-ptr #.$ODBC-LONG-TYPE)
831     (with-error-handling (:hdbc hdbc)
832                          (SQLGetConnectOption hdbc option param-ptr)
833       (deref-pointer param-ptr #.$ODBC-LONG-TYPE))))
834
835 (defun set-connection-option (hdbc option param)
836   (with-error-handling (:hdbc hdbc)
837     (SQLSetConnectOption hdbc option param)))
838
839 (defun disable-autocommit (hdbc)
840   (set-connection-option hdbc $SQL_AUTOCOMMIT $SQL_AUTOCOMMIT_OFF))
841
842 (defun enable-autocommit (hdbc)
843   (set-connection-option hdbc $SQL_AUTOCOMMIT $SQL_AUTOCOMMIT_ON))
844
845 (defun %sql-set-pos (hstmt row option lock)
846   (with-error-handling
847     (:hstmt hstmt)
848     (SQLSetPos hstmt row option lock)))
849
850 (defun %sql-extended-fetch (hstmt fetch-type row)
851   (with-foreign-objects ((row-count-ptr #.$ODBC-ULONG-TYPE)
852                          (row-status-ptr :short))
853     (with-error-handling (:hstmt hstmt)
854       (SQLExtendedFetch hstmt fetch-type row row-count-ptr
855                         row-status-ptr)
856       (values (deref-pointer row-count-ptr #.$ODBC-ULONG-TYPE)
857               (deref-pointer row-status-ptr :short)))))
858
859 ; column-nr is zero-based
860 (defun %sql-get-data (hstmt column-nr c-type data-ptr precision out-len-ptr)
861   (with-error-handling
862     (:hstmt hstmt :print-info nil)
863     (SQLGetData hstmt (if (eq column-nr :bookmark) 0 (1+ column-nr))
864                 c-type data-ptr precision out-len-ptr)))
865
866 (defun %sql-param-data (hstmt param-ptr)
867   (with-error-handling (:hstmt hstmt :print-info t) ;; nil
868       (SQLParamData hstmt param-ptr)))
869
870 (defun %sql-put-data (hstmt data-ptr size)
871   (with-error-handling
872     (:hstmt hstmt :print-info t) ;; nil
873     (SQLPutData hstmt data-ptr size)))
874
875 (defconstant $sql-data-truncated (intern "01004" :keyword))
876
877 (defun read-data-in-chunks (hstmt column-nr data-ptr c-type sql-type
878                                       out-len-ptr result-type)
879   (declare (type long-ptr-type out-len-ptr)
880            (ignore result-type))
881   (let* ((res (%sql-get-data hstmt column-nr c-type data-ptr
882                              +max-precision+ out-len-ptr))
883          (out-len (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE))
884          (offset 0)
885          (result (case out-len
886                    (#.$SQL_NULL_DATA
887                     (return-from read-data-in-chunks *null*))
888                    (#.$SQL_NO_TOTAL ;; don't know how long it is going to be
889                                     (let ((str (make-array 0 :element-type 'character :adjustable t)))
890                                       (loop do (if (= c-type #.$SQL_CHAR)
891                                                    (let ((data-length (foreign-string-length data-ptr)))
892                                                      (adjust-array str (+ offset data-length)
893                                                                    :initial-element #\?)
894                                                      (setf offset (%cstring-into-vector
895                                                                    data-ptr str
896                                                                    offset
897                                                                    data-length)))
898                                                  (error 'clsql:sql-database-error :message "wrong type. preliminary."))
899                                             while (and (= res $SQL_SUCCESS_WITH_INFO)
900                                                        (equal (sql-state +null-handle-ptr+ +null-handle-ptr+ hstmt)
901                                                               "01004"))
902                                             do (setf res (%sql-get-data hstmt column-nr c-type data-ptr
903                                                                         +max-precision+ out-len-ptr)))
904                                       (setf str (coerce str 'string))
905                                       (if (= sql-type $SQL_DECIMAL)
906                                           (let ((*read-base* 10))
907                                             (read-from-string str))
908                                         str)))
909                     (otherwise
910                     (let ((str)
911                           (offset 0)
912                           (octets (make-array out-len :element-type '(unsigned-byte 8) :initial-element 0)))
913                       (loop
914                          do
915                              (loop for i from 0 to (1- (min out-len +max-precision+))
916                                 do (setf (aref octets (+ offset i)) (deref-array data-ptr '(:array :unsigned-byte) i))
917                                 finally (incf offset (1- i)))
918                          while
919                            (and (= res $SQL_SUCCESS_WITH_INFO)
920                                 (> out-len +max-precision+))
921                          do
922                            (setf res (%sql-get-data hstmt column-nr c-type data-ptr +max-precision+ out-len-ptr)
923                                  out-len (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE)))
924                       (setf str (uffi:octets-to-string octets))
925                       (if (= sql-type $SQL_DECIMAL)
926                           (let ((*read-base* 10))
927                             (read-from-string str))
928                           str))))))
929     (setf (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE) #.$SQL_NO_TOTAL) ;; reset the out length for the next row
930     result))
931
932 (def-type c-timestamp-ptr-type (* (:struct sql-c-timestamp)))
933 (def-type c-time-ptr-type (* (:struct sql-c-time)))
934 (def-type c-date-ptr-type (* (:struct sql-c-date)))
935
936 (defun timestamp-to-universal-time (ptr)
937   (declare (type c-timestamp-ptr-type ptr))
938   (values
939    (encode-universal-time
940     (get-slot-value ptr 'sql-c-timestamp 'second)
941     (get-slot-value ptr 'sql-c-timestamp 'minute)
942     (get-slot-value ptr 'sql-c-timestamp 'hour)
943     (get-slot-value ptr 'sql-c-timestamp 'day)
944     (get-slot-value ptr 'sql-c-timestamp 'month)
945     (get-slot-value ptr 'sql-c-timestamp 'year))
946    (get-slot-value ptr 'sql-c-timestamp 'fraction)))
947
948 (defun universal-time-to-timestamp (time &optional (fraction 0))
949   "TODO: Dead function?"
950   (multiple-value-bind (sec min hour day month year)
951       (decode-universal-time time)
952     (let ((ptr (allocate-foreign-object 'sql-c-timestamp)))
953       (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
954             (get-slot-value ptr 'sql-c-timestamp 'minute) min
955             (get-slot-value ptr 'sql-c-timestamp 'hour) hour
956             (get-slot-value ptr 'sql-c-timestamp 'day) day
957             (get-slot-value ptr 'sql-c-timestamp 'month) month
958             (get-slot-value ptr 'sql-c-timestamp 'year) year
959             (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
960       ptr)))
961
962 (defun %put-timestamp (ptr time &optional (fraction 0))
963   "TODO: Dead function?"
964   (declare (type c-timestamp-ptr-type ptr))
965   (multiple-value-bind (sec min hour day month year)
966       (decode-universal-time time)
967     (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
968           (get-slot-value ptr 'sql-c-timestamp 'minute) min
969           (get-slot-value ptr 'sql-c-timestamp 'hour) hour
970           (get-slot-value ptr 'sql-c-timestamp 'day) day
971           (get-slot-value ptr 'sql-c-timestamp 'month) month
972           (get-slot-value ptr 'sql-c-timestamp 'year) year
973           (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
974       ptr))
975
976 (defun date-to-universal-time (ptr)
977   (declare (type c-date-ptr-type ptr))
978   (encode-universal-time
979    0 0 0
980    (get-slot-value ptr 'sql-c-timestamp 'day)
981    (get-slot-value ptr 'sql-c-timestamp 'month)
982    (get-slot-value ptr 'sql-c-timestamp 'year)))
983
984 (defun time-to-universal-time (ptr)
985   (declare (type c-time-ptr-type ptr))
986   (encode-universal-time
987    (get-slot-value ptr 'sql-c-timestamp 'second)
988    (get-slot-value ptr 'sql-c-timestamp 'minute)
989    (get-slot-value ptr 'sql-c-timestamp 'hour)
990    1 1 0))
991
992
993 ;;; Added by KMR
994
995 (defun %set-attr-odbc-version (henv version)
996   (with-error-handling (:henv henv)
997       ;;note that we are passing version as an integer that happens to be
998       ;;stuffed into a pointer.
999       ;;http://msdn.microsoft.com/en-us/library/ms709285%28v=VS.85%29.aspx
1000       (SQLSetEnvAttr henv $SQL_ATTR_ODBC_VERSION
1001                      (make-pointer version :void) 0)))
1002
1003 (defun %list-tables (hstmt)
1004   (with-error-handling (:hstmt hstmt)
1005     (SQLTables hstmt +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0)))
1006
1007 (defun %table-statistics (table hstmt &key unique (ensure t))
1008   (with-cstrings ((table-cs table))
1009     (with-error-handling (:hstmt hstmt)
1010       (SQLStatistics
1011        hstmt
1012        +null-ptr+ 0
1013        +null-ptr+ 0
1014        table-cs $SQL_NTS
1015        (if unique $SQL_INDEX_UNIQUE $SQL_INDEX_ALL)
1016        (if ensure $SQL_ENSURE $SQL_QUICK)))))
1017
1018 (defun %list-data-sources (henv)
1019   (let ((results nil))
1020     (with-foreign-strings ((dsn-ptr (1+ $SQL_MAX_DSN_LENGTH))
1021                            (desc-ptr 256))
1022       (with-foreign-objects ((dsn-len :short)
1023                              (desc-len :short))
1024        (let ((res (with-error-handling (:henv henv)
1025                       (SQLDataSources henv $SQL_FETCH_FIRST dsn-ptr
1026                                       (1+ $SQL_MAX_DSN_LENGTH)
1027                                       dsn-len desc-ptr 256 desc-len))))
1028          (when (or (eql res $SQL_SUCCESS)
1029                    (eql res $SQL_SUCCESS_WITH_INFO))
1030            (push (convert-from-foreign-string dsn-ptr) results))
1031
1032          (do ((res (with-error-handling (:henv henv)
1033                        (SQLDataSources henv $SQL_FETCH_NEXT dsn-ptr
1034                                        (1+ $SQL_MAX_DSN_LENGTH)
1035                                        dsn-len desc-ptr 256 desc-len))
1036                    (with-error-handling (:henv henv)
1037                        (SQLDataSources henv $SQL_FETCH_NEXT dsn-ptr
1038                                        (1+ $SQL_MAX_DSN_LENGTH)
1039                                        dsn-len desc-ptr 256 desc-len))))
1040              ((not (or (eql res $SQL_SUCCESS)
1041                        (eql res $SQL_SUCCESS_WITH_INFO))))
1042            (push (convert-from-foreign-string dsn-ptr) results)))))
1043     (nreverse results)))