ob-sql.el 15 KB

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