It has the secret for nested transactions.
This commit is contained in:
		
							parent
							
								
									ec81083aa9
								
							
						
					
					
						commit
						cf6f906fa4
					
				| 
						 | 
				
			
			@ -2,7 +2,7 @@ use crate::structs::*;
 | 
			
		|||
use lazy_static::lazy_static;
 | 
			
		||||
use regex::Regex;
 | 
			
		||||
use slug::slugify;
 | 
			
		||||
use sqlx::{sqlite::Sqlite, Done, Executor};
 | 
			
		||||
use sqlx::{sqlite::Sqlite, Acquire, Done, Executor, Transaction};
 | 
			
		||||
use std::collections::HashSet;
 | 
			
		||||
 | 
			
		||||
type SqlResult<T> = sqlx::Result<T>;
 | 
			
		||||
| 
						 | 
				
			
			@ -50,7 +50,10 @@ where
 | 
			
		|||
	E: Executor<'a, Database = Sqlite>,
 | 
			
		||||
{
 | 
			
		||||
	let initialize_sql = include_str!("sql/initialize_database.sql");
 | 
			
		||||
    sqlx::query(initialize_sql).execute(executor).await.map(|_| ())
 | 
			
		||||
	sqlx::query(initialize_sql)
 | 
			
		||||
		.execute(executor)
 | 
			
		||||
		.await
 | 
			
		||||
		.map(|_| ())
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
//  ___    _      _      _  __        _
 | 
			
		||||
| 
						 | 
				
			
			@ -97,7 +100,10 @@ where
 | 
			
		|||
// 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<Vec<Note>>
 | 
			
		||||
pub(crate) async fn select_backreferences_for_kasten<'a, E>(
 | 
			
		||||
	executor: E,
 | 
			
		||||
	kasten_id: &NoteId,
 | 
			
		||||
) -> SqlResult<Vec<Note>>
 | 
			
		||||
where
 | 
			
		||||
	E: Executor<'a, Database = Sqlite>,
 | 
			
		||||
{
 | 
			
		||||
| 
						 | 
				
			
			@ -209,7 +215,11 @@ pub(crate) fn create_zettlekasten(title: &str, slug: &str) -> NewNote {
 | 
			
		|||
//  \___/| .__/\__,_\__,_|\__\___|  \___/|_||_\___| |_|\_\___/\__\___|
 | 
			
		||||
//       |_|
 | 
			
		||||
 | 
			
		||||
pub(crate) async fn update_note_content<'a, E>(executor: E, note_id: &NoteId, content: &str) -> SqlResult<()>
 | 
			
		||||
pub(crate) async fn update_note_content<'a, E>(
 | 
			
		||||
	executor: E,
 | 
			
		||||
	note_id: &NoteId,
 | 
			
		||||
	content: &str,
 | 
			
		||||
) -> SqlResult<()>
 | 
			
		||||
where
 | 
			
		||||
	E: Executor<'a, Database = Sqlite>,
 | 
			
		||||
{
 | 
			
		||||
| 
						 | 
				
			
			@ -286,7 +296,11 @@ where
 | 
			
		|||
	Ok(())
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
pub(crate) async fn make_room_for_new_note<'a, E>(executor: E, parent_id: &ParentId, location: i64) -> SqlResult<()>
 | 
			
		||||
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>,
 | 
			
		||||
{
 | 
			
		||||
| 
						 | 
				
			
			@ -304,7 +318,10 @@ where
 | 
			
		|||
	Ok(())
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
pub(crate) async fn assert_max_child_location_for_note<'a, E>(executor: E, note_id: &ParentId) -> SqlResult<i64>
 | 
			
		||||
pub(crate) async fn assert_max_child_location_for_note<'a, E>(
 | 
			
		||||
	executor: E,
 | 
			
		||||
	note_id: &ParentId,
 | 
			
		||||
) -> SqlResult<i64>
 | 
			
		||||
where
 | 
			
		||||
	E: Executor<'a, Database = Sqlite>,
 | 
			
		||||
{
 | 
			
		||||
| 
						 | 
				
			
			@ -338,10 +355,11 @@ where
 | 
			
		|||
	}
 | 
			
		||||
 | 
			
		||||
	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 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 {
 | 
			
		||||
| 
						 | 
				
			
			@ -351,11 +369,15 @@ where
 | 
			
		|||
	request.execute(executor).await.map(|_| ())
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
pub(crate) async fn delete_bulk_note_to_kasten_relationships<'a, E>(executor: E, note_id: &NoteId) -> SqlResult<()>
 | 
			
		||||
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 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)
 | 
			
		||||
| 
						 | 
				
			
			@ -365,7 +387,10 @@ where
 | 
			
		|||
 | 
			
		||||
// 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<String> {
 | 
			
		||||
pub(crate) fn diff_references(
 | 
			
		||||
	references: &[String],
 | 
			
		||||
	found_references: &[PageTitle],
 | 
			
		||||
) -> Vec<String> {
 | 
			
		||||
	let all: HashSet<String> = references.iter().cloned().collect();
 | 
			
		||||
	let found: HashSet<String> = found_references.iter().map(|r| r.content.clone()).collect();
 | 
			
		||||
	all.difference(&found).cloned().collect()
 | 
			
		||||
| 
						 | 
				
			
			@ -398,8 +423,9 @@ where
 | 
			
		|||
		);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
    let find_all_references_for_sql =
 | 
			
		||||
        SELECT_ALL_REFERENCES_FOR_SQL_BASE.to_string() + &["?"].repeat(references.len()).join(",") + &");".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() {
 | 
			
		||||
| 
						 | 
				
			
			@ -440,7 +466,10 @@ where
 | 
			
		|||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
pub(crate) async fn delete_note_to_kasten_relationships<'a, E>(executor: E, note_id: &NoteId) -> SqlResult<()>
 | 
			
		||||
pub(crate) async fn delete_note_to_kasten_relationships<'a, E>(
 | 
			
		||||
	executor: E,
 | 
			
		||||
	note_id: &NoteId,
 | 
			
		||||
) -> SqlResult<()>
 | 
			
		||||
where
 | 
			
		||||
	E: Executor<'a, Database = Sqlite>,
 | 
			
		||||
{
 | 
			
		||||
| 
						 | 
				
			
			@ -510,17 +539,27 @@ where
 | 
			
		|||
 | 
			
		||||
// The dreaded miscellaneous!
 | 
			
		||||
 | 
			
		||||
pub(crate) async fn count_existing_note_relationships<'a, E>(executor: E, note_id: &NoteId) -> SqlResult<i64>
 | 
			
		||||
where
 | 
			
		||||
    E: Executor<'a, Database = Sqlite>,
 | 
			
		||||
{
 | 
			
		||||
pub(crate) async fn count_existing_note_relationships(
 | 
			
		||||
	tx: &mut Transaction<'_, Sqlite>,
 | 
			
		||||
	note_id: &NoteId,
 | 
			
		||||
) -> SqlResult<i64> {
 | 
			
		||||
	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 = ?;";
 | 
			
		||||
 | 
			
		||||
    let count: RowCount = sqlx::query_as(&count_existing_note_relationships_sql)
 | 
			
		||||
		sqlx::query_as(&count_existing_note_relationships_sql)
 | 
			
		||||
			.bind(&**note_id)
 | 
			
		||||
        .fetch_one(executor)
 | 
			
		||||
        .await?;
 | 
			
		||||
 | 
			
		||||
			.fetch_one(&mut txi)
 | 
			
		||||
			.await?
 | 
			
		||||
	};
 | 
			
		||||
	txi.commit().await?;
 | 
			
		||||
	Ok(count.count)
 | 
			
		||||
}
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
| 
						 | 
				
			
			@ -82,7 +82,9 @@ impl NoteStore {
 | 
			
		|||
	/// to its original empty form.  Do not use unless you
 | 
			
		||||
	/// really, really want that to happen.
 | 
			
		||||
	pub async fn reset_database(&self) -> NoteResult<()> {
 | 
			
		||||
        reset_database(&*self.0).await.map_err(NoteStoreError::DBError)
 | 
			
		||||
		reset_database(&*self.0)
 | 
			
		||||
			.await
 | 
			
		||||
			.map_err(NoteStoreError::DBError)
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/// Fetch page by slug
 | 
			
		||||
| 
						 | 
				
			
			@ -95,11 +97,14 @@ impl NoteStore {
 | 
			
		|||
	pub async fn get_kasten_by_slug(&self, slug: &str) -> NoteResult<(Vec<Note>, Vec<Note>)> {
 | 
			
		||||
		let kasten = select_kasten_by_slug(&*self.0, &NoteId(slug.to_string())).await?;
 | 
			
		||||
		if kasten.is_empty() {
 | 
			
		||||
			return Err(NoteStoreError::NotFound)
 | 
			
		||||
			return Err(NoteStoreError::NotFound);
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		let note_id = NoteId(kasten[0].id.clone());
 | 
			
		||||
        Ok((kasten, select_backreferences_for_kasten(&*self.0, ¬e_id).await?))
 | 
			
		||||
		Ok((
 | 
			
		||||
			kasten,
 | 
			
		||||
			select_backreferences_for_kasten(&*self.0, ¬e_id).await?,
 | 
			
		||||
		))
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/// Fetch page by title
 | 
			
		||||
| 
						 | 
				
			
			@ -117,7 +122,10 @@ impl NoteStore {
 | 
			
		|||
		let kasten = select_kasten_by_title(&*self.0, title).await?;
 | 
			
		||||
		if kasten.len() > 0 {
 | 
			
		||||
			let note_id = NoteId(kasten[0].id.clone());
 | 
			
		||||
            return Ok((kasten, select_backreferences_for_kasten(&*self.0, ¬e_id).await?));
 | 
			
		||||
			return Ok((
 | 
			
		||||
				kasten,
 | 
			
		||||
				select_backreferences_for_kasten(&*self.0, ¬e_id).await?,
 | 
			
		||||
			));
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		// Sanity check!
 | 
			
		||||
| 
						 | 
				
			
			@ -137,12 +145,20 @@ impl NoteStore {
 | 
			
		|||
		Ok((vec![Note::from(zettlekasten)], vec![]))
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
    pub async fn add_note(&self, note: &NewNote, parent_id: &str, location: Option<i64>) -> NoteResult<String> {
 | 
			
		||||
        let new_id = self.insert_note(
 | 
			
		||||
	pub async fn add_note(
 | 
			
		||||
		&self,
 | 
			
		||||
		note: &NewNote,
 | 
			
		||||
		parent_id: &str,
 | 
			
		||||
		location: Option<i64>,
 | 
			
		||||
	) -> NoteResult<String> {
 | 
			
		||||
		let new_id = self
 | 
			
		||||
			.insert_note(
 | 
			
		||||
				note,
 | 
			
		||||
				&ParentId(parent_id.to_string()),
 | 
			
		||||
				location,
 | 
			
		||||
            RelationshipKind::Direct).await?;
 | 
			
		||||
				RelationshipKind::Direct,
 | 
			
		||||
			)
 | 
			
		||||
			.await?;
 | 
			
		||||
		Ok(new_id)
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
| 
						 | 
				
			
			@ -166,11 +182,18 @@ impl NoteStore {
 | 
			
		|||
 | 
			
		||||
		let _ = delete_note_to_note_relationship(&mut tx, &old_parent_id, ¬e_id).await?;
 | 
			
		||||
		let _ = close_hole_for_deleted_note(&mut tx, &old_parent_id, old_note_location).await?;
 | 
			
		||||
        let parent_max_location = assert_max_child_location_for_note(&mut tx, &new_parent_id).await?;
 | 
			
		||||
		let parent_max_location =
 | 
			
		||||
			assert_max_child_location_for_note(&mut tx, &new_parent_id).await?;
 | 
			
		||||
		let new_location = cmp::min(parent_max_location + 1, new_location);
 | 
			
		||||
		let _ = make_room_for_new_note(&mut tx, &new_parent_id, new_location).await?;
 | 
			
		||||
        let _ =
 | 
			
		||||
            insert_note_to_note_relationship(&mut tx, &new_parent_id, ¬e_id, new_location, &old_note_kind).await?;
 | 
			
		||||
		let _ = insert_note_to_note_relationship(
 | 
			
		||||
			&mut tx,
 | 
			
		||||
			&new_parent_id,
 | 
			
		||||
			¬e_id,
 | 
			
		||||
			new_location,
 | 
			
		||||
			&old_note_kind,
 | 
			
		||||
		)
 | 
			
		||||
		.await?;
 | 
			
		||||
		tx.commit().await?;
 | 
			
		||||
		Ok(())
 | 
			
		||||
	}
 | 
			
		||||
| 
						 | 
				
			
			@ -184,7 +207,8 @@ impl NoteStore {
 | 
			
		|||
		let mut tx = self.0.begin().await?;
 | 
			
		||||
		let _ = update_note_content(&mut tx, ¬e_id, &content).await?;
 | 
			
		||||
		let _ = delete_bulk_note_to_kasten_relationships(&mut tx, ¬e_id).await?;
 | 
			
		||||
        let found_references = find_all_kasten_from_list_of_references(&mut tx, &references).await?;
 | 
			
		||||
		let found_references =
 | 
			
		||||
			find_all_kasten_from_list_of_references(&mut tx, &references).await?;
 | 
			
		||||
		let new_references = diff_references(&references, &found_references);
 | 
			
		||||
		let mut known_reference_ids: Vec<NoteId> = Vec::new();
 | 
			
		||||
		for one_reference in new_references.iter() {
 | 
			
		||||
| 
						 | 
				
			
			@ -194,8 +218,14 @@ impl NoteStore {
 | 
			
		|||
			known_reference_ids.push(NoteId(slug));
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
        known_reference_ids.append(&mut found_references.iter().map(|r| NoteId(r.id.clone())).collect());
 | 
			
		||||
        let _ = insert_bulk_note_to_kasten_relationships(&mut tx, ¬e_id, &known_reference_ids).await?;
 | 
			
		||||
		known_reference_ids.append(
 | 
			
		||||
			&mut found_references
 | 
			
		||||
				.iter()
 | 
			
		||||
				.map(|r| NoteId(r.id.clone()))
 | 
			
		||||
				.collect(),
 | 
			
		||||
		);
 | 
			
		||||
		let _ = insert_bulk_note_to_kasten_relationships(&mut tx, ¬e_id, &known_reference_ids)
 | 
			
		||||
			.await?;
 | 
			
		||||
		tx.commit().await?;
 | 
			
		||||
		Ok(())
 | 
			
		||||
	}
 | 
			
		||||
| 
						 | 
				
			
			@ -219,7 +249,6 @@ impl NoteStore {
 | 
			
		|||
		tx.commit().await?;
 | 
			
		||||
		Ok(())
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// The Private stuff
 | 
			
		||||
| 
						 | 
				
			
			@ -277,7 +306,8 @@ impl NoteStore {
 | 
			
		|||
		make_room_for_new_note(&mut tx, &parent_id, location).await?;
 | 
			
		||||
		insert_note_to_note_relationship(&mut tx, &parent_id, ¬e_id, location, &kind).await?;
 | 
			
		||||
 | 
			
		||||
        let found_references = find_all_kasten_from_list_of_references(&mut tx, &references).await?;
 | 
			
		||||
		let found_references =
 | 
			
		||||
			find_all_kasten_from_list_of_references(&mut tx, &references).await?;
 | 
			
		||||
		let new_references = diff_references(&references, &found_references);
 | 
			
		||||
		let mut known_reference_ids: Vec<NoteId> = Vec::new();
 | 
			
		||||
		for one_reference in new_references.iter() {
 | 
			
		||||
| 
						 | 
				
			
			@ -287,8 +317,14 @@ impl NoteStore {
 | 
			
		|||
			known_reference_ids.push(NoteId(slug));
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
        known_reference_ids.append(&mut found_references.iter().map(|r| NoteId(r.id.clone())).collect());
 | 
			
		||||
        let _ = insert_bulk_note_to_kasten_relationships(&mut tx, ¬e_id, &known_reference_ids).await?;
 | 
			
		||||
		known_reference_ids.append(
 | 
			
		||||
			&mut found_references
 | 
			
		||||
				.iter()
 | 
			
		||||
				.map(|r| NoteId(r.id.clone()))
 | 
			
		||||
				.collect(),
 | 
			
		||||
		);
 | 
			
		||||
		let _ = insert_bulk_note_to_kasten_relationships(&mut tx, ¬e_id, &known_reference_ids)
 | 
			
		||||
			.await?;
 | 
			
		||||
		tx.commit().await?;
 | 
			
		||||
		Ok(note_id.to_string())
 | 
			
		||||
	}
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
		Loading…
	
		Reference in New Issue