-
Notifications
You must be signed in to change notification settings - Fork 13
/
append.go
75 lines (69 loc) · 1.38 KB
/
append.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
package main
import (
"bufio"
"database/sql"
"errors"
"log"
"os"
"path/filepath"
_ "github.com/mattn/go-sqlite3"
)
var (
db *sql.DB
dbstore string
)
func init() {
const initSql = "create table if not exists topics(id int unique, title text unique);"
var err error
exe1, _ := os.Executable()
dbstore = filepath.Join(filepath.Dir(exe1), "..", "data")
os.MkdirAll(dbstore, os.ModePerm)
db, err = sql.Open("sqlite3", filepath.Join(dbstore, "topics.db"))
if err != nil {
panic(err)
}
_, err = db.Exec(initSql)
if err != nil {
panic(err)
}
}
func appendTopic(filename string) error {
const sqlAppend = "insert into topics(id,title) values(?,?);"
var id1 = filepath.Base(filename)
fp1, err := os.Open(filename)
if err != nil {
return err
}
defer fp1.Close()
var rd1 = bufio.NewReader(fp1)
line1, _, err := rd1.ReadLine()
if err != nil {
return err
}
res, err := db.Exec(sqlAppend, id1, line1)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 0 {
return errors.New("Unknown error")
}
return nil
}
func main() {
if len(os.Args) < 2 {
log.Panicln("usage: appendtopic <file1 file2 ...>")
return
}
for i := 1; i < len(os.Args); i++ {
err := appendTopic(os.Args[i])
if err == nil {
log.Println("OK", filepath.Base(os.Args[i]))
} else {
log.Println("Fail", filepath.Base(os.Args[i]))
}
}
}