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
11 ;;;; This file, part of CLSQL, is Copyright (c) 2004 by Kevin M. Rosenberg
12 ;;;; and Copyright (C) Paul Meurer 1999 - 2001. All rights reserved.
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 ;;;; *************************************************************************
22 "Lisp representation of SQL Null value, default = nil.
23 May be locally bound to something else if a certain type is necessary.")
26 (defvar *binary-format* :unsigned-byte-vector)
27 (defvar *time-conversion-function*
28 (lambda (universal-time &optional fraction)
29 (declare (ignore fraction))
30 (clsql-sys:format-time
31 nil (clsql-sys:utime->time universal-time)
35 "Bound to a function that converts from a Lisp universal time fixnum (and a fractional
36 as possible second argument) to the desired representation of date/time/timestamp. By default, returns an iso-timestring.")
38 (defvar +null-ptr+ (make-null-pointer :byte))
39 (defparameter +null-handle-ptr+ (make-null-pointer :void))
40 (defvar *info-output* nil
41 "Stream to send SUCCESS_WITH_INFO messages.")
43 (defmacro %put-str (ptr string &optional max-length)
44 (let ((size (gensym)))
45 `(let ((,size (length ,string)))
46 (when (and ,max-length (> ,size ,max-length))
47 (error 'clsql:sql-database-data-error
49 (format nil "string \"~a\" of length ~d is longer than max-length: ~d"
50 ,string ,size ,max-length)))
51 (with-cast-pointer (char-ptr ,ptr :byte)
53 (setf (deref-array char-ptr '(:array :byte) i)
54 (char-code (char ,string i))))
55 (setf (deref-array char-ptr '(:array :byte) ,size) 0)))))
57 (defun %cstring-into-vector (ptr vector offset size-in-bytes)
58 (dotimes (i size-in-bytes)
59 (setf (schar vector offset)
60 (ensure-char-character
61 (deref-array ptr '(:array :unsigned-char) i)))
65 (defun handle-error (henv hdbc hstmt)
66 (let ((sql-state (allocate-foreign-string 256))
67 (error-message (allocate-foreign-string #.$SQL_MAX_MESSAGE_LENGTH)))
68 (with-foreign-objects ((error-code #.$ODBC-LONG-TYPE)
70 (SQLError henv hdbc hstmt sql-state
71 error-code error-message
72 #.$SQL_MAX_MESSAGE_LENGTH msg-length)
73 (let ((err (convert-from-foreign-string error-message))
74 (state (convert-from-foreign-string sql-state)))
75 (free-foreign-object error-message)
76 (free-foreign-object sql-state)
80 (deref-pointer msg-length :short)
81 (deref-pointer error-code #.$ODBC-LONG-TYPE))))))
83 (defun sql-state (henv hdbc hstmt)
84 (let ((sql-state (allocate-foreign-string 256))
85 (error-message (allocate-foreign-string #.$SQL_MAX_MESSAGE_LENGTH)))
86 (with-foreign-objects ((error-code #.$ODBC-LONG-TYPE)
88 (SQLError henv hdbc hstmt sql-state error-code
89 error-message #.$SQL_MAX_MESSAGE_LENGTH msg-length)
90 (let ((state (convert-from-foreign-string sql-state)))
91 (free-foreign-object error-message)
92 (free-foreign-object sql-state)
94 ;; test this: return a keyword for efficiency
95 ;;(%cstring-to-keyword state)
98 (defmacro with-error-handling ((&key henv hdbc hstmt (print-info t))
100 (let ((result-code (gensym "RC-")))
101 `(let ((,result-code ,odbc-call))
103 ;; Check for allegro v7 & v8 bug with ODBC calls returning
104 ;; 32-bit unsigned ints, not 16-bit signed ints
105 #+(and allegro mswindows)
106 (when (> ,result-code #xFFFF)
107 (warn (format nil "16-bit return bug: result-code #x~X for expression ~S"
108 ,result-code (quote ,odbc-call)))
109 (setq ,result-code (logand ,result-code #xFFFF))
110 (when (> ,result-code #x7FFF)
111 (setq ,result-code (- ,result-code #x10000))))
115 (progn ,result-code ,@body))
116 (#.$SQL_SUCCESS_WITH_INFO
118 (multiple-value-bind (error-message sql-state)
119 (handle-error (or ,henv +null-handle-ptr+)
120 (or ,hdbc +null-handle-ptr+)
121 (or ,hstmt +null-handle-ptr+))
123 (format *info-output* "[ODBC info ~A] ~A state: ~A"
124 ,result-code error-message
126 (progn ,result-code ,@body))
127 (#.$SQL_INVALID_HANDLE
129 'clsql-sys:sql-database-error
130 :message "ODBC: Invalid handle"))
131 (#.$SQL_STILL_EXECUTING
133 'clsql-sys:sql-temporary-error
134 :message "ODBC: Still executing"))
136 (multiple-value-bind (error-message sql-state)
137 (handle-error (or ,henv +null-handle-ptr+)
138 (or ,hdbc +null-handle-ptr+)
139 (or ,hstmt +null-handle-ptr+))
141 'clsql-sys:sql-database-error
142 :message error-message
143 :secondary-error-id sql-state)))
144 (#.$SQL_NO_DATA_FOUND
145 (progn ,result-code ,@body))
146 ;; work-around for Allegro 7.0beta AMD64 which returns negative numbers
148 (multiple-value-bind (error-message sql-state)
149 (handle-error (or ,henv +null-handle-ptr+)
150 (or ,hdbc +null-handle-ptr+)
151 (or ,hstmt +null-handle-ptr+))
153 'clsql-sys:sql-database-error
154 :message error-message
155 :secondary-error-id sql-state))
157 (progn ,result-code ,@body))))))
159 (defun %new-environment-handle ()
161 (with-foreign-object (phenv 'sql-handle)
164 (SQLAllocHandle $SQL_HANDLE_ENV +null-handle-ptr+ phenv)
165 (deref-pointer phenv 'sql-handle)))))
166 (%set-attr-odbc-version henv $SQL_OV_ODBC3)
170 (defun %sql-free-environment (henv)
175 (defun %new-db-connection-handle (henv)
176 (with-foreign-object (phdbc 'sql-handle)
177 (setf (deref-pointer phdbc 'sql-handle) +null-handle-ptr+)
180 (SQLAllocHandle $SQL_HANDLE_DBC henv phdbc)
181 (deref-pointer phdbc 'sql-handle))))
183 (defun %free-statement (hstmt option)
191 (:unbind $SQL_UNBIND)
192 (:reset $SQL_RESET_PARAMS)))))
194 (defmacro with-statement-handle ((hstmt hdbc) &body body)
195 `(let ((,hstmt (%new-statement-handle ,hdbc)))
198 (%free-statement ,hstmt :drop))))
200 ;; functional interface
202 (defun %sql-connect (hdbc server uid pwd)
203 (with-cstrings ((server-ptr server)
208 (SQLConnect hdbc server-ptr $SQL_NTS uid-ptr
209 $SQL_NTS pwd-ptr $SQL_NTS))))
211 (defun %sql-driver-connect (hdbc connection-string completion window-handle)
212 (with-cstring (connection-ptr connection-string)
213 (let ((completed-connection-string (allocate-foreign-string $SQL_MAX_CONN_OUT)))
215 (with-foreign-object (completed-connection-length :short)
218 (SQLDriverConnect hdbc
220 connection-ptr $SQL_NTS
221 completed-connection-string $SQL_MAX_CONN_OUT
222 completed-connection-length
224 (free-foreign-object completed-connection-string)))))
226 (defun %disconnect (hdbc)
229 (SQLDisconnect hdbc)))
231 (defun %commit (henv hdbc)
233 (:henv henv :hdbc hdbc)
235 henv hdbc $SQL_COMMIT)))
237 (defun %rollback (henv hdbc)
239 (:henv henv :hdbc hdbc)
241 henv hdbc $SQL_ROLLBACK)))
243 ; col-nr is zero-based in Lisp but 1 based in sql
244 ; col-nr = :bookmark retrieves a bookmark.
245 (defun %bind-column (hstmt column-nr c-type data-ptr precision out-len-ptr)
249 (if (eq column-nr :bookmark) 0 (1+ column-nr))
250 c-type data-ptr precision out-len-ptr)))
252 ; parameter-nr is zero-based in Lisp
253 (defun %sql-bind-parameter (hstmt parameter-nr parameter-type c-type
254 sql-type precision scale data-ptr
255 max-value out-len-ptr)
258 (SQLBindParameter hstmt (1+ parameter-nr)
259 parameter-type ;$SQL_PARAM_INPUT
261 sql-type ;$SQL_VARCHAR
262 precision ;(1- (length str))
266 out-len-ptr ;#.+null-ptr+
269 (defun %sql-fetch (hstmt)
274 (defun %new-statement-handle (hdbc)
275 (let ((statement-handle
276 (with-foreign-object (phstmt 'sql-handle)
279 (SQLAllocHandle $SQL_HANDLE_STMT hdbc phstmt)
280 (deref-pointer phstmt 'sql-handle)))))
281 (if (uffi:null-pointer-p statement-handle)
282 (error 'clsql:sql-database-error :message "Received null statement handle.")
285 (defun %sql-get-info (hdbc info-type)
287 ;; those return string
288 ((#.$SQL_ACCESSIBLE_PROCEDURES
289 #.$SQL_ACCESSIBLE_TABLES
291 #.$SQL_DATA_SOURCE_NAME
292 #.$SQL_DATA_SOURCE_READ_ONLY
296 #.$SQL_DRIVER_ODBC_VER
298 #.$SQL_EXPRESSIONS_IN_ORDERBY
299 #.$SQL_IDENTIFIER_QUOTE_CHAR
301 #.$SQL_LIKE_ESCAPE_CLAUSE
302 #.$SQL_MAX_ROW_SIZE_INCLUDES_LONG
303 #.$SQL_MULT_RESULT_SETS
304 #.$SQL_MULTIPLE_ACTIVE_TXN
305 #.$SQL_NEED_LONG_DATA_LEN
306 #.$SQL_ODBC_SQL_OPT_IEF
308 #.$SQL_ORDER_BY_COLUMNS_IN_SELECT
311 #.$SQL_PROCEDURE_TERM
313 #.$SQL_QUALIFIER_NAME_SEPARATOR
314 #.$SQL_QUALIFIER_TERM
316 #.$SQL_SEARCH_PATTERN_ESCAPE
318 #.$SQL_SPECIAL_CHARACTERS
321 (let ((info-ptr (allocate-foreign-string 1024)))
322 (with-foreign-object (info-length-ptr :short)
325 (SQLGetInfo hdbc info-type info-ptr 1023 info-length-ptr)
326 (let ((info (convert-from-foreign-string info-ptr)))
327 (free-foreign-object info-ptr)
329 ;; those returning a word
330 ((#.$SQL_ACTIVE_CONNECTIONS
331 #.$SQL_ACTIVE_STATEMENTS
332 #.$SQL_CONCAT_NULL_BEHAVIOR
333 #.$SQL_CORRELATION_NAME
334 #.$SQL_CURSOR_COMMIT_BEHAVIOR
335 #.$SQL_CURSOR_ROLLBACK_BEHAVIOR
336 #.$SQL_MAX_COLUMN_NAME_LEN
337 #.$SQL_MAX_COLUMNS_IN_GROUP_BY
338 #.$SQL_MAX_COLUMNS_IN_INDEX
339 #.$SQL_MAX_COLUMNS_IN_ORDER_BY
340 #.$SQL_MAX_COLUMNS_IN_SELECT
341 #.$SQL_MAX_COLUMNS_IN_TABLE
342 #.$SQL_MAX_CURSOR_NAME_LEN
343 #.$SQL_MAX_OWNER_NAME_LEN
344 #.$SQL_MAX_PROCEDURE_NAME_LEN
345 #.$SQL_MAX_QUALIFIER_NAME_LEN
346 #.$SQL_MAX_TABLE_NAME_LEN
347 #.$SQL_MAX_TABLES_IN_SELECT
348 #.$SQL_MAX_USER_NAME_LEN
349 #.$SQL_NON_NULLABLE_COLUMNS
350 #.$SQL_NULL_COLLATION
351 #.$SQL_ODBC_API_CONFORMANCE
352 #.$SQL_ODBC_SAG_CLI_CONFORMANCE
353 #.$SQL_ODBC_SQL_CONFORMANCE
354 #.$SQL_QUALIFIER_LOCATION
355 #.$SQL_QUOTED_IDENTIFIER_CASE
357 (with-foreign-objects ((info-ptr :short)
358 (info-length-ptr :short))
366 (deref-pointer info-ptr :short)))
368 ;; those returning a long bitmask
370 #.$SQL_BOOKMARK_PERSISTENCE
371 #.$SQL_CONVERT_BIGINT
372 #.$SQL_CONVERT_BINARY
376 #.$SQL_CONVERT_DECIMAL
377 #.$SQL_CONVERT_DOUBLE
379 #.$SQL_CONVERT_INTEGER
380 #.$SQL_CONVERT_LONGVARCHAR
381 #.$SQL_CONVERT_NUMERIC
383 #.$SQL_CONVERT_SMALLINT
385 #.$SQL_CONVERT_TIMESTAMP
386 #.$SQL_CONVERT_TINYINT
387 #.$SQL_CONVERT_VARBINARY
388 #.$SQL_CONVERT_VARCHAR
389 #.$SQL_CONVERT_LONGVARBINARY
390 #.$SQL_CONVERT_FUNCTIONS
391 #.$SQL_FETCH_DIRECTION
393 #.$SQL_GETDATA_EXTENSIONS
395 #.$SQL_MAX_INDEX_SIZE
397 #.$SQL_MAX_STATEMENT_LEN
398 #.$SQL_NUMERIC_FUNCTIONS
400 #.$SQL_POS_OPERATIONS
401 #.$SQL_POSITIONED_STATEMENTS
402 #.$SQL_QUALIFIER_USAGE
403 #.$SQL_SCROLL_CONCURRENCY
404 #.$SQL_SCROLL_OPTIONS
405 #.$SQL_STATIC_SENSITIVITY
406 #.$SQL_STRING_FUNCTIONS
408 #.$SQL_SYSTEM_FUNCTIONS
409 #.$SQL_TIMEDATE_ADD_INTERVALS
410 #.$SQL_TIMEDATE_DIFF_INTERVALS
411 #.$SQL_TIMEDATE_FUNCTIONS
412 #.$SQL_TXN_ISOLATION_OPTION
414 (with-foreign-objects ((info-ptr #.$ODBC-LONG-TYPE)
415 (info-length-ptr :short))
423 (deref-pointer info-ptr #.$ODBC-LONG-TYPE)))
425 ;; those returning a long integer
426 ((#.$SQL_DEFAULT_TXN_ISOLATION
432 #.$SQL_IDENTIFIER_CASE
433 #.$SQL_MAX_BINARY_LITERAL_LEN
434 #.$SQL_MAX_CHAR_LITERAL_LEN
435 #.$SQL_ACTIVE_ENVIRONMENTS
437 (with-foreign-objects ((info-ptr #.$ODBC-LONG-TYPE)
438 (info-length-ptr :short))
441 (SQLGetInfo hdbc info-type info-ptr 255 info-length-ptr)
442 (deref-pointer info-ptr #.$ODBC-LONG-TYPE))))))
444 (defun %sql-exec-direct (sql hstmt henv hdbc)
445 (with-cstring (sql-ptr sql)
447 (:hstmt hstmt :henv henv :hdbc hdbc)
448 (SQLExecDirect hstmt sql-ptr $SQL_NTS))))
450 (defun %sql-cancel (hstmt)
455 (defun %sql-execute (hstmt)
460 (defun result-columns-count (hstmt)
461 (with-foreign-objects ((columns-nr-ptr :short))
462 (with-error-handling (:hstmt hstmt)
463 (SQLNumResultCols hstmt columns-nr-ptr)
464 (deref-pointer columns-nr-ptr :short))))
466 (defun result-rows-count (hstmt)
467 (with-foreign-objects ((row-count-ptr #.$ODBC-LONG-TYPE))
468 (with-error-handling (:hstmt hstmt)
469 (SQLRowCount hstmt row-count-ptr)
470 (deref-pointer row-count-ptr #.$ODBC-LONG-TYPE))))
472 ;; column counting is 1-based
473 (defun %describe-column (hstmt column-nr)
474 (let ((column-name-ptr (allocate-foreign-string 256)))
475 (with-foreign-objects ((column-name-length-ptr :short)
476 (column-sql-type-ptr :short)
477 (column-precision-ptr #.$ODBC-ULONG-TYPE)
478 (column-scale-ptr :short)
479 (column-nullable-p-ptr :short))
480 (with-error-handling (:hstmt hstmt)
481 (SQLDescribeCol hstmt column-nr column-name-ptr 256
482 column-name-length-ptr
486 column-nullable-p-ptr)
487 (let ((column-name (convert-from-foreign-string column-name-ptr)))
488 (free-foreign-object column-name-ptr)
491 (deref-pointer column-sql-type-ptr :short)
492 (deref-pointer column-precision-ptr #.$ODBC-ULONG-TYPE)
493 (deref-pointer column-scale-ptr :short)
494 (deref-pointer column-nullable-p-ptr :short)))))))
496 ;; this function isn't used, which is good because FreeTDS dosn't support it.
497 ;; parameter counting is 1-based
498 (defun %describe-parameter (hstmt parameter-nr)
499 (with-foreign-objects ((column-sql-type-ptr :short)
500 (column-precision-ptr #.$ODBC-ULONG-TYPE)
501 (column-scale-ptr :short)
502 (column-nullable-p-ptr :short))
505 (SQLDescribeParam hstmt parameter-nr
509 column-nullable-p-ptr)
511 (deref-pointer column-sql-type-ptr :short)
512 (deref-pointer column-precision-ptr #.$ODBC-ULONG-TYPE)
513 (deref-pointer column-scale-ptr :short)
514 (deref-pointer column-nullable-p-ptr :short)))))
516 (defun %column-attributes (hstmt column-nr descriptor-type)
517 (let ((descriptor-info-ptr (allocate-foreign-string 256)))
518 (with-foreign-objects ((descriptor-length-ptr :short)
519 (numeric-descriptor-ptr #.$ODBC-LONG-TYPE))
522 (SQLColAttributes hstmt column-nr descriptor-type descriptor-info-ptr
523 256 descriptor-length-ptr
524 numeric-descriptor-ptr)
525 (let ((desc (convert-from-foreign-string descriptor-info-ptr)))
526 (free-foreign-object descriptor-info-ptr)
529 (deref-pointer numeric-descriptor-ptr #.$ODBC-LONG-TYPE)))))))
531 (defun %prepare-describe-columns (hstmt table-qualifier table-owner
532 table-name column-name)
533 (with-cstrings ((table-qualifier-ptr table-qualifier)
534 (table-owner-ptr table-owner)
535 (table-name-ptr table-name)
536 (column-name-ptr column-name))
540 table-qualifier-ptr (length table-qualifier)
541 table-owner-ptr (length table-owner)
542 table-name-ptr (length table-name)
543 column-name-ptr (length column-name)))))
545 (defun %describe-columns (hdbc table-qualifier table-owner
546 table-name column-name)
547 (with-statement-handle (hstmt hdbc)
548 (%prepare-describe-columns hstmt table-qualifier table-owner
549 table-name column-name)
550 (fetch-all-rows hstmt)))
552 (defun %sql-data-sources (henv &key (direction :first))
553 (let ((name-ptr (allocate-foreign-string (1+ $SQL_MAX_DSN_LENGTH)))
554 (description-ptr (allocate-foreign-string 1024)))
555 (with-foreign-objects ((name-length-ptr :short)
556 (description-length-ptr :short))
557 (let ((res (with-error-handling
561 (:first $SQL_FETCH_FIRST)
562 (:next $SQL_FETCH_NEXT))
564 (1+ $SQL_MAX_DSN_LENGTH)
568 description-length-ptr))))
570 ((= res $SQL_NO_DATA_FOUND)
571 (let ((name (convert-from-foreign-string name-ptr))
572 (desc (convert-from-foreign-string description-ptr)))
573 (free-foreign-object name-ptr)
574 (free-foreign-object description-ptr)
579 (free-foreign-object name-ptr)
580 (free-foreign-object description-ptr)
585 (defun sql-to-c-type (sql-type)
587 ((#.$SQL_CHAR #.$SQL_VARCHAR #.$SQL_LONGVARCHAR
588 #.$SQL_NUMERIC #.$SQL_DECIMAL -8 -9 -10) $SQL_C_CHAR) ;; Added -10 for MSSQL ntext type
589 (#.$SQL_INTEGER $SQL_C_SLONG)
590 (#.$SQL_SMALLINT $SQL_C_SSHORT)
591 (#.$SQL_BIGINT $SQL_C_SBIGINT)
592 (#.$SQL_DOUBLE $SQL_C_DOUBLE)
593 (#.$SQL_FLOAT $SQL_C_DOUBLE)
594 (#.$SQL_REAL $SQL_C_FLOAT)
595 (#.$SQL_DATE $SQL_C_DATE)
596 (#.$SQL_TIME $SQL_C_TIME)
597 (#.$SQL_TIMESTAMP $SQL_C_TIMESTAMP)
598 (#.$SQL_TYPE_DATE $SQL_C_TYPE_DATE)
599 (#.$SQL_TYPE_TIME $SQL_C_TYPE_TIME)
600 (#.$SQL_TYPE_TIMESTAMP $SQL_C_TYPE_TIMESTAMP)
601 ((#.$SQL_BINARY #.$SQL_VARBINARY #.$SQL_LONGVARBINARY) $SQL_C_BINARY)
602 (#.$SQL_TINYINT $SQL_C_STINYINT)
603 (#.$SQL_BIT $SQL_C_BIT)))
605 (def-type byte-pointer-type (* :byte))
606 (def-type short-pointer-type (* :short))
607 (def-type int-pointer-type (* :int))
608 (def-type long-pointer-type (* #.$ODBC-LONG-TYPE))
609 (def-type big-pointer-type (* #.$ODBC-BIG-TYPE))
610 (def-type float-pointer-type (* :float))
611 (def-type double-pointer-type (* :double))
612 (def-type string-pointer-type (* :unsigned-char))
614 (defun get-cast-byte (ptr)
615 (locally (declare (type byte-pointer-type ptr))
616 (deref-pointer ptr :byte)))
618 (defun get-cast-short (ptr)
619 (locally (declare (type short-pointer-type ptr))
620 (deref-pointer ptr :short)))
622 (defun get-cast-int (ptr)
623 (locally (declare (type int-pointer-type ptr))
624 (deref-pointer ptr :int)))
626 (defun get-cast-long (ptr)
627 (locally (declare (type long-pointer-type ptr))
628 (deref-pointer ptr #.$ODBC-LONG-TYPE)))
630 (defun get-cast-big (ptr)
631 (locally (declare (type big-pointer-type ptr))
632 (deref-pointer ptr #.$ODBC-BIG-TYPE)))
634 (defun get-cast-single-float (ptr)
635 (locally (declare (type float-pointer-type ptr))
636 (deref-pointer ptr :float)))
638 (defun get-cast-double-float (ptr)
639 (locally (declare (type double-pointer-type ptr))
640 (deref-pointer ptr :double)))
642 (defun get-cast-foreign-string (ptr)
643 (locally (declare (type string-pointer-type ptr))
644 (convert-from-foreign-string ptr)))
646 (defun get-cast-binary (ptr len format)
647 "FORMAT is one of :unsigned-byte-vector, :bit-vector (:string, :hex-string)"
648 (with-cast-pointer (casted ptr :byte)
650 (:unsigned-byte-vector
651 (let ((vector (make-array len :element-type '(unsigned-byte 8))))
653 (setf (aref vector i)
654 (deref-array casted '(:array :byte) i)))
657 (let ((vector (make-array (ash len 3) :element-type 'bit)))
659 (let ((byte (deref-array casted '(:array :byte) i)))
661 (setf (bit vector (+ (ash i 3) j))
662 (logand (ash byte (- j 7)) 1)))))
666 (defun read-data (data-ptr c-type sql-type out-len-ptr result-type)
667 (declare (type long-ptr-type out-len-ptr))
668 (let* ((out-len (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE))
670 (cond ((= out-len $SQL_NULL_DATA)
674 ;; SQL extended datatypes
675 (#.$SQL_TINYINT (get-cast-byte data-ptr))
676 (#.$SQL_C_STINYINT (get-cast-byte data-ptr)) ;; ?
677 (#.$SQL_C_SSHORT (get-cast-short data-ptr)) ;; ?
678 (#.$SQL_SMALLINT (get-cast-short data-ptr)) ;; ??
679 (#.$SQL_INTEGER (get-cast-int data-ptr))
680 (#.$SQL_BIGINT (get-cast-big data-ptr))
682 (let ((*read-base* 10))
683 (read-from-string (get-cast-foreign-string data-ptr))))
684 (#.$SQL_BIT (get-cast-byte data-ptr))
687 ((#.$SQL_C_DATE #.$SQL_C_TYPE_DATE)
688 (funcall *time-conversion-function* (date-to-universal-time data-ptr)))
689 ((#.$SQL_C_TIME #.$SQL_C_TYPE_TIME)
690 (multiple-value-bind (universal-time frac) (time-to-universal-time data-ptr)
691 (funcall *time-conversion-function* universal-time frac)))
692 ((#.$SQL_C_TIMESTAMP #.$SQL_C_TYPE_TIMESTAMP)
693 (multiple-value-bind (universal-time frac) (timestamp-to-universal-time data-ptr)
694 (funcall *time-conversion-function* universal-time frac)))
696 (get-cast-int data-ptr))
698 (get-cast-single-float data-ptr))
700 (get-cast-double-float data-ptr))
702 (get-cast-long data-ptr))
704 (#.$SQL_C_BIT ; encountered only in Access
705 (get-cast-byte data-ptr))
707 (get-cast-binary data-ptr out-len *binary-format*))
708 ((#.$SQL_C_SSHORT #.$SQL_C_STINYINT) ; LMH short ints
709 (get-cast-short data-ptr)) ; LMH
712 (code-char (get-cast-short data-ptr)))
714 (get-cast-foreign-string data-ptr)))))))))
716 ;; FIXME: this could be better optimized for types which use READ-FROM-STRING above
718 (if (and (or (eq result-type t) (eq result-type :string))
720 (not (stringp value)))
721 (write-to-string value)
724 ;; which value is appropriate?
725 (defparameter +max-precision+ 4001)
727 (defvar *break-on-unknown-data-type* t)
729 ;; C. Stacy's idea to factor this out
730 ;; "Make it easy to add new datatypes by making new subroutine %ALLOCATE-BINDINGS,
731 ;; so that I don't have to remember to make changes in more than one place.
732 ;; Just keep it in synch with READ-DATA."
733 (defun %allocate-bindings (sql-type precision)
734 (let* ((c-type (sql-to-c-type sql-type))
735 (size (if (zerop precision)
736 +max-precision+ ;; if the precision cannot be determined
737 (min precision +max-precision+)))
738 (long-p (= size +max-precision+))
740 (case c-type ;; add more?
741 (#.$SQL_C_SLONG (uffi:allocate-foreign-object #.$ODBC-LONG-TYPE))
742 ((#.$SQL_C_DATE #.$SQL_C_TYPE_DATE) (allocate-foreign-object 'sql-c-date))
743 ((#.$SQL_C_TIME #.$SQL_C_TYPE_TIME) (allocate-foreign-object 'sql-c-time))
744 ((#.$SQL_C_TIMESTAMP #.$SQL_C_TYPE_TIMESTAMP) (allocate-foreign-object 'sql-c-timestamp))
745 (#.$SQL_C_FLOAT (uffi:allocate-foreign-object :float))
746 (#.$SQL_C_DOUBLE (uffi:allocate-foreign-object :double))
747 (#.$SQL_C_BIT (uffi:allocate-foreign-object :byte))
748 (#.$SQL_C_STINYINT (uffi:allocate-foreign-object :byte))
749 (#.$SQL_C_SSHORT (uffi:allocate-foreign-object :short))
750 (#.$SQL_C_SBIGINT (uffi:allocate-foreign-object #.$ODBC-BIG-TYPE))
751 (#.$SQL_C_CHAR (uffi:allocate-foreign-string (1+ size)))
752 (#.$SQL_C_BINARY (uffi:allocate-foreign-string (1+ (* 2 size))))
754 ;; Maybe should signal a restartable condition for this?
755 (when *break-on-unknown-data-type*
756 (break "SQL type is ~A, precision ~D, size ~D, C type is ~A"
757 sql-type precision size c-type))
758 (uffi:allocate-foreign-object :byte (1+ size)))))
759 (out-len-ptr (uffi:allocate-foreign-object #.$ODBC-LONG-TYPE)))
760 (values c-type data-ptr out-len-ptr size long-p)))
762 (defun fetch-all-rows (hstmt &key free-option flatp)
763 (let ((column-count (result-columns-count hstmt)))
764 (unless (zerop column-count)
765 (let ((names (make-array column-count))
766 (sql-types (make-array column-count :element-type 'fixnum))
767 (c-types (make-array column-count :element-type 'fixnum))
768 (precisions (make-array column-count :element-type 'fixnum))
769 (data-ptrs (make-array column-count :initial-element nil))
770 (out-len-ptrs (make-array column-count :initial-element nil))
771 (scales (make-array column-count :element-type 'fixnum))
772 (nullables-p (make-array column-count :element-type 'fixnum)))
776 (dotimes (col-nr column-count)
777 ;; get column information
778 (multiple-value-bind (name sql-type precision scale nullable-p)
779 (%describe-column hstmt (1+ col-nr))
780 ;; allocate space to bind result rows to
781 (multiple-value-bind (c-type data-ptr out-len-ptr)
782 (%allocate-bindings sql-type precision)
783 (%bind-column hstmt col-nr c-type data-ptr (1+ precision) out-len-ptr)
784 (setf (svref names col-nr) name
785 (aref sql-types col-nr) sql-type
786 (aref c-types col-nr) (sql-to-c-type sql-type)
787 (aref precisions col-nr) (if (zerop precision) 0 precision)
788 (aref scales col-nr) scale
789 (aref nullables-p col-nr) nullable-p
790 (aref data-ptrs col-nr) data-ptr
791 (aref out-len-ptrs col-nr) out-len-ptr))))
795 (when (> column-count 1)
796 (error 'clsql:sql-database-error
797 :message "If more than one column is to be fetched, flatp has to be nil."))
798 (loop until (= (%sql-fetch hstmt) $SQL_NO_DATA_FOUND)
800 (read-data (aref data-ptrs 0)
803 (aref out-len-ptrs 0)
806 (loop until (= (%sql-fetch hstmt) $SQL_NO_DATA_FOUND)
808 (loop for col-nr from 0 to (1- column-count)
810 (read-data (aref data-ptrs col-nr)
811 (aref c-types col-nr)
812 (aref sql-types col-nr)
813 (aref out-len-ptrs col-nr)
816 ;; dispose of memory etc
817 (when free-option (%free-statement hstmt free-option))
818 (dotimes (col-nr column-count)
819 (let ((data-ptr (aref data-ptrs col-nr))
820 (out-len-ptr (aref out-len-ptrs col-nr)))
821 (when data-ptr (free-foreign-object data-ptr)) ; we *did* allocate them
822 (when out-len-ptr (free-foreign-object out-len-ptr)))))))))
824 ;; to do: factor out common parts, put the sceleton (the obligatory macro part)
825 ;; of %do-fetch into sql package (has been done)
827 (defun %sql-prepare (hstmt sql)
828 (with-cstring (sql-ptr sql)
829 (with-error-handling (:hstmt hstmt)
830 (SQLPrepare hstmt sql-ptr $SQL_NTS))))
832 ;; depending on option, we return a long int or a string; string not implemented
833 (defun get-connection-option (hdbc option)
834 (with-foreign-object (param-ptr #.$ODBC-LONG-TYPE)
835 (with-error-handling (:hdbc hdbc)
836 (SQLGetConnectOption hdbc option param-ptr)
837 (deref-pointer param-ptr #.$ODBC-LONG-TYPE))))
839 (defun set-connection-option (hdbc option param)
840 (with-error-handling (:hdbc hdbc)
841 (SQLSetConnectOption hdbc option param)))
843 (defun disable-autocommit (hdbc)
844 (set-connection-option hdbc $SQL_AUTOCOMMIT $SQL_AUTOCOMMIT_OFF))
846 (defun enable-autocommit (hdbc)
847 (set-connection-option hdbc $SQL_AUTOCOMMIT $SQL_AUTOCOMMIT_ON))
849 (defun %sql-set-pos (hstmt row option lock)
852 (SQLSetPos hstmt row option lock)))
854 (defun %sql-extended-fetch (hstmt fetch-type row)
855 (with-foreign-objects ((row-count-ptr #.$ODBC-ULONG-TYPE)
856 (row-status-ptr :short))
857 (with-error-handling (:hstmt hstmt)
858 (SQLExtendedFetch hstmt fetch-type row row-count-ptr
860 (values (deref-pointer row-count-ptr #.$ODBC-ULONG-TYPE)
861 (deref-pointer row-status-ptr :short)))))
863 ; column-nr is zero-based
864 (defun %sql-get-data (hstmt column-nr c-type data-ptr precision out-len-ptr)
866 (:hstmt hstmt :print-info nil)
867 (SQLGetData hstmt (if (eq column-nr :bookmark) 0 (1+ column-nr))
868 c-type data-ptr precision out-len-ptr)))
870 (defun %sql-param-data (hstmt param-ptr)
871 (with-error-handling (:hstmt hstmt :print-info t) ;; nil
872 (SQLParamData hstmt param-ptr)))
874 (defun %sql-put-data (hstmt data-ptr size)
876 (:hstmt hstmt :print-info t) ;; nil
877 (SQLPutData hstmt data-ptr size)))
879 (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 (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE))
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)))
915 (loop do (if (= c-type #.$SQL_CHAR)
916 (setf offset (%cstring-into-vector ;string
919 (min out-len (1- +max-precision+))))
920 (error 'clsql:sql-database-error :message "wrong type. preliminary."))
922 (and (= res $SQL_SUCCESS_WITH_INFO)
923 (> out-len +max-precision+))
924 do (setf res (%sql-get-data hstmt column-nr c-type data-ptr
925 +max-precision+ out-len-ptr)
926 out-len (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE)))
927 (if (= sql-type $SQL_DECIMAL)
928 (let ((*read-base* 10))
929 (read-from-string str))
931 (setf (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE) #.$SQL_NO_TOTAL) ;; reset the out length for the next row
934 (def-type c-timestamp-ptr-type (* (:struct sql-c-timestamp)))
935 (def-type c-time-ptr-type (* (:struct sql-c-time)))
936 (def-type c-date-ptr-type (* (:struct sql-c-date)))
938 (defun timestamp-to-universal-time (ptr)
939 (declare (type c-timestamp-ptr-type ptr))
941 (encode-universal-time
942 (get-slot-value ptr 'sql-c-timestamp 'second)
943 (get-slot-value ptr 'sql-c-timestamp 'minute)
944 (get-slot-value ptr 'sql-c-timestamp 'hour)
945 (get-slot-value ptr 'sql-c-timestamp 'day)
946 (get-slot-value ptr 'sql-c-timestamp 'month)
947 (get-slot-value ptr 'sql-c-timestamp 'year))
948 (get-slot-value ptr 'sql-c-timestamp 'fraction)))
950 (defun universal-time-to-timestamp (time &optional (fraction 0))
951 (multiple-value-bind (sec min hour day month year)
952 (decode-universal-time time)
953 (let ((ptr (allocate-foreign-object 'sql-c-timestamp)))
954 (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
955 (get-slot-value ptr 'sql-c-timestamp 'minute) min
956 (get-slot-value ptr 'sql-c-timestamp 'hour) hour
957 (get-slot-value ptr 'sql-c-timestamp 'day) day
958 (get-slot-value ptr 'sql-c-timestamp 'month) month
959 (get-slot-value ptr 'sql-c-timestamp 'year) year
960 (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
963 (defun %put-timestamp (ptr time &optional (fraction 0))
964 (declare (type c-timestamp-ptr-type ptr))
965 (multiple-value-bind (sec min hour day month year)
966 (decode-universal-time time)
967 (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
968 (get-slot-value ptr 'sql-c-timestamp 'minute) min
969 (get-slot-value ptr 'sql-c-timestamp 'hour) hour
970 (get-slot-value ptr 'sql-c-timestamp 'day) day
971 (get-slot-value ptr 'sql-c-timestamp 'month) month
972 (get-slot-value ptr 'sql-c-timestamp 'year) year
973 (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
976 (defun date-to-universal-time (ptr)
977 (declare (type c-date-ptr-type ptr))
978 (encode-universal-time
980 (get-slot-value ptr 'sql-c-timestamp 'day)
981 (get-slot-value ptr 'sql-c-timestamp 'month)
982 (get-slot-value ptr 'sql-c-timestamp 'year)))
984 (defun time-to-universal-time (ptr)
985 (declare (type c-time-ptr-type ptr))
986 (encode-universal-time
987 (get-slot-value ptr 'sql-c-timestamp 'second)
988 (get-slot-value ptr 'sql-c-timestamp 'minute)
989 (get-slot-value ptr 'sql-c-timestamp 'hour)
995 (defun %set-attr-odbc-version (henv version)
996 (with-error-handling (:henv henv)
997 (SQLSetEnvAttr henv $SQL_ATTR_ODBC_VERSION
998 (make-pointer version :void) 0)))
1000 (defun %list-tables (hstmt)
1001 (with-error-handling (:hstmt hstmt)
1002 (SQLTables hstmt +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0)))
1004 (defun %table-statistics (table hstmt &key unique (ensure t))
1005 (with-cstrings ((table-cs table))
1006 (with-error-handling (:hstmt hstmt)
1012 (if unique $SQL_INDEX_UNIQUE $SQL_INDEX_ALL)
1013 (if ensure $SQL_ENSURE $SQL_QUICK)))))
1015 (defun %list-data-sources (henv)
1016 (let ((dsn (allocate-foreign-string (1+ $SQL_MAX_DSN_LENGTH)))
1017 (desc (allocate-foreign-string 256))
1020 (with-foreign-objects ((dsn-len :short)
1022 (let ((res (with-error-handling (:henv henv)
1023 (SQLDataSources henv $SQL_FETCH_FIRST dsn
1024 (1+ $SQL_MAX_DSN_LENGTH)
1025 dsn-len desc 256 desc-len))))
1026 (when (or (eql res $SQL_SUCCESS)
1027 (eql res $SQL_SUCCESS_WITH_INFO))
1028 (push (convert-from-foreign-string dsn) results))
1030 (do ((res (with-error-handling (:henv henv)
1031 (SQLDataSources henv $SQL_FETCH_NEXT dsn
1032 (1+ $SQL_MAX_DSN_LENGTH)
1033 dsn-len desc 256 desc-len))
1034 (with-error-handling (:henv henv)
1035 (SQLDataSources henv $SQL_FETCH_NEXT dsn
1036 (1+ $SQL_MAX_DSN_LENGTH)
1037 dsn-len desc 256 desc-len))))
1038 ((not (or (eql res $SQL_SUCCESS)
1039 (eql res $SQL_SUCCESS_WITH_INFO))))
1040 (push (convert-from-foreign-string dsn) results))))
1042 (free-foreign-object dsn)
1043 (free-foreign-object desc)))
1044 (nreverse results)))