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
use core::fmt;
use std::error::Error;
use std::io;
use std::path::Path;

use diesel::result::DatabaseErrorKind;
use diesel::{
    result::Error as DieselError, Connection, ConnectionError, ExpressionMethods, QueryDsl,
    RunQueryDsl, SqliteConnection,
};

pub use crate::porter::{CsvWriter, ExporterError};
use crate::vocab_store::entires::Entries;
pub use guess::Guess;
use guesses::Guesses;
pub use translation::Translation;

mod entires;
mod guess;
mod guesses;
mod translation;

const INIT: &str = include_str!("migrations/2020-02-22_vocab_table.sql");

#[derive(Debug)]
pub enum VocabStoreError {
    ConnectionError(ConnectionError),
    NotInitialised,
    AlreadyInitialised,
    DuplicateEntry,
    DatabaseError(DieselError),
    UnexpectedError(Box<dyn Error>),
    ExporterError(ExporterError),
    ReconciliationError,
}

impl fmt::Display for VocabStoreError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        write!(f, "{:?}", self)
    }
}

impl Error for VocabStoreError {}

impl From<ConnectionError> for VocabStoreError {
    fn from(e: ConnectionError) -> Self {
        VocabStoreError::ConnectionError(e)
    }
}

impl From<std::io::Error> for VocabStoreError {
    fn from(e: io::Error) -> Self {
        match e.kind() {
            io::ErrorKind::NotFound => VocabStoreError::NotInitialised,
            _ => VocabStoreError::UnexpectedError(Box::new(e)),
        }
    }
}

impl From<DieselError> for VocabStoreError {
    fn from(e: DieselError) -> Self {
        match e {
            DieselError::DatabaseError(DatabaseErrorKind::UniqueViolation, _) => {
                VocabStoreError::DuplicateEntry
            }
            _ => VocabStoreError::DatabaseError(e),
        }
    }
}

impl From<ExporterError> for VocabStoreError {
    fn from(e: ExporterError) -> Self {
        VocabStoreError::ExporterError(e)
    }
}

type VSResult<T> = Result<T, VocabStoreError>;

pub struct VocabStore(SqliteConnection);

impl VocabStore {
    pub fn from(file: &str) -> VSResult<VocabStore> {
        if !Path::new(file).exists() {
            return Err(VocabStoreError::NotInitialised);
        }
        let connection = SqliteConnection::establish(file)?;
        Ok(VocabStore(connection))
    }

    pub fn init(file: &str) -> VSResult<VocabStore> {
        if Path::new(file).exists() {
            return Err(VocabStoreError::AlreadyInitialised);
        }
        let connection = SqliteConnection::establish(file)?;
        diesel::sql_query(INIT).execute(&connection)?;
        Ok(VocabStore(connection))
    }

    pub fn add(&self, translation: &Translation) -> VSResult<()> {
        diesel::insert_into(crate::schema::translations::table)
            .values(translation)
            .execute(&self.0)?;
        Ok(())
    }

    pub fn save(&self, translation: &Translation) -> VSResult<()> {
        diesel::replace_into(crate::schema::translations::table)
            .values(translation)
            .execute(&self.0)?;
        Ok(())
    }

    pub fn find_local(&self, find_local: &str) -> VSResult<Option<Translation>> {
        use crate::schema::translations::dsl::*;

        Ok(translations
            .filter(local.eq(find_local))
            .limit(1)
            .load::<Translation>(&self.0)?
            .pop())
    }

    pub fn guesses(&self) -> Guesses {
        Guesses::new(&self.0)
    }

    pub fn entries(&self) -> Entries {
        Entries::new(&self.0)
    }
}

#[cfg(test)]
mod test {
    use std::fs;

    use diesel::{Connection, RunQueryDsl, SqliteConnection};

    use crate::{Translation, VocabStore, VocabStoreError};

    const TEST_FILE: &str = "test.sqlite";

    #[test]
    fn test_from() {
        let _ = fs::remove_file(&TEST_FILE); // Ok if it fails;
        SqliteConnection::establish(&TEST_FILE).unwrap();
        assert!(VocabStore::from(&TEST_FILE).is_ok());
    }

    #[test]
    fn test_from_error() {
        let _ = fs::remove_file(&TEST_FILE); // Ok if it fails;
        match VocabStore::from(&TEST_FILE) {
            Err(VocabStoreError::NotInitialised) => {}
            _ => assert!(false, "VocabStore did not return NotInitialised error"),
        }
    }

    #[test]
    fn test_init() {
        let _ = fs::remove_file(&TEST_FILE); // Ok if it fails;
        assert!(VocabStore::init(&TEST_FILE).is_ok());
    }

    #[test]
    fn test_init_error() {
        let _ = fs::remove_file(&TEST_FILE); // Ok if it fails;
        SqliteConnection::establish(&TEST_FILE).unwrap();
        match VocabStore::init(&TEST_FILE) {
            Err(VocabStoreError::AlreadyInitialised) => {}
            _ => assert!(false, "VocabStore did not return AlreadyInitialised error"),
        }
    }

    #[test]
    fn test_add() {
        use crate::schema::translations::dsl::*;

        let _ = fs::remove_file(&TEST_FILE); // Ok if it fails;
        let vocab_store = VocabStore::init(&TEST_FILE).unwrap();
        let translation = Translation::new("yes", "はい");
        vocab_store.add(&translation).unwrap();

        let conn = SqliteConnection::establish(&TEST_FILE).unwrap();
        let t: Translation = translations.load(&conn).unwrap().pop().unwrap();

        assert_eq!(t.local, "yes");
        assert_eq!(t.foreign, "はい");
    }

    #[test]
    fn test_add_duplicate_local() {
        let _ = fs::remove_file(&TEST_FILE); // Ok if it fails;
        let vocab_store = VocabStore::init(&TEST_FILE).unwrap();
        let translation = Translation::new("yes", "はい");
        vocab_store.add(&translation).unwrap();
        let different_foreign = Translation::new("no", "はい");
        match vocab_store.add(&different_foreign) {
            Err(VocabStoreError::DuplicateEntry) => {}
            Err(e) => assert!(
                false,
                "VocabStore did not return DuplicateEntry error: {:?}",
                e
            ),
            Ok(_) => assert!(false, "VocabStore did not return DuplicateEntry error"),
        }
    }

    #[test]
    fn test_add_duplicate_foreign() {
        let _ = fs::remove_file(&TEST_FILE); // Ok if it fails;
        let vocab_store = VocabStore::init(&TEST_FILE).unwrap();
        let translation = Translation::new("yes", "はい");
        vocab_store.add(&translation).unwrap();
        let different_local = Translation::new("no", "はい");
        match vocab_store.add(&different_local) {
            Err(VocabStoreError::DuplicateEntry) => {}
            Err(e) => assert!(
                false,
                "VocabStore did not return DuplicateEntry error: {:?}",
                e
            ),
            Ok(_) => assert!(false, "VocabStore did not return DuplicateEntry error"),
        }
    }

    #[test]
    fn test_save() {
        use crate::schema::translations::dsl::*;

        let _ = fs::remove_file(&TEST_FILE); // Ok if it fails;
        let vocab_store = VocabStore::init(&TEST_FILE).unwrap();
        let mut translation = Translation::new("yes", "はい");
        vocab_store.add(&translation).unwrap();

        let conn = SqliteConnection::establish(&TEST_FILE).unwrap();
        let t: Translation = translations.load(&conn).unwrap().pop().unwrap();

        assert_eq!(t.guesses_foreign_total, 0);

        translation.guesses_foreign_total = 2;
        vocab_store.save(&translation).unwrap();

        let conn = SqliteConnection::establish(&TEST_FILE).unwrap();
        let t: Translation = translations.load(&conn).unwrap().pop().unwrap();

        assert_eq!(t.guesses_foreign_total, 2);
    }
}