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