You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Support STABLE functions in INSERT statements #213
We took a conservative approach in function evaluation for INSERT: we evaluate immutable expressions (such as 2 + 2 or char_length('postgres')) during planning but reject any other expressions.
This means certain idioms (like using now() to timestamp a row) are unavailable when using pg_shard. The next logical step would be to coerce STABLE functions into constants during INSERT: evaluating them on the master would ensure all replicas receive an identical value.
I spent some time looking into a slightly more general solution to this, calling functions on the master during both INSERT and UPDATE.
I think these queries can all be supported: (this would fix #211)
UPDATE tbl SET column = now(); -- convert now() to a constant before pushing downUPDATE tbl SET column = column + now() -- convert now() to a constant before pushing downUPDATE tbl SET column = func(column) -- okay if func is not VOLATILE, otherwise throw an errorINSERT INTO tbl VALUES (...) -- always okay even if funcs are VOLATILE
RouterModifyTask in multi_router_planner uses the partition value of the column so we'll have to do any evaluation before it's hit. I think we can add two functions, TargetListCallsVolatileWithVar(Query) and EvaluateTargetList(Query)
TargetListCallsVolatileWithVar(Query) is called in ErrorIfModifyQueryNotSupported if this is an UPDATE and for each TargetEntry it walks the expression looking for VOLATILE functions for which one of the parameters (directly or indirectly) contains a Var. This is a pretty simple BFS that will look like contain_mutable_functions except it'll have a few more states and look at fewer kinds of nodes.
EvaluateTargetList(Query) I'm less sure about. It evaluates the expression as far as it can, pruning everything which doesn't require knowing the Var's value from the expression tree. It would be called in MultiRouterPlanCreate just after ErrorIfModifyQueryNotSupported I thiiink it'll look like evaluate_expr, except pg's executor doesn't seem to have any mechanism for walking and partially evaluating an expression, or for evaluating outside of the context of a tuple. Could Andres Freund (@anarazel) or Marco Slot (@marcocitus) chime in if they know how this would work?
Does the above approach sound like it would work?
It gets much easier to implement if we evaluate everything (even VOLATILE) when the expression has no Var's, and push down the unmodified target list of the expression has Vars (keeping the same restriction that all functions must be IMMUTABLE) but that sounds unintuitive and just asking for support requests.
It's also easier to implement if we limit scope to just supporting INSERT. There are no Vars there to confuse anything.
I guess you could recursively find subtrees that don't contain vars (e.g. using expression_tree_walker) and replace them by the result of calling evaluate_expr on the subtree, but I haven't really thought this through :).
I forgot to mention, enabling this will reducing the INSERT performance we've been trying to hard to improve. Maybe anything currently accepted (IMMUTABLE functions) is still pushed down to the workers, and just those expressions which require canonicalization from the master (STABLE and VOLATILE) are evaluated here.
Have you measured the effect of this? I'd be kinda surprised if this has
a significant impact with reasonable functions. If you use pg_sleep(10)
it'll obviously cause degradation, but in comparison to latency to the
workers a simple function evaluation should barely cause a blip.
One thing to consider here are prepared statements - trivially replacing
functions at plan time will cause issues.
Apologies, I don't know how prepared statements work, what's the issue?
With prepared statements one plan is (potentially) reused across several
executions. So if you replace the value at plan time, the values at
execution time will be always the same.
Interesting... So I'm thinking of a query like INSERT INTO table (part_col) VALUES (random()); The plan actually changes depending on what random() returns. We could:
Not support INSERT with a non-constant-expression part column
Not support PREPARE with an INSERT/UPDATE which uses non-IMMUTABLE functions. (Is it possible to know we're running inside a PREPARE?)
Refactor our nodes to not hard-code the target worker, and have the executor figure out which worker to hit. That lets us have the same plan between runs and defer evaluating functions until multi_router_executor starts running.
Looking into this a little more, the router planner/executor is self contained enough that refactoring it to find placements during execution instead of during planning doesn't look very difficult.
The code which prunes and finds the correct shard interval and the shard placements will have to be moved. As far as I can tell nothing relies on those being set during planning.
Some estimates:
Refactor router planner/executor to determine placements during execution: 2 days
Write TargetListCallsVolatileWithVar(Query): 1 day
Write EvaluateTargetList(Query) to mutate the tree and prune all it can: 2 days
Testing and review: 3 days (if I do it I'm sure lots of things will come up. If someone else does it this'll probably be lower)
The benefits:
Sequences work with nextval()
now(), which I think ORMs like to add, starts working
no more worrying about using timestamptz instead of timestamp and getting bit by the STABLE implicit casts
prepared statements now work in the face of updating metadata, where they previously started throwing errors if you moved any shards around (I assume).
I think this is a big enough usability improvement to be worth it. Do these estimates sound reasonable?
random() on an UPDATE which hits many rows should use a different value for every row. So for INSERT we can use VOLATILE functions, but in UPDATE we're stuck with STABLE.
nextval() is also allowed in SELECTs, it's a little weird for users that on INSERT nextval() uses the master's sequence, on UPDATE it's not allowed, and for SELECT it uses the worker's sequence.
Activity
ozgune commentedon Mar 16, 2016
Jason Petersen (@jasonmp85) - if we resolve this issue, will it also fix #240?
jasonmp85 commentedon Mar 18, 2016
Ozgun Erdogan (@ozgune) — Yes, that's one possibility.
lithp commentedon Apr 28, 2016
I spent some time looking into a slightly more general solution to this, calling functions on the master during both INSERT and UPDATE.
I think these queries can all be supported: (this would fix #211)
RouterModifyTaskin multi_router_planner uses the partition value of the column so we'll have to do any evaluation before it's hit. I think we can add two functions,TargetListCallsVolatileWithVar(Query)andEvaluateTargetList(Query)TargetListCallsVolatileWithVar(Query)is called inErrorIfModifyQueryNotSupportedif this is an UPDATE and for eachTargetEntryit walks the expression looking for VOLATILE functions for which one of the parameters (directly or indirectly) contains aVar. This is a pretty simple BFS that will look likecontain_mutable_functionsexcept it'll have a few more states and look at fewer kinds of nodes.EvaluateTargetList(Query)I'm less sure about. It evaluates the expression as far as it can, pruning everything which doesn't require knowing the Var's value from the expression tree. It would be called inMultiRouterPlanCreatejust afterErrorIfModifyQueryNotSupportedI thiiink it'll look likeevaluate_expr, except pg's executor doesn't seem to have any mechanism for walking and partially evaluating an expression, or for evaluating outside of the context of a tuple. Could Andres Freund (@anarazel) or Marco Slot (@marcocitus) chime in if they know how this would work?Does the above approach sound like it would work?
It gets much easier to implement if we evaluate everything (even VOLATILE) when the expression has no Var's, and push down the unmodified target list of the expression has Vars (keeping the same restriction that all functions must be IMMUTABLE) but that sounds unintuitive and just asking for support requests.
It's also easier to implement if we limit scope to just supporting INSERT. There are no Vars there to confuse anything.
marcocitus commentedon Apr 28, 2016
I guess you could recursively find subtrees that don't contain vars (e.g. using expression_tree_walker) and replace them by the result of calling evaluate_expr on the subtree, but I haven't really thought this through :).
lithp commentedon Apr 28, 2016
I forgot to mention, enabling this will reducing the INSERT performance we've been trying to hard to improve. Maybe anything currently accepted (IMMUTABLE functions) is still pushed down to the workers, and just those expressions which require canonicalization from the master (STABLE and VOLATILE) are evaluated here.
lithp commentedon Apr 28, 2016
Yeah, that sounds reasonable. I think we'd need expression_tree_mutator but that's definitely worth looking into.
anarazel commentedon Apr 28, 2016
Hi,
Have you measured the effect of this? I'd be kinda surprised if this has
a significant impact with reasonable functions. If you use pg_sleep(10)
it'll obviously cause degradation, but in comparison to latency to the
workers a simple function evaluation should barely cause a blip.
One thing to consider here are prepared statements - trivially replacing
functions at plan time will cause issues.
Andres
lithp commentedon Apr 28, 2016
Apologies, I don't know how prepared statements work, what's the issue?
anarazel commentedon Apr 28, 2016
lithp commentedon Apr 28, 2016
Interesting... So I'm thinking of a query like
INSERT INTO table (part_col) VALUES (random());The plan actually changes depending on what random() returns. We could:lithp commentedon Apr 29, 2016
Looking into this a little more, the router planner/executor is self contained enough that refactoring it to find placements during execution instead of during planning doesn't look very difficult.
The code which prunes and finds the correct shard interval and the shard placements will have to be moved. As far as I can tell nothing relies on those being set during planning.
Some estimates:
TargetListCallsVolatileWithVar(Query): 1 dayEvaluateTargetList(Query)to mutate the tree and prune all it can: 2 daysThe benefits:
timestamptzinstead oftimestampand getting bit by the STABLE implicit castsI think this is a big enough usability improvement to be worth it. Do these estimates sound reasonable?
lithp commentedon May 2, 2016
Some complications:
random() on an UPDATE which hits many rows should use a different value for every row. So for INSERT we can use VOLATILE functions, but in UPDATE we're stuck with STABLE.
nextval() is also allowed in SELECTs, it's a little weird for users that on INSERT nextval() uses the master's sequence, on UPDATE it's not allowed, and for SELECT it uses the worker's sequence.