use crate::structs::*; use lazy_static::lazy_static; use regex::Regex; use slug::slugify; use sqlx::{sqlite::Sqlite, Acquire, Done, Executor, Transaction}; use std::collections::HashSet; type SqlResult = sqlx::Result; // ___ _ _ // | _ \_ _(_)_ ____ _| |_ ___ // | _/ '_| \ V / _` | _/ -_) // |_| |_| |_|\_/\__,_|\__\___| // // I'm putting a lot of faith in Rust's ability to inline stuff. I'm // sure this is okay. But really, this lets the API be clean and // coherent and easily readable, and hides away the gnarliness of some // of the SQL queries. lazy_static! { static ref SELECT_KASTEN_BY_TITLE_SQL: String = str::replace( include_str!("sql/select_notes_by_parameter.sql"), "QUERYPARAMETER", "notes.content" ); } lazy_static! { static ref SELECT_KASTEN_BY_ID_SQL: String = str::replace( include_str!("sql/select_notes_by_parameter.sql"), "QUERYPARAMETER", "notes.id" ); } lazy_static! { static ref SELECT_NOTES_BACKREFENCING_KASTEN_SQL: &'static str = include_str!("sql/select_notes_backreferencing_kasten.sql"); } // ___ _ // | _ \___ ___ ___| |_ // | / -_|_-(executor: E) -> SqlResult<()> where E: Executor<'a, Database = Sqlite>, { let initialize_sql = include_str!("sql/initialize_database.sql"); sqlx::query(initialize_sql) .execute(executor) .await .map(|_| ()) } // ___ _ _ _ __ _ // | __|__| |_ __| |_ | |/ /__ _ __| |_ ___ _ _ // | _/ -_) _/ _| ' \ | ' (executor: E, slug: &NoteId) -> SqlResult> where E: Executor<'a, Database = Sqlite>, { let r: Vec = sqlx::query_as(&SELECT_KASTEN_BY_ID_SQL) .bind(&**slug) .fetch_all(executor) .await?; Ok(r.into_iter().map(|z| Note::from(z)).collect()) } // Fetch the kasten by title. The return value is an array of Note // objects; it is the responsibility of client code to restructure // these into a tree-like object. pub(crate) async fn select_kasten_by_title<'a, E>(executor: E, title: &str) -> SqlResult> where E: Executor<'a, Database = Sqlite>, { let r: Vec = sqlx::query_as(&SELECT_KASTEN_BY_TITLE_SQL) .bind(&title) .fetch_all(executor) .await?; Ok(r.into_iter().map(|z| Note::from(z)).collect()) } // Fetch all backreferences to a kasten. The return value is an array // of arrays, and inside each array is a list from a root kasten to // the note that references the give kasten. Clients may choose how // they want to display that collection. pub(crate) async fn select_backreferences_for_kasten<'a, E>( executor: E, kasten_id: &NoteId, ) -> SqlResult> where E: Executor<'a, Database = Sqlite>, { let r: Vec = sqlx::query_as(&SELECT_NOTES_BACKREFENCING_KASTEN_SQL) .bind(&**kasten_id) .fetch_all(executor) .await?; Ok(r.into_iter().map(|z| Note::from(z)).collect()) } // ___ _ ___ _ _ _ // |_ _|_ _ ___ ___ _ _| |_ / _ \ _ _ ___ | \| |___| |_ ___ // | || ' \(_-(executor: E, zettle: &NewNote) -> SqlResult where E: Executor<'a, Database = Sqlite>, { let insert_one_page_sql = concat!( "INSERT INTO notes (id, content, kind, ", " creation_date, updated_date, lastview_date) ", "VALUES (?, ?, ?, ?, ?, ?);" ); let _ = sqlx::query(insert_one_page_sql) .bind(&zettle.id) .bind(&zettle.content) .bind(zettle.kind.to_string()) .bind(&zettle.creation_date) .bind(&zettle.updated_date) .bind(&zettle.lastview_date) .execute(executor) .await?; Ok(zettle.id.clone()) } // ___ _ _ _ _ __ _ // | _ )_ _(_) |__| | | |/ /__ _ __| |_ ___ _ _ // | _ \ || | | / _` | | ' Option { lazy_static! { static ref RE_CAP_NUM: Regex = Regex::new(r"-(\d+)$").unwrap(); } if slugs.is_empty() { return None; } let mut slug_counters: Vec = slugs .iter() .filter_map(|slug| RE_CAP_NUM.captures(&slug.id)) .map(|cap| cap.get(1).unwrap().as_str().parse::().unwrap()) .collect(); slug_counters.sort_unstable(); slug_counters.pop() } // Given an initial string and an existing collection of slugs, // generate a new slug that does not conflict with the current // collection. Right now we're using the slugify operation, which... // isn't all that. pub(crate) async fn generate_slug<'a, E>(executor: E, title: &str) -> SqlResult where E: Executor<'a, Database = Sqlite>, { lazy_static! { static ref RE_STRIP_NUM: Regex = Regex::new(r"-\d+$").unwrap(); static ref SLUG_FINDER_SQL: String = format!( "SELECT id FROM notes WHERE kind = '{}' AND id LIKE '?%';", NoteKind::Kasten.to_string() ); } let initial_slug = slugify(title); let sample_slug = RE_STRIP_NUM.replace_all(&initial_slug, ""); let similar_slugs: Vec = sqlx::query_as(&SLUG_FINDER_SQL) .bind(&*sample_slug) .fetch_all(executor) .await?; let maximal_slug_number = find_maximal_slug_number(&similar_slugs); Ok(match maximal_slug_number { None => initial_slug, Some(slug_number) => format!("{}-{}", initial_slug, slug_number + 1), }) } // A helper function: given a title and a slug, create a KastenType // note. pub(crate) fn create_zettlekasten(title: &str, slug: &str) -> NewNote { NewNoteBuilder::default() .id(slug.to_string()) .content(title.to_string()) .kind(NoteKind::Kasten) .build() .unwrap() } // _ _ _ _ ___ _ _ _ // | | | |_ __ __| |__ _| |_ ___ / _ \ _ _ ___ | \| |___| |_ ___ // | |_| | '_ \/ _` / _` | _/ -_) | (_) | ' \/ -_) | .` / _ \ _/ -_) // \___/| .__/\__,_\__,_|\__\___| \___/|_||_\___| |_|\_\___/\__\___| // |_| pub(crate) async fn update_note_content<'a, E>( executor: E, note_id: &NoteId, content: &str, ) -> SqlResult<()> where E: Executor<'a, Database = Sqlite>, { let update_note_content_sql = "UPDATE notes SET content = ? WHERE note_id = ?"; let count = sqlx::query(update_note_content_sql) .bind(content) .bind(&**note_id) .execute(executor) .await? .rows_affected(); match count { 1 => Ok(()), _ => Err(sqlx::Error::RowNotFound), } } // ___ _ _ ___ _ _ _ ___ _ _ _ _ _ // | __|__| |_ __| |_ / _ \ _ _ ___ | \| |___| |_ ___ | _ \___| |__ _| |_(_)___ _ _ __| |_ (_)_ __ // | _/ -_) _/ _| ' \ | (_) | ' \/ -_) | .` / _ \ _/ -_) | / -_) / _` | _| / _ \ ' \(_-< ' \| | '_ \ // |_|\___|\__\__|_||_| \___/|_||_\___| |_|\_\___/\__\___| |_|_\___|_\__,_|\__|_\___/_||_/__/_||_|_| .__/ // |_| pub(crate) async fn select_note_to_note_relationship<'a, E>( executor: E, parent_id: &ParentId, note_id: &NoteId, ) -> SqlResult where E: Executor<'a, Database = Sqlite>, { let get_note_to_note_relationship_sql = concat!( "SELECT parent_id, note_id, location, kind ", "FROM note_relationships ", "WHERE parent_id = ? and note_id = ? ", "LIMIT 1" ); let s: NoteRelationshipRow = sqlx::query_as(get_note_to_note_relationship_sql) .bind(&**parent_id) .bind(&**note_id) .fetch_one(executor) .await?; Ok(NoteRelationship::from(s)) } // _ _ _ _ _ _ _ ___ _ _ _ _ _ // | \| |___| |_ ___ | |_ ___ | \| |___| |_ ___ | _ \___| |__ _| |_(_)___ _ _ __| |_ (_)_ __ ___ // | .` / _ \ _/ -_) | _/ _ \ | .` / _ \ _/ -_) | / -_) / _` | _| / _ \ ' \(_-< ' \| | '_ (_-< // |_|\_\___/\__\___| \__\___/ |_|\_\___/\__\___| |_|_\___|_\__,_|\__|_\___/_||_/__/_||_|_| .__/__/ // |_| pub(crate) async fn insert_note_to_note_relationship<'a, E>( executor: E, parent_id: &ParentId, note_id: &NoteId, location: i64, kind: &RelationshipKind, ) -> SqlResult<()> where E: Executor<'a, Database = Sqlite>, { let insert_note_to_note_relationship_sql = concat!( "INSERT INTO note_relationships (parent_id, note_id, location, kind) ", "values (?, ?, ?, ?)" ); let _ = sqlx::query(insert_note_to_note_relationship_sql) .bind(&**parent_id) .bind(&**note_id) .bind(&location) .bind(&kind.to_string()) .execute(executor) .await?; Ok(()) } pub(crate) async fn make_room_for_new_note<'a, E>( executor: E, parent_id: &ParentId, location: i64, ) -> SqlResult<()> where E: Executor<'a, Database = Sqlite>, { let make_room_for_new_note_sql = concat!( "UPDATE note_relationships ", "SET location = location + 1 ", "WHERE location >= ? and parent_id = ?;" ); let _ = sqlx::query(make_room_for_new_note_sql) .bind(&location) .bind(&**parent_id) .execute(executor) .await?; Ok(()) } pub(crate) async fn assert_max_child_location_for_note<'a, E>( executor: E, note_id: &ParentId, ) -> SqlResult where E: Executor<'a, Database = Sqlite>, { let assert_max_child_location_for_note_sql = "SELECT MAX(location) AS count FROM note_relationships WHERE parent_id = ?;"; let count: RowCount = sqlx::query_as(assert_max_child_location_for_note_sql) .bind(&**note_id) .fetch_one(executor) .await?; Ok(count.count) } // _ _ _ _ _ __ _ ___ _ _ _ _ _ // | \| |___| |_ ___ | |_ ___ | |/ /__ _ __| |_ ___ _ _ | _ \___| |__ _| |_(_)___ _ _ __| |_ (_)_ __ ___ // | .` / _ \ _/ -_) | _/ _ \ | ' ( executor: E, note_id: &NoteId, references: &[NoteId], ) -> SqlResult<()> where E: Executor<'a, Database = Sqlite>, { if references.is_empty() { return Ok(()); } let insert_pattern = format!("(?, ?, '{}')", KastenRelationshipKind::Kasten.to_string()); let insert_note_page_references_sql = "INSERT INTO note_kasten_relationships (note_id, kasten_id, kind) VALUES ".to_string() + &[insert_pattern.as_str()] .repeat(references.len()) .join(", ") + &";".to_string(); let mut request = sqlx::query(&insert_note_page_references_sql); for reference in references { request = request.bind(&**note_id).bind(&**reference); } request.execute(executor).await.map(|_| ()) } pub(crate) async fn delete_bulk_note_to_kasten_relationships<'a, E>( executor: E, note_id: &NoteId, ) -> SqlResult<()> where E: Executor<'a, Database = Sqlite>, { let delete_note_to_kasten_relationship_sql = "DELETE FROM note_kasten_relationships WHERE and note_id = ?;"; let _ = sqlx::query(delete_note_to_kasten_relationship_sql) .bind(&**note_id) .execute(executor) .await?; Ok(()) } // Given the references supplied, and the references found in the datastore, // return a list of the references not found in the datastore. pub(crate) fn diff_references( references: &[String], found_references: &[PageTitle], ) -> Vec { let all: HashSet = references.iter().cloned().collect(); let found: HashSet = found_references.iter().map(|r| r.content.clone()).collect(); all.difference(&found).cloned().collect() } // ___ _ _ _ _ __ _ ___ _ _ _ _ _ // / __|___ _ _| |_ ___ _ _| |_ | |_ ___ | |/ /__ _ __| |_ ___ _ _ | _ \___| |__ _| |_(_)___ _ _ __| |_ (_)_ __ ___ // | (__/ _ \ ' \ _/ -_) ' \ _| | _/ _ \ | ' ( executor: E, references: &[String], ) -> SqlResult> where E: Executor<'a, Database = Sqlite>, { if references.is_empty() { return Ok(vec![]); } lazy_static! { static ref SELECT_ALL_REFERENCES_FOR_SQL_BASE: String = format!( "SELECT id, content FROM notes WHERE kind = '{}' AND content IN (", NoteKind::Kasten.to_string() ); } let find_all_references_for_sql = SELECT_ALL_REFERENCES_FOR_SQL_BASE.to_string() + &["?"].repeat(references.len()).join(",") + &");".to_string(); let mut request = sqlx::query_as(&find_all_references_for_sql); for id in references.iter() { request = request.bind(id); } request.fetch_all(executor).await } // ___ _ _ // | \ ___| |___| |_ ___ // | |) / -_) / -_) _/ -_) // |___/\___|_\___|\__\___| // pub(crate) async fn delete_note_to_note_relationship<'a, E>( executor: E, parent_id: &ParentId, note_id: &NoteId, ) -> SqlResult<()> where E: Executor<'a, Database = Sqlite>, { let delete_note_to_note_relationship_sql = concat!( "DELETE FROM note_relationships ", "WHERE parent_id = ? and note_id = ? " ); let count = sqlx::query(delete_note_to_note_relationship_sql) .bind(&**parent_id) .bind(&**note_id) .execute(executor) .await? .rows_affected(); match count { 1 => Ok(()), _ => Err(sqlx::Error::RowNotFound), } } pub(crate) async fn delete_note_to_kasten_relationships<'a, E>( executor: E, note_id: &NoteId, ) -> SqlResult<()> where E: Executor<'a, Database = Sqlite>, { lazy_static! { static ref DELETE_NOTE_TO_KASTEN_RELATIONSHIPS_SQL: String = format!( "DELETE FROM note_relationships WHERE kind in ('{}', '{}') AND parent_id = ?;", KastenRelationshipKind::Kasten.to_string(), KastenRelationshipKind::Unacked.to_string() ); } let _ = sqlx::query(&DELETE_NOTE_TO_KASTEN_RELATIONSHIPS_SQL) .bind(&**note_id) .execute(executor) .await?; Ok(()) } pub(crate) async fn delete_note<'a, E>(executor: E, note_id: &NoteId) -> SqlResult<()> where E: Executor<'a, Database = Sqlite>, { let delete_note_sql = "DELETE FROM notes WHERE note_id = ?"; let count = sqlx::query(delete_note_sql) .bind(&**note_id) .execute(executor) .await? .rows_affected(); match count { 1 => Ok(()), _ => Err(sqlx::Error::RowNotFound), } } // After removing a note, recalculate the position of all notes under // the parent note, such that there order is now completely // sequential. pub(crate) async fn close_hole_for_deleted_note<'a, E>( executor: E, parent_id: &ParentId, location: i64, ) -> SqlResult<()> where E: Executor<'a, Database = Sqlite>, { let close_hole_for_deleted_note_sql = concat!( "UPDATE note_relationships ", "SET location = location - 1 ", "WHERE location > ? and parent_id = ?;" ); let _ = sqlx::query(close_hole_for_deleted_note_sql) .bind(&location) .bind(&**parent_id) .execute(executor) .await?; Ok(()) } // __ __ _ // | \/ (_)___ __ // | |\/| | (_-, note_id: &NoteId, ) -> SqlResult { let mut txi = tx.begin().await?; let count_existing_note_relationships_sql = "SELECT COUNT(*) as count FROM note_relationships WHERE note_id = ?;"; let _: RowCount = sqlx::query_as(&count_existing_note_relationships_sql) .bind(&**note_id) .fetch_one(&mut txi) .await?; let count: RowCount = { let count_existing_note_relationships_sql = "SELECT COUNT(*) as count FROM note_relationships WHERE note_id = ?;"; sqlx::query_as(&count_existing_note_relationships_sql) .bind(&**note_id) .fetch_one(&mut txi) .await? }; txi.commit().await?; Ok(count.count) }