ob-sql.el 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. ;;; ob-sql.el --- Babel Functions for SQL -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2009-2021 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. ;; - dbinstance (currently only used by SAP HANA)
  36. ;; - database
  37. ;; - colnames (default, nil, means "yes")
  38. ;; - result-params
  39. ;; - out-file
  40. ;;
  41. ;; The following are used but not really implemented for SQL:
  42. ;; - colname-names
  43. ;; - rownames
  44. ;; - rowname-names
  45. ;;
  46. ;; Engines supported:
  47. ;; - mysql
  48. ;; - dbi
  49. ;; - mssql
  50. ;; - sqsh
  51. ;; - postgresql (postgres)
  52. ;; - oracle
  53. ;; - vertica
  54. ;; - saphana
  55. ;;
  56. ;; TODO:
  57. ;;
  58. ;; - support for sessions
  59. ;; - support for more engines
  60. ;; - what's a reasonable way to drop table data into SQL?
  61. ;;
  62. ;;; Code:
  63. (require 'ob)
  64. (declare-function org-table-import "org-table" (file arg))
  65. (declare-function orgtbl-to-csv "org-table" (table params))
  66. (declare-function org-table-to-lisp "org-table" (&optional txt))
  67. (declare-function cygwin-convert-file-name-to-windows "cygw32.c" (file &optional absolute-p))
  68. (declare-function sql-set-product "sql" (product))
  69. (defvar sql-connection-alist)
  70. (defvar org-babel-default-header-args:sql '())
  71. (defconst org-babel-header-args:sql
  72. '((engine . :any)
  73. (out-file . :any)
  74. (dbhost . :any)
  75. (dbport . :any)
  76. (dbuser . :any)
  77. (dbpassword . :any)
  78. (dbinstance . :any)
  79. (database . :any))
  80. "SQL-specific header arguments.")
  81. (defun org-babel-expand-body:sql (body params)
  82. "Expand BODY according to the values of PARAMS."
  83. (org-babel-sql-expand-vars
  84. body (org-babel--get-vars params)))
  85. (defun org-babel-edit-prep:sql (info)
  86. "Set `sql-product' in Org edit buffer.
  87. Set `sql-product' in Org edit buffer according to the
  88. corresponding :engine source block header argument."
  89. (let ((product (cdr (assq :engine (nth 2 info)))))
  90. (sql-set-product product)))
  91. (defun org-babel-sql-dbstring-mysql (host port user password database)
  92. "Make MySQL cmd line args for database connection. 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 password (concat "-p" password))
  99. (when database (concat "-D" database))))))
  100. (defun org-babel-sql-dbstring-postgresql (host port user database)
  101. "Make PostgreSQL command line args for database connection.
  102. Pass nil to omit that arg."
  103. (combine-and-quote-strings
  104. (delq nil
  105. (list (when host (concat "-h" host))
  106. (when port (format "-p%d" port))
  107. (when user (concat "-U" user))
  108. (when database (concat "-d" database))))))
  109. (defun org-babel-sql-dbstring-oracle (host port user password database)
  110. "Make Oracle command line arguments for database connection.
  111. If HOST and PORT are nil then don't pass them. This allows you
  112. to use names defined in your \"TNSNAMES\" file. So you can
  113. connect with
  114. <user>/<password>@<host>:<port>/<database>
  115. or
  116. <user>/<password>@<database>
  117. using its alias."
  118. (cond ((and user password database host port)
  119. (format "%s/%s@%s:%s/%s" user password host port database))
  120. ((and user password database)
  121. (format "%s/%s@%s" user password database))
  122. (t (user-error "Missing information to connect to database"))))
  123. (defun org-babel-sql-dbstring-mssql (host user password database)
  124. "Make sqlcmd command line args for database connection.
  125. `sqlcmd' is the preferred command line tool to access Microsoft
  126. SQL Server on Windows and 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-sqsh (host user password database)
  135. "Make sqsh command line args for database connection.
  136. \"sqsh\" is one method to access Sybase or MS SQL via Linux platform"
  137. (mapconcat #'identity
  138. (delq nil
  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))))
  143. " "))
  144. (defun org-babel-sql-dbstring-vertica (host port user password database)
  145. "Make Vertica command line args for database connection.
  146. Pass nil to omit that arg."
  147. (mapconcat #'identity
  148. (delq nil
  149. (list (when host (format "-h %s" host))
  150. (when port (format "-p %d" port))
  151. (when user (format "-U %s" user))
  152. (when password (format "-w %s" (shell-quote-argument password) ))
  153. (when database (format "-d %s" database))))
  154. " "))
  155. (defun org-babel-sql-dbstring-saphana (host port instance user password database)
  156. "Make SAP HANA command line args for database connection.
  157. Pass nil to omit that arg."
  158. (mapconcat #'identity
  159. (delq nil
  160. (list (and host port (format "-n %s:%s" host port))
  161. (and host (not port) (format "-n %s" host))
  162. (and instance (format "-i %d" instance))
  163. (and user (format "-u %s" user))
  164. (and password (format "-p %s"
  165. (shell-quote-argument password)))
  166. (and database (format "-d %s" database))))
  167. " "))
  168. (defun org-babel-sql-convert-standard-filename (file)
  169. "Convert FILE to OS standard file name.
  170. If in Cygwin environment, uses Cygwin specific function to
  171. convert the file name. In a Windows-NT environment, do nothing.
  172. Otherwise, use Emacs' standard conversion function."
  173. (cond ((fboundp 'cygwin-convert-file-name-to-windows)
  174. (format "%S" (cygwin-convert-file-name-to-windows file)))
  175. ((string= "windows-nt" system-type) file)
  176. (t (format "%S" (convert-standard-filename file)))))
  177. (defun org-babel-find-db-connection-param (params name)
  178. "Return database connection parameter NAME.
  179. Given a parameter NAME, if :dbconnection is defined in PARAMS
  180. then look for the parameter into the corresponding connection
  181. defined in `sql-connection-alist`, otherwise look into PARAMS.
  182. Look `sql-connection-alist` (part of SQL mode) for how to define
  183. database connections."
  184. (if (assq :dbconnection params)
  185. (let* ((dbconnection (cdr (assq :dbconnection params)))
  186. (name-mapping '((:dbhost . sql-server)
  187. (:dbport . sql-port)
  188. (:dbuser . sql-user)
  189. (:dbpassword . sql-password)
  190. (:dbinstance . sql-dbinstance)
  191. (:database . sql-database)))
  192. (mapped-name (cdr (assq name name-mapping))))
  193. (cadr (assq mapped-name
  194. (cdr (assoc dbconnection sql-connection-alist)))))
  195. (cdr (assq name params))))
  196. (defun org-babel-execute:sql (body params)
  197. "Execute a block of Sql code with Babel.
  198. This function is called by `org-babel-execute-src-block'."
  199. (let* ((result-params (cdr (assq :result-params params)))
  200. (cmdline (cdr (assq :cmdline params)))
  201. (dbhost (org-babel-find-db-connection-param params :dbhost))
  202. (dbport (org-babel-find-db-connection-param params :dbport))
  203. (dbuser (org-babel-find-db-connection-param params :dbuser))
  204. (dbpassword (org-babel-find-db-connection-param params :dbpassword))
  205. (dbinstance (org-babel-find-db-connection-param params :dbinstance))
  206. (database (org-babel-find-db-connection-param params :database))
  207. (engine (cdr (assq :engine params)))
  208. (colnames-p (not (equal "no" (cdr (assq :colnames params)))))
  209. (in-file (org-babel-temp-file "sql-in-"))
  210. (out-file (or (cdr (assq :out-file params))
  211. (org-babel-temp-file "sql-out-")))
  212. (header-delim "")
  213. (command (cl-case (intern engine)
  214. (dbi (format "dbish --batch %s < %s | sed '%s' > %s"
  215. (or cmdline "")
  216. (org-babel-process-file-name in-file)
  217. "/^+/d;s/^|//;s/(NULL)/ /g;$d"
  218. (org-babel-process-file-name out-file)))
  219. (monetdb (format "mclient -f tab %s < %s > %s"
  220. (or cmdline "")
  221. (org-babel-process-file-name in-file)
  222. (org-babel-process-file-name out-file)))
  223. (mssql (format "sqlcmd %s -s \"\t\" %s -i %s -o %s"
  224. (or cmdline "")
  225. (org-babel-sql-dbstring-mssql
  226. dbhost dbuser dbpassword database)
  227. (org-babel-sql-convert-standard-filename
  228. (org-babel-process-file-name in-file))
  229. (org-babel-sql-convert-standard-filename
  230. (org-babel-process-file-name out-file))))
  231. (mysql (format "mysql %s %s %s < %s > %s"
  232. (org-babel-sql-dbstring-mysql
  233. dbhost dbport dbuser dbpassword database)
  234. (if colnames-p "" "-N")
  235. (or cmdline "")
  236. (org-babel-process-file-name in-file)
  237. (org-babel-process-file-name out-file)))
  238. ((postgresql postgres) (format
  239. "%s%s --set=\"ON_ERROR_STOP=1\" %s -A -P \
  240. footer=off -F \"\t\" %s -f %s -o %s %s"
  241. (if dbpassword
  242. (format "PGPASSWORD=%s " dbpassword)
  243. "")
  244. (or (bound-and-true-p
  245. sql-postgres-program)
  246. "psql")
  247. (if colnames-p "" "-t")
  248. (org-babel-sql-dbstring-postgresql
  249. dbhost dbport dbuser database)
  250. (org-babel-process-file-name in-file)
  251. (org-babel-process-file-name out-file)
  252. (or cmdline "")))
  253. (sqsh (format "sqsh %s %s -i %s -o %s -m csv"
  254. (or cmdline "")
  255. (org-babel-sql-dbstring-sqsh
  256. dbhost dbuser dbpassword database)
  257. (org-babel-sql-convert-standard-filename
  258. (org-babel-process-file-name in-file))
  259. (org-babel-sql-convert-standard-filename
  260. (org-babel-process-file-name out-file))))
  261. (vertica (format "vsql %s -f %s -o %s %s"
  262. (org-babel-sql-dbstring-vertica
  263. dbhost dbport dbuser dbpassword database)
  264. (org-babel-process-file-name in-file)
  265. (org-babel-process-file-name out-file)
  266. (or cmdline "")))
  267. (oracle (format
  268. "sqlplus -s %s < %s > %s"
  269. (org-babel-sql-dbstring-oracle
  270. dbhost dbport dbuser dbpassword database)
  271. (org-babel-process-file-name in-file)
  272. (org-babel-process-file-name out-file)))
  273. (saphana (format "hdbsql %s -I %s -o %s %s"
  274. (org-babel-sql-dbstring-saphana
  275. dbhost dbport dbinstance dbuser dbpassword database)
  276. (org-babel-process-file-name in-file)
  277. (org-babel-process-file-name out-file)
  278. (or cmdline "")))
  279. (t (user-error "No support for the %s SQL engine" engine)))))
  280. (with-temp-file in-file
  281. (insert
  282. (pcase (intern engine)
  283. (`dbi "/format partbox\n")
  284. (`oracle "SET PAGESIZE 50000
  285. SET NEWPAGE 0
  286. SET TAB OFF
  287. SET SPACE 0
  288. SET LINESIZE 9999
  289. SET TRIMOUT ON TRIMSPOOL ON
  290. SET ECHO OFF
  291. SET FEEDBACK OFF
  292. SET VERIFY OFF
  293. SET HEADING ON
  294. SET MARKUP HTML OFF SPOOL OFF
  295. SET COLSEP '|'
  296. ")
  297. ((or `mssql `sqsh) "SET NOCOUNT ON
  298. ")
  299. (`vertica "\\a\n")
  300. (_ ""))
  301. (org-babel-expand-body:sql body params)
  302. ;; "sqsh" requires "go" inserted at EOF.
  303. (if (string= engine "sqsh") "\ngo" "")))
  304. (org-babel-eval command "")
  305. (org-babel-result-cond result-params
  306. (with-temp-buffer
  307. (progn (insert-file-contents-literally out-file) (buffer-string)))
  308. (with-temp-buffer
  309. (cond
  310. ((memq (intern engine) '(dbi mysql postgresql postgres saphana sqsh vertica))
  311. ;; Add header row delimiter after column-names header in first line
  312. (cond
  313. (colnames-p
  314. (with-temp-buffer
  315. (insert-file-contents out-file)
  316. (goto-char (point-min))
  317. (forward-line 1)
  318. (insert "-\n")
  319. (setq header-delim "-")
  320. (write-file out-file)))))
  321. (t
  322. ;; Need to figure out the delimiter for the header row
  323. (with-temp-buffer
  324. (insert-file-contents out-file)
  325. (goto-char (point-min))
  326. (when (re-search-forward "^\\(-+\\)[^-]" nil t)
  327. (setq header-delim (match-string-no-properties 1)))
  328. (goto-char (point-max))
  329. (forward-char -1)
  330. (while (looking-at "\n")
  331. (delete-char 1)
  332. (goto-char (point-max))
  333. (forward-char -1))
  334. (write-file out-file))))
  335. (org-table-import out-file (if (string= engine "sqsh") '(4) '(16)))
  336. (org-babel-reassemble-table
  337. (mapcar (lambda (x)
  338. (if (string= (car x) header-delim)
  339. 'hline
  340. x))
  341. (org-table-to-lisp))
  342. (org-babel-pick-name (cdr (assq :colname-names params))
  343. (cdr (assq :colnames params)))
  344. (org-babel-pick-name (cdr (assq :rowname-names params))
  345. (cdr (assq :rownames params))))))))
  346. (defun org-babel-sql-expand-vars (body vars &optional sqlite)
  347. "Expand the variables held in VARS in BODY.
  348. If SQLITE has been provided, prevent passing a format to
  349. `orgtbl-to-csv'. This prevents overriding the default format, which if
  350. there were commas in the context of the table broke the table as an
  351. argument mechanism."
  352. (mapc
  353. (lambda (pair)
  354. (setq body
  355. (replace-regexp-in-string
  356. (format "$%s" (car pair))
  357. (let ((val (cdr pair)))
  358. (if (listp val)
  359. (let ((data-file (org-babel-temp-file "sql-data-")))
  360. (with-temp-file data-file
  361. (insert (orgtbl-to-csv
  362. val (if sqlite
  363. nil
  364. '(:fmt (lambda (el) (if (stringp el)
  365. el
  366. (format "%S" el))))))))
  367. data-file)
  368. (if (stringp val) val (format "%S" val))))
  369. body)))
  370. vars)
  371. body)
  372. (defun org-babel-prep-session:sql (_session _params)
  373. "Raise an error because Sql sessions aren't implemented."
  374. (error "SQL sessions not yet implemented"))
  375. (provide 'ob-sql)
  376. ;;; ob-sql.el ends here