ob-sql.el 15 KB

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