branch: elpa/emacsql commit adfbc7ed837d5757c5681d5d2e830c3d43b3201a Author: Christopher Wellons <well...@nullprogram.com> Commit: Christopher Wellons <well...@nullprogram.com>
Add emacsql-show-last-sql. --- README.md | 4 ++++ emacsql.el | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/README.md b/README.md index 12a8faa210..d1998e8d6c 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,10 @@ shouldn't impact normal use of the database. ;; => (("Jeff" 1000) ("Susan" 1001)) ``` +When editing these structured SQL statements, the `M-x +emacsql-show-last-sql` command (think `eval-last-sexp`) is useful for +seeing what the actual SQL expression will become when compiled. + ## Schema A table schema is a vector of column specifications, or a list diff --git a/emacsql.el b/emacsql.el index 64993134b7..2196d282ed 100644 --- a/emacsql.el +++ b/emacsql.el @@ -711,6 +711,54 @@ definitions for return from a `emacsql-defexpander'." (emacsql-defexpander :vacuum () (list "VACUUM")) +;; User interaction functions: + +(defvar emacsql-show-buffer-name "*emacsql-show*" + "Name of the buffer for displaying intermediate SQL.") + +(defun emacsql--indent () + "Indent and wrap the SQL expression in the current buffer." + (interactive) + (save-excursion + (setf (point) (point-min)) + (let ((case-fold-search nil)) + (while (search-forward-regexp " [A-Z]+" nil :no-error) + (when (> (current-column) (* fill-column 0.8)) + (backward-word) + (insert "\n ")))))) + +(defun emacsql-show-sql (string) + "Fontify and display the SQL expression in STRING." + (let ((fontified + (with-temp-buffer + (insert string) + (sql-mode) + (with-no-warnings ;; autoloaded by previous line + (sql-highlight-sqlite-keywords)) + (font-lock-fontify-buffer) + (emacsql--indent) + (buffer-string)))) + (with-current-buffer (get-buffer-create emacsql-show-buffer-name) + (if (< (length string) fill-column) + (message "%s" fontified) + (let ((buffer-read-only nil)) + (erase-buffer) + (insert fontified)) + (special-mode) + (visual-line-mode) + (pop-to-buffer (current-buffer)))))) + +(defun emacsql-flatten-sql (sql) + "Convert a structured SQL into a flat string for display." + (cl-destructuring-bind (string . vars) (emacsql-expand sql) + (apply #'format string (cl-loop for i from 1 to (length vars) + collect (intern (format "$%d" i)))))) + +(defun emacsql-show-last-sql () + "Display the compiled SQL of the structured SQL expression before point." + (interactive) + (emacsql-show-sql (emacsql-flatten-sql (preceding-sexp)))) + (provide 'emacsql) ;;; emacsql.el ends here