-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
103 lines (98 loc) · 2.08 KB
/
database.go
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
package main
import (
"database/sql"
"fmt"
"os/exec"
"time"
_ "github.com/mattn/go-sqlite3"
)
func createDb(dbfile string, epubs []Epub) {
start := time.Now()
db, err := sql.Open("sqlite3", dbfile)
c(err)
if db == nil {
panic("db nil")
}
defer db.Close()
c(err)
_, err = db.Exec(schema)
c(err)
_, err = db.Exec(fmt.Sprintf("INSERT INTO meta VALUES('%s', '%s');",
time.Now().UTC().Format("2006-01-02 15:04:05"),
VERSION))
c(err)
tx, err := db.Begin()
c(err)
stmt, err := tx.Prepare(insert)
c(err)
defer stmt.Close()
for _, epub := range epubs {
_, err := stmt.Exec(epub.FileName,
epub.Directory,
epub.Title,
epub.Author,
epub.Language,
epub.Publisher,
epub.Description, "")
if err != nil {
fmt.Println("THIS EPUB IS NOT VALID FOR DB:", epub)
tx.Rollback()
}
}
tx.Commit()
fmt.Printf("Database written to %q in %s\n", dbfile, time.Since(start))
}
func addText(dbfile string, epubs []Epub) {
db, err := sql.Open("sqlite3", dbfile)
c(err)
if db == nil {
panic("db nil")
}
defer db.Close()
tx, err := db.Begin()
c(err)
stmt, err := tx.Prepare("UPDATE epubs SET TextContent = ? WHERE Directory = ? AND FileName = ?;")
c(err)
defer stmt.Close()
for _, epub := range epubs {
path := epub.Directory + "/" + epub.FileName
fmt.Printf("Processing text of %q\n", path)
output, err := exec.Command("epub2txt", path).Output()
if err != nil {
fmt.Println("Skipping", path)
continue
}
text := string(output)
fmt.Println(len(text))
_, err = stmt.Exec(text, epub.Directory, epub.FileName)
c(err)
}
tx.Commit()
}
var schema = `
CREATE TABLE IF NOT EXISTS epubs(
FileName TEXT NOT NULL,
Directory TEXT NOT NULL,
Title TEXT NOT NULL,
Author TEXT NOT NULL,
Language TEXT NOT NULL,
Publisher TEXT NOT NULL,
Description TEXT NOT NULL,
TextContent TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS meta(
Timestamp TEXT NOT NULL,
Version TEXT NOT NULL
);
`
var insert = `INSERT INTO epubs(
FileName,
Directory,
Title,
Author,
Language,
Publisher,
Description,
TextContent
) VALUES (?, ?, ?, ?, ?, ?, ?, ?);
`