entity-derive-impl 0.20.16

Internal proc-macro implementation for entity-derive. Use entity-derive instead.
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
// SPDX-FileCopyrightText: 2025-2026 RAprogramm <andrey.rozanov.vl@gmail.com>
// SPDX-License-Identifier: MIT

//! DDL (Data Definition Language) generation for `PostgreSQL`.
//!
//! Generates CREATE TABLE, CREATE INDEX, and DROP TABLE statements.

use convert_case::{Case, Casing};

use crate::entity::{
    migrations::types::{PostgresTypeMapper, SqlType, TypeMapper},
    parse::{CompositeIndexDef, EntityDef, FieldDef}
};

/// Generate the complete UP migration SQL.
///
/// Includes:
/// - CREATE TABLE with columns and constraints
/// - CREATE INDEX for single-column indexes
/// - CREATE INDEX for composite indexes
pub fn generate_up(entity: &EntityDef) -> String {
    let mut sql = String::new();

    // CREATE TABLE
    sql.push_str(&generate_create_table(entity));

    // Single-column indexes
    for field in entity.column_fields() {
        if field.column().has_index() {
            sql.push_str(&generate_single_index(entity, field));
        }
        if field.is_unique() && field.column().ci {
            sql.push_str(&generate_ci_unique_index(entity, field));
        }
    }

    // Composite indexes
    for idx in &entity.indexes {
        sql.push_str(&generate_composite_index(entity, idx));
    }

    sql
}

/// Generate the DOWN migration SQL.
pub fn generate_down(entity: &EntityDef) -> String {
    format!(
        "DROP TABLE IF EXISTS {} CASCADE;\n",
        entity.full_table_name()
    )
}

/// Generate CREATE TABLE statement.
fn generate_create_table(entity: &EntityDef) -> String {
    let mapper = PostgresTypeMapper;
    let full_table = entity.full_table_name();

    let columns: Vec<String> = entity
        .column_fields()
        .into_iter()
        .map(|f| generate_column_def(f, &mapper, entity))
        .collect();

    format!(
        "CREATE TABLE IF NOT EXISTS {} (\n{}\n);\n",
        full_table,
        columns.join(",\n")
    )
}

/// Generate a single column definition.
fn generate_column_def(
    field: &FieldDef,
    mapper: &PostgresTypeMapper,
    entity: &EntityDef
) -> String {
    let column_name = field.column_name();
    let sql_type = mapper.map_type(field.ty(), field.column());

    let mut parts = vec![format!("    {}", column_name)];

    // Type with array suffix
    parts.push(sql_type.to_sql_string());

    // PRIMARY KEY for #[id] fields
    if field.is_id() {
        parts.push("PRIMARY KEY".to_string());
    } else if !sql_type.nullable {
        // NOT NULL unless nullable
        parts.push("NOT NULL".to_string());
    }

    // UNIQUE constraint; ci-unique columns get a functional
    // LOWER(...) index in generate_up instead of an inline constraint.
    if field.is_unique() && !field.column().ci {
        parts.push("UNIQUE".to_string());
    }

    // DEFAULT value: explicit declaration wins, otherwise an #[auto]
    // temporal column gets the default that makes the generated INSERT
    // (which skips auto columns) valid.
    if let Some(ref default) = field.column().default {
        parts.push(format!("DEFAULT {default}"));
    } else if let Some(default) = implicit_auto_default(field, &sql_type) {
        parts.push(format!("DEFAULT {default}"));
    }

    // CHECK constraint
    if let Some(ref check) = field.column().check {
        parts.push(format!("CHECK ({check})"));
    }

    // Foreign key REFERENCES from #[belongs_to]
    if field.is_relation()
        && let Some(parent) = field.belongs_to()
    {
        let parent_table = parent.to_string().to_case(Case::Snake);
        let ref_table = entity.full_table_name_for(&pluralize(&parent_table));
        let mut fk_str = format!("REFERENCES {ref_table}(id)");

        if let Some(action) = &field.storage.on_delete {
            fk_str.push_str(&format!(" ON DELETE {}", action.as_sql()));
        }

        parts.push(fk_str);
    }

    parts.join(" ")
}

/// Database-side default for an `#[auto]` column that carries no
/// explicit `#[column(default = ...)]`.
///
/// The generated INSERT skips `#[auto]` columns, so a `NOT NULL` one
/// without a default rejects every row. Temporal columns get the clock
/// function matching their type; anything else keeps no default, since
/// the macro has no meaningful value to invent.
fn implicit_auto_default(field: &FieldDef, sql_type: &SqlType) -> Option<&'static str> {
    if !field.is_auto() || sql_type.nullable || sql_type.array_dim > 0 {
        return None;
    }

    match sql_type.name.as_str() {
        "TIMESTAMPTZ" | "TIMESTAMP" => Some("NOW()"),
        "DATE" => Some("CURRENT_DATE"),
        "TIME" | "TIMETZ" => Some("CURRENT_TIME"),
        _ => None
    }
}

/// Generate CREATE INDEX for a single column.
fn generate_single_index(entity: &EntityDef, field: &FieldDef) -> String {
    let table = entity.table.clone();
    let column = field.column_name();

    let index_type = field.column().index.unwrap_or_default();
    let index_name = format!("idx_{table}_{column}");
    let using = index_type.as_sql_using();
    let qualified_table = entity.full_table_name_for(&table);

    format!("CREATE INDEX IF NOT EXISTS {index_name} ON {qualified_table}{using} ({column});\n")
}

/// Generate the functional unique index for a `#[column(unique, ci)]`
/// column: uniqueness is enforced on `LOWER(column)`.
fn generate_ci_unique_index(entity: &EntityDef, field: &FieldDef) -> String {
    let table = entity.table.clone();
    let column = field.column_name();
    let index_name = format!("{table}_{column}_lower_key");
    let qualified_table = entity.full_table_name_for(&table);

    format!(
        "CREATE UNIQUE INDEX IF NOT EXISTS {index_name} ON {qualified_table} (LOWER({column}));\n"
    )
}

/// Generate CREATE INDEX for a composite index.
fn generate_composite_index(entity: &EntityDef, idx: &CompositeIndexDef) -> String {
    let table = entity.table.clone();
    let index_name = idx.name_or_default(&table);
    let using = idx.index_type.as_sql_using();
    let unique_str = if idx.unique { "UNIQUE " } else { "" };
    let columns = idx.columns.join(", ");
    let qualified_table = entity.full_table_name_for(&table);

    let mut sql = format!(
        "CREATE {unique_str}INDEX IF NOT EXISTS {index_name} ON {qualified_table}{using} ({columns})"
    );

    if let Some(ref where_clause) = idx.where_clause {
        sql.push_str(&format!(" WHERE {where_clause}"));
    }

    sql.push_str(";\n");
    sql
}

/// Simple pluralization for table names.
fn pluralize(s: &str) -> String {
    if s.ends_with('s') || s.ends_with("sh") || s.ends_with("ch") || s.ends_with('x') {
        format!("{s}es")
    } else if s.ends_with('y') && !s.ends_with("ay") && !s.ends_with("ey") && !s.ends_with("oy") {
        format!("{}ies", &s[..s.len() - 1])
    } else {
        format!("{s}s")
    }
}

#[cfg(test)]
mod tests {
    use syn::DeriveInput;

    use super::*;
    use crate::entity::parse::EntityDef;

    fn parse_entity(tokens: proc_macro2::TokenStream) -> EntityDef {
        let input: DeriveInput = syn::parse_quote!(#tokens);
        EntityDef::from_derive_input(&input).unwrap()
    }

    #[test]
    fn pluralize_regular() {
        assert_eq!(pluralize("user"), "users");
        assert_eq!(pluralize("post"), "posts");
    }

    #[test]
    fn pluralize_es() {
        assert_eq!(pluralize("status"), "statuses");
        assert_eq!(pluralize("match"), "matches");
    }

    #[test]
    fn pluralize_ies() {
        assert_eq!(pluralize("category"), "categories");
        assert_eq!(pluralize("company"), "companies");
    }

    #[test]
    fn pluralize_ey_oy() {
        assert_eq!(pluralize("key"), "keys");
        assert_eq!(pluralize("toy"), "toys");
    }

    #[test]
    fn pluralize_sh() {
        assert_eq!(pluralize("wish"), "wishes");
        assert_eq!(pluralize("bush"), "bushes");
    }

    #[test]
    fn pluralize_x() {
        assert_eq!(pluralize("box"), "boxes");
        assert_eq!(pluralize("fox"), "foxes");
    }

    #[test]
    fn pluralize_ay() {
        assert_eq!(pluralize("day"), "days");
        assert_eq!(pluralize("way"), "ways");
    }

    #[test]
    fn generate_up_basic() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                pub name: String,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("CREATE TABLE IF NOT EXISTS users"));
        assert!(sql.contains("id UUID PRIMARY KEY"));
        assert!(sql.contains("name TEXT NOT NULL"));
    }

    #[test]
    fn generate_down_basic() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", schema = "core", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        });
        let sql = generate_down(&entity);
        assert_eq!(sql, "DROP TABLE IF EXISTS core.users CASCADE;\n");
    }

    #[test]
    fn generate_up_with_unique() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                #[column(unique)]
                pub email: String,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("email TEXT NOT NULL UNIQUE"));
    }

    #[test]
    fn auto_temporal_columns_get_a_clock_default() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(response)]
                #[auto]
                pub created_at: chrono::DateTime<chrono::Utc>,
                #[field(response)]
                #[auto]
                pub born_on: chrono::NaiveDate,
                #[field(response)]
                #[auto]
                pub rings_at: chrono::NaiveTime,
            }
        });
        let sql = generate_up(&entity);
        assert!(
            sql.contains("created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()"),
            "the generated INSERT skips auto columns, so the DDL must supply the value: {sql}"
        );
        assert!(sql.contains("born_on DATE NOT NULL DEFAULT CURRENT_DATE"));
        assert!(sql.contains("rings_at TIME NOT NULL DEFAULT CURRENT_TIME"));
    }

    #[test]
    fn explicit_default_wins_over_the_implicit_one() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(response)]
                #[auto]
                #[column(default = "'epoch'")]
                pub created_at: chrono::DateTime<chrono::Utc>,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("created_at TIMESTAMPTZ NOT NULL DEFAULT 'epoch'"));
        assert!(!sql.contains("NOW()"));
    }

    #[test]
    fn non_temporal_and_nullable_auto_columns_keep_no_default() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(response)]
                #[auto]
                pub token: String,
                #[field(response)]
                #[auto]
                pub seen_at: Option<chrono::DateTime<chrono::Utc>>,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("token TEXT NOT NULL,"));
        assert!(
            !sql.contains("seen_at TIMESTAMPTZ DEFAULT"),
            "a nullable auto column already accepts the absent value: {sql}"
        );
    }

    #[test]
    fn generate_up_with_default() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                #[column(default = "true")]
                pub active: bool,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("DEFAULT true"));
    }

    #[test]
    fn generate_up_with_check() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                #[column(check = "age >= 0")]
                pub age: i32,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("CHECK (age >= 0)"));
    }

    #[test]
    fn generate_up_with_index() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                #[column(index)]
                pub status: String,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("CREATE INDEX IF NOT EXISTS idx_users_status"));
    }

    #[test]
    fn generate_up_with_gin_index() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                #[column(index = "gin")]
                pub tags: Vec<String>,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("USING gin"));
    }

    #[test]
    fn generate_up_with_nullable() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                pub bio: Option<String>,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("bio TEXT"));
        assert!(!sql.contains("bio TEXT NOT NULL"));
    }

    #[test]
    fn generate_up_with_varchar() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                #[column(varchar = 100)]
                pub name: String,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("VARCHAR(100)"));
    }

    #[test]
    fn generate_up_with_belongs_to() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "posts", migrations)]
            pub struct Post {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                #[belongs_to(User)]
                pub user_id: uuid::Uuid,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("REFERENCES users(id)"));
    }

    #[test]
    fn generate_up_with_belongs_to_on_delete_cascade() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "posts", migrations)]
            pub struct Post {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                #[belongs_to(User, on_delete = "cascade")]
                pub user_id: uuid::Uuid,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("REFERENCES users(id) ON DELETE CASCADE"));
    }

    #[test]
    fn generate_composite_index_basic() {
        let idx = CompositeIndexDef {
            name:         None,
            columns:      vec!["name".to_string(), "email".to_string()],
            index_type:   crate::entity::parse::IndexType::BTree,
            unique:       false,
            where_clause: None
        };
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                pub name: String,
                #[field(create, response)]
                pub email: String,
            }
        });
        let sql = generate_composite_index(&entity, &idx);
        assert!(sql.contains("CREATE INDEX IF NOT EXISTS idx_users_name_email"));
        assert!(sql.contains("(name, email)"));
    }

    #[test]
    fn generate_up_ci_unique_uses_functional_index() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                #[column(unique, ci)]
                pub username: String,
            }
        });
        let sql = generate_up(&entity);
        assert!(!sql.contains("username TEXT NOT NULL UNIQUE"));
        assert!(sql.contains(
            "CREATE UNIQUE INDEX IF NOT EXISTS users_username_lower_key ON users (LOWER(username));"
        ));
    }

    #[test]
    fn generate_composite_index_unique() {
        let idx = CompositeIndexDef {
            name:         None,
            columns:      vec!["tenant_id".to_string(), "email".to_string()],
            index_type:   crate::entity::parse::IndexType::BTree,
            unique:       true,
            where_clause: None
        };
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        });
        let sql = generate_composite_index(&entity, &idx);
        assert!(sql.contains("CREATE UNIQUE INDEX"));
        assert!(sql.contains("(tenant_id, email)"));
    }

    #[test]
    fn generate_composite_index_with_where() {
        let idx = CompositeIndexDef {
            name:         Some("idx_active_users".to_string()),
            columns:      vec!["email".to_string()],
            index_type:   crate::entity::parse::IndexType::BTree,
            unique:       false,
            where_clause: Some("active = true".to_string())
        };
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        });
        let sql = generate_composite_index(&entity, &idx);
        assert!(sql.contains("idx_active_users"));
        assert!(sql.contains("WHERE active = true"));
    }

    #[test]
    fn generate_composite_index_gin() {
        let idx = CompositeIndexDef {
            name:         None,
            columns:      vec!["tags".to_string()],
            index_type:   crate::entity::parse::IndexType::Gin,
            unique:       false,
            where_clause: None
        };
        let entity = parse_entity(quote::quote! {
            #[entity(table = "posts", migrations)]
            pub struct Post {
                #[id]
                pub id: uuid::Uuid,
            }
        });
        let sql = generate_composite_index(&entity, &idx);
        assert!(sql.contains("USING gin"));
    }

    #[test]
    fn generate_up_with_composite_indexes() {
        let mut entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                pub name: String,
                #[field(create, response)]
                pub email: String,
            }
        });
        entity.indexes.push(CompositeIndexDef {
            name:         None,
            columns:      vec!["name".to_string(), "email".to_string()],
            index_type:   crate::entity::parse::IndexType::BTree,
            unique:       false,
            where_clause: None
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("CREATE INDEX IF NOT EXISTS idx_users_name_email"));
    }

    #[test]
    fn generate_up_with_explicit_public_schema() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", schema = "public", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                pub name: String,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("CREATE TABLE IF NOT EXISTS public.users"));
    }

    #[test]
    fn generate_up_with_custom_schema() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", schema = "core", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                pub name: String,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("CREATE TABLE IF NOT EXISTS core.users"));
    }

    #[test]
    fn generate_down_with_explicit_schema() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", schema = "core", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        });
        let sql = generate_down(&entity);
        assert_eq!(sql, "DROP TABLE IF EXISTS core.users CASCADE;\n");
    }

    #[test]
    fn generate_down_without_schema() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
            }
        });
        let sql = generate_down(&entity);
        assert_eq!(sql, "DROP TABLE IF EXISTS users CASCADE;\n");
    }

    #[test]
    fn generate_single_index_with_explicit_schema() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", schema = "core", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                #[column(index)]
                pub email: String,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("CREATE INDEX IF NOT EXISTS idx_users_email ON core.users"));
    }

    #[test]
    fn generate_single_index_without_schema() {
        let entity = parse_entity(quote::quote! {
            #[entity(table = "users", migrations)]
            pub struct User {
                #[id]
                pub id: uuid::Uuid,
                #[field(create, response)]
                #[column(index)]
                pub email: String,
            }
        });
        let sql = generate_up(&entity);
        assert!(sql.contains("CREATE INDEX IF NOT EXISTS idx_users_email ON users"));
    }
}