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