diesel-autoincrement-new-struct

Crates.iodiesel-autoincrement-new-struct
lib.rsdiesel-autoincrement-new-struct
version0.1.1
sourcesrc
created_at2022-08-07 15:19:17.998123
updated_at2022-08-07 22:44:57.170523
descriptionGenerate NewStructs for all your tables with autoincrementing IDs
homepagehttps://crates.io/crates/diesel_autoincrement_new_struct
repositoryhttps://github.com/LGUG2Z/diesel-autoincrement-new-struct
max_upload_size
id640251
size10,358
جاد (LGUG2Z)

documentation

https://docs.rs/diesel_autoincrement_new_struct

README

diesel-autoincrement-new-struct

Stop copying and pasting structs with the id field removed just so you can insert objects into tables with autoincrementing primary keys.

Motivation

I mean really, who wants to do all that copying and pasting? Who wants to keep attributes and documentation in sync between two otherwise identical structs?

This whole idea came about after finding the excellent macro_rules_attribute crate by Daniel Henry-Mantilla, aka my personal Rust macro hero.

Example

#[macro_use]
extern crate diesel_autoincrement_new_struct;

// Alternatively, you can either import the prelude where needed:
//
// use diesel_increment_new_struct::prelude::*;
//
// Or even import apply and NewInsertable individually:
//
// use diesel_increment_new_struct::apply;
// use diesel_increment_new_struct::NewInsertable;

use diesel::prelude::*;

table! {
    users(id) {
        id -> Integer,
        name -> Text,
    }
}

#[apply(NewInsertable!)]
#[derive(Debug, Clone, Queryable, AsChangeset)]
#[diesel(table_name = users)]
/// This is a user
pub struct User {
    /// This is the ID of the user
    id: i32,
    /// This is the name of the user
    name: String
}

// The code below gets generated by `#[apply(NewInsertable!)]`

#[derive(Debug, Clone, Queryable, AsChangeset)]
#[derive(Insertable)]
#[diesel(table_name = users)]
/// This is a user
pub struct NewUser {
    /// This is the name of the user
    name: String
}

Notes

  • This crate doesn't re-export Diesel, so make sure you have use diesel::prelude::*; or use diesel::Insertable; in whichever files you use this macro
  • This crate requires at least whichever version or revision of Diesel where the #[diesel(table_name = ...)] attribute stopped taking a double quoted string

The #[apply] attribute should always be the topmost attribute above a struct, unless the struct that you want to use it on is also deriving Identifiable. If that is the case, you should have that derive been the topmost attribute above the struct so that it is excluded when generating the NewStruct, becuase obviously, without an id, it won't be Identifiable:

#[derive(Identifiable)]
#[apply(NewInsertable!)]
#[derive(Debug, Clone, Queryable, AsChangeset)]
#[diesel(table_name = users)]
/// This is a user
pub struct User {
    /// This is the ID of the user
    id: i32,
    /// This is the name of the user
    name: String
}
Commit count: 2

cargo fmt