Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Checking non-null fields on inserts #3584

Open
Ddystopia opened this issue Oct 30, 2024 · 0 comments
Open

Checking non-null fields on inserts #3584

Ddystopia opened this issue Oct 30, 2024 · 0 comments
Labels
enhancement New feature or request

Comments

@Ddystopia
Copy link
Contributor

Ddystopia commented Oct 30, 2024

Is your feature request related to a problem? Please describe.

My attitude toward sqlx was that if it compiles, than db will not throw error at me at runtime.

Of course sqlx cannot check any possible constraint at compile time, but it can at least catch the most common stuff: adding a new non-null column to db.

Example:

use sqlx::PgPool;

fn main() {
    println!("Hello, world!");
}

struct User {
    id: i32,
    name: String,
    #[expect(dead_code)] // obviously that field would be used somewhere else in database and we cannot rely on that warning
    surname: String,
}

#[expect(dead_code)]
async fn insert(pool: PgPool, user: User) {
    // developer forgot to update insert query and compiler did not warn about it
    sqlx::query!(
        "INSERT INTO user (id, name) VALUES ($1, $2)",
        user.id,
        user.name
    )
    .execute(&pool)
    .await
    .unwrap();
}

Migrations:

  • initial:
create table user (id serial primary key, name text not null);
  • second:
alter table user add column surname varchar(255) not null;

Describe the solution you'd like
I expect sqlx to catch basic cases when non-null constraints are violated.

Describe alternatives you've considered

  1. Doing nothing
  2. Workarounds with macros with asserts that every field is used in some way
@Ddystopia Ddystopia added the enhancement New feature or request label Oct 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant