ox-koma-letter: Tiny refactoring and cosmetics
[org-mode/org-tableheadings.git] / lisp / ob-sql.el
blob8f0cc8b95a5301b98ba422f83cc77e2f8621a745
1 ;;; ob-sql.el --- Babel Functions for SQL -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2009-2018 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: https://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 <https://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
47 ;; The following are used but not really implemented for SQL:
48 ;; - colname-names
49 ;; - rownames
50 ;; - rowname-names
52 ;; Engines supported:
53 ;; - mysql
54 ;; - dbi
55 ;; - mssql
56 ;; - sqsh
57 ;; - postgresql
58 ;; - oracle
59 ;; - vertica
61 ;; TODO:
63 ;; - support for sessions
64 ;; - support for more engines
65 ;; - what's a reasonable way to drop table data into SQL?
68 ;;; Code:
69 (require 'ob)
71 (declare-function org-table-import "org-table" (file arg))
72 (declare-function orgtbl-to-csv "org-table" (table params))
73 (declare-function org-table-to-lisp "org-table" (&optional txt))
74 (declare-function cygwin-convert-file-name-to-windows "cygw32.c" (file &optional absolute-p))
76 (defvar org-babel-default-header-args:sql '())
78 (defconst org-babel-header-args:sql
79 '((engine . :any)
80 (out-file . :any)
81 (dbhost . :any)
82 (dbport . :any)
83 (dbuser . :any)
84 (dbpassword . :any)
85 (database . :any))
86 "SQL-specific header arguments.")
88 (defun org-babel-expand-body:sql (body params)
89 "Expand BODY according to the values of PARAMS."
90 (org-babel-sql-expand-vars
91 body (org-babel--get-vars params)))
93 (defun org-babel-sql-dbstring-mysql (host port user password database)
94 "Make MySQL cmd line args for database connection. Pass nil to omit that arg."
95 (combine-and-quote-strings
96 (delq nil
97 (list (when host (concat "-h" host))
98 (when port (format "-P%d" port))
99 (when user (concat "-u" user))
100 (when password (concat "-p" password))
101 (when database (concat "-D" database))))))
103 (defun org-babel-sql-dbstring-postgresql (host port user database)
104 "Make PostgreSQL command line args for database connection.
105 Pass nil to omit that arg."
106 (combine-and-quote-strings
107 (delq nil
108 (list (when host (concat "-h" host))
109 (when port (format "-p%d" port))
110 (when user (concat "-U" user))
111 (when database (concat "-d" database))))))
113 (defun org-babel-sql-dbstring-oracle (host port user password database)
114 "Make Oracle command line arguments for database connection.
116 If HOST and PORT are nil then don't pass them. This allows you
117 to use names defined in your \"TNSNAMES\" file. So you can
118 connect with
120 <user>/<password>@<host>:<port>/<database>
124 <user>/<password>@<database>
126 using its alias."
127 (cond ((and user password database host port)
128 (format "%s/%s@%s:%s/%s" user password host port database))
129 ((and user password database)
130 (format "%s/%s@%s" user password database))
131 (t (user-error "Missing information to connect to database"))))
133 (defun org-babel-sql-dbstring-mssql (host user password database)
134 "Make sqlcmd command line args for database connection.
135 `sqlcmd' is the preferred command line tool to access Microsoft
136 SQL Server on Windows and Linux platform."
137 (mapconcat #'identity
138 (delq nil
139 (list (when host (format "-S \"%s\"" host))
140 (when user (format "-U \"%s\"" user))
141 (when password (format "-P \"%s\"" password))
142 (when database (format "-d \"%s\"" database))))
143 " "))
145 (defun org-babel-sql-dbstring-sqsh (host user password database)
146 "Make sqsh command line args for database connection.
147 \"sqsh\" is one method to access Sybase or MS SQL via Linux platform"
148 (mapconcat #'identity
149 (delq nil
150 (list (when host (format "-S \"%s\"" host))
151 (when user (format "-U \"%s\"" user))
152 (when password (format "-P \"%s\"" password))
153 (when database (format "-D \"%s\"" database))))
154 " "))
156 (defun org-babel-sql-dbstring-vertica (host port user password database)
157 "Make Vertica command line args for database connection. Pass nil to omit that arg."
158 (mapconcat #'identity
159 (delq nil
160 (list (when host (format "-h %s" host))
161 (when port (format "-p %d" port))
162 (when user (format "-U %s" user))
163 (when password (format "-w %s" (shell-quote-argument password) ))
164 (when database (format "-d %s" database))))
165 " "))
167 (defun org-babel-sql-convert-standard-filename (file)
168 "Convert FILE to OS standard file name.
169 If in Cygwin environment, uses Cygwin specific function to
170 convert the file name. In a Windows-NT environment, do nothing.
171 Otherwise, use Emacs' standard conversion function."
172 (cond ((fboundp 'cygwin-convert-file-name-to-windows)
173 (format "%S" (cygwin-convert-file-name-to-windows file)))
174 ((string= "windows-nt" system-type) file)
175 (t (format "%S" (convert-standard-filename file)))))
177 (defun org-babel-execute:sql (body params)
178 "Execute a block of Sql code with Babel.
179 This function is called by `org-babel-execute-src-block'."
180 (let* ((result-params (cdr (assq :result-params params)))
181 (cmdline (cdr (assq :cmdline params)))
182 (dbhost (cdr (assq :dbhost params)))
183 (dbport (cdr (assq :dbport params)))
184 (dbuser (cdr (assq :dbuser params)))
185 (dbpassword (cdr (assq :dbpassword params)))
186 (database (cdr (assq :database params)))
187 (engine (cdr (assq :engine params)))
188 (colnames-p (not (equal "no" (cdr (assq :colnames params)))))
189 (in-file (org-babel-temp-file "sql-in-"))
190 (out-file (or (cdr (assq :out-file params))
191 (org-babel-temp-file "sql-out-")))
192 (header-delim "")
193 (command (pcase (intern engine)
194 (`dbi (format "dbish --batch %s < %s | sed '%s' > %s"
195 (or cmdline "")
196 (org-babel-process-file-name in-file)
197 "/^+/d;s/^|//;s/(NULL)/ /g;$d"
198 (org-babel-process-file-name out-file)))
199 (`monetdb (format "mclient -f tab %s < %s > %s"
200 (or cmdline "")
201 (org-babel-process-file-name in-file)
202 (org-babel-process-file-name out-file)))
203 (`mssql (format "sqlcmd %s -s \"\t\" %s -i %s -o %s"
204 (or cmdline "")
205 (org-babel-sql-dbstring-mssql
206 dbhost dbuser dbpassword database)
207 (org-babel-sql-convert-standard-filename
208 (org-babel-process-file-name in-file))
209 (org-babel-sql-convert-standard-filename
210 (org-babel-process-file-name out-file))))
211 (`mysql (format "mysql %s %s %s < %s > %s"
212 (org-babel-sql-dbstring-mysql
213 dbhost dbport dbuser dbpassword database)
214 (if colnames-p "" "-N")
215 (or cmdline "")
216 (org-babel-process-file-name in-file)
217 (org-babel-process-file-name out-file)))
218 (`postgresql (format
219 "%spsql --set=\"ON_ERROR_STOP=1\" %s -A -P \
220 footer=off -F \"\t\" %s -f %s -o %s %s"
221 (if dbpassword
222 (format "PGPASSWORD=%s " dbpassword)
224 (if colnames-p "" "-t")
225 (org-babel-sql-dbstring-postgresql
226 dbhost dbport dbuser database)
227 (org-babel-process-file-name in-file)
228 (org-babel-process-file-name out-file)
229 (or cmdline "")))
230 (`sqsh (format "sqsh %s %s -i %s -o %s -m csv"
231 (or cmdline "")
232 (org-babel-sql-dbstring-sqsh
233 dbhost dbuser dbpassword database)
234 (org-babel-sql-convert-standard-filename
235 (org-babel-process-file-name in-file))
236 (org-babel-sql-convert-standard-filename
237 (org-babel-process-file-name out-file))))
238 (`vertica (format "vsql %s -f %s -o %s %s"
239 (org-babel-sql-dbstring-vertica
240 dbhost dbport dbuser dbpassword database)
241 (org-babel-process-file-name in-file)
242 (org-babel-process-file-name out-file)
243 (or cmdline "")))
244 (`oracle (format
245 "sqlplus -s %s < %s > %s"
246 (org-babel-sql-dbstring-oracle
247 dbhost dbport dbuser dbpassword database)
248 (org-babel-process-file-name in-file)
249 (org-babel-process-file-name out-file)))
250 (_ (error "No support for the %s SQL engine" engine)))))
251 (with-temp-file in-file
252 (insert
253 (pcase (intern engine)
254 (`dbi "/format partbox\n")
255 (`oracle "SET PAGESIZE 50000
256 SET NEWPAGE 0
257 SET TAB OFF
258 SET SPACE 0
259 SET LINESIZE 9999
260 SET TRIMOUT ON TRIMSPOOL ON
261 SET ECHO OFF
262 SET FEEDBACK OFF
263 SET VERIFY OFF
264 SET HEADING ON
265 SET MARKUP HTML OFF SPOOL OFF
266 SET COLSEP '|'
269 ((or `mssql `sqsh) "SET NOCOUNT ON
272 (`vertica "\\a\n")
273 (_ ""))
274 (org-babel-expand-body:sql body params)
275 ;; "sqsh" requires "go" inserted at EOF.
276 (if (string= engine "sqsh") "\ngo" "")))
277 (org-babel-eval command "")
278 (org-babel-result-cond result-params
279 (with-temp-buffer
280 (progn (insert-file-contents-literally out-file) (buffer-string)))
281 (with-temp-buffer
282 (cond
283 ((memq (intern engine) '(dbi mysql postgresql sqsh vertica))
284 ;; Add header row delimiter after column-names header in first line
285 (cond
286 (colnames-p
287 (with-temp-buffer
288 (insert-file-contents out-file)
289 (goto-char (point-min))
290 (forward-line 1)
291 (insert "-\n")
292 (setq header-delim "-")
293 (write-file out-file)))))
295 ;; Need to figure out the delimiter for the header row
296 (with-temp-buffer
297 (insert-file-contents out-file)
298 (goto-char (point-min))
299 (when (re-search-forward "^\\(-+\\)[^-]" nil t)
300 (setq header-delim (match-string-no-properties 1)))
301 (goto-char (point-max))
302 (forward-char -1)
303 (while (looking-at "\n")
304 (delete-char 1)
305 (goto-char (point-max))
306 (forward-char -1))
307 (write-file out-file))))
308 (org-table-import out-file (if (string= engine "sqsh") '(4) '(16)))
309 (org-babel-reassemble-table
310 (mapcar (lambda (x)
311 (if (string= (car x) header-delim)
312 'hline
314 (org-table-to-lisp))
315 (org-babel-pick-name (cdr (assq :colname-names params))
316 (cdr (assq :colnames params)))
317 (org-babel-pick-name (cdr (assq :rowname-names params))
318 (cdr (assq :rownames params))))))))
320 (defun org-babel-sql-expand-vars (body vars)
321 "Expand the variables held in VARS in BODY."
322 (mapc
323 (lambda (pair)
324 (setq body
325 (replace-regexp-in-string
326 (format "$%s" (car pair))
327 (let ((val (cdr pair)))
328 (if (listp val)
329 (let ((data-file (org-babel-temp-file "sql-data-")))
330 (with-temp-file data-file
331 (insert (orgtbl-to-csv
332 val '(:fmt (lambda (el) (if (stringp el)
334 (format "%S" el)))))))
335 data-file)
336 (if (stringp val) val (format "%S" val))))
337 body)))
338 vars)
339 body)
341 (defun org-babel-prep-session:sql (_session _params)
342 "Raise an error because Sql sessions aren't implemented."
343 (error "SQL sessions not yet implemented"))
345 (provide 'ob-sql)
349 ;;; ob-sql.el ends here