rok-fluent 0.4.1

Eloquent-inspired async ORM for Rust (PostgreSQL, MySQL, SQLite)
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
//! Async PostgreSQL executor — runs [`QueryBuilder`] output against a live pool.
//!
//! # Example
//!
//! ```rust,no_run
//! # use rok_fluent::{Model, core::query::QueryBuilder, core::condition::SqlValue};
//! # use rok_fluent::orm::postgres::executor;
//! # #[derive(sqlx::FromRow)] struct User { pub id: i64, pub name: String }
//! # impl Model for User {
//! #   fn table_name() -> &'static str { "users" }
//! #   fn columns() -> &'static [&'static str] { &["id","name"] }
//! # }
//! # async fn example(pool: sqlx::PgPool) -> Result<(), sqlx::Error> {
//! let users: Vec<User> = executor::fetch_all(&pool, User::query().where_eq("active", true)).await?;
//! # Ok(()) }
//! ```

use crate::core::condition::SqlValue;
use crate::core::model::Model;
use crate::core::query::QueryBuilder;
use crate::core::sqlx::pg as sqlx_pg;
use crate::orm::hooks::{
    dispatch_created, dispatch_creating, dispatch_deleted, dispatch_deleting, dispatch_saved,
    dispatch_saving, dispatch_updated, dispatch_updating,
};
use sqlx::postgres::PgRow;
use sqlx::PgPool;
use std::time::Instant;

// ── Retry Configuration ────────────────────────────────────────────────────────

/// Configuration for automatic retry of serialisation-failed transactions / queries.
#[derive(Debug, Clone)]
pub struct RetryConfig {
    /// Maximum number of attempts before giving up.
    pub max_attempts: u32,
    /// Base delay between retries in milliseconds.
    pub base_delay_ms: u64,
    /// Maximum delay cap in milliseconds.
    pub max_delay_ms: u64,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_attempts: 3,
            base_delay_ms: 50,
            max_delay_ms: 2000,
        }
    }
}

/// A trait for errors that can be checked for retry eligibility.
pub trait IsRetryable {
    /// Returns `true` if this error is a transient condition that may succeed on retry.
    fn is_retryable(&self) -> bool;
}

impl IsRetryable for sqlx::Error {
    fn is_retryable(&self) -> bool {
        match self {
            sqlx::Error::Database(db_err) => {
                let code = db_err.code().map(|c| c.to_string()).unwrap_or_default();
                // 40001 = serialization_failure, 40P01 = deadlock_detected
                code == "40001" || code == "40P01"
            }
            _ => false,
        }
    }
}

/// Execute a closure with automatic retry on serialisation / deadlock errors.
///
/// Uses exponential backoff with delay capped at `config.max_delay_ms`.
pub async fn execute_with_retry<F, Fut, T, E>(
    pool: &PgPool,
    config: &RetryConfig,
    f: F,
) -> Result<T, E>
where
    F: Fn(&PgPool) -> Fut,
    Fut: std::future::Future<Output = Result<T, E>>,
    E: IsRetryable,
{
    let mut attempt = 0u32;
    loop {
        attempt += 1;
        match f(pool).await {
            Ok(val) => return Ok(val),
            Err(e) if e.is_retryable() && attempt < config.max_attempts => {
                let delay = config
                    .base_delay_ms
                    .saturating_mul(2u64.pow(attempt.saturating_sub(1)))
                    .min(config.max_delay_ms);
                tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
            }
            Err(e) => return Err(e),
        }
    }
}

/// Fetch all rows matching the query.
pub async fn fetch_all<T>(pool: &PgPool, builder: QueryBuilder<T>) -> Result<Vec<T>, sqlx::Error>
where
    T: Model + for<'r> sqlx::FromRow<'r, PgRow> + Send + Unpin,
{
    let (sql, params) = builder.to_sql();
    let start = Instant::now();
    let result = {
        let fut = sqlx_pg::fetch_all_as::<T>(pool, &sql, params);
        #[cfg(feature = "tracing")]
        {
            use tracing::Instrument;
            let span = tracing::info_span!(
                "db.query",
                "otel.kind" = "CLIENT",
                "db.system" = "postgresql",
                "db.operation" = "SELECT",
                "db.sql.table" = T::table_name(),
                "db.statement" = %sql,
            );
            fut.instrument(span).await
        }
        #[cfg(not(feature = "tracing"))]
        fut.await
    };
    let duration = start.elapsed().as_millis() as u64;
    let rows = result.as_ref().map(|v| v.len() as u64).unwrap_or(0);
    super::query_log::log_query(&sql, &[], duration, rows, T::table_name());
    result
}

/// Fetch at most one row matching the query.  Returns `None` if no rows match.
pub async fn fetch_optional<T>(
    pool: &PgPool,
    builder: QueryBuilder<T>,
) -> Result<Option<T>, sqlx::Error>
where
    T: Model + for<'r> sqlx::FromRow<'r, PgRow> + Send + Unpin,
{
    let (sql, params) = builder.to_sql();
    let start = Instant::now();
    let result = {
        let fut = sqlx_pg::fetch_optional_as::<T>(pool, &sql, params);
        #[cfg(feature = "tracing")]
        {
            use tracing::Instrument;
            let span = tracing::info_span!(
                "db.query",
                "otel.kind" = "CLIENT",
                "db.system" = "postgresql",
                "db.operation" = "SELECT",
                "db.sql.table" = T::table_name(),
                "db.statement" = %sql,
            );
            fut.instrument(span).await
        }
        #[cfg(not(feature = "tracing"))]
        fut.await
    };
    let duration = start.elapsed().as_millis() as u64;
    let rows = result
        .as_ref()
        .map(|r| if r.is_some() { 1 } else { 0 })
        .unwrap_or(0);
    super::query_log::log_query(&sql, &[], duration, rows, T::table_name());
    result
}

/// Return the row count matching the query's WHERE clause.
pub async fn count<T: Model>(pool: &PgPool, builder: QueryBuilder<T>) -> Result<i64, sqlx::Error> {
    let (sql, params) = builder.to_count_sql();
    let start = Instant::now();
    let row = {
        let fut = sqlx_pg::build_query(&sql, params).fetch_one(pool);
        #[cfg(feature = "tracing")]
        {
            use tracing::Instrument;
            let span = tracing::info_span!(
                "db.query",
                "otel.kind" = "CLIENT",
                "db.system" = "postgresql",
                "db.operation" = "SELECT COUNT",
                "db.sql.table" = T::table_name(),
                "db.statement" = %sql,
            );
            fut.instrument(span).await
        }
        #[cfg(not(feature = "tracing"))]
        fut.await
    };
    let duration = start.elapsed().as_millis() as u64;
    match row {
        Ok(row) => {
            use sqlx::Row;
            let val = row.try_get::<i64, _>(0)?;
            super::query_log::log_query(&sql, &[], duration, 1, T::table_name());
            Ok(val)
        }
        Err(e) => {
            super::query_log::log_query(&sql, &[], duration, 0, T::table_name());
            Err(e)
        }
    }
}

/// Execute a raw SQL string with positional parameters and return rows affected.
pub async fn execute_raw(
    pool: &PgPool,
    sql: &str,
    params: Vec<SqlValue>,
) -> Result<u64, sqlx::Error> {
    let fut = sqlx_pg::execute(pool, sql, params);
    #[cfg(feature = "tracing")]
    {
        use tracing::Instrument;
        let span = tracing::info_span!(
            "db.execute",
            "otel.kind" = "CLIENT",
            "db.system" = "postgresql",
            "db.statement" = %sql,
        );
        fut.instrument(span).await
    }
    #[cfg(not(feature = "tracing"))]
    fut.await
}

/// Insert a row using the column-value pairs and return rows affected.
pub async fn insert<T: 'static>(
    pool: &PgPool,
    table: &str,
    data: &[(&str, SqlValue)],
) -> Result<u64, sqlx::Error> {
    dispatch_saving::<T>(table, data).map_err(|e| sqlx::Error::Configuration(Box::new(e)))?;
    dispatch_creating::<T>(table, data).map_err(|e| sqlx::Error::Configuration(Box::new(e)))?;
    let (sql, params) = QueryBuilder::<T>::insert_sql(table, data);
    let start = Instant::now();
    let result = execute_raw(pool, &sql, params).await;
    let duration = start.elapsed().as_millis() as u64;
    let rows = result.as_ref().copied().unwrap_or(0);
    super::query_log::log_query(&sql, &[], duration, rows, table);
    dispatch_created::<T>(table, data);
    dispatch_saved::<T>(table, data);
    result
}

/// Update rows matching the builder's conditions and return rows affected.
pub async fn update<T: Model + 'static>(
    pool: &PgPool,
    builder: QueryBuilder<T>,
    data: &[(&str, SqlValue)],
) -> Result<u64, sqlx::Error> {
    let table = T::table_name();
    dispatch_saving::<T>(table, data).map_err(|e| sqlx::Error::Configuration(Box::new(e)))?;
    dispatch_updating::<T>(table, data).map_err(|e| sqlx::Error::Configuration(Box::new(e)))?;
    let (sql, params) = builder.to_update_sql(data);
    let start = Instant::now();
    let result = execute_raw(pool, &sql, params).await;
    let duration = start.elapsed().as_millis() as u64;
    let rows = result.as_ref().copied().unwrap_or(0);
    super::query_log::log_query(&sql, &[], duration, rows, table);
    dispatch_updated::<T>(table, data);
    dispatch_saved::<T>(table, data);
    result
}

/// Delete rows matching the builder's conditions and return rows affected.
pub async fn delete<T: Model + 'static>(
    pool: &PgPool,
    builder: QueryBuilder<T>,
) -> Result<u64, sqlx::Error> {
    let table = T::table_name();
    dispatch_deleting::<T>(table, &[]).map_err(|e| sqlx::Error::Configuration(Box::new(e)))?;
    let (sql, params) = builder.to_delete_sql();
    let start = Instant::now();
    let result = execute_raw(pool, &sql, params).await;
    let duration = start.elapsed().as_millis() as u64;
    let rows = result.as_ref().copied().unwrap_or(0);
    super::query_log::log_query(&sql, &[], duration, rows, table);
    dispatch_deleted::<T>(table, &[]);
    result
}

/// Insert multiple rows in a single `INSERT INTO … VALUES …, …` statement.
pub async fn bulk_insert<T: 'static>(
    pool: &PgPool,
    table: &str,
    rows: &[Vec<(&str, SqlValue)>],
) -> Result<u64, sqlx::Error> {
    if rows.is_empty() {
        return Ok(0);
    }
    let first_row = &rows[0];
    dispatch_saving::<T>(table, first_row).map_err(|e| sqlx::Error::Configuration(Box::new(e)))?;
    dispatch_creating::<T>(table, first_row)
        .map_err(|e| sqlx::Error::Configuration(Box::new(e)))?;
    let (sql, params) = QueryBuilder::<T>::bulk_insert_sql(table, rows);
    let start = Instant::now();
    let result = execute_raw(pool, &sql, params).await;
    let duration = start.elapsed().as_millis() as u64;
    let rows_affected = result.as_ref().copied().unwrap_or(0);
    super::query_log::log_query(&sql, &[], duration, rows_affected, table);
    dispatch_created::<T>(table, first_row);
    dispatch_saved::<T>(table, first_row);
    result
}

/// Soft-delete rows matching the builder's conditions by setting `delete_col = NOW()`.
pub async fn soft_delete<T: Model + 'static>(
    pool: &PgPool,
    builder: QueryBuilder<T>,
    delete_col: &str,
) -> Result<u64, sqlx::Error> {
    let table = T::table_name();
    dispatch_deleting::<T>(table, &[]).map_err(|e| sqlx::Error::Configuration(Box::new(e)))?;
    let (where_clause, params) = builder.to_where_clause();
    let sql = format!(
        "UPDATE {} SET {} = NOW(){}",
        table, delete_col, where_clause
    );
    let start = Instant::now();
    let result = execute_raw(pool, &sql, params).await;
    let duration = start.elapsed().as_millis() as u64;
    let rows = result.as_ref().copied().unwrap_or(0);
    super::query_log::log_query(&sql, &[], duration, rows, table);
    dispatch_deleted::<T>(table, &[]);
    result
}

/// Restore soft-deleted rows matching the builder by setting `delete_col = NULL`.
pub async fn restore<T: Model>(
    pool: &PgPool,
    builder: QueryBuilder<T>,
    delete_col: &str,
) -> Result<u64, sqlx::Error> {
    let (where_clause, params) = builder.to_where_clause();
    let sql = format!(
        "UPDATE {} SET {} = NULL{}",
        T::table_name(),
        delete_col,
        where_clause,
    );
    let start = Instant::now();
    let result = execute_raw(pool, &sql, params).await;
    let duration = start.elapsed().as_millis() as u64;
    let rows = result.as_ref().copied().unwrap_or(0);
    super::query_log::log_query(&sql, &[], duration, rows, T::table_name());
    result
}

/// Update `updated_at = NOW()` for rows matching the builder (touch).
///
/// Does nothing (returns 0) if the model has no `timestamp_columns()`.
pub async fn touch<T: Model>(pool: &PgPool, builder: QueryBuilder<T>) -> Result<u64, sqlx::Error> {
    if let Some((_, updated_at)) = T::timestamp_columns() {
        let (where_clause, params) = builder.to_where_clause();
        let sql = format!(
            "UPDATE {} SET {updated_at} = NOW(){}",
            T::table_name(),
            where_clause,
        );
        let start = Instant::now();
        let result = execute_raw(pool, &sql, params).await;
        let duration = start.elapsed().as_millis() as u64;
        let rows = result.as_ref().copied().unwrap_or(0);
        super::query_log::log_query(&sql, &[], duration, rows, T::table_name());
        result
    } else {
        Ok(0)
    }
}

/// Run an aggregate expression and return the raw scalar value.
///
/// `agg_expr` is something like `"MAX(total)"`, `"SUM(price)"`, `"AVG(score)"`.
/// Returns `None` when no rows match.
pub async fn aggregate<T: Model>(
    pool: &PgPool,
    builder: QueryBuilder<T>,
    agg_expr: &str,
) -> Result<Option<f64>, sqlx::Error> {
    let (sql, params) = builder.to_aggregate_sql(agg_expr);
    let start = Instant::now();
    let result = sqlx_pg::build_query(&sql, params)
        .fetch_optional(pool)
        .await;
    let duration = start.elapsed().as_millis() as u64;
    match result {
        Ok(row) => {
            super::query_log::log_query(&sql, &[], duration, 1, T::table_name());
            use sqlx::Row;
            Ok(row.and_then(|r| r.try_get::<Option<f64>, _>(0).ok().flatten()))
        }
        Err(e) => {
            super::query_log::log_query(&sql, &[], duration, 0, T::table_name());
            Err(e)
        }
    }
}

/// Insert a row using `INSERT … ON CONFLICT … DO UPDATE SET …` (PostgreSQL upsert).
pub async fn upsert<T: Model>(
    pool: &PgPool,
    data: &[(&str, SqlValue)],
    conflict_cols: &[&str],
) -> Result<u64, sqlx::Error> {
    let (sql, params) = QueryBuilder::<T>::upsert_sql(T::table_name(), data, conflict_cols);
    let start = Instant::now();
    let result = execute_raw(pool, &sql, params).await;
    let duration = start.elapsed().as_millis() as u64;
    let rows = result.as_ref().copied().unwrap_or(0);
    super::query_log::log_query(&sql, &[], duration, rows, T::table_name());
    result
}

/// Atomically increment `col` by `amount` for rows matching the builder.
pub async fn increment<T: Model>(
    pool: &PgPool,
    builder: QueryBuilder<T>,
    col: &str,
    amount: i64,
) -> Result<u64, sqlx::Error> {
    let (where_clause, params) = builder.to_where_clause();
    let sql = format!(
        "UPDATE {} SET {col} = {col} + {amount}{}",
        T::table_name(),
        where_clause
    );
    let start = Instant::now();
    let result = execute_raw(pool, &sql, params).await;
    let duration = start.elapsed().as_millis() as u64;
    let rows = result.as_ref().copied().unwrap_or(0);
    super::query_log::log_query(&sql, &[], duration, rows, T::table_name());
    result
}

/// Atomically decrement `col` by `amount` for rows matching the builder.
pub async fn decrement<T: Model>(
    pool: &PgPool,
    builder: QueryBuilder<T>,
    col: &str,
    amount: i64,
) -> Result<u64, sqlx::Error> {
    increment(pool, builder, col, -amount).await
}

/// Insert a single row and return it using `RETURNING *`.
pub async fn insert_returning<T>(
    pool: &PgPool,
    table: &str,
    data: &[(&str, SqlValue)],
) -> Result<T, sqlx::Error>
where
    T: Model + for<'r> sqlx::FromRow<'r, PgRow> + Send + Unpin,
{
    let (base_sql, params) = QueryBuilder::<T>::insert_sql(table, data);
    let sql = format!("{base_sql} RETURNING *");
    let start = Instant::now();
    let result = sqlx_pg::fetch_all_as::<T>(pool, &sql, params).await;
    let duration = start.elapsed().as_millis() as u64;
    match result {
        Ok(rows) => {
            let count = rows.len() as u64;
            let row = rows.into_iter().next().ok_or(sqlx::Error::RowNotFound)?;
            super::query_log::log_query(&sql, &[], duration, count, table);
            Ok(row)
        }
        Err(e) => {
            super::query_log::log_query(&sql, &[], duration, 0, table);
            Err(e)
        }
    }
}

/// Insert multiple rows and return all inserted rows via `RETURNING *`.
pub async fn bulk_insert_returning<T>(
    pool: &PgPool,
    table: &str,
    rows: &[Vec<(&str, SqlValue)>],
) -> Result<Vec<T>, sqlx::Error>
where
    T: Model + for<'r> sqlx::FromRow<'r, PgRow> + Send + Unpin,
{
    if rows.is_empty() {
        return Ok(vec![]);
    }
    let (base_sql, params) = QueryBuilder::<T>::bulk_insert_sql(table, rows);
    let sql = format!("{base_sql} RETURNING *");
    let start = Instant::now();
    let result = sqlx_pg::fetch_all_as::<T>(pool, &sql, params).await;
    let duration = start.elapsed().as_millis() as u64;
    let rows_affected = result.as_ref().map(|v| v.len() as u64).unwrap_or(0);
    super::query_log::log_query(&sql, &[], duration, rows_affected, table);
    result
}

/// Update rows matching the builder's conditions and return the affected rows via `RETURNING *`.
pub async fn update_returning<T>(
    pool: &PgPool,
    builder: QueryBuilder<T>,
    data: &[(&str, SqlValue)],
) -> Result<Vec<T>, sqlx::Error>
where
    T: Model + for<'r> sqlx::FromRow<'r, PgRow> + Send + Unpin + 'static,
{
    let table = T::table_name();
    dispatch_saving::<T>(table, data).map_err(|e| sqlx::Error::Configuration(Box::new(e)))?;
    dispatch_updating::<T>(table, data).map_err(|e| sqlx::Error::Configuration(Box::new(e)))?;
    let (base_sql, base_params) = builder.to_update_sql(data);
    let sql = format!("{base_sql} RETURNING *");
    let start = Instant::now();
    let result = sqlx_pg::fetch_all_as::<T>(pool, &sql, base_params).await;
    let duration = start.elapsed().as_millis() as u64;
    let rows_affected = result.as_ref().map(|v| v.len() as u64).unwrap_or(0);
    super::query_log::log_query(&sql, &[], duration, rows_affected, table);
    dispatch_updated::<T>(table, data);
    dispatch_saved::<T>(table, data);
    result
}

/// Delete rows matching the builder's conditions and return the deleted rows via `RETURNING *`.
pub async fn delete_returning<T>(
    pool: &PgPool,
    builder: QueryBuilder<T>,
) -> Result<Vec<T>, sqlx::Error>
where
    T: Model + for<'r> sqlx::FromRow<'r, PgRow> + Send + Unpin + 'static,
{
    let table = T::table_name();
    dispatch_deleting::<T>(table, &[]).map_err(|e| sqlx::Error::Configuration(Box::new(e)))?;
    let (base_sql, base_params) = builder.to_delete_sql();
    let sql = format!("{base_sql} RETURNING *");
    let start = Instant::now();
    let result = sqlx_pg::fetch_all_as::<T>(pool, &sql, base_params).await;
    let duration = start.elapsed().as_millis() as u64;
    let rows_affected = result.as_ref().map(|v| v.len() as u64).unwrap_or(0);
    super::query_log::log_query(&sql, &[], duration, rows_affected, table);
    dispatch_deleted::<T>(table, &[]);
    result
}

/// Insert multiple rows with `ON CONFLICT … DO UPDATE` in a single statement.
pub async fn bulk_upsert<T: Model + 'static>(
    pool: &PgPool,
    rows: &[Vec<(&str, SqlValue)>],
    conflict_cols: &[&str],
) -> Result<u64, sqlx::Error> {
    if rows.is_empty() {
        return Ok(0);
    }
    let table = T::table_name();
    let first_row = &rows[0];
    let cols: Vec<&str> = first_row.iter().map(|(c, _)| *c).collect();
    let conflict_target = conflict_cols.join(", ");
    let update_set: Vec<String> = cols
        .iter()
        .filter(|c| !conflict_cols.contains(c))
        .map(|c| format!("{c} = EXCLUDED.{c}"))
        .collect();

    let cols_count = cols.len();
    let mut row_placeholders: Vec<String> = Vec::with_capacity(rows.len());
    let mut params: Vec<SqlValue> = Vec::with_capacity(rows.len() * cols_count);

    for (row_idx, row) in rows.iter().enumerate() {
        let phs: Vec<String> = (0..cols_count)
            .map(|col_idx| format!("${}", row_idx * cols_count + col_idx + 1))
            .collect();
        row_placeholders.push(format!("({})", phs.join(", ")));
        for (_, val) in row.iter() {
            params.push(val.clone());
        }
    }

    let conflict_clause = if update_set.is_empty() {
        format!("ON CONFLICT ({conflict_target}) DO NOTHING")
    } else {
        format!(
            "ON CONFLICT ({conflict_target}) DO UPDATE SET {}",
            update_set.join(", ")
        )
    };

    let sql = format!(
        "INSERT INTO {} ({}) VALUES {} {}",
        table,
        cols.join(", "),
        row_placeholders.join(", "),
        conflict_clause,
    );

    let start = Instant::now();
    let result = execute_raw(pool, &sql, params).await;
    let duration = start.elapsed().as_millis() as u64;
    let rows_affected = result.as_ref().copied().unwrap_or(0);
    super::query_log::log_query(&sql, &[], duration, rows_affected, table);
    result
}

/// Upsert a row (`INSERT … ON CONFLICT … DO UPDATE SET …`) and return the affected row via `RETURNING *`.
pub async fn upsert_returning<T>(
    pool: &PgPool,
    data: &[(&str, SqlValue)],
    conflict_cols: &[&str],
) -> Result<T, sqlx::Error>
where
    T: Model + for<'r> sqlx::FromRow<'r, PgRow> + Send + Unpin,
{
    let (base_sql, params) = QueryBuilder::<T>::upsert_sql(T::table_name(), data, conflict_cols);
    let sql = format!("{base_sql} RETURNING *");
    let start = Instant::now();
    let result = sqlx_pg::fetch_all_as::<T>(pool, &sql, params).await;
    let duration = start.elapsed().as_millis() as u64;
    match result {
        Ok(rows) => {
            let count = rows.len() as u64;
            let row = rows.into_iter().next().ok_or(sqlx::Error::RowNotFound)?;
            super::query_log::log_query(&sql, &[], duration, count, T::table_name());
            Ok(row)
        }
        Err(e) => {
            super::query_log::log_query(&sql, &[], duration, 0, T::table_name());
            Err(e)
        }
    }
}