1
1
use itertools:: Itertools ;
2
- use proc_macro2:: TokenStream ;
2
+ use proc_macro2:: { Span , TokenStream } ;
3
3
use quote:: quote;
4
4
use syn:: Ident ;
5
5
6
6
use crate :: backend:: postgres:: { PgBackend , PgBindings } ;
7
7
use crate :: table:: { Table , TableField } ;
8
8
9
9
fn insert_sql ( table : & Table < PgBackend > , insert_fields : & [ & TableField < PgBackend > ] ) -> String {
10
- format ! (
11
- "INSERT INTO {} ({}) VALUES ({}) RETURNING {}" ,
12
- table. table,
13
- insert_fields. iter( ) . map( |field| field. column( ) ) . join( ", " ) ,
14
- PgBindings :: default ( ) . take( insert_fields. len( ) ) . join( ", " ) ,
15
- table
16
- . default_fields( )
17
- . map( TableField :: fmt_for_select)
18
- . join( ", " )
19
- )
10
+ let columns = insert_fields. iter ( ) . map ( |field| field. column ( ) ) . join ( ", " ) ;
11
+ let fields = PgBindings :: default ( ) . take ( insert_fields. len ( ) ) . join ( ", " ) ;
12
+ let returning_fields = table
13
+ . default_fields ( )
14
+ . map ( TableField :: fmt_for_select)
15
+ . join ( ", " ) ;
16
+
17
+ if returning_fields. is_empty ( ) {
18
+ format ! (
19
+ "INSERT INTO {} ({}) VALUES ({})" ,
20
+ table. table, columns, fields
21
+ )
22
+ } else {
23
+ format ! (
24
+ "INSERT INTO {} ({}) VALUES ({}) RETURNING {}" ,
25
+ table. table, columns, fields, returning_fields
26
+ )
27
+ }
20
28
}
21
29
22
30
pub fn impl_insert ( table : & Table < PgBackend > ) -> TokenStream {
@@ -52,6 +60,12 @@ pub fn impl_insert(table: &Table<PgBackend>) -> TokenStream {
52
60
} )
53
61
. collect :: < Vec < TokenStream > > ( ) ;
54
62
63
+ let fetch_funtion = if default_fields. is_empty ( ) {
64
+ Ident :: new ( "execute" , Span :: call_site ( ) )
65
+ } else {
66
+ Ident :: new ( "fetch_one" , Span :: call_site ( ) )
67
+ } ;
68
+
55
69
let box_future = crate :: utils:: box_future ( ) ;
56
70
quote ! {
57
71
impl ormx:: Insert for #insert_ident {
@@ -63,7 +77,7 @@ pub fn impl_insert(table: &Table<PgBackend>) -> TokenStream {
63
77
) -> #box_future<sqlx:: Result <Self :: Table >> {
64
78
Box :: pin( async move {
65
79
let _generated = sqlx:: query!( #insert_sql, #( #insert_field_exprs, ) * )
66
- . fetch_one ( db as & mut sqlx:: PgConnection )
80
+ . #fetch_funtion ( db as & mut sqlx:: PgConnection )
67
81
. await ?;
68
82
69
83
Ok ( Self :: Table {
0 commit comments