Skip to main content

Crate crudly

Crate crudly 

Source
Expand description

§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. Non-id column names live on HasColumns; IntoRow adds bind_arguments for a specific sqlx::Database.

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,
    #[crudly(flatten)]
    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:

However interacting with a DB via SQL is a somewhat opinionated matter. So all of these are gated behind the CrudlyDefault marker trait. To gain access you need to write:

ⓘ
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.

Modules§

sql
SQL helpers

Traits§

CrudlyDefault
Marker trait that opts an entity into the default crudly helpers.
DBAssignedId
Marker trait that indicates that the id of an entity is assigned by the database using something like an AUTOINCREMENT or SERIAL column.
DeleteAll
DeleteById
ExternallyAssignedId
Marker trait that indicates that the id of an entity is assigned not by the database but instead inside rust using something like a uuid.
HasColumns
Non-id column names for a row mapping. Split from IntoRow because column names do not depend on the database driver, and Schema flatten (among other call sites) must be able to read them without naming a Database type.
HasId
IdExists
Insert
InsertMany
InsertManyNoId
Batch insert_many for entities with no id column. Blanket impl provided for types that implement NoId — no opt-in via CrudlyDefault required.
InsertManyWithoutIds
InsertNoId
insert (returning ()) for entities with no id column. Blanket impl provided for types that implement NoId — no opt-in via CrudlyDefault required.
InsertWithoutId
Insert rows without supplying the id column so the database can assign ids (e.g. AUTOINCREMENT, SERIAL). This trait is available through the default blanket impls for types that implement CrudlyDefault and DBAssignedId.
IntoRow
Tries to be the counterpart to sqlx::FromRow. Binds non-id values onto an SQLx sqlx::Arguments buffer for Database DB (DB::Arguments).
NoId
Marker trait for entities that have no id column. Emitted automatically by #[derive(Schema)] when no field is marked with #[crudly(id)].
Schema
Describes how a rust struct maps to a database table.
SelectAll
SelectAllNoId
select_all for entities with no id column. Blanket impl provided for types that implement NoId — no opt-in via CrudlyDefault required.
SelectById
SelectByIds
UpdateById

Derive Macros§

IntoRow
Derives HasColumns and IntoRow for a struct.
Schema
Derives Schema (table_name() and columns()).