forked from digital-society-coop/axum-sqlx-tx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
235 lines (199 loc) · 6.37 KB
/
lib.rs
File metadata and controls
235 lines (199 loc) · 6.37 KB
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
use axum::response::IntoResponse;
use sqlx::{sqlite::SqliteArguments, Arguments as _};
use tempfile::NamedTempFile;
use tower::ServiceExt;
type Tx<E = axum_sqlx_tx::Error> = axum_sqlx_tx::Tx<sqlx::Sqlite, E>;
#[tokio::test]
async fn commit_on_success() {
let (_db, pool, response) = build_app(|mut tx: Tx| async move {
let (_, name) = insert_user(&mut tx, 1, "huge hackerman").await;
format!("hello {name}")
})
.await;
assert!(response.status.is_success());
assert_eq!(response.body, "hello huge hackerman");
let users: Vec<(i32, String)> = sqlx::query_as("SELECT * FROM users")
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(users, vec![(1, "huge hackerman".to_string())]);
}
#[tokio::test]
async fn commit_on_redirection() {
let (_db, pool, response) = build_app(|mut tx: Tx| async move {
let (_, _) = insert_user(&mut tx, 1, "john redirect").await;
http::StatusCode::SEE_OTHER
})
.await;
assert!(response.status.is_redirection());
let users: Vec<(i32, String)> = sqlx::query_as("SELECT * FROM users")
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(users, vec![(1, "john redirect".to_string())]);
}
#[tokio::test]
async fn rollback_on_error() {
let (_db, pool, response) = build_app(|mut tx: Tx| async move {
insert_user(&mut tx, 1, "michael oxmaul").await;
http::StatusCode::BAD_REQUEST
})
.await;
assert!(response.status.is_client_error());
assert!(response.body.is_empty());
assert_eq!(get_users(&pool).await, vec![]);
}
#[tokio::test]
async fn explicit_commit() {
let (_db, pool, response) = build_app(|mut tx: Tx| async move {
insert_user(&mut tx, 1, "michael oxmaul").await;
tx.commit().await.unwrap();
http::StatusCode::BAD_REQUEST
})
.await;
assert!(response.status.is_client_error());
assert!(response.body.is_empty());
assert_eq!(
get_users(&pool).await,
vec![(1, "michael oxmaul".to_string())]
);
}
#[tokio::test]
async fn missing_layer() {
let app = axum::Router::new().route("/", axum::routing::get(|_: Tx| async move {}));
let response = app
.oneshot(
http::Request::builder()
.uri("/")
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
assert!(response.status().is_server_error());
let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
assert_eq!(body, format!("{}", axum_sqlx_tx::Error::MissingExtension));
}
#[tokio::test]
async fn overlapping_extractors() {
let (_, _, response) = build_app(|_: Tx, _: Tx| async move {}).await;
assert!(response.status.is_server_error());
assert_eq!(
response.body,
format!("{}", axum_sqlx_tx::Error::OverlappingExtractors)
);
}
#[tokio::test]
async fn extractor_error_override() {
let (_, _, response) = build_app(|_: Tx, _: Tx<MyError>| async move {}).await;
assert!(response.status.is_client_error());
assert_eq!(response.body, "internal server error");
}
#[tokio::test]
async fn layer_error_override() {
let db = NamedTempFile::new().unwrap();
let pool = sqlx::SqlitePool::connect(&format!("sqlite://{}", db.path().display()))
.await
.unwrap();
sqlx::query("CREATE TABLE IF NOT EXISTS users (id INT PRIMARY KEY);")
.execute(&pool)
.await
.unwrap();
sqlx::query(
r#"
CREATE TABLE IF NOT EXISTS comments (
id INT PRIMARY KEY,
user_id INT,
FOREIGN KEY (user_id) REFERENCES users(id) DEFERRABLE INITIALLY DEFERRED
);"#,
)
.execute(&pool)
.await
.unwrap();
let app = axum::Router::new()
.route(
"/",
axum::routing::get(|mut tx: Tx| async move {
sqlx::query("INSERT INTO comments VALUES (random(), random())")
.execute(&mut tx)
.await
.unwrap();
}),
)
.layer(axum_sqlx_tx::Layer::new_with_error::<MyError>(pool.clone()));
let response = app
.oneshot(
http::Request::builder()
.uri("/")
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
let status = response.status();
let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
assert!(status.is_client_error());
assert_eq!(body, "internal server error");
}
async fn insert_user(tx: &mut Tx, id: i32, name: &str) -> (i32, String) {
let mut args = SqliteArguments::default();
args.add(id);
args.add(name);
sqlx::query_as_with(
r#"INSERT INTO users VALUES (?, ?) RETURNING id, name;"#,
args,
)
.fetch_one(tx)
.await
.unwrap()
}
async fn get_users(pool: &sqlx::SqlitePool) -> Vec<(i32, String)> {
sqlx::query_as("SELECT * FROM users")
.fetch_all(pool)
.await
.unwrap()
}
struct Response {
status: http::StatusCode,
body: axum::body::Bytes,
}
async fn build_app<H, T>(handler: H) -> (NamedTempFile, sqlx::SqlitePool, Response)
where
H: axum::handler::Handler<T, axum::body::Body>,
T: 'static,
{
let db = NamedTempFile::new().unwrap();
let pool = sqlx::SqlitePool::connect(&format!("sqlite://{}", db.path().display()))
.await
.unwrap();
sqlx::query("CREATE TABLE IF NOT EXISTS users (id INT PRIMARY KEY, name TEXT);")
.execute(&pool)
.await
.unwrap();
let app = axum::Router::new()
.route("/", axum::routing::get(handler))
.layer(axum_sqlx_tx::Layer::new(pool.clone()));
let response = app
.oneshot(
http::Request::builder()
.uri("/")
.body(axum::body::Body::empty())
.unwrap(),
)
.await
.unwrap();
let status = response.status();
let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
(db, pool, Response { status, body })
}
struct MyError(axum_sqlx_tx::Error);
impl From<axum_sqlx_tx::Error> for MyError {
fn from(error: axum_sqlx_tx::Error) -> Self {
Self(error)
}
}
impl IntoResponse for MyError {
fn into_response(self) -> axum::response::Response {
(http::StatusCode::IM_A_TEAPOT, "internal server error").into_response()
}
}