Hi,

I did some changes to support :dbname, :dbhost and :database in SQL code blocks when using postgresql engine.

Even if it was possible to specify this information using :cmdline parameter, I thought it was a bit cleaner to be able to provide this information in a way independent from the command line.

I will gladly accept any remark / comment on this patch.

Regards,
Steven Rémot
>From 6ad99759a16c8b6f9decfb8ea90c84e7a1c18fdc Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Steven=20R=C3=A9mot?= <steven.re...@gmail.com>
Date: Fri, 8 Aug 2014 21:49:44 +0200
Subject: [PATCH] ob-sql.el: Enhance postgresql support

* lisp/ob-sql.el: Add support for :dbhost, :dbuser and :database
  parameters in sql code blocks for postgresql engine.

Before this patch, it was necessary to use :cmdline parameter to
specify host, user and database different the the default ones.  Now,
this can be done using parameters that are independents of the engine
used.

This is not trivial (and not recommended) to pass password as a
command line argument to psql, so :dbpassword is not supported.
---
 lisp/ob-sql.el | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/lisp/ob-sql.el b/lisp/ob-sql.el
index 7b85df8..9fe9da2 100644
--- a/lisp/ob-sql.el
+++ b/lisp/ob-sql.el
@@ -87,6 +87,15 @@
 	       (when password (concat "-p" password))
 	       (when database (concat "-D" database))))))
 
+(defun dbstring-postgresql (host user database)
+  "Make PostgreSQL command line ards for database connection.
+Pass nil to omit that arg."
+  (combine-and-quote-strings
+   (remq nil
+	 (list (when host (concat "-h" host))
+	       (when user (concat "-U" user))
+	       (when database (concat "-d" database))))))
+
 (defun org-babel-execute:sql (body params)
   "Execute a block of Sql code with Babel.
 This function is called by `org-babel-execute-src-block'."
@@ -123,8 +132,9 @@ This function is called by `org-babel-execute-src-block'."
 				    (org-babel-process-file-name in-file)
 				    (org-babel-process-file-name out-file)))
 		    ('postgresql (format
-				  "psql --set=\"ON_ERROR_STOP=1\" %s -A -P footer=off -F \"\t\"  -f %s -o %s %s"
+				  "psql --set=\"ON_ERROR_STOP=1\" %s -A -P footer=off -F \"\t\"  %s -f %s -o %s %s"
 				  (if colnames-p "" "-t")
+				  (dbstring-postgresql dbhost dbuser database)
 				  (org-babel-process-file-name in-file)
 				  (org-babel-process-file-name out-file)
 				  (or cmdline "")))
-- 
1.9.1

Reply via email to