### SeaORM Getting Started and Integrations Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides links for getting started with SeaORM, including joining the Discord server and exploring integration examples with various web frameworks. ```rust ## Getting Started [![Discord](https://img.shields.io/discord/873880840487206962?label=Discord)](https://discord.com/invite/uCPdDXzbdv) Join our Discord server to chat with others! + [Documentation](https://www.sea-ql.org/SeaORM) Integration examples: + [Actix Example](https://github.com/SeaQL/sea-orm/tree/master/examples/actix_example) + [Axum Example](https://github.com/SeaQL/sea-orm/tree/master/examples/axum_example) + [GraphQL Example](https://github.com/SeaQL/sea-orm/tree/master/examples/graphql_example) + [jsonrpsee Example](https://github.com/SeaQL/sea-orm/tree/master/examples/jsonrpsee_example) + [Loco Example](https://github.com/SeaQL/sea-orm/tree/master/examples/loco_example) / [Loco REST Starter](https://github.com/SeaQL/sea-orm/tree/master/examples/loco_starter) + [Poem Example](https://github.com/SeaQL/sea-orm/tree/master/examples/poem_example) + [Rocket Example](https://github.com/SeaQL/sea-orm/tree/master/examples/rocket_example) / [Rocket OpenAPI Example](https://github.com/SeaQL/sea-orm/tree/master/examples/rocket_okapi_example) + [Salvo Example](https://github.com/SeaQL/sea-orm/tree/master/examples/salvo_example) + [Tonic Example](https://github.com/SeaQL/sea-orm/tree/master/examples/tonic_example) + [Seaography Example (Bakery)](https://github.com/SeaQL/sea-orm/tree/master/examples/seaography_example) / [Seaography Example (Sakila)](https://github.com/SeaQL/seaography/tree/main/examples/sqlite) If you want a simple, clean example that fits in a single file that demonstrates the best of SeaORM, you can try: + [Quickstart](https://github.com/SeaQL/sea-orm/blob/master/examples/quickstart/src/main.rs) Let's have a quick walk through of the unique features of SeaORM. ``` -------------------------------- ### Consolidate Query Example (Star Topology) Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/executor/select/three.rs.html?search=u32+-%3E+bool Example demonstrating how to use the `consolidate` method with `find_also_related` for a star topology (fruit -> cake -> filling). ```rust # use sea_orm::{tests_cfg::*}; # async fn function(db: &DbConn) -> Result<(), DbErr> { // fruit -> cake -> filling let items: Vec<(fruit::Model, Vec<(cake::Model, Vec)>)> = fruit::Entity::find() .find_also_related(cake::Entity) .and_also_related(filling::Entity) .consolidate() .all(db) .await?; # Ok(()) # } ``` -------------------------------- ### Example Search Queries Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/rbac/entity/permission/struct.ActiveModel.html?search= Demonstrates example search queries for exploring Rust code and types. These are illustrative and can be adapted for specific search needs. ```text * std::vec * u32 -> bool * Option, (T -> U) -> Option ``` -------------------------------- ### Consolidate Query Example (Chain Topology) Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/executor/select/three.rs.html?search=u32+-%3E+bool Example demonstrating how to use the `consolidate` method with `find_also_related` for a chain topology (cake -> fruit, cake -> filling). ```rust # use sea_orm::{tests_cfg::*}; # async fn function(db: &DbConn) -> Result<(), DbErr> { // cake -> fruit // -> filling let items: Vec<(cake::Model, Vec, Vec)> = cake::Entity::find() .find_also_related(fruit::Entity) .find_also_related(filling::Entity) .consolidate() .all(db) .await?; # Ok(()) # } ``` -------------------------------- ### Example Searches for Data Structures and Type Conversions Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/rbac/entity/role_permission/struct.Model.html?search= These are example search queries demonstrating how to find specific data structures or type conversion patterns. ```rust std::vec ``` ```rust u32 -> bool ``` ```rust Option, (T -> U) -> Option ``` -------------------------------- ### Get Ordinal Day of Year (0-365) from NaiveDate Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/struct.ChronoDate.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Use the `ordinal0()` method to get the day of the year, starting from 0. The range is 0 to 365, accounting for leap years. ```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 of Year (1-366) from NaiveDate Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/struct.ChronoDate.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Use the `ordinal()` method to get the day of the year, starting from 1. The range is 1 to 366, accounting for leap years. ```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); ``` -------------------------------- ### Mock Database Setup for Pagination Tests Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/executor/paginator.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Sets up a mock database with predefined query results for testing pagination functionality. ```rust fn setup() -> (DatabaseConnection, Vec>) { let page1 = vec![ fruit::Model { id: 1, name: "Blueberry".into(), cake_id: Some(1), }, fruit::Model { id: 2, name: "Raspberry".into(), cake_id: Some(1), }, ]; let page2 = vec![fruit::Model { id: 3, name: "Strawberry".into(), cake_id: Some(2), }]; let page3 = Vec::::new(); let db = MockDatabase::new(DbBackend::Postgres) .append_query_results([page1.clone(), page2.clone(), page3.clone()]) .into_connection(); (db, vec![page1, page2, page3]) } ``` -------------------------------- ### Get Day of Month (0-30) from NaiveDate Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/struct.ChronoDate.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Use the `day0()` method to get the day of the month, starting from 0. The range is 0 to 30, with the last day varying by month. ```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); ``` -------------------------------- ### Mock Database Setup for Transaction Logging Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/entity/active_model.rs.html Sets up a mock database with predefined execution and query results for testing transaction logging. This allows verification of SQL statements without a real database connection. ```rust let db = MockDatabase::new(DbBackend::Postgres) .append_exec_results(vec![MockExecResult { last_insert_id: 1, rows_affected: 1 }, MockExecResult { last_insert_id: 1, rows_affected: 1 }]) .append_query_results(vec![vec![fruit::Model { id: 1, name: "Apple".to_owned(), cake_id: None }], vec![fruit::Model { id: 1, name: "Apple".to_owned(), cake_id: None }]]) .into_connection(); ``` -------------------------------- ### NaiveTime Default Value Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/struct.ChronoTime.html Explains how to get the default `NaiveTime` value and provides an example. ```APIDOC ## NaiveTime Default Value ### Description Provides the default value for `NaiveTime`, which is midnight (00:00:00). ### Method - `default() -> NaiveTime` ### Example ```rust use chrono::NaiveTime; let default_time = NaiveTime::default(); assert_eq!(default_time, NaiveTime::from_hms_opt(0, 0, 0).unwrap()); ``` ``` -------------------------------- ### fn begin Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/trait.ProxyDatabaseTrait.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Begin a transaction in the ProxyDatabase. This is a provided method. ```rust fn begin<'life0, 'async_trait>( &'life0 self, ) -> Pin + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait { ... } ``` -------------------------------- ### Get Month of Date Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/struct.TimeDate.html?search=u32+-%3E+bool Retrieves the month component from a Date object. Includes examples for January and December. ```rust assert_eq!(date!(2019-01-01).month(), Month::January); assert_eq!(date!(2019-12-31).month(), Month::December); ``` -------------------------------- ### Get Year of Date Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/struct.TimeDate.html?search=u32+-%3E+bool Extracts the year component from a Date object. Shows examples for different dates. ```rust assert_eq!(date!(2019-01-01).year(), 2019); assert_eq!(date!(2019-12-31).year(), 2019); assert_eq!(date!(2020-01-01).year(), 2020); ``` -------------------------------- ### Connect to PostgreSQL with Options Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/driver/sqlx_postgres.rs.html?search=std%3A%3Avec Establishes a connection to a PostgreSQL database using SeaORM's ConnectOptions, configuring SQLx logging and search path. ```rust pub async fn connect(options: ConnectOptions) -> Result { let mut sqlx_opts = options .url .parse::() .map_err(sqlx_error_to_conn_err)?; use sqlx::ConnectOptions; if !options.sqlx_logging { sqlx_opts = sqlx_opts.disable_statement_logging(); } else { sqlx_opts = sqlx_opts.log_statements(options.sqlx_logging_level); if options.sqlx_slow_statements_logging_level != LevelFilter::Off { sqlx_opts = sqlx_opts.log_slow_statements( options.sqlx_slow_statements_logging_level, options.sqlx_slow_statements_logging_threshold, ); } } if let Some(application_name) = &options.application_name { sqlx_opts = sqlx_opts.application_name(application_name); } if let Some(f) = &options.pg_opts_fn { sqlx_opts = f(sqlx_opts); } let set_search_path_sql = options.schema_search_path.as_ref().map(|schema| { let mut string = "SET search_path = ".to_owned(); if schema.starts_with('"') { write!(&mut string, "{schema}").expect("Infallible"); } else { for (i, schema) in schema.split(',').enumerate() { if i > 0 { write!(&mut string, ",").expect("Infallible"); } if schema.starts_with('"') { write!(&mut string, "{schema}").expect("Infallible"); } else { write!(&mut string, "\"{schema}\"").expect("Infallible"); } } } string }); let lazy = options.connect_lazy; let after_connect = options.after_connect.clone(); let mut pool_options = options.sqlx_pool_options(); if let Some(sql) = set_search_path_sql { pool_options = pool_options.after_connect(move |conn, _| { let sql = sql.clone(); Box::pin(async move { sqlx::Executor::execute(conn, sql.as_str()) .await .map(|_| ()) // Ignore the result of SET search_path }) }); } let pool = if lazy { pool_options.connect_lazy_with(sqlx_opts) } else { pool_options .connect_with(sqlx_opts) .await .map_err(sqlx_error_to_conn_err)? }; let conn: DatabaseConnection = DatabaseConnectionType::SqlxPostgresPoolConnection(SqlxPostgresPoolConnection { pool, metric_callback: None, // This is handled by the common trait }) .into(); if let Some(after_connect) = after_connect { after_connect(conn.as_ref()).await?; } Ok(conn) } ``` -------------------------------- ### Connect to MySQL Database with Options Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/struct.SqlxMySqlConnector.html?search= Establishes a connection to a MySQL database using provided configuration options. This method allows for detailed setup of the database connection. ```rust pub async fn connect( options: ConnectOptions, ) -> Result ``` -------------------------------- ### Get Current Page Number Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/executor/paginator.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the current page number that the paginator is set to. The page numbering starts from zero. ```rust pub fn cur_page(&self) -> u64 { self.page } ``` -------------------------------- ### Paginator Get Current Page Number Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/executor/paginator.rs.html?search=std%3A%3Avec Returns the current page number that the paginator is set to. The page index starts from zero. ```rust pub fn cur_page(&self) -> u64 { self.page } ``` -------------------------------- ### Database Connection Method Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/struct.Database.html?search= Establishes a database connection using provided options. Returns an error if the database is unavailable. ```rust pub async fn connect(opt: C) -> Result where C: Into, ``` -------------------------------- ### Get Role Hierarchy Edges Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/struct.RestrictedConnection.html?search= Retrieves a list of edges representing the role hierarchy tree, starting from a specified role ID. ```rust pub fn role_hierarchy_edges( &self, role_id: RoleId, ) -> Result ``` -------------------------------- ### Connect to PostgreSQL with Options Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/driver/sqlx_postgres.rs.html Establishes a connection to a PostgreSQL database using provided SeaORM `ConnectOptions`. It configures sqlx logging, application name, and custom PostgreSQL options. Supports lazy connection establishment. ```rust pub async fn connect(options: ConnectOptions) -> Result { let mut sqlx_opts = options .url .parse::() .map_err(sqlx_error_to_conn_err)?; use sqlx::ConnectOptions; if !options.sqlx_logging { sqlx_opts = sqlx_opts.disable_statement_logging(); } else { sqlx_opts = sqlx_opts.log_statements(options.sqlx_logging_level); if options.sqlx_slow_statements_logging_level != LevelFilter::Off { sqlx_opts = sqlx_opts.log_slow_statements( options.sqlx_slow_statements_logging_level, options.sqlx_slow_statements_logging_threshold, ); } } if let Some(application_name) = &options.application_name { sqlx_opts = sqlx_opts.application_name(application_name); } if let Some(f) = &options.pg_opts_fn { sqlx_opts = f(sqlx_opts); } let set_search_path_sql = options.schema_search_path.as_ref().map(|schema| { let mut string = "SET search_path = ".to_owned(); if schema.starts_with('"') { write!(&mut string, "{schema}").expect("Infallible"); } else { for (i, schema) in schema.split(',').enumerate() { if i > 0 { write!(&mut string, ",").expect("Infallible"); } if schema.starts_with('"') { write!(&mut string, "{schema}").expect("Infallible"); } else { write!(&mut string, "\"{schema}\"").expect("Infallible"); } } } string }); let lazy = options.connect_lazy; let after_connect = options.after_connect.clone(); let mut pool_options = options.sqlx_pool_options(); if let Some(sql) = set_search_path_sql { pool_options = pool_options.after_connect(move |conn, _| { let sql = sql.clone(); Box::pin(async move { sqlx::Executor::execute(conn, sql.as_str()) .await .map(|_| ()) }) }); } let pool = if lazy { pool_options.connect_lazy_with(sqlx_opts) } else { pool_options .connect_with(sqlx_opts) .await .map_err(sqlx_error_to_conn_err)? }; let conn: DatabaseConnection = DatabaseConnectionType::SqlxPostgresPoolConnection(SqlxPostgresPoolConnection { pool, metric_callback: None, }) .into(); conn } ``` -------------------------------- ### Get Monday-Based Week Number Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/struct.TimeDateTime.html?search= Calculates the week number where week 1 starts on a Monday. The result ranges from 0 to 53. ```rust assert_eq!(datetime!(2019-01-01 0:00).monday_based_week(), 0); assert_eq!(datetime!(2020-01-01 0:00).monday_based_week(), 0); assert_eq!(datetime!(2020-12-31 0:00).monday_based_week(), 52); assert_eq!(datetime!(2021-01-01 0:00).monday_based_week(), 0); ``` -------------------------------- ### begin_with_config Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/struct.RestrictedConnection.html?search= Initiates a new database transaction with specified isolation level and access mode using the `BEGIN` SQL command. Returns a `RestrictedTransaction` object. ```APIDOC ## fn begin_with_config ### Description Execute SQL `BEGIN` transaction with isolation level and/or access mode. Returns a Transaction that can be committed or rolled back. ### Method Not applicable (SDK method) ### Parameters - **isolation_level**: Optional `IsolationLevel` for the transaction. - **access_mode**: Optional `AccessMode` for the transaction. ### Response - **Result**: A `Result` containing a `RestrictedTransaction` object or a `DbErr` if the transaction could not be started. ``` -------------------------------- ### Get Sunday-Based Week Number Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/struct.TimeDateTime.html?search= Calculates the week number where week 1 starts on a Sunday. The result ranges from 0 to 53. ```rust assert_eq!(datetime!(2019-01-01 0:00).sunday_based_week(), 0); assert_eq!(datetime!(2020-01-01 0:00).sunday_based_week(), 0); assert_eq!(datetime!(2020-12-31 0:00).sunday_based_week(), 52); assert_eq!(datetime!(2021-01-01 0:00).sunday_based_week(), 0); ``` -------------------------------- ### Example of getting naive date component Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/value/struct.ChronoUnixTimestampMillis.html?search=std%3A%3Avec Demonstrates how to extract the naive date component from a DateTime and a DateTime and assert their equality. ```rust use chrono::prelude::*; let date: DateTime = Utc.with_ymd_and_hms(2020, 1, 1, 0, 0, 0).unwrap(); let other: DateTime = FixedOffset::east_opt(23).unwrap().with_ymd_and_hms(2020, 1, 1, 0, 0, 0).unwrap(); assert_eq!(date.date_naive(), other.date_naive()); ``` -------------------------------- ### Create New ConnectOptions Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/database/mod.rs.html Initializes new `ConnectOptions` with a given database URL. Sets default values for various connection pool settings. ```rust /// Create new [ConnectOptions] for a [Database] by passing in a URI string pub fn new(url: T) -> Self where T: Into, { Self { url: url.into(), max_connections: None, min_connections: None, connect_timeout: None, idle_timeout: None, acquire_timeout: None, max_lifetime: None, sqlx_logging: true, sqlx_logging_level: log::LevelFilter::Info, sqlx_slow_statements_logging_level: log::LevelFilter::Off, sqlx_slow_statements_logging_threshold: Duration::from_secs(1), sqlcipher_key: None, schema_search_path: None, application_name: None, test_before_acquire: true, connect_lazy: false, after_connect: None, #[cfg(feature = "sqlx-mysql")] mysql_opts_fn: None, #[cfg(feature = "sqlx-postgres")] pg_opts_fn: None, #[cfg(feature = "sqlx-sqlite")] sqlite_opts_fn: None, } } ``` -------------------------------- ### SeaORM Library Setup and Features Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/lib.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E This snippet shows the basic configuration and features enabled for the SeaORM library, including documentation generation and linting rules. ```rust #![cfg_attr(docsrs, feature(doc_cfg))] #![warn(missing_docs)] #![deny( missing_debug_implementations, clippy::missing_panics_doc, clippy::unwrap_used, clippy::print_stderr, clippy::print_stdout )] ``` -------------------------------- ### Iterate NaiveDate by weeks Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/struct.ChronoDate.html Use `iter_weeks` to get an iterator that steps by weeks through all representable dates. The example shows how to iterate and verify specific dates. ```rust let expected = [ NaiveDate::from_ymd_opt(2016, 2, 27).unwrap(), NaiveDate::from_ymd_opt(2016, 3, 5).unwrap(), NaiveDate::from_ymd_opt(2016, 3, 12).unwrap(), NaiveDate::from_ymd_opt(2016, 3, 19).unwrap(), ]; let mut count = 0; for (idx, d) in NaiveDate::from_ymd_opt(2016, 2, 27).unwrap().iter_weeks().take(4).enumerate() { assert_eq!(d, expected[idx]); count += 1; } assert_eq!(count, 4); for d in NaiveDate::from_ymd_opt(2016, 3, 19).unwrap().iter_weeks().rev().take(4) { count -= 1; assert_eq!(d, expected[count]); } ``` -------------------------------- ### Iterate NaiveDate by days Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/struct.ChronoDate.html Use `iter_days` to get an iterator that steps by days through all representable dates. The example demonstrates iterating and asserting specific dates. ```rust let expected = [ NaiveDate::from_ymd_opt(2016, 2, 27).unwrap(), NaiveDate::from_ymd_opt(2016, 2, 28).unwrap(), NaiveDate::from_ymd_opt(2016, 2, 29).unwrap(), NaiveDate::from_ymd_opt(2016, 3, 1).unwrap(), ]; let mut count = 0; for (idx, d) in NaiveDate::from_ymd_opt(2016, 2, 27).unwrap().iter_days().take(4).enumerate() { assert_eq!(d, expected[idx]); count += 1; } assert_eq!(count, 4); for d in NaiveDate::from_ymd_opt(2016, 3, 1).unwrap().iter_days().rev().take(4) { count -= 1; assert_eq!(d, expected[count]); } ``` -------------------------------- ### Example Search: std::vec Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/struct.BoolColumn.html?search= Demonstrates a search pattern for std::vec. ```rust * std::vec ``` -------------------------------- ### Get Stream Position of Arc Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/type.RcOrArc.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the current seek position from the start of an Arc. Use to track current read/write location. ```rust use std::fs::File; use std::io::{Seek, Error}; use std::sync::Arc; let mut file = Arc::new(File::open("foo.txt")?); let position = file.stream_position()?; ``` -------------------------------- ### begin_with_config Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/enum.DatabaseExecutor.html?search=std%3A%3Avec Executes a `BEGIN` transaction SQL command with specified isolation level and/or access mode. It returns a `Transaction` object for commit or rollback. ```APIDOC ## begin_with_config ### Description Execute SQL `BEGIN` transaction with isolation level and/or access mode. Returns a Transaction that can be committed or rolled back. ### Method `begin_with_config` ### Parameters - **isolation_level** (Option) - Optional - The isolation level for the transaction. - **access_mode** (Option) - Optional - The access mode for the transaction. ### Response - Returns a `Pin> + Send + 'async_trait>>` which resolves to a `DatabaseTransaction` on success or `DbErr` on failure. ``` -------------------------------- ### fn begin Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/trait.ProxyDatabaseTrait.html?search=u32+-%3E+bool Begins a transaction in the proxy database. This is a provided method in the ProxyDatabaseTrait. ```APIDOC ## fn begin ### Description Begin a transaction in the [ProxyDatabase]. ### Signature `fn begin<'life0, 'async_trait>( &'life0 self, ) -> Pin + Send + 'async_trait>>` ``` -------------------------------- ### NaiveTime Subtraction with NaiveTime Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/struct.ChronoTime.html Demonstrates subtracting one NaiveTime from another to get a TimeDelta, with examples covering various time differences and leap second scenarios. ```APIDOC ## NaiveTime Subtraction with NaiveTime ### Description Subtracts one `NaiveTime` from another, returning a `TimeDelta`. This operation does not overflow or underflow and handles leap seconds with specific assumptions. ### Method `sub` (operator `-`) ### Endpoint N/A (In-memory operation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use chrono::{NaiveTime, TimeDelta}; let from_hmsm = |h, m, s, milli| NaiveTime::from_hms_milli_opt(h, m, s, milli).unwrap(); // Basic subtraction assert_eq!(from_hmsm(3, 5, 7, 900) - from_hmsm(3, 5, 7, 900), TimeDelta::zero()); assert_eq!(from_hmsm(3, 5, 7, 900) - from_hmsm(3, 5, 7, 875), TimeDelta::try_milliseconds(25).unwrap()); assert_eq!(from_hmsm(3, 5, 7, 900) - from_hmsm(3, 5, 6, 925), TimeDelta::try_milliseconds(975).unwrap()); assert_eq!(from_hmsm(3, 5, 7, 900) - from_hmsm(3, 5, 0, 900), TimeDelta::try_seconds(7).unwrap()); assert_eq!(from_hmsm(3, 5, 7, 900) - from_hmsm(3, 0, 7, 900), TimeDelta::try_seconds(5 * 60).unwrap()); assert_eq!(from_hmsm(3, 5, 7, 900) - from_hmsm(0, 5, 7, 900), TimeDelta::try_seconds(3 * 3600).unwrap()); assert_eq!(from_hmsm(3, 5, 7, 900) - from_hmsm(4, 5, 7, 900), TimeDelta::try_seconds(-3600).unwrap()); assert_eq!(from_hmsm(3, 5, 7, 900) - from_hmsm(2, 4, 6, 800), TimeDelta::try_seconds(3600 + 60 + 1).unwrap() + TimeDelta::try_milliseconds(100).unwrap()); // Leap second handling examples assert_eq!(from_hmsm(3, 0, 59, 1_000) - from_hmsm(3, 0, 59, 0), TimeDelta::try_seconds(1).unwrap()); assert_eq!(from_hmsm(3, 0, 59, 1_500) - from_hmsm(3, 0, 59, 0), TimeDelta::try_milliseconds(1500).unwrap()); assert_eq!(from_hmsm(3, 0, 59, 1_000) - from_hmsm(3, 0, 0, 0), TimeDelta::try_seconds(60).unwrap()); assert_eq!(from_hmsm(3, 0, 0, 0) - from_hmsm(2, 59, 59, 1_000), TimeDelta::try_seconds(1).unwrap()); assert_eq!(from_hmsm(3, 0, 59, 1_000) - from_hmsm(2, 59, 59, 1_000), TimeDelta::try_seconds(61).unwrap()); ``` ### Response #### Success Response (200) - **Output** (TimeDelta) - The resulting `TimeDelta` representing the difference between the two `NaiveTime` values. ``` -------------------------------- ### Basic Search Example Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/struct.BytesColumn.html?search= Demonstrates a basic search pattern using std::vec. ```rust std::vec ``` -------------------------------- ### Rust Vec extend_from_within example (range from index) Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/rbac/type.RbacRolesAndRanks.html?search= Appends clones of elements from a specified range (starting from an index to the end) to the Vec. The range must be a valid subslice. ```rust let mut characters = vec!['a', 'b', 'c', 'd', 'e']; characters.extend_from_within(2..); assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']); ``` -------------------------------- ### Yield indices of elements satisfying a predicate Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/rbac/entity/resource/struct.ColumnIter.html Use `positions` to get an iterator that yields the indices of all elements satisfying a given predicate. Indices are counted from the start of the iterator. ```rust fn positions

(self, predicate: P) -> Positions where Self: Sized, P: FnMut(Self::Item) -> bool, ``` -------------------------------- ### fn begin Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/trait.ProxyDatabaseTrait.html?search=std%3A%3Avec Begins a transaction in the proxy database. This is a provided method in ProxyDatabaseTrait. ```APIDOC ## fn begin ### Description Begin a transaction in the [ProxyDatabase]. ### Signature ```rust fn begin<'life0, 'async_trait>( &'life0 self, ) -> Pin + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait, ``` ``` -------------------------------- ### Get Dummy Value of Same Type Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/enum.Value.html?search=std%3A%3Avec Returns a default or 'dummy' value of the same type as the current Value variant. For example, Value::Int(None) becomes Value::Int(Some(0)). ```rust pub fn dummy_value(&self) -> Value ``` -------------------------------- ### begin Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/driver/sqlx_mysql.rs.html?search= Starts a new database transaction with optional isolation level and access mode. ```APIDOC ## begin ### Description Bundles a set of SQL statements that execute together as a transaction. Allows specifying isolation level and access mode. ### Method `async fn begin(&self, isolation_level: Option, access_mode: Option) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust // Example usage (assuming `db` is an instance of the driver) let transaction = db.begin(Some(IsolationLevel::ReadCommitted), None).await?; // Execute statements within the transaction ``` ### Response #### Success Response - `Ok(DatabaseTransaction)`: A new transaction object. #### Response Example ```rust // The DatabaseTransaction object is used to manage the transaction. // Example: // let transaction = db.begin(...).await?; // transaction.execute(...).await?; // transaction.commit().await?; ``` ``` -------------------------------- ### Get Column Definition for Table Alteration Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/schema/entity.rs.html?search=u32+-%3E+bool Generates a ColumnDef for a specific column of an entity, primarily used when altering tables. This example demonstrates adding a 'title' column to a 'posts' table in MySQL. ```rust pub fn get_column_def(&self, column: E::Column) -> ColumnDef where E: EntityTrait, { column_def_from_entity_column::(column, self.backend) } ``` ```rust use sea_orm::sea_query::TableAlterStatement; use sea_orm::{DbBackend, Schema, Statement}; mod post { use sea_orm::entity::prelude::*; #[sea_orm::model] #[derive(Clone, Debug, PartialEq, DeriveEntityModel)] #[sea_orm(table_name = "posts")] pub struct Model { #[sea_orm(primary_key)] pub id: u32, pub title: String, } impl ActiveModelBehavior for ActiveModel {} } let schema = Schema::new(DbBackend::MySql); let alter_table: Statement = DbBackend::MySql.build( TableAlterStatement::new() .table(post::Entity) .add_column(&mut schema.get_column_def::(post::Column::Title)), ); assert_eq!( alter_table.to_string(), "ALTER TABLE `posts` ADD COLUMN `title` varchar(255) NOT NULL" ); ``` -------------------------------- ### Execute SQL BEGIN transaction with configuration Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/enum.DatabaseExecutor.html Initiates a transaction with specified isolation levels and access modes. ```rust fn begin_with_config<'life0, 'async_trait>( &'life0 self, isolation_level: Option, access_mode: Option, ) -> Pin> + Send + 'async_trait>> where Self: 'async_trait, 'life0: 'async_trait, ``` -------------------------------- ### SeaORM Smart Entity Loader Example Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/index.html Demonstrates loading a user with their profile (1-1) and posts with tags (1-N) using SeaORM's smart entity loader, which employs joins and data loaders to prevent N+1 queries. ```rust // join paths: // user -> profile // user -> post // post -> post_tag -> tag let smart_user = user::Entity::load() .filter_by_id(42) // shorthand for .filter(user::COLUMN.id.eq(42)) .with(profile::Entity) // 1-1 uses join .with((post::Entity, tag::Entity)) // 1-N uses data loader .one(db) .await? .unwrap(); // 3 queries are executed under the hood: // 1. SELECT FROM user JOIN profile WHERE id = $ // 2. SELECT FROM post WHERE user_id IN (..) // 3. SELECT FROM tag JOIN post_tag WHERE post_id IN (..) smart_user == user::ModelEx { id: 42, name: "Bob".into(), email: "bob@sea-ql.org".into(), profile: HasOne::Loaded( profile::ModelEx { picture: "image.jpg".into(), } .into(), ), posts: HasMany::Loaded(vec![post::ModelEx { title: "Nice weather".into(), tags: HasMany::Loaded(vec![tag::ModelEx { tag: "sunny".into(), }]), }]), }; ``` -------------------------------- ### Arc::into_inner Guarantee Example Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/type.RcOrArc.html Illustrates the guarantee provided by `Arc::into_inner` where exactly one of the threads will successfully retrieve the inner value when multiple threads call it on clones of the same Arc. This contrasts with `Arc::try_unwrap(x).ok()` which could lead to both threads failing to get the value. ```Rust use std::sync::Arc; let x = Arc::new(3); let y = Arc::clone(&x); // Two threads calling `Arc::into_inner` on both clones of an `Arc`: let x_thread = std::thread::spawn(|| Arc::into_inner(x)); let y_thread = std::thread::spawn(|| Arc::into_inner(y)); let x_inner_value = x_thread.join().unwrap(); let y_inner_value = y_thread.join().unwrap(); // One of the threads is guaranteed to receive the inner value: assert!(matches!( (x_inner_value, y_inner_value), (None, Some(3)) | (Some(3), None) )); // The result could also be `(None, None)` if the threads called // `Arc::try_unwrap(x).ok()` and `Arc::try_unwrap(y).ok()` instead. ``` -------------------------------- ### Cursor Search Examples Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/struct.Cursor.html?search= Examples demonstrating how to search using the Cursor. ```APIDOC ## Cursor Search ### Description Provides examples of how to perform searches using the Cursor. ### Example Searches - `std::vec` - `u32 -> bool` - `Option, (T -> U) -> Option` ``` -------------------------------- ### fn begin Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/trait.ProxyDatabaseTrait.html?search= Begins a transaction in the ProxyDatabase. This is a provided method in the ProxyDatabaseTrait. ```APIDOC ## fn begin ### Description Begin a transaction in the [ProxyDatabase]. ### Method `begin` (async method) ### Return Value * `Pin + Send + 'async_trait>>` - A future that completes when the transaction begins. ``` -------------------------------- ### Getting Null or Dummy Value Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/query/enum.Value.html?search=std%3A%3Avec Use `as_null` to get a null variant of the Value's type. Use `dummy_value` to get a default value for the Value's type. ```rust pub fn as_null(&self) -> Value Get the null variant of self ``` use sea_query::Value; let v = Value::Int(Some(2)); let n = v.as_null(); assert_eq!(n, Value::Int(None)); // one liner: assert_eq!(Into::::into(2.2).as_null(), Value::Double(None)); ``` Source ``` ```rust pub fn dummy_value(&self) -> Value Get a default value of self’s type ``` use sea_query::Value; let v = Value::Int(None); let n = v.dummy_value(); assert_eq!(n, Value::Int(Some(0))); ``` Source ``` -------------------------------- ### Connect to Database with Options Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/database/mod.rs.html?search=std%3A%3Avec Connects to a database using provided options, selecting the appropriate driver based on the URL prefix. Supports MySql, Postgres, Sqlite, and Mock databases. ```rust pub async fn connect(opt: ConnectOptions) -> Result { let mut opt = opt; if opt.connect_lazy { opt.test_before_acquire = false; } #[cfg(feature = "sqlx-mysql")] if DbBackend::MySql.is_prefix_of(&opt.url) { return crate::SqlxMySqlConnector::connect(opt).await; } #[cfg(feature = "sqlx-postgres")] if DbBackend::Postgres.is_prefix_of(&opt.url) { return crate::SqlxPostgresConnector::connect(opt).await; } #[cfg(feature = "sqlx-sqlite")] if DbBackend::Sqlite.is_prefix_of(&opt.url) { return crate::SqlxSqliteConnector::connect(opt).await; } #[cfg(feature = "rusqlite")] if DbBackend::Sqlite.is_prefix_of(&opt.url) { return crate::driver::rusqlite::RusqliteConnector::connect(opt); } #[cfg(feature = "mock")] if crate::MockDatabaseConnector::accepts(&opt.url) { return crate::MockDatabaseConnector::connect(&opt.url).await; } Err(conn_err(format!( "The connection string '{}' has no supporting driver.", opt.url ))) } ``` -------------------------------- ### Manual PrimaryKeyTrait Implementation Example Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/trait.PrimaryKeyTrait.html Example of manually implementing the PrimaryKeyTrait for an enum. ```APIDOC ## Example: Manual Implementation ```rust use sea_orm::entity::prelude::*; #[derive(Copy, Clone, Debug, EnumIter)] pub enum PrimaryKey { Id, } impl PrimaryKeyTrait for PrimaryKey { type ValueType = i32; fn auto_increment() -> bool { true } } ``` ``` -------------------------------- ### Execute Raw SQL Queries and Transactions Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/entity/active_model.rs.html Demonstrates how to execute raw SQL queries and manage transactions using SeaORM. Includes examples for SELECT and UPDATE statements with parameter binding. ```rust r#"SELECT "fruit"."id", "fruit"."name", "fruit"."cake_id" FROM "fruit" WHERE "fruit"."id" = $1 LIMIT $2"#, vec![1i32.into(), 1u64.into()], ``` ```rust Transaction::from_sql_and_values( DbBackend::Postgres, r#"UPDATE "fruit" SET "name" = $1, "cake_id" = $2 WHERE "fruit"."id" = $3 RETURNING "id", "name", "cake_id""#, vec!["Apple".into(), Option::::None.into(), 1i32.into()], ) ``` -------------------------------- ### Example: Fetching and Asserting Query Results Source: https://docs.rs/sea-orm/2.0.0-rc.34/src/sea_orm/executor/query.rs.html Demonstrates executing a SQL statement and asserting the returned tuple values. This example requires mock database features and specific traits. ```rust # use sea_orm::{error::*, tests_cfg::*, *}; # # #[smol_potat::main] # #[cfg(all(feature = "mock", feature = "macros"))] # pub async fn main() -> Result<(), DbErr> { # # let db = MockDatabase::new(DbBackend::Postgres) # .append_query_results([ # maplit::btreemap! { # "name" => Into::::into("Chocolate Forest"), # "num_of_cakes" => Into::::into(1), # }, # maplit::btreemap! { # "name" => Into::::into("New York Cheese"), # "num_of_cakes" => Into::::into(1), # }, # ]) # .into_connection(); # 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""#, [] ),] ); # # Ok(()) # } ``` -------------------------------- ### Get Mask for IpNetwork Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/prelude/enum.IpNetwork.html?search=std%3A%3Avec Illustrates how to get the network mask for both IPv4 and IPv6 IpNetworks. ```rust use ipnetwork::IpNetwork; use std::net::{Ipv4Addr, Ipv6Addr}; let v4_net: IpNetwork = "10.9.0.1".parse().unwrap(); assert_eq!(v4_net.mask(), Ipv4Addr::new(255, 255, 255, 255)); let v4_net: IpNetwork = "10.9.0.32/16".parse().unwrap(); assert_eq!(v4_net.mask(), Ipv4Addr::new(255, 255, 0, 0)); let v6_net: IpNetwork = "ff01::0".parse().unwrap(); assert_eq!(v6_net.mask(), Ipv6Addr::new(0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff)); let v6_net: IpNetwork = "ff01::0/32".parse().unwrap(); assert_eq!(v6_net.mask(), Ipv6Addr::new(0xffff, 0xffff, 0, 0, 0, 0, 0, 0)); ``` -------------------------------- ### Starts With Operator (`starts_with`) Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/entity/trait.ColumnTrait.html Checks if a string starts with a specified prefix. This is a shorthand for `LIKE 'prefix%'`. ```APIDOC ## POST /query/expression/starts_with ### Description Checks if a string starts with a specified prefix. This is a shorthand for `LIKE 'prefix%'`. ### Method POST ### Endpoint /query/expression/starts_with ### Parameters #### Request Body - **s** (string) - Required - The prefix string. ### Request Example ```json { "column": "name", "s": "cheese" } ``` ### Response #### Success Response (200) - **Expr** (object) - The generated expression object. #### Response Example ```json { "expression": "`cake`.`name` LIKE 'cheese%'" } ``` ``` -------------------------------- ### ConnectOptions::new Source: https://docs.rs/sea-orm/2.0.0-rc.34/sea_orm/struct.ConnectOptions.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new ConnectOptions instance from a database URI string. ```APIDOC ## ConnectOptions::new ### Description Creates new ConnectOptions for a Database by passing in a URI string. ### Method `new(url: T)` ### Parameters #### Path Parameters - **url** (T): A type that can be converted into a String, representing the database URI. ```