zordfsdb/db.go

336 lines
7 KiB
Go
Raw Normal View History

2025-07-11 22:50:02 +03:00
// Copyright (C) 2025 Arns Udovič <zordsdavini@arns.lt>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package zordfsdb
import (
"fmt"
"math/rand"
"os"
"path"
"strings"
"time"
abcex "g.arns.lt/zordsdavini/abcex/v4"
)
type DB struct {
Root string
Nodes map[string]Node
}
func (db *DB) GetNodes() map[string]Node {
return db.Nodes
}
func (db *DB) Refresh() error {
db.Nodes = make(map[string]Node)
files, err := os.ReadDir(db.Root)
if err != nil {
return err
}
for _, file := range files {
node := Node{Key: file.Name()}
node.Nodes = make(map[string]Node)
if file.IsDir() {
node, err = readDir(db.Root, node)
if err != nil {
return err
}
} else {
b, err := os.ReadFile(path.Join(db.Root, file.Name()))
if err != nil {
return err
}
if file.Name() == ".template" {
node.Template = strings.Trim(string(b), "\n")
continue
}
node.Value = strings.Trim(string(b), "\n")
}
db.Nodes[file.Name()] = node
}
return nil
}
func (db *DB) Keys(vpath string) []string {
keys := []string{}
fullPath := []string{db.Root}
fullPath = append(fullPath, strings.Split(vpath, ".")...)
root := path.Join(fullPath...)
files, err := os.ReadDir(root)
if err != nil {
return keys
}
for _, file := range files {
if file.Name() == ".template" {
continue
}
keys = append(keys, file.Name())
}
return keys
}
func (db *DB) GetNode(vpath string) (Node, bool) {
nodes := db.Nodes
current := Node{}
STEP_LOOP:
for _, step := range strings.Split(vpath, ".") {
for _, node := range nodes {
if step == node.Key {
nodes = node.Nodes
current = node
continue STEP_LOOP
}
}
return current, false
}
return current, true
}
func (db *DB) Get(vpath string) (string, bool) {
node, found := db.GetNode(vpath)
if !found {
return "", false
}
return node.Value, true
}
func (db *DB) Inc(vpath string) bool {
fullPath := []string{db.Root}
fullPath = append(fullPath, strings.Split(vpath, ".")...)
val, found := db.Get(vpath)
if !found {
val = "0"
}
valAbc := abcex.Decode(val, abcex.BASE62)
valAbc++
val = abcex.Encode(valAbc, abcex.BASE62)
os.WriteFile(path.Join(fullPath...), []byte(string(val)), 0644)
err := db.Refresh()
if err != nil {
return false
}
return true
}
func (db *DB) Dec(vpath string) bool {
fullPath := []string{db.Root}
fullPath = append(fullPath, strings.Split(vpath, ".")...)
val, found := db.Get(vpath)
if !found {
val = "0"
}
valAbc := abcex.Decode(val, abcex.BASE62)
valAbc--
val = abcex.Encode(valAbc, abcex.BASE62)
os.WriteFile(path.Join(fullPath...), []byte(string(val)), 0644)
err := db.Refresh()
if err != nil {
return false
}
return true
}
func (db *DB) Now(vpath string) bool {
fullPath := []string{db.Root}
fullPath = append(fullPath, strings.Split(vpath, ".")...)
now := time.Now()
formatted := now.Format(time.RFC3339)
os.WriteFile(path.Join(fullPath...), []byte(formatted), 0644)
err := db.Refresh()
if err != nil {
return false
}
return true
}
func (db *DB) Save(vpath string, value string) bool {
fullPath := []string{db.Root}
fullPath = append(fullPath, strings.Split(vpath, ".")...)
err := os.WriteFile(path.Join(fullPath...), []byte(value), 0644)
if err != nil {
return false
}
err = db.Refresh()
if err != nil {
return false
}
return true
}
func (db *DB) Del(vpath string) bool {
fullPath := []string{db.Root}
fullPath = append(fullPath, strings.Split(vpath, ".")...)
os.RemoveAll(path.Join(fullPath...))
err := db.Refresh()
if err != nil {
return false
}
return true
}
func (db *DB) CreateNode(vpath string) bool {
fullPath := []string{db.Root}
fullPath = append(fullPath, strings.Split(vpath, ".")...)
err := os.Mkdir(path.Join(fullPath...), 0750)
if err != nil {
return false
}
err = db.Refresh()
if err != nil {
return false
}
return true
}
func (db *DB) AddObject(vpath string) (string, error) {
fullPath := []string{db.Root}
fullPath = append(fullPath, strings.Split(vpath, ".")...)
root := path.Join(fullPath...)
ids, err := os.ReadDir(root)
if err != nil {
return "", err
}
maxId := int64(0)
notEmpty := false
for _, id := range ids {
if id.Name() == ".template" {
continue
}
idInt := abcex.Decode(id.Name(), abcex.BASE62)
if maxId <= idInt {
maxId = idInt
notEmpty = true
}
}
if notEmpty {
maxId++
}
fmt.Println(fullPath, maxId)
maxIdAbc := abcex.Encode(maxId, abcex.BASE62)
fullPath = append(fullPath, maxIdAbc)
fmt.Println(fullPath, maxId, maxIdAbc)
err = os.Mkdir(path.Join(fullPath...), 0750)
if err != nil {
return "", err
}
list, found := db.GetNode(vpath)
if !found {
return "", fmt.Errorf("Node not found")
}
if list.Template != "" {
fmt.Println("Template", list.Template, vpath, maxIdAbc)
err = db.ExecuteCommands(list.Template, &vpath, &maxIdAbc)
}
err = db.Refresh()
if err != nil {
return "", err
}
return abcex.Encode(maxId, abcex.BASE62), nil
}
func (db *DB) Length(vpath string) (int64, error) {
node, found := db.GetNode(vpath)
if !found {
return 0, fmt.Errorf("Node not found")
}
if !node.List {
return 0, fmt.Errorf("Node is not a list")
}
return int64(len(node.Nodes)), nil
}
func (db *DB) GetRandomNode(vpath string) (Node, error) {
node, found := db.GetNode(vpath)
if !found {
return Node{}, fmt.Errorf("Node not found")
}
if !node.List {
return Node{}, fmt.Errorf("Not a list")
}
if len(node.Nodes) == 0 {
return Node{}, fmt.Errorf("List is empty")
}
keys := db.Keys(vpath)
randomKey := keys[rand.Intn(len(keys))]
return node.Nodes[randomKey], nil
}
func (db *DB) ExecuteCommands(commands string, lastPath *string, lastKey *string) error {
return ExecuteCommands(db, commands, lastPath, lastKey)
}
func (db *DB) AddTemplate(vpath string, template string) bool {
fullPath := []string{db.Root}
fullPath = append(fullPath, strings.Split(vpath, ".")...)
fullPath = append(fullPath, ".template")
err := os.WriteFile(path.Join(fullPath...), []byte(template), 0644)
if err != nil {
return false
}
err = db.Refresh()
if err != nil {
return false
}
return true
}