entity-derive 0.1.1

Derive macro for generating DTOs, repositories, and SQL from a single entity definition
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
432
433
434
435
<a id="top"></a>

<p align="center">
  <h1 align="center">entity-derive</h1>
  <p align="center">
    <strong>One macro to rule them all</strong>
  </p>
  <p align="center">
    Generate DTOs, repositories, mappers, and SQL from a single entity definition
  </p>
</p>

<p align="center">
  <a href="https://crates.io/crates/entity-derive">
    <img src="https://img.shields.io/crates/v/entity-derive.svg" alt="Crates.io"/>
  </a>
  <a href="https://docs.rs/entity-derive">
    <img src="https://docs.rs/entity-derive/badge.svg" alt="Documentation"/>
  </a>
  <a href="https://github.com/RAprogramm/entity-derive/actions">
    <img src="https://github.com/RAprogramm/entity-derive/workflows/CI/badge.svg" alt="CI Status"/>
  </a>
  <a href="https://codecov.io/gh/RAprogramm/entity-derive">
    <img src="https://codecov.io/gh/RAprogramm/entity-derive/graph/badge.svg?token=HGuwZf0REV" alt="Coverage"/>
  </a>
  <a href="https://github.com/RAprogramm/entity-derive/blob/main/LICENSE">
    <img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="License: MIT"/>
  </a>
  <a href="https://api.reuse.software/info/github.com/RAprogramm/entity-derive">
    <img src="https://api.reuse.software/badge/github.com/RAprogramm/entity-derive" alt="REUSE Compliant"/>
  </a>
</p>

---

## Table of Contents

- [The Problem]#the-problem
- [The Solution]#the-solution
- [Features]#features
- [Installation]#installation
- [Quick Start]#quick-start
- [Attribute Reference]#attribute-reference
- [Generated Code]#generated-code
- [Architecture]#architecture
- [Comparison]#comparison
- [Code Coverage]#code-coverage
- [Documentation]#documentation
- [MSRV]#msrv
- [License]#license
- [Contributing]#contributing

---

## The Problem

Building a typical CRUD application requires writing the same boilerplate over and over:

```rust,ignore
// 1. Your domain entity
pub struct User {
    pub id: Uuid,
    pub name: String,
    pub email: String,
    pub password_hash: String,
    pub created_at: DateTime<Utc>,
}

// 2. DTO for creating (without id, without auto-generated fields)
pub struct CreateUserRequest {
    pub name: String,
    pub email: String,
}

// 3. DTO for updating (all fields optional for partial updates)
pub struct UpdateUserRequest {
    pub name: Option<String>,
    pub email: Option<String>,
}

// 4. DTO for API response (without sensitive fields)
pub struct UserResponse {
    pub id: Uuid,
    pub name: String,
    pub email: String,
    pub created_at: DateTime<Utc>,
}

// 5. Database row struct
pub struct UserRow { /* ... */ }

// 6. Insertable struct
pub struct InsertableUser { /* ... */ }

// 7. Repository trait
pub trait UserRepository { /* ... */ }

// 8. SQL implementation
impl UserRepository for PgPool { /* ... */ }

// 9. Six From implementations for mapping between types
impl From<UserRow> for User { /* ... */ }
impl From<User> for UserResponse { /* ... */ }
// ... and more
```

**That's 200+ lines of boilerplate for a single entity.**

<div align="right"><a href="#top">⬆ back to top</a></div>

## The Solution

```rust,ignore
use entity_derive::Entity;

#[derive(Entity)]
#[entity(table = "users", schema = "core")]
pub struct User {
    #[id]
    pub id: Uuid,

    #[field(create, update, response)]
    pub name: String,

    #[field(create, update, response)]
    pub email: String,

    #[field(skip)]
    pub password_hash: String,

    #[field(response)]
    #[auto]
    pub created_at: DateTime<Utc>,
}
```

**Done.** The macro generates everything else.

<div align="right"><a href="#top">⬆ back to top</a></div>

## Features

- **Zero Runtime Cost** — All code generation happens at compile time
- **Type Safe** — Change a field type once, everything updates automatically
- **Flexible Attributes** — Fine-grained control over what goes where
- **SQL Generation** — Complete CRUD operations for PostgreSQL (via sqlx)
- **Partial Updates** — Non-optional fields automatically wrapped in `Option` for updates
- **Security by Default**`#[field(skip)]` ensures sensitive data never leaks to responses

<div align="right"><a href="#top">⬆ back to top</a></div>

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
entity-derive = "0.1"

# Required peer dependencies
uuid = { version = "1", features = ["v7"] }
chrono = { version = "0.4", features = ["serde"] }
serde = { version = "1", features = ["derive"] }
async-trait = "0.1"

# For database support
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres"] }
```

<div align="right"><a href="#top">⬆ back to top</a></div>

## Quick Start

```rust,ignore
use entity_derive::Entity;
use uuid::Uuid;
use chrono::{DateTime, Utc};

#[derive(Entity)]
#[entity(table = "posts", schema = "blog")]
pub struct Post {
    #[id]
    pub id: Uuid,

    #[field(create, update, response)]
    pub title: String,

    #[field(create, update, response)]
    pub content: String,

    #[field(create, response)]
    pub author_id: Uuid,

    #[field(response)]
    #[auto]
    pub created_at: DateTime<Utc>,

    #[field(response)]
    #[auto]
    pub updated_at: DateTime<Utc>,
}

// Now you have:
// - CreatePostRequest { title, content, author_id }
// - UpdatePostRequest { title?, content? }
// - PostResponse { id, title, content, author_id, created_at, updated_at }
// - PostRow, InsertablePost
// - PostRepository trait
// - impl PostRepository for sqlx::PgPool
```

<div align="right"><a href="#top">⬆ back to top</a></div>

## Attribute Reference

### Entity-Level: `#[entity(...)]`

| Attribute | Required | Default | Description |
|-----------|----------|---------|-------------|
| `table` | Yes || Database table name |
| `schema` | No | `"public"` | Database schema |
| `sql` | No | `"full"` | SQL generation level |

#### SQL Levels

| Level | Repository Trait | PgPool Impl | Use Case |
|-------|-----------------|-------------|----------|
| `full` | Yes | Yes | Simple entities with standard CRUD |
| `trait` | Yes | No | Custom queries (joins, CTEs, full-text search) |
| `none` | No | No | DTOs only, no database layer |

### Field-Level Attributes

| Attribute | Effect |
|-----------|--------|
| `#[id]` | Primary key, auto-generated UUID (v7), always in response |
| `#[auto]` | Auto-generated field (timestamps), excluded from create/update |
| `#[field(create)]` | Include in `CreateRequest` |
| `#[field(update)]` | Include in `UpdateRequest` (wrapped in `Option` if not already) |
| `#[field(response)]` | Include in `Response` |
| `#[field(skip)]` | Exclude from all DTOs (for sensitive data) |

Combine multiple: `#[field(create, update, response)]`

<div align="right"><a href="#top">⬆ back to top</a></div>

## Generated Code

For a `User` entity, the macro generates:

### DTOs

```rust,ignore
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateUserRequest {
    pub name: String,
    pub email: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateUserRequest {
    pub name: Option<String>,
    pub email: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserResponse {
    pub id: Uuid,
    pub name: String,
    pub email: String,
    pub created_at: DateTime<Utc>,
}
```

### Repository Trait

```rust,ignore
#[async_trait]
pub trait UserRepository: Send + Sync {
    type Error: std::error::Error + Send + Sync;

    async fn create(&self, dto: CreateUserRequest) -> Result<User, Self::Error>;
    async fn find_by_id(&self, id: Uuid) -> Result<Option<User>, Self::Error>;
    async fn update(&self, id: Uuid, dto: UpdateUserRequest) -> Result<User, Self::Error>;
    async fn delete(&self, id: Uuid) -> Result<bool, Self::Error>;
    async fn list(&self, limit: i64, offset: i64) -> Result<Vec<User>, Self::Error>;
}
```

### SQL Implementation

```rust,ignore
#[async_trait]
impl UserRepository for sqlx::PgPool {
    type Error = sqlx::Error;

    async fn create(&self, dto: CreateUserRequest) -> Result<User, Self::Error> {
        let entity = User::from(dto);
        let insertable = InsertableUser::from(&entity);
        sqlx::query(
            "INSERT INTO core.users (id, name, email, password_hash, created_at) \
             VALUES ($1, $2, $3, $4, $5)"
        )
        .bind(insertable.id)
        .bind(&insertable.name)
        .bind(&insertable.email)
        .bind(&insertable.password_hash)
        .bind(insertable.created_at)
        .execute(self)
        .await?;
        Ok(entity)
    }

    // ... find_by_id, update, delete, list
}
```

### Mappers

```rust,ignore
impl From<UserRow> for User { /* ... */ }
impl From<CreateUserRequest> for User { /* ... */ }
impl From<User> for UserResponse { /* ... */ }
impl From<&User> for InsertableUser { /* ... */ }
// ... and more
```

<div align="right"><a href="#top">⬆ back to top</a></div>

## Architecture

```text
┌─────────────────────────────────────────────────────────────┐
│                     Your Code                               │
│  #[derive(Entity)]                                          │
│  pub struct User { ... }                                    │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│                   entity-derive                             │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────────────┐  │
│  │   Parser    │  │ Generators  │  │      Output         │  │
│  │             │  │             │  │                     │  │
│  │ EntityDef   │─▶│ dto.rs      │─▶│ CreateRequest       │  │
│  │ FieldDef    │  │ row.rs      │  │ UpdateRequest       │  │
│  │ SqlLevel    │  │ repository  │  │ Response            │  │
│  │             │  │ sql.rs      │  │ Row, Insertable     │  │
│  │             │  │ mappers.rs  │  │ Repository trait    │  │
│  │             │  │             │  │ PgPool impl         │  │
│  │             │  │             │  │ From impls          │  │
│  └─────────────┘  └─────────────┘  └─────────────────────┘  │
└─────────────────────────────────────────────────────────────┘
```

<div align="right"><a href="#top">⬆ back to top</a></div>

## Comparison

| Aspect | Without entity-derive | With entity-derive |
|--------|----------------------|-------------------|
| Lines of code | 200+ per entity | ~15 per entity |
| Type safety | Manual sync required | Automatic |
| Sensitive data leaks | Possible | Prevented by `#[field(skip)]` |
| Partial updates | Manual wrapping | Automatic |
| SQL bindings | Error-prone | Always in sync |
| Refactoring | Update 8+ places | Update 1 place |

<div align="right"><a href="#top">⬆ back to top</a></div>

## Code Coverage

We maintain high test coverage to ensure reliability. Below are visual representations of our codebase coverage:

### Sunburst

The inner circle represents the entire project. Moving outward: folders, then individual files. Size = number of statements, color = coverage percentage.

<p align="center">
  <a href="https://codecov.io/gh/RAprogramm/entity-derive">
    <img src="https://codecov.io/gh/RAprogramm/entity-derive/graphs/sunburst.svg?token=HGuwZf0REV" alt="Coverage Sunburst"/>
  </a>
</p>

### Grid

Each block represents a file. Size = number of statements, color = coverage level (green = high, red = low).

<p align="center">
  <a href="https://codecov.io/gh/RAprogramm/entity-derive">
    <img src="https://codecov.io/gh/RAprogramm/entity-derive/graphs/tree.svg?token=HGuwZf0REV" alt="Coverage Grid"/>
  </a>
</p>

### Icicle

Hierarchical view: top = entire project, descending through folders to individual files. Size and color represent statements and coverage.

<p align="center">
  <a href="https://codecov.io/gh/RAprogramm/entity-derive">
    <img src="https://codecov.io/gh/RAprogramm/entity-derive/graphs/icicle.svg?token=HGuwZf0REV" alt="Coverage Icicle"/>
  </a>
</p>

<div align="right"><a href="#top">⬆ back to top</a></div>

## Documentation

- [**API Reference**]https://docs.rs/entity-derive — Full API documentation
- [**Wiki**]https://github.com/RAprogramm/entity-derive/wiki — Guides and examples:
  - [All Attributes Explained]https://github.com/RAprogramm/entity-derive/wiki/Attributes
  - [Real-World Examples]https://github.com/RAprogramm/entity-derive/wiki/Examples
  - [Custom SQL Queries]https://github.com/RAprogramm/entity-derive/wiki/Custom-SQL
  - [Integration with Axum/Actix]https://github.com/RAprogramm/entity-derive/wiki/Web-Frameworks
  - [Best Practices]https://github.com/RAprogramm/entity-derive/wiki/Best-Practices

<div align="right"><a href="#top">⬆ back to top</a></div>

## MSRV

Minimum Supported Rust Version: **1.92** (Edition 2024)

<div align="right"><a href="#top">⬆ back to top</a></div>

## License

Licensed under the [MIT License](https://github.com/RAprogramm/entity-derive/blob/main/LICENSE).

<div align="right"><a href="#top">⬆ back to top</a></div>

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

<div align="right"><a href="#top">⬆ back to top</a></div>