### Example Connection URLs for AnyConnectOptions Source: https://docs.rs/sqlx/latest/sqlx/any/struct.AnyConnectOptions.html Illustrative connection URLs that can be parsed to construct AnyConnectOptions. These examples show the expected format for PostgreSQL and MySQL. ```text postgres://postgres:password@localhost/database mysql://root:password@localhost/database ``` -------------------------------- ### Install Default Drivers for AnyConnection Source: https://docs.rs/sqlx/latest/src/sqlx/any/mod.rs.html Installs all compiled-in drivers for `AnyConnection`. Subsequent calls have no effect. Panics if non-default drivers were installed previously. ```rust pub fn install_default_drivers() { static ONCE: Once = Once::new(); ONCE.call_once(|| { install_drivers(&[ #[cfg(feature = "mysql")] sqlx_mysql::any::DRIVER, #[cfg(feature = "postgres")] sqlx_postgres::any::DRIVER, #[cfg(feature = "_sqlite")] sqlx_sqlite::any::DRIVER, ]) .expect("non-default drivers already installed") }); } ``` -------------------------------- ### install_default_drivers Source: https://docs.rs/sqlx/latest/sqlx/any/fn.install_default_drivers.html Installs all currently compiled-in drivers for `AnyConnection` to use. This function can be called multiple times, but only the first call will install drivers; subsequent calls will have no effect. It may panic if `install_drivers` has already been called through a different mechanism. ```APIDOC ## install_default_drivers ### Description Installs all currently compiled-in drivers for `AnyConnection` to use. May be called multiple times; only the first call will install drivers, subsequent calls will have no effect. ### Panics If `install_drivers` has already been called _not_ through this function. ### Signature ```rust pub fn install_default_drivers() ``` ### Availability Available on crate feature `any` only. ``` -------------------------------- ### try_begin Source: https://docs.rs/sqlx/latest/sqlx/type.AnyPool.html Attempts to acquire a connection from the pool and start a new transaction. Returns an `Option` if successful, or an `Error` if an issue occurs during connection acquisition or transaction start. ```APIDOC ## try_begin ### Description Attempts to retrieve a connection and immediately begins a new transaction if successful. ### Method `async fn try_begin(&self) -> Result>, Error>` ### Parameters None ### Returns - `Result>, Error>`: An `Ok` containing `Some(Transaction)` if a connection was acquired and a transaction started, `Ok(None)` if no connection could be acquired, or `Err(Error)` if an error occurred. ``` -------------------------------- ### Get Day0 from NaiveDate Source: https://docs.rs/sqlx/latest/sqlx/types/chrono/struct.NaiveDate.html Retrieves the day of the month starting from 0 for a NaiveDate. Supports both AD and BCE years. ```rust use chrono::{Datelike, NaiveDate}; assert_eq!(NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().day0(), 7); assert_eq!(NaiveDate::from_ymd_opt(-308, 3, 14).unwrap().day0(), 13) ``` -------------------------------- ### Iterating Over Characters and Their Indices Source: https://docs.rs/sqlx/latest/sqlx/postgres/types/struct.PgLTreeLabel.html Demonstrates iterating over a string slice to get both each character and its starting byte position using `char_indices`. ```Rust let s = "abc"; let mut iter = s.char_indices(); assert_eq!(iter.next(), Some((0, 'a'))); assert_eq!(iter.next(), Some((1, 'b'))); assert_eq!(iter.next(), Some((2, 'c'))); assert_eq!(iter.next(), None); ``` -------------------------------- ### begin_with Source: https://docs.rs/sqlx/latest/sqlx/type.SqlitePool.html Retrieves a connection and immediately begins a new transaction using the provided statement. This is a convenient way to start a transaction with a specific initial query. ```APIDOC ## begin_with ### Description Retrieves a connection and immediately begins a new transaction using the provided statement. This is a convenient way to start a transaction with a specific initial query. ### Method `async fn begin_with(&self, statement: impl SqlSafeStr) -> Result, Error>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage (assuming `pool` is a SqlitePool) // let transaction = pool.begin_with("BEGIN IMMEDIATE").await?; ``` ### Response #### Success Response Returns a `Transaction` object representing the newly started transaction. #### Response Example ```rust // Transaction<'static, DB> ``` #### Error Response Returns `Error` if a connection cannot be retrieved or the transaction cannot be started. ``` -------------------------------- ### begin_with Source: https://docs.rs/sqlx/latest/sqlx/postgres/type.PgPool.html Retrieves a connection and immediately begins a new transaction using the provided SQL statement. ```APIDOC ## begin_with ### Description Retrieves a connection and immediately begins a new transaction using the provided SQL statement. ### Method `async fn begin_with(&self, statement: impl SqlSafeStr) -> Result, Error>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage (assuming `pool` is a `PgPool`) let transaction = pool.begin_with("BEGIN").await?; ``` ### Response #### Success Response - `Transaction<'static, DB>`: A new transaction object. #### Response Example ```rust // Transaction object is returned on success ``` ERROR HANDLING: - Returns `Error::PoolClosed` if the pool is closed. ``` -------------------------------- ### Get Ordinal0 Day from NaiveDate Source: https://docs.rs/sqlx/latest/sqlx/types/chrono/struct.NaiveDate.html Retrieves the day of the year starting from 0 for a NaiveDate. The return value ranges from 0 to 365. ```rust use chrono::{Datelike, NaiveDate}; assert_eq!(NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().ordinal0(), 250); assert_eq!(NaiveDate::from_ymd_opt(-308, 3, 14).unwrap().ordinal0(), 73) ``` -------------------------------- ### Get Ordinal Day from NaiveDate Source: https://docs.rs/sqlx/latest/sqlx/types/chrono/struct.NaiveDate.html Retrieves the day of the year starting from 1 for a NaiveDate. The return value ranges from 1 to 366. ```rust use chrono::{Datelike, NaiveDate}; assert_eq!(NaiveDate::from_ymd_opt(2015, 9, 8).unwrap().ordinal(), 251); assert_eq!(NaiveDate::from_ymd_opt(-308, 3, 14).unwrap().ordinal(), 74) ``` -------------------------------- ### begin_with Source: https://docs.rs/sqlx/latest/sqlx/sqlite/type.SqlitePool.html Retrieves a connection and immediately begins a new transaction using the provided SQL statement. ```APIDOC ## begin_with ### Description Retrieves a connection and immediately begins a new transaction using the provided SQL statement. ### Method `async fn` ### Parameters #### Path Parameters - `statement` (impl SqlSafeStr) - Description not available ### Response #### Success Response - `Transaction<'static, DB>` - A new transaction object. - `Error` - If an error occurs during connection retrieval or transaction initiation. ``` -------------------------------- ### begin_with Source: https://docs.rs/sqlx/latest/sqlx/type.PgPool.html Retrieves a connection and immediately begins a new transaction using the provided SQL statement. ```APIDOC ## begin_with ### Description Retrieves a connection and immediately begins a new transaction using the provided SQL statement. ### Method `async fn begin_with(&self, statement: impl SqlSafeStr) -> Result, Error>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response Returns a `Transaction` object upon successful retrieval of a connection and initiation of a transaction. #### Response Example None ``` -------------------------------- ### BTreeMap Get Example Source: https://docs.rs/sqlx/latest/sqlx/postgres/types/struct.PgHstore.html Shows how to retrieve a value from a BTreeMap using a key. Returns `Some(&value)` if the key exists, and `None` otherwise. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); ``` -------------------------------- ### Get Ordinal Day of Year Source: https://docs.rs/sqlx/latest/sqlx/types/time/struct.Date.html Retrieves the day of the year (1-365 or 1-366) for a Date. This is the number of days elapsed since the start of the year. ```rust assert_eq!(date!(2019-01-01).ordinal(), 1); assert_eq!(date!(2019-12-31).ordinal(), 365); ``` -------------------------------- ### begin_with Source: https://docs.rs/sqlx/latest/sqlx/mysql/type.MySqlPool.html Retrieves a connection and immediately begins a new transaction using the provided SQL statement. ```APIDOC ## begin_with ### Description Retrieves a connection and immediately begins a new transaction using the provided SQL statement. ### Method `async fn` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response - `Result, Error>`: A new transaction object or an error. #### Response Example None ``` -------------------------------- ### BTreeMap Get Key Value Example Source: https://docs.rs/sqlx/latest/sqlx/postgres/types/struct.PgHstore.html Demonstrates retrieving both the key and value from a BTreeMap. This is useful when the key type might have non-identical but equal instances, or for obtaining a reference to the stored key. ```rust use std::cmp::Ordering; use std::collections::BTreeMap; #[derive(Clone, Copy, Debug)] struct S { id: u32, name: &'static str, // ignored by equality and ordering operations } impl PartialEq for S { fn eq(&self, other: &S) -> bool { self.id == other.id } } impl Eq for S {} impl PartialOrd for S { fn partial_cmp(&self, other: &S) -> Option { self.id.partial_cmp(&other.id) } } impl Ord for S { fn cmp(&self, other: &S) -> Ordering { self.id.cmp(&other.id) } } let j_a = S { id: 1, name: "Jessica" }; let j_b = S { id: 1, name: "Jess" }; let p = S { id: 2, name: "Paul" }; assert_eq!(j_a, j_b); let mut map = BTreeMap::new(); map.insert(j_a, "Paris"); assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris"))); assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case assert_eq!(map.get_key_value(&p), None); ``` -------------------------------- ### begin_with Source: https://docs.rs/sqlx/latest/sqlx/type.MySqlPool.html Retrieves a connection and immediately begins a new transaction using the provided SQL statement. ```APIDOC ## begin_with ### Description Retrieves a connection and immediately begins a new transaction using the provided SQL statement. ### Method `async fn begin_with(&self, statement: impl SqlSafeStr) -> Result, Error>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response `Transaction<'static, DB>`: A new transaction object. #### Response Example None ``` -------------------------------- ### Creating and Using a Pool Source: https://docs.rs/sqlx/latest/sqlx/pool/struct.Pool.html Demonstrates how to create a database pool and acquire connections. Connections are automatically returned to the pool when dropped. ```rust let pool = Pool::connect("postgres://user:password@host:port/database").await?; let mut conn = pool.acquire().await?; sqlx::query!("SELECT ! FROM users WHERE id = ?", 1).fetch_one(&mut conn).await?; ``` -------------------------------- ### Example of Box::new_uninit_in with System allocator Source: https://docs.rs/sqlx/latest/sqlx/_config/drivers/type.TryParseError.html Demonstrates constructing a Box with uninitialized contents using the nightly-only Box::new_uninit_in and the System allocator, followed by deferred initialization. ```rust #![feature(allocator_api)] use std::alloc::System; let mut five = Box::::new_uninit_in(System); // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5) ``` -------------------------------- ### Getting Elements and Sub-slices with get Source: https://docs.rs/sqlx/latest/sqlx/postgres/struct.PgArgumentBuffer.html Safely retrieves elements or sub-slices from a slice using `get` with various index types (position, range). Returns `None` for out-of-bounds indices. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### begin_with Source: https://docs.rs/sqlx/latest/sqlx/struct.Pool.html Retrieves a connection and starts a new transaction using a provided SQL statement. This is useful for custom transaction initialization. ```APIDOC ## begin_with ### Description Retrieves a connection and immediately begins a new transaction using the provided statement. ### Method `begin_with` ### Parameters * `statement` (impl SqlSafeStr) - The SQL statement to use for beginning the transaction. ### Returns `Result, Error>` - A `Result` containing the new transaction or an error. ``` -------------------------------- ### Get a clone of the pool's connection options Source: https://docs.rs/sqlx/latest/sqlx/mysql/type.MySqlPool.html Gets a clone of the connection options that this pool uses when opening new connections. ```rust use sqlx::mysql::{MySqlConnectOptions, MySqlPool}; use std::sync::Arc; fn get_connect_options(pool: &MySqlPool) -> Arc { pool.connect_options() } ``` -------------------------------- ### Check if ByteSlice Starts With Prefix Source: https://docs.rs/sqlx/latest/sqlx/types/bstr/trait.ByteSlice.html Returns true if the byte string starts with the specified prefix. The prefix can be any type that can be converted to `&[u8]`. ```rust use bstr::ByteSlice; assert!(b"foo bar".starts_with_str("foo")); assert!(!b"foo bar".starts_with_str("bar")); assert!(!b"foo".starts_with_str("foobar")); ``` -------------------------------- ### BitVec Example: Initialization and Manipulation Source: https://docs.rs/sqlx/latest/sqlx/types/struct.BitVec.html Demonstrates creating a BitVec, setting individual bits, iterating, and performing bitwise negation and clearing. ```rust use bit_vec::BitVec; let mut bv = BitVec::from_elem(10, false); // insert all primes less than 10 bv.set(2, true); bv.set(3, true); bv.set(5, true); bv.set(7, true); println!("{:?}", bv); println!("total bits set to true: {}", bv.iter().filter(|x| *x).count()); // flip all values in bitvector, producing non-primes less than 10 bv.negate(); println!("{:?}", bv); println!("total bits set to true: {}", bv.iter().filter(|x| *x).count()); // reset bitvector to empty bv.clear(); println!("{:?}", bv); println!("total bits set to true: {}", bv.iter().filter(|x| *x).count()); ``` -------------------------------- ### begin_with Source: https://docs.rs/sqlx/latest/sqlx/struct.SqliteConnection.html Starts a new transaction using a custom SQL statement. This allows for more control over the transaction's initial state. ```APIDOC ## begin_with ### Description Begins a new transaction using a specified SQL statement to initialize it. ### Method `begin_with` ### Parameters - `statement`: An SQL statement that defines the beginning of the transaction. ### Returns A `Future` that resolves to a `Result` containing a `Transaction` object or an `Error`. ``` -------------------------------- ### Getting Mutable Values from a BTreeMap Source: https://docs.rs/sqlx/latest/sqlx/postgres/types/struct.PgHstore.html Illustrates how to get a mutable iterator over the values of a BTreeMap and modify them in place. Requires `std::collections::BTreeMap`. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, String::from("hello")); a.insert(2, String::from("goodbye")); for value in a.values_mut() { value.push_str("!"); } let values: Vec = a.values().cloned().collect(); assert_eq!(values, [String::from("hello!"), String::from("goodbye!")]); ``` -------------------------------- ### Get Underlying Array Reference Source: https://docs.rs/sqlx/latest/sqlx/postgres/types/struct.PgLTree.html Attempts to get a reference to the underlying array if its length exactly matches N. Returns None otherwise. ```rust let arr = [1, 2, 3]; let slice = &arr[..]; // This will return Some(&[1, 2, 3]) let array_ref: Option<&[i32; 3]> = slice.as_array(); // This will return None because N (2) does not match slice length (3) let array_ref_mismatch: Option<&[i32; 2]> = slice.as_array(); ``` -------------------------------- ### begin_with Source: https://docs.rs/sqlx/latest/sqlx/type.AnyPool.html Retrieves a connection from the pool and starts a new transaction using a provided SQL statement. This is useful for custom transaction initialization. ```APIDOC ## begin_with ### Description Retrieves a connection and immediately begins a new transaction using the provided `statement`. ### Method `async fn begin_with(&self, statement: impl SqlSafeStr) -> Result, Error>` ### Parameters - `statement` (impl SqlSafeStr): The SQL statement to use for initializing the transaction. ### Returns - `Result, Error>`: An `Ok(Transaction)` if successful, or `Err(Error)` if an error occurred. ``` -------------------------------- ### Safely Get Subslice with Index Source: https://docs.rs/sqlx/latest/sqlx/postgres/types/struct.PgCiText.html Use `get` for non-panicking retrieval of subslices. It returns `None` if the index is invalid or not on a UTF-8 sequence boundary. ```rust let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` -------------------------------- ### begin_with Source: https://docs.rs/sqlx/latest/sqlx/pool/struct.Pool.html Retrieves a connection and immediately begins a new transaction using the provided SQL statement. This is an asynchronous operation. ```APIDOC ## begin_with ### Description Retrieves a connection and immediately begins a new transaction using the provided `statement`. ### Method `begin_with` ### Parameters * `statement` (impl SqlSafeStr) - The SQL statement to use for beginning the transaction. ### Returns `Result, Error>` - A `Result` containing a `Transaction` on success, or an `Error` if the operation fails. ``` -------------------------------- ### options Source: https://docs.rs/sqlx/latest/sqlx/postgres/struct.PgConnectOptions.html Set additional startup options for the connection as a list of key-value pairs. Escapes the options’ backslash and space characters. ```APIDOC ## options ### Description Set additional startup options for the connection as a list of key-value pairs. Escapes the options’ backslash and space characters as per https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-OPTIONS. ### Method `options` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust let options = PgConnectOptions::new() .options([("geqo", "off"), ("statement_timeout", "5min")]); ``` ### Response #### Success Response (200) Returns the modified `PgConnectOptions`. #### Response Example None ``` -------------------------------- ### Connecting to PostgreSQL with sqlx Source: https://docs.rs/sqlx/latest/sqlx/postgres/struct.PgConnectOptions.html Demonstrates connecting to a PostgreSQL database using both a URL string and manually constructed connection options. It also shows how to modify parsed options and create a connection pool. ```rust use sqlx::{Connection, ConnectOptions}; use sqlx::postgres::{PgConnectOptions, PgConnection, PgPool, PgSslMode}; // URL connection string let conn = PgConnection::connect("postgres://localhost/mydb").await?; // Manually-constructed options let conn = PgConnectOptions::new() .host("secret-host") .port(2525) .username("secret-user") .password("secret-password") .ssl_mode(PgSslMode::Require) .connect() .await?; // Modifying options parsed from a string let mut opts: PgConnectOptions = "postgres://localhost/mydb".parse()?; // Change the log verbosity level for queries. // Information about SQL queries is logged at `DEBUG` level by default. opts = opts.log_statements(log::LevelFilter::Trace); let pool = PgPool::connect_with(opts).await?; ``` -------------------------------- ### Attempt to Start a Transaction with a Statement Source: https://docs.rs/sqlx/latest/sqlx/type.AnyPool.html Attempts to start a new transaction using a specific SQL statement. Returns `Ok(None)` if the pool is closed. ```rust let tx = pool.try_begin_with("SET app.my_setting = true").await?; ``` -------------------------------- ### strip_prefix Source: https://docs.rs/sqlx/latest/sqlx/postgres/types/struct.PgLTree.html Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If the slice does not start with `prefix`, returns `None`. ```APIDOC ## pub fn strip_prefix

(&self, prefix: &P) -> Option<&[T]> ### Description Returns a subslice with the prefix removed. If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. If `prefix` is empty, simply returns the original slice. If `prefix` is equal to the original slice, returns an empty slice. If the slice does not start with `prefix`, returns `None`. ### Method `strip_prefix` ### Parameters #### Path Parameters - `prefix` (&P): The pattern to strip from the beginning of the slice. ### Response #### Success Response - `Option<&[T]>`: A subslice with the prefix removed, or `None` if the slice does not start with the prefix. ``` -------------------------------- ### Connect using AnyConnection Source: https://docs.rs/sqlx/latest/sqlx/database/index.html Demonstrates how to connect to a database using the `AnyConnection` type, which supports runtime selection of the driver based on the URL scheme. This allows for switching between SQLite and PostgreSQL without code changes. ```rust // connect to SQLite let conn = AnyConnection::connect("sqlite://file.db").await?; // connect to Postgres, no code change // required, decided by the scheme of the URL let conn = AnyConnection::connect("postgres://localhost/sqlx").await?; ``` -------------------------------- ### Example of Box::try_new_uninit_in with System allocator Source: https://docs.rs/sqlx/latest/sqlx/_config/drivers/type.TryParseError.html Illustrates using the nightly-only Box::try_new_uninit_in to create a Box with uninitialized contents, handling allocation errors and performing deferred initialization. ```rust #![feature(allocator_api)] use std::alloc::System; let mut five = Box::::try_new_uninit_in(System)?; // Deferred initialization: five.write(5); let five = unsafe { five.assume_init() }; assert_eq!(*five, 5); ``` -------------------------------- ### connect_with Source: https://docs.rs/sqlx/latest/sqlx/mysql/type.MySqlPool.html Creates a new connection pool with default configuration and provided `ConnectOptions`, establishing one connection immediately. Default configuration is for testing; production use may need adjustments. ```APIDOC ## connect_with ### Description Creates a new connection pool with a default pool configuration and the given `ConnectOptions`, and immediately establish one connection. ### Method `async fn connect_with(options: <::Connection as Connection>::Options) -> Result, Error>` ### Parameters #### Path Parameters - **options** (ConnectOptions) - Required - The connection options for the MySQL database. ### Response #### Success Response - **Pool** - A new connection pool. - **Error** - If connection fails. ``` -------------------------------- ### Box from_non_null Example (Nightly) Source: https://docs.rs/sqlx/latest/sqlx/_config/macros/type.RustType.html Illustrates recreating a `Box` from a `NonNull` pointer, similar to `from_raw` but using `NonNull`. This example requires the `box_vec_non_null` feature and is currently nightly-only. ```Rust #![feature(box_vec_non_null)] let x = Box::new(5); let non_null = Box::into_non_null(x); let x = unsafe { Box::from_non_null(non_null) }; ``` ```Rust #![feature(box_vec_non_null)] use std::alloc::{alloc, Layout}; use std::ptr::NonNull; unsafe { let non_null = NonNull::new(alloc(Layout::new::()).cast::()) .expect("allocation failed"); // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `non_null`. non_null.write(5); let x = Box::from_non_null(non_null); } ``` -------------------------------- ### Connect with Options Source: https://docs.rs/sqlx/latest/sqlx/struct.AnyConnection.html Establishes a new database connection using provided options, allowing for more configuration than a simple URL. ```rust pub async fn connect_with(options: &Self::Options) -> Result ``` -------------------------------- ### Accessing JSON values with get() Source: https://docs.rs/sqlx/latest/sqlx/types/enum.JsonValue.html Shows how to access elements within a JSON object or array using the `get` method. It returns `None` if the key or index is not found or if the type does not match. ```rust let object = json!({ "A": 65, "B": 66, "C": 67 }); assert_eq!(*object.get("A").unwrap(), json!(65)); let array = json!([ "A", "B", "C" ]); assert_eq!(*array.get(2).unwrap(), json!("C")); assert_eq!(array.get("A"), None); ``` -------------------------------- ### Get a future that resolves when the pool is closed Source: https://docs.rs/sqlx/latest/sqlx/mysql/type.MySqlPool.html Get a future that resolves when `Pool::close()` is called. If the pool is already closed, the future resolves immediately. This can be used to cancel long-running operations. ```rust use sqlx::PgPool; async fn on_pool_close(pool: PgPool) { let pool2 = pool.clone(); tokio::spawn(async move { pool2.close_event().await; println!("Pool is closing!"); }); pool.close().await; } ``` -------------------------------- ### Connect to Database using Options Source: https://docs.rs/sqlx/latest/sqlx/trait.Connection.html Establishes a new database connection using pre-configured connection options. This method is useful when you need more control over connection parameters than a simple URL provides. ```rust let options = PgConnectOptions::new().username("user").password("password"); let conn = PgConnection::connect_with(&options).await? ``` -------------------------------- ### Attempt to Start a Transaction Source: https://docs.rs/sqlx/latest/sqlx/type.AnyPool.html Attempts to start a new transaction. Returns `Ok(None)` if the pool is closed, otherwise returns `Ok(Some(Transaction))`. This is safer for scenarios where the pool might be shut down. ```rust let tx = pool.try_begin().await?; ``` -------------------------------- ### begin Source: https://docs.rs/sqlx/latest/sqlx/type.PgPool.html Retrieves a connection from the pool and immediately starts a new transaction. ```APIDOC ## pub async fn begin(&self) -> Result, Error> ### Description Retrieves a connection and immediately begins a new transaction. ``` -------------------------------- ### Getting Current Local Time and Date Source: https://docs.rs/sqlx/latest/sqlx/types/chrono/struct.Local.html Demonstrates how to get the current local date and time using Local::now(). It also shows conversions to DateTime and with a specific timezone offset. ```rust // Current local time let now = Local::now(); // Current local date let today = now.date_naive(); // Current local time, converted to `DateTime` let now_fixed_offset = Local::now().fixed_offset(); // or let now_fixed_offset: DateTime = Local::now().into(); // Current time in some timezone (let's use +05:00) // Note that it is usually more efficient to use `Utc::now` for this use case. let offset = FixedOffset::east_opt(5 * 60 * 60).unwrap(); let now_with_offset = Local::now().with_timezone(&offset); ``` -------------------------------- ### Getting a mutable reference to the value Source: https://docs.rs/sqlx/latest/sqlx/error/type.Result.html Shows how to use `as_mut()` to get a `Result<&mut T, &mut E>` from a `&mut Result`. This enables in-place modification of the contained `Ok` or `Err` values. ```Rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### begin Source: https://docs.rs/sqlx/latest/sqlx/mysql/type.MySqlPool.html Retrieves a connection from the pool and immediately starts a new transaction. ```APIDOC ## begin ### Description Retrieves a connection and immediately begins a new transaction. ### Method `async fn begin(&self) -> Result, Error>` ### Response #### Success Response - **Transaction<'static, DB>** - A new transaction. - **Error** - If connection or transaction start fails. ``` -------------------------------- ### strip_circumfix Source: https://docs.rs/sqlx/latest/sqlx/postgres/struct.PgArgumentBuffer.html Returns a subslice with the prefix and suffix removed. If the slice starts with `prefix` and ends with `suffix`, returns the subslice after the prefix and before the suffix, wrapped in `Some`. If the slice does not start with `prefix` or does not end with `suffix`, returns `None`. ```APIDOC ## pub fn strip_circumfix(&self, prefix: &P, suffix: &S) -> Option<&[T]> ### Description Returns a subslice with the prefix and suffix removed. ### Parameters - `prefix`: The pattern to remove from the beginning of the slice. - `suffix`: The pattern to remove from the end of the slice. ### Returns - `Some(&[T])`: If the slice starts with `prefix` and ends with `suffix`, returns the subslice between them. - `None`: If the slice does not start with `prefix` or does not end with `suffix`. ### Note This is a nightly-only experimental API. ### Examples ```rust #![feature(strip_circumfix)] let v = &[10, 50, 40, 30]; assert_eq!(v.strip_circumfix(&[10], &[30]), Some(&[50, 40][..])); assert_eq!(v.strip_circumfix(&[10], &[40, 30]), Some(&[50][..])); assert_eq!(v.strip_circumfix(&[10, 50], &[40, 30]), Some(&[][..])); assert_eq!(v.strip_circumfix(&[50], &[30]), None); assert_eq!(v.strip_circumfix(&[10], &[40]), None); assert_eq!(v.strip_circumfix(&[], &[40, 30]), Some(&[10, 50][..])); assert_eq!(v.strip_circumfix(&[10, 50], &[]), Some(&[40, 30][..])); ``` ``` -------------------------------- ### sqlx.toml: Create Schemas Example Source: https://docs.rs/sqlx/latest/sqlx/_config/migrate/struct.Config.html Specifies schema names to be created if they do not exist before checking for the migrations table. ```toml [migrate] create-schemas = ["foo"] ``` -------------------------------- ### strip_circumfix Source: https://docs.rs/sqlx/latest/sqlx/postgres/types/struct.PgLQuery.html Returns a subslice with the prefix and suffix removed. If the slice starts with `prefix` and ends with `suffix`, returns the subslice after the prefix and before the suffix, wrapped in `Some`. If the slice does not start with `prefix` or does not end with `suffix`, returns `None`. ```APIDOC ## strip_circumfix ### Description Returns a subslice with the prefix and suffix removed. If the slice starts with `prefix` and ends with `suffix`, returns the subslice after the prefix and before the suffix, wrapped in `Some`. If the slice does not start with `prefix` or does not end with `suffix`, returns `None`. ### Method `strip_circumfix(&self, prefix: &P, suffix: &S) -> Option<&[T]>` where T: PartialEq, S: SlicePattern + ?Sized, P: SlicePattern + ?Sized ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None provided in source. ### Response #### Success Response `Option<&[T]>`: Returns a subslice with both prefix and suffix removed if the slice matches the pattern, otherwise `None`. #### Response Example None provided in source. ``` -------------------------------- ### SQLx TOML Configuration for Multi-Database Projects Source: https://docs.rs/sqlx/latest/sqlx/_config/common/struct.Config.html Demonstrates how to configure different database URLs for separate crates within a workspace using sqlx.toml files. ```toml [common] database-url-var = "FOO_DATABASE_URL" ``` ```toml [common] database-url-var = "BAR_DATABASE_URL" ``` -------------------------------- ### connect_with Source: https://docs.rs/sqlx/latest/sqlx/sqlite/type.SqlitePoolOptions.html Create a new pool from this `PoolOptions` and immediately open at least one connection using provided connection options. ```APIDOC ## pub async fn connect_with( self, options: <::Connection as Connection>::Options, ) -> Result, Error> ### Description Create a new pool from this `PoolOptions` and immediately open at least one connection. This ensures the configuration is correct. The total number of connections opened is `max(1, min_connections)`. ### Parameters #### Path Parameters - **options** (`<::Connection as Connection>::Options`) - The database connection options. ### Returns - `Result, Error>` - A `Pool` instance if successful, or an `Error` if connection fails. ``` -------------------------------- ### Sum of Results Example Source: https://docs.rs/sqlx/latest/sqlx/error/type.Result.html Illustrates summing elements from an iterator where each element is a Result. The summation proceeds until an Err is encountered, which is then returned. If all elements are Ok, their sum is returned. This example specifically rejects negative numbers. ```rust let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### connect_with Source: https://docs.rs/sqlx/latest/sqlx/type.PgPool.html Creates a new connection pool with default configuration and provided `ConnectOptions`, establishing one connection immediately. Production applications may benefit from tuning with `PoolOptions`. ```APIDOC ## pub async fn connect_with( options: <::Connection as Connection>::Options, ) -> Result, Error> ### Description Create a new connection pool with a default pool configuration and the given `ConnectOptions`, and immediately establish one connection. The default configuration is mainly suited for testing and light-duty applications. For production applications, you’ll likely want to make at least few tweaks. See `PoolOptions::new()` for details. ``` -------------------------------- ### offset Source: https://docs.rs/sqlx/latest/sqlx/types/time/struct.OffsetDateTime.html Get the `UtcOffset` of the `OffsetDateTime`. ```APIDOC ## offset ### Description Get the `UtcOffset` of the `OffsetDateTime`. ### Method `offset()` ### Parameters None ### Returns `UtcOffset` - The UTC offset of the datetime. ``` -------------------------------- ### type_id Source: https://docs.rs/sqlx/latest/sqlx/struct.PgConnection.html Gets the `TypeId` of `self`. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Returns The `TypeId` of the instance. ``` -------------------------------- ### connect_with Source: https://docs.rs/sqlx/latest/sqlx/mysql/type.MySqlPoolOptions.html Create a new pool from this `PoolOptions` and immediately open at least one connection. This ensures the configuration is correct. The total number of connections opened is `max(1, min_connections)`. ```APIDOC ## pub async fn connect_with( self, options: <::Connection as Connection>::Options, ) -> Result, Error> ### Description Create a new pool from this `PoolOptions` and immediately open at least one connection. This ensures the configuration is correct. The total number of connections opened is `max(1, min_connections)`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ``` -------------------------------- ### Install Drivers for AnyConnection Source: https://docs.rs/sqlx/latest/sqlx/any/fn.install_drivers.html Registers drivers for `AnyConnection` to use. This function must be called before connecting to a database. It returns an error if called more than once. ```rust pub fn install_drivers( drivers: &'static [AnyDriver], ) -> Result<(), Box> ``` -------------------------------- ### Partial Sort Unstable By Key Example Source: https://docs.rs/sqlx/latest/sqlx/postgres/struct.PgArgumentBuffer.html Illustrates `partial_sort_unstable_by_key` for sorting slices based on a key extracted by a closure. Examples cover empty, single-element, and full ranges, demonstrating partitioning and sorting by absolute value. ```rust #![feature(slice_partial_sort_unstable)] let mut v = [4i32, -5, 1, -3, 2]; // empty range at the beginning, nothing changed v.partial_sort_unstable_by_key(0..0, |k| k.abs()); assert_eq!(v, [4, -5, 1, -3, 2]); // empty range in the middle, partitioning the slice v.partial_sort_unstable_by_key(2..2, |k| k.abs()); for i in 0..2 { assert!(v[i].abs() <= v[2].abs()); } for i in 3..v.len() { assert!(v[2].abs() <= v[i].abs()); } // single element range, same as select_nth_unstable v.partial_sort_unstable_by_key(2..3, |k| k.abs()); for i in 0..2 { assert!(v[i].abs() <= v[2].abs()); } for i in 3..v.len() { assert!(v[2].abs() <= v[i].abs()); } // partial sort a subrange v.partial_sort_unstable_by_key(1..4, |k| k.abs()); assert_eq!(&v[1..4], [2, -3, 4]); // partial sort the whole range, same as sort_unstable v.partial_sort_unstable_by_key(.., |k| k.abs()); assert_eq!(v, [1, 2, -3, 4, -5]); ``` -------------------------------- ### install_drivers Source: https://docs.rs/sqlx/latest/sqlx/any/fn.install_drivers.html Installs the provided list of drivers for `AnyConnection` to use. This function must be called before any `AnyConnection` or `AnyPool` can be connected. It returns an error if called more than once. ```APIDOC ## install_drivers ### Description Installs the list of drivers for `AnyConnection` to use. This function must be called before an `AnyConnection` or `AnyPool` can be connected. ### Method `fn install_drivers` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **drivers** (`&'static [AnyDriver]`) - Required - A static slice of `AnyDriver` to install. ### Response #### Success Response - `Ok(())` - Indicates that the drivers were successfully installed. #### Errors - `Err(Box)` - Returned if `install_drivers` is called more than once. ``` -------------------------------- ### Getting Ipv6Net Broadcast Address Source: https://docs.rs/sqlx/latest/sqlx/types/ipnet/struct.Ipv6Net.html Shows how to get the broadcast address (last address in the range) for an Ipv6Net. Note that IPv6 does not have a formal broadcast address, but this provides the last address for consistency. Requires the `ipnet` feature flag. ```rust let net: Ipv6Net = "fd00:1234:5678::/24".parse().unwrap(); assert_eq!(Ok(net.broadcast()), "fd00:12ff:ffff:ffff:ffff:ffff:ffff:ffff".parse()); ``` -------------------------------- ### connect_with Source: https://docs.rs/sqlx/latest/sqlx/trait.Connection.html Establishes a new database connection using a pre-configured set of connection options. ```APIDOC ## fn connect_with( options: &Self::Options, ) -> impl Future> + Send ### Description Establish a new database connection with the provided options. ### Parameters #### Path Parameters - **options** (`&Self::Options`) - The connection options to use for establishing the connection. ### Returns - `impl Future> + Send` - A future that resolves to a new database connection or an error. ``` -------------------------------- ### try_begin_with Source: https://docs.rs/sqlx/latest/sqlx/struct.Pool.html Attempts to retrieve a connection and start a new transaction with a custom SQL statement. Returns `None` if a connection cannot be acquired. ```APIDOC ## try_begin_with ### Description Attempts to retrieve a connection and, if successful, immediately begins a new transaction using the provided statement. Returns `None` if a connection could not be acquired. ### Method `try_begin_with` ### Parameters * `statement` (impl SqlSafeStr) - The SQL statement to use for beginning the transaction. ### Returns `Result>, Error>` - A `Result` containing an optional transaction or an error. ``` -------------------------------- ### SQL Injection Vulnerability Example Source: https://docs.rs/sqlx/latest/sqlx/fn.query.html This example demonstrates a dangerous pattern of directly formatting user input into SQL queries, leading to a SQL injection vulnerability. Do not use this approach unless you are absolutely certain of the security implications. ```rust let user_input = "possibly untrustworthy input!"; // DO NOT DO THIS unless you're ABSOLUTELY CERTAIN it's what you need! let query = format!("SELECT * FROM articles WHERE content LIKE '%{user_input}%'"); // where `conn` is `PgConnection` or `MySqlConnection` // or some other type that implements `Executor`. let results = sqlx::query(sqlx::AssertSqlSafe(query)).fetch_all(&mut conn).await?; ``` -------------------------------- ### to_julian_day Source: https://docs.rs/sqlx/latest/sqlx/types/time/struct.Date.html Get the Julian day for the date. ```APIDOC ## to_julian_day ### Description Get the Julian day for the date. ### Method `const fn to_julian_day(self) -> i32` ### Examples ```rust assert_eq!(date!(-4713-11-24).to_julian_day(), 0); assert_eq!(date!(2000-01-01).to_julian_day(), 2_451_545); assert_eq!(date!(2019-01-01).to_julian_day(), 2_458_485); assert_eq!(date!(2019-12-31).to_julian_day(), 2_458_849); ``` ``` -------------------------------- ### connect_with Source: https://docs.rs/sqlx/latest/sqlx/prelude/trait.Connection.html Establishes a new database connection using provided connection options. ```APIDOC ## fn connect_with(options: &Self::Options) -> impl Future> + Send where Self: Sized, ### Description Establish a new database connection with the provided options. ### Parameters * `options`: A reference to the connection options for the database. ### Returns A `Future` that resolves to a `Result` containing the new connection or an `Error`. ``` -------------------------------- ### get_username Source: https://docs.rs/sqlx/latest/sqlx/postgres/struct.PgConnectOptions.html Get the username for the PostgreSQL connection. ```APIDOC ## get_username ### Description Get the username for the PostgreSQL connection. ### Method `get_username` ### Parameters None ### Request Example ```rust let options = PgConnectOptions::new() .username("foo"); assert_eq!(options.get_username(), "foo"); ``` ### Response #### Success Response (200) - **username** (str) - The username. ``` -------------------------------- ### install_default_drivers Source: https://docs.rs/sqlx/latest/sqlx/any/index.html Installs all currently compiled-in drivers for `AnyConnection` to use. This is a convenience function to easily enable all supported database backends. ```APIDOC ## Function install_default_drivers ### Description Install all currently compiled-in drivers for `AnyConnection` to use. ### Synopsis ```rust fn install_default_drivers() ``` ### Usage This function should be called once at the beginning of your application to ensure that `AnyConnection` and `AnyPool` can connect to any of the supported databases. ``` -------------------------------- ### Connect to Database with Options Source: https://docs.rs/sqlx/latest/sqlx/prelude/trait.Connection.html Establishes a new database connection using a pre-configured set of connection options. This provides more explicit control over connection parameters compared to using a URL string. ```rust let options = PgConnectOptions::new().username("user").password("password").host("host").port(5432).database("database"); let conn = PgConnection::connect_with(&options).await.unwrap(); ``` -------------------------------- ### Builder::as_uuid Source: https://docs.rs/sqlx/latest/sqlx/types/uuid/struct.Builder.html Get a reference to the underlying Uuid. ```APIDOC ## Builder::as_uuid ### Description Get a reference to the underlying `Uuid`. ### Method `pub const fn as_uuid(&self) -> &Uuid` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Response #### Success Response - **&Uuid** - A reference to the underlying `Uuid`. ### Example ```rust let builder = Builder::nil(); let uuid1 = builder.as_uuid(); let uuid2 = builder.as_uuid(); assert_eq!(uuid1, uuid2); ``` ``` -------------------------------- ### Install Default Drivers Source: https://docs.rs/sqlx/latest/sqlx/any/fn.install_default_drivers.html Call this function to enable `AnyConnection` to connect to any supported database without explicitly registering drivers. ```rust sqlx::any::install_default_drivers(); ``` -------------------------------- ### to_calendar_date Source: https://docs.rs/sqlx/latest/sqlx/types/time/struct.OffsetDateTime.html Get the year, month, and day of the `OffsetDateTime`. ```APIDOC ## to_calendar_date ### Description Get the year, month, and day of the `OffsetDateTime`. ### Method `to_calendar_date()` ### Parameters None ### Returns `(i32, Month, u8)` - A tuple containing the year, month, and day. ``` -------------------------------- ### install_drivers Source: https://docs.rs/sqlx/latest/sqlx/any/index.html Installs a specific list of drivers for `AnyConnection` to use. This allows for more control over which database backends are enabled at runtime. ```APIDOC ## Function install_drivers ### Description Install the list of drivers for `AnyConnection` to use. ### Synopsis ```rust fn install_drivers(drivers: &[&'static str]) ``` ### Parameters #### Path Parameters - **drivers** (array of string slices) - Required - A slice of static string slices, where each string is the name of a driver to install (e.g., `"postgres"`, `"mysql"`). ### Usage Call this function with a list of driver names to enable only those specific database backends for use with `AnyConnection` and `AnyPool`. ``` -------------------------------- ### as_hms Source: https://docs.rs/sqlx/latest/sqlx/types/time/struct.PrimitiveDateTime.html Get the clock hour, minute, and second. ```APIDOC ## as_hms ### Description Get the clock hour, minute, and second. ### Method PrimitiveDateTime::as_hms ### Returns - `(u8, u8, u8)`: A tuple containing the hour, minute, and second. ```