From 67453f4c47545c2f396dfed933b81dd943cfd32d Mon Sep 17 00:00:00 2001 From: Jeremy Dormitzer Date: Tue, 9 Jun 2020 10:05:23 -0400 Subject: [PATCH] Add WHERE clause support --- structlog-mode.el | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/structlog-mode.el b/structlog-mode.el index 31b7ed8..1b4e7a4 100644 --- a/structlog-mode.el +++ b/structlog-mode.el @@ -112,7 +112,33 @@ (defun structlog--get-query-fields (query) "Returns the fields selected by `query'" - (plist-get query :select)) + (vconcat (plist-get query :select))) + +(defun structlog--parse-where-clause (where) + "Parses a single WHERE data clause" + (pcase where + (`(:and . ,clauses) (format "(%s)" + (s-join " AND " + (mapcar #'structlog--parse-where-clause + clauses)))) + (`(:or . ,clauses) (format "(%s)" + (s-join " OR " + (mapcar #'structlog--parse-where-clause + clauses)))) + (`(:not ,clause) (format "NOT %s" + (structlog--parse-where-clause clause))) + (`(:like ,sym ,str) (format "%s->>'%s' LIKE '%s'" + structlog-db-record-field + sym + str)) + (sym (format "%s->'%s' IS NOT NULL" + structlog-db-record-field + where)))) + +(defun structlog--get-where-sql (where) + "Returns the SQL WHERE clause for the `where' data" + (let ((parsed (structlog--parse-where-clause where))) + (and parsed (format "WHERE %s" parsed)))) (defun structlog--get-query-sql (query) "Returns the SQL query to run for `query'" @@ -122,8 +148,10 @@ (order-by (format "ORDER BY %s->'%s'" structlog-db-record-field structlog-time-field)) - (limit (plist-get query :limit))) + (limit (plist-get query :limit)) + (where (plist-get query :where))) (concat base " " + (when where (structlog--get-where-sql where)) " " order-by " " (when limit (format "LIMIT %s" limit))))) @@ -143,7 +171,7 @@ (list log-alist (cl-map 'vector (lambda (field) - (or (alist-get field log-alist) "")) + (or (format "%s" (alist-get field log-alist)) "")) structlog-fields))) structlog-logs)))