1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: odbc -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
5 ;;;; Name: odbc-api.lisp
6 ;;;; Purpose: Low-level ODBC API using UFFI
7 ;;;; Authors: Kevin M. Rosenberg and Paul Meurer
9 ;;;; This file, part of CLSQL, is Copyright (c) 2004 by Kevin M. Rosenberg
10 ;;;; and Copyright (C) Paul Meurer 1999 - 2001. All rights reserved.
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 ;;;; *************************************************************************
20 "Lisp representation of SQL Null value, default = nil.
21 May be locally bound to something else if a certain type is necessary.")
24 (defvar *binary-format* :unsigned-byte-vector)
25 (defvar *time-conversion-function*
26 (lambda (universal-time &optional fraction)
27 (let ((time (clsql-sys:utime->time universal-time)))
28 (setf time (clsql-sys:time+
30 (clsql-sys:make-duration :usec (/ fraction 1000))))
31 (clsql-sys:format-time nil time :format :iso))
34 "Bound to a function that converts from a Lisp universal time fixnum (and a fractional
35 as possible second argument) to the desired representation of date/time/timestamp. By default, returns an iso-timestring.")
37 (defvar +null-ptr+ (make-null-pointer :byte))
38 (defparameter +null-handle-ptr+ (make-null-pointer :void))
39 (defvar *info-output* nil
40 "Stream to send SUCCESS_WITH_INFO messages.")
42 (defmacro %put-str (ptr string &optional max-length)
43 (let ((size (gensym)))
44 `(let ((,size (length ,string)))
45 (when (and ,max-length (> ,size ,max-length))
46 (error 'clsql:sql-database-data-error
48 (format nil "string \"~a\" of length ~d is longer than max-length: ~d"
49 ,string ,size ,max-length)))
50 (with-cast-pointer (char-ptr ,ptr :byte)
52 (setf (deref-array char-ptr '(:array :byte) i)
53 (char-code (char ,string i))))
54 (setf (deref-array char-ptr '(:array :byte) ,size) 0)))))
56 (defun %cstring-into-vector (ptr vector offset size-in-bytes)
57 (dotimes (i size-in-bytes)
58 (setf (schar vector offset)
59 (ensure-char-character
60 (deref-array ptr '(:array :unsigned-char) i)))
64 (defun handle-error (henv hdbc hstmt)
65 (let ((sql-state (allocate-foreign-string 256))
66 (error-message (allocate-foreign-string #.$SQL_MAX_MESSAGE_LENGTH)))
67 (with-foreign-objects ((error-code #.$ODBC-LONG-TYPE)
69 (SQLError henv hdbc hstmt sql-state
70 error-code error-message
71 #.$SQL_MAX_MESSAGE_LENGTH msg-length)
72 (let ((err (convert-from-foreign-string error-message))
73 (state (convert-from-foreign-string sql-state)))
74 (free-foreign-object error-message)
75 (free-foreign-object sql-state)
79 (deref-pointer msg-length :short)
80 (deref-pointer error-code #.$ODBC-LONG-TYPE))))))
82 (defun sql-state (henv hdbc hstmt)
83 (let ((sql-state (allocate-foreign-string 256))
84 (error-message (allocate-foreign-string #.$SQL_MAX_MESSAGE_LENGTH)))
85 (with-foreign-objects ((error-code #.$ODBC-LONG-TYPE)
87 (SQLError henv hdbc hstmt sql-state error-code
88 error-message #.$SQL_MAX_MESSAGE_LENGTH msg-length)
89 (let ((state (convert-from-foreign-string sql-state)))
90 (free-foreign-object error-message)
91 (free-foreign-object sql-state)
93 ;; test this: return a keyword for efficiency
94 ;;(%cstring-to-keyword state)
97 (defmacro with-error-handling ((&key henv hdbc hstmt (print-info t))
99 (let ((result-code (gensym "RC-")))
100 `(let ((,result-code ,odbc-call))
102 ;; Check for allegro v7 & v8 bug with ODBC calls returning
103 ;; 32-bit unsigned ints, not 16-bit signed ints
104 #+(and allegro mswindows)
105 (when (> ,result-code #xFFFF)
106 (warn (format nil "16-bit return bug: result-code #x~X for expression ~S"
107 ,result-code (quote ,odbc-call)))
108 (setq ,result-code (logand ,result-code #xFFFF))
109 (when (> ,result-code #x7FFF)
110 (setq ,result-code (- ,result-code #x10000))))
114 (progn ,result-code ,@body))
115 (#.$SQL_SUCCESS_WITH_INFO
117 (multiple-value-bind (error-message sql-state)
118 (handle-error (or ,henv +null-handle-ptr+)
119 (or ,hdbc +null-handle-ptr+)
120 (or ,hstmt +null-handle-ptr+))
122 (format *info-output* "[ODBC info ~A] ~A state: ~A"
123 ,result-code error-message
125 (progn ,result-code ,@body))
126 (#.$SQL_INVALID_HANDLE
128 'clsql-sys:sql-database-error
129 :message "ODBC: Invalid handle"))
130 (#.$SQL_STILL_EXECUTING
132 'clsql-sys:sql-temporary-error
133 :message "ODBC: Still executing"))
135 (multiple-value-bind (error-message sql-state)
136 (handle-error (or ,henv +null-handle-ptr+)
137 (or ,hdbc +null-handle-ptr+)
138 (or ,hstmt +null-handle-ptr+))
140 'clsql-sys:sql-database-error
141 :message error-message
142 :secondary-error-id sql-state)))
143 (#.$SQL_NO_DATA_FOUND
144 (progn ,result-code ,@body))
145 ;; work-around for Allegro 7.0beta AMD64 which returns negative numbers
147 (multiple-value-bind (error-message sql-state)
148 (handle-error (or ,henv +null-handle-ptr+)
149 (or ,hdbc +null-handle-ptr+)
150 (or ,hstmt +null-handle-ptr+))
152 'clsql-sys:sql-database-error
153 :message error-message
154 :secondary-error-id sql-state))
156 (progn ,result-code ,@body))))))
158 (defun %new-environment-handle ()
160 (with-foreign-object (phenv 'sql-handle)
163 (SQLAllocHandle $SQL_HANDLE_ENV +null-handle-ptr+ phenv)
164 (deref-pointer phenv 'sql-handle)))))
165 (%set-attr-odbc-version henv $SQL_OV_ODBC3)
169 (defun %sql-free-environment (henv)
174 (defun %new-db-connection-handle (henv)
175 (with-foreign-object (phdbc 'sql-handle)
176 (setf (deref-pointer phdbc 'sql-handle) +null-handle-ptr+)
179 (SQLAllocHandle $SQL_HANDLE_DBC henv phdbc)
180 (deref-pointer phdbc 'sql-handle))))
182 (defun %free-statement (hstmt option)
190 (:unbind $SQL_UNBIND)
191 (:reset $SQL_RESET_PARAMS)))))
193 (defmacro with-statement-handle ((hstmt hdbc) &body body)
194 `(let ((,hstmt (%new-statement-handle ,hdbc)))
197 (%free-statement ,hstmt :drop))))
199 ;; functional interface
201 (defun %sql-connect (hdbc server uid pwd)
202 (with-cstrings ((server-ptr server)
207 (SQLConnect hdbc server-ptr $SQL_NTS uid-ptr
208 $SQL_NTS pwd-ptr $SQL_NTS))))
210 (defun %sql-driver-connect (hdbc connection-string completion window-handle)
211 (with-cstring (connection-ptr connection-string)
212 (let ((completed-connection-string (allocate-foreign-string $SQL_MAX_CONN_OUT)))
214 (with-foreign-object (completed-connection-length :short)
217 (SQLDriverConnect hdbc
219 connection-ptr $SQL_NTS
220 completed-connection-string $SQL_MAX_CONN_OUT
221 completed-connection-length
223 (free-foreign-object completed-connection-string)))))
225 (defun %disconnect (hdbc)
228 (SQLDisconnect hdbc)))
230 (defun %commit (henv hdbc)
232 (:henv henv :hdbc hdbc)
234 henv hdbc $SQL_COMMIT)))
236 (defun %rollback (henv hdbc)
238 (:henv henv :hdbc hdbc)
240 henv hdbc $SQL_ROLLBACK)))
242 ; col-nr is zero-based in Lisp but 1 based in sql
243 ; col-nr = :bookmark retrieves a bookmark.
244 (defun %bind-column (hstmt column-nr c-type data-ptr precision out-len-ptr)
248 (if (eq column-nr :bookmark) 0 (1+ column-nr))
249 c-type data-ptr precision out-len-ptr)))
251 ; parameter-nr is zero-based in Lisp
252 (defun %sql-bind-parameter (hstmt parameter-nr parameter-type c-type
253 sql-type precision scale data-ptr
254 max-value out-len-ptr)
257 (SQLBindParameter hstmt (1+ parameter-nr)
258 parameter-type ;$SQL_PARAM_INPUT
260 sql-type ;$SQL_VARCHAR
261 precision ;(1- (length str))
265 out-len-ptr ;#.+null-ptr+
268 (defun %sql-fetch (hstmt)
273 (defun %new-statement-handle (hdbc)
274 (let ((statement-handle
275 (with-foreign-object (phstmt 'sql-handle)
278 (SQLAllocHandle $SQL_HANDLE_STMT hdbc phstmt)
279 (deref-pointer phstmt 'sql-handle)))))
280 (if (uffi:null-pointer-p statement-handle)
281 (error 'clsql:sql-database-error :message "Received null statement handle.")
284 (defun %sql-get-info (hdbc info-type)
286 ;; those return string
287 ((#.$SQL_ACCESSIBLE_PROCEDURES
288 #.$SQL_ACCESSIBLE_TABLES
290 #.$SQL_DATA_SOURCE_NAME
291 #.$SQL_DATA_SOURCE_READ_ONLY
295 #.$SQL_DRIVER_ODBC_VER
297 #.$SQL_EXPRESSIONS_IN_ORDERBY
298 #.$SQL_IDENTIFIER_QUOTE_CHAR
300 #.$SQL_LIKE_ESCAPE_CLAUSE
301 #.$SQL_MAX_ROW_SIZE_INCLUDES_LONG
302 #.$SQL_MULT_RESULT_SETS
303 #.$SQL_MULTIPLE_ACTIVE_TXN
304 #.$SQL_NEED_LONG_DATA_LEN
305 #.$SQL_ODBC_SQL_OPT_IEF
307 #.$SQL_ORDER_BY_COLUMNS_IN_SELECT
310 #.$SQL_PROCEDURE_TERM
312 #.$SQL_QUALIFIER_NAME_SEPARATOR
313 #.$SQL_QUALIFIER_TERM
315 #.$SQL_SEARCH_PATTERN_ESCAPE
317 #.$SQL_SPECIAL_CHARACTERS
320 (let ((info-ptr (allocate-foreign-string 1024)))
321 (with-foreign-object (info-length-ptr :short)
324 (SQLGetInfo hdbc info-type info-ptr 1023 info-length-ptr)
325 (let ((info (convert-from-foreign-string info-ptr)))
326 (free-foreign-object info-ptr)
328 ;; those returning a word
329 ((#.$SQL_ACTIVE_CONNECTIONS
330 #.$SQL_ACTIVE_STATEMENTS
331 #.$SQL_CONCAT_NULL_BEHAVIOR
332 #.$SQL_CORRELATION_NAME
333 #.$SQL_CURSOR_COMMIT_BEHAVIOR
334 #.$SQL_CURSOR_ROLLBACK_BEHAVIOR
335 #.$SQL_MAX_COLUMN_NAME_LEN
336 #.$SQL_MAX_COLUMNS_IN_GROUP_BY
337 #.$SQL_MAX_COLUMNS_IN_INDEX
338 #.$SQL_MAX_COLUMNS_IN_ORDER_BY
339 #.$SQL_MAX_COLUMNS_IN_SELECT
340 #.$SQL_MAX_COLUMNS_IN_TABLE
341 #.$SQL_MAX_CURSOR_NAME_LEN
342 #.$SQL_MAX_OWNER_NAME_LEN
343 #.$SQL_MAX_PROCEDURE_NAME_LEN
344 #.$SQL_MAX_QUALIFIER_NAME_LEN
345 #.$SQL_MAX_TABLE_NAME_LEN
346 #.$SQL_MAX_TABLES_IN_SELECT
347 #.$SQL_MAX_USER_NAME_LEN
348 #.$SQL_NON_NULLABLE_COLUMNS
349 #.$SQL_NULL_COLLATION
350 #.$SQL_ODBC_API_CONFORMANCE
351 #.$SQL_ODBC_SAG_CLI_CONFORMANCE
352 #.$SQL_ODBC_SQL_CONFORMANCE
353 #.$SQL_QUALIFIER_LOCATION
354 #.$SQL_QUOTED_IDENTIFIER_CASE
356 (with-foreign-objects ((info-ptr :short)
357 (info-length-ptr :short))
365 (deref-pointer info-ptr :short)))
367 ;; those returning a long bitmask
369 #.$SQL_BOOKMARK_PERSISTENCE
370 #.$SQL_CONVERT_BIGINT
371 #.$SQL_CONVERT_BINARY
375 #.$SQL_CONVERT_DECIMAL
376 #.$SQL_CONVERT_DOUBLE
378 #.$SQL_CONVERT_INTEGER
379 #.$SQL_CONVERT_LONGVARCHAR
380 #.$SQL_CONVERT_NUMERIC
382 #.$SQL_CONVERT_SMALLINT
384 #.$SQL_CONVERT_TIMESTAMP
385 #.$SQL_CONVERT_TINYINT
386 #.$SQL_CONVERT_VARBINARY
387 #.$SQL_CONVERT_VARCHAR
388 #.$SQL_CONVERT_LONGVARBINARY
389 #.$SQL_CONVERT_FUNCTIONS
390 #.$SQL_FETCH_DIRECTION
392 #.$SQL_GETDATA_EXTENSIONS
394 #.$SQL_MAX_INDEX_SIZE
396 #.$SQL_MAX_STATEMENT_LEN
397 #.$SQL_NUMERIC_FUNCTIONS
399 #.$SQL_POS_OPERATIONS
400 #.$SQL_POSITIONED_STATEMENTS
401 #.$SQL_QUALIFIER_USAGE
402 #.$SQL_SCROLL_CONCURRENCY
403 #.$SQL_SCROLL_OPTIONS
404 #.$SQL_STATIC_SENSITIVITY
405 #.$SQL_STRING_FUNCTIONS
407 #.$SQL_SYSTEM_FUNCTIONS
408 #.$SQL_TIMEDATE_ADD_INTERVALS
409 #.$SQL_TIMEDATE_DIFF_INTERVALS
410 #.$SQL_TIMEDATE_FUNCTIONS
411 #.$SQL_TXN_ISOLATION_OPTION
413 (with-foreign-objects ((info-ptr #.$ODBC-LONG-TYPE)
414 (info-length-ptr :short))
422 (deref-pointer info-ptr #.$ODBC-LONG-TYPE)))
424 ;; those returning a long integer
425 ((#.$SQL_DEFAULT_TXN_ISOLATION
431 #.$SQL_IDENTIFIER_CASE
432 #.$SQL_MAX_BINARY_LITERAL_LEN
433 #.$SQL_MAX_CHAR_LITERAL_LEN
434 #.$SQL_ACTIVE_ENVIRONMENTS
436 (with-foreign-objects ((info-ptr #.$ODBC-LONG-TYPE)
437 (info-length-ptr :short))
440 (SQLGetInfo hdbc info-type info-ptr 255 info-length-ptr)
441 (deref-pointer info-ptr #.$ODBC-LONG-TYPE))))))
443 (defun %sql-exec-direct (sql hstmt henv hdbc)
444 (with-cstring (sql-ptr sql)
446 (:hstmt hstmt :henv henv :hdbc hdbc)
447 (SQLExecDirect hstmt sql-ptr $SQL_NTS))))
449 (defun %sql-cancel (hstmt)
454 (defun %sql-execute (hstmt)
459 (defun result-columns-count (hstmt)
460 (with-foreign-objects ((columns-nr-ptr :short))
461 (with-error-handling (:hstmt hstmt)
462 (SQLNumResultCols hstmt columns-nr-ptr)
463 (deref-pointer columns-nr-ptr :short))))
465 (defun result-rows-count (hstmt)
466 (with-foreign-objects ((row-count-ptr #.$ODBC-LONG-TYPE))
467 (with-error-handling (:hstmt hstmt)
468 (SQLRowCount hstmt row-count-ptr)
469 (deref-pointer row-count-ptr #.$ODBC-LONG-TYPE))))
471 ;; column counting is 1-based
472 (defun %describe-column (hstmt column-nr)
473 (let ((column-name-ptr (allocate-foreign-string 256)))
474 (with-foreign-objects ((column-name-length-ptr :short)
475 (column-sql-type-ptr :short)
476 (column-precision-ptr #.$ODBC-ULONG-TYPE)
477 (column-scale-ptr :short)
478 (column-nullable-p-ptr :short))
479 (with-error-handling (:hstmt hstmt)
480 (SQLDescribeCol hstmt column-nr column-name-ptr 256
481 column-name-length-ptr
485 column-nullable-p-ptr)
486 (let ((column-name (convert-from-foreign-string column-name-ptr)))
487 (free-foreign-object column-name-ptr)
490 (deref-pointer column-sql-type-ptr :short)
491 (deref-pointer column-precision-ptr #.$ODBC-ULONG-TYPE)
492 (deref-pointer column-scale-ptr :short)
493 (deref-pointer column-nullable-p-ptr :short)))))))
495 ;; parameter counting is 1-based
496 ;; this function isn't used, which is good because FreeTDS dosn't support it.
497 (defun %describe-parameter (hstmt parameter-nr)
498 (with-foreign-objects ((column-sql-type-ptr :short)
499 (column-precision-ptr #.$ODBC-ULONG-TYPE)
500 (column-scale-ptr :short)
501 (column-nullable-p-ptr :short))
504 (SQLDescribeParam hstmt parameter-nr
508 column-nullable-p-ptr)
510 (deref-pointer column-sql-type-ptr :short)
511 (deref-pointer column-precision-ptr #.$ODBC-ULONG-TYPE)
512 (deref-pointer column-scale-ptr :short)
513 (deref-pointer column-nullable-p-ptr :short)))))
515 (defun %column-attributes (hstmt column-nr descriptor-type)
516 (let ((descriptor-info-ptr (allocate-foreign-string 256)))
517 (with-foreign-objects ((descriptor-length-ptr :short)
518 (numeric-descriptor-ptr #.$ODBC-LONG-TYPE))
521 (SQLColAttributes hstmt column-nr descriptor-type descriptor-info-ptr
522 256 descriptor-length-ptr
523 numeric-descriptor-ptr)
524 (let ((desc (convert-from-foreign-string descriptor-info-ptr)))
525 (free-foreign-object descriptor-info-ptr)
528 (deref-pointer numeric-descriptor-ptr #.$ODBC-LONG-TYPE)))))))
530 (defun %prepare-describe-columns (hstmt table-qualifier table-owner
531 table-name column-name)
532 (with-cstrings ((table-qualifier-ptr table-qualifier)
533 (table-owner-ptr table-owner)
534 (table-name-ptr table-name)
535 (column-name-ptr column-name))
539 table-qualifier-ptr (length table-qualifier)
540 table-owner-ptr (length table-owner)
541 table-name-ptr (length table-name)
542 column-name-ptr (length column-name)))))
544 (defun %describe-columns (hdbc table-qualifier table-owner
545 table-name column-name)
546 (with-statement-handle (hstmt hdbc)
547 (%prepare-describe-columns hstmt table-qualifier table-owner
548 table-name column-name)
549 (fetch-all-rows hstmt)))
551 (defun %sql-data-sources (henv &key (direction :first))
552 (let ((name-ptr (allocate-foreign-string (1+ $SQL_MAX_DSN_LENGTH)))
553 (description-ptr (allocate-foreign-string 1024)))
554 (with-foreign-objects ((name-length-ptr :short)
555 (description-length-ptr :short))
556 (let ((res (with-error-handling
560 (:first $SQL_FETCH_FIRST)
561 (:next $SQL_FETCH_NEXT))
563 (1+ $SQL_MAX_DSN_LENGTH)
567 description-length-ptr))))
569 ((= res $SQL_NO_DATA_FOUND)
570 (let ((name (convert-from-foreign-string name-ptr))
571 (desc (convert-from-foreign-string description-ptr)))
572 (free-foreign-object name-ptr)
573 (free-foreign-object description-ptr)
578 (free-foreign-object name-ptr)
579 (free-foreign-object description-ptr)
584 (defun sql-to-c-type (sql-type)
586 ((#.$SQL_CHAR #.$SQL_VARCHAR #.$SQL_LONGVARCHAR
587 #.$SQL_NUMERIC #.$SQL_DECIMAL -8 -9 -10) $SQL_C_CHAR) ;; Added -10 for MSSQL ntext type
588 (#.$SQL_INTEGER $SQL_C_SLONG)
589 (#.$SQL_BIGINT $SQL_C_SBIGINT)
590 (#.$SQL_SMALLINT $SQL_C_SSHORT)
591 (#.$SQL_DOUBLE $SQL_C_DOUBLE)
592 (#.$SQL_FLOAT $SQL_C_DOUBLE)
593 (#.$SQL_REAL $SQL_C_FLOAT)
594 (#.$SQL_DATE $SQL_C_DATE)
595 (#.$SQL_TIME $SQL_C_TIME)
596 (#.$SQL_TIMESTAMP $SQL_C_TIMESTAMP)
597 (#.$SQL_TYPE_DATE $SQL_C_TYPE_DATE)
598 (#.$SQL_TYPE_TIME $SQL_C_TYPE_TIME)
599 (#.$SQL_TYPE_TIMESTAMP $SQL_C_TYPE_TIMESTAMP)
600 ((#.$SQL_BINARY #.$SQL_VARBINARY #.$SQL_LONGVARBINARY) $SQL_C_BINARY)
601 (#.$SQL_TINYINT $SQL_C_STINYINT)
602 (#.$SQL_BIT $SQL_C_BIT)))
604 (def-type byte-pointer-type (* :byte))
605 (def-type short-pointer-type (* :short))
606 (def-type int-pointer-type (* :int))
607 (def-type long-pointer-type (* #.$ODBC-LONG-TYPE))
608 (def-type big-pointer-type (* #.$ODBC-BIG-TYPE))
609 (def-type float-pointer-type (* :float))
610 (def-type double-pointer-type (* :double))
611 (def-type string-pointer-type (* :unsigned-char))
613 (defun get-cast-byte (ptr)
614 (locally (declare (type byte-pointer-type ptr))
615 (deref-pointer ptr :byte)))
617 (defun get-cast-short (ptr)
618 (locally (declare (type short-pointer-type ptr))
619 (deref-pointer ptr :short)))
621 (defun get-cast-int (ptr)
622 (locally (declare (type int-pointer-type ptr))
623 (deref-pointer ptr :int)))
625 (defun get-cast-long (ptr)
626 (locally (declare (type long-pointer-type ptr))
627 (deref-pointer ptr #.$ODBC-LONG-TYPE)))
629 (defun get-cast-big (ptr)
630 (locally (declare (type big-pointer-type ptr))
631 (deref-pointer ptr #.$ODBC-BIG-TYPE)))
633 (defun get-cast-single-float (ptr)
634 (locally (declare (type float-pointer-type ptr))
635 (deref-pointer ptr :float)))
637 (defun get-cast-double-float (ptr)
638 (locally (declare (type double-pointer-type ptr))
639 (deref-pointer ptr :double)))
641 (defun get-cast-foreign-string (ptr)
642 (locally (declare (type string-pointer-type ptr))
643 (convert-from-foreign-string ptr)))
645 (defun get-cast-binary (ptr len format)
646 "FORMAT is one of :unsigned-byte-vector, :bit-vector (:string, :hex-string)"
647 (with-cast-pointer (casted ptr :unsigned-byte)
649 (:unsigned-byte-vector
650 (let ((vector (make-array len :element-type '(unsigned-byte 8))))
652 (setf (aref vector i)
653 (deref-array casted '(:array :unsigned-byte) i)))
656 (let ((vector (make-array (ash len 3) :element-type 'bit)))
658 (let ((byte (deref-array casted '(:array :byte) i)))
660 (setf (bit vector (+ (ash i 3) j))
661 (logand (ash byte (- j 7)) 1)))))
665 (defun read-data (data-ptr c-type sql-type out-len-ptr result-type)
666 (declare (type long-ptr-type out-len-ptr))
667 (let* ((out-len (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE))
669 (cond ((= out-len $SQL_NULL_DATA)
673 ;; SQL extended datatypes
674 (#.$SQL_TINYINT (get-cast-byte data-ptr))
675 (#.$SQL_C_STINYINT (get-cast-byte data-ptr)) ;; ?
676 (#.$SQL_C_SSHORT (get-cast-short data-ptr)) ;; ?
677 (#.$SQL_SMALLINT (get-cast-short data-ptr)) ;; ??
678 (#.$SQL_INTEGER (get-cast-int data-ptr))
679 (#.$SQL_BIGINT (get-cast-big data-ptr))
681 (let ((*read-base* 10))
682 (read-from-string (get-cast-foreign-string data-ptr))))
683 (#.$SQL_BIT (get-cast-byte data-ptr))
686 ((#.$SQL_C_DATE #.$SQL_C_TYPE_DATE)
687 (funcall *time-conversion-function* (date-to-universal-time data-ptr)))
688 ((#.$SQL_C_TIME #.$SQL_C_TYPE_TIME)
689 (multiple-value-bind (universal-time frac) (time-to-universal-time data-ptr)
690 (funcall *time-conversion-function* universal-time frac)))
691 ((#.$SQL_C_TIMESTAMP #.$SQL_C_TYPE_TIMESTAMP)
692 (multiple-value-bind (universal-time frac) (timestamp-to-universal-time data-ptr)
693 (funcall *time-conversion-function* universal-time frac)))
695 (get-cast-int data-ptr))
697 (get-cast-single-float data-ptr))
699 (get-cast-double-float data-ptr))
701 (get-cast-long data-ptr))
703 (#.$SQL_C_BIT ; encountered only in Access
704 (get-cast-byte data-ptr))
706 (get-cast-binary data-ptr out-len *binary-format*))
707 ((#.$SQL_C_SSHORT #.$SQL_C_STINYINT) ; LMH short ints
708 (get-cast-short data-ptr)) ; LMH
709 (#.$SQL_C_SBIGINT (uffi:allocate-foreign-object #.$ODBC-BIG-TYPE)
710 (get-cast-short data-ptr))
713 (code-char (get-cast-short data-ptr)))
715 (get-cast-foreign-string data-ptr)))))))))
717 ;; FIXME: this could be better optimized for types which use READ-FROM-STRING above
719 (if (and (or (eq result-type t) (eq result-type :string))
721 (not (stringp value)))
722 (write-to-string value)
725 ;; which value is appropriate?
726 (defparameter +max-precision+ 4001)
728 (defvar *break-on-unknown-data-type* t)
730 ;; C. Stacy's idea to factor this out
731 ;; "Make it easy to add new datatypes by making new subroutine %ALLOCATE-BINDINGS,
732 ;; so that I don't have to remember to make changes in more than one place.
733 ;; Just keep it in synch with READ-DATA."
734 (defun %allocate-bindings (sql-type precision)
735 (let* ((c-type (sql-to-c-type sql-type))
736 (size (if (zerop precision)
737 +max-precision+ ;; if the precision cannot be determined
738 (min precision +max-precision+)))
739 (long-p (= size +max-precision+))
741 (case c-type ;; add more?
742 (#.$SQL_C_SLONG (uffi:allocate-foreign-object #.$ODBC-LONG-TYPE))
743 ((#.$SQL_C_DATE #.$SQL_C_TYPE_DATE) (allocate-foreign-object 'sql-c-date))
744 ((#.$SQL_C_TIME #.$SQL_C_TYPE_TIME) (allocate-foreign-object 'sql-c-time))
745 ((#.$SQL_C_TIMESTAMP #.$SQL_C_TYPE_TIMESTAMP) (allocate-foreign-object 'sql-c-timestamp))
746 (#.$SQL_C_FLOAT (uffi:allocate-foreign-object :float))
747 (#.$SQL_C_DOUBLE (uffi:allocate-foreign-object :double))
748 (#.$SQL_C_BIT (uffi:allocate-foreign-object :byte))
749 (#.$SQL_C_STINYINT (uffi:allocate-foreign-object :byte))
750 (#.$SQL_C_SBIGINT (uffi:allocate-foreign-object #.$ODBC-BIG-TYPE))
751 (#.$SQL_C_SSHORT (uffi:allocate-foreign-object :short))
752 (#.$SQL_C_CHAR (uffi:allocate-foreign-string (1+ size)))
753 (#.$SQL_C_BINARY (uffi:allocate-foreign-string (1+ (* 2 size))))
755 ;; Maybe should signal a restartable condition for this?
756 (when *break-on-unknown-data-type*
757 (break "SQL type is ~A, precision ~D, size ~D, C type is ~A"
758 sql-type precision size c-type))
759 (uffi:allocate-foreign-object :byte (1+ size)))))
760 (out-len-ptr (uffi:allocate-foreign-object #.$ODBC-LONG-TYPE)))
761 (values c-type data-ptr out-len-ptr size long-p)))
763 (defun fetch-all-rows (hstmt &key free-option flatp)
764 (let ((column-count (result-columns-count hstmt)))
765 (unless (zerop column-count)
766 (let ((names (make-array column-count))
767 (sql-types (make-array column-count :element-type 'fixnum))
768 (c-types (make-array column-count :element-type 'fixnum))
769 (precisions (make-array column-count :element-type 'fixnum))
770 (data-ptrs (make-array column-count :initial-element nil))
771 (out-len-ptrs (make-array column-count :initial-element nil))
772 (scales (make-array column-count :element-type 'fixnum))
773 (nullables-p (make-array column-count :element-type 'fixnum)))
777 (dotimes (col-nr column-count)
778 ;; get column information
779 (multiple-value-bind (name sql-type precision scale nullable-p)
780 (%describe-column hstmt (1+ col-nr))
781 ;; allocate space to bind result rows to
782 (multiple-value-bind (c-type data-ptr out-len-ptr)
783 (%allocate-bindings sql-type precision)
784 (%bind-column hstmt col-nr c-type data-ptr (1+ precision) out-len-ptr)
785 (setf (svref names col-nr) name
786 (aref sql-types col-nr) sql-type
787 (aref c-types col-nr) (sql-to-c-type sql-type)
788 (aref precisions col-nr) (if (zerop precision) 0 precision)
789 (aref scales col-nr) scale
790 (aref nullables-p col-nr) nullable-p
791 (aref data-ptrs col-nr) data-ptr
792 (aref out-len-ptrs col-nr) out-len-ptr))))
796 (when (> column-count 1)
797 (error 'clsql:sql-database-error
798 :message "If more than one column is to be fetched, flatp has to be nil."))
799 (loop until (= (%sql-fetch hstmt) $SQL_NO_DATA_FOUND)
801 (read-data (aref data-ptrs 0)
804 (aref out-len-ptrs 0)
807 (loop until (= (%sql-fetch hstmt) $SQL_NO_DATA_FOUND)
809 (loop for col-nr from 0 to (1- column-count)
811 (read-data (aref data-ptrs col-nr)
812 (aref c-types col-nr)
813 (aref sql-types col-nr)
814 (aref out-len-ptrs col-nr)
817 ;; dispose of memory etc
818 (when free-option (%free-statement hstmt free-option))
819 (dotimes (col-nr column-count)
820 (let ((data-ptr (aref data-ptrs col-nr))
821 (out-len-ptr (aref out-len-ptrs col-nr)))
822 (when data-ptr (free-foreign-object data-ptr)) ; we *did* allocate them
823 (when out-len-ptr (free-foreign-object out-len-ptr)))))))))
825 ;; to do: factor out common parts, put the sceleton (the obligatory macro part)
826 ;; of %do-fetch into sql package (has been done)
828 (defun %sql-prepare (hstmt sql)
829 (with-cstring (sql-ptr sql)
830 (with-error-handling (:hstmt hstmt)
831 (SQLPrepare hstmt sql-ptr $SQL_NTS))))
833 ;; depending on option, we return a long int or a string; string not implemented
834 (defun get-connection-option (hdbc option)
835 (with-foreign-object (param-ptr #.$ODBC-LONG-TYPE)
836 (with-error-handling (:hdbc hdbc)
837 (SQLGetConnectOption hdbc option param-ptr)
838 (deref-pointer param-ptr #.$ODBC-LONG-TYPE))))
840 (defun set-connection-option (hdbc option param)
841 (with-error-handling (:hdbc hdbc)
842 (SQLSetConnectOption hdbc option param)))
844 (defun disable-autocommit (hdbc)
845 (set-connection-option hdbc $SQL_AUTOCOMMIT $SQL_AUTOCOMMIT_OFF))
847 (defun enable-autocommit (hdbc)
848 (set-connection-option hdbc $SQL_AUTOCOMMIT $SQL_AUTOCOMMIT_ON))
850 (defun %sql-set-pos (hstmt row option lock)
853 (SQLSetPos hstmt row option lock)))
855 (defun %sql-extended-fetch (hstmt fetch-type row)
856 (with-foreign-objects ((row-count-ptr #.$ODBC-ULONG-TYPE)
857 (row-status-ptr :short))
858 (with-error-handling (:hstmt hstmt)
859 (SQLExtendedFetch hstmt fetch-type row row-count-ptr
861 (values (deref-pointer row-count-ptr #.$ODBC-ULONG-TYPE)
862 (deref-pointer row-status-ptr :short)))))
864 ; column-nr is zero-based
865 (defun %sql-get-data (hstmt column-nr c-type data-ptr precision out-len-ptr)
867 (:hstmt hstmt :print-info nil)
868 (SQLGetData hstmt (if (eq column-nr :bookmark) 0 (1+ column-nr))
869 c-type data-ptr precision out-len-ptr)))
871 (defun %sql-param-data (hstmt param-ptr)
872 (with-error-handling (:hstmt hstmt :print-info t) ;; nil
873 (SQLParamData hstmt param-ptr)))
875 (defun %sql-put-data (hstmt data-ptr size)
877 (:hstmt hstmt :print-info t) ;; nil
878 (SQLPutData hstmt data-ptr size)))
880 (defconstant $sql-data-truncated (intern "01004" :keyword))
882 (defun read-data-in-chunks (hstmt column-nr data-ptr c-type sql-type
883 out-len-ptr result-type)
884 (declare (type long-ptr-type out-len-ptr)
885 (ignore result-type))
886 (let* ((res (%sql-get-data hstmt column-nr c-type data-ptr
887 +max-precision+ out-len-ptr))
888 (out-len (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE))
890 (result (case out-len
892 (return-from read-data-in-chunks *null*))
893 (#.$SQL_NO_TOTAL ;; don't know how long it is going to be
894 (let ((str (make-array 0 :element-type 'character :adjustable t)))
895 (loop do (if (= c-type #.$SQL_CHAR)
896 (let ((data-length (foreign-string-length data-ptr)))
897 (adjust-array str (+ offset data-length)
898 :initial-element #\?)
899 (setf offset (%cstring-into-vector
903 (error 'clsql:sql-database-error :message "wrong type. preliminary."))
904 while (and (= res $SQL_SUCCESS_WITH_INFO)
905 (equal (sql-state +null-handle-ptr+ +null-handle-ptr+ hstmt)
907 do (setf res (%sql-get-data hstmt column-nr c-type data-ptr
908 +max-precision+ out-len-ptr)))
909 (setf str (coerce str 'string))
910 (if (= sql-type $SQL_DECIMAL)
911 (let ((*read-base* 10))
912 (read-from-string str))
917 (octets (make-array out-len :element-type '(unsigned-byte 8) :initial-element 0)))
920 (loop for i from 0 to (1- (min out-len +max-precision+))
921 do (setf (aref octets (+ offset i)) (deref-array data-ptr '(:array :unsigned-byte) i))
922 finally (incf offset (1- i)))
924 (and (= res $SQL_SUCCESS_WITH_INFO)
925 (> out-len +max-precision+))
927 (setf res (%sql-get-data hstmt column-nr c-type data-ptr +max-precision+ out-len-ptr)
928 out-len (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE)))
929 (setf str (uffi:octets-to-string octets))
930 (if (= sql-type $SQL_DECIMAL)
931 (let ((*read-base* 10))
932 (read-from-string str))
934 (setf (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE) #.$SQL_NO_TOTAL) ;; reset the out length for the next row
937 (def-type c-timestamp-ptr-type (* (:struct sql-c-timestamp)))
938 (def-type c-time-ptr-type (* (:struct sql-c-time)))
939 (def-type c-date-ptr-type (* (:struct sql-c-date)))
941 (defun timestamp-to-universal-time (ptr)
942 (declare (type c-timestamp-ptr-type ptr))
944 (encode-universal-time
945 (get-slot-value ptr 'sql-c-timestamp 'second)
946 (get-slot-value ptr 'sql-c-timestamp 'minute)
947 (get-slot-value ptr 'sql-c-timestamp 'hour)
948 (get-slot-value ptr 'sql-c-timestamp 'day)
949 (get-slot-value ptr 'sql-c-timestamp 'month)
950 (get-slot-value ptr 'sql-c-timestamp 'year))
951 (get-slot-value ptr 'sql-c-timestamp 'fraction)))
953 (defun universal-time-to-timestamp (time &optional (fraction 0))
954 (multiple-value-bind (sec min hour day month year)
955 (decode-universal-time time)
956 (let ((ptr (allocate-foreign-object 'sql-c-timestamp)))
957 (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
958 (get-slot-value ptr 'sql-c-timestamp 'minute) min
959 (get-slot-value ptr 'sql-c-timestamp 'hour) hour
960 (get-slot-value ptr 'sql-c-timestamp 'day) day
961 (get-slot-value ptr 'sql-c-timestamp 'month) month
962 (get-slot-value ptr 'sql-c-timestamp 'year) year
963 (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
966 (defun %put-timestamp (ptr time &optional (fraction 0))
967 (declare (type c-timestamp-ptr-type ptr))
968 (multiple-value-bind (sec min hour day month year)
969 (decode-universal-time time)
970 (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
971 (get-slot-value ptr 'sql-c-timestamp 'minute) min
972 (get-slot-value ptr 'sql-c-timestamp 'hour) hour
973 (get-slot-value ptr 'sql-c-timestamp 'day) day
974 (get-slot-value ptr 'sql-c-timestamp 'month) month
975 (get-slot-value ptr 'sql-c-timestamp 'year) year
976 (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
979 (defun date-to-universal-time (ptr)
980 (declare (type c-date-ptr-type ptr))
981 (encode-universal-time
983 (get-slot-value ptr 'sql-c-timestamp 'day)
984 (get-slot-value ptr 'sql-c-timestamp 'month)
985 (get-slot-value ptr 'sql-c-timestamp 'year)))
987 (defun time-to-universal-time (ptr)
988 (declare (type c-time-ptr-type ptr))
989 (encode-universal-time
990 (get-slot-value ptr 'sql-c-timestamp 'second)
991 (get-slot-value ptr 'sql-c-timestamp 'minute)
992 (get-slot-value ptr 'sql-c-timestamp 'hour)
998 (defun %set-attr-odbc-version (henv version)
999 (with-error-handling (:henv henv)
1000 (SQLSetEnvAttr henv $SQL_ATTR_ODBC_VERSION
1001 (make-pointer version :void) 0)))
1003 (defun %list-tables (hstmt)
1004 (with-error-handling (:hstmt hstmt)
1005 (SQLTables hstmt +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0)))
1007 (defun %table-statistics (table hstmt &key unique (ensure t))
1008 (with-cstrings ((table-cs table))
1009 (with-error-handling (:hstmt hstmt)
1015 (if unique $SQL_INDEX_UNIQUE $SQL_INDEX_ALL)
1016 (if ensure $SQL_ENSURE $SQL_QUICK)))))
1018 (defun %list-data-sources (henv)
1019 (let ((dsn (allocate-foreign-string (1+ $SQL_MAX_DSN_LENGTH)))
1020 (desc (allocate-foreign-string 256))
1023 (with-foreign-objects ((dsn-len :short)
1025 (let ((res (with-error-handling (:henv henv)
1026 (SQLDataSources henv $SQL_FETCH_FIRST dsn
1027 (1+ $SQL_MAX_DSN_LENGTH)
1028 dsn-len desc 256 desc-len))))
1029 (when (or (eql res $SQL_SUCCESS)
1030 (eql res $SQL_SUCCESS_WITH_INFO))
1031 (push (convert-from-foreign-string dsn) results))
1033 (do ((res (with-error-handling (:henv henv)
1034 (SQLDataSources henv $SQL_FETCH_NEXT dsn
1035 (1+ $SQL_MAX_DSN_LENGTH)
1036 dsn-len desc 256 desc-len))
1037 (with-error-handling (:henv henv)
1038 (SQLDataSources henv $SQL_FETCH_NEXT dsn
1039 (1+ $SQL_MAX_DSN_LENGTH)
1040 dsn-len desc 256 desc-len))))
1041 ((not (or (eql res $SQL_SUCCESS)
1042 (eql res $SQL_SUCCESS_WITH_INFO))))
1043 (push (convert-from-foreign-string dsn) results))))
1045 (free-foreign-object dsn)
1046 (free-foreign-object desc)))
1047 (nreverse results)))