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