notesmachine/server/nm-store/src/store.rs

215 lines
6.4 KiB
Rust

use crate::errors::NoteStoreError;
use crate::row_structs::{RawNote, RawPage};
use chrono;
use friendly_id;
use sqlx;
use sqlx::{
sqlite::{Sqlite, SqlitePool},
Done, Executor,
};
use std::sync::Arc;
/// A handle to our Sqlite database.
#[derive(Clone, Debug)]
pub struct NoteStore(Arc<SqlitePool>);
type NoteResult<T> = core::result::Result<T, NoteStoreError>;
type SqlResult<T> = sqlx::Result<T>;
impl NoteStore {
pub async fn new(url: &str) -> NoteResult<Self> {
let pool = SqlitePool::connect(url).await?;
Ok(NoteStore(Arc::new(pool)))
}
// Erase all the data in the database and restore it
// to its original empty form. Do not use unless you
// really, really want that to happen.
pub async fn reset_database(&self) -> NoteResult<()> {
reset_databate(&*self.0).await
}
/// Fetch page by slug
///
/// 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
/// 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
/// requested page, return a basic NotFound.
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 mut tx = self.0.begin().await?;
// let notes = sqlx::query_as(select_note_collection_for_root)
// .bind(page.note_id)
// .fetch(&tx)
// .await?;
tx.commit().await?;
Ok((page, vec![]))
}
pub async fn get_page_by_title(&self, title: &str) -> NoteResult<(RawPage, Vec<RawNote>)> {
let mut tx = self.0.begin().await?;
let page = match select_page_by_title(&mut tx, title) {
Ok(page) => page,
Err(sqlx::Error::NotFound) => {
match create_page_for_title(&mut tx, title) {
Ok(page) => page,
Err(e) => return Err(e)
}
},
Err(e) => return Err(e),
};
// Todo: Replace vec with the results of the CTE
return Ok((page, vec![]))
}
}
// ___ _ _
// | _ \_ _(_)_ ____ _| |_ ___
// | _/ '_| \ V / _` | _/ -_)
// |_| |_| |_|\_/\__,_|\__\___|
//
// I'm putting a lot of faith in Rust's ability to inline stuff. I'm
// sure this is okay. But really, this lets the API be clean and
// coherent and easily readable, and hides away the gnarliness of some
// of the SQL queries.
async fn select_page_by_slug<'e, E>(executor: E, slug: &str) -> SqlResult<RawPage>
where
E: 'e + Executor<'e, 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 slug=?;"
);
sqlx::query_as(select_one_page_by_slug_sql)
.bind(&slug)
.fetch_one(&mut executor)
.await?
}
async fn select_page_by_title<'e, E>(executor: E, title: &str) -> SqlResult<RawPage>
where
E: 'e + Executor<'e, 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=?;"
);
sqlx::query_as(select_one_page_by_title_sql)
.bind(&title)
.fetch_one(&mut executor)
.await?
}
async fn reset_database<'e, E>(executor: E) -> SqlResult<()>
where
E: 'e + Executor<'e, Database = Sqlite>,
{
let initialize_sql = include_str!("sql/initialize_database.sql");
sqlx::query(initialize_sql).execute(&*self.0).await?
}
async fn get_note_collection_for_root<'e, E>(executor: E, root: i64) -> SqlResult<Vec<RawNotes>>
where
E: 'e + Executor<'e, Database = Sqlite>,
{
let select_note_collection_for_root = include_str!("sql/select_note_collection_for_root.sql");
sqlx::query_as(select_note_collection_for_root)
.fetch(&*self.0)
.await?
}
async fn insert_one_new_note<'e, E>(executor: E, note: &NewNote) -> SqlResult<i64> where
E: 'e + Executor<'e, Database = Sqlite>,
{
let insert_one_note_sql = concat!(
"INSERT INTO notes ( ",
" uuid, ",
" content, ",
" notetype, ",
" creation_date, ",
" updated_date, ",
" lastview_date) ",
"VALUES (?, ?, ?, ?, ?, ?);");
Ok(sqlx::query(insert_one_note_sql)
.bind(&note.uuid)
.bind(&note.content)
.bind(&note.note_type)
.bind(&note.creation_date)
.bind(&note.updated_date)
.bind(&note.lastview_date)
.execute(&mut tx)
.await?
.last_insert_rowid())
}
// Given an initial string and an existing collection of slugs,
// generate a new slug that does not conflict with the current
// collection.
async fn generate_slug<'e, E>(executor: E, title: &str) -> SqlResult<String>
where
E: 'e + Executor<'e, Database = Sqlite>,
{
lazy_static! {
static ref RE_STRIP_NUM: Regex = Regex::new(r"-\d+$").unwrap();
}
lazy_static! {
static ref RE_CAP_NUM: Regex = Regex::new(r"-(\d+)$").unwrap();
}
let initial_slug = slugify::slugify(title);
let sample_slug = RE_STRIP_NUM.replace_all(slug, "");
let similar_slugs: Vec<JustSlugs> = sqlx::query("SELECT slug FROM pages WHERE slug LIKE '?%';")
.bind(&sample_slug)
.execute(executor)
.await?;
let slug_counters = similar_slugs
.iter()
.map(|slug| RE_CAPNUM.captures(slug.slug))
.filter_map(|cap| cap.get(1).unwrap().parse::<u32>().unwrap())
.collect();
match slug_counters.len() {
0 => Ok(initial_slug),
_ => {
slug_counters.sort_unstable();
return Ok(format!("{}-{}", initial_slug, slug_counters.pop() + 1))
}
}
}
async fn insert_one_new_page<'e, E>(executor: E, page: &NewPage) -> SqlResult<i64>
where
E: 'e + Executor<'e, Database = Sqlite>,
{
let insert_one_page_sql = concat!(
"INSERT INTO pages ( ",
" slug, ",
" title, ",
" note_id, ",
" creation_date, ",
" updated_date, ",
" lastview_date) ",
"VALUES (?, ?, ?, ?, ?, ?);");
Ok(sqlx::query(insert_one_page_sql)
.bind(&page.slug)
.bind(&page.title)
.bind(&page.note_id)
.bind(&page.creation_date)
.bind(&page.updated_date)
.bind(&page.lastview_date)
.execute(&mut tx)
.await?
.last_insert_rowid())
}
async fn create_page_for_title<'e, E>(executor: E, title: &str) -> SqlResult<RawPage> where
E: 'e + Executor<'e, Database = Sqlite>,
{
todo!()
}