Compare commits

...

8 Commits

Author SHA1 Message Date
Elf M. Sternberg bad0de9bc0 Mostly documentation changes, but I do want to emphasize that by the
time we hit this layer, the distinction between an API note and a
REST note have been made.
2020-11-06 14:43:05 -08:00
Elf M. Sternberg 2eeb96a26a Enabling the tree-handling API. 2020-11-05 09:34:21 -08:00
Elf M. Sternberg 83d5858a45 Refinements to the tree structure. 2020-11-05 08:30:02 -08:00
Elf M. Sternberg 4776541df4 A little store-level constraining never hurt nobody. 2020-11-05 05:45:57 -08:00
Elf M. Sternberg 9337b98ad3 REFACTOR Again! note->note and note->kasten are now separate tables
This was getting semantically confusing, so I decided to short
circuit the whole mess by separating the two.  The results are
promising.  It does mean that deleting a note means traversing
two tables to clean out all the cruft, which is *sigh*, but it
also means that the tree is stored in one table and the graph in
another, giving us a much better separation of concerns down at
the SQL layer.
2020-11-04 17:53:25 -08:00
Elf M. Sternberg 1bbe8c1ee8 Completely revamped the internal structures.
This removes the page/note dichotomy, since it wasn't working
as well as I'd hoped.  The discipline required now is higher
where the data store layer is concerned, but the actual structures
are smaller and more efficient.
2020-11-04 12:54:17 -08:00
Elf M. Sternberg 0a2b96cea6 This is wrong, but it's something. 2020-11-02 21:56:45 -08:00
Elf M. Sternberg 77ca6d0304 A reset for the single table case. 2020-11-02 18:32:01 -08:00
23 changed files with 1133 additions and 857 deletions

6
.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
/target
Cargo.lock
*#
.#*
*~

2
Cargo.toml Normal file
View File

@ -0,0 +1,2 @@
[workspace]
members = ["server/*"]

11
server/Pipfile Normal file
View File

@ -0,0 +1,11 @@
[[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"
[packages]
[dev-packages]
[requires]
python_version = "2.7"

View File

@ -0,0 +1,4 @@
[ ] Add RelationshipKind to Notes passed out
[ ] Add KastenKind to Backreferences passed out
[ ] Provide the array of notes references (the 'cycle' manager) to make
mapping from Vec->Tree easier.

View File

@ -0,0 +1,10 @@
The thing of it is, we have two kinds of notes:
1. This layer of the system will handle broken/missing position issues.
2. The client layer of the system will ensure that a parent is provided.
3. The notes retrieved via the CTE have information and parenting and
location.
4. Notes put *into* the system have parent and location provided
separately.
5. Clients do not specify the ids of notes put into the system.
6. Retrieval by slug must test for is-a-box.

View File

@ -1,3 +1,4 @@
use sqlx;
use thiserror::Error; use thiserror::Error;
/// All the ways looking up objects can fail /// All the ways looking up objects can fail
@ -8,6 +9,9 @@ pub enum NoteStoreError {
#[error("Invalid Note Structure")] #[error("Invalid Note Structure")]
InvalidNoteStructure(String), InvalidNoteStructure(String),
/// The requested kasten or note was not found. As much as
/// possible, this should be preferred to a
/// sqlx::Error::RowNotFound.
#[error("Not found")] #[error("Not found")]
NotFound, NotFound,

View File

@ -6,7 +6,8 @@ mod structs;
pub use crate::errors::NoteStoreError; pub use crate::errors::NoteStoreError;
pub use crate::store::NoteStore; pub use crate::store::NoteStore;
pub use crate::structs::{RawPage, RawNote, NewPage, NewNote}; pub use crate::structs::{Note, NoteKind, NoteRelationship, KastenRelationship};
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
@ -23,14 +24,14 @@ mod tests {
storagepool storagepool
} }
// Request for the page by slug. // Request for the page by slug. If the page exists, return it.
// If the page exists, return it. If the page doesn't, return NotFound // If the page doesn't, return NotFound
//
#[tokio::test(threaded_scheduler)] #[tokio::test(threaded_scheduler)]
async fn fetching_unfound_page_by_slug_works() { async fn fetching_unfound_page_by_slug_works() {
let storagepool = fresh_inmemory_database().await; let storagepool = fresh_inmemory_database().await;
let unfoundpage = storagepool.get_page_by_slug("nonexistent-page").await; let foundkasten = storagepool.get_kasten_by_slug("nonexistent-kasten").await;
assert!(unfoundpage.is_err()); assert!(foundkasten.is_err());
} }
// Request for the page by title. If the page exists, return it. // Request for the page by title. If the page exists, return it.
@ -42,18 +43,17 @@ mod tests {
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_kasten_by_title(&title).await;
assert!(newpageresult.is_ok(), "{:?}", newpageresult); assert!(newpageresult.is_ok(), "{:?}", newpageresult);
let (newpage, newnotes) = newpageresult.unwrap(); let (newpages, _) = newpageresult.unwrap();
assert_eq!(newpage.title, title, "{:?}", newpage.title); assert_eq!(newpages.len(), 1);
assert_eq!(newpage.slug, "nonexistent-page"); let newpage = newpages.iter().next().unwrap();
assert_eq!(newnotes.len(), 1);
assert_eq!(newnotes[0].notetype, "root");
assert_eq!(newpage.note_id, newnotes[0].id);
assert_eq!(newpage.content, title, "{:?}", newpage.content);
assert_eq!(newpage.id, "nonexistent-page");
assert_eq!(newpage.kind, NoteKind::Kasten);
assert!((newpage.creation_date - now).num_minutes() < 1); assert!((newpage.creation_date - now).num_minutes() < 1);
assert!((newpage.updated_date - now).num_minutes() < 1); assert!((newpage.updated_date - now).num_minutes() < 1);
assert!((newpage.lastview_date - now).num_minutes() < 1); assert!((newpage.lastview_date - now).num_minutes() < 1);
@ -71,39 +71,49 @@ mod tests {
async fn can_nest_notes() { async fn can_nest_notes() {
let title = "Nonexistent Page"; let title = "Nonexistent Page";
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_kasten_by_title(&title).await;
let (_newpage, newnotes) = newpageresult.unwrap();
let root = &newnotes[0]; assert!(newpageresult.is_ok(), "{:?}", newpageresult);
let (newpages, _) = newpageresult.unwrap();
assert_eq!(newpages.len(), 1);
let root = &newpages[0];
// root <- 1 <- 3
// <- 2 <- 4
let note1 = make_new_note("1"); let note1 = make_new_note("1");
let note1_uuid = storagepool.insert_nested_note(&note1, &root.uuid, 0).await; let note1_id = storagepool.add_note(&note1, &root.id, Some(0)).await;
assert!(note1_uuid.is_ok(), "{:?}", note1_uuid); assert!(note1_id.is_ok(), "{:?}", note1_id);
let note1_uuid = note1_uuid.unwrap(); let note1_id = note1_id.unwrap();
let note2 = make_new_note("2"); let note2 = make_new_note("2");
let note2_uuid = storagepool.insert_nested_note(&note2, &root.uuid, 0).await; let note2_id = storagepool.add_note(&note2, &root.id, Some(0)).await;
assert!(note2_uuid.is_ok(), "{:?}", note2_uuid); assert!(note2_id.is_ok(), "{:?}", note2_id);
let note2_uuid = note2_uuid.unwrap(); let note2_id = note2_id.unwrap();
let note3 = make_new_note("3"); let note3 = make_new_note("3");
let note3_uuid = storagepool.insert_nested_note(&note3, &note1_uuid, 0).await; let note3_id = storagepool.add_note(&note3, &note1_id, Some(0)).await;
assert!(note3_uuid.is_ok(), "{:?}", note3_uuid); assert!(note3_id.is_ok(), "{:?}", note3_id);
let _note3_uuid = note3_uuid.unwrap(); let _note3_id = note3_id.unwrap();
let note4 = make_new_note("4"); let note4 = make_new_note("4");
let note4_uuid = storagepool.insert_nested_note(&note4, &note2_uuid, 0).await; let note4_id = storagepool.add_note(&note4, &note2_id, Some(0)).await;
assert!(note4_uuid.is_ok(), "{:?}", note4_uuid); assert!(note4_id.is_ok(), "{:?}", note4_id);
let _note4_uuid = note4_uuid.unwrap(); let _note4_id = note4_id.unwrap();
let newpageresult = storagepool.get_page_by_title(&title).await; let newpageresult = storagepool.get_kasten_by_title(&title).await;
let (newpage, newnotes) = newpageresult.unwrap(); assert!(newpageresult.is_ok(), "{:?}", newpageresult);
let (newpages, _) = newpageresult.unwrap();
assert_eq!(newpage.title, title, "{:?}", newpage.title); assert_eq!(newpages.len(), 5);
assert_eq!(newpage.slug, "nonexistent-page"); let newroot = newpages.iter().next().unwrap();
assert_eq!(newnotes.len(), 5); assert_eq!(newroot.content, title, "{:?}", newroot.content);
assert_eq!(newnotes[0].notetype, "root"); assert_eq!(newroot.id, "nonexistent-page");
assert_eq!(newpage.note_id, newnotes[0].id);
assert_eq!(newpages[1].parent_id, Some(newroot.id.clone()));
assert_eq!(newpages[2].parent_id, Some(newpages[1].id.clone()));
} }
} }

View File

@ -1,53 +1,58 @@
DROP TABLE IF EXISTS notes; DROP TABLE IF EXISTS notes;
DROP TABLE IF EXISTS note_relationships; DROP TABLE IF EXISTS note_relationships;
DROP TABLE IF EXISTS pages; DROP TABLE IF EXISTS note_kasten_relationships;
DROP TABLE IF EXISTS page_relationships;
DROP TABLE IF EXISTS favorites; DROP TABLE IF EXISTS favorites;
CREATE TABLE notes ( CREATE TABLE notes (
id INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL PRIMARY KEY,
uuid TEXT NOT NULL UNIQUE, content TEXT NOT NULL,
content TEXT NULL, kind TEXT NOT NULL,
notetype TEXT,
creation_date DATETIME NOT NULL, creation_date DATETIME NOT NULL,
updated_date DATETIME NOT NULL, updated_date DATETIME NOT NULL,
lastview_date DATETIME NOT NULL, lastview_date DATETIME NOT NULL,
deleted_date DATETIME NULL deleted_date DATETIME NULL
); );
CREATE INDEX notes_uuids ON notes (uuid); CREATE INDEX note_ids ON notes (id);
CREATE TABLE pages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title text NOT NULL UNIQUE,
slug text NOT NULL UNIQUE,
note_id INTEGER,
creation_date DATETIME NOT NULL,
updated_date DATETIME NOT NULL,
lastview_date DATETIME NOT NULL,
deleted_date DATETIME NULL,
FOREIGN KEY (note_id) REFERENCES notes (id) ON DELETE NO ACTION ON UPDATE NO ACTION
);
CREATE INDEX pages_slugs ON pages (slug);
CREATE TABLE favorites ( CREATE TABLE favorites (
id INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE,
position INTEGER NOT NULL location INTEGER NOT NULL,
FOREIGN KEY (id) REFERENCES notes (id) ON DELETE CASCADE
); );
-- This table represents the forest of data relating a kasten to its
-- collections of notes. The root is itself "a note," but the content
-- of that note will always be just the title of the kasten.
--
CREATE TABLE note_relationships ( CREATE TABLE note_relationships (
note_id INTEGER NOT NULL, note_id TEXT NOT NULL,
parent_id INTEGER NOT NULL, parent_id TEXT NOT NULL,
position INTEGER NOT NULL, location INTEGER NOT NULL,
nature TEXT NOT NULL, kind TEXT NOT NULL,
FOREIGN KEY (note_id) REFERENCES notes (id) ON DELETE NO ACTION ON UPDATE NO ACTION, -- If either note disappears, we want all the edges to disappear as well.
FOREIGN KEY (parent_id) REFERENCES notes (id) ON DELETE NO ACTION ON UPDATE NO ACTION FOREIGN KEY (note_id) REFERENCES notes (id) ON DELETE CASCADE,
FOREIGN KEY (parent_id) REFERENCES notes (id) ON DELETE CASCADE,
UNIQUE (note_id, parent_id),
CHECK (note_id <> parent_id)
); );
CREATE TABLE page_relationships ( -- This table represents the graph of data relating notes to kastens.
note_id INTEGER NOT NULL, --
page_id INTEGER NOT NULL, CREATE TABLE note_kasten_relationships (
FOREIGN KEY (note_id) references notes (id) ON DELETE NO ACTION ON UPDATE NO ACTION, note_id TEXT NOT NULL,
FOREIGN KEY (page_id) references pages (id) ON DELETE NO ACTION ON UPDATE NO ACTION kasten_id TEXT NOT NULL,
kind TEXT NOT NULL,
-- If either note disappears, we want all the edges to disappear as well.
FOREIGN KEY (note_id) REFERENCES notes (id) ON DELETE CASCADE,
FOREIGN KEY (kasten_id) REFERENCES notes (id) ON DELETE CASCADE,
UNIQUE (note_id, kasten_id),
CHECK (note_id <> kasten_id)
); );
-- A fabulous constraint. This index prevents us from saying that
-- if a note points to a kasten, the kasten may not point to a
-- note. Now, it's absolutely required that a kasten_id point to
-- a KastenType note; the content should be a title only.
CREATE UNIQUE INDEX note_kasten_unique_idx
ON note_kasten_relationships (MIN(note_id, kasten_id), MAX(note_id, kasten_id));

View File

@ -1,8 +0,0 @@
INSERT INTO notes (
uuid,
content,
notetype,
creation_date,
updated_date,
lastview_date)
VALUES (?, ?, ?, ?, ?, ?);

View File

@ -1,8 +0,0 @@
INSERT INTO pages (
slug,
title,
note_id,
creation_date,
updated_date,
lastview_date)
VALUES (?, ?, ?, ?, ?, ?);

View File

@ -1,91 +0,0 @@
-- This is undoubtedly one of the more complex bits of code I've
-- written recently, and I do wish there had been macros because
-- there's a lot of hand-written, copy-pasted code here around the
-- basic content of a note; it would have been nice to be able to DRY
-- that out.
-- This expression creates a table, 'notetree', that contains all of
-- the notes nested under a page. Each entry in the table includes
-- the note's parent's internal and external ids so that applications
-- can build an actual tree out of a vec of these things.
-- TODO: Extensive testing to validate that the nodes are delivered
-- *in nesting order* to the client.
SELECT
id,
uuid,
parent_id,
parent_uuid,
content,
position,
notetype,
creation_date,
updated_date,
lastview_date,
deleted_date
FROM (
WITH RECURSIVE notetree (
id,
uuid,
parent_id,
parent_uuid,
content,
position,
notetype,
creation_date,
updated_date,
lastview_date,
deleted_date,
cycle
)
AS (
SELECT
notes.id,
notes.uuid,
notes.id AS parent_id,
notes.uuid AS parent_uuid,
notes.content,
0, -- Root notes are always in position 0
notes.notetype,
notes.creation_date,
notes.updated_date,
notes.lastview_date,
notes.deleted_date,
','||notes.id||',' -- Cycle monitor
FROM notes
WHERE notes.id = ? AND notes.notetype = "root"
-- RECURSIVE expression
UNION SELECT
notes.id,
notes.uuid,
notetree.id AS parent_id,
notetree.uuid AS parent_uuid,
notes.content,
note_relationships.position,
notes.notetype,
notes.creation_date,
notes.updated_date,
notes.lastview_date,
notes.deleted_date,
notetree.cycle||notes.id||','
FROM notes
INNER JOIN note_relationships
ON notes.id = note_relationships.note_id
-- For a given ID in the level of notetree in *this* recursion,
-- we want each note's branches one level down.
INNER JOIN notetree
ON note_relationships.parent_id = notetree.id
-- And we want to make sure there are no cycles. There shouldn't
-- be; we're supposed to prevent those. But you never know.
WHERE notetree.cycle NOT LIKE '%,'||notes.id||',%'
ORDER BY note_relationships.position
)
SELECT * from notetree);

View File

@ -1,10 +1,9 @@
SELECT SELECT
id, id,
uuid,
parent_id, parent_id,
parent_uuid,
content, content,
notetype, location,
kind,
creation_date, creation_date,
updated_date, updated_date,
lastview_date, lastview_date,
@ -14,11 +13,10 @@ FROM (
WITH RECURSIVE parents ( WITH RECURSIVE parents (
id, id,
uuid,
parent_id, parent_id,
parent_uuid,
content, content,
notetype, location,
kind,
creation_date, creation_date,
updated_date, updated_date,
lastview_date, lastview_date,
@ -30,11 +28,10 @@ FROM (
SELECT SELECT
notes.id, notes.id,
notes.uuid,
note_parents.id, note_parents.id,
note_parents.uuid,
notes.content, notes.content,
notes.notetype, note_relationships.location,
notes.kind,
notes.creation_date, notes.creation_date,
notes.updated_date, notes.updated_date,
notes.lastview_date, notes.lastview_date,
@ -43,18 +40,21 @@ FROM (
FROM notes FROM notes
INNER JOIN note_relationships INNER JOIN note_relationships
ON notes.id = note_relationships.note_id ON notes.id = note_relationships.note_id
AND notes.notetype = 'note' AND notes.kind = 'note'
INNER JOIN notes as note_parents INNER JOIN notes as note_parents
ON note_parents.id = note_relationships.parent_id ON note_parents.id = note_relationships.parent_id
WHERE notes.id = ? -- IMPORTANT: THIS IS THE PARAMETER WHERE notes.id
IN (SELECT note_id
FROM note_kasten_relationships
WHERE kasten_id = ?) -- IMPORTANT: THIS IS THE PARAMETER
UNION UNION
SELECT DISTINCT SELECT DISTINCT
notes.id, notes.id,
notes.uuid,
next_parent.id, next_parent.id,
next_parent.uuid,
notes.content, notes.content,
note_relationships.location,
notes.kind,
notes.creation_date, notes.creation_date,
notes.updated_date, notes.updated_date,
notes.lastview_date, notes.lastview_date,

View File

@ -0,0 +1,98 @@
-- This is undoubtedly one of the more complex bits of code I've
-- written recently, and I do wish there had been macros because
-- there's a lot of hand-written, copy-pasted code here around the
-- basic content of a note; it would have been nice to be able to DRY
-- that out.
-- This expression creates a table, 'notetree', that contains all of
-- the notes nested under a page. Each entry in the table includes
-- the note's parent's internal and external ids so that applications
-- can build an actual tree out of a vec of these things.
-- TODO: Extensive testing to validate that the nodes are delivered
-- *in nesting order* to the client.
-- Search in here for the term QUERYPARAMETER. That string will be
-- substituted with the correct parameter (id or title) depending on
-- the use case, by the level 1 client (the private parts of
-- store.rs).
SELECT
id,
parent_id,
content,
location,
kind,
creation_date,
updated_date,
lastview_date,
deleted_date
FROM (
WITH RECURSIVE notestree (
id,
parent_id,
content,
location,
kind,
creation_date,
updated_date,
lastview_date,
deleted_date,
cycle
)
AS (
-- The seed query. Finds the root node of any tree of notes,
-- which by definition has a location of zero and a type of
-- 'page'.
SELECT
notes.id,
NULL as parent_id,
notes.content,
0, -- All boxes are at position zero. They are the root of the tree.
notes.kind,
notes.creation_date,
notes.updated_date,
notes.lastview_date,
notes.deleted_date,
','||notes.id||',' -- Cycle monitor
FROM notes
WHERE notes.kind = "box"
AND QUERYPARAMETER = ? -- The Query Parameter
-- RECURSIVE expression
--
-- Here, for each recursion down the tree, we collect the child
-- nodes for a given node, eliding any cycles.
--
-- TODO: Figure out what to do when a cycle DOES occur.
UNION SELECT
notes.id,
notestree.id AS parent_id,
notes.content,
note_relationships.location,
notes.kind,
notes.creation_date,
notes.updated_date,
notes.lastview_date,
notes.deleted_date,
notestree.cycle||notes.id||','
FROM notes
INNER JOIN note_relationships
ON notes.id = note_relationships.note_id
-- For a given ID in the level of notestree in *this* recursion,
-- we want each note's branches one level down.
INNER JOIN notestree
ON note_relationships.parent_id = notestree.id
-- And we want to make sure there are no cycles. There shouldn't
-- be; we're supposed to prevent those. But you never know.
WHERE notestree.cycle NOT LIKE '%,'||notes.id||',%'
ORDER BY note_relationships.location
)
SELECT * from notestree);

View File

@ -1 +0,0 @@
SELECT id, uuid, content, notetype, creation_date, updated_date, lastview_date, deleted_date FROM notes WHERE uuid=?;

View File

@ -1 +0,0 @@
SELECT id, title, slug, note_id, creation_date, updated_date, lastview_date, deleted_date FROM pages WHERE slug=?;

View File

@ -1,3 +0,0 @@
UPDATE notes
SET content = ?, updated_date = ?, lastview_date = ?
WHERE uuid = ?;

View File

@ -6,12 +6,13 @@
//! //!
//! This library implements the core functionality of Notesmachine and //! This library implements the core functionality of Notesmachine and
//! describes that functionality to a storage layer. There's a bit of //! describes that functionality to a storage layer. There's a bit of
//! intermingling in here which can't be helped, although it may make sense //! intermingling in here which can't be helped, although it may make
//! in the future to separate the decomposition of the note content into a //! sense in the future to separate the decomposition of the note
//! higher layer. //! content into a higher layer.
//! //!
//! Notesmachine storage notes consist of two items: Zettle and Kasten, //! Notesmachine storage notes consist of two items: Note and Kasten.
//! which are German for "Note" and "Box". Here are the basic rules: //! This distinction is somewhat arbitrary, as structurally these two
//! items are stored in the same table.
//! //!
//! - Boxes have titles (and date metadata) //! - Boxes have titles (and date metadata)
//! - Notes have content and a type (and date metadata) //! - Notes have content and a type (and date metadata)
@ -56,7 +57,7 @@ use crate::store_private::*;
use crate::structs::*; use crate::structs::*;
use sqlx::sqlite::SqlitePool; use sqlx::sqlite::SqlitePool;
use std::cmp; use std::cmp;
use std::collections::HashMap; // use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
/// A handle to our Sqlite database. /// A handle to our Sqlite database.
@ -65,12 +66,9 @@ pub struct NoteStore(Arc<SqlitePool>);
type NoteResult<T> = core::result::Result<T, NoteStoreError>; type NoteResult<T> = core::result::Result<T, NoteStoreError>;
// One thing that's pretty terrible about this code is that the // After wrestling for a while with the fact that 'box' is a reserved
// Executor type in Sqlx is move-only, so it can only be used once per // word in Rust, I decided to just go with Note (note) and Kasten
// outgoing function call. That means that a lot of this code is // (box).
// internally duplicated, which sucks. I tried using the Acquire()
// trait, but its interaction with Executor was not very
// deterministic.
impl NoteStore { impl NoteStore {
/// Initializes a new instance of the note store. Note that the /// Initializes a new instance of the note store. Note that the
@ -80,7 +78,6 @@ impl NoteStore {
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.
@ -95,208 +92,204 @@ impl NoteStore {
/// 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_kasten_by_slug(&self, slug: &str) -> NoteResult<(Vec<Note>, Vec<Note>)> {
// let select_note_collection_for_root = include_str!("sql/select_note_collection_for_root.sql"); let kasten = select_kasten_by_slug(&*self.0, &NoteId(slug.to_string())).await?;
let mut tx = self.0.begin().await?; if kasten.is_empty() {
let page = select_page_by_slug(&mut tx, slug).await?; return Err(NoteStoreError::NotFound)
let note_id = page.note_id; }
let notes = select_note_collection_from_root(&mut tx, note_id).await?;
tx.commit().await?; let note_id = NoteId(kasten[0].id.clone());
Ok((page, notes)) Ok((kasten, select_backreferences_for_kasten(&*self.0, &note_id).await?))
} }
/// Fetch page by title /// 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))
}
/// Insert a note as the child of an existing note, at a set position. /// The most common use case: the user is navigating by requesting
pub async fn insert_nested_note( /// a page. The page either exists or it doesn't. If it
&self, /// doesn't, we go out and make it. Since we know it doesn't exist,
note: &NewNote, /// we also know no backreferences to it exist, so in that case you
parent_note_uuid: &str, /// get back two empty vecs.
position: i64, pub async fn get_kasten_by_title(&self, title: &str) -> NoteResult<(Vec<Note>, Vec<Note>)> {
) -> NoteResult<String> { if title.len() == 0 {
let mut new_note = note.clone();
new_note.uuid = friendly_id::create();
let references = build_references(&note.content);
let mut tx = self.0.begin().await?;
// Start by building the note and putting it into its relationship.
println!("Select_note_id_for_uuid");
let parent_id: ParentId = select_note_id_for_uuid(&mut tx, parent_note_uuid).await?;
// Ensure new position is sane
println!("Assert Max Child Position");
let parent_max_position = assert_max_child_position_for_note(&mut tx, parent_id).await?;
let position = cmp::min(parent_max_position + 1, position);
println!("Insert_one_new_note");
let new_note_id = insert_one_new_note(&mut tx, &new_note).await?;
println!("make_room_for_new_note");
let _ = make_room_for_new_note(&mut tx, parent_id, position).await?;
println!("Insert_note_to_note_relationship");
let _ = insert_note_to_note_relationship(&mut tx, parent_id, new_note_id, position, "note").await?;
// From the references, make lists of pages that exist, and pages
// that do not.
println!("Find_all_page_references");
let found_references = find_all_page_references_for(&mut tx, &references).await?;
let new_references = diff_references(&references, &found_references);
let mut known_reference_ids: Vec<PageId> = Vec::new();
// Create the pages that don't exist
for one_reference in new_references.iter() {
let new_root_note = create_unique_root_note();
println!("Insert_one_new_root_note");
let new_root_note_id = insert_one_new_note(&mut tx, &new_root_note).await?;
println!("Generate_slug");
let new_page_slug = generate_slug(&mut tx, &one_reference).await?;
let new_page = create_new_page_for(&one_reference, &new_page_slug, new_root_note_id);
println!("insert_one_new_page");
known_reference_ids.push(insert_one_new_page(&mut tx, &new_page).await?)
}
// And associate the note with all the pages.
known_reference_ids.append(&mut found_references.iter().map(|r| PageId(r.id)).collect());
println!("insert_note_to_page_relationships");
let _ = insert_note_to_page_relationships(&mut tx, new_note_id, &known_reference_ids).await?;
tx.commit().await?;
Ok(new_note.uuid)
}
// This doesn't do anything with the references, as those are
// dependent entirely on the *content*, and not the *position*, of
// the note and the referenced page.
//
/// 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 all_uuids = vec![note_uuid, old_parent_uuid, new_parent_uuid];
let mut tx = self.0.begin().await?;
// 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, &all_uuids).await?;
let found_ids: HashMap<String, i64> = found_id_vec.into_iter().collect();
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 kasten = select_kasten_by_title(&*self.0, title).await?;
let new_parent_id = ParentId(*found_ids.get(new_parent_uuid).unwrap()); if kasten.len() > 0 {
let note_id = NoteId(*found_ids.get(note_uuid).unwrap()); let note_id = NoteId(kasten[0].id.clone());
return Ok((kasten, select_backreferences_for_kasten(&*self.0, &note_id).await?));
}
let old_note = get_note_to_note_relationship(&mut tx, old_parent_id, note_id).await?; // Sanity check!
let old_note_position = old_note.position; let references = build_references(&title);
let old_note_nature = &old_note.nature; if references.len() > 0 {
return Err(NoteStoreError::InvalidNoteStructure(
"Titles may not contain nested references.".to_string(),
));
}
let _ = delete_note_to_note_relationship(&mut tx, old_parent_id, note_id).await?; let mut tx = self.0.begin().await?;
let _ = close_hole_for_deleted_note(&mut tx, old_parent_id, old_note_position).await?; let slug = generate_slug(&mut tx, title).await?;
let parent_max_position = assert_max_child_position_for_note(&mut tx, new_parent_id).await?; let zettlekasten = create_zettlekasten(&title, &slug);
let new_position = cmp::min(parent_max_position + 1, new_position); let _ = insert_note(&mut tx, &zettlekasten).await?;
let _ = make_room_for_new_note(&mut tx, new_parent_id, new_position).await?;
let _ =
insert_note_to_note_relationship(&mut tx, new_parent_id, note_id, new_position, old_note_nature).await?;
tx.commit().await?; tx.commit().await?;
Ok(())
Ok((vec![Note::from(zettlekasten)], vec![]))
} }
/// Embed or reference a note from a different location. pub async fn add_note(&self, note: &NewNote, parent_id: &str, location: Option<i64>) -> NoteResult<String> {
pub async fn reference_or_embed_note( let new_id = self.insert_note(
note,
&ParentId(parent_id.to_string()),
location,
RelationshipKind::Direct).await?;
Ok(new_id)
}
/// Move a note from one location to another.
pub async fn move_note(
&self, &self,
note_uuid: &str, note_id: &str,
new_parent_uuid: &str, old_parent_id: &str,
new_position: i64, new_parent_id: &str,
new_nature: &str, new_location: i64,
) -> NoteResult<()> { ) -> NoteResult<()> {
let mut tx = self.0.begin().await?; let mut tx = self.0.begin().await?;
let existing_note_id: NoteId = NoteId(select_note_id_for_uuid(&mut tx, note_uuid).await?.0);
let new_parent_id: ParentId = select_note_id_for_uuid(&mut tx, new_parent_uuid).await?;
let _ = make_room_for_new_note(&mut tx, new_parent_id, new_position).await?;
let _ = insert_note_to_note_relationship(&mut tx, new_parent_id, existing_note_id, new_position, new_nature)
.await?;
tx.commit().await?;
Ok(())
}
/// Deletes a note. If the note's relationship drops to zero, all let old_parent_id = ParentId(old_parent_id.to_string());
/// references from that note to pages are also deleted. let new_parent_id = ParentId(new_parent_id.to_string());
pub async fn delete_note(&self, note_uuid: &str, note_parent_uuid: &str) -> NoteResult<()> { let note_id = NoteId(note_id.to_string());
let mut tx = self.0.begin().await?;
let condemned_note_id: NoteId = NoteId(select_note_id_for_uuid(&mut tx, note_uuid).await?.0); let old_note = select_note_to_note_relationship(&mut tx, &old_parent_id, &note_id).await?;
let note_parent_id: ParentId = select_note_id_for_uuid(&mut tx, note_parent_uuid).await?; let old_note_location = old_note.location;
let _ = delete_note_to_note_relationship(&mut tx, note_parent_id, condemned_note_id); let old_note_kind = old_note.kind;
if count_existing_note_relationships(&mut tx, condemned_note_id).await? == 0 {
let _ = delete_note_to_page_relationships(&mut tx, condemned_note_id).await?; let _ = delete_note_to_note_relationship(&mut tx, &old_parent_id, &note_id).await?;
let _ = delete_note(&mut tx, condemned_note_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 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, &note_id, new_location, &old_note_kind).await?;
tx.commit().await?; tx.commit().await?;
Ok(()) Ok(())
} }
/// Updates a note's content. Completely rebuilds the note's /// Updates a note's content. Completely rebuilds the note's
/// outgoing edge reference list every time. /// outgoing edge reference list every time.
pub async fn update_note_content(&self, note_uuid: &str, content: &str) -> NoteResult<()> { pub async fn update_note_content(&self, note_id: &str, content: &str) -> NoteResult<()> {
let references = build_references(&content); let references = build_references(&content);
let note_id = NoteId(note_id.to_string());
let mut tx = self.0.begin().await?; let mut tx = self.0.begin().await?;
let _ = update_note_content(&mut tx, &note_id, &content).await?;
let note_id: NoteId = NoteId(select_note_id_for_uuid(&mut tx, note_uuid).await?.0); let _ = delete_bulk_note_to_kasten_relationships(&mut tx, &note_id).await?;
let _ = update_note_content(&mut tx, note_id, &content).await?; let found_references = find_all_kasten_from_list_of_references(&mut tx, &references).await?;
let found_references = find_all_page_references_for(&mut tx, &references).await?;
let new_references = diff_references(&references, &found_references); let new_references = diff_references(&references, &found_references);
let mut known_reference_ids: Vec<PageId> = Vec::new(); let mut known_reference_ids: Vec<NoteId> = Vec::new();
// Create the pages that don't exist
for one_reference in new_references.iter() { for one_reference in new_references.iter() {
let new_root_note = create_unique_root_note(); let slug = generate_slug(&mut tx, one_reference).await?;
let new_root_note_id = insert_one_new_note(&mut tx, &new_root_note).await?; let zettlekasten = create_zettlekasten(&one_reference, &slug);
let new_page_slug = generate_slug(&mut tx, &one_reference).await?; let _ = insert_note(&mut tx, &zettlekasten).await?;
let new_page = create_new_page_for(&one_reference, &new_page_slug, new_root_note_id); known_reference_ids.push(NoteId(slug));
known_reference_ids.push(insert_one_new_page(&mut tx, &new_page).await?)
} }
// And associate the note with all the pages. known_reference_ids.append(&mut found_references.iter().map(|r| NoteId(r.id.clone())).collect());
known_reference_ids.append(&mut found_references.iter().map(|r| PageId(r.id)).collect()); let _ = insert_bulk_note_to_kasten_relationships(&mut tx, &note_id, &known_reference_ids).await?;
let _ = insert_note_to_page_relationships(&mut tx, note_id, &known_reference_ids).await?;
tx.commit().await?; tx.commit().await?;
Ok(()) Ok(())
} }
/// Deletes a note. If the note's relationship drops to zero, all
/// references from that note to pages are also deleted.
pub async fn delete_note(&self, note_id: &str, note_parent_id: &str) -> NoteResult<()> {
let mut tx = self.0.begin().await?;
let note_id = NoteId(note_id.to_string());
let parent_id = ParentId(note_parent_id.to_string());
if *parent_id != *note_id {
let _ = delete_note_to_note_relationship(&mut tx, &parent_id, &note_id);
}
// The big one: if zero parents report having an interest in this note, then it,
// *and any sub-relationships*, go away.
if count_existing_note_relationships(&mut tx, &note_id).await? == 0 {
let _ = delete_note_to_kasten_relationships(&mut tx, &note_id).await?;
let _ = delete_note(&mut tx, &note_id).await?;
}
tx.commit().await?;
Ok(())
}
}
// The Private stuff
impl NoteStore {
// Pretty much the most dangerous function in our system. Has to
// have ALL the error checking.
async fn insert_note(
&self,
note: &NewNote,
parent_id: &ParentId,
location: Option<i64>,
kind: RelationshipKind,
) -> NoteResult<String> {
if let Some(location) = location {
if location < 0 {
return Err(NoteStoreError::InvalidNoteStructure(
"Add note: A negative location is not valid.".to_string(),
));
}
}
if parent_id.is_empty() {
return Err(NoteStoreError::InvalidNoteStructure(
"Add note: A parent note ID is required.".to_string(),
));
}
if note.id.is_empty() {
return Err(NoteStoreError::InvalidNoteStructure(
"Add note: Your note should have an id already".to_string(),
));
}
if note.content.is_empty() {
return Err(NoteStoreError::InvalidNoteStructure(
"Add note: Empty notes are not supported.".to_string(),
));
}
let references = build_references(&note.content);
let mut tx = self.0.begin().await?;
let location = {
let max_child = assert_max_child_location_for_note(&mut tx, parent_id).await? + 1;
if let Some(location) = location {
cmp::min(max_child, location)
} else {
max_child
}
};
let note_id = NoteId(note.id.clone());
insert_note(&mut tx, &note).await?;
make_room_for_new_note(&mut tx, &parent_id, location).await?;
insert_note_to_note_relationship(&mut tx, &parent_id, &note_id, location, &kind).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() {
let slug = generate_slug(&mut tx, one_reference).await?;
let zettlekasten = create_zettlekasten(&one_reference, &slug);
let _ = insert_note(&mut tx, &zettlekasten).await?;
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, &note_id, &known_reference_ids).await?;
tx.commit().await?;
Ok(note_id.to_string())
}
} }

View File

@ -2,10 +2,7 @@ use crate::structs::*;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use regex::Regex; use regex::Regex;
use slug::slugify; use slug::slugify;
use sqlx::{ use sqlx::{sqlite::Sqlite, Done, Executor};
sqlite::{Sqlite, SqliteRow},
Done, Executor, Row,
};
use std::collections::HashSet; use std::collections::HashSet;
type SqlResult<T> = sqlx::Result<T>; type SqlResult<T> = sqlx::Result<T>;
@ -21,6 +18,33 @@ type SqlResult<T> = sqlx::Result<T>;
// coherent and easily readable, and hides away the gnarliness of some // coherent and easily readable, and hides away the gnarliness of some
// of the SQL queries. // 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");
}
// ___ _
// | _ \___ ___ ___| |_
// | / -_|_-</ -_) _|
// |_|_\___/__/\___|\__|
//
pub(crate) async fn reset_database<'a, E>(executor: E) -> SqlResult<()> pub(crate) async fn reset_database<'a, E>(executor: E) -> SqlResult<()>
where where
E: Executor<'a, Database = Sqlite>, E: Executor<'a, Database = Sqlite>,
@ -29,133 +53,99 @@ where
sqlx::query(initialize_sql).execute(executor).await.map(|_| ()) sqlx::query(initialize_sql).execute(executor).await.map(|_| ())
} }
pub(crate) async fn select_page_by_slug<'a, E>(executor: E, slug: &str) -> SqlResult<RawPage> // ___ _ _ _ __ _
// | __|__| |_ __| |_ | |/ /__ _ __| |_ ___ _ _
// | _/ -_) _/ _| ' \ | ' </ _` (_-< _/ -_) ' \
// |_|\___|\__\__|_||_| |_|\_\__,_/__/\__\___|_||_|
//
// Select the requested kasten via its id. This is fairly rare;
// kastens should usually be picked up via their title, but if you're
// navigating to an instance, this is how you specify the kasten in a
// URL. The return value is an array of Note objects; it is the
// responsibility of client code to restructure these into a tree-like
// object.
//
// Recommended: Clients should update the URL whenever changing
// kasten.
pub(crate) async fn select_kasten_by_slug<'a, E>(executor: E, slug: &NoteId) -> SqlResult<Vec<Note>>
where where
E: Executor<'a, Database = Sqlite>, E: Executor<'a, Database = Sqlite>,
{ {
let select_one_page_by_slug_sql = concat!( let r: Vec<RowNote> = sqlx::query_as(&SELECT_KASTEN_BY_ID_SQL)
"SELECT id, title, slug, note_id, creation_date, updated_date, ", .bind(&**slug)
"lastview_date, deleted_date FROM pages WHERE slug=?;"
);
Ok(sqlx::query_as(&select_one_page_by_slug_sql)
.bind(&slug)
.fetch_one(executor)
.await?)
}
pub(crate) async fn select_page_by_title<'a, E>(executor: E, title: &str) -> SqlResult<RawPage>
where
E: Executor<'a, Database = Sqlite>,
{
let select_one_page_by_title_sql = concat!(
"SELECT id, title, slug, note_id, creation_date, updated_date, ",
"lastview_date, deleted_date FROM pages WHERE title=?;"
);
Ok(sqlx::query_as(&select_one_page_by_title_sql)
.bind(&title)
.fetch_one(executor)
.await?)
}
pub(crate) async fn select_note_id_for_uuid<'a, E>(executor: E, uuid: &str) -> SqlResult<ParentId>
where
E: Executor<'a, Database = Sqlite>,
{
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)
.bind(&uuid)
.fetch_one(executor)
.await?;
Ok(ParentId(id.id))
}
pub(crate) async fn make_room_for_new_note<'a, E>(executor: E, parent_id: ParentId, position: i64) -> SqlResult<()>
where
E: Executor<'a, Database = Sqlite>,
{
let make_room_for_new_note_sql = concat!(
"UPDATE note_relationships ",
"SET position = position + 1 ",
"WHERE position >= ? and parent_id = ?;"
);
sqlx::query(make_room_for_new_note_sql)
.bind(&position)
.bind(&*parent_id)
.execute(executor)
.await
.map(|_| ())
}
pub(crate) async fn insert_note_to_note_relationship<'a, E>(
executor: E,
parent_id: ParentId,
note_id: NoteId,
position: i64,
nature: &str,
) -> SqlResult<()>
where
E: Executor<'a, Database = Sqlite>,
{
let insert_note_to_note_relationship_sql = concat!(
"INSERT INTO note_relationships (parent_id, note_id, position, nature) ",
"values (?, ?, ?, ?)"
);
sqlx::query(insert_note_to_note_relationship_sql)
.bind(&*parent_id)
.bind(&*note_id)
.bind(&position)
.bind(&nature)
.execute(executor)
.await
.map(|_| ())
}
pub(crate) async fn select_note_collection_from_root<'a, E>(executor: E, root: i64) -> SqlResult<Vec<RawNote>>
where
E: Executor<'a, Database = Sqlite>,
{
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) .fetch_all(executor)
.await?) .await?;
Ok(r.into_iter().map(|z| Note::from(z)).collect())
} }
pub(crate) async fn insert_one_new_note<'a, E>(executor: E, note: &NewNote) -> SqlResult<NoteId> // 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<Vec<Note>>
where where
E: Executor<'a, Database = Sqlite>, E: Executor<'a, Database = Sqlite>,
{ {
let insert_one_note_sql = concat!( let r: Vec<RowNote> = sqlx::query_as(&SELECT_KASTEN_BY_TITLE_SQL)
"INSERT INTO notes ( ", .bind(&title)
" uuid, ", .fetch_all(executor)
" content, ", .await?;
" notetype, ", Ok(r.into_iter().map(|z| Note::from(z)).collect())
" creation_date, ", }
" updated_date, ",
" lastview_date) ", // 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<Vec<Note>>
where
E: Executor<'a, Database = Sqlite>,
{
let r: Vec<RowNote> = 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())
}
// ___ _ ___ _ _ _
// |_ _|_ _ ___ ___ _ _| |_ / _ \ _ _ ___ | \| |___| |_ ___
// | || ' \(_-</ -_) '_| _| | (_) | ' \/ -_) | .` / _ \ _/ -_)
// |___|_||_/__/\___|_| \__| \___/|_||_\___| |_|\_\___/\__\___|
//
// Inserts a single note into the notes table. That is all.
pub(crate) async fn insert_note<'a, E>(executor: E, zettle: &NewNote) -> SqlResult<String>
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 (?, ?, ?, ?, ?, ?);" "VALUES (?, ?, ?, ?, ?, ?);"
); );
Ok(NoteId( let _ = sqlx::query(insert_one_page_sql)
sqlx::query(insert_one_note_sql) .bind(&zettle.id)
.bind(&note.uuid) .bind(&zettle.content)
.bind(&note.content) .bind(zettle.kind.to_string())
.bind(&note.notetype) .bind(&zettle.creation_date)
.bind(&note.creation_date) .bind(&zettle.updated_date)
.bind(&note.updated_date) .bind(&zettle.lastview_date)
.bind(&note.lastview_date) .execute(executor)
.execute(executor) .await?;
.await? Ok(zettle.id.clone())
.last_insert_rowid(),
))
} }
// ___ _ _ _ _ __ _
// | _ )_ _(_) |__| | | |/ /__ _ __| |_ ___ _ _
// | _ \ || | | / _` | | ' </ _` (_-< _/ -_) ' \
// |___/\_,_|_|_\__,_| |_|\_\__,_/__/\__\___|_||_|
//
// Given a possible slug, find the slug with the highest // Given a possible slug, find the slug with the highest
// uniquification number, and return that number, if any. // uniquification number, and return that number, if any.
pub(crate) fn find_maximal_slug_number(slugs: &[JustId]) -> Option<u32> {
pub(crate) fn find_maximal_slug(slugs: &[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();
} }
@ -166,7 +156,7 @@ pub(crate) fn find_maximal_slug(slugs: &[JustSlugs]) -> Option<u32> {
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.id))
.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();
@ -175,62 +165,170 @@ pub(crate) fn find_maximal_slug(slugs: &[JustSlugs]) -> Option<u32> {
// Given an initial string and an existing collection of slugs, // Given an initial string and an existing collection of slugs,
// generate a new slug that does not conflict with the current // generate a new slug that does not conflict with the current
// collection. // 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<String> pub(crate) 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();
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 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 similar_slugs: Vec<JustId> = 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_number = find_maximal_slug_number(&similar_slugs);
match maximal_slug { Ok(match maximal_slug_number {
None => Ok(initial_slug), None => initial_slug,
Some(max_slug) => Ok(format!("{}-{}", initial_slug, max_slug + 1)), Some(slug_number) => format!("{}-{}", initial_slug, slug_number + 1),
} })
} }
pub(crate) async fn insert_one_new_page<'a, E>(executor: E, page: &NewPage) -> SqlResult<PageId> // 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 where
E: Executor<'a, Database = Sqlite>, E: Executor<'a, Database = Sqlite>,
{ {
let insert_one_page_sql = concat!( let update_note_content_sql = "UPDATE notes SET content = ? WHERE note_id = ?";
"INSERT INTO pages ( ", let count = sqlx::query(update_note_content_sql)
" slug, ", .bind(content)
" title, ", .bind(&**note_id)
" note_id, ", .execute(executor)
" creation_date, ", .await?
" updated_date, ", .rows_affected();
" lastview_date) ",
"VALUES (?, ?, ?, ?, ?, ?);"
);
Ok(PageId( match count {
sqlx::query(insert_one_page_sql) 1 => Ok(()),
.bind(&page.slug) _ => Err(sqlx::Error::RowNotFound),
.bind(&page.title) }
.bind(&page.note_id)
.bind(&page.creation_date)
.bind(&page.updated_date)
.bind(&page.lastview_date)
.execute(executor)
.await?
.last_insert_rowid(),
))
} }
pub(crate) async fn insert_note_to_page_relationships<'a, E>( // ___ _ _ ___ _ _ _ ___ _ _ _ _ _
// | __|__| |_ __| |_ / _ \ _ _ ___ | \| |___| |_ ___ | _ \___| |__ _| |_(_)___ _ _ __| |_ (_)_ __
// | _/ -_) _/ _| ' \ | (_) | ' \/ -_) | .` / _ \ _/ -_) | / -_) / _` | _| / _ \ ' \(_-< ' \| | '_ \
// |_|\___|\__\__|_||_| \___/|_||_\___| |_|\_\___/\__\___| |_|_\___|_\__,_|\__|_\___/_||_/__/_||_|_| .__/
// |_|
pub(crate) async fn select_note_to_note_relationship<'a, E>(
executor: E, executor: E,
note_id: NoteId, parent_id: &ParentId,
references: &[PageId], note_id: &NoteId,
) -> SqlResult<NoteRelationship>
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<i64>
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)
}
// _ _ _ _ _ __ _ ___ _ _ _ _ _
// | \| |___| |_ ___ | |_ ___ | |/ /__ _ __| |_ ___ _ _ | _ \___| |__ _| |_(_)___ _ _ __| |_ (_)_ __ ___
// | .` / _ \ _/ -_) | _/ _ \ | ' </ _` (_-< _/ -_) ' \ | / -_) / _` | _| / _ \ ' \(_-< ' \| | '_ (_-<
// |_|\_\___/\__\___| \__\___/ |_|\_\__,_/__/\__\___|_||_| |_|_\___|_\__,_|\__|_\___/_||_/__/_||_|_| .__/__/
// |_|
pub(crate) async fn insert_bulk_note_to_kasten_relationships<'a, E>(
executor: E,
note_id: &NoteId,
references: &[NoteId],
) -> SqlResult<()> ) -> SqlResult<()>
where where
E: Executor<'a, Database = Sqlite>, E: Executor<'a, Database = Sqlite>,
@ -239,77 +337,87 @@ where
return Ok(()); return Ok(());
} }
let insert_note_page_references_sql = "INSERT INTO page_relationships (note_id, page_id) VALUES ".to_string() let insert_pattern = format!("(?, ?, '{}')", KastenRelationshipKind::Kasten.to_string());
+ &["(?, ?)"].repeat(references.len()).join(", ") 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(); + &";".to_string();
let mut request = sqlx::query(&insert_note_page_references_sql); let mut request = sqlx::query(&insert_note_page_references_sql);
for reference in references { for reference in references {
request = request.bind(*note_id).bind(**reference); request = request.bind(&**note_id).bind(&**reference);
} }
request.execute(executor).await.map(|_| ()) request.execute(executor).await.map(|_| ())
} }
// For a given collection of uuids, retrieve the internal ID used by pub(crate) async fn delete_bulk_note_to_kasten_relationships<'a, E>(executor: E, note_id: &NoteId) -> SqlResult<()>
// the database.
pub(crate) async fn bulk_select_ids_for_note_uuids<'a, E>(executor: E, ids: &[&str]) -> SqlResult<Vec<(String, i64)>>
where where
E: Executor<'a, Database = Sqlite>, E: Executor<'a, Database = Sqlite>,
{ {
if ids.is_empty() { 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<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()
}
// ___ _ _ _ _ __ _ ___ _ _ _ _ _
// / __|___ _ _| |_ ___ _ _| |_ | |_ ___ | |/ /__ _ __| |_ ___ _ _ | _ \___| |__ _| |_(_)___ _ _ __| |_ (_)_ __ ___
// | (__/ _ \ ' \ _/ -_) ' \ _| | _/ _ \ | ' </ _` (_-< _/ -_) ' \ | / -_) / _` | _| / _ \ ' \(_-< ' \| | '_ (_-<
// \___\___/_||_\__\___|_||_\__| \__\___/ |_|\_\__,_/__/\__\___|_||_| |_|_\___|_\__,_|\__|_\___/_||_/__/_||_|_| .__/__/
// |_|
// Returns all the (Id, title) pairs found in the database out of a
// list of titles. Used by insert_note and update_note_content to
// find the ids of all the references in a given document.
pub(crate) async fn find_all_kasten_from_list_of_references<'a, E>(
executor: E,
references: &[String],
) -> SqlResult<Vec<PageTitle>>
where
E: Executor<'a, Database = Sqlite>,
{
if references.is_empty() {
return Ok(vec![]); return Ok(vec![]);
} }
let bulk_select_ids_for_note_uuids_sql = "SELECT uuid, id FROM notes WHERE uuid IN (".to_string() lazy_static! {
+ &["?"].repeat(ids.len()).join(",") static ref SELECT_ALL_REFERENCES_FOR_SQL_BASE: String = format!(
+ &");".to_string(); "SELECT id, content FROM notes WHERE kind = '{}' AND content IN (",
NoteKind::Kasten.to_string()
);
}
let mut request = sqlx::query(&bulk_select_ids_for_note_uuids_sql); let find_all_references_for_sql =
for id in ids.iter() { 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 = request.bind(id);
} }
Ok(request request.fetch_all(executor).await
.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())
} }
// Used by move_note to identify the single note to note relationship // ___ _ _
// by the original parent and child pair. Used mostly to find the // | \ ___| |___| |_ ___
// position for recalculation, to create a new gap or close an old // | |) / -_) / -_) _/ -_)
// one. // |___/\___|_\___|\__\___|
pub(crate) async fn get_note_to_note_relationship<'a, E>( //
executor: E,
parent_id: ParentId,
note_id: NoteId,
) -> SqlResult<NoteRelationship>
where
E: Executor<'a, Database = Sqlite>,
{
let get_note_to_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_to_note_relationship_sql)
.bind(&*parent_id)
.bind(&*note_id)
.fetch_one(executor)
.await
}
pub(crate) async fn delete_note_to_note_relationship<'a, E>( pub(crate) async fn delete_note_to_note_relationship<'a, E>(
executor: E, executor: E,
parent_id: ParentId, parent_id: &ParentId,
note_id: NoteId, note_id: &NoteId,
) -> SqlResult<()> ) -> SqlResult<()>
where where
E: Executor<'a, Database = Sqlite>, E: Executor<'a, Database = Sqlite>,
@ -320,8 +428,8 @@ where
); );
let count = sqlx::query(delete_note_to_note_relationship_sql) let count = sqlx::query(delete_note_to_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();
@ -332,27 +440,33 @@ where
} }
} }
pub(crate) async fn delete_note_to_page_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 where
E: Executor<'a, Database = Sqlite>, E: Executor<'a, Database = Sqlite>,
{ {
let delete_note_to_page_relationships_sql = "DELETE FROM page_relationships WHERE note_id = ?;"; 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_page_relationships_sql) let _ = sqlx::query(&DELETE_NOTE_TO_KASTEN_RELATIONSHIPS_SQL)
.bind(&*note_id) .bind(&**note_id)
.execute(executor) .execute(executor)
.await?; .await?;
Ok(()) Ok(())
} }
pub(crate) async fn delete_note<'a, E>(executor: E, note_id: NoteId) -> SqlResult<()> pub(crate) async fn delete_note<'a, E>(executor: E, note_id: &NoteId) -> SqlResult<()>
where where
E: Executor<'a, Database = Sqlite>, E: Executor<'a, Database = Sqlite>,
{ {
let delete_note_sql = "DELETE FROM notes WHERE note_id = ?"; let delete_note_sql = "DELETE FROM notes WHERE note_id = ?";
let count = sqlx::query(delete_note_sql) let count = sqlx::query(delete_note_sql)
.bind(&*note_id) .bind(&**note_id)
.execute(executor) .execute(executor)
.await? .await?
.rows_affected(); .rows_affected();
@ -363,118 +477,50 @@ where
} }
} }
pub(crate) async fn count_existing_note_relationships<'a, E>(executor: E, note_id: NoteId) -> SqlResult<i64>
where
E: Executor<'a, Database = Sqlite>,
{
let count_existing_note_relationships_sql = "SELECT COUNT(*) as count FROM page_relationships WHERE note_id = ?;";
let count: RowCount = sqlx::query_as(count_existing_note_relationships_sql)
.bind(&*note_id)
.fetch_one(executor)
.await?;
Ok(count.count)
}
pub(crate) async fn assert_max_child_position_for_note<'a, E>(executor: E, note_id: ParentId) -> SqlResult<i64>
where
E: Executor<'a, Database = Sqlite>,
{
let assert_max_child_position_for_note_sql =
"SELECT MAX(position) AS count FROM note_relationships WHERE parent_id = ?;";
let count: RowCount = sqlx::query_as(assert_max_child_position_for_note_sql)
.bind(&*note_id)
.fetch_one(executor)
.await?;
Ok(count.count)
}
// After removing a note, recalculate the position of all notes under // After removing a note, recalculate the position of all notes under
// the parent note, such that there order is now completely // the parent note, such that there order is now completely
// sequential. // sequential.
pub(crate) async fn close_hole_for_deleted_note<'a, E>(executor: E, parent_id: ParentId, position: i64) -> SqlResult<()> pub(crate) async fn close_hole_for_deleted_note<'a, E>(
executor: E,
parent_id: &ParentId,
location: i64,
) -> SqlResult<()>
where where
E: Executor<'a, Database = Sqlite>, E: Executor<'a, Database = Sqlite>,
{ {
let close_hole_for_deleted_note_sql = concat!( let close_hole_for_deleted_note_sql = concat!(
"UPDATE note_relationships ", "UPDATE note_relationships ",
"SET position = position - 1 ", "SET location = location - 1 ",
"WHERE position > ? and parent_id = ?;" "WHERE location > ? and parent_id = ?;"
); );
sqlx::query(close_hole_for_deleted_note_sql) let _ = sqlx::query(close_hole_for_deleted_note_sql)
.bind(&position) .bind(&location)
.bind(&*parent_id) .bind(&**parent_id)
.execute(executor) .execute(executor)
.await .await?;
.map(|_| ()) Ok(())
} }
pub(crate) async fn find_all_page_references_for<'a, E>( // __ __ _
executor: E, // | \/ (_)___ __
references: &[String], // | |\/| | (_-</ _|
) -> SqlResult<Vec<PageTitles>> // |_| |_|_/__/\__|
//
// The dreaded miscellaneous!
pub(crate) async fn count_existing_note_relationships<'a, E>(executor: E, note_id: &NoteId) -> SqlResult<i64>
where where
E: Executor<'a, Database = Sqlite>, E: Executor<'a, Database = Sqlite>,
{ {
if references.is_empty() { let count_existing_note_relationships_sql =
return Ok(vec![]); "SELECT COUNT(*) as count FROM note_relationships WHERE note_id = ?;";
}
let find_all_references_for_sql = "SELECT id, title FROM pages WHERE title IN (".to_string() let count: RowCount = sqlx::query_as(&count_existing_note_relationships_sql)
+ &["?"].repeat(references.len()).join(",") .bind(&**note_id)
+ &");".to_string(); .fetch_one(executor)
.await?;
let mut request = sqlx::query_as(&find_all_references_for_sql); Ok(count.count)
for id in references.iter() {
request = request.bind(id);
}
request.fetch_all(executor).await
}
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) fn create_unique_root_note() -> NewNote {
NewNoteBuilder::default()
.uuid(friendly_id::create())
.content("".to_string())
.notetype("root".to_string())
.build()
.unwrap()
}
pub(crate) 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)
.build()
.unwrap()
}
// 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: &[PageTitles]) -> Vec<String> {
let all: HashSet<String> = references.iter().cloned().collect();
let found: HashSet<String> = found_references.iter().map(|r| r.title.clone()).collect();
all.difference(&found).cloned().collect()
} }

View File

@ -1,75 +1,149 @@
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use derive_builder::Builder; use derive_builder::Builder;
use serde::{Deserialize, Serialize}; use friendly_id;
use shrinkwraprs::Shrinkwrap; use shrinkwraprs::Shrinkwrap;
use sqlx::{self, FromRow}; use sqlx::{self, FromRow};
#[derive(Shrinkwrap, Copy, Clone)] // Kasten is German for "Box," and is used both because this is
pub(crate) struct PageId(pub i64); // supposed to be a Zettlekasten, and because "Box" is a heavily
// reserved word in Rust. So, for that matter, are "crate" and
// "cargo," "cell," and so forth. If I'd wanted to go the Full
// Noguchi, I guess I could have used "envelope."
#[derive(Shrinkwrap, Copy, Clone)] // In order to prevent arbitrary enumeration tokens from getting into
pub(crate) struct NoteId(pub i64); // the database, the private layer takes a very hard line on insisting
// that everything sent TO the datastore come in the enumerated
// format, and everything coming OUT of the database be converted back
// into an enumeration. These macros instantiate those objects
// and their conversions to/from strings.
#[derive(Shrinkwrap, Copy, Clone)] macro_rules! build_conversion_enums {
pub(crate) struct ParentId(pub i64); ( $ty:ident, $( $s:literal => $x:ident, )*) => {
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum $ty {
$( $x ), *
}
/// A RawPage is what this layer of the API returns when requesting a impl From<String> for $ty {
/// page. Note that usually what you'll get back in the RawPage and a fn from(kind: String) -> Self {
/// Vec<RawNote>. It's the next level's responsibility to turn that match &kind[..] {
/// into a proper tree. $( $s => $ty::$x, )*
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)] _ => panic!("Illegal value in $ty database: {}", kind),
pub struct RawPage { }
pub id: i64, }
pub slug: String, }
pub title: String,
pub note_id: i64, impl From<$ty> for String {
pub creation_date: DateTime<Utc>, fn from(kind: $ty) -> Self {
pub updated_date: DateTime<Utc>, match kind {
pub lastview_date: DateTime<Utc>, $( $ty::$x => $s ),*
pub deleted_date: Option<DateTime<Utc>>, }
.to_string()
}
}
impl $ty {
pub fn to_string(&self) -> String {
String::from(self.clone())
}
}
};
} }
/// A RawNote is what this layer of the API returns #[derive(Shrinkwrap, Clone)]
/// when requesting a note. pub(crate) struct NoteId(pub String);
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)]
pub struct RawNote { #[derive(Shrinkwrap, Clone)]
pub id: i64, pub(crate) struct ParentId(pub String);
pub uuid: String,
pub parent_id: i64, // The different kinds of objects we support.
pub parent_uuid: String,
build_conversion_enums!(
NoteKind,
"box" => Kasten,
"note" => Note,
"resource" => Resource,
);
// The different kinds of relationships we support. I do not yet
// know how to ensure that there is a maximum of one (a ->
// b)::Direct, and that for any (a -> b) there is no (b <- a), that
// is, nor, for that matter, do I know how to prevent cycles.
build_conversion_enums!(
RelationshipKind,
"direct" => Direct,
"reference" => Reference,
"embed" => Embed,
);
build_conversion_enums!(
KastenRelationshipKind,
"kasten" => Kasten,
"unacked" => Unacked,
"cancelled" => Cancelled,
);
// A Note is the base construct of our system. It represents a
// single note and contains information about its parent and location.
// This is the object *retrieved* from the database.
#[derive(Clone, Debug, FromRow)]
pub(crate) struct RowNote {
pub id: String,
pub parent_id: Option<String>,
pub content: String, pub content: String,
pub position: i64, pub kind: String,
pub notetype: String, pub location: 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>>,
} }
/// The interface for passing a new page to the store. /// A Note as it's returned from the private layer. This is
#[derive(Clone, Serialize, Deserialize, Debug, Builder)] /// provided to ensure that the NoteKind is an enum, and that we
pub struct NewPage { /// control the list of possible values stored in the database.
pub slug: String, #[derive(Clone, Debug)]
pub title: String, pub struct Note {
pub note_id: i64, pub id: String,
#[builder(default = r#"chrono::Utc::now()"#)] pub parent_id: Option<String>,
pub content: String,
pub kind: NoteKind,
pub location: i64,
pub creation_date: DateTime<Utc>, pub creation_date: DateTime<Utc>,
#[builder(default = r#"chrono::Utc::now()"#)]
pub updated_date: DateTime<Utc>, pub updated_date: DateTime<Utc>,
#[builder(default = r#"chrono::Utc::now()"#)]
pub lastview_date: DateTime<Utc>, pub lastview_date: DateTime<Utc>,
#[builder(default = r#"None"#)]
pub deleted_date: Option<DateTime<Utc>>, pub deleted_date: Option<DateTime<Utc>>,
} }
/// The interface for passing a new note to the store. impl From<RowNote> for Note {
#[derive(Clone, Serialize, Deserialize, Debug, Builder)] fn from(note: RowNote) -> Self {
Self {
id: note.id,
parent_id: note.parent_id,
content: note.content,
kind: NoteKind::from(note.kind),
location: note.location,
creation_date: note.creation_date,
updated_date: note.updated_date,
lastview_date: note.lastview_date,
deleted_date: note.deleted_date,
}
}
}
/// A new Note object as it's inserted into the system. It has no
/// parent or location information; those are data relative to the
/// parent, and must be provided by the client. In the case of a
/// Kasten, no location or parent is necessary.
#[derive(Clone, Debug, Builder)]
pub struct NewNote { pub struct NewNote {
#[builder(default = r#""".to_string()"#)] #[builder(default = r#"friendly_id::create()"#)]
pub uuid: String, pub id: String,
pub content: String, pub content: String,
#[builder(default = r#""note".to_string()"#)] #[builder(default = r#"NoteKind::Note"#)]
pub notetype: String, pub kind: NoteKind,
#[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()"#)]
@ -80,40 +154,92 @@ pub struct NewNote {
pub deleted_date: Option<DateTime<Utc>>, pub deleted_date: Option<DateTime<Utc>>,
} }
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)] impl From<NewNote> for Note {
pub(crate) struct JustSlugs { /// Only used for building new kastens, so the decision- making is
pub slug: String, /// limited to kasten-level things, like pointing to self and
/// having a location of zero.
fn from(note: NewNote) -> Self {
Self {
id: note.id,
parent_id: None,
content: note.content,
kind: note.kind,
location: 0,
creation_date: note.creation_date,
updated_date: note.updated_date,
lastview_date: note.lastview_date,
deleted_date: note.deleted_date,
}
}
} }
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)] #[derive(Clone, Debug, FromRow)]
pub(crate) struct JustTitles {
title: String,
}
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)]
pub(crate) struct JustId { pub(crate) struct JustId {
pub id: i64, pub id: String,
} }
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)] #[derive(Clone, Debug, FromRow)]
pub(crate) struct PageTitles { pub(crate) struct PageTitle {
pub id: i64, pub id: String,
pub title: String, pub content: String,
} }
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)] #[derive(Clone, Debug, FromRow)]
pub(crate) struct NoteRelationship {
pub parent_id: i64,
pub note_id: i64,
pub position: i64,
pub nature: String,
}
#[derive(Clone, Serialize, Deserialize, Debug, FromRow)]
pub(crate) struct RowCount { pub(crate) struct RowCount {
pub count: i64, pub count: i64,
} }
#[derive(Clone, Debug, FromRow)]
pub(crate) struct NoteRelationshipRow {
pub parent_id: String,
pub note_id: String,
pub location: i64,
pub kind: String,
}
#[derive(Clone, Debug)]
pub struct NoteRelationship {
pub parent_id: String,
pub note_id: String,
pub location: i64,
pub kind: RelationshipKind,
}
impl From<NoteRelationshipRow> for NoteRelationship {
fn from(rel: NoteRelationshipRow) -> Self {
Self {
parent_id: rel.parent_id,
note_id: rel.note_id,
location: rel.location,
kind: RelationshipKind::from(rel.kind),
}
}
}
#[derive(Clone, Debug, FromRow)]
pub(crate) struct KastenRelationshipRow {
pub note_id: String,
pub kasten_id: String,
pub kind: String,
}
#[derive(Clone, Debug)]
pub struct KastenRelationship {
pub note_id: String,
pub kasten_id: String,
pub kind: KastenRelationshipKind,
}
impl From<KastenRelationshipRow> for KastenRelationship {
fn from(rel: KastenRelationshipRow) -> Self {
Self {
kasten_id: rel.kasten_id,
note_id: rel.note_id,
kind: KastenRelationshipKind::from(rel.kind),
}
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -121,11 +247,8 @@ mod tests {
#[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().content("bar".to_string()).build().unwrap();
.uuid("foo".to_string()) assert!(newnote.id.len() > 4);
.content("bar".to_string())
.build()
.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);

15
server/nm-trees/Makefile Normal file
View File

@ -0,0 +1,15 @@
.PHONY: all
all: help
.PHONY: help
help:
@M=$$(perl -ne 'm/((\w|-)*):.*##/ && print length($$1)."\n"' Makefile | \
sort -nr | head -1) && \
perl -ne "m/^((\w|-)*):.*##\s*(.*)/ && print(sprintf(\"%s: %s\t%s\n\", \$$1, \" \"x($$M-length(\$$1)), \$$3))" Makefile
# This is necessary because I'm trying hard not to use
# any `nightly` features. But rustfmt is likely to be
# a `nightly-only` feature for a long time to come, so
# this is my hack.
fmt: ## Format the code, using the most modern version of rustfmt
rustup run nightly cargo fmt

View File

@ -12,76 +12,108 @@
mod make_tree; mod make_tree;
mod structs; mod structs;
use nm_store::{NoteStore, NoteStoreError, NewNote}; use crate::make_tree::{make_backreferences, make_note_tree};
use crate::structs::Page; use crate::structs::{Note, Page};
use crate::make_tree::make_tree; use chrono::{DateTime, Utc};
use nm_store::{NewNote, NoteStore, NoteStoreError};
#[derive(Debug)] #[derive(Debug)]
pub struct Notesmachine(pub(crate) NoteStore); pub struct Notesmachine(pub(crate) NoteStore);
type Result<T> = core::result::Result<T, NoteStoreError>; type Result<T> = core::result::Result<T, NoteStoreError>;
impl Notesmachine { pub fn make_page(foundtree: &Note, backreferences: Vec<Vec<Note>>) -> Page {
pub async fn new(url: &str) -> Result<Self> { Page {
let notestore = NoteStore::new(url).await?; slug: foundtree.id,
Ok(Notesmachine(notestore)) title: foundtree.content,
} creation_date: foundtree.creation_date,
updated_date: foundtree.updated_date,
pub async fn navigate_via_slug(&self, slug: &str) -> Result<Page> { lastview_date: foundtree.lastview_date,
let (rawpage, rawnotes) = self.0.get_page_by_slug(slug).await?; deleted_date: foundtree.deleted_date,
Ok(make_tree(&rawpage, &rawnotes)) notes: foundtree.children,
} backreferences: backreferences,
}
pub async fn get_box(&self, title: &str) -> Result<Page> {
let (rawpage, rawnotes) = self.0.get_page_by_title(title).await?;
Ok(make_tree(&rawpage, &rawnotes))
}
// TODO:
// You should be able to:
// Add a note that has no parent (gets added to "today")
// Add a note that specifies only the page (gets added to page/root)
// Add a note that has no position (gets tacked onto the end of the above)
// Add a note that specifies the date of creation.
pub async fn add_note(&self, note: &NewNote) -> Result<()> {
todo!();
}
pub async fn add_note_to_page(&self, note: &NewNote) -> Result<()> {
todo!();
}
pub async fn add_note_to_today(&self, note: &NewNote) -> Result<()> {
todo!();
}
pub async fn reference_note(&self, note_id: &str, new_parent_id: &str, new_position: i64) -> Result<()> {
todo!();
}
pub async fn embed_note(&self, note_id: &str, new_parent_id: &str, new_position: i64) -> Result<()> {
todo!();
}
pub async fn move_note(&self, note_id: &str, old_parent_id: &str, new_parent_id: &str, position: i64) -> Result<()> {
todo!();
}
pub async fn update_note(&self, note_id: &str, content: &str) -> Result<()> {
todo!();
}
pub async fn delete_note(&self, note_id: &str) -> Result<()> {
todo!();
}
} }
impl Notesmachine {
pub async fn new(url: &str) -> Result<Self> {
let notestore = NoteStore::new(url).await?;
Ok(Notesmachine(notestore))
}
pub async fn get_page_via_slug(&self, slug: &str) -> Result<Page> {
let (rawtree, rawbackreferences) = self.0.get_kasten_by_slug(slug).await?;
Ok(make_page(
&make_note_tree(&rawtree),
make_backreferences(&rawbackreferences),
))
}
pub async fn get_page(&self, title: &str) -> Result<Page> {
let (rawtree, rawbackreferences) = self.0.get_kasten_by_title(title).await?;
Ok(make_page(
&make_note_tree(&rawtree),
make_backreferences(&rawbackreferences),
))
}
// TODO:
// You should be able to:
// Add a note that has no parent (gets added to "today")
// Add a note that specifies only the page (gets added to page/root)
// Add a note that has no location (gets tacked onto the end of the above)
// Add a note that specifies the date of creation.
pub async fn add_note(&self, note: &NewNote) -> Result<String> {
let mut note = note.clone();
if note.parent_id.is_none() {
note.parent_id = self.get_today_page().await?;
}
Ok(self.0.add_note(&note))
}
// pub async fn reference_note(&self, note_id: &str, new_parent_id: &str, new_location: i64) -> Result<()> {
// todo!();
// }
//
// pub async fn embed_note(&self, note_id: &str, new_parent_id: &str, new_location: i64) -> Result<()> {
// todo!();
// }
pub async fn move_note(
&self,
note_id: &str,
old_parent_id: &str,
new_parent_id: &str,
location: i64,
) -> Result<()> {
self.0.move_note(note_id, old_parent_id, new_parent_id, location).await
}
pub async fn update_note(&self, note_id: &str, content: &str) -> Result<()> {
self.0.update_note_content(note_id, content).await
}
pub async fn delete_note(&self, note_id: &str, parent_note_id: &str) -> Result<()> {
self.0.delete_note(note_id, parent_note_id).await
}
}
// Private stuff
impl Notesmachine {
async fn get_today_page(&self) -> Result<String> {
let title = chrono::Utc::now().format("%F").to_string();
let (rawtree, _) = self.0.get_kasten_by_title(title).await?;
Ok(rawtree.id)
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use tokio; use tokio;
async fn fresh_inmemory_database() -> Notesmachine { async fn fresh_inmemory_database() -> Notesmachine {
let notesmachine = Notesmachine::new("sqlite://:memory:").await; let notesmachine = Notesmachine::new("sqlite://:memory:").await;
assert!(notesmachine.is_ok(), "{:?}", notesmachine); assert!(notesmachine.is_ok(), "{:?}", notesmachine);
let notesmachine = notesmachine.unwrap(); let notesmachine = notesmachine.unwrap();
@ -93,7 +125,7 @@ mod tests {
#[tokio::test(threaded_scheduler)] #[tokio::test(threaded_scheduler)]
async fn fetching_unfound_page_by_slug_works() { async fn fetching_unfound_page_by_slug_works() {
let notesmachine = fresh_inmemory_database().await; let notesmachine = fresh_inmemory_database().await;
let unfoundpage = notesmachine.navigate_via_slug("nonexistent-slug").await; let unfoundpage = notesmachine.get_page_via_slug("nonexistent-slug").await;
assert!(unfoundpage.is_err()); assert!(unfoundpage.is_err());
} }
@ -101,15 +133,14 @@ mod tests {
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 notesmachine = fresh_inmemory_database().await; let notesmachine = fresh_inmemory_database().await;
let newpageresult = notesmachine.get_box(&title).await; let newpageresult = notesmachine.get_page(&title).await;
assert!(newpageresult.is_ok(), "{:?}", newpageresult); assert!(newpageresult.is_ok(), "{:?}", newpageresult);
let newpage = newpageresult.unwrap(); let newpage = newpageresult.unwrap();
assert_eq!(newpage.title, title, "{:?}", newpage.title); assert_eq!(newpage.title, title, "{:?}", newpage.title);
assert_eq!(newpage.slug, "nonexistent-page", "{:?}", newpage.slug); assert_eq!(newpage.slug, "nonexistent-page", "{:?}", newpage.slug);
assert_eq!(newpage.root_note.content, "", "{:?}", newpage.root_note.content); assert_eq!(newpage.root_note.content, "", "{:?}", newpage.root_note.content);
assert_eq!(newpage.root_note.notetype, "root", "{:?}", newpage.root_note.notetype); assert_eq!(newpage.root_note.notetype, "root", "{:?}", newpage.root_note.notetype);
assert_eq!(newpage.root_note.children.len(), 0, "{:?}", newpage.root_note.children); assert_eq!(newpage.root_note.children.len(), 0, "{:?}", newpage.root_note.children);
} }
} }

View File

@ -1,8 +1,12 @@
use crate::structs::{Note, Page}; use crate::structs::{Note, Page};
use nm_store::{RawNote, RawPage}; use nm_store::NoteKind;
fn make_note_tree(rawnotes: &[RawNote], root: i64) -> Note { fn make_note_tree_from(rawnotes: &[nm_store::Note], root_id: &str) -> Note {
let the_note = rawnotes.iter().find(|note| note.id == root).unwrap().clone(); let the_note = {
let foundroots: Vec<&nm_store::Note> = rawnotes.iter().filter(|note| note.id == root_id).collect();
debug_assert!(foundroots.len() == 1);
foundroots.iter().next().unwrap().clone()
};
// The special case of the root node must be filtered out here to // The special case of the root node must be filtered out here to
// prevent the first pass from smashing the stack in an infinite // prevent the first pass from smashing the stack in an infinite
@ -11,35 +15,61 @@ fn make_note_tree(rawnotes: &[RawNote], root: i64) -> Note {
// are faster. // are faster.
let mut children = rawnotes let mut children = rawnotes
.iter() .iter()
.filter(|note| note.parent_id == root && note.id != root) .filter(|note| note.parent_id.is_some() && note.parent_id.unwrap() == root_id && note.id != the_note.id)
.map(|note| make_note_tree(rawnotes, note.id)) .map(|note| make_note_tree_from(rawnotes, &note.id))
.collect::<Vec<Note>>(); .collect::<Vec<Note>>();
children.sort_unstable_by(|a, b| a.position.cmp(&b.position)); children.sort_unstable_by(|a, b| a.location.cmp(&b.location));
Note { Note {
uuid: the_note.uuid, id: the_note.id,
parent_uuid: the_note.parent_uuid, parent_id: the_note.parent_id,
content: the_note.content, content: the_note.content,
notetype: the_note.notetype, kind: the_note.kind.to_string(),
position: the_note.position, location: the_note.location,
creation_date: the_note.creation_date, creation_date: the_note.creation_date,
updated_date: the_note.updated_date, updated_date: the_note.updated_date,
lastview_date: the_note.updated_date, lastview_date: the_note.updated_date,
deleted_date: the_note.deleted_date, deleted_date: the_note.deleted_date,
children: vec![], children: children,
} }
} }
pub(crate) fn make_tree(rawpage: &RawPage, rawnotes: &[RawNote]) -> Page { pub(crate) fn make_note_tree(rawnotes: &[nm_store::Note]) -> Note {
let the_page = rawpage.clone(); let the_root = {
let foundroots: Vec<&nm_store::Note> = rawnotes.iter().filter(|note| note.kind == NoteKind::Kasten).collect();
debug_assert!(foundroots.len() == 1);
foundroots.iter().next().unwrap().clone()
};
make_note_tree_from(&rawnotes, &the_root.id)
}
Page { fn add_child(rawnotes: &[nm_store::Note], acc: &mut Vec<Note>, note_id: &str) -> Vec<Note> {
slug: the_page.slug, let child = rawnotes
title: the_page.title, .iter()
creation_date: the_page.creation_date, .find(|note| note.parent_id.is_some() && note.parent_id.unwrap() == note_id);
updated_date: the_page.updated_date, if let Some(c) = child {
lastview_date: the_page.updated_date, acc.push(Note {
deleted_date: the_page.deleted_date, id: c.id,
root_note: make_note_tree(rawnotes, rawpage.note_id), parent_id: Some(note_id.to_string()),
content: c.content,
kind: c.kind.to_string(),
location: c.location,
creation_date: c.creation_date,
updated_date: c.updated_date,
lastview_date: c.updated_date,
deleted_date: c.deleted_date,
children: vec![],
});
add_child(rawnotes, acc, &c.id)
} else {
acc.to_vec()
} }
} }
pub(crate) fn make_backreferences(rawnotes: &[nm_store::Note]) -> Vec<Vec<Note>> {
rawnotes
.iter()
.filter(|note| note.parent_id.is_none() && note.kind == NoteKind::Kasten)
.map(|root| add_child(rawnotes, &mut Vec::<Note>::new(), &root.id))
.collect()
}

View File

@ -1,13 +1,12 @@
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize, Debug)] #[derive(Clone, Debug)]
pub struct Note { pub struct Note {
pub uuid: String, pub id: String,
pub parent_uuid: String, pub parent_id: Option<String>,
pub content: String, pub content: String,
pub position: i64, pub location: i64,
pub notetype: String, pub kind: 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>,
@ -15,7 +14,7 @@ pub struct Note {
pub children: Vec<Note>, pub children: Vec<Note>,
} }
#[derive(Clone, Serialize, Deserialize, Debug)] #[derive(Clone, Debug)]
pub struct Page { pub struct Page {
pub slug: String, pub slug: String,
pub title: String, pub title: String,
@ -23,5 +22,6 @@ pub struct Page {
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>>,
pub root_note: Note, pub notes: Vec<Note>,
pub backreferences: Vec<Vec<Note>>,
} }