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