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