;;;; -- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; Package: umlisp -*-
;;;; *************************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name:          connect.lisp
;;;; Purpose:       Low-level SQL routines data for UMLisp
;;;; Programmer:    Kevin M. Rosenberg
;;;; Date Started:  Apr 2000
;;;;
;;;; $Id$
;;;;
;;;; This file is Copyright (c) 2000-2003 by Kevin M. Rosenberg
;;;; *************************************************************************

(in-package #:hyperobject)

(defvar *ho-sql-db* "ho")
(defun ho-sql-db ()
  *ho-sql-db*)
(defun ho-sql-db! (dbname)
  (sql-disconnect-pooled)
  (setq *ho-sql-db* dbname))

(defvar *ho-sql-user* "secret")
(defun ho-sql-user ()
  *ho-sql-user*)
(defun ho-sql-user! (u)
  (sql-disconnect-pooled)
  (setq *ho-sql-user* u))

(defvar *ho-sql-passwd* "secret")
(defun ho-sql-passwd ()
  *ho-sql-passwd*)
(defun ho-sql-passwd! (p)
  (sql-disconnect-pooled)
  (setq *ho-sql-passwd* p))

(defvar *ho-sql-host* "localhost")
(defun ho-sql-host ()
  *ho-sql-host*)
(defun ho-sql-host! (h)
  (sql-disconnect-pooled)
  (setq *ho-sql-host* h))

(defvar *ho-sql-type* :mysql)
(defun ho-sql-type ()
  *ho-sql-type*)
(defun ho-sql-type! (h)
  (sql-disconnect-pooled)
  (setq *ho-sql-type* h))

(defun sql-connect ()
  "Connect to HO database, automatically used pooled connections"
  (clsql:connect `(,(ho-sql-host) ,(ho-sql-db) ,(ho-sql-user) ,(ho-sql-passwd))
                 :database-type *ho-sql-type* :pool t))

(defun sql-disconnect (conn)
  "Disconnect from HO database, but put connection back into pool"
  (clsql:disconnect :database conn))

(defun sql-disconnect-pooled ()
  (clsql:disconnect-pooled))

(defmacro with-sql-connection ((conn) &body body)
  `(let ((,conn (sql-connect)))
     (unwind-protect
         (progn ,@body)
       (when ,conn (clsql:disconnect :database ,conn)))))

(defun sql-query (cmd conn &key (types :auto))
  (clsql:query cmd :database conn :types types))

(defun sql-execute (cmd conn)
  (clsql:execute-command cmd :database conn))

;;; Pool of open connections

(defmacro with-mutex-sql ((conn) &body body)
  `(let ((,conn (sql-connect)))
     (unwind-protect
         (progn ,@body)
       (when ,conn (sql-disconnect ,conn)))))

(defun mutex-sql-execute (cmd)
  (with-mutex-sql (conn)
    (sql-execute cmd conn)))

(defun mutex-sql-query (cmd &key (types :auto))
  (with-mutex-sql (conn)
    (sql-query cmd conn :types types)))
