summary refs log tree commit diff stats
path: root/svc/db.go
blob: 260c5cc1355d9309e11b38b9fdd23aca1de59643 (plain) (blame)
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
package svc // import "github.com/getwtxt/getwtxt/svc"

import (
	"github.com/syndtr/goleveldb/leveldb"
	"golang.org/x/sys/unix"
)

// Everything in this file is database-agnostic.
// Functions and types related to specific kinds
// of databases will be in their own respective
// files, such as:
//  - leveldb.go
//  - sqlite.go

// Abstraction to allow several different
// databases to be used interchangeably.
type dbase interface {
	push() error
	pull()
}

// Opens a new connection to the specified
// database, then reads it into memory.
func initDatabase() {
	var db dbase
	confObj.Mu.RLock()
	dbpath := confObj.DBPath
	confObj.Mu.RUnlock()

	switch confObj.DBType {

	case "leveldb":
		lvl, err := leveldb.OpenFile(dbpath, nil)
		errFatal("", err)
		db = &dbLevel{db: lvl}

	case "sqlite":
		db = initSqlite()

	}

	dbChan <- db
	pullDB()
}

// Close the database connection.
func killDB() {
	db := <-dbChan
	switch dbType := db.(type) {
	case *dbLevel:
		errLog("", dbType.db.Close())
	case *dbSqlite:
		errLog("", dbType.db.Close())
	}
}

// Pushes the registry's cache data
// to a local database for safe keeping.
func pushDB() error {
	db := <-dbChan
	err := db.push()
	dbChan <- db

	unix.Sync()

	return err
}

// Reads the database from disk into memory.
func pullDB() {
	db := <-dbChan
	db.pull()
	dbChan <- db
}