So, change_global_var is called 3 times for -- one for inserting and two for
comparison. I expected that it would call function one time, save result and
use saved result for comparisons and insertion. Such behaviour is very
confusing and should be documented or fixed.
Another kind of useful optimization is calling deterministic function
without arguments only once for entire table. Currently, it is called for
each row. It is unlikely to be important optimization, but can be
> On Nov 10, 2017, at 9:51 AM, korablev <[hidden email]> wrote:
> I have noticed strange behaviour of user functions. Consider following
In reports like this, it really helps if you can clearly state the situation at the start, instead of dumping hundreds of lines of code and output, and expecting the reader to figure out what’s going on.
Down at the end:
> So, change_global_var is called 3 times for -- one for inserting and two for
> comparison. I expected that it would call function one time, save result and
> use saved result for comparisons and insertion.
This is what should have been at the top :)
First off, you didn’t register the function as deterministic, so SQLite has to assume it can return a different result every time it’s called, even with the same arguments. That immediately prevents the kind of optimization you wanted.
As for deterministic functions, I asked a similar question a month or two ago, about factoring multiple calls out of a query. You can find list archives and read the thread. It doesn’t sound likely to happen.
Jens Alfke-2 wrote
> First off, you didn’t register the function as deterministic, so SQLite
> has to assume it can return a different result every time it’s called,
> even with the same arguments. That immediately prevents the kind of
> optimization you wanted.
I guess, it doesn't really matter whether function is deterministic or not.
It is rather about how aliases should work. To prove it I have found
"alias.test" in test folder. There is a comment:
# Aliases are currently evaluated twice. We might try to change this
# in the future. But not now.
The test is quite old, but still doesn't work.
Moreover, consider query: SELECT x, rand() as random FROM tab WHERE random >
Currently, it would return random numbers which might be less than 0.5 due
to two calls of rand(x).
Well, behaviour of deterministic function is really strange.
SELECT x, sequence() AS y FROM t1 WHERE y>0 AND y<99 AND y!=55 AND y NOT IN
(56,57,58) AND y NOT LIKE 'abc%' AND y%10==2 order by x desc
(Example from alias.test, I have declared sequence() with
Trace for the query above:
Function0 0 0 1 sequence(0) 00 r=func(r)
Integer 0 2 0 00 r=0
Integer 99 3 0 00 r=99
Integer 55 4 0 00 r=55
String8 0 13 0 abc% 00 r='abc%'
Function0 0 0 14 sequence(0) 00 r=func(r)
Function0 3 13 8 like(2) 02 r=func(r[13..14])
Function0 0 0 7 sequence(0) 00 r=func(r)
sequence() is called 3 times in trace(even without branching), instead of
using register r after first call.