do not use UPSERT

This commit is contained in:
Martin Brodbeck 2025-01-16 14:25:01 +01:00
parent eab0e2bac8
commit fd4603ba42

View file

@ -87,9 +87,7 @@ async fn main() {
let mut bind_with = "127.0.0.1:".to_owned(); let mut bind_with = "127.0.0.1:".to_owned();
bind_with += &listen_port; bind_with += &listen_port;
let listener = tokio::net::TcpListener::bind(bind_with) let listener = tokio::net::TcpListener::bind(bind_with).await.unwrap();
.await
.unwrap();
axum::serve(listener, app).await.unwrap(); axum::serve(listener, app).await.unwrap();
} }
@ -190,27 +188,50 @@ async fn update_progress(
.unwrap() .unwrap()
.as_secs(); .as_secs();
let row: (i64,) = sqlx::query_as("SELECT id FROM users WHERE username = $1") let user_row: (i64,) = sqlx::query_as("SELECT id FROM users WHERE username = $1")
.bind(&username) .bind(&username)
.fetch_one(&db_pool) .fetch_one(&db_pool)
.await .await
.unwrap(); .unwrap();
let user_id = row.0; let user_id = user_row.0;
sqlx::query("INSERT INTO progresses (user_id, document, progress, percentage, device, device_id, timestamp) VALUES ($1, $2, $3, $4, $5, $6, $7) \ let mut tx = db_pool.begin().await.unwrap();
ON CONFLICT (user_id, document) DO UPDATE \
SET user_id = $1, document = $2, progress = $3, percentage = $4, device = $5, device_id = $6, timestamp = $7") let doc_row = sqlx::query("SELECT 1 FROM progresses WHERE user_id = $1 AND document = $2")
.bind(user_id) .bind(user_id)
.bind(&payload.document) .bind(&payload.document)
.bind(&payload.progress) .fetch_optional(&mut *tx)
.bind(&payload.percentage) .await
.bind(&payload.device) .unwrap();
.bind(&payload.device_id)
.bind(timestamp as i64) if doc_row.is_none() {
.execute(&db_pool) sqlx::query("INSERT INTO progresses (user_id, document, progress, percentage, device, device_id, timestamp) VALUES ($1, $2, $3, $4, $5, $6, $7)")
.await .bind(user_id)
.unwrap(); .bind(&payload.document)
.bind(&payload.progress)
.bind(&payload.percentage)
.bind(&payload.device)
.bind(&payload.device_id)
.bind(timestamp as i64)
.execute(&mut *tx)
.await
.unwrap();
} else {
sqlx::query("UPDATE progresses SET progress = $3, percentage = $4, device = $5, device_id = $6, timestamp = $7 WHERE user_id = $1 AND document = $2")
.bind(user_id)
.bind(&payload.document)
.bind(&payload.progress)
.bind(&payload.percentage)
.bind(&payload.device)
.bind(&payload.device_id)
.bind(timestamp as i64)
.execute(&mut *tx)
.await
.unwrap();
}
tx.commit().await.unwrap();
StatusCode::OK StatusCode::OK
} }