package Database
|
|
|
|
import (
|
|
"database/sql"
|
|
"os"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
bolt "go.etcd.io/bbolt"
|
|
|
|
"PackageManager/Variables"
|
|
)
|
|
|
|
var (
|
|
DB *sql.DB
|
|
FsDB *bolt.DB
|
|
)
|
|
|
|
func InitConfigDir() error {
|
|
var err error
|
|
_, err = os.Stat(Variables.ConfigDir)
|
|
if os.IsNotExist(err) {
|
|
return os.MkdirAll(Variables.ConfigDir, 0644)
|
|
}
|
|
return err
|
|
}
|
|
|
|
func InitDatabaseFiles() error {
|
|
var err error
|
|
// Initialise sqlite3 database for package versioning
|
|
DB, err = sql.Open(
|
|
"sqlite3",
|
|
filepath.Join(Variables.ConfigDir, Variables.DatabaseName),
|
|
)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// Initialise bolt db for filesystem hashing
|
|
FsDB, err = bolt.Open(
|
|
filepath.Join(Variables.ConfigDir, Variables.FsHashDatabaseName),
|
|
0600,
|
|
&bolt.Options{
|
|
Timeout: 5 * time.Second,
|
|
},
|
|
)
|
|
|
|
return err
|
|
}
|
|
|
|
func init() {
|
|
var err error
|
|
|
|
err = InitConfigDir()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
err = InitDatabaseFiles()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
func InitBoltDB() error {
|
|
var (
|
|
tx *bolt.Tx
|
|
err error
|
|
)
|
|
|
|
tx, err = FsDB.Begin(true)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
|
|
_, err = tx.CreateBucketIfNotExists(Variables.FsHashIndexBucket)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = tx.CreateBucketIfNotExists(Variables.FsHashPicksBucket)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return tx.Commit()
|
|
}
|
|
|
|
func InitSqlite3DB() error {
|
|
var (
|
|
stmt *sql.Stmt
|
|
err error
|
|
)
|
|
|
|
stmt, err = 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 err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = stmt.Exec()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
stmt, err = 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 err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = stmt.Exec()
|
|
return err
|
|
}
|
|
|
|
func InitDB() error {
|
|
var err error = InitBoltDB()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return InitSqlite3DB()
|
|
}
|