go-jet / jet

Type safe SQL builder with code generation and automatic query result data mapping
Apache License 2.0
2.52k stars 118 forks source link

More convenient way to implement raw/custom operators #338

Closed kblomster closed 5 months ago

kblomster commented 6 months ago

Problem

When we want to call a function that Jet doesn't support natively, we can use jet.Func("funcname", SomeExpression, ...). This is convenient; only the function name needs to be a hardcoded string, while the arguments can be any Jet expression. Jet will take care of serializing the expressions to SQL.

However, if we want to use an operator that Jet doesn't support, say for example ILIKE (aka. ~~*) in postgres, then we have to resort to jet.Raw, which is not nearly as convenient: we have to serialize the operands ourselves in some way. Expressions that are actual columns are easy enough, we can just say someColumn.Name() and put that into the raw string, but if it's a more complex expression I don't see an obvious way of doing it.

Proposed solution

I see that internally Jet does have a function that does almost exactly what I'd like: NewBinaryOperatorExpression(lhs Serializer, rhs Serializer, operator string). If the public API exposed a wrapper around this, something like jet.BinaryOperator(lhs jet.Expression, rhs jet.Expression, operator string) jet.Expression then I could do things like this to implement my own operators:

func ILIKE(lhs jet.StringExpression, rhs jet.StringExpression) jet.BoolExpression {
    return jet.BoolExp(jet.BinaryOperator(lhs, rhs, "~~*"))
}
go-jet commented 6 months ago

Makes sense.

kblomster commented 6 months ago

Thanks! I'm happy with this so I'll close the issue :)

kblomster commented 6 months ago

Actually, reopening this. I've cloned the wiki and added documentation about BinaryOperator to the FAQ in my cloned repo: https://github.com/kblomster/jet/wiki/FAQ#how-to-use-custom-or-currently-unsupported-sql-operators

I'm not sure how easy it is to get wiki changes upstreamed, but this gist suggests a workflow at least: https://gist.github.com/omaraboumrad/35654da0a376c57a2e0ab4d92ad0c339#core-contributors

Let me know if you have feedback on the docs.

go-jet commented 5 months ago

Merged. :+1:

kblomster commented 5 months ago

Thanks! With that I'll consider this issue well addressed. :)