Derive Macro Get

Source
#[derive(Get)]
{
    // Attributes available to this derive:
    #[sql]
}
Expand description

fn get_by_{field-name}({field-name}: {field-type}, exec: impl sqlx::SqliteExecutor<’_ >) -> Result<Self, sqlx::Error>

Generate fn for PRIMARY KEY and every UNIQUE constraint.
Works only if constraint is in all caps, lowercase serves as escape hatch.

#[derive(CreateTableSql,Get,Insert,sqlx::FromRow)]
struct Cat {
   #[sql(constraint = "PRIMARY KEY")]
   id: i64,
   #[sql(constraint = "UNIQUE")]
   name: String,
   #[sql(constraint = "uNIQUE")]
   owner: String,
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), sqlx::Error> {
   use sqlx::{Connection, Executor};
   let mut conn = sqlx::SqliteConnection::connect(":memory:").await?;
   conn.execute(Cat::CREATE_TABLE_SQL).await?;

   let c = Cat {
      id: 0,
      name: "meouw".to_owned(),
      owner: "nobody".to_owned()
   };
   let id = c.insert(&mut conn).await?;
   assert!(id > 0);

   let c2 = Cat::get_by_id(1,&mut conn).await?;
   assert_eq!(c2.name,"meouw");
   let c3 = Cat::get_by_name("meouw",&mut conn).await?;
   assert_eq!(c3.owner,"nobody");

   // there is no fn get_by_owner
   // because the constraint contains lowercase-chars

   Ok(())
}