-
Notifications
You must be signed in to change notification settings - Fork 0
/
filer.go
51 lines (45 loc) · 1 KB
/
filer.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
package filer
import (
"log"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
)
type File struct {
Name string `db:"NAME"`
File_ID string `db:"FILE_ID"`
}
func (file *File) Insert(db *sqlx.DB) int {
tx := db.MustBegin()
_, err := tx.Exec("INSERT INTO FILE(NAME,FILE_ID) VALUES ($1,$2)", file.Name, file.File_ID)
if err != nil {
log.Println("File Already Exists")
return 0
}
tx.Commit()
return 1
}
func InitDB() *sqlx.DB {
schema := `CREATE TABLE IF NOT EXISTS FILE (NAME text NOT NULL UNIQUE,FILE_ID text NOT NULL UNIQUE);`
db, err := sqlx.Connect("sqlite3", "test.db")
if err != nil {
panic(err)
}
err = db.Ping()
if err != nil {
log.Fatalf("Cannot Ping the DB")
}
db.MustExec(schema)
return db
}
func Search(term string, db *sqlx.DB) []File {
var files []File
err := db.Select(&files, "SELECT * FROM FILE WHERE NAME LIKE $1", "%"+term+"%")
if err != nil {
log.Println("Cannot find any record")
}
n := len(files)
if n > 10 {
return files[0:10]
}
return files[0:n]
}