### Uuid Structure and Basic Usage Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/struct This section details the Uuid struct, its availability with the 'with-uuid' feature, and provides examples for parsing and creating UUIDs. ```APIDOC ## Uuid Struct ### Description A Universally Unique Identifier (UUID). Available on **crate feature `with-uuid`** only. ### Examples **Parse a UUID:** ```rust let my_uuid = Uuid::parse_str("a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8")?; println!("{}", my_uuid.urn()); ``` **Create a new random (V4) UUID:** ```rust // Note that this requires the `v4` feature enabled in the uuid crate. let my_uuid = Uuid::new_v4(); println!("{}", my_uuid); ``` ``` -------------------------------- ### Uuid Formatting Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/struct Explains the different ways a UUID can be formatted, including simple, hyphenated, URN, and braced formats, with examples for default and custom formatting. ```APIDOC ## Uuid Formatting ### Description A UUID can be formatted in one of a few ways: * `simple`: `a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8`. * `hyphenated`: `a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8`. * `urn`: `urn:uuid:A1A2A3A4-B1B2-C1C2-D1D2-D3D4D5D6D7D8`. * `braced`: `{a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8}`. The default representation when formatting a UUID with `Display` is hyphenated. ### Examples **Default (hyphenated) formatting:** ```rust let my_uuid = Uuid::parse_str("a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8")?; assert_eq!( "a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8", my_uuid.to_string(), ); ``` **Custom formatting (URN):** ```rust let my_uuid = Uuid::parse_str("a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8")?; assert_eq!( "urn:uuid:a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8", my_uuid.urn().to_string(), ); ``` ``` -------------------------------- ### sea-orm find_by_statement Example Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/trait Demonstrates how to use the find_by_statement method from the TryGetableMany trait to fetch aggregated data from a database. This example retrieves the name and count of cakes, aliasing the count as 'num_of_cakes'. ```rust use sea_orm::{DeriveIden, EnumIter, TryGetableMany, entity::*, query::*, tests_cfg::cake}; #[derive(EnumIter, DeriveIden)] enum ResultCol { Name, NumOfCakes, } let res: Vec<(String, i32)> = <(String, i32)>::find_by_statement::(Statement::from_sql_and_values( DbBackend::Postgres, r#"SELECT "cake"."name", count("cake"."id") AS "num_of_cakes" FROM "cake""#, [], )) .all(&db) .await?; assert_eq!( res, [ ("Chocolate Forest".to_owned(), 1), ("New York Cheese".to_owned(), 1), ] ); assert_eq!( db.into_transaction_log(), [ Transaction::from_sql_and_values( DbBackend::Postgres, r#"SELECT "cake"."name", count("cake"."id") AS "num_of_cakes" FROM "cake""#, [] ), ] ); ``` -------------------------------- ### Create Max UUID (Rust) Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/struct Demonstrates creating the 'max' UUID, which has all 128 bits set to one. The example formats it using the hyphenated representation. ```rust let uuid = Uuid::max(); assert_eq!( "ffffffff-ffff-ffff-ffff-ffffffffffff", uuid.hyphenated().to_string(), ); ``` -------------------------------- ### SeaORM RelationDef Reverse Relation Example Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/type Demonstrates how to reverse a relation using the `rev()` method on `RelationDef`. This is useful for building queries where the direction of the relationship needs to be swapped. ```rust use sea_orm::{ DbBackend, entity::*, query::*, tests_cfg::{cake, cake_filling}, }; use sea_query::Alias; let cf = "cf"; assert_eq!( cake::Entity::find() .join_as( JoinType::LeftJoin, cake_filling::Relation::Cake.def().rev(), cf.clone() ) .join( JoinType::LeftJoin, cake_filling::Relation::Filling.def().from_alias(cf) ) .build(DbBackend::MySql) .to_string(), [ "SELECT `cake`.`id`, `cake`.`name` FROM `cake`", "LEFT JOIN `cake_filling` AS `cf` ON `cake`.`id` = `cf`.`cake_id`", "LEFT JOIN `filling` ON `cf`.`filling_id` = `filling`.`id`", ] .join(" ") ); ``` -------------------------------- ### Uuid Conversion From Other Types Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/struct Demonstrates how to create a Uuid from various other types, including `Braced`, `Hyphenated`, `NonNilUuid`, `Simple`, and `Urn` formats. An example shows converting from `NonNilUuid` back to `Uuid`. ```rust fn from(f: Braced) -> Uuid Converts to this type from the input type. ``` ```rust fn from(f: Hyphenated) -> Uuid Converts to this type from the input type. ``` ```rust fn from(non_nil: NonNilUuid) -> Uuid Converts a `NonNilUuid` back into a `Uuid`. ``` ```rust fn from(f: Simple) -> Uuid Converts to this type from the input type. ``` ```rust fn from(f: Urn) -> Uuid Converts to this type from the input type. ``` ```rust fn from(x: Uuid) -> Value Converts to this type from the input type. ``` ```rust fn from(value: Uuid) -> Vec ⓘ Converts to this type from the input type. ``` ```rust let uuid = Uuid::from_u128(0x0123456789abcdef0123456789abcdef); let non_nil = NonNilUuid::try_from(uuid).unwrap(); let uuid_again = Uuid::from(non_nil); assert_eq!(uuid, uuid_again); ``` -------------------------------- ### Rust: Iterators - Positional Searching (position, rposition) Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/entity/role/struct Demonstrates the `position` and `rposition` iterator methods for finding the index of elements. `position` finds the first matching element from the start, while `rposition` finds the first matching element from the end. Both return `Option`. ```rust struct MyIterator { data: Vec, index: usize, } impl Iterator for MyIterator { type Item = i32; fn next(&mut self) -> Option { if self.index < self.data.len() { let item = self.data[self.index]; self.index += 1; Some(item) } else { None } } } // ExactSizeIterator and DoubleEndedIterator are traits that need to be implemented // for rposition to work efficiently. For this example, we'll use a Vec directly // which implements these traits. fn main() { let data = vec![10, 20, 30, 40, 30, 50]; let position_of_30 = data.iter().position(|&x| x == 30); println!("Position of first 30: {:?}", position_of_30); let rposition_of_30 = data.iter().rposition(|&x| x == 30); println!("Position of last 30: {:?}", rposition_of_30); } ``` -------------------------------- ### Select Specific Columns in SeaORM Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/query/trait Demonstrates how to select specific columns from an entity using `select_only()` and `columns()`. This method allows precise control over which fields are retrieved, as shown in the PostgreSQL example. ```rust use sea_orm::{DbBackend, entity::*, query::*, tests_cfg::cake}; assert_eq!( cake::Entity::find() .select_only() .columns([cake::Column::Id, cake::Column::Name]) .build(DbBackend::Postgres) .to_string(), r#"SELECT "cake"."id", "cake"."name" FROM "cake""# ); ``` -------------------------------- ### Build MySQL Query with Left Join and Custom Condition Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/type Demonstrates building a MySQL query using SeaORM's query builder, including a LEFT JOIN with a custom ON condition that checks a column value greater than 10. This example utilizes the `cake` and `cake_filling` entities and their relations. ```rust use sea_orm::{entity::*, query::*, DbBackend, tests_cfg::{cake, cake_filling}}; use sea_query::{Expr, ExprTrait, IntoCondition, ConditionType}; assert_eq!( cake::Entity::find() .join( JoinType::LeftJoin, cake_filling::Relation::Cake .def() .rev() .condition_type(ConditionType::Any) .on_condition(|_left, right| { Expr::col((right, cake_filling::Column::CakeId)) .gt(10i32) .into_condition() }) ) .build(DbBackend::MySql) .to_string(), [ "SELECT `cake`.`id`, `cake`.`name` FROM `cake`", "LEFT JOIN `cake_filling` ON `cake`.`id` = `cake_filling`.`cake_id` OR `cake_filling`.`cake_id` > 10", ] .join(" ") ); ``` -------------------------------- ### Add Limit Expression in SeaORM Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/query/trait Explains how to apply a limit to a query using the `limit()` method. Similar to `offset()`, passing `None` removes the limit. Examples for MySQL demonstrate single and chained `limit()` calls. ```rust use sea_orm::{DbBackend, entity::*, query::*, tests_cfg::cake}; assert_eq!( cake::Entity::find() .limit(10) .build(DbBackend::MySql) .to_string(), "SELECT `cake`.`id`, `cake`.`name` FROM `cake` LIMIT 10" ); assert_eq!( cake::Entity::find() .limit(Some(10)) .limit(Some(20)) .build(DbBackend::MySql) .to_string(), "SELECT `cake`.`id`, `cake`.`name` FROM `cake` LIMIT 20" ); assert_eq!( cake::Entity::find() .limit(10) .limit(None) .build(DbBackend::MySql) .to_string(), "SELECT `cake`.`id`, `cake`.`name` FROM `cake`" ); ``` -------------------------------- ### Other Implementations Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/entity/user/struct Includes miscellaneous implementations for PrimaryKeyArity, Same, VZip, WithSubscriber, and ErasedDestructor. ```APIDOC ## Other Implementations ### Description This section covers various other implementations in SeaORM, including traits for primary key arity, type identity, zipped iteration, subscriber attachment, and erased destructors. ### Traits and Methods - **`PrimaryKeyArity`**: - `ARITY`: A constant usize indicating the arity of the primary key (always 1 in this context). - **`Same`**: - `Output`: An associated type that should always be `Self`. - **`VZip`**: - `vzip()`: Returns a zipped iterator of type `V`. - **`WithSubscriber`**: - `with_subscriber(subscriber)`: Attaches a `Subscriber` to the type, returning a `WithDispatch` wrapper. - `with_current_subscriber()`: Attaches the current default `Subscriber`, returning a `WithDispatch` wrapper. - **`ErasedDestructor`**: - This trait is implemented for types that are `'static`, indicating they can be safely destructed after being erased. ### Parameters - **`subscriber`**: An object that can be converted into a `Dispatch`. ### Response - **`WithDispatch`**: Returned by `with_subscriber` and `with_current_subscriber`. ``` -------------------------------- ### Rust Iterator Adaptor: Get a subsection by index Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/compound/struct The `get` adaptor returns an iterator over a subsection of the original iterator, specified by an index. It requires the index type `R` to implement `IteratorIndex` for the iterator. ```rust fn get(self, index: R) -> >::Output where Self: Sized, R: IteratorIndex ``` -------------------------------- ### Itertools - Get Sub-iterator Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/entity/user_override/struct Returns an iterator over a subsection of the original iterator based on an index type. ```APIDOC ## POST /iterators/get ### Description Returns an iterator over a subsection of the iterator. ### Method POST ### Endpoint `/iterators/get` ### Parameters #### Request Body - **iterator** (Iterator) - Required - The iterator to slice. - **index** (IteratorIndex) - Required - The index defining the subsection (e.g., a range). ### Request Example ```json { "iterator": [10, 20, 30, 40, 50], "index": {"start": 1, "end": 3} } ``` ### Response #### Success Response (200) - **result** (Iterator) - An iterator yielding elements from the specified subsection. #### Response Example ```json { "result": [20, 30] } ``` ``` -------------------------------- ### Uuid as_ref Method Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/struct Provides a method to get a shared reference to the Uuid, typically used when the input type is inferred. ```rust fn as_ref(&self) -> &Uuid Converts this type into a shared reference of the (usually inferred) input type. ``` -------------------------------- ### Load Related Entities with SeaORM's Smart Loader in Rust Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/index Demonstrates how to use SeaORM's Smart Entity Loader in Rust to fetch a 'cake' entity along with its related 'fruit' (1-1) and 'fillings' (1-N) entities, avoiding the N+1 query problem. This code requires the 'sea-orm' crate and uses features like `.with()` for eager loading and `.one()` to execute the query against a database connection. ```rust // join paths: // cake -> fruit // cake -> cake_filling -> filling // filling -> ingredient let super_cake = cake::Entity::load() .filter_by_id(42) // shorthand for .filter(cake::Column::Id.eq(42)) .with(fruit::Entity) // 1-1 uses join .with((filling::Entity, ingredient::Entity)) // 1-N uses data loader .one(db) .await? .unwrap(); // 3 queries are executed under the hood: // 1. SELECT FROM cake JOIN fruit WHERE id = $ // 2. SELECT FROM filling JOIN cake_filling WHERE cake_id IN (..) // 3. SELECT FROM ingredient WHERE filling_id IN (..) super_cake == cake::ModelEx { id: 42, name: "Black Forest".into(), fruit: HasOne::Loaded( fruit::ModelEx { name: "Cherry".into(), } .into(), ), fillings: HasMany::Loaded(vec![filling::ModelEx { name: "Chocolate".into(), ingredients: HasMany::Loaded(vec![ingredient::ModelEx { name: "Syrup".into(), }]), }]), }; ``` -------------------------------- ### Basic Select Operations in SeaORM Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/index Demonstrates fundamental 'SELECT' operations for retrieving data. Supports fetching all records, filtering by conditions, finding by ID, and querying related models (both one-to-one and one-to-many/many-to-many) using lazy and eager loading. ```rust // find all models let cakes: Vec = Cake::find().all(db).await?; // find and filter let chocolate: Vec = Cake::find() .filter(cake::Column::Name.contains("chocolate")) .all(db) .await?; // find one model let cheese: Option = Cake::find_by_id(1).one(db).await?; let cheese: cake::Model = cheese.unwrap(); // find related models (lazy) let fruit: Option = cheese.find_related(Fruit).one(db).await?; // find related models (eager): for 1-1 relations let cake_with_fruit: Vec<(cake::Model, Option)> = Cake::find().find_also_related(Fruit).all(db).await?; // find related models (eager): works for both 1-N and M-N relations let cake_with_fillings: Vec<(cake::Model, Vec)> = Cake::find() .find_with_related(Filling) // for M-N relations, two joins are performed .all(db) // rows are automatically consolidated by left entity .await?; ``` -------------------------------- ### Get Type ID of a Type (Rust) Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/entity/user_role/struct Returns the `TypeId` of the current type. This is a fundamental operation for runtime type introspection and is part of the `Any` trait. ```rust fn type_id(&self) -> TypeId { // Implementation details for getting TypeId unimplemented!() } ``` -------------------------------- ### Utility and Interoperability Implementations (Rust) Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/enum Includes implementations for `Instrument`, `IntoEither`, `Same`, `Equivalent`, and `VZip`, providing enhanced utilities for instrumentation, error handling, type identity, and parallel processing. ```rust impl Instrument for T impl IntoEither for T impl Same for T impl Equivalent for Q impl VZip for T ``` -------------------------------- ### IdenStatic Trait Implementation for Entity Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/entity/role_permission/struct Implements the IdenStatic trait for the Entity struct, providing a method to get the static string identity of the identifier. ```rust impl IdenStatic for Entity { fn as_str(&self) -> &'static str { // ... implementation details ... } } ``` -------------------------------- ### Get UUID Version Number - Rust Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/struct Returns the version number of a Uuid as a usize. This is a future-proof method for checking the UUID generation algorithm. ```rust let my_uuid = Uuid::parse_str("02f09a3f-1624-3b1d-8409-44eff7708208")?; assert_eq!(3, my_uuid.get_version_num()); ``` -------------------------------- ### Execute Raw SQL Queries in SeaORM Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/index Enables executing raw SQL queries when ORM-level abstractions are insufficient. Supports parameterized queries using macros and binds values from Rust variables. Handles different SQL dialects via the `Sqlite` macro. ```rust let item = Item { name: "Chocolate" }; // nested parameter access let ids = [2, 3, 4]; // expanded by the `..` operator let cake: Option = Cake::find() .from_raw_sql(raw_sql!( Sqlite, r#"SELECT "id", "name" FROM "cake"\n WHERE "name" LIKE {item.name}\n AND "id" in ({..ids})\n "# )) .one(db) .await?; ``` -------------------------------- ### Rust: Generic Implementations for Fallible Conversions and Zipping Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/entity/role_permission/struct This section covers generic blanket implementations in Rust for fallible conversions using `TryFrom` and `TryInto`, allowing for conversions that might fail. It also includes the `VZip` implementation for zipping lanes of data, useful in parallel processing or data structure transformations. ```rust impl TryFrom for T where U: Into, impl TryInto for T where U: TryFrom, impl VZip for T where V: MultiLane, ``` -------------------------------- ### Get Type ID of a Type (Rust) Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/entity/role_hierarchy/struct Retrieves the TypeId of a given type. This is a common operation for runtime type introspection and is part of the Any trait implementation. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### PostgreSQL Get JSON Field Expression Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/enum Expresses retrieving a JSON field as a JSON value (`->`) in PostgreSQL. It takes an expression as input. ```rust fn get_json_field(self, right: T) -> Expr where T: Into, ``` -------------------------------- ### Execute Raw SQL Queries with `raw_sql!` Macro in SeaORM Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/index Shows how to use the `raw_sql!` macro in SeaORM for executing SQL queries safely, preventing SQL injection. It demonstrates querying with nested selects, joins, and filtering using parameters like arrays, and maps the result to custom structs (`CakeWithBakery`, `Bakery`). ```Rust @derive(FromQueryResult) struct CakeWithBakery { name: String, #[sea_orm(nested)] bakery: Option, } @derive(FromQueryResult) struct Bakery { #[sea_orm(alias = "bakery_name")] name: String, } let cake_ids = [2, 3, 4]; // expanded by the `..` operator // can use many APIs with raw SQL, including nested select let cake: Option = CakeWithBakery::find_by_statement(raw_sql!( Sqlite, r#"SELECT "cake"."name", "bakery"."name" AS "bakery_name" FROM "cake" LEFT JOIN "bakery" ON "cake"."bakery_id" = "bakery"."id" WHERE "cake"."id" IN ({..cake_ids})"# )) .one(db) .await?; ``` -------------------------------- ### Uuid Implementations Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/struct Provides documentation for various implementation methods of the Uuid struct, including nil, max, from_fields, from_fields_le, and from_u128. ```APIDOC ## Implementations: `impl Uuid` ### `nil()` **Description**: The ‘nil UUID’ (all zeros). The nil UUID is a special form of UUID that is specified to have all 128 bits set to zero. **References**: Nil UUID in RFC 9562 **Example**: ```rust let uuid = Uuid::nil(); assert_eq!( "00000000-0000-0000-0000-000000000000", uuid.hyphenated().to_string(), ); ``` ### `max()` **Description**: The ‘max UUID’ (all ones). The max UUID is a special form of UUID that is specified to have all 128 bits set to one. **References**: Max UUID in RFC 9562 **Example**: ```rust let uuid = Uuid::max(); assert_eq!( "ffffffff-ffff-ffff-ffff-ffffffffffff", uuid.hyphenated().to_string(), ); ``` ### `from_fields(d1: u32, d2: u16, d3: u16, d4: &[u8; 8]) -> Uuid` **Description**: Creates a UUID from four field values (big-endian). **Example**: ```rust let d1 = 0xa1a2a3a4; let d2 = 0xb1b2; let d3 = 0xc1c2; let d4 = [0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8]; let uuid = Uuid::from_fields(d1, d2, d3, &d4); assert_eq!( "a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8", uuid.hyphenated().to_string(), ); ``` ### `from_fields_le(d1: u32, d2: u16, d3: u16, d4: &[u8; 8]) -> Uuid` **Description**: Creates a UUID from four field values in little-endian order. The bytes in the `d1`, `d2` and `d3` fields will be flipped to convert into big-endian order. **Example**: ```rust let d1 = 0xa1a2a3a4; let d2 = 0xb1b2; let d3 = 0xc1c2; let d4 = [0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8]; let uuid = Uuid::from_fields_le(d1, d2, d3, &d4); assert_eq!( "a4a3a2a1-b2b1-c2c1-d1d2-d3d4d5d6d7d8", uuid.hyphenated().to_string(), ); ``` ### `from_u128(v: u128) -> Uuid` **Description**: Creates a UUID from a 128bit value. **Example**: ```rust let v = 0xa1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8u128; let uuid = Uuid::from_u128(v); assert_eq!( "a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8", uuid.hyphenated().to_string(), ); ``` ``` -------------------------------- ### Ownership and Borrowing Implementations (Rust) Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/enum Details implementations for `CloneToUninit`, `ToOwned`, `Borrow`, and `BorrowMut`, facilitating efficient ownership management and data access. ```rust impl CloneToUninit for T impl ToOwned for T impl Borrow for T impl BorrowMut for T ``` -------------------------------- ### Get UUID Fields (Big-Endian) - Rust Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/struct Returns the four field values of a Uuid in big-endian order. These can be used to reconstruct the Uuid using from_fields. ```rust let uuid = Uuid::nil(); assert_eq!(uuid.as_fields(), (0, 0, 0, &[0u8; 8])); let uuid = Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8")?; assert_eq!( uuid.as_fields(), ( 0xa1a2a3a4, 0xb1b2, 0xc1c2, &[0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8], ) ); ``` -------------------------------- ### Rust: Implement Equivalent for Q Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/enum This blanket implementation allows comparing types `Q` with `K` if `Q` implements `Eq` and `K` can borrow as `Q`. The `equivalent` method checks if `self` is equal to `key`, facilitating flexible comparisons in collections. ```rust impl Equivalent for Q where Q: Eq + ?Sized, K: Borrow + ?Sized, { fn equivalent(&self, key: &K) -> bool { // ... implementation details ... } } ``` -------------------------------- ### Blanket Implementations Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/schema/struct Various blanket implementations available for EntitySchemaInfo. ```APIDOC ### Blanket Implementations - `impl Any for T` - `fn type_id(&self) -> TypeId` - `impl Borrow for T` - `fn borrow(&self) -> &T` - `impl BorrowMut for T` - `fn borrow_mut(&mut self) -> &mut T` - `impl From for T` - `fn from(t: T) -> T` - `impl Instrument for T` - `fn instrument(self, span: Span) -> Instrumented` - `fn in_current_span(self) -> Instrumented` - `impl Into for T where U: From` - `fn into(self) -> U` - `impl IntoEither for T` - `fn into_either(self, into_left: bool) -> Either` - `fn into_either_with(self, into_left: F) -> Either` - `impl Same for T` - `type Output = T` - `impl TryFrom for T where U: Into` - `type Error = Infallible` - `fn try_from(value: U) -> Result>::Error>` - `impl TryInto for T where U: TryFrom` - `type Error = >::Error` - `fn try_into(self) -> Result>::Error>` - `impl VZip for T where V: MultiLane` - `fn vzip(self) -> V` - `impl WithSubscriber for T` - `fn with_subscriber(self, subscriber: S) -> WithDispatch` - `fn with_current_subscriber(self) -> WithDispatch` - `impl ErasedDestructor for T where T: 'static` ``` -------------------------------- ### Accessing Json Value (Rust) Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/query/enum Provides a method to get a reference to the inner `Value` if the variant is `Json`. This allows for safe access to the JSON data. ```rust pub fn as_ref_json(&self) -> Option<&Value> ``` -------------------------------- ### Type Conversion Implementations (Rust) Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/enum Shows implementations for `From`, `TryFrom`, `Into`, and `TryInto`, enabling flexible type conversions involving AccessType. ```rust impl From for T impl TryFrom for T impl Into for T impl TryInto for T ``` -------------------------------- ### Implement RelationTrait for Relation in Rust Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/entity/resource/enum This Rust code implements the `RelationTrait` for the `Relation` enum. It includes methods `def()` to create a `RelationDef` and `name()` to get the name of the relation. ```rust impl RelationTrait for Relation { fn def(&self) -> RelationDef fn name(&self) -> String } ``` -------------------------------- ### Rust: Implement PartialEq for Value Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/enum This implementation provides methods for comparing two `Value` instances for equality. The `eq` method tests for equality using `==`, and the `ne` method tests for inequality using `!=`. These are fundamental for data comparison operations. ```rust impl PartialEq for Value { fn eq(&self, other: &Value) -> bool { // ... implementation details ... } fn ne(&self, other: &Rhs) -> bool { // ... implementation details ... } } ``` -------------------------------- ### TryIntoModel Trait Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/trait Details of the TryIntoModel trait, including its purpose, required methods, and implementors. ```APIDOC ## Trait TryIntoModel ### Description A Trait for any type that can be converted into an Model. ### Required Methods #### `fn try_into_model(self) -> Result` Method to call to perform the conversion. ### Implementors - `impl TryIntoModel for sea_orm::rbac::entity::permission::ActiveModel` (Requires `rbac` crate feature) - `impl TryIntoModel for sea_orm::rbac::entity::resource::ActiveModel` (Requires `rbac` crate feature) - `impl TryIntoModel for sea_orm::rbac::entity::role::ActiveModel` (Requires `rbac` crate feature) - `impl TryIntoModel for sea_orm::rbac::entity::role_hierarchy::ActiveModel` (Requires `rbac` crate feature) - `impl TryIntoModel for sea_orm::rbac::entity::role_permission::ActiveModel` (Requires `rbac` crate feature) - `impl TryIntoModel for sea_orm::rbac::entity::user_override::ActiveModel` (Requires `rbac` crate feature) - `impl TryIntoModel for sea_orm::rbac::entity::user_role::ActiveModel` (Requires `rbac` crate feature) - `impl TryIntoModel for M where M: ModelTrait` ``` -------------------------------- ### Get UUID Version - Rust Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/struct Returns the recognized version of a Uuid as an Option. If the version is not recognized, None is returned. Use get_version_num for unconditional version retrieval. ```rust let my_uuid = Uuid::parse_str("02f09a3f-1624-3b1d-8409-44eff7708208")?; assert_eq!(Some(Version::Md5), my_uuid.get_version()); ``` -------------------------------- ### Null and Like Expressions Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/entity/user/struct Methods for checking for null values and performing pattern matching with `LIKE` and `NOT LIKE`. ```APIDOC ## Null and Like Expressions This section details methods for null checks and pattern matching. ### `is_null(self) -> Expr` Expresses a `IS NULL` expression. ### `is_not_null(self) -> Expr` Expresses a `IS NOT NULL` expression. ### `like(self, like: L) -> Expr` Expresses a `LIKE` expression. ### `not_like(self, like: L) -> Expr` Expresses a `NOT LIKE` expression. ``` -------------------------------- ### Get UUID Variant - Rust Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/struct Retrieves the variant of a Uuid, indicating its structural interpretation. This method reads the variant byte without validating the entire UUID structure. ```rust let my_uuid = Uuid::parse_str("02f09a3f-1624-3b1d-8409-44eff7708208")?; assert_eq!(Variant::RFC4122, my_uuid.get_variant()); ``` -------------------------------- ### Delete Operations with ActiveModel and Repository Style in SeaORM Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/index Illustrates various ways to delete records using SeaORM. It covers deleting a single record using Active Record style (fetching first, then deleting), deleting a single record using repository style by specifying the ID, and deleting multiple records matching a condition using `delete_many` with a filter. ```Rust // delete one: Active Record style let orange: Option = Fruit::find_by_id(1).one(db).await?; let orange: fruit::Model = orange.unwrap(); orange.delete(db).await?; // delete one: repository style let orange = fruit::ActiveModel { id: Set(2), ..Default::default() }; fruit::Entity::delete(orange).exec(db).await?; // delete many: DELETE FROM "fruit" WHERE "fruit"."name" LIKE '%Orange%' fruit::Entity::delete_many() .filter(fruit::Column::Name.contains("Orange")) .exec(db) .await?; ``` -------------------------------- ### Get Owned Type (Rust) Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/entity/user_role/struct Defines the `Owned` associated type, which represents the type obtained after taking ownership of the current value. This is commonly used with traits like `ToOwned`. ```rust type Owned = T; // The resulting type after obtaining ownership. ``` -------------------------------- ### Type Conversion and Wrapping in SeaORM Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/struct This snippet covers various type conversion and wrapping functionalities in SeaORM. It includes generic `From` implementations, converting tuples to values, and instrumenting types with spans for performance monitoring. These are essential for managing data flow and debugging. ```rust impl From for T { fn from(t: T) -> T } impl FromValueTuple for V where V: Into + ValueType { fn from_value_tuple(i: I) -> V where I: IntoValueTuple } impl Instrument for T { fn instrument(self, span: Span) -> Instrumented fn in_current_span(self) -> Instrumented } impl Into for T where U: From { fn into(self) -> U } impl IntoEither for T { fn into_either(self, into_left: bool) -> Either fn into_either_with(self, into_left: F) -> Either where F: FnOnce(&Self) -> bool } impl IntoLikeExpr for T where T: Into { fn into_like_expr(self) -> LikeExpr } impl IntoValueTuple for T where T: Into { fn into_value_tuple(self) -> ValueTuple } ``` -------------------------------- ### Get RoleId from RbacContext Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/context/struct A synchronous function to retrieve the RoleId associated with a given role name from the RbacContext. It returns a Result containing a reference to the RoleId or a DbErr if the role is not found. ```rust pub fn get_role(&self, role: &'static str) -> Result<&RoleId, DbErr> ``` -------------------------------- ### Rust: Implement Error for SqlxSqliteError Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/error/struct Implements the standard Error trait for SqlxSqliteError. This includes methods to get the underlying source of the error, and deprecated methods for description and cause. ```rust impl Error for SqliteError { fn source(&self) -> Option<&(dyn Error + 'static)>; // Deprecated methods: // fn description(&self) -> &str; // fn cause(&self) -> Option<&dyn Error>; // fn provide<'a>(&'a self, request: &mut Request<'a>); // Nightly-only experimental API } ``` -------------------------------- ### Parse and Format UUID (Rust) Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/struct Demonstrates parsing a UUID string in simple format and then printing it as a URN. It requires the `with-uuid` feature. ```rust let my_uuid = Uuid::parse_str("a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8")?; println!("{}", my_uuid.urn()); ``` -------------------------------- ### Subscriber Management Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/enum Documentation for methods related to managing subscribers, including attaching custom and default subscribers. ```APIDOC ## POST /subscriber/with_subscriber ### Description Attaches a provided `Subscriber` to a type, returning a `WithDispatch` wrapper. This allows for custom event handling or observation. ### Method POST ### Endpoint `/subscriber/with_subscriber` ### Parameters #### Query Parameters - **None** #### Request Body - **subscriber** (object) - The subscriber implementation to attach. - **target_type** (string) - The type to attach the subscriber to. - **target_value** (any) - The value of the target type. ### Request Example ```json { "subscriber": {"on_event": "log_event"}, "target_type": "MyService", "target_value": {"name": "service1"} } ``` ### Response #### Success Response (200) - **wrapped_value** (any) - The `WithDispatch` wrapper containing the original value and the attached subscriber. #### Response Example ```json { "wrapped_value": {"name": "service1", "subscriber_attached": true} } ``` ## POST /subscriber/with_current_subscriber ### Description Attaches the current default `Subscriber` to a type, returning a `WithDispatch` wrapper. Useful for integrating with the existing tracing or logging context. ### Method POST ### Endpoint `/subscriber/with_current_subscriber` ### Parameters #### Query Parameters - **None** #### Request Body - **target_type** (string) - The type to attach the subscriber to. - **target_value** (any) - The value of the target type. ### Request Example ```json { "target_type": "MyTask", "target_value": {"id": "task123"} } ``` ### Response #### Success Response (200) - **wrapped_value** (any) - The `WithDispatch` wrapper containing the original value and the attached subscriber. #### Response Example ```json { "wrapped_value": {"id": "task123", "subscriber_attached": true} } ``` ``` -------------------------------- ### Rust: Blanket Implementations for SqlxSqliteError Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/error/struct Shows various blanket implementations for SqlxSqliteError, such as Any, Borrow, From, Instrument, Into, Same, ToString, TryFrom, and TryInto. These traits provide fundamental functionalities and conversions. ```rust // Example: Implementation of Any trait impl Any for T where T: 'static + ?Sized { fn type_id(&self) -> TypeId; } // Example: Implementation of From trait impl From for T { fn from(t: T) -> T; } // Example: Implementation of ToString trait impl ToString for T where T: Display + ?Sized { fn to_string(&self) -> String; } ``` -------------------------------- ### Get UUID Fields (Little-Endian) - Rust Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/entity/prelude/struct Returns the four field values of a Uuid with bytes converted to little-endian order. This conversion is independent of the target environment's endianness. ```rust let uuid = Uuid::nil(); assert_eq!(uuid.to_fields_le(), (0, 0, 0, &[0u8; 8])); ``` -------------------------------- ### Rust: Advanced Iterator Adaptors from Itertools Source: https://docs.rs/sea-orm/2.0.0-rc.17/sea_orm/rbac/entity/role/struct A collection of advanced iterator adaptors including interleaving, interspersing, getting subsections, zipping with longest or equal length, batching, and chunking by key. ```rust impl Itertools for T where T: Iterator + ?Sized, fn interleave( self, other: J, ) -> Interleave::IntoIter> where J: IntoIterator, Self: Sized ``` ```rust fn interleave_shortest( self, other: J, ) -> InterleaveShortest::IntoIter> where J: IntoIterator, Self: Sized ``` ```rust fn intersperse( self, element: Self::Item, ) -> IntersperseWith> where Self: Sized, Self::Item: Clone ``` ```rust fn intersperse_with(self, element: F) -> IntersperseWith where Self: Sized, F: FnMut() -> Self::Item ``` ```rust fn get(self, index: R) -> >::Output where Self: Sized, R: IteratorIndex ``` ```rust fn zip_longest( self, other: J, ) -> ZipLongest::IntoIter> where J: IntoIterator, Self: Sized ``` ```rust fn zip_eq(self, other: J) -> ZipEq::IntoIter> where J: IntoIterator, Self: Sized ``` ```rust fn batching(self, f: F) -> Batching where F: FnMut(&mut Self) -> Option, Self: Sized ``` ```rust fn chunk_by(self, key: F) -> ChunkBy where Self: Sized, F: FnMut(&Self::Item) -> K, K: PartialEq ```