diff --git a/CHANGELOG.md b/CHANGELOG.md index d48d9c5..9580eb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ * 2.6.next in progress * Fix [#543](https://github.com/seancorfield/honeysql/issues/543) by supporting both symbols and keywords in named parameters. + * Address [#541](https://github.com/seancorfield/honeysql/issues/541) by specifying the expected result of a formatter function passed to `register-clause!` and adding the example from the README to **Extending HoneySQL**. * Getting Started updated based on feedback from Los Angeles Clojure meetup walkthrough [#539](https://github.com/seancorfield/honeysql/issues/539). * Fix [#538](https://github.com/seancorfield/honeysql/issues/538) by removing `mod` from list of infix operators. * Update Clojure version to 1.12.0. diff --git a/doc/extending-honeysql.md b/doc/extending-honeysql.md index 6011b8d..012e437 100644 --- a/doc/extending-honeysql.md +++ b/doc/extending-honeysql.md @@ -50,6 +50,11 @@ The formatter function will be called with: * The clause name (always as a keyword), * The sequence of arguments provided. +The formatter function should return a vector whose first element is the +generated SQL string and whose remaining elements (if any) are the parameters +lifted from the DSL (for which the generated SQL string should contain `?` +placeholders). + The third argument to `register-clause!` allows you to insert your new clause formatter so that clauses are formatted in the correct order for your SQL dialect. @@ -57,6 +62,26 @@ For example, `:select` comes before `:from` which comes before `:where`. You can call `clause-order` to see what the current ordering of clauses is. + +```clojure +;; the formatter will be passed your new clause and the value associated +;; with that clause in the DSL (which is often a sequence but does not +;; need to be -- it can be whatever syntax you desire in the DSL): +(sql/register-clause! :foobar + (fn [clause x] + (let [[sql & params] + (if (ident? x) + (sql/format-expr x) + (sql/format-dsl x))] + (c/into [(str (sql/sql-kw clause) " " sql)] params))) + :from) ; SELECT ... FOOBAR ... FROM ... +;; example usage: +(sql/format {:select [:a :b] :foobar :baz}) +=> ["SELECT a, b FOOBAR baz"] +(sql/format {:select [:a :b] :foobar {:where [:= :id 1]}}) +=> ["SELECT a, b FOOBAR WHERE id = ?" 1] +``` + > Note: if you call `register-clause!` more than once for the same clause, the last call "wins". This allows you to correct an incorrect clause order insertion by simply calling `register-clause!` again with a different third argument. ## Defining a Helper Function for a New Clause