r9133: case handling, test report summarizing, documentation additions
[clsql.git] / db-odbc / odbc-dbi.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:    odbc-dbi.cl
6 ;;;; Purpose: Mid-level (DBI) interface for CLSQL ODBC backend
7 ;;;; Author:  Kevin M. Rosenberg
8 ;;;; Create:  April 2004
9 ;;;;
10 ;;;; $Id: odbc-sql.lisp 8983 2004-04-12 21:16:48Z kevin $
11 ;;;;
12 ;;;; This file, part of CLSQL, is Copyright (c) 2002 by Kevin M. Rosenberg
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 #:cl-user)
20
21 (defpackage #:odbc-dbi
22   (:use #:cl #:odbc)
23   (:export
24    #:bind-parameter
25    #:close-query
26    #:connect
27    #:db-external-format
28    #:db-hstmt
29    #:db-width
30    #:disconnect
31    #:end-transaction
32    #:fetch-row
33    #:list-all-data-sources
34    #:list-all-database-tables
35    #:list-all-table-columns
36    #:list-table-indexes
37    #:loop-over-results
38    #:prepare-sql
39    #:rr-sql
40    #:run-prepared-sql
41    #:set-autocommit
42    #:sql
43    
44    #:*auto-trim-strings*
45    #:*default-database*
46    #:*default-odbc-external-format*
47    #:*null-value*
48    )
49   (:documentation "This is the mid-level interface ODBC."))
50
51 (in-package #:odbc-dbi)
52
53 ;;; SQL Interface
54
55 (defclass odbc-db ()
56   (;; any reason to have more than one henv?
57    (width :initform +max-precision+ :accessor db-width)
58    (hstmt :initform nil :accessor db-hstmt)
59    (henv :initform nil :allocation :class :initarg :henv :accessor henv)
60    (hdbc :initform nil :initarg :hdbc :accessor hdbc)
61    ;; info returned from SQLGetInfo
62    (info :initform (make-hash-table) :reader db-info)
63    (type :initform nil :initarg :db-type :reader db-type)
64    (connected-p :initform nil :accessor db-connected-p)
65    ;; not used yet
66    (count :initform 0 :initarg :count :accessor db-count)
67    ;; not used yet
68    (total-count :initform 0 :allocation :class :accessor db-total-count)
69    ;; the use of this slot is deprecated; it will be removed when dtf works without it.
70    (query :initform nil :accessor db-query-object)
71    ;; resource of (active and inactive) query objects
72    (queries :initform () :accessor db-queries)))
73
74 (defclass odbc-query ()
75   ((hstmt :initform nil :initarg :hstmt :accessor hstmt) ; = cursor??
76    (width :initform +max-precision+ :accessor query-width)
77    (computed-result-types :initform nil :initarg :computed-result-types :accessor computed-result-types)
78    (column-count :initform nil :accessor column-count)
79    (column-names :initform (make-array 0 :element-type 'string :adjustable t :fill-pointer t)
80                  :accessor column-names)
81    (column-c-types :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
82                    :accessor column-c-types)
83    (column-sql-types :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
84                      :accessor column-sql-types)
85    (column-data-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
86                      :accessor data-ptrs)
87    (column-out-len-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
88                         :accessor column-out-len-ptrs)
89    (column-precisions :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
90                       :accessor column-precisions)
91    (column-scales :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
92                   :accessor column-scales)
93    (column-nullables-p :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
94                        :accessor column-nullables-p)
95       ;;(parameter-count :initform 0 :accessor parameter-count)
96    (parameter-data-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
97                         :accessor parameter-ptrs)
98    ;; a query string or a query expression object
99    (sql-expression :initform nil :initarg :sql-expression :accessor sql-expression)
100    ;; database object the query is to be run against
101    (database :initarg :database :reader query-database)
102    (active-p :initform nil :initarg :active-p :accessor query-active-p))
103   (:documentation
104    "Stores query information, like SQL query string/expression and database to run
105 the query against." ))
106
107 ;;; AODBC Compatible interface
108
109 (defun connect (&key data-source-name user password (autocommit t))
110   (let ((db (make-instance 'odbc-db)))
111     (unless (henv db) ;; has class allocation!
112       (setf (henv db) (%new-environment-handle)))
113     (setf (hdbc db) (%new-db-connection-handle (henv db)))
114     (%sql-connect (hdbc db) data-source-name user password)
115     #+ignore (setf (db-hstmt db) (%new-statement-handle (hdbc db)))
116     (when (/= (get-odbc-info db odbc::$SQL_TXN_CAPABLE) odbc::$SQL_TC_NONE)
117       (if autocommit
118           (enable-autocommit (hdbc db))
119           (disable-autocommit (hdbc db))))
120     db))
121
122 (defun disconnect (database)
123   (with-slots (hdbc queries) database
124     (dolist (query queries)
125       (if (query-active-p query)
126           (with-slots (hstmt) query
127             (when hstmt 
128               (%free-statement hstmt :drop)
129               (setf hstmt nil)))))
130     (when (db-hstmt database)
131       (%free-statement (db-hstmt database) :drop))
132     (%disconnect hdbc)))
133
134
135 (defun sql (expr &key db result-types row-count (column-names t) query 
136                       hstmt width)
137   (declare (ignore hstmt))
138   (cond
139    (query
140     (let ((q (db-open-query db expr :result-types result-types :width width)))
141       (if column-names
142           (values q (column-names q))
143         q)))
144    (t
145     (multiple-value-bind (data col-names)
146         (db-query db expr :result-types result-types :width width)
147       (cond
148         (row-count
149          (if (consp data) (length data) data))
150         (column-names
151          (values data col-names))
152         (t
153          data))))))
154
155 (defun fetch-row (query &optional (eof-errorp t) eof-value)
156   (multiple-value-bind (row query count) (db-fetch-query-results query 1)
157     (cond
158      ((zerop count)
159       (close-query query)
160       (when eof-errorp
161         (error 'clsql-odbc-error :odbc-message "Ran out of data in fetch-row"))
162       eof-value)
163      (t
164       (car row)))))
165       
166
167 (defun close-query (query)
168   (db-close-query query))
169
170 (defun list-all-database-tables (&key db hstmt)
171   (declare (ignore hstmt))
172   (let ((query (get-free-query db)))
173     (unwind-protect
174         (progn
175           (with-slots (hstmt) query
176             (unless hstmt (setf hstmt (%new-statement-handle (hdbc db))))
177             (%list-tables hstmt)
178             (%initialize-query query nil nil)
179             (values
180              (db-fetch-query-results query)
181              (coerce (column-names query) 'list))))
182       (db-close-query query))))
183
184 (defun list-table-indexes (table &key db unique hstmt)
185   (declare (ignore hstmt))
186   (let ((query (get-free-query db)))
187     (unwind-protect
188         (progn
189           (with-slots (hstmt) query
190             (unless hstmt
191               (setf hstmt (%new-statement-handle (hdbc db))))
192             (%table-statistics table hstmt :unique unique)
193             (%initialize-query query nil nil)
194             (values
195              (db-fetch-query-results query)
196              (coerce (column-names query) 'list))))
197       (db-close-query query))))
198
199 (defun list-all-table-columns (table &key db hstmt)
200   (declare (ignore hstmt))
201   (db-describe-columns db "" "" table ""))
202
203 (defun list-all-data-sources ()
204   (let ((db (make-instance 'odbc-db)))
205     (unless (henv db) ;; has class allocation!
206       (setf (henv db) (%new-environment-handle)))
207     (%list-data-sources (henv db))))
208
209 (defun rr-sql (hstmt sql-statement &key db)
210   (declare (ignore hstmt sql-statement db))
211   (warn "rr-sql not implemented."))
212
213 ;;; Mid-level interface
214
215 (defmethod db-commit ((database odbc-db))
216   (%commit (henv database) (hdbc database)))
217
218 (defmethod db-rollback ((database odbc-db))
219   (%rollback (henv database) (hdbc database)))
220
221 (defmethod db-cancel-query ((query odbc-query))
222   (with-slots (hstmt) query
223     (%sql-cancel hstmt)
224     (setf (query-active-p query) nil)))
225
226 #+simple-version
227 (defmacro with-transaction (&body body)
228   `(%with-transaction
229      (:henv (henv ,*default-database*) :hdbc (hdbc ,*default-database*))
230      ,@body))
231
232 (defmethod initialize-instance :after ((query odbc-query) 
233                                        &key sql henv hdbc &allow-other-keys)
234   (when sql
235     (let ((hstmt (%new-statement-handle hdbc)))
236       (%sql-exec-direct sql hstmt henv hdbc)
237       (with-slots (column-count 
238                    column-names column-c-types column-sql-types column-data-ptrs 
239                    column-out-len-ptrs column-precisions column-scales
240                    column-nullables-p active-p) query
241         (setf (hstmt query) hstmt)
242         (%initialize-query query nil nil)
243         (setf active-p t)))))
244
245 ;; one for odbc-db is missing
246 (defmethod terminate ((query odbc-query))
247   ;;(format tb::*local-output* "~%*** terminated: ~s" query)
248   (with-slots (hstmt) query
249     (when hstmt
250       ;(%free-statement hstmt :drop)
251       (uffi:free-foreign-object hstmt)) ;; ??
252     (%dispose-column-ptrs query)))
253
254 (defmethod %dispose-column-ptrs ((query odbc-query))
255   (with-slots (column-data-ptrs column-out-len-ptrs hstmt) query
256     (loop for data-ptr across column-data-ptrs
257           when data-ptr do (uffi:free-foreign-object data-ptr))
258     (loop for out-len-ptr across column-out-len-ptrs
259           when out-len-ptr do (uffi:free-foreign-object out-len-ptr))))
260
261 (defmethod db-open-query ((database odbc-db) query-expression
262                           &key arglen col-positions result-types width
263                           &allow-other-keys)
264   (db-open-query (get-free-query database) query-expression
265                  :arglen arglen :col-positions col-positions
266                  :result-types result-types
267                  :width (if width width (db-width database))))
268
269 (defmethod db-open-query ((query odbc-query) query-expression
270                           &key arglen col-positions result-types width
271                           &allow-other-keys)
272   (%db-execute query query-expression)
273   (%initialize-query query arglen col-positions :result-types result-types
274                      :width width))
275
276 (defmethod db-fetch-query-results ((database odbc-db) &optional count)
277   (db-fetch-query-results (db-query-object database) count))
278
279 (defmethod db-fetch-query-results ((query odbc-query) &optional count)
280   (when (query-active-p query)
281     (with-slots (column-count column-data-ptrs column-c-types column-sql-types 
282                  column-out-len-ptrs column-precisions hstmt computed-result-types)
283         query
284       (let* ((rows-fetched 0)
285              (rows
286               (loop for i from 0 
287                   until (or (and count (= i count))
288                             (= (%sql-fetch hstmt) odbc::$SQL_NO_DATA_FOUND))
289                   collect
290                     (loop for result-type across computed-result-types
291                         for data-ptr across column-data-ptrs
292                         for c-type across column-c-types
293                         for sql-type across column-sql-types
294                         for out-len-ptr across column-out-len-ptrs
295                         for precision across column-precisions
296                         for j from 0    ; column count is zero based in lisp
297                         collect 
298                           (progn
299                             (incf rows-fetched)
300                             (cond ((< 0 precision (query-width query))
301                                    (read-data data-ptr c-type sql-type out-len-ptr result-type))
302                                   ((zerop (get-cast-long out-len-ptr))
303                               nil)
304                                   (t
305                                    (read-data-in-chunks hstmt j data-ptr c-type sql-type
306                                                         out-len-ptr result-type))))))))
307         (values rows query rows-fetched)))))
308
309 (defmethod db-query ((database odbc-db) query-expression &key result-types width)
310   (let ((free-query (get-free-query database)))
311     (setf (sql-expression free-query) query-expression)
312     (unwind-protect
313       (progn
314         (%db-execute free-query query-expression)
315         (%initialize-query free-query nil nil :result-types result-types :width width)
316         (if (plusp (column-count free-query)) ;; KMR: Added check for commands that don't return columns
317             (values
318              (db-fetch-query-results free-query nil)
319              (column-names free-query))
320           (values
321            (result-rows-count (hstmt free-query))
322            nil)))
323       (db-close-query free-query)
324       )))
325
326 (defmethod %db-execute ((database odbc-db) sql-expression &key &allow-other-keys)
327   (%db-execute (get-free-query database) sql-expression))
328
329 (defmethod %db-execute ((query odbc-query) sql-expression &key &allow-other-keys)
330   (with-slots (henv hdbc) (odbc::query-database query)
331     (with-slots (hstmt) query
332       (unless hstmt (setf hstmt (%new-statement-handle hdbc))) 
333       (setf (sql-expression query) sql-expression)
334       (%sql-exec-direct sql-expression hstmt henv hdbc)
335       query)))
336
337 ;; reuse inactive queries
338 (defmethod get-free-query ((database odbc-db))
339   "get-free-query finds or makes a nonactive query object, and then sets it to active.
340 This makes the functions db-execute-command and db-query thread safe."
341   (with-slots (queries hdbc) database
342     (or (clsql-base-sys:without-interrupts
343          (let ((inactive-query (find-if (lambda (query)
344                                           (not (query-active-p query)))
345                                         queries)))
346            (when inactive-query 
347              (with-slots (column-count column-names column-c-types 
348                           width hstmt
349                           column-sql-types column-data-ptrs
350                           column-out-len-ptrs column-precisions
351                           column-scales column-nullables-p)
352                          inactive-query
353                ;;(print column-data-ptrs tb::*local-output*)
354                ;;(%dispose-column-ptrs inactive-query)
355                (setf column-count 0
356                      width +max-precision+
357                      ;; KMR hstmt (%new-statement-handle hdbc)
358                      (fill-pointer column-names) 0
359                      (fill-pointer column-c-types) 0
360                      (fill-pointer column-sql-types) 0
361                      (fill-pointer column-data-ptrs) 0
362                      (fill-pointer column-out-len-ptrs) 0
363                      (fill-pointer column-precisions) 0
364                      (fill-pointer column-scales) 0
365                      (fill-pointer column-nullables-p) 0))
366              (setf (query-active-p inactive-query) t))
367            inactive-query))
368         (let ((new-query (make-instance 'odbc-query
369                                         :database database
370                                         ;;(clone-database database)
371                                         :active-p t)))
372           (push new-query queries)
373           new-query))))
374
375 (defmethod db-execute-command ((database odbc-db) sql-string)
376   (db-execute-command (get-free-query database) sql-string))
377
378 (defmethod db-execute-command ((query odbc-query) sql-string)
379   (with-slots (hstmt database) query
380     (with-slots (henv hdbc) database
381       (unless hstmt (setf hstmt (%new-statement-handle hdbc))) 
382       (unwind-protect 
383           (%sql-exec-direct sql-string hstmt henv hdbc)
384         (db-close-query query)))))
385
386 (defmethod %initialize-query ((database odbc-db) arglen col-positions &key result-types width)
387   (%initialize-query (db-query-object database) arglen col-positions
388                      :result-types result-types 
389                      :width (if width width (db-width database))))
390
391 (defmethod %initialize-query ((query odbc-query) arglen col-positions &key result-types width)
392   (with-slots (hstmt computed-result-types
393                column-count column-names column-c-types column-sql-types
394                column-data-ptrs column-out-len-ptrs column-precisions
395                column-scales column-nullables-p) 
396       query 
397     (setf column-count (if arglen
398                          (min arglen (result-columns-count hstmt))
399                          (result-columns-count hstmt)))
400     (when width (setf (query-width query) width))
401     ;;(format tb::*local-output* "~%column-count: ~d, col-positions: ~d" column-count col-positions)
402     (labels ((initialize-column (col-nr)
403                 (multiple-value-bind (name sql-type precision scale nullable-p)
404                                      (%describe-column hstmt (1+ col-nr))
405                   ;; allocate space to bind result rows to
406                   (multiple-value-bind (c-type data-ptr out-len-ptr size long-p)
407                                        (%allocate-bindings sql-type precision)
408                     (unless long-p ;; if long-p we fetch in chunks with %sql-get-data
409                       (%bind-column hstmt col-nr c-type data-ptr (1+ size) out-len-ptr))
410                     (vector-push-extend name column-names) 
411                     (vector-push-extend sql-type column-sql-types)
412                     (vector-push-extend (sql-to-c-type sql-type) column-c-types)
413                     (vector-push-extend precision column-precisions)
414                     (vector-push-extend scale column-scales)
415                     (vector-push-extend nullable-p column-nullables-p)
416                     (vector-push-extend data-ptr column-data-ptrs)
417                     (vector-push-extend out-len-ptr column-out-len-ptrs)))))
418       (if col-positions
419         (dolist (col-nr col-positions)
420           (initialize-column col-nr))
421         (dotimes (col-nr column-count)
422           ;; get column information
423           (initialize-column col-nr))))
424     
425     (setf computed-result-types (make-array column-count))
426     (dotimes (i column-count)
427       (setf (aref computed-result-types i) 
428         (cond
429          ((consp result-types)
430           (nth i result-types))
431          ((eq result-types :auto)
432           (if (eq (aref column-sql-types i) odbc::$SQL_BIGINT)
433               :number
434             (case (aref column-c-types i)
435               (#.odbc::$SQL_C_SLONG :int)
436               (#.odbc::$SQL_C_DOUBLE :double)
437               (#.odbc::$SQL_C_FLOAT :float)
438               (#.odbc::$SQL_C_SSHORT :short)
439               (#.odbc::$SQL_BIGINT :short)
440               (t t))))
441           (t
442           t)))))
443   query)
444
445 (defmethod db-close-query ((query odbc-query) &key drop-p)
446   (with-slots (hstmt column-count column-names column-c-types column-sql-types
447                      column-data-ptrs column-out-len-ptrs column-precisions
448                      column-scales column-nullables-p) query
449     (let ((count (fill-pointer column-data-ptrs)))
450       (when (not (zerop count))
451         (dotimes (col-nr count)
452           (let ((data-ptr (aref column-data-ptrs col-nr))
453                 (out-len-ptr (aref column-out-len-ptrs col-nr)))
454             ;; free-statment :unbind frees these
455             #+ignore (when data-ptr (uffi:free-foreign-object data-ptr))
456             #+ignore (when out-len-ptr (uffi:free-foreign-object out-len-ptr)))))
457       (cond ((null hstmt)
458              nil)
459             (drop-p
460              (%free-statement hstmt :drop)
461              (setf hstmt nil))
462             (t
463              (%free-statement hstmt :unbind)
464              (%free-statement hstmt :reset)
465              (%free-statement hstmt :close)))
466       (setf (query-active-p query) nil)))
467   query)
468
469 (defmethod %read-query-data ((database odbc-db) ignore-columns)
470   (%read-query-data (db-query-object database) ignore-columns))
471
472 (defmethod %read-query-data ((query odbc-query) ignore-columns)
473   (with-slots (hstmt column-count column-c-types column-sql-types 
474                column-data-ptrs column-out-len-ptrs column-precisions
475                computed-result-types)
476       query
477     (unless (= (SQLFetch hstmt) odbc::$SQL_NO_DATA_FOUND)
478       (values
479        (loop for col-nr from 0 to (- column-count 
480                                      (if (eq ignore-columns :last) 2 1))
481            for result-type across computed-result-types
482            collect
483              (let ((precision (aref column-precisions col-nr))
484                    (sql-type (aref column-sql-types col-nr)))
485                (cond ((or (< 0 precision (query-width query))
486                           (and (zerop precision) (not (find sql-type '($SQL_C_CHAR)))))
487                       (read-data (aref column-data-ptrs col-nr) 
488                                  (aref column-c-types col-nr)
489                                  sql-type
490                                  (aref column-out-len-ptrs col-nr)
491                                  result-type))
492                      ((zerop (get-cast-long (aref column-out-len-ptrs col-nr)))
493                       *null*)
494                      (t
495                       (read-data-in-chunks hstmt col-nr
496                                            (aref column-data-ptrs col-nr) 
497                                            (aref column-c-types col-nr)
498                                            (aref column-sql-types col-nr)
499                                            (aref column-out-len-ptrs col-nr)
500                                            result-type)))))
501        t))))
502
503 (defmethod db-map-query ((database odbc-db) type function query-exp &key result-types)
504   (db-map-query (get-free-query database) type function query-exp :result-types result-types))
505
506 (defmethod db-map-query ((query odbc-query) type function query-exp &key result-types)
507   (declare (ignore type)) ; preliminary. Do a type coersion here
508   (%db-execute query (sql-expression query-exp))
509   (unwind-protect
510     (progn
511       (%initialize-query query nil nil :result-types result-types)
512       ;; the main loop
513       (loop for data = (%read-query-data query nil)
514             while data
515             do (apply function data)))
516     ;; dispose of memory and set query inactive or get rid of it
517     (db-close-query query)))
518
519 (defmethod db-map-bind-query ((query odbc-query) type function 
520                                  &rest parameters)
521   (declare (ignore type)) ; preliminary. Do a type coersion here
522   (unwind-protect
523     (progn
524       (apply #'%db-bind-execute query parameters)
525       ;; the main loop
526       (loop with data
527             while (setf data (%read-query-data query nil))
528             do (apply function data)))
529     ;; dispose of memory and set query inactive or get rid of it
530     (%db-reset-query query)))
531
532 ;; does not always return exactly a lisp type...
533 (defun sql-to-lisp-type (sql-type)
534   (ecase sql-type
535     ((#.odbc::$SQL_CHAR #.odbc::$SQL_VARCHAR #.odbc::$SQL_LONGVARCHAR) :string)
536     ((#.odbc::$SQL_NUMERIC #.odbc::$SQL_DECIMAL #.odbc::$SQL_BIGINT) :string) ; ??
537     (#.odbc::$SQL_INTEGER :long)
538     (#.odbc::$SQL_SMALLINT :short)
539     ((#.odbc::$SQL_FLOAT #.odbc::$SQL_DOUBLE) :long)
540     (#.odbc::$SQL_REAL :long)
541     (#.odbc::$SQL_DATE 'sql-c-date)
542     (#.odbc::$SQL_TIME 'sql-c-time)
543     (#.odbc::$SQL_TIMESTAMP 'sql-c-timestamp)
544     ;;((#.odbc::$SQL_BINARY #.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) odbc::$SQL_C_BINARY) ; ??
545     (#.odbc::$SQL_TINYINT :short)
546     ;;(#.odbc::$SQL_BIT odbc::$SQL_C_BIT) ; ??
547     ((#.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) :binary)
548     ))
549
550 ;; prepared queries
551
552 (defmethod db-prepare-statement ((database odbc-db) sql
553                                      &key parameter-table parameter-columns)
554   (with-slots (hdbc) database
555     (let ((query (get-free-query database))) 
556       (with-slots (hstmt) query
557         (unless hstmt (setf hstmt (%new-statement-handle hdbc))))
558       (db-prepare-statement query sql parameter-table parameter-columns))))
559
560 (defmethod db-prepare-statement ((query odbc-query) (sql string)
561                                      &key parameter-table parameter-columns)
562   ;; this is a workaround to get hold of the column types when the driver does not
563   ;; support SQLDescribeParam. To do: put code in here for drivers that do
564   ;; support it.
565   (unless (string-equal sql "insert" :end1 6)
566     (error "Only insert expressions are supported in literal ODBC: '~a'." sql))
567   (%db-execute query (format nil "select ~{~a~^,~} from ~a where 0 = 1"
568                              (or parameter-columns '("*")) parameter-table))
569   (%initialize-query query nil nil)
570   (with-slots (hstmt) query
571     (%free-statement hstmt :unbind)
572     (%free-statement hstmt :reset)
573     (setf (sql-expression query) sql)
574     (%sql-prepare hstmt sql))
575   query)
576
577
578 (defmethod %db-bind-execute ((query odbc-query) &rest parameters)
579   (with-slots (hstmt parameter-data-ptrs) query
580     (loop for parameter in parameters
581           with data-ptr and size and parameter-string
582           do
583           (setf parameter-string
584                 (if (stringp parameter)
585                   parameter
586                   (write-to-string parameter))
587            size (length parameter-string)
588                 data-ptr 
589                 (uffi:allocate-foreign-string (1+ size)))
590           (vector-push-extend data-ptr parameter-data-ptrs)
591           (%sql-bind-parameter 
592            hstmt (1- (fill-pointer parameter-data-ptrs)) odbc::$SQL_PARAM_INPUT
593            odbc::$SQL_C_CHAR ; (aref column-c-types parameter-count)
594            odbc::$SQL_CHAR ; sql-type
595            (query-width query)          ;precision ; this should be the actual precision!
596            ;; scale
597            0 ;; should be calculated for odbc::$SQL_DECIMAL,
598            ;;$SQL_NUMERIC and odbc::$SQL_TIMESTAMP
599            data-ptr ;; = rgbValue
600            0
601            ;; *pcbValue;
602            ;; change this for output and binary input! (see 3-32)
603            +null-ptr+)
604           (%put-str data-ptr parameter-string size))
605         (%sql-execute hstmt)))
606
607
608 (defmethod %db-reset-query ((query odbc-query))
609   (with-slots (hstmt parameter-data-ptrs) query
610     (prog1
611       (db-fetch-query-results query nil) 
612       (%free-statement hstmt :reset) ;; but _not_ :unbind !
613       (%free-statement hstmt :close)
614       (dotimes (param-nr (fill-pointer parameter-data-ptrs))
615         (let ((data-ptr (aref parameter-data-ptrs param-nr)))
616           (when data-ptr (uffi:free-foreign-object data-ptr))))
617       (setf (fill-pointer parameter-data-ptrs) 0))))
618
619 (defun data-parameter-ptr (hstmt)
620   (uffi:with-foreign-object (param-ptr :pointer-void)
621     (let ((return-code (%sql-param-data hstmt param-ptr)))
622       ;;(format t "~%return-code from %sql-param-data: ~a~%" return-code)
623       (when (= return-code odbc::$SQL_NEED_DATA)
624         ;;(ffc::%pointer-to-address (%get-ptr param-ptr))
625         (uffi:deref-pointer param-ptr :pointer-void)))))
626
627 ;; database inquiery functions
628
629 (defmethod db-describe-columns ((database odbc-db) 
630                                     table-qualifier table-owner table-name column-name)
631   (with-slots (hdbc) database
632     (%describe-columns hdbc table-qualifier table-owner table-name column-name)))
633
634 ;; should translate info-type integers to keywords in order to make this 
635 ;; more readable?
636 (defmethod get-odbc-info ((database odbc-db) info-type)
637   (with-slots (hdbc info) database
638     (or (gethash info-type info)
639         (setf (gethash info-type info)
640               (%sql-get-info hdbc info-type)))))
641
642 (defmethod get-odbc-info ((query odbc-query) info-type)
643   (get-odbc-info (odbc::query-database query) info-type))
644
645 ;; driver inquiery
646 (defmethod db-data-sources ((db-type (eql :odbc)))
647    "Returns a list of (data-source description) - pairs"
648    (let ((henv (%new-environment-handle)))
649     (unwind-protect
650           (loop with direction = :first
651                for data-source+description 
652                = (multiple-value-list (%sql-data-sources henv :direction direction))
653                while (car data-source+description)
654                collect data-source+description
655                do (setf direction :next))
656       (%sql-free-environment henv))))
657
658 ; EOF