Struct pgx::pgbox::PgBox

source · []
#[repr(transparent)]
pub struct PgBox<T, AllocatedBy: WhoAllocated<T> = AllocatedByPostgres> { /* private fields */ }
Expand description

Similar to Rust’s Box<T> type, PgBox<T> also represents heap-allocated memory.

However, it represents a heap-allocated pointer that was allocated by Postgres’s memory allocation functions (palloc, etc). Think of PgBox<T> as a wrapper around an otherwise opaque Postgres type that is projected as a concrete Rust type.

Depending on its usage, it’ll interoperate correctly with Rust’s Drop semantics, such that the backing Postgres-allocated memory is pfree()'d when the PgBox<T> is dropped, but it is possible to effectively return management of the memory back to Postgres (to free on Transaction end, for example) by calling ::into_pg() or ``::into_pg_boxed()`. This is especially useful for returning values back to Postgres.

Examples

This example allocates a simple Postgres structure, modifies it, and returns it back to Postgres:

use pgx::*;

#[pg_guard]
pub fn do_something() -> pg_sys::ItemPointer {
    // postgres-allocate an ItemPointerData structure
    let mut tid = PgBox::<pg_sys::ItemPointerData>::alloc();

    // set its position to 42
    tid.ip_posid = 42;

    // return it to Postgres
    tid.into_pg()
}

A similar example, but instead the PgBox<T>’s backing memory gets freed when the box is dropped:

use pgx::*;

#[pg_guard]
pub fn do_something()  {
    // postgres-allocate an ItemPointerData structure
    let mut tid = PgBox::<pg_sys::ItemPointerData>::alloc();

    // set its position to 42
    tid.ip_posid = 42;

    // tid gets dropped here and as such, gets immediately pfree()'d
}

Alternatively, perhaps you want to work with a pointer Postgres gave you as if it were a Rust type, but it can’t be freed on Drop since you don’t own it – Postgres does:

use pgx::*;

#[pg_guard]
pub fn do_something()  {
    // open a relation and project it as a pg_sys::Relation
    let relid: pg_sys::Oid = 42;
    let lockmode = pg_sys::AccessShareLock as i32;
    let relation = unsafe { PgBox::from_pg(pg_sys::relation_open(relid, lockmode)) };

    // do something with/to 'relation'
    // ...

    // pass the relation back to Postgres
    unsafe { pg_sys::relation_close(relation.as_ptr(), lockmode); }

    // While the `PgBox` instance gets dropped, the backing Postgres-allocated pointer is
    // **not** freed since it came "::from_pg()".  We don't own the underlying memory so
    // we can't free it
}

Implementations

Box a pointer that cames from Postgres.

When this PgBox<T> is dropped, the boxed memory is not freed. Since Postgres allocated it, Postgres is responsible for freeing it.

Allocates memory in PostgreSQL and then places val into it.

This value is managed by Rust, so gets dropped via normal Drop semantics.

If you need to give the boxed pointer to Postgres, call .into_pg().

use pgx::{PgBox, AllocatedByRust};

let ptr: PgBox<i32, AllocatedByRust> = PgBox::new(5);
assert_eq!(*ptr, 5);

let mut ptr: PgBox<Vec<i32>, AllocatedByRust> = PgBox::new(vec![]);
assert_eq!(*ptr, Vec::<i32>::default());

ptr.push(1);
assert_eq!(*ptr, vec![1]);
    
ptr.push(2);
assert_eq!(*ptr, vec![1, 2]);

ptr.push(3);
assert_eq!(*ptr, vec![1, 2, 3]);

let drained = ptr.drain(..).collect::<Vec<_>>();
assert_eq!(drained, vec![1, 2, 3])

Allocates memory in PostgreSQL and then places val into it.

This value is managed by Rust, so gets dropped via normal Drop semantics.

If you need to give the boxed pointer to Postgres, call .into_pg().

use pgx::{PgBox, PgMemoryContexts, AllocatedByRust};

let ptr: PgBox<i32, AllocatedByRust> = PgBox::new_in_context(5, PgMemoryContexts::CurrentMemoryContext);
assert_eq!(*ptr, 5);

Box a pointer that was allocated within Rust

When this PgBox<T> is dropped, the boxed memory is freed. Since Rust allocated it, Rust is responsible for freeing it.

If you need to give the boxed pointer to Postgres, call .into_pg()

Allocate enough memory for the type’d struct, within Postgres’ CurrentMemoryContext The allocated memory is uninitialized.

When this object is dropped the backing memory will be pfree’d, unless it is instead turned into_pg(), at which point it will be freeded when its owning MemoryContext is deleted by Postgres (likely transaction end).

Examples
use pgx::{PgBox, pg_sys};
let ctid = PgBox::<pg_sys::ItemPointerData>::alloc();

Allocate enough memory for the type’d struct, within Postgres’ CurrentMemoryContext The allocated memory is zero-filled.

When this object is dropped the backing memory will be pfree’d, unless it is instead turned into_pg(), at which point it will be freeded when its owning MemoryContext is deleted by Postgres (likely transaction end).

Examples
use pgx::{PgBox, pg_sys};
let ctid = PgBox::<pg_sys::ItemPointerData>::alloc0();

Allocate enough memory for the type’d struct, within the specified Postgres MemoryContext. The allocated memory is uninitalized.

When this object is dropped the backing memory will be pfree’d, unless it is instead turned into_pg(), at which point it will be freeded when its owning MemoryContext is deleted by Postgres (likely transaction end).

Examples
use pgx::{PgBox, pg_sys, PgMemoryContexts};
let ctid = PgBox::<pg_sys::ItemPointerData>::alloc_in_context(PgMemoryContexts::TopTransactionContext);

Allocate enough memory for the type’d struct, within the specified Postgres MemoryContext. The allocated memory is zero-filled.

When this object is dropped the backing memory will be pfree’d, unless it is instead turned into_pg(), at which point it will be freeded when its owning MemoryContext is deleted by Postgres (likely transaction end).

Examples
use pgx::{PgBox, pg_sys, PgMemoryContexts};
let ctid = PgBox::<pg_sys::ItemPointerData>::alloc0_in_context(PgMemoryContexts::TopTransactionContext);

Allocate a Postgres pg_sys::Node subtype, using palloc in the CurrentMemoryContext.

The allocated node will have it’s type_ field set to the node_tag argument, and will otherwise be initialized with all zeros

Examples
use pgx::{PgBox, pg_sys};
let create_trigger_statement = PgBox::<pg_sys::CreateTrigStmt>::alloc_node(pg_sys::NodeTag_T_CreateTrigStmt);

Box nothing

Are we boxing a NULL?

Return the boxed pointer, so that it can be passed back into a Postgres function

Useful for returning the boxed pointer back to Postgres (as a return value, for example).

The boxed pointer is not free’d by Rust

Useful for returning the boxed pointer back to Postgres (as a return value, for example).

The boxed pointer is not free’d by Rust

Execute a closure with a mutable, PgBox’d form of the specified ptr

Trait Implementations

The resulting type after dereferencing.

Dereferences the value.

Mutably dereferences the value.

Executes the destructor for this type. Read more

for user types

Safety Read more

Default implementation switched to the specified memory context and then simply calls From::from_datum(...) from within that context. Read more

for user types

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Performs the conversion.

Set the foreground color generically Read more

Set the background color generically. Read more

Change the foreground color to black

Change the background color to black

Change the foreground color to red

Change the background color to red

Change the foreground color to green

Change the background color to green

Change the foreground color to yellow

Change the background color to yellow

Change the foreground color to blue

Change the background color to blue

Change the foreground color to magenta

Change the background color to magenta

Change the foreground color to purple

Change the background color to purple

Change the foreground color to cyan

Change the background color to cyan

Change the foreground color to white

Change the background color to white

Change the foreground color to the terminal default

Change the background color to the terminal default

Change the foreground color to bright black

Change the background color to bright black

Change the foreground color to bright red

Change the background color to bright red

Change the foreground color to bright green

Change the background color to bright green

Change the foreground color to bright yellow

Change the background color to bright yellow

Change the foreground color to bright blue

Change the background color to bright blue

Change the foreground color to bright magenta

Change the background color to bright magenta

Change the foreground color to bright purple

Change the background color to bright purple

Change the foreground color to bright cyan

Change the background color to bright cyan

Change the foreground color to bright white

Change the background color to bright white

Make the text bold

Make the text dim

Make the text italicized

Make the text italicized

Make the text blink

Make the text blink (but fast!)

Swap the foreground and background colors

Hide the text

Cross out the text

Set the foreground color at runtime. Only use if you do not know which color will be used at compile-time. If the color is constant, use either OwoColorize::fg or a color-specific method, such as OwoColorize::green, Read more

Set the background color at runtime. Only use if you do not know what color to use at compile-time. If the color is constant, use either OwoColorize::bg or a color-specific method, such as OwoColorize::on_yellow, Read more

Set the foreground color to a specific RGB value.

Set the background color to a specific RGB value.

Sets the foreground color to an RGB value.

Sets the background color to an RGB value.

Apply a runtime-determined style

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more