### Asserting Option values in examples Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Demonstrates basic assertion checks for Option values. ```rust assert_eq!(res, None); assert_eq!(shared, 6); ``` -------------------------------- ### Implementing Connection for tokio_postgres::Client Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/trait.Connection.html Example implementation of the Connection trait for a PostgreSQL client, mapping database rows to protobuf structs. ```rust use postgrpc::pools::{Connection, Parameter}; use tonic::{Row, Status}; // implementing a real StructStream (a fallible stream of Structs) // is an exercise left to the reader struct StructStream; impl From> for StructStream { // also an exercise for the reader } #[async_trait] impl Connection for tokio_postgres::Client { type Error = Status; type RowStream = StructStream; async fn query( &self, statement: &str, parameters: &[Parameter], ) -> Result { // Parameter implements ToSql, so can be used directly in query() let rows: Vec<_> = self .query(statement, parameters) .await .map_error(|error| Status::invalid_argument(error.to_string()))?; // it's best to stream rows instead of collecting them into a Vec // but this is only meant to be a quick example Ok(StructStream::from(rows)) } #[tracing::instrument(skip(self))] async fn batch(&self, query: &str) -> Result<(), Self::Error> { tracing::trace!("Executing batch query on Connection"); self.batch_execute(query).await.map_err(|error| Status::invalid_argument(error.to_string())) } } ``` -------------------------------- ### Implement a Custom Pool Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/trait.Pool.html An example implementation of the Pool trait using a BTreeMap and RwLock to manage connections keyed by Uuid. ```rust use postgrpc::pools::{Pool, Connection}; use std::collections::BTreeMap; use tokio::sync::RwLock; use uuid::Uuid; use tonic::Status; // a simple connection wrapper // (implementing postgrpc::Connection is an exercise for the reader) #[derive(Clone)] struct MyConnection(Arc); // a toy pool wrapping a collection of tokio_postgres::Clients // accessible by unique IDs that are provided by the caller struct MyPool { connections: RwLock>, config: tokio_postgres::config::Config } #[postgrpc::async_trait] impl Pool for MyPool { type Key: Uuid; type Connection: MyConnection; type Error: Status; async fn get_connection(&self, key: Self::Key) -> Result { // get a connection from the pool or store one for later let connections = self.connections.read().await; match connections.get(&key) { Some(connection) => Ok(Arc::clone(connection.0)), None => { // drop the previous lock on the connections drop(connections); // connect to the database using the configuration let (client, connection) = self .config .connect(tokio_postgres::NoTls) .map_error(|error| Status::internal(error.to_string()))?; // spawn the raw connection off onto an executor tokio::spawn(async move { if let Err(error) = connection.await { eprintln!("connection error: {}", error); } }); // store a reference to the connection for later let connection = MyConnection(Arc::new(client)); self.connections.write().await.insert(key, connection); // return another reference to the connection for use Ok(connection) } } } } ``` -------------------------------- ### tonic::server::NamedService Integration Source: https://docs.rs/postgrpc/0.1.2/postgrpc/index.html Example of integrating the postgrpc Postgres service into a tonic gRPC server using the deadpool feature. ```APIDOC ## tonic::server::NamedService Integration ### Description This example demonstrates how to use the `services::postgres` service within a `tonic` server application. It requires the `deadpool` feature to be enabled. ### Implementation ```rust use postgrpc::{pools::deadpool, services::postgres}; use std::sync::Arc; use tonic::transport::Server; use envy::from_env; #[tokio::main] async fn main() -> Result<(), Box> { // create the connection pool from environment variables let pool = from_env::()? .create_pool() .map(Arc::new)?; // configure and run the tonic server on port 8675 Server::builder() .add_service(services::postgres::new(pool)) .serve(([127, 0, 0, 1], 8675).into()) .await?; Ok(()) } ``` ``` -------------------------------- ### Integrate postgrpc with tonic Source: https://docs.rs/postgrpc Demonstrates using the deadpool feature to integrate a Postgres service into a tonic server. ```rust use postgrpc::{pools::deadpool, services::postgres}; use std::sync::Arc; use tonic::transport::Server; // deadpool::Configuration implements serde::Deserialize, // so envy can be used to deserialize it from environment variables use envy::from_env; #[tokio::main] async fn main() -> Result<(), Box> { // create the connection pool from environment variables let pool = from_env::()? .create_pool() .map(Arc::new)?; // configure and run the tonic server on port 8675 Server::builder() .add_service(services::postgres::new(pool)) .serve(([127, 0, 0, 1], 8675).into()) .await?; Ok(()) } ``` -------------------------------- ### pub fn new

(pool: Arc

) -> HealthServer> Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/health/fn.new.html Initializes a new Health service instance. This function requires the 'health' crate feature to be enabled. ```APIDOC ## Function: new ### Description Creates a new Health service from a connection pool. This function is used to instantiate the health check service for the application. ### Signature `pub fn new

(pool: Arc

) -> HealthServer>` ### Constraints - `P: Pool + 'static` - `P::Key: Hash + Eq + Default + Clone` ### Requirements - Available on crate feature `health` only. ``` -------------------------------- ### Initialize TransactionServer Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/fn.new.html Creates a new Transaction service instance from a connection pool. Requires the transaction feature flag to be enabled. ```rust pub fn new

(pool: Arc

) -> TransactionServer> where P: Pool + 'static, P::Key: FromRequest + Hash + Eq + Clone, ``` -------------------------------- ### Pool::begin Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/transaction/struct.Pool.html Begins a transaction and stores the associated connection in the cache. ```APIDOC ## pub async fn begin(&self, key: P::Key) -> Result> ### Description Begins a transaction, storing the associated connection in the cache for the provided key. ``` -------------------------------- ### CloneToUninit Implementation Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.BeginResponse.html Experimental nightly-only API for performing copy-assignment to uninitialized memory. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Pool::new Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/transaction/struct.Pool.html Initializes a new shared transaction pool. ```APIDOC ## pub fn new(pool: Arc

) -> Self ### Description Initializes a new shared transaction pool wrapping a lower-level Pool implementation. ``` -------------------------------- ### Create a new Key Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/transaction/struct.Key.html Constructor for creating a new Key instance by pairing a connection pool key with a unique transaction ID. ```rust pub fn new(key: K, transaction_id: Uuid) -> Self ``` -------------------------------- ### Using Option::and Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns None if the option is None, otherwise returns the provided option. ```rust let x = Some(2); let y: Option<&str> = None; assert_eq!(x.and(y), None); let x: Option = None; let y = Some("foo"); assert_eq!(x.and(y), None); let x = Some(2); let y = Some("foo"); assert_eq!(x.and(y), Some("foo")); let x: Option = None; let y: Option<&str> = None; assert_eq!(x.and(y), None); ``` -------------------------------- ### Calculate Product of Option Values Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Demonstrates using the product method on an iterator of Option values, returning None if any element is None. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Option = nums.iter().map(|w| w.parse::().ok()).product(); assert_eq!(total, Some(100)); let nums = vec!["5", "10", "one", "2"]; let total: Option = nums.iter().map(|w| w.parse::().ok()).product(); assert_eq!(total, None); ``` -------------------------------- ### batch Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/deadpool/struct.Client.html Runs a set of SQL statements using the simple query protocol. ```APIDOC ## fn batch(&self, query: &str) -> Pin> + Send + '_>> ### Description Runs a set of SQL statements using the simple query protocol. ### Parameters - **query** (&str) - The SQL query string to execute. ### Returns - **Result<(), Self::Error>** - A future resolving to unit on success or an error. ``` -------------------------------- ### Initialize Postgres Service Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/postgres/fn.new.html Creates a new Postgres service instance from a connection pool wrapped in an Arc. The pool must implement the Pool trait and its key must satisfy the FromRequest trait. ```rust pub fn new

(pool: Arc

) -> PostgresServer> where P: Pool + 'static, P::Key: FromRequest, ``` -------------------------------- ### create_pool Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/deadpool/struct.Configuration.html Creates a new pool instance from the current configuration settings. ```APIDOC ## pub fn create_pool(self) -> Result ### Description Creates a new `Pool` instance using the settings defined in the `Configuration` struct. ### Returns - **Result** - Returns a `Pool` on success, or an `Error` if the pool creation fails. ``` -------------------------------- ### Initialize Health Service Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/health/fn.new.html Creates a new Health service instance from a connection pool. Requires the health feature flag to be enabled. ```rust pub fn new

(pool: Arc

) -> HealthServer> where P: Pool + 'static, P::Key: Hash + Eq + Default + Clone, ``` -------------------------------- ### Iterating over an Option Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Demonstrates using iter_mut on an Option. ```rust let mut x: Option = None; assert_eq!(x.iter_mut().next(), None); ``` -------------------------------- ### Map Option value Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Demonstrates mapping an Option value to a new value. ```rust let x: Option<&str> = None; assert_eq!(x.map(|s| s.len()), None); ``` -------------------------------- ### Default Option Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns a None value for an Option. ```rust let opt: Option = Option::default(); assert!(opt.is_none()); ``` -------------------------------- ### Implement FromRequest for Role Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/trait.FromRequest.html Implementation of FromRequest for the Role type, requiring the role-header feature. ```rust impl FromRequest for Role Available on crate feature`role-header` only. Source§ type Error = Status ``` -------------------------------- ### Using Option::or Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns the option if it contains a value, otherwise returns the provided option. ```rust let x = Some(2); let y = None; assert_eq!(x.or(y), Some(2)); let x = None; let y = Some(100); assert_eq!(x.or(y), Some(100)); let x = Some(2); let y = Some(100); assert_eq!(x.or(y), Some(2)); let x: Option = None; let y = None; assert_eq!(x.or(y), None); ``` -------------------------------- ### Using Option::xor Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns Some if exactly one of the options is Some. ```rust let x = Some(2); let y: Option = None; assert_eq!(x.xor(y), Some(2)); let x: Option = None; let y = Some(2); assert_eq!(x.xor(y), Some(2)); let x = Some(2); let y = Some(2); assert_eq!(x.xor(y), None); let x: Option = None; let y: Option = None; assert_eq!(x.xor(y), None); ``` -------------------------------- ### Convert to Reference Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Converts Option to Option<&T>. ```rust let text: Option = Some("Hello, world!".to_string()); // First, cast `Option` to `Option<&String>` with `as_ref`, // then consume *that* with `map`, leaving `text` on the stack. let text_length: Option = text.as_ref().map(|s| s.len()); println!("still can print text: {text:?}"); ``` -------------------------------- ### fn get_connection Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/trait.Pool.html Retrieves a connection from the pool based on the provided key. This method is asynchronous and returns a connection or an error. ```APIDOC ## fn get_connection ### Description Retrieves a single connection from the pool using a specified key. The key allows the pool to manage connection isolation and preparation logic internally. ### Signature `fn get_connection<'life0, 'async_trait>(&'life0 self, key: Self::Key) -> Pin> + Send + 'async_trait>>` ### Parameters - **key** (Self::Key) - Required - The key used to identify or fetch the specific connection from the pool. ### Returns - **Result** - A future that resolves to the connection or an error if the connection could not be retrieved. ``` -------------------------------- ### From Trait Implementation Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.BeginResponse.html Returns the argument unchanged. ```rust fn from(t: T) -> T ``` -------------------------------- ### Define Client struct Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/deadpool/struct.Client.html The definition of the Client struct, which is only available when the deadpool feature is enabled. ```rust pub struct Client { /* private fields */ } ``` -------------------------------- ### Calculate Sum of Option Values Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Demonstrates using the sum method on an iterator of Option values, returning None if any element is None. ```rust let words = vec!["have", "a", "great", "day"]; let total: Option = words.iter().map(|w| w.find('a')).sum(); assert_eq!(total, Some(5)); let words = vec!["have", "a", "good", "day"]; let total: Option = words.iter().map(|w| w.find('a')).sum(); assert_eq!(total, None); ``` -------------------------------- ### query Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/deadpool/struct.Client.html Runs a query parameterized by the Connection’s associated Parameter, returning a RowStream. ```APIDOC ## fn query(&self, statement: &str, parameters: &[Parameter]) -> Pin> + Send + '_>> ### Description Runs a query parameterized by the Connection’s associated Parameter, returning a RowStream. ### Parameters - **statement** (&str) - The SQL statement to execute. - **parameters** (&[Parameter]) - The parameters to bind to the query. ### Returns - **Result** - A future resolving to a fallible stream of rows returned as protobuf structs or an error. ``` -------------------------------- ### Using Option::filter Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Filters the Option based on a predicate. ```rust fn is_even(n: &i32) -> bool { n % 2 == 0 } assert_eq!(None.filter(is_even), None); assert_eq!(Some(3).filter(is_even), None); assert_eq!(Some(4).filter(is_even), Some(4)); ``` -------------------------------- ### BeginResponse Struct Definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.BeginResponse.html The structure definition for BeginResponse, containing the unique transaction ID. ```rust pub struct BeginResponse { pub id: String, } ``` -------------------------------- ### Implement FromRequest for unit type Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/trait.FromRequest.html A default implementation of FromRequest for the unit type (). ```rust impl FromRequest for () Source§ type Error = UnitConversion Source§ fn from_request(_: &mut Request) -> Result ``` -------------------------------- ### Expect a value from Option Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns the contained value or panics with a custom message if the Option is None. ```rust let x = Some("value"); assert_eq!(x.expect("fruits are healthy"), "value"); ``` ```rust let x: Option<&str> = None; x.expect("fruits are healthy"); // panics with `fruits are healthy` ``` ```rust let item = slice.get(0) .expect("slice should not be empty"); ``` -------------------------------- ### Collecting Option into a Vector Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Shows how to use into_iter to collect the contents of an Option into a Vec. ```rust let x = Some("string"); let v: Vec<&str> = x.into_iter().collect(); assert_eq!(v, ["string"]); let x = None; let v: Vec<&str> = x.into_iter().collect(); assert!(v.is_empty()); ``` -------------------------------- ### Using Option::and_then Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Chains fallible operations that return an Option. ```rust fn sq_then_to_string(x: u32) -> Option { x.checked_mul(x).map(|sq| sq.to_string()) } assert_eq!(Some(2).and_then(sq_then_to_string), Some(4.to_string())); assert_eq!(Some(1_000_000).and_then(sq_then_to_string), None); // overflowed! assert_eq!(None.and_then(sq_then_to_string), None); ``` ```rust let arr_2d = [["A0", "A1"], ["B0", "B1"]]; let item_0_1 = arr_2d.get(0).and_then(|row| row.get(1)); assert_eq!(item_0_1, Some(&"A1")); let item_2_0 = arr_2d.get(2).and_then(|row| row.get(0)); assert_eq!(item_2_0, None); ``` -------------------------------- ### get_connection Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/deadpool/struct.Pool.html Retrieves a single connection from the pool using a specified key. ```APIDOC ## fn get_connection ### Description Get a single connection from the pool using some key. ### Signature `fn get_connection<'life0, 'async_trait>(&'life0 self, key: Self::Key) -> Pin> + Send + 'async_trait>>` ### Parameters - **key** (Self::Key) - Required - The key by which connections are selected from the Pool. ``` -------------------------------- ### Zip two Options with a function Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Combines two options using a provided function if both are Some. Requires the option_zip feature. ```rust #![feature(option_zip)] #[derive(Debug, PartialEq)] struct Point { x: f64, y: f64, } impl Point { fn new(x: f64, y: f64) -> Self { Self { x, y } } } let x = Some(17.5); let y = Some(42.7); ``` -------------------------------- ### Check None or Predicate Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Checks if an option is None or matches a predicate. ```rust let x: Option = Some(2); assert_eq!(x.is_none_or(|x| x > 1), true); let x: Option = Some(0); assert_eq!(x.is_none_or(|x| x > 1), false); let x: Option = None; assert_eq!(x.is_none_or(|x| x > 1), true); let x: Option = Some("ownership".to_string()); assert_eq!(x.as_ref().is_none_or(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Map Option or default value Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Maps an Option to a value, returning the type's default if None. ```rust let x: Option<&str> = Some("hi"); let y: Option<&str> = None; assert_eq!(x.map_or_default(|x| x.len()), 2); assert_eq!(y.map_or_default(|y| y.len()), 0); ``` -------------------------------- ### Using Option::get_or_insert Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Inserts a value if the option is None, then returns a mutable reference. ```rust let mut x = None; { let y: &mut u32 = x.get_or_insert(5); assert_eq!(y, &5); *y = 7; } ``` -------------------------------- ### Take value from Option Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Extracts the value from the option, leaving None in its place. ```rust let mut x = Some(2); let y = x.take(); assert_eq!(x, None); assert_eq!(y, Some(2)); let mut x: Option = None; let y = x.take(); assert_eq!(x, None); assert_eq!(y, None); ``` -------------------------------- ### Check Some Value with Predicate Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Checks if an option is Some and matches a predicate. ```rust let x: Option = Some(2); assert_eq!(x.is_some_and(|x| x > 1), true); let x: Option = Some(0); assert_eq!(x.is_some_and(|x| x > 1), false); let x: Option = None; assert_eq!(x.is_some_and(|x| x > 1), false); let x: Option = Some("ownership".to_string()); assert_eq!(x.as_ref().is_some_and(|x| x.len() > 1), true); println!("still alive {:?}", x); ``` -------------------------------- ### Implement role-header interceptor Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/index.html Requires the 'role-header' feature enabled. This interceptor is used with tonic services to extract Postgres roles from requests. ```rust // requires the "role-header" feature use postgrpc::{extensions, pools::Pool, services}; use tonic::codegen::InterceptedService; // somewhere in a tonic app services::postgres::with_interceptor(pool, extensions::role_header::interceptor) ``` -------------------------------- ### Using Option::insert Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Inserts a value into the option and returns a mutable reference. ```rust let mut opt = None; let val = opt.insert(1); assert_eq!(*val, 1); assert_eq!(opt.unwrap(), 1); let val = opt.insert(2); assert_eq!(*val, 2); *val = 3; assert_eq!(opt.unwrap(), 3); ``` -------------------------------- ### Zip two Options into a tuple Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Combines two options into a single option containing a tuple if both are Some. ```rust let x = Some(1); let y = Some("hi"); let z = None::; assert_eq!(x.zip(y), Some((1, "hi"))); assert_eq!(x.zip(z), None); ``` -------------------------------- ### Map Option or default Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns a default value if None, or applies a function to the contained value. ```rust let x = Some("foo"); assert_eq!(x.map_or(42, |v| v.len()), 3); let x: Option<&str> = None; assert_eq!(x.map_or(42, |v| v.len()), 42); ``` -------------------------------- ### Into Trait Implementation Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.BeginResponse.html Performs a conversion into another type using the From implementation. ```rust fn into(self) -> U ``` -------------------------------- ### Iterate over Option Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns an iterator over the contained value. ```rust let x = Some(4); assert_eq!(x.iter().next(), Some(&4)); let x: Option = None; assert_eq!(x.iter().next(), None); ``` -------------------------------- ### Map Option or else Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Computes a default value using a function if None, or applies a function to the contained value. ```rust let k = 21; let x = Some("foo"); assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); let x: Option<&str> = None; assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); ``` ```rust let v: u64 = std::env::args() .nth(1) .map_or_else(|| std::fs::read_to_string("/etc/someconfig.conf"), Ok)? .parse()?; ``` -------------------------------- ### pub fn interceptor(request: Request<()>) -> Result, Status> Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/fn.interceptor.html Interceptor function for collecting user ROLEs from tonic::Request headers. ```APIDOC ## Function: interceptor ### Description Interceptor function for collecting user `ROLE`s from `tonic::Request` headers. This function is available only when the `role-header` crate feature is enabled. ### Signature `pub fn interceptor(request: Request<()>) -> Result, Status>` ### Parameters - **request** (Request<()>) - The incoming tonic request containing headers to be processed. ### Returns - **Result, Status>** - Returns the original request if successful, or a tonic::Status error if the interception fails. ``` -------------------------------- ### Convert Value to Option Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Moves a value into a new Some variant. ```rust let o: Option = Option::from(67); assert_eq!(Some(67), o); ``` -------------------------------- ### Check for None Value Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Checks if an option is None. ```rust let x: Option = Some(2); assert_eq!(x.is_none(), false); let x: Option = None; assert_eq!(x.is_none(), true); ``` -------------------------------- ### Unwrap with default value Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns the contained value or a provided default value. ```rust assert_eq!(Some("car").unwrap_or("bike"), "car"); assert_eq!(None.unwrap_or("bike"), "bike"); ``` -------------------------------- ### Reduce Options Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Reduces two options into one using a provided function if both are Some. ```rust #![feature(option_reduce)] let s12 = Some(12); let s17 = Some(17); let n = None; let f = |a, b| a + b; assert_eq!(s12.reduce(s17, f), Some(29)); assert_eq!(s12.reduce(n, f), Some(12)); assert_eq!(n.reduce(s17, f), Some(17)); assert_eq!(n.reduce(n, f), None); ``` -------------------------------- ### with_interceptor function signature Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/postgres/fn.with_interceptor.html Defines the function signature for creating an intercepted Postgres service. ```rust pub fn with_interceptor( pool: Arc

, interceptor: I, ) -> InterceptedService>, I> where P: Pool + 'static, P::Key: FromRequest, I: Interceptor, ``` -------------------------------- ### FromRef Trait Implementation Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.BeginResponse.html Converts to this type from a reference to the input type. ```rust fn from_ref(input: &T) -> T ``` -------------------------------- ### Unwrap an Option Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns the contained value, panicking if the Option is None. Prefer safer alternatives like pattern matching or unwrap_or. ```rust let x = Some("air"); assert_eq!(x.unwrap(), "air"); ``` ```rust let x: Option<&str> = None; assert_eq!(x.unwrap(), "air"); // fails ``` -------------------------------- ### from_request Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Derives a Role value from a tonic::Request. This method is used to extract the Role from incoming gRPC requests. ```APIDOC ## fn from_request(request: &mut Request) -> Result ### Description Derive a value from a `tonic::Request`. ### Parameters - **request** (&mut Request) - Required - The gRPC request to derive the Role from. ### Response - **Result** - Returns the Role instance on success, or a Status error if the derivation fails. ``` -------------------------------- ### Convert to Slice Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns a slice of the contained value or an empty slice. ```rust assert_eq!( [Some(1234).as_slice(), None.as_slice()], [&[1234][..], &[][..]], ); ``` ```rust for i in [Some(1234_u16), None] { assert_eq!(i.as_ref(), i.as_slice().first()); } ``` -------------------------------- ### Using Option::or_else Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns the option if it contains a value, otherwise calls the provided function. ```rust fn nobody() -> Option<&'static str> { None } fn vikings() -> Option<&'static str> { Some("vikings") } assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians")); assert_eq!(None.or_else(vikings), Some("vikings")); assert_eq!(None.or_else(nobody), None); ``` -------------------------------- ### Transform Option to Result with closure Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Converts an Option to a Result, using a closure to generate the error if None. ```rust let x = Some("foo"); assert_eq!(x.ok_or_else(|| 0), Ok("foo")); let x: Option<&str> = None; assert_eq!(x.ok_or_else(|| 0), Err(0)); ``` -------------------------------- ### Replace value in Option Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Replaces the current value with a new one and returns the old value. ```rust let mut x = Some(2); let old = x.replace(5); assert_eq!(x, Some(5)); assert_eq!(old, Some(2)); let mut x = None; let old = x.replace(3); assert_eq!(x, Some(3)); assert_eq!(old, None); ``` -------------------------------- ### Use into_flat_iter Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Transforms an optional iterator into an iterator. ```rust #![feature(option_into_flat_iter)] let o1 = Some([1, 2]); let o2 = None::<&[usize]>; assert_eq!(o1.into_flat_iter().collect::>(), [1, 2]); assert_eq!(o2.into_flat_iter().collect::>(), Vec::<&usize>::new()); ``` -------------------------------- ### Apply async_trait attribute Source: https://docs.rs/postgrpc/0.1.2/postgrpc/attr.async_trait.html Use this attribute macro to enable async trait implementations. ```rust #[async_trait] ``` -------------------------------- ### Map an Option Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Applies a function to the contained value if Some, otherwise returns None. ```rust let maybe_some_string = Some(String::from("Hello, World!")); // `Option::map` takes self *by value*, consuming `maybe_some_string` let maybe_some_len = maybe_some_string.map(|s| s.len()); assert_eq!(maybe_some_len, Some(13)); ``` -------------------------------- ### Convert to Mutable Reference Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Converts Option to Option<&mut T>. ```rust let mut x = Some(2); match x.as_mut() { Some(v) => *v = 42, None => {}, } assert_eq!(x, Some(42)); ``` -------------------------------- ### Check for Some Value Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Checks if an option contains a value. ```rust let x: Option = Some(2); assert_eq!(x.is_some(), true); let x: Option = None; assert_eq!(x.is_some(), false); ``` -------------------------------- ### Key Struct Definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/transaction/struct.Key.html The definition of the Key struct, which requires the generic type K to implement Hash and Eq. ```rust pub struct Key where K: Hash + Eq, { /* private fields */ } ``` -------------------------------- ### Inspect Option value Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Executes a function with a reference to the contained value if it is Some. ```rust let list = vec![1, 2, 3]; // prints "got: 2" let x = list .get(1) .inspect(|x| println!("got: {x}")) .expect("list should be long enough"); // prints nothing list.get(5).inspect(|x| println!("got: {x}")); ``` -------------------------------- ### Collect Iterator of Options Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Collects an iterator of Options into an Option of a collection, returning None if any element is None. ```rust let items = vec![0_u16, 1, 2]; let res: Option> = items .iter() .map(|x| x.checked_add(1)) .collect(); assert_eq!(res, Some(vec![1, 2, 3])); ``` ```rust let items = vec![2_u16, 1, 0]; let res: Option> = items .iter() .map(|x| x.checked_sub(1)) .collect(); assert_eq!(res, None); ``` ```rust let items = vec![3_u16, 2, 1, 10]; let mut shared = 0; let res: Option> = items .iter() .map(|x| { shared += x; x.checked_sub(2) }) .collect(); ``` -------------------------------- ### QueryRequest Struct Definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/postgres/struct.QueryRequest.html The structure definition for QueryRequest, consisting of a statement string and a vector of values. ```rust pub struct QueryRequest { pub statement: String, pub values: Vec, } ``` -------------------------------- ### IntoRequest Trait Implementation Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.BeginResponse.html Wraps the input message into a tonic Request. ```rust fn into_request(self) -> Request ``` -------------------------------- ### Transform Option to Result Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Converts an Option to a Result, using a provided error value if None. ```rust let x = Some("foo"); assert_eq!(x.ok_or(0), Ok("foo")); let x: Option<&str> = None; assert_eq!(x.ok_or(0), Err(0)); ``` -------------------------------- ### Instrument Trait Implementation Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.BeginResponse.html Provides methods to instrument types with tracing spans. ```rust fn instrument(self, span: Span) -> Instrumented fn in_current_span(self) -> Instrumented ``` -------------------------------- ### Postgres Struct Definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/postgres/struct.Postgres.html The primary definition of the Postgres struct, which is generic over a pool type P. ```rust pub struct Postgres

{ /* private fields */ } ``` -------------------------------- ### Conditionally take value from Option Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Takes the value out of the option only if the provided predicate returns true. ```rust let mut x = Some(42); let prev = x.take_if(|v| if *v == 42 { *v += 1; false } else { false }); assert_eq!(x, Some(43)); assert_eq!(prev, None); let prev = x.take_if(|v| *v == 43); assert_eq!(x, None); assert_eq!(prev, Some(43)); ``` -------------------------------- ### with_interceptor function signature Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/fn.with_interceptor.html Defines the function signature for creating an intercepted transaction service. Requires the transaction feature flag to be enabled. ```rust pub fn with_interceptor( pool: Arc

, interceptor: I, ) -> InterceptedService>, I> where P: Pool + 'static, P::Key: FromRequest + Hash + Eq + Clone, I: Interceptor, ``` -------------------------------- ### Unwrap with closure Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns the contained value or computes a default value using a closure. ```rust let k = 10; assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); assert_eq!(None.unwrap_or_else(|| 2 * k), 20); ``` -------------------------------- ### Insert default value into Option Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Inserts the default value if the option is None and returns a mutable reference to the value. ```rust let mut x = None; { let y: &mut u32 = x.get_or_insert_default(); assert_eq!(y, &0); *y = 7; } assert_eq!(x, Some(7)); ``` -------------------------------- ### StructStream Definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/deadpool/struct.StructStream.html The definition of the StructStream struct. ```rust pub struct StructStream { /* private fields */ } ``` -------------------------------- ### Connection Trait Definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/trait.Connection.html The core trait definition requiring Send and Sync, defining associated types for row streams and errors, and specifying query and batch methods. ```rust pub trait Connection: Send + Sync { type RowStream: TryStream + Send + Sync; type Error: Error + Into + Send + Sync; // Required methods fn query<'life0, 'life1, 'life2, 'async_trait>( &'life0 self, statement: &'life1 str, parameters: &'life2 [Parameter], ) -> Pin> + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait; fn batch<'life0, 'life1, 'async_trait>( &'life0 self, query: &'life1 str, ) -> Pin> + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait; } ``` -------------------------------- ### Parameter struct definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/struct.Parameter.html The definition of the Parameter struct as a private newtype wrapper. ```rust pub struct Parameter(/* private fields */); ``` -------------------------------- ### Convert Option to mutable slice Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Use as_mut_slice to obtain a mutable slice of the contained value, returning an empty slice if None. ```rust assert_eq!( [Some(1234).as_mut_slice(), None.as_mut_slice()], [&mut [1234][..], &mut [][..]], ); ``` ```rust let mut x = Some(1234); x.as_mut_slice()[0] += 1; assert_eq!(x, Some(1235)); ``` ```rust assert_eq!(Some(123).as_mut_slice().first_mut(), Some(&mut 123)) ``` -------------------------------- ### TryFrom Trait Implementation Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.BeginResponse.html Performs a fallible conversion from another type. ```rust fn try_from(value: U) -> Result>::Error> ``` -------------------------------- ### TransactionQueryRequest Struct Definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.TransactionQueryRequest.html The primary data structure for transaction queries, containing the statement, values, and ID fields. ```rust pub struct TransactionQueryRequest { pub statement: String, pub values: Vec, pub id: String, } ``` -------------------------------- ### TryInto Trait Implementation Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.BeginResponse.html Performs a fallible conversion into another type. ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Define Role Type Alias Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html The primary definition of the Role type alias. ```rust pub type Role = Option; ``` -------------------------------- ### Represent Role Enum Structure Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html The underlying enum structure for the Role type. ```rust pub enum Role { None, Some(String), } ``` -------------------------------- ### Conditionally insert value using Try trait Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Inserts a value if the option is None, provided the closure returns a successful result. Requires the option_get_or_try_insert_with feature. ```rust #![feature(option_get_or_try_insert_with)] let mut o1: Option = None; let mut o2: Option = None; let number = "12345"; assert_eq!(o1.get_or_try_insert_with(|| number.parse()).copied(), Ok(12345)); assert!(o2.get_or_try_insert_with(|| number.parse()).is_err()); assert_eq!(o1, Some(12345)); assert_eq!(o2, None); ``` -------------------------------- ### Define the Pool Trait Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/trait.Pool.html The core trait definition requiring Send and Sync bounds, associated types for keys, connections, and errors, and the get_connection method. ```rust pub trait Pool: Send + Sync { type Key: Debug + Send + Sync; type Connection: Connection; type Error: Error + From<::Error> + Into + Send + Sync; // Required method fn get_connection<'life0, 'async_trait>( &'life0 self, key: Self::Key, ) -> Pin> + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait; } ``` -------------------------------- ### WithSubscriber Trait Implementation Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.BeginResponse.html Attaches a subscriber to the type for tracing purposes. ```rust fn with_subscriber(self, subscriber: S) -> WithDispatch fn with_current_subscriber(self) -> WithDispatch ``` -------------------------------- ### interceptor Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/index.html An interceptor function used to collect user roles from tonic::Request headers. ```APIDOC ## interceptor ### Description Interceptor function for collecting user `ROLE`s from `tonic::Request` headers. This function is available when the `role-header` feature is enabled. ### Signature `pub fn interceptor(request: tonic::Request) -> Result, tonic::Status>` ``` -------------------------------- ### Define Pool struct Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/deadpool/struct.Pool.html The internal structure of the Pool type. ```rust pub struct Pool { /* private fields */ } ``` -------------------------------- ### Define UnitConversion struct Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/struct.UnitConversion.html The definition of the UnitConversion unit struct. ```rust pub struct UnitConversion; ``` -------------------------------- ### Insert value from closure into Option Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Computes a value from a closure to insert if the option is None, returning a mutable reference. ```rust let mut x = None; { let y: &mut u32 = x.get_or_insert_with(|| 5); assert_eq!(y, &5); *y = 7; } assert_eq!(x, Some(7)); ``` -------------------------------- ### Mutably iterate over Option Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns a mutable iterator over the contained value. ```rust let mut x = Some(4); match x.iter_mut().next() { Some(v) => *v = 42, None => {}, } assert_eq!(x, Some(42)); ``` -------------------------------- ### CommitRequest Struct Definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.CommitRequest.html The primary structure definition for CommitRequest, containing the transaction ID. ```rust pub struct CommitRequest { pub id: String, } ``` -------------------------------- ### Define the FromRequest trait Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/trait.FromRequest.html The trait definition requires an associated Error type that can be converted into a tonic::Status. ```rust pub trait FromRequest where Self: Sized, { type Error: Error + Into; // Required method fn from_request(request: &mut Request) -> Result; } ``` -------------------------------- ### Unwrap with default trait Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns the contained value or the default value for the type if None. ```rust let x: Option = None; let y: Option = Some(12); assert_eq!(x.unwrap_or_default(), 0); assert_eq!(y.unwrap_or_default(), 12); ``` -------------------------------- ### Interceptor function signature Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/fn.interceptor.html The function signature for the interceptor used to process tonic requests. ```rust pub fn interceptor(request: Request<()>) -> Result, Status> ``` -------------------------------- ### Health Struct Definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/health/struct.Health.html The definition of the Health struct, which is generic over a connection pool P. ```rust pub struct Health

where P: Pool, P::Key: Hash + Eq + Default + Clone, { /* private fields */ } ``` -------------------------------- ### Pool::rollback Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/transaction/struct.Pool.html Rolls back a transaction and removes it from the cache. ```APIDOC ## pub async fn rollback(&self, transaction_id: Uuid, key: P::Key) -> Result<(), Error<...>> ### Description Removes a transaction from the cache, rolling back all intermediate changes. ``` -------------------------------- ### HealthCheckResponse struct definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/health/struct.HealthCheckResponse.html The primary structure definition for the health check response. ```rust pub struct HealthCheckResponse { pub status: i32, } ``` -------------------------------- ### Transaction Struct Definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.Transaction.html The definition of the Transaction struct, requiring a pool that implements the Pool trait. ```rust pub struct Transaction

where P: Pool, P::Key: Hash + Eq + Clone, { /* private fields */ } ``` -------------------------------- ### Pool::commit Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/transaction/struct.Pool.html Commits a transaction and removes it from the cache. ```APIDOC ## pub async fn commit(&self, transaction_id: Uuid, key: P::Key) -> Result<(), Error<...>> ### Description Removes a transaction from the cache, committing its changeset in postgres. ``` -------------------------------- ### RollbackRequest Struct Definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.RollbackRequest.html The definition of the RollbackRequest struct containing the transaction ID. ```rust pub struct RollbackRequest { pub id: String, } ``` -------------------------------- ### Define Transaction Struct Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/transaction/struct.Transaction.html The definition of the Transaction struct, which is generic over a Connection type and contains private fields. ```rust pub struct Transaction where C: Connection, { /* private fields */ } ``` -------------------------------- ### HealthCheckRequest struct definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/health/struct.HealthCheckRequest.html The primary structure definition for HealthCheckRequest containing the service field. ```rust pub struct HealthCheckRequest { pub service: String, } ``` -------------------------------- ### Pool Struct Definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/transaction/struct.Pool.html The definition of the Pool struct, requiring a generic type P that implements the Pool trait. ```rust pub struct Pool

where P: Pool, P::Key: Hash + Eq + Clone, { /* private fields */ } ``` -------------------------------- ### Unwrap without checking Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Returns the contained value without checking for None. Calling on None is undefined behavior. ```rust let x = Some("air"); assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); ``` ```rust let x: Option<&str> = None; assert_eq!(unsafe { x.unwrap_unchecked() }, "air"); // Undefined behavior! ``` -------------------------------- ### Deref Option contents Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Converts an Option to an Option containing a reference to the inner type's target. ```rust let x: Option = Some("hey".to_owned()); assert_eq!(x.as_deref(), Some("hey")); let x: Option = None; assert_eq!(x.as_deref(), None); ``` -------------------------------- ### ToOwned Trait Implementation Source: https://docs.rs/postgrpc/0.1.2/postgrpc/services/transaction/struct.BeginResponse.html Provides methods for creating owned data from borrowed data. ```rust fn to_owned(&self) -> T fn clone_into(&self, target: &mut T) ``` -------------------------------- ### Error Enum Definition Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/deadpool/enum.Error.html The structure of the Error enum used for handling database and pooling operations. ```rust pub enum Error { Params { expected: usize, actual: usize, }, Pool(PoolError), Query(Error), Role(Error), InvalidJson, Create(CreatePoolError), Tls(Error), } ``` -------------------------------- ### Define the Error enum Source: https://docs.rs/postgrpc/0.1.2/postgrpc/pools/transaction/enum.Error.html The Error enum structure for transaction pool operations, generic over a connection error type C. ```rust pub enum Error where C: Error + 'static, { Connection(C), ConnectionFailure, Uninitialized, } ``` -------------------------------- ### Deref Option contents mutably Source: https://docs.rs/postgrpc/0.1.2/postgrpc/extensions/role_header/type.Role.html Converts an Option to an Option containing a mutable reference to the inner type's target. ```rust let mut x: Option = Some("hey".to_owned()); assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), Some("HEY".to_owned().as_mut_str())); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.