ignis-db 0.2.0

A comprehensive PostgreSQL ORM with macro-driven schema management
Documentation
# Ignis-DB API Clarification & Integration Guide

Based on your specific questions about ignis-db integration, here are the accurate answers and guidance:

## 1. Query Builder API - INSERT, UPDATE, DELETE Methods

**Current State**: The `Query` struct in the `dsl` module does **NOT** have `insert()`, `update()`, or `delete()` methods. These operations are handled by separate builders.

**Correct Approach**:

```rust
use ignis_db::macros::SafeInsertBuilder;
use ignis_db::macros::SafeUpdateBuilder;
use ignis_db::macros::SafeDeleteBuilder;

// For INSERT operations
let insert = SafeInsertBuilder::new("users")?
    .value("email", "user@example.com")?
    .value("password_hash", "hashed_password")?
    .value("active", true)?;

let result = insert.execute(&pool).await?;

// For UPDATE operations
let update = SafeUpdateBuilder::new("users")
    .set("last_login", chrono::Utc::now())
    .set("active", false)
    .where_("id = ?", user_id);

let result = update.execute(&pool).await?;

// For DELETE operations
let delete = SafeDeleteBuilder::new("users")
    .where_("id = ?", user_id);

let result = delete.execute(&pool).await?;
```

## 2. Insertable Trait Usage

**Correct Usage**: The `Insertable` trait is designed for model instances, not for building queries.

```rust
use ignis_db::traits::Insertable;

#[derive(Table, Insertable)]
#[table_name = "users"]
pub struct User {
    pub id: uuid::Uuid,
    pub email: String,
    pub password_hash: String,
    pub active: bool,
}

// Usage with Insertable trait
let user = User {
    id: uuid::Uuid::new_v4(),
    email: "user@example.com".to_string(),
    password_hash: "hashed_password".to_string(),
    active: true,
};

// Execute the insert
let rows_affected = user.insert(&pool).await?;
```

**Note**: The `Insertable` trait requires the model to implement the `Table` derive macro and is designed for direct model insertion, not query building.

## 3. Query Execution - Current Limitations

**Important**: The current `Query` struct does **NOT** have `execute()` or `fetch_*()` methods. It only generates SQL strings.

**Current Workaround**:

```rust
use ignis_db::dsl::Query;
use sqlx::PgPool;

// Build the query
let query = Query::new()
    .from_table_name("users")
    .select_columns_str(&["id", "email", "active"])
    .filter("active = true")
    .order_by("created_at")
    .limit(10);

// Generate SQL
let sql = query.to_sql();
println!("Generated SQL: {}", sql);

// Execute with sqlx directly
let rows = sqlx::query(&sql)
    .fetch_all(&pool)
    .await?;
```

**For Type-Safe Queries**, use `TypedQuery`:

```rust
use ignis_db::dsl::TypedQuery;

// TypedQuery generates SQL but doesn't execute
let typed_query = TypedQuery::new()
    .from_table_name("users")
    .select_columns_from(&["id", "email", "active"])
    .where_clause(/* WhereCondition */)
    .limit(10);

let sql = typed_query.to_sql();
// Still need to execute with sqlx
```

## 4. FromRow Compatibility

**Manual Implementation Required**: ignis-db does **NOT** provide derive macros for `FromRow`. You must implement it manually.

```rust
use sqlx::FromRow;

#[derive(Table, Serialize, Deserialize, Clone, Debug)]
#[table_name = "users"]
pub struct User {
    pub id: uuid::Uuid,
    pub email: String,
    pub password_hash: String,
    pub active: bool,
    pub created_at: chrono::DateTime<chrono::Utc>,
}

// Manual FromRow implementation
impl FromRow<'_, sqlx::PostgresRow> for User {
    fn from_row(row: &sqlx::PostgresRow) -> Result<Self, sqlx::Error> {
        Ok(User {
            id: row.get("id"),
            email: row.get("email"),
            password_hash: row.get("password_hash"),
            active: row.get("active"),
            created_at: row.get("created_at"),
        })
    }
}

// Usage with sqlx
let users: Vec<User> = sqlx::query_as::<_, User>("SELECT * FROM users WHERE active = $1")
    .bind(true)
    .fetch_all(&pool)
    .await?;
```

## 5. Recommended Best Practice

**Hybrid Approach** is recommended:

### For Simple CRUD Operations:

```rust
use ignis_db::macros::*;
use ignis_db::traits::*;

// Use SafeInsertBuilder, SafeUpdateBuilder, SafeDeleteBuilder
// for type-safe parameter binding

let insert = SafeInsertBuilder::new("users")?
    .value("email", &user.email)?
    .value("password_hash", &user.password_hash)?;

insert.execute(&pool).await?;
```

### For Complex Queries:

```rust
use ignis_db::dsl::Query;
use sqlx::PgPool;

// Use Query builder for complex SQL generation
let query = Query::new()
    .from_table_name("users")
    .select_columns_str(&["u.id", "u.email", "r.name as role_name"])
    .inner_join(/* join logic */)
    .filter("u.active = true AND r.name = 'admin'")
    .order_by("u.created_at")
    .limit(100);

let sql = query.to_sql();

// Execute with sqlx for full control
let rows = sqlx::query(&sql)
    .fetch_all(&pool)
    .await?;
```

### For Model-Based Operations:

```rust
// Use Insertable/Updatable traits for direct model operations
let user = User { /* ... */ };
let rows_affected = user.insert(&pool).await?;

// Or use SafeInsertBuilder for more control
let insert = SafeInsertBuilder::new("users")?
    .value("email", &user.email)?
    .value("password_hash", &user.password_hash)?;
```

## Complete Authentication Service Example

```rust
use ignis_db::*;
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, PgPool};
use uuid::Uuid;

#[derive(Table, Serialize, Deserialize, Clone, Debug)]
#[table_name = "users"]
pub struct User {
    pub id: Uuid,
    pub email: String,
    pub password_hash: String,
    pub active: bool,
    pub created_at: chrono::DateTime<chrono::Utc>,
}

impl FromRow<'_, sqlx::PostgresRow> for User {
    fn from_row(row: &sqlx::PostgresRow) -> Result<Self, sqlx::Error> {
        Ok(User {
            id: row.get("id"),
            email: row.get("email"),
            password_hash: row.get("password_hash"),
            active: row.get("active"),
            created_at: row.get("created_at"),
        })
    }
}

pub struct UserRepository {
    pool: PgPool,
}

impl UserRepository {
    pub fn new(pool: PgPool) -> Self {
        Self { pool }
    }

    // Simple CRUD with SafeInsertBuilder
    pub async fn create_user(&self, email: String, password_hash: String) -> Result<Uuid, sqlx::Error> {
        let user_id = Uuid::new_v4();

        let insert = SafeInsertBuilder::new("users")?
            .value("id", user_id)?
            .value("email", email)?
            .value("password_hash", password_hash)?
            .value("active", true)?
            .value("created_at", chrono::Utc::now())?;

        insert.execute(&self.pool).await?;
        Ok(user_id)
    }

    // Complex queries with Query builder + sqlx
    pub async fn find_users_with_roles(&self) -> Result<Vec<UserWithRole>, sqlx::Error> {
        let query = Query::new()
            .from_table_name("users")
            .select_columns_str(&["u.id", "u.email", "r.name as role_name"])
            .inner_join(/* join logic */)
            .filter("u.active = true")
            .order_by("u.email");

        let sql = query.to_sql();

        sqlx::query_as::<_, UserWithRole>(&sql)
            .fetch_all(&self.pool)
            .await
    }

    // Direct sqlx for maximum control
    pub async fn find_by_email(&self, email: &str) -> Result<Option<User>, sqlx::Error> {
        sqlx::query_as::<_, User>("SELECT * FROM users WHERE email = $1")
            .bind(email)
            .fetch_optional(&self.pool)
            .await
    }

    // Update with SafeUpdateBuilder
    pub async fn update_user(&self, id: Uuid, email: Option<String>, active: Option<bool>) -> Result<(), sqlx::Error> {
        let mut update = SafeUpdateBuilder::new("users");

        if let Some(email) = email {
            update = update.set("email", email);
        }
        if let Some(active) = active {
            update = update.set("active", active);
        }

        update = update.where_("id = ?", id);
        update.execute(&self.pool).await?;
        Ok(())
    }
}

#[derive(FromRow, Serialize, Deserialize, Debug)]
pub struct UserWithRole {
    pub id: Uuid,
    pub email: String,
    pub role_name: String,
}
```

## Key Takeaways

1. **Query struct**: Only for SQL generation, not execution
2. **SafeInsertBuilder/SafeUpdateBuilder/SafeDeleteBuilder**: For type-safe mutations
3. **Insertable/Updatable traits**: For direct model operations
4. **Manual FromRow**: Required for sqlx compatibility
5. **Hybrid approach**: Use ignis-db builders + sqlx execution for best results

This approach gives you the type safety and SQL generation benefits of ignis-db while maintaining full control over query execution through sqlx.