## Coverage Report

#### Created: 2025-11-22 06:00

next uncovered line (L), next uncovered region (R), next uncovered branch (B)

    /Users/andrewlamb/Software/datafusion/datafusion/functions/src/datetime/to_unixtime.rs

    Line
    Count
    Source
    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
    use super::to_timestamp::ToTimestampSecondsFunc;
    19
    use crate::datetime::common::*;
    20
    use arrow::datatypes::{DataType, TimeUnit};
    21
    use datafusion_common::{exec_err, Result};
    22
    use datafusion_expr::{
    23
        ColumnarValue, Documentation, ScalarUDFImpl, Signature, Volatility,
    24
    };
    25
    use datafusion_macros::user_doc;
    26
    use std::any::Any;
    27
    28
    #[user_doc(
    29
        doc_section(label = "Time and Date Functions"),
    30
        description = "Converts a value to seconds since the unix epoch (`1970-01-01T00:00:00Z`). Supports strings, dates, timestamps and double types as input. Strings are parsed as RFC3339 (e.g. '2023-07-20T05:44:00') if no [Chrono formats](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) are provided.",
    31
        syntax_example = "to_unixtime(expression[, ..., format_n])",
    32
        sql_example = r#"
    33
    ```sql
    34
    > select to_unixtime('2020-09-08T12:00:00+00:00');
    35
    +------------------------------------------------+
    36
    | to_unixtime(Utf8("2020-09-08T12:00:00+00:00")) |
    37
    +------------------------------------------------+
    38
    | 1599566400                                     |
    39
    +------------------------------------------------+
    40
    > select to_unixtime('01-14-2023 01:01:30+05:30', '%q', '%d-%m-%Y %H/%M/%S', '%+', '%m-%d-%Y %H:%M:%S%#z');
    41
    +-----------------------------------------------------------------------------------------------------------------------------+
    42
    | to_unixtime(Utf8("01-14-2023 01:01:30+05:30"),Utf8("%q"),Utf8("%d-%m-%Y %H/%M/%S"),Utf8("%+"),Utf8("%m-%d-%Y %H:%M:%S%#z")) |
    43
    +-----------------------------------------------------------------------------------------------------------------------------+
    44
    | 1673638290                                                                                                                  |
    45
    +-----------------------------------------------------------------------------------------------------------------------------+
    46
    ```
    47
    "#,
    48
        argument(
    49
            name = "expression",
    50
            description = "Expression to operate on. Can be a constant, column, or function, and any combination of arithmetic operators."
    51
        ),
    52
        argument(
    53
            name = "format_n",
    54
            description = "Optional [Chrono format](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) strings to use to parse the expression. Formats will be tried in the order they appear with the first successful one being returned. If none of the formats successfully parse the expression an error will be returned."
    55
        )
    56
    )]
    57
    #[derive(Debug, PartialEq, Eq, Hash)]
    58
    pub struct ToUnixtimeFunc {
    59
        signature: Signature,
    60
    }
    61
    62
    impl Default for ToUnixtimeFunc {
    63
    0
        fn default() -> Self {
    64
    0
            Self::new()
    65
    0
        }
    66
    }
    67
    68
    impl ToUnixtimeFunc {
    69
    0
        pub fn new() -> Self {
    70
    0
            Self {
    71
    0
                signature: Signature::variadic_any(Volatility::Immutable),
    72
    0
            }
    73
    0
        }
    74
    }
    75
    76
    impl ScalarUDFImpl for ToUnixtimeFunc {
    77
    0
        fn as_any(&self) -> &dyn Any {
    78
    0
            self
    79
    0
        }
    80
    81
    0
        fn name(&self) -> &str {
    82
    0
            "to_unixtime"
    83
    0
        }
    84
    85
    0
        fn signature(&self) -> &Signature {
    86
    0
            &self.signature
    87
    0
        }
    88
    89
    0
        fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {
    90
    0
            Ok(DataType::Int64)
    91
    0
        }
    92
    93
    0
        fn invoke_with_args(
    94
    0
            &self,
    95
    0
            args: datafusion_expr::ScalarFunctionArgs,
    96
    0
        ) -> Result<ColumnarValue> {
    97
    0
            let arg_args = &args.args;
    98
    0
            if arg_args.is_empty() {
    99
    0
                return exec_err!("to_unixtime function requires 1 or more arguments, got 0");
    100
    0
            }
    101
    102
            // validate that any args after the first one are Utf8
    103
    0
            if arg_args.len() > 1 {
    104
    0
                validate_data_types(arg_args, "to_unixtime")?;
    105
    0
            }
    106
    107
    0
            match arg_args[0].data_type() {
    108
                DataType::Int32 | DataType::Int64 | DataType::Null | DataType::Float64 => {
    109
    0
                    arg_args[0].cast_to(&DataType::Int64, None)
    110
                }
    111
    0
                DataType::Date64 | DataType::Date32 => arg_args[0]
    112
    0
                    .cast_to(&DataType::Timestamp(TimeUnit::Second, None), None)?
    113
    0
                    .cast_to(&DataType::Int64, None),
    114
    0
                DataType::Timestamp(_, tz) => arg_args[0]
    115
    0
                    .cast_to(&DataType::Timestamp(TimeUnit::Second, tz), None)?
    116
    0
                    .cast_to(&DataType::Int64, None),
    117
    0
                DataType::Utf8 => ToTimestampSecondsFunc::new()
    118
    0
                    .invoke_with_args(args)?
    119
    0
                    .cast_to(&DataType::Int64, None),
    120
    0
                other => {
    121
    0
                    exec_err!("Unsupported data type {} for function to_unixtime", other)
    122
                }
    123
            }
    124
    0
        }
    125
    126
    0
        fn documentation(&self) -> Option<&Documentation> {
    127
    0
            self.doc()
    128
    0
        }
    129
    }