ob-sql.el 12 KB

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