Monday, November 26, 2012

Playing cheat code in Jasper iReport

where 1=1 $P!{Parameter_value}, this code is so beautiful.

I learned a trick on how could I handle false condition on dynamic SQL generation in Jasper iReport. In a conditional SQL select statement, result set is return only if the condition is true, otherwise I'll see nothing. Usually this is what I did everyday.

Now I have a weird requirement, if the condition is not match (meaning false), I still want to see the result set without the condition. That can be done, but my way, no way, so much ugly. Until I meet where 1=1 $P!{Parameter_value}, this guy did a very good job in keeping the code clean. I like this guy, a very smart guy.

I suppose to put the condition validation of a select statement in the where clause, but I take it out instead. Giving an order to Jasper to hold this value for me, say Parameter_value. Now I append 1=1 at the end of the where clause, become this where 1=1. The first time I see this code I though it was a joke because this query will always return a valid result set.

Magic happened when I append $P!{Parameter_value} after where 1=1. Jasper will always compile the Parameter then only compile the whole query statement. If the condition given in $P!{Parameter_value} is valid, then the result set with conditional validation is returned. If the condition given in $P!{Parameter_value} is invalid, then query will become where 1=1, with an empty string at the end, and since 1 always equals to 1, thus it will just return anything without the conditional validation.

This code is like playing cheat, I love it, and like it.

No comments: