You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
sisyphus/database.go

91 lines
2.1 KiB
Go

package sisyphus
7 years ago
import (
log "github.com/sirupsen/logrus"
7 years ago
"github.com/boltdb/bolt"
)
// openDB creates and opens a new database and its respective buckets (if required)
func openDB(m Maildir) (db *bolt.DB, err error) {
7 years ago
log.WithFields(log.Fields{
"dir": string(m),
}).Info("Loading database")
7 years ago
// Open the sisyphus.db data file in your current directory.
// It will be created if it doesn't exist.
db, err = bolt.Open(string(m)+"/sisyphus.db", 0600, nil)
7 years ago
if err != nil {
return db, err
}
// Create DB bucket for the map of processed e-mail IDs
err = db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("Statistics"))
7 years ago
return err
})
if err != nil {
return db, err
}
7 years ago
// Create DB bucket for word lists
err = db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("Wordlists"))
7 years ago
return err
7 years ago
})
if err != nil {
return db, err
}
// Create DB bucket for Junk inside bucket Wordlists
err = db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("Wordlists"))
_, err := b.CreateBucketIfNotExists([]byte("Junk"))
7 years ago
return err
7 years ago
})
if err != nil {
return db, err
}
// Create DB bucket for Good inside bucket Wordlists
7 years ago
err = db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("Wordlists"))
_, err := b.CreateBucketIfNotExists([]byte("Good"))
7 years ago
return err
7 years ago
})
7 years ago
return db, err
7 years ago
}
// LoadDatabases loads all databases from a given slice of Maildirs
func LoadDatabases(d []Maildir) (databases map[Maildir]*bolt.DB, err error) {
databases = make(map[Maildir]*bolt.DB)
for _, val := range d {
databases[val], err = openDB(val)
if err != nil {
return databases, err
}
}
log.Info("All databases loaded")
return databases, nil
}
// CloseDatabases closes all databases from a given slice of Maildirs
func CloseDatabases(databases map[Maildir]*bolt.DB) {
for key, val := range databases {
err := val.Close()
if err != nil {
log.WithFields(log.Fields{
"db": string(key) + "/sisyphus.db",
}).Error("Unable to close database")
}
log.WithFields(log.Fields{
"db": string(key) + "/sisyphus.db",
}).Info("Database closed")
}
return
}