Dont declare the the column precisions to be a fixnum since odbc
[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 'integer :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_BIT :short)
463               (#.odbc::$SQL_C_SLONG :int)
464               (#.odbc::$SQL_C_DOUBLE :double)
465               (#.odbc::$SQL_C_FLOAT :float)
466               (#.odbc::$SQL_C_SSHORT :short)
467               (#.odbc::$SQL_C_STINYINT :short)
468               (#.odbc::$SQL_BIGINT :short)
469               (t t))))
470           (t
471            t)))))
472   query)
473
474 (defun db-close-query (query &key drop-p)
475   (with-slots (hstmt column-count column-names column-c-types column-sql-types
476                      column-data-ptrs column-out-len-ptrs column-precisions
477                      column-scales column-nullables-p) query
478     (let ((count (fill-pointer column-data-ptrs)))
479       (when (not (zerop count))
480         (dotimes (col-nr count)
481           (let ((data-ptr (aref column-data-ptrs col-nr))
482                 (out-len-ptr (aref column-out-len-ptrs col-nr)))
483             (declare (ignorable data-ptr out-len-ptr))
484             ;; free-statment :unbind frees these
485             #+ignore (when data-ptr (uffi:free-foreign-object data-ptr))
486             #+ignore (when out-len-ptr (uffi:free-foreign-object out-len-ptr)))))
487       (cond ((null hstmt)
488              nil)
489             (drop-p
490              (%free-statement hstmt :drop)
491              (setf hstmt nil))
492             (t
493              (%free-statement hstmt :unbind)
494              (%free-statement hstmt :reset)
495              (%free-statement hstmt :close)))
496       (setf (query-active-p query) nil)))
497   query)
498
499 (defmethod %read-query-data ((database odbc-db) ignore-columns)
500   (%read-query-data (db-query-object database) ignore-columns))
501
502 (defmethod %read-query-data ((query odbc-query) ignore-columns)
503   (with-slots (hstmt column-count column-c-types column-sql-types
504                column-data-ptrs column-out-len-ptrs column-precisions
505                computed-result-types)
506       query
507     (unless (= (odbc::SQLFetch hstmt) odbc::$SQL_NO_DATA_FOUND)
508       (values
509        (loop for col-nr from 0 to (- column-count
510                                      (if (eq ignore-columns :last) 2 1))
511            for result-type across computed-result-types
512            collect
513              (let ((precision (aref column-precisions col-nr))
514                    (sql-type (aref column-sql-types col-nr)))
515                (cond ((or (< 0 precision (query-width query))
516                           (and (zerop precision) (not (find sql-type '($SQL_C_CHAR)))))
517                       (read-data (aref column-data-ptrs col-nr)
518                                  (aref column-c-types col-nr)
519                                  sql-type
520                                  (aref column-out-len-ptrs col-nr)
521                                  result-type))
522                      ((zerop (get-cast-long (aref column-out-len-ptrs col-nr)))
523                       *null*)
524                      (t
525                       (read-data-in-chunks hstmt col-nr
526                                            (aref column-data-ptrs col-nr)
527                                            (aref column-c-types col-nr)
528                                            (aref column-sql-types col-nr)
529                                            (aref column-out-len-ptrs col-nr)
530                                            result-type)))))
531        t))))
532
533 (defmethod db-map-query ((database odbc-db) type function query-exp &key result-types)
534   (db-map-query (get-free-query database) type function query-exp :result-types result-types))
535
536 (defmethod db-map-query ((query odbc-query) type function query-exp &key result-types)
537   (declare (ignore type)) ; preliminary. Do a type coersion here
538   (%db-execute query (sql-expression query-exp))
539   (unwind-protect
540     (progn
541       (%initialize-query query nil nil :result-types result-types)
542       ;; the main loop
543       (loop for data = (%read-query-data query nil)
544             while data
545             do (apply function data)))
546     ;; dispose of memory and set query inactive or get rid of it
547     (db-close-query query)))
548
549 (defun db-map-bind-query (query type function
550                           &rest parameters)
551   (declare (ignore type)) ; preliminary. Do a type coersion here
552   (unwind-protect
553     (progn
554       (apply #'%db-bind-execute query parameters)
555       ;; the main loop
556       (loop with data
557             while (setf data (%read-query-data query nil))
558             do (apply function data)))
559     ;; dispose of memory and set query inactive or get rid of it
560     (%db-reset-query query)))
561
562 ;; does not always return exactly a lisp type...
563 (defun sql-to-lisp-type (sql-type)
564   (ecase sql-type
565     ((#.odbc::$SQL_CHAR #.odbc::$SQL_VARCHAR #.odbc::$SQL_LONGVARCHAR) :string)
566     ((#.odbc::$SQL_NUMERIC #.odbc::$SQL_DECIMAL #.odbc::$SQL_BIGINT) :string) ; ??
567     (#.odbc::$SQL_INTEGER #.odbc::$ODBC-LONG-TYPE)
568     (#.odbc::$SQL_SMALLINT :short)
569     ((#.odbc::$SQL_FLOAT #.odbc::$SQL_DOUBLE) #.odbc::$ODBC-LONG-TYPE)
570     (#.odbc::$SQL_REAL #.odbc::$ODBC-LONG-TYPE)
571     ((#.odbc::$SQL_DATE #.odbc::$SQL_TYPE_DATE) 'sql-c-date)
572     ((#.odbc::$SQL_TIME #.odbc::$SQL_TYPE_TIME) 'sql-c-time)
573     ((#.odbc::$SQL_TIMESTAMP #.odbc::$SQL_TYPE_TIMESTAMP) 'sql-c-timestamp)
574     ;;((#.odbc::$SQL_BINARY #.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) odbc::$SQL_C_BINARY) ; ??
575     (#.odbc::$SQL_TINYINT :short)
576     ;;(#.odbc::$SQL_BIT odbc::$SQL_C_BIT) ; ??
577     (#.odbc::$SQL_BIT :short)
578     ((#.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) :binary)
579     ))
580
581 ;; prepared queries
582
583 (defmethod db-prepare-statement ((database odbc-db) sql
584                                      &key parameter-table parameter-columns)
585   (with-slots (hdbc) database
586     (let ((query (get-free-query database)))
587       (with-slots (hstmt) query
588         (unless hstmt (setf hstmt (%new-statement-handle hdbc))))
589       (db-prepare-statement query sql parameter-table parameter-columns))))
590
591 (defmethod db-prepare-statement ((query odbc-query) (sql string)
592                                      &key parameter-table parameter-columns)
593   ;; this is a workaround to get hold of the column types when the driver does not
594   ;; support SQLDescribeParam. To do: put code in here for drivers that do
595   ;; support it.
596   (unless (string-equal sql "insert" :end1 6)
597     (error 'clsql:sql-database-error
598            (format nil
599                    "Only insert expressions are supported in literal ODBC: '~a'." sql)))
600   (%db-execute query (format nil "select ~{~a~^,~} from ~a where 0 = 1"
601                              (or parameter-columns '("*")) parameter-table))
602   (%initialize-query query nil nil)
603   (with-slots (hstmt) query
604     (%free-statement hstmt :unbind)
605     (%free-statement hstmt :reset)
606     (setf (sql-expression query) sql)
607     (%sql-prepare hstmt sql))
608   query)
609
610
611 (defun %db-bind-execute (query &rest parameters)
612   (with-slots (hstmt parameter-data-ptrs) query
613     (loop for parameter in parameters
614           with data-ptr and size and parameter-string
615           do
616           (setf parameter-string
617                 (if (stringp parameter)
618                   parameter
619                   (write-to-string parameter))
620            size (length parameter-string)
621                 data-ptr
622                 (uffi:allocate-foreign-string (1+ size)))
623           (vector-push-extend data-ptr parameter-data-ptrs)
624           (%sql-bind-parameter
625            hstmt (1- (fill-pointer parameter-data-ptrs)) odbc::$SQL_PARAM_INPUT
626            odbc::$SQL_C_CHAR ; (aref column-c-types parameter-count)
627            odbc::$SQL_CHAR ; sql-type
628            (query-width query)          ;precision ; this should be the actual precision!
629            ;; scale
630            0 ;; should be calculated for odbc::$SQL_DECIMAL,
631            ;;$SQL_NUMERIC and odbc::$SQL_TIMESTAMP
632            data-ptr ;; = rgbValue
633            0
634            ;; *pcbValue;
635            ;; change this for output and binary input! (see 3-32)
636            +null-ptr+)
637           (%put-str data-ptr parameter-string size))
638         (%sql-execute hstmt)))
639
640
641 (defun %db-reset-query (query)
642   (with-slots (hstmt parameter-data-ptrs) query
643     (prog1
644       (db-fetch-query-results query nil)
645       (%free-statement hstmt :reset) ;; but _not_ :unbind !
646       (%free-statement hstmt :close)
647       (dotimes (param-nr (fill-pointer parameter-data-ptrs))
648         (let ((data-ptr (aref parameter-data-ptrs param-nr)))
649           (when data-ptr (uffi:free-foreign-object data-ptr))))
650       (setf (fill-pointer parameter-data-ptrs) 0))))
651
652 (defun data-parameter-ptr (hstmt)
653   (uffi:with-foreign-object (param-ptr :pointer-void)
654     (let ((return-code (%sql-param-data hstmt param-ptr)))
655       ;;(format t "~%return-code from %sql-param-data: ~a~%" return-code)
656       (when (= return-code odbc::$SQL_NEED_DATA)
657         ;;(ffc::%pointer-to-address (%get-ptr param-ptr))
658         (uffi:deref-pointer param-ptr :pointer-void)))))
659
660 ;; database inquiery functions
661
662 (defun db-describe-columns (database table-qualifier table-owner
663                             table-name column-name)
664   (with-slots (hdbc) database
665     (%describe-columns hdbc table-qualifier table-owner table-name column-name)))
666
667 ;; should translate info-type integers to keywords in order to make this
668 ;; more readable?
669 (defmethod get-odbc-info ((database odbc-db) info-type)
670   (with-slots (hdbc info) database
671     (or (gethash info-type info)
672         (setf (gethash info-type info)
673               (%sql-get-info hdbc info-type)))))
674
675 (defmethod get-odbc-info ((query odbc-query) info-type)
676   (get-odbc-info (odbc::query-database query) info-type))
677
678 ;; driver inquiry
679 ;; How does this differ from list-data-sources?
680 (defgeneric db-data-sources (db-type))
681 (defmethod db-data-sources ((db-type (eql :odbc)))
682    "Returns a list of (data-source description) - pairs"
683    (let ((henv (%new-environment-handle)))
684     (unwind-protect
685           (loop with direction = :first
686                for data-source+description
687                = (multiple-value-list (%sql-data-sources henv :direction direction))
688                while (car data-source+description)
689                collect data-source+description
690                do (setf direction :next))
691       (%sql-free-environment henv))))