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
/*
* @Author: plucky
* @Date: 2022-10-22 18:08:45
*
*/
use crate::db_type::db::*;
use crate::helper::*;
use crate::impl_by_field::*;
use proc_macro::TokenStream;
use quote::quote;
use syn::{Data, DataStruct, DeriveInput, Fields};
/// generate_crud
pub(crate) fn generate_crud(input: DeriveInput) -> TokenStream {
let table_name = get_table_name(&input);
// println!("table_name: {}", table_name);
let struct_name = &input.ident;
let fields1 = match &input.data {
Data::Struct(DataStruct {
fields: Fields::Named(fields),
..
}) => &fields.named,
_ => panic!("expected a struct with named fields"),
};
// for f in fields1 {
// if let Err(e) = check_attributes(&f.attrs) {
// return e.to_compile_error().into();
// }
// }
// filter skip ignore fields
let fields = fields1.iter().filter(|f| !is_skip(f)).collect::<Vec<_>>();
// insert skip seq field
let fields_insert = fields.iter().filter(|f| !is_seq(f)).collect::<Vec<_>>();
let field_name_insert = fields_insert.iter().map(|field| &field.ident).collect::<Vec<_>>();
// insert (a,b,c) values (?,?,?)
let insert_columns = fields_insert
.iter()
.map(|field| format!("`{}`", get_field_name(field)))
.collect::<Vec<_>>()
.join(",");
let values = question_marks(fields_insert.len());
let select_columns = fields
.iter()
.map(|field| format!("`{}`", get_field_name(field)))
.collect::<Vec<_>>()
.join(",");
// upsert use all fields except ignore
// let field_name_all = fields.iter().map(|field| {
// &field.ident
// }).collect::<Vec<_>>();
// with id field
// let values_all = question_marks(fields.len());
// find `orm_pk` or default the first field as the "id" column
let id_field = fields.iter().find(|f| is_id(f)).unwrap_or_else(|| fields.first().unwrap());
let id_column = id_field.ident.as_ref().unwrap();
let id_name = get_field_name(id_field);
let id_ty = &id_field.ty;
// skip id field
let update_fields = fields.iter().filter(|f| f != &id_field);
// a=?,b=?,c=? or a=$1,b=$2,c=$3
let update_fields_str = update_fields
.clone()
.enumerate()
.map(|(i, f)| format!("`{}` = {}", get_field_name(f), db_placeholder(i + 1)))
.collect::<Vec<_>>()
.join(",");
// println!("update_fields_str: {}", update_fields_str);
let update_fields = update_fields.flat_map(|f| &f.ident).collect::<Vec<_>>();
let len = update_fields.len();
let (pool, query_result, db_arguments) = db_pool_token();
let placeholder = db_placeholder(1);
let placeholder_u = db_placeholder(len + 1);
// update field
let update_token = generate_update_field(&fields, &table_name, id_column);
// by field
// let curd_by_field_token =
// generate_crud_by_field(&fields, &table_name, &update_fields_str, &select_columns, len);
let ts = quote! {
impl #struct_name {
// #curd_by_field_token
#update_token
/// get by id
///
/// Example:
/// ```` no_run
/// User::get(&pool, 1).await
/// ````
pub async fn get(pool: &#pool, id: #id_ty) -> sqlx::Result<Self> {
let sql = format!("SELECT {} FROM {} WHERE {} = {}",#select_columns, #table_name, #id_name, #placeholder);
sqlx::query_as::<_, Self>(&sql)
.bind(id)
.fetch_one(pool).await
}
/// get by where sql
/// Example:
/// ```rust, no_run
/// User::get_by(&pool, "where id=?", args!(1)).await
/// ```
pub async fn get_by(pool: &#pool, where_sql: impl AsRef<str>, args: #db_arguments) -> sqlx::Result<Self> {
let sql = format!("SELECT {} FROM {} {}",#select_columns, #table_name, where_sql.as_ref());
// sqlx::query_as::<_, Self>(&sql)
sqlx::query_as_with::<_,Self,_>(&sql, args)
.fetch_one(pool).await
}
/// get by `co_orm::Where`
/// # Example:
/// ```ignore
/// let w = Where::new().eq("id", 1);
/// let user = User::get_where(pool, w).await?;
/// ```
pub async fn get_where(pool: &#pool, w: co_orm::Where) -> sqlx::Result<Self> {
let (where_sql, args) = w.build();
let sql = format!("SELECT {} FROM {} {}", #select_columns, #table_name, where_sql);
sqlx::query_as_with::<_, Self, _>(&sql, args)
.fetch_one(pool)
.await
}
/// query all
pub async fn query(pool: &#pool) -> sqlx::Result<Vec<Self>> {
let sql = format!("SELECT {} FROM {}", #select_columns, #table_name);
sqlx::query_as::<_, Self>(&sql)
.fetch_all(pool).await
}
/// query by where sql
///
/// Example:
/// ```` no_run
/// User::query_by(&pool, "where id=?", args!(1)).await
/// ````
pub async fn query_by(pool: &#pool, where_sql: impl AsRef<str>, args: #db_arguments) -> sqlx::Result<Vec<Self>> {
let sql = format!("SELECT {} FROM {} {}", #select_columns, #table_name, where_sql.as_ref());
// sqlx::query_as::<_, Self>(&sql)
sqlx::query_as_with::<_,Self,_>(&sql, args)
.fetch_all(pool).await
}
/// query by `co_orm::Where`
/// # Example:
/// ```ignore
/// let w = Where::new().eq("id", 1);
/// let list = User::query_where(pool, w).await?;
/// ```
pub async fn query_where(pool: &#pool, w: co_orm::Where) -> sqlx::Result<Vec<Self>> {
let (where_sql, args) = w.build();
let sql = format!("SELECT {} FROM {} {}", #select_columns, #table_name, where_sql);
sqlx::query_as_with::<_, Self, _>(&sql, args)
.fetch_all(pool)
.await
}
/// insert
pub async fn insert(&self, pool: &#pool) -> sqlx::Result<#query_result> {
let sql = format!("INSERT INTO {} ({}) values ({}) ", #table_name, #insert_columns, #values);
// RETURNING {}
sqlx::query(&sql)
#(
.bind(&self.#field_name_insert)
)*
.execute(pool).await
}
// pub async fn upsert(&self, pool: &#pool) -> sqlx::Result<#query_result> {
// let sql = format!("REPLACE INTO {} ({}) values ({})", #table_name, #columns_all, #values_all);
// sqlx::query(&sql)
// #(
// .bind(&self.#field_name_all)
// )*
// .execute(pool).await
// }
/// delete by id
pub async fn delete(&self, pool: &#pool) -> sqlx::Result<#query_result> {
let mut sql = format!("DELETE FROM {} WHERE {}={}", #table_name,#id_name,#placeholder);
sqlx::query(&sql)
.bind(&self.#id_column)
.execute(pool).await
}
/// delete by where sql
///
/// Example:
/// ```` no_run
/// User::delete_by(&pool, "where id=?", args!(1)).await
/// ````
pub async fn delete_by(pool: &#pool, where_sql: impl AsRef<str>, args: #db_arguments) -> sqlx::Result<#query_result> {
let sql = format!("DELETE FROM {} {}", #table_name, where_sql.as_ref());
sqlx::query_with(&sql,args)
.execute(pool).await
}
/// delete by `co_orm::Where`
/// # Example:
/// ```ignore
/// let w = Where::new().eq("id", 1);
/// User::delete_where(pool, w).await?;
/// ```
pub async fn delete_where(pool: &#pool, w: co_orm::Where) -> sqlx::Result<#query_result> {
let (where_sql, args) = w.build();
let sql = format!("DELETE FROM {} {}", #table_name, where_sql);
sqlx::query_with(&sql, args)
.execute(pool)
.await
}
/// update by id
pub async fn update(&self, pool: &#pool) -> sqlx::Result<#query_result> {
let sql = format!("UPDATE {} SET {} WHERE {} = {}", #table_name, #update_fields_str, #id_name, #placeholder_u);
sqlx::query(&sql)
#(
.bind(&self.#update_fields)
)*
.bind(&self.#id_column)
.execute(pool).await
}
/// update by where sql
///
/// Example:
/// ```` no_run
/// User::update_by(&pool, "where id=1").await?;
/// ````
pub async fn update_by(&self, pool: &#pool, where_sql: impl AsRef<str>) -> sqlx::Result<#query_result> {
let sql = format!("UPDATE {} SET {} {}", #table_name, #update_fields_str, where_sql.as_ref());
sqlx::query(&sql)
#(
.bind(&self.#update_fields)
)*
.execute(pool).await
}
// /// update by `co_orm::Where`
// /// # Example:
// /// ```ignore
// /// let w = Where::new().eq("id", 1);
// /// User::update_where(pool, w).await?;
// /// ```
// pub async fn update_where(&self, pool: &#pool, w: co_orm::Where) -> sqlx::Result<#query_result> {
// let (where_sql, _args) = w.build();
// let sql = format!("UPDATE {} SET {} {}", #table_name, #update_fields_str, where_sql);
// sqlx::query(&sql)
// #(
// .bind(&self.#update_fields)
// )*
// .execute(pool).await
// }
/// insert all list
pub async fn insert_all(pool: &#pool, list: Vec<Self>) -> sqlx::Result<u64> {
let sql = format!("INSERT INTO {} ({}) ", #table_name, #insert_columns);
let mut qb = sqlx::QueryBuilder::new(sql);
qb.push_values(list, |mut q, one| {
// q.push_bind(one.name).push_bind(one.password);
q
#(
.push_bind(one.#field_name_insert)
)*
;
});
let id = qb.build().execute(pool).await?;
Ok(id.rows_affected())
}
/// guery page by where sql
///
/// Example:
/// ```` no_run
/// let (count, list) = User::query_page_by(&pool, "where id>?", page_args!(1), 1, 10).await?;
/// println!("count: {}, list: {:?}", count, list);
/// ````
pub async fn query_page_by(pool: &#pool, where_sql: impl AsRef<str>, args: (#db_arguments, #db_arguments), page: i32, page_size: i32) -> sqlx::Result<(i64, Vec<Self>)> {
let sql = format!("SELECT {} FROM {} {}", #select_columns, #table_name, where_sql.as_ref());
let count_sql = format!("select count(*) from ({}) as c", sql);
let mut a = sqlx::query_scalar_with::<_, i64, _>(&count_sql, args.0);
let total = a.fetch_one(pool).await?;
let sql = format!("{} LIMIT {} OFFSET {}", sql, page_size, page_size * (page - 1));
sqlx::query_as_with::<_, Self, _>(&sql, args.1)
.fetch_all(pool)
.await
.map(|list| (total, list))
}
/// query page by `co_orm::Where`
/// # Example:
/// ```ignore
/// let w = Where::new().eq("id", 1);
/// let (count, list) = User::query_page_where(pool, w, 1, 10).await?;
/// println!("count: {}, list: {:?}", count, list);
/// ```
pub async fn query_page_where(pool: &#pool, w: co_orm::Where, page: i32, page_size: i32) -> sqlx::Result<(i64, Vec<Self>)> {
let (where_sql_count, args_count) = w.clone().build();
let (where_sql_list, args_list) = w.build();
let sql_c = format!("SELECT {} FROM {} {}", #select_columns, #table_name, where_sql_count);
let count_sql = format!("select count(*) from ({}) as c", sql_c);
let total = sqlx::query_scalar_with::<_, i64, _>(&count_sql, args_count).fetch_one(pool).await?;
let sql_l = format!("SELECT {} FROM {} {} LIMIT {} OFFSET {}", #select_columns, #table_name, where_sql_list, page_size, page_size * (page - 1));
sqlx::query_as_with::<_, Self, _>(&sql_l, args_list)
.fetch_all(pool)
.await
.map(|list| (total, list))
}
}
};
TokenStream::from(ts)
}