lume 0.13.1

A simple and intuitive Query Builder inspired by Drizzle
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
#![warn(missing_docs)]

//! # Insert Operation
//!
//! This module provides the [`Insert`] struct for type-safe insertion of records
//! into a MySQL, PostgreSQL, or SQLite database using a schema definition. It supports optional
//! returning of inserted rows and handles value binding for various SQL types.

use crate::database::error::DatabaseError;
use crate::dialects::get_dialect;
use crate::helpers::{StartingSql, bind_column_value, get_starting_sql, validate_column_value};
use crate::row::Row;
use crate::schema::{ColumnConstraint, ColumnInfo, Schema, Select, Value};

#[cfg(feature = "mysql")]
use sqlx::{MySql, MySqlPool};

#[cfg(feature = "postgres")]
use sqlx::{Executor, PgPool, Postgres};

#[cfg(feature = "sqlite")]
use sqlx::{Sqlite, SqlitePool};

use sqlx::pool::PoolConnection;

use std::collections::HashMap;
use std::fmt::Debug;
use std::sync::Arc;

/// Select columns that should be included in an INSERT statement based on provided values.
///
/// Omits columns that have defaults or are auto-incremented when their value is absent or Null.
fn select_insertable_columns<'a>(
    all_columns: Vec<ColumnInfo<'a>>,
    values: &HashMap<String, Value>,
) -> Vec<ColumnInfo<'a>> {
    all_columns
        .into_iter()
        .filter(|col| match values.get(col.name) {
            None => {
                !(col.has_default || col.constraints.contains(&ColumnConstraint::AutoIncrement))
            }
            Some(Value::Null) => {
                !(col.has_default || col.constraints.contains(&ColumnConstraint::AutoIncrement))
            }
            _ => true,
        })
        .collect()
}

/// A type-safe insert operation for a given schema type.
///
/// The [`Insert`] struct allows you to insert a record of type `T` (which must
/// implement [`Schema`] and [`Debug`]) into the corresponding database table.
/// It builds the SQL statement and binds values according to the schema.
///
/// # Example
///
/// ```no_run
/// use lume::database::Database;
/// use lume::define_schema;
/// use lume::schema::Schema;
/// use lume::schema::ColumnInfo;
///
/// define_schema! {
///     User {
///         id: i32 [primary_key()],
///         name: String [not_null()],
///     }
/// }
///
/// #[tokio::main]
/// async fn main() {
///     let db = Database::connect("mysql://...").await.unwrap();
///     db.insert(User { id: 1, name: "guru".to_string() })
///         .execute()
///         .await
///         .unwrap();
/// }
/// ```
pub struct Insert<T> {
    /// The data to be inserted.
    data: T,

    #[cfg(feature = "mysql")]
    /// The database connection pool.
    conn: Arc<MySqlPool>,

    #[cfg(feature = "postgres")]
    /// The database connection pool.
    conn: Arc<PgPool>,

    #[cfg(feature = "sqlite")]
    /// The database connection pool.
    conn: Arc<SqlitePool>,

    /// Whether to return the inserted row(s).
    returning: Vec<&'static str>,
}

impl<T: Schema + Debug> Insert<T> {
    #[cfg(feature = "mysql")]
    /// Creates a new [`Insert`] operation for the given data and connection.
    pub fn new(data: T, conn: Arc<MySqlPool>) -> Self {
        Self {
            data,
            conn,
            returning: Vec::new(),
        }
    }

    #[cfg(feature = "postgres")]
    /// Creates a new [`Insert`] operation for the given data and connection.
    pub fn new(data: T, conn: Arc<PgPool>) -> Self {
        Self {
            data,
            conn,
            returning: Vec::new(),
        }
    }

    #[cfg(feature = "sqlite")]
    /// Creates a new [`Insert`] operation for the given data and connection.
    pub fn new(data: T, conn: Arc<SqlitePool>) -> Self {
        Self {
            data,
            conn,
            returning: Vec::new(),
        }
    }

    /// Configures the insert to return the inserted row(s).
    ///
    /// # Returns
    ///
    /// The [`Insert`] instance with returning enabled.
    pub fn returning<S: Select + Debug>(mut self, select: S) -> Self {
        self.returning = select.get_selected();
        self
    }

    /// Executes the insert operation asynchronously.
    ///
    /// This method builds the SQL `INSERT` statement, binds all values
    /// according to the schema, and executes the query.
    ///
    /// # Returns
    ///
    /// * `Ok(())` if the insert was successful.
    /// * `Err(DatabaseError)` if an error occurred.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use lume::database::Database;
    /// # use lume::define_schema;
    /// # use lume::schema::Schema;
    /// # use lume::schema::ColumnInfo;
    /// # define_schema! {
    /// #     User {
    /// #         id: i32 [primary_key()],
    /// #         name: String [not_null()],
    /// #     }
    /// # }
    /// # #[tokio::main]
    /// # async fn main() {
    /// let db = Database::connect("mysql://...").await.unwrap();
    /// db.insert(User { id: 1, name: "guru".to_string() })
    ///     .execute()
    ///     .await
    ///     .unwrap();
    /// # }
    /// ```
    pub async fn execute(self) -> Result<Option<Vec<Row<T>>>, DatabaseError> {
        let conn = self.conn.acquire().await;

        if let Err(e) = conn {
            return Err(DatabaseError::ConnectionError(e));
        }

        let mut conn = conn.unwrap();

        let values = self.data.values();
        let all_columns = T::get_all_columns();

        // Select columns to include: omit columns with defaults/auto_increment when value is None/Null
        let selected: Vec<ColumnInfo> = select_insertable_columns(all_columns, &values);

        let sql = get_starting_sql(StartingSql::Insert, T::table_name());
        let sql = get_dialect().insert_sql(sql, &selected);
        let mut query = sqlx::query(&sql);

        for col in selected.iter() {
            let value = values.get(col.name);
            if validate_column_value(col, value) {
                query = bind_column_value(query, col, value);
            } else {
                eprintln!("Warning: Column {} is not valid for insert", col.name);
                return Err(DatabaseError::InvalidValue(format!(
                    "Column {} is not valid for insert",
                    col.name
                )));
            }
        }

        // For PostgreSQL with RETURNING, we need to add RETURNING clause to the INSERT
        #[cfg(feature = "postgres")]
        if !self.returning.is_empty() {
            let sql = get_starting_sql(StartingSql::Insert, T::table_name());
            let sql = get_dialect().insert_sql(sql, &selected);
            let sql = get_dialect().returning_sql(sql, &self.returning);
            let mut query = sqlx::query(&sql);

            for col in selected.iter() {
                let value = values.get(col.name);
                query = bind_column_value(query, col, value);
            }

            let rows = query.fetch_all(&mut *conn).await;
            if let Err(e) = rows {
                return Err(DatabaseError::QueryError(e.to_string()));
            }
            let rows = rows.unwrap();
            let rows = Row::<T>::from_postgres_row(rows, None);
            return Ok(Some(rows));
        }

        // For SQLite with "RETURNING"
        #[cfg(feature = "sqlite")]
        if !self.returning.is_empty() {
            let sql = get_starting_sql(StartingSql::Insert, T::table_name());
            let sql = get_dialect().insert_sql(sql, &selected);
            let sql = get_dialect().returning_sql(sql, &self.returning);
            let mut query = sqlx::query(&sql);

            for col in selected.iter() {
                let value = values.get(col.name);
                query = bind_column_value(query, col, value);
            }

            let rows = query.fetch_all(&mut *conn).await;
            if let Err(e) = rows {
                return Err(DatabaseError::QueryError(e.to_string()));
            }
            let rows = rows.unwrap();
            let rows = Row::<T>::from_sqlite_row(rows, None);
            return Ok(Some(rows));
        }

        let _result = query.execute(&mut *conn).await;

        if let Err(e) = _result {
            return Err(DatabaseError::ExecutionError(e.to_string()));
        }

        let _result = _result.unwrap();

        if self.returning.is_empty() {
            return Ok(None);
        }

        // For MySQL, build SELECT ... WHERE id = ? using either provided id or last_insert_id
        #[cfg(feature = "mysql")]
        {
            let select_sql = get_starting_sql(StartingSql::Select, T::table_name());
            let mut select_sql = get_dialect().returning_sql(select_sql, &self.returning);
            select_sql.push_str(format!(" FROM {} WHERE id = ?;", T::table_name()).as_str());

            let conn = self.conn.acquire().await;

            if let Err(e) = conn {
                return Err(DatabaseError::ConnectionError(e));
            }

            let mut conn = conn.unwrap();

            let mut query = sqlx::query(&select_sql);

            query = query.bind(_result.last_insert_id());

            let rows = query.fetch_all(&mut *conn).await;

            if let Err(e) = rows {
                return Err(DatabaseError::QueryError(e.to_string()));
            }

            let rows = rows.unwrap();

            let rows = Row::<T>::from_mysql_row(rows, None);
            Ok(Some(rows))
        }

        #[cfg(feature = "sqlite")]
        {
            // In SQLite, if user called returning(), they already got results above.
            // Otherwise, emulate by SELECT ... WHERE rowid = last_insert_rowid().

            if self.returning.is_empty() {
                return Ok(None);
            }

            let select_sql = get_starting_sql(StartingSql::Select, T::table_name());
            let mut select_sql = get_dialect().returning_sql(select_sql, &self.returning);

            // Look for an "id" column in the table schema, not just the values
            let has_id_column = {
                let columns = T::get_all_columns();
                columns.iter().any(|col| col.name == "id")
            };

            let id_col = if has_id_column { "id" } else { "rowid" };
            select_sql.push_str(&format!(
                " FROM {} WHERE {} = last_insert_rowid();",
                T::table_name(),
                id_col
            ));

            let query = sqlx::query(&select_sql);

            let rows = query.fetch_all(&mut *conn).await;

            if let Err(e) = rows {
                return Err(DatabaseError::QueryError(e.to_string()));
            }

            let rows = rows.unwrap();

            let rows = Row::<T>::from_sqlite_row(rows, None);
            Ok(Some(rows))
        }

        #[cfg(feature = "postgres")]
        {
            // This should not be reached as we handle RETURNING above
            Ok(None)
        }
    }
}

/// A type-safe insert operation for inserting multiple records of a given schema type.
///
/// Executes one INSERT per record for simplicity and correctness. This can be
/// optimized later to a multi-row VALUES statement if needed.
pub struct InsertMany<T: Schema + Debug> {
    /// The list of records to be inserted.
    data: Vec<T>,

    #[cfg(feature = "mysql")]
    /// The database connection pool.
    conn: Arc<MySqlPool>,

    #[cfg(feature = "postgres")]
    /// The database connection pool.
    conn: Arc<PgPool>,

    #[cfg(feature = "sqlite")]
    /// The database connection pool.
    conn: Arc<SqlitePool>,

    /// Whether to return the inserted rows.
    returning: Vec<&'static str>,
}

impl<T: Schema + Debug> InsertMany<T> {
    #[cfg(feature = "mysql")]
    /// Creates a new [`InsertMany`] operation for the given records and connection.
    pub fn new(data: Vec<T>, conn: Arc<MySqlPool>) -> Self {
        Self {
            data,
            conn,
            returning: Vec::new(),
        }
    }

    #[cfg(feature = "postgres")]
    /// Creates a new [`InsertMany`] operation for the given records and connection.
    pub fn new(data: Vec<T>, conn: Arc<PgPool>) -> Self {
        Self {
            data,
            conn,
            returning: Vec::new(),
        }
    }

    #[cfg(feature = "sqlite")]
    /// Creates a new [`InsertMany`] operation for the given records and connection.
    pub fn new(data: Vec<T>, conn: Arc<SqlitePool>) -> Self {
        Self {
            data,
            conn,
            returning: Vec::new(),
        }
    }

    /// Configures the insert to return the inserted row(s).
    pub fn returning<S: Select + Debug>(mut self, select: S) -> Self {
        self.returning = select.get_selected();
        self
    }

    /// Executes the insert operation for all records asynchronously.
    pub async fn execute(self) -> Result<Option<Vec<Row<T>>>, DatabaseError> {
        let conn = self.conn.acquire().await;

        if let Err(e) = conn {
            return Err(DatabaseError::ConnectionError(e));
        }

        let mut conn = conn.unwrap();

        #[allow(unused_mut)]
        let mut final_rows = Vec::new();
        #[allow(unused_mut)]
        let mut inserted_ids: Vec<u64> = Vec::new();

        for record in &self.data {
            let values = record.values();
            let all_columns = T::get_all_columns();
            let selected: Vec<ColumnInfo> = select_insertable_columns(all_columns, &values);

            let sql = get_starting_sql(StartingSql::Insert, T::table_name());
            let sql = get_dialect().insert_sql(sql, &selected);
            let mut query = sqlx::query(&sql);

            for col in selected.iter() {
                let value = values.get(col.name);
                query = bind_column_value(query, col, value);
            }

            #[cfg(feature = "mysql")]
            self.insert_mysql_row_and_capture_id_or_returning(
                &mut conn,
                query,
                &mut inserted_ids,
                &values,
            )
            .await
            .unwrap();

            #[cfg(feature = "postgres")]
            self.insert_postgres_row_and_capture_id_or_returning(
                &mut conn,
                query,
                &mut inserted_ids,
                &values,
                &selected,
                &mut final_rows,
            )
            .await
            .unwrap();

            #[cfg(feature = "sqlite")]
            let _ = self
                .insert_sqlite_row_and_capture_id_or_returning(&mut conn, selected, &values)
                .await
                .unwrap();
        }

        #[cfg(feature = "sqlite")]
        return self
            .fetch_sqlite_returning_rows(final_rows, inserted_ids, conn)
            .await;

        #[cfg(feature = "mysql")]
        return self
            .fetch_mysql_returning_rows(final_rows, inserted_ids, conn)
            .await;

        #[cfg(feature = "postgres")]
        return self
            .fetch_postgres_returning_rows(final_rows, inserted_ids, conn)
            .await;
    }

    #[cfg(feature = "postgres")]
    async fn fetch_postgres_returning_rows(
        &self,
        mut final_rows: Vec<Row<T>>,
        inserted_ids: Vec<u64>,
        mut conn: PoolConnection<Postgres>,
    ) -> Result<Option<Vec<Row<T>>>, DatabaseError> {
        if !self.returning.is_empty() {
            Ok(Some(final_rows))
        } else if !inserted_ids.is_empty() {
            let select_sql = get_starting_sql(StartingSql::Select, T::table_name());
            let mut select_sql = get_dialect().returning_sql(select_sql, &self.returning);
            select_sql.push_str(format!(" FROM {} WHERE id = $1;", T::table_name()).as_str());

            for id in inserted_ids {
                let q = sqlx::query(&select_sql).bind(id as i64);
                let rows = q.fetch_all(&mut *conn).await;
                if let Err(e) = rows {
                    return Err(DatabaseError::QueryError(e.to_string()));
                }
                let rows = rows.unwrap();

                let rows = Row::<T>::from_postgres_row(rows, None);
                final_rows.extend(rows);
            }

            Ok(Some(final_rows))
        } else {
            Ok(None)
            // Fetch selected columns for all inserted ids
        }
    }

    #[cfg(feature = "mysql")]
    async fn fetch_mysql_returning_rows(
        &self,
        mut final_rows: Vec<Row<T>>,
        inserted_ids: Vec<u64>,
        mut conn: PoolConnection<MySql>,
    ) -> Result<Option<Vec<Row<T>>>, DatabaseError> {
        if self.returning.is_empty() {
            return Ok(None);
        }

        // Fetch selected columns for all inserted ids
        let select_sql = get_starting_sql(StartingSql::Select, T::table_name());
        let mut select_sql = get_dialect().returning_sql(select_sql, &self.returning);
        select_sql.push_str(format!(" FROM {} WHERE id = ?;", T::table_name()).as_str());

        for id in inserted_ids {
            let q = sqlx::query(&select_sql).bind(id);

            let rows = q.fetch_all(&mut *conn).await;

            if let Err(e) = rows {
                return Err(DatabaseError::QueryError(e.to_string()));
            }

            let rows = rows.unwrap();

            let rows = Row::<T>::from_mysql_row(rows, None);

            final_rows.extend(rows);
        }

        Ok(Some(final_rows))
    }

    #[cfg(feature = "sqlite")]
    async fn fetch_sqlite_returning_rows(
        &self,
        mut final_rows: Vec<Row<T>>,
        inserted_ids: Vec<u64>,
        mut conn: PoolConnection<Sqlite>,
    ) -> Result<Option<Vec<Row<T>>>, DatabaseError> {
        if self.returning.is_empty() {
            return Ok(None);
        }

        // Fetch selected columns for all inserted ids
        let select_sql = get_starting_sql(StartingSql::Select, T::table_name());
        let mut select_sql = get_dialect().returning_sql(select_sql, &self.returning);
        select_sql.push_str(format!(" FROM {} WHERE id = ?;", T::table_name()).as_str());

        for id in inserted_ids {
            let q = sqlx::query(&select_sql).bind(id as i64);

            let rows = q.fetch_all(&mut *conn).await;

            if let Err(e) = rows {
                return Err(DatabaseError::QueryError(e.to_string()));
            }

            let rows = rows.unwrap();
            let rows = Row::<T>::from_sqlite_row(rows, None);

            final_rows.extend(rows);
        }

        Ok(Some(final_rows))
    }

    #[cfg(feature = "sqlite")]
    async fn insert_sqlite_row_and_capture_id_or_returning(
        &self,
        conn: &mut PoolConnection<Sqlite>,
        selected: Vec<ColumnInfo<'_>>,
        values: &HashMap<String, Value>,
    ) -> Result<Result<Vec<Row<T>>, u64>, DatabaseError> {
        // If RETURNING is requested, return the resulting row(s)
        if !self.returning.is_empty() {
            let sql = get_starting_sql(StartingSql::Insert, T::table_name());
            let sql = get_dialect().insert_sql(sql, &selected);
            let sql = get_dialect().returning_sql(sql, &self.returning);
            let mut query = sqlx::query(&sql);

            for col in selected.iter() {
                let value = values.get(col.name);
                query = bind_column_value(query, col, value);
            }

            let rows = query.fetch_all(&mut **conn).await;
            if let Err(e) = rows {
                return Err(DatabaseError::QueryError(e.to_string()));
            }
            let rows = rows.unwrap();
            let out_rows = Row::<T>::from_sqlite_row(rows, None);
            return Ok(Ok(out_rows));
        } else {
            // Otherwise, execute and return the inserted id (rowid)
            let sql = get_starting_sql(StartingSql::Insert, T::table_name());
            let sql = get_dialect().insert_sql(sql, &selected);
            let mut query = sqlx::query(&sql);

            for col in selected.iter() {
                let value = values.get(col.name);
                query = bind_column_value(query, col, value);
            }

            let result = query.execute(&mut **conn).await;
            if let Err(e) = result {
                return Err(DatabaseError::ExecutionError(e.to_string()));
            }
            let result = result.unwrap();

            // Try to get id from input values if present, else use last_insert_rowid
            let id_val = values.get("id");
            let id: u64 = if let Some(id_val) = id_val {
                match id_val {
                    Value::Int64(v) => *v as u64,
                    Value::Int32(v) => *v as u64,
                    Value::Int16(v) => *v as u64,
                    Value::Int8(v) => *v as u64,
                    Value::UInt64(v) => *v,
                    Value::UInt32(v) => *v as u64,
                    Value::UInt16(v) => *v as u64,
                    Value::UInt8(v) => *v as u64,
                    Value::String(_)
                    | Value::Uuid(_)
                    | Value::Float32(_)
                    | Value::Float64(_)
                    | Value::Bool(_)
                    | Value::Between(_, _)
                    | Value::Array(_)
                    | Value::Null => result.last_insert_rowid() as u64,
                }
            } else {
                result.last_insert_rowid() as u64
            };

            return Ok(Err(id));
        }
    }

    #[cfg(feature = "mysql")]
    async fn insert_mysql_row_and_capture_id_or_returning(
        &self,
        conn: &mut PoolConnection<MySql>,
        query: sqlx::query::Query<'_, MySql, sqlx::mysql::MySqlArguments>,
        inserted_ids: &mut Vec<u64>,
        values: &HashMap<String, Value>,
    ) -> Result<(), DatabaseError> {
        let result: Result<sqlx::mysql::MySqlQueryResult, sqlx::Error> =
            query.execute(&mut **conn).await;

        if let Err(e) = result {
            return Err(DatabaseError::ExecutionError(e.to_string()));
        }

        let result = result.unwrap();

        // Capture id: prefer provided id, else last_insert_id
        if let Some(id_val) = values.get("id") {
            match id_val {
                Value::Array(_) => inserted_ids.push(result.last_insert_id()),
                Value::Int64(v) => inserted_ids.push(*v as u64),
                Value::Int32(v) => inserted_ids.push(*v as u64),
                Value::Int16(v) => inserted_ids.push(*v as u64),
                Value::Int8(v) => inserted_ids.push(*v as u64),
                Value::UInt64(v) => inserted_ids.push(*v),
                Value::UInt32(v) => inserted_ids.push(*v as u64),
                Value::UInt16(v) => inserted_ids.push(*v as u64),
                Value::UInt8(v) => inserted_ids.push(*v as u64),
                Value::String(_)
                | Value::Uuid(_)
                | Value::Float32(_)
                | Value::Float64(_)
                | Value::Bool(_)
                | Value::Between(_, _)
                | Value::Null => inserted_ids.push(result.last_insert_id()),
            }

            Ok(())
        } else {
            inserted_ids.push(result.last_insert_id());

            Ok(())
        }
    }

    #[cfg(feature = "postgres")]
    async fn insert_postgres_row_and_capture_id_or_returning(
        &self,
        conn: &mut PoolConnection<Postgres>,
        query: sqlx::query::Query<'_, Postgres, sqlx::postgres::PgArguments>,
        inserted_ids: &mut Vec<u64>,
        values: &HashMap<String, Value>,
        selected: &Vec<ColumnInfo<'_>>,
        final_rows: &mut Vec<Row<T>>,
    ) -> Result<(), DatabaseError> {
        // For PostgreSQL, if returning is requested, we need to use RETURNING clause
        if !self.returning.is_empty() {
            let sql = get_starting_sql(StartingSql::Insert, T::table_name());
            let sql = get_dialect().insert_sql(sql, &selected);
            let sql = get_dialect().returning_sql(sql, &self.returning);
            let mut query = sqlx::query(&sql);

            for col in selected.iter() {
                let value = values.get(col.name);
                query = bind_column_value(query, col, value);
            }

            let rows = query.fetch_all(&mut **conn).await;
            if let Err(e) = rows {
                return Err(DatabaseError::QueryError(e.to_string()));
            }
            let rows = rows.unwrap();
            let rows = Row::<T>::from_postgres_row(rows, None);
            final_rows.extend(rows);
        } else {
            // Execute without returning
            match query.execute(&mut **conn).await {
                Ok(_) => {}
                Err(e) => return Err(DatabaseError::ExecutionError(e.to_string())),
            }

            // Capture id: prefer provided id
            if let Some(id_val) = values.get("id") {
                match id_val {
                    Value::Int64(v) => inserted_ids.push(*v as u64),
                    Value::Int32(v) => inserted_ids.push(*v as u64),
                    Value::Int16(v) => inserted_ids.push(*v as u64),
                    Value::Int8(v) => inserted_ids.push(*v as u64),
                    _ => {
                        // For PostgreSQL without RETURNING, we can't get the id
                        // This is a limitation - user should use returning() to get ids
                    }
                }
            }
        }
        Ok(())
    }
}