datafusion_functions/core/expr_ext.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Extension methods for Expr.
19
20use datafusion_expr::{Expr, Literal};
21
22use super::expr_fn::get_field;
23
24/// Return access to the named field. Example `expr["name"]`
25///
26/// ## Access field "my_field" from column "c1"
27///
28/// For example if column "c1" holds documents like this
29///
30/// ```json
31/// {
32/// "my_field": 123.34,
33/// "other_field": "Boston",
34/// }
35/// ```
36///
37/// You can access column "my_field" with
38///
39/// ```
40/// # use datafusion_expr::{col};
41/// # use datafusion_functions::core::expr_ext::FieldAccessor;
42/// let expr = col("c1")
43/// .field("my_field");
44/// assert_eq!(expr.schema_name().to_string(), "c1[my_field]");
45/// ```
46pub trait FieldAccessor {
47 fn field(self, name: impl Literal) -> Expr;
48}
49
50impl FieldAccessor for Expr {
51 fn field(self, name: impl Literal) -> Expr {
52 get_field(self, name)
53 }
54}
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59
60 use datafusion_expr::col;
61
62 #[test]
63 fn test_field() {
64 let expr1 = col("a").field("b");
65 let expr2 = get_field(col("a"), "b");
66 assert_eq!(expr1, expr2);
67 }
68}