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/>.
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.
43 ;; - colnames (default, nil, means "yes")
47 ;; The following are used but not really implemented for SQL:
63 ;; - support for sessions
64 ;; - support for more engines
65 ;; - what's a reasonable way to drop table data into SQL?
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
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
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
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
120 <user>/<password>@<host>:<port>/<database>
124 <user>/<password>@<database>
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
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
))))
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
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
))))
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
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
))))
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-")))
193 (command (pcase (intern engine
)
194 (`dbi
(format "dbish --batch %s < %s | sed '%s' > %s"
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"
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"
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")
216 (org-babel-process-file-name in-file
)
217 (org-babel-process-file-name out-file
)))
219 "%spsql --set=\"ON_ERROR_STOP=1\" %s -A -P \
220 footer=off -F \"\t\" %s -f %s -o %s %s"
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
)
230 (`sqsh
(format "sqsh %s %s -i %s -o %s -m csv"
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
)
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
253 (pcase (intern engine
)
254 (`dbi
"/format partbox\n")
255 (`oracle
"SET PAGESIZE 50000
260 SET TRIMOUT ON TRIMSPOOL ON
265 SET MARKUP HTML OFF SPOOL OFF
269 ((or `mssql
`sqsh
) "SET NOCOUNT ON
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
280 (progn (insert-file-contents-literally out-file
) (buffer-string)))
283 ((memq (intern engine
) '(dbi mysql postgresql sqsh vertica
))
284 ;; Add header row delimiter after column-names header in first line
288 (insert-file-contents out-file
)
289 (goto-char (point-min))
292 (setq header-delim
"-")
293 (write-file out-file
)))))
295 ;; Need to figure out the delimiter for the header row
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))
303 (while (looking-at "\n")
305 (goto-char (point-max))
307 (write-file out-file
))))
308 (org-table-import out-file
(if (string= engine
"sqsh") '(4) '(16)))
309 (org-babel-reassemble-table
311 (if (string= (car x
) header-delim
)
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."
325 (replace-regexp-in-string
326 (format "$%s" (car pair
))
327 (let ((val (cdr pair
)))
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
)))))))
336 (if (stringp val
) val
(format "%S" val
))))
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"))
349 ;;; ob-sql.el ends here