#lang scheme/base
(require (planet bzlib/base)
(planet bzlib/dbi)
(prefix-in dbd: (planet jaz/mysql)))
(define (mysql-connect driver . attrs)
(let-values (((loader attrs)
(filter-file-loader/attrs attrs)))
(let ((handle (make-handle driver (apply* dbd:connect attrs)
(make-immutable-hash-registry)
0)))
(load-files! handle (if (list? loader) loader
(list loader)))
handle)))
(define (mysql-disconnect handle)
(dbd:close-connection! (handle-conn handle)))
(define (mysql-query handle stmt (args '()))
(convert-result
(if (symbol? stmt) (if-it (registry-ref (handle-query handle) stmt) (begin
(let ((query (prepared-query it))
(stmt (prepared-inner it)))
(dbd:execute stmt (map cell->sql-cell (phq-map-values query args)))))
(error 'query "unknown prepared statement ~a" stmt))
(let ((query (make-place-holder-query default-converter stmt)))
(dbd:query #:connection (handle-conn handle)
(phq-merge-query query
(map cell->sql-cell (phq-map-values query args))))))))
(define (mysql-prepare dbh key stmt)
(define (helper query)
(registry-set! (handle-query dbh)
key
(make-prepared query
(dbd:prepare #:connection
(handle-conn dbh)
(phq-converted query)))))
(helper (make-place-holder-query question-converter stmt)))
(define (convert-result rs)
(cond ((dbd:side-effect? rs)
rs)
((dbd:result-set? rs)
(cons (vector->list (dbd:result-set-field-names rs))
(map vector->list (dbd:result-set-rows rs))))))
(define (cell->sql-cell cell)
(cond ((null? cell) dbd:sql-null)
(else cell)))
(define (sql-cell->cell cell)
(cond ((dbd:sql-null? cell) '())
(else cell)))
(registry-set! drivers 'jazmysql
(make-driver mysql-connect
mysql-disconnect
mysql-query
mysql-prepare
default-begin
default-commit
default-rollback))