datafusion_spark/function/url/
try_parse_url.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
18use std::any::Any;
19
20use crate::function::url::parse_url::{spark_handled_parse_url, ParseUrl};
21use arrow::array::ArrayRef;
22use arrow::datatypes::DataType;
23use datafusion_common::Result;
24use datafusion_expr::{
25    ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature,
26    Volatility,
27};
28use datafusion_functions::utils::make_scalar_function;
29
30/// TRY_PARSE_URL function for tolerant URL component extraction (never errors; returns NULL on invalid or missing parts).
31/// <https://spark.apache.org/docs/latest/api/sql/index.html#try_parse_url>
32#[derive(Debug, PartialEq, Eq, Hash)]
33pub struct TryParseUrl {
34    signature: Signature,
35}
36
37impl Default for TryParseUrl {
38    fn default() -> Self {
39        Self::new()
40    }
41}
42
43impl TryParseUrl {
44    pub fn new() -> Self {
45        Self {
46            signature: Signature::one_of(
47                vec![TypeSignature::String(2), TypeSignature::String(3)],
48                Volatility::Immutable,
49            ),
50        }
51    }
52}
53
54impl ScalarUDFImpl for TryParseUrl {
55    fn as_any(&self) -> &dyn Any {
56        self
57    }
58
59    fn name(&self) -> &str {
60        "try_parse_url"
61    }
62
63    fn signature(&self) -> &Signature {
64        &self.signature
65    }
66
67    fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
68        let parse_url: ParseUrl = ParseUrl::new();
69        parse_url.return_type(arg_types)
70    }
71
72    fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
73        let ScalarFunctionArgs { args, .. } = args;
74        make_scalar_function(spark_try_parse_url, vec![])(&args)
75    }
76}
77
78fn spark_try_parse_url(args: &[ArrayRef]) -> Result<ArrayRef> {
79    spark_handled_parse_url(args, |x| match x {
80        Err(_) => Ok(None),
81        result => result,
82    })
83}