runique 3.0.2

A Django-inspired web framework for Rust with ORM, templates, and comprehensive security middleware
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! `Objects<E>` — Django-style manager for SeaORM entities, exposed via `impl_objects!`.

/// Django-style ORM manager for entities
///
/// This struct provides a Django-like interface for querying database entities.
/// It's designed to be used as a constant field on entity structs, enabling
/// the syntax `User::objects.filter(...)` without parentheses.
///
/// # Examples
///
/// ```rust
/// #[cfg(feature = "sqlite")]
/// async fn sqlite_objects_example() {
///     use sea_orm::entity::prelude::*;
///     use sea_orm::{Database, DbBackend, Schema, Set};
///
///     #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
///     #[sea_orm(table_name = "users")]
///     pub struct Model {
///         #[sea_orm(primary_key)]
///         pub id: i32,
///         pub username: String,
///         pub age: i32,
///     }
///
///     #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
///     pub enum Relation {}
///
///     impl ActiveModelBehavior for ActiveModel {}
///
///     // SQLite in-memory connection
///     let db = Database::connect("sqlite::memory:").await.unwrap();
///
///     // Table creation
///     let stmt = Schema::new(DbBackend::Sqlite).create_table_from_entity(Entity);
///     db.execute(&stmt).await.unwrap();
///
///     // Using ActiveModel for insertion
///     ActiveModel {
///         username: Set("Bob".to_owned()),
///         age: Set(25),
///         ..Default::default()
///     }
///     .insert(&db)
///     .await
///     .unwrap();
///
///     // Retrieval
///     let user: Option<Model> = Entity::find()
///         .filter(Column::Username.eq("Bob"))
///         .one(&db)
///         .await
///         .unwrap();
///     assert!(user.is_some());
/// }
///
/// #[cfg(feature = "sqlite")]
/// tokio::runtime::Runtime::new().unwrap().block_on(sqlite_objects_example());
/// ```
use super::query::RuniqueQueryBuilder;
use crate::context::template::Request;
use crate::utils::aliases::ADb;
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::response::Response;
use sea_orm::{ColumnTrait, Condition, DbErr, EntityTrait};
use std::marker::PhantomData;

/// Django-style ORM manager for entities
///
#[doc = include_str!("../../../doc-tests/macro_db/model_complete.md")]
pub struct Objects<E: EntityTrait> {
    _phantom: PhantomData<E>,
}

impl<E: EntityTrait> Default for Objects<E> {
    fn default() -> Self {
        Self::new()
    }
}

impl<E: EntityTrait> Objects<E> {
    /// Creates an empty manager. Holds no state beyond `PhantomData<E>`,
    /// which is what lets `Objects<E>` be declared as an associated `const`
    /// (see `impl_objects!`).
    pub const fn new() -> Self {
        Self {
            _phantom: PhantomData,
        }
    }

    /// Returns a builder over every row of the entity — equivalent to `E::find()`.
    pub fn all(&self) -> RuniqueQueryBuilder<E> {
        RuniqueQueryBuilder::new(E::find())
    }

    // In impl<E: EntityTrait> Objects<E>

    // === EXISTING (keeping current filter/exclude) ===
    /// Starts a query builder with a `WHERE` condition already applied.
    pub fn filter<C>(&self, condition: C) -> RuniqueQueryBuilder<E>
    where
        C: Into<Condition>,
    {
        RuniqueQueryBuilder::new(E::find()).filter(condition.into())
    }

    /// Starts a query builder that excludes rows matching `condition`.
    pub fn exclude<C>(&self, condition: C) -> RuniqueQueryBuilder<E>
    where
        C: Into<Condition>,
    {
        RuniqueQueryBuilder::new(E::find()).exclude(condition.into())
    }

    // === NEW : simplified vector filter ===
    /// Starts a query builder filtered on several `(column, value)` equality
    /// pairs at once (conditions are ANDed). See
    /// [`RuniqueQueryBuilder::filter_many`].
    pub fn filter_many<C, V, I>(&self, filters: I) -> RuniqueQueryBuilder<E>
    where
        C: ColumnTrait,
        V: Into<sea_orm::Value>,
        I: IntoIterator<Item = (C, V)>,
    {
        RuniqueQueryBuilder::new(E::find()).filter_many(filters)
    }

    /// Starts a query builder that excludes rows matching any of several
    /// `(column, value)` pairs. See [`RuniqueQueryBuilder::exclude_many`].
    pub fn exclude_many<C, V, I>(&self, filters: I) -> RuniqueQueryBuilder<E>
    where
        C: ColumnTrait,
        V: Into<sea_orm::Value>,
        I: IntoIterator<Item = (C, V)>,
    {
        RuniqueQueryBuilder::new(E::find()).exclude_many(filters)
    }

    /// Fetches the row with primary key `id`, or `DbErr::RecordNotFound` if none exists.
    pub async fn get(
        &self,
        db: &ADb,
        id: impl Into<<E::PrimaryKey as sea_orm::PrimaryKeyTrait>::ValueType>,
    ) -> Result<E::Model, DbErr> {
        E::find_by_id(id)
            .one(db)
            .await?
            .ok_or(DbErr::RecordNotFound("Record not found".to_string()))
    }

    /// Fetches the row with primary key `id`, returning `None` instead of an
    /// error if it doesn't exist.
    pub async fn get_optional(
        &self,
        db: &ADb,
        id: impl Into<<E::PrimaryKey as sea_orm::PrimaryKeyTrait>::ValueType>,
    ) -> Result<Option<E::Model>, DbErr> {
        E::find_by_id(id).one(db).await
    }

    /// Returns the total number of rows in the entity's table.
    pub async fn count(&self, db: &ADb) -> Result<u64, DbErr>
    where
        E::Model: Sync,
    {
        use sea_orm::PaginatorTrait;
        E::find().count(db).await
    }
    /// Fetches the row with primary key `id` and returns it, or renders
    /// `404.html` as an early `Err` response if it doesn't exist (or
    /// `500.html` if the lookup itself fails).
    pub async fn get_or_404(
        &self,
        db: &ADb,
        id: impl Into<<E::PrimaryKey as sea_orm::PrimaryKeyTrait>::ValueType>,
        ctx: &Request,
        error_msg: &str,
    ) -> Result<E::Model, Response> {
        match self.get_optional(db, id).await {
            Ok(Some(entity)) => Ok(entity),
            Ok(None) => {
                let mut context = ctx.context.clone();
                context.insert("title", "Page not found");
                context.insert("error_message", error_msg);
                match ctx.engine.tera.render("404.html", &context) {
                    Ok(html) => Err(axum::response::Html(html).into_response()),
                    Err(e) => {
                        tracing::error!("Tera render 404 error: {}", e);
                        Err((StatusCode::INTERNAL_SERVER_ERROR, "Internal error").into_response())
                    }
                }
            }
            Err(_) => {
                let mut context = ctx.context.clone();
                context.insert("title", "Server error");
                context.insert("error_message", "Database error");
                match ctx.engine.tera.render("500.html", &context) {
                    Ok(html) => Err(axum::response::Html(html).into_response()),
                    Err(e) => {
                        tracing::error!("Tera render 500 error: {}", e);
                        Err((StatusCode::INTERNAL_SERVER_ERROR, "Internal error").into_response())
                    }
                }
            }
        }
    }
}

impl<E: EntityTrait> Copy for Objects<E> {}
impl<E: EntityTrait> Clone for Objects<E> {
    fn clone(&self) -> Self {
        *self
    }
}

// =====================================================
// SQLite tests enabled with "sqlite" feature
// =====================================================

#[cfg(feature = "sqlite")]
#[cfg(test)]
mod tests {
    use super::*;
    use sea_orm::ActiveModelTrait;
    use sea_orm::Set;
    use sea_orm::entity::prelude::*;

    // Test model definition
    #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
    #[sea_orm(table_name = "users")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        pub username: String,
        pub age: i32,
    }

    #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
    pub enum Relation {}

    impl ActiveModelBehavior for ActiveModel {}

    // Objects implementation for our test Entity
    impl Entity {
        #[allow(non_upper_case_globals)]
        pub const objects: Objects<Self> = Objects::new();
    }

    // Helper function for DB setup
    async fn setup_db() -> Result<ADb, DbErr> {
        let db = sea_orm::Database::connect("sqlite::memory:").await?;

        use sea_orm::Schema;
        let schema = Schema::new(sea_orm::DatabaseBackend::Sqlite);
        let stmt = schema.create_table_from_entity(Entity);
        db.execute(&stmt).await?;

        Ok(ADb::from_connection(db))
    }

    #[tokio::test]
    async fn test_objects_all() -> Result<(), DbErr> {
        let db = setup_db().await?;

        let user = ActiveModel {
            username: Set("alice".to_string()),
            age: Set(25),
            ..Default::default()
        };
        user.insert(&db).await?;

        let users = Entity::objects.all().all(&db).await?;
        assert_eq!(users.len(), 1);
        Ok(())
    }

    #[tokio::test]
    async fn test_objects_filter() -> Result<(), DbErr> {
        let db = setup_db().await?;

        let young = ActiveModel {
            username: Set("young".to_string()),
            age: Set(16),
            ..Default::default()
        };
        let adult = ActiveModel {
            username: Set("adult".to_string()),
            age: Set(25),
            ..Default::default()
        };
        young.insert(&db).await?;
        adult.insert(&db).await?;

        let adults = Entity::objects.filter(Column::Age.gte(18)).all(&db).await?;
        assert_eq!(adults.len(), 1);
        assert_eq!(adults[0].username, "adult");
        Ok(())
    }

    #[tokio::test]
    async fn test_objects_exclude() -> Result<(), DbErr> {
        let db = setup_db().await?;

        let alice = ActiveModel {
            username: Set("alice".to_string()),
            age: Set(25),
            ..Default::default()
        };
        let banned = ActiveModel {
            username: Set("banned".to_string()),
            age: Set(30),
            ..Default::default()
        };
        alice.insert(&db).await?;
        banned.insert(&db).await?;

        let active_users = Entity::objects.exclude(Column::Age.eq(30)).all(&db).await?;
        assert_eq!(active_users.len(), 1);
        assert_eq!(active_users[0].username, "alice");
        Ok(())
    }

    #[tokio::test]
    async fn test_objects_count() -> Result<(), DbErr> {
        let db = setup_db().await?;

        for i in 1..=3 {
            let user = ActiveModel {
                username: Set(format!("user{}", i)),
                age: Set(20 + i),
                ..Default::default()
            };
            user.insert(&db).await?;
        }

        let count = Entity::objects.count(&db).await?;
        assert_eq!(count, 3);
        Ok(())
    }

    #[tokio::test]
    async fn test_objects_get_found() -> Result<(), DbErr> {
        let db = setup_db().await?;
        let inserted = ActiveModel {
            username: Set("diana".to_string()),
            age: Set(28),
            ..Default::default()
        }
        .insert(&db)
        .await?;

        let user = Entity::objects.get(&db, inserted.id).await?;
        assert_eq!(user.username, "diana");
        Ok(())
    }

    #[tokio::test]
    async fn test_objects_get_not_found() -> Result<(), DbErr> {
        let db = setup_db().await?;
        let result = Entity::objects.get(&db, 9999).await;
        assert!(result.is_err());
        Ok(())
    }

    #[tokio::test]
    async fn test_objects_get_optional_found() -> Result<(), DbErr> {
        let db = setup_db().await?;
        let inserted = ActiveModel {
            username: Set("eve".to_string()),
            age: Set(22),
            ..Default::default()
        }
        .insert(&db)
        .await?;

        let result = Entity::objects.get_optional(&db, inserted.id).await?;
        assert!(result.is_some());
        assert_eq!(result.unwrap().username, "eve");
        Ok(())
    }

    #[tokio::test]
    async fn test_objects_get_optional_not_found() -> Result<(), DbErr> {
        let db = setup_db().await?;
        let result = Entity::objects.get_optional(&db, 9999).await?;
        assert!(result.is_none());
        Ok(())
    }

    #[tokio::test]
    async fn test_objects_filter_many() -> Result<(), DbErr> {
        let db = setup_db().await?;
        for (name, age) in [("a", 20), ("b", 25), ("c", 20)] {
            ActiveModel {
                username: Set(name.to_string()),
                age: Set(age),
                ..Default::default()
            }
            .insert(&db)
            .await?;
        }
        let result = Entity::objects
            .filter_many([(Column::Age, 20)])
            .all(&db)
            .await?;
        assert_eq!(result.len(), 2);
        Ok(())
    }

    #[tokio::test]
    async fn test_objects_exclude_many() -> Result<(), DbErr> {
        let db = setup_db().await?;
        for (name, age) in [("x", 10), ("y", 20)] {
            ActiveModel {
                username: Set(name.to_string()),
                age: Set(age),
                ..Default::default()
            }
            .insert(&db)
            .await?;
        }
        let result = Entity::objects
            .exclude_many([(Column::Username, "x".to_string())])
            .all(&db)
            .await?;
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].username, "y");
        Ok(())
    }
}