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 (henv :initform nil :allocation :class :initarg :henv :accessor henv)
56 (hdbc :initform nil :initarg :hdbc :accessor hdbc)
57 ;; info returned from SQLGetInfo
58 (info :initform (make-hash-table) :reader db-info)
59 (type :initform nil :initarg :db-type :reader db-type)
60 (connected-p :initform nil :accessor db-connected-p)
62 (count :initform 0 :initarg :count :accessor db-count)
64 (total-count :initform 0 :allocation :class :accessor db-total-count)
65 ;; the use of this slot is deprecated; it will be removed when dtf works without it.
66 (query :initform nil :accessor db-query-object)
67 ;; resource of (active and inactive) query objects
68 (queries :initform () :accessor db-queries)))
71 ((hstmt :initform nil :initarg :hstmt :accessor hstmt) ; = cursor??
72 (column-count :initform nil :accessor column-count)
73 (column-names :initform (make-array 0 :element-type 'string :adjustable t :fill-pointer t)
74 :accessor column-names)
75 (column-c-types :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
76 :accessor column-c-types)
77 (column-sql-types :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
78 :accessor column-sql-types)
79 (column-data-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
81 (column-out-len-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
82 :accessor column-out-len-ptrs)
83 (column-precisions :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
84 :accessor column-precisions)
85 (column-scales :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
86 :accessor column-scales)
87 (column-nullables-p :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
88 :accessor column-nullables-p)
89 ;;(parameter-count :initform 0 :accessor parameter-count)
90 (parameter-data-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
91 :accessor parameter-ptrs)
92 ;; a query string or a query expression object
93 (sql-expression :initform nil :initarg :sql-expression :accessor sql-expression)
94 ;; database object the query is to be run against
95 (database :initarg :database :reader query-database)
96 (active-p :initform nil :initarg :active-p :accessor query-active-p))
98 "Stores query information, like SQL query string/expression and database to run
99 the query against." ))
101 (defun connect (&key data-source-name user password (autocommit t))
102 (let ((db (make-instance 'odbc-db)))
103 (unless (henv db) ;; has class allocation!
104 (setf (henv db) (%new-environment-handle)))
105 (setf (hdbc db) (%new-db-connection-handle (henv db)))
106 (%sql-connect (hdbc db) data-source-name user password)
107 ;; FIXME: Check if connected
108 (when (/= (get-odbc-info db odbc::$SQL_TXN_CAPABLE) odbc::$SQL_TC_NONE)
110 (enable-autocommit (hdbc db))
111 (disable-autocommit (hdbc db))))
114 (defun disconnect (database)
115 (with-slots (hdbc queries) database
116 (dolist (query queries)
117 (if (query-active-p query)
118 (with-slots (hstmt) query
120 (%free-statement hstmt :drop)
125 (defun sql (expr &key db result-types row-count column-names query)
128 (db-execute db expr)))
130 (defun close-query (result-set)
131 (warn "Not implemented."))
133 (defun fetch-row (result-set error-eof eof-value)
134 (warn "Not implemented."))
136 (defclass odbc-query (query)
137 ((hstmt :initform nil :initarg :hstmt :accessor hstmt) ; = cursor??
138 (column-count :initform nil :accessor column-count)
139 (column-names :initform (make-array 0 :element-type 'string :adjustable t :fill-pointer t)
140 :accessor column-names)
141 (column-c-types :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
142 :accessor column-c-types)
143 (column-sql-types :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
144 :accessor column-sql-types)
145 (column-data-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
147 (column-out-len-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
148 :accessor column-out-len-ptrs)
149 (column-precisions :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
150 :accessor column-precisions)
151 (column-scales :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
152 :accessor column-scales)
153 (column-nullables-p :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
154 :accessor column-nullables-p)
155 ;;(parameter-count :initform 0 :accessor parameter-count)
156 (parameter-data-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
157 :accessor parameter-ptrs)))
159 (defmethod db-commit ((database odbc-db))
160 (%commit (henv database) (hdbc database)))
162 (defmethod db-rollback ((database odbc-db))
163 (%rollback (henv database) (hdbc database)))
165 (defmethod db-cancel-query ((query odbc-query))
166 (with-slots (hstmt) query
168 (setf (query-active-p query) nil)))
171 (defmacro with-transaction (&body body)
173 (:henv (henv ,*default-database*) :hdbc (hdbc ,*default-database*))
176 (defmethod initialize-instance :after ((query odbc-query)
177 &key sql henv hdbc &allow-other-keys)
179 (let ((hstmt (%new-statement-handle hdbc)))
180 (%sql-exec-direct sql hstmt henv hdbc)
181 (with-slots (column-count
182 column-names column-c-types column-sql-types column-data-ptrs
183 column-out-len-ptrs column-precisions column-scales
184 column-nullables-p active-p) query
185 (setf (hstmt query) hstmt)
186 (%initialize-query query)
187 (setf active-p t)))))
189 ;; one for odbc-db is missing
190 (defmethod terminate ((query odbc-query))
191 ;;(format tb::*local-output* "~%*** terminated: ~s" query)
192 (with-slots (hstmt) query
194 ;(%free-statement hstmt :drop)
195 (uffi:free-foreign-object hstmt)) ;; ??
196 (%dispose-column-ptrs query)))
198 (defmethod %dispose-column-ptrs ((query odbc-query))
199 (with-slots (column-data-ptrs column-out-len-ptrs hstmt) query
200 (loop for data-ptr across column-data-ptrs
201 when data-ptr do (uffi:free-foreign-object data-ptr))
202 (loop for out-len-ptr across column-out-len-ptrs
203 when out-len-ptr do (uffi:free-foreign-object out-len-ptr))))
205 (defmethod db-open-query ((database odbc-db) query-expression
206 &key arglen col-positions
208 (db-open-query (get-free-query database) query-expression
209 :arglen arglen :col-positions col-positions))
211 (defmethod db-open-query ((query odbc-query) query-expression
212 &key arglen col-positions &allow-other-keys)
213 (%db-execute query query-expression)
214 (%initialize-query query arglen col-positions))
216 (defmethod db-fetch-query-results ((database odbc-db) &optional count)
217 (db-fetch-query-results (db-query-object database) count))
219 (defmethod db-fetch-query-results ((query odbc-query) &optional count)
220 (when (query-active-p query)
221 (let (#+ignore(no-data nil))
222 (with-slots (column-count column-data-ptrs column-c-types column-sql-types
223 column-out-len-ptrs column-precisions hstmt)
227 until (or (and count (= i count))
228 (= (%sql-fetch hstmt) odbc::$SQL_NO_DATA_FOUND))
230 (loop for data-ptr across column-data-ptrs
231 for c-type across column-c-types
232 for sql-type across column-sql-types
233 for out-len-ptr across column-out-len-ptrs
234 for precision across column-precisions
235 for j from 0 ; column count is zero based in lisp
237 (cond ((< 0 precision +max-precision+)
238 (read-data data-ptr c-type sql-type out-len-ptr nil))
239 ((zerop (get-cast-long out-len-ptr))
242 (read-data-in-chunks hstmt j data-ptr c-type sql-type
246 (defmacro without-interrupts (&body body)
247 #+lispworks `(mp:without-preemption ,@body)
248 #+allegro `(mp:without-scheduling ,@body)
249 #+cmu `(pcl::without-interrupts ,@body)
250 #+sbcl `(sb-sys::without-interrupts ,@body)
251 #+openmcl `(ccl:without-interrupts ,@body))
253 (defmethod db-query ((database odbc-db) query-expression)
255 ;; make it thread safe
256 (get-free-query database)))
257 ;;(format tb::*local-output* "~%new query: ~s" free-query)
258 (setf (sql-expression free-query) query-expression)
261 (%db-execute free-query query-expression)
262 (%initialize-query free-query)
264 (db-fetch-query-results free-query nil)
265 ;; LMH return the column names as well
266 (column-names free-query)))
267 (db-close-query free-query)
268 ;;(format tb::*local-output* "~%query closed: ~s" free-query)
271 (defmethod %db-execute ((database odbc-db) sql-expression &key &allow-other-keys)
272 (%db-execute (get-free-query database) sql-expression))
274 (defmethod %db-execute ((query odbc-query) sql-expression &key &allow-other-keys)
275 (with-slots (henv hdbc) (odbc::query-database query)
276 (with-slots (hstmt) query
277 (unless hstmt (setf hstmt (%new-statement-handle hdbc)))
278 ;;(print (list :new hstmt) tb::*local-output*)
279 (setf (sql-expression query) sql-expression)
280 (%sql-exec-direct sql-expression hstmt henv hdbc)
283 ;; reuse inactive queries
284 (defmethod get-free-query ((database odbc-db))
285 "get-free-query finds or makes a nonactive query object, and then sets it to active.
286 This makes the functions db-execute-command and db-query thread safe."
287 (with-slots (queries) database
288 (or (without-interrupts ;; not context switch allowed here
289 (let ((inactive-query (find-if (lambda (query)
290 (not (query-active-p query)))
293 (with-slots (column-count column-names column-c-types
294 column-sql-types column-data-ptrs
295 column-out-len-ptrs column-precisions
296 column-scales column-nullables-p)
298 ;;(print column-data-ptrs tb::*local-output*)
299 ;;(%dispose-column-ptrs inactive-query)
301 (fill-pointer column-names) 0
302 (fill-pointer column-c-types) 0
303 (fill-pointer column-sql-types) 0
304 (fill-pointer column-data-ptrs) 0
305 (fill-pointer column-out-len-ptrs) 0
306 (fill-pointer column-precisions) 0
307 (fill-pointer column-scales) 0
308 (fill-pointer column-nullables-p) 0))
309 (setf (query-active-p inactive-query) t))
311 (let ((new-query (make-instance 'odbc-query
313 ;;(clone-database database)
315 (push new-query queries)
318 (defmethod db-execute-command ((database odbc-db) sql-string)
319 (db-execute-command (get-free-query database) sql-string))
321 (defmethod db-execute-command ((query odbc-query) sql-string)
322 (with-slots (hstmt database) query
323 (with-slots (henv hdbc) database
324 (unless hstmt (setf hstmt (%new-statement-handle hdbc)))
326 (%sql-exec-direct sql-string hstmt henv hdbc)
327 (db-close-query query)))))
329 (defmethod %initialize-query ((database odbc-db) &optional arglen col-positions)
330 (%initialize-query (db-query-object database) arglen col-positions))
332 (defmethod %initialize-query ((query odbc-query) &optional arglen col-positions)
334 column-count column-names column-c-types column-sql-types
335 column-data-ptrs column-out-len-ptrs column-precisions
336 column-scales column-nullables-p)
338 (setf column-count (if arglen
339 (min arglen (result-columns-count hstmt))
340 (result-columns-count hstmt)))
341 ;;(format tb::*local-output* "~%column-count: ~d, col-positions: ~d" column-count col-positions)
342 (labels ((initialize-column (col-nr)
343 (multiple-value-bind (name sql-type precision scale nullable-p)
344 (%describe-column hstmt (1+ col-nr))
345 ;; allocate space to bind result rows to
346 (multiple-value-bind (c-type data-ptr out-len-ptr size long-p)
347 (%allocate-bindings sql-type precision)
348 (unless long-p ;; if long-p we fetch in chunks with %sql-get-data
349 (%bind-column hstmt col-nr c-type data-ptr (1+ size) out-len-ptr))
350 (vector-push-extend name column-names)
351 (vector-push-extend sql-type column-sql-types)
352 (vector-push-extend (sql-to-c-type sql-type) column-c-types)
353 (vector-push-extend precision column-precisions)
354 (vector-push-extend scale column-scales)
355 (vector-push-extend nullable-p column-nullables-p)
356 (vector-push-extend data-ptr column-data-ptrs)
357 (vector-push-extend out-len-ptr column-out-len-ptrs)))))
359 (dolist (col-nr col-positions)
360 (initialize-column col-nr))
361 (dotimes (col-nr column-count)
362 ;; get column information
363 (initialize-column col-nr)))))
366 (defmethod db-close-query ((query odbc-query) &key drop-p)
367 (with-slots (hstmt column-count column-names column-c-types column-sql-types
368 column-data-ptrs column-out-len-ptrs column-precisions
369 column-scales column-nullables-p) query
370 (let ((count (fill-pointer column-data-ptrs)))
371 (when (not (zerop count))
372 (dotimes (col-nr count)
373 (let ((data-ptr (aref column-data-ptrs col-nr))
374 (out-len-ptr (aref column-out-len-ptrs col-nr)))
375 (when data-ptr (uffi:free-foreign-object data-ptr)) ; we *did* allocate them
376 (when out-len-ptr (uffi:free-foreign-object out-len-ptr)))))
380 (%free-statement hstmt :drop)
383 (%free-statement hstmt :unbind)
384 (%free-statement hstmt :reset)
385 (%free-statement hstmt :close)))
386 (setf (query-active-p query) nil)))
389 (defmethod %read-query-data ((database odbc-db) ignore-columns)
390 (%read-query-data (db-query-object database) ignore-columns))
392 (defmethod %read-query-data ((query odbc-query) ignore-columns)
393 (with-slots (hstmt column-count column-c-types column-sql-types
394 column-data-ptrs column-out-len-ptrs column-precisions)
396 (unless (= (SQLFetch hstmt) odbc::$SQL_NO_DATA_FOUND)
398 (loop for col-nr from 0 to (- column-count
399 (if (eq ignore-columns :last) 2 1))
401 (let ((precision (aref column-precisions col-nr))
402 (sql-type (aref column-sql-types col-nr)))
403 (cond ((or (< 0 precision +max-precision+)
404 (and (zerop precision) (not (find sql-type '($SQL_C_CHAR)))))
405 (read-data (aref column-data-ptrs col-nr)
406 (aref column-c-types col-nr)
408 (aref column-out-len-ptrs col-nr)
410 ((zerop (get-cast-long (aref column-out-len-ptrs col-nr)))
413 (read-data-in-chunks hstmt col-nr
414 (aref column-data-ptrs col-nr)
415 (aref column-c-types col-nr)
416 (aref column-sql-types col-nr)
417 (aref column-out-len-ptrs col-nr)
421 (defmethod db-map-query ((database odbc-db) type function query-exp)
422 (db-map-query (get-free-query database) type function query-exp))
424 (defmethod db-map-query ((query odbc-query) type function query-exp)
425 (declare (ignore type)) ; preliminary. Do a type coersion here
426 (%db-execute query (sql-expression query-exp))
429 (%initialize-query query)
431 (loop for data = (%read-query-data query nil)
433 do (apply function data)))
434 ;; dispose of memory and set query inactive or get rid of it
435 (db-close-query query)))
437 (defmethod db-map-bind-query ((query odbc-query) type function
439 (declare (ignore type)) ; preliminary. Do a type coersion here
442 (apply #'%db-bind-execute query parameters)
445 while (setf data (%read-query-data query nil))
446 do (apply function data)))
447 ;; dispose of memory and set query inactive or get rid of it
448 (%db-reset-query query)))
450 ;; does not always return exactly a lisp type...
451 (defun sql-to-lisp-type (sql-type)
453 ((#.odbc::$SQL_CHAR #.odbc::$SQL_VARCHAR #.odbc::$SQL_LONGVARCHAR) :string)
454 ((#.odbc::$SQL_NUMERIC #.odbc::$SQL_DECIMAL #.odbc::$SQL_BIGINT) :string) ; ??
455 (#.odbc::$SQL_INTEGER :long)
456 (#.odbc::$SQL_SMALLINT :short)
457 ((#.odbc::$SQL_FLOAT #.odbc::$SQL_DOUBLE) :long)
458 (#.odbc::$SQL_REAL :long)
459 (#.odbc::$SQL_DATE 'sql-c-date)
460 (#.odbc::$SQL_TIME 'sql-c-time)
461 (#.odbc::$SQL_TIMESTAMP 'sql-c-timestamp)
462 ;;((#.odbc::$SQL_BINARY #.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) odbc::$SQL_C_BINARY) ; ??
463 (#.odbc::$SQL_TINYINT :short)
464 ;;(#.odbc::$SQL_BIT odbc::$SQL_C_BIT) ; ??
465 ((#.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) :binary)
470 (defmethod db-prepare-statement ((database odbc-db) sql
471 &key parameter-table parameter-columns)
472 (with-slots (hdbc) database
473 (let ((query (get-free-query database)))
474 (with-slots (hstmt) query
475 (unless hstmt (setf hstmt (%new-statement-handle hdbc))))
476 (db-prepare-statement query sql parameter-table parameter-columns))))
478 (defmethod db-prepare-statement ((query odbc-query) (sql string)
479 &key parameter-table parameter-columns)
480 ;; this is a workaround to get hold of the column types when the driver does not
481 ;; support SQLDescribeParam. To do: put code in here for drivers that do
483 (unless (string-equal sql "insert" :end1 6)
484 (error "Only insert expressions are supported in literal ODBC: '~a'." sql))
485 (%db-execute query (format nil "select ~{~a~^,~} from ~a where 0 = 1"
486 (or parameter-columns '("*")) parameter-table))
487 (%initialize-query query)
488 (with-slots (hstmt) query
489 (%free-statement hstmt :unbind)
490 (%free-statement hstmt :reset)
491 (setf (sql-expression query) sql)
492 (%sql-prepare hstmt sql))
496 (defmethod %db-bind-execute ((query odbc-query) &rest parameters)
497 (with-slots (hstmt parameter-data-ptrs) query
498 (loop for parameter in parameters
499 with data-ptr and size and parameter-string
501 (setf parameter-string
502 (if (stringp parameter)
504 (write-to-string parameter))
505 size (length parameter-string)
507 (uffi:allocate-foreign-string (1+ size)))
508 (vector-push-extend data-ptr parameter-data-ptrs)
510 hstmt (1- (fill-pointer parameter-data-ptrs)) odbc::$SQL_PARAM_INPUT
511 odbc::$SQL_C_CHAR ; (aref column-c-types parameter-count)
512 odbc::$SQL_CHAR ; sql-type
513 +max-precision+ ;precision ; this should be the actual precision!
515 0 ;; should be calculated for odbc::$SQL_DECIMAL,
516 ;;$SQL_NUMERIC and odbc::$SQL_TIMESTAMP
517 data-ptr ;; = rgbValue
520 ;; change this for output and binary input! (see 3-32)
522 (%put-str data-ptr parameter-string size))
523 (%sql-execute hstmt)))
526 (defmethod %db-reset-query ((query odbc-query))
527 (with-slots (hstmt parameter-data-ptrs) query
529 (db-fetch-query-results query nil
531 (%free-statement hstmt :reset) ;; but _not_ :unbind !
532 (%free-statement hstmt :close)
533 (dotimes (param-nr (fill-pointer parameter-data-ptrs))
534 (let ((data-ptr (aref parameter-data-ptrs param-nr)))
535 (when data-ptr (uffi:free-foreign-object data-ptr))))
536 (setf (fill-pointer parameter-data-ptrs) 0))))
538 (defun data-parameter-ptr (hstmt)
539 (uffi:with-foreign-object (param-ptr (* :pointer-void))
540 (let ((return-code (%sql-param-data hstmt param-ptr)))
541 ;;(format t "~%return-code from %sql-param-data: ~a~%" return-code)
542 (when (= return-code odbc::$SQL_NEED_DATA)
543 ;;(ffc::%pointer-to-address (%get-ptr param-ptr))
544 (uffi:deref-pointer param-ptr :pointer-void)))))
546 ;; database inquiery functions
548 (defmethod db-describe-columns ((database odbc-db)
549 table-qualifier table-owner table-name column-name)
550 (with-slots (hdbc) database
551 (%describe-columns hdbc table-qualifier table-owner table-name column-name)))
553 ;; should translate info-type integers to keywords in order to make this
555 (defmethod get-odbc-info ((database odbc-db) info-type)
556 (with-slots (hdbc info) database
557 (or (gethash info-type info)
558 (setf (gethash info-type info)
559 (%sql-get-info hdbc info-type)))))
561 (defmethod get-odbc-info ((query odbc-query) info-type)
562 (get-odbc-info (odbc::query-database query) info-type))
565 (defmethod db-data-sources ((db-type (eql :odbc)))
566 "Returns a list of (data-source description) - pairs"
567 (let ((henv (%new-environment-handle)))
569 (loop with direction = :first
570 for data-source+description
571 = (multiple-value-list (%sql-data-sources henv :direction direction))
572 while (car data-source+description)
573 collect data-source+description
574 do (setf direction :next))
575 (%sql-free-environment henv))))