prax-orm 0.6.4

A next-generation, type-safe ORM for Rust inspired by Prisma
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
#![allow(dead_code, unused, clippy::type_complexity)]
//! # Relations Examples
//!
//! This example demonstrates working with relations in Prax:
//! - One-to-one relations
//! - One-to-many relations
//! - Many-to-many relations
//! - Self-referential relations
//! - Eager loading with include()
//! - Nested writes
//!
//! ## Running this example
//!
//! ```bash
//! cargo run --example relations
//! ```

// Mock types representing generated models
#[derive(Debug, Clone)]
struct User {
    id: i32,
    email: String,
    name: Option<String>,
    // Relations (loaded on demand)
    posts: Option<Vec<Post>>,
    profile: Option<Box<Profile>>,
}

#[derive(Debug, Clone)]
struct Post {
    id: i32,
    title: String,
    content: Option<String>,
    author_id: i32,
    // Relations
    author: Option<Box<User>>,
    tags: Option<Vec<Tag>>,
    comments: Option<Vec<Comment>>,
}

#[derive(Debug, Clone)]
struct Profile {
    id: i32,
    bio: Option<String>,
    user_id: i32,
    // Relations
    user: Option<Box<User>>,
}

#[derive(Debug, Clone)]
struct Tag {
    id: i32,
    name: String,
    // Relations
    posts: Option<Vec<Post>>,
}

#[derive(Debug, Clone)]
struct Comment {
    id: i32,
    content: String,
    post_id: i32,
    parent_id: Option<i32>,
    // Relations
    post: Option<Box<Post>>,
    parent: Option<Box<Comment>>,
    replies: Option<Vec<Comment>>,
}

// Mock query builder for demonstration
struct MockClient;

impl MockClient {
    fn user(&self) -> UserQuery {
        UserQuery
    }

    fn post(&self) -> PostQuery {
        PostQuery
    }
}

struct UserQuery;

impl UserQuery {
    fn find_unique(self) -> UserFindUnique {
        UserFindUnique { includes: vec![] }
    }

    fn find_many(self) -> UserFindMany {
        UserFindMany { includes: vec![] }
    }

    fn create(self, _data: CreateUserData) -> UserCreate {
        UserCreate
    }
}

struct UserFindUnique {
    includes: Vec<String>,
}

impl UserFindUnique {
    #[allow(non_snake_case)]
    fn r#where(self, _filter: &str) -> Self {
        self
    }

    fn include(mut self, relation: &str) -> Self {
        self.includes.push(relation.to_string());
        self
    }

    async fn exec(self) -> Result<Option<User>, Box<dyn std::error::Error>> {
        // Mock response with included relations
        let mut user = User {
            id: 1,
            email: "alice@example.com".to_string(),
            name: Some("Alice".to_string()),
            posts: None,
            profile: None,
        };

        if self.includes.contains(&"posts".to_string()) {
            user.posts = Some(vec![
                Post {
                    id: 1,
                    title: "First Post".to_string(),
                    content: Some("Content...".to_string()),
                    author_id: 1,
                    author: None,
                    tags: None,
                    comments: None,
                },
                Post {
                    id: 2,
                    title: "Second Post".to_string(),
                    content: Some("More content...".to_string()),
                    author_id: 1,
                    author: None,
                    tags: None,
                    comments: None,
                },
            ]);
        }

        if self.includes.contains(&"profile".to_string()) {
            user.profile = Some(Box::new(Profile {
                id: 1,
                bio: Some("Software developer".to_string()),
                user_id: 1,
                user: None,
            }));
        }

        Ok(Some(user))
    }
}

struct UserFindMany {
    includes: Vec<String>,
}

impl UserFindMany {
    fn include(mut self, relation: &str) -> Self {
        self.includes.push(relation.to_string());
        self
    }

    fn take(self, _count: usize) -> Self {
        self
    }

    async fn exec(self) -> Result<Vec<User>, Box<dyn std::error::Error>> {
        Ok(vec![User {
            id: 1,
            email: "alice@example.com".to_string(),
            name: Some("Alice".to_string()),
            posts: if self.includes.contains(&"posts".to_string()) {
                Some(vec![])
            } else {
                None
            },
            profile: None,
        }])
    }
}

struct CreateUserData {
    email: String,
    name: Option<String>,
    posts: Option<NestedPostCreate>,
    profile: Option<NestedProfileCreate>,
}

struct NestedPostCreate {
    data: Vec<CreatePostData>,
}

struct CreatePostData {
    title: String,
    content: Option<String>,
}

struct NestedProfileCreate {
    data: CreateProfileData,
}

struct CreateProfileData {
    bio: Option<String>,
}

struct UserCreate;

impl UserCreate {
    fn include(self, _relation: &str) -> Self {
        self
    }

    async fn exec(self) -> Result<User, Box<dyn std::error::Error>> {
        Ok(User {
            id: 3,
            email: "new@example.com".to_string(),
            name: Some("New User".to_string()),
            posts: Some(vec![Post {
                id: 10,
                title: "My First Post".to_string(),
                content: Some("Hello world!".to_string()),
                author_id: 3,
                author: None,
                tags: None,
                comments: None,
            }]),
            profile: Some(Box::new(Profile {
                id: 3,
                bio: Some("Just joined!".to_string()),
                user_id: 3,
                user: None,
            })),
        })
    }
}

struct PostQuery;

impl PostQuery {
    fn find_unique(self) -> PostFindUnique {
        PostFindUnique { includes: vec![] }
    }
}

struct PostFindUnique {
    includes: Vec<String>,
}

impl PostFindUnique {
    #[allow(non_snake_case)]
    fn r#where(self, _filter: &str) -> Self {
        self
    }

    fn include(mut self, relation: &str) -> Self {
        self.includes.push(relation.to_string());
        self
    }

    async fn exec(self) -> Result<Option<Post>, Box<dyn std::error::Error>> {
        let mut post = Post {
            id: 1,
            title: "First Post".to_string(),
            content: Some("Content...".to_string()),
            author_id: 1,
            author: None,
            tags: None,
            comments: None,
        };

        if self.includes.contains(&"author".to_string()) {
            post.author = Some(Box::new(User {
                id: 1,
                email: "alice@example.com".to_string(),
                name: Some("Alice".to_string()),
                posts: None,
                profile: None,
            }));
        }

        if self.includes.contains(&"tags".to_string()) {
            post.tags = Some(vec![
                Tag {
                    id: 1,
                    name: "rust".to_string(),
                    posts: None,
                },
                Tag {
                    id: 2,
                    name: "tutorial".to_string(),
                    posts: None,
                },
            ]);
        }

        if self.includes.contains(&"comments".to_string()) {
            post.comments = Some(vec![Comment {
                id: 1,
                content: "Great post!".to_string(),
                post_id: 1,
                parent_id: None,
                post: None,
                parent: None,
                replies: Some(vec![Comment {
                    id: 2,
                    content: "Thanks!".to_string(),
                    post_id: 1,
                    parent_id: Some(1),
                    post: None,
                    parent: None,
                    replies: None,
                }]),
            }]);
        }

        Ok(Some(post))
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("=== Prax Relations Examples ===\n");

    let client = MockClient;

    // =========================================================================
    // ONE-TO-MANY: User -> Posts
    // =========================================================================
    println!("--- One-to-Many: User with Posts ---");

    let user = client
        .user()
        .find_unique()
        .r#where("id = 1")
        .include("posts")
        .exec()
        .await?
        .expect("User not found");

    println!(
        "User: {} ({})",
        user.email,
        user.name.as_deref().unwrap_or("")
    );
    if let Some(posts) = &user.posts {
        println!("Posts ({}):", posts.len());
        for post in posts {
            println!("  - {} (id: {})", post.title, post.id);
        }
    }
    println!();

    // =========================================================================
    // ONE-TO-ONE: User -> Profile
    // =========================================================================
    println!("--- One-to-One: User with Profile ---");

    let user = client
        .user()
        .find_unique()
        .r#where("id = 1")
        .include("profile")
        .exec()
        .await?
        .expect("User not found");

    println!("User: {}", user.email);
    if let Some(profile) = &user.profile {
        println!("Profile bio: {:?}", profile.bio);
    }
    println!();

    // =========================================================================
    // MULTIPLE RELATIONS
    // =========================================================================
    println!("--- Multiple Relations ---");

    let user = client
        .user()
        .find_unique()
        .r#where("id = 1")
        .include("posts")
        .include("profile")
        .exec()
        .await?
        .expect("User not found");

    println!("User: {}", user.email);
    println!("Has posts: {}", user.posts.is_some());
    println!("Has profile: {}", user.profile.is_some());
    println!();

    // =========================================================================
    // MANY-TO-MANY: Post -> Tags
    // =========================================================================
    println!("--- Many-to-Many: Post with Tags ---");

    let post = client
        .post()
        .find_unique()
        .r#where("id = 1")
        .include("tags")
        .exec()
        .await?
        .expect("Post not found");

    println!("Post: {}", post.title);
    if let Some(tags) = &post.tags {
        println!(
            "Tags: {:?}",
            tags.iter().map(|t| &t.name).collect::<Vec<_>>()
        );
    }
    println!();

    // =========================================================================
    // REVERSE RELATION: Post -> Author
    // =========================================================================
    println!("--- Reverse Relation: Post with Author ---");

    let post = client
        .post()
        .find_unique()
        .r#where("id = 1")
        .include("author")
        .exec()
        .await?
        .expect("Post not found");

    println!("Post: {}", post.title);
    if let Some(author) = &post.author {
        println!(
            "Author: {} ({})",
            author.email,
            author.name.as_deref().unwrap_or("")
        );
    }
    println!();

    // =========================================================================
    // NESTED RELATIONS: Post with Comments and Replies
    // =========================================================================
    println!("--- Nested Relations: Post with Comments ---");

    let post = client
        .post()
        .find_unique()
        .r#where("id = 1")
        .include("comments")
        .exec()
        .await?
        .expect("Post not found");

    println!("Post: {}", post.title);
    if let Some(comments) = &post.comments {
        for comment in comments {
            println!("  Comment: {}", comment.content);
            if let Some(replies) = &comment.replies {
                for reply in replies {
                    println!("    Reply: {}", reply.content);
                }
            }
        }
    }
    println!();

    // =========================================================================
    // NESTED WRITES: Create User with Posts and Profile
    // =========================================================================
    println!("--- Nested Writes: Create User with Relations ---");

    let new_user = client
        .user()
        .create(CreateUserData {
            email: "new@example.com".to_string(),
            name: Some("New User".to_string()),
            posts: Some(NestedPostCreate {
                data: vec![CreatePostData {
                    title: "My First Post".to_string(),
                    content: Some("Hello world!".to_string()),
                }],
            }),
            profile: Some(NestedProfileCreate {
                data: CreateProfileData {
                    bio: Some("Just joined!".to_string()),
                },
            }),
        })
        .include("posts")
        .include("profile")
        .exec()
        .await?;

    println!("Created user: {} (id: {})", new_user.email, new_user.id);
    if let Some(posts) = &new_user.posts {
        println!("With {} post(s)", posts.len());
    }
    if let Some(profile) = &new_user.profile {
        println!("With profile: {:?}", profile.bio);
    }
    println!();

    // =========================================================================
    // SCHEMA EXAMPLE
    // =========================================================================
    println!("--- Relation Schema Example ---");

    let schema_example = r#"
// One-to-Many: User has many Posts
model User {
    id    Int    @id @auto
    email String @unique
    posts Post[]   // One-to-many relation
}

model Post {
    id       Int  @id @auto
    title    String
    authorId Int
    author   User @relation(fields: [authorId], references: [id])
}

// One-to-One: User has one Profile
model Profile {
    id     Int    @id @auto
    bio    String?
    userId Int    @unique  // Unique makes it one-to-one
    user   User   @relation(fields: [userId], references: [id])
}

// Many-to-Many: Post has many Tags, Tag has many Posts
model Tag {
    id    Int    @id @auto
    name  String @unique
    posts Post[] @relation("PostTags")
}

// Self-referential: Comment replies
model Comment {
    id       Int       @id @auto
    content  String
    parentId Int?
    parent   Comment?  @relation("CommentReplies", fields: [parentId], references: [id])
    replies  Comment[] @relation("CommentReplies")
}
"#;

    println!("Schema for relations:");
    println!("{}", schema_example);

    println!("=== All examples completed successfully! ===");

    Ok(())
}