-
Notifications
You must be signed in to change notification settings - Fork 126
remove query comments #560 #749
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
Draft
dev-lew
wants to merge
10
commits into
pgdogdev:main
Choose a base branch
from
dev-lew:dev-lew/Remove-query-comments-#560
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.
Draft
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
96ee4b6
Create initial comment removal function
f58258c
Change the implementation for remove_comments
8f0000e
Merge remote-tracking branch 'upstream' into dev-lew/Remove-query-com…
9b5a0bc
Rename variable for clarity
d4dbe41
Upload untested except version
0319387
Simplify removal code
212e143
Preserve non token characters
1ace2e8
Merge remote-tracking branch 'upstream' into dev-lew/Remove-query-com…
f80d1e7
Add retry logic in cache_impl.rs
fe745e1
Refactor according to comments
dev-lew 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
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,4 +1,5 @@ | ||
| use once_cell::sync::Lazy; | ||
| use pg_query::protobuf::ScanToken; | ||
| use pg_query::scan_raw; | ||
| use pg_query::{protobuf::Token, scan}; | ||
| use pgdog_config::QueryParserEngine; | ||
|
|
@@ -11,11 +12,12 @@ use crate::frontend::router::sharding::ContextBuilder; | |
| use super::super::parser::Shard; | ||
| use super::Error; | ||
|
|
||
| static SHARD: Lazy<Regex> = Lazy::new(|| Regex::new(r#"pgdog_shard: *([0-9]+)"#).unwrap()); | ||
| static SHARDING_KEY: Lazy<Regex> = Lazy::new(|| { | ||
| pub static SHARD: Lazy<Regex> = Lazy::new(|| Regex::new(r#"pgdog_shard: *([0-9]+)"#).unwrap()); | ||
| pub static SHARDING_KEY: Lazy<Regex> = Lazy::new(|| { | ||
| Regex::new(r#"pgdog_sharding_key: *(?:"([^"]*)"|'([^']*)'|([0-9a-zA-Z-]+))"#).unwrap() | ||
| }); | ||
| static ROLE: Lazy<Regex> = Lazy::new(|| Regex::new(r#"pgdog_role: *(primary|replica)"#).unwrap()); | ||
| pub static ROLE: Lazy<Regex> = | ||
| Lazy::new(|| Regex::new(r#"pgdog_role: *(primary|replica)"#).unwrap()); | ||
|
|
||
| fn get_matched_value<'a>(caps: &'a regex::Captures<'a>) -> Option<&'a str> { | ||
| caps.get(1) | ||
|
|
@@ -24,23 +26,26 @@ fn get_matched_value<'a>(caps: &'a regex::Captures<'a>) -> Option<&'a str> { | |
| .map(|m| m.as_str()) | ||
| } | ||
|
|
||
| /// Extract shard number from a comment. | ||
| /// Extract shard number from a comment. Additionally returns the entire | ||
| /// comment string if it exists. | ||
| /// | ||
| /// Comment style uses the C-style comments (not SQL comments!) | ||
| /// Comment style for the shard metadata uses the C-style comments (not SQL comments!) | ||
| /// as to allow the comment to appear anywhere in the query. | ||
| /// | ||
| /// See [`SHARD`] and [`SHARDING_KEY`] for the style of comment we expect. | ||
| /// | ||
| pub fn comment( | ||
| pub fn parse_comment( | ||
| query: &str, | ||
| schema: &ShardingSchema, | ||
| ) -> Result<(Option<Shard>, Option<Role>), Error> { | ||
| ) -> Result<(Option<Shard>, Option<Role>, Option<String>), Error> { | ||
| let tokens = match schema.query_parser_engine { | ||
| QueryParserEngine::PgQueryProtobuf => scan(query), | ||
| QueryParserEngine::PgQueryRaw => scan_raw(query), | ||
| } | ||
| .map_err(Error::PgQuery)?; | ||
| let mut shard = None; | ||
| let mut role = None; | ||
| let mut filtered_query = None; | ||
|
|
||
| for token in tokens.tokens.iter() { | ||
| if token.token == Token::CComment as i32 { | ||
|
|
@@ -57,33 +62,95 @@ pub fn comment( | |
| if let Some(cap) = SHARDING_KEY.captures(comment) { | ||
| if let Some(sharding_key) = get_matched_value(&cap) { | ||
| if let Some(schema) = schema.schemas.get(Some(sharding_key.into())) { | ||
| return Ok((Some(schema.shard().into()), role)); | ||
| shard = Some(schema.shard().into()); | ||
| } else { | ||
| let ctx = ContextBuilder::infer_from_from_and_config(sharding_key, schema)? | ||
| .shards(schema.shards) | ||
| .build()?; | ||
| shard = Some(ctx.apply()?); | ||
| } | ||
| let ctx = ContextBuilder::infer_from_from_and_config(sharding_key, schema)? | ||
| .shards(schema.shards) | ||
| .build()?; | ||
| return Ok((Some(ctx.apply()?), role)); | ||
| } | ||
| } | ||
| if let Some(cap) = SHARD.captures(comment) { | ||
| if let Some(shard) = cap.get(1) { | ||
| return Ok(( | ||
| Some( | ||
| shard | ||
| .as_str() | ||
| .parse::<usize>() | ||
| .ok() | ||
| .map(Shard::Direct) | ||
| .unwrap_or(Shard::All), | ||
| ), | ||
| role, | ||
| )); | ||
| if let Some(s) = cap.get(1) { | ||
| shard = Some( | ||
| s.as_str() | ||
| .parse::<usize>() | ||
| .ok() | ||
| .map(Shard::Direct) | ||
| .unwrap_or(Shard::All), | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| Ok((None, role)) | ||
| if has_comments(&tokens.tokens) { | ||
| filtered_query = Some(remove_comments( | ||
| query, | ||
| &tokens.tokens, | ||
| Some(&[&SHARD, &*SHARDING_KEY, &ROLE]), | ||
| )?); | ||
| } | ||
|
|
||
| Ok((shard, role, filtered_query)) | ||
| } | ||
|
|
||
| pub fn has_comments(tokenized_query: &Vec<ScanToken>) -> bool { | ||
| tokenized_query | ||
| .iter() | ||
| .any(|st| st.token == Token::CComment as i32 || st.token == Token::SqlComment as i32) | ||
| } | ||
|
|
||
| pub fn remove_comments( | ||
| query: &str, | ||
| tokenized_query: &Vec<ScanToken>, | ||
| except: Option<&[&Regex]>, | ||
| ) -> Result<String, Error> { | ||
| let mut cursor = 0; | ||
| let mut out = String::with_capacity(query.len()); | ||
|
|
||
| for st in tokenized_query { | ||
| let start = st.start as usize; | ||
| let end = st.end as usize; | ||
|
|
||
| out.push_str(&query[cursor..start]); | ||
|
Author
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. The code involving cursor keeps non token characters (between and at the end of all tokens) like spaces to preserve the original query. We don't want to do anything extra like normalize it or something. |
||
|
|
||
| match st.token { | ||
| t if t == Token::CComment as i32 => { | ||
| let comment = &query[start..end]; | ||
|
|
||
| if let Some(except) = except { | ||
| let rewritten = keep_only_matching(comment, except); | ||
|
|
||
| out.push_str(&rewritten); | ||
| } | ||
| } | ||
| _ => { | ||
| out.push_str(&query[start..end]); | ||
| } | ||
| } | ||
|
|
||
| cursor = end; | ||
| } | ||
|
|
||
| if cursor < query.len() { | ||
| out.push_str(&query[cursor..]); | ||
| } | ||
|
|
||
| Ok(out) | ||
| } | ||
|
|
||
| fn keep_only_matching(comment: &str, regs: &[&Regex]) -> String { | ||
| let mut out = String::new(); | ||
|
|
||
| for reg in regs { | ||
| for m in reg.find_iter(comment) { | ||
| out.push_str(m.as_str()); | ||
| } | ||
| } | ||
|
|
||
| out | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
|
|
||
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.
It is possible that this function is over-generalized and may not need the except parameter.