Skip to content

Commit

Permalink
refactor: Protect database file and better handling on missing db file
Browse files Browse the repository at this point in the history
- Use read-only mode to open the SQLite database file
- Do not create a new database file while the given db file is missing
  • Loading branch information
antonyho committed Dec 2, 2023
1 parent af22b21 commit 66fe355
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions engine/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"database/sql"
"errors"
"fmt"
"os"
"unicode/utf8"

// SQLite3 driver for the engine, the engine uses SQlite3.
Expand All @@ -17,6 +18,10 @@ const (
CangjieV5 CangjieVersion = 5
)

const (
DatabaseDSNPattern = "file:%s?mode=ro"
)

type Option func(*Engine)

func WithCangjieV3() Option {
Expand Down Expand Up @@ -84,8 +89,14 @@ func New(options ...Option) *Engine {
option(e)
}

db, _ := sql.Open("sqlite3", e.dbPath)
e.db = db
if _, err := os.Stat(e.dbPath); err != nil && errors.Is(err, os.ErrNotExist) {
// The Cangjie database does not exist, create an in-memory database.
// This is a constructor. Trying not to return error here.
e.db, _ = sql.Open("sqlite3", ":memory:")
} else {
dsn := fmt.Sprintf(DatabaseDSNPattern, e.dbPath)
e.db, _ = sql.Open("sqlite3", dsn)
}

e.determineQuery()

Expand All @@ -101,8 +112,12 @@ func (e *Engine) Set(options ...Option) {
}

func (e *Engine) Encode(radicals string) (results []rune, err error) {
results = make([]rune, 0)
err = e.db.Ping()
if err != nil {
return
}

results = make([]rune, 0)
codes := radicals
if e.Easy {
if len(radicals) > 1 {
Expand Down

0 comments on commit 66fe355

Please sign in to comment.