Compare commits

..

No commits in common. "7639d1a6f26ce5bbb4586775240935791ff7ba7f" and "1c0f3abd6cedd3bc2d0620047d170571e50494dc" have entirely different histories.

2 changed files with 325 additions and 370 deletions

View File

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

View File

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