-
Notifications
You must be signed in to change notification settings - Fork 19
/
session.go
215 lines (173 loc) · 5.09 KB
/
session.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// This file is part of Gopher2600.
//
// Gopher2600 is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Gopher2600 is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Gopher2600. If not, see <https://www.gnu.org/licenses/>.
package database
import (
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
)
// sentinal error returned when requested database is not available.
var NotAvailable = errors.New("not available")
// Activity is used to specify the general activity of what will be occurring
// during the database session.
type Activity int
// Valid activities: the "higher level" activities inherit the activity
// abilities of the activity levels lower down the scale.
const (
ActivityReading Activity = iota
// Modifying implies Reading.
ActivityModifying
// Creating implies Modifying (which in turn implies Reading).
ActivityCreating
)
// Session keeps track of a database session.
type Session struct {
dbfile *os.File
activity Activity
entries map[int]Entry
// deserialisers for the different entries that may appear in the database
entryTypes map[string]Deserialiser
}
// StartSession starts/initialises a new DB session. The init argument is the
// function to call when database has been successfully opened. This function
// should be used to add information about the different entries that are to be
// used in the database (see AddEntryType() function).
//
// Calls to StartSession must be paired with a call to EndSesion().
func StartSession(path string, activity Activity, init func(*Session) error) (*Session, error) {
var err error
db := &Session{activity: activity}
db.entryTypes = make(map[string]Deserialiser)
var flags int
switch activity {
case ActivityReading:
flags = os.O_RDONLY
case ActivityModifying:
flags = os.O_RDWR
case ActivityCreating:
flags = os.O_RDWR | os.O_CREATE
}
db.dbfile, err = os.OpenFile(path, flags, 0600)
if err != nil {
switch err.(type) {
case *os.PathError:
return nil, fmt.Errorf("%w: %s", NotAvailable, path)
}
return nil, fmt.Errorf("database: %w", err)
}
// closing of db.dbfile requires a call to endSession()
err = init(db)
if err != nil {
return nil, err
}
err = db.readDBFile()
if err != nil {
return nil, err
}
return db, nil
}
// EndSession closes the database.
func (db *Session) EndSession(commitChanges bool) error {
// write entries to database
if commitChanges {
if db.activity == ActivityReading {
return fmt.Errorf("database: cannot commit to a read-only database")
}
err := db.dbfile.Truncate(0)
if err != nil {
return err
}
_, err = db.dbfile.Seek(0, io.SeekStart)
if err != nil {
return err
}
for k, v := range db.entries {
s := strings.Builder{}
ser, err := v.Serialise()
if err != nil {
return err
}
s.WriteString(recordHeader(k, v.EntryType()))
for i := 0; i < len(ser); i++ {
s.WriteString(fieldSep)
s.WriteString(ser[i])
}
s.WriteString(entrySep)
_, err = db.dbfile.WriteString(s.String())
if err != nil {
return err
}
}
}
// end session by closing file
if db.dbfile != nil {
err := db.dbfile.Close()
if err != nil {
return err
}
db.dbfile = nil
}
return nil
}
// readDBFile reads each line in the database file, checks for validity of key
// and entry type and tries to deserialise the entry. it fails on the first
// error it encounters.
func (db *Session) readDBFile() error {
// clobbers the contents of db.entries
db.entries = make(map[int]Entry, len(db.entries))
// make sure we're at the beginning of the file
if _, err := db.dbfile.Seek(0, io.SeekStart); err != nil {
return err
}
buffer, err := io.ReadAll(db.dbfile)
if err != nil {
return fmt.Errorf("database: %w", err)
}
// split entries
lines := strings.Split(string(buffer), entrySep)
for i := 0; i < len(lines); i++ {
lines[i] = strings.TrimSpace(lines[i])
if len(lines[i]) == 0 {
continue
}
// comment line
if strings.HasPrefix(lines[i], "#") {
continue
}
// loop through file until EOF is reached
fields := strings.SplitN(lines[i], fieldSep, numLeaderFields+1)
key, err := strconv.Atoi(fields[leaderFieldKey])
if err != nil {
return fmt.Errorf("invalid key (%s) [line %d]", fields[leaderFieldKey], i+1)
}
if _, ok := db.entries[key]; ok {
return fmt.Errorf("duplicate key (%d) [line %d]", key, i+1)
}
var ent Entry
deserialise, ok := db.entryTypes[fields[leaderFieldID]]
if !ok {
return fmt.Errorf("unrecognised entry type (%s) [line %d]", fields[leaderFieldID], i+1)
}
ent, err = deserialise(strings.Split(fields[numLeaderFields], ","))
if err != nil {
return fmt.Errorf("%w [line %d]", err, i+1)
}
db.entries[key] = ent
}
return nil
}