1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
6 ;;;; Purpose: Mid-level (DBI) interface for CLSQL ODBC backend
7 ;;;; Author: Kevin M. Rosenberg
8 ;;;; Create: April 2004
10 ;;;; $Id: odbc-sql.lisp 8983 2004-04-12 21:16:48Z kevin $
12 ;;;; This file, part of CLSQL, is Copyright (c) 2002 by Kevin M. Rosenberg
14 ;;;; CLSQL users are granted the rights to distribute and use this software
15 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
16 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
17 ;;;; *************************************************************************
19 (in-package #:cl-user)
21 (defpackage #:odbc-dbi
33 #:list-all-data-sources
34 #:list-all-database-tables
35 #:list-all-table-columns
46 #:*default-odbc-external-format*
49 (:documentation "This is the mid-level interface ODBC."))
51 (in-package #:odbc-dbi)
56 (;; any reason to have more than one henv?
57 (width :initform +max-precision+ :accessor db-width)
58 (hstmt :initform nil :accessor db-hstmt)
59 (henv :initform nil :allocation :class :initarg :henv :accessor henv)
60 (hdbc :initform nil :initarg :hdbc :accessor hdbc)
61 ;; info returned from SQLGetInfo
62 (info :initform (make-hash-table) :reader db-info)
63 (type :initform nil :initarg :db-type :reader db-type)
64 (connected-p :initform nil :accessor db-connected-p)
66 (count :initform 0 :initarg :count :accessor db-count)
68 (total-count :initform 0 :allocation :class :accessor db-total-count)
69 ;; the use of this slot is deprecated; it will be removed when dtf works without it.
70 (query :initform nil :accessor db-query-object)
71 ;; resource of (active and inactive) query objects
72 (queries :initform () :accessor db-queries)))
74 (defclass odbc-query ()
75 ((hstmt :initform nil :initarg :hstmt :accessor hstmt) ; = cursor??
76 (width :initform +max-precision+ :accessor query-width)
77 (computed-result-types :initform nil :initarg :computed-result-types :accessor computed-result-types)
78 (column-count :initform nil :accessor column-count)
79 (column-names :initform (make-array 0 :element-type 'string :adjustable t :fill-pointer t)
80 :accessor column-names)
81 (column-c-types :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
82 :accessor column-c-types)
83 (column-sql-types :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
84 :accessor column-sql-types)
85 (column-data-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
87 (column-out-len-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
88 :accessor column-out-len-ptrs)
89 (column-precisions :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
90 :accessor column-precisions)
91 (column-scales :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
92 :accessor column-scales)
93 (column-nullables-p :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
94 :accessor column-nullables-p)
95 ;;(parameter-count :initform 0 :accessor parameter-count)
96 (parameter-data-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
97 :accessor parameter-ptrs)
98 ;; a query string or a query expression object
99 (sql-expression :initform nil :initarg :sql-expression :accessor sql-expression)
100 ;; database object the query is to be run against
101 (database :initarg :database :reader query-database)
102 (active-p :initform nil :initarg :active-p :accessor query-active-p))
104 "Stores query information, like SQL query string/expression and database to run
105 the query against." ))
107 ;;; AODBC Compatible interface
109 (defun connect (&key data-source-name user password (autocommit t))
110 (let ((db (make-instance 'odbc-db)))
111 (unless (henv db) ;; has class allocation!
112 (setf (henv db) (%new-environment-handle)))
113 (setf (hdbc db) (%new-db-connection-handle (henv db)))
114 (%sql-connect (hdbc db) data-source-name user password)
115 #+ignore (setf (db-hstmt db) (%new-statement-handle (hdbc db)))
116 (when (/= (get-odbc-info db odbc::$SQL_TXN_CAPABLE) odbc::$SQL_TC_NONE)
118 (enable-autocommit (hdbc db))
119 (disable-autocommit (hdbc db))))
122 (defun disconnect (database)
123 (with-slots (hdbc queries) database
124 (dolist (query queries)
125 (if (query-active-p query)
126 (with-slots (hstmt) query
128 (%free-statement hstmt :drop)
130 (when (db-hstmt database)
131 (%free-statement (db-hstmt database) :drop))
135 (defun sql (expr &key db result-types row-count (column-names t) query
137 (declare (ignore hstmt))
140 (let ((q (db-open-query db expr :result-types result-types :width width)))
142 (values q (column-names q))
145 (multiple-value-bind (data col-names)
146 (db-query db expr :result-types result-types :width width)
149 (if (consp data) (length data) data))
151 (values data col-names))
155 (defun fetch-row (query &optional (eof-errorp t) eof-value)
156 (multiple-value-bind (row query count) (db-fetch-query-results query 1)
161 (error 'clsql-odbc-error :odbc-message "Ran out of data in fetch-row"))
167 (defun close-query (query)
168 (db-close-query query))
170 (defun list-all-database-tables (&key db hstmt)
171 (declare (ignore hstmt))
172 (let ((query (get-free-query db)))
175 (with-slots (hstmt) query
176 (unless hstmt (setf hstmt (%new-statement-handle (hdbc db))))
178 (%initialize-query query nil nil)
180 (db-fetch-query-results query)
181 (coerce (column-names query) 'list))))
182 (db-close-query query))))
184 (defun list-table-indexes (table &key db unique hstmt)
185 (declare (ignore hstmt))
186 (let ((query (get-free-query db)))
189 (with-slots (hstmt) query
191 (setf hstmt (%new-statement-handle (hdbc db))))
192 (%table-statistics table hstmt :unique unique)
193 (%initialize-query query nil nil)
195 (db-fetch-query-results query)
196 (coerce (column-names query) 'list))))
197 (db-close-query query))))
199 (defun list-all-table-columns (table &key db hstmt)
200 (declare (ignore hstmt))
201 (db-describe-columns db "" "" table ""))
203 (defun list-all-data-sources ()
204 (let ((db (make-instance 'odbc-db)))
205 (unless (henv db) ;; has class allocation!
206 (setf (henv db) (%new-environment-handle)))
207 (%list-data-sources (henv db))))
209 (defun rr-sql (hstmt sql-statement &key db)
210 (declare (ignore hstmt sql-statement db))
211 (warn "rr-sql not implemented."))
213 ;;; Mid-level interface
215 (defmethod db-commit ((database odbc-db))
216 (%commit (henv database) (hdbc database)))
218 (defmethod db-rollback ((database odbc-db))
219 (%rollback (henv database) (hdbc database)))
221 (defmethod db-cancel-query ((query odbc-query))
222 (with-slots (hstmt) query
224 (setf (query-active-p query) nil)))
227 (defmacro with-transaction (&body body)
229 (:henv (henv ,*default-database*) :hdbc (hdbc ,*default-database*))
232 (defmethod initialize-instance :after ((query odbc-query)
233 &key sql henv hdbc &allow-other-keys)
235 (let ((hstmt (%new-statement-handle hdbc)))
236 (%sql-exec-direct sql hstmt henv hdbc)
237 (with-slots (column-count
238 column-names column-c-types column-sql-types column-data-ptrs
239 column-out-len-ptrs column-precisions column-scales
240 column-nullables-p active-p) query
241 (setf (hstmt query) hstmt)
242 (%initialize-query query nil nil)
243 (setf active-p t)))))
245 ;; one for odbc-db is missing
246 (defmethod terminate ((query odbc-query))
247 ;;(format tb::*local-output* "~%*** terminated: ~s" query)
248 (with-slots (hstmt) query
250 ;(%free-statement hstmt :drop)
251 (uffi:free-foreign-object hstmt)) ;; ??
252 (%dispose-column-ptrs query)))
254 (defmethod %dispose-column-ptrs ((query odbc-query))
255 (with-slots (column-data-ptrs column-out-len-ptrs hstmt) query
256 (loop for data-ptr across column-data-ptrs
257 when data-ptr do (uffi:free-foreign-object data-ptr))
258 (loop for out-len-ptr across column-out-len-ptrs
259 when out-len-ptr do (uffi:free-foreign-object out-len-ptr))))
261 (defmethod db-open-query ((database odbc-db) query-expression
262 &key arglen col-positions result-types width
264 (db-open-query (get-free-query database) query-expression
265 :arglen arglen :col-positions col-positions
266 :result-types result-types
267 :width (if width width (db-width database))))
269 (defmethod db-open-query ((query odbc-query) query-expression
270 &key arglen col-positions result-types width
272 (%db-execute query query-expression)
273 (%initialize-query query arglen col-positions :result-types result-types
276 (defmethod db-fetch-query-results ((database odbc-db) &optional count)
277 (db-fetch-query-results (db-query-object database) count))
279 (defmethod db-fetch-query-results ((query odbc-query) &optional count)
280 (when (query-active-p query)
281 (with-slots (column-count column-data-ptrs column-c-types column-sql-types
282 column-out-len-ptrs column-precisions hstmt computed-result-types)
284 (let* ((rows-fetched 0)
287 until (or (and count (= i count))
288 (= (%sql-fetch hstmt) odbc::$SQL_NO_DATA_FOUND))
290 (loop for result-type across computed-result-types
291 for data-ptr across column-data-ptrs
292 for c-type across column-c-types
293 for sql-type across column-sql-types
294 for out-len-ptr across column-out-len-ptrs
295 for precision across column-precisions
296 for j from 0 ; column count is zero based in lisp
300 (cond ((< 0 precision (query-width query))
301 (read-data data-ptr c-type sql-type out-len-ptr result-type))
302 ((zerop (get-cast-long out-len-ptr))
305 (read-data-in-chunks hstmt j data-ptr c-type sql-type
306 out-len-ptr result-type))))))))
307 (values rows query rows-fetched)))))
309 (defmethod db-query ((database odbc-db) query-expression &key result-types width)
310 (let ((free-query (get-free-query database)))
311 (setf (sql-expression free-query) query-expression)
314 (%db-execute free-query query-expression)
315 (%initialize-query free-query nil nil :result-types result-types :width width)
316 (if (plusp (column-count free-query)) ;; KMR: Added check for commands that don't return columns
318 (db-fetch-query-results free-query nil)
319 (column-names free-query))
321 (result-rows-count (hstmt free-query))
323 (db-close-query free-query)
326 (defmethod %db-execute ((database odbc-db) sql-expression &key &allow-other-keys)
327 (%db-execute (get-free-query database) sql-expression))
329 (defmethod %db-execute ((query odbc-query) sql-expression &key &allow-other-keys)
330 (with-slots (henv hdbc) (odbc::query-database query)
331 (with-slots (hstmt) query
332 (unless hstmt (setf hstmt (%new-statement-handle hdbc)))
333 (setf (sql-expression query) sql-expression)
334 (%sql-exec-direct sql-expression hstmt henv hdbc)
337 ;; reuse inactive queries
338 (defmethod get-free-query ((database odbc-db))
339 "get-free-query finds or makes a nonactive query object, and then sets it to active.
340 This makes the functions db-execute-command and db-query thread safe."
341 (with-slots (queries hdbc) database
342 (or (clsql-base-sys:without-interrupts
343 (let ((inactive-query (find-if (lambda (query)
344 (not (query-active-p query)))
347 (with-slots (column-count column-names column-c-types
349 column-sql-types column-data-ptrs
350 column-out-len-ptrs column-precisions
351 column-scales column-nullables-p)
353 ;;(print column-data-ptrs tb::*local-output*)
354 ;;(%dispose-column-ptrs inactive-query)
356 width +max-precision+
357 ;; KMR hstmt (%new-statement-handle hdbc)
358 (fill-pointer column-names) 0
359 (fill-pointer column-c-types) 0
360 (fill-pointer column-sql-types) 0
361 (fill-pointer column-data-ptrs) 0
362 (fill-pointer column-out-len-ptrs) 0
363 (fill-pointer column-precisions) 0
364 (fill-pointer column-scales) 0
365 (fill-pointer column-nullables-p) 0))
366 (setf (query-active-p inactive-query) t))
368 (let ((new-query (make-instance 'odbc-query
370 ;;(clone-database database)
372 (push new-query queries)
375 (defmethod db-execute-command ((database odbc-db) sql-string)
376 (db-execute-command (get-free-query database) sql-string))
378 (defmethod db-execute-command ((query odbc-query) sql-string)
379 (with-slots (hstmt database) query
380 (with-slots (henv hdbc) database
381 (unless hstmt (setf hstmt (%new-statement-handle hdbc)))
383 (%sql-exec-direct sql-string hstmt henv hdbc)
384 (db-close-query query)))))
386 (defmethod %initialize-query ((database odbc-db) arglen col-positions &key result-types width)
387 (%initialize-query (db-query-object database) arglen col-positions
388 :result-types result-types
389 :width (if width width (db-width database))))
391 (defmethod %initialize-query ((query odbc-query) arglen col-positions &key result-types width)
392 (with-slots (hstmt computed-result-types
393 column-count column-names column-c-types column-sql-types
394 column-data-ptrs column-out-len-ptrs column-precisions
395 column-scales column-nullables-p)
397 (setf column-count (if arglen
398 (min arglen (result-columns-count hstmt))
399 (result-columns-count hstmt)))
400 (when width (setf (query-width query) width))
401 ;;(format tb::*local-output* "~%column-count: ~d, col-positions: ~d" column-count col-positions)
402 (labels ((initialize-column (col-nr)
403 (multiple-value-bind (name sql-type precision scale nullable-p)
404 (%describe-column hstmt (1+ col-nr))
405 ;; allocate space to bind result rows to
406 (multiple-value-bind (c-type data-ptr out-len-ptr size long-p)
407 (%allocate-bindings sql-type precision)
408 (unless long-p ;; if long-p we fetch in chunks with %sql-get-data
409 (%bind-column hstmt col-nr c-type data-ptr (1+ size) out-len-ptr))
410 (vector-push-extend name column-names)
411 (vector-push-extend sql-type column-sql-types)
412 (vector-push-extend (sql-to-c-type sql-type) column-c-types)
413 (vector-push-extend precision column-precisions)
414 (vector-push-extend scale column-scales)
415 (vector-push-extend nullable-p column-nullables-p)
416 (vector-push-extend data-ptr column-data-ptrs)
417 (vector-push-extend out-len-ptr column-out-len-ptrs)))))
419 (dolist (col-nr col-positions)
420 (initialize-column col-nr))
421 (dotimes (col-nr column-count)
422 ;; get column information
423 (initialize-column col-nr))))
425 (setf computed-result-types (make-array column-count))
426 (dotimes (i column-count)
427 (setf (aref computed-result-types i)
429 ((consp result-types)
430 (nth i result-types))
431 ((eq result-types :auto)
432 (if (eq (aref column-sql-types i) odbc::$SQL_BIGINT)
434 (case (aref column-c-types i)
435 (#.odbc::$SQL_C_SLONG :int)
436 (#.odbc::$SQL_C_DOUBLE :double)
437 (#.odbc::$SQL_C_FLOAT :float)
438 (#.odbc::$SQL_C_SSHORT :short)
439 (#.odbc::$SQL_BIGINT :short)
445 (defmethod db-close-query ((query odbc-query) &key drop-p)
446 (with-slots (hstmt column-count column-names column-c-types column-sql-types
447 column-data-ptrs column-out-len-ptrs column-precisions
448 column-scales column-nullables-p) query
449 (let ((count (fill-pointer column-data-ptrs)))
450 (when (not (zerop count))
451 (dotimes (col-nr count)
452 (let ((data-ptr (aref column-data-ptrs col-nr))
453 (out-len-ptr (aref column-out-len-ptrs col-nr)))
454 ;; free-statment :unbind frees these
455 #+ignore (when data-ptr (uffi:free-foreign-object data-ptr))
456 #+ignore (when out-len-ptr (uffi:free-foreign-object out-len-ptr)))))
460 (%free-statement hstmt :drop)
463 (%free-statement hstmt :unbind)
464 (%free-statement hstmt :reset)
465 (%free-statement hstmt :close)))
466 (setf (query-active-p query) nil)))
469 (defmethod %read-query-data ((database odbc-db) ignore-columns)
470 (%read-query-data (db-query-object database) ignore-columns))
472 (defmethod %read-query-data ((query odbc-query) ignore-columns)
473 (with-slots (hstmt column-count column-c-types column-sql-types
474 column-data-ptrs column-out-len-ptrs column-precisions
475 computed-result-types)
477 (unless (= (SQLFetch hstmt) odbc::$SQL_NO_DATA_FOUND)
479 (loop for col-nr from 0 to (- column-count
480 (if (eq ignore-columns :last) 2 1))
481 for result-type across computed-result-types
483 (let ((precision (aref column-precisions col-nr))
484 (sql-type (aref column-sql-types col-nr)))
485 (cond ((or (< 0 precision (query-width query))
486 (and (zerop precision) (not (find sql-type '($SQL_C_CHAR)))))
487 (read-data (aref column-data-ptrs col-nr)
488 (aref column-c-types col-nr)
490 (aref column-out-len-ptrs col-nr)
492 ((zerop (get-cast-long (aref column-out-len-ptrs col-nr)))
495 (read-data-in-chunks hstmt col-nr
496 (aref column-data-ptrs col-nr)
497 (aref column-c-types col-nr)
498 (aref column-sql-types col-nr)
499 (aref column-out-len-ptrs col-nr)
503 (defmethod db-map-query ((database odbc-db) type function query-exp &key result-types)
504 (db-map-query (get-free-query database) type function query-exp :result-types result-types))
506 (defmethod db-map-query ((query odbc-query) type function query-exp &key result-types)
507 (declare (ignore type)) ; preliminary. Do a type coersion here
508 (%db-execute query (sql-expression query-exp))
511 (%initialize-query query nil nil :result-types result-types)
513 (loop for data = (%read-query-data query nil)
515 do (apply function data)))
516 ;; dispose of memory and set query inactive or get rid of it
517 (db-close-query query)))
519 (defmethod db-map-bind-query ((query odbc-query) type function
521 (declare (ignore type)) ; preliminary. Do a type coersion here
524 (apply #'%db-bind-execute query parameters)
527 while (setf data (%read-query-data query nil))
528 do (apply function data)))
529 ;; dispose of memory and set query inactive or get rid of it
530 (%db-reset-query query)))
532 ;; does not always return exactly a lisp type...
533 (defun sql-to-lisp-type (sql-type)
535 ((#.odbc::$SQL_CHAR #.odbc::$SQL_VARCHAR #.odbc::$SQL_LONGVARCHAR) :string)
536 ((#.odbc::$SQL_NUMERIC #.odbc::$SQL_DECIMAL #.odbc::$SQL_BIGINT) :string) ; ??
537 (#.odbc::$SQL_INTEGER :long)
538 (#.odbc::$SQL_SMALLINT :short)
539 ((#.odbc::$SQL_FLOAT #.odbc::$SQL_DOUBLE) :long)
540 (#.odbc::$SQL_REAL :long)
541 (#.odbc::$SQL_DATE 'sql-c-date)
542 (#.odbc::$SQL_TIME 'sql-c-time)
543 (#.odbc::$SQL_TIMESTAMP 'sql-c-timestamp)
544 ;;((#.odbc::$SQL_BINARY #.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) odbc::$SQL_C_BINARY) ; ??
545 (#.odbc::$SQL_TINYINT :short)
546 ;;(#.odbc::$SQL_BIT odbc::$SQL_C_BIT) ; ??
547 ((#.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) :binary)
552 (defmethod db-prepare-statement ((database odbc-db) sql
553 &key parameter-table parameter-columns)
554 (with-slots (hdbc) database
555 (let ((query (get-free-query database)))
556 (with-slots (hstmt) query
557 (unless hstmt (setf hstmt (%new-statement-handle hdbc))))
558 (db-prepare-statement query sql parameter-table parameter-columns))))
560 (defmethod db-prepare-statement ((query odbc-query) (sql string)
561 &key parameter-table parameter-columns)
562 ;; this is a workaround to get hold of the column types when the driver does not
563 ;; support SQLDescribeParam. To do: put code in here for drivers that do
565 (unless (string-equal sql "insert" :end1 6)
566 (error "Only insert expressions are supported in literal ODBC: '~a'." sql))
567 (%db-execute query (format nil "select ~{~a~^,~} from ~a where 0 = 1"
568 (or parameter-columns '("*")) parameter-table))
569 (%initialize-query query nil nil)
570 (with-slots (hstmt) query
571 (%free-statement hstmt :unbind)
572 (%free-statement hstmt :reset)
573 (setf (sql-expression query) sql)
574 (%sql-prepare hstmt sql))
578 (defmethod %db-bind-execute ((query odbc-query) &rest parameters)
579 (with-slots (hstmt parameter-data-ptrs) query
580 (loop for parameter in parameters
581 with data-ptr and size and parameter-string
583 (setf parameter-string
584 (if (stringp parameter)
586 (write-to-string parameter))
587 size (length parameter-string)
589 (uffi:allocate-foreign-string (1+ size)))
590 (vector-push-extend data-ptr parameter-data-ptrs)
592 hstmt (1- (fill-pointer parameter-data-ptrs)) odbc::$SQL_PARAM_INPUT
593 odbc::$SQL_C_CHAR ; (aref column-c-types parameter-count)
594 odbc::$SQL_CHAR ; sql-type
595 (query-width query) ;precision ; this should be the actual precision!
597 0 ;; should be calculated for odbc::$SQL_DECIMAL,
598 ;;$SQL_NUMERIC and odbc::$SQL_TIMESTAMP
599 data-ptr ;; = rgbValue
602 ;; change this for output and binary input! (see 3-32)
604 (%put-str data-ptr parameter-string size))
605 (%sql-execute hstmt)))
608 (defmethod %db-reset-query ((query odbc-query))
609 (with-slots (hstmt parameter-data-ptrs) query
611 (db-fetch-query-results query nil)
612 (%free-statement hstmt :reset) ;; but _not_ :unbind !
613 (%free-statement hstmt :close)
614 (dotimes (param-nr (fill-pointer parameter-data-ptrs))
615 (let ((data-ptr (aref parameter-data-ptrs param-nr)))
616 (when data-ptr (uffi:free-foreign-object data-ptr))))
617 (setf (fill-pointer parameter-data-ptrs) 0))))
619 (defun data-parameter-ptr (hstmt)
620 (uffi:with-foreign-object (param-ptr :pointer-void)
621 (let ((return-code (%sql-param-data hstmt param-ptr)))
622 ;;(format t "~%return-code from %sql-param-data: ~a~%" return-code)
623 (when (= return-code odbc::$SQL_NEED_DATA)
624 ;;(ffc::%pointer-to-address (%get-ptr param-ptr))
625 (uffi:deref-pointer param-ptr :pointer-void)))))
627 ;; database inquiery functions
629 (defmethod db-describe-columns ((database odbc-db)
630 table-qualifier table-owner table-name column-name)
631 (with-slots (hdbc) database
632 (%describe-columns hdbc table-qualifier table-owner table-name column-name)))
634 ;; should translate info-type integers to keywords in order to make this
636 (defmethod get-odbc-info ((database odbc-db) info-type)
637 (with-slots (hdbc info) database
638 (or (gethash info-type info)
639 (setf (gethash info-type info)
640 (%sql-get-info hdbc info-type)))))
642 (defmethod get-odbc-info ((query odbc-query) info-type)
643 (get-odbc-info (odbc::query-database query) info-type))
646 (defmethod db-data-sources ((db-type (eql :odbc)))
647 "Returns a list of (data-source description) - pairs"
648 (let ((henv (%new-environment-handle)))
650 (loop with direction = :first
651 for data-source+description
652 = (multiple-value-list (%sql-data-sources henv :direction direction))
653 while (car data-source+description)
654 collect data-source+description
655 do (setf direction :next))
656 (%sql-free-environment henv))))