dd623033013e7952bf9140a3f0cabe99030ba94c
[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-base #: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               (type (uffi:get-slot-value field 'mysql-field 'type)))
45         (push
46          (case type
47            ((#.mysql-field-types#tiny 
48              #.mysql-field-types#short
49              #.mysql-field-types#int24
50              #.mysql-field-types#long)
51             :int32)
52            (#.mysql-field-types#longlong
53             :int64)
54            ((#.mysql-field-types#double
55              #.mysql-field-types#float
56              #.mysql-field-types#decimal)
57             :double)
58            (otherwise
59             t))
60          new-types)))
61     (nreverse new-types)))
62
63 (defun canonicalize-types (types num-fields res-ptr)
64   (when types
65     (let ((auto-list (make-type-list-for-auto num-fields res-ptr)))
66       (cond
67         ((listp types)
68          (canonicalize-type-list types auto-list))
69         ((eq types :auto)
70          auto-list)
71         (t
72          nil)))))
73
74 (defmethod database-initialize-database-type ((database-type (eql :mysql)))
75   t)
76
77 (uffi:def-type mysql-mysql-ptr-def (* mysql-mysql))
78 (uffi:def-type mysql-row-def mysql-row)
79 (uffi:def-type mysql-mysql-res-ptr-def (* mysql-mysql-res))
80
81 (defclass mysql-database (database)
82   ((mysql-ptr :accessor database-mysql-ptr :initarg :mysql-ptr
83               :type mysql-mysql-ptr-def)))
84
85 (defmethod database-type ((database mysql-database))
86   :mysql)
87
88 (defmethod database-name-from-spec (connection-spec (database-type (eql :mysql)))
89   (check-connection-spec connection-spec database-type (host db user password))
90   (destructuring-bind (host db user password) connection-spec
91     (declare (ignore password))
92     (concatenate 'string 
93                  (if host host "localhost")
94                  "/" db "/" user)))
95
96 (defmethod database-connect (connection-spec (database-type (eql :mysql)))
97   (check-connection-spec connection-spec database-type (host db user password))
98   (destructuring-bind (host db user password) connection-spec
99     (let ((mysql-ptr (mysql-init (uffi:make-null-pointer 'mysql-mysql)))
100           (socket nil))
101       (if (uffi:null-pointer-p mysql-ptr)
102           (error 'clsql-connect-error
103                  :database-type database-type
104                  :connection-spec connection-spec
105                  :errno (mysql-errno mysql-ptr)
106                  :error (mysql-error-string mysql-ptr))
107         (uffi:with-cstrings ((host-native host)
108                             (user-native user)
109                             (password-native password)
110                             (db-native db)
111                             (socket-native socket))
112           (let ((error-occurred nil))
113             (unwind-protect
114                 (if (uffi:null-pointer-p 
115                      (mysql-real-connect 
116                       mysql-ptr host-native user-native password-native
117                       db-native 0 socket-native 0))
118                     (progn
119                       (setq error-occurred t)
120                       (error 'clsql-connect-error
121                              :database-type database-type
122                              :connection-spec connection-spec
123                              :errno (mysql-errno mysql-ptr)
124                              :error (mysql-error-string mysql-ptr)))
125                   (make-instance 'mysql-database
126                     :name (database-name-from-spec connection-spec
127                                                    database-type)
128                     :database-type :mysql
129                     :connection-spec connection-spec
130                     :mysql-ptr mysql-ptr))
131               (when error-occurred (mysql-close mysql-ptr)))))))))
132
133
134 (defmethod database-disconnect ((database mysql-database))
135   (mysql-close (database-mysql-ptr database))
136   (setf (database-mysql-ptr database) nil)
137   t)
138
139
140 (defmethod database-query (query-expression (database mysql-database) 
141                            result-types field-names)
142   (declare (optimize (speed 3) (safety 0) (debug 0) (space 0)))
143   (let ((mysql-ptr (database-mysql-ptr database)))
144     (uffi:with-cstring (query-native query-expression)
145       (if (zerop (mysql-real-query mysql-ptr query-native 
146                                    (length query-expression)))
147           (let ((res-ptr (mysql-use-result mysql-ptr)))
148             (if res-ptr
149                 (unwind-protect
150                      (let ((num-fields (mysql-num-fields res-ptr)))
151                        (declare (fixnum num-fields))
152                        (setq result-types (canonicalize-types 
153                                     result-types num-fields
154                                     res-ptr))
155                        (values
156                         (loop for row = (mysql-fetch-row res-ptr)
157                               for lengths = (mysql-fetch-lengths res-ptr)
158                               until (uffi:null-pointer-p row)
159                               collect
160                               (do* ((rlist (make-list num-fields))
161                                     (i 0 (1+ i))
162                                     (pos rlist (cdr pos)))
163                                    ((= i num-fields) rlist)
164                                 (declare (fixnum i))
165                                 (setf (car pos)  
166                                       (convert-raw-field
167                                        (uffi:deref-array row '(:array
168                                                                (* :unsigned-char))
169                                                          i)
170                                        result-types i
171                                        (uffi:deref-array lengths '(:array :unsigned-long)
172                                                          i)))))
173                         (when field-names
174                           (result-field-names num-fields res-ptr))))
175                   (mysql-free-result res-ptr))
176                 (error 'clsql-sql-error
177                        :database database
178                        :expression query-expression
179                        :errno (mysql-errno mysql-ptr)
180                        :error (mysql-error-string mysql-ptr))))
181           (error 'clsql-sql-error
182                  :database database
183                  :expression query-expression
184                  :errno (mysql-errno mysql-ptr)
185                  :error (mysql-error-string mysql-ptr))))))
186
187 (defmethod database-execute-command (sql-expression (database mysql-database))
188   (uffi:with-cstring (sql-native sql-expression)
189     (let ((mysql-ptr (database-mysql-ptr database)))
190       (declare (type mysql-mysql-ptr-def mysql-ptr))
191       (if (zerop (mysql-real-query mysql-ptr sql-native 
192                                    (length sql-expression)))
193           t
194         (error 'clsql-sql-error
195                :database database
196                :expression sql-expression
197                :errno (mysql-errno mysql-ptr)
198                :error (mysql-error-string mysql-ptr))))))
199
200
201 (defstruct mysql-result-set 
202   (res-ptr (uffi:make-null-pointer 'mysql-mysql-res) :type mysql-mysql-res-ptr-def)
203   (types nil :type list)
204   (num-fields 0 :type fixnum)
205   (full-set nil :type boolean))
206
207
208 (defmethod database-query-result-set ((query-expression string)
209                                       (database mysql-database)
210                                       &key full-set result-types)
211   (uffi:with-cstring (query-native query-expression)
212     (let ((mysql-ptr (database-mysql-ptr database)))
213      (declare (type mysql-mysql-ptr-def mysql-ptr))
214       (if (zerop (mysql-real-query mysql-ptr query-native
215                                    (length query-expression)))
216           (let ((res-ptr (if full-set
217                              (mysql-store-result mysql-ptr)
218                            (mysql-use-result mysql-ptr))))
219             (declare (type mysql-mysql-res-ptr-def res-ptr))
220             (if (not (uffi:null-pointer-p res-ptr))
221                 (let* ((num-fields (mysql-num-fields res-ptr))
222                        (result-set (make-mysql-result-set
223                                     :res-ptr res-ptr
224                                     :num-fields num-fields
225                                     :full-set full-set
226                                     :types
227                                     (canonicalize-types 
228                                      result-types num-fields
229                                      res-ptr)))) 
230                   (if full-set
231                       (values result-set
232                               num-fields
233                               (mysql-num-rows res-ptr))
234                       (values result-set
235                               num-fields)))
236                 (error 'clsql-sql-error
237                      :database database
238                      :expression query-expression
239                      :errno (mysql-errno mysql-ptr)
240                      :error (mysql-error-string mysql-ptr))))
241         (error 'clsql-sql-error
242                :database database
243                :expression query-expression
244                :errno (mysql-errno mysql-ptr)
245                :error (mysql-error-string mysql-ptr))))))
246
247 (defmethod database-dump-result-set (result-set (database mysql-database))
248   (mysql-free-result (mysql-result-set-res-ptr result-set))
249   t)
250
251
252 (defmethod database-store-next-row (result-set (database mysql-database) list)
253   (let* ((res-ptr (mysql-result-set-res-ptr result-set))
254          (row (mysql-fetch-row res-ptr))
255          (lengths (mysql-fetch-lengths res-ptr))
256          (types (mysql-result-set-types result-set)))
257     (declare (type mysql-mysql-res-ptr-def res-ptr)
258              (type mysql-row-def row))
259     (unless (uffi:null-pointer-p row)
260       (loop for i from 0 below (mysql-result-set-num-fields result-set)
261             for rest on list
262             do
263             (setf (car rest) 
264                   (convert-raw-field
265                    (uffi:deref-array row '(:array (* :unsigned-char)) i)
266                    types
267                    i
268                    (uffi:deref-array lengths '(:array :unsigned-long) i))))
269       list)))
270
271
272 ;; Table and attribute introspection
273
274 (defmethod database-list-tables ((database mysql-database) &key (owner nil))
275   (declare (ignore owner))
276   (remove-if #'(lambda (s)
277                  (and (>= (length s) 11)
278                       (string-equal (subseq s 0 11) "_CLSQL_SEQ_")))
279              (mapcar #'car (database-query "SHOW TABLES" database nil nil))))
280     
281 ;; MySQL 4.1 does not support views 
282 (defmethod database-list-views ((database mysql-database)
283                                 &key (owner nil))
284   (declare (ignore owner))
285   nil)
286
287 (defmethod database-list-indexes ((database mysql-database)
288                                   &key (owner nil))
289   (let ((result '()))
290     (dolist (table (database-list-tables database :owner owner) result)
291       (setq result
292         (append (database-list-table-indexes table database :owner owner)
293                 result)))))
294
295 (defmethod database-list-table-indexes (table (database mysql-database)
296                                         &key (owner nil))
297   (declare (ignore owner))
298   (do ((results nil)
299        (rows (database-query 
300               (format nil "SHOW INDEX FROM ~A" (string-upcase table))
301               database nil nil)
302              (cdr rows)))
303       ((null rows) (nreverse results))
304     (let ((col (nth 2 (car rows))))
305       (unless (find col results :test #'string-equal)
306         (push col results)))))
307   
308 (defmethod database-list-attributes ((table string) (database mysql-database)
309                                      &key (owner nil))
310   (declare (ignore owner))
311   (mapcar #'car
312           (database-query
313            (format nil "SHOW COLUMNS FROM ~A" table)
314            database nil nil)))
315
316 (defmethod database-attribute-type (attribute (table string)
317                                     (database mysql-database)
318                                     &key (owner nil))
319   (declare (ignore owner))
320   (let ((row (car (database-query
321                    (format nil
322                            "SHOW COLUMNS FROM ~A LIKE '~A'" table attribute)
323                    database nil nil))))
324     (let* ((raw-type (second row))
325            (null (third row))
326            (start-length (position #\( raw-type))
327            (type (if start-length
328                      (subseq raw-type 0 start-length)
329                      raw-type))
330            (length (when start-length
331                      (parse-integer (subseq raw-type (1+ start-length))
332                                     :junk-allowed t))))
333       (when type
334         (values (ensure-keyword type) length nil (if (string-equal null "YES") 1 0))))))
335
336 ;;; Sequence functions
337
338 (defun %sequence-name-to-table (sequence-name)
339   (concatenate 'string "_CLSQL_SEQ_" (sql-escape sequence-name)))
340
341 (defun %table-name-to-sequence-name (table-name)
342   (and (>= (length table-name) 11)
343        (string-equal (subseq table-name 0 11) "_CLSQL_SEQ_")
344        (subseq table-name 11)))
345
346 (defmethod database-create-sequence (sequence-name
347                                      (database mysql-database))
348   (let ((table-name (%sequence-name-to-table sequence-name)))
349     (database-execute-command
350      (concatenate 'string "CREATE TABLE " table-name
351                   " (id int NOT NULL PRIMARY KEY AUTO_INCREMENT)")
352      database)
353     (database-execute-command 
354      (concatenate 'string "INSERT INTO " table-name
355                   " VALUES (-1)")
356      database)))
357
358 (defmethod database-drop-sequence (sequence-name
359                                    (database mysql-database))
360   (database-execute-command
361    (concatenate 'string "DROP TABLE " (%sequence-name-to-table sequence-name)) 
362    database))
363
364 (defmethod database-list-sequences ((database mysql-database)
365                                     &key (owner nil))
366   (declare (ignore owner))
367   (mapcan #'(lambda (s)
368               (let ((sn (%table-name-to-sequence-name (car s))))
369                 (and sn (list sn))))
370           (database-query "SHOW TABLES" database nil nil)))
371
372 (defmethod database-set-sequence-position (sequence-name
373                                            (position integer)
374                                            (database mysql-database))
375   (database-execute-command
376    (format nil "UPDATE ~A SET id=~A" (%sequence-name-to-table sequence-name)
377            position)
378    database)
379   (mysql:mysql-insert-id (clsql-mysql::database-mysql-ptr database)))
380
381 (defmethod database-sequence-next (sequence-name (database mysql-database))
382   (without-interrupts
383    (database-execute-command 
384     (concatenate 'string "UPDATE " (%sequence-name-to-table sequence-name)
385                  " SET id=LAST_INSERT_ID(id+1)")
386     database)
387    (mysql:mysql-insert-id (clsql-mysql::database-mysql-ptr database))))
388
389 (defmethod database-sequence-last (sequence-name (database mysql-database))
390   (declare (ignore sequence-name)))
391
392 (defmethod database-create (connection-spec (type (eql :mysql)))
393   (destructuring-bind (host name user password) connection-spec
394     (multiple-value-bind (output status)
395         (clsql-base:command-output "mysqladmin create -u~A -p~A -h~A ~A"
396                                        user password 
397                                        (if host host "localhost")
398                                        name)
399       (if (or (not (eql 0 status))
400               (and (search "failed" output) (search "error" output)))
401           (error 'clsql-access-error
402                  :connection-spec connection-spec
403                  :database-type type
404                  :error 
405                  (format nil "database-create failed: ~A" output))
406           t))))
407
408 (defmethod database-destroy (connection-spec (type (eql :mysql)))
409   (destructuring-bind (host name user password) connection-spec
410     (multiple-value-bind (output status)
411         (clsql-base:command-output "mysqladmin drop -f -u~A -p~A -h~A ~A"
412                                        user password 
413                                        (if host host "localhost")
414                                        name)
415       (if (or (not (eql 0 status))
416               (and (search "failed" output) (search "error" output)))
417           (error 'clsql-access-error
418                  :connection-spec connection-spec
419                  :database-type type
420                  :error 
421                  (format nil "database-destroy failed: ~A" output))
422         t))))
423
424 (defmethod database-probe (connection-spec (type (eql :mysql)))
425   (when (find (second connection-spec) (database-list connection-spec type)
426               :key #'car :test #'string-equal)
427     t))
428
429 (defmethod database-list (connection-spec (type (eql :mysql)))
430   (destructuring-bind (host name user password) connection-spec
431     (declare (ignore name))
432     (let ((database (database-connect (list host "mysql" user password) type)))
433       (unwind-protect
434            (progn
435              (setf (slot-value database 'clsql-base::state) :open)
436              (mapcar #'car (database-query "show databases" database :auto nil)))
437         (progn
438           (database-disconnect database)
439           (setf (slot-value database 'clsql-base::state) :closed))))))
440
441 ;;; Database capabilities
442
443 (defmethod db-type-use-column-on-drop-index? ((db-type (eql :mysql)))
444   t)
445
446 (defmethod db-type-has-views? ((db-type (eql :mysql)))
447   ;; MySQL 4.1 will apparently have views, need to check *mysql-client-info*
448   nil)
449
450 (defmethod db-type-has-subqueries? ((db-type (eql :mysql)))
451   ;; MySQL 4.1 will apparently have subqueries, need to check *mysql-client-info*
452   nil)
453
454 (defmethod db-type-has-boolean-where? ((db-type (eql :mysql)))
455   nil)
456
457 (defmethod db-type-transaction-capable? ((db-type (eql :mysql)) database)
458   (let ((tuple (car (database-query "SHOW VARIABLES LIKE 'HAVE_INNODB'" database :auto nil))))
459     (and tuple (string-equal "YES" (second tuple)))))
460
461 (when (clsql-base:database-type-library-loaded :mysql)
462   (clsql-base:initialize-database-type :database-type :mysql))
463