sea-orm 2.0.0-rc.42

🐚 An async & dynamic 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
#![allow(unused_imports, dead_code)]

pub mod common;

use crate::common::TestContext;
use sea_orm::{
    DatabaseBackend, DatabaseConnection, DbErr, Statement,
    entity::*,
    query::*,
    sea_query::{Condition, Expr, Query, SelectStatement},
};

// Scenario 1: table is first synced with a `#[sea_orm(unique)]` column already
// present. Repeated syncs must not drop the column-level unique constraint.
mod item_v1 {
    use sea_orm::entity::prelude::*;

    #[sea_orm::model]
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(table_name = "sync_item")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        #[sea_orm(unique)]
        pub name: String,
    }

    impl ActiveModelBehavior for ActiveModel {}
}

// Scenario 2a: initial version of the table — no unique column yet.
mod product_v1 {
    use sea_orm::entity::prelude::*;

    #[sea_orm::model]
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(table_name = "sync_product")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
    }

    impl ActiveModelBehavior for ActiveModel {}
}

// Scenario 2b: updated version — a unique column is added.
mod product_v2 {
    use sea_orm::entity::prelude::*;

    #[sea_orm::model]
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(table_name = "sync_product")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        #[sea_orm(unique)]
        pub sku: String,
    }

    impl ActiveModelBehavior for ActiveModel {}
}

// Scenario 4a: initial version — column has UNIQUE.
mod order_v1 {
    use sea_orm::entity::prelude::*;

    #[sea_orm::model]
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(table_name = "sync_order")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        #[sea_orm(unique)]
        pub ref_no: String,
    }

    impl ActiveModelBehavior for ActiveModel {}
}

// Scenario 4b: UNIQUE removed from the column.
mod order_v2 {
    use sea_orm::entity::prelude::*;

    #[sea_orm::model]
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(table_name = "sync_order")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        pub ref_no: String,
    }

    impl ActiveModelBehavior for ActiveModel {}
}

// Scenario 3a: initial version — column exists without UNIQUE.
mod user_v1 {
    use sea_orm::entity::prelude::*;

    #[sea_orm::model]
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(table_name = "sync_user")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        pub email: String,
    }

    impl ActiveModelBehavior for ActiveModel {}
}

// Scenario 3b: updated version — the existing column is made unique.
mod user_v2 {
    use sea_orm::entity::prelude::*;

    #[sea_orm::model]
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(table_name = "sync_user")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        #[sea_orm(unique)]
        pub email: String,
    }

    impl ActiveModelBehavior for ActiveModel {}
}

// Entity in a non-default PostgreSQL schema — for multi-schema sync testing.
mod custom_schema_entity {
    use sea_orm::entity::prelude::*;

    #[sea_orm::model]
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(schema_name = "test_schema_2952", table_name = "sync_custom_schema")]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        pub name: String,
    }

    impl ActiveModelBehavior for ActiveModel {}
}

// Entity with generated indexes in a non-default PostgreSQL schema.
mod custom_schema_indexed_entity {
    use sea_orm::entity::prelude::*;

    #[sea_orm::model]
    #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
    #[sea_orm(
        schema_name = "test_schema_3084",
        table_name = "sync_custom_schema_indexed"
    )]
    pub struct Model {
        #[sea_orm(primary_key)]
        pub id: i32,
        #[sea_orm(indexed)]
        pub email: String,
        #[sea_orm(unique_key = "tenant_name")]
        pub tenant_id: i32,
        #[sea_orm(unique_key = "tenant_name")]
        pub name: String,
    }

    impl ActiveModelBehavior for ActiveModel {}
}

/// Regression test for <https://github.com/SeaQL/sea-orm/issues/2970>.
///
/// A table with a `#[sea_orm(unique)]` column is created on the first sync.
/// The subsequent sync must not attempt to drop the column-level unique index.
#[sea_orm_macros::test]
async fn test_sync_unique_column_no_drop() -> Result<(), DbErr> {
    let ctx = TestContext::new("test_sync_unique_column_no_drop").await;
    let db = &ctx.db;

    #[cfg(feature = "schema-sync")]
    {
        // First sync: creates the table with the unique column
        db.get_schema_builder()
            .register(item_v1::Entity)
            .sync(db)
            .await?;

        // Second sync: must not try to drop the column-level unique index
        db.get_schema_builder()
            .register(item_v1::Entity)
            .sync(db)
            .await?;

        #[cfg(feature = "sqlx-postgres")]
        assert!(
            pg_index_exists(db, "sync_item", "sync_item_name_key").await?,
            "unique index on `sync_item.name` should still exist after repeated sync"
        );
    }

    Ok(())
}

/// Regression test for <https://github.com/SeaQL/sea-orm/issues/2970>.
///
/// A unique column is added to an existing table via sync (ALTER TABLE ADD
/// COLUMN … UNIQUE), which creates a column-level unique index. A subsequent
/// sync must not attempt to drop that index.
#[sea_orm_macros::test]
#[cfg(not(any(feature = "sqlx-sqlite", feature = "rusqlite")))]
async fn test_sync_add_unique_column_no_drop() -> Result<(), DbErr> {
    let ctx = TestContext::new("test_sync_add_unique_column_no_drop").await;
    let db = &ctx.db;

    #[cfg(feature = "schema-sync")]
    {
        // First sync: creates the table without the unique column
        db.get_schema_builder()
            .register(product_v1::Entity)
            .sync(db)
            .await?;

        // Second sync: adds the unique column via ALTER TABLE ADD COLUMN … UNIQUE
        db.get_schema_builder()
            .register(product_v2::Entity)
            .sync(db)
            .await?;

        // Third sync: must not try to drop the unique index created above
        db.get_schema_builder()
            .register(product_v2::Entity)
            .sync(db)
            .await?;

        #[cfg(feature = "sqlx-postgres")]
        assert!(
            pg_index_exists(db, "sync_product", "sync_product_sku_key").await?,
            "unique index on `sync_product.sku` should still exist after repeated sync"
        );
    }

    Ok(())
}

/// Scenario 3: an existing column is made unique in a later sync.
///
/// When a column that already exists in the DB is annotated with
/// `#[sea_orm(unique)]`, the sync must create a unique index for it.
#[sea_orm_macros::test]
async fn test_sync_make_existing_column_unique() -> Result<(), DbErr> {
    let ctx = TestContext::new("test_sync_make_existing_column_unique").await;
    let db = &ctx.db;

    #[cfg(feature = "schema-sync")]
    {
        // First sync: creates the table with a plain (non-unique) email column
        db.get_schema_builder()
            .register(user_v1::Entity)
            .sync(db)
            .await?;

        // Second sync: email is now marked unique — should create the unique index
        db.get_schema_builder()
            .register(user_v2::Entity)
            .sync(db)
            .await?;

        // Third sync: must not try to drop or re-create the index
        db.get_schema_builder()
            .register(user_v2::Entity)
            .sync(db)
            .await?;

        #[cfg(feature = "sqlx-postgres")]
        assert!(
            pg_index_exists(db, "sync_user", "idx-sync_user-email").await?,
            "unique index on `sync_user.email` should be created when column is made unique"
        );
    }

    Ok(())
}

/// Regression test for <https://github.com/SeaQL/sea-orm/issues/2994>.
///
/// A column marked `#[sea_orm(unique)]` is synced, then the unique attribute is
/// removed. The second sync must drop the PostgreSQL constraint without error.
#[sea_orm_macros::test]
#[cfg(feature = "sqlx-postgres")]
async fn test_sync_drop_unique_constraint() -> Result<(), DbErr> {
    let ctx = TestContext::new("test_sync_drop_unique_constraint").await;
    let db = &ctx.db;

    #[cfg(feature = "schema-sync")]
    {
        // First sync: creates the table with the unique constraint
        db.get_schema_builder()
            .register(order_v1::Entity)
            .sync(db)
            .await?;

        assert!(
            pg_index_exists(db, "sync_order", "sync_order_ref_no_key").await?,
            "unique constraint should exist after first sync"
        );

        // Second sync: unique is removed — must not error on PostgreSQL
        db.get_schema_builder()
            .register(order_v2::Entity)
            .sync(db)
            .await?;

        assert!(
            !pg_index_exists(db, "sync_order", "sync_order_ref_no_key").await?,
            "unique constraint should be gone after second sync"
        );
    }

    Ok(())
}

/// Regression test for <https://github.com/SeaQL/sea-orm/issues/2952>.
///
/// An entity with `schema_name` pointing to a non-default PostgreSQL schema is
/// synced twice. The second sync must not fail with "relation already exists".
#[sea_orm_macros::test]
#[cfg(feature = "sqlx-postgres")]
async fn test_sync_non_default_schema() -> Result<(), DbErr> {
    let ctx = TestContext::new("test_sync_non_default_schema").await;
    let db = &ctx.db;

    #[cfg(feature = "schema-sync")]
    {
        db.execute_raw(Statement::from_string(
            DatabaseBackend::Postgres,
            "CREATE SCHEMA IF NOT EXISTS test_schema_2952".to_owned(),
        ))
        .await?;

        // First sync: creates the table in the non-default schema
        db.get_schema_builder()
            .register(custom_schema_entity::Entity)
            .sync(db)
            .await?;

        assert!(
            pg_table_exists_in_schema(db, "test_schema_2952", "sync_custom_schema").await?,
            "table should exist in schema `test_schema_2952`"
        );

        assert!(
            !pg_table_exists_in_schema(db, "public", "sync_custom_schema").await?,
            "table should NOT exist in schema `public`"
        );

        // Second sync: must not fail with "relation already exists"
        db.get_schema_builder()
            .register(custom_schema_entity::Entity)
            .sync(db)
            .await?;
    }

    Ok(())
}

/// Regression test for <https://github.com/SeaQL/sea-orm/issues/3084>.
///
/// An entity with `schema_name` pointing to a non-default PostgreSQL schema
/// should create generated indexes against that schema-qualified table.
#[sea_orm_macros::test]
#[cfg(feature = "sqlx-postgres")]
async fn test_sync_non_default_schema_indexes() -> Result<(), DbErr> {
    let ctx = TestContext::new("test_sync_non_default_schema_indexes").await;
    let db = &ctx.db;

    #[cfg(feature = "schema-sync")]
    {
        db.execute_raw(Statement::from_string(
            DatabaseBackend::Postgres,
            "CREATE SCHEMA IF NOT EXISTS test_schema_3084".to_owned(),
        ))
        .await?;

        db.get_schema_builder()
            .register(custom_schema_indexed_entity::Entity)
            .sync(db)
            .await?;

        assert!(
            pg_table_exists_in_schema(db, "test_schema_3084", "sync_custom_schema_indexed").await?,
            "table should exist in schema `test_schema_3084`"
        );

        assert!(
            pg_index_exists_in_schema(
                db,
                "test_schema_3084",
                "sync_custom_schema_indexed",
                "idx-sync_custom_schema_indexed-email"
            )
            .await?,
            "index on `sync_custom_schema_indexed.email` should exist in schema `test_schema_3084`"
        );

        assert!(
            pg_index_exists_in_schema(
                db,
                "test_schema_3084",
                "sync_custom_schema_indexed",
                "idx-sync_custom_schema_indexed-tenant_name"
            )
            .await?,
            "unique index on `sync_custom_schema_indexed.(tenant_id, name)` should exist in schema `test_schema_3084`"
        );

        db.get_schema_builder()
            .register(custom_schema_indexed_entity::Entity)
            .sync(db)
            .await?;
    }

    Ok(())
}

#[cfg(feature = "sqlx-postgres")]
fn pg_table_exists_in_schema_query(schema: &str, table: &str) -> SelectStatement {
    Query::select()
        .expr(Expr::cust("COUNT(*) > 0"))
        .from(("information_schema", "tables"))
        .cond_where(
            Condition::all()
                .add(Expr::col("table_schema").eq(schema))
                .add(Expr::col("table_name").eq(table)),
        )
        .to_owned()
}

#[cfg(feature = "sqlx-postgres")]
#[test]
fn pg_table_exists_in_schema_query_qualifies_information_schema() {
    use sea_orm::sea_query::PostgresQueryBuilder;

    assert_eq!(
        pg_table_exists_in_schema_query("test_schema_2952", "sync_custom_schema")
            .to_string(PostgresQueryBuilder),
        r#"SELECT COUNT(*) > 0 FROM "information_schema"."tables" WHERE "table_schema" = 'test_schema_2952' AND "table_name" = 'sync_custom_schema'"#,
    );
}

#[cfg(feature = "sqlx-postgres")]
async fn pg_table_exists_in_schema(
    db: &DatabaseConnection,
    schema: &str,
    table: &str,
) -> Result<bool, DbErr> {
    db.query_one(&pg_table_exists_in_schema_query(schema, table))
        .await?
        .unwrap()
        .try_get_by_index(0)
        .map_err(DbErr::from)
}

#[cfg(feature = "sqlx-postgres")]
fn pg_index_exists_in_schema_query(schema: &str, table: &str, index: &str) -> SelectStatement {
    Query::select()
        .expr(Expr::cust("COUNT(*) > 0"))
        .from("pg_indexes")
        .cond_where(
            Condition::all()
                .add(Expr::col("schemaname").eq(schema))
                .add(Expr::col("tablename").eq(table))
                .add(Expr::col("indexname").eq(index)),
        )
        .to_owned()
}

#[cfg(feature = "sqlx-postgres")]
async fn pg_index_exists_in_schema(
    db: &DatabaseConnection,
    schema: &str,
    table: &str,
    index: &str,
) -> Result<bool, DbErr> {
    db.query_one(&pg_index_exists_in_schema_query(schema, table, index))
        .await?
        .unwrap()
        .try_get_by_index(0)
        .map_err(DbErr::from)
}

#[cfg(feature = "sqlx-postgres")]
async fn pg_index_exists(db: &DatabaseConnection, table: &str, index: &str) -> Result<bool, DbErr> {
    db.query_one(
        Query::select()
            .expr(Expr::cust("COUNT(*) > 0"))
            .from("pg_indexes")
            .cond_where(
                Condition::all()
                    .add(Expr::cust("schemaname = CURRENT_SCHEMA()"))
                    .add(Expr::col("tablename").eq(table))
                    .add(Expr::col("indexname").eq(index)),
            ),
    )
    .await?
    .unwrap()
    .try_get_by_index(0)
    .map_err(DbErr::from)
}