crudly 0.4.0

Derivable crud helpers for sqlx. Write your SELECT, INSERT, UPDATE and DELETE queries once and reuse them for all your entities.
Documentation
#![forbid(unsafe_code)]
//! # Crudly
//! Derivable crud helpers for sqlx. Write your `SELECT`, `INSERT`, `UPDATE`, and `DELETE` queries once and reuse them for all your entities.
//!
//! Provides the `#[derive(IntoRow)]` and `#[derive(Crudly)]` macros.
//!
//! ## Features
//!
//! - `derive`: (Default) Enables the `#[derive(Crudly)]` and `#[derive(IntoRow)]` macros
//! - `postgres`: Enables default crud implementations for database
//! - `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](https://crates.io/crates/serde).
//!
//! ## Example
//!
//! ```rust
//! # #[allow(unused_variables)]
//! # use crudly::{Crudly, InsertReturningId};
//! # use sqlx::{SqlitePool, query};
//! #[derive(sqlx::FromRow, crudly::IntoRow, crudly::Crudly)]
//! struct User {
//!     #[crudly(id)]
//!     id: i64,
//!     name: String,
//! }
//!
//! 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_returning_id(&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](https://docs.rs/sqlx/latest/sqlx/trait.FromRow.html).
//! 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 the same attributes as `sqlx::FromRow` supports as of sqlx 0.8.6. So The code below will just work:
//! ```
//! # #[allow(unused_variables)]
//! # use crudly::{Crudly, IntoRow, HasColumns};
//! # use sqlx::{SqlitePool, query};
//! #[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 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.
//!
//! **Note:** the field with the `#[crudly(id)]` attribute will never be included in the arguments generated by IntoRow,
//! because depending on context the id might or might not be desired.
//!
//! ## The `Crudly` trait
//!
//! Deriving Crudly enables the following methods: `select_all`, `select_by_id`, `update_by_id`,
//! `id_exists`, `delete_by_id` and either `insert_returning_id` or `insert_with_id` (see next section).
//!
//! ### IDs
//!
//! Currently crudly requires that every entity has a single id column that is expected to be unique (probably a PK).
//! A future version might introduce support for multiple id columns if theres a need for it.
//! The id must be marked with the `#[crudly(id)]` attribute.
//!
//! Further crudly distinguishes between two types of ids:
//!
//! - `DBAssignedId`: The id is assigned by the database using something like an AUTOINCREMENT or SERIAL column.
//! - `ExternallyAssignedId`: The id is assigned by the application using something like a uuid.
//!
//! By default crudly will assume that the id is assigned by the database. If you want to assign the id inside of
//! rust instead, use `#[crudly(external_ids)]` on the struct. See the
//! [external_ids example](https://docs.rs/crudly/latest/crudly/example.external_ids/index.html).
//!
//! ## Executors
//!
//! Crudly provides default implementations for performing the crud operations for sqlite, mysql and postgres.
//! However you might want to customize their behavior. Add some logging, return a custom error type or even add another Database.
//! For this purpose crudly provides the `CRUDExecutor` trait. By default crudly will use the `DefaultCRUDExecutor` struct for all crud operations.
//! you can overwrite this by using the `#[crudly(executor = ...)]` attribute. See the [executor example](https://docs.rs/crudly/latest/crudly/example.custom_executor/index.html) for more details.
//!
//! ```
//! # #[allow(unused_variables)]
//! # use crudly::{Crudly, IntoRow, HasColumns, DefaultCRUDExecutor};
//! # use sqlx::{SqlitePool, query};
//! #[derive(sqlx::FromRow, crudly::IntoRow, crudly::Crudly)]
//! #[crudly(executor = DefaultCRUDExecutor)] // <-- Use your custom executor here
//! struct User {
//!     #[crudly(id)]
//!     id: i64,
//!     user_name: String,
//! }
//! ```
//!
//! ## MSRV
//! The minimum supported Rust version is 1.85.0 (the version that released edition 2024).
//!
//! ## Contributing
//! Contributions, bug reports and feature requests are always welcome! Please open an issue or a pull request on
//! [GitHub](https://github.com/TimoLehnertz/crudly).

mod executor;
mod traits;

#[cfg(feature = "derive")]
pub use crudly_macros::{Crudly, IntoRow};

pub use executor::*;
pub use traits::*;