Skip to content

Commit 4780b67

Browse files
CuteChuanChuantobixdev
authored andcommitted
chore: Format examples in doc strings - expr (apache#18340)
## Which issue does this PR close? Part of apache#16915 ## Rationale for this change Format code examples in documentation comments to improve readability and maintain consistent code style across the codebase. This is part of a multi-PR effort to format all doc comment examples and eventually enable CI checks to enforce this formatting. ## What changes are included in this PR? Run `cargo fmt -p <crate> -- --config format_code_in_doc_comments=true` for the following datasource-related crates: - `datafusion-expr` - `datafusion-expr-common` ## Are these changes tested? No testing needed - this is purely a formatting change with no functional modifications. ## Are there any user-facing changes? No - this only affects documentation formatting.
1 parent f695ff6 commit 4780b67

File tree

12 files changed

+168
-173
lines changed

12 files changed

+168
-173
lines changed

datafusion/expr-common/src/interval_arithmetic.rs

Lines changed: 37 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1670,22 +1670,23 @@ fn cast_scalar_value(
16701670
///
16711671
/// // [1, 2) U {NULL}
16721672
/// let maybe_null = NullableInterval::MaybeNull {
1673-
/// values: Interval::try_new(
1674-
/// ScalarValue::Int32(Some(1)),
1675-
/// ScalarValue::Int32(Some(2)),
1676-
/// ).unwrap(),
1673+
/// values: Interval::try_new(
1674+
/// ScalarValue::Int32(Some(1)),
1675+
/// ScalarValue::Int32(Some(2)),
1676+
/// )
1677+
/// .unwrap(),
16771678
/// };
16781679
///
16791680
/// // (0, ∞)
16801681
/// let not_null = NullableInterval::NotNull {
1681-
/// values: Interval::try_new(
1682-
/// ScalarValue::Int32(Some(0)),
1683-
/// ScalarValue::Int32(None),
1684-
/// ).unwrap(),
1682+
/// values: Interval::try_new(ScalarValue::Int32(Some(0)), ScalarValue::Int32(None))
1683+
/// .unwrap(),
16851684
/// };
16861685
///
16871686
/// // {NULL}
1688-
/// let null_interval = NullableInterval::Null { datatype: DataType::Int32 };
1687+
/// let null_interval = NullableInterval::Null {
1688+
/// datatype: DataType::Int32,
1689+
/// };
16891690
///
16901691
/// // {4}
16911692
/// let single_value = NullableInterval::from(ScalarValue::Int32(Some(4)));
@@ -1787,22 +1788,26 @@ impl NullableInterval {
17871788
///
17881789
/// ```
17891790
/// use datafusion_common::ScalarValue;
1790-
/// use datafusion_expr_common::operator::Operator;
17911791
/// use datafusion_expr_common::interval_arithmetic::Interval;
17921792
/// use datafusion_expr_common::interval_arithmetic::NullableInterval;
1793+
/// use datafusion_expr_common::operator::Operator;
17931794
///
17941795
/// // 4 > 3 -> true
17951796
/// let lhs = NullableInterval::from(ScalarValue::Int32(Some(4)));
17961797
/// let rhs = NullableInterval::from(ScalarValue::Int32(Some(3)));
17971798
/// let result = lhs.apply_operator(&Operator::Gt, &rhs).unwrap();
1798-
/// assert_eq!(result, NullableInterval::from(ScalarValue::Boolean(Some(true))));
1799+
/// assert_eq!(
1800+
/// result,
1801+
/// NullableInterval::from(ScalarValue::Boolean(Some(true)))
1802+
/// );
17991803
///
18001804
/// // [1, 3) > NULL -> NULL
18011805
/// let lhs = NullableInterval::NotNull {
18021806
/// values: Interval::try_new(
1803-
/// ScalarValue::Int32(Some(1)),
1804-
/// ScalarValue::Int32(Some(3)),
1805-
/// ).unwrap(),
1807+
/// ScalarValue::Int32(Some(1)),
1808+
/// ScalarValue::Int32(Some(3)),
1809+
/// )
1810+
/// .unwrap(),
18061811
/// };
18071812
/// let rhs = NullableInterval::from(ScalarValue::Int32(None));
18081813
/// let result = lhs.apply_operator(&Operator::Gt, &rhs).unwrap();
@@ -1811,22 +1816,27 @@ impl NullableInterval {
18111816
/// // [1, 3] > [2, 4] -> [false, true]
18121817
/// let lhs = NullableInterval::NotNull {
18131818
/// values: Interval::try_new(
1814-
/// ScalarValue::Int32(Some(1)),
1815-
/// ScalarValue::Int32(Some(3)),
1816-
/// ).unwrap(),
1819+
/// ScalarValue::Int32(Some(1)),
1820+
/// ScalarValue::Int32(Some(3)),
1821+
/// )
1822+
/// .unwrap(),
18171823
/// };
18181824
/// let rhs = NullableInterval::NotNull {
1819-
/// values: Interval::try_new(
1820-
/// ScalarValue::Int32(Some(2)),
1821-
/// ScalarValue::Int32(Some(4)),
1822-
/// ).unwrap(),
1825+
/// values: Interval::try_new(
1826+
/// ScalarValue::Int32(Some(2)),
1827+
/// ScalarValue::Int32(Some(4)),
1828+
/// )
1829+
/// .unwrap(),
18231830
/// };
18241831
/// let result = lhs.apply_operator(&Operator::Gt, &rhs).unwrap();
18251832
/// // Both inputs are valid (non-null), so result must be non-null
1826-
/// assert_eq!(result, NullableInterval::NotNull {
1827-
/// // Uncertain whether inequality is true or false
1828-
/// values: Interval::UNCERTAIN,
1829-
/// });
1833+
/// assert_eq!(
1834+
/// result,
1835+
/// NullableInterval::NotNull {
1836+
/// // Uncertain whether inequality is true or false
1837+
/// values: Interval::UNCERTAIN,
1838+
/// }
1839+
/// );
18301840
/// ```
18311841
pub fn apply_operator(&self, op: &Operator, rhs: &Self) -> Result<Self> {
18321842
match op {
@@ -1924,7 +1934,8 @@ impl NullableInterval {
19241934
/// values: Interval::try_new(
19251935
/// ScalarValue::Int32(Some(1)),
19261936
/// ScalarValue::Int32(Some(4)),
1927-
/// ).unwrap(),
1937+
/// )
1938+
/// .unwrap(),
19281939
/// };
19291940
/// assert_eq!(interval.single_value(), None);
19301941
/// ```

datafusion/expr-common/src/signature.rs

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -127,11 +127,10 @@ pub enum Arity {
127127
/// ```
128128
/// # use arrow::datatypes::DataType;
129129
/// # use datafusion_expr_common::signature::{TypeSignature};
130-
/// // Declares the function must be invoked with a single argument of type `Utf8View`.
131-
/// // if a user calls the function with `Utf8` or `LargeUtf8`, DataFusion will
132-
/// // automatically add a cast to `Utf8View` during planning.
133-
/// let type_signature = TypeSignature::Exact(vec![DataType::Utf8View]);
134-
///
130+
/// // Declares the function must be invoked with a single argument of type `Utf8View`.
131+
/// // if a user calls the function with `Utf8` or `LargeUtf8`, DataFusion will
132+
/// // automatically add a cast to `Utf8View` during planning.
133+
/// let type_signature = TypeSignature::Exact(vec![DataType::Utf8View]);
135134
/// ```
136135
///
137136
/// # Example: Timestamps
@@ -144,11 +143,11 @@ pub enum Arity {
144143
/// # use arrow::datatypes::{DataType, TimeUnit};
145144
/// # use datafusion_expr_common::signature::{TIMEZONE_WILDCARD, TypeSignature};
146145
/// let type_signature = TypeSignature::Exact(vec![
147-
/// // A nanosecond precision timestamp with ANY timezone
148-
/// // matches Timestamp(Nanosecond, Some("+0:00"))
149-
/// // matches Timestamp(Nanosecond, Some("+5:00"))
150-
/// // does not match Timestamp(Nanosecond, None)
151-
/// DataType::Timestamp(TimeUnit::Nanosecond, Some(TIMEZONE_WILDCARD.into())),
146+
/// // A nanosecond precision timestamp with ANY timezone
147+
/// // matches Timestamp(Nanosecond, Some("+0:00"))
148+
/// // matches Timestamp(Nanosecond, Some("+5:00"))
149+
/// // does not match Timestamp(Nanosecond, None)
150+
/// DataType::Timestamp(TimeUnit::Nanosecond, Some(TIMEZONE_WILDCARD.into())),
152151
/// ]);
153152
/// ```
154153
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Hash)]
@@ -858,8 +857,8 @@ fn get_data_types(native_type: &NativeType) -> Vec<DataType> {
858857
/// # Examples
859858
///
860859
/// ```
860+
/// use datafusion_common::types::{logical_binary, logical_string, NativeType};
861861
/// use datafusion_expr_common::signature::{Coercion, TypeSignatureClass};
862-
/// use datafusion_common::types::{NativeType, logical_binary, logical_string};
863862
///
864863
/// // Exact coercion that only accepts timestamp types
865864
/// let exact = Coercion::new_exact(TypeSignatureClass::Timestamp);
@@ -868,7 +867,7 @@ fn get_data_types(native_type: &NativeType) -> Vec<DataType> {
868867
/// let implicit = Coercion::new_implicit(
869868
/// TypeSignatureClass::Native(logical_string()),
870869
/// vec![TypeSignatureClass::Native(logical_binary())],
871-
/// NativeType::String
870+
/// NativeType::String,
872871
/// );
873872
/// ```
874873
///
@@ -1275,8 +1274,9 @@ impl Signature {
12751274
/// ```
12761275
/// # use datafusion_expr_common::signature::{Signature, Volatility};
12771276
/// # use arrow::datatypes::DataType;
1278-
/// let sig = Signature::exact(vec![DataType::Int32, DataType::Utf8], Volatility::Immutable)
1279-
/// .with_parameter_names(vec!["count".to_string(), "name".to_string()]);
1277+
/// let sig =
1278+
/// Signature::exact(vec![DataType::Int32, DataType::Utf8], Volatility::Immutable)
1279+
/// .with_parameter_names(vec!["count".to_string(), "name".to_string()]);
12801280
/// ```
12811281
///
12821282
/// # Errors

datafusion/expr/src/expr.rs

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -164,11 +164,11 @@ impl From<sqlparser::ast::NullTreatment> for NullTreatment {
164164
/// # use datafusion_expr::{lit, col, Operator, Expr};
165165
/// // Use the `+` operator to add two columns together
166166
/// let expr = col("c1") + col("c2");
167-
/// assert!(matches!(expr, Expr::BinaryExpr { ..} ));
167+
/// assert!(matches!(expr, Expr::BinaryExpr { .. }));
168168
/// if let Expr::BinaryExpr(binary_expr) = expr {
169-
/// assert_eq!(*binary_expr.left, col("c1"));
170-
/// assert_eq!(*binary_expr.right, col("c2"));
171-
/// assert_eq!(binary_expr.op, Operator::Plus);
169+
/// assert_eq!(*binary_expr.left, col("c1"));
170+
/// assert_eq!(*binary_expr.right, col("c2"));
171+
/// assert_eq!(binary_expr.op, Operator::Plus);
172172
/// }
173173
/// ```
174174
///
@@ -179,12 +179,12 @@ impl From<sqlparser::ast::NullTreatment> for NullTreatment {
179179
/// # use datafusion_common::ScalarValue;
180180
/// # use datafusion_expr::{lit, col, Operator, Expr};
181181
/// let expr = col("c1").eq(lit(42_i32));
182-
/// assert!(matches!(expr, Expr::BinaryExpr { .. } ));
182+
/// assert!(matches!(expr, Expr::BinaryExpr { .. }));
183183
/// if let Expr::BinaryExpr(binary_expr) = expr {
184-
/// assert_eq!(*binary_expr.left, col("c1"));
185-
/// let scalar = ScalarValue::Int32(Some(42));
186-
/// assert_eq!(*binary_expr.right, Expr::Literal(scalar, None));
187-
/// assert_eq!(binary_expr.op, Operator::Eq);
184+
/// assert_eq!(*binary_expr.left, col("c1"));
185+
/// let scalar = ScalarValue::Int32(Some(42));
186+
/// assert_eq!(*binary_expr.right, Expr::Literal(scalar, None));
187+
/// assert_eq!(binary_expr.op, Operator::Eq);
188188
/// }
189189
/// ```
190190
///
@@ -197,22 +197,22 @@ impl From<sqlparser::ast::NullTreatment> for NullTreatment {
197197
/// # use datafusion_expr::Expr;
198198
/// // Create a schema c1(int, c2 float)
199199
/// let arrow_schema = Schema::new(vec![
200-
/// Field::new("c1", DataType::Int32, false),
201-
/// Field::new("c2", DataType::Float64, false),
200+
/// Field::new("c1", DataType::Int32, false),
201+
/// Field::new("c2", DataType::Float64, false),
202202
/// ]);
203203
/// // DFSchema is a an Arrow schema with optional relation name
204-
/// let df_schema = DFSchema::try_from_qualified_schema("t1", &arrow_schema)
205-
/// .unwrap();
204+
/// let df_schema = DFSchema::try_from_qualified_schema("t1", &arrow_schema).unwrap();
206205
///
207206
/// // Form Vec<Expr> with an expression for each column in the schema
208-
/// let exprs: Vec<_> = df_schema.iter()
209-
/// .map(Expr::from)
210-
/// .collect();
211-
///
212-
/// assert_eq!(exprs, vec![
213-
/// Expr::from(Column::from_qualified_name("t1.c1")),
214-
/// Expr::from(Column::from_qualified_name("t1.c2")),
215-
/// ]);
207+
/// let exprs: Vec<_> = df_schema.iter().map(Expr::from).collect();
208+
///
209+
/// assert_eq!(
210+
/// exprs,
211+
/// vec![
212+
/// Expr::from(Column::from_qualified_name("t1.c1")),
213+
/// Expr::from(Column::from_qualified_name("t1.c2")),
214+
/// ]
215+
/// );
216216
/// ```
217217
///
218218
/// # Examples: Displaying `Exprs`
@@ -273,12 +273,13 @@ impl From<sqlparser::ast::NullTreatment> for NullTreatment {
273273
/// let mut scalars = HashSet::new();
274274
/// // apply recursively visits all nodes in the expression tree
275275
/// expr.apply(|e| {
276-
/// if let Expr::Literal(scalar, _) = e {
277-
/// scalars.insert(scalar);
278-
/// }
279-
/// // The return value controls whether to continue visiting the tree
280-
/// Ok(TreeNodeRecursion::Continue)
281-
/// }).unwrap();
276+
/// if let Expr::Literal(scalar, _) = e {
277+
/// scalars.insert(scalar);
278+
/// }
279+
/// // The return value controls whether to continue visiting the tree
280+
/// Ok(TreeNodeRecursion::Continue)
281+
/// })
282+
/// .unwrap();
282283
/// // All subtrees have been visited and literals found
283284
/// assert_eq!(scalars.len(), 2);
284285
/// assert!(scalars.contains(&ScalarValue::Int32(Some(5))));
@@ -1640,7 +1641,6 @@ impl Expr {
16401641
/// let metadata = FieldMetadata::from(metadata);
16411642
/// let expr = col("foo").alias_with_metadata("bar", Some(metadata));
16421643
/// ```
1643-
///
16441644
pub fn alias_with_metadata(
16451645
self,
16461646
name: impl Into<String>,
@@ -1670,9 +1670,9 @@ impl Expr {
16701670
/// # use datafusion_common::metadata::FieldMetadata;
16711671
/// let metadata = HashMap::from([("key".to_string(), "value".to_string())]);
16721672
/// let metadata = FieldMetadata::from(metadata);
1673-
/// let expr = col("foo").alias_qualified_with_metadata(Some("tbl"), "bar", Some(metadata));
1673+
/// let expr =
1674+
/// col("foo").alias_qualified_with_metadata(Some("tbl"), "bar", Some(metadata));
16741675
/// ```
1675-
///
16761676
pub fn alias_qualified_with_metadata(
16771677
self,
16781678
relation: Option<impl Into<TableReference>>,

datafusion/expr/src/expr_schema.rs

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -82,15 +82,17 @@ impl ExprSchemable for Expr {
8282
/// # use std::collections::HashMap;
8383
///
8484
/// fn main() {
85-
/// let expr = col("c1") + col("c2");
86-
/// let schema = DFSchema::from_unqualified_fields(
87-
/// vec![
88-
/// Field::new("c1", DataType::Int32, true),
89-
/// Field::new("c2", DataType::Float32, true),
90-
/// ].into(),
91-
/// HashMap::new(),
92-
/// ).unwrap();
93-
/// assert_eq!("Float32", format!("{}", expr.get_type(&schema).unwrap()));
85+
/// let expr = col("c1") + col("c2");
86+
/// let schema = DFSchema::from_unqualified_fields(
87+
/// vec![
88+
/// Field::new("c1", DataType::Int32, true),
89+
/// Field::new("c2", DataType::Float32, true),
90+
/// ]
91+
/// .into(),
92+
/// HashMap::new(),
93+
/// )
94+
/// .unwrap();
95+
/// assert_eq!("Float32", format!("{}", expr.get_type(&schema).unwrap()));
9496
/// }
9597
/// ```
9698
///
@@ -734,7 +736,6 @@ impl Expr {
734736
/// new projection with the casted expression.
735737
/// 2. **Non-projection plan**: If the subquery isn't a projection, it adds a projection to the plan
736738
/// with the casted first column.
737-
///
738739
pub fn cast_subquery(subquery: Subquery, cast_to_type: &DataType) -> Result<Subquery> {
739740
if subquery.subquery.schema().field(0).data_type() == cast_to_type {
740741
return Ok(subquery);

datafusion/expr/src/logical_plan/builder.rs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -450,14 +450,13 @@ impl LogicalPlanBuilder {
450450
/// # ])) as _;
451451
/// # let table_source = Arc::new(LogicalTableSource::new(employee_schema));
452452
/// // VALUES (1), (2)
453-
/// let input = LogicalPlanBuilder::values(vec![vec![lit(1)], vec![lit(2)]])?
454-
/// .build()?;
453+
/// let input = LogicalPlanBuilder::values(vec![vec![lit(1)], vec![lit(2)]])?.build()?;
455454
/// // INSERT INTO MyTable VALUES (1), (2)
456455
/// let insert_plan = LogicalPlanBuilder::insert_into(
457-
/// input,
458-
/// "MyTable",
459-
/// table_source,
460-
/// InsertOp::Append,
456+
/// input,
457+
/// "MyTable",
458+
/// table_source,
459+
/// InsertOp::Append,
461460
/// )?;
462461
/// # Ok(())
463462
/// # }
@@ -953,8 +952,8 @@ impl LogicalPlanBuilder {
953952
/// // Form the expression `(left.a != right.a)` AND `(left.b != right.b)`
954953
/// let exprs = vec![
955954
/// col("left.a").eq(col("right.a")),
956-
/// col("left.b").not_eq(col("right.b"))
957-
/// ];
955+
/// col("left.b").not_eq(col("right.b")),
956+
/// ];
958957
///
959958
/// // Perform the equivalent of `left INNER JOIN right ON (a != a2 AND b != b2)`
960959
/// // finding all pairs of rows from `left` and `right` where

datafusion/expr/src/logical_plan/display.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -94,17 +94,17 @@ impl<'n> TreeNodeVisitor<'n> for IndentVisitor<'_, '_> {
9494
/// `foo:Utf8;N` if `foo` is nullable.
9595
///
9696
/// ```
97-
/// use arrow::datatypes::{Field, Schema, DataType};
97+
/// use arrow::datatypes::{DataType, Field, Schema};
9898
/// # use datafusion_expr::logical_plan::display_schema;
9999
/// let schema = Schema::new(vec![
100100
/// Field::new("id", DataType::Int32, false),
101101
/// Field::new("first_name", DataType::Utf8, true),
102-
/// ]);
102+
/// ]);
103103
///
104-
/// assert_eq!(
105-
/// "[id:Int32, first_name:Utf8;N]",
106-
/// format!("{}", display_schema(&schema))
107-
/// );
104+
/// assert_eq!(
105+
/// "[id:Int32, first_name:Utf8;N]",
106+
/// format!("{}", display_schema(&schema))
107+
/// );
108108
/// ```
109109
pub fn display_schema(schema: &Schema) -> impl fmt::Display + '_ {
110110
struct Wrapper<'a>(&'a Schema);

0 commit comments

Comments
 (0)