entity-core 0.8.0

Core traits and types for entity-derive
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
// SPDX-FileCopyrightText: 2025-2026 RAprogramm <andrey.rozanov.vl@gmail.com>
// SPDX-License-Identifier: MIT

//! Core traits and types for entity-derive.
//!
//! This crate provides the foundational traits and types used by entity-derive
//! generated code. It can also be used standalone for manual implementations.
//!
//! # Overview
//!
//! - [`Repository`] — Base trait for all generated repository traits
//! - [`Pagination`] — Common pagination parameters
//! - [`prelude`] — Convenient re-exports
//!
//! # Usage
//!
//! Most users should use `entity-derive` directly, which re-exports this crate.
//! For manual implementations:
//!
//! ```rust,ignore
//! use entity_core::prelude::*;
//!
//! #[async_trait]
//! impl UserRepository for MyPool {
//!     type Error = MyError;
//!     type Pool = PgPool;
//!     // ...
//! }
//! ```

#![warn(missing_docs)]
#![warn(clippy::all)]

#[cfg(feature = "outbox")]
pub mod outbox;
pub mod policy;
pub mod prelude;
#[cfg(feature = "streams")]
pub mod stream;
pub mod transaction;

/// Re-export `async_trait` for generated code.
pub use async_trait::async_trait;

/// Compare two strings in const context.
///
/// Used by generated code to verify at compile time that
/// `#[column(pg_enum = "...")]` matches the `ValueObject`'s
/// `#[value_object(pg_type = "...")]` declaration.
#[must_use]
pub const fn const_str_eq(a: &str, b: &str) -> bool {
    let a = a.as_bytes();
    let b = b.as_bytes();
    if a.len() != b.len() {
        return false;
    }
    let mut i = 0;
    while i < a.len() {
        if a[i] != b[i] {
            return false;
        }
        i += 1;
    }
    true
}

/// Base repository trait.
///
/// All generated `{Entity}Repository` traits include these associated types
/// and methods. This trait is not directly extended but serves as documentation
/// for the common interface.
///
/// # Associated Types
///
/// - `Error` — Error type for repository operations
/// - `Pool` — Underlying database pool type
///
/// # Example
///
/// Generated traits follow this pattern:
///
/// ```rust,ignore
/// #[async_trait]
/// pub trait UserRepository: Send + Sync {
///     type Error: std::error::Error + Send + Sync;
///     type Pool;
///
///     fn pool(&self) -> &Self::Pool;
///     async fn create(&self, dto: CreateUserRequest) -> Result<User, Self::Error>;
///     async fn find_by_id(&self, id: Uuid) -> Result<Option<User>, Self::Error>;
///     // ...
/// }
/// ```
pub trait Repository: Send + Sync {
    /// Error type for repository operations.
    ///
    /// Must implement `std::error::Error + Send + Sync` for async
    /// compatibility.
    type Error: std::error::Error + Send + Sync;

    /// Underlying database pool type.
    ///
    /// Enables access to the pool for transactions and custom queries.
    type Pool;

    /// Get reference to the underlying database pool.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let pool = repo.pool();
    /// let mut tx = pool.begin().await?;
    /// // Custom operations...
    /// tx.commit().await?;
    /// ```
    fn pool(&self) -> &Self::Pool;
}

/// Pagination parameters for list operations.
///
/// Used by `list` and `query` methods to control result pagination.
///
/// # Example
///
/// ```rust
/// use entity_core::Pagination;
///
/// let page = Pagination::new(10, 0); // First 10 items
/// let next = Pagination::new(10, 10); // Next 10 items
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Pagination {
    /// Maximum number of results to return.
    pub limit: i64,

    /// Number of results to skip.
    pub offset: i64
}

impl Pagination {
    /// Create new pagination parameters.
    ///
    /// # Arguments
    ///
    /// * `limit` — Maximum results to return
    /// * `offset` — Number of results to skip
    #[must_use]
    pub const fn new(limit: i64, offset: i64) -> Self {
        Self {
            limit,
            offset
        }
    }

    /// Create pagination for a specific page.
    ///
    /// # Arguments
    ///
    /// * `page` — Page number (0-indexed)
    /// * `per_page` — Items per page
    ///
    /// # Example
    ///
    /// ```rust
    /// use entity_core::Pagination;
    ///
    /// let page_0 = Pagination::page(0, 25); // offset=0, limit=25
    /// let page_2 = Pagination::page(2, 25); // offset=50, limit=25
    /// ```
    #[must_use]
    pub const fn page(page: i64, per_page: i64) -> Self {
        Self {
            limit:  per_page,
            offset: page * per_page
        }
    }
}

impl Default for Pagination {
    fn default() -> Self {
        Self {
            limit:  100,
            offset: 0
        }
    }
}

/// Sort direction for ordered queries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SortDirection {
    /// Ascending order (A-Z, 0-9, oldest first).
    #[default]
    Asc,

    /// Descending order (Z-A, 9-0, newest first).
    Desc
}

impl SortDirection {
    /// Convert to SQL keyword.
    #[must_use]
    pub const fn as_sql(&self) -> &'static str {
        match self {
            Self::Asc => "ASC",
            Self::Desc => "DESC"
        }
    }
}

/// Kind of lifecycle event.
///
/// Used by generated event enums to categorize events.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EventKind {
    /// Entity was created.
    Created,

    /// Entity was updated.
    Updated,

    /// Entity was soft-deleted.
    SoftDeleted,

    /// Entity was hard-deleted (permanently removed).
    HardDeleted,

    /// Entity was restored from soft-delete.
    Restored
}

impl EventKind {
    /// Check if this is a delete event (soft or hard).
    #[must_use]
    pub const fn is_delete(&self) -> bool {
        matches!(self, Self::SoftDeleted | Self::HardDeleted)
    }

    /// Check if this is a mutation event (create, update, delete).
    #[must_use]
    pub const fn is_mutation(&self) -> bool {
        !matches!(self, Self::Restored)
    }
}

/// Base trait for entity lifecycle events.
///
/// Generated event enums implement this trait, enabling generic
/// event handling and dispatching.
///
/// # Example
///
/// ```rust,ignore
/// fn handle_event<E: EntityEvent>(event: &E) {
///     println!("Event {:?} for entity {:?}", event.kind(), event.entity_id());
/// }
/// ```
pub trait EntityEvent: Send + Sync + std::fmt::Debug {
    /// Type of entity ID.
    type Id;

    /// Get the kind of event.
    fn kind(&self) -> EventKind;

    /// Get the entity ID associated with this event.
    fn entity_id(&self) -> &Self::Id;
}

/// Kind of business command.
///
/// Used by generated command enums to categorize commands for auditing
/// and routing purposes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CommandKind {
    /// Creates a new entity (e.g., Register, Create).
    Create,

    /// Modifies an existing entity (e.g., `UpdateEmail`, `ChangeStatus`).
    Update,

    /// Removes an entity (e.g., Delete, Deactivate).
    Delete,

    /// Custom business operation that doesn't fit CRUD.
    Custom
}

impl CommandKind {
    /// Check if this command creates an entity.
    #[must_use]
    pub const fn is_create(&self) -> bool {
        matches!(self, Self::Create)
    }

    /// Check if this command modifies state.
    #[must_use]
    pub const fn is_mutation(&self) -> bool {
        !matches!(self, Self::Custom)
    }
}

/// Base trait for entity commands.
///
/// Generated command enums implement this trait, enabling generic
/// command handling, auditing, and dispatching.
///
/// # Example
///
/// ```rust,ignore
/// fn audit_command<C: EntityCommand>(cmd: &C) {
///     log::info!("Executing command: {} ({:?})", cmd.name(), cmd.kind());
/// }
/// ```
pub trait EntityCommand: Send + Sync + std::fmt::Debug {
    /// Get the kind of command for categorization.
    fn kind(&self) -> CommandKind;

    /// Get the command name as a string for logging/auditing.
    fn name(&self) -> &'static str;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pagination_new() {
        let p = Pagination::new(50, 100);
        assert_eq!(p.limit, 50);
        assert_eq!(p.offset, 100);
    }

    #[test]
    fn pagination_page() {
        let p = Pagination::page(2, 25);
        assert_eq!(p.limit, 25);
        assert_eq!(p.offset, 50);
    }

    #[test]
    fn pagination_default() {
        let p = Pagination::default();
        assert_eq!(p.limit, 100);
        assert_eq!(p.offset, 0);
    }

    #[test]
    fn sort_direction_sql() {
        assert_eq!(SortDirection::Asc.as_sql(), "ASC");
        assert_eq!(SortDirection::Desc.as_sql(), "DESC");
    }

    #[test]
    fn sort_direction_default() {
        assert_eq!(SortDirection::default(), SortDirection::Asc);
    }

    #[test]
    fn event_kind_is_delete() {
        assert!(!EventKind::Created.is_delete());
        assert!(!EventKind::Updated.is_delete());
        assert!(EventKind::SoftDeleted.is_delete());
        assert!(EventKind::HardDeleted.is_delete());
        assert!(!EventKind::Restored.is_delete());
    }

    #[test]
    fn event_kind_is_mutation() {
        assert!(EventKind::Created.is_mutation());
        assert!(EventKind::Updated.is_mutation());
        assert!(EventKind::SoftDeleted.is_mutation());
        assert!(EventKind::HardDeleted.is_mutation());
        assert!(!EventKind::Restored.is_mutation());
    }

    #[test]
    fn command_kind_is_create() {
        assert!(CommandKind::Create.is_create());
        assert!(!CommandKind::Update.is_create());
        assert!(!CommandKind::Delete.is_create());
        assert!(!CommandKind::Custom.is_create());
    }

    #[test]
    fn command_kind_is_mutation() {
        assert!(CommandKind::Create.is_mutation());
        assert!(CommandKind::Update.is_mutation());
        assert!(CommandKind::Delete.is_mutation());
        assert!(!CommandKind::Custom.is_mutation());
    }

    #[test]
    fn const_str_eq_equal_strings() {
        assert!(const_str_eq("order_status", "order_status"));
        assert!(const_str_eq("", ""));
    }

    #[test]
    fn const_str_eq_different_lengths() {
        assert!(!const_str_eq("order", "order_status"));
        assert!(!const_str_eq("order_status", ""));
    }

    #[test]
    fn const_str_eq_same_length_different_content() {
        assert!(!const_str_eq("order_status", "order_states"));
        assert!(!const_str_eq("abc", "abd"));
    }

    #[test]
    fn const_str_eq_in_const_context() {
        const OK: bool = const_str_eq("user_role", "user_role");
        const MISMATCH: bool = const_str_eq("user_role", "user_rank");
        assert_eq!((OK, MISMATCH), (true, false));
    }
}