Skip to content

Commit

Permalink
Added postgres asind
Browse files Browse the repository at this point in the history
  • Loading branch information
dadepo committed Dec 23, 2023
1 parent 64329b5 commit 85c73e7
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 2 deletions.
80 changes: 80 additions & 0 deletions src/postgres/math_udfs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,38 @@ pub fn cosd(args: &[ArrayRef]) -> Result<ArrayRef> {
Ok(Arc::new(float64array_builder.finish()) as ArrayRef)
}

/// Inverse sine, result in degrees.
pub fn asind(args: &[ArrayRef]) -> Result<ArrayRef> {
let values = datafusion::common::cast::as_float64_array(&args[0])?;
let mut float64array_builder = Float64Array::builder(args[0].len());

values.iter().try_for_each(|value| {
if let Some(value) = value {
if value > 1.0 {
return Err(DataFusionError::Internal(
"input is out of range".to_string(),
));
}
let result = value.asin().to_degrees();
if result.fract() < 0.9 {
if result.fract() < 0.01 {
float64array_builder.append_value(result.floor());
} else {
float64array_builder.append_value(result);
}
} else {
float64array_builder.append_value(result.ceil());
}
Ok::<(), DataFusionError>(())
} else {
float64array_builder.append_null();
Ok::<(), DataFusionError>(())
}
})?;

Ok(Arc::new(float64array_builder.finish()) as ArrayRef)
}

/// Nearest integer greater than or equal to argument (same as ceil).
pub fn ceiling(args: &[ArrayRef]) -> Result<ArrayRef> {
let values = datafusion::common::cast::as_float64_array(&args[0])?;
Expand Down Expand Up @@ -305,6 +337,54 @@ mod tests {
Ok(())
}

#[tokio::test]
async fn test_sind() -> Result<()> {
let ctx = register_udfs_for_test()?;
let df = ctx.sql("select asind(0.5) as col_result").await?;

let batches = df.clone().collect().await?;

let expected: Vec<&str> = r#"
+------------+
| col_result |
+------------+
| 30.0 |
+------------+"#
.split('\n')
.filter_map(|input| {
if input.is_empty() {
None
} else {
Some(input.trim())
}
})
.collect();
assert_batches_sorted_eq!(expected, &batches);

let df = ctx.sql("select asind(0.4) as col_result").await?;

let batches = df.clone().collect().await?;

let expected: Vec<&str> = r#"
+--------------------+
| col_result |
+--------------------+
| 23.578178478201835 |
+--------------------+"#
.split('\n')
.filter_map(|input| {
if input.is_empty() {
None
} else {
Some(input.trim())
}
})
.collect();
assert_batches_sorted_eq!(expected, &batches);

Ok(())
}

#[tokio::test]
async fn test_ceiling() -> Result<()> {
let ctx = register_udfs_for_test()?;
Expand Down
16 changes: 15 additions & 1 deletion src/postgres/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use std::sync::Arc;

use crate::postgres::math_udfs::{acosd, ceiling, cosd, div, erf, erfc};
use crate::postgres::math_udfs::{acosd, asind, ceiling, cosd, div, erf, erfc};
use crate::postgres::network_udfs::{
broadcast, family, host, hostmask, inet_merge, inet_same_family, masklen, netmask, network,
set_masklen,
Expand All @@ -24,6 +24,7 @@ pub fn register_postgres_udfs(ctx: &SessionContext) -> Result<()> {

fn register_math_udfs(ctx: &SessionContext) -> Result<()> {
register_acosd(ctx);
register_asind(ctx);
register_cosd(ctx);
register_ceiling(ctx);
register_erf(ctx);
Expand All @@ -45,6 +46,19 @@ fn register_acosd(ctx: &SessionContext) {
ctx.register_udf(acosd_udf);
}

fn register_asind(ctx: &SessionContext) {
let asind_udf = make_scalar_function(asind);
let return_type: ReturnTypeFunction = Arc::new(move |_| Ok(Arc::new(Float64)));
let asind_udf = ScalarUDF::new(
"asind",
&Signature::uniform(1, vec![Float64], Volatility::Immutable),
&return_type,
&asind_udf,
);

ctx.register_udf(asind_udf);
}

fn register_cosd(ctx: &SessionContext) {
let cosd_udf = make_scalar_function(cosd);
let return_type: ReturnTypeFunction = Arc::new(move |_| Ok(Arc::new(Float64)));
Expand Down
2 changes: 1 addition & 1 deletion supports/postgres.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ https://www.postgresql.org/docs/16/functions-math.html
|| width_bucket ( operand numeric, low numeric, high numeric, count integer ) → integer | Returns the number of the bucket in which operand falls in a histogram having count equal-width buckets spanning the range low to high. Returns 0 or count+1 for an input outside that range. | width_bucket(5.35, 0.024, 10.06, 5) → 3 |
|| random_normal ( [ mean double precision [, stddev double precision ]] ) → double precision | Returns a random value from the normal distribution with the given parameters; mean defaults to 0.0 and stddev defaults to 1.0 | random_normal(0.0, 1.0) → 0.051285419 |
|| acosd ( double precision ) → double precision | Inverse cosine, result in degrees | acosd(0.5) → 60 |
| | asind ( double precision ) → double precision | Inverse sine, result in degrees | asind(0.5) → 30 |
| | asind ( double precision ) → double precision | Inverse sine, result in degrees | asind(0.5) → 30 |
|| atand ( double precision ) → double precision | Inverse tangent, result in degrees | atand(1) → 45 |
|| cosd ( double precision ) → double precision | Cosine, argument in degrees | cosd(60) → 0.5 |
|| cotd ( double precision ) → double precision | Cotangent, argument in degrees | cotd(45) → 1 |
Expand Down

0 comments on commit 85c73e7

Please sign in to comment.