-
Notifications
You must be signed in to change notification settings - Fork 272
fix: omit cross-shard aggregate helpers on single-shard queries #1474
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
murex971
wants to merge
2
commits into
pgdogdev:main
Choose a base branch
from
murex971:fix-direct-aggregate-helpers
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
89 changes: 89 additions & 0 deletions
89
pgdog/src/frontend/client/query_engine/test/rewrite_aggregate.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| use crate::frontend::router::parser::Shard; | ||
|
|
||
| use super::prelude::*; | ||
| use super::test_sharded_client; | ||
|
|
||
| async fn route_and_rewrite_request(messages: Vec<ProtocolMessage>) -> (Shard, String) { | ||
| let mut client = test_sharded_client(); | ||
| client.client_request = ClientRequest::from(messages); | ||
|
|
||
| let mut engine = QueryEngine::from_client(&client).unwrap(); | ||
| let mut context = QueryEngineContext::new(&mut client); | ||
|
|
||
| let rewrite = engine.parse_and_rewrite(&mut context).unwrap(); | ||
| engine | ||
| .route_query(&mut context, rewrite.as_ref()) | ||
| .await | ||
| .unwrap(); | ||
|
|
||
| let route = context.client_request.route().shard().clone(); | ||
| let sql = context | ||
| .client_request | ||
| .iter() | ||
| .find_map(|message| match message { | ||
| ProtocolMessage::Query(query) => Some(query.query().to_owned()), | ||
| ProtocolMessage::Parse(parse) => Some(parse.query().to_owned()), | ||
| _ => None, | ||
| }) | ||
| .unwrap(); | ||
|
|
||
| (route, sql) | ||
| } | ||
|
|
||
| async fn route_and_rewrite(sql: &str) -> (Shard, String) { | ||
| route_and_rewrite_request(vec![Query::new(sql).into()]).await | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_direct_aggregates_do_not_include_cross_shard_helpers() { | ||
| for function in ["avg", "stddev", "variance"] { | ||
| let (route, sql) = route_and_rewrite(&format!( | ||
| "SELECT {function}(region_id) FROM sharded WHERE id = 1" | ||
| )) | ||
| .await; | ||
|
|
||
| assert!(matches!(route, Shard::Direct(_))); | ||
| assert!( | ||
| !sql.contains("__pgdog_"), | ||
| "direct {function} query included helper columns: {sql}" | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_cross_shard_aggregate_keeps_helpers() { | ||
| let (route, sql) = route_and_rewrite("SELECT stddev(region_id) FROM sharded").await; | ||
|
|
||
| assert!(route.is_all()); | ||
| assert!(sql.contains("__pgdog_count_col0")); | ||
| assert!(sql.contains("__pgdog_sum_col0")); | ||
| assert!(sql.contains("__pgdog_sumsq_col0")); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_direct_extended_aggregate_does_not_include_helpers() { | ||
| let (route, sql) = route_and_rewrite_request(vec![ | ||
| Parse::new_anonymous("SELECT avg(region_id) FROM sharded WHERE id = $1").into(), | ||
| Bind::new_params("", &[Parameter::new(b"1")]).into(), | ||
| Execute::new().into(), | ||
| Sync.into(), | ||
| ]) | ||
| .await; | ||
|
|
||
| assert!(matches!(route, Shard::Direct(_))); | ||
| assert!(!sql.contains("__pgdog_")); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_cross_shard_extended_aggregate_keeps_helpers() { | ||
| let (route, sql) = route_and_rewrite_request(vec![ | ||
| Parse::new_anonymous("SELECT avg(region_id) FROM sharded").into(), | ||
| Bind::new_params("", &[]).into(), | ||
| Execute::new().into(), | ||
| Sync.into(), | ||
| ]) | ||
| .await; | ||
|
|
||
| assert!(route.is_all()); | ||
| assert!(sql.contains("__pgdog_count_col0")); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| use crate::frontend::{ClientRequest, PreparedStatements}; | ||
| use crate::net::messages::bind::{Format, Parameter}; | ||
| use crate::net::{Bind, Parse, ProtocolMessage, Query}; | ||
| use crate::net::{Bind, ProtocolMessage}; | ||
| use crate::unique_id::UniqueId; | ||
|
|
||
| use super::insert::build_split_requests; | ||
|
|
@@ -9,6 +9,21 @@ use super::{ | |
| Error, InsertSplit, PrepareExecute, ShardingKeyUpdate, aggregate::AggregateRewritePlan, | ||
| }; | ||
|
|
||
| fn apply_statement(request: &mut ClientRequest, stmt: &str) { | ||
| for message in request.messages.iter_mut() { | ||
| match message { | ||
| ProtocolMessage::Query(query) => query.set_query(stmt), | ||
| ProtocolMessage::Parse(parse) => { | ||
| parse.set_query(stmt); | ||
| if !parse.anonymous() { | ||
| PreparedStatements::global().write().rewrite(parse); | ||
| } | ||
| } | ||
| _ => {} | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Statement rewrite plan. | ||
| /// | ||
| /// Executed in order of fields in this struct. | ||
|
|
@@ -30,6 +45,11 @@ pub(crate) struct RewritePlan { | |
| /// Rewritten SQL statement. | ||
| pub(crate) stmt: Option<String>, | ||
|
|
||
| /// Rewritten SQL statement without cross-shard aggregate helper columns. | ||
| /// | ||
| /// Restored after routing when a query only needs one shard. | ||
| pub(crate) direct_stmt: Option<String>, | ||
|
|
||
| /// Prepared statements to prepend to the client request. | ||
| /// Each tuple contains (name, statement) for ProtocolMessage::Prepare. | ||
| pub(crate) prepare_rewrites: Vec<PrepareExecute>, | ||
|
|
@@ -52,7 +72,10 @@ pub(crate) struct RewritePlan { | |
|
|
||
| #[derive(Debug, Clone)] | ||
| pub(crate) enum RewriteResult { | ||
| InPlace { offset: Option<OffsetPlan> }, | ||
| InPlace { | ||
| offset: Option<OffsetPlan>, | ||
| direct_stmt: Option<String>, | ||
| }, | ||
| InsertSplit(Vec<ClientRequest>), | ||
| ShardingKeyUpdate(ShardingKeyUpdate), | ||
| } | ||
|
|
@@ -61,8 +84,25 @@ impl RewriteResult { | |
| pub(crate) fn apply_after_parser(&self, request: &mut ClientRequest) -> Result<(), Error> { | ||
| match self { | ||
| Self::InPlace { | ||
| offset: Some(offset), | ||
| } => offset.apply_after_parser(request), | ||
| offset, | ||
| direct_stmt, | ||
| } => { | ||
| if request.is_executable() | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I wouldn't mind moving this to |
||
| && request | ||
| .route | ||
| .as_ref() | ||
| .is_some_and(|route| !route.is_cross_shard()) | ||
| && let Some(stmt) = direct_stmt | ||
| { | ||
| apply_statement(request, stmt); | ||
| } | ||
|
|
||
| if let Some(offset) = offset { | ||
| offset.apply_after_parser(request)?; | ||
| } | ||
|
|
||
| Ok(()) | ||
| } | ||
| _ => Ok(()), | ||
| } | ||
| } | ||
|
|
@@ -100,23 +140,6 @@ impl RewritePlan { | |
| Ok(()) | ||
| } | ||
|
|
||
| /// Apply the rewrite plan to a Parse message by updating the SQL. | ||
| pub(crate) fn apply_parse(&self, parse: &mut Parse) { | ||
| if let Some(ref stmt) = self.stmt { | ||
| parse.set_query(stmt); | ||
| if !parse.anonymous() { | ||
| PreparedStatements::global().write().rewrite(parse); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Apply the rewrite plan to a Query message by updating the SQL. | ||
| pub(crate) fn apply_query(&self, query: &mut Query) { | ||
| if let Some(ref stmt) = self.stmt { | ||
| query.set_query(stmt); | ||
| } | ||
| } | ||
|
|
||
| /// Apply the rewrite plan to a ClientRequest. | ||
| pub(crate) fn apply(&self, request: &mut ClientRequest) -> Result<RewriteResult, Error> { | ||
| // Prepend any required Prepare messages for EXECUTE statements. | ||
|
|
@@ -136,12 +159,13 @@ impl RewritePlan { | |
| }); | ||
| } | ||
|
|
||
| if let Some(stmt) = &self.stmt { | ||
| apply_statement(request, stmt); | ||
| } | ||
|
|
||
| for message in request.messages.iter_mut() { | ||
| match message { | ||
| ProtocolMessage::Parse(parse) => self.apply_parse(parse), | ||
| ProtocolMessage::Query(query) => self.apply_query(query), | ||
| ProtocolMessage::Bind(bind) => self.apply_bind(bind)?, | ||
| _ => {} | ||
| if let ProtocolMessage::Bind(bind) = message { | ||
| self.apply_bind(bind)?; | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -163,6 +187,7 @@ impl RewritePlan { | |
|
|
||
| Ok(RewriteResult::InPlace { | ||
| offset: self.offset.clone(), | ||
| direct_stmt: self.direct_stmt.clone(), | ||
| }) | ||
| } | ||
| } | ||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it would cool to have a
rollback_aggregatesfunction (should be pretty easy to remove the helper columns we added) and only then calldeparse. That way, queries without aggregates bypass the deparse step and remain fast!