bottle_orm/model.rs
1//! # Model Module
2//!
3//! This module defines the core `Model` trait and associated structures for Bottle ORM.
4//! It provides the interface that all database entities must implement, along with
5//! metadata structures for describing table columns.
6//!
7//! ## Overview
8//!
9//! The `Model` trait is the foundation of Bottle ORM. It defines how Rust structs
10//! map to database tables, including:
11//!
12//! - Table name resolution
13//! - Column metadata (types, constraints, relationships)
14//! - Serialization to/from database format
15//!
16//! ## Automatic Implementation
17//!
18//! The `Model` trait is typically implemented automatically via the `#[derive(Model)]`
19//! procedural macro, which analyzes struct fields and `#[orm(...)]` attributes to
20//! generate the necessary implementation.
21//!
22//! ## Example Usage
23//!
24//! ```rust,ignore
25//! use bottle_orm::Model;
26//! use uuid::Uuid;
27//! use chrono::{DateTime, Utc};
28//! use serde::{Deserialize, Serialize};
29//! use sqlx::FromRow;
30//!
31//! #[derive(Model, Debug, Clone, Serialize, Deserialize, FromRow)]
32//! struct User {
33//! #[orm(primary_key)]
34//! id: Uuid,
35//!
36//! #[orm(size = 50, unique, index)]
37//! username: String,
38//!
39//! #[orm(size = 100)]
40//! email: String,
41//!
42//! age: Option<i32>,
43//!
44//! #[orm(create_time)]
45//! created_at: DateTime<Utc>,
46//! }
47//!
48//! #[derive(Model, Debug, Clone, Serialize, Deserialize, FromRow)]
49//! struct Post {
50//! #[orm(primary_key)]
51//! id: Uuid,
52//!
53//! #[orm(foreign_key = "User::id")]
54//! user_id: Uuid,
55//!
56//! #[orm(size = 200)]
57//! title: String,
58//!
59//! content: String,
60//!
61//! #[orm(create_time)]
62//! created_at: DateTime<Utc>,
63//! }
64//! ```
65//!
66//! ## Supported ORM Attributes
67//!
68//! - `#[orm(primary_key)]` - Marks field as primary key
69//! - `#[orm(unique)]` - Adds UNIQUE constraint
70//! - `#[orm(index)]` - Creates database index
71//! - `#[orm(size = N)]` - Sets VARCHAR size (for String fields)
72//! - `#[orm(create_time)]` - Auto-populate with current timestamp on creation
73//! - `#[orm(update_time)]` - Auto-update timestamp on modification (future feature)
74//! - `#[orm(foreign_key = "Table::Column")]` - Defines foreign key relationship
75
76// ============================================================================
77// External Crate Imports
78// ============================================================================
79
80use std::collections::HashMap;
81
82// ============================================================================
83// Column Metadata Structure
84// ============================================================================
85
86/// Metadata information about a database column.
87///
88/// This structure contains all the information needed to generate SQL table
89/// definitions and handle type conversions between Rust and SQL. It is populated
90/// automatically by the `#[derive(Model)]` macro based on struct field types
91/// and `#[orm(...)]` attributes.
92///
93/// # Fields
94///
95/// * `name` - Column name (field name from struct)
96/// * `sql_type` - SQL type string (e.g., "INTEGER", "TEXT", "UUID", "TIMESTAMPTZ")
97/// * `is_primary_key` - Whether this is the primary key column
98/// * `is_nullable` - Whether NULL values are allowed (from Option<T>)
99/// * `create_time` - Auto-populate with CURRENT_TIMESTAMP on insert
100/// * `update_time` - Auto-update timestamp on modification (future feature)
101/// * `unique` - Whether UNIQUE constraint should be added
102/// * `index` - Whether to create an index on this column
103/// * `foreign_table` - Name of referenced table (for foreign keys)
104/// * `foreign_key` - Name of referenced column (for foreign keys)
105///
106/// # Example
107///
108/// ```rust,ignore
109/// // For this field:
110/// #[orm(size = 50, unique, index)]
111/// username: String,
112///
113/// // The generated ColumnInfo would be:
114/// ColumnInfo {
115/// name: "username",
116/// sql_type: "VARCHAR(50)",
117/// is_primary_key: false,
118/// is_nullable: false,
119/// create_time: false,
120/// update_time: false,
121/// unique: true,
122/// index: true,
123/// foreign_table: None,
124/// foreign_key: None,
125/// }
126/// ```
127///
128/// # SQL Type Mapping
129///
130/// The `sql_type` field contains the SQL type based on the Rust type:
131///
132/// - `i32` → `"INTEGER"`
133/// - `i64` → `"BIGINT"`
134/// - `String` → `"TEXT"` or `"VARCHAR(N)"` with size attribute
135/// - `bool` → `"BOOLEAN"`
136/// - `f64` → `"DOUBLE PRECISION"`
137/// - `Uuid` → `"UUID"`
138/// - `DateTime<Utc>` → `"TIMESTAMPTZ"`
139/// - `NaiveDateTime` → `"TIMESTAMP"`
140/// - `NaiveDate` → `"DATE"`
141/// - `NaiveTime` → `"TIME"`
142/// - `Option<T>` → Same as T, but `is_nullable = true`
143#[derive(Debug, Clone)]
144pub struct ColumnInfo {
145 /// The column name in the database.
146 ///
147 /// This is derived from the struct field name and is typically converted
148 /// to snake_case when generating SQL. The `r#` prefix is stripped if present
149 /// (for Rust keywords used as field names).
150 ///
151 /// # Example
152 /// ```rust,ignore
153 /// // Field: user_id: i32
154 /// name: "user_id"
155 ///
156 /// // Field: r#type: String (type is a Rust keyword)
157 /// name: "r#type" // The r# will be stripped in SQL generation
158 /// ```
159 pub name: &'static str,
160
161 /// The SQL type of the column (e.g., "TEXT", "INTEGER", "TIMESTAMPTZ").
162 ///
163 /// This string is used directly in CREATE TABLE statements. It must be
164 /// a valid SQL type for the target database.
165 ///
166 /// # Example
167 /// ```rust,ignore
168 /// // i32 field
169 /// sql_type: "INTEGER"
170 ///
171 /// // UUID field
172 /// sql_type: "UUID"
173 ///
174 /// // String with size = 100
175 /// sql_type: "VARCHAR(100)"
176 /// ```
177 pub sql_type: &'static str,
178
179 /// Whether this column is a Primary Key.
180 ///
181 /// Set to `true` via `#[orm(primary_key)]` attribute. A table should have
182 /// exactly one primary key column.
183 ///
184 /// # SQL Impact
185 /// - Adds `PRIMARY KEY` constraint
186 /// - Implicitly makes column `NOT NULL`
187 /// - Creates a unique index automatically
188 ///
189 /// # Example
190 /// ```rust,ignore
191 /// #[orm(primary_key)]
192 /// id: Uuid,
193 /// // is_primary_key: true
194 /// ```
195 pub is_primary_key: bool,
196
197 /// Whether this column allows NULL values.
198 ///
199 /// Automatically set to `true` when the field type is `Option<T>`,
200 /// otherwise `false` for non-optional types.
201 ///
202 /// # SQL Impact
203 /// - `false`: Adds `NOT NULL` constraint
204 /// - `true`: Allows NULL values
205 ///
206 /// # Example
207 /// ```rust,ignore
208 /// // Required field
209 /// username: String,
210 /// // is_nullable: false → NOT NULL
211 ///
212 /// // Optional field
213 /// middle_name: Option<String>,
214 /// // is_nullable: true → allows NULL
215 /// ```
216 pub is_nullable: bool,
217
218 /// Whether this column should be automatically populated with the creation timestamp.
219 ///
220 /// Set via `#[orm(create_time)]` attribute. When `true`, the column gets
221 /// a `DEFAULT CURRENT_TIMESTAMP` constraint.
222 ///
223 /// # SQL Impact
224 /// - Adds `DEFAULT CURRENT_TIMESTAMP`
225 /// - Column is auto-populated on INSERT
226 ///
227 /// # Example
228 /// ```rust,ignore
229 /// #[orm(create_time)]
230 /// created_at: DateTime<Utc>,
231 /// // create_time: true
232 /// // SQL: created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
233 /// ```
234 pub create_time: bool,
235
236 /// Whether this column should be automatically updated on modification.
237 ///
238 /// Set via `#[orm(update_time)]` attribute. This is a **future feature**
239 /// not yet fully implemented.
240 ///
241 /// # Future Implementation
242 /// When implemented, this will:
243 /// - Add database trigger or application-level update
244 /// - Auto-update timestamp on every UPDATE
245 ///
246 /// # Example
247 /// ```rust,ignore
248 /// #[orm(update_time)]
249 /// updated_at: DateTime<Utc>,
250 /// // update_time: true (future feature)
251 /// ```
252 pub update_time: bool,
253
254 /// Whether this column has a UNIQUE constraint.
255 ///
256 /// Set via `#[orm(unique)]` attribute. Ensures no two rows can have
257 /// the same value in this column (NULL values may be exempt depending
258 /// on database).
259 ///
260 /// # SQL Impact
261 /// - Adds `UNIQUE` constraint
262 /// - Creates a unique index automatically
263 ///
264 /// # Example
265 /// ```rust,ignore
266 /// #[orm(unique)]
267 /// username: String,
268 /// // unique: true
269 /// // SQL: username VARCHAR(255) UNIQUE
270 /// ```
271 pub unique: bool,
272
273 /// Whether an index should be created for this column.
274 ///
275 /// Set via `#[orm(index)]` attribute. Creates a database index to speed
276 /// up queries that filter or sort by this column.
277 ///
278 /// # SQL Impact
279 /// - Creates separate `CREATE INDEX` statement
280 /// - Index name: `idx_{table}_{column}`
281 ///
282 /// # Example
283 /// ```rust,ignore
284 /// #[orm(index)]
285 /// email: String,
286 /// // index: true
287 /// // SQL: CREATE INDEX idx_user_email ON user (email)
288 /// ```
289 pub index: bool,
290
291 /// The name of the foreign table, if this is a Foreign Key.
292 ///
293 /// Set via `#[orm(foreign_key = "Table::Column")]` attribute. Contains
294 /// the name of the referenced table.
295 ///
296 /// # Example
297 /// ```rust,ignore
298 /// #[orm(foreign_key = "User::id")]
299 /// user_id: Uuid,
300 /// // foreign_table: Some("User")
301 /// ```
302 pub foreign_table: Option<&'static str>,
303
304 /// The name of the foreign column, if this is a Foreign Key.
305 ///
306 /// Set via `#[orm(foreign_key = "Table::Column")]` attribute. Contains
307 /// the name of the referenced column in the foreign table.
308 ///
309 /// # Example
310 /// ```rust,ignore
311 /// #[orm(foreign_key = "User::id")]
312 /// user_id: Uuid,
313 /// // foreign_key: Some("id")
314 /// // SQL: FOREIGN KEY (user_id) REFERENCES user (id)
315 /// ```
316 pub foreign_key: Option<&'static str>,
317
318 /// Whether this field should be omitted from queries by default.
319 ///
320 /// Set via `#[orm(omit)]` attribute. When `true`, this column will be
321 /// excluded from query results unless explicitly selected.
322 ///
323 /// # Example
324 /// ```rust,ignore
325 /// #[orm(omit)]
326 /// password: String,
327 /// // omit: true
328 /// // This field will not be included in SELECT * queries
329 /// ```
330 pub omit: bool,
331
332 /// Whether this field is used for soft delete functionality.
333 ///
334 /// Set via `#[orm(soft_delete)]` attribute. When `true`, this column
335 /// will be used to track deletion timestamps. Queries will automatically
336 /// filter out records where this column is not NULL.
337 ///
338 /// # Example
339 /// ```rust,ignore
340 /// #[orm(soft_delete)]
341 /// deleted_at: Option<DateTime<Utc>>,
342 /// // soft_delete: true
343 /// // Records with deleted_at set will be excluded from queries
344 /// ```
345 pub soft_delete: bool,
346}
347
348// ============================================================================
349// Model Trait
350// ============================================================================
351
352/// The core trait defining a Database Model (Table) in Bottle ORM.
353///
354/// This trait must be implemented by all structs that represent database tables.
355/// It provides methods for retrieving table metadata, column information, and
356/// converting instances to/from database format.
357///
358/// # Automatic Implementation
359///
360/// This trait is typically implemented automatically via the `#[derive(Model)]`
361/// procedural macro. Manual implementation is possible but not recommended.
362///
363/// # Required Methods
364///
365/// * `table_name()` - Returns the table name
366/// * `columns()` - Returns column metadata
367/// * `active_columns()` - Returns column names
368/// * `to_map()` - Serializes instance to a HashMap
369///
370/// # Example with Derive
371///
372/// ```rust,ignore
373/// use bottle_orm::Model;
374/// use uuid::Uuid;
375///
376/// #[derive(Model)]
377/// struct User {
378/// #[orm(primary_key)]
379/// id: Uuid,
380/// username: String,
381/// age: i32,
382/// }
383///
384/// // Now you can use:
385/// assert_eq!(User::table_name(), "User");
386/// assert_eq!(User::active_columns(), vec!["id", "username", "age"]);
387/// ```
388///
389/// # Example Manual Implementation
390///
391/// ```rust,ignore
392/// use bottle_orm::{Model, ColumnInfo};
393/// use std::collections::HashMap;
394///
395/// struct CustomUser {
396/// id: i32,
397/// name: String,
398/// }
399///
400/// impl Model for CustomUser {
401/// fn table_name() -> &'static str {
402/// "custom_users"
403/// }
404///
405/// fn columns() -> Vec<ColumnInfo> {
406/// vec![
407/// ColumnInfo {
408/// name: "id",
409/// sql_type: "INTEGER",
410/// is_primary_key: true,
411/// is_nullable: false,
412/// create_time: false,
413/// update_time: false,
414/// unique: false,
415/// index: false,
416/// foreign_table: None,
417/// foreign_key: None,
418/// },
419/// ColumnInfo {
420/// name: "name",
421/// sql_type: "TEXT",
422/// is_primary_key: false,
423/// is_nullable: false,
424/// create_time: false,
425/// update_time: false,
426/// unique: false,
427/// index: false,
428/// foreign_table: None,
429/// foreign_key: None,
430/// },
431/// ]
432/// }
433///
434/// fn active_columns() -> Vec<&'static str> {
435/// vec!["id", "name"]
436/// }
437///
438/// fn to_map(&self) -> HashMap<String, String> {
439/// let mut map = HashMap::new();
440/// map.insert("id".to_string(), self.id.to_string());
441/// map.insert("name".to_string(), self.name.clone());
442/// map
443/// }
444/// }
445/// ```
446pub trait Model {
447 /// Returns the table name associated with this model.
448 ///
449 /// The table name is derived from the struct name and is used in all
450 /// SQL queries. By default, the derive macro uses the struct name as-is,
451 /// which is then converted to snake_case when generating SQL.
452 ///
453 /// # Returns
454 ///
455 /// A static string slice containing the table name
456 ///
457 /// # Example
458 ///
459 /// ```rust,ignore
460 /// #[derive(Model)]
461 /// struct UserProfile {
462 /// // ...
463 /// }
464 ///
465 /// // Returns "UserProfile"
466 /// // SQL will use: "user_profile" (snake_case)
467 /// assert_eq!(UserProfile::table_name(), "UserProfile");
468 /// ```
469 fn table_name() -> &'static str;
470
471 /// Returns the list of column definitions for this model.
472 ///
473 /// This method provides complete metadata about each column, including
474 /// SQL types, constraints, and relationships. The information is used
475 /// for table creation, query building, and type conversion.
476 ///
477 /// # Returns
478 ///
479 /// A vector of `ColumnInfo` structs describing each column
480 ///
481 /// # Example
482 ///
483 /// ```rust,ignore
484 /// #[derive(Model)]
485 /// struct User {
486 /// #[orm(primary_key)]
487 /// id: Uuid,
488 /// username: String,
489 /// }
490 ///
491 /// let columns = User::columns();
492 /// assert_eq!(columns.len(), 2);
493 /// assert!(columns[0].is_primary_key);
494 /// assert_eq!(columns[1].sql_type, "TEXT");
495 /// ```
496 fn columns() -> Vec<ColumnInfo>;
497
498 /// Returns the names of active columns (struct fields).
499 ///
500 /// This method returns a simple list of column names without metadata.
501 /// It's used for query building and SELECT statement generation.
502 ///
503 /// # Returns
504 ///
505 /// A vector of static string slices containing column names
506 ///
507 /// # Example
508 ///
509 /// ```rust,ignore
510 /// #[derive(Model)]
511 /// struct User {
512 /// #[orm(primary_key)]
513 /// id: Uuid,
514 /// username: String,
515 /// email: String,
516 /// }
517 ///
518 /// assert_eq!(
519 /// User::active_columns(),
520 /// vec!["id", "username", "email"]
521 /// );
522 /// ```
523 fn active_columns() -> Vec<&'static str>;
524
525 /// Converts the model instance into a value map (Column Name → String Value).
526 ///
527 /// This method serializes the model instance into a HashMap where keys are
528 /// column names and values are string representations. It's used primarily
529 /// for INSERT operations.
530 ///
531 /// # Returns
532 ///
533 /// A HashMap mapping column names to string values
534 ///
535 /// # Type Conversion
536 ///
537 /// All values are converted to strings via the `ToString` trait:
538 /// - Primitives: Direct conversion (e.g., `42` → `"42"`)
539 /// - UUID: Hyphenated format (e.g., `"550e8400-e29b-41d4-a716-446655440000"`)
540 /// - DateTime: RFC 3339 format
541 /// - Option<T>: Only included if Some, omitted if None
542 ///
543 /// # Example
544 ///
545 /// ```rust,ignore
546 /// use uuid::Uuid;
547 ///
548 /// #[derive(Model)]
549 /// struct User {
550 /// #[orm(primary_key)]
551 /// id: Uuid,
552 /// username: String,
553 /// age: i32,
554 /// }
555 ///
556 /// let user = User {
557 /// id: Uuid::new_v4(),
558 /// username: "john_doe".to_string(),
559 /// age: 25,
560 /// };
561 ///
562 /// let map = user.to_map();
563 /// assert!(map.contains_key("id"));
564 /// assert_eq!(map.get("username"), Some(&"john_doe".to_string()));
565 /// assert_eq!(map.get("age"), Some(&"25".to_string()));
566 /// ```
567 fn to_map(&self) -> HashMap<String, String>;
568}
569
570// ============================================================================
571// Tests
572// ============================================================================
573
574#[cfg(test)]
575mod tests {
576 use super::*;
577
578 #[test]
579 fn test_column_info_creation() {
580 let col = ColumnInfo {
581 name: "test_column",
582 sql_type: "INTEGER",
583 is_primary_key: true,
584 is_nullable: false,
585 create_time: false,
586 update_time: false,
587 unique: false,
588 index: false,
589 foreign_table: None,
590 foreign_key: None,
591 omit: false,
592 soft_delete: false,
593 };
594
595 assert_eq!(col.name, "test_column");
596 assert_eq!(col.sql_type, "INTEGER");
597 assert!(col.is_primary_key);
598 assert!(!col.is_nullable);
599 }
600
601 #[test]
602 fn test_column_info_with_foreign_key() {
603 let col = ColumnInfo {
604 name: "user_id",
605 sql_type: "UUID",
606 is_primary_key: false,
607 is_nullable: false,
608 create_time: false,
609 update_time: false,
610 unique: false,
611 index: false,
612 foreign_table: Some("User"),
613 foreign_key: Some("id"),
614 omit: false,
615 soft_delete: false,
616 };
617
618 assert_eq!(col.foreign_table, Some("User"));
619 assert_eq!(col.foreign_key, Some("id"));
620 }
621}