package Database
|
|
|
|
import (
|
|
"database/sql"
|
|
"time"
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
bolt "go.etcd.io/bbolt"
|
|
|
|
"PackageManager/Variables"
|
|
)
|
|
|
|
var (
|
|
DB *sql.DB
|
|
FsDB *bolt.DB
|
|
)
|
|
|
|
func init() {
|
|
var e error
|
|
// Initialise sqlite3 database for package versioning
|
|
DB, e = sql.Open("sqlite3", Variables.DatabaseName)
|
|
if e != nil {
|
|
panic(e)
|
|
}
|
|
|
|
// Initialise bolt db for filesystem hashing
|
|
FsDB, e = bolt.Open(Variables.FsHashDatabaseName, 0600, &bolt.Options{
|
|
Timeout: 5 * time.Second,
|
|
})
|
|
if e != nil {
|
|
panic(e)
|
|
}
|
|
}
|
|
|
|
func InitBoltDB() error {
|
|
var (
|
|
tx *bolt.Tx
|
|
e error
|
|
)
|
|
|
|
tx, e = FsDB.Begin(true)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
defer tx.Rollback()
|
|
|
|
_, e = tx.CreateBucketIfNotExists(Variables.FsHashIndexBucket)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
|
|
_, e = tx.CreateBucketIfNotExists(Variables.FsHashPicksBucket)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
|
|
e = tx.Commit()
|
|
|
|
return e
|
|
}
|
|
|
|
func InitSqlite3DB() error {
|
|
var (
|
|
stmt *sql.Stmt
|
|
e error
|
|
)
|
|
|
|
stmt, e = DB.Prepare(`
|
|
CREATE TABLE IF NOT EXISTS installed_packages (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
name VARCHAR(64) NOT NULL,
|
|
version VARCHAR(64) NOT NULL,
|
|
installed_at INTEGER NOT NULL
|
|
)
|
|
`)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
|
|
_, e = stmt.Exec()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
|
|
stmt, e = DB.Prepare(`
|
|
CREATE TABLE IF NOT EXISTS dependancy_linker (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
package_id INTEGER,
|
|
dependancy_id INTEGER,
|
|
FOREIGN KEY(package_id) REFERENCES installed_packages(id),
|
|
FOREIGN KEY(dependancy_id) REFERENCES installed_packages(id)
|
|
)
|
|
`)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
|
|
_, e = stmt.Exec()
|
|
return e
|
|
}
|
|
|
|
func InitDB() error {
|
|
var e error
|
|
e = InitBoltDB()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
|
|
return InitSqlite3DB()
|
|
}
|