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