Fix query function returned data processing logic
[org-tag-eldoc.git] / org-tag-eldoc-database.el
blobb1e8b694d3ec0e385cd72fa15e46f7d1409c6633
1 ;;; org-tag-eldoc-database.el --- org-tag-eldoc database storage -*- lexical-binding: t; -*-
2 ;; -*- coding: utf-8 -*-
4 ;; Copyright (C) 2024-2025 Christopher M. Miles, all rights reserved.
6 ;;; Commentary:
10 ;;; Code:
12 (require 'sqlite nil t)
15 (defcustom org-tag-eldoc-database-file
16 (expand-file-name ".org-tag-eldoc-database.db" user-emacs-directory)
17 "The location of org-tag-eldoc SQLite3 database."
18 :type 'string
19 :safe #'stringp
20 :group 'org-tags)
22 (defmacro org-tag-eldoc-database--execute-with-db (&rest body)
23 "A macro for execute BODY with database."
24 `(if (sqlite-available-p)
25 (let ((db (sqlite-open org-tag-eldoc-database-file)))
26 (prog1 db
27 ,@body
28 (sqlite-close db)))
29 (error (format "[org-tag-eldoc] Error: database backend SQLite support of Emacs not available!"))))
31 ;;; TEST: expand the macro
32 ;; (macroexpand-all
33 ;; '(org-tag-eldoc-database--execute-with-db
34 ;; (sqlite-select db "SELECT 1+1;")
35 ;; (sqlite-execute db "SELECT 1+1;")))
37 ;;;###autoload
38 (defun org-tag-eldoc-database--initlize ()
39 "Initialize the default SQLite3 database file `org-tag-eldoc-database-file'."
40 ;; Create the empty SQLite3 database file.
41 (unless (file-exists-p org-tag-eldoc-database-file)
42 (shell-command
43 (format "sqlite3 %s \"VACUUM\";" org-tag-eldoc-database-file))
44 (org-tag-eldoc-database--execute-with-db
45 (sqlite-execute db (format "CREATE TABLE 'org-tag-eldoc' (tag VARCHAR, explanation TEXT);")))))
47 ;;;###autoload
48 (org-tag-eldoc-database--initlize)
50 (defun org-tag-eldoc-database-query (tag)
51 "Query TAG for explanation in database."
52 (org-tag-eldoc-database--execute-with-db
53 (setq org-tag-eldoc--explanation
54 (caar
55 (sqlite-select db (format "SELECT explanation from 'org-tag-eldoc' WHERE tag = '%s';" tag))))))
57 (defun org-tag-eldoc-database-save (tag explanation)
58 "Save TAG and EXPLANATION into database."
59 (org-tag-eldoc-database--execute-with-db
60 (sqlite-execute db (format "INSERT INTO 'org-tag-eldoc' (tag, explanation) VALUES ('%s', '%s');" tag explanation)))
61 ;; Still return the `explanation' after save to database.
62 explanation)
66 (provide 'org-tag-eldoc-database)
68 ;;; org-tag-eldoc-database.el ends here