dbi icon indicating copy to clipboard operation
dbi copied to clipboard

Extending dbi for more functionality and ease of use

Open jonathanvx opened this issue 5 years ago • 0 comments

Here is a pseudo code/demo that includes some pretend features that make this slightly more extendable.

#[dbi_trait(impl_for(new="UserDao"))]
pub trait UserDaoImpl {

    #[schema (production)]
    -- helps with testing in 'test' environments and testing fn's in isolation

    #[base (SELECT u.user_id, u.name FROM #schema.users u )
    -- its good practice not to use 'SELECT * FROM', because if someone adds a column to that table, it can break your code

    #[sql_query(base + "WHERE u.user_id = :id", use_named_params=true)]
    fn find_by_id(self, id: i32) -> Box<Future<Item=Option<User>, Error=my::errors::Error> + Send>;

    #[sql_query(base + "WHERE u.user_id = ?", mapper="|row| { let (id, full_name) = my::from_row_opt(row)?; Ok(User {id, full_name}) }")]
    fn find_by_id_faster(self, id: i32) -> Box<Future<Item=Option<User>, Error=my::errors::Error> + Send>;

    #[sql_query(base + "JOIN #schema.parent p USING (parent_id) WHERE p.parent_id = ?", mapper="|row| { let (id, full_name) = my::from_row_opt(row)?; Ok(Parent {id, full_name}) }")]
    fn find_by_parent_id_faster(self, id: i32) -> Box<Future<Item=Option<User>, Error=my::errors::Error> + Send>;

    #[sql_query("SELECT u.name FROM users u")]
    fn find_all_names(self) -> Box<futures::Future<Item=Vec<String>, Error=my::errors::Error> + Send>;

    #[sql_update("INSERT INTO #schema.users (name,email_id,parent_id) VALUES (:name, :email_id, :parent_id) 
    ON DUPLICATE KEY UPDATE names=VALUES(name),parent_id=VALUES(parent_id)", use_named_params=true)]
    fn create_user_named(self, name: String) -> Box<futures::Future<Item=Option<u64>, Error=my::errors::Error> + Send>;
    -- INSERT or UPDATE (UPSERT) 
    -- If not exist: INSERT, if exists UPDATE non-PRIMARY/UNIQUE columns
    -- if exists and data is the same, database says 'OK', but does nothing and wastes no IO.

    #[sql_create(CREATE TABLE IF NOT EXISTS #schema.users
      user_id int unsigned not null auto_increment,
      name varchar(255) not null,
      email_id int unsigned default null,
      parent_id int unsigned default null,
      updated_at DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY(user_id),
      UNIQUE KEY unq_email(email_id)
      KEY idx_name(name),
      KEY idx_updated(updated_at)) engine = innodb default charset=utf8]
    fn setup_table()
    -- easier for isolated testing for the functions
    -- also helpful to see how the table is built while writing the queries
    -- note: updated_at is for tracking down issues, not loading into the app.
}

jonathanvx avatar Nov 16 '18 11:11 jonathanvx