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)
27 (clsql-sys:format-time nil time :format :iso))
28 "Bound to a function that converts from a clsql:wall-time to the desired
29 representation of date/time/timestamp.
30 By default, returns an iso-timestring.")
32 (defvar +null-ptr+ (make-null-pointer :byte))
33 (defparameter +null-handle-ptr+ (make-null-pointer :void))
34 (defvar *info-output* nil
35 "Stream to send SUCCESS_WITH_INFO messages.")
37 (defmacro %put-str (ptr string &optional max-length)
38 (let ((size (gensym)))
39 `(let ((,size (length ,string)))
40 (when (and ,max-length (> ,size ,max-length))
41 (error 'clsql:sql-database-data-error
43 (format nil "string \"~a\" of length ~d is longer than max-length: ~d"
44 ,string ,size ,max-length)))
45 (with-cast-pointer (char-ptr ,ptr :byte)
47 (setf (deref-array char-ptr '(:array :byte) i)
48 (char-code (char ,string i))))
49 (setf (deref-array char-ptr '(:array :byte) ,size) 0)))))
51 (defun %cstring-into-vector (ptr vector offset size-in-bytes)
52 (dotimes (i size-in-bytes)
53 (setf (schar vector offset)
54 (ensure-char-character
55 ;; this is MUCH faster than (sb-alien:deref ptr i) even though
56 ;; sb-alien:deref makes more sense. I snagged this by looking at
57 ;; cffi which we had used previously without this bug
58 #+(and sbcl (not cffi))
59 (sb-sys:sap-ref-8 (sb-alien:alien-sap ptr) i)
60 #-(and sbcl (not cffi))
61 (deref-array ptr '(:array :unsigned-char) i)
66 (defmacro with-allocate-foreign-string ((var len) &body body)
67 "Safely does uffi:allocate-foreign-string-- making sure we do the uffi:free-foreign-object"
71 (setf ,var (uffi:allocate-foreign-string ,len))
74 (uffi:free-foreign-object ,var)))))
76 (defmacro with-allocate-foreign-strings (bindings &rest body)
78 `(with-allocate-foreign-string ,(car bindings)
79 (with-allocate-foreign-strings ,(cdr bindings)
83 (defun handle-error (henv hdbc hstmt)
84 (with-allocate-foreign-strings ((sql-state 256)
85 (error-message #.$SQL_MAX_MESSAGE_LENGTH))
86 (with-foreign-objects ((error-code #.$ODBC-LONG-TYPE)
88 (SQLError henv hdbc hstmt sql-state
89 error-code error-message
90 #.$SQL_MAX_MESSAGE_LENGTH msg-length)
92 (convert-from-foreign-string error-message)
93 (convert-from-foreign-string sql-state)
94 (deref-pointer msg-length :short)
95 (deref-pointer error-code #.$ODBC-LONG-TYPE)))))
97 (defun sql-state (henv hdbc hstmt)
98 (with-allocate-foreign-strings ((sql-state 256)
99 (error-message #.$SQL_MAX_MESSAGE_LENGTH))
100 (with-foreign-objects ((error-code #.$ODBC-LONG-TYPE)
102 (SQLError henv hdbc hstmt sql-state error-code
103 error-message #.$SQL_MAX_MESSAGE_LENGTH msg-length)
104 (convert-from-foreign-string sql-state)
105 ;; test this: return a keyword for efficiency
106 ;;(%cstring-to-keyword state)
109 (defmacro with-error-handling ((&key henv hdbc hstmt (print-info t))
110 odbc-call &body body)
111 (let ((result-code (gensym "RC-")))
112 `(let ((,result-code ,odbc-call))
114 ;; Check for allegro v7 & v8 bug with ODBC calls returning
115 ;; 32-bit unsigned ints, not 16-bit signed ints
116 #+(and allegro mswindows)
117 (when (> ,result-code #xFFFF)
118 (warn (format nil "16-bit return bug: result-code #x~X for expression ~S"
119 ,result-code (quote ,odbc-call)))
120 (setq ,result-code (logand ,result-code #xFFFF))
121 (when (> ,result-code #x7FFF)
122 (setq ,result-code (- ,result-code #x10000))))
126 (progn ,result-code ,@body))
127 (#.$SQL_SUCCESS_WITH_INFO
129 (multiple-value-bind (error-message sql-state)
130 (handle-error (or ,henv +null-handle-ptr+)
131 (or ,hdbc +null-handle-ptr+)
132 (or ,hstmt +null-handle-ptr+))
134 (format *info-output* "[ODBC info ~A] ~A state: ~A"
135 ,result-code error-message
137 (progn ,result-code ,@body))
138 (#.$SQL_INVALID_HANDLE
140 'clsql-sys:sql-database-error
141 :message "ODBC: Invalid handle"))
142 (#.$SQL_STILL_EXECUTING
144 'clsql-sys:sql-temporary-error
145 :message "ODBC: Still executing"))
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)))
155 (#.$SQL_NO_DATA_FOUND
156 (progn ,result-code ,@body))
157 ;; work-around for Allegro 7.0beta AMD64 which returns negative numbers
159 (multiple-value-bind (error-message sql-state)
160 (handle-error (or ,henv +null-handle-ptr+)
161 (or ,hdbc +null-handle-ptr+)
162 (or ,hstmt +null-handle-ptr+))
164 'clsql-sys:sql-database-error
165 :message error-message
166 :secondary-error-id sql-state))
168 (progn ,result-code ,@body))))))
170 (defun %new-environment-handle ()
172 (with-foreign-object (phenv 'sql-handle)
175 (SQLAllocHandle $SQL_HANDLE_ENV +null-handle-ptr+ phenv)
176 (deref-pointer phenv 'sql-handle)))))
177 (%set-attr-odbc-version henv $SQL_OV_ODBC3)
181 (defun %sql-free-environment (henv)
186 (defun %new-db-connection-handle (henv)
187 (with-foreign-object (phdbc 'sql-handle)
188 (setf (deref-pointer phdbc 'sql-handle) +null-handle-ptr+)
191 (SQLAllocHandle $SQL_HANDLE_DBC henv phdbc)
192 (deref-pointer phdbc 'sql-handle))))
194 (defun %free-statement (hstmt option)
202 (:unbind $SQL_UNBIND)
203 (:reset $SQL_RESET_PARAMS)))))
205 (defmacro with-statement-handle ((hstmt hdbc) &body body)
206 `(let ((,hstmt (%new-statement-handle ,hdbc)))
209 (%free-statement ,hstmt :drop))))
211 ;; functional interface
213 (defun %sql-connect (hdbc server uid pwd)
214 (with-cstrings ((server-ptr server)
219 (SQLConnect hdbc server-ptr $SQL_NTS uid-ptr
220 $SQL_NTS pwd-ptr $SQL_NTS))))
222 (defun %sql-driver-connect (hdbc connection-string completion window-handle)
223 (with-cstring (connection-ptr connection-string)
224 (with-allocate-foreign-string (completed-connection-string-ptr $SQL_MAX_CONN_OUT)
225 (with-foreign-object (completed-connection-length :short)
228 (SQLDriverConnect hdbc
230 connection-ptr $SQL_NTS
231 completed-connection-string-ptr $SQL_MAX_CONN_OUT
232 completed-connection-length
235 (defun %disconnect (hdbc)
241 (SQLFreeHandle $SQL_HANDLE_DBC hdbc))))
243 (defun %commit (henv hdbc)
245 (:henv henv :hdbc hdbc)
247 henv hdbc $SQL_COMMIT)))
249 (defun %rollback (henv hdbc)
251 (:henv henv :hdbc hdbc)
253 henv hdbc $SQL_ROLLBACK)))
255 ; col-nr is zero-based in Lisp but 1 based in sql
256 ; col-nr = :bookmark retrieves a bookmark.
257 (defun %bind-column (hstmt column-nr c-type data-ptr precision out-len-ptr)
261 (if (eq column-nr :bookmark) 0 (1+ column-nr))
262 c-type data-ptr precision out-len-ptr)))
264 ; parameter-nr is zero-based in Lisp
265 (defun %sql-bind-parameter (hstmt parameter-nr parameter-type c-type
266 sql-type precision scale data-ptr
267 max-value out-len-ptr)
270 (SQLBindParameter hstmt (1+ parameter-nr)
271 parameter-type ;$SQL_PARAM_INPUT
273 sql-type ;$SQL_VARCHAR
274 precision ;(1- (length str))
278 out-len-ptr ;#.+null-ptr+
281 (defun %sql-fetch (hstmt)
286 (defun %new-statement-handle (hdbc)
287 (let ((statement-handle
288 (with-foreign-object (phstmt 'sql-handle)
291 (SQLAllocHandle $SQL_HANDLE_STMT hdbc phstmt)
292 (deref-pointer phstmt 'sql-handle)))))
293 (if (uffi:null-pointer-p statement-handle)
294 (error 'clsql:sql-database-error :message "Received null statement handle.")
297 (defun %sql-get-info (hdbc info-type)
299 ;; those return string
300 ((#.$SQL_ACCESSIBLE_PROCEDURES
301 #.$SQL_ACCESSIBLE_TABLES
303 #.$SQL_DATA_SOURCE_NAME
304 #.$SQL_DATA_SOURCE_READ_ONLY
308 #.$SQL_DRIVER_ODBC_VER
310 #.$SQL_EXPRESSIONS_IN_ORDERBY
311 #.$SQL_IDENTIFIER_QUOTE_CHAR
313 #.$SQL_LIKE_ESCAPE_CLAUSE
314 #.$SQL_MAX_ROW_SIZE_INCLUDES_LONG
315 #.$SQL_MULT_RESULT_SETS
316 #.$SQL_MULTIPLE_ACTIVE_TXN
317 #.$SQL_NEED_LONG_DATA_LEN
318 #.$SQL_ODBC_SQL_OPT_IEF
320 #.$SQL_ORDER_BY_COLUMNS_IN_SELECT
323 #.$SQL_PROCEDURE_TERM
325 #.$SQL_QUALIFIER_NAME_SEPARATOR
326 #.$SQL_QUALIFIER_TERM
328 #.$SQL_SEARCH_PATTERN_ESCAPE
330 #.$SQL_SPECIAL_CHARACTERS
333 (with-allocate-foreign-string (info-ptr 1024)
334 (with-foreign-object (info-length-ptr :short)
337 (SQLGetInfo hdbc info-type info-ptr 1023 info-length-ptr)
338 (convert-from-foreign-string info-ptr)))))
339 ;; those returning a word
340 ((#.$SQL_ACTIVE_CONNECTIONS
341 #.$SQL_ACTIVE_STATEMENTS
342 #.$SQL_CONCAT_NULL_BEHAVIOR
343 #.$SQL_CORRELATION_NAME
344 #.$SQL_CURSOR_COMMIT_BEHAVIOR
345 #.$SQL_CURSOR_ROLLBACK_BEHAVIOR
346 #.$SQL_MAX_COLUMN_NAME_LEN
347 #.$SQL_MAX_COLUMNS_IN_GROUP_BY
348 #.$SQL_MAX_COLUMNS_IN_INDEX
349 #.$SQL_MAX_COLUMNS_IN_ORDER_BY
350 #.$SQL_MAX_COLUMNS_IN_SELECT
351 #.$SQL_MAX_COLUMNS_IN_TABLE
352 #.$SQL_MAX_CURSOR_NAME_LEN
353 #.$SQL_MAX_OWNER_NAME_LEN
354 #.$SQL_MAX_PROCEDURE_NAME_LEN
355 #.$SQL_MAX_QUALIFIER_NAME_LEN
356 #.$SQL_MAX_TABLE_NAME_LEN
357 #.$SQL_MAX_TABLES_IN_SELECT
358 #.$SQL_MAX_USER_NAME_LEN
359 #.$SQL_NON_NULLABLE_COLUMNS
360 #.$SQL_NULL_COLLATION
361 #.$SQL_ODBC_API_CONFORMANCE
362 #.$SQL_ODBC_SAG_CLI_CONFORMANCE
363 #.$SQL_ODBC_SQL_CONFORMANCE
364 #.$SQL_QUALIFIER_LOCATION
365 #.$SQL_QUOTED_IDENTIFIER_CASE
367 (with-foreign-objects ((info-ptr :short)
368 (info-length-ptr :short))
376 (deref-pointer info-ptr :short)))
378 ;; those returning a long bitmask
380 #.$SQL_BOOKMARK_PERSISTENCE
381 #.$SQL_CONVERT_BIGINT
382 #.$SQL_CONVERT_BINARY
386 #.$SQL_CONVERT_DECIMAL
387 #.$SQL_CONVERT_DOUBLE
389 #.$SQL_CONVERT_INTEGER
390 #.$SQL_CONVERT_LONGVARCHAR
391 #.$SQL_CONVERT_NUMERIC
393 #.$SQL_CONVERT_SMALLINT
395 #.$SQL_CONVERT_TIMESTAMP
396 #.$SQL_CONVERT_TINYINT
397 #.$SQL_CONVERT_VARBINARY
398 #.$SQL_CONVERT_VARCHAR
399 #.$SQL_CONVERT_LONGVARBINARY
400 #.$SQL_CONVERT_FUNCTIONS
401 #.$SQL_FETCH_DIRECTION
403 #.$SQL_GETDATA_EXTENSIONS
405 #.$SQL_MAX_INDEX_SIZE
407 #.$SQL_MAX_STATEMENT_LEN
408 #.$SQL_NUMERIC_FUNCTIONS
410 #.$SQL_POS_OPERATIONS
411 #.$SQL_POSITIONED_STATEMENTS
412 #.$SQL_QUALIFIER_USAGE
413 #.$SQL_SCROLL_CONCURRENCY
414 #.$SQL_SCROLL_OPTIONS
415 #.$SQL_STATIC_SENSITIVITY
416 #.$SQL_STRING_FUNCTIONS
418 #.$SQL_SYSTEM_FUNCTIONS
419 #.$SQL_TIMEDATE_ADD_INTERVALS
420 #.$SQL_TIMEDATE_DIFF_INTERVALS
421 #.$SQL_TIMEDATE_FUNCTIONS
422 #.$SQL_TXN_ISOLATION_OPTION
424 (with-foreign-objects ((info-ptr #.$ODBC-LONG-TYPE)
425 (info-length-ptr :short))
433 (deref-pointer info-ptr #.$ODBC-LONG-TYPE)))
435 ;; those returning a long integer
436 ((#.$SQL_DEFAULT_TXN_ISOLATION
442 #.$SQL_IDENTIFIER_CASE
443 #.$SQL_MAX_BINARY_LITERAL_LEN
444 #.$SQL_MAX_CHAR_LITERAL_LEN
445 #.$SQL_ACTIVE_ENVIRONMENTS
447 (with-foreign-objects ((info-ptr #.$ODBC-LONG-TYPE)
448 (info-length-ptr :short))
451 (SQLGetInfo hdbc info-type info-ptr 255 info-length-ptr)
452 (deref-pointer info-ptr #.$ODBC-LONG-TYPE))))))
454 (defun %sql-exec-direct (sql hstmt henv hdbc)
455 (with-cstring (sql-ptr sql)
457 (:hstmt hstmt :henv henv :hdbc hdbc)
458 (SQLExecDirect hstmt sql-ptr $SQL_NTS))))
460 (defun %sql-cancel (hstmt)
465 (defun %sql-execute (hstmt)
470 (defun result-columns-count (hstmt)
471 (with-foreign-objects ((columns-nr-ptr :short))
472 (with-error-handling (:hstmt hstmt)
473 (SQLNumResultCols hstmt columns-nr-ptr)
474 (deref-pointer columns-nr-ptr :short))))
476 (defun result-rows-count (hstmt)
477 (with-foreign-objects ((row-count-ptr #.$ODBC-LONG-TYPE))
478 (with-error-handling (:hstmt hstmt)
479 (SQLRowCount hstmt row-count-ptr)
480 (deref-pointer row-count-ptr #.$ODBC-LONG-TYPE))))
482 ;; column counting is 1-based
483 (defun %describe-column (hstmt column-nr)
484 (with-allocate-foreign-string (column-name-ptr 256)
485 (with-foreign-objects ((column-name-length-ptr :short)
486 (column-sql-type-ptr :short)
487 (column-precision-ptr #.$ODBC-ULONG-TYPE)
488 (column-scale-ptr :short)
489 (column-nullable-p-ptr :short))
490 (with-error-handling (:hstmt hstmt)
491 (SQLDescribeCol hstmt column-nr column-name-ptr 256
492 column-name-length-ptr
496 column-nullable-p-ptr)
498 (convert-from-foreign-string column-name-ptr)
499 (deref-pointer column-sql-type-ptr :short)
500 (deref-pointer column-precision-ptr #.$ODBC-ULONG-TYPE)
501 (deref-pointer column-scale-ptr :short)
502 (deref-pointer column-nullable-p-ptr :short))))))
504 ;; parameter counting is 1-based
505 ;; this function isn't used, which is good because FreeTDS dosn't support it.
506 (defun %describe-parameter (hstmt parameter-nr)
507 (with-foreign-objects ((column-sql-type-ptr :short)
508 (column-precision-ptr #.$ODBC-ULONG-TYPE)
509 (column-scale-ptr :short)
510 (column-nullable-p-ptr :short))
513 (SQLDescribeParam hstmt parameter-nr
517 column-nullable-p-ptr)
519 (deref-pointer column-sql-type-ptr :short)
520 (deref-pointer column-precision-ptr #.$ODBC-ULONG-TYPE)
521 (deref-pointer column-scale-ptr :short)
522 (deref-pointer column-nullable-p-ptr :short)))))
524 (defun %column-attributes (hstmt column-nr descriptor-type)
525 (with-allocate-foreign-string (descriptor-info-ptr 256)
526 (with-foreign-objects ((descriptor-length-ptr :short)
527 (numeric-descriptor-ptr #.$ODBC-LONG-TYPE))
530 (SQLColAttributes hstmt column-nr descriptor-type descriptor-info-ptr
531 256 descriptor-length-ptr
532 numeric-descriptor-ptr)
534 (convert-from-foreign-string descriptor-info-ptr)
535 (deref-pointer numeric-descriptor-ptr #.$ODBC-LONG-TYPE))))))
537 (defun %prepare-describe-columns (hstmt table-qualifier table-owner
538 table-name column-name)
539 (with-cstrings ((table-qualifier-ptr table-qualifier)
540 (table-owner-ptr table-owner)
541 (table-name-ptr table-name)
542 (column-name-ptr column-name))
546 table-qualifier-ptr (length table-qualifier)
547 table-owner-ptr (length table-owner)
548 table-name-ptr (length table-name)
549 column-name-ptr (length column-name)))))
551 (defun %describe-columns (hdbc table-qualifier table-owner
552 table-name column-name)
553 (with-statement-handle (hstmt hdbc)
554 (%prepare-describe-columns hstmt table-qualifier table-owner
555 table-name column-name)
556 (fetch-all-rows hstmt)))
558 (defun %sql-data-sources (henv &key (direction :first))
559 (with-allocate-foreign-strings ((name-ptr (1+ $SQL_MAX_DSN_LENGTH))
560 (description-ptr 1024))
561 (with-foreign-objects ((name-length-ptr :short)
562 (description-length-ptr :short))
563 (let ((res (with-error-handling
567 (:first $SQL_FETCH_FIRST)
568 (:next $SQL_FETCH_NEXT))
570 (1+ $SQL_MAX_DSN_LENGTH)
574 description-length-ptr))))
575 (when (= res $SQL_NO_DATA_FOUND)
577 (convert-from-foreign-string name-ptr)
578 (convert-from-foreign-string description-ptr)))))))
582 (defun sql-to-c-type (sql-type)
584 ;; Added -10 for MSSQL ntext type and -11 for nvarchar
585 ((#.$SQL_CHAR #.$SQL_VARCHAR #.$SQL_LONGVARCHAR
586 #.$SQL_NUMERIC #.$sql_decimal -8 -9 -10 -11) $SQL_C_CHAR)
587 (#.$SQL_INTEGER $SQL_C_SLONG)
588 (#.$SQL_BIGINT $SQL_C_SBIGINT)
589 (#.$SQL_SMALLINT $SQL_C_SSHORT)
590 (#.$SQL_DOUBLE $SQL_C_DOUBLE)
591 (#.$SQL_FLOAT $SQL_C_DOUBLE)
592 (#.$SQL_REAL $SQL_C_FLOAT)
593 (#.$SQL_DATE $SQL_C_DATE)
594 (#.$SQL_TIME $SQL_C_TIME)
595 (#.$SQL_TIMESTAMP $SQL_C_TIMESTAMP)
596 (#.$SQL_TYPE_DATE $SQL_C_TYPE_DATE)
597 (#.$SQL_TYPE_TIME $SQL_C_TYPE_TIME)
598 (#.$SQL_TYPE_TIMESTAMP $SQL_C_TYPE_TIMESTAMP)
599 ((#.$SQL_BINARY #.$SQL_VARBINARY #.$SQL_LONGVARBINARY) $SQL_C_BINARY)
600 (#.$SQL_TINYINT $SQL_C_STINYINT)
601 (#.$SQL_BIT $SQL_C_BIT)))
603 (def-type byte-pointer-type (* :byte))
604 (def-type short-pointer-type (* :short))
605 (def-type int-pointer-type (* :int))
606 (def-type long-pointer-type (* #.$ODBC-LONG-TYPE))
607 (def-type big-pointer-type (* #.$ODBC-BIG-TYPE))
608 (def-type float-pointer-type (* :float))
609 (def-type double-pointer-type (* :double))
610 (def-type string-pointer-type (* :unsigned-char))
612 (defun get-cast-byte (ptr)
613 (locally (declare (type byte-pointer-type ptr))
614 (deref-pointer ptr :byte)))
616 (defun get-cast-short (ptr)
617 (locally (declare (type short-pointer-type ptr))
618 (deref-pointer ptr :short)))
620 (defun get-cast-int (ptr)
621 (locally (declare (type int-pointer-type ptr))
622 (deref-pointer ptr :int)))
624 (defun get-cast-long (ptr)
625 (locally (declare (type long-pointer-type ptr))
626 (deref-pointer ptr #.$ODBC-LONG-TYPE)))
628 (defun get-cast-big (ptr)
629 (locally (declare (type big-pointer-type ptr))
630 (deref-pointer ptr #.$ODBC-BIG-TYPE)))
632 (defun get-cast-single-float (ptr)
633 (locally (declare (type float-pointer-type ptr))
634 (deref-pointer ptr :float)))
636 (defun get-cast-double-float (ptr)
637 (locally (declare (type double-pointer-type ptr))
638 (deref-pointer ptr :double)))
640 (defun get-cast-foreign-string (ptr)
641 (locally (declare (type string-pointer-type ptr))
642 (convert-from-foreign-string ptr)))
644 (defun get-cast-binary (ptr len format)
645 "FORMAT is one of :unsigned-byte-vector, :bit-vector (:string, :hex-string)"
646 (with-cast-pointer (casted ptr :unsigned-byte)
648 (:unsigned-byte-vector
649 (let ((vector (make-array len :element-type '(unsigned-byte 8))))
651 (setf (aref vector i)
652 (deref-array casted '(:array :unsigned-byte) i)))
655 (let ((vector (make-array (ash len 3) :element-type 'bit)))
657 (let ((byte (deref-array casted '(:array :byte) i)))
659 (setf (bit vector (+ (ash i 3) j))
660 (logand (ash byte (- j 7)) 1)))))
664 (defun read-data (data-ptr c-type sql-type out-len-ptr result-type)
665 (declare (type long-ptr-type out-len-ptr))
666 (let* ((out-len (get-cast-long out-len-ptr))
668 (cond ((= out-len $SQL_NULL_DATA) *null*)
671 ;; SQL extended datatypes
672 (#.$SQL_TINYINT (get-cast-byte data-ptr))
673 (#.$SQL_C_STINYINT (get-cast-byte data-ptr)) ;; ?
674 (#.$SQL_C_SSHORT (get-cast-short data-ptr)) ;; ?
675 (#.$SQL_SMALLINT (get-cast-short data-ptr)) ;; ??
676 (#.$SQL_INTEGER (get-cast-int data-ptr))
677 (#.$SQL_BIGINT (get-cast-big data-ptr))
678 ;; TODO: Change this to read in rationals instead of doubles
679 ((#.$SQL_DECIMAL #.$SQL_NUMERIC)
680 (let* ((*read-base* 10)
681 (*read-default-float-format* 'double-float)
682 (str (get-cast-foreign-string data-ptr)))
683 (read-from-string str)))
684 (#.$SQL_BIT (get-cast-byte data-ptr))
687 ((#.$SQL_C_DATE #.$SQL_C_TYPE_DATE)
688 (funcall *time-format* (date-to-clsql-time data-ptr)))
689 ((#.$SQL_C_TIME #.$SQL_C_TYPE_TIME)
690 (funcall *time-format* (time-to-clsql-time data-ptr)))
691 ((#.$SQL_C_TIMESTAMP #.$SQL_C_TYPE_TIMESTAMP)
692 (funcall *time-format* (timestamp-to-clsql-time data-ptr)))
694 (get-cast-int data-ptr))
696 (get-cast-single-float data-ptr))
698 (get-cast-double-float data-ptr))
700 (get-cast-long data-ptr))
702 (#.$SQL_C_BIT ; encountered only in Access
703 (get-cast-byte data-ptr))
705 (get-cast-binary data-ptr out-len *binary-format*))
706 ((#.$SQL_C_SSHORT #.$SQL_C_STINYINT) ; LMH short ints
707 (get-cast-short data-ptr)) ; LMH
708 (#.$SQL_C_SBIGINT (get-cast-big data-ptr))
711 (code-char (get-cast-short data-ptr)))
713 (get-cast-foreign-string data-ptr)))))))))
715 ;; FIXME: this could be better optimized for types which use READ-FROM-STRING above
717 (if (and (or (eq result-type t) (eq result-type :string))
719 (not (stringp value)))
720 (write-to-string value)
723 ;; which value is appropriate?
724 (defparameter +max-precision+ 4001)
726 (defvar *break-on-unknown-data-type* t)
728 ;; C. Stacy's idea to factor this out
729 ;; "Make it easy to add new datatypes by making new subroutine %ALLOCATE-BINDINGS,
730 ;; so that I don't have to remember to make changes in more than one place.
731 ;; Just keep it in synch with READ-DATA."
732 (defun %allocate-bindings (sql-type precision)
733 (let* ((c-type (sql-to-c-type sql-type))
734 (size (if (zerop precision)
735 +max-precision+ ;; if the precision cannot be determined
736 (min precision +max-precision+)))
737 (long-p (= size +max-precision+))
739 (case c-type ;; add more?
740 (#.$SQL_C_SLONG (uffi:allocate-foreign-object #.$ODBC-LONG-TYPE))
741 ((#.$SQL_C_DATE #.$SQL_C_TYPE_DATE) (allocate-foreign-object 'sql-c-date))
742 ((#.$SQL_C_TIME #.$SQL_C_TYPE_TIME) (allocate-foreign-object 'sql-c-time))
743 ((#.$SQL_C_TIMESTAMP #.$SQL_C_TYPE_TIMESTAMP) (allocate-foreign-object 'sql-c-timestamp))
744 (#.$SQL_C_FLOAT (uffi:allocate-foreign-object :float))
745 (#.$SQL_C_DOUBLE (uffi:allocate-foreign-object :double))
746 (#.$SQL_C_BIT (uffi:allocate-foreign-object :byte))
747 (#.$SQL_C_STINYINT (uffi:allocate-foreign-object :byte))
748 (#.$SQL_C_SBIGINT (uffi:allocate-foreign-object #.$ODBC-BIG-TYPE))
749 (#.$SQL_C_SSHORT (uffi:allocate-foreign-object :short))
750 (#.$SQL_C_CHAR (uffi:allocate-foreign-string (1+ size)))
751 (#.$SQL_C_BINARY (uffi:allocate-foreign-string (1+ (* 2 size))))
753 ;; Maybe should signal a restartable condition for this?
754 (when *break-on-unknown-data-type*
755 (break "SQL type is ~A, precision ~D, size ~D, C type is ~A"
756 sql-type precision size c-type))
757 (uffi:allocate-foreign-object :byte (1+ size)))))
758 (out-len-ptr (uffi:allocate-foreign-object #.$ODBC-LONG-TYPE)))
759 (values c-type data-ptr out-len-ptr size long-p)))
761 (defun fetch-all-rows (hstmt &key free-option flatp)
762 (let ((column-count (result-columns-count hstmt)))
763 (unless (zerop column-count)
764 (let ((names (make-array column-count))
765 (sql-types (make-array column-count :element-type 'fixnum))
766 (c-types (make-array column-count :element-type 'fixnum))
767 (precisions (make-array column-count :element-type 'fixnum))
768 (data-ptrs (make-array column-count :initial-element nil))
769 (out-len-ptrs (make-array column-count :initial-element nil))
770 (scales (make-array column-count :element-type 'fixnum))
771 (nullables-p (make-array column-count :element-type 'fixnum)))
775 (dotimes (col-nr column-count)
776 ;; get column information
777 (multiple-value-bind (name sql-type precision scale nullable-p)
778 (%describe-column hstmt (1+ col-nr))
779 ;; allocate space to bind result rows to
780 (multiple-value-bind (c-type data-ptr out-len-ptr)
781 (%allocate-bindings sql-type precision)
782 (%bind-column hstmt col-nr c-type data-ptr (1+ precision) out-len-ptr)
783 (setf (svref names col-nr) name
784 (aref sql-types col-nr) sql-type
785 (aref c-types col-nr) (sql-to-c-type sql-type)
786 (aref precisions col-nr) (if (zerop precision) 0 precision)
787 (aref scales col-nr) scale
788 (aref nullables-p col-nr) nullable-p
789 (aref data-ptrs col-nr) data-ptr
790 (aref out-len-ptrs col-nr) out-len-ptr))))
794 (when (> column-count 1)
795 (error 'clsql:sql-database-error
796 :message "If more than one column is to be fetched, flatp has to be nil."))
797 (loop until (= (%sql-fetch hstmt) $SQL_NO_DATA_FOUND)
799 (read-data (aref data-ptrs 0)
802 (aref out-len-ptrs 0)
805 (loop until (= (%sql-fetch hstmt) $SQL_NO_DATA_FOUND)
807 (loop for col-nr from 0 to (1- column-count)
809 (read-data (aref data-ptrs col-nr)
810 (aref c-types col-nr)
811 (aref sql-types col-nr)
812 (aref out-len-ptrs col-nr)
815 ;; dispose of memory etc
816 (when free-option (%free-statement hstmt free-option))
817 (dotimes (col-nr column-count)
818 (let ((data-ptr (aref data-ptrs col-nr))
819 (out-len-ptr (aref out-len-ptrs col-nr)))
820 (when data-ptr (free-foreign-object data-ptr)) ; we *did* allocate them
821 (when out-len-ptr (free-foreign-object out-len-ptr)))))))))
823 ;; to do: factor out common parts, put the sceleton (the obligatory macro part)
824 ;; of %do-fetch into sql package (has been done)
826 (defun %sql-prepare (hstmt sql)
827 (with-cstring (sql-ptr sql)
828 (with-error-handling (:hstmt hstmt)
829 (SQLPrepare hstmt sql-ptr $SQL_NTS))))
831 ;; depending on option, we return a long int or a string; string not implemented
832 (defun get-connection-option (hdbc option)
833 (with-foreign-object (param-ptr #.$ODBC-LONG-TYPE)
834 (with-error-handling (:hdbc hdbc)
835 (SQLGetConnectOption hdbc option param-ptr)
836 (deref-pointer param-ptr #.$ODBC-LONG-TYPE))))
838 (defun set-connection-option (hdbc option param)
839 (with-error-handling (:hdbc hdbc)
840 (SQLSetConnectOption hdbc option param)))
842 (defun disable-autocommit (hdbc)
843 (set-connection-option hdbc $SQL_AUTOCOMMIT $SQL_AUTOCOMMIT_OFF))
845 (defun enable-autocommit (hdbc)
846 (set-connection-option hdbc $SQL_AUTOCOMMIT $SQL_AUTOCOMMIT_ON))
848 (defun %sql-set-pos (hstmt row option lock)
851 (SQLSetPos hstmt row option lock)))
853 (defun %sql-extended-fetch (hstmt fetch-type row)
854 (with-foreign-objects ((row-count-ptr #.$ODBC-ULONG-TYPE)
855 (row-status-ptr :short))
856 (with-error-handling (:hstmt hstmt)
857 (SQLExtendedFetch hstmt fetch-type row row-count-ptr
859 (values (deref-pointer row-count-ptr #.$ODBC-ULONG-TYPE)
860 (deref-pointer row-status-ptr :short)))))
862 ; column-nr is zero-based
863 (defun %sql-get-data (hstmt column-nr c-type data-ptr precision out-len-ptr)
865 (:hstmt hstmt :print-info nil)
866 (SQLGetData hstmt (if (eq column-nr :bookmark) 0 (1+ column-nr))
867 c-type data-ptr precision out-len-ptr)))
869 (defun %sql-param-data (hstmt param-ptr)
870 (with-error-handling (:hstmt hstmt :print-info t) ;; nil
871 (SQLParamData hstmt param-ptr)))
873 (defun %sql-put-data (hstmt data-ptr size)
875 (:hstmt hstmt :print-info t) ;; nil
876 (SQLPutData hstmt data-ptr size)))
878 (defconstant $sql-data-truncated (intern "01004" :keyword))
881 (defun read-data-in-chunks (hstmt column-nr data-ptr c-type sql-type
882 out-len-ptr result-type)
883 (declare (type long-ptr-type out-len-ptr)
884 (ignore result-type))
885 (let* ((res (%sql-get-data hstmt column-nr c-type data-ptr
886 +max-precision+ out-len-ptr))
887 (out-len (get-cast-long out-len-ptr))
889 (result (case out-len
891 (return-from read-data-in-chunks *null*))
892 (#.$SQL_NO_TOTAL ;; don't know how long it is going to be
893 (let ((str (make-array 0 :element-type 'character :adjustable t)))
894 (loop do (if (= c-type #.$SQL_CHAR)
895 (let ((data-length (foreign-string-length data-ptr)))
896 (adjust-array str (+ offset data-length)
897 :initial-element #\?)
898 (setf offset (%cstring-into-vector
902 (error 'clsql:sql-database-error :message "wrong type. preliminary."))
903 while (and (= res $SQL_SUCCESS_WITH_INFO)
904 (equal (sql-state +null-handle-ptr+ +null-handle-ptr+ hstmt)
906 do (setf res (%sql-get-data hstmt column-nr c-type data-ptr
907 +max-precision+ out-len-ptr)))
908 (setf str (coerce str 'string))
909 (if (= sql-type $SQL_DECIMAL)
910 (let ((*read-base* 10))
911 (read-from-string str))
914 (let ((str (make-string out-len)))
917 (if (= c-type #.$SQL_CHAR)
918 (setf offset (%cstring-into-vector ;string
921 (min out-len (1- +max-precision+))))
922 (error 'clsql:sql-database-error :message "wrong type. preliminary."))
924 (and (= res $SQL_SUCCESS_WITH_INFO)
925 (>= out-len +max-precision+))
926 do (setf res (%sql-get-data hstmt column-nr c-type data-ptr
927 +max-precision+ out-len-ptr)
928 out-len (get-cast-long out-len-ptr)))
929 (if (= sql-type $SQL_DECIMAL)
930 (let ((*read-base* 10)
931 (*read-default-float-format* 'double-float))
932 (read-from-string str))
935 (setf (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE) #.$SQL_NO_TOTAL) ;; reset the out length for the next row
939 (def-type c-timestamp-ptr-type (* (:struct sql-c-timestamp)))
940 (def-type c-time-ptr-type (* (:struct sql-c-time)))
941 (def-type c-date-ptr-type (* (:struct sql-c-date)))
943 (defun timestamp-to-clsql-time (ptr)
944 (declare (type c-timestamp-ptr-type ptr))
946 :second (get-slot-value ptr 'sql-c-timestamp 'second)
947 :minute (get-slot-value ptr 'sql-c-timestamp 'minute)
948 :hour (get-slot-value ptr 'sql-c-timestamp 'hour)
949 :day (get-slot-value ptr 'sql-c-timestamp 'day)
950 :month (get-slot-value ptr 'sql-c-timestamp 'month)
951 :year (get-slot-value ptr 'sql-c-timestamp 'year)
952 :usec (let ((frac (get-slot-value ptr 'sql-c-timestamp 'fraction)))
953 (if frac (/ frac 1000) 0))))
955 (defun universal-time-to-timestamp (time &optional (fraction 0))
956 "TODO: Dead function?"
957 (multiple-value-bind (sec min hour day month year)
958 (decode-universal-time time)
959 (let ((ptr (allocate-foreign-object 'sql-c-timestamp)))
960 (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
961 (get-slot-value ptr 'sql-c-timestamp 'minute) min
962 (get-slot-value ptr 'sql-c-timestamp 'hour) hour
963 (get-slot-value ptr 'sql-c-timestamp 'day) day
964 (get-slot-value ptr 'sql-c-timestamp 'month) month
965 (get-slot-value ptr 'sql-c-timestamp 'year) year
966 (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
969 (defun %put-timestamp (ptr time &optional (fraction 0))
970 "TODO: Dead function?"
971 (declare (type c-timestamp-ptr-type ptr))
972 (multiple-value-bind (sec min hour day month year)
973 (decode-universal-time time)
974 (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
975 (get-slot-value ptr 'sql-c-timestamp 'minute) min
976 (get-slot-value ptr 'sql-c-timestamp 'hour) hour
977 (get-slot-value ptr 'sql-c-timestamp 'day) day
978 (get-slot-value ptr 'sql-c-timestamp 'month) month
979 (get-slot-value ptr 'sql-c-timestamp 'year) year
980 (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
983 (defun date-to-clsql-time (ptr)
984 (declare (type c-date-ptr-type ptr))
986 :second 0 :minute 0 :hour 0
987 :day (get-slot-value ptr 'sql-c-timestamp 'day)
988 :month (get-slot-value ptr 'sql-c-timestamp 'month)
989 :year (get-slot-value ptr 'sql-c-timestamp 'year)))
991 (defun time-to-clsql-time (ptr)
992 (declare (type c-time-ptr-type ptr))
994 :second (get-slot-value ptr 'sql-c-timestamp 'second)
995 :minute (get-slot-value ptr 'sql-c-timestamp 'minute)
996 :hour (get-slot-value ptr 'sql-c-timestamp 'hour)))
1001 (defun %set-attr-odbc-version (henv version)
1002 (with-error-handling (:henv henv)
1003 ;;note that we are passing version as an integer that happens to be
1004 ;;stuffed into a pointer.
1005 ;;http://msdn.microsoft.com/en-us/library/ms709285%28v=VS.85%29.aspx
1006 (SQLSetEnvAttr henv $SQL_ATTR_ODBC_VERSION
1007 (make-pointer version :void) 0)))
1009 (defun %list-tables (hstmt)
1010 (with-error-handling (:hstmt hstmt)
1011 (SQLTables hstmt +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0)))
1013 (defun %table-statistics (table hstmt &key unique (ensure t)
1014 &aux (table (princ-to-string
1015 (clsql-sys::unescaped-database-identifier table))))
1016 (with-cstrings ((table-cs table))
1017 (with-error-handling (:hstmt hstmt)
1023 (if unique $SQL_INDEX_UNIQUE $SQL_INDEX_ALL)
1024 (if ensure $SQL_ENSURE $SQL_QUICK)))))
1026 (defun %list-data-sources (henv)
1027 (let ((results nil))
1028 (with-foreign-strings ((dsn-ptr (1+ $SQL_MAX_DSN_LENGTH))
1030 (with-foreign-objects ((dsn-len :short)
1032 (let ((res (with-error-handling (:henv henv)
1033 (SQLDataSources henv $SQL_FETCH_FIRST dsn-ptr
1034 (1+ $SQL_MAX_DSN_LENGTH)
1035 dsn-len desc-ptr 256 desc-len))))
1036 (when (or (eql res $SQL_SUCCESS)
1037 (eql res $SQL_SUCCESS_WITH_INFO))
1038 (push (convert-from-foreign-string dsn-ptr) results))
1040 (do ((res (with-error-handling (:henv henv)
1041 (SQLDataSources henv $SQL_FETCH_NEXT dsn-ptr
1042 (1+ $SQL_MAX_DSN_LENGTH)
1043 dsn-len desc-ptr 256 desc-len))
1044 (with-error-handling (:henv henv)
1045 (SQLDataSources henv $SQL_FETCH_NEXT dsn-ptr
1046 (1+ $SQL_MAX_DSN_LENGTH)
1047 dsn-len desc-ptr 256 desc-len))))
1048 ((not (or (eql res $SQL_SUCCESS)
1049 (eql res $SQL_SUCCESS_WITH_INFO))))
1050 (push (convert-from-foreign-string dsn-ptr) results)))))
1051 (nreverse results)))