FEAT: Move note now works.
This commit is contained in:
parent
380d3f4a7c
commit
1c0f3abd6c
|
@ -38,25 +38,70 @@ mod tests {
|
||||||
#[tokio::test(threaded_scheduler)]
|
#[tokio::test(threaded_scheduler)]
|
||||||
async fn fetching_unfound_page_by_title_works() {
|
async fn fetching_unfound_page_by_title_works() {
|
||||||
let title = "Nonexistent Page";
|
let title = "Nonexistent Page";
|
||||||
let _now = chrono::Utc::now();
|
let now = chrono::Utc::now();
|
||||||
let storagepool = fresh_inmemory_database().await;
|
let storagepool = fresh_inmemory_database().await;
|
||||||
let newpageresult = storagepool.get_page_by_title(&title).await;
|
let newpageresult = storagepool.get_page_by_title(&title).await;
|
||||||
|
|
||||||
assert!(newpageresult.is_ok(), "{:?}", newpageresult);
|
assert!(newpageresult.is_ok(), "{:?}", newpageresult);
|
||||||
let (newpage, _newnotes) = newpageresult.unwrap();
|
let (newpage, newnotes) = newpageresult.unwrap();
|
||||||
|
|
||||||
assert_eq!(newpage.title, title, "{:?}", newpage.title);
|
assert_eq!(newpage.title, title, "{:?}", newpage.title);
|
||||||
assert_eq!(newpage.slug, "nonexistent-page");
|
assert_eq!(newpage.slug, "nonexistent-page");
|
||||||
|
|
||||||
|
assert_eq!(newnotes.len(), 1);
|
||||||
|
assert_eq!(newnotes[0].notetype, "root");
|
||||||
|
assert_eq!(newpage.note_id, newnotes[0].id);
|
||||||
|
|
||||||
|
assert!((newpage.creation_date - now).num_minutes() < 1);
|
||||||
|
assert!((newpage.updated_date - now).num_minutes() < 1);
|
||||||
|
assert!((newpage.lastview_date - now).num_minutes() < 1);
|
||||||
|
assert!(newpage.deleted_date.is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
// // TODO: This should be 1, not 0
|
fn make_new_note(content: &str) -> row_structs::NewNote {
|
||||||
// assert_eq!(newnotes.len(), 0);
|
row_structs::NewNoteBuilder::default()
|
||||||
// // assert_eq!(newnotes[0].notetype, "root");
|
.content(content.to_string())
|
||||||
// // assert_eq!(newpage.note_id, newnotes[0].id);
|
.build()
|
||||||
//
|
.unwrap()
|
||||||
// assert!((newpage.creation_date - now).num_minutes() < 1.0);
|
}
|
||||||
// assert!((newpage.updated_date - now).num_minutes() < 1.0);
|
|
||||||
// assert!((newpage.lastview_date - now).num_minutes() < 1.0);
|
#[tokio::test(threaded_scheduler)]
|
||||||
// assert!(newpage.deleted_date.is_none());
|
async fn can_nest_notes() {
|
||||||
// }
|
let title = "Nonexistent Page";
|
||||||
|
let storagepool = fresh_inmemory_database().await;
|
||||||
|
let newpageresult = storagepool.get_page_by_title(&title).await;
|
||||||
|
let (_newpage, newnotes) = newpageresult.unwrap();
|
||||||
|
|
||||||
|
let root = &newnotes[0];
|
||||||
|
|
||||||
|
let note1 = make_new_note("1");
|
||||||
|
let note1_uuid = storagepool.insert_nested_note(¬e1, &root.uuid, 0).await;
|
||||||
|
assert!(note1_uuid.is_ok(), "{:?}", note1_uuid);
|
||||||
|
let note1_uuid = note1_uuid.unwrap();
|
||||||
|
|
||||||
|
let note2 = make_new_note("2");
|
||||||
|
let note2_uuid = storagepool.insert_nested_note(¬e2, &root.uuid, 0).await;
|
||||||
|
assert!(note2_uuid.is_ok(), "{:?}", note2_uuid);
|
||||||
|
let note2_uuid = note2_uuid.unwrap();
|
||||||
|
|
||||||
|
let note3 = make_new_note("3");
|
||||||
|
let note3_uuid = storagepool.insert_nested_note(¬e3, ¬e1_uuid, 0).await;
|
||||||
|
assert!(note3_uuid.is_ok(), "{:?}", note3_uuid);
|
||||||
|
let note3_uuid = note3_uuid.unwrap();
|
||||||
|
|
||||||
|
let note4 = make_new_note("4");
|
||||||
|
let note4_uuid = storagepool.insert_nested_note(¬e4, ¬e2_uuid, 0).await;
|
||||||
|
assert!(note4_uuid.is_ok(), "{:?}", note4_uuid);
|
||||||
|
let note4_uuid = note4_uuid.unwrap();
|
||||||
|
|
||||||
|
let newpageresult = storagepool.get_page_by_title(&title).await;
|
||||||
|
let (newpage, newnotes) = newpageresult.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(newpage.title, title, "{:?}", newpage.title);
|
||||||
|
assert_eq!(newpage.slug, "nonexistent-page");
|
||||||
|
|
||||||
|
assert_eq!(newnotes.len(), 5);
|
||||||
|
assert_eq!(newnotes[0].notetype, "root");
|
||||||
|
assert_eq!(newpage.note_id, newnotes[0].id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -5,92 +5,101 @@ use sqlx::{self, FromRow};
|
||||||
|
|
||||||
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)]
|
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)]
|
||||||
pub struct RawPage {
|
pub struct RawPage {
|
||||||
pub id: i64,
|
pub id: i64,
|
||||||
pub slug: String,
|
pub slug: String,
|
||||||
pub title: String,
|
pub title: String,
|
||||||
pub note_id: i64,
|
pub note_id: i64,
|
||||||
pub creation_date: DateTime<Utc>,
|
pub creation_date: DateTime<Utc>,
|
||||||
pub updated_date: DateTime<Utc>,
|
pub updated_date: DateTime<Utc>,
|
||||||
pub lastview_date: DateTime<Utc>,
|
pub lastview_date: DateTime<Utc>,
|
||||||
pub deleted_date: Option<DateTime<Utc>>,
|
pub deleted_date: Option<DateTime<Utc>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)]
|
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)]
|
||||||
pub struct RawNote {
|
pub struct RawNote {
|
||||||
pub id: i64,
|
pub id: i64,
|
||||||
pub uuid: String,
|
pub uuid: String,
|
||||||
pub parent_id: i64,
|
pub parent_id: i64,
|
||||||
pub parent_uuid: String,
|
pub parent_uuid: String,
|
||||||
pub content: String,
|
pub content: String,
|
||||||
pub position: i64,
|
pub position: i64,
|
||||||
pub notetype: String,
|
pub notetype: String,
|
||||||
pub creation_date: DateTime<Utc>,
|
pub creation_date: DateTime<Utc>,
|
||||||
pub updated_date: DateTime<Utc>,
|
pub updated_date: DateTime<Utc>,
|
||||||
pub lastview_date: DateTime<Utc>,
|
pub lastview_date: DateTime<Utc>,
|
||||||
pub deleted_date: Option<DateTime<Utc>>,
|
pub deleted_date: Option<DateTime<Utc>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Serialize, Deserialize, Debug, Builder)]
|
#[derive(Clone, Serialize, Deserialize, Debug, Builder)]
|
||||||
pub struct NewPage {
|
pub struct NewPage {
|
||||||
pub slug: String,
|
pub slug: String,
|
||||||
pub title: String,
|
pub title: String,
|
||||||
pub note_id: i64,
|
pub note_id: i64,
|
||||||
#[builder(default = r#"chrono::Utc::now()"#)]
|
#[builder(default = r#"chrono::Utc::now()"#)]
|
||||||
pub creation_date: DateTime<Utc>,
|
pub creation_date: DateTime<Utc>,
|
||||||
#[builder(default = r#"chrono::Utc::now()"#)]
|
#[builder(default = r#"chrono::Utc::now()"#)]
|
||||||
pub updated_date: DateTime<Utc>,
|
pub updated_date: DateTime<Utc>,
|
||||||
#[builder(default = r#"chrono::Utc::now()"#)]
|
#[builder(default = r#"chrono::Utc::now()"#)]
|
||||||
pub lastview_date: DateTime<Utc>,
|
pub lastview_date: DateTime<Utc>,
|
||||||
#[builder(default = r#"None"#)]
|
#[builder(default = r#"None"#)]
|
||||||
pub deleted_date: Option<DateTime<Utc>>,
|
pub deleted_date: Option<DateTime<Utc>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Serialize, Deserialize, Debug, Builder)]
|
#[derive(Clone, Serialize, Deserialize, Debug, Builder)]
|
||||||
pub struct NewNote {
|
pub struct NewNote {
|
||||||
pub uuid: String,
|
#[builder(default = r#""".to_string()"#)]
|
||||||
pub content: String,
|
pub uuid: String,
|
||||||
#[builder(default = r#""note".to_string()"#)]
|
pub content: String,
|
||||||
pub notetype: String,
|
#[builder(default = r#""note".to_string()"#)]
|
||||||
#[builder(default = r#"chrono::Utc::now()"#)]
|
pub notetype: String,
|
||||||
pub creation_date: DateTime<Utc>,
|
#[builder(default = r#"chrono::Utc::now()"#)]
|
||||||
#[builder(default = r#"chrono::Utc::now()"#)]
|
pub creation_date: DateTime<Utc>,
|
||||||
pub updated_date: DateTime<Utc>,
|
#[builder(default = r#"chrono::Utc::now()"#)]
|
||||||
#[builder(default = r#"chrono::Utc::now()"#)]
|
pub updated_date: DateTime<Utc>,
|
||||||
pub lastview_date: DateTime<Utc>,
|
#[builder(default = r#"chrono::Utc::now()"#)]
|
||||||
#[builder(default = r#"None"#)]
|
pub lastview_date: DateTime<Utc>,
|
||||||
pub deleted_date: Option<DateTime<Utc>>,
|
#[builder(default = r#"None"#)]
|
||||||
|
pub deleted_date: Option<DateTime<Utc>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)]
|
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)]
|
||||||
pub(crate) struct JustSlugs {
|
pub(crate) struct JustSlugs {
|
||||||
pub slug: String,
|
pub slug: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)]
|
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)]
|
||||||
pub(crate) struct JustTitles {
|
pub(crate) struct JustTitles {
|
||||||
title: String,
|
title: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)]
|
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)]
|
||||||
pub(crate) struct JustId {
|
pub(crate) struct JustId {
|
||||||
pub id: i64,
|
pub id: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)]
|
||||||
|
pub(crate) struct NoteRelationship {
|
||||||
|
pub parent_id: i64,
|
||||||
|
pub note_id: i64,
|
||||||
|
pub position: i64,
|
||||||
|
pub nature: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn can_build_new_note() {
|
fn can_build_new_note() {
|
||||||
let now = chrono::Utc::now();
|
let now = chrono::Utc::now();
|
||||||
let newnote = NewNoteBuilder::default()
|
let newnote = NewNoteBuilder::default()
|
||||||
.uuid("foo".to_string())
|
.uuid("foo".to_string())
|
||||||
.content("bar".to_string())
|
.content("bar".to_string())
|
||||||
.build()
|
.build()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!((newnote.creation_date - now).num_minutes() < 1);
|
assert!((newnote.creation_date - now).num_minutes() < 1);
|
||||||
assert!((newnote.updated_date - now).num_minutes() < 1);
|
assert!((newnote.updated_date - now).num_minutes() < 1);
|
||||||
assert!((newnote.lastview_date - now).num_minutes() < 1);
|
assert!((newnote.lastview_date - now).num_minutes() < 1);
|
||||||
assert!(newnote.deleted_date.is_none());
|
assert!(newnote.deleted_date.is_none());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,15 +1,17 @@
|
||||||
use crate::errors::NoteStoreError;
|
use crate::errors::NoteStoreError;
|
||||||
use crate::row_structs::{
|
use crate::row_structs::{
|
||||||
JustId, JustSlugs, NewNote, NewNoteBuilder, NewPage, NewPageBuilder, RawNote, RawPage,
|
JustId, JustSlugs, NewNote, NewNoteBuilder, NewPage,
|
||||||
|
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 slug::slugify;
|
use slug::slugify;
|
||||||
use sqlx;
|
use sqlx;
|
||||||
use sqlx::{
|
use sqlx::{
|
||||||
sqlite::{Sqlite, SqlitePool},
|
sqlite::{Sqlite, SqlitePool, SqliteRow},
|
||||||
Executor,
|
Done, Executor, Row
|
||||||
};
|
};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
@ -21,94 +23,149 @@ type NoteResult<T> = core::result::Result<T, NoteStoreError>;
|
||||||
type SqlResult<T> = sqlx::Result<T>;
|
type SqlResult<T> = sqlx::Result<T>;
|
||||||
|
|
||||||
impl NoteStore {
|
impl NoteStore {
|
||||||
pub async fn new(url: &str) -> NoteResult<Self> {
|
pub async fn new(url: &str) -> NoteResult<Self> {
|
||||||
let pool = SqlitePool::connect(url).await?;
|
let pool = SqlitePool::connect(url).await?;
|
||||||
Ok(NoteStore(Arc::new(pool)))
|
Ok(NoteStore(Arc::new(pool)))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Erase all the data in the database and restore it
|
// Erase all the data in the database and restore it
|
||||||
// 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
|
||||||
///
|
///
|
||||||
/// Supports the use case of the user navigating to a known place
|
/// Supports the use case of the user navigating to a known place
|
||||||
/// via a bookmark or other URL. Since the title isn't clear from
|
/// via a bookmark or other URL. Since the title isn't clear from
|
||||||
/// the slug, the slug is insufficient to generate a new page, so
|
/// the slug, the slug is insufficient to generate a new page, so
|
||||||
/// this use case says that in the event of a failure to find the
|
/// this use case says that in the event of a failure to find the
|
||||||
/// requested page, return a basic NotFound.
|
/// requested page, return a basic NotFound.
|
||||||
pub async fn get_page_by_slug(&self, slug: &str) -> NoteResult<(RawPage, Vec<RawNote>)> {
|
pub async fn get_page_by_slug(&self, slug: &str) -> NoteResult<(RawPage, Vec<RawNote>)> {
|
||||||
// let select_note_collection_for_root = include_str!("sql/select_note_collection_for_root.sql");
|
// let select_note_collection_for_root = include_str!("sql/select_note_collection_for_root.sql");
|
||||||
let mut tx = self.0.begin().await?;
|
let mut tx = self.0.begin().await?;
|
||||||
let page = select_page_by_slug(&mut tx, slug).await?;
|
let page = select_page_by_slug(&mut tx, slug).await?;
|
||||||
// let notes = sqlx::query_as(select_note_collection_for_root)
|
let note_id = page.note_id;
|
||||||
// .bind(page.note_id)
|
let notes = select_note_collection_from_root(&mut tx, note_id).await?;
|
||||||
// .fetch(&tx)
|
tx.commit().await?;
|
||||||
// .await?;
|
Ok((page, notes))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch page by title
|
||||||
|
///
|
||||||
|
/// Supports the use case of the user navigating to a page via
|
||||||
|
/// the page's formal title. Since the title is the key reference
|
||||||
|
/// of the system, if no page with that title is found, a page with
|
||||||
|
/// that title is generated automatically.
|
||||||
|
pub async fn get_page_by_title(&self, title: &str) -> NoteResult<(RawPage, Vec<RawNote>)> {
|
||||||
|
let mut tx = self.0.begin().await?;
|
||||||
|
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?)
|
||||||
|
}
|
||||||
|
Err(sqlx::Error::RowNotFound) => {
|
||||||
|
let page = {
|
||||||
|
let new_root_note = create_unique_root_note();
|
||||||
|
let new_root_note_id = insert_one_new_note(&mut tx, &new_root_note).await?;
|
||||||
|
let new_page_slug = generate_slug(&mut tx, title).await?;
|
||||||
|
let new_page = create_new_page_for(&title, &new_page_slug, new_root_note_id);
|
||||||
|
let _ = insert_one_new_page(&mut tx, &new_page).await?;
|
||||||
|
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?)
|
||||||
|
}
|
||||||
|
Err(e) => return Err(NoteStoreError::DBError(e)),
|
||||||
|
};
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok((page, notes))
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Make sure the position is sane.
|
||||||
|
/// Insert a note as the child of an existing note, at a set position.
|
||||||
|
pub async fn insert_nested_note(
|
||||||
|
&self,
|
||||||
|
note: &NewNote,
|
||||||
|
parent_note_uuid: &str,
|
||||||
|
position: i64,
|
||||||
|
) -> NoteResult<String> {
|
||||||
|
let mut new_note = note.clone();
|
||||||
|
new_note.uuid = friendly_id::create();
|
||||||
|
let mut tx = self.0.begin().await?;
|
||||||
|
let parent_id = select_note_id_for_uuid(&mut tx, parent_note_uuid).await?;
|
||||||
|
let new_note_id = insert_one_new_note(&mut tx, &new_note).await?;
|
||||||
|
let _ = make_room_for_new_note(&mut tx, parent_id, position).await?;
|
||||||
|
let _ = insert_note_note_relationship(&mut tx, parent_id, new_note_id, position).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
Ok(new_note.uuid)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: Make sure the new position is sane.
|
||||||
|
/// Move a note from one location to another.
|
||||||
|
pub async fn move_note(
|
||||||
|
&self,
|
||||||
|
note_uuid: &str,
|
||||||
|
old_parent_uuid: &str,
|
||||||
|
new_parent_uuid: &str,
|
||||||
|
new_position: i64,
|
||||||
|
) -> 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();
|
||||||
|
|
||||||
|
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_note_position = get_note_note_relationship(&mut tx, old_parent_id, note_id)
|
||||||
|
.await?
|
||||||
|
.position;
|
||||||
|
|
||||||
|
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?;
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
Ok((page, vec![]))
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch page by title
|
/// Embed or reference a note from a different location.
|
||||||
///
|
pub async fn reference_or_embed_note(
|
||||||
/// Supports the use case of the user navigating to a page via
|
|
||||||
/// the page's formal title. Since the title is the key reference
|
|
||||||
/// of the system, if no page with that title is found, a page with
|
|
||||||
/// that title is generated automatically.
|
|
||||||
pub async fn get_page_by_title(&self, title: &str) -> NoteResult<(RawPage, Vec<RawNote>)> {
|
|
||||||
let mut tx = self.0.begin().await?;
|
|
||||||
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?,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Err(sqlx::Error::RowNotFound) => {
|
|
||||||
let page = {
|
|
||||||
let new_root_note = create_unique_root_note();
|
|
||||||
let new_root_note_id = insert_one_new_note(&mut tx, &new_root_note).await?;
|
|
||||||
let new_page_slug = generate_slug(&mut tx, title).await?;
|
|
||||||
let new_page = create_new_page_for(&title, &new_page_slug, new_root_note_id);
|
|
||||||
let _ = insert_one_new_page(&mut tx, &new_page).await?;
|
|
||||||
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?,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
Err(e) => return Err(NoteStoreError::DBError(e)),
|
|
||||||
};
|
|
||||||
tx.commit().await?;
|
|
||||||
Ok((page, notes))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn insert_nested_note(
|
|
||||||
&self,
|
&self,
|
||||||
note: NewNote,
|
note_uuid: &str,
|
||||||
parent_note_uuid: &str,
|
new_parent_uuid: &str,
|
||||||
position: i32,
|
new_position: i64,
|
||||||
) -> NoteResult<String> {
|
new_nature: &str) -> NoteResult<()> {
|
||||||
let mut new_note = note.clone();
|
todo!()
|
||||||
new_note.uuid = friendly_id::create();
|
}
|
||||||
let mut tx = self.0.begin().await?;
|
|
||||||
let parent_id = select_note_id_for_uuid(&mut tx, parent_note_uuid).await?;
|
/// Delete a note
|
||||||
let new_note_id = insert_one_new_note(&mut tx, &new_note).await?;
|
pub async fn delete_note(
|
||||||
let _ = make_room_for_new_note(&mut tx, parent_id, position).await?;
|
&self,
|
||||||
let _ = insert_note_note_relationship(&mut tx, parent_id, new_note_id, position).await?;
|
note_uuid: &str,
|
||||||
tx.commit().await?;
|
note_parent_uuid: &str) -> NoteResult<()> {
|
||||||
Ok(new_note.uuid)
|
todo!()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update a note's content
|
||||||
|
pub async fn update_note_content(
|
||||||
|
&self,
|
||||||
|
note_uuid: &str,
|
||||||
|
content: &str) -> NoteResult<()> {
|
||||||
|
todo!()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ___ _ _
|
// ___ _ _
|
||||||
// | _ \_ _(_)_ ____ _| |_ ___
|
// | _ \_ _(_)_ ____ _| |_ ___
|
||||||
// | _/ '_| \ V / _` | _/ -_)
|
// | _/ '_| \ V / _` | _/ -_)
|
||||||
|
@ -122,152 +179,143 @@ impl NoteStore {
|
||||||
|
|
||||||
async fn reset_database<'a, E>(executor: E) -> SqlResult<()>
|
async fn reset_database<'a, E>(executor: E) -> SqlResult<()>
|
||||||
where
|
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>
|
||||||
where
|
where
|
||||||
E: Executor<'a, Database = Sqlite>,
|
E: Executor<'a, Database = Sqlite>,
|
||||||
{
|
{
|
||||||
let select_one_page_by_slug_sql = concat!(
|
let select_one_page_by_slug_sql = concat!(
|
||||||
"SELECT id, title, slug, note_id, creation_date, updated_date, ",
|
"SELECT id, title, slug, note_id, creation_date, updated_date, ",
|
||||||
"lastview_date, deleted_date FROM pages WHERE slug=?;"
|
"lastview_date, deleted_date FROM pages WHERE slug=?;"
|
||||||
);
|
);
|
||||||
Ok(sqlx::query_as(&select_one_page_by_slug_sql)
|
Ok(sqlx::query_as(&select_one_page_by_slug_sql)
|
||||||
.bind(&slug)
|
.bind(&slug)
|
||||||
.fetch_one(executor)
|
.fetch_one(executor)
|
||||||
.await?)
|
.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn select_page_by_title<'a, E>(executor: E, title: &str) -> SqlResult<RawPage>
|
async fn select_page_by_title<'a, E>(executor: E, title: &str) -> SqlResult<RawPage>
|
||||||
where
|
where
|
||||||
E: Executor<'a, Database = Sqlite>,
|
E: Executor<'a, Database = Sqlite>,
|
||||||
{
|
{
|
||||||
let select_one_page_by_title_sql = concat!(
|
let select_one_page_by_title_sql = concat!(
|
||||||
"SELECT id, title, slug, note_id, creation_date, updated_date, ",
|
"SELECT id, title, slug, note_id, creation_date, updated_date, ",
|
||||||
"lastview_date, deleted_date FROM pages WHERE title=?;"
|
"lastview_date, deleted_date FROM pages WHERE title=?;"
|
||||||
);
|
);
|
||||||
Ok(sqlx::query_as(&select_one_page_by_title_sql)
|
Ok(sqlx::query_as(&select_one_page_by_title_sql)
|
||||||
.bind(&title)
|
.bind(&title)
|
||||||
.fetch_one(executor)
|
.fetch_one(executor)
|
||||||
.await?)
|
.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<i64>
|
||||||
where
|
where
|
||||||
E: Executor<'a, Database = Sqlite>,
|
E: Executor<'a, Database = Sqlite>,
|
||||||
{
|
{
|
||||||
let select_note_id_for_uuid_sql = "SELECT id FROM notes WHERE uuid = ?";
|
let select_note_id_for_uuid_sql = "SELECT id FROM notes WHERE uuid = ?";
|
||||||
let id: JustId = sqlx::query_as(&select_note_id_for_uuid_sql)
|
let id: JustId = sqlx::query_as(&select_note_id_for_uuid_sql)
|
||||||
.bind(&uuid)
|
.bind(&uuid)
|
||||||
.fetch_one(executor)
|
.fetch_one(executor)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(id.id)
|
Ok(id.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn make_room_for_new_note<'a, E>(executor: E, parent_id: i64, position: i32) -> SqlResult<()>
|
async fn make_room_for_new_note<'a, E>(executor: E, parent_id: i64, position: i64) -> SqlResult<()>
|
||||||
where
|
where
|
||||||
E: Executor<'a, Database = Sqlite>,
|
E: Executor<'a, Database = Sqlite>,
|
||||||
{
|
{
|
||||||
let make_room_for_new_note_sql = concat!(
|
let make_room_for_new_note_sql = concat!(
|
||||||
"UPDATE note_relationships ",
|
"UPDATE note_relationships ",
|
||||||
"SET position = position + 1 ",
|
"SET position = position + 1 ",
|
||||||
"WHERE position >= ? and parent_id = ?;"
|
"WHERE position >= ? and parent_id = ?;"
|
||||||
);
|
);
|
||||||
|
|
||||||
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: i64,
|
|
||||||
note_id: i64,
|
|
||||||
position: i32,
|
|
||||||
) -> SqlResult<()>
|
|
||||||
where
|
where
|
||||||
E: Executor<'a, Database = Sqlite>,
|
E: Executor<'a, Database = Sqlite>,
|
||||||
{
|
{
|
||||||
let insert_note_note_relationship_sql = concat!(
|
let insert_note_note_relationship_sql = concat!(
|
||||||
"INSERT INTO note_relationships (parent_id, note_id, position, nature) ",
|
"INSERT INTO note_relationships (parent_id, note_id, position, nature) ",
|
||||||
"values (?, ?, ?, ?)"
|
"values (?, ?, ?, ?)"
|
||||||
);
|
);
|
||||||
|
|
||||||
sqlx::query(insert_note_note_relationship_sql)
|
sqlx::query(insert_note_note_relationship_sql)
|
||||||
.bind(&parent_id)
|
.bind(&parent_id)
|
||||||
.bind(¬e_id)
|
.bind(¬e_id)
|
||||||
.bind(&position)
|
.bind(&position)
|
||||||
.bind("note")
|
.bind("note")
|
||||||
.execute(executor)
|
.execute(executor)
|
||||||
.await
|
.await
|
||||||
.map(|_| ())
|
.map(|_| ())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn select_note_collection_from_root<'a, E>(executor: E, root: i64) -> SqlResult<Vec<RawNote>>
|
async fn select_note_collection_from_root<'a, E>(executor: E, root: i64) -> SqlResult<Vec<RawNote>>
|
||||||
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<i64>
|
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>,
|
||||||
{
|
{
|
||||||
let insert_one_note_sql = concat!(
|
let insert_one_note_sql = concat!(
|
||||||
"INSERT INTO notes ( ",
|
"INSERT INTO notes ( ",
|
||||||
" uuid, ",
|
" uuid, ",
|
||||||
" content, ",
|
" content, ",
|
||||||
" notetype, ",
|
" notetype, ",
|
||||||
" creation_date, ",
|
" creation_date, ",
|
||||||
" updated_date, ",
|
" updated_date, ",
|
||||||
" lastview_date) ",
|
" lastview_date) ",
|
||||||
"VALUES (?, ?, ?, ?, ?, ?);"
|
"VALUES (?, ?, ?, ?, ?, ?);"
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok(sqlx::query(insert_one_note_sql)
|
Ok(sqlx::query(insert_one_note_sql)
|
||||||
.bind(¬e.uuid)
|
.bind(¬e.uuid)
|
||||||
.bind(¬e.content)
|
.bind(¬e.content)
|
||||||
.bind(¬e.notetype)
|
.bind(¬e.notetype)
|
||||||
.bind(¬e.creation_date)
|
.bind(¬e.creation_date)
|
||||||
.bind(¬e.updated_date)
|
.bind(¬e.updated_date)
|
||||||
.bind(¬e.lastview_date)
|
.bind(¬e.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> {
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
static ref RE_CAP_NUM: Regex = Regex::new(r"-(\d+)$").unwrap();
|
static ref RE_CAP_NUM: Regex = Regex::new(r"-(\d+)$").unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
if slugs.len() == 0 {
|
if slugs.len() == 0 {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut slug_counters: Vec<u32> = slugs
|
let mut slug_counters: Vec<u32> = slugs
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|slug| RE_CAP_NUM.captures(&slug.slug))
|
.filter_map(|slug| RE_CAP_NUM.captures(&slug.slug))
|
||||||
.map(|cap| cap.get(1).unwrap().as_str().parse::<u32>().unwrap())
|
.map(|cap| cap.get(1).unwrap().as_str().parse::<u32>().unwrap())
|
||||||
.collect();
|
.collect();
|
||||||
slug_counters.sort_unstable();
|
slug_counters.sort_unstable();
|
||||||
slug_counters.pop()
|
slug_counters.pop()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Given an initial string and an existing collection of slugs,
|
// Given an initial string and an existing collection of slugs,
|
||||||
|
@ -275,67 +323,148 @@ fn find_maximal_slug(slugs: &Vec<JustSlugs>) -> Option<u32> {
|
||||||
// collection.
|
// collection.
|
||||||
async fn generate_slug<'a, E>(executor: E, title: &str) -> SqlResult<String>
|
async fn generate_slug<'a, E>(executor: E, title: &str) -> SqlResult<String>
|
||||||
where
|
where
|
||||||
E: Executor<'a, Database = Sqlite>,
|
E: Executor<'a, Database = Sqlite>,
|
||||||
{
|
{
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
static ref RE_STRIP_NUM: Regex = Regex::new(r"-\d+$").unwrap();
|
static ref RE_STRIP_NUM: Regex = Regex::new(r"-\d+$").unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
let initial_slug = slugify(title);
|
let initial_slug = slugify(title);
|
||||||
let sample_slug = RE_STRIP_NUM.replace_all(&initial_slug, "");
|
let sample_slug = RE_STRIP_NUM.replace_all(&initial_slug, "");
|
||||||
let slug_finder_sql = "SELECT slug FROM pages WHERE slug LIKE '?%';";
|
let slug_finder_sql = "SELECT slug FROM pages WHERE slug LIKE '?%';";
|
||||||
let similar_slugs: Vec<JustSlugs> = sqlx::query_as(&slug_finder_sql)
|
let similar_slugs: Vec<JustSlugs> = sqlx::query_as(&slug_finder_sql)
|
||||||
.bind(&*sample_slug)
|
.bind(&*sample_slug)
|
||||||
.fetch_all(executor)
|
.fetch_all(executor)
|
||||||
.await?;
|
.await?;
|
||||||
let maximal_slug = find_maximal_slug(&similar_slugs);
|
let maximal_slug = find_maximal_slug(&similar_slugs);
|
||||||
match maximal_slug {
|
match maximal_slug {
|
||||||
None => Ok(initial_slug),
|
None => Ok(initial_slug),
|
||||||
Some(max_slug) => Ok(format!("{}-{}", initial_slug, max_slug + 1)),
|
Some(max_slug) => Ok(format!("{}-{}", initial_slug, max_slug + 1)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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<i64>
|
||||||
where
|
where
|
||||||
E: Executor<'a, Database = Sqlite>,
|
E: Executor<'a, Database = Sqlite>,
|
||||||
{
|
{
|
||||||
let insert_one_page_sql = concat!(
|
let insert_one_page_sql = concat!(
|
||||||
"INSERT INTO pages ( ",
|
"INSERT INTO pages ( ",
|
||||||
" slug, ",
|
" slug, ",
|
||||||
" title, ",
|
" title, ",
|
||||||
" note_id, ",
|
" note_id, ",
|
||||||
" creation_date, ",
|
" creation_date, ",
|
||||||
" updated_date, ",
|
" updated_date, ",
|
||||||
" lastview_date) ",
|
" lastview_date) ",
|
||||||
"VALUES (?, ?, ?, ?, ?, ?);"
|
"VALUES (?, ?, ?, ?, ?, ?);"
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok(sqlx::query(insert_one_page_sql)
|
Ok(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)
|
||||||
.bind(&page.creation_date)
|
.bind(&page.creation_date)
|
||||||
.bind(&page.updated_date)
|
.bind(&page.updated_date)
|
||||||
.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>(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 mut request = sqlx::query(&bulk_select_ids_for_note_uuids_sql);
|
||||||
|
for id in ids.iter() {
|
||||||
|
request = request.bind(id);
|
||||||
|
}
|
||||||
|
Ok(request
|
||||||
|
.try_map(|row: SqliteRow| {
|
||||||
|
let l = row.try_get::<String, _>(0)?;
|
||||||
|
let r = row.try_get::<i64, _>(1)?;
|
||||||
|
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>
|
||||||
|
where
|
||||||
|
E: Executor<'a, Database = Sqlite>,
|
||||||
|
{
|
||||||
|
let get_note_note_relationship_sql = concat!(
|
||||||
|
"SELECT parent_id, note_id, position, nature ",
|
||||||
|
"FROM note_relationships ",
|
||||||
|
"WHERE parent_id = ? and note_id = ? ",
|
||||||
|
"LIMIT 1"
|
||||||
|
);
|
||||||
|
sqlx::query_as(get_note_note_relationship_sql)
|
||||||
|
.bind(&parent_id)
|
||||||
|
.bind(¬e_id)
|
||||||
|
.fetch_one(executor)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete_note_note_relationship<'a, E>(executor: E, parent_id: i64, note_id: i64) -> SqlResult<()>
|
||||||
|
where
|
||||||
|
E: Executor<'a, Database = Sqlite>,
|
||||||
|
{
|
||||||
|
let delete_note_note_relationship_sql = concat!(
|
||||||
|
"DELETE FROM note_relationships ",
|
||||||
|
"WHERE parent_id = ? and note_id = ? "
|
||||||
|
);
|
||||||
|
|
||||||
|
let count = sqlx::query(delete_note_note_relationship_sql)
|
||||||
|
.bind(&parent_id)
|
||||||
|
.bind(¬e_id)
|
||||||
|
.execute(executor)
|
||||||
|
.await?
|
||||||
|
.rows_affected();
|
||||||
|
|
||||||
|
match count {
|
||||||
|
1 => Ok(()),
|
||||||
|
_ => Err(sqlx::Error::RowNotFound),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn close_hole_for_deleted_note<'a, E>(executor: E, parent_id: i64, position: i64) -> SqlResult<()>
|
||||||
|
where
|
||||||
|
E: Executor<'a, Database = Sqlite>,
|
||||||
|
{
|
||||||
|
let close_hole_for_deleted_note_sql = concat!(
|
||||||
|
"UPDATE note_relationships ",
|
||||||
|
"SET position = position - 1 ",
|
||||||
|
"WHERE position > ? and parent_id = ?;"
|
||||||
|
);
|
||||||
|
|
||||||
|
sqlx::query(close_hole_for_deleted_note_sql)
|
||||||
|
.bind(&position)
|
||||||
|
.bind(&parent_id)
|
||||||
|
.execute(executor)
|
||||||
|
.await
|
||||||
|
.map(|_| ())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_unique_root_note() -> NewNote {
|
fn create_unique_root_note() -> NewNote {
|
||||||
NewNoteBuilder::default()
|
NewNoteBuilder::default()
|
||||||
.uuid(friendly_id::create())
|
.uuid(friendly_id::create())
|
||||||
.content("".to_string())
|
.content("".to_string())
|
||||||
.notetype("root".to_string())
|
.notetype("root".to_string())
|
||||||
.build()
|
.build()
|
||||||
.unwrap()
|
.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: 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()
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue