Skip to content

Better way to do dynamic WHERE clauses? "apply"ing ScalarExprs to operators. #29

Description

@chuck-sys

Let's say we have a table that looks like this:

CREATE TABLE media (
    id SERIAL PRIMARY KEY,
    title text,
    artist text,
    album text
);

And want to create a query that sometimes searches the fields title, artist, and album. So one query might look like:

SELECT * FROM media WHERE title LIKE "%someTitle%";

But others might look like:

SELECT * FROM media WHERE title LIKE "%someTitle%" AND album LIKE "%someAlbum%";

The way I figure out was to use ScalarExpr:INJECT like so:

;; make-media-single-condition: (list/c symbol? string?) -> scalar-expr-ast?
(define (make-media-single-condition condition)
  (match-let ([(list col val) condition])
    (scalar-expr-qq
      (like (Ident:AST ,(make-ident-ast col))
            (|| "%" (ScalarExpr:AST ,val) "%")))))

(scalar-expr-qq
  (ScalarExpr:INJECT
    ,(string-join
       (map
         (compose sql-ast->string make-media-single-condition)
         conditions)
       " AND ")))])))

Which is a bit hacky but gets the job done. Is there a way to apply the list of ScalarExpr to the and?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions