prax-orm 0.6.5

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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! Integration tests for schema parsing and validation.
//!
//! These tests verify that the schema parser correctly handles various
//! schema definitions and edge cases.

use prax_orm::schema::{PraxConfig, parse_schema, validate_schema};

/// Test basic model parsing with all common field types
#[test]
fn test_parse_model_with_all_field_types() {
    let schema = parse_schema(
        r#"
        model AllTypes {
            id        Int       @id @auto
            bigInt    BigInt
            float     Float
            decimal   Decimal
            string    String
            boolean   Boolean
            dateTime  DateTime
            date      Date
            time      Time
            json      Json
            bytes     Bytes
            uuid      Uuid
            optional  String?
            list      String[]
        }
    "#,
    )
    .expect("Failed to parse schema");

    let model = schema.get_model("AllTypes").expect("Model not found");
    assert_eq!(model.fields.len(), 14);
}

/// Test model with all field attributes
#[test]
fn test_parse_model_with_all_attributes() {
    let schema = parse_schema(
        r#"
        model User {
            id         Int      @id @auto
            email      String   @unique @index
            name       String?  @default("Anonymous")
            password   String   @omit
            createdAt  DateTime @default(now())
            updatedAt  DateTime @updated_at
            role       String   @map("user_role")
            bio        String?  @db.Text

            @@map("users")
            @@index([email, name])
            @@unique([email])
        }
    "#,
    )
    .expect("Failed to parse schema");

    let model = schema.get_model("User").expect("Model not found");

    // Check id field has @id and @auto
    let id_field = model.fields.get("id").expect("id field not found");
    assert!(id_field.attributes.iter().any(|a| a.name.name == "id"));
    assert!(id_field.attributes.iter().any(|a| a.name.name == "auto"));

    // Check model has @@map attribute
    assert!(model.attributes.iter().any(|a| a.name.name == "map"));
}

/// Test relation parsing
#[test]
fn test_parse_relations() {
    let schema = parse_schema(
        r#"
        model User {
            id       Int       @id @auto
            email    String    @unique
            posts    Post[]
            profile  Profile?
        }

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

        model Profile {
            id     Int    @id @auto
            bio    String?
            userId Int    @unique
            user   User   @relation(fields: [userId], references: [id])
        }
    "#,
    )
    .expect("Failed to parse schema");

    assert_eq!(schema.model_names().count(), 3);

    // Check User has posts relation
    let user = schema.get_model("User").unwrap();
    assert!(user.fields.contains_key("posts"));
    assert!(user.fields.contains_key("profile"));

    // Check Post has author relation with @relation attribute
    let post = schema.get_model("Post").unwrap();
    let author_field = post.fields.get("author").expect("author field not found");
    assert!(
        author_field
            .attributes
            .iter()
            .any(|a| a.name.name == "relation")
    );
}

/// Test self-referential relations
#[test]
fn test_parse_self_referential_relation() {
    let schema = parse_schema(
        r#"
        model Category {
            id       Int         @id @auto
            name     String
            parentId Int?
            parent   Category?   @relation("CategoryTree", fields: [parentId], references: [id])
            children Category[]  @relation("CategoryTree")
        }
    "#,
    )
    .expect("Failed to parse schema");

    let category = schema.get_model("Category").unwrap();
    assert_eq!(category.fields.len(), 5); // id, name, parentId, parent, children
}

/// Test enum parsing
#[test]
fn test_parse_enums() {
    let schema = parse_schema(
        r#"
        enum Role {
            User
            Admin
            Moderator
        }

        enum Status {
            Draft
            Published
            Archived

            @@map("post_status")
        }

        model User {
            id   Int  @id @auto
            role Role @default(User)
        }
    "#,
    )
    .expect("Failed to parse schema");

    assert_eq!(schema.enum_names().count(), 2);

    let role = schema.get_enum("Role").unwrap();
    assert_eq!(role.variants.len(), 3);

    let status = schema.get_enum("Status").unwrap();
    assert!(status.attributes.iter().any(|a| a.name.name == "map"));
}

/// Test composite type parsing
#[test]
fn test_parse_composite_types() {
    let schema = parse_schema(
        r#"
        type Address {
            street     String
            city       String
            state      String?
            postalCode String
            country    String @default("US")
        }

        type GeoPoint {
            latitude  Float
            longitude Float
        }

        model User {
            id      Int     @id @auto
            address Address
        }
    "#,
    )
    .expect("Failed to parse schema");

    assert_eq!(schema.types.len(), 2);

    let address = schema.get_type("Address").unwrap();
    assert_eq!(address.fields.len(), 5);
}

/// Test view parsing
#[test]
fn test_parse_views() {
    let schema = parse_schema(
        r#"
model Post {
    id        Int    @id @auto
    title     String
    viewCount Int    @default(0)
}

view PopularPosts {
    id        Int    @unique
    title     String
    viewCount Int

    @@map("popular_posts_view")
}
"#,
    )
    .expect("Failed to parse schema");

    // Views are included in the schema - test via stats
    let stats = schema.stats();
    assert_eq!(stats.model_count, 1, "Should have 1 model (Post)");
    assert_eq!(stats.view_count, 1, "Should have 1 view (PopularPosts)");

    // Access view by name
    let view = schema.get_view("PopularPosts");
    assert!(view.is_some(), "PopularPosts view should exist");

    let view = view.unwrap();
    assert_eq!(view.fields.len(), 3, "View should have 3 fields");
}

/// Test server group parsing
#[test]
fn test_parse_server_groups() {
    let schema = parse_schema(
        r#"
model User {
    id    Int    @id @auto
    email String @unique
}

serverGroup MainCluster {
    server primary {
        url  = "postgresql://primary:5432/db"
        role = "primary"
    }

    server replica1 {
        url    = "postgresql://replica1:5432/db"
        role   = "replica"
        weight = 50
    }

    @@strategy("ReadReplica")
    @@loadBalance("RoundRobin")
}
"#,
    )
    .expect("Failed to parse schema");

    assert_eq!(schema.server_group_names().count(), 1);

    let sg = schema.get_server_group("MainCluster").unwrap();
    assert_eq!(sg.servers.len(), 2);
}

/// Test documentation comments
#[test]
fn test_parse_documentation() {
    let schema = parse_schema(
        r#"/// User account in the system.
/// Contains authentication and profile information.
model User {
    /// Primary key
    id    Int    @id @auto

    /// User's email address
    email String @unique
}
"#,
    )
    .expect("Failed to parse schema");

    let user = schema.get_model("User").unwrap();
    // Documentation parsing is optional - check if it's supported
    // If documentation is present, verify it contains expected text
    if let Some(doc) = &user.documentation {
        assert!(doc.text.to_lowercase().contains("user"));
    }

    // Field documentation may not be supported in all versions
    // let id_field = user.fields.get("id").expect("id field not found");
    // if let Some(doc) = &id_field.documentation {
    //     assert!(doc.text.contains("Primary"));
    // }
}

/// Test schema validation - valid schema
#[test]
fn test_validate_valid_schema() {
    let result = validate_schema(
        r#"
        model User {
            id    Int    @id @auto
            email String @unique
            posts Post[]
        }

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

    assert!(result.is_ok(), "Schema should be valid: {:?}", result.err());
}

/// Test schema validation - missing @id
#[test]
fn test_validate_missing_id() {
    let result = validate_schema(
        r#"
        model User {
            email String @unique
            name  String
        }
    "#,
    );

    // This should either pass (if @id is optional) or fail with a specific error
    // Depending on validation rules
    match result {
        Ok(_) => {} // Some ORMs allow tables without explicit primary key
        Err(e) => {
            assert!(
                e.to_string().contains("id") || e.to_string().contains("primary"),
                "Error should mention missing id: {}",
                e
            );
        }
    }
}

/// Test schema statistics
#[test]
fn test_schema_statistics() {
    let schema = parse_schema(
        r#"
model User { id Int @id @auto }
model Post { id Int @id @auto }
model Comment { id Int @id @auto }

enum Role { User Admin }
enum Status { Draft Published }

type Address { street String }

view UserStats { id Int @unique }

serverGroup Cluster {
    server primary { url = "postgres://localhost/db" }
}
"#,
    )
    .expect("Failed to parse schema");

    let stats = schema.stats();
    assert_eq!(stats.model_count, 3);
    assert_eq!(stats.enum_count, 2);
    assert_eq!(stats.type_count, 1);
    assert_eq!(stats.view_count, 1);
    assert_eq!(stats.server_group_count, 1);
}

/// Test configuration parsing
#[test]
fn test_config_parsing() {
    let config_str = r#"
        [database]
        provider = "postgresql"
        url = "postgresql://localhost:5432/mydb"

        [database.pool]
        min_connections = 2
        max_connections = 10

        [generator.client]
        output = "./src/generated"

        [migrations]
        directory = "./prax/migrations"
    "#;

    let config: PraxConfig = toml::from_str(config_str).expect("Failed to parse config");

    assert_eq!(
        config.database.url,
        Some("postgresql://localhost:5432/mydb".to_string())
    );
    assert_eq!(config.database.pool.min_connections, 2);
    assert_eq!(config.database.pool.max_connections, 10);
}

/// Test configuration with environment variables
#[test]
fn test_config_with_env_vars() {
    let config_str = r#"
        [database]
        provider = "postgresql"
        url = "${DATABASE_URL}"
    "#;

    let config: PraxConfig = toml::from_str(config_str).expect("Failed to parse config");

    assert_eq!(config.database.url, Some("${DATABASE_URL}".to_string()));
}

/// Test schema merging
#[test]
fn test_schema_merging() {
    let schema1 = parse_schema(
        r#"
        model User {
            id    Int    @id @auto
            email String @unique
        }
    "#,
    )
    .expect("Failed to parse schema 1");

    let schema2 = parse_schema(
        r#"
        model Post {
            id    Int    @id @auto
            title String
        }
    "#,
    )
    .expect("Failed to parse schema 2");

    let mut merged = schema1;
    merged.merge(schema2);

    assert_eq!(merged.model_names().count(), 2);
    assert!(merged.get_model("User").is_some());
    assert!(merged.get_model("Post").is_some());
}

/// Test index definitions
#[test]
fn test_parse_indexes() {
    let schema = parse_schema(
        r#"
        model User {
            id        Int      @id @auto
            email     String   @unique @index
            firstName String
            lastName  String
            createdAt DateTime

            @@index([firstName, lastName])
            @@index([createdAt], map: "idx_created")
            @@unique([email, firstName])
        }
    "#,
    )
    .expect("Failed to parse schema");

    let user = schema.get_model("User").unwrap();

    // Count @@index and @@unique attributes
    let index_count = user
        .attributes
        .iter()
        .filter(|a| a.name.name == "index")
        .count();
    let unique_count = user
        .attributes
        .iter()
        .filter(|a| a.name.name == "unique")
        .count();

    assert!(index_count >= 2, "Should have at least 2 indexes");
    assert!(
        unique_count >= 1,
        "Should have at least 1 unique constraint"
    );
}

/// Test default values
#[test]
fn test_parse_default_values() {
    let schema = parse_schema(
        r#"
        model Post {
            id        Int      @id @auto
            title     String
            views     Int      @default(0)
            rating    Float    @default(0.0)
            published Boolean  @default(false)
            content   String   @default("")
            status    Status   @default(Draft)
            createdAt DateTime @default(now())
            uuid      String   @default(uuid())
            cuid      String   @default(cuid())
        }

        enum Status {
            Draft
            Published
        }
    "#,
    )
    .expect("Failed to parse schema");

    let post = schema.get_model("Post").unwrap();

    // Check views has @default(0)
    let views = post.fields.get("views").expect("views field not found");
    assert!(views.attributes.iter().any(|a| a.name.name == "default"));

    // Check createdAt has @default(now())
    let created_at = post
        .fields
        .get("createdAt")
        .expect("createdAt field not found");
    assert!(
        created_at
            .attributes
            .iter()
            .any(|a| a.name.name == "default")
    );
}

/// Test database type annotations
#[test]
fn test_parse_db_types() {
    let schema = parse_schema(
        r#"
        model Content {
            id          Int     @id @auto
            title       String  @db.VarChar(200)
            description String? @db.Text
            metadata    String? @db.Json
            data        Bytes?  @db.ByteA
        }
    "#,
    )
    .expect("Failed to parse schema");

    let content = schema.get_model("Content").unwrap();

    // Check title has @db.VarChar
    let title = content.fields.get("title").expect("title field not found");
    let has_db_attr = title
        .attributes
        .iter()
        .any(|a| a.name.name == "db.VarChar" || a.name.name.starts_with("db"));
    assert!(has_db_attr, "title should have @db attribute");
}

/// Test referential actions in relations
#[test]
fn test_parse_referential_actions() {
    let schema = parse_schema(
        r#"
        model User {
            id    Int    @id @auto
            posts Post[]
        }

        model Post {
            id       Int    @id @auto
            authorId Int
            author   User   @relation(fields: [authorId], references: [id], onDelete: Cascade, onUpdate: Cascade)
        }
    "#,
    )
    .expect("Failed to parse schema");

    let post = schema.get_model("Post").unwrap();
    let author = post.fields.get("author").expect("author field not found");
    let relation = author
        .attributes
        .iter()
        .find(|a| a.name.name == "relation")
        .expect("relation attribute not found");

    // Relation should have onDelete and onUpdate arguments
    assert!(!relation.args.is_empty());
}

/// Test field names are unique within model
#[test]
fn test_field_names_unique() {
    let schema = parse_schema(
        r#"
        model User {
            id    Int    @id @auto
            email String
            name  String
        }
    "#,
    )
    .expect("Failed to parse schema");

    let user = schema.get_model("User").unwrap();
    assert_eq!(user.fields.len(), 3);
}

/// Test multiple models in one schema
#[test]
fn test_multiple_models() {
    let schema = parse_schema(
        r#"
        model User { id Int @id @auto }
        model Post { id Int @id @auto }
        model Comment { id Int @id @auto }
        model Tag { id Int @id @auto }
        model Category { id Int @id @auto }
    "#,
    )
    .expect("Failed to parse schema");

    assert_eq!(schema.model_names().count(), 5);
}