`ColumnNotFound("id")` when inserting with SQLx

77 views Asked by At

I want to insert a new row and then get back the row I just inserted.

use serde::{Deserialize, Serialize};
use sqlx::{FromRow, mysql::MySqlPoolOptions};
use tokio;

#[derive(Debug, Deserialize, Serialize, FromRow)]
struct Session {
    id: i32,
    name: String,
}

#[tokio::main]
async fn main() {
    let pool = MySqlPoolOptions::new()
        .max_connections(10)
        .connect("mysql://me:password@localhost/time_tracker")
        .await
        .unwrap();
    let session: Session = sqlx::query_as("INSERT INTO sessions (name) VALUES (?) RETURNING *")
        .bind("Session name")
        .fetch_one(&pool)
        .await
        .unwrap();
    println!("{session:?}");
}

The table looks like this:

MariaDB [time_tracker]> DESCRIBE sessions;
Field Type Null Key Default Extra
id int(11) NO PRI NULL auto_increment
name varchar(255) YES NULL
start_time datetime YES NULL
end_time datetime YES NULL
pay_rate decimal(10,2) YES NULL

But I get this error. If I change it to RETURNING name I get the same error.

thread 'main' panicked at src/main.rs:22:10:
called `Result::unwrap()` on an `Err` value: ColumnNotFound("id")

If I change it to this:

    let row = sqlx::query("INSERT INTO sessions (name) VALUES (?)")
        .bind("Session name")
        .fetch_one(&pool)
        .await
        .unwrap();

I get:

thread 'main' panicked at src/main.rs:22:10:
called `Result::unwrap()` on an `Err` value: RowNotFound

The query works just fine if I do it in MariaDB directly.

MariaDB [time_tracker]> INSERT INTO sessions (name) VALUES ("Session name") RETURNING *;
id name start_time end_time pay_rate
32 Session name NULL NULL NULL

What am I doing wrong?

0

There are 0 answers