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