'SQLC named parameter in generated code for sql containing conditional where
I am using golang SQLC to generate CRUD operation go code from sql.
My select query is like bellow
-- name: SearchProducts :many
SELECT * FROM product
WHERE ( $1::varchar(100) IS NULL OR name LIKE '%$1%' )
AND ( $2::varchar(1000) IS NULL OR description LIKE '%$2%' );
SQLC generating code like bellow
type SearchProductsParams struct {
Column1 string `json:"column_1"`
Column2 string `json:"column_2"`
}
func (q *Queries) SearchProducts(ctx context.Context, arg SearchProductsParams) ([]Product, error) {
rows, err := q.db.QueryContext(ctx, searchProducts, arg.Column1, arg.Column2)
if err != nil {
return nil, err
}
....
Is there any way to configure sqlc so that it will use name & description instead of Column1 & Column2 in SearchProductsParams struct
Solution 1:[1]
You can use named parameters
-- name: SearchProducts :many
SELECT * FROM product
WHERE ( sqlc.arg(email)::varchar(100) IS NULL OR name LIKE '%sqlc.arg(email)%' )
AND ( sqlc.arg(description)::varchar(1000) IS NULL OR description LIKE '%sqlc.arg(description)%' );
You can find the documentation here
When doing selects with conditional filters what it works for me was something like this:
SELECT * FROM product
WHERE
email like CASE
WHEN @filter_email::bool
THEN @email::VARCHAR
ELSE '%'
END
AND
description = CASE
WHEN @filter_description::bool
THEN @description::VARCHAR
ELSE description
END
You have to use the flag filter_email or filter_description flag and the value when you actually want to filter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
