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
//! Graph update methods code generation.
//!
//! This module contains code generation for:
//! - `update_by_id_graph` method
//! - `update_by_id_graph_returning` method
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::Result;
use super::attrs::StructAttrs;
use super::gen_children::{generate_has_many_update_code, generate_has_one_update_code};
/// Generate update_by_id_graph and update_by_id_graph_returning methods.
pub(super) fn generate_update_graph_methods(
attrs: &StructAttrs,
id_col_expr: &TokenStream,
) -> Result<TokenStream> {
let graph = &attrs.graph;
// If no graph declarations, don't generate graph methods
if !graph.has_any() {
return Ok(quote! {});
}
let table_name = &attrs.table;
// Generate child table handling code
let has_many_code = generate_has_many_update_code(graph, table_name)?;
let has_one_code = generate_has_one_update_code(graph, table_name)?;
// Generate code to check if any child fields have values (Some(...))
let mut check_children_stmts = Vec::new();
for rel in &graph.has_many {
let field_ident = format_ident!("{}", rel.field);
check_children_stmts.push(quote! {
if self.#field_ident.is_some() { __pgorm_has_child_ops = true; }
});
}
for rel in &graph.has_one {
let field_ident = format_ident!("{}", rel.field);
check_children_stmts.push(quote! {
if self.#field_ident.is_some() { __pgorm_has_child_ops = true; }
});
}
let check_children_code = quote! { #(#check_children_stmts)* };
// The graph methods need to handle (per doc §6.3):
// 1. If root patch has main table fields and affected == 0: NotFound
// 2. If root patch has no main table fields but children have changes: verify root exists first
// 3. If nothing to do (no main fields, all children None): Validation error
let update_by_id_graph_method = quote! {
/// Update this struct and all related child tables by primary key.
///
/// Child fields with `None` are not touched. `Some(vec)` triggers the configured strategy.
///
/// Per doc §6.3:
/// - If root has fields to update but affected == 0: returns NotFound
/// - If root has no fields but children have changes: verifies root exists first
/// - If nothing to do at all: returns Validation error
pub async fn update_by_id_graph<I>(
mut self,
conn: &impl ::pgorm::GenericClient,
id: I,
) -> ::pgorm::OrmResult<u64>
where
I: ::pgorm::tokio_postgres::types::ToSql + ::core::marker::Sync + ::core::marker::Send + ::core::clone::Clone + 'static,
{
let mut __pgorm_total_affected: u64 = 0;
let __pgorm_id = id.clone();
// Check if any child fields have operations
let mut __pgorm_has_child_ops = false;
#check_children_code
// Try to update main table
let __pgorm_main_update_result = self.update_by_id(conn, id).await;
match __pgorm_main_update_result {
::std::result::Result::Ok(affected) => {
if affected == 0 {
// Main table had fields to update but no rows matched - NotFound
return ::std::result::Result::Err(::pgorm::OrmError::NotFound(
"update_by_id_graph: root row not found".to_string()
));
}
__pgorm_total_affected += affected;
}
::std::result::Result::Err(::pgorm::OrmError::Validation(msg)) if msg.contains("no fields to update") => {
// No main table fields to update
if !__pgorm_has_child_ops {
// Nothing to do at all - validation error
return ::std::result::Result::Err(::pgorm::OrmError::Validation(
"WriteGraph: no operations to perform".to_string()
));
}
// Verify root exists before touching children
let exists_sql = ::std::format!(
"SELECT 1 FROM {} WHERE {} = $1",
#table_name,
#id_col_expr
);
let exists_result = ::pgorm::query(exists_sql)
.bind(__pgorm_id.clone())
.fetch_opt(conn)
.await?;
if exists_result.is_none() {
return ::std::result::Result::Err(::pgorm::OrmError::NotFound(
"update_by_id_graph: root row not found".to_string()
));
}
}
::std::result::Result::Err(e) => return ::std::result::Result::Err(e),
}
// Process has_many child tables
#has_many_code
// Process has_one child tables
#has_one_code
::std::result::Result::Ok(__pgorm_total_affected)
}
};
let update_by_id_graph_returning_method = if let Some(returning_ty) = attrs.returning.as_ref() {
quote! {
/// Update this struct and all related child tables, returning the updated root row.
///
/// Child fields with `None` are not touched. `Some(vec)` triggers the configured strategy.
///
/// Per doc §6.3:
/// - If root has fields to update but affected == 0: returns NotFound
/// - If root has no fields but children have changes: verifies root exists first
/// - If nothing to do at all: returns Validation error
pub async fn update_by_id_graph_returning<I>(
mut self,
conn: &impl ::pgorm::GenericClient,
id: I,
) -> ::pgorm::OrmResult<#returning_ty>
where
I: ::pgorm::tokio_postgres::types::ToSql + ::core::marker::Sync + ::core::marker::Send + ::core::clone::Clone + 'static,
#returning_ty: ::pgorm::FromRow,
{
let mut __pgorm_total_affected: u64 = 0;
let __pgorm_id = id.clone();
let __pgorm_root_result: #returning_ty;
// Check if any child fields have operations
let mut __pgorm_has_child_ops = false;
#check_children_code
// Try to update main table
let __pgorm_main_update_result = self.update_by_id_returning(conn, id).await;
match __pgorm_main_update_result {
::std::result::Result::Ok(result) => {
__pgorm_total_affected += 1;
__pgorm_root_result = result;
}
::std::result::Result::Err(::pgorm::OrmError::Validation(msg)) if msg.contains("no fields to update") => {
// No main table fields to update
if !__pgorm_has_child_ops {
// Nothing to do at all - validation error
return ::std::result::Result::Err(::pgorm::OrmError::Validation(
"WriteGraph: no operations to perform".to_string()
));
}
// Fetch current row (also verifies it exists)
let sql = ::std::format!(
"SELECT {} FROM {} {} WHERE {}.{} = $1",
#returning_ty::SELECT_LIST,
#table_name,
#returning_ty::JOIN_CLAUSE,
#table_name,
#id_col_expr
);
__pgorm_root_result = ::pgorm::query(sql)
.bind(__pgorm_id.clone())
.fetch_one_as::<#returning_ty>(conn)
.await
.map_err(|e| match e {
::pgorm::OrmError::NotFound(_) => ::pgorm::OrmError::NotFound(
"update_by_id_graph: root row not found".to_string()
),
other => other,
})?;
}
::std::result::Result::Err(::pgorm::OrmError::NotFound(_)) => {
return ::std::result::Result::Err(::pgorm::OrmError::NotFound(
"update_by_id_graph: root row not found".to_string()
));
}
::std::result::Result::Err(e) => return ::std::result::Result::Err(e),
}
// Process has_many child tables
#has_many_code
// Process has_one child tables
#has_one_code
::std::result::Result::Ok(__pgorm_root_result)
}
}
} else {
quote! {}
};
Ok(quote! {
#update_by_id_graph_method
#update_by_id_graph_returning_method
})
}