crudly 0.6.2

Derivable crud helpers for sqlx. Write your SELECT, INSERT, UPDATE and DELETE queries once and reuse them for all your entities.
Documentation

Crates.io Documentation dependency status

Crudly

Crudly helps you work with database entities in three ways:

  1. Traits that describe how an entity maps to a database table. Table name, column names, Id column, and more.
  2. Derive macros #[derive(Schema)] and #[derive(IntoRow)] which implement those traits for you.
  3. Opinionated CRUD implementations—default implementations of select_by_id(), insert(), update_by_id(), and more for any type that implements the traits. Alternatively, you can write your own SQL helpers against the same traits and then reuse them for all your entity types.

Features

  • derive: (Default) Enables the #[derive(Schema)] and #[derive(IntoRow)] macros
  • postgres: Enables default crud implementations for postgres
  • mysql: Enables default crud implementations for MySQL
  • sqlite: Enables default crud implementations for sqlite
  • all-databases: Enables default crud implementations all DBs above
  • json: Enables support for the #[sqlx(json)] / #[crudly(json)] attribute using serde.

Example

#[derive(sqlx::FromRow, crudly::IntoRow, crudly::Schema)]
struct User {
    #[crudly(id)]
    id: i64,
    name: String,
}

// Opt into default crudly implementations. This enables the insert,
// select_all, update_by_id, delete_by_id implementations used below.
// Here instead you could use your own generic sql implementations.
impl crudly::CrudlyDefault for User {}

const CREATE_USERS_TABLE_SQL: &str =
    "CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT NOT NULL);";

#[tokio::main]
async fn main() {
    let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
    query(CREATE_USERS_TABLE_SQL).execute(&pool).await.unwrap();
    // --------------- Inserting a user ---------------
    let user = User {
        id: 0,
        name: "John Doe".to_string(),
    };
    let inserted_id = user.insert(&pool).await.unwrap();
    assert_eq!(inserted_id, 1);
    // --------------- Selecting all users ---------------
    let mut users: Vec<User> = User::select_all(&pool).await.unwrap();
    assert_eq!(users.len(), 1);
    let mut jon = users.remove(0);
    jon.name = "Jane Doe".to_string();
    // --------------- Updating a user ---------------
    let updated = jon.update_by_id(&pool).await.unwrap();
    assert!(updated);
    // --------------- Getting a user by id ---------------
    let updated_user = User::select_by_id(&1, &pool).await.unwrap().unwrap();
    assert_eq!(updated_user.name, "Jane Doe");
    // --------------- Deleting a user ---------------
    let deleted = User::delete_by_id(&1, &pool).await.unwrap();
    assert!(deleted);
    let users: Vec<User> = User::select_all(&pool).await.unwrap();
    assert!(users.is_empty());
}

The IntoRow trait

IntoRow tries to be the counterpart to sqlx::FromRow. It exposes the following two functions:

  • columns: Returns the column names for the struct (respecting all sqlx attributes)
  • bind_arguments: Binds the values of the struct to an SQLx [sqlx::Arguments] buffer Deriving IntoRow IntoRow understands all attributes that sqlx::FromRow supports as of sqlx 0.9.0. So The code below will just work:
#[derive(crudly::IntoRow)]
#[sqlx(rename_all = "camelCase")]
struct User {
    #[sqlx(rename = "userId")]
    id: i64,
    user_name: String,
    #[sqlx(skip)]
    skip_me: String,
}

assert_eq!(User::columns(), vec!["userId", "userName"]);

In case you only want to derive [IntoRow] and not sqlx::FromRow all the attributes also have a #[crudly(rename = "name")] format. Crudly understands the #[sqlx(try_from = ...))] as #[crudly(try_into = ...)] for binding to arguments it will then use the TryInto trait before decoding. Just like with sqlx::FromRow, [IntoRow] can be nested. Say you have the following:

#[derive(IntoRow)]
struct Address {
    street: String,
    city: String,
}

#[derive(IntoRow)]
struct User {
    name: String,
    address: Address,
}

Then User will behave as if Address would be inlined into it. Note: Fields annotated with #[crudly(id)] will not be included in the arguments generated by IntoRow.

IDs

Crudly allows annotating a field with #[crudly(id)]. Doing this will enable the update_by_id and delete_by_id methods. Then crudly distinguishes between two types of ids:

  • ab assigned ids (default): The id is assigned by the database using something like an AUTOINCREMENT or SERIAL column.
  • Externally assigned ids: The id is assigned in rust. By default, the insert method will not insert the id column. Instead it returns the id that the DB generated. That is only supported for integer ids. If your DB assigns non integer ids (uuid or similar) you will need to implement your own insert functions. If you don't generate ids in the db at all, you can opt out with the #[crudly(external_ids)]attribute. Have a look at the external_ids example example. With this, the insert functions will just insert the id column like any other column and not return anything.

CrudlyDefault

The following helpers are available:

impl CrudlyDefault for MyEntity {}

The helper impl all look like the following:

impl<T> SelectAll<MySql> for T where T: CrudlyDefault + Schema + HasId {/* ... */}

If you need custom behavior, simply implement your own SelectAll, SelectById, etc. traits and then add blanked impls like the one above. If doing so, you might find the helpers defined in the [sql] module useful.

MSRV

The minimum supported Rust version is 1.94.0 (the version that sqlx 0.9.0 requires).

Contributing

Contributions, bug reports and feature requests are always welcome! Please open an issue or a pull request on GitHub.