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