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