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