1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: odbc -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
5 ;;;; Name: odbc-api.lisp
6 ;;;; Purpose: Low-level ODBC API using UFFI
7 ;;;; Authors: Kevin M. Rosenberg and Paul Meurer
9 ;;;; This file, part of CLSQL, is Copyright (c) 2004 by Kevin M. Rosenberg
10 ;;;; and Copyright (C) Paul Meurer 1999 - 2001. All rights reserved.
12 ;;;; CLSQL users are granted the rights to distribute and use this software
13 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
14 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
15 ;;;; *************************************************************************
20 "Lisp representation of SQL Null value, default = nil.
21 May be locally bound to something else if a certain type is necessary.")
24 (defvar *binary-format* :unsigned-byte-vector)
25 (defvar *time-conversion-function*
26 (lambda (universal-time &optional fraction)
27 (let ((time (clsql-sys:utime->time universal-time)))
28 (setf time (clsql-sys:time+
30 (clsql-sys:make-duration :usec (/ fraction 1000))))
31 (clsql-sys:format-time nil time :format :iso))
34 "Bound to a function that converts from a Lisp universal time fixnum (and a fractional
35 as possible second argument) to the desired representation of date/time/timestamp. By default, returns an iso-timestring.")
37 (defvar +null-ptr+ (make-null-pointer :byte))
38 (defparameter +null-handle-ptr+ (make-null-pointer :void))
39 (defvar *info-output* nil
40 "Stream to send SUCCESS_WITH_INFO messages.")
42 (defmacro %put-str (ptr string &optional max-length)
43 (let ((size (gensym)))
44 `(let ((,size (length ,string)))
45 (when (and ,max-length (> ,size ,max-length))
46 (error 'clsql:sql-database-data-error
48 (format nil "string \"~a\" of length ~d is longer than max-length: ~d"
49 ,string ,size ,max-length)))
50 (with-cast-pointer (char-ptr ,ptr :byte)
52 (setf (deref-array char-ptr '(:array :byte) i)
53 (char-code (char ,string i))))
54 (setf (deref-array char-ptr '(:array :byte) ,size) 0)))))
56 (defun %cstring-into-vector (ptr vector offset size-in-bytes)
57 (dotimes (i size-in-bytes)
58 (setf (schar vector offset)
59 (ensure-char-character
60 (deref-array ptr '(:array :unsigned-char) i)))
64 (defmacro with-allocate-foreign-string ((var len) &body body)
65 "Safely does uffi:allocate-foreign-string-- making sure we do the uffi:free-foreign-object"
69 (setf ,var (uffi:allocate-foreign-string ,len))
72 (uffi:free-foreign-object ,var)))))
74 (defmacro with-allocate-foreign-strings (bindings &rest body)
76 `(with-allocate-foreign-string ,(car bindings)
77 (with-allocate-foreign-strings ,(cdr bindings)
81 (defun handle-error (henv hdbc hstmt)
82 (with-allocate-foreign-strings ((sql-state 256)
83 (error-message #.$SQL_MAX_MESSAGE_LENGTH))
84 (with-foreign-objects ((error-code #.$ODBC-LONG-TYPE)
86 (SQLError henv hdbc hstmt sql-state
87 error-code error-message
88 #.$SQL_MAX_MESSAGE_LENGTH msg-length)
90 (convert-from-foreign-string error-message)
91 (convert-from-foreign-string sql-state)
92 (deref-pointer msg-length :short)
93 (deref-pointer error-code #.$ODBC-LONG-TYPE)))))
95 (defun sql-state (henv hdbc hstmt)
96 (with-allocate-foreign-strings ((sql-state 256)
97 (error-message #.$SQL_MAX_MESSAGE_LENGTH))
98 (with-foreign-objects ((error-code #.$ODBC-LONG-TYPE)
100 (SQLError henv hdbc hstmt sql-state error-code
101 error-message #.$SQL_MAX_MESSAGE_LENGTH msg-length)
102 (convert-from-foreign-string sql-state)
103 ;; test this: return a keyword for efficiency
104 ;;(%cstring-to-keyword state)
107 (defmacro with-error-handling ((&key henv hdbc hstmt (print-info t))
108 odbc-call &body body)
109 (let ((result-code (gensym "RC-")))
110 `(let ((,result-code ,odbc-call))
112 ;; Check for allegro v7 & v8 bug with ODBC calls returning
113 ;; 32-bit unsigned ints, not 16-bit signed ints
114 #+(and allegro mswindows)
115 (when (> ,result-code #xFFFF)
116 (warn (format nil "16-bit return bug: result-code #x~X for expression ~S"
117 ,result-code (quote ,odbc-call)))
118 (setq ,result-code (logand ,result-code #xFFFF))
119 (when (> ,result-code #x7FFF)
120 (setq ,result-code (- ,result-code #x10000))))
124 (progn ,result-code ,@body))
125 (#.$SQL_SUCCESS_WITH_INFO
127 (multiple-value-bind (error-message sql-state)
128 (handle-error (or ,henv +null-handle-ptr+)
129 (or ,hdbc +null-handle-ptr+)
130 (or ,hstmt +null-handle-ptr+))
132 (format *info-output* "[ODBC info ~A] ~A state: ~A"
133 ,result-code error-message
135 (progn ,result-code ,@body))
136 (#.$SQL_INVALID_HANDLE
138 'clsql-sys:sql-database-error
139 :message "ODBC: Invalid handle"))
140 (#.$SQL_STILL_EXECUTING
142 'clsql-sys:sql-temporary-error
143 :message "ODBC: Still executing"))
145 (multiple-value-bind (error-message sql-state)
146 (handle-error (or ,henv +null-handle-ptr+)
147 (or ,hdbc +null-handle-ptr+)
148 (or ,hstmt +null-handle-ptr+))
150 'clsql-sys:sql-database-error
151 :message error-message
152 :secondary-error-id sql-state)))
153 (#.$SQL_NO_DATA_FOUND
154 (progn ,result-code ,@body))
155 ;; work-around for Allegro 7.0beta AMD64 which returns negative numbers
157 (multiple-value-bind (error-message sql-state)
158 (handle-error (or ,henv +null-handle-ptr+)
159 (or ,hdbc +null-handle-ptr+)
160 (or ,hstmt +null-handle-ptr+))
162 'clsql-sys:sql-database-error
163 :message error-message
164 :secondary-error-id sql-state))
166 (progn ,result-code ,@body))))))
168 (defun %new-environment-handle ()
170 (with-foreign-object (phenv 'sql-handle)
173 (SQLAllocHandle $SQL_HANDLE_ENV +null-handle-ptr+ phenv)
174 (deref-pointer phenv 'sql-handle)))))
175 (%set-attr-odbc-version henv $SQL_OV_ODBC3)
179 (defun %sql-free-environment (henv)
184 (defun %new-db-connection-handle (henv)
185 (with-foreign-object (phdbc 'sql-handle)
186 (setf (deref-pointer phdbc 'sql-handle) +null-handle-ptr+)
189 (SQLAllocHandle $SQL_HANDLE_DBC henv phdbc)
190 (deref-pointer phdbc 'sql-handle))))
192 (defun %free-statement (hstmt option)
200 (:unbind $SQL_UNBIND)
201 (:reset $SQL_RESET_PARAMS)))))
203 (defmacro with-statement-handle ((hstmt hdbc) &body body)
204 `(let ((,hstmt (%new-statement-handle ,hdbc)))
207 (%free-statement ,hstmt :drop))))
209 ;; functional interface
211 (defun %sql-connect (hdbc server uid pwd)
212 (with-cstrings ((server-ptr server)
217 (SQLConnect hdbc server-ptr $SQL_NTS uid-ptr
218 $SQL_NTS pwd-ptr $SQL_NTS))))
220 (defun %sql-driver-connect (hdbc connection-string completion window-handle)
221 (with-cstring (connection-ptr connection-string)
222 (with-allocate-foreign-string (completed-connection-string-ptr $SQL_MAX_CONN_OUT)
223 (with-foreign-object (completed-connection-length :short)
226 (SQLDriverConnect hdbc
228 connection-ptr $SQL_NTS
229 completed-connection-string-ptr $SQL_MAX_CONN_OUT
230 completed-connection-length
233 (defun %disconnect (hdbc)
239 (SQLFreeHandle $SQL_HANDLE_DBC hdbc))))
241 (defun %commit (henv hdbc)
243 (:henv henv :hdbc hdbc)
245 henv hdbc $SQL_COMMIT)))
247 (defun %rollback (henv hdbc)
249 (:henv henv :hdbc hdbc)
251 henv hdbc $SQL_ROLLBACK)))
253 ; col-nr is zero-based in Lisp but 1 based in sql
254 ; col-nr = :bookmark retrieves a bookmark.
255 (defun %bind-column (hstmt column-nr c-type data-ptr precision out-len-ptr)
259 (if (eq column-nr :bookmark) 0 (1+ column-nr))
260 c-type data-ptr precision out-len-ptr)))
262 ; parameter-nr is zero-based in Lisp
263 (defun %sql-bind-parameter (hstmt parameter-nr parameter-type c-type
264 sql-type precision scale data-ptr
265 max-value out-len-ptr)
268 (SQLBindParameter hstmt (1+ parameter-nr)
269 parameter-type ;$SQL_PARAM_INPUT
271 sql-type ;$SQL_VARCHAR
272 precision ;(1- (length str))
276 out-len-ptr ;#.+null-ptr+
279 (defun %sql-fetch (hstmt)
284 (defun %new-statement-handle (hdbc)
285 (let ((statement-handle
286 (with-foreign-object (phstmt 'sql-handle)
289 (SQLAllocHandle $SQL_HANDLE_STMT hdbc phstmt)
290 (deref-pointer phstmt 'sql-handle)))))
291 (if (uffi:null-pointer-p statement-handle)
292 (error 'clsql:sql-database-error :message "Received null statement handle.")
295 (defun %sql-get-info (hdbc info-type)
297 ;; those return string
298 ((#.$SQL_ACCESSIBLE_PROCEDURES
299 #.$SQL_ACCESSIBLE_TABLES
301 #.$SQL_DATA_SOURCE_NAME
302 #.$SQL_DATA_SOURCE_READ_ONLY
306 #.$SQL_DRIVER_ODBC_VER
308 #.$SQL_EXPRESSIONS_IN_ORDERBY
309 #.$SQL_IDENTIFIER_QUOTE_CHAR
311 #.$SQL_LIKE_ESCAPE_CLAUSE
312 #.$SQL_MAX_ROW_SIZE_INCLUDES_LONG
313 #.$SQL_MULT_RESULT_SETS
314 #.$SQL_MULTIPLE_ACTIVE_TXN
315 #.$SQL_NEED_LONG_DATA_LEN
316 #.$SQL_ODBC_SQL_OPT_IEF
318 #.$SQL_ORDER_BY_COLUMNS_IN_SELECT
321 #.$SQL_PROCEDURE_TERM
323 #.$SQL_QUALIFIER_NAME_SEPARATOR
324 #.$SQL_QUALIFIER_TERM
326 #.$SQL_SEARCH_PATTERN_ESCAPE
328 #.$SQL_SPECIAL_CHARACTERS
331 (with-allocate-foreign-string (info-ptr 1024)
332 (with-foreign-object (info-length-ptr :short)
335 (SQLGetInfo hdbc info-type info-ptr 1023 info-length-ptr)
336 (convert-from-foreign-string info-ptr)))))
337 ;; those returning a word
338 ((#.$SQL_ACTIVE_CONNECTIONS
339 #.$SQL_ACTIVE_STATEMENTS
340 #.$SQL_CONCAT_NULL_BEHAVIOR
341 #.$SQL_CORRELATION_NAME
342 #.$SQL_CURSOR_COMMIT_BEHAVIOR
343 #.$SQL_CURSOR_ROLLBACK_BEHAVIOR
344 #.$SQL_MAX_COLUMN_NAME_LEN
345 #.$SQL_MAX_COLUMNS_IN_GROUP_BY
346 #.$SQL_MAX_COLUMNS_IN_INDEX
347 #.$SQL_MAX_COLUMNS_IN_ORDER_BY
348 #.$SQL_MAX_COLUMNS_IN_SELECT
349 #.$SQL_MAX_COLUMNS_IN_TABLE
350 #.$SQL_MAX_CURSOR_NAME_LEN
351 #.$SQL_MAX_OWNER_NAME_LEN
352 #.$SQL_MAX_PROCEDURE_NAME_LEN
353 #.$SQL_MAX_QUALIFIER_NAME_LEN
354 #.$SQL_MAX_TABLE_NAME_LEN
355 #.$SQL_MAX_TABLES_IN_SELECT
356 #.$SQL_MAX_USER_NAME_LEN
357 #.$SQL_NON_NULLABLE_COLUMNS
358 #.$SQL_NULL_COLLATION
359 #.$SQL_ODBC_API_CONFORMANCE
360 #.$SQL_ODBC_SAG_CLI_CONFORMANCE
361 #.$SQL_ODBC_SQL_CONFORMANCE
362 #.$SQL_QUALIFIER_LOCATION
363 #.$SQL_QUOTED_IDENTIFIER_CASE
365 (with-foreign-objects ((info-ptr :short)
366 (info-length-ptr :short))
374 (deref-pointer info-ptr :short)))
376 ;; those returning a long bitmask
378 #.$SQL_BOOKMARK_PERSISTENCE
379 #.$SQL_CONVERT_BIGINT
380 #.$SQL_CONVERT_BINARY
384 #.$SQL_CONVERT_DECIMAL
385 #.$SQL_CONVERT_DOUBLE
387 #.$SQL_CONVERT_INTEGER
388 #.$SQL_CONVERT_LONGVARCHAR
389 #.$SQL_CONVERT_NUMERIC
391 #.$SQL_CONVERT_SMALLINT
393 #.$SQL_CONVERT_TIMESTAMP
394 #.$SQL_CONVERT_TINYINT
395 #.$SQL_CONVERT_VARBINARY
396 #.$SQL_CONVERT_VARCHAR
397 #.$SQL_CONVERT_LONGVARBINARY
398 #.$SQL_CONVERT_FUNCTIONS
399 #.$SQL_FETCH_DIRECTION
401 #.$SQL_GETDATA_EXTENSIONS
403 #.$SQL_MAX_INDEX_SIZE
405 #.$SQL_MAX_STATEMENT_LEN
406 #.$SQL_NUMERIC_FUNCTIONS
408 #.$SQL_POS_OPERATIONS
409 #.$SQL_POSITIONED_STATEMENTS
410 #.$SQL_QUALIFIER_USAGE
411 #.$SQL_SCROLL_CONCURRENCY
412 #.$SQL_SCROLL_OPTIONS
413 #.$SQL_STATIC_SENSITIVITY
414 #.$SQL_STRING_FUNCTIONS
416 #.$SQL_SYSTEM_FUNCTIONS
417 #.$SQL_TIMEDATE_ADD_INTERVALS
418 #.$SQL_TIMEDATE_DIFF_INTERVALS
419 #.$SQL_TIMEDATE_FUNCTIONS
420 #.$SQL_TXN_ISOLATION_OPTION
422 (with-foreign-objects ((info-ptr #.$ODBC-LONG-TYPE)
423 (info-length-ptr :short))
431 (deref-pointer info-ptr #.$ODBC-LONG-TYPE)))
433 ;; those returning a long integer
434 ((#.$SQL_DEFAULT_TXN_ISOLATION
440 #.$SQL_IDENTIFIER_CASE
441 #.$SQL_MAX_BINARY_LITERAL_LEN
442 #.$SQL_MAX_CHAR_LITERAL_LEN
443 #.$SQL_ACTIVE_ENVIRONMENTS
445 (with-foreign-objects ((info-ptr #.$ODBC-LONG-TYPE)
446 (info-length-ptr :short))
449 (SQLGetInfo hdbc info-type info-ptr 255 info-length-ptr)
450 (deref-pointer info-ptr #.$ODBC-LONG-TYPE))))))
452 (defun %sql-exec-direct (sql hstmt henv hdbc)
453 (with-cstring (sql-ptr sql)
455 (:hstmt hstmt :henv henv :hdbc hdbc)
456 (SQLExecDirect hstmt sql-ptr $SQL_NTS))))
458 (defun %sql-cancel (hstmt)
463 (defun %sql-execute (hstmt)
468 (defun result-columns-count (hstmt)
469 (with-foreign-objects ((columns-nr-ptr :short))
470 (with-error-handling (:hstmt hstmt)
471 (SQLNumResultCols hstmt columns-nr-ptr)
472 (deref-pointer columns-nr-ptr :short))))
474 (defun result-rows-count (hstmt)
475 (with-foreign-objects ((row-count-ptr #.$ODBC-LONG-TYPE))
476 (with-error-handling (:hstmt hstmt)
477 (SQLRowCount hstmt row-count-ptr)
478 (deref-pointer row-count-ptr #.$ODBC-LONG-TYPE))))
480 ;; column counting is 1-based
481 (defun %describe-column (hstmt column-nr)
482 (with-allocate-foreign-string (column-name-ptr 256)
483 (with-foreign-objects ((column-name-length-ptr :short)
484 (column-sql-type-ptr :short)
485 (column-precision-ptr #.$ODBC-ULONG-TYPE)
486 (column-scale-ptr :short)
487 (column-nullable-p-ptr :short))
488 (with-error-handling (:hstmt hstmt)
489 (SQLDescribeCol hstmt column-nr column-name-ptr 256
490 column-name-length-ptr
494 column-nullable-p-ptr)
496 (convert-from-foreign-string column-name-ptr)
497 (deref-pointer column-sql-type-ptr :short)
498 (deref-pointer column-precision-ptr #.$ODBC-ULONG-TYPE)
499 (deref-pointer column-scale-ptr :short)
500 (deref-pointer column-nullable-p-ptr :short))))))
502 ;; parameter counting is 1-based
503 ;; this function isn't used, which is good because FreeTDS dosn't support it.
504 (defun %describe-parameter (hstmt parameter-nr)
505 (with-foreign-objects ((column-sql-type-ptr :short)
506 (column-precision-ptr #.$ODBC-ULONG-TYPE)
507 (column-scale-ptr :short)
508 (column-nullable-p-ptr :short))
511 (SQLDescribeParam hstmt parameter-nr
515 column-nullable-p-ptr)
517 (deref-pointer column-sql-type-ptr :short)
518 (deref-pointer column-precision-ptr #.$ODBC-ULONG-TYPE)
519 (deref-pointer column-scale-ptr :short)
520 (deref-pointer column-nullable-p-ptr :short)))))
522 (defun %column-attributes (hstmt column-nr descriptor-type)
523 (with-allocate-foreign-string (descriptor-info-ptr 256)
524 (with-foreign-objects ((descriptor-length-ptr :short)
525 (numeric-descriptor-ptr #.$ODBC-LONG-TYPE))
528 (SQLColAttributes hstmt column-nr descriptor-type descriptor-info-ptr
529 256 descriptor-length-ptr
530 numeric-descriptor-ptr)
532 (convert-from-foreign-string descriptor-info-ptr)
533 (deref-pointer numeric-descriptor-ptr #.$ODBC-LONG-TYPE))))))
535 (defun %prepare-describe-columns (hstmt table-qualifier table-owner
536 table-name column-name)
537 (with-cstrings ((table-qualifier-ptr table-qualifier)
538 (table-owner-ptr table-owner)
539 (table-name-ptr table-name)
540 (column-name-ptr column-name))
544 table-qualifier-ptr (length table-qualifier)
545 table-owner-ptr (length table-owner)
546 table-name-ptr (length table-name)
547 column-name-ptr (length column-name)))))
549 (defun %describe-columns (hdbc table-qualifier table-owner
550 table-name column-name)
551 (with-statement-handle (hstmt hdbc)
552 (%prepare-describe-columns hstmt table-qualifier table-owner
553 table-name column-name)
554 (fetch-all-rows hstmt)))
556 (defun %sql-data-sources (henv &key (direction :first))
557 (with-allocate-foreign-strings ((name-ptr (1+ $SQL_MAX_DSN_LENGTH))
558 (description-ptr 1024))
559 (with-foreign-objects ((name-length-ptr :short)
560 (description-length-ptr :short))
561 (let ((res (with-error-handling
565 (:first $SQL_FETCH_FIRST)
566 (:next $SQL_FETCH_NEXT))
568 (1+ $SQL_MAX_DSN_LENGTH)
572 description-length-ptr))))
573 (when (= res $SQL_NO_DATA_FOUND)
575 (convert-from-foreign-string name-ptr)
576 (convert-from-foreign-string description-ptr)))))))
580 (defun sql-to-c-type (sql-type)
582 ((#.$SQL_CHAR #.$SQL_VARCHAR #.$SQL_LONGVARCHAR
583 #.$SQL_NUMERIC #.$SQL_DECIMAL -8 -9 -10) $SQL_C_CHAR) ;; Added -10 for MSSQL ntext type
584 (#.$SQL_INTEGER $SQL_C_SLONG)
585 (#.$SQL_BIGINT $SQL_C_SBIGINT)
586 (#.$SQL_SMALLINT $SQL_C_SSHORT)
587 (#.$SQL_DOUBLE $SQL_C_DOUBLE)
588 (#.$SQL_FLOAT $SQL_C_DOUBLE)
589 (#.$SQL_REAL $SQL_C_FLOAT)
590 (#.$SQL_DATE $SQL_C_DATE)
591 (#.$SQL_TIME $SQL_C_TIME)
592 (#.$SQL_TIMESTAMP $SQL_C_TIMESTAMP)
593 (#.$SQL_TYPE_DATE $SQL_C_TYPE_DATE)
594 (#.$SQL_TYPE_TIME $SQL_C_TYPE_TIME)
595 (#.$SQL_TYPE_TIMESTAMP $SQL_C_TYPE_TIMESTAMP)
596 ((#.$SQL_BINARY #.$SQL_VARBINARY #.$SQL_LONGVARBINARY) $SQL_C_BINARY)
597 (#.$SQL_TINYINT $SQL_C_STINYINT)
598 (#.$SQL_BIT $SQL_C_BIT)))
600 (def-type byte-pointer-type (* :byte))
601 (def-type short-pointer-type (* :short))
602 (def-type int-pointer-type (* :int))
603 (def-type long-pointer-type (* #.$ODBC-LONG-TYPE))
604 (def-type big-pointer-type (* #.$ODBC-BIG-TYPE))
605 (def-type float-pointer-type (* :float))
606 (def-type double-pointer-type (* :double))
607 (def-type string-pointer-type (* :unsigned-char))
609 (defun get-cast-byte (ptr)
610 (locally (declare (type byte-pointer-type ptr))
611 (deref-pointer ptr :byte)))
613 (defun get-cast-short (ptr)
614 (locally (declare (type short-pointer-type ptr))
615 (deref-pointer ptr :short)))
617 (defun get-cast-int (ptr)
618 (locally (declare (type int-pointer-type ptr))
619 (deref-pointer ptr :int)))
621 (defun get-cast-long (ptr)
622 (locally (declare (type long-pointer-type ptr))
623 (deref-pointer ptr #.$ODBC-LONG-TYPE)))
625 (defun get-cast-big (ptr)
626 (locally (declare (type big-pointer-type ptr))
627 (deref-pointer ptr #.$ODBC-BIG-TYPE)))
629 (defun get-cast-single-float (ptr)
630 (locally (declare (type float-pointer-type ptr))
631 (deref-pointer ptr :float)))
633 (defun get-cast-double-float (ptr)
634 (locally (declare (type double-pointer-type ptr))
635 (deref-pointer ptr :double)))
637 (defun get-cast-foreign-string (ptr)
638 (locally (declare (type string-pointer-type ptr))
639 (convert-from-foreign-string ptr)))
641 (defun get-cast-binary (ptr len format)
642 "FORMAT is one of :unsigned-byte-vector, :bit-vector (:string, :hex-string)"
643 (with-cast-pointer (casted ptr :unsigned-byte)
645 (:unsigned-byte-vector
646 (let ((vector (make-array len :element-type '(unsigned-byte 8))))
648 (setf (aref vector i)
649 (deref-array casted '(:array :unsigned-byte) i)))
652 (let ((vector (make-array (ash len 3) :element-type 'bit)))
654 (let ((byte (deref-array casted '(:array :byte) i)))
656 (setf (bit vector (+ (ash i 3) j))
657 (logand (ash byte (- j 7)) 1)))))
661 (defun read-data (data-ptr c-type sql-type out-len-ptr result-type)
662 (declare (type long-ptr-type out-len-ptr))
663 (let* ((out-len (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE))
665 (cond ((= out-len $SQL_NULL_DATA)
669 ;; SQL extended datatypes
670 (#.$SQL_TINYINT (get-cast-byte data-ptr))
671 (#.$SQL_C_STINYINT (get-cast-byte data-ptr)) ;; ?
672 (#.$SQL_C_SSHORT (get-cast-short data-ptr)) ;; ?
673 (#.$SQL_SMALLINT (get-cast-short data-ptr)) ;; ??
674 (#.$SQL_INTEGER (get-cast-int data-ptr))
675 (#.$SQL_BIGINT (get-cast-big 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
705 (#.$SQL_C_SBIGINT (get-cast-big data-ptr))
708 (code-char (get-cast-short data-ptr)))
710 (get-cast-foreign-string data-ptr)))))))))
712 ;; FIXME: this could be better optimized for types which use READ-FROM-STRING above
714 (if (and (or (eq result-type t) (eq result-type :string))
716 (not (stringp value)))
717 (write-to-string value)
720 ;; which value is appropriate?
721 (defparameter +max-precision+ 4001)
723 (defvar *break-on-unknown-data-type* t)
725 ;; C. Stacy's idea to factor this out
726 ;; "Make it easy to add new datatypes by making new subroutine %ALLOCATE-BINDINGS,
727 ;; so that I don't have to remember to make changes in more than one place.
728 ;; Just keep it in synch with READ-DATA."
729 (defun %allocate-bindings (sql-type precision)
730 (let* ((c-type (sql-to-c-type sql-type))
731 (size (if (zerop precision)
732 +max-precision+ ;; if the precision cannot be determined
733 (min precision +max-precision+)))
734 (long-p (= size +max-precision+))
736 (case c-type ;; add more?
737 (#.$SQL_C_SLONG (uffi:allocate-foreign-object #.$ODBC-LONG-TYPE))
738 ((#.$SQL_C_DATE #.$SQL_C_TYPE_DATE) (allocate-foreign-object 'sql-c-date))
739 ((#.$SQL_C_TIME #.$SQL_C_TYPE_TIME) (allocate-foreign-object 'sql-c-time))
740 ((#.$SQL_C_TIMESTAMP #.$SQL_C_TYPE_TIMESTAMP) (allocate-foreign-object 'sql-c-timestamp))
741 (#.$SQL_C_FLOAT (uffi:allocate-foreign-object :float))
742 (#.$SQL_C_DOUBLE (uffi:allocate-foreign-object :double))
743 (#.$SQL_C_BIT (uffi:allocate-foreign-object :byte))
744 (#.$SQL_C_STINYINT (uffi:allocate-foreign-object :byte))
745 (#.$SQL_C_SBIGINT (uffi:allocate-foreign-object #.$ODBC-BIG-TYPE))
746 (#.$SQL_C_SSHORT (uffi:allocate-foreign-object :short))
747 (#.$SQL_C_CHAR (uffi:allocate-foreign-string (1+ size)))
748 (#.$SQL_C_BINARY (uffi:allocate-foreign-string (1+ (* 2 size))))
750 ;; Maybe should signal a restartable condition for this?
751 (when *break-on-unknown-data-type*
752 (break "SQL type is ~A, precision ~D, size ~D, C type is ~A"
753 sql-type precision size c-type))
754 (uffi:allocate-foreign-object :byte (1+ size)))))
755 (out-len-ptr (uffi:allocate-foreign-object #.$ODBC-LONG-TYPE)))
756 (values c-type data-ptr out-len-ptr size long-p)))
758 (defun fetch-all-rows (hstmt &key free-option flatp)
759 (let ((column-count (result-columns-count hstmt)))
760 (unless (zerop column-count)
761 (let ((names (make-array column-count))
762 (sql-types (make-array column-count :element-type 'fixnum))
763 (c-types (make-array column-count :element-type 'fixnum))
764 (precisions (make-array column-count :element-type 'fixnum))
765 (data-ptrs (make-array column-count :initial-element nil))
766 (out-len-ptrs (make-array column-count :initial-element nil))
767 (scales (make-array column-count :element-type 'fixnum))
768 (nullables-p (make-array column-count :element-type 'fixnum)))
772 (dotimes (col-nr column-count)
773 ;; get column information
774 (multiple-value-bind (name sql-type precision scale nullable-p)
775 (%describe-column hstmt (1+ col-nr))
776 ;; allocate space to bind result rows to
777 (multiple-value-bind (c-type data-ptr out-len-ptr)
778 (%allocate-bindings sql-type precision)
779 (%bind-column hstmt col-nr c-type data-ptr (1+ precision) out-len-ptr)
780 (setf (svref names col-nr) name
781 (aref sql-types col-nr) sql-type
782 (aref c-types col-nr) (sql-to-c-type sql-type)
783 (aref precisions col-nr) (if (zerop precision) 0 precision)
784 (aref scales col-nr) scale
785 (aref nullables-p col-nr) nullable-p
786 (aref data-ptrs col-nr) data-ptr
787 (aref out-len-ptrs col-nr) out-len-ptr))))
791 (when (> column-count 1)
792 (error 'clsql:sql-database-error
793 :message "If more than one column is to be fetched, flatp has to be nil."))
794 (loop until (= (%sql-fetch hstmt) $SQL_NO_DATA_FOUND)
796 (read-data (aref data-ptrs 0)
799 (aref out-len-ptrs 0)
802 (loop until (= (%sql-fetch hstmt) $SQL_NO_DATA_FOUND)
804 (loop for col-nr from 0 to (1- column-count)
806 (read-data (aref data-ptrs col-nr)
807 (aref c-types col-nr)
808 (aref sql-types col-nr)
809 (aref out-len-ptrs col-nr)
812 ;; dispose of memory etc
813 (when free-option (%free-statement hstmt free-option))
814 (dotimes (col-nr column-count)
815 (let ((data-ptr (aref data-ptrs col-nr))
816 (out-len-ptr (aref out-len-ptrs col-nr)))
817 (when data-ptr (free-foreign-object data-ptr)) ; we *did* allocate them
818 (when out-len-ptr (free-foreign-object out-len-ptr)))))))))
820 ;; to do: factor out common parts, put the sceleton (the obligatory macro part)
821 ;; of %do-fetch into sql package (has been done)
823 (defun %sql-prepare (hstmt sql)
824 (with-cstring (sql-ptr sql)
825 (with-error-handling (:hstmt hstmt)
826 (SQLPrepare hstmt sql-ptr $SQL_NTS))))
828 ;; depending on option, we return a long int or a string; string not implemented
829 (defun get-connection-option (hdbc option)
830 (with-foreign-object (param-ptr #.$ODBC-LONG-TYPE)
831 (with-error-handling (:hdbc hdbc)
832 (SQLGetConnectOption hdbc option param-ptr)
833 (deref-pointer param-ptr #.$ODBC-LONG-TYPE))))
835 (defun set-connection-option (hdbc option param)
836 (with-error-handling (:hdbc hdbc)
837 (SQLSetConnectOption hdbc option param)))
839 (defun disable-autocommit (hdbc)
840 (set-connection-option hdbc $SQL_AUTOCOMMIT $SQL_AUTOCOMMIT_OFF))
842 (defun enable-autocommit (hdbc)
843 (set-connection-option hdbc $SQL_AUTOCOMMIT $SQL_AUTOCOMMIT_ON))
845 (defun %sql-set-pos (hstmt row option lock)
848 (SQLSetPos hstmt row option lock)))
850 (defun %sql-extended-fetch (hstmt fetch-type row)
851 (with-foreign-objects ((row-count-ptr #.$ODBC-ULONG-TYPE)
852 (row-status-ptr :short))
853 (with-error-handling (:hstmt hstmt)
854 (SQLExtendedFetch hstmt fetch-type row row-count-ptr
856 (values (deref-pointer row-count-ptr #.$ODBC-ULONG-TYPE)
857 (deref-pointer row-status-ptr :short)))))
859 ; column-nr is zero-based
860 (defun %sql-get-data (hstmt column-nr c-type data-ptr precision out-len-ptr)
862 (:hstmt hstmt :print-info nil)
863 (SQLGetData hstmt (if (eq column-nr :bookmark) 0 (1+ column-nr))
864 c-type data-ptr precision out-len-ptr)))
866 (defun %sql-param-data (hstmt param-ptr)
867 (with-error-handling (:hstmt hstmt :print-info t) ;; nil
868 (SQLParamData hstmt param-ptr)))
870 (defun %sql-put-data (hstmt data-ptr size)
872 (:hstmt hstmt :print-info t) ;; nil
873 (SQLPutData hstmt data-ptr size)))
875 (defconstant $sql-data-truncated (intern "01004" :keyword))
877 (defun read-data-in-chunks (hstmt column-nr data-ptr c-type sql-type
878 out-len-ptr result-type)
879 (declare (type long-ptr-type out-len-ptr)
880 (ignore result-type))
881 (let* ((res (%sql-get-data hstmt column-nr c-type data-ptr
882 +max-precision+ out-len-ptr))
883 (out-len (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE))
885 (result (case out-len
887 (return-from read-data-in-chunks *null*))
888 (#.$SQL_NO_TOTAL ;; don't know how long it is going to be
889 (let ((str (make-array 0 :element-type 'character :adjustable t)))
890 (loop do (if (= c-type #.$SQL_CHAR)
891 (let ((data-length (foreign-string-length data-ptr)))
892 (adjust-array str (+ offset data-length)
893 :initial-element #\?)
894 (setf offset (%cstring-into-vector
898 (error 'clsql:sql-database-error :message "wrong type. preliminary."))
899 while (and (= res $SQL_SUCCESS_WITH_INFO)
900 (equal (sql-state +null-handle-ptr+ +null-handle-ptr+ hstmt)
902 do (setf res (%sql-get-data hstmt column-nr c-type data-ptr
903 +max-precision+ out-len-ptr)))
904 (setf str (coerce str 'string))
905 (if (= sql-type $SQL_DECIMAL)
906 (let ((*read-base* 10))
907 (read-from-string str))
912 (octets (make-array out-len :element-type '(unsigned-byte 8) :initial-element 0)))
915 (loop for i from 0 to (1- (min out-len +max-precision+))
916 do (setf (aref octets (+ offset i)) (deref-array data-ptr '(:array :unsigned-byte) i))
917 finally (incf offset (1- i)))
919 (and (= res $SQL_SUCCESS_WITH_INFO)
920 (> out-len +max-precision+))
922 (setf res (%sql-get-data hstmt column-nr c-type data-ptr +max-precision+ out-len-ptr)
923 out-len (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE)))
924 (setf str (uffi:octets-to-string octets))
925 (if (= sql-type $SQL_DECIMAL)
926 (let ((*read-base* 10))
927 (read-from-string str))
929 (setf (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE) #.$SQL_NO_TOTAL) ;; reset the out length for the next row
932 (def-type c-timestamp-ptr-type (* (:struct sql-c-timestamp)))
933 (def-type c-time-ptr-type (* (:struct sql-c-time)))
934 (def-type c-date-ptr-type (* (:struct sql-c-date)))
936 (defun timestamp-to-universal-time (ptr)
937 (declare (type c-timestamp-ptr-type ptr))
939 (encode-universal-time
940 (get-slot-value ptr 'sql-c-timestamp 'second)
941 (get-slot-value ptr 'sql-c-timestamp 'minute)
942 (get-slot-value ptr 'sql-c-timestamp 'hour)
943 (get-slot-value ptr 'sql-c-timestamp 'day)
944 (get-slot-value ptr 'sql-c-timestamp 'month)
945 (get-slot-value ptr 'sql-c-timestamp 'year))
946 (get-slot-value ptr 'sql-c-timestamp 'fraction)))
948 (defun universal-time-to-timestamp (time &optional (fraction 0))
949 "TODO: Dead function?"
950 (multiple-value-bind (sec min hour day month year)
951 (decode-universal-time time)
952 (let ((ptr (allocate-foreign-object 'sql-c-timestamp)))
953 (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
954 (get-slot-value ptr 'sql-c-timestamp 'minute) min
955 (get-slot-value ptr 'sql-c-timestamp 'hour) hour
956 (get-slot-value ptr 'sql-c-timestamp 'day) day
957 (get-slot-value ptr 'sql-c-timestamp 'month) month
958 (get-slot-value ptr 'sql-c-timestamp 'year) year
959 (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
962 (defun %put-timestamp (ptr time &optional (fraction 0))
963 "TODO: Dead function?"
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 ;;note that we are passing version as an integer that happens to be
998 ;;stuffed into a pointer.
999 ;;http://msdn.microsoft.com/en-us/library/ms709285%28v=VS.85%29.aspx
1000 (SQLSetEnvAttr henv $SQL_ATTR_ODBC_VERSION
1001 (make-pointer version :void) 0)))
1003 (defun %list-tables (hstmt)
1004 (with-error-handling (:hstmt hstmt)
1005 (SQLTables hstmt +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0)))
1007 (defun %table-statistics (table hstmt &key unique (ensure t))
1008 (with-cstrings ((table-cs table))
1009 (with-error-handling (:hstmt hstmt)
1015 (if unique $SQL_INDEX_UNIQUE $SQL_INDEX_ALL)
1016 (if ensure $SQL_ENSURE $SQL_QUICK)))))
1018 (defun %list-data-sources (henv)
1019 (let ((results nil))
1020 (with-foreign-strings ((dsn-ptr (1+ $SQL_MAX_DSN_LENGTH))
1022 (with-foreign-objects ((dsn-len :short)
1024 (let ((res (with-error-handling (:henv henv)
1025 (SQLDataSources henv $SQL_FETCH_FIRST dsn-ptr
1026 (1+ $SQL_MAX_DSN_LENGTH)
1027 dsn-len desc-ptr 256 desc-len))))
1028 (when (or (eql res $SQL_SUCCESS)
1029 (eql res $SQL_SUCCESS_WITH_INFO))
1030 (push (convert-from-foreign-string dsn-ptr) results))
1032 (do ((res (with-error-handling (:henv henv)
1033 (SQLDataSources henv $SQL_FETCH_NEXT dsn-ptr
1034 (1+ $SQL_MAX_DSN_LENGTH)
1035 dsn-len desc-ptr 256 desc-len))
1036 (with-error-handling (:henv henv)
1037 (SQLDataSources henv $SQL_FETCH_NEXT dsn-ptr
1038 (1+ $SQL_MAX_DSN_LENGTH)
1039 dsn-len desc-ptr 256 desc-len))))
1040 ((not (or (eql res $SQL_SUCCESS)
1041 (eql res $SQL_SUCCESS_WITH_INFO))))
1042 (push (convert-from-foreign-string dsn-ptr) results)))))
1043 (nreverse results)))