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