MERGE Shrinkwrap and Comrak updates.

This commit is contained in:
Elf M. Sternberg 2020-10-13 18:03:12 -07:00
commit 0f98dc4523
2 changed files with 370 additions and 325 deletions

View File

@ -16,6 +16,7 @@ thiserror = "1.0.20"
derive_builder = "0.9.0"
lazy_static = "1.4.0"
comrak = "0.8.2"
shrinkwraprs = "0.3.0"
regex = "1.3.9"
slug = "0.1.4"
tokio = { version = "0.2.22", features = ["rt-threaded", "blocking"] }

View File

@ -1,20 +1,27 @@
use crate::errors::NoteStoreError;
use crate::row_structs::{
JustId, JustSlugs, NewNote, NewNoteBuilder, NewPage,
NewPageBuilder, NoteRelationship, RawNote, RawPage,
JustId, JustSlugs, NewNote, NewNoteBuilder, NewPage, NewPageBuilder, NoteRelationship, RawNote,
RawPage,
};
use friendly_id;
use lazy_static::lazy_static;
use std::collections::HashMap;
use regex::Regex;
use shrinkwraprs::Shrinkwrap;
use slug::slugify;
use sqlx;
use sqlx::{
sqlite::{Sqlite, SqlitePool, SqliteRow},
Done, Executor, Row
Done, Executor, Row,
};
use std::collections::HashMap;
use std::sync::Arc;
#[derive(Shrinkwrap, Copy, Clone)]
struct ParentId(i64);
#[derive(Shrinkwrap, Copy, Clone)]
struct NoteId(i64);
/// A handle to our Sqlite database.
#[derive(Clone, Debug)]
pub struct NoteStore(Arc<SqlitePool>);
@ -32,7 +39,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
@ -63,7 +72,10 @@ impl NoteStore {
let (page, notes) = match select_page_by_title(&mut tx, title).await {
Ok(page) => {
let note_id = page.note_id;
(page, select_note_collection_from_root(&mut tx, note_id).await?)
(
page,
select_note_collection_from_root(&mut tx, note_id).await?,
)
}
Err(sqlx::Error::RowNotFound) => {
let page = {
@ -75,7 +87,10 @@ impl NoteStore {
select_page_by_title(&mut tx, &title).await?
};
let note_id = page.note_id;
(page, select_note_collection_from_root(&mut tx, note_id).await?)
(
page,
select_note_collection_from_root(&mut tx, note_id).await?,
)
}
Err(e) => return Err(NoteStoreError::DBError(e)),
};
@ -113,20 +128,20 @@ impl NoteStore {
) -> NoteResult<()> {
let sample = vec![note_uuid, old_parent_uuid, new_parent_uuid];
let mut tx = self.0.begin().await?;
let found_id_vec = bulk_select_ids_for_note_uuids(&mut tx, &sample)
.await?;
let found_ids: HashMap<String, i64> = found_id_vec
.into_iter()
.collect();
// This is one of the few cases where we we're getting IDs for
// notes, but the nature of the ID isn't known at this time.
// This has to be handled manually, in the next paragraph
// below.
let found_id_vec = bulk_select_ids_for_note_uuids(&mut tx, &sample).await?;
let found_ids: HashMap<String, i64> = found_id_vec.into_iter().collect();
if found_ids.len() != 3 {
return Err(NoteStoreError::NotFound);
}
let old_parent_id = *found_ids.get(old_parent_uuid).unwrap();
let new_parent_id = *found_ids.get(new_parent_uuid).unwrap();
let note_id = *found_ids.get(note_uuid).unwrap();
let old_parent_id = ParentId(*found_ids.get(old_parent_uuid).unwrap());
let new_parent_id = ParentId(*found_ids.get(new_parent_uuid).unwrap());
let note_id = NoteId(*found_ids.get(note_uuid).unwrap());
let old_note_position = get_note_note_relationship(&mut tx, old_parent_id, note_id)
.await?
@ -135,7 +150,8 @@ impl NoteStore {
let _ = delete_note_note_relationship(&mut tx, old_parent_id, note_id).await?;
let _ = close_hole_for_deleted_note(&mut tx, old_parent_id, old_note_position).await?;
let _ = make_room_for_new_note(&mut tx, new_parent_id, new_position).await?;
let _ = insert_note_note_relationship(&mut tx, new_parent_id, note_id, new_position).await?;
let _ =
insert_note_note_relationship(&mut tx, new_parent_id, note_id, new_position).await?;
tx.commit().await?;
Ok(())
}
@ -146,23 +162,18 @@ impl NoteStore {
note_uuid: &str,
new_parent_uuid: &str,
new_position: i64,
new_nature: &str) -> NoteResult<()> {
new_nature: &str,
) -> NoteResult<()> {
todo!()
}
/// Delete a note
pub async fn delete_note(
&self,
note_uuid: &str,
note_parent_uuid: &str) -> NoteResult<()> {
pub async fn delete_note(&self, note_uuid: &str, note_parent_uuid: &str) -> NoteResult<()> {
todo!()
}
/// Update a note's content
pub async fn update_note_content(
&self,
note_uuid: &str,
content: &str) -> NoteResult<()> {
pub async fn update_note_content(&self, note_uuid: &str, content: &str) -> NoteResult<()> {
todo!()
}
}
@ -182,7 +193,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(|_| ())
}
async fn select_page_by_slug<'a, E>(executor: E, slug: &str) -> SqlResult<RawPage>
@ -213,7 +227,7 @@ where
.await?)
}
async fn select_note_id_for_uuid<'a, E>(executor: E, uuid: &str) -> SqlResult<i64>
async fn select_note_id_for_uuid<'a, E>(executor: E, uuid: &str) -> SqlResult<ParentId>
where
E: Executor<'a, Database = Sqlite>,
{
@ -222,10 +236,14 @@ where
.bind(&uuid)
.fetch_one(executor)
.await?;
Ok(id.id)
Ok(ParentId(id.id))
}
async fn make_room_for_new_note<'a, E>(executor: E, parent_id: i64, position: i64) -> SqlResult<()>
async fn make_room_for_new_note<'a, E>(
executor: E,
parent_id: ParentId,
position: i64,
) -> SqlResult<()>
where
E: Executor<'a, Database = Sqlite>,
{
@ -237,13 +255,18 @@ where
sqlx::query(make_room_for_new_note_sql)
.bind(&position)
.bind(&parent_id)
.bind(&*parent_id)
.execute(executor)
.await
.map(|_| ())
}
async fn insert_note_note_relationship<'a, E>(executor: E, parent_id: i64, note_id: i64, position: i64) -> SqlResult<()>
async fn insert_note_note_relationship<'a, E>(
executor: E,
parent_id: ParentId,
note_id: NoteId,
position: i64,
) -> SqlResult<()>
where
E: Executor<'a, Database = Sqlite>,
{
@ -253,8 +276,8 @@ where
);
sqlx::query(insert_note_note_relationship_sql)
.bind(&parent_id)
.bind(&note_id)
.bind(&*parent_id)
.bind(&*note_id)
.bind(&position)
.bind("note")
.execute(executor)
@ -266,14 +289,15 @@ async fn select_note_collection_from_root<'a, E>(executor: E, root: i64) -> SqlR
where
E: Executor<'a, Database = Sqlite>,
{
let select_note_collection_from_root_sql = include_str!("sql/select_note_collection_from_root.sql");
let select_note_collection_from_root_sql =
include_str!("sql/select_note_collection_from_root.sql");
Ok(sqlx::query_as(&select_note_collection_from_root_sql)
.bind(&root)
.fetch_all(executor)
.await?)
}
async fn insert_one_new_note<'a, E>(executor: E, note: &NewNote) -> SqlResult<i64>
async fn insert_one_new_note<'a, E>(executor: E, note: &NewNote) -> SqlResult<NoteId>
where
E: Executor<'a, Database = Sqlite>,
{
@ -288,7 +312,8 @@ where
"VALUES (?, ?, ?, ?, ?, ?);"
);
Ok(sqlx::query(insert_one_note_sql)
Ok(NoteId(
sqlx::query(insert_one_note_sql)
.bind(&note.uuid)
.bind(&note.content)
.bind(&note.notetype)
@ -297,7 +322,8 @@ where
.bind(&note.lastview_date)
.execute(executor)
.await?
.last_insert_rowid())
.last_insert_rowid(),
))
}
fn find_maximal_slug(slugs: &Vec<JustSlugs>) -> Option<u32> {
@ -343,7 +369,7 @@ where
}
}
async fn insert_one_new_page<'a, E>(executor: E, page: &NewPage) -> SqlResult<i64>
async fn insert_one_new_page<'a, E>(executor: E, page: &NewPage) -> SqlResult<NoteId>
where
E: Executor<'a, Database = Sqlite>,
{
@ -358,7 +384,8 @@ where
"VALUES (?, ?, ?, ?, ?, ?);"
);
Ok(sqlx::query(insert_one_page_sql)
Ok(NoteId(
sqlx::query(insert_one_page_sql)
.bind(&page.slug)
.bind(&page.title)
.bind(&page.note_id)
@ -367,17 +394,21 @@ where
.bind(&page.lastview_date)
.execute(executor)
.await?
.last_insert_rowid())
.last_insert_rowid(),
))
}
async fn bulk_select_ids_for_note_uuids<'a, E>(executor: E, ids: &Vec<&str>) -> SqlResult<Vec<(String, i64)>>
async fn bulk_select_ids_for_note_uuids<'a, E>(
executor: E,
ids: &Vec<&str>,
) -> SqlResult<Vec<(String, i64)>>
where
E: Executor<'a, Database = Sqlite>,
{
let bulk_select_ids_for_note_uuids_sql =
"SELECT uuid, id FROM notes WHERE uuid IN (".to_string() +
&["?",].repeat(ids.len()).join(",") +
&");".to_string();
let bulk_select_ids_for_note_uuids_sql = "SELECT uuid, id FROM notes WHERE uuid IN ("
.to_string()
+ &["?"].repeat(ids.len()).join(",")
+ &");".to_string();
let mut request = sqlx::query(&bulk_select_ids_for_note_uuids_sql);
for id in ids.iter() {
@ -387,14 +418,19 @@ where
.try_map(|row: SqliteRow| {
let l = row.try_get::<String, _>(0)?;
let r = row.try_get::<i64, _>(1)?;
Ok((l, r)) })
Ok((l, r))
})
.fetch_all(executor)
.await?
.into_iter()
.collect())
}
async fn get_note_note_relationship<'a, E>(executor: E, parent_id: i64, note_id: i64) -> SqlResult<NoteRelationship>
async fn get_note_note_relationship<'a, E>(
executor: E,
parent_id: ParentId,
note_id: NoteId,
) -> SqlResult<NoteRelationship>
where
E: Executor<'a, Database = Sqlite>,
{
@ -405,13 +441,17 @@ where
"LIMIT 1"
);
sqlx::query_as(get_note_note_relationship_sql)
.bind(&parent_id)
.bind(&note_id)
.bind(&*parent_id)
.bind(&*note_id)
.fetch_one(executor)
.await
}
async fn delete_note_note_relationship<'a, E>(executor: E, parent_id: i64, note_id: i64) -> SqlResult<()>
async fn delete_note_note_relationship<'a, E>(
executor: E,
parent_id: ParentId,
note_id: NoteId,
) -> SqlResult<()>
where
E: Executor<'a, Database = Sqlite>,
{
@ -421,8 +461,8 @@ where
);
let count = sqlx::query(delete_note_note_relationship_sql)
.bind(&parent_id)
.bind(&note_id)
.bind(&*parent_id)
.bind(&*note_id)
.execute(executor)
.await?
.rows_affected();
@ -433,7 +473,11 @@ where
}
}
async fn close_hole_for_deleted_note<'a, E>(executor: E, parent_id: i64, position: i64) -> SqlResult<()>
async fn close_hole_for_deleted_note<'a, E>(
executor: E,
parent_id: ParentId,
position: i64,
) -> SqlResult<()>
where
E: Executor<'a, Database = Sqlite>,
{
@ -445,7 +489,7 @@ where
sqlx::query(close_hole_for_deleted_note_sql)
.bind(&position)
.bind(&parent_id)
.bind(&*parent_id)
.execute(executor)
.await
.map(|_| ())
@ -460,11 +504,11 @@ fn create_unique_root_note() -> NewNote {
.unwrap()
}
fn create_new_page_for(title: &str, slug: &str, note_id: i64) -> NewPage {
fn create_new_page_for(title: &str, slug: &str, note_id: NoteId) -> NewPage {
NewPageBuilder::default()
.slug(slug.to_string())
.title(title.to_string())
.note_id(note_id)
.note_id(*note_id)
.build()
.unwrap()
}