With a little side of applesauce...

Thursday, October 27, 2011

EMACS - sql-mode connect to multiple databases

I just wanted to show my setup for connecting to multiple databases on multiple hosts via sql-mode in EMACS:

;; sql
(setq sql-connection-alist
(sql-name "host1_db1")
(sql-product 'postgres)
(sql-server "host1.example.com")
(sql-user "db1user")
(sql-password "")
(sql-database "db1")
(sql-port 5432))
(sql-name "host2_db1")
(sql-product 'postgres)
(sql-server "host2.example.com")
(sql-user "db2user")
(sql-password "")
(sql-database "db2")
(sql-port 5432))
(sql-name "local_mydb")
(sql-product 'postgres)
(sql-server "localhost")
(sql-user "myuser")
(sql-password "")
(sql-database "mydb")
(sql-port 5432))))

(defun sql-pool-host1_db1 ()
(sql-connect-preset 'pool-host1_db1))
(defun sql-pool-host2_db1 ()
(sql-connect-preset 'host2_db1))
(defun sql-pool-local_mydb ()
(sql-connect-preset 'pool-local_mydb))

;; this makes all it all happen via M-x sql-pool-host1_db1, etc.
(defun sql-connect-preset (name)
"Connect to a predefined SQL connection listed in `sql-connection-alist'"
(eval `(let ,(cdr (assoc name sql-connection-alist))
(flet ((sql-get-login (&rest what)))
(sql-product-interactive sql-product)))))

;; names the buffer *SQL: <host>_<db>, which is easier to
;; find when you M-x list-buffers, or C-x C-b
(defun sql-make-smart-buffer-name ()
"Return a string that can be used to rename a SQLi buffer.
This is used to set `sql-alternate-buffer-name' within
(or (and (boundp 'sql-name) sql-name)
(concat (if (not(string= "" sql-server))
(or (and (string-match "[0-9.]+" sql-server) sql-server)
(car (split-string sql-server "\\.")))

(add-hook 'sql-interactive-mode-hook
(lambda ()
(setq sql-alternate-buffer-name (sql-make-smart-buffer-name))

sql-make-smart-buffer-name () is added to make it easier to find the buffer when you have twenty-thirty buffers open.

No comments: