docstore/pkg/db/index.go
2019-08-24 20:29:43 +02:00

151 lines
2.8 KiB
Go

// Copyright (C) 2019 Marius Schellenberger
package db
import (
"errors"
"git.giftfish.de/ston1th/docstore/pkg/core"
"git.giftfish.de/ston1th/docstore/pkg/log"
"git.giftfish.de/ston1th/docstore/pkg/tags"
)
const (
// schema:
// key: id/<path>
// value: <id>
idPrefix = "id/"
// schema:
// key: path/<id>
// value: <path>
pathPrefix = "path/"
)
func (db *DB) Reindex(path string, match []core.RTag) (err error) {
if match == nil {
match, err = db.GetAllRTags()
if err != nil {
return
}
}
id, err := db.GetID(path)
if err != nil {
return
}
log.Debugf("db: reindexing: %s", path)
doc, err := db.Index.Get(id)
if err != nil {
return
}
doc.Tags = tags.Find(doc.Text, match)
err = db.Index.Reindex(id, doc)
if err != nil {
return
}
return db.SetTag(path, doc.Tags)
}
func (db *DB) ReindexAll() (err error) {
var paths []string
err = db.store.ForEachPrefix(idPrefix, func(k string, _ []byte) error {
paths = append(paths, k)
return nil
})
if err != nil {
return
}
match, err := db.GetAllRTags()
if err != nil {
return
}
for _, p := range paths {
e := db.Reindex(p, match)
if e != nil {
if err == nil {
err = errors.New("reindexAll had errors")
}
log.Printf("db: error reindexing %s: %s", p, e)
}
}
return
}
func (db *DB) GetPaths(res []core.Result) {
for i, v := range res {
err := db.store.Get(pathPrefix+v.ID, &res[i].Path)
if err != nil {
res[i].Path = err.Error()
}
}
}
func (db *DB) GetIndexed(p core.Paths) {
for i, v := range p {
p[i].Flag = db.IsIndexed(v.Abs)
p[i].Tags, _ = db.GetTag(v.Abs)
}
}
func (db *DB) IsIndexed(path string) bool {
return db.store.Get(idPrefix+path, nil) == nil
}
func (db *DB) GetPath(id string) (path string, err error) {
err = db.store.Get(pathPrefix+id, &path)
return
}
func (db *DB) GetID(path string) (id string, err error) {
err = db.store.Get(idPrefix+path, &id)
return
}
func (db *DB) DeletePath(id string) error {
return db.store.Delete(pathPrefix + id)
}
func (db *DB) DeleteID(path string) error {
return db.store.Delete(idPrefix + path)
}
func (db *DB) NewFile(id, path string, tag []string) (err error) {
err = db.store.Set(idPrefix+path, id)
if err != nil {
return
}
err = db.store.Set(pathPrefix+id, path)
if err != nil {
return
}
return db.SetTag(path, tag)
}
func (db *DB) MoveFile(op, np string) (err error) {
if !db.IsIndexed(op) {
return nil
}
id, tag, err := db.DeleteFile(op)
if err != nil {
return
}
return db.NewFile(id, np, tag)
}
func (db *DB) DeleteFile(path string) (id string, tag []string, err error) {
if !db.IsIndexed(path) {
return
}
id, err = db.GetID(path)
if err != nil {
return
}
err = db.DeleteID(path)
if err != nil {
return
}
tag, err = db.UnsetTag(path)
if err != nil {
return
}
err = db.DeletePath(id)
return
}