sea-orm-sync 2.0.0-rc.38

🐚 The sync version of SeaORM
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
use super::ReturningSelector;
use crate::{
    ActiveModelTrait, ColumnTrait, ConnectionTrait, DbBackend, EntityTrait, Insert, InsertMany,
    IntoActiveModel, Iterable, PrimaryKeyToColumn, PrimaryKeyTrait, SelectModel, TryFromU64,
    TryInsert, error::*,
};
use sea_query::{FromValueTuple, Iden, InsertStatement, Query, ReturningClause, ValueTuple};
use std::marker::PhantomData;

type PrimaryKey<A> = <<A as ActiveModelTrait>::Entity as EntityTrait>::PrimaryKey;

/// Defines a structure to perform INSERT operations in an ActiveModel
#[derive(Debug)]
pub struct Inserter<A>
where
    A: ActiveModelTrait,
{
    primary_key: Option<ValueTuple>,
    query: InsertStatement,
    model: PhantomData<A>,
}

/// The result of an INSERT operation on an ActiveModel
#[derive(Debug)]
#[non_exhaustive]
pub struct InsertResult<A>
where
    A: ActiveModelTrait,
{
    /// The primary key value of the last inserted row
    pub last_insert_id: <PrimaryKey<A> as PrimaryKeyTrait>::ValueType,
}

/// The result of an INSERT many operation for a set of ActiveModels
#[derive(Debug)]
#[non_exhaustive]
pub struct InsertManyResult<A>
where
    A: ActiveModelTrait,
{
    /// The primary key value of the last inserted row
    pub last_insert_id: Option<<PrimaryKey<A> as PrimaryKeyTrait>::ValueType>,
}

/// The result of executing a [`crate::TryInsert`].
///
/// This enum represents no‑op inserts (e.g. conflict `DO NOTHING`) without treating
/// them as errors.
#[derive(Debug)]
pub enum TryInsertResult<T> {
    /// There was nothing to insert, so no SQL was executed.
    ///
    /// This typically happens when creating a [`crate::TryInsert`] from an empty iterator or None.
    Empty,
    /// The statement was executed, but SeaORM could not get the inserted row / insert id.
    ///
    /// This is commonly caused by `ON CONFLICT ... DO NOTHING` (Postgres / SQLite) or the MySQL
    /// polyfill (`ON DUPLICATE KEY UPDATE pk = pk`).
    ///
    /// Note that this variant maps from `DbErr::RecordNotInserted`, so it can also represent other
    /// situations where the backend/driver reports no inserted row (e.g. an empty `RETURNING`
    /// result set or a "no-op" update in MySQL where `last_insert_id` is reported as `0`). In rare
    /// cases, this can be a false negative where a row was inserted but the backend did not report
    /// it.
    Conflicted,
    /// Successfully inserted
    Inserted(T),
}

impl<A> TryInsertResult<InsertResult<A>>
where
    A: ActiveModelTrait,
{
    /// Extract the last inserted id.
    ///
    /// - [`TryInsertResult::Empty`] => `Ok(None)`
    /// - [`TryInsertResult::Inserted`] => `Ok(Some(last_insert_id))`
    /// - [`TryInsertResult::Conflicted`] => `Err(DbErr::RecordNotInserted)`
    pub fn last_insert_id(
        self,
    ) -> Result<Option<<PrimaryKey<A> as PrimaryKeyTrait>::ValueType>, DbErr> {
        match self {
            Self::Empty => Ok(None),
            Self::Inserted(v) => Ok(Some(v.last_insert_id)),
            Self::Conflicted => Err(DbErr::RecordNotInserted),
        }
    }
}

impl<A> TryInsert<A>
where
    A: ActiveModelTrait,
{
    /// Execute an insert operation
    pub fn exec<C>(self, db: &C) -> Result<TryInsertResult<InsertResult<A>>, DbErr>
    where
        C: ConnectionTrait,
    {
        if self.empty {
            return Ok(TryInsertResult::Empty);
        }
        let res = self.insert_struct.exec(db);
        match res {
            Ok(res) => Ok(TryInsertResult::Inserted(res)),
            Err(DbErr::RecordNotInserted) => Ok(TryInsertResult::Conflicted),
            Err(err) => Err(err),
        }
    }

    /// Execute an insert operation without returning (don't use `RETURNING` syntax)
    /// Number of rows affected is returned
    pub fn exec_without_returning<C>(self, db: &C) -> Result<TryInsertResult<u64>, DbErr>
    where
        C: ConnectionTrait,
    {
        if self.empty {
            return Ok(TryInsertResult::Empty);
        }
        let res = self.insert_struct.exec_without_returning(db);
        match res {
            Ok(res) => Ok(TryInsertResult::Inserted(res)),
            Err(DbErr::RecordNotInserted) => Ok(TryInsertResult::Conflicted),
            Err(err) => Err(err),
        }
    }

    /// Execute an insert operation and return the inserted model (use `RETURNING` syntax if supported)
    pub fn exec_with_returning<C>(
        self,
        db: &C,
    ) -> Result<TryInsertResult<<A::Entity as EntityTrait>::Model>, DbErr>
    where
        <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
        C: ConnectionTrait,
    {
        if self.empty {
            return Ok(TryInsertResult::Empty);
        }
        let res = self.insert_struct.exec_with_returning(db);
        match res {
            Ok(res) => Ok(TryInsertResult::Inserted(res)),
            Err(DbErr::RecordNotInserted) => Ok(TryInsertResult::Conflicted),
            Err(err) => Err(err),
        }
    }

    /// Execute an insert operation and return primary keys of inserted models
    pub fn exec_with_returning_keys<C>(
        self,
        db: &C,
    ) -> Result<TryInsertResult<Vec<<PrimaryKey<A> as PrimaryKeyTrait>::ValueType>>, DbErr>
    where
        <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
        C: ConnectionTrait,
    {
        if self.empty {
            return Ok(TryInsertResult::Empty);
        }

        let res = self.insert_struct.exec_with_returning_keys(db);
        match res {
            Ok(res) => Ok(TryInsertResult::Inserted(res)),
            Err(DbErr::RecordNotInserted) => Ok(TryInsertResult::Conflicted),
            Err(err) => Err(err),
        }
    }

    /// Execute an insert operation and return all inserted models
    pub fn exec_with_returning_many<C>(
        self,
        db: &C,
    ) -> Result<TryInsertResult<Vec<<A::Entity as EntityTrait>::Model>>, DbErr>
    where
        <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
        C: ConnectionTrait,
    {
        if self.empty {
            return Ok(TryInsertResult::Empty);
        }

        let res = self.insert_struct.exec_with_returning_many(db);
        match res {
            Ok(res) => Ok(TryInsertResult::Inserted(res)),
            Err(DbErr::RecordNotInserted) => Ok(TryInsertResult::Conflicted),
            Err(err) => Err(err),
        }
    }
}

impl<A> Insert<A>
where
    A: ActiveModelTrait,
{
    /// Execute an insert operation
    pub fn exec<'a, C>(self, db: &'a C) -> Result<InsertResult<A>, DbErr>
    where
        C: ConnectionTrait,
        A: 'a,
    {
        // so that self is dropped before entering await
        let mut query = self.query;
        if db.support_returning() {
            query.returning(returning_pk::<A>(db.get_database_backend()));
        }
        Inserter::<A>::new(self.primary_key, query).exec(db)
    }

    /// Execute an insert operation without returning (don't use `RETURNING` syntax)
    /// Number of rows affected is returned
    pub fn exec_without_returning<'a, C>(self, db: &'a C) -> Result<u64, DbErr>
    where
        C: ConnectionTrait,
        A: 'a,
    {
        Inserter::<A>::new(self.primary_key, self.query).exec_without_returning(db)
    }

    /// Execute an insert operation and return the inserted model (use `RETURNING` syntax if supported)
    ///
    /// + To get back all inserted models, use [`exec_with_returning_many`].
    /// + To get back all inserted primary keys, use [`exec_with_returning_keys`].
    pub fn exec_with_returning<'a, C>(
        self,
        db: &'a C,
    ) -> Result<<A::Entity as EntityTrait>::Model, DbErr>
    where
        <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
        C: ConnectionTrait,
        A: 'a,
    {
        Inserter::<A>::new(self.primary_key, self.query).exec_with_returning(db)
    }

    /// Execute an insert operation and return primary keys of inserted models
    pub fn exec_with_returning_keys<'a, C>(
        self,
        db: &'a C,
    ) -> Result<Vec<<PrimaryKey<A> as PrimaryKeyTrait>::ValueType>, DbErr>
    where
        <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
        C: ConnectionTrait,
        A: 'a,
    {
        Inserter::<A>::new(self.primary_key, self.query).exec_with_returning_keys(db)
    }

    /// Execute an insert operation and return all inserted models
    pub fn exec_with_returning_many<'a, C>(
        self,
        db: &'a C,
    ) -> Result<Vec<<A::Entity as EntityTrait>::Model>, DbErr>
    where
        <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
        C: ConnectionTrait,
        A: 'a,
    {
        Inserter::<A>::new(self.primary_key, self.query).exec_with_returning_many(db)
    }
}

impl<A> InsertMany<A>
where
    A: ActiveModelTrait,
{
    /// Execute an insert operation
    pub fn exec<C>(self, db: &C) -> Result<InsertManyResult<A>, DbErr>
    where
        C: ConnectionTrait,
    {
        if self.empty {
            return Ok(InsertManyResult {
                last_insert_id: None,
            });
        }
        let res = self.into_one().exec(db);
        match res {
            Ok(r) => Ok(InsertManyResult {
                last_insert_id: Some(r.last_insert_id),
            }),
            Err(err) => Err(err),
        }
    }

    /// Execute an insert operation without returning (don't use `RETURNING` syntax)
    /// Number of rows affected is returned
    pub fn exec_without_returning<C>(self, db: &C) -> Result<u64, DbErr>
    where
        C: ConnectionTrait,
    {
        if self.empty {
            return Ok(0);
        }
        self.into_one().exec_without_returning(db)
    }

    /// Execute an insert operation and return all inserted models
    pub fn exec_with_returning<C>(
        self,
        db: &C,
    ) -> Result<Vec<<A::Entity as EntityTrait>::Model>, DbErr>
    where
        <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
        C: ConnectionTrait,
    {
        if self.empty {
            return Ok(Vec::new());
        }

        self.into_one().exec_with_returning_many(db)
    }

    /// Alias to [`InsertMany::exec_with_returning`].
    #[deprecated(
        since = "2.0.0",
        note = "Please use [`InsertMany::exec_with_returning`]"
    )]
    pub fn exec_with_returning_many<C>(
        self,
        db: &C,
    ) -> Result<Vec<<A::Entity as EntityTrait>::Model>, DbErr>
    where
        <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
        C: ConnectionTrait,
    {
        if self.empty {
            return Ok(Vec::new());
        }

        self.into_one().exec_with_returning_many(db)
    }

    /// Execute an insert operation and return primary keys of inserted models
    pub fn exec_with_returning_keys<C>(
        self,
        db: &C,
    ) -> Result<Vec<<PrimaryKey<A> as PrimaryKeyTrait>::ValueType>, DbErr>
    where
        <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
        C: ConnectionTrait,
    {
        if self.empty {
            return Ok(Vec::new());
        }

        self.into_one().exec_with_returning_keys(db)
    }
}

impl<A> Inserter<A>
where
    A: ActiveModelTrait,
{
    /// Instantiate a new insert operation
    pub fn new(primary_key: Option<ValueTuple>, query: InsertStatement) -> Self {
        Self {
            primary_key,
            query,
            model: PhantomData,
        }
    }

    /// Execute an insert operation, returning the last inserted id
    pub fn exec<'a, C>(self, db: &'a C) -> Result<InsertResult<A>, DbErr>
    where
        C: ConnectionTrait,
        A: 'a,
    {
        exec_insert(self.primary_key, self.query, db)
    }

    /// Execute an insert operation
    pub fn exec_without_returning<'a, C>(self, db: &'a C) -> Result<u64, DbErr>
    where
        C: ConnectionTrait,
        A: 'a,
    {
        exec_insert_without_returning(self.query, db)
    }

    /// Execute an insert operation and return the inserted model (use `RETURNING` syntax if supported)
    pub fn exec_with_returning<'a, C>(
        self,
        db: &'a C,
    ) -> Result<<A::Entity as EntityTrait>::Model, DbErr>
    where
        <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
        C: ConnectionTrait,
        A: 'a,
    {
        exec_insert_with_returning::<A, _>(self.primary_key, self.query, db)
    }

    /// Execute an insert operation and return primary keys of inserted models
    pub fn exec_with_returning_keys<'a, C>(
        self,
        db: &'a C,
    ) -> Result<Vec<<PrimaryKey<A> as PrimaryKeyTrait>::ValueType>, DbErr>
    where
        <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
        C: ConnectionTrait,
        A: 'a,
    {
        exec_insert_with_returning_keys::<A, _>(self.query, db)
    }

    /// Execute an insert operation and return all inserted models
    pub fn exec_with_returning_many<'a, C>(
        self,
        db: &'a C,
    ) -> Result<Vec<<A::Entity as EntityTrait>::Model>, DbErr>
    where
        <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
        C: ConnectionTrait,
        A: 'a,
    {
        exec_insert_with_returning_many::<A, _>(self.query, db)
    }
}

fn exec_insert<A, C>(
    primary_key: Option<ValueTuple>,
    statement: InsertStatement,
    db: &C,
) -> Result<InsertResult<A>, DbErr>
where
    C: ConnectionTrait,
    A: ActiveModelTrait,
{
    type ValueTypeOf<A> = <PrimaryKey<A> as PrimaryKeyTrait>::ValueType;

    let db_backend = db.get_database_backend();

    let last_insert_id = match (primary_key, db.support_returning()) {
        (_, true) => {
            let mut rows = db.query_all(&statement)?;
            let row = match rows.pop() {
                Some(row) => row,
                None => return Err(DbErr::RecordNotInserted),
            };
            let cols = PrimaryKey::<A>::iter()
                .map(|col| col.to_string())
                .collect::<Vec<_>>();
            row.try_get_many("", cols.as_ref())
                .map_err(|_| DbErr::UnpackInsertId)?
        }
        (Some(value_tuple), false) => {
            let res = db.execute(&statement)?;
            if res.rows_affected() == 0 {
                return Err(DbErr::RecordNotInserted);
            }
            FromValueTuple::from_value_tuple(value_tuple)
        }
        (None, false) => {
            let res = db.execute(&statement)?;
            if res.rows_affected() == 0 {
                return Err(DbErr::RecordNotInserted);
            }
            let last_insert_id = res.last_insert_id();
            // For MySQL, the affected-rows number:
            //   - The affected-rows value per row is `1` if the row is inserted as a new row,
            //   - `2` if an existing row is updated,
            //   - and `0` if an existing row is set to its current values.
            // Reference: https://dev.mysql.com/doc/refman/8.4/en/insert-on-duplicate.html
            if db_backend == DbBackend::MySql && last_insert_id == 0 {
                return Err(DbErr::RecordNotInserted);
            }
            ValueTypeOf::<A>::try_from_u64(last_insert_id).map_err(|_| DbErr::UnpackInsertId)?
        }
    };

    Ok(InsertResult { last_insert_id })
}

fn exec_insert_without_returning<C>(insert_statement: InsertStatement, db: &C) -> Result<u64, DbErr>
where
    C: ConnectionTrait,
{
    let exec_result = db.execute(&insert_statement)?;
    Ok(exec_result.rows_affected())
}

fn exec_insert_with_returning<A, C>(
    primary_key: Option<ValueTuple>,
    mut insert_statement: InsertStatement,
    db: &C,
) -> Result<<A::Entity as EntityTrait>::Model, DbErr>
where
    <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
    C: ConnectionTrait,
    A: ActiveModelTrait,
{
    let db_backend = db.get_database_backend();
    let found = match db.support_returning() {
        true => {
            let returning = Query::returning().exprs(
                <A::Entity as EntityTrait>::Column::iter()
                    .map(|c| c.select_as(c.into_returning_expr(db_backend))),
            );
            insert_statement.returning(returning);
            ReturningSelector::<SelectModel<<A::Entity as EntityTrait>::Model>, _>::from_query(
                insert_statement,
            )
            .one(db)?
        }
        false => {
            let insert_res = exec_insert::<A, _>(primary_key, insert_statement, db)?;
            <A::Entity as EntityTrait>::find_by_id(insert_res.last_insert_id).one(db)?
        }
    };
    match found {
        Some(model) => Ok(model),
        None => Err(DbErr::RecordNotFound(
            "Failed to find inserted item".to_owned(),
        )),
    }
}

fn exec_insert_with_returning_keys<A, C>(
    mut insert_statement: InsertStatement,
    db: &C,
) -> Result<Vec<<PrimaryKey<A> as PrimaryKeyTrait>::ValueType>, DbErr>
where
    <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
    C: ConnectionTrait,
    A: ActiveModelTrait,
{
    let db_backend = db.get_database_backend();
    match db.support_returning() {
        true => {
            insert_statement.returning(returning_pk::<A>(db_backend));
            let rows = db.query_all(&insert_statement)?;
            let cols = PrimaryKey::<A>::iter()
                .map(|col| col.to_string())
                .collect::<Vec<_>>();
            let mut keys = Vec::new();
            for row in rows {
                keys.push(
                    row.try_get_many("", cols.as_ref())
                        .map_err(|_| DbErr::UnpackInsertId)?,
                );
            }
            Ok(keys)
        }
        false => Err(DbErr::BackendNotSupported {
            db: db_backend.as_str(),
            ctx: "INSERT RETURNING",
        }),
    }
}

fn exec_insert_with_returning_many<A, C>(
    mut insert_statement: InsertStatement,
    db: &C,
) -> Result<Vec<<A::Entity as EntityTrait>::Model>, DbErr>
where
    <A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
    C: ConnectionTrait,
    A: ActiveModelTrait,
{
    let db_backend = db.get_database_backend();
    match db.support_returning() {
        true => {
            let returning = Query::returning().exprs(
                <A::Entity as EntityTrait>::Column::iter()
                    .map(|c| c.select_as(c.into_returning_expr(db_backend))),
            );
            insert_statement.returning(returning);
            ReturningSelector::<SelectModel<<A::Entity as EntityTrait>::Model>, _>::from_query(
                insert_statement,
            )
            .all(db)
        }
        false => Err(DbErr::BackendNotSupported {
            db: db_backend.as_str(),
            ctx: "INSERT RETURNING",
        }),
    }
}

fn returning_pk<A>(db_backend: DbBackend) -> ReturningClause
where
    A: ActiveModelTrait,
{
    Query::returning().exprs(<A::Entity as EntityTrait>::PrimaryKey::iter().map(|c| {
        c.into_column()
            .select_as(c.into_column().into_returning_expr(db_backend))
    }))
}