-
-
Notifications
You must be signed in to change notification settings - Fork 524
/
insert.rs
213 lines (201 loc) Β· 6.75 KB
/
insert.rs
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
use crate::{
cast_enum_as_text, error::*, ActiveModelTrait, ConnectionTrait, EntityTrait, Insert,
IntoActiveModel, Iterable, PrimaryKeyTrait, SelectModel, SelectorRaw, Statement, TryFromU64,
};
use sea_query::{Expr, FromValueTuple, Iden, InsertStatement, IntoColumnRef, Query, ValueTuple};
use std::{future::Future, marker::PhantomData};
/// Defines a structure to perform INSERT operations in an ActiveModel
#[derive(Debug)]
pub struct Inserter<A>
where
A: ActiveModelTrait,
{
primary_key: Option<ValueTuple>,
query: InsertStatement,
model: PhantomData<A>,
}
/// The result of an INSERT operation on an ActiveModel
#[derive(Debug)]
pub struct InsertResult<A>
where
A: ActiveModelTrait,
{
/// The id performed when AUTOINCREMENT was performed on the PrimaryKey
pub last_insert_id: <<<A as ActiveModelTrait>::Entity as EntityTrait>::PrimaryKey as PrimaryKeyTrait>::ValueType,
}
impl<A> Insert<A>
where
A: ActiveModelTrait,
{
/// Execute an insert operation
#[allow(unused_mut)]
pub fn exec<'a, C>(self, db: &'a C) -> impl Future<Output = Result<InsertResult<A>, DbErr>> + '_
where
C: ConnectionTrait,
A: 'a,
{
// so that self is dropped before entering await
let mut query = self.query;
if db.support_returning() && <A::Entity as EntityTrait>::PrimaryKey::iter().count() > 0 {
let returning = Query::returning().columns(
<A::Entity as EntityTrait>::PrimaryKey::iter().map(|c| c.into_column_ref()),
);
query.returning(returning);
}
Inserter::<A>::new(self.primary_key, query).exec(db)
}
/// Execute an insert operation without returning (don't use `RETURNING` syntax)
/// Number of rows affected is returned
pub fn exec_without_returning<'a, C>(
self,
db: &'a C,
) -> impl Future<Output = Result<u64, DbErr>> + '_
where
<A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
C: ConnectionTrait,
A: 'a,
{
Inserter::<A>::new(self.primary_key, self.query).exec_without_returning(db)
}
/// Execute an insert operation and return the inserted model (use `RETURNING` syntax if database supported)
pub fn exec_with_returning<'a, C>(
self,
db: &'a C,
) -> impl Future<Output = Result<<A::Entity as EntityTrait>::Model, DbErr>> + '_
where
<A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
C: ConnectionTrait,
A: 'a,
{
Inserter::<A>::new(self.primary_key, self.query).exec_with_returning(db)
}
}
impl<A> Inserter<A>
where
A: ActiveModelTrait,
{
/// Instantiate a new insert operation
pub fn new(primary_key: Option<ValueTuple>, query: InsertStatement) -> Self {
Self {
primary_key,
query,
model: PhantomData,
}
}
/// Execute an insert operation, returning the last inserted id
pub fn exec<'a, C>(self, db: &'a C) -> impl Future<Output = Result<InsertResult<A>, DbErr>> + '_
where
C: ConnectionTrait,
A: 'a,
{
let builder = db.get_database_backend();
exec_insert(self.primary_key, builder.build(&self.query), db)
}
/// Execute an insert operation
pub fn exec_without_returning<'a, C>(
self,
db: &'a C,
) -> impl Future<Output = Result<u64, DbErr>> + '_
where
C: ConnectionTrait,
A: 'a,
{
exec_insert_without_returning(self.query, db)
}
/// Execute an insert operation and return the inserted model (use `RETURNING` syntax if database supported)
pub fn exec_with_returning<'a, C>(
self,
db: &'a C,
) -> impl Future<Output = Result<<A::Entity as EntityTrait>::Model, DbErr>> + '_
where
<A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
C: ConnectionTrait,
A: 'a,
{
exec_insert_with_returning::<A, _>(self.primary_key, self.query, db)
}
}
#[allow(unused_variables, unreachable_code)]
async fn exec_insert<A, C>(
primary_key: Option<ValueTuple>,
statement: Statement,
db: &C,
) -> Result<InsertResult<A>, DbErr>
where
C: ConnectionTrait,
A: ActiveModelTrait,
{
type PrimaryKey<A> = <<A as ActiveModelTrait>::Entity as EntityTrait>::PrimaryKey;
type ValueTypeOf<A> = <PrimaryKey<A> as PrimaryKeyTrait>::ValueType;
let last_insert_id_opt = match db.support_returning() {
true => {
let cols = PrimaryKey::<A>::iter()
.map(|col| col.to_string())
.collect::<Vec<_>>();
let res = db.query_one(statement).await?.unwrap();
res.try_get_many("", cols.as_ref()).ok()
}
false => {
let last_insert_id = db.execute(statement).await?.last_insert_id();
ValueTypeOf::<A>::try_from_u64(last_insert_id).ok()
}
};
let last_insert_id = match primary_key {
Some(value_tuple) => FromValueTuple::from_value_tuple(value_tuple),
None => match last_insert_id_opt {
Some(last_insert_id) => last_insert_id,
None => return Err(DbErr::UnpackInsertId),
},
};
Ok(InsertResult { last_insert_id })
}
async fn exec_insert_without_returning<C>(
insert_statement: InsertStatement,
db: &C,
) -> Result<u64, DbErr>
where
C: ConnectionTrait,
{
let db_backend = db.get_database_backend();
let exec_result = db.execute(db_backend.build(&insert_statement)).await?;
Ok(exec_result.rows_affected())
}
async fn exec_insert_with_returning<A, C>(
primary_key: Option<ValueTuple>,
mut insert_statement: InsertStatement,
db: &C,
) -> Result<<A::Entity as EntityTrait>::Model, DbErr>
where
<A::Entity as EntityTrait>::Model: IntoActiveModel<A>,
C: ConnectionTrait,
A: ActiveModelTrait,
{
let db_backend = db.get_database_backend();
let found = match db.support_returning() {
true => {
let returning = Query::returning().exprs(
<A::Entity as EntityTrait>::Column::iter()
.map(|c| cast_enum_as_text(Expr::col(c), &c)),
);
insert_statement.returning(returning);
SelectorRaw::<SelectModel<<A::Entity as EntityTrait>::Model>>::from_statement(
db_backend.build(&insert_statement),
)
.one(db)
.await?
}
false => {
let insert_res =
exec_insert::<A, _>(primary_key, db_backend.build(&insert_statement), db).await?;
<A::Entity as EntityTrait>::find_by_id(insert_res.last_insert_id)
.one(db)
.await?
}
};
match found {
Some(model) => Ok(model),
None => Err(DbErr::RecordNotFound(
"Failed to find inserted item".to_owned(),
)),
}
}