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