pub enum PKeyPolicy<T> {
    Fixed(T),
    Generate,
}
Expand description

Helper struct to use with functions that insert data into the database.

Examples

Usage when inserting to a database

By calling .into_uuid() function implemented by PKeyPolicy<Uuid>, this enum can be used with SQLX queries while letting the caller dictate how the primary key should be decided.

async fn insert(
    conn: &mut PgConnection,
    pkey_policy: PKeyPolicy<Uuid>,
) -> ModelResult<Uuid> {
    let res = sqlx::query!(
        "INSERT INTO organizations (id) VALUES ($1) RETURNING id",
        pkey_policy.into_uuid(),
    )
    .fetch_one(conn)
    .await?;
    Ok(res.id)
}

// Insert using generated id.
let foo_1_id = insert(conn, PKeyPolicy::Generate).await.unwrap();

// Insert using fixed id.
let uuid = Uuid::parse_str("8fce44cf-738e-4fc9-8d8e-47c350fd3a7f").unwrap();
let foo_2_id = insert(conn, PKeyPolicy::Fixed(uuid)).await.unwrap();
assert_eq!(foo_2_id, uuid);

Usage in a higher-order function.

When PKeyPolicy is used with a higher-order function, an arbitrary struct can be provided instead. The data can be mapped further by calling the .map() or .map_ref() methods.


struct FooBar {
    foo: Uuid,
    bar: Uuid,
}

async fn multiple_inserts(
    conn: &mut PgConnection,
    pkey_policy: PKeyPolicy<FooBar>,
) -> ModelResult<()> {
    foos::insert(conn, pkey_policy.map_ref(|x| x.foo)).await?;
    bars::insert(conn, pkey_policy.map_ref(|x| x.bar)).await?;
    Ok(())
}

// Insert using generated ids.
assert!(multiple_inserts(conn, PKeyPolicy::Generate).await.is_ok());

// Insert using fixed ids.
let foobar = FooBar {
    foo: Uuid::parse_str("52760668-cc9d-4144-9226-d2aacb83bea9").unwrap(),
    bar: Uuid::parse_str("ce9bd0cd-0e66-4522-a1b4-52a9347a115c").unwrap(),
};
assert!(multiple_inserts(conn, PKeyPolicy::Fixed(foobar)).await.is_ok());

Variants§

§

Fixed(T)

Ids will be generated based on the associated data. Usually only used in local test environments where reproducible database states are desired.

§

Generate

Ids will be generated on the database level. This should be the default behavior.

Implementations§

source§

impl<T> PKeyPolicy<T>

source

pub fn fixed(&self) -> Option<&T>

Gets reference to the fixed data, if there are any.

source

pub fn map<U, F>(self, f: F) -> PKeyPolicy<U>
where F: FnOnce(T) -> U,

Maps PKeyPolicy<T> to PKeyPolicy<U> by applying a function to the contained value.

source

pub fn map_ref<U, F>(&self, f: F) -> PKeyPolicy<U>
where F: FnOnce(&T) -> U,

Maps a reference of contained data in Fixed(T) to PKeyPolicy<U> by applying a function to the contained value. This is useful whenever a referenced value can be used instead of having to consume the original value.

source§

impl PKeyPolicy<Uuid>

source

pub fn into_uuid(self) -> Uuid

Maps into the contained Uuid value or generates a new one.

Auto Trait Implementations§

§

impl<T> RefUnwindSafe for PKeyPolicy<T>
where T: RefUnwindSafe,

§

impl<T> Send for PKeyPolicy<T>
where T: Send,

§

impl<T> Sync for PKeyPolicy<T>
where T: Sync,

§

impl<T> Unpin for PKeyPolicy<T>
where T: Unpin,

§

impl<T> UnwindSafe for PKeyPolicy<T>
where T: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> Chain<T> for T

source§

fn len(&self) -> usize

The number of items that this chain link consists of.
source§

fn append_to(self, v: &mut Vec<T>)

Append the elements in this link to the chain.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

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

fn in_current_span(self) -> Instrumented<Self>

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

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

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

fn with_current_subscriber(self) -> WithDispatch<Self>

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