Adding todo
[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 (defvar *reuse-query-objects* t)
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 'integer :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 connection-string completion window-handle (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     (if connection-string
133         (%sql-driver-connect (hdbc db)
134                              connection-string
135                              (ecase completion
136                                (:no-prompt odbc::$SQL_DRIVER_NOPROMPT)
137                                (:complete odbc::$SQL_DRIVER_COMPLETE)
138                                (:prompt odbc::$SQL_DRIVER_PROMPT)
139                                (:complete-required odbc::$SQL_DRIVER_COMPLETE_REQUIRED))
140                              window-handle)
141       (%sql-connect (hdbc db) data-source-name user password))
142     #+ignore (setf (db-hstmt db) (%new-statement-handle (hdbc db)))
143     (when (/= (get-odbc-info db odbc::$SQL_TXN_CAPABLE) odbc::$SQL_TC_NONE)
144       (if autocommit
145           (enable-autocommit (hdbc db))
146           (disable-autocommit (hdbc db))))
147     db))
148
149 (defun disconnect (database)
150   "This is set in the generic-odbc-database disconnect-fn slot so xref fails
151    but this does get called on generic ODBC connections "
152   (with-slots (hdbc queries) database
153     (dolist (query queries)
154       (db-close-query query :drop-p T))
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 ;; TODO: Seems to be uncalled
273 (defmethod terminate ((query odbc-query))
274   ;;(format tb::*local-output* "~%*** terminated: ~s" query)
275   (db-close-query query))
276
277 (defun %dispose-column-ptrs (query)
278   "frees memory allocated for query object column-data and column-data-length"
279   (with-slots (column-data-ptrs column-out-len-ptrs hstmt) query
280     (loop for data-ptr across column-data-ptrs
281           for out-len-ptr across column-out-len-ptrs
282           when data-ptr
283             do (uffi:free-foreign-object data-ptr)
284           when out-len-ptr
285             do (uffi:free-foreign-object out-len-ptr))
286     (setf (fill-pointer column-data-ptrs) 0
287           (fill-pointer column-out-len-ptrs) 0)))
288
289 (defmethod db-open-query ((database odbc-db) query-expression
290                           &key arglen col-positions result-types width
291                           &allow-other-keys)
292   (db-open-query (get-free-query database) query-expression
293                  :arglen arglen :col-positions col-positions
294                  :result-types result-types
295                  :width (if width width (db-width database))))
296
297 (defmethod db-open-query ((query odbc-query) query-expression
298                           &key arglen col-positions result-types width
299                           &allow-other-keys)
300   (%db-execute query query-expression)
301   (%initialize-query query arglen col-positions :result-types result-types
302                      :width width))
303
304 (defmethod db-fetch-query-results ((database odbc-db) &optional count)
305   (db-fetch-query-results (db-query-object database) count))
306
307 (defmethod db-fetch-query-results ((query odbc-query) &optional count)
308   (when (query-active-p query)
309     (with-slots (column-count column-data-ptrs column-c-types column-sql-types
310                  column-out-len-ptrs column-precisions hstmt computed-result-types)
311         query
312       (let* ((rows-fetched 0)
313              (rows
314               (loop for i from 0
315                   until (or (and count (= i count))
316                             (= (%sql-fetch hstmt) odbc::$SQL_NO_DATA_FOUND))
317                   collect
318                     (loop for result-type across computed-result-types
319                         for data-ptr across column-data-ptrs
320                         for c-type across column-c-types
321                         for sql-type across column-sql-types
322                         for out-len-ptr across column-out-len-ptrs
323                         for precision across column-precisions
324                         for j from 0    ; column count is zero based in lisp
325                         collect
326                           (progn
327                             (incf rows-fetched)
328                             (cond ((< 0 precision (query-width query))
329                                    (read-data data-ptr c-type sql-type out-len-ptr result-type))
330                                   ((zerop (get-cast-long out-len-ptr))
331                                    nil)
332                                   (t
333                                    (read-data-in-chunks hstmt j data-ptr c-type sql-type
334                                                         out-len-ptr result-type))))))))
335         (values rows query rows-fetched)))))
336
337 (defun db-query (database query-expression &key result-types width)
338   (let ((free-query (get-free-query database)))
339     (setf (sql-expression free-query) query-expression)
340     (unwind-protect
341       (progn
342         (%db-execute free-query query-expression)
343         (%initialize-query free-query nil nil :result-types result-types :width width)
344         (if (plusp (column-count free-query)) ;; KMR: Added check for commands that don't return columns
345             (values
346              (db-fetch-query-results free-query nil)
347              (map 'list #'identity (column-names free-query)))
348           (values
349            (result-rows-count (hstmt free-query))
350            nil)))
351       (db-close-query free-query)
352       )))
353
354 (defmethod %db-execute ((database odbc-db) sql-expression &key &allow-other-keys)
355   (%db-execute (get-free-query database) sql-expression))
356
357 (defmethod %db-execute ((query odbc-query) sql-expression &key &allow-other-keys)
358   (with-slots (henv hdbc) (odbc::query-database query)
359     (with-slots (hstmt) query
360       (unless hstmt (setf hstmt (%new-statement-handle hdbc)))
361       (setf (sql-expression query) sql-expression)
362       (%sql-exec-direct sql-expression hstmt henv hdbc)
363       query)))
364
365 ;; reuse inactive queries
366 (defun get-free-query (database)
367   "get-free-query finds or makes a nonactive query object, and then sets it to active.
368 This makes the functions db-execute-command and db-query thread safe."
369   (with-slots (queries hdbc) database
370     (or (and *reuse-query-objects*
371              (clsql-sys:without-interrupts
372                (let ((inactive-query (find-if (lambda (query)
373                                                 (not (query-active-p query)))
374                                               queries)))
375                  (when inactive-query
376                    (with-slots (column-count column-names column-c-types
377                                 width hstmt
378                                 column-sql-types column-data-ptrs
379                                 column-out-len-ptrs column-precisions
380                                 column-scales column-nullables-p)
381                        inactive-query
382                      (setf column-count 0
383                            width +max-precision+
384                            ;; KMR hstmt (%new-statement-handle hdbc)
385                            (fill-pointer column-names) 0
386                            (fill-pointer column-c-types) 0
387                            (fill-pointer column-sql-types) 0
388                            (fill-pointer column-data-ptrs) 0
389                            (fill-pointer column-out-len-ptrs) 0
390                            (fill-pointer column-precisions) 0
391                            (fill-pointer column-scales) 0
392                            (fill-pointer column-nullables-p) 0))
393                    (setf (query-active-p inactive-query) t))
394                  inactive-query)))
395         (let ((new-query (make-instance 'odbc-query
396                                         :database database
397                                         ;;(clone-database database)
398                                         :active-p t)))
399           (push new-query queries)
400           new-query))))
401
402 (defmethod db-execute-command ((database odbc-db) sql-string)
403   (db-execute-command (get-free-query database) sql-string))
404
405 (defmethod db-execute-command ((query odbc-query) sql-string)
406   (with-slots (hstmt database) query
407     (with-slots (henv hdbc) database
408       (unless hstmt (setf hstmt (%new-statement-handle hdbc)))
409       (unwind-protect
410           (%sql-exec-direct sql-string hstmt henv hdbc)
411         (db-close-query query)))))
412
413 (defmethod %initialize-query ((database odbc-db) arglen col-positions &key result-types width)
414   (%initialize-query (db-query-object database) arglen col-positions
415                      :result-types result-types
416                      :width (if width width (db-width database))))
417
418 (defmethod %initialize-query ((query odbc-query) arglen col-positions &key result-types width)
419   (with-slots (hstmt computed-result-types
420                column-count column-names column-c-types column-sql-types
421                column-data-ptrs column-out-len-ptrs column-precisions
422                column-scales column-nullables-p)
423       query
424     (setf column-count (if arglen
425                          (min arglen (result-columns-count hstmt))
426                          (result-columns-count hstmt)))
427     (when width (setf (query-width query) width))
428     ;;(format tb::*local-output* "~%column-count: ~d, col-positions: ~d" column-count col-positions)
429     (labels ((initialize-column (col-nr)
430                 (multiple-value-bind (name sql-type precision scale nullable-p)
431                                      (%describe-column hstmt (1+ col-nr))
432                   ;; allocate space to bind result rows to
433                   (multiple-value-bind (c-type data-ptr out-len-ptr size long-p)
434                                        (%allocate-bindings sql-type precision)
435                     (if long-p ;; if long-p we fetch in chunks with %sql-get-data but must ensure that out_len_ptr is non zero
436                         (setf (uffi:deref-pointer out-len-ptr #.odbc::$ODBC-LONG-TYPE) #.odbc::$SQL_NO_TOTAL)
437                       (%bind-column hstmt col-nr c-type data-ptr (1+ size) out-len-ptr))
438                     (vector-push-extend name column-names)
439                     (vector-push-extend sql-type column-sql-types)
440                     (vector-push-extend (sql-to-c-type sql-type) column-c-types)
441                     (vector-push-extend precision column-precisions)
442                     (vector-push-extend scale column-scales)
443                     (vector-push-extend nullable-p column-nullables-p)
444                     (vector-push-extend data-ptr column-data-ptrs)
445                     (vector-push-extend out-len-ptr column-out-len-ptrs)))))
446       (if col-positions
447         (dolist (col-nr col-positions)
448           (initialize-column col-nr))
449         (dotimes (col-nr column-count)
450           ;; get column information
451           (initialize-column col-nr))))
452
453     ;; TODO: move this into the above loop
454     (setf computed-result-types (make-array column-count))
455     (dotimes (i column-count)
456       (setf (aref computed-result-types i)
457             (cond
458               ((consp result-types)
459                (nth i result-types))
460               ((eq result-types :auto)
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_C_SBIGINT #.odbc::$ODBC-BIG-TYPE)
468                  (#.odbc::$SQL_C_TYPE_TIMESTAMP :time)
469                  (#.odbc::$SQL_C_CHAR ;; TODO: Read this as rational instead of double
470                    (or (case (aref column-sql-types i)
471                          (#.odbc::$SQL_NUMERIC :double))
472                        T))
473
474                  (t t)))
475               (t t)))))
476   query)
477
478 (defun db-close-query (query &key (drop-p (not *reuse-query-objects*)))
479   (with-slots (hstmt column-count column-names column-c-types column-sql-types
480                column-data-ptrs column-out-len-ptrs column-precisions
481                column-scales column-nullables-p database) query
482     (%dispose-column-ptrs query)
483     (cond ((null hstmt) nil)
484           (drop-p
485            (%free-statement hstmt :drop)
486            ;; dont free with uffi/ this is a double free and crashes everything
487            ;; (uffi:free-foreign-object hstmt)
488            (setf hstmt nil))
489           (t
490            (%free-statement hstmt :unbind)
491            (%free-statement hstmt :reset)
492            (%free-statement hstmt :close)))
493     (setf (query-active-p query) nil)
494     (when drop-p
495       (clsql-sys:without-interrupts
496         (with-slots (queries) database
497           (setf queries (remove query queries))))))
498   query)
499
500 (defmethod %read-query-data ((database odbc-db) ignore-columns)
501   (%read-query-data (db-query-object database) ignore-columns))
502
503 (defmethod %read-query-data ((query odbc-query) ignore-columns)
504   (with-slots (hstmt column-count column-c-types column-sql-types
505                column-data-ptrs column-out-len-ptrs column-precisions
506                computed-result-types)
507       query
508     (unless (= (odbc::SQLFetch hstmt) odbc::$SQL_NO_DATA_FOUND)
509       (values
510        (loop for col-nr from 0 to (- column-count
511                                      (if (eq ignore-columns :last) 2 1))
512            for result-type across computed-result-types
513            collect
514              (let ((precision (aref column-precisions col-nr))
515                    (sql-type (aref column-sql-types col-nr)))
516                (cond ((or (< 0 precision (query-width query))
517                           (and (zerop precision) (not (find sql-type '($SQL_C_CHAR)))))
518                       (read-data (aref column-data-ptrs col-nr)
519                                  (aref column-c-types col-nr)
520                                  sql-type
521                                  (aref column-out-len-ptrs col-nr)
522                                  result-type))
523                      ((zerop (get-cast-long (aref column-out-len-ptrs col-nr)))
524                       *null*)
525                      (t
526                       (read-data-in-chunks hstmt col-nr
527                                            (aref column-data-ptrs col-nr)
528                                            (aref column-c-types col-nr)
529                                            (aref column-sql-types col-nr)
530                                            (aref column-out-len-ptrs col-nr)
531                                            result-type)))))
532        t))))
533
534 (defmethod db-map-query ((database odbc-db) type function query-exp &key result-types)
535   (db-map-query (get-free-query database) type function query-exp :result-types result-types))
536
537 (defmethod db-map-query ((query odbc-query) type function query-exp &key result-types)
538   (declare (ignore type)) ; preliminary. Do a type coersion here
539   (%db-execute query (sql-expression query-exp))
540   (unwind-protect
541     (progn
542       (%initialize-query query nil nil :result-types result-types)
543       ;; the main loop
544       (loop for data = (%read-query-data query nil)
545             while data
546             do (apply function data)))
547     ;; dispose of memory and set query inactive or get rid of it
548     (db-close-query query)))
549
550 (defun db-map-bind-query (query type function
551                           &rest parameters)
552   (declare (ignore type)) ; preliminary. Do a type coersion here
553   (unwind-protect
554     (progn
555       (apply #'%db-bind-execute query parameters)
556       ;; the main loop
557       (loop with data
558             while (setf data (%read-query-data query nil))
559             do (apply function data)))
560     ;; dispose of memory and set query inactive or get rid of it
561     (%db-reset-query query)))
562
563 ;; does not always return exactly a lisp type...
564 (defun sql-to-lisp-type (sql-type)
565   (ecase sql-type
566     ((#.odbc::$SQL_CHAR #.odbc::$SQL_VARCHAR #.odbc::$SQL_LONGVARCHAR) :string)
567     ((#.odbc::$SQL_NUMERIC #.odbc::$SQL_DECIMAL) :string) ; ??
568     (#.odbc::$SQL_BIGINT #.odbc::$ODBC-BIG-TYPE)
569     (#.odbc::$SQL_INTEGER #.odbc::$ODBC-LONG-TYPE)
570     (#.odbc::$SQL_SMALLINT :short)
571     ((#.odbc::$SQL_FLOAT #.odbc::$SQL_DOUBLE) #.odbc::$ODBC-LONG-TYPE)
572     (#.odbc::$SQL_REAL #.odbc::$ODBC-LONG-TYPE)
573     ((#.odbc::$SQL_DATE #.odbc::$SQL_TYPE_DATE) 'sql-c-date)
574     ((#.odbc::$SQL_TIME #.odbc::$SQL_TYPE_TIME) 'sql-c-time)
575     ((#.odbc::$SQL_TIMESTAMP #.odbc::$SQL_TYPE_TIMESTAMP) 'sql-c-timestamp)
576     ;;((#.odbc::$SQL_BINARY #.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) odbc::$SQL_C_BINARY) ; ??
577     (#.odbc::$SQL_TINYINT :short)
578     ;;(#.odbc::$SQL_BIT odbc::$SQL_C_BIT) ; ??
579     (#.odbc::$SQL_BIT :short)
580     ((#.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) :binary)
581     ))
582
583 ;; prepared queries
584
585 (defmethod db-prepare-statement ((database odbc-db) sql
586                                      &key parameter-table parameter-columns)
587   (with-slots (hdbc) database
588     (let ((query (get-free-query database)))
589       (with-slots (hstmt) query
590         (unless hstmt (setf hstmt (%new-statement-handle hdbc))))
591       (db-prepare-statement
592        query sql :parameter-table parameter-table :parameter-columns parameter-columns))))
593
594 (defmethod db-prepare-statement ((query odbc-query) (sql string)
595                                      &key parameter-table parameter-columns)
596   ;; this is a workaround to get hold of the column types when the driver does not
597   ;; support SQLDescribeParam. To do: put code in here for drivers that do
598   ;; support it.
599   (unless (string-equal sql "insert" :end1 6)
600     (error 'clsql:sql-database-error
601            (format nil
602                    "Only insert expressions are supported in literal ODBC: '~a'." sql)))
603   (%db-execute query (format nil "select ~{~a~^,~} from ~a where 0 = 1"
604                              (or parameter-columns '("*")) parameter-table))
605   (%initialize-query query nil nil)
606   (with-slots (hstmt) query
607     (%free-statement hstmt :unbind)
608     (%free-statement hstmt :reset)
609     (setf (sql-expression query) sql)
610     (%sql-prepare hstmt sql))
611   query)
612
613
614 (defun %db-bind-execute (query &rest parameters)
615   "Only used from db-map-bind-query
616     parameters are released in %reset-query
617   "
618   (with-slots (hstmt parameter-data-ptrs) query
619     (loop for parameter in parameters
620           with data-ptr and size and parameter-string
621           do
622           (setf parameter-string
623                 (if (stringp parameter)
624                     parameter
625                     (write-to-string parameter))
626                 size (length parameter-string)
627                 data-ptr
628                 (uffi:allocate-foreign-string (1+ size)))
629           (vector-push-extend data-ptr parameter-data-ptrs)
630           (%sql-bind-parameter
631            hstmt (1- (fill-pointer parameter-data-ptrs)) odbc::$SQL_PARAM_INPUT
632            odbc::$SQL_C_CHAR ; (aref column-c-types parameter-count)
633            odbc::$SQL_CHAR ; sql-type
634            (query-width query)          ;precision ; this should be the actual precision!
635            ;; scale
636            0 ;; should be calculated for odbc::$SQL_DECIMAL,
637            ;;$SQL_NUMERIC and odbc::$SQL_TIMESTAMP
638            data-ptr ;; = rgbValue
639            0
640            ;; *pcbValue;
641            ;; change this for output and binary input! (see 3-32)
642            +null-ptr+)
643           (%put-str data-ptr parameter-string size))
644         (%sql-execute hstmt)))
645
646
647 (defun %db-reset-query (query)
648   "Only used from db-map-bind-query
649     parameters are allocated in %db-bind-execute
650   "
651   (with-slots (hstmt parameter-data-ptrs) query
652     (prog1
653         (db-fetch-query-results query nil)
654       (%free-statement hstmt :reset) ;; but _not_ :unbind !
655       (%free-statement hstmt :close)
656       (dotimes (param-nr (fill-pointer parameter-data-ptrs))
657         (let ((data-ptr (aref parameter-data-ptrs param-nr)))
658           (when data-ptr (uffi:free-foreign-object data-ptr))))
659       (setf (fill-pointer parameter-data-ptrs) 0))))
660
661 (defun data-parameter-ptr (hstmt)
662   (uffi:with-foreign-object (param-ptr :pointer-void)
663     (let ((return-code (%sql-param-data hstmt param-ptr)))
664       ;;(format t "~%return-code from %sql-param-data: ~a~%" return-code)
665       (when (= return-code odbc::$SQL_NEED_DATA)
666         ;;(ffc::%pointer-to-address (%get-ptr param-ptr))
667         (uffi:deref-pointer param-ptr :pointer-void)))))
668
669 ;; database inquiery functions
670
671 (defun db-describe-columns (database table-qualifier table-owner
672                             table-name column-name)
673   (with-slots (hdbc) database
674     (%describe-columns hdbc table-qualifier table-owner table-name column-name)))
675
676 ;; should translate info-type integers to keywords in order to make this
677 ;; more readable?
678 (defmethod get-odbc-info ((database odbc-db) info-type)
679   (with-slots (hdbc info) database
680     (or (gethash info-type info)
681         (setf (gethash info-type info)
682               (%sql-get-info hdbc info-type)))))
683
684 (defmethod get-odbc-info ((query odbc-query) info-type)
685   (get-odbc-info (odbc::query-database query) info-type))
686
687 ;; driver inquiry
688 ;; How does this differ from list-data-sources?
689 (defgeneric db-data-sources (db-type))
690 (defmethod db-data-sources ((db-type (eql :odbc)))
691    "Returns a list of (data-source description) - pairs"
692    (let ((henv (%new-environment-handle)))
693     (unwind-protect
694           (loop with direction = :first
695                for data-source+description
696                = (multiple-value-list (%sql-data-sources henv :direction direction))
697                while (car data-source+description)
698                collect data-source+description
699                do (setf direction :next))
700       (%sql-free-environment henv))))