Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chuck-sys opened this issue Nov 27, 2022 · 0 comments

Comments

@chuck-sys
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant