first commit

This commit is contained in:
2024-04-08 17:17:57 +00:00
commit 3e3b9a8c61
9 changed files with 296 additions and 0 deletions

58
pkg/data/data.go Normal file
View File

@@ -0,0 +1,58 @@
package data
import (
"database/sql"
"errors"
"log"
"path/filepath"
_ "github.com/mattn/go-sqlite3"
)
type (
Repository struct {
path string
conn *sql.DB
}
)
func New(path string) *Repository {
dbPath := filepath.Join(path, "system.db")
conn, err := sql.Open("sqlite3", dbPath)
if err != nil {
log.Fatal(err)
}
r := &Repository{
path: path,
conn: conn,
}
if err := r.check(); err != nil {
log.Fatalf("[PANIC] %s", err)
}
return r
}
func (r *Repository) Close() error {
return r.conn.Close()
}
func (r *Repository) check() error {
rows, err := r.conn.Query("SELECT value FROM system WHERE key = 'db.version'")
if err != nil {
m := new(migratorVersion1)
m.conn = r.conn
return m.create()
}
defer rows.Close()
var version string
if !rows.Next() {
return errors.New("no version found in the system database")
}
if err := rows.Scan(&version); err != nil {
return err
}
log.Printf("[INFO] database loaded with version %s", version)
return nil
}

40
pkg/data/db_struct_v1.sql Normal file
View File

@@ -0,0 +1,40 @@
CREATE TABLE system (
key string primary key,
value string
);
CREATE TABLE users (
uuid string primary key,
username string,
password string
);
CREATE TABLE roles (
uuid string primary key,
descriptor string
);
CREATE TABLE role_permissions (
uuid string primary key,
role string,
system_permission string
);
CREATE TABLE user_roles (
uuid string primary key,
role string,
user string
);
CREATE TABLE saves (
uuid string primary key,
name string,
user string,
path string
);
INSERT INTO system (key, value) VALUES ('db.version', '1');
INSERT INTO users (uuid, username) VALUES ('4b5b9489-973c-44e7-bae0-5ab23b56abe7', 'root');
INSERT INTO roles (uuid, descriptor) VALUES ('4b5b9489-973c-44e7-bae0-5ab23b56abe7', 'root');
INSERT INTO role_permissions (uuid, role, system_permission) VALUES ('4b5b9489-973c-44e7-bae0-5ab23b56abe7', '4b5b9489-973c-44e7-bae0-5ab23b56abe7', '*.*');
INSERT INTO user_roles (uuid, role, user) VALUES ('4b5b9489-973c-44e7-bae0-5ab23b56abe7', '4b5b9489-973c-44e7-bae0-5ab23b56abe7', '4b5b9489-973c-44e7-bae0-5ab23b56abe7');

27
pkg/data/migration.go Normal file
View File

@@ -0,0 +1,27 @@
package data
import (
"database/sql"
_ "embed"
"log"
)
//go:embed db_struct_v1.sql
var dbStructV1SQL string
type (
migratorVersion1 struct {
conn *sql.DB
}
)
func (m *migratorVersion1) create() error {
log.Printf("[INFO] no database, creating system database structure...")
_, err := m.conn.Exec(dbStructV1SQL)
if err != nil {
return err
}
log.Printf("[INFO] root user and role inserted by default")
log.Println("[INFO] database created with success!")
return nil
}