df-derive 0.3.0

Derive fast conversions from Rust structs into Polars DataFrames.
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
use df_derive::ToDataFrame;
use polars::prelude::*;
#[path = "../common.rs"]
mod core;
use crate::core::dataframe::ToDataFrame;

// Basic nested struct
#[derive(ToDataFrame)]
struct Address {
    street: String,
    city: String,
    zip: u32,
}

// Multiple data types and nested struct
#[derive(ToDataFrame)]
struct Person {
    name: String,
    age: u32,
    address: Address,
    salary: f64,
}

// Nested struct with optional fields
#[derive(ToDataFrame)]
struct Contact {
    email: Option<String>,
    phone: Option<String>,
    verified: bool,
}

// Complex nested structure with multiple nested structs
#[derive(ToDataFrame)]
struct Employee {
    id: i64,
    name: String,
    address: Address,
    contact: Contact,
    salary: f64,
    active: bool,
}

// Multiple levels of nesting
#[derive(ToDataFrame)]
struct Coordinates {
    latitude: f64,
    longitude: f64,
}

#[derive(ToDataFrame)]
struct Location {
    name: String,
    coordinates: Coordinates,
}

#[derive(ToDataFrame)]
struct Company {
    name: String,
    location: Location,
    employee_count: u32,
}

// Nested struct with Vec fields
#[derive(ToDataFrame)]
struct Skills {
    programming: Vec<String>,
    languages: Vec<String>,
}

#[derive(ToDataFrame)]
struct Developer {
    name: String,
    skills: Skills,
    experience_years: u32,
}

// Empty nested struct
#[derive(ToDataFrame)]
struct EmptyNested {}

#[derive(ToDataFrame)]
struct WithEmpty {
    id: u32,
    empty: EmptyNested,
    value: String,
}

// Multiple instances of the same nested type
#[derive(ToDataFrame)]
struct MultipleAddresses {
    id: u32,
    home_address: Address,
    work_address: Address,
    name: String,
}

// Mixed nesting: primitives, nested structs, and options
#[derive(ToDataFrame)]
struct ComplexMixed {
    id: i64,
    primary_contact: Option<Contact>,
    backup_contact: Contact,
    addresses: Vec<String>, // Simple vector
    main_location: Location,
    active: bool,
}

fn main() {
    // Test 1: Basic nested struct functionality
    test_basic_nested_struct();

    // Test 2: Complex nested structure with multiple nested structs
    test_complex_nested_structure();

    // Test 3: Multiple levels of nesting (3 levels deep)
    test_deep_nesting();

    // Test 4: Nested struct with Vec fields
    test_nested_with_vectors();

    // Test 5: Empty nested struct
    test_empty_nested_struct();

    // Test 6: Empty dataframe functionality
    test_empty_dataframes();

    // Test 7: Data types and values validation
    test_data_types_and_values();

    // Test 8: Multiple instances of same nested type
    test_multiple_nested_instances();

    // Test 9: Complex mixed scenarios
    test_complex_mixed_scenarios();

    println!("All nested struct tests passed!");
}

fn test_basic_nested_struct() {
    println!("Testing basic nested struct...");

    let person = Person {
        name: "John Doe".to_string(),
        age: 30,
        address: Address {
            street: "123 Main St".to_string(),
            city: "Anytown".to_string(),
            zip: 12345,
        },
        salary: 75000.0,
    };

    let df = person.to_dataframe().unwrap();

    // Should flatten nested struct fields with dot notation
    // Expected columns: name, age, address.street, address.city, address.zip, salary
    assert_eq!(df.shape(), (1, 6));

    let column_names = df.get_column_names();
    let expected_columns = [
        "name",
        "age",
        "address.street",
        "address.city",
        "address.zip",
        "salary",
    ];
    for expected_col in &expected_columns {
        assert!(
            column_names
                .iter()
                .any(|name| name.as_str() == *expected_col),
            "Column '{}' not found in {:?}",
            expected_col,
            column_names.iter().map(|s| s.as_str()).collect::<Vec<_>>()
        );
    }

    // Test specific values
    assert_eq!(
        df.column("name").unwrap().get(0).unwrap(),
        AnyValue::String("John Doe")
    );
    assert_eq!(
        df.column("age").unwrap().get(0).unwrap(),
        AnyValue::UInt32(30)
    );
    assert_eq!(
        df.column("address.street").unwrap().get(0).unwrap(),
        AnyValue::String("123 Main St")
    );
    assert_eq!(
        df.column("address.city").unwrap().get(0).unwrap(),
        AnyValue::String("Anytown")
    );
    assert_eq!(
        df.column("address.zip").unwrap().get(0).unwrap(),
        AnyValue::UInt32(12345)
    );
    assert_eq!(
        df.column("salary").unwrap().get(0).unwrap(),
        AnyValue::Float64(75000.0)
    );
}

fn test_complex_nested_structure() {
    println!("Testing complex nested structure...");

    let employee = Employee {
        id: 12345,
        name: "Jane Smith".to_string(),
        address: Address {
            street: "456 Oak Ave".to_string(),
            city: "Springfield".to_string(),
            zip: 67890,
        },
        contact: Contact {
            email: Some("jane.smith@example.com".to_string()),
            phone: Some("555-1234".to_string()),
            verified: true,
        },
        salary: 85000.0,
        active: true,
    };

    let df = employee.to_dataframe().unwrap();

    // Expected columns: id, name, address.*, contact.*, salary, active
    // Adjust the count based on what we expect:
    // id(1) + name(1) + address(3) + contact(3) + salary(1) + active(1) = 10 columns
    assert_eq!(df.shape(), (1, 10));

    let expected_columns = [
        "id",
        "name",
        "address.street",
        "address.city",
        "address.zip",
        "contact.email",
        "contact.phone",
        "contact.verified",
        "salary",
        "active",
    ];

    let column_names = df.get_column_names();
    for expected_col in &expected_columns {
        assert!(
            column_names
                .iter()
                .any(|name| name.as_str() == *expected_col),
            "Column '{}' not found in {:?}",
            expected_col,
            column_names.iter().map(|s| s.as_str()).collect::<Vec<_>>()
        );
    }

    // Test optional field values
    assert_eq!(
        df.column("contact.email").unwrap().get(0).unwrap(),
        AnyValue::String("jane.smith@example.com")
    );
    assert_eq!(
        df.column("contact.phone").unwrap().get(0).unwrap(),
        AnyValue::String("555-1234")
    );
    assert_eq!(
        df.column("contact.verified").unwrap().get(0).unwrap(),
        AnyValue::Boolean(true)
    );
}

fn test_deep_nesting() {
    println!("Testing deep nesting (3 levels)...");

    let company = Company {
        name: "Tech Corp".to_string(),
        location: Location {
            name: "Silicon Valley".to_string(),
            coordinates: Coordinates {
                latitude: 37.3861,
                longitude: -122.0839,
            },
        },
        employee_count: 500,
    };

    let df = company.to_dataframe().unwrap();

    // Expected columns: name, location.name, location.coordinates.latitude, location.coordinates.longitude, employee_count
    assert_eq!(df.shape(), (1, 5));

    let expected_columns = [
        "name",
        "location.name",
        "location.coordinates.latitude",
        "location.coordinates.longitude",
        "employee_count",
    ];

    let column_names = df.get_column_names();
    for expected_col in &expected_columns {
        assert!(
            column_names
                .iter()
                .any(|name| name.as_str() == *expected_col),
            "Column '{}' not found in {:?}",
            expected_col,
            column_names.iter().map(|s| s.as_str()).collect::<Vec<_>>()
        );
    }

    // Test deep nested values
    assert_eq!(
        df.column("name").unwrap().get(0).unwrap(),
        AnyValue::String("Tech Corp")
    );
    assert_eq!(
        df.column("location.name").unwrap().get(0).unwrap(),
        AnyValue::String("Silicon Valley")
    );
    assert_eq!(
        df.column("location.coordinates.latitude")
            .unwrap()
            .get(0)
            .unwrap(),
        AnyValue::Float64(37.3861)
    );
    assert_eq!(
        df.column("location.coordinates.longitude")
            .unwrap()
            .get(0)
            .unwrap(),
        AnyValue::Float64(-122.0839)
    );
    assert_eq!(
        df.column("employee_count").unwrap().get(0).unwrap(),
        AnyValue::UInt32(500)
    );
}

fn test_nested_with_vectors() {
    println!("Testing nested struct with vectors...");

    let developer = Developer {
        name: "Alice Johnson".to_string(),
        skills: Skills {
            programming: vec![
                "Rust".to_string(),
                "Python".to_string(),
                "JavaScript".to_string(),
            ],
            languages: vec!["English".to_string(), "Spanish".to_string()],
        },
        experience_years: 5,
    };

    let df = developer.to_dataframe().unwrap();

    // Expected columns: name, skills.programming, skills.languages, experience_years
    assert_eq!(df.shape(), (1, 4));

    let expected_columns = [
        "name",
        "skills.programming",
        "skills.languages",
        "experience_years",
    ];

    let column_names = df.get_column_names();
    for expected_col in &expected_columns {
        assert!(
            column_names
                .iter()
                .any(|name| name.as_str() == *expected_col),
            "Column '{}' not found in {:?}",
            expected_col,
            column_names.iter().map(|s| s.as_str()).collect::<Vec<_>>()
        );
    }

    // Test that vector fields are properly handled
    assert_eq!(
        df.column("name").unwrap().get(0).unwrap(),
        AnyValue::String("Alice Johnson")
    );
    assert_eq!(
        df.column("experience_years").unwrap().get(0).unwrap(),
        AnyValue::UInt32(5)
    );

    // Vector fields should be List types
    let programming_value = df.column("skills.programming").unwrap().get(0).unwrap();
    let languages_value = df.column("skills.languages").unwrap().get(0).unwrap();

    // Check that these are list types (exact value checking for lists is complex)
    assert!(matches!(programming_value, AnyValue::List(_)));
    assert!(matches!(languages_value, AnyValue::List(_)));
}

fn test_empty_nested_struct() {
    println!("Testing empty nested struct...");

    let with_empty = WithEmpty {
        id: 42,
        empty: EmptyNested {},
        value: "test".to_string(),
    };

    let df = with_empty.to_dataframe().unwrap();

    // Should have columns for id and value, but empty struct should contribute 0 columns
    assert_eq!(df.shape(), (1, 2));

    let expected_columns = ["id", "value"];

    let column_names = df.get_column_names();
    for expected_col in &expected_columns {
        assert!(
            column_names
                .iter()
                .any(|name| name.as_str() == *expected_col),
            "Column '{}' not found in {:?}",
            expected_col,
            column_names.iter().map(|s| s.as_str()).collect::<Vec<_>>()
        );
    }

    assert_eq!(
        df.column("id").unwrap().get(0).unwrap(),
        AnyValue::UInt32(42)
    );
    assert_eq!(
        df.column("value").unwrap().get(0).unwrap(),
        AnyValue::String("test")
    );
}

fn test_empty_dataframes() {
    println!("Testing empty dataframe functionality...");

    // Test empty dataframe for basic nested struct
    let person_empty = Person::empty_dataframe().unwrap();
    assert_eq!(person_empty.shape(), (0, 6));

    let expected_columns = [
        "name",
        "age",
        "address.street",
        "address.city",
        "address.zip",
        "salary",
    ];
    let column_names = person_empty.get_column_names();
    for expected_col in &expected_columns {
        assert!(
            column_names
                .iter()
                .any(|name| name.as_str() == *expected_col),
            "Column '{}' not found in empty dataframe",
            expected_col
        );
    }

    // Test empty dataframe for complex nested struct
    let employee_empty = Employee::empty_dataframe().unwrap();
    assert_eq!(employee_empty.shape(), (0, 10));

    // Test empty dataframe for deep nesting
    let company_empty = Company::empty_dataframe().unwrap();
    assert_eq!(company_empty.shape(), (0, 5));

    // Test empty dataframe for struct with vectors
    let developer_empty = Developer::empty_dataframe().unwrap();
    assert_eq!(developer_empty.shape(), (0, 4));

    // Test empty dataframe for struct with empty nested struct
    let with_empty_empty = WithEmpty::empty_dataframe().unwrap();
    assert_eq!(with_empty_empty.shape(), (0, 2));
}

fn test_data_types_and_values() {
    println!("Testing data types and values...");

    let employee = Employee {
        id: -12345, // Test negative i64
        name: "Test Employee".to_string(),
        address: Address {
            street: "123 Test St".to_string(),
            city: "Test City".to_string(),
            zip: 99999,
        },
        contact: Contact {
            email: None, // Test None values
            phone: None, // Test None values
            verified: false,
        },
        salary: 0.0, // Test zero value
        active: false,
    };

    let df = employee.to_dataframe().unwrap();

    // Test data types are preserved correctly
    assert_eq!(df.column("id").unwrap().dtype(), &DataType::Int64);
    assert_eq!(df.column("name").unwrap().dtype(), &DataType::String);
    assert_eq!(
        df.column("address.street").unwrap().dtype(),
        &DataType::String
    );
    assert_eq!(df.column("address.zip").unwrap().dtype(), &DataType::UInt32);
    assert_eq!(df.column("salary").unwrap().dtype(), &DataType::Float64);
    assert_eq!(df.column("active").unwrap().dtype(), &DataType::Boolean);
    assert_eq!(
        df.column("contact.verified").unwrap().dtype(),
        &DataType::Boolean
    );

    // Test specific values including edge cases
    assert_eq!(
        df.column("id").unwrap().get(0).unwrap(),
        AnyValue::Int64(-12345)
    );
    assert_eq!(
        df.column("salary").unwrap().get(0).unwrap(),
        AnyValue::Float64(0.0)
    );
    assert_eq!(
        df.column("active").unwrap().get(0).unwrap(),
        AnyValue::Boolean(false)
    );
    assert_eq!(
        df.column("contact.verified").unwrap().get(0).unwrap(),
        AnyValue::Boolean(false)
    );

    // Test None values are handled correctly
    let email_value = df.column("contact.email").unwrap().get(0).unwrap();
    let phone_value = df.column("contact.phone").unwrap().get(0).unwrap();
    assert!(matches!(email_value, AnyValue::Null));
    assert!(matches!(phone_value, AnyValue::Null));
}

fn test_multiple_nested_instances() {
    println!("Testing multiple instances of same nested type...");

    let multiple_addresses = MultipleAddresses {
        id: 123,
        home_address: Address {
            street: "123 Home St".to_string(),
            city: "Hometown".to_string(),
            zip: 11111,
        },
        work_address: Address {
            street: "456 Work Ave".to_string(),
            city: "Worktown".to_string(),
            zip: 22222,
        },
        name: "John Worker".to_string(),
    };

    let df = multiple_addresses.to_dataframe().unwrap();

    // Expected columns: id, home_address.*, work_address.*, name
    // id(1) + home_address(3) + work_address(3) + name(1) = 8 columns
    assert_eq!(df.shape(), (1, 8));

    let expected_columns = [
        "id",
        "home_address.street",
        "home_address.city",
        "home_address.zip",
        "work_address.street",
        "work_address.city",
        "work_address.zip",
        "name",
    ];

    let column_names = df.get_column_names();
    for expected_col in &expected_columns {
        assert!(
            column_names
                .iter()
                .any(|name| name.as_str() == *expected_col),
            "Column '{}' not found in {:?}",
            expected_col,
            column_names.iter().map(|s| s.as_str()).collect::<Vec<_>>()
        );
    }

    // Test that both instances have correct values
    assert_eq!(
        df.column("id").unwrap().get(0).unwrap(),
        AnyValue::UInt32(123)
    );
    assert_eq!(
        df.column("name").unwrap().get(0).unwrap(),
        AnyValue::String("John Worker")
    );

    // Home address values
    assert_eq!(
        df.column("home_address.street").unwrap().get(0).unwrap(),
        AnyValue::String("123 Home St")
    );
    assert_eq!(
        df.column("home_address.city").unwrap().get(0).unwrap(),
        AnyValue::String("Hometown")
    );
    assert_eq!(
        df.column("home_address.zip").unwrap().get(0).unwrap(),
        AnyValue::UInt32(11111)
    );

    // Work address values
    assert_eq!(
        df.column("work_address.street").unwrap().get(0).unwrap(),
        AnyValue::String("456 Work Ave")
    );
    assert_eq!(
        df.column("work_address.city").unwrap().get(0).unwrap(),
        AnyValue::String("Worktown")
    );
    assert_eq!(
        df.column("work_address.zip").unwrap().get(0).unwrap(),
        AnyValue::UInt32(22222)
    );

    // Test empty dataframe
    let empty_df = MultipleAddresses::empty_dataframe().unwrap();
    assert_eq!(empty_df.shape(), (0, 8));
    assert_eq!(empty_df.get_column_names(), column_names);
}

fn test_complex_mixed_scenarios() {
    println!("Testing complex mixed scenarios...");

    let complex_mixed = ComplexMixed {
        id: 999,
        primary_contact: Some(Contact {
            email: Some("primary@example.com".to_string()),
            phone: None,
            verified: true,
        }),
        backup_contact: Contact {
            email: None,
            phone: Some("555-BACKUP".to_string()),
            verified: false,
        },
        addresses: vec!["123 Main St".to_string(), "456 Secondary St".to_string()],
        main_location: Location {
            name: "Main Office".to_string(),
            coordinates: Coordinates {
                latitude: 40.7128,
                longitude: -74.0060,
            },
        },
        active: true,
    };

    let df = complex_mixed.to_dataframe().unwrap();

    // Expected columns:
    // id(1) + primary_contact(3) + backup_contact(3) + addresses(1) + main_location(3) + active(1) = 12
    assert_eq!(df.shape(), (1, 12));

    let expected_columns = [
        "id",
        "primary_contact.email",
        "primary_contact.phone",
        "primary_contact.verified",
        "backup_contact.email",
        "backup_contact.phone",
        "backup_contact.verified",
        "addresses",
        "main_location.name",
        "main_location.coordinates.latitude",
        "main_location.coordinates.longitude",
        "active",
    ];

    let column_names = df.get_column_names();
    for expected_col in &expected_columns {
        assert!(
            column_names
                .iter()
                .any(|name| name.as_str() == *expected_col),
            "Column '{}' not found in {:?}",
            expected_col,
            column_names.iter().map(|s| s.as_str()).collect::<Vec<_>>()
        );
    }

    // Test specific values
    assert_eq!(
        df.column("id").unwrap().get(0).unwrap(),
        AnyValue::Int64(999)
    );
    assert_eq!(
        df.column("active").unwrap().get(0).unwrap(),
        AnyValue::Boolean(true)
    );

    // Test optional nested struct fields
    assert_eq!(
        df.column("primary_contact.email").unwrap().get(0).unwrap(),
        AnyValue::String("primary@example.com")
    );
    let primary_phone = df.column("primary_contact.phone").unwrap().get(0).unwrap();
    assert!(matches!(primary_phone, AnyValue::Null));
    assert_eq!(
        df.column("primary_contact.verified")
            .unwrap()
            .get(0)
            .unwrap(),
        AnyValue::Boolean(true)
    );

    // Test non-optional nested struct fields
    let backup_email = df.column("backup_contact.email").unwrap().get(0).unwrap();
    assert!(matches!(backup_email, AnyValue::Null));
    assert_eq!(
        df.column("backup_contact.phone").unwrap().get(0).unwrap(),
        AnyValue::String("555-BACKUP")
    );
    assert_eq!(
        df.column("backup_contact.verified")
            .unwrap()
            .get(0)
            .unwrap(),
        AnyValue::Boolean(false)
    );

    // Test deeply nested values
    assert_eq!(
        df.column("main_location.name").unwrap().get(0).unwrap(),
        AnyValue::String("Main Office")
    );
    assert_eq!(
        df.column("main_location.coordinates.latitude")
            .unwrap()
            .get(0)
            .unwrap(),
        AnyValue::Float64(40.7128)
    );
    assert_eq!(
        df.column("main_location.coordinates.longitude")
            .unwrap()
            .get(0)
            .unwrap(),
        AnyValue::Float64(-74.0060)
    );

    // Test vector field
    let addresses_value = df.column("addresses").unwrap().get(0).unwrap();
    assert!(matches!(addresses_value, AnyValue::List(_)));

    // Test empty dataframe
    let empty_df = ComplexMixed::empty_dataframe().unwrap();
    assert_eq!(empty_df.shape(), (0, 12));
    assert_eq!(empty_df.get_column_names(), column_names);
}