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

spi: simplify (optimize?) Datum preparation #1256

Merged
merged 1 commit into from
Aug 16, 2023
Merged
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
30 changes: 23 additions & 7 deletions pgrx/src/spi/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ use std::marker::PhantomData;
use std::ops::Deref;
use std::ptr::NonNull;

use libc::c_char;
use pg_sys::{Datum, Oid};

use super::{Spi, SpiClient, SpiCursor, SpiError, SpiResult, SpiTupleTable};
use crate::pg_sys::{self, PgOid};

Expand Down Expand Up @@ -50,6 +53,24 @@ fn prepare_datum(datum: Option<pg_sys::Datum>) -> (pg_sys::Datum, std::os::raw::
}
}

fn args_to_datums(
args: Vec<(PgOid, Option<pg_sys::Datum>)>,
) -> (Vec<Oid>, Vec<Datum>, Vec<c_char>) {
let mut argtypes = Vec::with_capacity(args.len());
let mut datums = Vec::with_capacity(args.len());
let mut nulls = Vec::with_capacity(args.len());

for (types, maybe_datum) in args {
let (datum, null) = prepare_datum(maybe_datum);

argtypes.push(types.value());
datums.push(datum);
nulls.push(null);
}

(argtypes, datums, nulls)
}

impl<'conn> Query<'conn> for &str {
type Arguments = Option<Vec<(PgOid, Option<pg_sys::Datum>)>>;

Expand All @@ -71,10 +92,7 @@ impl<'conn> Query<'conn> for &str {
let status_code = match arguments {
Some(args) => {
let nargs = args.len();
let (types, data): (Vec<_>, Vec<_>) = args.into_iter().unzip();
let mut argtypes = types.into_iter().map(PgOid::value).collect::<Vec<_>>();
let (mut datums, nulls): (Vec<_>, Vec<_>) =
data.into_iter().map(prepare_datum).unzip();
let (mut argtypes, mut datums, nulls) = args_to_datums(args);

// SAFETY: arguments are prepared above
unsafe {
Expand Down Expand Up @@ -107,9 +125,7 @@ impl<'conn> Query<'conn> for &str {
let args = args.unwrap_or_default();

let nargs = args.len();
let (types, data): (Vec<_>, Vec<_>) = args.into_iter().unzip();
let mut argtypes = types.into_iter().map(PgOid::value).collect::<Vec<_>>();
let (mut datums, nulls): (Vec<_>, Vec<_>) = data.into_iter().map(prepare_datum).unzip();
let (mut argtypes, mut datums, nulls) = args_to_datums(args);

let ptr = unsafe {
// SAFETY: arguments are prepared above and SPI_cursor_open_with_args will never return
Expand Down