-
Notifications
You must be signed in to change notification settings - Fork 4
Fix case-sensitive VISUALISE column reference validation #143
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
cpsievert
wants to merge
1
commit into
posit-dev:main
Choose a base branch
from
cpsievert:fix/case-insensitive-visualise-columns
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
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
Some comments aren't visible on the classic Files Changed page.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -33,6 +33,71 @@ use crate::reader::Reader; | |
| #[cfg(all(feature = "duckdb", test))] | ||
| use crate::reader::DuckDBReader; | ||
|
|
||
| // ============================================================================= | ||
| // Column Name Normalization | ||
| // ============================================================================= | ||
|
|
||
| /// Normalize aesthetic column references to match the actual schema column names. | ||
| /// | ||
| /// DuckDB lowercases unquoted identifiers, but users may write column names in | ||
| /// any case in VISUALISE/MAPPING clauses. Since ggsql quotes column names in | ||
| /// generated SQL (making them case-sensitive), we must normalize references to | ||
| /// match the actual column names returned by the database. | ||
| /// | ||
| /// This function walks all aesthetic mappings (global and per-layer) and replaces | ||
| /// column names with the matching schema column name (matched case-insensitively). | ||
| fn normalize_column_names(specs: &mut [Plot], layer_schemas: &[Schema]) { | ||
| for spec in specs { | ||
| // Normalize global mappings using the first layer's schema (global mappings | ||
| // are merged into all layers, so any layer's schema suffices for normalization) | ||
|
Comment on lines
+51
to
+52
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. This assertion is wrong. Each layer only takes from the global mapping what their data source and aesthetic requirements dictates. It's better to wait until global mapping has been merged into the layers and then do the normalisation only for the layers |
||
| if let Some(schema) = layer_schemas.first() { | ||
| let schema_names: Vec<&str> = schema.iter().map(|c| c.name.as_str()).collect(); | ||
| for value in spec.global_mappings.aesthetics.values_mut() { | ||
| normalize_aesthetic_value(value, &schema_names); | ||
cpsievert marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
|
|
||
| // Normalize per-layer mappings and partition_by using each layer's own schema | ||
| for (layer, schema) in spec.layers.iter_mut().zip(layer_schemas.iter()) { | ||
| let schema_names: Vec<&str> = schema.iter().map(|c| c.name.as_str()).collect(); | ||
| for value in layer.mappings.aesthetics.values_mut() { | ||
| normalize_aesthetic_value(value, &schema_names); | ||
| } | ||
| for col in &mut layer.partition_by { | ||
| normalize_column_ref(col, &schema_names); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Resolve a column name to match actual schema casing (case-insensitive). | ||
| /// | ||
| /// Only normalizes when there is no exact match and exactly one case-insensitive | ||
| /// match exists. This preserves correct behavior when the schema contains columns | ||
| /// that differ only by case (e.g., via quoted identifiers like `"Foo"` and `"foo"`). | ||
| fn normalize_column_ref(name: &mut String, schema_names: &[&str]) { | ||
| if schema_names.contains(&name.as_str()) { | ||
| return; | ||
| } | ||
|
|
||
| let name_lower = name.to_lowercase(); | ||
| let matches: Vec<&&str> = schema_names | ||
| .iter() | ||
| .filter(|s| s.to_lowercase() == name_lower) | ||
| .collect(); | ||
|
|
||
| if matches.len() == 1 { | ||
| *name = matches[0].to_string(); | ||
| } | ||
| } | ||
|
|
||
| /// Normalize a single aesthetic value's column name to match schema casing. | ||
| fn normalize_aesthetic_value(value: &mut AestheticValue, schema_names: &[&str]) { | ||
| if let AestheticValue::Column { name, .. } = value { | ||
| normalize_column_ref(name, schema_names); | ||
| } | ||
| } | ||
|
|
||
| // ============================================================================= | ||
| // Validation | ||
| // ============================================================================= | ||
|
|
@@ -570,6 +635,12 @@ pub fn prepare_data_with_reader<R: Reader>(query: &str, reader: &R) -> Result<Pr | |
| .map(|ti| schema::type_info_to_schema(ti)) | ||
| .collect(); | ||
|
|
||
| // Normalize column names in aesthetic references to match actual schema casing. | ||
| // DuckDB lowercases unquoted identifiers, but users may write them in any case | ||
| // in VISUALISE/MAPPING. Since generated SQL quotes column names (case-sensitive), | ||
| // we must normalize before merging or building queries. | ||
| normalize_column_names(&mut specs, &layer_schemas); | ||
|
|
||
| // Merge global mappings into layer aesthetics and expand wildcards | ||
| // Smart wildcard expansion only creates mappings for columns that exist in schema | ||
| merge_global_mappings_into_layers(&mut specs, &layer_schemas); | ||
|
|
@@ -1243,4 +1314,72 @@ mod tests { | |
| // Should have fewer rows than original (binned) | ||
| assert!(layer_df.height() < 100); | ||
| } | ||
|
|
||
| /// Test that VISUALISE column references are matched case-insensitively. | ||
| /// | ||
| /// DuckDB lowercases unquoted identifiers, so `SELECT UPPER_COL` returns a | ||
| /// column named `upper_col`. VISUALISE references like `UPPER_COL AS x` must | ||
| /// be normalized to match the actual schema column name before validation | ||
| /// and query building. | ||
| #[cfg(feature = "duckdb")] | ||
| #[test] | ||
| fn test_case_insensitive_column_references() { | ||
| let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); | ||
|
|
||
| // Create a table with uppercase column names via aliasing | ||
| reader | ||
| .connection() | ||
| .execute( | ||
| "CREATE TABLE case_test AS SELECT 'A' AS category, 10 AS value UNION ALL SELECT 'B', 20", | ||
| duckdb::params![], | ||
| ) | ||
| .unwrap(); | ||
|
|
||
| // VISUALISE references use UPPERCASE but DuckDB stores them as lowercase | ||
| let query = r#" | ||
| SELECT category, value FROM case_test | ||
| VISUALISE CATEGORY AS x, VALUE AS y | ||
| DRAW bar | ||
| "#; | ||
|
|
||
| let result = prepare_data_with_reader(query, &reader); | ||
| assert!( | ||
| result.is_ok(), | ||
| "Case-insensitive column references should work: {:?}", | ||
| result.err() | ||
| ); | ||
|
|
||
| let result = result.unwrap(); | ||
| let layer_df = result.data.get(&naming::layer_key(0)).unwrap(); | ||
| assert_eq!(layer_df.height(), 2); | ||
cpsievert marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
cpsievert marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| /// Mixed-case VISUALISE references (e.g., `CaTeGoRy`) should normalize | ||
| /// to the actual schema column name. | ||
| #[cfg(feature = "duckdb")] | ||
| #[test] | ||
| fn test_mixed_case_column_references() { | ||
| let reader = DuckDBReader::from_connection_string("duckdb://memory").unwrap(); | ||
|
|
||
| reader | ||
| .connection() | ||
| .execute( | ||
| "CREATE TABLE mixed_case AS SELECT 'A' AS category, 10 AS value UNION ALL SELECT 'B', 20", | ||
| duckdb::params![], | ||
| ) | ||
| .unwrap(); | ||
|
|
||
| let query = r#" | ||
| SELECT category, value FROM mixed_case | ||
| VISUALISE CaTeGoRy AS x, VaLuE AS y | ||
| DRAW bar | ||
| "#; | ||
|
|
||
| let result = prepare_data_with_reader(query, &reader); | ||
| assert!( | ||
| result.is_ok(), | ||
| "Mixed-case column references should be normalized: {:?}", | ||
| result.err() | ||
| ); | ||
| } | ||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.