ob-sql.el 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. ;;; ob-sql.el --- Babel Functions for SQL -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2016 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 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 user (concat "-U" user))
  85. (when database (concat "-d" database))))))
  86. (defun org-babel-sql-dbstring-oracle (host port user password database)
  87. "Make Oracle command line args for database connection."
  88. (format "%s/%s@%s:%s/%s" user password host port database))
  89. (defun org-babel-sql-dbstring-mssql (host user password database)
  90. "Make sqlcmd commmand line args for database connection.
  91. `sqlcmd' is the preferred command line tool to access Microsoft
  92. SQL Server on Windows and Linux platform."
  93. (mapconcat #'identity
  94. (delq nil
  95. (list (when host (format "-S \"%s\"" host))
  96. (when user (format "-U \"%s\"" user))
  97. (when password (format "-P \"%s\"" password))
  98. (when database (format "-d \"%s\"" database))))
  99. " "))
  100. (defun org-babel-sql-convert-standard-filename (file)
  101. "Convert the file name to OS standard.
  102. If in Cygwin environment, uses Cygwin specific function to
  103. convert the file name. Otherwise, uses Emacs' standard conversion
  104. function."
  105. (format "\"%s\""
  106. (if (fboundp 'cygwin-convert-file-name-to-windows)
  107. (cygwin-convert-file-name-to-windows file)
  108. (convert-standard-filename file))))
  109. (defun org-babel-execute:sql (body params)
  110. "Execute a block of Sql code with Babel.
  111. This function is called by `org-babel-execute-src-block'."
  112. (let* ((result-params (cdr (assoc :result-params params)))
  113. (cmdline (cdr (assoc :cmdline params)))
  114. (dbhost (cdr (assoc :dbhost params)))
  115. (dbport (cdr (assq :dbport params)))
  116. (dbuser (cdr (assoc :dbuser params)))
  117. (dbpassword (cdr (assoc :dbpassword params)))
  118. (database (cdr (assoc :database params)))
  119. (engine (cdr (assoc :engine params)))
  120. (colnames-p (not (equal "no" (cdr (assoc :colnames params)))))
  121. (in-file (org-babel-temp-file "sql-in-"))
  122. (out-file (or (cdr (assoc :out-file params))
  123. (org-babel-temp-file "sql-out-")))
  124. (header-delim "")
  125. (command (pcase (intern engine)
  126. (`dbi (format "dbish --batch %s < %s | sed '%s' > %s"
  127. (or cmdline "")
  128. (org-babel-process-file-name in-file)
  129. "/^+/d;s/^|//;s/(NULL)/ /g;$d"
  130. (org-babel-process-file-name out-file)))
  131. (`monetdb (format "mclient -f tab %s < %s > %s"
  132. (or cmdline "")
  133. (org-babel-process-file-name in-file)
  134. (org-babel-process-file-name out-file)))
  135. (`mssql (format "sqlcmd %s -s \"\t\" %s -i %s -o %s"
  136. (or cmdline "")
  137. (org-babel-sql-dbstring-mssql
  138. dbhost dbuser dbpassword database)
  139. (org-babel-sql-convert-standard-filename
  140. (org-babel-process-file-name in-file))
  141. (org-babel-sql-convert-standard-filename
  142. (org-babel-process-file-name out-file))))
  143. (`mysql (format "mysql %s %s %s < %s > %s"
  144. (org-babel-sql-dbstring-mysql
  145. dbhost dbport dbuser dbpassword database)
  146. (if colnames-p "" "-N")
  147. (or cmdline "")
  148. (org-babel-process-file-name in-file)
  149. (org-babel-process-file-name out-file)))
  150. (`postgresql (format
  151. "psql --set=\"ON_ERROR_STOP=1\" %s -A -P \
  152. footer=off -F \"\t\" %s -f %s -o %s %s"
  153. (if colnames-p "" "-t")
  154. (org-babel-sql-dbstring-postgresql
  155. dbhost dbuser database)
  156. (org-babel-process-file-name in-file)
  157. (org-babel-process-file-name out-file)
  158. (or cmdline "")))
  159. (`oracle (format
  160. "sqlplus -s %s < %s > %s"
  161. (org-babel-sql-dbstring-oracle
  162. dbhost dbport dbuser dbpassword database)
  163. (org-babel-process-file-name in-file)
  164. (org-babel-process-file-name out-file)))
  165. (_ (error "No support for the %s SQL engine" engine)))))
  166. (with-temp-file in-file
  167. (insert
  168. (pcase (intern engine)
  169. (`dbi "/format partbox\n")
  170. (`oracle "SET PAGESIZE 50000
  171. SET NEWPAGE 0
  172. SET TAB OFF
  173. SET SPACE 0
  174. SET LINESIZE 9999
  175. SET ECHO OFF
  176. SET FEEDBACK OFF
  177. SET VERIFY OFF
  178. SET HEADING ON
  179. SET MARKUP HTML OFF SPOOL OFF
  180. SET COLSEP '|'
  181. ")
  182. (`mssql "SET NOCOUNT ON
  183. ")
  184. (_ ""))
  185. (org-babel-expand-body:sql body params)))
  186. (org-babel-eval command "")
  187. (org-babel-result-cond result-params
  188. (with-temp-buffer
  189. (progn (insert-file-contents-literally out-file) (buffer-string)))
  190. (with-temp-buffer
  191. (cond
  192. ((memq (intern engine) '(dbi mysql postgresql))
  193. ;; Add header row delimiter after column-names header in first line
  194. (cond
  195. (colnames-p
  196. (with-temp-buffer
  197. (insert-file-contents out-file)
  198. (goto-char (point-min))
  199. (forward-line 1)
  200. (insert "-\n")
  201. (setq header-delim "-")
  202. (write-file out-file)))))
  203. (t
  204. ;; Need to figure out the delimiter for the header row
  205. (with-temp-buffer
  206. (insert-file-contents out-file)
  207. (goto-char (point-min))
  208. (when (re-search-forward "^\\(-+\\)[^-]" nil t)
  209. (setq header-delim (match-string-no-properties 1)))
  210. (goto-char (point-max))
  211. (forward-char -1)
  212. (while (looking-at "\n")
  213. (delete-char 1)
  214. (goto-char (point-max))
  215. (forward-char -1))
  216. (write-file out-file))))
  217. (org-table-import out-file '(16))
  218. (org-babel-reassemble-table
  219. (mapcar (lambda (x)
  220. (if (string= (car x) header-delim)
  221. 'hline
  222. x))
  223. (org-table-to-lisp))
  224. (org-babel-pick-name (cdr (assoc :colname-names params))
  225. (cdr (assoc :colnames params)))
  226. (org-babel-pick-name (cdr (assoc :rowname-names params))
  227. (cdr (assoc :rownames params))))))))
  228. (defun org-babel-sql-expand-vars (body vars)
  229. "Expand the variables held in VARS in BODY."
  230. (mapc
  231. (lambda (pair)
  232. (setq body
  233. (replace-regexp-in-string
  234. (format "$%s" (car pair))
  235. (let ((val (cdr pair)))
  236. (if (listp val)
  237. (let ((data-file (org-babel-temp-file "sql-data-")))
  238. (with-temp-file data-file
  239. (insert (orgtbl-to-csv
  240. val '(:fmt (lambda (el) (if (stringp el)
  241. el
  242. (format "%S" el)))))))
  243. data-file)
  244. (if (stringp val) val (format "%S" val))))
  245. body)))
  246. vars)
  247. body)
  248. (defun org-babel-prep-session:sql (_session _params)
  249. "Raise an error because Sql sessions aren't implemented."
  250. (error "SQL sessions not yet implemented"))
  251. (provide 'ob-sql)
  252. ;;; ob-sql.el ends here