### TideORM Quick Start Example Source: https://github.com/mohamadzoh/tideorm/blob/master/README.md Demonstrates connecting to a PostgreSQL database with auto schema sync (for development only), creating a user, querying users with filters, loading relations, updating a user, and deleting a user. This example requires a running PostgreSQL instance and the 'tokio' runtime. ```rust #[tokio::main] async fn main() -> tideorm::Result<()> { // Connect with auto schema sync (development only!) TideConfig::init() .database("postgres://localhost/mydb") .sync(true) .connect() .await?; // Create let user = User { email: "john@example.com".into(), name: "John Doe".into(), active: true, ..Default::default() }; let user = user.save().await?; // Query let users = User::query() .where_eq("active", true) .order_desc("created_at") .limit(10) .get() .await?; // Complex queries with OR conditions let matching_users = User::query() .where_eq("active", true) .begin_or() .or_where_like("name", "%Jane%") .or_where_like("email", "%@example.com") .end_or() .get() .await?; // Load relations let posts = user.posts.load().await?; let profile = user.profile.load().await?; // Update let mut user = User::find(1).await?.unwrap(); user.name = "Jane Doe".into(); user.update().await?; // Delete User::destroy(1).await?; Ok(()) } ``` -------------------------------- ### Real-World Examples Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Practical examples of using the fluent OR API for common e-commerce, inventory, marketing, search, and analytics scenarios. ```APIDOC ## Real-World Examples ### E-commerce: Flash sale eligibility ```rust let flash_sale_products = Product::query() .where_eq("active", true) .where_gt("stock", 100) .where_gte("rating", 4.3) .where_null("discount_percent") // Not already discounted .get() .await?; ``` ### Inventory: Reorder alerts ```rust let reorder_needed = Product::query() .where_eq("active", true) .begin_or() .or_where_lt("stock", 50).and_where_gt("rating", 4.5) // Popular items low .or_where_lt("stock", 30) // Any item critically low .end_or() .order_by("stock", Order::Asc) .get() .await?; ``` ### Marketing: Cross-sell recommendations ```rust let recommendations = Product::query() .where_eq("active", true) .begin_or() .or_where_eq("brand", "Apple") .or_where_eq("brand", "Samsung").and_where_gt("price", 500.0) .or_where_eq("featured", true).and_where_not("category", "Electronics") .end_or() .order_by("rating", Order::Desc) .limit(10) .get() .await?; ``` ### Search: Multi-pattern name matching ```rust let search_results = Product::query() .begin_or() .or_where_like("name", "iPhone%") .or_where_like("name", "Galaxy%") .or_where_like("name", "%Pro%") .end_or() .where_eq("active", true) .get() .await?; ``` ### Analytics: Price segmentation ```rust let segmented = Product::query() .begin_or() .or_where_eq("category", "Electronics") .or_where_eq("category", "Books") .end_or() .begin_or() .or_where_gt("price", 1000.0) // Premium .or_where_lt("price", 50.0) // Budget .end_or() .order_by("price", Order::Desc) .get() .await?; ``` ``` -------------------------------- ### JSON Output with URL Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/relations.md Example of the JSON structure when a base URL is configured. ```json { "thumbnail": { "key": "products/123/thumb.jpg", "filename": "thumb.jpg", "url": "https://cdn.example.com/uploads/products/123/thumb.jpg" } } ``` -------------------------------- ### Install TideORM Macros dependency Source: https://github.com/mohamadzoh/tideorm/blob/master/tideorm-macros/README.md Add this to your Cargo.toml file to use the macros crate directly. ```toml [dependencies] tideorm-macros = "0.9.9" ``` -------------------------------- ### Perform Basic Full-Text Search Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Examples for simple searching, ranking results by relevance, counting matches, and retrieving the first result. ```rust use tideorm::prelude::*;\n\n// Simple full-text search\nlet results = Article::search(&["title", "content"], "rust programming")\n .await?;\n\n// Search with ranking (ordered by relevance)\nlet ranked = Article::search_ranked(&["title", "content"], "rust async")\n .limit(10)\n .get_ranked()\n .await?;\n\nfor result in ranked {\n println!("{}: {} (rank: {:.2})", \n result.record.id, \n result.record.title, \n result.rank\n );\n}\n\n// Count matching results\nlet count = Article::search(&["title", "content"], "rust")\n .count()\n .await?;\n\n// Get first matching result\nlet first = Article::search(&["title"], "rust")\n .first()\n .await?; ``` -------------------------------- ### Implement Migration Struct Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/migrations.md Example of a full migration implementation using the Migration trait to define up and down schema changes. ```rust use tideorm::prelude::*; use tideorm::migration::*; struct CreateUsersTable; #[async_trait] impl Migration for CreateUsersTable { fn version(&self) -> &str { "20260115_001" } fn name(&self) -> &str { "create_users_table" } async fn up(&self, schema: &mut Schema) -> Result<()> { schema.create_table("users", |t| { t.id(); // id BIGSERIAL PRIMARY KEY t.string("email").unique().not_null(); // email VARCHAR(255) UNIQUE NOT NULL t.string("name").not_null(); // name VARCHAR(255) NOT NULL t.text("bio").nullable(); // bio TEXT NULL t.boolean("active").default(true); // active BOOLEAN DEFAULT true t.date("birth_date").nullable(); // birth_date DATE NULL t.decimal_with("balance", 12, 2) // balance DECIMAL(12,2) DEFAULT 0.00 .default("0.00"); t.jsonb("preferences").nullable(); // preferences JSONB NULL t.timestamptz("email_verified_at") // email_verified_at TIMESTAMPTZ NULL .nullable(); t.timestamps(); // created_at, updated_at TIMESTAMPTZ t.soft_deletes(); // deleted_at TIMESTAMPTZ NULL }).await?; // Add custom index schema.create_index("users", "idx_users_email_active", &["email", "active"], false).await?; Ok(()) } async fn down(&self, schema: &mut Schema) -> Result<()> { schema.drop_table("users").await } } ``` -------------------------------- ### TideORM Installation for PostgreSQL Source: https://github.com/mohamadzoh/tideorm/blob/master/README.md Add TideORM to your project's Cargo.toml file with the 'postgres' feature enabled for PostgreSQL support. This is the default database backend. ```toml [dependencies] # PostgreSQL (default) tideorm = { version = "0.9.9", features = ["postgres"] } ``` -------------------------------- ### Setup Model for File Attachments Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/relations.md Uses has_one_file and has_many_files attributes on a model with a JSONB column to store attachment metadata. ```rust #[tideorm::model(table = "products")] #[tideorm(has_one_file = "thumbnail")] #[tideorm(has_many_files = "images,documents")] pub struct Product { #[tideorm(primary_key, auto_increment)] pub id: i64, pub name: String, pub files: Option, // JSONB column storing attachments } ``` -------------------------------- ### TideORM Installation for MySQL Source: https://github.com/mohamadzoh/tideorm/blob/master/README.md Add TideORM to your project's Cargo.toml file with the 'mysql' feature enabled for MySQL support. Ensure you have the correct version specified. ```toml # MySQL tideorm = { version = "0.9.9", features = ["mysql"] } ``` -------------------------------- ### Manual Profiling Session with Profiler Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/profiling.md Starts a profiler, records a simple query with its duration, records a more detailed query with table and row information, and then stops the profiler to generate a report. Use when you want to capture custom SQL strings, table names, row counts, and run QueryAnalyzer over a curated set of queries. ```rust use std::time::Duration; use tideorm::profiling::{ProfiledQuery, Profiler}; let mut profiler = Profiler::start(); profiler.record("SELECT * FROM users WHERE active = true", Duration::from_millis(12)); profiler.record_full( ProfiledQuery::new("SELECT * FROM posts WHERE user_id = 42", Duration::from_millis(37)) .with_table("posts") .with_rows(8), ); let report = profiler.stop(); println!("{}", report); ``` -------------------------------- ### TideORM Installation with Attachments Feature Source: https://github.com/mohamadzoh/tideorm/blob/master/README.md Enable the 'attachments' feature alongside your chosen database backend (e.g., 'postgres') in your Cargo.toml to use TideORM's attachment handling capabilities. ```toml # Enable attachments support explicitly tideorm = { version = "0.9.9", features = ["postgres", "attachments"] } ``` -------------------------------- ### TideORM Installation for SQLite Source: https://github.com/mohamadzoh/tideorm/blob/master/README.md Add TideORM to your project's Cargo.toml file with the 'sqlite' feature enabled for SQLite support. This allows for file-based database operations. ```toml # SQLite tideorm = { version = "0.9.9", features = ["sqlite"] } ``` -------------------------------- ### Use Attachments and Translations Together in Rust Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/relations.md Example of setting a translation for a specific field and locale, attaching a single file to 'thumbnail', and multiple files to 'images', followed by updating the record. ```rust // Use both features product.set_translation("name", "ar", "اسم المنتج")?; product.attach("thumbnail", "uploads/thumb.jpg")?; product.attach_many("images", vec!["img1.jpg", "img2.jpg"])?; product.update().await?; ``` -------------------------------- ### Find entities by primary key in EntityManager Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/entity-manager.md Examples of retrieving entities using different primary key shapes within an entity manager context. ```rust User::find_in_entity_manager(1, &entity_manager) ``` ```rust ApiKey::find_in_entity_manager("api-key-1".to_string(), &entity_manager) ``` ```rust Membership::find_in_entity_manager((team_id, member_id), &entity_manager) ``` -------------------------------- ### Enable and Use Global Profiler Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/profiling.md Enables global profiling, resets statistics, sets a slow query threshold, executes a query, retrieves statistics, and then disables the profiler. Use when you want to observe real query execution with minimal setup. ```rust use tideorm::prelude::*; use tideorm::profiling::GlobalProfiler; GlobalProfiler::enable(); GlobalProfiler::reset(); GlobalProfiler::set_slow_threshold(200); let users = User::query() .where_eq("active", true) .limit(25) .get() .await?; let stats = GlobalProfiler::stats(); println!("{}", stats); GlobalProfiler::disable(); ``` -------------------------------- ### Build and serve documentation locally Source: https://github.com/mohamadzoh/tideorm/blob/master/DOCUMENTATION.md Commands to compile the mdBook documentation and launch a local development server. ```bash mdbook build mdbook serve --open ``` -------------------------------- ### Initialize Database Connection Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/getting-started.md Use `Database::init` for a simple connection or `TideConfig::init` with `connect` for more configuration options. Both require an asynchronous context. ```rust Database::init("postgres://localhost/mydb").await?; ``` ```rust TideConfig::init() .database("postgres://localhost/mydb") .connect() .await?; ``` -------------------------------- ### Get Translated Value with Fallback Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/relations.md Use `get_translated` to get a translation, falling back to a secondary language or default field value if the requested translation is not found. ```rust let name = product.get_translated("name", "ar")?; ``` -------------------------------- ### JSON Storage Format Example Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/relations.md The internal JSONB structure used to store file attachments. ```json { "thumbnail": { "key": "uploads/thumb.jpg", "filename": "thumb.jpg", "created_at": "2024-01-15T10:30:00Z" }, "images": [ { "key": "uploads/img1.jpg", "filename": "img1.jpg", "created_at": "2024-01-15T10:30:00Z", "size": 1048576, "mime_type": "image/jpeg" }, { "key": "uploads/img2.jpg", "filename": "img2.jpg", "created_at": "2024-01-15T10:31:00Z" } ] } ``` -------------------------------- ### Execute Window Functions and CTEs Source: https://context7.com/mohamadzoh/tideorm/llms.txt Demonstrates advanced query building including ranking, running totals, and recursive CTEs. Requires models to derive query capabilities. ```rust use tideorm::prelude::*;\n\n// ROW_NUMBER\nlet products = Product::query()\n .row_number("row_num", Some("category"), "price", Order::Desc)\n .get_raw()\n .await?;\n\n// RANK and DENSE_RANK\nlet employees = Employee::query()\n .rank("salary_rank", Some("department_id"), "salary", Order::Desc)\n .get_raw()\n .await?;\n\n// Running totals\nlet sales = Sale::query()\n .running_sum("running_total", "amount", "date", Order::Asc)\n .get_raw()\n .await?;\n\n// LAG/LEAD for previous/next row values\nlet orders = Order::query()\n .lag("prev_total", "total", 1, Some("0"), "user_id", "created_at", Order::Asc)\n .get_raw()\n .await?;\n\n// Common Table Expressions (CTEs)\nlet orders = Order::query()\n .with_cte(CTE::new(\n "high_value_orders",\n "SELECT * FROM orders WHERE total > 1000".to_string()\n ))\n .where_raw("id IN (SELECT id FROM high_value_orders)")\n .get()\n .await?;\n\n// Recursive CTE for hierarchical data\nlet employees = Employee::query()\n .with_recursive_cte(\n "org_tree",\n vec!["id", "name", "manager_id", "level"],\n "SELECT id, name, manager_id, 0 FROM employees WHERE manager_id IS NULL",\n "SELECT e.id, e.name, e.manager_id, t.level + 1\n FROM employees e INNER JOIN org_tree t ON e.manager_id = t.id"\n )\n .where_raw("id IN (SELECT id FROM org_tree)")\n .get()\n .await?; ``` -------------------------------- ### Get All Translations for a Language Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/relations.md Fetch all translations across all translatable fields for a specific language using `get_translations_for_language`. ```rust let arabic = product.get_translations_for_language("ar")?; // Returns: {"name": "اسم المنتج", "description": "وصف المنتج"} ``` -------------------------------- ### Define Matching Model Struct Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/migrations.md Example of a Rust struct mapped to the database table using the tideorm model attribute. ```rust use chrono::{DateTime, NaiveDate, Utc}; use rust_decimal::Decimal; #[tideorm::model(table = "users", soft_delete)] pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, pub email: String, pub name: String, pub bio: Option, pub active: bool, pub birth_date: Option, pub balance: Decimal, pub preferences: Option, pub email_verified_at: Option>, pub created_at: DateTime, pub updated_at: DateTime, pub deleted_at: Option>, } ``` -------------------------------- ### Build Documentation with mdBook Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/getting-started.md Rebuild the project's documentation using mdBook after making documentation changes. ```bash # Rebuild the book after documentation changes mdbook build ``` -------------------------------- ### Get JSON with Fallback Translation Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/relations.md When using `to_translated_json`, if the primary language translation is not found, it will attempt to use the fallback language. ```rust let json = product.to_translated_json(Some(opts)); ``` -------------------------------- ### Configure Database Connection in TideORM Source: https://context7.com/mohamadzoh/tideorm/llms.txt Initialize database connections using simple or full configuration with connection pooling and timeouts. Supports PostgreSQL, MySQL, and SQLite. ```rust use tideorm::prelude::*; use std::time::Duration; // Simple connection Database::init("postgres://localhost/mydb").await?; // Full configuration with connection pool settings TideConfig::init() .database("postgres://user:pass@localhost/mydb") .database_type(DatabaseType::Postgres) // or MySQL, SQLite .max_connections(20) .min_connections(5) .connect_timeout(Duration::from_secs(10)) .idle_timeout(Duration::from_secs(300)) .max_lifetime(Duration::from_secs(3600)) .sync(true) // Auto schema sync (development only!) .connect() .await?; // MySQL connection TideConfig::init() .database("mysql://user:pass@localhost/mydb") .connect() .await?; // SQLite connection TideConfig::init() .database("sqlite://./data.db?mode=rwc") .connect() .await?; // Reset global state for tests or reconfiguration Database::reset_global(); TideConfig::reset(); TokenConfig::reset(); ``` -------------------------------- ### Get Available Languages for a Field Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/relations.md Retrieve a list of all language codes for which translations exist for a given field using `available_languages`. ```rust let languages = product.available_languages("name")?; println!("Name available in: {:?}", languages); ``` -------------------------------- ### Configure Full-Text Search Modes Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Demonstrates switching between natural language, boolean, phrase, and prefix search modes. ```rust use tideorm::fulltext::{SearchMode, FullTextConfig};\n\n// Natural language search (default)\nArticle::search(&["content"], "learn rust programming").await?;\n\n// Boolean search with operators\nArticle::search(&["content"], "+rust +async -javascript")\n .mode(SearchMode::Boolean)\n .get()\n .await?;\n\n// Phrase search (exact phrase matching)\nArticle::search(&["content"], "async await")\n .mode(SearchMode::Phrase)\n .get()\n .await?;\n\n// Prefix search (for autocomplete)\nArticle::search(&["title"], "prog")\n .mode(SearchMode::Prefix)\n .get()\n .await?; ``` -------------------------------- ### Get Specific Translation Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/relations.md Retrieve a specific translation for a field and language using `get_translation`. Returns `None` if the translation does not exist. ```rust if let Some(name) = product.get_translation("name", "ar")? { println!("Arabic name: {}", name); } ``` -------------------------------- ### Tokenization Configuration Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/models.md Details on how to configure the encryption key for tokenization, preferably during application startup. ```APIDOC ## Tokenization Configuration ### Description This section explains how to configure the encryption key for tokenization, which is crucial for security. It's recommended to set this during application startup. ### Method N/A (Configuration) ### Endpoint N/A ### Parameters N/A ### Request Example ```rust use tideorm::config::TideConfig; let encryption_key = std::env::var("ENCRYPTION_KEY")?; TideConfig::init() .database("postgres://localhost/mydb") .encryption_key(&encryption_key) .connect() .await?; ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Get JSON Including All Translations Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/relations.md Generate a JSON output that includes all translations for all fields, typically for administrative interfaces, using `to_json_with_all_translations`. ```rust let json = product.to_json_with_all_translations(); // Result includes raw translations field ``` -------------------------------- ### Get All Translations for a Field Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/relations.md Retrieve all available translations for a given field using `get_all_translations`. This returns a HashMap of language codes to their translated values. ```rust let all_names = product.get_all_translations("name")?; for (lang, value) in all_names { println!("{}: {}", lang, value); } ``` -------------------------------- ### Advanced Query Building in Rust Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/models.md Demonstrates EXISTS subqueries, array-based filtering, and query fragment reuse. ```rust // has_related() - EXISTS subqueries let cakes = Cake::query() .has_related("fruits", "cake_id", "id", "name", "Mango") .get().await?; // eq_any() / ne_all() - PostgreSQL array optimizations let users = User::query() .eq_any("id", vec![1, 2, 3, 4, 5]) // "id" = ANY(ARRAY[...]) .ne_all("role", vec!["banned"]) // "role" <> ALL(ARRAY[...]) .get().await?; // Unix timestamps use tideorm::types::{UnixTimestamp, UnixTimestampMillis}; let ts = UnixTimestamp::now(); let dt = ts.to_datetime(); // Batch insert let users: Vec = User::insert_all(vec![u1, u2]).await?; // consolidate() - Reusable query fragments let active_scope = User::query() .where_eq("status", "active") .consolidate(); let admins = User::query().apply(&active_scope).where_eq("role", "admin").get().await?; // Multi-column unique constraints (migrations) builder.unique(&["user_id", "role_id"]); builder.unique_named("uq_email_tenant", &["email", "tenant_id"]); // CHECK constraints (migrations) builder.string("email").check("email LIKE '%@%'"); ``` -------------------------------- ### Connect to PostgreSQL Database Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Establish a connection to a PostgreSQL database using a connection string. ```rust // PostgreSQL TideConfig::init() .database("postgres://user:pass@localhost/mydb") .connect() .await?; ``` -------------------------------- ### Get JSON with Translated Fields Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/relations.md Generate a JSON representation of the model with translated fields for a specified language using `to_translated_json`. Options can specify the target language. ```rust let mut opts = HashMap::new(); opts.insert("language".to_string(), "ar".to_string()); let json = product.to_translated_json(Some(opts)); // Result: {"id": 1, "name": "اسم المنتج", "description": "وصف المنتج", "price": 99.99} ``` -------------------------------- ### Run Cargo Tests for Default Backend Suite Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/getting-started.md Run the test suite for the default backend, typically PostgreSQL, by enabling the corresponding feature. ```bash # Default backend suite cargo test --features postgres ``` -------------------------------- ### Use Schema Convenience Methods Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/migrations.md Helper methods for common table requirements like primary keys, timestamps, and soft deletes. ```rust t.id(); // BIGSERIAL PRIMARY KEY (auto-increment) t.big_increments("id"); // Same as id() t.increments("id"); // INTEGER PRIMARY KEY (auto-increment) t.foreign_id("user_id"); // BIGINT (for foreign keys) t.timestamps(); // created_at + updated_at (TIMESTAMPTZ) t.timestamps_naive(); // created_at + updated_at (TIMESTAMP, no tz) t.soft_deletes(); // deleted_at (nullable TIMESTAMPTZ) ``` -------------------------------- ### Fluent OR API Usage Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Demonstrates how to build queries with grouped OR conditions, including nested AND chains. ```APIDOC ## Fluent OR API (begin_or / end_or) For complex queries with grouped OR conditions combined with AND, use the fluent OR API. ### Basic OR group ```rust Product::query() .begin_or() .or_where_eq(Product::columns.category, "Electronics") .or_where_eq(Product::columns.category, "Home") .end_or() .get() .await?; ``` ### OR with AND chains ```rust Product::query() .begin_or() .or_where_eq("brand", "Apple").and_where_eq("active", true) .or_where_eq("brand", "Samsung").and_where_eq("featured", true) .end_or() .get() .await?; ``` ### Complex OR and AND combination ```rust Product::query() .where_eq("active", true) .where_gte("rating", 4.0) .begin_or() .or_where_eq("category", "Electronics").and_where_lt("price", 1000.0) .or_where_eq("category", "Home").and_where_eq("featured", true) .end_or() .get() .await?; ``` ### Multiple sequential OR groups ```rust Product::query() .where_eq("active", true) .begin_or() .or_where_eq("category", "Electronics") .or_where_eq("category", "Home") .end_or() .begin_or() .or_where_eq("brand", "Apple") .or_where_eq("brand", "Samsung") .end_or() .get() .await?; ``` ``` -------------------------------- ### Enable Query Logging Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Set the environment variable to log all SQL queries to stderr. ```bash # Set environment variable TIDE_LOG_QUERIES=true cargo run ``` -------------------------------- ### Connect to MySQL/MariaDB Database Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Establish a connection to a MySQL or MariaDB database using a connection string. ```rust // MySQL / MariaDB TideConfig::init() .database("mysql://user:pass@localhost/mydb") .connect() .await?; ``` -------------------------------- ### Run Full Suite for PostgreSQL Source: https://github.com/mohamadzoh/tideorm/blob/master/README.md Execute the full test suite for PostgreSQL support by running 'cargo test --features postgres'. ```bash cargo test --features postgres ``` -------------------------------- ### Configure Global Base URL Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/relations.md Set a base URL during initialization to automatically prepend it to file keys in JSON output. ```rust TideConfig::init() .database("postgres://localhost/mydb") .file_base_url("https://cdn.example.com/uploads") .connect() .await?; ``` -------------------------------- ### Customize Full-Text Search Configuration Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Advanced configuration for language, word length constraints, and custom ranking weights. ```rust use tideorm::fulltext::{FullTextConfig, SearchMode, SearchWeights};\n\nlet config = FullTextConfig::new()\n .language("english") // Text analysis language\n .mode(SearchMode::Boolean) // Search mode\n .min_word_length(3) // Minimum word length to index\n .max_word_length(50) // Maximum word length\n // Custom weights for ranking (title > summary > content)\n .weights(SearchWeights::new(1.0, 0.5, 0.3, 0.1));\n\nlet results = Article::search_with_config(\n &["title", "summary", "content"],\n "rust programming",\n config\n).get().await?; ``` -------------------------------- ### Define and Apply Scopes Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/models.md Shows how to define reusable query fragments (scopes) as functions and apply them to a query builder. Scopes help in organizing and reusing query logic. ```rust // Define scope functions fn active(q: QueryBuilder) -> QueryBuilder { q.where_eq("active", true) } fn recent(q: QueryBuilder) -> QueryBuilder { q.order_desc("created_at").limit(10) } // Apply scopes let users = User::query() .scope(active) .scope(recent) .get() .await?; ``` -------------------------------- ### Ordering, Grouping, and Aggregations with Typed Columns Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/models.md Shows how to use typed columns for ordering, grouping, and aggregation functions in queries. ```rust // Ordering and grouping also support typed columns: User::query() .order_by(User::columns.created_at, Order::Desc) .order_asc(User::columns.name) .group_by(User::columns.role) .get() .await?; // Aggregations with typed columns: let total = Order::query().sum(Order::columns.amount).await?; let average = Product::query().avg(Product::columns.price).await?; let max_age = User::query().max(User::columns.age).await?; ``` -------------------------------- ### Run Cargo Tests for PostgreSQL Integration Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/getting-started.md Execute the PostgreSQL integration test suite. This requires specifying the test binary. ```bash # PostgreSQL integration suite cargo test --test postgres_integration_tests ``` -------------------------------- ### Profile Database Queries in Rust Source: https://context7.com/mohamadzoh/tideorm/llms.txt Enable global profiling for application-wide metrics or use manual sessions for specific performance analysis. Query analysis provides suggestions for optimization. ```rust use tideorm::prelude::*;\nuse tideorm::profiling::{GlobalProfiler, Profiler, ProfiledQuery, QueryAnalyzer};\nuse std::time::Duration;\n\n// Global profiling (lightweight, application-wide)\nGlobalProfiler::enable();\nGlobalProfiler::reset();\nGlobalProfiler::set_slow_threshold(200); // ms\n\nlet users = User::query().where_eq("active", true).limit(25).get().await?;\n\nlet stats = GlobalProfiler::stats();\nprintln!("Total queries: {}", stats.total_queries);\nprintln!("Total time: {:?}", stats.total_time());\nprintln!("Slow queries: {} ({:.1}%)", stats.slow_queries, stats.slow_percentage());\nGlobalProfiler::disable();\n\n// Manual profiling sessions\nlet mut profiler = Profiler::start();\nprofiler.record("SELECT * FROM users WHERE active = true", Duration::from_millis(12));\nprofiler.record_full(\n ProfiledQuery::new("SELECT * FROM posts WHERE user_id = 42", Duration::from_millis(37))\n .with_table("posts")\n .with_rows(8),\n);\nlet report = profiler.stop();\nprintln!("{}", report);\n\n// Query analysis\nlet suggestions = QueryAnalyzer::analyze("SELECT * FROM users WHERE email = 'john@example.com'");\nfor suggestion in suggestions {\n println!("{}", suggestion);\n} ``` -------------------------------- ### Connect to SQLite Database Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Establish a connection to an SQLite database using a connection string. Supports read-write-create mode. ```rust // SQLite TideConfig::init() .database("sqlite://./data.db?mode=rwc") .connect() .await?; ``` -------------------------------- ### Configure Connection Pool Settings Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/getting-started.md Customize connection pool behavior by setting maximum and minimum connections, connect timeout, idle timeout, and maximum lifetime. Ensure `Duration` is imported. ```rust TideConfig::init() .database("postgres://localhost/mydb") .max_connections(20) // Maximum pool size .min_connections(5) // Minimum idle connections .connect_timeout(Duration::from_secs(10)) .idle_timeout(Duration::from_secs(300)) .max_lifetime(Duration::from_secs(3600)) .connect() .await?; ``` -------------------------------- ### Run Cargo Tests for MySQL Integration Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/getting-started.md Execute the MySQL integration test suite. This requires specifying the test binary and enabling the MySQL feature. ```bash # MySQL integration suite cargo test --test mysql_integration_tests --features mysql ``` -------------------------------- ### Run Cargo Tests for Library Validation Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/getting-started.md Execute the smallest command that covers your change for fast library validation. ```bash # Fast library validation cargo test --lib ``` -------------------------------- ### Connect with Explicit Database Type Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Configure the database connection by explicitly specifying the database type and connection string. ```rust TideConfig::init() .database_type(DatabaseType::MySQL) .database("mysql://localhost/mydb") .connect() .await?; ``` -------------------------------- ### Execute Raw SQL Queries Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Methods for executing raw SQL queries and statements with or without parameters. ```rust // Execute raw SQL and return model instances let users: Vec = Database::raw::( "SELECT * FROM users WHERE age > 18" ).await?; // With parameters (use $1, $2 for PostgreSQL, ? for MySQL/SQLite) let users: Vec = Database::raw_with_params::( "SELECT * FROM users WHERE age > $1 AND status = $2", vec![18.into(), "active".into()] ).await?; // Execute raw SQL statement (INSERT, UPDATE, DELETE) let affected = Database::execute( "UPDATE users SET active = false WHERE last_login < NOW() - INTERVAL '1 year'" ).await?; // Execute with parameters let affected = Database::execute_with_params( "DELETE FROM users WHERE status = $1", vec!["banned".into()] ).await?; ``` -------------------------------- ### Marketing Cross-Sell Recommendations Query Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Generate cross-sell recommendations based on brand, price, and featured status, excluding certain categories. ```rust // Marketing: Cross-sell recommendations let recommendations = Product::query() .where_eq("active", true) .begin_or() .or_where_eq("brand", "Apple") .or_where_eq("brand", "Samsung").and_where_gt("price", 500.0) .or_where_eq("featured", true).and_where_not("category", "Electronics") .end_or() .order_by("rating", Order::Desc) .limit(10) .get() .await?; ``` -------------------------------- ### Analyze SQL Query for Optimization Suggestions Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/profiling.md Analyzes a given SQL query string and returns a collection of optimization suggestions. Use this alongside Profiler when you want human-readable guidance about indexing, query shape, and complexity. ```rust use tideorm::profiling::QueryAnalyzer; let suggestions = QueryAnalyzer::analyze("SELECT * FROM users WHERE email = 'john@example.com'"); for suggestion in suggestions { println!("{}", suggestion); } ``` -------------------------------- ### Run Cargo Tests for Broad Compatibility Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/getting-started.md Execute tests with all features enabled to ensure broad compatibility across different configurations. ```bash # Broad compatibility pass cargo test --all-features ``` -------------------------------- ### Check Database Feature Support Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Retrieve the backend database type and check for supported features like JSON, arrays, RETURNING clause, UPSERT, window functions, CTEs, and full-text search. ```rust let db_type = require_db()?.backend(); // Feature checks if db_type.supports_json() { // JSON/JSONB operations available } if db_type.supports_arrays() { // Native array operations (PostgreSQL only) } if db_type.supports_returning() { // RETURNING clause for INSERT/UPDATE } if db_type.supports_upsert() { // ON CONFLICT / ON DUPLICATE KEY support } if db_type.supports_window_functions() { // OVER(), ROW_NUMBER(), etc. } if db_type.supports_cte() { // WITH ... AS (Common Table Expressions) } if db_type.supports_fulltext_search() { // Full-text search capabilities } ``` -------------------------------- ### Search Multi-Pattern Name Matching Query Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Perform a search for products matching multiple name patterns using OR conditions with LIKE. ```rust // Search: Multi-pattern name matching let search_results = Product::query() .begin_or() .or_where_like("name", "iPhone%") .or_where_like("name", "Galaxy%") .or_where_like("name", "%Pro%") .end_or() .where_eq("active", true) .get() .await?; ``` -------------------------------- ### Window Functions in TideORM Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Perform complex calculations across sets of rows using standard SQL window functions. ```rust use tideorm::prelude::*; // ROW_NUMBER - assign sequential numbers let products = Product::query() .row_number("row_num", Some("category"), "price", Order::Desc) .get_raw() .await?; // SQL: ROW_NUMBER() OVER (PARTITION BY "category" ORDER BY "price" DESC) AS "row_num" // RANK - rank with gaps for ties let employees = Employee::query() .rank("salary_rank", Some("department_id"), "salary", Order::Desc) .get_raw() .await?; // DENSE_RANK - rank without gaps let students = Student::query() .dense_rank("score_rank", None, "score", Order::Desc) .get_raw() .await?; // Running totals with SUM window let sales = Sale::query() .running_sum("running_total", "amount", "date", Order::Asc) .get_raw() .await?; // LAG - access previous row value let orders = Order::query() .lag("prev_total", "total", 1, Some("0"), "user_id", "created_at", Order::Asc) .get_raw() .await?; // LEAD - access next row value let appointments = Appointment::query() .lead("next_date", "date", 1, None, "patient_id", "date", Order::Asc) .get_raw() .await?; // NTILE - distribute into buckets let products = Product::query() .ntile("price_quartile", 4, "price", Order::Asc) .get_raw() .await?; // Custom window function with full control let results = Order::query() .window( WindowFunction::new(WindowFunctionType::Sum("amount".to_string()), "total_sales") .partition_by("region") .order_by("month", Order::Asc) .frame(FrameType::Rows, FrameBound::UnboundedPreceding, FrameBound::CurrentRow) ) .get_raw() .await?; ``` -------------------------------- ### Apply Conditional Scopes Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/models.md Demonstrates applying scopes conditionally based on boolean flags or Option values using `when` and `when_some` methods. This allows for dynamic query construction. ```rust // Apply scope conditionally let include_inactive = false; let users = User::query() .when(include_inactive, |q| q.with_trashed()) .get() .await?; ``` ```rust // Apply scope based on Option value let status_filter: Option<&str> = Some("active"); let users = User::query() .when_some(status_filter, |q, status| q.where_eq("status", status)) .get() .await?; ``` -------------------------------- ### Configure TideConfig with Encryption Key Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/models.md Initialize the application configuration with an encryption key to support secure tokenization. ```rust let encryption_key = std::env::var("ENCRYPTION_KEY")?; TideConfig::init() .database("postgres://localhost/mydb") .encryption_key(&encryption_key) .connect() .await?; ``` -------------------------------- ### Run Cargo Tests for SQLite Integration Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/getting-started.md Execute the SQLite integration test suite. This requires specifying the test binary and enabling SQLite and runtime features while disabling default features. ```bash # SQLite integration suite cargo test --test sqlite_integration_tests --features "sqlite runtime-tokio" --no-default-features ``` -------------------------------- ### Create a New Record Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/models.md Save a new model instance to the database using the save method. ```rust let user = User { email: "john@example.com".to_string(), name: "John Doe".to_string(), active: true, ..Default::default() }; let user = user.save().await?; println!("Created user with id: {}", user.id); ``` -------------------------------- ### Execute Batch Operations Source: https://context7.com/mohamadzoh/tideorm/llms.txt Perform bulk inserts, updates, and deletes to improve database performance. ```rust use tideorm::prelude::*; // Batch insert let users = vec![ User { name: "John".into(), email: "john@example.com".into(), ..Default::default() }, User { name: "Jane".into(), email: "jane@example.com".into(), ..Default::default() }, User { name: "Bob".into(), email: "bob@example.com".into(), ..Default::default() }, ]; let inserted = User::insert_all(users).await?; // Bulk update with conditions let affected = User::update_all() .set("active", false) .set("updated_at", Utc::now()) .where_eq("last_login_before", "2024-01-01") .execute() .await?; // Bulk delete let deleted = User::query() .where_eq("status", "inactive") .delete() .await?; ``` -------------------------------- ### OR Conditions with Pattern Matching Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Illustrates using OR conditions with LIKE for pattern matching. This enables searching for records that match one of several patterns. ```rust User::query() .or_where_like(User::columns.name, "John%") // name LIKE 'John%' .or_where_like(User::columns.name, "Jane%") // OR name LIKE 'Jane%' .get() .await?; ``` -------------------------------- ### Define Database Migrations Source: https://context7.com/mohamadzoh/tideorm/llms.txt Implements the Migration trait to define table structures and indices. Requires the tideorm::migration module. ```rust use tideorm::prelude::*;\nuse tideorm::migration::*;\n\nstruct CreateUsersTable;\n\n#[async_trait]\nimpl Migration for CreateUsersTable {\n fn version(&self) -> &str { "20260115_001" }\n fn name(&self) -> &str { "create_users_table" }\n\n async fn up(&self, schema: &mut Schema) -> Result<()> {\n schema.create_table("users", |t| {\n t.id(); // BIGSERIAL PRIMARY KEY\n t.string("email").unique().not_null(); // VARCHAR(255) UNIQUE NOT NULL\n t.string("name").not_null();\n t.text("bio").nullable();\n t.boolean("active").default(true);\n t.decimal_with("balance", 12, 2).default("0.00");\n t.jsonb("preferences").nullable();\n t.timestamps(); // created_at, updated_at\n t.soft_deletes(); // deleted_at\n }).await?;\n\n schema.create_index("users", "idx_users_email_active", &["email", "active"], false).await?;\n Ok(())\n }\n\n async fn down(&self, schema: &mut Schema) -> Result<()> {\n schema.drop_table("users").await\n }\n}\n\n// Column type helpers: id(), string(), text(), integer(), big_integer(), float(),\n// double(), decimal(), boolean(), date(), time(), timestamp(), timestamptz(),\n// uuid(), json(), jsonb(), binary(), integer_array(), text_array(), timestamps(),\n// soft_deletes(), foreign_id() ``` -------------------------------- ### Execution Methods in TideORM Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/queries.md Execute queries to retrieve, count, check existence, or delete records. ```rust // Get all matching records let users = User::query() .where_eq("active", true) .get() .await?; // Vec // Get first record let user = User::query() .where_eq("email", "admin@example.com") .first() .await?; // Option // Get first or fail let user = User::query() .where_eq("id", 1) .first_or_fail() .await?; // Result // Count (efficient SQL COUNT) let count = User::query() .where_eq("active", true) .count() .await?; // u64 // Check existence let exists = User::query() .where_eq("email", "admin@example.com") .exists() .await?; // bool // Bulk delete (efficient single DELETE statement) let deleted = User::query() .where_eq("status", "inactive") .delete() .await?; // u64 (rows affected) ``` -------------------------------- ### Implement Record Tokenization Source: https://github.com/mohamadzoh/tideorm/blob/master/docs/models.md Enable tokenization on a model to obfuscate primary keys. Ensure an encryption key is set before performing token operations. ```rust use tideorm::prelude::*; #[tideorm::model(table = "users", tokenize)] // Enable tokenization pub struct User { #[tideorm(primary_key, auto_increment)] pub id: i64, pub email: String, pub name: String, } // Configure encryption key once at startup TokenConfig::set_encryption_key("your-32-byte-secret-key-here-xx"); // Tokenize a record let user = User::find(1).await?.unwrap(); let token = user.tokenize()?; // "iIBmdKYhJh4_vSKFlBTP..." // Decode token to the model's primary key type (doesn't hit database) let id = User::detokenize(&token)?; // 1 // Fetch record directly from token let same_user = User::from_token(&token).await?; assert_eq!(user.id, same_user.id); ```