Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix (zero-copy)-Array so that when working with fixed-size, pass-by-value… #1125

Merged
merged 2 commits into from
Apr 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions pgrx-tests/src/tests/array_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ Use of this source code is governed by the MIT license that can be found in the

use pgrx::array::RawArray;
use pgrx::prelude::*;
use pgrx::PostgresEnum;
use pgrx::{Array, Json};
use serde::Serialize;
use serde_json::*;

#[pg_extern(name = "sum_array")]
Expand Down Expand Up @@ -147,16 +149,39 @@ fn arr_sort_uniq(arr: Array<i32>) -> Vec<i32> {
v
}

#[derive(Debug, Eq, PartialEq, PostgresEnum, Serialize)]
pub enum ArrayTestEnum {
One,
Two,
Three,
}

#[pg_extern]
fn enum_array_roundtrip(a: Array<ArrayTestEnum>) -> Vec<Option<ArrayTestEnum>> {
a.into_iter().collect()
}

#[cfg(any(test, feature = "pg_test"))]
#[pgrx::pg_schema]
mod tests {
#[allow(unused_imports)]
use crate as pgrx_tests;

use crate::tests::array_tests::ArrayTestEnum;
use pgrx::prelude::*;
use pgrx::{IntoDatum, Json};
use serde_json::json;

#[pg_test]
fn test_enum_array_roundtrip() -> spi::Result<()> {
let a = Spi::get_one::<Vec<Option<ArrayTestEnum>>>(
"SELECT enum_array_roundtrip(ARRAY['One', 'Two']::ArrayTestEnum[])",
)?
.expect("SPI result was null");
assert_eq!(a, vec![Some(ArrayTestEnum::One), Some(ArrayTestEnum::Two)]);
Ok(())
}

#[pg_test]
fn test_sum_array_i32() {
let sum = Spi::get_one::<i32>("SELECT sum_array(ARRAY[1,2,3]::integer[])");
Expand Down
56 changes: 54 additions & 2 deletions pgrx/src/datum/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ use core::ffi::CStr;
use core::ops::DerefMut;
use core::ptr::NonNull;
use once_cell::sync::OnceCell;
use pgrx_pg_sys::Datum;
use pgrx_sql_entity_graph::metadata::{
ArgumentError, Returns, ReturnsError, SqlMapping, SqlTranslatable,
};
Expand Down Expand Up @@ -234,15 +235,66 @@ impl<'a, T: FromDatum> Array<'a, T> {
}

match self.elem_layout.pass {
PassBy::Value => Some(unsafe { ptr.cast::<T>().read() }),
PassBy::Value => match self.elem_layout.size {
//
// NB: Leaving this commented out because it's not clear to me that this will be
// correct in every case. This assumption got us in trouble with arrays of enums
// already, and I'd rather err on the side of correctness.
//
// Size::Fixed(size) if size as usize == std::mem::size_of::<T>() => unsafe {
// // short-circuit if the size of the element matches the size of `T`.
// // This most likely means that the element Datum actually represents the same
// // type as the rust `T`
//
// Some(ptr.cast::<T>().read())
// },
Size::Fixed(size) => {
// copy off `size` bytes from the head of `ptr` and convert that into a `usize`
// using proper platform endianness, converting it into a `Datum`
#[inline(always)]
fn bytes_to_datum(ptr: *const u8, size: usize) -> Datum {
const USIZE_BYTE_LEN: usize = std::mem::size_of::<usize>();

// a zero-padded buffer in which we'll store bytes so we can
// ultimately make a `usize` that we convert into a `Datum`
let mut buf = [0u8; USIZE_BYTE_LEN];

match size {
1..=USIZE_BYTE_LEN => unsafe {
// copy to the end
#[cfg(target_endian = "big")]
let dst = (&mut buff[8 - size as usize..]).as_mut_ptr();

// copy to the head
#[cfg(target_endian = "little")]
let dst = (&mut buf[0..]).as_mut_ptr();

std::ptr::copy_nonoverlapping(ptr, dst, size as usize);
},
other => {
panic!("unexpected fixed size array element size: {}", other)
}
}

Datum::from(usize::from_ne_bytes(buf))
}

let datum = bytes_to_datum(ptr, size as usize);
unsafe { T::from_polymorphic_datum(datum, false, self.raw.oid()) }
}

other => {
panic!("unrecognized pass-by-value array element layout size: {:?}", other)
}
},
PassBy::Ref => {
let datum = pg_sys::Datum::from(ptr);
#[cfg(debug_assertions)]
assert_eq!(
Some(datum),
self._datum_slice.get().and_then(|s| unsafe { s.get(_index) }).copied()
);
unsafe { T::from_polymorphic_datum(datum, is_null, self.raw.oid()) }
unsafe { T::from_polymorphic_datum(datum, false, self.raw.oid()) }
}
}
}
Expand Down