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 ;; fixme: don't return all query results.
131 (defun close-query (result-set)
132 (warn "Not implemented."))
134 (defun fetch-row (result-set error-eof eof-value)
135 (warn "Not implemented."))
137 (defclass odbc-query (query)
138 ((hstmt :initform nil :initarg :hstmt :accessor hstmt) ; = cursor??
139 (column-count :initform nil :accessor column-count)
140 (column-names :initform (make-array 0 :element-type 'string :adjustable t :fill-pointer t)
141 :accessor column-names)
142 (column-c-types :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
143 :accessor column-c-types)
144 (column-sql-types :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
145 :accessor column-sql-types)
146 (column-data-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
148 (column-out-len-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
149 :accessor column-out-len-ptrs)
150 (column-precisions :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
151 :accessor column-precisions)
152 (column-scales :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
153 :accessor column-scales)
154 (column-nullables-p :initform (make-array 0 :element-type 'fixnum :adjustable t :fill-pointer t)
155 :accessor column-nullables-p)
156 ;;(parameter-count :initform 0 :accessor parameter-count)
157 (parameter-data-ptrs :initform (make-array 0 :adjustable t :fill-pointer t)
158 :accessor parameter-ptrs)))
160 (defmethod db-commit ((database odbc-db))
161 (%commit (henv database) (hdbc database)))
163 (defmethod db-rollback ((database odbc-db))
164 (%rollback (henv database) (hdbc database)))
166 (defmethod db-cancel-query ((query odbc-query))
167 (with-slots (hstmt) query
169 (setf (query-active-p query) nil)))
172 (defmacro with-transaction (&body body)
174 (:henv (henv ,*default-database*) :hdbc (hdbc ,*default-database*))
177 (defmethod initialize-instance :after ((query odbc-query)
178 &key sql henv hdbc &allow-other-keys)
180 (let ((hstmt (%new-statement-handle hdbc)))
181 (%sql-exec-direct sql hstmt henv hdbc)
182 (with-slots (column-count
183 column-names column-c-types column-sql-types column-data-ptrs
184 column-out-len-ptrs column-precisions column-scales
185 column-nullables-p active-p) query
186 (setf (hstmt query) hstmt)
187 (%initialize-query query)
188 (setf active-p t)))))
190 ;; one for odbc-db is missing
191 (defmethod terminate ((query odbc-query))
192 ;;(format tb::*local-output* "~%*** terminated: ~s" query)
193 (with-slots (hstmt) query
195 ;(%free-statement hstmt :drop)
196 (uffi:free-foreign-object hstmt)) ;; ??
197 (%dispose-column-ptrs query)))
199 (defmethod %dispose-column-ptrs ((query odbc-query))
200 (with-slots (column-data-ptrs column-out-len-ptrs hstmt) query
201 (loop for data-ptr across column-data-ptrs
202 when data-ptr do (uffi:free-foreign-object data-ptr))
203 (loop for out-len-ptr across column-out-len-ptrs
204 when out-len-ptr do (uffi:free-foreign-object out-len-ptr))))
206 (defmethod db-open-query ((database odbc-db) query-expression
207 &key arglen col-positions
209 (db-open-query (get-free-query database) query-expression
210 :arglen arglen :col-positions col-positions))
212 (defmethod db-open-query ((query odbc-query) query-expression
213 &key arglen col-positions &allow-other-keys)
214 (%db-execute query query-expression)
215 (%initialize-query query arglen col-positions))
217 (defmethod db-fetch-query-results ((database odbc-db) &optional count)
218 (db-fetch-query-results (db-query-object database) count))
220 (defmethod db-fetch-query-results ((query odbc-query) &optional count)
221 (when (query-active-p query)
222 (let (#+ignore(no-data nil))
223 (with-slots (column-count column-data-ptrs column-c-types column-sql-types
224 column-out-len-ptrs column-precisions hstmt)
228 until (or (and count (= i count))
229 (= (%sql-fetch hstmt) odbc::$SQL_NO_DATA_FOUND))
231 (loop for data-ptr across column-data-ptrs
232 for c-type across column-c-types
233 for sql-type across column-sql-types
234 for out-len-ptr across column-out-len-ptrs
235 for precision across column-precisions
236 for j from 0 ; column count is zero based in lisp
238 (cond ((< 0 precision +max-precision+)
239 (read-data data-ptr c-type sql-type out-len-ptr nil))
240 ((zerop (get-cast-long out-len-ptr))
243 (read-data-in-chunks hstmt j data-ptr c-type sql-type
247 (defmethod db-query ((database odbc-db) query-expression)
249 ;; make it thread safe
250 (get-free-query database)))
251 ;;(format tb::*local-output* "~%new query: ~s" free-query)
252 (setf (sql-expression free-query) query-expression)
255 (%db-execute free-query query-expression)
256 (%initialize-query free-query)
258 (db-fetch-query-results free-query nil)
259 ;; LMH return the column names as well
260 (column-names free-query)))
261 (db-close-query free-query)
262 ;;(format tb::*local-output* "~%query closed: ~s" free-query)
265 (defmethod %db-execute ((database odbc-db) sql-expression &key &allow-other-keys)
266 (%db-execute (get-free-query database) sql-expression))
268 (defmethod %db-execute ((query odbc-query) sql-expression &key &allow-other-keys)
269 (with-slots (henv hdbc) (odbc::query-database query)
270 (with-slots (hstmt) query
271 (unless hstmt (setf hstmt (%new-statement-handle hdbc)))
272 ;;(print (list :new hstmt) tb::*local-output*)
273 (setf (sql-expression query) sql-expression)
274 (%sql-exec-direct sql-expression hstmt henv hdbc)
277 ;; reuse inactive queries
278 (defmethod get-free-query ((database odbc-db))
279 "get-free-query finds or makes a nonactive query object, and then sets it to active.
280 This makes the functions db-execute-command and db-query thread safe."
281 (with-slots (queries) database
282 (or (clsql-base-sys:without-interrupts ;; not context switch allowed here
283 (let ((inactive-query (find-if (lambda (query)
284 (not (query-active-p query)))
287 (with-slots (column-count column-names column-c-types
288 column-sql-types column-data-ptrs
289 column-out-len-ptrs column-precisions
290 column-scales column-nullables-p)
292 ;;(print column-data-ptrs tb::*local-output*)
293 ;;(%dispose-column-ptrs inactive-query)
295 (fill-pointer column-names) 0
296 (fill-pointer column-c-types) 0
297 (fill-pointer column-sql-types) 0
298 (fill-pointer column-data-ptrs) 0
299 (fill-pointer column-out-len-ptrs) 0
300 (fill-pointer column-precisions) 0
301 (fill-pointer column-scales) 0
302 (fill-pointer column-nullables-p) 0))
303 (setf (query-active-p inactive-query) t))
305 (let ((new-query (make-instance 'odbc-query
307 ;;(clone-database database)
309 (push new-query queries)
312 (defmethod db-execute-command ((database odbc-db) sql-string)
313 (db-execute-command (get-free-query database) sql-string))
315 (defmethod db-execute-command ((query odbc-query) sql-string)
316 (with-slots (hstmt database) query
317 (with-slots (henv hdbc) database
318 (unless hstmt (setf hstmt (%new-statement-handle hdbc)))
320 (%sql-exec-direct sql-string hstmt henv hdbc)
321 (db-close-query query)))))
323 (defmethod %initialize-query ((database odbc-db) &optional arglen col-positions)
324 (%initialize-query (db-query-object database) arglen col-positions))
326 (defmethod %initialize-query ((query odbc-query) &optional arglen col-positions)
328 column-count column-names column-c-types column-sql-types
329 column-data-ptrs column-out-len-ptrs column-precisions
330 column-scales column-nullables-p)
332 (setf column-count (if arglen
333 (min arglen (result-columns-count hstmt))
334 (result-columns-count hstmt)))
335 ;;(format tb::*local-output* "~%column-count: ~d, col-positions: ~d" column-count col-positions)
336 (labels ((initialize-column (col-nr)
337 (multiple-value-bind (name sql-type precision scale nullable-p)
338 (%describe-column hstmt (1+ col-nr))
339 ;; allocate space to bind result rows to
340 (multiple-value-bind (c-type data-ptr out-len-ptr size long-p)
341 (%allocate-bindings sql-type precision)
342 (unless long-p ;; if long-p we fetch in chunks with %sql-get-data
343 (%bind-column hstmt col-nr c-type data-ptr (1+ size) out-len-ptr))
344 (vector-push-extend name column-names)
345 (vector-push-extend sql-type column-sql-types)
346 (vector-push-extend (sql-to-c-type sql-type) column-c-types)
347 (vector-push-extend precision column-precisions)
348 (vector-push-extend scale column-scales)
349 (vector-push-extend nullable-p column-nullables-p)
350 (vector-push-extend data-ptr column-data-ptrs)
351 (vector-push-extend out-len-ptr column-out-len-ptrs)))))
353 (dolist (col-nr col-positions)
354 (initialize-column col-nr))
355 (dotimes (col-nr column-count)
356 ;; get column information
357 (initialize-column col-nr)))))
360 (defmethod db-close-query ((query odbc-query) &key drop-p)
361 (with-slots (hstmt column-count column-names column-c-types column-sql-types
362 column-data-ptrs column-out-len-ptrs column-precisions
363 column-scales column-nullables-p) query
364 (let ((count (fill-pointer column-data-ptrs)))
365 (when (not (zerop count))
366 (dotimes (col-nr count)
367 (let ((data-ptr (aref column-data-ptrs col-nr))
368 (out-len-ptr (aref column-out-len-ptrs col-nr)))
369 (when data-ptr (uffi:free-foreign-object data-ptr)) ; we *did* allocate them
370 (when out-len-ptr (uffi:free-foreign-object out-len-ptr)))))
374 (%free-statement hstmt :drop)
377 (%free-statement hstmt :unbind)
378 (%free-statement hstmt :reset)
379 (%free-statement hstmt :close)))
380 (setf (query-active-p query) nil)))
383 (defmethod %read-query-data ((database odbc-db) ignore-columns)
384 (%read-query-data (db-query-object database) ignore-columns))
386 (defmethod %read-query-data ((query odbc-query) ignore-columns)
387 (with-slots (hstmt column-count column-c-types column-sql-types
388 column-data-ptrs column-out-len-ptrs column-precisions)
390 (unless (= (SQLFetch hstmt) odbc::$SQL_NO_DATA_FOUND)
392 (loop for col-nr from 0 to (- column-count
393 (if (eq ignore-columns :last) 2 1))
395 (let ((precision (aref column-precisions col-nr))
396 (sql-type (aref column-sql-types col-nr)))
397 (cond ((or (< 0 precision +max-precision+)
398 (and (zerop precision) (not (find sql-type '($SQL_C_CHAR)))))
399 (read-data (aref column-data-ptrs col-nr)
400 (aref column-c-types col-nr)
402 (aref column-out-len-ptrs col-nr)
404 ((zerop (get-cast-long (aref column-out-len-ptrs col-nr)))
407 (read-data-in-chunks hstmt col-nr
408 (aref column-data-ptrs col-nr)
409 (aref column-c-types col-nr)
410 (aref column-sql-types col-nr)
411 (aref column-out-len-ptrs col-nr)
415 (defmethod db-map-query ((database odbc-db) type function query-exp)
416 (db-map-query (get-free-query database) type function query-exp))
418 (defmethod db-map-query ((query odbc-query) type function query-exp)
419 (declare (ignore type)) ; preliminary. Do a type coersion here
420 (%db-execute query (sql-expression query-exp))
423 (%initialize-query query)
425 (loop for data = (%read-query-data query nil)
427 do (apply function data)))
428 ;; dispose of memory and set query inactive or get rid of it
429 (db-close-query query)))
431 (defmethod db-map-bind-query ((query odbc-query) type function
433 (declare (ignore type)) ; preliminary. Do a type coersion here
436 (apply #'%db-bind-execute query parameters)
439 while (setf data (%read-query-data query nil))
440 do (apply function data)))
441 ;; dispose of memory and set query inactive or get rid of it
442 (%db-reset-query query)))
444 ;; does not always return exactly a lisp type...
445 (defun sql-to-lisp-type (sql-type)
447 ((#.odbc::$SQL_CHAR #.odbc::$SQL_VARCHAR #.odbc::$SQL_LONGVARCHAR) :string)
448 ((#.odbc::$SQL_NUMERIC #.odbc::$SQL_DECIMAL #.odbc::$SQL_BIGINT) :string) ; ??
449 (#.odbc::$SQL_INTEGER :long)
450 (#.odbc::$SQL_SMALLINT :short)
451 ((#.odbc::$SQL_FLOAT #.odbc::$SQL_DOUBLE) :long)
452 (#.odbc::$SQL_REAL :long)
453 (#.odbc::$SQL_DATE 'sql-c-date)
454 (#.odbc::$SQL_TIME 'sql-c-time)
455 (#.odbc::$SQL_TIMESTAMP 'sql-c-timestamp)
456 ;;((#.odbc::$SQL_BINARY #.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) odbc::$SQL_C_BINARY) ; ??
457 (#.odbc::$SQL_TINYINT :short)
458 ;;(#.odbc::$SQL_BIT odbc::$SQL_C_BIT) ; ??
459 ((#.odbc::$SQL_VARBINARY #.odbc::$SQL_LONGVARBINARY) :binary)
464 (defmethod db-prepare-statement ((database odbc-db) sql
465 &key parameter-table parameter-columns)
466 (with-slots (hdbc) database
467 (let ((query (get-free-query database)))
468 (with-slots (hstmt) query
469 (unless hstmt (setf hstmt (%new-statement-handle hdbc))))
470 (db-prepare-statement query sql parameter-table parameter-columns))))
472 (defmethod db-prepare-statement ((query odbc-query) (sql string)
473 &key parameter-table parameter-columns)
474 ;; this is a workaround to get hold of the column types when the driver does not
475 ;; support SQLDescribeParam. To do: put code in here for drivers that do
477 (unless (string-equal sql "insert" :end1 6)
478 (error "Only insert expressions are supported in literal ODBC: '~a'." sql))
479 (%db-execute query (format nil "select ~{~a~^,~} from ~a where 0 = 1"
480 (or parameter-columns '("*")) parameter-table))
481 (%initialize-query query)
482 (with-slots (hstmt) query
483 (%free-statement hstmt :unbind)
484 (%free-statement hstmt :reset)
485 (setf (sql-expression query) sql)
486 (%sql-prepare hstmt sql))
490 (defmethod %db-bind-execute ((query odbc-query) &rest parameters)
491 (with-slots (hstmt parameter-data-ptrs) query
492 (loop for parameter in parameters
493 with data-ptr and size and parameter-string
495 (setf parameter-string
496 (if (stringp parameter)
498 (write-to-string parameter))
499 size (length parameter-string)
501 (uffi:allocate-foreign-string (1+ size)))
502 (vector-push-extend data-ptr parameter-data-ptrs)
504 hstmt (1- (fill-pointer parameter-data-ptrs)) odbc::$SQL_PARAM_INPUT
505 odbc::$SQL_C_CHAR ; (aref column-c-types parameter-count)
506 odbc::$SQL_CHAR ; sql-type
507 +max-precision+ ;precision ; this should be the actual precision!
509 0 ;; should be calculated for odbc::$SQL_DECIMAL,
510 ;;$SQL_NUMERIC and odbc::$SQL_TIMESTAMP
511 data-ptr ;; = rgbValue
514 ;; change this for output and binary input! (see 3-32)
516 (%put-str data-ptr parameter-string size))
517 (%sql-execute hstmt)))
520 (defmethod %db-reset-query ((query odbc-query))
521 (with-slots (hstmt parameter-data-ptrs) query
523 (db-fetch-query-results query nil
525 (%free-statement hstmt :reset) ;; but _not_ :unbind !
526 (%free-statement hstmt :close)
527 (dotimes (param-nr (fill-pointer parameter-data-ptrs))
528 (let ((data-ptr (aref parameter-data-ptrs param-nr)))
529 (when data-ptr (uffi:free-foreign-object data-ptr))))
530 (setf (fill-pointer parameter-data-ptrs) 0))))
532 (defun data-parameter-ptr (hstmt)
533 (uffi:with-foreign-object (param-ptr (* :pointer-void))
534 (let ((return-code (%sql-param-data hstmt param-ptr)))
535 ;;(format t "~%return-code from %sql-param-data: ~a~%" return-code)
536 (when (= return-code odbc::$SQL_NEED_DATA)
537 ;;(ffc::%pointer-to-address (%get-ptr param-ptr))
538 (uffi:deref-pointer param-ptr :pointer-void)))))
540 ;; database inquiery functions
542 (defmethod db-describe-columns ((database odbc-db)
543 table-qualifier table-owner table-name column-name)
544 (with-slots (hdbc) database
545 (%describe-columns hdbc table-qualifier table-owner table-name column-name)))
547 ;; should translate info-type integers to keywords in order to make this
549 (defmethod get-odbc-info ((database odbc-db) info-type)
550 (with-slots (hdbc info) database
551 (or (gethash info-type info)
552 (setf (gethash info-type info)
553 (%sql-get-info hdbc info-type)))))
555 (defmethod get-odbc-info ((query odbc-query) info-type)
556 (get-odbc-info (odbc::query-database query) info-type))
559 (defmethod db-data-sources ((db-type (eql :odbc)))
560 "Returns a list of (data-source description) - pairs"
561 (let ((henv (%new-environment-handle)))
563 (loop with direction = :first
564 for data-source+description
565 = (multiple-value-list (%sql-data-sources henv :direction direction))
566 while (car data-source+description)
567 collect data-source+description
568 do (setf direction :next))
569 (%sql-free-environment henv))))