1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Package: odbc -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
5 ;;;; Name: odbc-api.lisp
6 ;;;; Purpose: Low-level ODBC API using UFFI
7 ;;;; Authors: Kevin M. Rosenberg and Paul Meurer
9 ;;;; This file, part of CLSQL, is Copyright (c) 2004 by Kevin M. Rosenberg
10 ;;;; and Copyright (C) Paul Meurer 1999 - 2001. All rights reserved.
12 ;;;; CLSQL users are granted the rights to distribute and use this software
13 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
14 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
15 ;;;; *************************************************************************
20 "Lisp representation of SQL Null value, default = nil.
21 May be locally bound to something else if a certain type is necessary.")
24 (defvar *binary-format* :unsigned-byte-vector)
27 (clsql-sys:format-time nil time :format :iso))
28 "Bound to a function that converts from a clsql:wall-time to the desired
29 representation of date/time/timestamp.
30 By default, returns an iso-timestring.")
32 (defvar +null-ptr+ (make-null-pointer :byte))
33 (defparameter +null-handle-ptr+ (make-null-pointer :void))
34 (defvar *info-output* nil
35 "Stream to send SUCCESS_WITH_INFO messages.")
37 (defmacro %put-str (ptr string &optional max-length)
38 (let ((size (gensym)))
39 `(let ((,size (length ,string)))
40 (when (and ,max-length (> ,size ,max-length))
41 (error 'clsql:sql-database-data-error
43 (format nil "string \"~a\" of length ~d is longer than max-length: ~d"
44 ,string ,size ,max-length)))
45 (with-cast-pointer (char-ptr ,ptr :byte)
47 (setf (deref-array char-ptr '(:array :byte) i)
48 (char-code (char ,string i))))
49 (setf (deref-array char-ptr '(:array :byte) ,size) 0)))))
51 (defun %cstring-into-vector (ptr vector offset size-in-bytes)
52 (dotimes (i size-in-bytes)
53 (setf (schar vector offset)
54 (ensure-char-character
55 ;; this is MUCH faster than (sb-alien:deref ptr i) even though
56 ;; sb-alien:deref makes more sense. I snagged this by looking at
57 ;; cffi which we had used previously without this bug
58 #+(and sbcl (not cffi))
59 (sb-sys:sap-ref-8 (sb-alien:alien-sap ptr) i)
60 #-(and sbcl (not cffi))
61 (deref-array ptr '(:array :unsigned-char) i)
66 (defmacro with-allocate-foreign-string ((var len) &body body)
67 "Safely does uffi:allocate-foreign-string-- making sure we do the uffi:free-foreign-object"
71 (setf ,var (uffi:allocate-foreign-string ,len))
74 (uffi:free-foreign-object ,var)))))
76 (defmacro with-allocate-foreign-strings (bindings &rest body)
78 `(with-allocate-foreign-string ,(car bindings)
79 (with-allocate-foreign-strings ,(cdr bindings)
83 (defun handle-error (henv hdbc hstmt)
84 (with-allocate-foreign-strings ((sql-state 256)
85 (error-message #.$SQL_MAX_MESSAGE_LENGTH))
86 (with-foreign-objects ((error-code #.$ODBC-LONG-TYPE)
88 (SQLError henv hdbc hstmt sql-state
89 error-code error-message
90 #.$SQL_MAX_MESSAGE_LENGTH msg-length)
92 (convert-from-foreign-string error-message)
93 (convert-from-foreign-string sql-state)
94 (deref-pointer msg-length :short)
95 (deref-pointer error-code #.$ODBC-LONG-TYPE)))))
97 (defun sql-state (henv hdbc hstmt)
98 (with-allocate-foreign-strings ((sql-state 256)
99 (error-message #.$SQL_MAX_MESSAGE_LENGTH))
100 (with-foreign-objects ((error-code #.$ODBC-LONG-TYPE)
102 (SQLError henv hdbc hstmt sql-state error-code
103 error-message #.$SQL_MAX_MESSAGE_LENGTH msg-length)
104 (convert-from-foreign-string sql-state)
105 ;; test this: return a keyword for efficiency
106 ;;(%cstring-to-keyword state)
109 (defmacro with-error-handling ((&key henv hdbc hstmt (print-info t))
110 odbc-call &body body)
111 (let ((result-code (gensym "RC-")))
112 `(let ((,result-code ,odbc-call))
114 ;; Check for allegro v7 & v8 bug with ODBC calls returning
115 ;; 32-bit unsigned ints, not 16-bit signed ints
116 #+(and allegro mswindows)
117 (when (> ,result-code #xFFFF)
118 (warn (format nil "16-bit return bug: result-code #x~X for expression ~S"
119 ,result-code (quote ,odbc-call)))
120 (setq ,result-code (logand ,result-code #xFFFF))
121 (when (> ,result-code #x7FFF)
122 (setq ,result-code (- ,result-code #x10000))))
126 (progn ,result-code ,@body))
127 (#.$SQL_SUCCESS_WITH_INFO
129 (multiple-value-bind (error-message sql-state)
130 (handle-error (or ,henv +null-handle-ptr+)
131 (or ,hdbc +null-handle-ptr+)
132 (or ,hstmt +null-handle-ptr+))
134 (format *info-output* "[ODBC info ~A] ~A state: ~A"
135 ,result-code error-message
137 (progn ,result-code ,@body))
138 (#.$SQL_INVALID_HANDLE
140 'clsql-sys:sql-database-error
141 :message "ODBC: Invalid handle"))
142 (#.$SQL_STILL_EXECUTING
144 'clsql-sys:sql-temporary-error
145 :message "ODBC: Still executing"))
147 (multiple-value-bind (error-message sql-state)
148 (handle-error (or ,henv +null-handle-ptr+)
149 (or ,hdbc +null-handle-ptr+)
150 (or ,hstmt +null-handle-ptr+))
152 'clsql-sys:sql-database-error
153 :message error-message
154 :secondary-error-id sql-state)))
155 (#.$SQL_NO_DATA_FOUND
156 (progn ,result-code ,@body))
157 ;; work-around for Allegro 7.0beta AMD64 which returns negative numbers
159 (multiple-value-bind (error-message sql-state)
160 (handle-error (or ,henv +null-handle-ptr+)
161 (or ,hdbc +null-handle-ptr+)
162 (or ,hstmt +null-handle-ptr+))
164 'clsql-sys:sql-database-error
165 :message error-message
166 :secondary-error-id sql-state))
168 (progn ,result-code ,@body))))))
170 (defun %new-environment-handle ()
172 (with-foreign-object (phenv 'sql-handle)
175 (SQLAllocHandle $SQL_HANDLE_ENV +null-handle-ptr+ phenv)
176 (deref-pointer phenv 'sql-handle)))))
177 (%set-attr-odbc-version henv $SQL_OV_ODBC3)
181 (defun %sql-free-environment (henv)
186 (defun %new-db-connection-handle (henv)
187 (with-foreign-object (phdbc 'sql-handle)
188 (setf (deref-pointer phdbc 'sql-handle) +null-handle-ptr+)
191 (SQLAllocHandle $SQL_HANDLE_DBC henv phdbc)
192 (deref-pointer phdbc 'sql-handle))))
194 (defun %free-statement (hstmt option)
202 (:unbind $SQL_UNBIND)
203 (:reset $SQL_RESET_PARAMS)))))
205 (defmacro with-statement-handle ((hstmt hdbc) &body body)
206 `(let ((,hstmt (%new-statement-handle ,hdbc)))
209 (%free-statement ,hstmt :drop))))
211 ;; functional interface
213 (defun %sql-connect (hdbc server uid pwd)
214 (with-cstrings ((server-ptr server)
219 (SQLConnect hdbc server-ptr $SQL_NTS uid-ptr
220 $SQL_NTS pwd-ptr $SQL_NTS))))
222 (defun %sql-driver-connect (hdbc connection-string completion window-handle)
223 (with-cstring (connection-ptr connection-string)
224 (with-allocate-foreign-string (completed-connection-string-ptr $SQL_MAX_CONN_OUT)
225 (with-foreign-object (completed-connection-length :short)
228 (SQLDriverConnect hdbc
231 connection-ptr $SQL_NTS
232 completed-connection-string-ptr $SQL_MAX_CONN_OUT
233 completed-connection-length
236 (defun %disconnect (hdbc)
242 (SQLFreeHandle $SQL_HANDLE_DBC hdbc))))
244 (defun %commit (henv hdbc)
246 (:henv henv :hdbc hdbc)
248 henv hdbc $SQL_COMMIT)))
250 (defun %rollback (henv hdbc)
252 (:henv henv :hdbc hdbc)
254 henv hdbc $SQL_ROLLBACK)))
256 ; col-nr is zero-based in Lisp but 1 based in sql
257 ; col-nr = :bookmark retrieves a bookmark.
258 (defun %bind-column (hstmt column-nr c-type data-ptr precision out-len-ptr)
262 (if (eq column-nr :bookmark) 0 (1+ column-nr))
263 c-type data-ptr precision out-len-ptr)))
265 ; parameter-nr is zero-based in Lisp
266 (defun %sql-bind-parameter (hstmt parameter-nr parameter-type c-type
267 sql-type precision scale data-ptr
268 max-value out-len-ptr)
271 (SQLBindParameter hstmt (1+ parameter-nr)
272 parameter-type ;$SQL_PARAM_INPUT
274 sql-type ;$SQL_VARCHAR
275 precision ;(1- (length str))
279 out-len-ptr ;#.+null-ptr+
282 (defun %sql-fetch (hstmt)
287 (defun %new-statement-handle (hdbc)
288 (let ((statement-handle
289 (with-foreign-object (phstmt 'sql-handle)
292 (SQLAllocHandle $SQL_HANDLE_STMT hdbc phstmt)
293 (deref-pointer phstmt 'sql-handle)))))
294 (if (uffi:null-pointer-p statement-handle)
295 (error 'clsql:sql-database-error :message "Received null statement handle.")
298 (defun %sql-get-info (hdbc info-type)
300 ;; those return string
301 ((#.$SQL_ACCESSIBLE_PROCEDURES
302 #.$SQL_ACCESSIBLE_TABLES
304 #.$SQL_DATA_SOURCE_NAME
305 #.$SQL_DATA_SOURCE_READ_ONLY
309 #.$SQL_DRIVER_ODBC_VER
311 #.$SQL_EXPRESSIONS_IN_ORDERBY
312 #.$SQL_IDENTIFIER_QUOTE_CHAR
314 #.$SQL_LIKE_ESCAPE_CLAUSE
315 #.$SQL_MAX_ROW_SIZE_INCLUDES_LONG
316 #.$SQL_MULT_RESULT_SETS
317 #.$SQL_MULTIPLE_ACTIVE_TXN
318 #.$SQL_NEED_LONG_DATA_LEN
319 #.$SQL_ODBC_SQL_OPT_IEF
321 #.$SQL_ORDER_BY_COLUMNS_IN_SELECT
324 #.$SQL_PROCEDURE_TERM
326 #.$SQL_QUALIFIER_NAME_SEPARATOR
327 #.$SQL_QUALIFIER_TERM
329 #.$SQL_SEARCH_PATTERN_ESCAPE
331 #.$SQL_SPECIAL_CHARACTERS
334 (with-allocate-foreign-string (info-ptr 1024)
335 (with-foreign-object (info-length-ptr :short)
338 (SQLGetInfo hdbc info-type info-ptr 1023 info-length-ptr)
339 (convert-from-foreign-string info-ptr)))))
340 ;; those returning a word
341 ((#.$SQL_ACTIVE_CONNECTIONS
342 #.$SQL_ACTIVE_STATEMENTS
343 #.$SQL_CONCAT_NULL_BEHAVIOR
344 #.$SQL_CORRELATION_NAME
345 #.$SQL_CURSOR_COMMIT_BEHAVIOR
346 #.$SQL_CURSOR_ROLLBACK_BEHAVIOR
347 #.$SQL_MAX_COLUMN_NAME_LEN
348 #.$SQL_MAX_COLUMNS_IN_GROUP_BY
349 #.$SQL_MAX_COLUMNS_IN_INDEX
350 #.$SQL_MAX_COLUMNS_IN_ORDER_BY
351 #.$SQL_MAX_COLUMNS_IN_SELECT
352 #.$SQL_MAX_COLUMNS_IN_TABLE
353 #.$SQL_MAX_CURSOR_NAME_LEN
354 #.$SQL_MAX_OWNER_NAME_LEN
355 #.$SQL_MAX_PROCEDURE_NAME_LEN
356 #.$SQL_MAX_QUALIFIER_NAME_LEN
357 #.$SQL_MAX_TABLE_NAME_LEN
358 #.$SQL_MAX_TABLES_IN_SELECT
359 #.$SQL_MAX_USER_NAME_LEN
360 #.$SQL_NON_NULLABLE_COLUMNS
361 #.$SQL_NULL_COLLATION
362 #.$SQL_ODBC_API_CONFORMANCE
363 #.$SQL_ODBC_SAG_CLI_CONFORMANCE
364 #.$SQL_ODBC_SQL_CONFORMANCE
365 #.$SQL_QUALIFIER_LOCATION
366 #.$SQL_QUOTED_IDENTIFIER_CASE
368 (with-foreign-objects ((info-ptr :short)
369 (info-length-ptr :short))
377 (deref-pointer info-ptr :short)))
379 ;; those returning a long bitmask
381 #.$SQL_BOOKMARK_PERSISTENCE
382 #.$SQL_CONVERT_BIGINT
383 #.$SQL_CONVERT_BINARY
387 #.$SQL_CONVERT_DECIMAL
388 #.$SQL_CONVERT_DOUBLE
390 #.$SQL_CONVERT_INTEGER
391 #.$SQL_CONVERT_LONGVARCHAR
392 #.$SQL_CONVERT_NUMERIC
394 #.$SQL_CONVERT_SMALLINT
396 #.$SQL_CONVERT_TIMESTAMP
397 #.$SQL_CONVERT_TINYINT
398 #.$SQL_CONVERT_VARBINARY
399 #.$SQL_CONVERT_VARCHAR
400 #.$SQL_CONVERT_LONGVARBINARY
401 #.$SQL_CONVERT_FUNCTIONS
402 #.$SQL_FETCH_DIRECTION
404 #.$SQL_GETDATA_EXTENSIONS
406 #.$SQL_MAX_INDEX_SIZE
408 #.$SQL_MAX_STATEMENT_LEN
409 #.$SQL_NUMERIC_FUNCTIONS
411 #.$SQL_POS_OPERATIONS
412 #.$SQL_POSITIONED_STATEMENTS
413 #.$SQL_QUALIFIER_USAGE
414 #.$SQL_SCROLL_CONCURRENCY
415 #.$SQL_SCROLL_OPTIONS
416 #.$SQL_STATIC_SENSITIVITY
417 #.$SQL_STRING_FUNCTIONS
419 #.$SQL_SYSTEM_FUNCTIONS
420 #.$SQL_TIMEDATE_ADD_INTERVALS
421 #.$SQL_TIMEDATE_DIFF_INTERVALS
422 #.$SQL_TIMEDATE_FUNCTIONS
423 #.$SQL_TXN_ISOLATION_OPTION
425 (with-foreign-objects ((info-ptr #.$ODBC-LONG-TYPE)
426 (info-length-ptr :short))
434 (deref-pointer info-ptr #.$ODBC-LONG-TYPE)))
436 ;; those returning a long integer
437 ((#.$SQL_DEFAULT_TXN_ISOLATION
443 #.$SQL_IDENTIFIER_CASE
444 #.$SQL_MAX_BINARY_LITERAL_LEN
445 #.$SQL_MAX_CHAR_LITERAL_LEN
446 #.$SQL_ACTIVE_ENVIRONMENTS
448 (with-foreign-objects ((info-ptr #.$ODBC-LONG-TYPE)
449 (info-length-ptr :short))
452 (SQLGetInfo hdbc info-type info-ptr 255 info-length-ptr)
453 (deref-pointer info-ptr #.$ODBC-LONG-TYPE))))))
455 (defun %sql-exec-direct (sql hstmt henv hdbc)
456 (with-cstring (sql-ptr sql)
458 (:hstmt hstmt :henv henv :hdbc hdbc)
459 (SQLExecDirect hstmt sql-ptr $SQL_NTS))))
461 (defun %sql-cancel (hstmt)
466 (defun %sql-execute (hstmt)
471 (defun result-columns-count (hstmt)
472 (with-foreign-objects ((columns-nr-ptr :short))
473 (with-error-handling (:hstmt hstmt)
474 (SQLNumResultCols hstmt columns-nr-ptr)
475 (deref-pointer columns-nr-ptr :short))))
477 (defun result-rows-count (hstmt)
478 (with-foreign-objects ((row-count-ptr #.$ODBC-LONG-TYPE))
479 (with-error-handling (:hstmt hstmt)
480 (SQLRowCount hstmt row-count-ptr)
481 (deref-pointer row-count-ptr #.$ODBC-LONG-TYPE))))
483 ;; column counting is 1-based
484 (defun %describe-column (hstmt column-nr)
485 (with-allocate-foreign-string (column-name-ptr 256)
486 (with-foreign-objects ((column-name-length-ptr :short)
487 (column-sql-type-ptr :short)
488 (column-precision-ptr #.$ODBC-ULONG-TYPE)
489 (column-scale-ptr :short)
490 (column-nullable-p-ptr :short))
491 (with-error-handling (:hstmt hstmt)
492 (SQLDescribeCol hstmt column-nr column-name-ptr 256
493 column-name-length-ptr
497 column-nullable-p-ptr)
499 (convert-from-foreign-string column-name-ptr)
500 (deref-pointer column-sql-type-ptr :short)
501 (deref-pointer column-precision-ptr #.$ODBC-ULONG-TYPE)
502 (deref-pointer column-scale-ptr :short)
503 (deref-pointer column-nullable-p-ptr :short))))))
505 ;; parameter counting is 1-based
506 ;; this function isn't used, which is good because FreeTDS dosn't support it.
507 (defun %describe-parameter (hstmt parameter-nr)
508 (with-foreign-objects ((column-sql-type-ptr :short)
509 (column-precision-ptr #.$ODBC-ULONG-TYPE)
510 (column-scale-ptr :short)
511 (column-nullable-p-ptr :short))
514 (SQLDescribeParam hstmt parameter-nr
518 column-nullable-p-ptr)
520 (deref-pointer column-sql-type-ptr :short)
521 (deref-pointer column-precision-ptr #.$ODBC-ULONG-TYPE)
522 (deref-pointer column-scale-ptr :short)
523 (deref-pointer column-nullable-p-ptr :short)))))
525 (defun %column-attributes (hstmt column-nr descriptor-type)
526 (with-allocate-foreign-string (descriptor-info-ptr 256)
527 (with-foreign-objects ((descriptor-length-ptr :short)
528 (numeric-descriptor-ptr #.$ODBC-LONG-TYPE))
531 (SQLColAttributes hstmt column-nr descriptor-type descriptor-info-ptr
532 256 descriptor-length-ptr
533 numeric-descriptor-ptr)
535 (convert-from-foreign-string descriptor-info-ptr)
536 (deref-pointer numeric-descriptor-ptr #.$ODBC-LONG-TYPE))))))
538 (defun %prepare-describe-columns (hstmt table-qualifier table-owner
539 table-name column-name)
540 (with-cstrings ((table-qualifier-ptr table-qualifier)
541 (table-owner-ptr table-owner)
542 (table-name-ptr table-name)
543 (column-name-ptr column-name))
547 table-qualifier-ptr (length table-qualifier)
548 table-owner-ptr (length table-owner)
549 table-name-ptr (length table-name)
550 column-name-ptr (length column-name)))))
552 (defun %describe-columns (hdbc table-qualifier table-owner
553 table-name column-name)
554 (with-statement-handle (hstmt hdbc)
555 (%prepare-describe-columns hstmt table-qualifier table-owner
556 table-name column-name)
557 (fetch-all-rows hstmt)))
559 (defun %sql-data-sources (henv &key (direction :first))
560 (with-allocate-foreign-strings ((name-ptr (1+ $SQL_MAX_DSN_LENGTH))
561 (description-ptr 1024))
562 (with-foreign-objects ((name-length-ptr :short)
563 (description-length-ptr :short))
564 (let ((res (with-error-handling
568 (:first $SQL_FETCH_FIRST)
569 (:next $SQL_FETCH_NEXT))
571 (1+ $SQL_MAX_DSN_LENGTH)
575 description-length-ptr))))
576 (when (= res $SQL_NO_DATA_FOUND)
578 (convert-from-foreign-string name-ptr)
579 (convert-from-foreign-string description-ptr)))))))
583 (defun sql-to-c-type (sql-type)
585 ;; Added -10 for MSSQL ntext type and -11 for nvarchar
586 ((#.$SQL_CHAR #.$SQL_VARCHAR #.$SQL_LONGVARCHAR
587 #.$SQL_NUMERIC #.$sql_decimal -8 -9 -10 -11) $SQL_C_CHAR)
588 (#.$SQL_INTEGER $SQL_C_SLONG)
589 (#.$SQL_BIGINT $SQL_C_SBIGINT)
590 (#.$SQL_SMALLINT $SQL_C_SSHORT)
591 (#.$SQL_DOUBLE $SQL_C_DOUBLE)
592 (#.$SQL_FLOAT $SQL_C_DOUBLE)
593 (#.$SQL_REAL $SQL_C_FLOAT)
594 (#.$SQL_DATE $SQL_C_DATE)
595 (#.$SQL_TIME $SQL_C_TIME)
596 (#.$SQL_TIMESTAMP $SQL_C_TIMESTAMP)
597 (#.$SQL_TYPE_DATE $SQL_C_TYPE_DATE)
598 (#.$SQL_TYPE_TIME $SQL_C_TYPE_TIME)
599 (#.$SQL_TYPE_TIMESTAMP $SQL_C_TYPE_TIMESTAMP)
600 ((#.$SQL_BINARY #.$SQL_VARBINARY #.$SQL_LONGVARBINARY) $SQL_C_BINARY)
601 (#.$SQL_TINYINT $SQL_C_STINYINT)
602 (#.$SQL_BIT $SQL_C_BIT)))
604 (def-type byte-pointer-type (* :byte))
605 (def-type short-pointer-type (* :short))
606 (def-type int-pointer-type (* :int))
607 (def-type long-pointer-type (* #.$ODBC-LONG-TYPE))
608 (def-type big-pointer-type (* #.$ODBC-BIG-TYPE))
609 (def-type float-pointer-type (* :float))
610 (def-type double-pointer-type (* :double))
611 (def-type string-pointer-type (* :unsigned-char))
613 (defun get-cast-byte (ptr)
614 (locally (declare (type byte-pointer-type ptr))
615 (deref-pointer ptr :byte)))
617 (defun get-cast-short (ptr)
618 (locally (declare (type short-pointer-type ptr))
619 (deref-pointer ptr :short)))
621 (defun get-cast-int (ptr)
622 (locally (declare (type int-pointer-type ptr))
623 (deref-pointer ptr :int)))
625 (defun get-cast-long (ptr)
626 (locally (declare (type long-pointer-type ptr))
627 (deref-pointer ptr #.$ODBC-LONG-TYPE)))
629 (defun get-cast-big (ptr)
630 (locally (declare (type big-pointer-type ptr))
631 (deref-pointer ptr #.$ODBC-BIG-TYPE)))
633 (defun get-cast-single-float (ptr)
634 (locally (declare (type float-pointer-type ptr))
635 (deref-pointer ptr :float)))
637 (defun get-cast-double-float (ptr)
638 (locally (declare (type double-pointer-type ptr))
639 (deref-pointer ptr :double)))
641 (defun get-cast-foreign-string (ptr)
642 (locally (declare (type string-pointer-type ptr))
643 (convert-from-foreign-string ptr)))
645 (defun get-cast-binary (ptr len format)
646 "FORMAT is one of :unsigned-byte-vector, :bit-vector (:string, :hex-string)"
647 (with-cast-pointer (casted ptr :unsigned-byte)
649 (:unsigned-byte-vector
650 (let ((vector (make-array len :element-type '(unsigned-byte 8))))
652 (setf (aref vector i)
653 (deref-array casted '(:array :unsigned-byte) i)))
656 (let ((vector (make-array (ash len 3) :element-type 'bit)))
658 (let ((byte (deref-array casted '(:array :byte) i)))
660 (setf (bit vector (+ (ash i 3) j))
661 (logand (ash byte (- j 7)) 1)))))
665 (defun read-data (data-ptr c-type sql-type out-len-ptr result-type)
666 (declare (type long-ptr-type out-len-ptr))
667 (let* ((out-len (get-cast-long out-len-ptr))
669 (cond ((= out-len $SQL_NULL_DATA) *null*)
672 ;; SQL extended datatypes
673 (#.$SQL_TINYINT (get-cast-byte data-ptr))
674 (#.$SQL_C_STINYINT (get-cast-byte data-ptr)) ;; ?
675 (#.$SQL_C_SSHORT (get-cast-short data-ptr)) ;; ?
676 (#.$SQL_SMALLINT (get-cast-short data-ptr)) ;; ??
677 (#.$SQL_INTEGER (get-cast-int data-ptr))
678 (#.$SQL_BIGINT (get-cast-big data-ptr))
679 ;; TODO: Change this to read in rationals instead of doubles
680 ((#.$SQL_DECIMAL #.$SQL_NUMERIC)
681 (let* ((*read-base* 10)
682 (*read-default-float-format* 'double-float)
683 (str (get-cast-foreign-string data-ptr)))
684 (read-from-string str)))
685 (#.$SQL_BIT (get-cast-byte data-ptr))
688 ((#.$SQL_C_DATE #.$SQL_C_TYPE_DATE)
689 (funcall *time-format* (date-to-clsql-time data-ptr)))
690 ((#.$SQL_C_TIME #.$SQL_C_TYPE_TIME)
691 (funcall *time-format* (time-to-clsql-time data-ptr)))
692 ((#.$SQL_C_TIMESTAMP #.$SQL_C_TYPE_TIMESTAMP)
693 (funcall *time-format* (timestamp-to-clsql-time data-ptr)))
695 (get-cast-int data-ptr))
697 (get-cast-single-float data-ptr))
699 (get-cast-double-float data-ptr))
701 (get-cast-long data-ptr))
703 (#.$SQL_C_BIT ; encountered only in Access
704 (get-cast-byte data-ptr))
706 (get-cast-binary data-ptr out-len *binary-format*))
707 ((#.$SQL_C_SSHORT #.$SQL_C_STINYINT) ; LMH short ints
708 (get-cast-short data-ptr)) ; LMH
709 (#.$SQL_C_SBIGINT (get-cast-big data-ptr))
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_SBIGINT (uffi:allocate-foreign-object #.$ODBC-BIG-TYPE))
750 (#.$SQL_C_SSHORT (uffi:allocate-foreign-object :short))
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))
882 (defun read-data-in-chunks (hstmt column-nr data-ptr c-type sql-type
883 out-len-ptr result-type)
884 (declare (type long-ptr-type out-len-ptr)
885 (ignore result-type))
887 (let* ((res (%sql-get-data hstmt column-nr c-type data-ptr
888 +max-precision+ out-len-ptr))
889 (out-len (get-cast-long out-len-ptr))
890 (result (if (equal out-len #.$SQL_NULL_DATA)
891 (return-from read-data-in-chunks *null*)
893 ;;this isn't the most efficient way of doing it:
894 ;;the foreign string gets copied to lisp, then
895 ;;that is copied into the final string. However,
896 ;;the previous impl that tried to copy one
897 ;;character over at a time failed miserably on
898 ;;multibyte characters.
900 ;;In the face of multibyte characters, the out-len
901 ;;tells us the length in bytes but that doesn't
902 ;;particularly help us here in allocating a lisp
903 ;;array. So our best strategy is to just let the
904 ;;foreign library that's already dealing with
905 ;;encodings do its thing.
907 (with-output-to-string (str)
908 (loop do (if (= c-type #.$SQL_CHAR)
909 (write-sequence (get-cast-foreign-string data-ptr) str)
910 (error 'clsql:sql-database-error
911 :message "wrong type. preliminary."))
912 while (and (= res $SQL_SUCCESS_WITH_INFO)
913 (equal (sql-state +null-handle-ptr+ +null-handle-ptr+ hstmt)
915 do (setf res (%sql-get-data hstmt column-nr c-type data-ptr
916 +max-precision+ out-len-ptr)))))))
918 ;; reset the out length for the next row
919 (setf (deref-pointer out-len-ptr #.$ODBC-LONG-TYPE) #.$SQL_NO_TOTAL)
920 (if (= sql-type $SQL_DECIMAL)
921 (let ((*read-base* 10))
922 (read-from-string result))
926 (def-type c-timestamp-ptr-type (* (:struct sql-c-timestamp)))
927 (def-type c-time-ptr-type (* (:struct sql-c-time)))
928 (def-type c-date-ptr-type (* (:struct sql-c-date)))
930 (defun timestamp-to-clsql-time (ptr)
931 (declare (type c-timestamp-ptr-type ptr))
933 :second (get-slot-value ptr 'sql-c-timestamp 'second)
934 :minute (get-slot-value ptr 'sql-c-timestamp 'minute)
935 :hour (get-slot-value ptr 'sql-c-timestamp 'hour)
936 :day (get-slot-value ptr 'sql-c-timestamp 'day)
937 :month (get-slot-value ptr 'sql-c-timestamp 'month)
938 :year (get-slot-value ptr 'sql-c-timestamp 'year)
939 :usec (let ((frac (get-slot-value ptr 'sql-c-timestamp 'fraction)))
940 (if frac (/ frac 1000) 0))))
942 (defun universal-time-to-timestamp (time &optional (fraction 0))
943 "TODO: Dead function?"
944 (multiple-value-bind (sec min hour day month year)
945 (decode-universal-time time)
946 (let ((ptr (allocate-foreign-object 'sql-c-timestamp)))
947 (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
948 (get-slot-value ptr 'sql-c-timestamp 'minute) min
949 (get-slot-value ptr 'sql-c-timestamp 'hour) hour
950 (get-slot-value ptr 'sql-c-timestamp 'day) day
951 (get-slot-value ptr 'sql-c-timestamp 'month) month
952 (get-slot-value ptr 'sql-c-timestamp 'year) year
953 (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
956 (defun %put-timestamp (ptr time &optional (fraction 0))
957 "TODO: Dead function?"
958 (declare (type c-timestamp-ptr-type ptr))
959 (multiple-value-bind (sec min hour day month year)
960 (decode-universal-time time)
961 (setf (get-slot-value ptr 'sql-c-timestamp 'second) sec
962 (get-slot-value ptr 'sql-c-timestamp 'minute) min
963 (get-slot-value ptr 'sql-c-timestamp 'hour) hour
964 (get-slot-value ptr 'sql-c-timestamp 'day) day
965 (get-slot-value ptr 'sql-c-timestamp 'month) month
966 (get-slot-value ptr 'sql-c-timestamp 'year) year
967 (get-slot-value ptr 'sql-c-timestamp 'fraction) fraction)
970 (defun date-to-clsql-time (ptr)
971 (declare (type c-date-ptr-type ptr))
973 :second 0 :minute 0 :hour 0
974 :day (get-slot-value ptr 'sql-c-timestamp 'day)
975 :month (get-slot-value ptr 'sql-c-timestamp 'month)
976 :year (get-slot-value ptr 'sql-c-timestamp 'year)))
978 (defun time-to-clsql-time (ptr)
979 (declare (type c-time-ptr-type ptr))
981 :second (get-slot-value ptr 'sql-c-timestamp 'second)
982 :minute (get-slot-value ptr 'sql-c-timestamp 'minute)
983 :hour (get-slot-value ptr 'sql-c-timestamp 'hour)))
988 (defun %set-attr-odbc-version (henv version)
989 (with-error-handling (:henv henv)
990 ;;note that we are passing version as an integer that happens to be
991 ;;stuffed into a pointer.
992 ;;http://msdn.microsoft.com/en-us/library/ms709285%28v=VS.85%29.aspx
993 (SQLSetEnvAttr henv $SQL_ATTR_ODBC_VERSION
994 (make-pointer version :void) 0)))
996 (defun %list-tables (hstmt)
997 (with-error-handling (:hstmt hstmt)
998 (SQLTables hstmt +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0 +null-ptr+ 0)))
1000 (defun %table-statistics (table hstmt &key unique (ensure t)
1001 &aux (table (princ-to-string
1002 (clsql-sys::unescaped-database-identifier table))))
1003 (with-cstrings ((table-cs table))
1004 (with-error-handling (:hstmt hstmt)
1010 (if unique $SQL_INDEX_UNIQUE $SQL_INDEX_ALL)
1011 (if ensure $SQL_ENSURE $SQL_QUICK)))))
1013 (defun %list-data-sources (henv)
1014 (let ((results nil))
1015 (with-foreign-strings ((dsn-ptr (1+ $SQL_MAX_DSN_LENGTH))
1017 (with-foreign-objects ((dsn-len :short)
1019 (let ((res (with-error-handling (:henv henv)
1020 (SQLDataSources henv $SQL_FETCH_FIRST dsn-ptr
1021 (1+ $SQL_MAX_DSN_LENGTH)
1022 dsn-len desc-ptr 256 desc-len))))
1023 (when (or (eql res $SQL_SUCCESS)
1024 (eql res $SQL_SUCCESS_WITH_INFO))
1025 (push (convert-from-foreign-string dsn-ptr) results))
1027 (do ((res (with-error-handling (:henv henv)
1028 (SQLDataSources henv $SQL_FETCH_NEXT dsn-ptr
1029 (1+ $SQL_MAX_DSN_LENGTH)
1030 dsn-len desc-ptr 256 desc-len))
1031 (with-error-handling (:henv henv)
1032 (SQLDataSources henv $SQL_FETCH_NEXT dsn-ptr
1033 (1+ $SQL_MAX_DSN_LENGTH)
1034 dsn-len desc-ptr 256 desc-len))))
1035 ((not (or (eql res $SQL_SUCCESS)
1036 (eql res $SQL_SUCCESS_WITH_INFO))))
1037 (push (convert-from-foreign-string dsn-ptr) results)))))
1038 (nreverse results)))