ob-sql.el 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. ;;; ob-sql.el --- Babel Functions for SQL -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2019 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: https://orgmode.org
  6. ;; This file is part of GNU Emacs.
  7. ;; GNU Emacs is free software: you can redistribute it and/or modify
  8. ;; it under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation, either version 3 of the License, or
  10. ;; (at your option) any later version.
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;; GNU General Public License for more details.
  15. ;; You should have received a copy of the GNU General Public License
  16. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  17. ;;; Commentary:
  18. ;; Org-Babel support for evaluating sql source code.
  19. ;; (see also ob-sqlite.el)
  20. ;;
  21. ;; SQL is somewhat unique in that there are many different engines for
  22. ;; the evaluation of sql (Mysql, PostgreSQL, etc...), so much of this
  23. ;; file will have to be implemented engine by engine.
  24. ;;
  25. ;; Also SQL evaluation generally takes place inside of a database.
  26. ;;
  27. ;; Header args used:
  28. ;; - engine
  29. ;; - cmdline
  30. ;; - dbhost
  31. ;; - dbport
  32. ;; - dbuser
  33. ;; - dbpassword
  34. ;; - dbconnection (to reference connections in sql-connection-alist)
  35. ;; - database
  36. ;; - colnames (default, nil, means "yes")
  37. ;; - result-params
  38. ;; - out-file
  39. ;;
  40. ;; The following are used but not really implemented for SQL:
  41. ;; - colname-names
  42. ;; - rownames
  43. ;; - rowname-names
  44. ;;
  45. ;; Engines supported:
  46. ;; - mysql
  47. ;; - dbi
  48. ;; - mssql
  49. ;; - sqsh
  50. ;; - postgresql
  51. ;; - oracle
  52. ;; - vertica
  53. ;;
  54. ;; TODO:
  55. ;;
  56. ;; - support for sessions
  57. ;; - support for more engines
  58. ;; - what's a reasonable way to drop table data into SQL?
  59. ;;
  60. ;;; Code:
  61. (require 'ob)
  62. (declare-function org-table-import "org-table" (file arg))
  63. (declare-function orgtbl-to-csv "org-table" (table params))
  64. (declare-function org-table-to-lisp "org-table" (&optional txt))
  65. (declare-function cygwin-convert-file-name-to-windows "cygw32.c" (file &optional absolute-p))
  66. (defvar sql-connection-alist)
  67. (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.")
  77. (defun org-babel-expand-body:sql (body params)
  78. "Expand BODY according to the values of PARAMS."
  79. (org-babel-sql-expand-vars
  80. body (org-babel--get-vars params)))
  81. (defun org-babel-sql-dbstring-mysql (host port user password database)
  82. "Make MySQL cmd line args for database connection. Pass nil to omit that arg."
  83. (combine-and-quote-strings
  84. (delq nil
  85. (list (when host (concat "-h" host))
  86. (when port (format "-P%d" port))
  87. (when user (concat "-u" user))
  88. (when password (concat "-p" password))
  89. (when database (concat "-D" database))))))
  90. (defun org-babel-sql-dbstring-postgresql (host port user database)
  91. "Make PostgreSQL command line args for database connection.
  92. Pass nil to omit that arg."
  93. (combine-and-quote-strings
  94. (delq nil
  95. (list (when host (concat "-h" host))
  96. (when port (format "-p%d" port))
  97. (when user (concat "-U" user))
  98. (when database (concat "-d" database))))))
  99. (defun org-babel-sql-dbstring-oracle (host port user password database)
  100. "Make Oracle command line arguments for database connection.
  101. If HOST and PORT are nil then don't pass them. This allows you
  102. to use names defined in your \"TNSNAMES\" file. So you can
  103. connect with
  104. <user>/<password>@<host>:<port>/<database>
  105. or
  106. <user>/<password>@<database>
  107. using its alias."
  108. (cond ((and user password database host port)
  109. (format "%s/%s@%s:%s/%s" user password host port database))
  110. ((and user password database)
  111. (format "%s/%s@%s" user password database))
  112. (t (user-error "Missing information to connect to database"))))
  113. (defun org-babel-sql-dbstring-mssql (host user password database)
  114. "Make sqlcmd command line args for database connection.
  115. `sqlcmd' is the preferred command line tool to access Microsoft
  116. SQL Server on Windows and Linux platform."
  117. (mapconcat #'identity
  118. (delq nil
  119. (list (when host (format "-S \"%s\"" host))
  120. (when user (format "-U \"%s\"" user))
  121. (when password (format "-P \"%s\"" password))
  122. (when database (format "-d \"%s\"" database))))
  123. " "))
  124. (defun org-babel-sql-dbstring-sqsh (host user password database)
  125. "Make sqsh command line args for database connection.
  126. \"sqsh\" is one method to access Sybase or MS SQL via Linux platform"
  127. (mapconcat #'identity
  128. (delq nil
  129. (list (when host (format "-S \"%s\"" host))
  130. (when user (format "-U \"%s\"" user))
  131. (when password (format "-P \"%s\"" password))
  132. (when database (format "-D \"%s\"" database))))
  133. " "))
  134. (defun org-babel-sql-dbstring-vertica (host port user password database)
  135. "Make Vertica command line args for database connection. Pass nil to omit that arg."
  136. (mapconcat #'identity
  137. (delq nil
  138. (list (when host (format "-h %s" host))
  139. (when port (format "-p %d" port))
  140. (when user (format "-U %s" user))
  141. (when password (format "-w %s" (shell-quote-argument password) ))
  142. (when database (format "-d %s" database))))
  143. " "))
  144. (defun org-babel-sql-convert-standard-filename (file)
  145. "Convert FILE to OS standard file name.
  146. If in Cygwin environment, uses Cygwin specific function to
  147. convert the file name. In a Windows-NT environment, do nothing.
  148. Otherwise, use Emacs' standard conversion function."
  149. (cond ((fboundp 'cygwin-convert-file-name-to-windows)
  150. (format "%S" (cygwin-convert-file-name-to-windows file)))
  151. ((string= "windows-nt" system-type) file)
  152. (t (format "%S" (convert-standard-filename file)))))
  153. (defun org-babel-find-db-connection-param (params name)
  154. "Return database connection parameter NAME.
  155. Given a parameter NAME, if :dbconnection is defined in PARAMS
  156. then look for the parameter into the corresponding connection
  157. defined in `sql-connection-alist`, otherwise look into PARAMS.
  158. Look `sql-connection-alist` (part of SQL mode) for how to define
  159. database connections."
  160. (if (assq :dbconnection params)
  161. (let* ((dbconnection (cdr (assq :dbconnection params)))
  162. (name-mapping '((:dbhost . sql-server)
  163. (:dbport . sql-port)
  164. (:dbuser . sql-user)
  165. (:dbpassword . sql-password)
  166. (:database . sql-database)))
  167. (mapped-name (cdr (assq name name-mapping))))
  168. (cadr (assq mapped-name
  169. (cdr (assoc dbconnection sql-connection-alist)))))
  170. (cdr (assq name params))))
  171. (defun org-babel-execute:sql (body params)
  172. "Execute a block of Sql code with Babel.
  173. This function is called by `org-babel-execute-src-block'."
  174. (let* ((result-params (cdr (assq :result-params params)))
  175. (cmdline (cdr (assq :cmdline params)))
  176. (dbhost (org-babel-find-db-connection-param params :dbhost))
  177. (dbport (org-babel-find-db-connection-param params :dbport))
  178. (dbuser (org-babel-find-db-connection-param params :dbuser))
  179. (dbpassword (org-babel-find-db-connection-param params :dbpassword))
  180. (database (org-babel-find-db-connection-param params :database))
  181. (engine (cdr (assq :engine params)))
  182. (colnames-p (not (equal "no" (cdr (assq :colnames params)))))
  183. (in-file (org-babel-temp-file "sql-in-"))
  184. (out-file (or (cdr (assq :out-file params))
  185. (org-babel-temp-file "sql-out-")))
  186. (header-delim "")
  187. (command (pcase (intern engine)
  188. (`dbi (format "dbish --batch %s < %s | sed '%s' > %s"
  189. (or cmdline "")
  190. (org-babel-process-file-name in-file)
  191. "/^+/d;s/^|//;s/(NULL)/ /g;$d"
  192. (org-babel-process-file-name out-file)))
  193. (`monetdb (format "mclient -f tab %s < %s > %s"
  194. (or cmdline "")
  195. (org-babel-process-file-name in-file)
  196. (org-babel-process-file-name out-file)))
  197. (`mssql (format "sqlcmd %s -s \"\t\" %s -i %s -o %s"
  198. (or cmdline "")
  199. (org-babel-sql-dbstring-mssql
  200. dbhost dbuser dbpassword database)
  201. (org-babel-sql-convert-standard-filename
  202. (org-babel-process-file-name in-file))
  203. (org-babel-sql-convert-standard-filename
  204. (org-babel-process-file-name out-file))))
  205. (`mysql (format "mysql %s %s %s < %s > %s"
  206. (org-babel-sql-dbstring-mysql
  207. dbhost dbport dbuser dbpassword database)
  208. (if colnames-p "" "-N")
  209. (or cmdline "")
  210. (org-babel-process-file-name in-file)
  211. (org-babel-process-file-name out-file)))
  212. (`postgresql (format
  213. "%spsql --set=\"ON_ERROR_STOP=1\" %s -A -P \
  214. footer=off -F \"\t\" %s -f %s -o %s %s"
  215. (if dbpassword
  216. (format "PGPASSWORD=%s " dbpassword)
  217. "")
  218. (if colnames-p "" "-t")
  219. (org-babel-sql-dbstring-postgresql
  220. dbhost dbport dbuser database)
  221. (org-babel-process-file-name in-file)
  222. (org-babel-process-file-name out-file)
  223. (or cmdline "")))
  224. (`sqsh (format "sqsh %s %s -i %s -o %s -m csv"
  225. (or cmdline "")
  226. (org-babel-sql-dbstring-sqsh
  227. dbhost dbuser dbpassword database)
  228. (org-babel-sql-convert-standard-filename
  229. (org-babel-process-file-name in-file))
  230. (org-babel-sql-convert-standard-filename
  231. (org-babel-process-file-name out-file))))
  232. (`vertica (format "vsql %s -f %s -o %s %s"
  233. (org-babel-sql-dbstring-vertica
  234. dbhost dbport dbuser dbpassword database)
  235. (org-babel-process-file-name in-file)
  236. (org-babel-process-file-name out-file)
  237. (or cmdline "")))
  238. (`oracle (format
  239. "sqlplus -s %s < %s > %s"
  240. (org-babel-sql-dbstring-oracle
  241. dbhost dbport dbuser dbpassword database)
  242. (org-babel-process-file-name in-file)
  243. (org-babel-process-file-name out-file)))
  244. (_ (error "No support for the %s SQL engine" engine)))))
  245. (with-temp-file in-file
  246. (insert
  247. (pcase (intern engine)
  248. (`dbi "/format partbox\n")
  249. (`oracle "SET PAGESIZE 50000
  250. SET NEWPAGE 0
  251. SET TAB OFF
  252. SET SPACE 0
  253. SET LINESIZE 9999
  254. SET TRIMOUT ON TRIMSPOOL ON
  255. SET ECHO OFF
  256. SET FEEDBACK OFF
  257. SET VERIFY OFF
  258. SET HEADING ON
  259. SET MARKUP HTML OFF SPOOL OFF
  260. SET COLSEP '|'
  261. ")
  262. ((or `mssql `sqsh) "SET NOCOUNT ON
  263. ")
  264. (`vertica "\\a\n")
  265. (_ ""))
  266. (org-babel-expand-body:sql body params)
  267. ;; "sqsh" requires "go" inserted at EOF.
  268. (if (string= engine "sqsh") "\ngo" "")))
  269. (org-babel-eval command "")
  270. (org-babel-result-cond result-params
  271. (with-temp-buffer
  272. (progn (insert-file-contents-literally out-file) (buffer-string)))
  273. (with-temp-buffer
  274. (cond
  275. ((memq (intern engine) '(dbi mysql postgresql sqsh vertica))
  276. ;; Add header row delimiter after column-names header in first line
  277. (cond
  278. (colnames-p
  279. (with-temp-buffer
  280. (insert-file-contents out-file)
  281. (goto-char (point-min))
  282. (forward-line 1)
  283. (insert "-\n")
  284. (setq header-delim "-")
  285. (write-file out-file)))))
  286. (t
  287. ;; Need to figure out the delimiter for the header row
  288. (with-temp-buffer
  289. (insert-file-contents out-file)
  290. (goto-char (point-min))
  291. (when (re-search-forward "^\\(-+\\)[^-]" nil t)
  292. (setq header-delim (match-string-no-properties 1)))
  293. (goto-char (point-max))
  294. (forward-char -1)
  295. (while (looking-at "\n")
  296. (delete-char 1)
  297. (goto-char (point-max))
  298. (forward-char -1))
  299. (write-file out-file))))
  300. (org-table-import out-file (if (string= engine "sqsh") '(4) '(16)))
  301. (org-babel-reassemble-table
  302. (mapcar (lambda (x)
  303. (if (string= (car x) header-delim)
  304. 'hline
  305. x))
  306. (org-table-to-lisp))
  307. (org-babel-pick-name (cdr (assq :colname-names params))
  308. (cdr (assq :colnames params)))
  309. (org-babel-pick-name (cdr (assq :rowname-names params))
  310. (cdr (assq :rownames params))))))))
  311. (defun org-babel-sql-expand-vars (body vars)
  312. "Expand the variables held in VARS in BODY."
  313. (mapc
  314. (lambda (pair)
  315. (setq body
  316. (replace-regexp-in-string
  317. (format "$%s" (car pair))
  318. (let ((val (cdr pair)))
  319. (if (listp val)
  320. (let ((data-file (org-babel-temp-file "sql-data-")))
  321. (with-temp-file data-file
  322. (insert (orgtbl-to-csv
  323. val '(:fmt (lambda (el) (if (stringp el)
  324. el
  325. (format "%S" el)))))))
  326. data-file)
  327. (if (stringp val) val (format "%S" val))))
  328. body)))
  329. vars)
  330. body)
  331. (defun org-babel-prep-session:sql (_session _params)
  332. "Raise an error because Sql sessions aren't implemented."
  333. (error "SQL sessions not yet implemented"))
  334. (provide 'ob-sql)
  335. ;;; ob-sql.el ends here