r10383: 06 Apr 2005 Kevin Rosenberg <kevin@rosenberg.net>
[clsql.git] / db-mysql / mysql-sql.lisp
1 ;;;; -*- Mode: LISP; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          mysql-sql.lisp
6 ;;;; Purpose:       High-level MySQL interface using UFFI
7 ;;;; Date Started:  Feb 2002
8 ;;;;
9 ;;;; $Id$
10 ;;;;
11 ;;;; CLSQL users are granted the rights to distribute and use this software
12 ;;;; as governed by the terms of the Lisp Lesser GNU Public License
13 ;;;; (http://opensource.franz.com/preamble.html), also known as the LLGPL.
14 ;;;; *************************************************************************
15
16 (defpackage #:clsql-mysql
17     (:use #:common-lisp #:clsql-sys #:mysql #:clsql-uffi)
18     (:export #:mysql-database)
19     (:documentation "This is the CLSQL interface to MySQL."))
20
21 (in-package #:clsql-mysql)
22
23 ;;; Field conversion functions
24
25 (defun result-field-names (num-fields res-ptr)
26   (declare (fixnum num-fields))
27   (let ((names '())
28         (field-vec (mysql-fetch-fields res-ptr)))
29     (dotimes (i num-fields)
30       (declare (fixnum i))
31       (let* ((field (uffi:deref-array field-vec '(:array mysql-field) i))
32              (name (uffi:convert-from-foreign-string
33                     (uffi:get-slot-value field 'mysql-field 'mysql::name))))
34         (push name names)))
35     (nreverse names)))
36
37 (defun make-type-list-for-auto (num-fields res-ptr)
38   (declare (fixnum num-fields))
39   (let ((new-types '())
40         (field-vec (mysql-fetch-fields res-ptr)))
41     (dotimes (i num-fields)
42       (declare (fixnum i))
43       (let* ((field (uffi:deref-array field-vec '(:array mysql-field) i))
44              (flags (uffi:get-slot-value field 'mysql-field 'mysql::flags))
45              (unsigned (plusp (logand flags 32)))
46              (type (uffi:get-slot-value field 'mysql-field 'type)))
47         (push
48          (case type
49            ((#.mysql-field-types#tiny 
50              #.mysql-field-types#short
51              #.mysql-field-types#int24)
52             (if unsigned
53                 :uint32
54               :int32))
55            (#.mysql-field-types#long
56             (if unsigned
57                 :uint
58               :int))
59             (#.mysql-field-types#longlong
60              (if unsigned
61                  :uint64
62                :int64))
63            ((#.mysql-field-types#double
64              #.mysql-field-types#float
65              #.mysql-field-types#decimal)
66             :double)
67            (otherwise
68             t))
69          new-types)))
70     (nreverse new-types)))
71
72 (defun canonicalize-types (types num-fields res-ptr)
73   (when types
74     (let ((auto-list (make-type-list-for-auto num-fields res-ptr)))
75       (cond
76         ((listp types)
77          (canonicalize-type-list types auto-list))
78         ((eq types :auto)
79          auto-list)
80         (t
81          nil)))))
82
83 (defmethod database-initialize-database-type ((database-type (eql :mysql)))
84   t)
85
86 (uffi:def-type mysql-mysql-ptr-def (* mysql-mysql))
87 (uffi:def-type mysql-row-def mysql-row)
88 (uffi:def-type mysql-mysql-res-ptr-def (* mysql-mysql-res))
89
90 (defclass mysql-database (database)
91   ((mysql-ptr :accessor database-mysql-ptr :initarg :mysql-ptr
92               :type mysql-mysql-ptr-def)))
93
94 (defmethod database-type ((database mysql-database))
95   :mysql)
96
97 (defmethod database-name-from-spec (connection-spec (database-type (eql :mysql)))
98   (check-connection-spec connection-spec database-type
99                          (host db user password &optional port))
100   (destructuring-bind (host db user password &optional port) connection-spec
101     (declare (ignore password))
102     (concatenate 'string 
103                  (etypecase host
104                    (null "localhost")
105                    (pathname (namestring host))
106                    (string host))
107                  (if port 
108                      (concatenate 'string
109                                   ":"
110                                   (etypecase port
111                                     (integer (write-to-string port))
112                                     (string port)))
113                      "")
114                  "/" db "/" user)))
115
116 (defmethod database-connect (connection-spec (database-type (eql :mysql)))
117   (check-connection-spec connection-spec database-type
118                          (host db user password &optional port))
119   (destructuring-bind (host db user password &optional port) connection-spec
120     (let ((mysql-ptr (mysql-init (uffi:make-null-pointer 'mysql-mysql)))
121           (socket nil))
122       (if (uffi:null-pointer-p mysql-ptr)
123           (error 'sql-connection-error
124                  :database-type database-type
125                  :connection-spec connection-spec
126                  :error-id (mysql-errno mysql-ptr)
127                  :message (mysql-error-string mysql-ptr))
128         (uffi:with-cstrings ((host-native host)
129                             (user-native user)
130                             (password-native password)
131                             (db-native db)
132                             (socket-native socket))
133           (let ((error-occurred nil))
134             (unwind-protect
135                 (if (uffi:null-pointer-p 
136                      (mysql-real-connect 
137                       mysql-ptr host-native user-native password-native
138                       db-native
139                       (etypecase port
140                         (null 0)
141                         (integer port)
142                         (string (parse-integer port)))
143                       socket-native 0))
144                     (progn
145                       (setq error-occurred t)
146                       (error 'sql-connection-error
147                              :database-type database-type
148                              :connection-spec connection-spec
149                              :error-id (mysql-errno mysql-ptr)
150                              :message (mysql-error-string mysql-ptr)))
151                   (make-instance 'mysql-database
152                     :name (database-name-from-spec connection-spec
153                                                    database-type)
154                     :database-type :mysql
155                     :connection-spec connection-spec
156                     :mysql-ptr mysql-ptr))
157               (when error-occurred (mysql-close mysql-ptr)))))))))
158
159
160 (defmethod database-disconnect ((database mysql-database))
161   (mysql-close (database-mysql-ptr database))
162   (setf (database-mysql-ptr database) nil)
163   t)
164
165
166 (defmethod database-query (query-expression (database mysql-database) 
167                            result-types field-names)
168   (declare (optimize (speed 3) (safety 0) (debug 0) (space 0)))
169   (let ((mysql-ptr (database-mysql-ptr database)))
170     (uffi:with-cstring (query-native query-expression)
171       (if (zerop (mysql-real-query mysql-ptr query-native 
172                                    (length query-expression)))
173           (let ((res-ptr (mysql-use-result mysql-ptr)))
174             (if res-ptr
175                 (unwind-protect
176                      (let ((num-fields (mysql-num-fields res-ptr)))
177                        (declare (fixnum num-fields))
178                        (setq result-types (canonicalize-types 
179                                     result-types num-fields
180                                     res-ptr))
181                        (values
182                         (loop for row = (mysql-fetch-row res-ptr)
183                               for lengths = (mysql-fetch-lengths res-ptr)
184                               until (uffi:null-pointer-p row)
185                               collect
186                               (do* ((rlist (make-list num-fields))
187                                     (i 0 (1+ i))
188                                     (pos rlist (cdr pos)))
189                                    ((= i num-fields) rlist)
190                                 (declare (fixnum i))
191                                 (setf (car pos)  
192                                       (convert-raw-field
193                                        (uffi:deref-array row '(:array
194                                                                (* :unsigned-char))
195                                                          i)
196                                        result-types i
197                                        (uffi:deref-array lengths '(:array :unsigned-long)
198                                                          i)))))
199                         (when field-names
200                           (result-field-names num-fields res-ptr))))
201                   (mysql-free-result res-ptr))
202                 (error 'sql-database-data-error
203                        :database database
204                        :expression query-expression
205                        :error-id (mysql-errno mysql-ptr)
206                        :message (mysql-error-string mysql-ptr))))
207           (error 'sql-database-data-error
208                  :database database
209                  :expression query-expression
210                  :error-id (mysql-errno mysql-ptr)
211                  :message (mysql-error-string mysql-ptr))))))
212
213 (defmethod database-execute-command (sql-expression (database mysql-database))
214   (uffi:with-cstring (sql-native sql-expression)
215     (let ((mysql-ptr (database-mysql-ptr database)))
216       (declare (type mysql-mysql-ptr-def mysql-ptr))
217       (if (zerop (mysql-real-query mysql-ptr sql-native 
218                                    (length sql-expression)))
219           t
220         (error 'sql-database-data-error
221                :database database
222                :expression sql-expression
223                :error-id (mysql-errno mysql-ptr)
224                :message (mysql-error-string mysql-ptr))))))
225
226
227 (defstruct mysql-result-set 
228   (res-ptr (uffi:make-null-pointer 'mysql-mysql-res) :type mysql-mysql-res-ptr-def)
229   (types nil :type list)
230   (num-fields 0 :type fixnum)
231   (full-set nil :type boolean))
232
233
234 (defmethod database-query-result-set ((query-expression string)
235                                       (database mysql-database)
236                                       &key full-set result-types)
237   (uffi:with-cstring (query-native query-expression)
238     (let ((mysql-ptr (database-mysql-ptr database)))
239      (declare (type mysql-mysql-ptr-def mysql-ptr))
240       (if (zerop (mysql-real-query mysql-ptr query-native
241                                    (length query-expression)))
242           (let ((res-ptr (if full-set
243                              (mysql-store-result mysql-ptr)
244                            (mysql-use-result mysql-ptr))))
245             (declare (type mysql-mysql-res-ptr-def res-ptr))
246             (if (not (uffi:null-pointer-p res-ptr))
247                 (let* ((num-fields (mysql-num-fields res-ptr))
248                        (result-set (make-mysql-result-set
249                                     :res-ptr res-ptr
250                                     :num-fields num-fields
251                                     :full-set full-set
252                                     :types
253                                     (canonicalize-types 
254                                      result-types num-fields
255                                      res-ptr)))) 
256                   (if full-set
257                       (values result-set
258                               num-fields
259                               (mysql-num-rows res-ptr))
260                       (values result-set
261                               num-fields)))
262                 (error 'sql-database-data-error
263                      :database database
264                      :expression query-expression
265                      :error-id (mysql-errno mysql-ptr)
266                      :message (mysql-error-string mysql-ptr))))
267         (error 'sql-database-data-error
268                :database database
269                :expression query-expression
270                :error-id (mysql-errno mysql-ptr)
271                :message (mysql-error-string mysql-ptr))))))
272
273 (defmethod database-dump-result-set (result-set (database mysql-database))
274   (mysql-free-result (mysql-result-set-res-ptr result-set))
275   t)
276
277
278 (defmethod database-store-next-row (result-set (database mysql-database) list)
279   (let* ((res-ptr (mysql-result-set-res-ptr result-set))
280          (row (mysql-fetch-row res-ptr))
281          (lengths (mysql-fetch-lengths res-ptr))
282          (types (mysql-result-set-types result-set)))
283     (declare (type mysql-mysql-res-ptr-def res-ptr)
284              (type mysql-row-def row))
285     (unless (uffi:null-pointer-p row)
286       (loop for i from 0 below (mysql-result-set-num-fields result-set)
287             for rest on list
288             do
289             (setf (car rest) 
290                   (convert-raw-field
291                    (uffi:deref-array row '(:array (* :unsigned-char)) i)
292                    types
293                    i
294                    (uffi:deref-array lengths '(:array :unsigned-long) i))))
295       list)))
296
297
298 ;; Table and attribute introspection
299
300 (defmethod database-list-tables ((database mysql-database) &key (owner nil))
301   (declare (ignore owner))
302   (remove-if #'(lambda (s)
303                  (and (>= (length s) 11)
304                       (string-equal (subseq s 0 11) "_CLSQL_SEQ_")))
305              (mapcar #'car (database-query "SHOW TABLES" database nil nil))))
306     
307 ;; MySQL 4.1 does not support views 
308 (defmethod database-list-views ((database mysql-database)
309                                 &key (owner nil))
310   (declare (ignore owner))
311   nil)
312
313 (defmethod database-list-indexes ((database mysql-database)
314                                   &key (owner nil))
315   (let ((result '()))
316     (dolist (table (database-list-tables database :owner owner) result)
317       (setq result
318         (append (database-list-table-indexes table database :owner owner)
319                 result)))))
320
321 (defmethod database-list-table-indexes (table (database mysql-database)
322                                         &key (owner nil))
323   (declare (ignore owner))
324   (do ((results nil)
325        (rows (database-query 
326               (format nil "SHOW INDEX FROM ~A" (string-upcase table))
327               database nil nil)
328              (cdr rows)))
329       ((null rows) (nreverse results))
330     (let ((col (nth 2 (car rows))))
331       (unless (find col results :test #'string-equal)
332         (push col results)))))
333   
334 (defmethod database-list-attributes ((table string) (database mysql-database)
335                                      &key (owner nil))
336   (declare (ignore owner))
337   (mapcar #'car
338           (database-query
339            (format nil "SHOW COLUMNS FROM ~A" table)
340            database nil nil)))
341
342 (defmethod database-attribute-type (attribute (table string)
343                                     (database mysql-database)
344                                     &key (owner nil))
345   (declare (ignore owner))
346   (let ((row (car (database-query
347                    (format nil
348                            "SHOW COLUMNS FROM ~A LIKE '~A'" table attribute)
349                    database nil nil))))
350     (let* ((raw-type (second row))
351            (null (third row))
352            (start-length (position #\( raw-type))
353            (type (if start-length
354                      (subseq raw-type 0 start-length)
355                      raw-type))
356            (length (when start-length
357                      (parse-integer (subseq raw-type (1+ start-length))
358                                     :junk-allowed t))))
359       (when type
360         (values (ensure-keyword type) length nil (if (string-equal null "YES") 1 0))))))
361
362 ;;; Sequence functions
363
364 (defun %sequence-name-to-table (sequence-name)
365   (concatenate 'string "_CLSQL_SEQ_" (sql-escape sequence-name)))
366
367 (defun %table-name-to-sequence-name (table-name)
368   (and (>= (length table-name) 11)
369        (string-equal (subseq table-name 0 11) "_CLSQL_SEQ_")
370        (subseq table-name 11)))
371
372 (defmethod database-create-sequence (sequence-name
373                                      (database mysql-database))
374   (let ((table-name (%sequence-name-to-table sequence-name)))
375     (database-execute-command
376      (concatenate 'string "CREATE TABLE " table-name
377                   " (id int NOT NULL PRIMARY KEY AUTO_INCREMENT)")
378      database)
379     (database-execute-command 
380      (concatenate 'string "INSERT INTO " table-name
381                   " VALUES (-1)")
382      database)))
383
384 (defmethod database-drop-sequence (sequence-name
385                                    (database mysql-database))
386   (database-execute-command
387    (concatenate 'string "DROP TABLE " (%sequence-name-to-table sequence-name)) 
388    database))
389
390 (defmethod database-list-sequences ((database mysql-database)
391                                     &key (owner nil))
392   (declare (ignore owner))
393   (mapcan #'(lambda (s)
394               (let ((sn (%table-name-to-sequence-name (car s))))
395                 (and sn (list sn))))
396           (database-query "SHOW TABLES" database nil nil)))
397
398 (defmethod database-set-sequence-position (sequence-name
399                                            (position integer)
400                                            (database mysql-database))
401   (database-execute-command
402    (format nil "UPDATE ~A SET id=~A" (%sequence-name-to-table sequence-name)
403            position)
404    database)
405   (mysql:mysql-insert-id (clsql-mysql::database-mysql-ptr database)))
406
407 (defmethod database-sequence-next (sequence-name (database mysql-database))
408   (without-interrupts
409    (database-execute-command 
410     (concatenate 'string "UPDATE " (%sequence-name-to-table sequence-name)
411                  " SET id=LAST_INSERT_ID(id+1)")
412     database)
413    (mysql:mysql-insert-id (clsql-mysql::database-mysql-ptr database))))
414
415 (defmethod database-sequence-last (sequence-name (database mysql-database))
416   (without-interrupts
417     (caar (database-query 
418            (concatenate 'string "SELECT id from " 
419                         (%sequence-name-to-table sequence-name))
420            database :auto nil))))
421
422 (defmethod database-create (connection-spec (type (eql :mysql)))
423   (destructuring-bind (host name user password &optional port) connection-spec
424     (multiple-value-bind (output status)
425         (clsql-sys:command-output "mysqladmin create -u~A -p~A -h~A~@[ -P~A~] ~A"
426                                        user password 
427                                        (if host host "localhost")
428                                        port name
429                                        name)
430       (if (or (not (eql 0 status))
431               (and (search "failed" output) (search "error" output)))
432           (error 'sql-database-error
433                  :message 
434                  (format nil "mysql database creation failed with connection-spec ~A."
435                          connection-spec))
436         t))))
437
438 (defmethod database-destroy (connection-spec (type (eql :mysql)))
439   (destructuring-bind (host name user password &optional port) connection-spec
440     (multiple-value-bind (output status)
441         (clsql-sys:command-output "mysqladmin drop -f -u~A -p~A -h~A~@[ -P~A~] ~A"
442                                        user password 
443                                        (if host host "localhost")
444                                        port name)
445       (if (or (not (eql 0 status))
446               (and (search "failed" output) (search "error" output)))
447           (error 'sql-database-error
448                  :message 
449                  (format nil "mysql database deletion failed with connection-spec ~A."
450                          connection-spec))
451         t))))
452
453 (defmethod database-probe (connection-spec (type (eql :mysql)))
454   (when (find (second connection-spec) (database-list connection-spec type)
455               :key #'car :test #'string-equal)
456     t))
457
458 (defmethod database-list (connection-spec (type (eql :mysql)))
459   (destructuring-bind (host name user password &optional port) connection-spec
460     (declare (ignore name))
461     (let ((database (database-connect (list host "mysql" user password port) type)))
462       (unwind-protect
463            (progn
464              (setf (slot-value database 'clsql-sys::state) :open)
465              (mapcar #'car (database-query "show databases" database :auto nil)))
466         (progn
467           (database-disconnect database)
468           (setf (slot-value database 'clsql-sys::state) :closed))))))
469
470
471 ;;; Prepared statements
472
473 (defclass mysql-stmt ()
474   ((database :initarg :database :reader database)
475    (stmt :initarg :stmt :accessor stmt)
476    (input-bind :initarg :input-bind :reader input-bind)
477    (output-bind :initarg :output-bind :reader output-bind)
478    (types :initarg :types :reader types)
479    (result-set :initarg :result-set :reader result-set)
480    (num-fields :initarg :num-fields :reader num-fields)
481    (field-names :initarg :field-names :accessor stmt-field-names)
482    (length-ptr :initarg :length-ptr :reader length-ptr)
483    (is-null-ptr :initarg :is-null-ptr :reader is-null-ptr)
484    (result-types :initarg :result-types :reader result-types)))
485   
486 (defun clsql-type->mysql-type (type)
487   (cond
488     ((in type :null) mysql-field-types#null)
489     ((in type :int :integer) mysql-field-types#long)
490     ((in type :short) mysql-field-types#short)
491     ((in type :bigint) mysql-field-types#longlong)
492     ((in type :float :double :number) mysql-field-types#double)
493     ((and (consp type) (in (car type) :char :string :varchar)) mysql-field-types#var-string)
494     ((or (eq type :blob) (and (consp type) (in (car type) :blob))) mysql-field-types#var-string)
495     (t
496        (error 'sql-user-error 
497               :message 
498               (format nil "Unknown clsql type ~A." type)))))
499
500 #+mysql-client-v4.1
501 (defmethod database-prepare (sql-stmt types (database mysql-database) result-types field-names)
502   (let* ((mysql-ptr (database-mysql-ptr database))
503          (stmt (mysql-stmt-init mysql-ptr)))
504     (when (uffi:null-pointer-p stmt)
505       (error 'sql-database-error
506              :error-id (mysql-errno mysql-ptr)
507              :message (mysql-error-string mysql-ptr)))
508
509     (uffi:with-cstring (native-query sql-stmt)
510       (unless (zerop (mysql-stmt-prepare stmt native-query (length sql-stmt)))
511         (mysql-stmt-close stmt)
512         (error 'sql-database-error
513                :error-id (mysql-errno mysql-ptr)
514                :message (mysql-error-string mysql-ptr))))
515     
516     (unless (= (mysql-stmt-param-count stmt) (length types))
517       (mysql-stmt-close stmt)
518       (error 'sql-database-error
519              :message 
520              (format nil "Mysql param count (~D) does not match number of types (~D)"
521                      (mysql-stmt-param-count stmt) (length types))))
522
523     (let ((rs (mysql-stmt-result-metadata stmt)))
524       (when (uffi:null-pointer-p rs)
525         (warn "mysql_stmt_result_metadata returned NULL")
526         #+nil
527         (mysql-stmt-close stmt)
528         #+nil
529         (error 'sql-database-error
530                :message "mysql_stmt_result_metadata returned NULL"))
531       
532       (let ((input-bind (uffi:allocate-foreign-object 'mysql-bind (length types)))
533             (mysql-types (mapcar 'clsql-type->mysql-type types))
534             field-vec num-fields is-null-ptr output-bind length-ptr)
535         
536         (print 'a)
537         (dotimes (i (length types))
538           (let* ((binding (uffi:deref-array input-bind '(:array mysql-bind) i)))
539             (setf (uffi:get-slot-value binding 'mysql-bind 'mysql::buffer-type) 
540               (nth i mysql-types))
541             (setf (uffi:get-slot-value binding 'mysql-bind 'mysql::buffer-length) 0)))      
542         
543         (print 'b)
544         (unless (uffi:null-pointer-p rs)
545           (setq field-vec (mysql-fetch-fields rs)
546                 num-fields (mysql-num-fields rs)
547                 is-null-ptr (uffi:allocate-foreign-object :byte num-fields)
548                 output-bind (uffi:allocate-foreign-object 'mysql-bind num-fields)
549                 length-ptr (uffi:allocate-foreign-object :unsigned-long num-fields))
550           (dotimes (i num-fields)
551             (declare (fixnum i))
552             (let* ((field (uffi:deref-array field-vec '(:array mysql-field) i))
553                    (type (uffi:get-slot-value field 'mysql-field 'type))
554                    (binding (uffi:deref-array output-bind '(:array mysql-bind) i)))
555               (setf (uffi:get-slot-value binding 'mysql-bind 'mysql::buffer-type) type)
556               
557               (setf (uffi:get-slot-value binding 'mysql-bind 'mysql::buffer-length) 0)
558               #+need-to-allocate-foreign-object-for-this
559               (setf (uffi:get-slot-value binding 'mysql-bind 'mysql::is-null) 
560                 (+ i (uffi:pointer-address is-null-ptr)))
561               #+need-to-allocate-foreign-object-for-this
562               (setf (uffi:get-slot-value binding 'mysql-bind 'length) 
563                 (+ (* i 8) (uffi:pointer-address length-ptr)))
564               
565               (case type
566                 ((#.mysql-field-types#var-string #.mysql-field-types#string
567                   #.mysql-field-types#tiny-blob #.mysql-field-types#blob
568                   #.mysql-field-types#medium-blob #.mysql-field-types#long-blob)
569                  (setf (uffi:get-slot-value binding 'mysql-bind 'mysql::buffer-length) 1024)
570                  (setf (uffi:get-slot-value binding 'mysql-bind 'mysql::buffer)
571                    (uffi:allocate-foreign-object :unsigned-char 1024)))
572                 (#.mysql-field-types#tiny
573                  (setf (uffi:get-slot-value binding 'mysql-bind 'mysql::buffer)
574                    (uffi:allocate-foreign-object :byte)))
575                 (#.mysql-field-types#short
576                  (setf (uffi:get-slot-value binding 'mysql-bind 'mysql::buffer)
577                    (uffi:allocate-foreign-object :short)))
578                 (#.mysql-field-types#long
579                  (setf (uffi:get-slot-value binding 'mysql-bind 'mysql::buffer)
580                    ;; segfaults if supply :int on amd64
581                    (uffi:allocate-foreign-object :long)))
582                 #+64bit
583                 (#.mysql-field-types#longlong
584                  (setf (uffi:get-slot-value binding 'mysql-bind 'mysql::buffer)
585                    (uffi:allocate-foreign-object :long)))
586                 (#.mysql-field-types#float
587                  (setf (uffi:get-slot-value binding 'mysql-bind 'mysql::buffer)
588                    (uffi:allocate-foreign-object :float)))
589                 (#.mysql-field-types#double
590                  (setf (uffi:get-slot-value binding 'mysql-bind 'mysql::buffer)
591                    (uffi:allocate-foreign-object :double)))
592                 ((#.mysql-field-types#time #.mysql-field-types#date
593                   #.mysql-field-types#datetime #.mysql-field-types#timestamp)
594                  (uffi:allocate-foreign-object 'mysql-time))
595                 (t
596                  (error "mysql type ~D not supported." type)))))
597         
598           (unless (zerop (mysql-stmt-bind-result stmt output-bind))
599             (mysql-stmt-close stmt)
600             (error 'sql-database-error
601                    :error-id (mysql-stmt-errno stmt)
602                    :message  (uffi:convert-from-cstring
603                               (mysql-stmt-error stmt)))))
604         
605         (make-instance 'mysql-stmt
606           :database database
607           :stmt stmt
608           :num-fields num-fields
609           :input-bind input-bind
610           :output-bind output-bind
611           :result-set rs
612           :result-types result-types
613           :length-ptr length-ptr
614           :is-null-ptr is-null-ptr
615           :types mysql-types
616           :field-names field-names)))))
617
618 #+mysql-client-v4.1
619 (defmethod database-bind-parameter ((stmt mysql-stmt) position value)
620   ;; FIXME: will need to allocate bind structure. This should probably be
621   ;; done in C since the API is not mature and may change
622   (let ((binding (uffi:deref-array (input-bind stmt) '(:array mysql-bind) (1- position)))
623         (type (nth (1- position) (types stmt))))
624     (setf (uffi:get-slot-value binding 'mysql-bind 'length) 0)
625     (cond
626      ((null value)
627       (when (is-null-ptr stmt)
628         (setf (uffi:deref-array (is-null-ptr stmt) '(:array :byte) (1- position)) 1)))
629      (t
630       (when (is-null-ptr stmt)
631         (setf (uffi:deref-array (is-null-ptr stmt) '(:array :byte) (1- position)) 0))
632       (case type
633         (#.mysql-field-types#long
634          (setf (uffi:get-slot-value binding 'mysql-bind 'mysql::buffer) value))
635         (t
636          (warn "Unknown input bind type ~D." type))
637         )))))
638
639 #+mysql-client-v4.1
640 (defmethod database-run-prepared ((stmt mysql-stmt))
641   (print 'a1)
642   (when (input-bind stmt)
643     (unless (zerop (mysql-stmt-bind-param (stmt stmt) (input-bind stmt)))
644       (error 'sql-database-error
645              :error-id (mysql-stmt-errno (stmt stmt))
646              :message  (uffi:convert-from-cstring
647                         (mysql-stmt-error (stmt stmt))))))
648   (print 'a2)
649   (unless (zerop (mysql-stmt-execute (stmt stmt)))
650     (error 'sql-database-error
651            :error-id (mysql-stmt-errno (stmt stmt))
652            :message  (uffi:convert-from-cstring
653                       (mysql-stmt-error (stmt stmt)))))
654   (print 'a3)
655   (unless (zerop (mysql-stmt-store-result (stmt stmt)))
656     (error 'sql-database-error
657            :error-id (mysql-stmt-errno (stmt stmt))
658            :message  (uffi:convert-from-cstring
659                       (mysql-stmt-error (stmt stmt)))))
660   (database-fetch-prepared-rows stmt))
661
662 #+mysql-client-v4.1
663 (defun database-fetch-prepared-rows (stmt)
664   (do ((rc (mysql-stmt-fetch (stmt stmt)) (mysql-stmt-fetch (stmt stmt)))
665        (num-fields (num-fields stmt))
666        (rows '()))
667       ((not (zerop rc)) (nreverse rows))
668     (push
669      (loop for i from 0 below num-fields
670            collect
671            (let ((is-null 
672                   (not (zerop (uffi:ensure-char-integer
673                                (uffi:deref-array (is-null-ptr stmt) '(:array :byte) i))))))
674              (unless is-null
675                (let* ((bind (uffi:deref-array (output-bind stmt) '(:array mysql-bind) i))
676                       (type (uffi:get-slot-value bind 'mysql-bind 'mysql::buffer-type))
677                       (buffer (uffi:get-slot-value bind 'mysql-bind 'mysql::buffer)))
678                  (case type
679                    ((#.mysql-field-types#var-string #.mysql-field-types#string
680                      #.mysql-field-types#tiny-blob #.mysql-field-types#blob
681                      #.mysql-field-types#medium-blob #.mysql-field-types#long-blob)
682                     (uffi:convert-from-foreign-string buffer))
683                     (#.mysql-field-types#tiny
684                      (uffi:ensure-char-integer
685                       (uffi:deref-pointer buffer :byte)))
686                     (#.mysql-field-types#short
687                      (uffi:deref-pointer buffer :short))
688                     (#.mysql-field-types#long
689                      (uffi:deref-pointer buffer :int))
690                     #+64bit
691                     (#.mysql-field-types#longlong
692                      (uffi:deref-pointer buffer :long))
693                     (#.mysql-field-types#float
694                      (uffi:deref-pointer buffer :float))
695                     (#.mysql-field-types#double
696                      (uffi:deref-pointer buffer :double))
697                    ((#.mysql-field-types#time #.mysql-field-types#date
698                                               #.mysql-field-types#datetime #.mysql-field-types#timestamp)
699                     (let ((year (uffi:get-slot-value buffer 'mysql-time 'mysql::year))
700                           (month (uffi:get-slot-value buffer 'mysql-time 'mysql::month))
701                           (day (uffi:get-slot-value buffer 'mysql-time 'mysql::day))
702                           (hour (uffi:get-slot-value buffer 'mysql-time 'mysql::hour))
703                           (minute (uffi:get-slot-value buffer 'mysql-time 'mysql::minute))
704                   (second (uffi:get-slot-value buffer 'mysql-time 'mysql::second)))
705                       (db-timestring
706                        (make-time :year year :month month :day day :hour hour
707                                   :minute minute :second second))))
708                    (t
709                     (list type)))))))
710      rows)))
711                   
712               
713
714   
715 #+mysql-client-v4.1
716 (defmethod database-free-prepared ((stmt mysql-stmt))
717   (with-slots (stmt) stmt
718     (mysql-stmt-close stmt))
719   )
720
721
722 ;;; Database capabilities
723
724 (defmethod db-type-use-column-on-drop-index? ((db-type (eql :mysql)))
725   t)
726
727 (defmethod db-type-has-views? ((db-type (eql :mysql)))
728   #+mysql-client-v5.1 t
729   #-mysql-client-v5.1 nil)
730
731 (defmethod db-type-has-subqueries? ((db-type (eql :mysql)))
732   #+mysql-client-v4.1 t
733   #-mysql-client-v4.1 nil)
734
735 (defmethod db-type-has-boolean-where? ((db-type (eql :mysql)))
736   #+mysql-client-v4.1 t
737   #-mysql-client-v4.1 nil)
738
739 (defmethod db-type-has-union? ((db-type (eql :mysql)))
740   (not (eql (schar mysql::*mysql-client-info* 0) #\3)))
741
742 (defmethod db-type-transaction-capable? ((db-type (eql :mysql)) database)
743   (let ((tuple (car (database-query "SHOW VARIABLES LIKE 'HAVE_INNODB'" database :auto nil))))
744     (and tuple (string-equal "YES" (second tuple)))))
745
746 (defmethod db-type-has-prepared-stmt? ((db-type (eql :mysql)))
747   #+mysql-client-v4.1 t
748   #-mysql-client-v4.1 nil)
749
750 (when (clsql-sys:database-type-library-loaded :mysql)
751   (clsql-sys:initialize-database-type :database-type :mysql))
752