lnotebook 0.1.9

asynchronous API to creating notebooks that stores notes in a database
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! This module contains functions used to control a notebook.

pub mod execute_commands;
use crate::errors;
use errors::NotebookError;

use sqlx::{self, PgPool};
use tracing::{event, Level};

/// This is a `struct` that containing information about notes.
///
/// This `struct` is returned by `functions` from [`command` module][`crate::commands`]:
/// * [`add`]
/// * [`upd`]
/// * [`upd_notename`]
/// * [`display`]
/// ### Example
/// ```rust,no run
/// async fn struct_example(pool: &PgPool) -> Result<(), NotebookError> {
///     // `add()` returns struct `Note` that we can use later as we wish
///     let row = add("early_sleep", "I'll go to bed early today", pool).await?;
///
///     assert_eq!("early_sleep", row.note_name);
///
///     Ok(())
/// }
pub struct Note {
    pub id: i32,
    pub note: Option<String>,
    pub note_name: String,
}

impl Note {
    /// Return field `note` as `&str`.
    ///
    /// If note is `Some()`, returns content of note as `&str`; else returns empty `&str`("")
    pub async fn note_str(&mut self) -> String {
        if let Some(some_note) = &self.note {
            some_note.to_owned()
        } else {
            "".to_owned()
        }
    }
}

/// Displays the requested note.
/// ### Returns
/// * Errors
///     * [`NotebookError::Sqlx`] error from [`sqlx::Error`]
pub async fn display(notename: &str, pool: &PgPool) -> Result<(), NotebookError> {
    let mut row = select_one(notename, pool).await?;
    let row_note = row.note_str().await;

    event!(
        Level::INFO,
        "Requested note:\nID: {}\nName: {}\nData:\n{}",
        row.id,
        row.note_name,
        row_note
    );

    Ok(())
}

/// Displays all total notes in notebook.
/// ### Returns
/// * Errors
///     * [`NotebookError::Sqlx`][NotebookError] error from [`sqlx::Error`]
pub async fn display_all(pool: &PgPool) -> Result<(), NotebookError> {
    let rows = sqlx::query!(
        "
SELECT * 
FROM notebook
        "
    )
    .fetch_all(pool)
    .await?;

    event!(Level::INFO, "All notes in notebook:");
    rows.iter().for_each(|row| {
        let row_note = if let Some(n) = &row.note { n } else { "" };

        event!(
            Level::INFO,
            "\nID: {}:\nName: {}\nData:\n{}",
            row.id,
            row.note_name,
            row_note
        );
    });

    Ok(())
}

/// Adds and returns a new note to notebook.
/// ### Returns
/// * Ok
///     * [Note] that was added into notebook
/// * Errors
///     * [`NotebookError::AlreadyTaken`] error if a note with the same name already exists
///     * [`NotebookError::Sqlx`] error from [`sqlx::Error`]
/// if any other [`sqlx::Error`] occurs
/// ### Example
/// ```rust,no run
/// async fn add_example(pool: &PgPool) -> Result<(), NotebookError> {
///     add("add_note", "Added a some note so you don't forget", pool).await?;
///
///     let row = select_one("add_note", pool).await?;
///
///     assert_eq!("add", row.note_name);
///
///     Ok(())
/// }
/// ```
pub async fn add(notename: &str, note: &str, pool: &PgPool) -> Result<Note, NotebookError> {
    match sqlx::query!(
        "
INSERT INTO notebook (note_name, note)
VALUES ( $1, $2 )
RETURNING id, note_name, note
        ",
        notename,
        note
    )
    .fetch_one(pool)
    .await
    {
        Ok(row) => {
            event!(
                Level::INFO,
                "Insert note with name `{}` with data `{}` into notebook",
                notename,
                note
            );
            Ok(Note {
                id: row.id,
                note: row.note,
                note_name: row.note_name,
            })
        }
        Err(err) => {
            if let Some(db_err) = err.as_database_error() {
                if let Some(code) = db_err.code() {
                    if code == "23505" {
                        return Err(NotebookError::AlreadyTaken {
                            notename: notename.to_owned(),
                        });
                    }
                }
            }
            Err(err.into())
        }
    }
}

/// Deletes the requested note.
/// ### Returns
/// * Errors
///     * [`NotebookError::Sqlx`][NotebookError] error from [`sqlx::Error`]
/// ### Example
/// ```rust,no run
/// async fn delete_example(pool: &PgPool) -> Result<(), NotebookError> {
///     add("bad_cat", "Buy new slippers. The old ones were ruined by the cat", pool).await?;
///
///     del(&row.note_name, pool).await?;
///
///     // Should return error because note `bad_cat` is not exist
///     select_one("bad_cat", pool).await?;
///
///     Ok(())
/// }
/// ```
pub async fn del(notename: &str, pool: &PgPool) -> Result<(), NotebookError> {
    match sqlx::query!(
        "
DELETE FROM notebook
WHERE note_name = $1
RETURNING id, note_name, note
        ",
        notename
    )
    .fetch_one(pool)
    .await
    {
        Ok(row) => {
            let row_note = if let Some(n) = &row.note { n } else { "" };

            event!(
                Level::INFO,
                "Deleteing note:\nID: {}\nName: {}\nData:\n{}",
                row.id,
                notename,
                row_note
            );

            Ok(())
        }
        Err(err) => Err(NotebookError::Sqlx(err)),
    }
}

/// Deletes all total notes in notebook.
/// ### Returns
/// * Errors
///     * [`NotebookError::Sqlx`][NotebookError] error from [`sqlx::Error`]
/// ### Example
/// ```rust,no run
/// async fn delete_all_example(pool: &PgPool) -> Result<(), NotebookError> {
///     // Adding new notes
///     add(
///         "bad_cat",
///         "Buy new slippers. the old ones were ruined by the cat",
///         pool,
///     )
///     .await?;
///     add(
///         "cool_cat",
///         "Don't forget to post a photo of my cool cat",
///         pool,
///     )
///     .await?;
///     add("empty", "", pool).await?;
///
///     del_all(pool).await?;
///
///     // Should display empty list
///     display_all(pool).await?;
///
///     Ok(())
/// }
/// ```
pub async fn del_all(pool: &PgPool) -> Result<(), NotebookError> {
    match sqlx::query!(
        "
DELETE FROM notebook
RETURNING id, note_name, note
        "
    )
    .fetch_all(pool)
    .await
    {
        Ok(del_rows) => {
            del_rows.iter().for_each(|row| {
                let row_note = if let Some(n) = &row.note { n } else { "" };

                event!(
                    Level::INFO,
                    "Deleting ID: {}; Name: {}; Data:\n{}",
                    row.id,
                    row.note_name,
                    row_note
                )
            });

            Ok(())
        }
        Err(err) => Err(NotebookError::Sqlx(err)),
    }
}

/// Clears the content of requested note.
/// ### Returns
/// * Errors
///     * [`NotebookError::Sqlx`][NotebookError] error from [`sqlx::Error`]
/// ### Example
/// ```rust,no run
/// async fn delete_example(pool: &PgPool) -> Result<(), NotebookError> {
///     add("clear_note", "meow meow meow meow", pool).await?;
///
///     clear("clear_note", pool).await?;
///     let row = select_one("clear_note", pool).await?;
///
///     assert_eq!("", row.note_str().await);
///
///     Ok(())
/// }
/// ```
pub async fn clear(notename: &str, pool: &PgPool) -> Result<(), NotebookError> {
    match sqlx::query!(
        "
UPDATE notebook
SET note = ''
WHERE note_name = $1
RETURNING note_name
        ",
        notename
    )
    .fetch_one(pool)
    .await
    {
        Ok(_) => {
            event!(Level::INFO, "Content of `{}` was cleared", notename);

            Ok(())
        }
        Err(err) => Err(NotebookError::Sqlx(err)),
    }
}

/// Updates content of note and returns updated note.
/// ### Returns
/// * Ok
///     * [Note] that was updated
/// * Errors
///     * [`NotebookError::Sqlx`][NotebookError] error from [`sqlx::Error`]
/// ### Example
/// ```rust,no run
/// async fn upd_example(pool: &PgPool) -> Result<(), NotebookError> {
///    add("wrong_note", "Thos is erong nlte", pool).await?;
///
///    // Returns updated note
///    let mut upd_row = upd("wrong_note", "This is NOT wrong note", pool).await?;
///
///    assert_eq!("This is NOT wrong note", upd_row.note_str().await);
///
///    Ok(())
/// }
/// ```
pub async fn upd(notename: &str, new_note: &str, pool: &PgPool) -> Result<Note, NotebookError> {
    match sqlx::query!(
        "
UPDATE notebook
SET note = $1
WHERE note_name = $2
RETURNING id, note_name, note
        ",
        new_note,
        notename,
    )
    .fetch_one(pool)
    .await
    {
        Ok(upd_row) => {
            event!(Level::INFO, "Update `{}` data to:\n{}", notename, new_note,);

            Ok(Note {
                id: upd_row.id,
                note_name: upd_row.note_name,
                note: upd_row.note,
            })
        }
        Err(err) => Err(NotebookError::Sqlx(err)),
    }
}

/// Updates notename and returns note that name was updated.
/// ### Returns
/// * Ok
///     * [Note] that name was updated
/// * Errors
///     * [`NotebookError::Sqlx`][NotebookError] error from [`sqlx::Error`]
/// ### Example
/// ```rust,no run
/// async fn upd_notename_example(pool: &PgPool) -> Result<(), NotebookError> {
///    add("wrlng_nptenAme", "", pool).await?;
///
///    // Returns updated notename
///    let upd_row = upd_notename("wrlng_nptenAme", "not_wrong_name", pool).await?;
///
///    assert_eq!("not_wrong_name", upd_row.note_name);
///
///    Ok(())
/// }
/// ```
pub async fn upd_notename(
    notename: &str,
    new_notename: &str,
    pool: &PgPool,
) -> Result<Note, NotebookError> {
    match sqlx::query!(
        "
UPDATE notebook
SET note_name = $1
WHERE note_name = $2
RETURNING id, note_name, note
        ",
        new_notename,
        notename
    )
    .fetch_one(pool)
    .await
    {
        Ok(upd_row) => {
            event!(
                Level::INFO,
                "Update notename\nFrom: {}\nTo: {}",
                notename,
                new_notename
            );

            Ok(Note {
                id: upd_row.id,
                note_name: upd_row.note_name,
                note: upd_row.note,
            })
        }
        Err(err) => Err(NotebookError::Sqlx(err)),
    }
}

/// Returns the requested note.
/// ### Returns
/// * Ok
///     * [Note]
/// * Errors
///     * [`NotebookError::Sqlx`][NotebookError] error from [`sqlx::Error`]
pub async fn select_one(notename: &str, pool: &PgPool) -> Result<Note, NotebookError> {
    let row = sqlx::query!(
        "
SELECT *
FROM notebook
WHERE note_name = $1
        ",
        notename
    )
    .fetch_one(pool)
    .await?;

    Ok(Note {
        id: row.id,
        note: row.note,
        note_name: row.note_name,
    })
}