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-database-tables
34 #:list-all-table-columns
44 #:*default-odbc-external-format*
47 (:documentation "This is the mid-level interface ODBC."))
49 (in-package #:odbc-dbi)
54 (;; any reason to have more than one henv?
55 (width :initform +max-precision+ :accessor db-width)
56 (hstmt :initform nil :accessor db-hstmt)
57 (henv :initform nil :allocation :class :initarg :henv :accessor henv)
58 (hdbc :initform nil :initarg :hdbc :accessor hdbc)
59 ;; info returned from SQLGetInfo
60 (info :initform (make-hash-table) :reader db-info)
61 (type :initform nil :initarg :db-type :reader db-type)
62 (connected-p :initform nil :accessor db-connected-p)
64 (count :initform 0 :initarg :count :accessor db-count)
66 (total-count :initform 0 :allocation :class :accessor db-total-count)
67 ;; the use of this slot is deprecated; it will be removed when dtf works without it.
68 (query :initform nil :accessor db-query-object)
69 ;; resource of (active and inactive) query objects
70 (queries :initform () :accessor db-queries)))
72 (defclass odbc-query ()
73 ((hstmt :initform nil :initarg :hstmt :accessor hstmt) ; = cursor??
74 (width :initform +max-precision+ :accessor query-width)
75 (computed-result-types :initform nil :initarg :computed-result-types :accessor computed-result-types)
76 (column-count :initform nil :accessor column-count)
77 (column-names :initform (make-array 0 :element-type 'string :adjustable t :fill-pointer t)
78 :accessor column-names)
79 (column-c-types :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
80 :accessor column-c-types)
81 (column-sql-types :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
82 :accessor column-sql-types)
83 (column-data-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
85 (column-out-len-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
86 :accessor column-out-len-ptrs)
87 (column-precisions :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
88 :accessor column-precisions)
89 (column-scales :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
90 :accessor column-scales)
91 (column-nullables-p :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
92 :accessor column-nullables-p)
93 ;;(parameter-count :initform 0 :accessor parameter-count)
94 (parameter-data-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
95 :accessor parameter-ptrs)
96 ;; a query string or a query expression object
97 (sql-expression :initform nil :initarg :sql-expression :accessor sql-expression)
98 ;; database object the query is to be run against
99 (database :initarg :database :reader query-database)
100 (active-p :initform nil :initarg :active-p :accessor query-active-p))
102 "Stores query information, like SQL query string/expression and database to run
103 the query against." ))
105 ;;; AODBC Compatible interface
107 (defun connect (&key data-source-name user password (autocommit t))
108 (let ((db (make-instance 'odbc-db)))
109 (unless (henv db) ;; has class allocation!
110 (setf (henv db) (%new-environment-handle)))
111 (setf (hdbc db) (%new-db-connection-handle (henv db)))
112 (%sql-connect (hdbc db) data-source-name user password)
113 #+ignore (setf (db-hstmt db) (%new-statement-handle (hdbc db)))
114 (when (/= (get-odbc-info db odbc::$SQL_TXN_CAPABLE) odbc::$SQL_TC_NONE)
116 (enable-autocommit (hdbc db))
117 (disable-autocommit (hdbc db))))
120 (defun disconnect (database)
121 (with-slots (hdbc queries) database
122 (dolist (query queries)
123 (if (query-active-p query)
124 (with-slots (hstmt) query
126 (%free-statement hstmt :drop)
128 (when (db-hstmt database)
129 (%free-statement (db-hstmt database) :drop))
133 (defun sql (expr &key db result-types row-count (column-names t) query
135 (declare (ignore hstmt))
138 (let ((q (db-open-query db expr :result-types result-types :width width)))
140 (values q (column-names q))
143 (multiple-value-bind (data col-names)
144 (db-query db expr :result-types result-types :width width)
147 (if (consp data) (length data) data))
149 (values data col-names))
153 (defun fetch-row (query &optional (eof-errorp t) eof-value)
154 (multiple-value-bind (row query count) (db-fetch-query-results query 1)
159 (error 'clsql-odbc-error :odbc-message "Ran out of data in fetch-row"))
165 (defun close-query (query)
166 (db-close-query query))
168 (defun list-all-database-tables (&key db hstmt)
169 (declare (ignore hstmt))
170 (let ((query (get-free-query db)))
173 (with-slots (hstmt) query
174 (unless hstmt (setf hstmt (%new-statement-handle (hdbc db))))
176 (%initialize-query query nil nil)
178 (db-fetch-query-results query)
179 (coerce (column-names query) 'list))))
180 (db-close-query query))))
182 (defun list-all-table-columns (table &key db hstmt)
183 (declare (ignore hstmt))
184 (db-describe-columns db "" "" table ""))
186 (defun rr-sql (hstmt sql-statement &key db)
187 (declare (ignore hstmt sql-statement db))
188 (warn "rr-sql not implemented."))
190 ;;; Mid-level interface
192 (defmethod db-commit ((database odbc-db))
193 (%commit (henv database) (hdbc database)))
195 (defmethod db-rollback ((database odbc-db))
196 (%rollback (henv database) (hdbc database)))
198 (defmethod db-cancel-query ((query odbc-query))
199 (with-slots (hstmt) query
201 (setf (query-active-p query) nil)))
204 (defmacro with-transaction (&body body)
206 (:henv (henv ,*default-database*) :hdbc (hdbc ,*default-database*))
209 (defmethod initialize-instance :after ((query odbc-query)
210 &key sql henv hdbc &allow-other-keys)
212 (let ((hstmt (%new-statement-handle hdbc)))
213 (%sql-exec-direct sql hstmt henv hdbc)
214 (with-slots (column-count
215 column-names column-c-types column-sql-types column-data-ptrs
216 column-out-len-ptrs column-precisions column-scales
217 column-nullables-p active-p) query
218 (setf (hstmt query) hstmt)
219 (%initialize-query query nil nil)
220 (setf active-p t)))))
222 ;; one for odbc-db is missing
223 (defmethod terminate ((query odbc-query))
224 ;;(format tb::*local-output* "~%*** terminated: ~s" query)
225 (with-slots (hstmt) query
227 ;(%free-statement hstmt :drop)
228 (uffi:free-foreign-object hstmt)) ;; ??
229 (%dispose-column-ptrs query)))
231 (defmethod %dispose-column-ptrs ((query odbc-query))
232 (with-slots (column-data-ptrs column-out-len-ptrs hstmt) query
233 (loop for data-ptr across column-data-ptrs
234 when data-ptr do (uffi:free-foreign-object data-ptr))
235 (loop for out-len-ptr across column-out-len-ptrs
236 when out-len-ptr do (uffi:free-foreign-object out-len-ptr))))
238 (defmethod db-open-query ((database odbc-db) query-expression
239 &key arglen col-positions result-types width
241 (db-open-query (get-free-query database) query-expression
242 :arglen arglen :col-positions col-positions
243 :result-types result-types
244 :width (if width width (db-width database))))
246 (defmethod db-open-query ((query odbc-query) query-expression
247 &key arglen col-positions result-types width
249 (%db-execute query query-expression)
250 (%initialize-query query arglen col-positions :result-types result-types
253 (defmethod db-fetch-query-results ((database odbc-db) &optional count)
254 (db-fetch-query-results (db-query-object database) count))
256 (defmethod db-fetch-query-results ((query odbc-query) &optional count)
257 (when (query-active-p query)
258 (with-slots (column-count column-data-ptrs column-c-types column-sql-types
259 column-out-len-ptrs column-precisions hstmt computed-result-types)
261 (let* ((rows-fetched 0)
264 until (or (and count (= i count))
265 (= (%sql-fetch hstmt) odbc::$SQL_NO_DATA_FOUND))
267 (loop for result-type across computed-result-types
268 for data-ptr across column-data-ptrs
269 for c-type across column-c-types
270 for sql-type across column-sql-types
271 for out-len-ptr across column-out-len-ptrs
272 for precision across column-precisions
273 for j from 0 ; column count is zero based in lisp
277 (cond ((< 0 precision (query-width query))
278 (read-data data-ptr c-type sql-type out-len-ptr result-type))
279 ((zerop (get-cast-long out-len-ptr))
282 (read-data-in-chunks hstmt j data-ptr c-type sql-type
283 out-len-ptr result-type))))))))
284 (values rows query rows-fetched)))))
286 (defmethod db-query ((database odbc-db) query-expression &key result-types width)
287 (let ((free-query (get-free-query database)))
288 (setf (sql-expression free-query) query-expression)
291 (%db-execute free-query query-expression)
292 (%initialize-query free-query nil nil :result-types result-types :width width)
293 (if (plusp (column-count free-query)) ;; KMR: Added check for commands that don't return columns
295 (db-fetch-query-results free-query nil)
296 (column-names free-query))
298 (result-rows-count (hstmt free-query))
300 (db-close-query free-query)
303 (defmethod %db-execute ((database odbc-db) sql-expression &key &allow-other-keys)
304 (%db-execute (get-free-query database) sql-expression))
306 (defmethod %db-execute ((query odbc-query) sql-expression &key &allow-other-keys)
307 (with-slots (henv hdbc) (odbc::query-database query)
308 (with-slots (hstmt) query
309 (unless hstmt (setf hstmt (%new-statement-handle hdbc)))
310 (setf (sql-expression query) sql-expression)
311 (%sql-exec-direct sql-expression hstmt henv hdbc)
314 ;; reuse inactive queries
315 (defmethod get-free-query ((database odbc-db))
316 "get-free-query finds or makes a nonactive query object, and then sets it to active.
317 This makes the functions db-execute-command and db-query thread safe."
318 (with-slots (queries hdbc) database
319 (or (clsql-base-sys:without-interrupts
320 (let ((inactive-query (find-if (lambda (query)
321 (not (query-active-p query)))
324 (with-slots (column-count column-names column-c-types
326 column-sql-types column-data-ptrs
327 column-out-len-ptrs column-precisions
328 column-scales column-nullables-p)
330 ;;(print column-data-ptrs tb::*local-output*)
331 ;;(%dispose-column-ptrs inactive-query)
333 width +max-precision+
334 ;; KMR hstmt (%new-statement-handle hdbc)
335 (fill-pointer column-names) 0
336 (fill-pointer column-c-types) 0
337 (fill-pointer column-sql-types) 0
338 (fill-pointer column-data-ptrs) 0
339 (fill-pointer column-out-len-ptrs) 0
340 (fill-pointer column-precisions) 0
341 (fill-pointer column-scales) 0
342 (fill-pointer column-nullables-p) 0))
343 (setf (query-active-p inactive-query) t))
345 (let ((new-query (make-instance 'odbc-query
347 ;;(clone-database database)
349 (push new-query queries)
352 (defmethod db-execute-command ((database odbc-db) sql-string)
353 (db-execute-command (get-free-query database) sql-string))
355 (defmethod db-execute-command ((query odbc-query) sql-string)
356 (with-slots (hstmt database) query
357 (with-slots (henv hdbc) database
358 (unless hstmt (setf hstmt (%new-statement-handle hdbc)))
360 (%sql-exec-direct sql-string hstmt henv hdbc)
361 (db-close-query query)))))
363 (defmethod %initialize-query ((database odbc-db) arglen col-positions &key result-types width)
364 (%initialize-query (db-query-object database) arglen col-positions
365 :result-types result-types
366 :width (if width width (db-width database))))
368 (defmethod %initialize-query ((query odbc-query) arglen col-positions &key result-types width)
369 (with-slots (hstmt computed-result-types
370 column-count column-names column-c-types column-sql-types
371 column-data-ptrs column-out-len-ptrs column-precisions
372 column-scales column-nullables-p)
374 (setf column-count (if arglen
375 (min arglen (result-columns-count hstmt))
376 (result-columns-count hstmt)))
377 (when width (setf (query-width query) width))
378 ;;(format tb::*local-output* "~%column-count: ~d, col-positions: ~d" column-count col-positions)
379 (labels ((initialize-column (col-nr)
380 (multiple-value-bind (name sql-type precision scale nullable-p)
381 (%describe-column hstmt (1+ col-nr))
382 ;; allocate space to bind result rows to
383 (multiple-value-bind (c-type data-ptr out-len-ptr size long-p)
384 (%allocate-bindings sql-type precision)
385 (unless long-p ;; if long-p we fetch in chunks with %sql-get-data
386 (%bind-column hstmt col-nr c-type data-ptr (1+ size) out-len-ptr))
387 (vector-push-extend name column-names)
388 (vector-push-extend sql-type column-sql-types)
389 (vector-push-extend (sql-to-c-type sql-type) column-c-types)
390 (vector-push-extend precision column-precisions)
391 (vector-push-extend scale column-scales)
392 (vector-push-extend nullable-p column-nullables-p)
393 (vector-push-extend data-ptr column-data-ptrs)
394 (vector-push-extend out-len-ptr column-out-len-ptrs)))))
396 (dolist (col-nr col-positions)
397 (initialize-column col-nr))
398 (dotimes (col-nr column-count)
399 ;; get column information
400 (initialize-column col-nr))))
402 (setf computed-result-types (make-array column-count))
403 (dotimes (i column-count)
404 (setf (aref computed-result-types i)
406 ((consp result-types)
407 (nth i result-types))
408 ((eq result-types :auto)
409 (if (eq (aref column-sql-types i) odbc::$SQL_BIGINT)
411 (case (aref column-c-types i)
412 (#.odbc::$SQL_C_SLONG :int)
413 (#.odbc::$SQL_C_DOUBLE :double)
414 (#.odbc::$SQL_C_FLOAT :float)
415 (#.odbc::$SQL_C_SSHORT :short)
416 (#.odbc::$SQL_BIGINT :short)
422 (defmethod db-close-query ((query odbc-query) &key drop-p)
423 (with-slots (hstmt column-count column-names column-c-types column-sql-types
424 column-data-ptrs column-out-len-ptrs column-precisions
425 column-scales column-nullables-p) query
426 (let ((count (fill-pointer column-data-ptrs)))
427 (when (not (zerop count))
428 (dotimes (col-nr count)
429 (let ((data-ptr (aref column-data-ptrs col-nr))
430 (out-len-ptr (aref column-out-len-ptrs col-nr)))
431 ;; free-statment unbind frees theses
432 #+ignore (when data-ptr (uffi:free-foreign-object data-ptr))
433 #+ignore (when out-len-ptr (uffi:free-foreign-object out-len-ptr)))))
437 (%free-statement hstmt :drop)
440 (%free-statement hstmt :unbind)
441 (%free-statement hstmt :reset)
442 (%free-statement hstmt :close)))
443 (setf (query-active-p query) nil)))
446 (defmethod %read-query-data ((database odbc-db) ignore-columns)
447 (%read-query-data (db-query-object database) ignore-columns))
449 (defmethod %read-query-data ((query odbc-query) ignore-columns)
450 (with-slots (hstmt column-count column-c-types column-sql-types
451 column-data-ptrs column-out-len-ptrs column-precisions
452 computed-result-types)
454 (unless (= (SQLFetch hstmt) odbc::$SQL_NO_DATA_FOUND)
456 (loop for col-nr from 0 to (- column-count
457 (if (eq ignore-columns :last) 2 1))
458 for result-type across computed-result-types
460 (let ((precision (aref column-precisions col-nr))
461 (sql-type (aref column-sql-types col-nr)))
462 (cond ((or (< 0 precision (query-width query))
463 (and (zerop precision) (not (find sql-type '($SQL_C_CHAR)))))
464 (read-data (aref column-data-ptrs col-nr)
465 (aref column-c-types col-nr)
467 (aref column-out-len-ptrs col-nr)
469 ((zerop (get-cast-long (aref column-out-len-ptrs col-nr)))
472 (read-data-in-chunks hstmt col-nr
473 (aref column-data-ptrs col-nr)
474 (aref column-c-types col-nr)
475 (aref column-sql-types col-nr)
476 (aref column-out-len-ptrs col-nr)
480 (defmethod db-map-query ((database odbc-db) type function query-exp &key result-types)
481 (db-map-query (get-free-query database) type function query-exp :result-types result-types))
483 (defmethod db-map-query ((query odbc-query) type function query-exp &key result-types)
484 (declare (ignore type)) ; preliminary. Do a type coersion here
485 (%db-execute query (sql-expression query-exp))
488 (%initialize-query query nil nil :result-types result-types)
490 (loop for data = (%read-query-data query nil)
492 do (apply function data)))
493 ;; dispose of memory and set query inactive or get rid of it
494 (db-close-query query)))
496 (defmethod db-map-bind-query ((query odbc-query) type function
498 (declare (ignore type)) ; preliminary. Do a type coersion here
501 (apply #'%db-bind-execute query parameters)
504 while (setf data (%read-query-data query nil))
505 do (apply function data)))
506 ;; dispose of memory and set query inactive or get rid of it
507 (%db-reset-query query)))
509 ;; does not always return exactly a lisp type...
510 (defun sql-to-lisp-type (sql-type)
512 ((#.odbc::$SQL_CHAR #.odbc::$SQL_VARCHAR #.odbc::$SQL_LONGVARCHAR) :string)
513 ((#.odbc::$SQL_NUMERIC #.odbc::$SQL_DECIMAL #.odbc::$SQL_BIGINT) :string) ; ??
514 (#.odbc::$SQL_INTEGER :long)
515 (#.odbc::$SQL_SMALLINT :short)
516 ((#.odbc::$SQL_FLOAT #.odbc::$SQL_DOUBLE) :long)
517 (#.odbc::$SQL_REAL :long)
518 (#.odbc::$SQL_DATE 'sql-c-date)
519 (#.odbc::$SQL_TIME 'sql-c-time)
520 (#.odbc::$SQL_TIMESTAMP 'sql-c-timestamp)
521 ;;((#.odbc::$SQL_BINARY #.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) odbc::$SQL_C_BINARY) ; ??
522 (#.odbc::$SQL_TINYINT :short)
523 ;;(#.odbc::$SQL_BIT odbc::$SQL_C_BIT) ; ??
524 ((#.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) :binary)
529 (defmethod db-prepare-statement ((database odbc-db) sql
530 &key parameter-table parameter-columns)
531 (with-slots (hdbc) database
532 (let ((query (get-free-query database)))
533 (with-slots (hstmt) query
534 (unless hstmt (setf hstmt (%new-statement-handle hdbc))))
535 (db-prepare-statement query sql parameter-table parameter-columns))))
537 (defmethod db-prepare-statement ((query odbc-query) (sql string)
538 &key parameter-table parameter-columns)
539 ;; this is a workaround to get hold of the column types when the driver does not
540 ;; support SQLDescribeParam. To do: put code in here for drivers that do
542 (unless (string-equal sql "insert" :end1 6)
543 (error "Only insert expressions are supported in literal ODBC: '~a'." sql))
544 (%db-execute query (format nil "select ~{~a~^,~} from ~a where 0 = 1"
545 (or parameter-columns '("*")) parameter-table))
546 (%initialize-query query nil nil)
547 (with-slots (hstmt) query
548 (%free-statement hstmt :unbind)
549 (%free-statement hstmt :reset)
550 (setf (sql-expression query) sql)
551 (%sql-prepare hstmt sql))
555 (defmethod %db-bind-execute ((query odbc-query) &rest parameters)
556 (with-slots (hstmt parameter-data-ptrs) query
557 (loop for parameter in parameters
558 with data-ptr and size and parameter-string
560 (setf parameter-string
561 (if (stringp parameter)
563 (write-to-string parameter))
564 size (length parameter-string)
566 (uffi:allocate-foreign-string (1+ size)))
567 (vector-push-extend data-ptr parameter-data-ptrs)
569 hstmt (1- (fill-pointer parameter-data-ptrs)) odbc::$SQL_PARAM_INPUT
570 odbc::$SQL_C_CHAR ; (aref column-c-types parameter-count)
571 odbc::$SQL_CHAR ; sql-type
572 (query-width query) ;precision ; this should be the actual precision!
574 0 ;; should be calculated for odbc::$SQL_DECIMAL,
575 ;;$SQL_NUMERIC and odbc::$SQL_TIMESTAMP
576 data-ptr ;; = rgbValue
579 ;; change this for output and binary input! (see 3-32)
581 (%put-str data-ptr parameter-string size))
582 (%sql-execute hstmt)))
585 (defmethod %db-reset-query ((query odbc-query))
586 (with-slots (hstmt parameter-data-ptrs) query
588 (db-fetch-query-results query nil)
589 (%free-statement hstmt :reset) ;; but _not_ :unbind !
590 (%free-statement hstmt :close)
591 (dotimes (param-nr (fill-pointer parameter-data-ptrs))
592 (let ((data-ptr (aref parameter-data-ptrs param-nr)))
593 (when data-ptr (uffi:free-foreign-object data-ptr))))
594 (setf (fill-pointer parameter-data-ptrs) 0))))
596 (defun data-parameter-ptr (hstmt)
597 (uffi:with-foreign-object (param-ptr :pointer-void)
598 (let ((return-code (%sql-param-data hstmt param-ptr)))
599 ;;(format t "~%return-code from %sql-param-data: ~a~%" return-code)
600 (when (= return-code odbc::$SQL_NEED_DATA)
601 ;;(ffc::%pointer-to-address (%get-ptr param-ptr))
602 (uffi:deref-pointer param-ptr :pointer-void)))))
604 ;; database inquiery functions
606 (defmethod db-describe-columns ((database odbc-db)
607 table-qualifier table-owner table-name column-name)
608 (with-slots (hdbc) database
609 (%describe-columns hdbc table-qualifier table-owner table-name column-name)))
611 ;; should translate info-type integers to keywords in order to make this
613 (defmethod get-odbc-info ((database odbc-db) info-type)
614 (with-slots (hdbc info) database
615 (or (gethash info-type info)
616 (setf (gethash info-type info)
617 (%sql-get-info hdbc info-type)))))
619 (defmethod get-odbc-info ((query odbc-query) info-type)
620 (get-odbc-info (odbc::query-database query) info-type))
623 (defmethod db-data-sources ((db-type (eql :odbc)))
624 "Returns a list of (data-source description) - pairs"
625 (let ((henv (%new-environment-handle)))
627 (loop with direction = :first
628 for data-source+description
629 = (multiple-value-list (%sql-data-sources henv :direction direction))
630 while (car data-source+description)
631 collect data-source+description
632 do (setf direction :next))
633 (%sql-free-environment henv))))