|
1 | 1 | use std::collections::HashMap; |
2 | 2 |
|
| 3 | +use regex::Regex; |
3 | 4 | use sqlparser::{ |
4 | 5 | ast::Statement, |
5 | 6 | dialect::{Dialect, PostgreSqlDialect}, |
@@ -39,7 +40,7 @@ impl Dialect for MySqlDialectWithBackTicks { |
39 | 40 | } |
40 | 41 |
|
41 | 42 | lazy_static! { |
42 | | - static ref SIGMA_WORKAROUND: regex::Regex = regex::Regex::new(r#"(?s)^\s*with\s+nsp\sas\s\(.*nspname\s=\s(?P<nspname>'[^']+'|\$\d+).*\),\s+tbl\sas\s\(.*relname\s=\s(?P<relname>'[^']+'|\$\d+).*\).*$"#).unwrap(); |
| 43 | + static ref SIGMA_WORKAROUND: Regex = Regex::new(r#"(?s)^\s*with\s+nsp\sas\s\(.*nspname\s=\s.*\),\s+tbl\sas\s\(.*relname\s=\s.*\).*select\s+attname.*from\spg_attribute.*$"#).unwrap(); |
43 | 44 | } |
44 | 45 |
|
45 | 46 | pub fn parse_sql_to_statements( |
@@ -184,33 +185,17 @@ pub fn parse_sql_to_statements( |
184 | 185 | ); |
185 | 186 |
|
186 | 187 | // Sigma Computing WITH query workaround |
187 | | - let query = match SIGMA_WORKAROUND.captures(&query) { |
188 | | - Some(c) => { |
189 | | - let nspname = c.name("nspname").unwrap().as_str(); |
190 | | - let relname = c.name("relname").unwrap().as_str(); |
191 | | - format!( |
192 | | - " |
193 | | - select |
194 | | - attname, |
195 | | - typname, |
196 | | - description |
197 | | - from pg_attribute a |
198 | | - join pg_type on atttypid = pg_type.oid |
199 | | - left join pg_description on |
200 | | - attrelid = objoid and |
201 | | - attnum = objsubid |
202 | | - join pg_catalog.pg_namespace nsp ON nspname = {} |
203 | | - join pg_catalog.pg_class tbl ON relname = {} and relnamespace = nsp.oid |
204 | | - where |
205 | | - attnum > 0 and |
206 | | - attrelid = tbl.oid |
207 | | - order by attnum |
208 | | - ; |
209 | | - ", |
210 | | - nspname, relname |
211 | | - ) |
212 | | - } |
213 | | - None => query, |
| 188 | + let query = if SIGMA_WORKAROUND.is_match(&query) { |
| 189 | + let relnamespace_re = Regex::new(r#"(?s)from\spg_catalog\.pg_class\s+where\s+relname\s=\s(?P<relname>'(?:[^']|'')+'|\$\d+)\s+and\s+relnamespace\s=\s\(select\soid\sfrom\snsp\)"#).unwrap(); |
| 190 | + let relnamespace_replaced = relnamespace_re.replace( |
| 191 | + &query, |
| 192 | + "from pg_catalog.pg_class join nsp on relnamespace = nsp.oid where relname = $relname", |
| 193 | + ); |
| 194 | + let attrelid_re = Regex::new(r#"(?s)left\sjoin\spg_description\son\s+attrelid\s=\sobjoid\sand\s+attnum\s=\sobjsubid\s+where\s+attnum\s>\s0\s+and\s+attrelid\s=\s\(select\soid\sfrom\stbl\)"#).unwrap(); |
| 195 | + let attrelid_replaced = attrelid_re.replace(&relnamespace_replaced, "left join pg_description on attrelid = objoid and attnum = objsubid join tbl on attrelid = tbl.oid where attnum > 0"); |
| 196 | + attrelid_replaced.to_string() |
| 197 | + } else { |
| 198 | + query |
214 | 199 | }; |
215 | 200 |
|
216 | 201 | // Metabase |
|
0 commit comments