Skip to main content

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