pgorm-derive 0.3.0

Derive macros for pgorm
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
//! Base update methods code generation.
//!
//! This module contains code generation for:
//! - `update_by_id` / `update_by_ids` methods
//! - `update_by_id_returning` / `update_by_ids_returning` methods
//! - `update_by_id_force` / `update_by_id_force_returning` methods (when version field exists)

use proc_macro2::TokenStream;
use quote::quote;

use super::attrs::StructAttrs;

/// Generate update_by_id and update_by_ids methods.
pub(super) fn generate_update_by_id_methods(
    table_name: &str,
    id_col_expr: &TokenStream,
    destructure: &TokenStream,
    set_stmts: &[TokenStream],
    has_auto_now: bool,
    version_field: Option<&(syn::Ident, String)>,
) -> TokenStream {
    let now_init = if has_auto_now {
        quote! { let __pgorm_now = ::chrono::Utc::now(); }
    } else {
        quote! {}
    };

    // Generate version SET clause: version = version + 1
    let version_set = if let Some((_, version_col)) = version_field {
        quote! {
            if !first {
                q.push(", ");
            } else {
                first = false;
            }
            q.push(#version_col);
            q.push(" = ");
            q.push(#version_col);
            q.push(" + 1");
        }
    } else {
        quote! {}
    };

    // Generate version WHERE clause: AND version = $N
    let version_where = if let Some((version_ident, version_col)) = version_field {
        quote! {
            q.push(" AND ");
            q.push(#version_col);
            q.push(" = ");
            q.push_bind(#version_ident as i64);
        }
    } else {
        quote! {}
    };

    // Suppress unused variable warning for version ident in update_by_ids
    // (bulk updates don't use version checking)
    let version_suppress = if let Some((version_ident, _)) = version_field {
        quote! { let _ = #version_ident; }
    } else {
        quote! {}
    };

    // For version checking, we need to capture id string before push_bind moves it
    let (id_capture, execute_with_check) = if let Some((version_ident, _)) = version_field {
        let capture = quote! {
            let __id_str = format!("{:?}", &id);
            let __version_val = #version_ident as i64;
        };
        let check = quote! {
            let __affected = q.execute(conn).await?;
            if __affected == 0 {
                return Err(pgorm::OrmError::stale_record(
                    #table_name,
                    __id_str,
                    __version_val,
                ));
            }
            Ok(__affected)
        };
        (capture, check)
    } else {
        (quote! {}, quote! { q.execute(conn).await })
    };

    quote! {
        /// Update columns by primary key (patch-style).
        ///
        /// If the struct has a `#[orm(version)]` field, this method performs optimistic locking:
        /// it checks that the version matches and returns `OrmError::StaleRecord` if not.
        pub async fn update_by_id<I>(
            self,
            conn: &impl pgorm::GenericClient,
            id: I,
        ) -> pgorm::OrmResult<u64>
        where
            I: ::pgorm::tokio_postgres::types::ToSql + ::core::marker::Sync + ::core::marker::Send + 'static,
        {
            #destructure
            #now_init
            #id_capture

            let mut q = pgorm::sql("UPDATE ");
            q.push(#table_name);
            q.push(" SET ");

            let mut first = true;
            #(#set_stmts)*
            #version_set

            if first {
                return Err(pgorm::OrmError::Validation(
                    "UpdateModel: no fields to update".to_string(),
                ));
            }

            q.push(" WHERE ");
            q.push(#table_name);
            q.push(".");
            q.push(#id_col_expr);
            q.push(" = ");
            q.push_bind(id);
            #version_where

            #execute_with_check
        }

        /// Update columns by primary key for multiple rows (patch-style).
        ///
        /// The same patch is applied to every matched row.
        ///
        /// Note: Optimistic locking (version check) is NOT supported for bulk updates.
        /// If you need version checking, use a loop with `update_by_id` instead.
        pub async fn update_by_ids<I>(
            self,
            conn: &impl pgorm::GenericClient,
            ids: ::std::vec::Vec<I>,
        ) -> pgorm::OrmResult<u64>
        where
            I: ::pgorm::tokio_postgres::types::ToSql + ::core::marker::Sync + ::core::marker::Send + 'static,
        {
            if ids.is_empty() {
                return ::std::result::Result::Ok(0);
            }

            #destructure
            #now_init
            #version_suppress

            let mut q = pgorm::sql("UPDATE ");
            q.push(#table_name);
            q.push(" SET ");

            let mut first = true;
            #(#set_stmts)*
            #version_set

            if first {
                return Err(pgorm::OrmError::Validation(
                    "UpdateModel: no fields to update".to_string(),
                ));
            }

            q.push(" WHERE ");
            q.push(#table_name);
            q.push(".");
            q.push(#id_col_expr);
            q.push(" = ANY(");
            q.push_bind(ids);
            q.push(")");

            // Note: No version check for bulk updates
            q.execute(conn).await
        }
    }
}

/// Generate update_by_id_force methods (skip version check).
/// Only generated when version field exists.
pub(super) fn generate_update_force_methods(
    table_name: &str,
    id_col_expr: &TokenStream,
    destructure: &TokenStream,
    set_stmts: &[TokenStream],
    has_auto_now: bool,
    version_col: &str,
    version_ident: &syn::Ident,
) -> TokenStream {
    let now_init = if has_auto_now {
        quote! { let __pgorm_now = ::chrono::Utc::now(); }
    } else {
        quote! {}
    };

    let version_suppress = quote! { let _ = #version_ident; };

    // Version SET clause (still increment version, just don't check it)
    let version_set = quote! {
        if !first {
            q.push(", ");
        } else {
            first = false;
        }
        q.push(#version_col);
        q.push(" = ");
        q.push(#version_col);
        q.push(" + 1");
    };

    quote! {
        /// Update columns by primary key, skipping optimistic locking check.
        ///
        /// This method still increments the version field but does NOT check
        /// the current version. Use this for admin overrides or when you
        /// explicitly want to bypass version checking.
        pub async fn update_by_id_force<I>(
            self,
            conn: &impl pgorm::GenericClient,
            id: I,
        ) -> pgorm::OrmResult<u64>
        where
            I: ::pgorm::tokio_postgres::types::ToSql + ::core::marker::Sync + ::core::marker::Send + 'static,
        {
            #destructure
            #now_init
            #version_suppress

            let mut q = pgorm::sql("UPDATE ");
            q.push(#table_name);
            q.push(" SET ");

            let mut first = true;
            #(#set_stmts)*
            #version_set

            if first {
                return Err(pgorm::OrmError::Validation(
                    "UpdateModel: no fields to update".to_string(),
                ));
            }

            q.push(" WHERE ");
            q.push(#table_name);
            q.push(".");
            q.push(#id_col_expr);
            q.push(" = ");
            q.push_bind(id);

            q.execute(conn).await
        }
    }
}

/// Generate update_by_id_returning and update_by_ids_returning methods.
pub(super) fn generate_update_returning_methods(
    attrs: &StructAttrs,
    table_name: &str,
    id_col_expr: &TokenStream,
    destructure: &TokenStream,
    set_stmts: &[TokenStream],
    has_auto_now: bool,
    version_field: Option<&(syn::Ident, String)>,
) -> TokenStream {
    let returning_ty = match attrs.returning.as_ref() {
        Some(ty) => ty,
        None => return quote! {},
    };

    let now_init = if has_auto_now {
        quote! { let __pgorm_now = ::chrono::Utc::now(); }
    } else {
        quote! {}
    };

    // Generate version SET clause: version = version + 1
    let version_set = if let Some((_, version_col)) = version_field {
        quote! {
            if !first {
                q.push(", ");
            } else {
                first = false;
            }
            q.push(#version_col);
            q.push(" = ");
            q.push(#version_col);
            q.push(" + 1");
        }
    } else {
        quote! {}
    };

    // Generate version WHERE clause: AND version = $N
    let version_where = if let Some((version_ident, version_col)) = version_field {
        quote! {
            q.push(" AND ");
            q.push(#version_col);
            q.push(" = ");
            q.push_bind(#version_ident as i64);
        }
    } else {
        quote! {}
    };

    // Suppress unused variable warning for version ident in bulk/force methods
    let version_suppress = if let Some((version_ident, _)) = version_field {
        quote! { let _ = #version_ident; }
    } else {
        quote! {}
    };

    // For returning methods, we need to capture id string before push_bind moves it
    let (id_capture, fetch_with_check) = if let Some((version_ident, _)) = version_field {
        let capture = quote! {
            let __id_str = format!("{:?}", &id);
            let __version_val = #version_ident as i64;
        };
        let check = quote! {
            match q.fetch_one_as::<#returning_ty>(conn).await {
                Ok(row) => Ok(row),
                Err(pgorm::OrmError::NotFound(_)) => {
                    Err(pgorm::OrmError::stale_record(
                        #table_name,
                        __id_str,
                        __version_val,
                    ))
                }
                Err(e) => Err(e),
            }
        };
        (capture, check)
    } else {
        (
            quote! {},
            quote! { q.fetch_one_as::<#returning_ty>(conn).await },
        )
    };

    // Generate force returning method if version field exists
    let force_returning = if let Some((_, version_col)) = version_field {
        let version_set_force = quote! {
            if !first {
                q.push(", ");
            } else {
                first = false;
            }
            q.push(#version_col);
            q.push(" = ");
            q.push(#version_col);
            q.push(" + 1");
        };

        quote! {
            /// Update columns by primary key and return the updated row, skipping optimistic locking check.
            ///
            /// This method still increments the version field but does NOT check
            /// the current version. Use this for admin overrides or when you
            /// explicitly want to bypass version checking.
            pub async fn update_by_id_force_returning<I>(
                self,
                conn: &impl pgorm::GenericClient,
                id: I,
            ) -> pgorm::OrmResult<#returning_ty>
            where
                I: ::pgorm::tokio_postgres::types::ToSql + ::core::marker::Sync + ::core::marker::Send + 'static,
                #returning_ty: pgorm::FromRow,
            {
                #destructure
                #now_init
                #version_suppress

                let mut q = pgorm::Sql::empty();
                q.push("WITH ");
                q.push(#table_name);
                q.push(" AS (UPDATE ");
                q.push(#table_name);
                q.push(" SET ");

                let mut first = true;
                #(#set_stmts)*
                #version_set_force

                if first {
                    return Err(pgorm::OrmError::Validation(
                        "UpdateModel: no fields to update".to_string(),
                    ));
                }

                q.push(" WHERE ");
                q.push(#table_name);
                q.push(".");
                q.push(#id_col_expr);
                q.push(" = ");
                q.push_bind(id);

                q.push(" RETURNING *) SELECT ");
                q.push(#returning_ty::SELECT_LIST);
                q.push(" FROM ");
                q.push(#table_name);
                q.push(" ");
                q.push(#returning_ty::JOIN_CLAUSE);

                q.fetch_one_as::<#returning_ty>(conn).await
            }
        }
    } else {
        quote! {}
    };

    quote! {
        /// Update columns by primary key and return the updated row mapped as the configured returning type.
        ///
        /// If the struct has a `#[orm(version)]` field, this method performs optimistic locking:
        /// it checks that the version matches and returns `OrmError::StaleRecord` if not.
        pub async fn update_by_id_returning<I>(
            self,
            conn: &impl pgorm::GenericClient,
            id: I,
        ) -> pgorm::OrmResult<#returning_ty>
        where
            I: ::pgorm::tokio_postgres::types::ToSql + ::core::marker::Sync + ::core::marker::Send + 'static,
            #returning_ty: pgorm::FromRow,
        {
            #destructure
            #now_init
            #id_capture

            let mut q = pgorm::Sql::empty();
            q.push("WITH ");
            q.push(#table_name);
            q.push(" AS (UPDATE ");
            q.push(#table_name);
            q.push(" SET ");

            let mut first = true;
            #(#set_stmts)*
            #version_set

            if first {
                return Err(pgorm::OrmError::Validation(
                    "UpdateModel: no fields to update".to_string(),
                ));
            }

            q.push(" WHERE ");
            q.push(#table_name);
            q.push(".");
            q.push(#id_col_expr);
            q.push(" = ");
            q.push_bind(id);
            #version_where

            q.push(" RETURNING *) SELECT ");
            q.push(#returning_ty::SELECT_LIST);
            q.push(" FROM ");
            q.push(#table_name);
            q.push(" ");
            q.push(#returning_ty::JOIN_CLAUSE);

            #fetch_with_check
        }

        #force_returning

        /// Update columns by primary key for multiple rows and return updated rows
        /// mapped as the configured returning type.
        ///
        /// The same patch is applied to every matched row.
        ///
        /// Note: Optimistic locking (version check) is NOT supported for bulk updates.
        /// If you need version checking, use a loop with `update_by_id_returning` instead.
        pub async fn update_by_ids_returning<I>(
            self,
            conn: &impl pgorm::GenericClient,
            ids: ::std::vec::Vec<I>,
        ) -> pgorm::OrmResult<::std::vec::Vec<#returning_ty>>
        where
            I: ::pgorm::tokio_postgres::types::ToSql + ::core::marker::Sync + ::core::marker::Send + 'static,
            #returning_ty: pgorm::FromRow,
        {
            if ids.is_empty() {
                return ::std::result::Result::Ok(::std::vec::Vec::new());
            }

            #destructure
            #now_init
            #version_suppress

            let mut q = pgorm::Sql::empty();
            q.push("WITH ");
            q.push(#table_name);
            q.push(" AS (UPDATE ");
            q.push(#table_name);
            q.push(" SET ");

            let mut first = true;
            #(#set_stmts)*
            #version_set

            if first {
                return Err(pgorm::OrmError::Validation(
                    "UpdateModel: no fields to update".to_string(),
                ));
            }

            q.push(" WHERE ");
            q.push(#table_name);
            q.push(".");
            q.push(#id_col_expr);
            q.push(" = ANY(");
            q.push_bind(ids);
            q.push(")");

            q.push(" RETURNING *) SELECT ");
            q.push(#returning_ty::SELECT_LIST);
            q.push(" FROM ");
            q.push(#table_name);
            q.push(" ");
            q.push(#returning_ty::JOIN_CLAUSE);

            // Note: No version check for bulk updates
            q.fetch_all_as::<#returning_ty>(conn).await
        }
    }
}