Function: emacsql-with-bind

emacsql-with-bind is a macro defined in emacsql.el.

Signature

(emacsql-with-bind CONNECTION SQL-AND-ARGS &rest BODY)

Documentation

For each result row bind the column names for each returned row.

Returns the result of the last evaluated BODY.

All column names must be provided in the query ($ and * are not allowed). Hint: all of the bound identifiers must be known at compile time. For example, in the expression below the variables name and phone will be bound for the body.

  (emacsql-with-bind db [:select [name phone] :from people]
    (message "Found %s with %s" name phone))

  (emacsql-with-bind db ([:select [name phone]
                          :from people
                          :where (= name $1)] my-name)
    (message "Found %s with %s" name phone))

Each column must be a plain symbol, no expressions allowed here.

Source Code

;; Defined in ~/.emacs.d/elpa/emacsql-20261001.1544/emacsql.el
(defmacro emacsql-with-bind (connection sql-and-args &rest body)
  "For each result row bind the column names for each returned row.
Returns the result of the last evaluated BODY.

All column names must be provided in the query ($ and * are not
allowed).  Hint: all of the bound identifiers must be known at
compile time.  For example, in the expression below the variables
`name' and `phone' will be bound for the body.

  (emacsql-with-bind db [:select [name phone] :from people]
    (message \"Found %s with %s\" name phone))

  (emacsql-with-bind db ([:select [name phone]
                          :from people
                          :where (= name $1)] my-name)
    (message \"Found %s with %s\" name phone))

Each column must be a plain symbol, no expressions allowed here."
  (declare (indent 2))
  (let ((sql (if (vectorp sql-and-args) sql-and-args (car sql-and-args)))
        (args (and (not (vectorp sql-and-args)) (cdr sql-and-args))))
    (cl-assert (eq :select (elt sql 0)))
    (let ((vars (elt sql 1)))
      (when (eq vars '*)
        (error "Must explicitly list columns in `emacsql-with-bind'"))
      (cl-assert (cl-every #'symbolp vars))
      `(let ((emacsql--results (emacsql ,connection ,sql ,@args))
             (emacsql--final nil))
         (dolist (emacsql--result emacsql--results emacsql--final)
           (setq emacsql--final
                 (cl-destructuring-bind ,(cl-coerce vars 'list) emacsql--result
                   ,@body)))))))