Struct Db

Source
pub struct Db { /* private fields */ }
Expand description

Container for the database. Usually only one is used per application.

§Examples

use vdb::{Db, Entry};
let mut db = Db::new("test-db");
let _row_id = db.add_row(vec![Entry::new_string("mundo", "world")]);

Implementations§

Source§

impl Db

Source

pub fn new(filename: &str) -> Db

Create new database in memory. The file is not created until save() is called.

Examples found in repository?
examples/notebook.rs (line 105)
100fn main() {
101    let db_name = "notebook";
102    let mut db = if let Ok(db) = Db::load(db_name) {
103        db
104    } else {
105        Db::new(db_name)
106    };
107    main_loop(&mut db);
108}
Source

pub fn load(filename: &str) -> Result<Db, Box<dyn Error>>

Load a database file from the filesystem under the subdirectory save/.

§Errors

May return errors from external modules while opening the file or parsing the contents.

Examples found in repository?
examples/notebook.rs (line 102)
100fn main() {
101    let db_name = "notebook";
102    let mut db = if let Ok(db) = Db::load(db_name) {
103        db
104    } else {
105        Db::new(db_name)
106    };
107    main_loop(&mut db);
108}
Source

pub fn save(&mut self) -> Result<(), Box<dyn Error>>

Save database under the subdirectory save/ with the same name it was opened or created with. The subdirectory save/ must exist.

Examples found in repository?
examples/notebook.rs (line 90)
80fn main_loop(db: &mut Db) {
81    let mut input = "".to_string();
82    print_menu();
83    while let Ok(_bytes_read) = io::stdin().read_line(&mut input) {
84        let trimmed = input.trim();
85        match trimmed {
86            "l" => list_entries(db),
87            "e" => new_entry(db),
88            "d" => delete_entry(db),
89            "" | "q" => {
90                let _ = db.save();
91                break;
92            }
93            _ => (),
94        }
95        print_menu();
96        input.clear();
97    }
98}
Source

pub fn get_name(&self) -> String

Returns the filename of the database

Source

pub fn db_string(v: &str) -> Data

Returns a new Data::DbString

Examples found in repository?
examples/notebook.rs (line 60)
49fn delete_entry(db: &mut Db) {
50    println!("Enter title to delete:");
51    print!("> ");
52    io::stdout().flush().unwrap();
53
54    let mut input = "".to_string();
55    let title = {
56        let _bytes_read = io::stdin().read_line(&mut input).unwrap();
57        input.trim()
58    };
59    if !title.is_empty() {
60        let row_ids = db.find_row_ids_by_value("title", &Db::db_string(title));
61        db.delete_rows(&row_ids);
62    } else {
63        println!("Abort.");
64    }
65}
Source

pub fn db_i32(v: i32) -> Data

Returns a new Data::DbI32

Source

pub fn find_first_i32(&self, name: &str) -> Option<i32>

Find a i32 by name

use vdb::{Db, Entry};
let mut db = Db::new("test-db");
let name = "yoyo";
let value = 7;
let _row_id = db.add_row(vec![Entry::new_i32(name, value)]);
assert_eq!(db.find_first_i32(name), Some(value));
Source

pub fn find_first_string(&self, name: &str) -> Option<String>

Find a string by name

use vdb::{Db, Entry};
let mut db = Db::new("test-db");
let name = "yoyo";
let value = "lila";
let _row_id = db.add_row(vec![Entry::new_string(name, value)]);
assert_eq!(db.find_first_string(name), Some(value.to_string()));
Source

pub fn db_datetime(v: &str) -> Result<Data, Box<dyn Error>>

Parse &str into a DbDateTime. The format string is %Y-%m-%d %H:%M:%S.

Source

pub fn add_i32(&mut self, name: &str, value: i32) -> RowId

Add a new row with one i32

Source

pub fn add_string(&mut self, name: &str, value: &str) -> RowId

Add a new row with one string

Source

pub fn add_row(&mut self, entries: Vec<Entry>) -> RowId

Add a new row with multiple entries.

Examples found in repository?
examples/notebook.rs (lines 40-43)
23fn new_entry(db: &mut Db) {
24    println!("Enter title:");
25    print!("> ");
26    io::stdout().flush().unwrap();
27
28    let mut input = "".to_string();
29    let title = {
30        let _bytes_read = io::stdin().read_line(&mut input).unwrap();
31        input.trim()
32    };
33    if !title.is_empty() {
34        println!("Enter text:");
35        print!("> ");
36        io::stdout().flush().unwrap();
37        let mut input = "".to_string();
38        let _bytes_read = io::stdin().read_line(&mut input).unwrap();
39        let text = input.trim();
40        db.add_row(vec![
41            Entry::new_string("title", title),
42            Entry::new_string("text", text),
43        ]);
44    } else {
45        println!("Abort.");
46    }
47}
Source

pub fn add_or_update_entry(&mut self, row_id: RowId, new_entry: Entry)

Add a single entry to an existing row. An existing entry with the same name is overwritten. If multiple entries with the same name exist, they will be overwritten.

Source

pub fn remove_by_name(&mut self, row_id: RowId, name: &str)

Removes all entries with name ‘name’ and row ‘row_id’. Does not delete the whole row and leaves entries with other names.

Source

pub fn remove_by_row_id(&mut self, row_id: RowId)

Removes all entries with row ‘row_id’

Source

pub fn add_row_id_entry(&mut self, row_id: RowId, entry: Entry)

Add a single entry to an existing row. Does not check if entry exists.

Source

pub fn delete_rows(&mut self, row_ids: &[RowId])

Delete rows in the database

§Examples
use vdb::{Db, Entry};
let mut db = Db::new("test-db");
let row_1 = db.add_row(vec![
        Entry::new_string("word", "cocina"),
        Entry::new_string("translation", "cuisine"),
        Entry::new_string("translation", "kitchen"),
]);
let row_2 = db.add_row(vec![
        Entry::new_string("word", "coche"),
        Entry::new_string("translation", "car"),
]);
let coche = db.find_first_row_id_by_value("word", &Db::db_string("coche"));
assert_eq!(coche, Some(row_2));
db.delete_rows(&[row_1, row_2]);
let no_coche = db.find_first_row_id_by_value("word", &Db::db_string("coche"));
assert_eq!(no_coche, None);
Examples found in repository?
examples/notebook.rs (line 61)
49fn delete_entry(db: &mut Db) {
50    println!("Enter title to delete:");
51    print!("> ");
52    io::stdout().flush().unwrap();
53
54    let mut input = "".to_string();
55    let title = {
56        let _bytes_read = io::stdin().read_line(&mut input).unwrap();
57        input.trim()
58    };
59    if !title.is_empty() {
60        let row_ids = db.find_row_ids_by_value("title", &Db::db_string(title));
61        db.delete_rows(&row_ids);
62    } else {
63        println!("Abort.");
64    }
65}
Source

pub fn delete_entry_all(&mut self, name: &str)

Delete all entries with this name in the whole database. Does not delete all rows. Deletes matching entries in the row. The row will be kept if there are entries left, otherwise deleted.

Source

pub fn find_row_ids_by_name(&self, name: &str) -> Vec<RowId>

Return row_ids of entries where an entry with name “name” exists.

Examples found in repository?
examples/notebook.rs (line 9)
8fn list_entries(db: &mut Db) {
9    let row_ids = db.find_row_ids_by_name("title");
10    let entries = db.entries_from_row_ids(&row_ids, &["title", "text"]);
11    if entries.is_empty() {
12        println!();
13        println!("No entries.");
14    } else {
15        for entry in &entries {
16            if entry.len() >= 2 {
17                println!("{}: {}", entry[0].value, entry[1].value);
18            }
19        }
20    }
21}
Source

pub fn find_row_ids_by_value(&self, name: &str, value: &Data) -> Vec<RowId>

Return row_ids of entries that are exactly “value”. For partial string matches, use Predicates.

Examples found in repository?
examples/notebook.rs (line 60)
49fn delete_entry(db: &mut Db) {
50    println!("Enter title to delete:");
51    print!("> ");
52    io::stdout().flush().unwrap();
53
54    let mut input = "".to_string();
55    let title = {
56        let _bytes_read = io::stdin().read_line(&mut input).unwrap();
57        input.trim()
58    };
59    if !title.is_empty() {
60        let row_ids = db.find_row_ids_by_value("title", &Db::db_string(title));
61        db.delete_rows(&row_ids);
62    } else {
63        println!("Abort.");
64    }
65}
Source

pub fn find_first_row_id_by_name(&self, name: &str) -> Option<RowId>

Return reference to first entry found in a given row.

Source

pub fn find_first_row_id_by_value( &self, name: &str, value: &Data, ) -> Option<RowId>

Return reference to first entry found in a given row.

Source

pub fn find_first_entry_by_name( &self, row_id: RowId, name: &str, ) -> Option<Entry>

Return reference to first entry found in a given row.

Source

pub fn find_by_predicate(&self, predicate: &Predicate) -> Vec<RowId>

Source

pub fn find_row_ids_by_predicate( &self, predicates: &[Predicate], max_results: Option<usize>, ) -> Vec<RowId>

Returns all rows if no predicates are given. The first predicate is evaluated first and should have high selectivity, i. e. evaluate to a small number of rows, to improve execution time. The number of results can be limited with Some(max_results)

§Examples
// Like SQL "select name, value from testdb where name='coche' limit 15"
use vdb::{Data, Db, Entry, Predicate, RowId};
let mut db = Db::new("test-db");
let _id = db.add_row(vec![
    Entry {
        name: String::from("set"),
        value: Db::db_string("es-en"),
    },
    Entry {
        name: String::from("name"),
        value: Db::db_string("coche"),
    },
    Entry {
        name: String::from("value"),
        value: Db::db_string("car"),
    },
]);
let predicates = vec![Predicate::new_equal_string("name", "coche")];
let row_ids = db.find_row_ids_by_predicate(&predicates, Some(15));
assert_eq!(row_ids, [RowId(1)]);
assert_eq!(db.entries_from_row_ids(&row_ids, &["name", "value"])[0][0], Entry::new_string("name", "coche"));

See also find_entries_by_predicate()

Source

pub fn find_all_row_ids(&self) -> Vec<RowId>

Returns all rows in the database

Source

pub fn entries_from_row_ids( &self, row_ids: &[RowId], names: &[&str], ) -> Vec<Vec<Entry>>

Returns entries for given row_ids.

Examples found in repository?
examples/notebook.rs (line 10)
8fn list_entries(db: &mut Db) {
9    let row_ids = db.find_row_ids_by_name("title");
10    let entries = db.entries_from_row_ids(&row_ids, &["title", "text"]);
11    if entries.is_empty() {
12        println!();
13        println!("No entries.");
14    } else {
15        for entry in &entries {
16            if entry.len() >= 2 {
17                println!("{}: {}", entry[0].value, entry[1].value);
18            }
19        }
20    }
21}

Trait Implementations§

Source§

impl Clone for Db

Source§

fn clone(&self) -> Db

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Db

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Db

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for Db

Source§

fn eq(&self, other: &Db) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Db

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Db

Auto Trait Implementations§

§

impl Freeze for Db

§

impl RefUnwindSafe for Db

§

impl Send for Db

§

impl Sync for Db

§

impl Unpin for Db

§

impl UnwindSafe for Db

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,