pgorm 0.1.1

A lightweight Postgres-only ORM for Rust
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
639
640
641
642
643
644
645
646
647
648
649
//! Compile-time tests for multi-table write (graph) macros.
//!
//! These tests verify that the macro-generated code compiles correctly.
//! They do not run actual database operations.

#![allow(dead_code)]

use pgorm::{FromRow, InsertModel, Model, ModelPk, UpdateModel, WriteReport, WriteStepReport};

// ============================================
// Test: Basic InsertModel with has_many
// ============================================

#[derive(Debug, FromRow, Model)]
#[orm(table = "orders")]
struct Order {
    #[orm(id)]
    id: i64,
    user_id: i64,
    total_cents: i64,
}

#[derive(Clone, InsertModel)]
#[orm(table = "order_items")]
struct NewOrderItem {
    order_id: Option<i64>,
    sku: String,
    qty: i32,
}

// Note: has_many requires returning type to get root ID for FK injection
// This test verifies the macro compiles for the basic InsertModel without graph
#[derive(InsertModel)]
#[orm(table = "orders")]
struct NewOrderBasic {
    user_id: i64,
    total_cents: i64,
}

#[test]
fn test_insert_model_basic_compiles() {
    let _order = NewOrderBasic {
        user_id: 1,
        total_cents: 1000,
    };

    assert_eq!(NewOrderBasic::TABLE, "orders");
    assert_eq!(NewOrderItem::TABLE, "order_items");
}

// ============================================
// Test: InsertModel with has_one (requires returning)
// ============================================

#[derive(Debug, FromRow, Model)]
#[orm(table = "users")]
struct User {
    #[orm(id)]
    id: i64,
    username: String,
}

#[derive(Clone, InsertModel)]
#[orm(table = "user_profiles")]
struct NewUserProfile {
    user_id: Option<i64>,
    bio: String,
}

// Basic user without graph
#[derive(InsertModel)]
#[orm(table = "users")]
struct NewUserBasic {
    username: String,
}

#[test]
fn test_insert_model_user_basic_compiles() {
    let _user = NewUserBasic {
        username: "alice".into(),
    };

    assert_eq!(NewUserBasic::TABLE, "users");
}

// ============================================
// Test: InsertModel with belongs_to (pre-insert dependency)
// ============================================

#[derive(Debug, FromRow, Model)]
#[orm(table = "categories")]
struct Category {
    #[orm(id)]
    id: i64,
    name: String,
}

#[derive(Clone, InsertModel)]
#[orm(table = "categories", returning = "Category")]
struct NewCategory {
    name: String,
}

#[derive(Debug, FromRow, Model)]
#[orm(table = "products")]
struct Product {
    #[orm(id)]
    id: i64,
    name: String,
    category_id: Option<i64>,
}

// Product with belongs_to for category
#[derive(InsertModel)]
#[orm(table = "products", returning = "Product")]
#[orm(graph_root_key = "id")]
#[orm(belongs_to(
    NewCategory,
    field = "category",
    set_fk_field = "category_id",
    mode = "insert_returning",
    required = false
))]
struct NewProduct {
    name: String,
    category_id: Option<i64>,
    category: Option<NewCategory>,
}

#[test]
fn test_insert_model_with_belongs_to_compiles() {
    // Use existing category_id
    let _product1 = NewProduct {
        name: "Widget".into(),
        category_id: Some(1),
        category: None,
    };

    // Create new category via belongs_to
    let _product2 = NewProduct {
        name: "Gadget".into(),
        category_id: None,
        category: Some(NewCategory {
            name: "Electronics".into(),
        }),
    };

    assert_eq!(NewProduct::TABLE, "products");
}

// ============================================
// Test: InsertModel with before/after_insert steps
// ============================================

#[derive(Clone, InsertModel)]
#[orm(table = "audit_logs")]
struct NewAuditLog {
    action: String,
    entity: String,
}

#[derive(InsertModel)]
#[orm(table = "users", returning = "User")]
#[orm(graph_root_key = "id")]
#[orm(after_insert(NewAuditLog, field = "audit", mode = "insert"))]
struct NewUserWithAudit {
    username: String,
    audit: Option<NewAuditLog>,
}

#[test]
fn test_insert_model_with_after_insert_compiles() {
    let _user = NewUserWithAudit {
        username: "bob".into(),
        audit: Some(NewAuditLog {
            action: "CREATE".into(),
            entity: "user".into(),
        }),
    };

    assert_eq!(NewUserWithAudit::TABLE, "users");
}

// ============================================
// Test: InsertModel with conflict_target (composite unique key)
// ============================================

#[derive(Clone, InsertModel)]
#[orm(table = "order_items", conflict_target = "order_id, sku")]
struct NewOrderItemUpsert {
    order_id: i64,
    sku: String,
    qty: i32,
}

#[test]
fn test_insert_model_with_composite_conflict_target_compiles() {
    let _item = NewOrderItemUpsert {
        order_id: 1,
        sku: "ABC123".into(),
        qty: 5,
    };

    assert_eq!(NewOrderItemUpsert::TABLE, "order_items");
}

// ============================================
// Test: InsertModel with conflict_constraint (named constraint)
// ============================================

#[derive(Clone, InsertModel)]
#[orm(table = "tags", conflict_constraint = "tags_name_unique")]
struct NewTagWithConstraint {
    name: String,
    color: Option<String>,
}

#[test]
fn test_insert_model_with_conflict_constraint_compiles() {
    let _tag = NewTagWithConstraint {
        name: "rust".into(),
        color: Some("orange".into()),
    };

    assert_eq!(NewTagWithConstraint::TABLE, "tags");
}

// ============================================
// Test: Basic UpdateModel (without graph)
// ============================================

#[derive(UpdateModel)]
#[orm(table = "orders", model = "Order", returning = "Order")]
struct OrderPatchBasic {
    total_cents: Option<i64>,
}

#[test]
fn test_update_model_basic_compiles() {
    let _patch = OrderPatchBasic {
        total_cents: Some(1500),
    };

    assert_eq!(OrderPatchBasic::TABLE, "orders");
}

// ============================================
// Test: UpdateModel for users
// ============================================

#[derive(UpdateModel)]
#[orm(table = "users", model = "User", returning = "User")]
struct UserPatchBasic {
    username: Option<String>,
}

#[test]
fn test_update_model_user_basic_compiles() {
    let _patch = UserPatchBasic {
        username: Some("new_name".into()),
    };

    assert_eq!(UserPatchBasic::TABLE, "users");
}

// ============================================
// Test: WriteReport type
// ============================================

#[test]
fn test_write_report_type_exists() {
    let report: WriteReport<i32> = WriteReport {
        affected: 5,
        steps: vec![
            WriteStepReport {
                tag: "graph:root:test",
                affected: 1,
            },
            WriteStepReport {
                tag: "graph:has_many:items",
                affected: 4,
            },
        ],
        root: Some(42),
    };

    assert_eq!(report.affected, 5);
    assert_eq!(report.steps.len(), 2);
    assert_eq!(report.root, Some(42));
}

// ============================================
// Test: InsertModel with has_many (with returning for FK injection)
// ============================================

#[derive(InsertModel)]
#[orm(table = "orders", returning = "Order")]
#[orm(graph_root_key = "id")]
#[orm(has_many(NewOrderItem, field = "items", fk_field = "order_id", fk_wrap = "some"))]
struct NewOrderWithItems {
    user_id: i64,
    total_cents: i64,
    items: Option<Vec<NewOrderItem>>,
}

#[test]
fn test_insert_model_with_has_many_compiles() {
    let _order = NewOrderWithItems {
        user_id: 1,
        total_cents: 1000,
        items: Some(vec![
            NewOrderItem {
                order_id: None,
                sku: "A".into(),
                qty: 1,
            },
            NewOrderItem {
                order_id: None,
                sku: "B".into(),
                qty: 2,
            },
        ]),
    };

    assert_eq!(NewOrderWithItems::TABLE, "orders");
}

// ============================================
// Test: InsertModel with has_one
// ============================================

#[derive(InsertModel)]
#[orm(table = "users", returning = "User")]
#[orm(graph_root_key = "id")]
#[orm(has_one(
    NewUserProfile,
    field = "profile",
    fk_field = "user_id",
    fk_wrap = "some"
))]
struct NewUserWithProfile {
    username: String,
    profile: Option<NewUserProfile>,
}

#[test]
fn test_insert_model_with_has_one_compiles() {
    let _user = NewUserWithProfile {
        username: "alice".into(),
        profile: Some(NewUserProfile {
            user_id: None,
            bio: "Hello world".into(),
        }),
    };

    assert_eq!(NewUserWithProfile::TABLE, "users");
}

// ============================================
// Test: ModelPk trait is implemented by Model derive
// ============================================

#[test]
fn test_model_pk_trait() {
    // ModelPk is implemented for Order (which has #[orm(id)])
    let order = Order {
        id: 42,
        user_id: 1,
        total_cents: 1000,
    };

    // pk() returns a reference to the id field
    let pk: &i64 = order.pk();
    assert_eq!(*pk, 42);

    // ModelPk::Id associated type is i64
    fn assert_model_pk<M: ModelPk<Id = i64>>(_: &M) {}
    assert_model_pk(&order);
}

// ============================================
// Test: with_* setters are generated for InsertModel
// ============================================

#[test]
fn test_with_setters() {
    // Non-Option field: with_sku(String) -> Self
    let item1 = NewOrderItem {
        order_id: None,
        sku: "default".into(),
        qty: 0,
    };
    let item1 = item1.with_sku("ABC123".to_string());
    assert_eq!(item1.sku, "ABC123");

    // Option field: with_order_id(i64) wraps in Some
    let item2 = NewOrderItem {
        order_id: None,
        sku: "test".into(),
        qty: 1,
    };
    let item2 = item2.with_order_id(42);
    assert_eq!(item2.order_id, Some(42));

    // Option field: with_order_id_opt(Option<i64>) sets directly
    let item3 = NewOrderItem {
        order_id: Some(1),
        sku: "test".into(),
        qty: 1,
    };
    let item3 = item3.with_order_id_opt(None);
    assert_eq!(item3.order_id, None);
}

// ============================================
// Test: conflict_update attribute
// ============================================

#[derive(Clone, InsertModel)]
#[orm(
    table = "order_items",
    conflict_target = "order_id, sku",
    conflict_update = "qty"
)]
struct NewOrderItemUpsertPartial {
    order_id: i64,
    sku: String,
    qty: i32,
    notes: String,
}

#[test]
fn test_conflict_update_attribute() {
    // This struct should compile with conflict_update attribute
    let _item = NewOrderItemUpsertPartial {
        order_id: 1,
        sku: "ABC123".into(),
        qty: 5,
        notes: "test".into(),
    };

    assert_eq!(NewOrderItemUpsertPartial::TABLE, "order_items");
}

// ============================================
// Test: UpdateModel with has_many_update (structure only, no method call)
// ============================================

// Note: We can't actually test update_by_id_graph without a database connection,
// but we can verify the struct compiles with the attribute

#[derive(Clone, InsertModel)]
#[orm(table = "order_items", conflict_target = "order_id, sku")]
struct NewOrderItemForUpdate {
    order_id: Option<i64>,
    sku: String,
    qty: i32,
}

// The has_many_update attribute is parsed but methods require database to call
// For compile-time testing, we just verify the struct definition compiles
// #[derive(UpdateModel)]
// #[orm(table = "orders", model = "Order", returning = "Order")]
// #[orm(has_many_update(NewOrderItemForUpdate, field = "items", fk_column = "order_id", fk_field = "order_id", strategy = "replace"))]
// struct OrderPatchWithItems {
//     total_cents: Option<i64>,
//     items: Option<Vec<NewOrderItemForUpdate>>,
// }

#[test]
fn test_insert_model_for_update_compiles() {
    let _item = NewOrderItemForUpdate {
        order_id: Some(1),
        sku: "ABC".into(),
        qty: 1,
    };

    assert_eq!(NewOrderItemForUpdate::TABLE, "order_items");
}

// ============================================
// Test: UpdateModel with has_one_update (structure only)
// ============================================

#[derive(Clone, InsertModel)]
#[orm(table = "user_profiles", conflict_target = "user_id")]
struct NewUserProfileForUpdate {
    user_id: Option<i64>,
    bio: String,
}

#[test]
fn test_insert_model_for_profile_update_compiles() {
    let _profile = NewUserProfileForUpdate {
        user_id: Some(1),
        bio: "Test bio".into(),
    };

    assert_eq!(NewUserProfileForUpdate::TABLE, "user_profiles");
}

// ============================================
// Test: diff helper is generated for InsertModel with upsert
// ============================================

#[test]
fn test_diff_helper_method_exists() {
    // NewOrderItemForUpdate should have __pgorm_diff_many_by_fk since it has conflict_target
    // We can't call it without a database, but we can verify it exists by referencing the method
    // This test just verifies the struct compiles and has the method signature
    assert_eq!(NewOrderItemForUpdate::TABLE, "order_items");
}

// ============================================
// Test: auto_now_add attribute for InsertModel
// ============================================

use chrono::{DateTime, Utc};

#[derive(InsertModel)]
#[orm(table = "posts", returning = "Post")]
struct NewPostWithTimestamps {
    title: String,
    content: String,

    #[orm(auto_now_add)]
    created_at: Option<DateTime<Utc>>,

    #[orm(auto_now_add)]
    updated_at: Option<DateTime<Utc>>,
}

#[derive(Debug, FromRow, Model)]
#[orm(table = "posts")]
struct Post {
    #[orm(id)]
    id: i64,
    title: String,
    content: String,
    created_at: DateTime<Utc>,
    updated_at: DateTime<Utc>,
}

#[test]
fn test_insert_model_with_auto_now_add_compiles() {
    // Test with None - should auto-fill
    let _post1 = NewPostWithTimestamps {
        title: "Hello".into(),
        content: "World".into(),
        created_at: None,
        updated_at: None,
    };

    // Test with fixed time - should use provided value
    let fixed_time = Utc::now();
    let _post2 = NewPostWithTimestamps {
        title: "Fixed".into(),
        content: "Time".into(),
        created_at: Some(fixed_time),
        updated_at: Some(fixed_time),
    };

    assert_eq!(NewPostWithTimestamps::TABLE, "posts");
}

// ============================================
// Test: auto_now_add with NaiveDateTime
// ============================================

use chrono::NaiveDateTime;

#[derive(InsertModel)]
#[orm(table = "events")]
struct NewEvent {
    name: String,

    #[orm(auto_now_add)]
    created_at: Option<NaiveDateTime>,
}

#[test]
fn test_insert_model_with_auto_now_add_naive_compiles() {
    let _event = NewEvent {
        name: "Launch".into(),
        created_at: None,
    };

    assert_eq!(NewEvent::TABLE, "events");
}

// ============================================
// Test: auto_now attribute for UpdateModel
// ============================================

#[derive(UpdateModel)]
#[orm(table = "posts", model = "Post", returning = "Post")]
struct PostPatchWithAutoNow {
    title: Option<String>,

    #[orm(auto_now)]
    updated_at: Option<DateTime<Utc>>,
}

#[test]
fn test_update_model_with_auto_now_compiles() {
    // Regular update - updated_at will be auto-set
    let _patch1 = PostPatchWithAutoNow {
        title: Some("New title".into()),
        updated_at: None,
    };

    // Touch - only updated_at will be set (won't trigger "no fields to update")
    let _patch2 = PostPatchWithAutoNow {
        title: None,
        updated_at: None,
    };

    // Explicit time - should use provided value
    let fixed_time = Utc::now();
    let _patch3 = PostPatchWithAutoNow {
        title: Some("Another".into()),
        updated_at: Some(fixed_time),
    };

    assert_eq!(PostPatchWithAutoNow::TABLE, "posts");
}

// ============================================
// Test: auto_now with NaiveDateTime for UpdateModel
// ============================================

#[derive(UpdateModel)]
#[orm(table = "events", id_column = "id")]
struct EventPatch {
    name: Option<String>,

    #[orm(auto_now)]
    modified_at: Option<NaiveDateTime>,
}

#[test]
fn test_update_model_with_auto_now_naive_compiles() {
    let _patch = EventPatch {
        name: Some("Updated".into()),
        modified_at: None,
    };

    assert_eq!(EventPatch::TABLE, "events");
}