org-src: Use cl-lib
[org-mode.git] / lisp / ob-sql.el
blob7801c5ff5cfe76dbcf25e2a962d9dafe153152cc
1 ;;; ob-sql.el --- Babel Functions for SQL -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2009-2016 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; Org-Babel support for evaluating sql source code.
27 ;; (see also ob-sqlite.el)
29 ;; SQL is somewhat unique in that there are many different engines for
30 ;; the evaluation of sql (Mysql, PostgreSQL, etc...), so much of this
31 ;; file will have to be implemented engine by engine.
33 ;; Also SQL evaluation generally takes place inside of a database.
35 ;; Header args used:
36 ;; - engine
37 ;; - cmdline
38 ;; - dbhost
39 ;; - dbport
40 ;; - dbuser
41 ;; - dbpassword
42 ;; - database
43 ;; - colnames (default, nil, means "yes")
44 ;; - result-params
45 ;; - out-file
46 ;; The following are used but not really implemented for SQL:
47 ;; - colname-names
48 ;; - rownames
49 ;; - rowname-names
51 ;; TODO:
53 ;; - support for sessions
54 ;; - support for more engines (currently only supports mysql)
55 ;; - what's a reasonable way to drop table data into SQL?
58 ;;; Code:
59 (require 'ob)
61 (declare-function org-table-import "org-table" (file arg))
62 (declare-function orgtbl-to-csv "org-table" (table params))
63 (declare-function org-table-to-lisp "org-table" (&optional txt))
64 (declare-function cygwin-convert-file-name-to-windows "cygw32.c" (file &optional absolute-p))
66 (defvar org-babel-default-header-args:sql '())
68 (defconst org-babel-header-args:sql
69 '((engine . :any)
70 (out-file . :any)
71 (dbhost . :any)
72 (dbport . :any)
73 (dbuser . :any)
74 (dbpassword . :any)
75 (database . :any))
76 "SQL-specific header arguments.")
78 (defun org-babel-expand-body:sql (body params)
79 "Expand BODY according to the values of PARAMS."
80 (org-babel-sql-expand-vars
81 body (org-babel--get-vars params)))
83 (defun org-babel-sql-dbstring-mysql (host port user password database)
84 "Make MySQL cmd line args for database connection. Pass nil to omit that arg."
85 (combine-and-quote-strings
86 (delq nil
87 (list (when host (concat "-h" host))
88 (when port (format "-P%d" port))
89 (when user (concat "-u" user))
90 (when password (concat "-p" password))
91 (when database (concat "-D" database))))))
93 (defun org-babel-sql-dbstring-postgresql (host user database)
94 "Make PostgreSQL command line args for database connection.
95 Pass nil to omit that arg."
96 (combine-and-quote-strings
97 (delq nil
98 (list (when host (concat "-h" host))
99 (when user (concat "-U" user))
100 (when database (concat "-d" database))))))
102 (defun org-babel-sql-dbstring-oracle (host port user password database)
103 "Make Oracle command line args for database connection."
104 (format "%s/%s@%s:%s/%s" user password host port database))
106 (defun org-babel-sql-dbstring-mssql (host user password database)
107 "Make sqlcmd commmand line args for database connection.
108 `sqlcmd' is the preferred command line tool to access Microsoft
109 SQL Server on Windows and Linux platform."
110 (mapconcat #'identity
111 (delq nil
112 (list (when host (format "-S \"%s\"" host))
113 (when user (format "-U \"%s\"" user))
114 (when password (format "-P \"%s\"" password))
115 (when database (format "-d \"%s\"" database))))
116 " "))
118 (defun org-babel-sql-convert-standard-filename (file)
119 "Convert the file name to OS standard.
120 If in Cygwin environment, uses Cygwin specific function to
121 convert the file name. Otherwise, uses Emacs' standard conversion
122 function."
123 (format "\"%s\""
124 (if (fboundp 'cygwin-convert-file-name-to-windows)
125 (cygwin-convert-file-name-to-windows file)
126 (convert-standard-filename file))))
128 (defun org-babel-execute:sql (body params)
129 "Execute a block of Sql code with Babel.
130 This function is called by `org-babel-execute-src-block'."
131 (let* ((result-params (cdr (assoc :result-params params)))
132 (cmdline (cdr (assoc :cmdline params)))
133 (dbhost (cdr (assoc :dbhost params)))
134 (dbport (cdr (assq :dbport params)))
135 (dbuser (cdr (assoc :dbuser params)))
136 (dbpassword (cdr (assoc :dbpassword params)))
137 (database (cdr (assoc :database params)))
138 (engine (cdr (assoc :engine params)))
139 (colnames-p (not (equal "no" (cdr (assoc :colnames params)))))
140 (in-file (org-babel-temp-file "sql-in-"))
141 (out-file (or (cdr (assoc :out-file params))
142 (org-babel-temp-file "sql-out-")))
143 (header-delim "")
144 (command (pcase (intern engine)
145 (`dbi (format "dbish --batch %s < %s | sed '%s' > %s"
146 (or cmdline "")
147 (org-babel-process-file-name in-file)
148 "/^+/d;s/^|//;s/(NULL)/ /g;$d"
149 (org-babel-process-file-name out-file)))
150 (`monetdb (format "mclient -f tab %s < %s > %s"
151 (or cmdline "")
152 (org-babel-process-file-name in-file)
153 (org-babel-process-file-name out-file)))
154 (`mssql (format "sqlcmd %s -s \"\t\" %s -i %s -o %s"
155 (or cmdline "")
156 (org-babel-sql-dbstring-mssql
157 dbhost dbuser dbpassword database)
158 (org-babel-sql-convert-standard-filename
159 (org-babel-process-file-name in-file))
160 (org-babel-sql-convert-standard-filename
161 (org-babel-process-file-name out-file))))
162 (`mysql (format "mysql %s %s %s < %s > %s"
163 (org-babel-sql-dbstring-mysql
164 dbhost dbport dbuser dbpassword database)
165 (if colnames-p "" "-N")
166 (or cmdline "")
167 (org-babel-process-file-name in-file)
168 (org-babel-process-file-name out-file)))
169 (`postgresql (format
170 "psql --set=\"ON_ERROR_STOP=1\" %s -A -P \
171 footer=off -F \"\t\" %s -f %s -o %s %s"
172 (if colnames-p "" "-t")
173 (org-babel-sql-dbstring-postgresql
174 dbhost dbuser database)
175 (org-babel-process-file-name in-file)
176 (org-babel-process-file-name out-file)
177 (or cmdline "")))
178 (`oracle (format
179 "sqlplus -s %s < %s > %s"
180 (org-babel-sql-dbstring-oracle
181 dbhost dbport dbuser dbpassword database)
182 (org-babel-process-file-name in-file)
183 (org-babel-process-file-name out-file)))
184 (_ (error "No support for the %s SQL engine" engine)))))
185 (with-temp-file in-file
186 (insert
187 (pcase (intern engine)
188 (`dbi "/format partbox\n")
189 (`oracle "SET PAGESIZE 50000
190 SET NEWPAGE 0
191 SET TAB OFF
192 SET SPACE 0
193 SET LINESIZE 9999
194 SET ECHO OFF
195 SET FEEDBACK OFF
196 SET VERIFY OFF
197 SET HEADING ON
198 SET MARKUP HTML OFF SPOOL OFF
199 SET COLSEP '|'
202 (`mssql "SET NOCOUNT ON
205 (_ ""))
206 (org-babel-expand-body:sql body params)))
207 (org-babel-eval command "")
208 (org-babel-result-cond result-params
209 (with-temp-buffer
210 (progn (insert-file-contents-literally out-file) (buffer-string)))
211 (with-temp-buffer
212 (cond
213 ((memq (intern engine) '(dbi mysql postgresql))
214 ;; Add header row delimiter after column-names header in first line
215 (cond
216 (colnames-p
217 (with-temp-buffer
218 (insert-file-contents out-file)
219 (goto-char (point-min))
220 (forward-line 1)
221 (insert "-\n")
222 (setq header-delim "-")
223 (write-file out-file)))))
225 ;; Need to figure out the delimiter for the header row
226 (with-temp-buffer
227 (insert-file-contents out-file)
228 (goto-char (point-min))
229 (when (re-search-forward "^\\(-+\\)[^-]" nil t)
230 (setq header-delim (match-string-no-properties 1)))
231 (goto-char (point-max))
232 (forward-char -1)
233 (while (looking-at "\n")
234 (delete-char 1)
235 (goto-char (point-max))
236 (forward-char -1))
237 (write-file out-file))))
238 (org-table-import out-file '(16))
239 (org-babel-reassemble-table
240 (mapcar (lambda (x)
241 (if (string= (car x) header-delim)
242 'hline
244 (org-table-to-lisp))
245 (org-babel-pick-name (cdr (assoc :colname-names params))
246 (cdr (assoc :colnames params)))
247 (org-babel-pick-name (cdr (assoc :rowname-names params))
248 (cdr (assoc :rownames params))))))))
250 (defun org-babel-sql-expand-vars (body vars)
251 "Expand the variables held in VARS in BODY."
252 (mapc
253 (lambda (pair)
254 (setq body
255 (replace-regexp-in-string
256 (format "$%s" (car pair))
257 (let ((val (cdr pair)))
258 (if (listp val)
259 (let ((data-file (org-babel-temp-file "sql-data-")))
260 (with-temp-file data-file
261 (insert (orgtbl-to-csv
262 val '(:fmt (lambda (el) (if (stringp el)
264 (format "%S" el)))))))
265 data-file)
266 (if (stringp val) val (format "%S" val))))
267 body)))
268 vars)
269 body)
271 (defun org-babel-prep-session:sql (_session _params)
272 "Raise an error because Sql sessions aren't implemented."
273 (error "SQL sessions not yet implemented"))
275 (provide 'ob-sql)
279 ;;; ob-sql.el ends here