r9113: intial changes for list-table-indexes
[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 (setf hstmt (%new-statement-handle (hdbc db))))
191             (%table-statistics table hstmt :unique unique)
192             (%initialize-query query nil nil)
193             (values
194              (db-fetch-query-results query)
195              (coerce (column-names query) 'list))))
196       (db-close-query query))))
197
198 (defun list-all-table-columns (table &key db hstmt)
199   (declare (ignore hstmt))
200   (db-describe-columns db "" "" table ""))
201
202 (defun list-all-data-sources ()
203   (let ((db (make-instance 'odbc-db)))
204     (unless (henv db) ;; has class allocation!
205       (setf (henv db) (%new-environment-handle)))
206     (%list-data-sources (henv db))))
207
208 (defun rr-sql (hstmt sql-statement &key db)
209   (declare (ignore hstmt sql-statement db))
210   (warn "rr-sql not implemented."))
211
212 ;;; Mid-level interface
213
214 (defmethod db-commit ((database odbc-db))
215   (%commit (henv database) (hdbc database)))
216
217 (defmethod db-rollback ((database odbc-db))
218   (%rollback (henv database) (hdbc database)))
219
220 (defmethod db-cancel-query ((query odbc-query))
221   (with-slots (hstmt) query
222     (%sql-cancel hstmt)
223     (setf (query-active-p query) nil)))
224
225 #+simple-version
226 (defmacro with-transaction (&body body)
227   `(%with-transaction
228      (:henv (henv ,*default-database*) :hdbc (hdbc ,*default-database*))
229      ,@body))
230
231 (defmethod initialize-instance :after ((query odbc-query) 
232                                        &key sql henv hdbc &allow-other-keys)
233   (when sql
234     (let ((hstmt (%new-statement-handle hdbc)))
235       (%sql-exec-direct sql hstmt henv hdbc)
236       (with-slots (column-count 
237                    column-names column-c-types column-sql-types column-data-ptrs 
238                    column-out-len-ptrs column-precisions column-scales
239                    column-nullables-p active-p) query
240         (setf (hstmt query) hstmt)
241         (%initialize-query query nil nil)
242         (setf active-p t)))))
243
244 ;; one for odbc-db is missing
245 (defmethod terminate ((query odbc-query))
246   ;;(format tb::*local-output* "~%*** terminated: ~s" query)
247   (with-slots (hstmt) query
248     (when hstmt
249       ;(%free-statement hstmt :drop)
250       (uffi:free-foreign-object hstmt)) ;; ??
251     (%dispose-column-ptrs query)))
252
253 (defmethod %dispose-column-ptrs ((query odbc-query))
254   (with-slots (column-data-ptrs column-out-len-ptrs hstmt) query
255     (loop for data-ptr across column-data-ptrs
256           when data-ptr do (uffi:free-foreign-object data-ptr))
257     (loop for out-len-ptr across column-out-len-ptrs
258           when out-len-ptr do (uffi:free-foreign-object out-len-ptr))))
259
260 (defmethod db-open-query ((database odbc-db) query-expression
261                           &key arglen col-positions result-types width
262                           &allow-other-keys)
263   (db-open-query (get-free-query database) query-expression
264                  :arglen arglen :col-positions col-positions
265                  :result-types result-types
266                  :width (if width width (db-width database))))
267
268 (defmethod db-open-query ((query odbc-query) query-expression
269                           &key arglen col-positions result-types width
270                           &allow-other-keys)
271   (%db-execute query query-expression)
272   (%initialize-query query arglen col-positions :result-types result-types
273                      :width width))
274
275 (defmethod db-fetch-query-results ((database odbc-db) &optional count)
276   (db-fetch-query-results (db-query-object database) count))
277
278 (defmethod db-fetch-query-results ((query odbc-query) &optional count)
279   (when (query-active-p query)
280     (with-slots (column-count column-data-ptrs column-c-types column-sql-types 
281                  column-out-len-ptrs column-precisions hstmt computed-result-types)
282         query
283       (let* ((rows-fetched 0)
284              (rows
285               (loop for i from 0 
286                   until (or (and count (= i count))
287                             (= (%sql-fetch hstmt) odbc::$SQL_NO_DATA_FOUND))
288                   collect
289                     (loop for result-type across computed-result-types
290                         for data-ptr across column-data-ptrs
291                         for c-type across column-c-types
292                         for sql-type across column-sql-types
293                         for out-len-ptr across column-out-len-ptrs
294                         for precision across column-precisions
295                         for j from 0    ; column count is zero based in lisp
296                         collect 
297                           (progn
298                             (incf rows-fetched)
299                             (cond ((< 0 precision (query-width query))
300                                    (read-data data-ptr c-type sql-type out-len-ptr result-type))
301                                   ((zerop (get-cast-long out-len-ptr))
302                               nil)
303                                   (t
304                                    (read-data-in-chunks hstmt j data-ptr c-type sql-type
305                                                         out-len-ptr result-type))))))))
306         (values rows query rows-fetched)))))
307
308 (defmethod db-query ((database odbc-db) query-expression &key result-types width)
309   (let ((free-query (get-free-query database)))
310     (setf (sql-expression free-query) query-expression)
311     (unwind-protect
312       (progn
313         (%db-execute free-query query-expression)
314         (%initialize-query free-query nil nil :result-types result-types :width width)
315         (if (plusp (column-count free-query)) ;; KMR: Added check for commands that don't return columns
316             (values
317              (db-fetch-query-results free-query nil)
318              (column-names free-query))
319           (values
320            (result-rows-count (hstmt free-query))
321            nil)))
322       (db-close-query free-query)
323       )))
324
325 (defmethod %db-execute ((database odbc-db) sql-expression &key &allow-other-keys)
326   (%db-execute (get-free-query database) sql-expression))
327
328 (defmethod %db-execute ((query odbc-query) sql-expression &key &allow-other-keys)
329   (with-slots (henv hdbc) (odbc::query-database query)
330     (with-slots (hstmt) query
331       (unless hstmt (setf hstmt (%new-statement-handle hdbc))) 
332       (setf (sql-expression query) sql-expression)
333       (%sql-exec-direct sql-expression hstmt henv hdbc)
334       query)))
335
336 ;; reuse inactive queries
337 (defmethod get-free-query ((database odbc-db))
338   "get-free-query finds or makes a nonactive query object, and then sets it to active.
339 This makes the functions db-execute-command and db-query thread safe."
340   (with-slots (queries hdbc) database
341     (or (clsql-base-sys:without-interrupts
342          (let ((inactive-query (find-if (lambda (query)
343                                           (not (query-active-p query)))
344                                         queries)))
345            (when inactive-query 
346              (with-slots (column-count column-names column-c-types 
347                           width hstmt
348                           column-sql-types column-data-ptrs
349                           column-out-len-ptrs column-precisions
350                           column-scales column-nullables-p)
351                          inactive-query
352                ;;(print column-data-ptrs tb::*local-output*)
353                ;;(%dispose-column-ptrs inactive-query)
354                (setf column-count 0
355                      width +max-precision+
356                      ;; KMR hstmt (%new-statement-handle hdbc)
357                      (fill-pointer column-names) 0
358                      (fill-pointer column-c-types) 0
359                      (fill-pointer column-sql-types) 0
360                      (fill-pointer column-data-ptrs) 0
361                      (fill-pointer column-out-len-ptrs) 0
362                      (fill-pointer column-precisions) 0
363                      (fill-pointer column-scales) 0
364                      (fill-pointer column-nullables-p) 0))
365              (setf (query-active-p inactive-query) t))
366            inactive-query))
367         (let ((new-query (make-instance 'odbc-query
368                                         :database database
369                                         ;;(clone-database database)
370                                         :active-p t)))
371           (push new-query queries)
372           new-query))))
373
374 (defmethod db-execute-command ((database odbc-db) sql-string)
375   (db-execute-command (get-free-query database) sql-string))
376
377 (defmethod db-execute-command ((query odbc-query) sql-string)
378   (with-slots (hstmt database) query
379     (with-slots (henv hdbc) database
380       (unless hstmt (setf hstmt (%new-statement-handle hdbc))) 
381       (unwind-protect 
382           (%sql-exec-direct sql-string hstmt henv hdbc)
383         (db-close-query query)))))
384
385 (defmethod %initialize-query ((database odbc-db) arglen col-positions &key result-types width)
386   (%initialize-query (db-query-object database) arglen col-positions
387                      :result-types result-types 
388                      :width (if width width (db-width database))))
389
390 (defmethod %initialize-query ((query odbc-query) arglen col-positions &key result-types width)
391   (with-slots (hstmt computed-result-types
392                column-count column-names column-c-types column-sql-types
393                column-data-ptrs column-out-len-ptrs column-precisions
394                column-scales column-nullables-p) 
395       query 
396     (setf column-count (if arglen
397                          (min arglen (result-columns-count hstmt))
398                          (result-columns-count hstmt)))
399     (when width (setf (query-width query) width))
400     ;;(format tb::*local-output* "~%column-count: ~d, col-positions: ~d" column-count col-positions)
401     (labels ((initialize-column (col-nr)
402                 (multiple-value-bind (name sql-type precision scale nullable-p)
403                                      (%describe-column hstmt (1+ col-nr))
404                   ;; allocate space to bind result rows to
405                   (multiple-value-bind (c-type data-ptr out-len-ptr size long-p)
406                                        (%allocate-bindings sql-type precision)
407                     (unless long-p ;; if long-p we fetch in chunks with %sql-get-data
408                       (%bind-column hstmt col-nr c-type data-ptr (1+ size) out-len-ptr))
409                     (vector-push-extend name column-names) 
410                     (vector-push-extend sql-type column-sql-types)
411                     (vector-push-extend (sql-to-c-type sql-type) column-c-types)
412                     (vector-push-extend precision column-precisions)
413                     (vector-push-extend scale column-scales)
414                     (vector-push-extend nullable-p column-nullables-p)
415                     (vector-push-extend data-ptr column-data-ptrs)
416                     (vector-push-extend out-len-ptr column-out-len-ptrs)))))
417       (if col-positions
418         (dolist (col-nr col-positions)
419           (initialize-column col-nr))
420         (dotimes (col-nr column-count)
421           ;; get column information
422           (initialize-column col-nr))))
423     
424     (setf computed-result-types (make-array column-count))
425     (dotimes (i column-count)
426       (setf (aref computed-result-types i) 
427         (cond
428          ((consp result-types)
429           (nth i result-types))
430          ((eq result-types :auto)
431           (if (eq (aref column-sql-types i) odbc::$SQL_BIGINT)
432               :number
433             (case (aref column-c-types i)
434               (#.odbc::$SQL_C_SLONG :int)
435               (#.odbc::$SQL_C_DOUBLE :double)
436               (#.odbc::$SQL_C_FLOAT :float)
437               (#.odbc::$SQL_C_SSHORT :short)
438               (#.odbc::$SQL_BIGINT :short)
439               (t t))))
440           (t
441           t)))))
442   query)
443
444 (defmethod db-close-query ((query odbc-query) &key drop-p)
445   (with-slots (hstmt column-count column-names column-c-types column-sql-types
446                      column-data-ptrs column-out-len-ptrs column-precisions
447                      column-scales column-nullables-p) query
448     (let ((count (fill-pointer column-data-ptrs)))
449       (when (not (zerop count))
450         (dotimes (col-nr count)
451           (let ((data-ptr (aref column-data-ptrs col-nr))
452                 (out-len-ptr (aref column-out-len-ptrs col-nr)))
453             ;; free-statment :unbind frees these
454             #+ignore (when data-ptr (uffi:free-foreign-object data-ptr))
455             #+ignore (when out-len-ptr (uffi:free-foreign-object out-len-ptr)))))
456       (cond ((null hstmt)
457              nil)
458             (drop-p
459              (%free-statement hstmt :drop)
460              (setf hstmt nil))
461             (t
462              (%free-statement hstmt :unbind)
463              (%free-statement hstmt :reset)
464              (%free-statement hstmt :close)))
465       (setf (query-active-p query) nil)))
466   query)
467
468 (defmethod %read-query-data ((database odbc-db) ignore-columns)
469   (%read-query-data (db-query-object database) ignore-columns))
470
471 (defmethod %read-query-data ((query odbc-query) ignore-columns)
472   (with-slots (hstmt column-count column-c-types column-sql-types 
473                column-data-ptrs column-out-len-ptrs column-precisions
474                computed-result-types)
475       query
476     (unless (= (SQLFetch hstmt) odbc::$SQL_NO_DATA_FOUND)
477       (values
478        (loop for col-nr from 0 to (- column-count 
479                                      (if (eq ignore-columns :last) 2 1))
480            for result-type across computed-result-types
481            collect
482              (let ((precision (aref column-precisions col-nr))
483                    (sql-type (aref column-sql-types col-nr)))
484                (cond ((or (< 0 precision (query-width query))
485                           (and (zerop precision) (not (find sql-type '($SQL_C_CHAR)))))
486                       (read-data (aref column-data-ptrs col-nr) 
487                                  (aref column-c-types col-nr)
488                                  sql-type
489                                  (aref column-out-len-ptrs col-nr)
490                                  result-type))
491                      ((zerop (get-cast-long (aref column-out-len-ptrs col-nr)))
492                       *null*)
493                      (t
494                       (read-data-in-chunks hstmt col-nr
495                                            (aref column-data-ptrs col-nr) 
496                                            (aref column-c-types col-nr)
497                                            (aref column-sql-types col-nr)
498                                            (aref column-out-len-ptrs col-nr)
499                                            result-type)))))
500        t))))
501
502 (defmethod db-map-query ((database odbc-db) type function query-exp &key result-types)
503   (db-map-query (get-free-query database) type function query-exp :result-types result-types))
504
505 (defmethod db-map-query ((query odbc-query) type function query-exp &key result-types)
506   (declare (ignore type)) ; preliminary. Do a type coersion here
507   (%db-execute query (sql-expression query-exp))
508   (unwind-protect
509     (progn
510       (%initialize-query query nil nil :result-types result-types)
511       ;; the main loop
512       (loop for data = (%read-query-data query nil)
513             while data
514             do (apply function data)))
515     ;; dispose of memory and set query inactive or get rid of it
516     (db-close-query query)))
517
518 (defmethod db-map-bind-query ((query odbc-query) type function 
519                                  &rest parameters)
520   (declare (ignore type)) ; preliminary. Do a type coersion here
521   (unwind-protect
522     (progn
523       (apply #'%db-bind-execute query parameters)
524       ;; the main loop
525       (loop with data
526             while (setf data (%read-query-data query nil))
527             do (apply function data)))
528     ;; dispose of memory and set query inactive or get rid of it
529     (%db-reset-query query)))
530
531 ;; does not always return exactly a lisp type...
532 (defun sql-to-lisp-type (sql-type)
533   (ecase sql-type
534     ((#.odbc::$SQL_CHAR #.odbc::$SQL_VARCHAR #.odbc::$SQL_LONGVARCHAR) :string)
535     ((#.odbc::$SQL_NUMERIC #.odbc::$SQL_DECIMAL #.odbc::$SQL_BIGINT) :string) ; ??
536     (#.odbc::$SQL_INTEGER :long)
537     (#.odbc::$SQL_SMALLINT :short)
538     ((#.odbc::$SQL_FLOAT #.odbc::$SQL_DOUBLE) :long)
539     (#.odbc::$SQL_REAL :long)
540     (#.odbc::$SQL_DATE 'sql-c-date)
541     (#.odbc::$SQL_TIME 'sql-c-time)
542     (#.odbc::$SQL_TIMESTAMP 'sql-c-timestamp)
543     ;;((#.odbc::$SQL_BINARY #.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) odbc::$SQL_C_BINARY) ; ??
544     (#.odbc::$SQL_TINYINT :short)
545     ;;(#.odbc::$SQL_BIT odbc::$SQL_C_BIT) ; ??
546     ((#.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) :binary)
547     ))
548
549 ;; prepared queries
550
551 (defmethod db-prepare-statement ((database odbc-db) sql
552                                      &key parameter-table parameter-columns)
553   (with-slots (hdbc) database
554     (let ((query (get-free-query database))) 
555       (with-slots (hstmt) query
556         (unless hstmt (setf hstmt (%new-statement-handle hdbc))))
557       (db-prepare-statement query sql parameter-table parameter-columns))))
558
559 (defmethod db-prepare-statement ((query odbc-query) (sql string)
560                                      &key parameter-table parameter-columns)
561   ;; this is a workaround to get hold of the column types when the driver does not
562   ;; support SQLDescribeParam. To do: put code in here for drivers that do
563   ;; support it.
564   (unless (string-equal sql "insert" :end1 6)
565     (error "Only insert expressions are supported in literal ODBC: '~a'." sql))
566   (%db-execute query (format nil "select ~{~a~^,~} from ~a where 0 = 1"
567                              (or parameter-columns '("*")) parameter-table))
568   (%initialize-query query nil nil)
569   (with-slots (hstmt) query
570     (%free-statement hstmt :unbind)
571     (%free-statement hstmt :reset)
572     (setf (sql-expression query) sql)
573     (%sql-prepare hstmt sql))
574   query)
575
576
577 (defmethod %db-bind-execute ((query odbc-query) &rest parameters)
578   (with-slots (hstmt parameter-data-ptrs) query
579     (loop for parameter in parameters
580           with data-ptr and size and parameter-string
581           do
582           (setf parameter-string
583                 (if (stringp parameter)
584                   parameter
585                   (write-to-string parameter))
586            size (length parameter-string)
587                 data-ptr 
588                 (uffi:allocate-foreign-string (1+ size)))
589           (vector-push-extend data-ptr parameter-data-ptrs)
590           (%sql-bind-parameter 
591            hstmt (1- (fill-pointer parameter-data-ptrs)) odbc::$SQL_PARAM_INPUT
592            odbc::$SQL_C_CHAR ; (aref column-c-types parameter-count)
593            odbc::$SQL_CHAR ; sql-type
594            (query-width query)          ;precision ; this should be the actual precision!
595            ;; scale
596            0 ;; should be calculated for odbc::$SQL_DECIMAL,
597            ;;$SQL_NUMERIC and odbc::$SQL_TIMESTAMP
598            data-ptr ;; = rgbValue
599            0
600            ;; *pcbValue;
601            ;; change this for output and binary input! (see 3-32)
602            +null-ptr+)
603           (%put-str data-ptr parameter-string size))
604         (%sql-execute hstmt)))
605
606
607 (defmethod %db-reset-query ((query odbc-query))
608   (with-slots (hstmt parameter-data-ptrs) query
609     (prog1
610       (db-fetch-query-results query nil) 
611       (%free-statement hstmt :reset) ;; but _not_ :unbind !
612       (%free-statement hstmt :close)
613       (dotimes (param-nr (fill-pointer parameter-data-ptrs))
614         (let ((data-ptr (aref parameter-data-ptrs param-nr)))
615           (when data-ptr (uffi:free-foreign-object data-ptr))))
616       (setf (fill-pointer parameter-data-ptrs) 0))))
617
618 (defun data-parameter-ptr (hstmt)
619   (uffi:with-foreign-object (param-ptr :pointer-void)
620     (let ((return-code (%sql-param-data hstmt param-ptr)))
621       ;;(format t "~%return-code from %sql-param-data: ~a~%" return-code)
622       (when (= return-code odbc::$SQL_NEED_DATA)
623         ;;(ffc::%pointer-to-address (%get-ptr param-ptr))
624         (uffi:deref-pointer param-ptr :pointer-void)))))
625
626 ;; database inquiery functions
627
628 (defmethod db-describe-columns ((database odbc-db) 
629                                     table-qualifier table-owner table-name column-name)
630   (with-slots (hdbc) database
631     (%describe-columns hdbc table-qualifier table-owner table-name column-name)))
632
633 ;; should translate info-type integers to keywords in order to make this 
634 ;; more readable?
635 (defmethod get-odbc-info ((database odbc-db) info-type)
636   (with-slots (hdbc info) database
637     (or (gethash info-type info)
638         (setf (gethash info-type info)
639               (%sql-get-info hdbc info-type)))))
640
641 (defmethod get-odbc-info ((query odbc-query) info-type)
642   (get-odbc-info (odbc::query-database query) info-type))
643
644 ;; driver inquiery
645 (defmethod db-data-sources ((db-type (eql :odbc)))
646    "Returns a list of (data-source description) - pairs"
647    (let ((henv (%new-environment-handle)))
648     (unwind-protect
649           (loop with direction = :first
650                for data-source+description 
651                = (multiple-value-list (%sql-data-sources henv :direction direction))
652                while (car data-source+description)
653                collect data-source+description
654                do (setf direction :next))
655       (%sql-free-environment henv))))
656
657 ; EOF