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").field("my_field");
43/// assert_eq!(expr.schema_name().to_string(), "c1[my_field]");
44/// ```
45pub trait FieldAccessor {
46    fn field(self, name: impl Literal) -> Expr;
47}
48
49impl FieldAccessor for Expr {
50    fn field(self, name: impl Literal) -> Expr {
51        get_field(self, name)
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    use datafusion_expr::col;
60
61    #[test]
62    fn test_field() {
63        let expr1 = col("a").field("b");
64        let expr2 = get_field(col("a"), "b");
65        assert_eq!(expr1, expr2);
66    }
67}