-
Notifications
You must be signed in to change notification settings - Fork 71
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
Variable (decided at runtime) number of ?
substitutions?
#263
Comments
There are a few ways this can be done. The first way is to write the query with the expectation that every time you run this query, you'll always pass in every value. This involves making use of coalesce. INSERT INTO blog_tags (entry_id, tag) VALUES (coalesce(?, currval(blog_entries_entry_id_seq)), ?) The next option is to use CTEs and WITH
options (keyword, price) AS (VALUES (?, ?))
SELECT
*
FROM
foo
, options
WHERE
CASE WHEN options.price IS NOT NULL THEN foo.price && options.price END
AND CASE WHEN options.keyword IS NOT NULL THEN to_tsvector(foo.name) @@ plainto_tsquery(options.price) END The last method involves creating a import Data.List (intercalate)
import Database.PostgreSQL.Simple.ToField (ToField(..), Action(..))
data FooSearch = FooSearch
{ keyword :: Maybe Text
, price :: PGRange Int
}
instance ToField FooSearch where
toField s = buildWhereClause
[ if price s == (PGRange NegInfinity PosInfinity) then Nothing else Just [ Plain "price :: INT <@ ", toField $ price s, Plain " :: INT4RANGE" ]
, (\x -> [ Plain "to_tsvector(name) @@ plainto_tsquery(", toField x, Plain ")" ]) <$> keyword s
]
buildWhereClause :: [Maybe [Action]] -> Action
buildWhereClause = combineActionsWith (Plain " AND ")
combineActionsWith :: Action -> [Maybe [Action]] -> Action
combineActionsWith joiner xs = case intercalate [joiner] (catMaybes xs) of
[] -> Plain "1 = 1"
xs' -> Many xs' If you run it like this: query "SELECT * FROM foo WHERE ?" (Only $ FooSearch Nothing $ PGRange NegInfinity PosInfinity) You get a query that looks like this: SELECT * FROM foo WHERE 1 = 1 |
Thank you very much for the inspiration! 💞 |
If I have a query that once takes
(a,b)
and the other time only(Only a)
, how to do that?For the time being, this seems sensible:
But, I think, I’d much rather like to have a possibility to return an empty
Action
somehow…Is there anything available already?
The text was updated successfully, but these errors were encountered: