-
Notifications
You must be signed in to change notification settings - Fork 1.4k
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
Support marking columns as system columns via Field's metadata #14362
Open
adriangb
wants to merge
16
commits into
apache:main
Choose a base branch
from
pydantic:system-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
Show all changes
16 commits
Select commit
Hold shift + click to select a range
e21dbce
Support marking columns as system columns via metadata
adriangb 72c36a2
fmt
adriangb 251b6b9
use trait
adriangb 12c4847
import
adriangb c82f556
remove unnecessary collect
adriangb 76b2346
rename method
adriangb ee88d1d
add test for conflicting column names
adriangb 6d0d268
fmt
adriangb 72f2065
more tests
adriangb 0c40c90
fmt
adriangb c472aea
split up tests
adriangb 7eff84e
better tests, handle joins
adriangb 193532d
add header
adriangb 366398f
fix rebase
adriangb 2cae61d
remove comment
adriangb af6e972
cleanup
adriangb 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 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 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,214 @@ | ||
// Licensed to the Apache Software Foundation (ASF) under one | ||
// or more contributor license agreements. See the NOTICE file | ||
// distributed with this work for additional information | ||
// regarding copyright ownership. The ASF licenses this file | ||
// to you under the Apache License, Version 2.0 (the | ||
// "License"); you may not use this file except in compliance | ||
// with the License. You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, | ||
// software distributed under the License is distributed on an | ||
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
// KIND, either express or implied. See the License for the | ||
// specific language governing permissions and limitations | ||
// under the License. | ||
|
||
use std::sync::Arc; | ||
|
||
use arrow::array::record_batch; | ||
use datafusion::arrow::datatypes::{DataType, Field, Schema}; | ||
|
||
use datafusion::common::FieldExt; | ||
use datafusion::{assert_batches_eq, prelude::*}; | ||
|
||
/// This example shows how to mark fields as system columns. | ||
/// System columns are columns which meant to be semi-public stores of the internal details of the table. | ||
/// For example, `ctid` in Postgres would be considered a metadata column | ||
/// (Postgres calls these "system columns", see [the Postgres docs](https://www.postgresql.org/docs/current/ddl-system-columns.html) for more information and examples. | ||
/// Spark has a `_metadata` column that it uses to include details about each file read in a query (see [Spark's docs](https://docs.databricks.com/en/ingestion/file-metadata-column.html)). | ||
/// | ||
/// DataFusion allows fields to be declared as metadata columns by setting the `datafusion.system_column` key in the field's metadata | ||
/// to `true`. | ||
/// | ||
/// As an example of how this works in practice, if you have the following Postgres table: | ||
/// | ||
/// ```sql | ||
/// CREATE TABLE t (x int); | ||
/// INSERT INTO t VALUES (1); | ||
/// ``` | ||
/// | ||
/// And you do a `SELECT * FROM t`, you would get the following schema: | ||
/// | ||
/// ```text | ||
/// +---+ | ||
/// | x | | ||
/// +---+ | ||
/// | 1 | | ||
/// +---+ | ||
/// ``` | ||
/// | ||
/// But if you do `SELECT ctid, * FROM t`, you would get the following schema (ignore the meaning of the value of `ctid`, this is just an example): | ||
/// | ||
/// ```text | ||
/// +-----+---+ | ||
/// | ctid| x | | ||
/// +-----+---+ | ||
/// | 0 | 1 | | ||
/// +-----+---+ | ||
/// ``` | ||
#[tokio::main] | ||
async fn main() { | ||
let batch = record_batch!( | ||
("a", Int32, [1, 2, 3]), | ||
("b", Utf8, ["foo", "bar", "baz"]), | ||
("_row_num", UInt32, [1, 2, 3]) | ||
) | ||
.unwrap(); | ||
let batch = batch | ||
.with_schema(Arc::new(Schema::new(vec![ | ||
Field::new("a", DataType::Int32, true), | ||
Field::new("b", DataType::Utf8, true), | ||
Field::new("_row_num", DataType::UInt32, true).to_system_column(), | ||
]))) | ||
.unwrap(); | ||
|
||
let ctx = SessionContext::new(); | ||
let _ = ctx.register_batch("t", batch); | ||
|
||
let res = ctx | ||
.sql("SELECT a, b FROM t") | ||
.await | ||
.unwrap() | ||
.collect() | ||
.await | ||
.unwrap(); | ||
#[rustfmt::skip] | ||
let expected: Vec<&str> = vec![ | ||
"+---+-----+", | ||
"| a | b |", | ||
"+---+-----+", | ||
"| 1 | foo |", | ||
"| 2 | bar |", | ||
"| 3 | baz |", | ||
"+---+-----+", | ||
]; | ||
assert_batches_eq!(expected, &res); | ||
|
||
let res = ctx | ||
.sql("SELECT _row_num FROM t") | ||
.await | ||
.unwrap() | ||
.collect() | ||
.await | ||
.unwrap(); | ||
#[rustfmt::skip] | ||
let expected: Vec<&str> = vec![ | ||
"+----------+", | ||
"| _row_num |", | ||
"+----------+", | ||
"| 1 |", | ||
"| 2 |", | ||
"| 3 |", | ||
"+----------+", | ||
]; | ||
assert_batches_eq!(expected, &res); | ||
|
||
let res = ctx | ||
.sql("SELECT * FROM t") | ||
.await | ||
.unwrap() | ||
.collect() | ||
.await | ||
.unwrap(); | ||
// does not include _row_num | ||
#[rustfmt::skip] | ||
let expected: Vec<&str> = vec![ | ||
"+---+-----+", | ||
"| a | b |", | ||
"+---+-----+", | ||
"| 1 | foo |", | ||
"| 2 | bar |", | ||
"| 3 | baz |", | ||
"+---+-----+", | ||
]; | ||
assert_batches_eq!(expected, &res); | ||
|
||
let res = ctx | ||
.sql("SELECT *, _row_num FROM t") | ||
.await | ||
.unwrap() | ||
.collect() | ||
.await | ||
.unwrap(); | ||
#[rustfmt::skip] | ||
let expected: Vec<&str> = vec![ | ||
"+---+-----+----------+", | ||
"| a | b | _row_num |", | ||
"+---+-----+----------+", | ||
"| 1 | foo | 1 |", | ||
"| 2 | bar | 2 |", | ||
"| 3 | baz | 3 |", | ||
"+---+-----+----------+", | ||
]; | ||
assert_batches_eq!(expected, &res); | ||
|
||
let res = ctx | ||
.sql("SELECT t._row_num FROM t") | ||
.await | ||
.unwrap() | ||
.collect() | ||
.await | ||
.unwrap(); | ||
#[rustfmt::skip] | ||
let expected: Vec<&str> = vec![ | ||
"+----------+", | ||
"| _row_num |", | ||
"+----------+", | ||
"| 1 |", | ||
"| 2 |", | ||
"| 3 |", | ||
"+----------+", | ||
]; | ||
assert_batches_eq!(expected, &res); | ||
|
||
let res = ctx | ||
.sql("SELECT t.* FROM t") | ||
.await | ||
.unwrap() | ||
.collect() | ||
.await | ||
.unwrap(); | ||
// does not include _row_num | ||
#[rustfmt::skip] | ||
let expected: Vec<&str> = vec![ | ||
"+---+-----+", | ||
"| a | b |", | ||
"+---+-----+", | ||
"| 1 | foo |", | ||
"| 2 | bar |", | ||
"| 3 | baz |", | ||
"+---+-----+", | ||
]; | ||
assert_batches_eq!(expected, &res); | ||
|
||
let res = ctx | ||
.sql("SELECT t.*, _row_num FROM t") | ||
.await | ||
.unwrap() | ||
.collect() | ||
.await | ||
.unwrap(); | ||
#[rustfmt::skip] | ||
let expected: Vec<&str> = vec![ | ||
"+---+-----+----------+", | ||
"| a | b | _row_num |", | ||
"+---+-----+----------+", | ||
"| 1 | foo | 1 |", | ||
"| 2 | bar | 2 |", | ||
"| 3 | baz | 3 |", | ||
"+---+-----+----------+", | ||
]; | ||
assert_batches_eq!(expected, &res); | ||
} |
This file contains 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 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 |
---|---|---|
|
@@ -494,6 +494,29 @@ impl DFSchema { | |
// Project a.id as id TableScan b id | ||
// In this case, there isn't `ambiguous name` problem. When `matches` just contains | ||
// one field without qualifier, we should return it. | ||
// Another scenario where we can disambiguate is when we have a conflict between | ||
// a system column and a non system column. | ||
// In this case we return the non system column. | ||
let mut non_system_columns = HashSet::new(); | ||
for (_, f) in matches.iter() { | ||
if !f.is_system_column() { | ||
non_system_columns.insert(f.name().to_string()); | ||
} | ||
} | ||
let matches_filtered = matches | ||
.iter() | ||
.filter_map(|(q, f)| { | ||
if f.is_system_column() && non_system_columns.contains(f.name()) { | ||
None | ||
} else { | ||
Some((q, f)) | ||
} | ||
}) | ||
.collect::<Vec<_>>(); | ||
if matches_filtered.len() == 1 { | ||
let (q, f) = matches_filtered[0]; | ||
return Ok((*q, *f)); | ||
} | ||
let fields_without_qualifier = matches | ||
.iter() | ||
.filter(|(q, _)| q.is_none()) | ||
|
@@ -1056,6 +1079,107 @@ pub fn qualified_name(qualifier: Option<&TableReference>, name: &str) -> String | |
} | ||
} | ||
|
||
/// Extension trait to manage DataFusion specific metadata on Arrow fields. | ||
pub trait FieldExt { | ||
/// Check if this field is a system columns. | ||
/// | ||
/// System columns are columns which meant to be semi-public stores of the internal details of the table. | ||
/// For example, `ctid` in Postgres would be considered a metadata column | ||
/// (Postgres calls these "system columns", see [the Postgres docs](https://www.postgresql.org/docs/current/ddl-system-columns.html) for more information and examples. | ||
/// Spark has a `_metadata` column that it uses to include details about each file read in a query (see [Spark's docs](https://docs.databricks.com/en/ingestion/file-metadata-column.html)). | ||
/// | ||
/// DataFusion allows fields to be declared as metadata columns by setting the `datafusion.system_column` key in the field's metadata | ||
/// to `true`. | ||
/// | ||
/// As an example of how this works in practice, if you have the following Postgres table: | ||
/// | ||
/// ```sql | ||
/// CREATE TABLE t (x int); | ||
/// INSERT INTO t VALUES (1); | ||
/// ``` | ||
/// | ||
/// And you do a `SELECT * FROM t`, you would get the following schema: | ||
/// | ||
/// ```text | ||
/// +---+ | ||
/// | x | | ||
/// +---+ | ||
/// | 1 | | ||
/// +---+ | ||
/// ``` | ||
/// | ||
/// But if you do `SELECT ctid, * FROM t`, you would get the following schema (ignore the meaning of the value of `ctid`, this is just an example): | ||
/// | ||
/// ```text | ||
/// +-----+---+ | ||
/// | ctid| x | | ||
/// +-----+---+ | ||
/// | 0 | 1 | | ||
/// +-----+---+ | ||
/// ``` | ||
fn is_system_column(&self) -> bool; | ||
|
||
/// Mark this field as a system column. | ||
/// | ||
/// See [`FieldExt::is_system_column`] for more information on what a system column is. | ||
fn to_system_column(self) -> Self; | ||
|
||
/// Mark this field as a non system column by removing the `datafusion.system_column` key from the field's metadata. | ||
/// | ||
/// See [`FieldExt::is_system_column`] for more information on what a system column is. | ||
fn to_non_system_column(self) -> Self; | ||
} | ||
|
||
/// See [`FieldExt`]. | ||
impl FieldExt for Field { | ||
/// Check if this field is a system column. | ||
/// See [`FieldExt::is_system_column`] for more information on what a system column is. | ||
fn is_system_column(&self) -> bool { | ||
self.metadata() | ||
.get("datafusion.system_column") | ||
.map(|v| v.to_lowercase().starts_with("t")) | ||
.unwrap_or(false) | ||
} | ||
|
||
/// Mark this field as a system column. | ||
/// See [`FieldExt::to_system_column`] for more information on what a system column is. | ||
fn to_system_column(mut self) -> Self { | ||
let mut metadata = self.metadata().clone(); | ||
metadata.insert("datafusion.system_column".to_string(), "true".to_string()); | ||
self.set_metadata(metadata); | ||
self | ||
} | ||
|
||
/// Mark this field as a non system column by removing the `datafusion.system_column` key from the field's metadata. | ||
/// See [`FieldExt::to_non_system_column`] for more information on what a system column is. | ||
fn to_non_system_column(mut self) -> Self { | ||
let mut metadata = self.metadata().clone(); | ||
metadata.remove("datafusion.system_column"); | ||
self.set_metadata(metadata); | ||
self | ||
} | ||
} | ||
|
||
impl FieldExt for Arc<Field> { | ||
/// Check if this field is a system column. | ||
/// See [`FieldExt::is_system_column`] for more information on what a system column is. | ||
fn is_system_column(&self) -> bool { | ||
FieldExt::is_system_column(self.as_ref()) | ||
} | ||
|
||
/// Mark this field as a system column. | ||
/// See [`FieldExt::to_system_column`] for more information on what a system column is. | ||
fn to_system_column(self) -> Self { | ||
Arc::new(FieldExt::to_system_column(Arc::unwrap_or_clone(self))) | ||
} | ||
|
||
/// Mark this field as a non system column by removing the `datafusion.system_column` key from the field's metadata. | ||
/// See [`FieldExt::to_non_system_column`] for more information on what a system column is. | ||
fn to_non_system_column(self) -> Self { | ||
Arc::new(FieldExt::to_non_system_column(Arc::unwrap_or_clone(self))) | ||
} | ||
Comment on lines
+1170
to
+1180
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. Can probably make these no op / zero cost by calling |
||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use crate::assert_contains; | ||
|
This file contains 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 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
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.
Make it a const?
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.
👍🏻 will do next iteration