-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_transactions.go
79 lines (68 loc) · 1.54 KB
/
db_transactions.go
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
* Created on 27 Feb 2024
* @author Sai Sumanth
*/
package main
import (
"encoding/json"
"fmt"
"os"
"sync"
)
// / Map of arrays will be stored in this database, array name will be the key
var database = make(map[string][]int)
var mx sync.Mutex
// writes data to .wkn file
func WriteDataToFile() error {
mx.Lock()
defer mx.Unlock()
// convert map data to []byte data
data, err := json.Marshal(database)
if err != nil {
return err
}
/// write byte data to file
err = os.WriteFile(".wkn", data, 0644)
if err != nil {
return err
}
return err
}
// trigger when user enters `new array_name` command
func CreateNewArray(arrayName string, arr []int) {
defer WriteDataToFile()
mx.Lock()
defer mx.Unlock()
database[arrayName] = arr
arrLength := len(arr)
if arrLength == 0 {
fmt.Println("CREATED")
} else {
fmt.Printf("CREATED (%d)\n", len(arr))
}
}
// Deletes an array with given arrName from database
func DeleteArray(arrName string) {
defer WriteDataToFile()
mx.Lock()
defer mx.Unlock()
if _, doesExists := database[arrName]; doesExists {
/// remove key from map
delete(database, arrName)
fmt.Println("DELETED")
} else {
errMessage := fmt.Sprintf("Error: \"%s\" does not exist", arrName)
fmt.Println(errMessage)
}
}
// trigger when user enters `show array_name` command
func GetArray(arrayName string) {
mx.Lock()
defer mx.Unlock()
if arr, doesExists := database[arrayName]; doesExists {
fmt.Println(arr)
} else {
errMessage := fmt.Sprintf("Error: \"%s\" does not exist", arrayName)
fmt.Println(errMessage)
}
}