chewing 0.12.0

The Chewing (酷音) intelligent Zhuyin input method.
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
use std::{
    error::Error,
    fmt::Display,
    path::{Path, PathBuf},
    str,
};

use log::debug;
use rusqlite::{Connection, Error as RusqliteError, OpenFlags, OptionalExtension, params};

use super::{
    BuildDictionaryError, Dictionary, DictionaryBuilder, DictionaryInfo, Entries, LookupStrategy,
    Phrase, UpdateDictionaryError,
};
use crate::{dictionary::DictionaryUsage, exn::ResultExt, zhuyin::Syllable};

const APPLICATION_ID: u32 = 0x43484557; // 'CHEW' in big-endian
const USER_VERSION: u32 = 0;

/// A slice that can be converted to a slice of syllables.
trait SyllableSlice {
    fn to_bytes(&self) -> Vec<u8>;
}

impl SyllableSlice for &[Syllable] {
    fn to_bytes(&self) -> Vec<u8> {
        let mut syllables_bytes = vec![];
        self.iter().for_each(|syl| {
            syllables_bytes.extend_from_slice(&syl.as_ref().to_u16().to_le_bytes())
        });
        syllables_bytes
    }
}

/// TODO: doc
#[derive(Debug)]
#[non_exhaustive]
pub enum SqliteDictionaryError {
    /// TODO: doc
    SqliteError {
        /// TODO: doc
        source: RusqliteError,
    },
    /// TODO: doc
    MissingTable {
        /// TODO: doc
        table: String,
    },
    ReadOnly,
}

impl Display for SqliteDictionaryError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SqliteDictionaryError::SqliteError { source: _ } => {
                write!(f, "failed to perform sqlite operation")
            }
            SqliteDictionaryError::MissingTable { table } => {
                write!(f, "sqlite {table} does not exist")
            }
            SqliteDictionaryError::ReadOnly => write!(f, "sqlite file is readonly"),
        }
    }
}

impl Error for SqliteDictionaryError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            SqliteDictionaryError::SqliteError { source } => Some(source),
            _ => None,
        }
    }
}

impl From<RusqliteError> for SqliteDictionaryError {
    fn from(value: RusqliteError) -> Self {
        SqliteDictionaryError::SqliteError { source: value }
    }
}

/// TODO: doc
#[derive(Debug)]
pub struct SqliteDictionary {
    conn: Connection,
    path: Option<PathBuf>,
    info: DictionaryInfo,
    readonly: bool,
}

impl SqliteDictionary {
    /// TODO: doc
    pub fn open<P: AsRef<Path>>(path: P) -> Result<SqliteDictionary, SqliteDictionaryError> {
        let path = path.as_ref().to_path_buf();
        debug!("open sqlite dictionary at {path:?}");
        let mut conn = Connection::open(&path)?;
        debug!("initialize dictionary tables");
        Self::initialize_tables(&conn)?;
        debug!("migrate from userphrase_v1");
        Self::migrate_from_userphrase_v1(&mut conn)?;
        debug!("ensure tables exist");
        Self::ensure_tables(&conn)?;
        let info = Self::read_info_v1(&conn)?;
        debug!("read dictionary info {info:?}");

        Ok(SqliteDictionary {
            conn,
            path: Some(path),
            info,
            readonly: false,
        })
    }

    /// TODO: doc
    pub fn open_readonly<P: AsRef<Path>>(
        path: P,
    ) -> Result<SqliteDictionary, SqliteDictionaryError> {
        let path = path.as_ref().to_path_buf();
        let conn = Connection::open_with_flags(&path, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
        Self::ensure_tables(&conn)?;
        let info = Self::read_info_v1(&conn)?;

        Ok(SqliteDictionary {
            conn,
            path: Some(path),
            info,
            readonly: true,
        })
    }

    /// TODO: doc
    pub fn open_in_memory() -> Result<SqliteDictionary, SqliteDictionaryError> {
        let conn = Connection::open_in_memory()?;
        Self::initialize_tables(&conn)?;
        Self::ensure_tables(&conn)?;
        let info = Self::read_info_v1(&conn)?;

        Ok(SqliteDictionary {
            conn,
            path: None,
            info,
            readonly: false,
        })
    }

    fn initialize_tables(conn: &Connection) -> Result<(), SqliteDictionaryError> {
        conn.pragma_update(None, "application_id", APPLICATION_ID)?;
        conn.pragma_update(None, "user_version", USER_VERSION)?;
        conn.pragma_update(None, "journal_mode", "WAL")?;
        conn.pragma_update(None, "synchronous", "NORMAL")?;
        conn.pragma_update(None, "wal_autocheckpoint", 0)?;
        conn.execute(
            "CREATE TABLE IF NOT EXISTS dictionary_v1 (
                syllables BLOB NOT NULL,
                phrase TEXT NOT NULL,
                freq INTEGER NOT NULL,
                sort_id INTEGER,
                userphrase_id INTEGER,
                PRIMARY KEY (syllables, phrase)
            ) WITHOUT ROWID",
            [],
        )?;

        conn.execute(
            "CREATE TABLE IF NOT EXISTS userphrase_v2 (
                id INTEGER PRIMARY KEY,
                user_freq INTEGER,
                time INTEGER
            )",
            [],
        )?;

        conn.execute(
            "CREATE TABLE IF NOT EXISTS migration_v1 (name TEXT PRIMARY KEY) WITHOUT ROWID",
            [],
        )?;

        conn.execute(
            "CREATE TABLE IF NOT EXISTS info_v1 (
                key TEXT PRIMARY KEY,
                value TEXT NOT NULL
            ) WITHOUT ROWID",
            [],
        )?;

        Ok(())
    }

    fn ensure_tables(conn: &Connection) -> Result<(), SqliteDictionaryError> {
        let mut stmt = conn
            .prepare("SELECT EXISTS (SELECT 1 FROM sqlite_schema WHERE type='table' AND name=?)")?;
        for table_name in ["dictionary_v1", "userphrase_v2", "migration_v1", "info_v1"] {
            let has_table: bool = stmt.query_row([table_name], |row| row.get(0))?;
            if !has_table {
                return Err(SqliteDictionaryError::MissingTable {
                    table: table_name.into(),
                });
            }
        }
        Ok(())
    }

    fn migrate_from_userphrase_v1(conn: &mut Connection) -> Result<(), SqliteDictionaryError> {
        debug!("query has_userphrase_v1");
        let has_userphrase_v1: bool = conn.query_row(
            "SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type='table' AND name='userphrase_v1')",
            [],
            |row| row.get(0)
        )?;
        debug!("query migrated");
        let migrated: bool = conn.query_row(
            "SELECT EXISTS (SELECT 1 FROM migration_v1 WHERE name='migrate_from_userphrase_v1')",
            [],
            |row| row.get(0),
        )?;
        debug!("has_userphrase_v1={has_userphrase_v1} migrated={migrated}");
        if !has_userphrase_v1 || migrated {
            // Don't need to migrate
            conn.execute(
                "INSERT OR IGNORE INTO migration_v1 (name) VALUES ('migrate_from_userphrase_v1')",
                [],
            )?;
            return Ok(());
        }

        let mut userphrases: Vec<(Vec<Syllable>, String, u32, u32, i64)> = vec![];
        {
            let mut stmt = conn.prepare(
                "SELECT
                    phrase,
                    orig_freq,
                    user_freq,
                    time,
                    phone_0,
                    phone_1,
                    phone_2,
                    phone_3,
                    phone_4,
                    phone_5,
                    phone_6,
                    phone_7,
                    phone_8,
                    phone_9,
                    phone_10
                FROM userphrase_v1",
            )?;
            let mut rows = stmt.query([])?;
            while let Some(row) = rows.next()? {
                let mut syllables = vec![];
                for i in 4..15 {
                    let syllable_u16: u16 = row.get(i)?;
                    if let Ok(syllable) = Syllable::try_from(syllable_u16) {
                        if !syllable.is_empty() {
                            syllables.push(syllable);
                        }
                    }
                }
                userphrases.push((
                    syllables,
                    row.get(0)?,
                    row.get(1).unwrap_or(0),
                    row.get(2).unwrap_or(0),
                    row.get(3).unwrap_or(0),
                ));
            }
        }
        debug!("{} phrases loaded", userphrases.len());
        let tx = conn.transaction()?;
        {
            for item in userphrases {
                let mut stmt = tx.prepare_cached(
                    "INSERT INTO userphrase_v2 (
                        user_freq,
                        time
                    ) VALUES (?, ?)",
                )?;
                stmt.execute(params![item.3, item.4])?;
                let row_id = tx.last_insert_rowid();
                let mut stmt = tx.prepare_cached(
                    "INSERT OR REPLACE INTO dictionary_v1 (
                        syllables,
                        phrase,
                        freq,
                        userphrase_id
                    ) VALUES (?, ?, ?, ?)",
                )?;
                let mut syllables_bytes = vec![];
                item.0
                    .into_iter()
                    .for_each(|syl| syllables_bytes.extend_from_slice(&syl.to_u16().to_le_bytes()));
                stmt.execute(params![syllables_bytes, item.1, item.2, row_id])?;
            }
            tx.execute(
                "INSERT INTO migration_v1 (name) VALUES ('migrate_from_userphrase_v1')",
                [],
            )?;
        }
        tx.commit()?;
        Ok(())
    }

    fn read_info_v1(conn: &Connection) -> Result<DictionaryInfo, SqliteDictionaryError> {
        let mut info = DictionaryInfo::default();
        let mut stmt = conn.prepare(
            "SELECT key, value FROM info_v1 WHERE key IN (
                'name',
                'copyright',
                'license',
                'version',
                'software'
            )",
        )?;
        let mut rows = stmt.query([])?;
        while let Some(row) = rows.next()? {
            let key: String = row.get(0)?;
            let value: String = row.get(1)?;
            match key.as_str() {
                "name" => info.name = value,
                "copyright" => info.copyright = value,
                "license" => info.license = value,
                "version" => info.version = value,
                "software" => info.software = value,
                _ => (),
            }
        }
        Ok(info)
    }
}

impl Dictionary for SqliteDictionary {
    fn lookup(&self, syllables: &[Syllable], strategy: LookupStrategy) -> Vec<Phrase> {
        let _ = strategy;
        let syllables_bytes = syllables.to_bytes();
        let mut stmt = self
            .conn
            .prepare_cached(
                "SELECT
                    phrase,
                    max(freq, coalesce(user_freq, 0)),
                    time
                FROM dictionary_v1 LEFT JOIN userphrase_v2 ON userphrase_id = id
                WHERE syllables = ?
                ORDER BY sort_id ASC, max(freq, coalesce(user_freq, 0)) DESC, phrase DESC",
            )
            .expect("SQL error");
        stmt.query_map([syllables_bytes], |row| {
            let (phrase, freq, time): (Box<str>, _, Option<i64>) = row.try_into()?;
            let mut phrase = Phrase::new(phrase, freq);
            if let Some(last_used) = time {
                phrase = phrase.with_time(last_used as u64);
            }
            Ok(phrase)
        })
        .unwrap()
        .map(|r| r.unwrap())
        .collect()
    }

    // FIXME too many clone
    fn entries(&self) -> Entries<'_> {
        let mut stmt = self
            .conn
            .prepare_cached(
                "SELECT syllables, phrase, max(freq, coalesce(user_freq, 0)), time
                FROM dictionary_v1 LEFT JOIN userphrase_v2 ON userphrase_id = id",
            )
            .expect("SQL error");
        Box::new(
            stmt.query_map([], |row| {
                let (syllables_bytes, phrase, freq, time): (Vec<u8>, Box<str>, _, Option<i64>) =
                    row.try_into()?;
                let syllables = syllables_bytes
                    .chunks_exact(2)
                    .map(|bytes| {
                        let mut u16_bytes = [0; 2];
                        u16_bytes.copy_from_slice(bytes);
                        let syl_u16 = u16::from_le_bytes(u16_bytes);
                        Syllable::try_from(syl_u16).unwrap()
                    })
                    .collect::<Vec<_>>();
                let mut phrase = Phrase::new(phrase, freq);
                if let Some(last_used) = time {
                    phrase = phrase.with_time(last_used as u64);
                }
                Ok((syllables, phrase))
            })
            .unwrap()
            .map(|r| r.unwrap())
            .collect::<Vec<_>>()
            .into_iter(),
        )
    }

    fn about(&self) -> DictionaryInfo {
        self.info.clone()
    }

    fn path(&self) -> Option<&Path> {
        self.path.as_ref().map(|p| p as &Path)
    }

    fn set_usage(&mut self, _usage: DictionaryUsage) {}

    fn reopen(&mut self) -> Result<(), UpdateDictionaryError> {
        Ok(())
    }

    fn flush(&mut self) -> Result<(), UpdateDictionaryError> {
        let make_error = |e| UpdateDictionaryError {
            message: "flush sqlite failed",
            source: Some(Box::new(e)),
        };
        if self.readonly {
            return Err(UpdateDictionaryError {
                message: "sqlite dictionary is readonly",
                source: None,
            });
        }
        self.conn
            .pragma_update(None, "wal_checkpoint", "PASSIVE")
            .map_err(make_error)?;
        Ok(())
    }

    fn add_phrase(
        &mut self,
        syllables: &[Syllable],
        phrase: Phrase,
    ) -> Result<(), UpdateDictionaryError> {
        let make_error = |e| UpdateDictionaryError {
            message: "add phrae to sqlite failed",
            source: Some(Box::new(e)),
        };
        if self.readonly {
            return Err(UpdateDictionaryError {
                message: "sqlite dictionary is readonly",
                source: None,
            });
        }
        let syllables_bytes = syllables.to_bytes();
        let mut stmt = self
            .conn
            .prepare_cached(
                "INSERT OR REPLACE INTO dictionary_v1 (
                    syllables,
                    phrase,
                    freq
            ) VALUES (?, ?, ?)",
            )
            .map_err(make_error)?;
        stmt.execute(params![syllables_bytes, phrase.as_str(), phrase.freq()])
            .map_err(make_error)?;
        Ok(())
    }

    fn update_phrase(
        &mut self,
        syllables: &[Syllable],
        phrase: Phrase,
        user_freq: u32,
        time: u64,
    ) -> Result<(), UpdateDictionaryError> {
        let make_error = |e| UpdateDictionaryError {
            message: "update phrae in sqlite failed",
            source: Some(Box::new(e)),
        };
        // sqlite only supports i64
        let time: i64 = time.clamp(0, i64::MAX as u64) as i64;
        if self.readonly {
            return Err(UpdateDictionaryError {
                message: "sqlite dictionary is readonly",
                source: None,
            });
        }
        let syllables_bytes = syllables.to_bytes();
        let tx = self.conn.transaction().map_err(make_error)?;
        {
            let mut stmt = tx
                .prepare_cached(
                    "SELECT userphrase_id FROM dictionary_v1 WHERE syllables = ? AND phrase = ?",
                )
                .map_err(make_error)?;
            let userphrase_id: Option<Option<i64>> = stmt
                .query_row(params![syllables_bytes, phrase.as_str()], |row| row.get(0))
                .optional()
                .map_err(make_error)?;
            match userphrase_id {
                Some(Some(id)) => {
                    let mut stmt = tx
                        .prepare_cached("UPDATE userphrase_v2 SET user_freq = ? WHERE id = ?")
                        .map_err(make_error)?;
                    stmt.execute(params![user_freq, id]).map_err(make_error)?;
                }
                Some(None) | None => {
                    let mut stmt = tx
                        .prepare_cached("INSERT INTO userphrase_v2 (user_freq, time) VALUES (?, ?)")
                        .map_err(make_error)?;
                    stmt.execute(params![user_freq, time]).map_err(make_error)?;
                    let userphrase_id = tx.last_insert_rowid();
                    let mut stmt = tx
                        .prepare_cached(
                            "INSERT OR REPLACE INTO dictionary_v1 (
                            syllables,
                            phrase,
                            freq,
                            userphrase_id
                        ) VALUES (?, ?, ?, ?)",
                        )
                        .map_err(make_error)?;
                    stmt.execute(params![
                        syllables_bytes,
                        phrase.as_str(),
                        phrase.freq(),
                        userphrase_id
                    ])
                    .map_err(make_error)?;
                }
            }
        }
        tx.commit().map_err(make_error)?;
        Ok(())
    }

    fn remove_phrase(
        &mut self,
        syllables: &[Syllable],
        phrase_str: &str,
    ) -> Result<(), UpdateDictionaryError> {
        let make_error = |e| UpdateDictionaryError {
            message: "remove phrae from sqlite failed",
            source: Some(Box::new(e)),
        };
        let syllables_bytes = syllables.to_bytes();
        let mut stmt = self
            .conn
            .prepare_cached("DELETE FROM dictionary_v1 WHERE syllables = ? AND phrase = ?")
            .map_err(make_error)?;
        stmt.execute(params![syllables_bytes, phrase_str])
            .map_err(make_error)?;
        Ok(())
    }
}

/// TODO: doc
#[derive(Debug)]
pub struct SqliteDictionaryBuilder {
    dict: SqliteDictionary,
    sort_id: i64,
}

impl SqliteDictionaryBuilder {
    /// TODO: doc
    pub fn new() -> SqliteDictionaryBuilder {
        let dict = SqliteDictionary::open_in_memory().unwrap();
        SqliteDictionaryBuilder { dict, sort_id: 0 }
    }
}

impl Default for SqliteDictionaryBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl DictionaryBuilder for SqliteDictionaryBuilder {
    fn set_info(&mut self, info: DictionaryInfo) -> Result<(), BuildDictionaryError> {
        let err = || BuildDictionaryError::new("failed to set dictionary info");
        let tx = self.dict.conn.transaction().or_raise(err)?;
        {
            let mut stmt = tx
                .prepare("INSERT OR REPLACE INTO info_v1 (key, value) VALUES (?, ?)")
                .or_raise(err)?;
            stmt.execute(["name", &info.name]).or_raise(err)?;
            stmt.execute(["copyright", &info.copyright]).or_raise(err)?;
            stmt.execute(["license", &info.license]).or_raise(err)?;
            stmt.execute(["version", &info.version]).or_raise(err)?;
            stmt.execute(["software", &info.software]).or_raise(err)?;
        }
        tx.commit().or_raise(err)?;
        Ok(())
    }

    fn insert(
        &mut self,
        syllables: &[Syllable],
        phrase: Phrase,
    ) -> Result<(), BuildDictionaryError> {
        let err = || BuildDictionaryError::new("failed to insert phrase");
        let sort_id = if syllables.len() == 1 {
            self.sort_id += 1;
            self.sort_id
        } else {
            0
        };
        let syllables_bytes = syllables.to_bytes();
        let mut stmt = self
            .dict
            .conn
            .prepare_cached(
                "INSERT OR REPLACE INTO dictionary_v1 (
                    syllables,
                    phrase,
                    freq,
                    sort_id
            ) VALUES (?, ?, ?, ?)",
            )
            .or_raise(err)?;
        stmt.execute(params![
            syllables_bytes,
            phrase.as_str(),
            phrase.freq(),
            sort_id
        ])
        .or_raise(err)?;

        Ok(())
    }

    fn build(&mut self, path: &Path) -> Result<(), BuildDictionaryError> {
        let path = path
            .to_str()
            .or_raise(|| BuildDictionaryError::new("cannot convert file path to utf8"))?;
        self.dict
            .conn
            .execute("VACUUM INTO ?", [path])
            .or_raise(|| BuildDictionaryError::new("failed to finalize dictionary"))?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::error::Error;

    use rusqlite::{Connection, params};
    use tempfile::{NamedTempFile, tempdir};

    use super::SqliteDictionary;
    use crate::{
        dictionary::{
            Dictionary, DictionaryBuilder, LookupStrategy, Phrase, SqliteDictionaryBuilder,
        },
        syl,
        zhuyin::Bopomofo,
    };

    #[test]
    fn migration_from_userphrase_v1() {
        let temp_path = NamedTempFile::new()
            .expect("Unable to create tempfile")
            .into_temp_path();
        let temp_db = Connection::open(&temp_path).expect("Unable to open database");
        temp_db.execute(
            "CREATE TABLE IF NOT EXISTS userphrase_v1 (
                time INTEGER,
                user_freq INTEGER,
                max_freq INTEGER,
                orig_freq INTEGER,
                length INTEGER,
                phone_0 INTEGER,
                phone_1 INTEGER,
                phone_2 INTEGER,
                phone_3 INTEGER,
                phone_4 INTEGER,
                phone_5 INTEGER,
                phone_6 INTEGER,
                phone_7 INTEGER,
                phone_8 INTEGER,
                phone_9 INTEGER,
                phone_10 INTEGER,
                phrase TEXT,
                PRIMARY KEY (phone_0,phone_1,phone_2,phone_3,phone_4,phone_5,phone_6,phone_7,phone_8,phone_9,phone_10,phrase)
            )", []).expect("Initialize db failed");
        temp_db
            .execute(
                "INSERT INTO userphrase_v1 (
                    time, user_freq, max_freq, orig_freq, length,
                    phone_0,phone_1,phone_2,phone_3,phone_4,phone_5,phone_6,phone_7,phone_8,phone_9,phone_10,phrase
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                params![186613,9318,9318,9318,2,10268,8708,0,0,0,0,0,0,0,0,0,"測試".to_string(),
                        186613,318,9318,9318,2,10268,8708,0,0,0,0,0,0,0,0,0,"策士".to_string()],
            )
            .expect("Initialize db failed");
        temp_db.close().expect("Unable to close database");

        let dict = SqliteDictionary::open(&temp_path).expect("Unable to open database");
        assert_eq!(
            vec![
                Phrase::new("策士", 9318).with_time(186613),
                Phrase::new("測試", 9318).with_time(186613)
            ],
            dict.lookup(
                &[
                    syl![Bopomofo::C, Bopomofo::E, Bopomofo::TONE4],
                    syl![Bopomofo::SH, Bopomofo::TONE4],
                ],
                LookupStrategy::Standard
            )
        );
    }

    #[test]
    fn open_readonly() {
        let temp_dir = tempdir().expect("Unable to create tempdir");
        let temp_path = temp_dir.path().join("readonly.sqlite3");
        let mut builder = SqliteDictionaryBuilder::new();
        builder.build(&temp_path).expect("Build failure");

        let mut dict =
            SqliteDictionary::open_readonly(&temp_path).expect("Unable to open database");
        assert_eq!(temp_path.to_path_buf(), dict.path().unwrap());
        assert!(dict.flush().is_err());
    }

    #[test]
    fn insert_and_update_user_freq() -> Result<(), Box<dyn Error>> {
        let mut dict = SqliteDictionary::open_in_memory()?;
        dict.update_phrase(
            &[
                syl![Bopomofo::C, Bopomofo::E, Bopomofo::TONE4],
                syl![Bopomofo::SH, Bopomofo::TONE4],
            ],
            ("測試", 9318).into(),
            9900,
            0,
        )?;
        assert_eq!(
            vec![Phrase::new("測試", 9900).with_time(0)],
            dict.lookup(
                &[
                    syl![Bopomofo::C, Bopomofo::E, Bopomofo::TONE4],
                    syl![Bopomofo::SH, Bopomofo::TONE4],
                ],
                LookupStrategy::Standard
            )
        );
        Ok(())
    }

    #[test]
    fn update_user_freq() -> Result<(), Box<dyn Error>> {
        let mut dict = SqliteDictionary::open_in_memory()?;
        let syllables = [
            syl![Bopomofo::C, Bopomofo::E, Bopomofo::TONE4],
            syl![Bopomofo::SH, Bopomofo::TONE4],
        ];
        dict.add_phrase(&syllables, ("測試", 9318).into())?;
        dict.update_phrase(&syllables, ("測試", 9318).into(), 9900, 0)?;
        assert_eq!(
            vec![Phrase::new("測試", 9900).with_time(0)],
            dict.lookup(
                &[
                    syl![Bopomofo::C, Bopomofo::E, Bopomofo::TONE4],
                    syl![Bopomofo::SH, Bopomofo::TONE4],
                ],
                LookupStrategy::Standard
            )
        );
        Ok(())
    }
}