diff --git a/src/main.rs b/src/main.rs index e95c146..f4f3bdc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -87,9 +87,7 @@ async fn main() { let mut bind_with = "127.0.0.1:".to_owned(); bind_with += &listen_port; - let listener = tokio::net::TcpListener::bind(bind_with) - .await - .unwrap(); + let listener = tokio::net::TcpListener::bind(bind_with).await.unwrap(); axum::serve(listener, app).await.unwrap(); } @@ -190,27 +188,50 @@ async fn update_progress( .unwrap() .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) .fetch_one(&db_pool) .await .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) \ - ON CONFLICT (user_id, document) DO UPDATE \ - SET user_id = $1, document = $2, progress = $3, percentage = $4, device = $5, device_id = $6, timestamp = $7") - .bind(user_id) - .bind(&payload.document) - .bind(&payload.progress) - .bind(&payload.percentage) - .bind(&payload.device) - .bind(&payload.device_id) - .bind(timestamp as i64) - .execute(&db_pool) - .await - .unwrap(); + let mut tx = db_pool.begin().await.unwrap(); + + let doc_row = sqlx::query("SELECT 1 FROM progresses WHERE user_id = $1 AND document = $2") + .bind(user_id) + .bind(&payload.document) + .fetch_optional(&mut *tx) + .await + .unwrap(); + + if doc_row.is_none() { + sqlx::query("INSERT INTO progresses (user_id, document, progress, percentage, device, device_id, timestamp) VALUES ($1, $2, $3, $4, $5, $6, $7)") + .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(); + } 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 }