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 (let ((time (clsql-sys:utime->time universal-time)))
30 (setf time (clsql-sys:time+
32 (clsql-sys:make-duration :usec (/ fraction 1000))))
33 (clsql-sys:format-time nil time :format :iso))
36 "Bound to a function that converts from a Lisp universal time fixnum (and a fractional
37 as possible second argument) to the desired representation of date/time/timestamp. By default, returns an iso-timestring.")
39 (defvar +null-ptr+ (make-null-pointer :byte))
40 (defparameter +null-handle-ptr+ (make-null-pointer :void))
41 (defvar *info-output* nil
42 "Stream to send SUCCESS_WITH_INFO messages.")
44 (defmacro %put-str (ptr string &optional max-length)
45 (let ((size (gensym)))
46 `(let ((,size (length ,string)))
47 (when (and ,max-length (> ,size ,max-length))
48 (error 'clsql:sql-database-data-error
50 (format nil "string \"~a\" of length ~d is longer than max-length: ~d"
51 ,string ,size ,max-length)))
52 (with-cast-pointer (char-ptr ,ptr :byte)
54 (setf (deref-array char-ptr '(:array :byte) i)
55 (char-code (char ,string i))))
56 (setf (deref-array char-ptr '(:array :byte) ,size) 0)))))
58 (defun %cstring-into-vector (ptr vector offset size-in-bytes)
59 (dotimes (i size-in-bytes)
60 (setf (schar vector offset)
61 (ensure-char-character
62 (deref-array ptr '(:array :unsigned-char) i)))
66 (defun handle-error (henv hdbc hstmt)
67 (let ((sql-state (allocate-foreign-string 256))
68 (error-message (allocate-foreign-string #.$SQL_MAX_MESSAGE_LENGTH)))
69 (with-foreign-objects ((error-code #.$ODBC-LONG-TYPE)
71 (SQLError henv hdbc hstmt sql-state
72 error-code error-message
73 #.$SQL_MAX_MESSAGE_LENGTH msg-length)
74 (let ((err (convert-from-foreign-string error-message))
75 (state (convert-from-foreign-string sql-state)))
76 (free-foreign-object error-message)
77 (free-foreign-object sql-state)
81 (deref-pointer msg-length :short)
82 (deref-pointer error-code #.$ODBC-LONG-TYPE))))))
84 (defun sql-state (henv hdbc hstmt)
85 (let ((sql-state (allocate-foreign-string 256))
86 (error-message (allocate-foreign-string #.$SQL_MAX_MESSAGE_LENGTH)))
87 (with-foreign-objects ((error-code #.$ODBC-LONG-TYPE)
89 (SQLError henv hdbc hstmt sql-state error-code
90 error-message #.$SQL_MAX_MESSAGE_LENGTH msg-length)
91 (let ((state (convert-from-foreign-string sql-state)))
92 (free-foreign-object error-message)
93 (free-foreign-object sql-state)
95 ;; test this: return a keyword for efficiency
96 ;;(%cstring-to-keyword state)
99 (defmacro with-error-handling ((&key henv hdbc hstmt (print-info t))
100 odbc-call &body body)
101 (let ((result-code (gensym "RC-")))
102 `(let ((,result-code ,odbc-call))
104 ;; Check for allegro v7 & v8 bug with ODBC calls returning
105 ;; 32-bit unsigned ints, not 16-bit signed ints
106 #+(and allegro mswindows)
107 (when (> ,result-code #xFFFF)
108 (warn (format nil "16-bit return bug: result-code #x~X for expression ~S"
109 ,result-code (quote ,odbc-call)))
110 (setq ,result-code (logand ,result-code #xFFFF))
111 (when (> ,result-code #x7FFF)
112 (setq ,result-code (- ,result-code #x10000))))
116 (progn ,result-code ,@body))
117 (#.$SQL_SUCCESS_WITH_INFO
119 (multiple-value-bind (error-message sql-state)
120 (handle-error (or ,henv +null-handle-ptr+)
121 (or ,hdbc +null-handle-ptr+)
122 (or ,hstmt +null-handle-ptr+))
124 (format *info-output* "[ODBC info ~A] ~A state: ~A"
125 ,result-code error-message
127 (progn ,result-code ,@body))
128 (#.$SQL_INVALID_HANDLE
130 'clsql-sys:sql-database-error
131 :message "ODBC: Invalid handle"))
132 (#.$SQL_STILL_EXECUTING
134 'clsql-sys:sql-temporary-error
135 :message "ODBC: Still executing"))
137 (multiple-value-bind (error-message sql-state)
138 (handle-error (or ,henv +null-handle-ptr+)
139 (or ,hdbc +null-handle-ptr+)
140 (or ,hstmt +null-handle-ptr+))
142 'clsql-sys:sql-database-error
143 :message error-message
144 :secondary-error-id sql-state)))
145 (#.$SQL_NO_DATA_FOUND
146 (progn ,result-code ,@body))
147 ;; work-around for Allegro 7.0beta AMD64 which returns negative numbers
149 (multiple-value-bind (error-message sql-state)
150 (handle-error (or ,henv +null-handle-ptr+)
151 (or ,hdbc +null-handle-ptr+)
152 (or ,hstmt +null-handle-ptr+))
154 'clsql-sys:sql-database-error
155 :message error-message
156 :secondary-error-id sql-state))
158 (progn ,result-code ,@body))))))
160 (defun %new-environment-handle ()
162 (with-foreign-object (phenv 'sql-handle)
165 (SQLAllocHandle $SQL_HANDLE_ENV +null-handle-ptr+ phenv)
166 (deref-pointer phenv 'sql-handle)))))
167 (%set-attr-odbc-version henv $SQL_OV_ODBC3)
171 (defun %sql-free-environment (henv)
176 (defun %new-db-connection-handle (henv)
177 (with-foreign-object (phdbc 'sql-handle)
178 (setf (deref-pointer phdbc 'sql-handle) +null-handle-ptr+)
181 (SQLAllocHandle $SQL_HANDLE_DBC henv phdbc)
182 (deref-pointer phdbc 'sql-handle))))
184 (defun %free-statement (hstmt option)
192 (:unbind $SQL_UNBIND)
193 (:reset $SQL_RESET_PARAMS)))))
195 (defmacro with-statement-handle ((hstmt hdbc) &body body)
196 `(let ((,hstmt (%new-statement-handle ,hdbc)))
199 (%free-statement ,hstmt :drop))))
201 ;; functional interface
203 (defun %sql-connect (hdbc server uid pwd)
204 (with-cstrings ((server-ptr server)
209 (SQLConnect hdbc server-ptr $SQL_NTS uid-ptr
210 $SQL_NTS pwd-ptr $SQL_NTS))))
212 (defun %sql-driver-connect (hdbc connection-string completion window-handle)
213 (with-cstring (connection-ptr connection-string)
214 (let ((completed-connection-string (allocate-foreign-string $SQL_MAX_CONN_OUT)))
216 (with-foreign-object (completed-connection-length :short)
219 (SQLDriverConnect hdbc
221 connection-ptr $SQL_NTS
222 completed-connection-string $SQL_MAX_CONN_OUT
223 completed-connection-length
225 (free-foreign-object completed-connection-string)))))
227 (defun %disconnect (hdbc)
230 (SQLDisconnect hdbc)))
232 (defun %commit (henv hdbc)
234 (:henv henv :hdbc hdbc)
236 henv hdbc $SQL_COMMIT)))
238 (defun %rollback (henv hdbc)
240 (:henv henv :hdbc hdbc)
242 henv hdbc $SQL_ROLLBACK)))
244 ; col-nr is zero-based in Lisp
245 ; col-nr = :bookmark retrieves a bookmark.
246 (defun %bind-column (hstmt column-nr c-type data-ptr precision out-len-ptr)
250 (if (eq column-nr :bookmark) 0 (1+ column-nr))
251 c-type data-ptr precision out-len-ptr)))
253 ; parameter-nr is zero-based in Lisp
254 (defun %sql-bind-parameter (hstmt parameter-nr parameter-type c-type
255 sql-type precision scale data-ptr
256 max-value out-len-ptr)
259 (SQLBindParameter hstmt (1+ parameter-nr)
260 parameter-type ;$SQL_PARAM_INPUT
262 sql-type ;$SQL_VARCHAR
263 precision ;(1- (length str))
267 out-len-ptr ;#.+null-ptr+
270 (defun %sql-fetch (hstmt)
275 (defun %new-statement-handle (hdbc)
276 (let ((statement-handle
277 (with-foreign-object (phstmt 'sql-handle)
280 (SQLAllocHandle $SQL_HANDLE_STMT hdbc phstmt)
281 (deref-pointer phstmt 'sql-handle)))))
282 (if (uffi:null-pointer-p statement-handle)
283 (error 'clsql:sql-database-error :message "Received null statement handle.")
286 (defun %sql-get-info (hdbc info-type)
288 ;; those return string
289 ((#.$SQL_ACCESSIBLE_PROCEDURES
290 #.$SQL_ACCESSIBLE_TABLES
292 #.$SQL_DATA_SOURCE_NAME
293 #.$SQL_DATA_SOURCE_READ_ONLY
297 #.$SQL_DRIVER_ODBC_VER
299 #.$SQL_EXPRESSIONS_IN_ORDERBY
300 #.$SQL_IDENTIFIER_QUOTE_CHAR
302 #.$SQL_LIKE_ESCAPE_CLAUSE
303 #.$SQL_MAX_ROW_SIZE_INCLUDES_LONG
304 #.$SQL_MULT_RESULT_SETS
305 #.$SQL_MULTIPLE_ACTIVE_TXN
306 #.$SQL_NEED_LONG_DATA_LEN
307 #.$SQL_ODBC_SQL_OPT_IEF
309 #.$SQL_ORDER_BY_COLUMNS_IN_SELECT
312 #.$SQL_PROCEDURE_TERM
314 #.$SQL_QUALIFIER_NAME_SEPARATOR
315 #.$SQL_QUALIFIER_TERM
317 #.$SQL_SEARCH_PATTERN_ESCAPE
319 #.$SQL_SPECIAL_CHARACTERS
322 (let ((info-ptr (allocate-foreign-string 1024)))
323 (with-foreign-object (info-length-ptr :short)
326 (SQLGetInfo hdbc info-type info-ptr 1023 info-length-ptr)
327 (let ((info (convert-from-foreign-string info-ptr)))
328 (free-foreign-object info-ptr)
330 ;; those returning a word
331 ((#.$SQL_ACTIVE_CONNECTIONS
332 #.$SQL_ACTIVE_STATEMENTS
333 #.$SQL_CONCAT_NULL_BEHAVIOR
334 #.$SQL_CORRELATION_NAME
335 #.$SQL_CURSOR_COMMIT_BEHAVIOR
336 #.$SQL_CURSOR_ROLLBACK_BEHAVIOR
337 #.$SQL_MAX_COLUMN_NAME_LEN
338 #.$SQL_MAX_COLUMNS_IN_GROUP_BY
339 #.$SQL_MAX_COLUMNS_IN_INDEX
340 #.$SQL_MAX_COLUMNS_IN_ORDER_BY
341 #.$SQL_MAX_COLUMNS_IN_SELECT
342 #.$SQL_MAX_COLUMNS_IN_TABLE
343 #.$SQL_MAX_CURSOR_NAME_LEN
344 #.$SQL_MAX_OWNER_NAME_LEN
345 #.$SQL_MAX_PROCEDURE_NAME_LEN
346 #.$SQL_MAX_QUALIFIER_NAME_LEN
347 #.$SQL_MAX_TABLE_NAME_LEN
348 #.$SQL_MAX_TABLES_IN_SELECT
349 #.$SQL_MAX_USER_NAME_LEN
350 #.$SQL_NON_NULLABLE_COLUMNS
351 #.$SQL_NULL_COLLATION
352 #.$SQL_ODBC_API_CONFORMANCE
353 #.$SQL_ODBC_SAG_CLI_CONFORMANCE
354 #.$SQL_ODBC_SQL_CONFORMANCE
355 #.$SQL_QUALIFIER_LOCATION
356 #.$SQL_QUOTED_IDENTIFIER_CASE
358 (with-foreign-objects ((info-ptr :short)
359 (info-length-ptr :short))
367 (deref-pointer info-ptr :short)))
369 ;; those returning a long bitmask
371 #.$SQL_BOOKMARK_PERSISTENCE
372 #.$SQL_CONVERT_BIGINT
373 #.$SQL_CONVERT_BINARY
377 #.$SQL_CONVERT_DECIMAL
378 #.$SQL_CONVERT_DOUBLE
380 #.$SQL_CONVERT_INTEGER
381 #.$SQL_CONVERT_LONGVARCHAR
382 #.$SQL_CONVERT_NUMERIC
384 #.$SQL_CONVERT_SMALLINT
386 #.$SQL_CONVERT_TIMESTAMP
387 #.$SQL_CONVERT_TINYINT
388 #.$SQL_CONVERT_VARBINARY
389 #.$SQL_CONVERT_VARCHAR
390 #.$SQL_CONVERT_LONGVARBINARY
391 #.$SQL_CONVERT_FUNCTIONS
392 #.$SQL_FETCH_DIRECTION
394 #.$SQL_GETDATA_EXTENSIONS
396 #.$SQL_MAX_INDEX_SIZE
398 #.$SQL_MAX_STATEMENT_LEN
399 #.$SQL_NUMERIC_FUNCTIONS
401 #.$SQL_POS_OPERATIONS
402 #.$SQL_POSITIONED_STATEMENTS
403 #.$SQL_QUALIFIER_USAGE
404 #.$SQL_SCROLL_CONCURRENCY
405 #.$SQL_SCROLL_OPTIONS
406 #.$SQL_STATIC_SENSITIVITY
407 #.$SQL_STRING_FUNCTIONS
409 #.$SQL_SYSTEM_FUNCTIONS
410 #.$SQL_TIMEDATE_ADD_INTERVALS
411 #.$SQL_TIMEDATE_DIFF_INTERVALS
412 #.$SQL_TIMEDATE_FUNCTIONS
413 #.$SQL_TXN_ISOLATION_OPTION
415 (with-foreign-objects ((info-ptr #.$ODBC-LONG-TYPE)
416 (info-length-ptr :short))
424 (deref-pointer info-ptr #.$ODBC-LONG-TYPE)))
426 ;; those returning a long integer
427 ((#.$SQL_DEFAULT_TXN_ISOLATION
433 #.$SQL_IDENTIFIER_CASE
434 #.$SQL_MAX_BINARY_LITERAL_LEN
435 #.$SQL_MAX_CHAR_LITERAL_LEN
436 #.$SQL_ACTIVE_ENVIRONMENTS
438 (with-foreign-objects ((info-ptr #.$ODBC-LONG-TYPE)
439 (info-length-ptr :short))
442 (SQLGetInfo hdbc info-type info-ptr 255 info-length-ptr)
443 (deref-pointer info-ptr #.$ODBC-LONG-TYPE))))))
445 (defun %sql-exec-direct (sql hstmt henv hdbc)
446 (with-cstring (sql-ptr sql)
448 (:hstmt hstmt :henv henv :hdbc hdbc)
449 (SQLExecDirect hstmt sql-ptr $SQL_NTS))))
451 (defun %sql-cancel (hstmt)
456 (defun %sql-execute (hstmt)
461 (defun result-columns-count (hstmt)
462 (with-foreign-objects ((columns-nr-ptr :short))
463 (with-error-handling (:hstmt hstmt)
464 (SQLNumResultCols hstmt columns-nr-ptr)
465 (deref-pointer columns-nr-ptr :short))))
467 (defun result-rows-count (hstmt)
468 (with-foreign-objects ((row-count-ptr #.$ODBC-LONG-TYPE))
469 (with-error-handling (:hstmt hstmt)
470 (SQLRowCount hstmt row-count-ptr)
471 (deref-pointer row-count-ptr #.$ODBC-LONG-TYPE))))
473 ;; column counting is 1-based
474 (defun %describe-column (hstmt column-nr)
475 (let ((column-name-ptr (allocate-foreign-string 256)))
476 (with-foreign-objects ((column-name-length-ptr :short)
477 (column-sql-type-ptr :short)
478 (column-precision-ptr #.$ODBC-ULONG-TYPE)
479 (column-scale-ptr :short)
480 (column-nullable-p-ptr :short))
481 (with-error-handling (:hstmt hstmt)
482 (SQLDescribeCol hstmt column-nr column-name-ptr 256
483 column-name-length-ptr
487 column-nullable-p-ptr)
488 (let ((column-name (convert-from-foreign-string column-name-ptr)))
489 (free-foreign-object column-name-ptr)
492 (deref-pointer column-sql-type-ptr :short)
493 (deref-pointer column-precision-ptr #.$ODBC-ULONG-TYPE)
494 (deref-pointer column-scale-ptr :short)
495 (deref-pointer column-nullable-p-ptr :short)))))))
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 #.$SQL_BIGINT -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_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 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-single-float (ptr)
629 (locally (declare (type float-pointer-type ptr))
630 (deref-pointer ptr :float)))
632 (defun get-cast-double-float (ptr)
633 (locally (declare (type double-pointer-type ptr))
634 (deref-pointer ptr :double)))
636 (defun get-cast-foreign-string (ptr)
637 (locally (declare (type string-pointer-type ptr))
638 (convert-from-foreign-string ptr)))
640 (defun get-cast-binary (ptr len format)
641 "FORMAT is one of :unsigned-byte-vector, :bit-vector (:string, :hex-string)"
642 (with-cast-pointer (casted ptr :byte)
644 (:unsigned-byte-vector
645 (let ((vector (make-array len :element-type '(unsigned-byte 8))))
647 (setf (aref vector i)
648 (deref-array casted '(:array :byte) i)))
651 (let ((vector (make-array (ash len 3) :element-type 'bit)))
653 (let ((byte (deref-array casted '(:array :byte) i)))
655 (setf (bit vector (+ (ash i 3) j))
656 (logand (ash byte (- j 7)) 1)))))
660 (defun read-data (data-ptr c-type sql-type out-len-ptr result-type)
661 (declare (type long-ptr-type out-len-ptr))
662 (let* ((out-len (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE))
664 (cond ((= out-len $SQL_NULL_DATA)
668 ;; SQL extended datatypes
669 (#.$SQL_TINYINT (get-cast-byte data-ptr))
670 (#.$SQL_C_STINYINT (get-cast-byte data-ptr)) ;; ?
671 (#.$SQL_C_SSHORT (get-cast-short data-ptr)) ;; ?
672 (#.$SQL_SMALLINT (get-cast-short data-ptr)) ;; ??
673 (#.$SQL_INTEGER (get-cast-int data-ptr))
674 (#.$SQL_BIGINT (read-from-string
675 (get-cast-foreign-string data-ptr)))
677 (let ((*read-base* 10))
678 (read-from-string (get-cast-foreign-string data-ptr))))
679 (#.$SQL_BIT (get-cast-byte data-ptr))
682 ((#.$SQL_C_DATE #.$SQL_C_TYPE_DATE)
683 (funcall *time-conversion-function* (date-to-universal-time data-ptr)))
684 ((#.$SQL_C_TIME #.$SQL_C_TYPE_TIME)
685 (multiple-value-bind (universal-time frac) (time-to-universal-time data-ptr)
686 (funcall *time-conversion-function* universal-time frac)))
687 ((#.$SQL_C_TIMESTAMP #.$SQL_C_TYPE_TIMESTAMP)
688 (multiple-value-bind (universal-time frac) (timestamp-to-universal-time data-ptr)
689 (funcall *time-conversion-function* universal-time frac)))
691 (get-cast-int data-ptr))
693 (get-cast-single-float data-ptr))
695 (get-cast-double-float data-ptr))
697 (get-cast-long data-ptr))
699 (#.$SQL_C_BIT ; encountered only in Access
700 (get-cast-byte data-ptr))
702 (get-cast-binary data-ptr out-len *binary-format*))
703 ((#.$SQL_C_SSHORT #.$SQL_C_STINYINT) ; LMH short ints
704 (get-cast-short data-ptr)) ; LMH
707 (code-char (get-cast-short data-ptr)))
709 (get-cast-foreign-string data-ptr)))))))))
711 ;; FIXME: this could be better optimized for types which use READ-FROM-STRING above
713 (if (and (or (eq result-type t) (eq result-type :string))
715 (not (stringp value)))
716 (write-to-string value)
719 ;; which value is appropriate?
720 (defparameter +max-precision+ 4001)
722 (defvar *break-on-unknown-data-type* t)
724 ;; C. Stacy's idea to factor this out
725 ;; "Make it easy to add new datatypes by making new subroutine %ALLOCATE-BINDINGS,
726 ;; so that I don't have to remember to make changes in more than one place.
727 ;; Just keep it in synch with READ-DATA."
728 (defun %allocate-bindings (sql-type precision)
729 (let* ((c-type (sql-to-c-type sql-type))
730 (size (if (zerop precision)
731 +max-precision+ ;; if the precision cannot be determined
732 (min precision +max-precision+)))
733 (long-p (= size +max-precision+))
735 (case c-type ;; add more?
736 (#.$SQL_C_SLONG (uffi:allocate-foreign-object #.$ODBC-LONG-TYPE))
737 ((#.$SQL_C_DATE #.$SQL_C_TYPE_DATE) (allocate-foreign-object 'sql-c-date))
738 ((#.$SQL_C_TIME #.$SQL_C_TYPE_TIME) (allocate-foreign-object 'sql-c-time))
739 ((#.$SQL_C_TIMESTAMP #.$SQL_C_TYPE_TIMESTAMP) (allocate-foreign-object 'sql-c-timestamp))
740 (#.$SQL_C_FLOAT (uffi:allocate-foreign-object :float))
741 (#.$SQL_C_DOUBLE (uffi:allocate-foreign-object :double))
742 (#.$SQL_C_BIT (uffi:allocate-foreign-object :byte))
743 (#.$SQL_C_STINYINT (uffi:allocate-foreign-object :byte))
744 (#.$SQL_C_SSHORT (uffi:allocate-foreign-object :short))
745 (#.$SQL_C_CHAR (uffi:allocate-foreign-string (1+ size)))
746 (#.$SQL_C_BINARY (uffi:allocate-foreign-string (1+ (* 2 size))))
748 ;; Maybe should signal a restartable condition for this?
749 (when *break-on-unknown-data-type*
750 (break "SQL type is ~A, precision ~D, size ~D, C type is ~A"
751 sql-type precision size c-type))
752 (uffi:allocate-foreign-object :byte (1+ size)))))
753 (out-len-ptr (uffi:allocate-foreign-object #.$ODBC-LONG-TYPE)))
754 (values c-type data-ptr out-len-ptr size long-p)))
756 (defun fetch-all-rows (hstmt &key free-option flatp)
757 (let ((column-count (result-columns-count hstmt)))
758 (unless (zerop column-count)
759 (let ((names (make-array column-count))
760 (sql-types (make-array column-count :element-type 'fixnum))
761 (c-types (make-array column-count :element-type 'fixnum))
762 (precisions (make-array column-count :element-type 'fixnum))
763 (data-ptrs (make-array column-count :initial-element nil))
764 (out-len-ptrs (make-array column-count :initial-element nil))
765 (scales (make-array column-count :element-type 'fixnum))
766 (nullables-p (make-array column-count :element-type 'fixnum)))
770 (dotimes (col-nr column-count)
771 ;; get column information
772 (multiple-value-bind (name sql-type precision scale nullable-p)
773 (%describe-column hstmt (1+ col-nr))
774 ;; allocate space to bind result rows to
775 (multiple-value-bind (c-type data-ptr out-len-ptr)
776 (%allocate-bindings sql-type precision)
777 (%bind-column hstmt col-nr c-type data-ptr (1+ precision) out-len-ptr)
778 (setf (svref names col-nr) name
779 (aref sql-types col-nr) sql-type
780 (aref c-types col-nr) (sql-to-c-type sql-type)
781 (aref precisions col-nr) (if (zerop precision) 0 precision)
782 (aref scales col-nr) scale
783 (aref nullables-p col-nr) nullable-p
784 (aref data-ptrs col-nr) data-ptr
785 (aref out-len-ptrs col-nr) out-len-ptr))))
789 (when (> column-count 1)
790 (error 'clsql:sql-database-error
791 :message "If more than one column is to be fetched, flatp has to be nil."))
792 (loop until (= (%sql-fetch hstmt) $SQL_NO_DATA_FOUND)
794 (read-data (aref data-ptrs 0)
797 (aref out-len-ptrs 0)
800 (loop until (= (%sql-fetch hstmt) $SQL_NO_DATA_FOUND)
802 (loop for col-nr from 0 to (1- column-count)
804 (read-data (aref data-ptrs col-nr)
805 (aref c-types col-nr)
806 (aref sql-types col-nr)
807 (aref out-len-ptrs col-nr)
810 ;; dispose of memory etc
811 (when free-option (%free-statement hstmt free-option))
812 (dotimes (col-nr column-count)
813 (let ((data-ptr (aref data-ptrs col-nr))
814 (out-len-ptr (aref out-len-ptrs col-nr)))
815 (when data-ptr (free-foreign-object data-ptr)) ; we *did* allocate them
816 (when out-len-ptr (free-foreign-object out-len-ptr)))))))))
818 ;; to do: factor out common parts, put the sceleton (the obligatory macro part)
819 ;; of %do-fetch into sql package (has been done)
821 (defun %sql-prepare (hstmt sql)
822 (with-cstring (sql-ptr sql)
823 (with-error-handling (:hstmt hstmt)
824 (SQLPrepare hstmt sql-ptr $SQL_NTS))))
826 ;; depending on option, we return a long int or a string; string not implemented
827 (defun get-connection-option (hdbc option)
828 (with-foreign-object (param-ptr #.$ODBC-LONG-TYPE)
829 (with-error-handling (:hdbc hdbc)
830 (SQLGetConnectOption hdbc option param-ptr)
831 (deref-pointer param-ptr #.$ODBC-LONG-TYPE))))
833 (defun set-connection-option (hdbc option param)
834 (with-error-handling (:hdbc hdbc)
835 (SQLSetConnectOption hdbc option param)))
837 (defun disable-autocommit (hdbc)
838 (set-connection-option hdbc $SQL_AUTOCOMMIT $SQL_AUTOCOMMIT_OFF))
840 (defun enable-autocommit (hdbc)
841 (set-connection-option hdbc $SQL_AUTOCOMMIT $SQL_AUTOCOMMIT_ON))
843 (defun %sql-set-pos (hstmt row option lock)
846 (SQLSetPos hstmt row option lock)))
848 (defun %sql-extended-fetch (hstmt fetch-type row)
849 (with-foreign-objects ((row-count-ptr #.$ODBC-ULONG-TYPE)
850 (row-status-ptr :short))
851 (with-error-handling (:hstmt hstmt)
852 (SQLExtendedFetch hstmt fetch-type row row-count-ptr
854 (values (deref-pointer row-count-ptr #.$ODBC-ULONG-TYPE)
855 (deref-pointer row-status-ptr :short)))))
857 ; column-nr is zero-based
858 (defun %sql-get-data (hstmt column-nr c-type data-ptr precision out-len-ptr)
860 (:hstmt hstmt :print-info nil)
861 (SQLGetData hstmt (if (eq column-nr :bookmark) 0 (1+ column-nr))
862 c-type data-ptr precision out-len-ptr)))
864 (defun %sql-param-data (hstmt param-ptr)
865 (with-error-handling (:hstmt hstmt :print-info t) ;; nil
866 (SQLParamData hstmt param-ptr)))
868 (defun %sql-put-data (hstmt data-ptr size)
870 (:hstmt hstmt :print-info t) ;; nil
871 (SQLPutData hstmt data-ptr size)))
873 (defconstant $sql-data-truncated (intern "01004" :keyword))
875 (defun read-data-in-chunks (hstmt column-nr data-ptr c-type sql-type
876 out-len-ptr result-type)
877 (declare (type long-ptr-type out-len-ptr)
878 (ignore result-type))
879 (let* ((res (%sql-get-data hstmt column-nr c-type data-ptr
880 +max-precision+ out-len-ptr))
881 (out-len (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE))
883 (result (case out-len
885 (return-from read-data-in-chunks *null*))
886 (#.$SQL_NO_TOTAL ;; don't know how long it is going to be
887 (let ((str (make-array 0 :element-type 'character :adjustable t)))
888 (loop do (if (= c-type #.$SQL_CHAR)
889 (let ((data-length (foreign-string-length data-ptr)))
890 (adjust-array str (+ offset data-length)
891 :initial-element #\?)
892 (setf offset (%cstring-into-vector
896 (error 'clsql:sql-database-error :message "wrong type. preliminary."))
897 while (and (= res $SQL_SUCCESS_WITH_INFO)
898 (equal (sql-state +null-handle-ptr+ +null-handle-ptr+ hstmt)
900 do (setf res (%sql-get-data hstmt column-nr c-type data-ptr
901 +max-precision+ out-len-ptr)))
902 (setf str (coerce str 'string))
903 (if (= sql-type $SQL_DECIMAL)
904 (let ((*read-base* 10))
905 (read-from-string str))
908 (let ((str (make-string out-len)))
909 (loop do (if (= c-type #.$SQL_CHAR)
910 (setf offset (%cstring-into-vector ;string
913 (min out-len (1- +max-precision+))))
914 (error 'clsql:sql-database-error :message "wrong type. preliminary."))
916 (and (= res $SQL_SUCCESS_WITH_INFO)
917 #+ingore(eq (sql-state +null-handle-ptr+ +null-handle-ptr+ hstmt)
919 (equal (sql-state +null-handle-ptr+ +null-handle-ptr+ hstmt)
921 do (setf res (%sql-get-data hstmt column-nr c-type data-ptr
922 +max-precision+ out-len-ptr)
923 out-len (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE)))
924 (if (= sql-type $SQL_DECIMAL)
925 (let ((*read-base* 10))
926 (read-from-string str))
928 (setf (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE) #.$SQL_NO_TOTAL) ;; reset the out length for the next row
931 (def-type c-timestamp-ptr-type (* (:struct sql-c-timestamp)))
932 (def-type c-time-ptr-type (* (:struct sql-c-time)))
933 (def-type c-date-ptr-type (* (:struct sql-c-date)))
935 (defun timestamp-to-universal-time (ptr)
936 (declare (type c-timestamp-ptr-type ptr))
938 (encode-universal-time
939 (get-slot-value ptr 'sql-c-timestamp 'second)
940 (get-slot-value ptr 'sql-c-timestamp 'minute)
941 (get-slot-value ptr 'sql-c-timestamp 'hour)
942 (get-slot-value ptr 'sql-c-timestamp 'day)
943 (get-slot-value ptr 'sql-c-timestamp 'month)
944 (get-slot-value ptr 'sql-c-timestamp 'year))
945 (get-slot-value ptr 'sql-c-timestamp 'fraction)))
947 (defun universal-time-to-timestamp (time &optional (fraction 0))
948 (multiple-value-bind (sec min hour day month year)
949 (decode-universal-time time)
950 (let ((ptr (allocate-foreign-object 'sql-c-timestamp)))
951 (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
952 (get-slot-value ptr 'sql-c-timestamp 'minute) min
953 (get-slot-value ptr 'sql-c-timestamp 'hour) hour
954 (get-slot-value ptr 'sql-c-timestamp 'day) day
955 (get-slot-value ptr 'sql-c-timestamp 'month) month
956 (get-slot-value ptr 'sql-c-timestamp 'year) year
957 (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
960 (defun %put-timestamp (ptr time &optional (fraction 0))
961 (declare (type c-timestamp-ptr-type ptr))
962 (multiple-value-bind (sec min hour day month year)
963 (decode-universal-time time)
964 (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
965 (get-slot-value ptr 'sql-c-timestamp 'minute) min
966 (get-slot-value ptr 'sql-c-timestamp 'hour) hour
967 (get-slot-value ptr 'sql-c-timestamp 'day) day
968 (get-slot-value ptr 'sql-c-timestamp 'month) month
969 (get-slot-value ptr 'sql-c-timestamp 'year) year
970 (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
973 (defun date-to-universal-time (ptr)
974 (declare (type c-date-ptr-type ptr))
975 (encode-universal-time
977 (get-slot-value ptr 'sql-c-timestamp 'day)
978 (get-slot-value ptr 'sql-c-timestamp 'month)
979 (get-slot-value ptr 'sql-c-timestamp 'year)))
981 (defun time-to-universal-time (ptr)
982 (declare (type c-time-ptr-type ptr))
983 (encode-universal-time
984 (get-slot-value ptr 'sql-c-timestamp 'second)
985 (get-slot-value ptr 'sql-c-timestamp 'minute)
986 (get-slot-value ptr 'sql-c-timestamp 'hour)
992 (defun %set-attr-odbc-version (henv version)
993 (with-error-handling (:henv henv)
994 (SQLSetEnvAttr henv $SQL_ATTR_ODBC_VERSION
995 (make-pointer version :void) 0)))
997 (defun %list-tables (hstmt)
998 (with-error-handling (:hstmt hstmt)
999 (SQLTables hstmt +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0)))
1001 (defun %table-statistics (table hstmt &key unique (ensure t))
1002 (with-cstrings ((table-cs table))
1003 (with-error-handling (:hstmt hstmt)
1009 (if unique $SQL_INDEX_UNIQUE $SQL_INDEX_ALL)
1010 (if ensure $SQL_ENSURE $SQL_QUICK)))))
1012 (defun %list-data-sources (henv)
1013 (let ((dsn (allocate-foreign-string (1+ $SQL_MAX_DSN_LENGTH)))
1014 (desc (allocate-foreign-string 256))
1017 (with-foreign-objects ((dsn-len :short)
1019 (let ((res (with-error-handling (:henv henv)
1020 (SQLDataSources henv $SQL_FETCH_FIRST dsn
1021 (1+ $SQL_MAX_DSN_LENGTH)
1022 dsn-len desc 256 desc-len))))
1023 (when (or (eql res $SQL_SUCCESS)
1024 (eql res $SQL_SUCCESS_WITH_INFO))
1025 (push (convert-from-foreign-string dsn) results))
1027 (do ((res (with-error-handling (:henv henv)
1028 (SQLDataSources henv $SQL_FETCH_NEXT dsn
1029 (1+ $SQL_MAX_DSN_LENGTH)
1030 dsn-len desc 256 desc-len))
1031 (with-error-handling (:henv henv)
1032 (SQLDataSources henv $SQL_FETCH_NEXT dsn
1033 (1+ $SQL_MAX_DSN_LENGTH)
1034 dsn-len desc 256 desc-len))))
1035 ((not (or (eql res $SQL_SUCCESS)
1036 (eql res $SQL_SUCCESS_WITH_INFO))))
1037 (push (convert-from-foreign-string dsn) results))))
1039 (free-foreign-object dsn)
1040 (free-foreign-object desc)))
1041 (nreverse results)))