-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
93 lines (77 loc) · 2.15 KB
/
db.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package app
import (
"database/sql"
"log"
_ "github.com/mattn/go-sqlite3" // SQLite driver
)
type Namespace struct {
ID int
Prefix string
Pubkey string
Identity *string
AdminMetadata *string
}
func createNamespaceTable(db *sql.DB) {
query := `
CREATE TABLE IF NOT EXISTS namespace (
id INTEGER PRIMARY KEY AUTOINCREMENT,
prefix TEXT NOT NULL UNIQUE,
pubkey TEXT NOT NULL,
identity TEXT,
admin_metadata TEXT
);`
_, err := db.Exec(query)
if err != nil {
log.Fatalf("Failed to create table: %v", err)
}
}
func addNamespace(db *sql.DB, ns *Namespace) error {
query := `INSERT INTO namespace (prefix, pubkey, identity, admin_metadata) VALUES (?, ?, ?, ?)`
_, err := db.Exec(query, ns.Prefix, ns.Pubkey, ns.Identity, ns.AdminMetadata)
return err
}
func updateNamespace(db *sql.DB, ns *Namespace) error {
query := `UPDATE namespace SET pubkey = ?, identity = ?, admin_metadata = ? WHERE prefix = ?`
_, err := db.Exec(query, ns.Pubkey, ns.Identity, ns.AdminMetadata, ns.Prefix)
return err
}
func deleteNamespace(db *sql.DB, prefix string) error {
query := `DELETE FROM namespace WHERE prefix = ?`
_, err := db.Exec(query, prefix)
return err
}
func getNamespace(db *sql.DB, prefix string) (*Namespace, error) {
ns := &Namespace{}
query := `SELECT * FROM namespace WHERE prefix = ?`
err := db.QueryRow(query, prefix).Scan(&ns.ID, &ns.Prefix, &ns.Pubkey, &ns.Identity, &ns.AdminMetadata)
if err != nil {
return nil, err
}
return ns, nil
}
func getAllNamespaces(db *sql.DB) ([]*Namespace, error) {
query := `SELECT * FROM namespace`
rows, err := db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
namespaces := make([]*Namespace, 0)
for rows.Next() {
ns := &Namespace{}
if err := rows.Scan(&ns.ID, &ns.Prefix, &ns.Pubkey, &ns.Identity, &ns.AdminMetadata); err != nil {
return nil, err
}
namespaces = append(namespaces, ns)
}
return namespaces, nil
}
func InitDB() (*sql.DB){
db, err := sql.Open("sqlite3", "./namespace.db")
if err != nil {
log.Fatalf("Failed to open database: %v", err)
}
defer db.Close()
createNamespaceTable(db)
return db
}