ob-sql.el 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. ;;; ob-sql.el --- Babel Functions for SQL -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2017 Free Software Foundation, Inc.
  3. ;; Author: Eric Schulte
  4. ;; Keywords: literate programming, reproducible research
  5. ;; Homepage: http://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 <http://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. ;; The following are used but not really implemented for SQL:
  39. ;; - colname-names
  40. ;; - rownames
  41. ;; - rowname-names
  42. ;;
  43. ;; TODO:
  44. ;;
  45. ;; - support for sessions
  46. ;; - support for more engines (currently only supports mysql)
  47. ;; - what's a reasonable way to drop table data into SQL?
  48. ;;
  49. ;;; Code:
  50. (require 'ob)
  51. (declare-function org-table-import "org-table" (file arg))
  52. (declare-function orgtbl-to-csv "org-table" (table params))
  53. (declare-function org-table-to-lisp "org-table" (&optional txt))
  54. (declare-function cygwin-convert-file-name-to-windows "cygw32.c" (file &optional absolute-p))
  55. (defvar org-babel-default-header-args:sql '())
  56. (defconst org-babel-header-args:sql
  57. '((engine . :any)
  58. (out-file . :any)
  59. (dbhost . :any)
  60. (dbport . :any)
  61. (dbuser . :any)
  62. (dbpassword . :any)
  63. (database . :any))
  64. "SQL-specific header arguments.")
  65. (defun org-babel-expand-body:sql (body params)
  66. "Expand BODY according to the values of PARAMS."
  67. (org-babel-sql-expand-vars
  68. body (org-babel--get-vars params)))
  69. (defun org-babel-sql-dbstring-mysql (host port user password database)
  70. "Make MySQL cmd line args for database connection. Pass nil to omit that arg."
  71. (combine-and-quote-strings
  72. (delq nil
  73. (list (when host (concat "-h" host))
  74. (when port (format "-P%d" port))
  75. (when user (concat "-u" user))
  76. (when password (concat "-p" password))
  77. (when database (concat "-D" database))))))
  78. (defun org-babel-sql-dbstring-postgresql (host port user database)
  79. "Make PostgreSQL command line args for database connection.
  80. 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 database (concat "-d" database))))))
  87. (defun org-babel-sql-dbstring-oracle (host port user password database)
  88. "Make Oracle command line args for database connection."
  89. (format "%s/%s@%s:%s/%s" user password host port database))
  90. (defun org-babel-sql-dbstring-mssql (host user password database)
  91. "Make sqlcmd commmand line args for database connection.
  92. `sqlcmd' is the preferred command line tool to access Microsoft
  93. SQL Server on Windows and Linux platform."
  94. (mapconcat #'identity
  95. (delq nil
  96. (list (when host (format "-S \"%s\"" host))
  97. (when user (format "-U \"%s\"" user))
  98. (when password (format "-P \"%s\"" password))
  99. (when database (format "-d \"%s\"" database))))
  100. " "))
  101. (defun org-babel-sql-convert-standard-filename (file)
  102. "Convert the file name to OS standard.
  103. If in Cygwin environment, uses Cygwin specific function to
  104. convert the file name. Otherwise, uses Emacs' standard conversion
  105. function."
  106. (format "\"%s\""
  107. (if (fboundp 'cygwin-convert-file-name-to-windows)
  108. (cygwin-convert-file-name-to-windows file)
  109. (convert-standard-filename file))))
  110. (defun org-babel-execute:sql (body params)
  111. "Execute a block of Sql code with Babel.
  112. This function is called by `org-babel-execute-src-block'."
  113. (let* ((result-params (cdr (assq :result-params params)))
  114. (cmdline (cdr (assq :cmdline params)))
  115. (dbhost (cdr (assq :dbhost params)))
  116. (dbport (cdr (assq :dbport params)))
  117. (dbuser (cdr (assq :dbuser params)))
  118. (dbpassword (cdr (assq :dbpassword params)))
  119. (database (cdr (assq :database params)))
  120. (engine (cdr (assq :engine params)))
  121. (colnames-p (not (equal "no" (cdr (assq :colnames params)))))
  122. (in-file (org-babel-temp-file "sql-in-"))
  123. (out-file (or (cdr (assq :out-file params))
  124. (org-babel-temp-file "sql-out-")))
  125. (header-delim "")
  126. (command (pcase (intern engine)
  127. (`dbi (format "dbish --batch %s < %s | sed '%s' > %s"
  128. (or cmdline "")
  129. (org-babel-process-file-name in-file)
  130. "/^+/d;s/^|//;s/(NULL)/ /g;$d"
  131. (org-babel-process-file-name out-file)))
  132. (`monetdb (format "mclient -f tab %s < %s > %s"
  133. (or cmdline "")
  134. (org-babel-process-file-name in-file)
  135. (org-babel-process-file-name out-file)))
  136. (`mssql (format "sqlcmd %s -s \"\t\" %s -i %s -o %s"
  137. (or cmdline "")
  138. (org-babel-sql-dbstring-mssql
  139. dbhost dbuser dbpassword database)
  140. (org-babel-sql-convert-standard-filename
  141. (org-babel-process-file-name in-file))
  142. (org-babel-sql-convert-standard-filename
  143. (org-babel-process-file-name out-file))))
  144. (`mysql (format "mysql %s %s %s < %s > %s"
  145. (org-babel-sql-dbstring-mysql
  146. dbhost dbport dbuser dbpassword database)
  147. (if colnames-p "" "-N")
  148. (or cmdline "")
  149. (org-babel-process-file-name in-file)
  150. (org-babel-process-file-name out-file)))
  151. (`postgresql (format
  152. "%spsql --set=\"ON_ERROR_STOP=1\" %s -A -P \
  153. footer=off -F \"\t\" %s -f %s -o %s %s"
  154. (if dbpassword
  155. (format "PGPASSWORD=%s " dbpassword)
  156. "")
  157. (if colnames-p "" "-t")
  158. (org-babel-sql-dbstring-postgresql
  159. dbhost dbport dbuser database)
  160. (org-babel-process-file-name in-file)
  161. (org-babel-process-file-name out-file)
  162. (or cmdline "")))
  163. (`oracle (format
  164. "sqlplus -s %s < %s > %s"
  165. (org-babel-sql-dbstring-oracle
  166. dbhost dbport dbuser dbpassword database)
  167. (org-babel-process-file-name in-file)
  168. (org-babel-process-file-name out-file)))
  169. (_ (error "No support for the %s SQL engine" engine)))))
  170. (with-temp-file in-file
  171. (insert
  172. (pcase (intern engine)
  173. (`dbi "/format partbox\n")
  174. (`oracle "SET PAGESIZE 50000
  175. SET NEWPAGE 0
  176. SET TAB OFF
  177. SET SPACE 0
  178. SET LINESIZE 9999
  179. SET ECHO OFF
  180. SET FEEDBACK OFF
  181. SET VERIFY OFF
  182. SET HEADING ON
  183. SET MARKUP HTML OFF SPOOL OFF
  184. SET COLSEP '|'
  185. ")
  186. (`mssql "SET NOCOUNT ON
  187. ")
  188. (_ ""))
  189. (org-babel-expand-body:sql body params)))
  190. (org-babel-eval command "")
  191. (org-babel-result-cond result-params
  192. (with-temp-buffer
  193. (progn (insert-file-contents-literally out-file) (buffer-string)))
  194. (with-temp-buffer
  195. (cond
  196. ((memq (intern engine) '(dbi mysql postgresql))
  197. ;; Add header row delimiter after column-names header in first line
  198. (cond
  199. (colnames-p
  200. (with-temp-buffer
  201. (insert-file-contents out-file)
  202. (goto-char (point-min))
  203. (forward-line 1)
  204. (insert "-\n")
  205. (setq header-delim "-")
  206. (write-file out-file)))))
  207. (t
  208. ;; Need to figure out the delimiter for the header row
  209. (with-temp-buffer
  210. (insert-file-contents out-file)
  211. (goto-char (point-min))
  212. (when (re-search-forward "^\\(-+\\)[^-]" nil t)
  213. (setq header-delim (match-string-no-properties 1)))
  214. (goto-char (point-max))
  215. (forward-char -1)
  216. (while (looking-at "\n")
  217. (delete-char 1)
  218. (goto-char (point-max))
  219. (forward-char -1))
  220. (write-file out-file))))
  221. (org-table-import out-file '(16))
  222. (org-babel-reassemble-table
  223. (mapcar (lambda (x)
  224. (if (string= (car x) header-delim)
  225. 'hline
  226. x))
  227. (org-table-to-lisp))
  228. (org-babel-pick-name (cdr (assq :colname-names params))
  229. (cdr (assq :colnames params)))
  230. (org-babel-pick-name (cdr (assq :rowname-names params))
  231. (cdr (assq :rownames params))))))))
  232. (defun org-babel-sql-expand-vars (body vars)
  233. "Expand the variables held in VARS in BODY."
  234. (mapc
  235. (lambda (pair)
  236. (setq body
  237. (replace-regexp-in-string
  238. (format "$%s" (car pair))
  239. (let ((val (cdr pair)))
  240. (if (listp val)
  241. (let ((data-file (org-babel-temp-file "sql-data-")))
  242. (with-temp-file data-file
  243. (insert (orgtbl-to-csv
  244. val '(:fmt (lambda (el) (if (stringp el)
  245. el
  246. (format "%S" el)))))))
  247. data-file)
  248. (if (stringp val) val (format "%S" val))))
  249. body)))
  250. vars)
  251. body)
  252. (defun org-babel-prep-session:sql (_session _params)
  253. "Raise an error because Sql sessions aren't implemented."
  254. (error "SQL sessions not yet implemented"))
  255. (provide 'ob-sql)
  256. ;;; ob-sql.el ends here