-
Notifications
You must be signed in to change notification settings - Fork 1
/
page.go
504 lines (450 loc) · 11.5 KB
/
page.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
package newdb
import (
"bytes"
"crypto/sha1"
"encoding"
"fmt"
"io"
"os"
"github.com/anydemo/newdb/pkg/bitset"
)
// PageID page id
type PageID interface {
ID() string
PageNum() int
TableID() string
}
//Page page
type Page interface {
encoding.BinaryMarshaler
// PageID get the PageID
PageID() PageID
// MarkDirty mark the page dirty
// if TxID is nil, Mark not dirty
MarkDirty(*TxID)
TupleDesc() *TupleDesc
}
// DBFile The interface for database files on disk.
// Each table is represented by a single DBFile.
// DbFiles can fetch pages and iterate through tuples.
// Each file has a unique id used to store metadata about the table in the Catalog.
// DbFiles are generally accessed through the buffer pool, rather than directly by operators.
type DBFile interface {
ID() string
ReadPage(pid PageID) (Page, error)
WritePage(p Page) error
InsertTuple(*TxID, *Tuple) ([]Page, error)
DeleteTuple(*TxID, *Tuple) ([]Page, error)
TupleDesc() *TupleDesc
Iterator(*TxID) DbFileIterator
}
// DbFileIterator DbFileIterator is the iterator interface that all newDB Dbfile should implement.
type DbFileIterator interface {
Iterator
}
var _ PageID = (*HeapPageID)(nil)
// HeapPageID HeapPageID
type HeapPageID struct {
// TID TableID
TID string
// PNum PageNum
PNum int
}
// ID ${TableID}-${PageNum} identify the PageID
func (hid HeapPageID) ID() string {
return fmt.Sprintf("%v-%v", hid.TID, hid.PNum)
}
// TableID table ID
func (hid HeapPageID) TableID() string {
return hid.TID
}
// PageNum page num
func (hid HeapPageID) PageNum() int {
return hid.PNum
}
// NewHeapPageID new HeapPageID
func NewHeapPageID(tID string, pn int) *HeapPageID {
return &HeapPageID{TID: tID, PNum: pn}
}
var (
_ DBFile = (*HeapFile)(nil)
hfLog = log.WithField("name", "heapfile")
)
// HeapFile HeapFile
//
// file format:
//
// [Page][Page][Page][Page]...
type HeapFile struct {
File *os.File
TD *TupleDesc
}
// NewHeapFile new HeapFile
func NewHeapFile(file *os.File, td *TupleDesc) *HeapFile {
return &HeapFile{
File: file,
TD: td,
}
}
// ID string
func (hf HeapFile) ID() string {
return fmt.Sprintf("%x", sha1.Sum([]byte(hf.File.Name())))
}
// ReadPage read one page
func (hf HeapFile) ReadPage(pid PageID) (Page, error) {
seek, err := hf.File.Seek(int64(pid.PageNum()*DB.B().PageSize()), 0)
if err != nil {
return nil, err
}
buf := make([]byte, DB.B().PageSize())
n, err := hf.File.Read(buf)
if err != nil {
return nil, err
}
hfLog.WithField("op", "read_page").WithField("seek", seek).WithField("read_len", n).Infof("read page from HeapFile")
heapPID, ok := pid.(*HeapPageID)
if !ok {
return nil, fmt.Errorf("pid is not HeapPageID")
}
page, err := NewHeapPage(heapPID, buf)
if err != nil {
return nil, err
}
return page, err
}
// WritePage write one page
func (hf *HeapFile) WritePage(page Page) error {
seek, err := hf.File.Seek(int64(page.PageID().PageNum()*DB.B().PageSize()), 0)
if err != nil {
return err
}
buf, err := page.MarshalBinary()
if err != nil {
return err
}
n, err := hf.File.Write(buf)
if err != nil {
return err
}
err = hf.File.Sync()
hfLog.WithField("op", "write_page").WithField("seek", seek).WithField("write_size", n).Infof("write page to HeapFile")
return err
}
// NumPagesInFile get real num pages in file
func (hf HeapFile) NumPagesInFile() int64 {
info, err := hf.File.Stat()
if err != nil {
hfLog.WithError(err).WithField("id", hf.ID())
return 0
}
pageSize := int64(DB.B().PageSize())
return (info.Size() pageSize - 1) / pageSize
}
// InsertTuple insert tuple to the HeapPage
func (hf *HeapFile) InsertTuple(txID *TxID, tuple *Tuple) (ret []Page, err error) {
for i := 0; int64(i) <= hf.NumPagesInFile(); i {
HPID := NewHeapPageID(hf.ID(), i)
var page Page
if int64(i) < hf.NumPagesInFile() {
page, err = DB.B().GetPage(txID, HPID, PermReadWrite)
if err != nil {
return nil, err
}
} else {
page, err = NewHeapPage(NewHeapPageID(hf.ID(), i), HeapPageCreateEmptyPageData())
if err != nil {
return nil, err
}
}
heapPage, ok := page.(*HeapPage)
if !ok {
return nil, fmt.Errorf("assign page HeapPage error")
}
if heapPage.EmptyTupleNum() > 0 {
err = heapPage.InsertTuple(tuple)
if err != nil {
hfLog.WithError(err).WithField("page_id", page.PageID).Warn("can not insert to this page, so insert to next page")
continue
}
// flush newly created page to disk
if int64(i) == hf.NumPagesInFile() {
err = hf.WritePage(page)
if err != nil {
hfLog.WithError(err).WithField("page", page.PageID()).Error("write page error")
return nil, err
}
hfLog.WithField("pid", page.PageID).Infof("page full, write to disk")
}
ret = append(ret, heapPage)
return
}
}
return nil, fmt.Errorf("failed to insert this tuple")
}
// DeleteTuple del tuple to the HeapPage
func (hf *HeapFile) DeleteTuple(*TxID, *Tuple) ([]Page, error) {
panic("not implemented")
}
// TupleDesc return TupleDesc
func (hf HeapFile) TupleDesc() *TupleDesc {
return hf.TD
}
// Iterator DbFileIterator
func (hf *HeapFile) Iterator(txID *TxID) DbFileIterator {
return nil
}
var _ Page = (*HeapPage)(nil)
// HeapPage heap page
//
// file format:
//
// | header bit set | [Tuple][Tuple][Tuple][Tuple] |
type HeapPage struct {
PID *HeapPageID
TD *TupleDesc
Head []byte
Tuples []*Tuple
TxMarkDirty *TxID
}
// NewHeapPage new HeapPage
func NewHeapPage(pid *HeapPageID, data []byte) (*HeapPage, error) {
ret := HeapPage{}
ret.TD = DB.C().GetTableByID(pid.TableID()).TupleDesc()
ret.PID = pid
bufReader := bytes.NewReader(data)
ret.Head = make([]byte, ret.HeaderSize())
n, err := bufReader.Read(ret.Head)
if err != nil {
err = fmt.Errorf("read header error %v", err)
log.WithError(err).Warnf("read header error")
return nil, err
}
if n < ret.HeaderSize() {
err = fmt.Errorf("read head want %v, get %v", ret.HeaderSize(), n)
log.WithError(err).Warnf("read head error")
return nil, err
}
// TODO: implement here
ret.Tuples = make([]*Tuple, ret.NumOfTuples())
for i := 0; i < ret.NumOfTuples(); i {
ret.Tuples[i], err = ret.readNextTuple(bufReader, i)
if err != nil && err != io.EOF {
err = fmt.Errorf("read tuple %vth err: %v", i, err)
return nil, err
}
if err == io.EOF {
log.Debugf("read %vth tuple, and end", i)
}
}
return &ret, nil
}
// TupleDesc get the tuple desc
func (hp HeapPage) TupleDesc() *TupleDesc {
return hp.TD
}
// PageID get pageID
func (hp HeapPage) PageID() PageID {
return hp.PID
}
// Bitset get bitset
func (hp *HeapPage) Bitset() bitset.BitSet {
return bitset.Bytes(hp.Head)
}
// MarkDirty mark the page dirty
// if TxID is nil, Mark not dirty
func (hp *HeapPage) MarkDirty(txID *TxID) {
hp.TxMarkDirty = txID
}
// IsDirty if return *TxID != nil, is dirty
func (hp HeapPage) IsDirty() *TxID {
return hp.TxMarkDirty
}
// EmptyTupleNum num of empty tuple
func (hp HeapPage) EmptyTupleNum() (ret int) {
for i := 0; i < hp.NumOfTuples(); i {
if !hp.Bitset().Get(uint(i)) {
ret
}
}
return
}
// NumOfTuples retrieve the number of tuples on this page.
func (hp HeapPage) NumOfTuples() int {
return (DB.B().PageSize() * 8) / (hp.TD.Size()*8 1)
}
// HeaderSize computes the number of bytes in the header of
// a page in a HeapFile with each tuple occupying tupleSize bytes
func (hp HeapPage) HeaderSize() int {
return (hp.NumOfTuples() 7) / 8
}
func (hp HeapPage) readNextTuple(r io.Reader, slotID int) (*Tuple, error) {
// if page not used
if !hp.Bitset().Get(uint(slotID)) {
buf := make([]byte, hp.TD.Size())
n, err := r.Read(buf)
if err != nil {
return nil, err
}
if n != hp.TD.Size() {
err = fmt.Errorf("read size want: %v, get: %v", hp.TD.Size(), n)
return nil, err
}
assertEqual(n, hp.TD.Size())
return nil, nil
}
// else if page is used, read the Tuple
ret := &Tuple{TD: hp.TupleDesc(), RecordID: NewRecordID(hp.PageID(), slotID)}
for _, field := range hp.TD.TdItems {
f, err := field.Type.Parse(r)
if err != nil {
return nil, err
}
ret.Fields = append(ret.Fields, f)
}
return ret, nil
}
// InsertTuple insert one tuple one the page
func (hp *HeapPage) InsertTuple(tuple *Tuple) error {
if !hp.TupleDesc().Equal(tuple.TD) {
return fmt.Errorf("tuple desc is diff")
}
for i := 0; i < hp.NumOfTuples(); i {
if !hp.Bitset().Get(uint(i)) {
hp.Tuples[i] = tuple
tuple.RecordID = NewRecordID(hp.PID, i)
hp.Bitset().Set(uint(i))
return nil
}
}
return fmt.Errorf("page is full")
}
// MarshalBinary implement encoding.BinaryMarshaler
func (hp HeapPage) MarshalBinary() (data []byte, err error) {
data = make([]byte, DB.B().PageSize())
var n = copy(data, []byte(hp.Head))
tupleSize := hp.TupleDesc().Size()
var buf []byte
for index, tuple := range hp.Tuples {
if hp.Bitset().Get(uint(index)) {
buf, err = tuple.MarshalBinary()
if err != nil {
return nil, err
}
} else {
buf = make([]byte, tupleSize)
}
n = copy(data[n:], buf)
}
return
}
// Iterator iterator
func (hp *HeapPage) Iterator(txID *TxID) DbFileIterator {
return nil
}
var _ DbFileIterator = (*HeapPageDbFileIterator)(nil)
// HeapPageDbFileIterator HeapPage HeapPageDbFileIterator
type HeapPageDbFileIterator struct {
curPage int
iter OpIterator
txID *TxID
hf *HeapFile
Err error
}
// NewHeapPageDbFileIterator new HeapPageDbFileIterator with txID
func NewHeapPageDbFileIterator(txID *TxID, hf *HeapFile) *HeapPageDbFileIterator {
return &HeapPageDbFileIterator{
curPage: -1,
txID: txID,
hf: hf,
}
}
// Open open the iterator
func (it *HeapPageDbFileIterator) Open() error {
it.curPage = 0
for (int64(it.curPage)) < it.hf.NumPagesInFile() {
if it.iter == nil {
page, err := DB.B().GetPage(it.txID, NewHeapPageID(it.hf.ID(), it.curPage), PermReadOnly)
if it.Err = err; err != nil {
return it.Error()
}
hp, ok := page.(*HeapPage)
if !ok {
it.Err = fmt.Errorf("page is not HeapPage: %T", page)
return it.Error()
}
it.iter = NewTupleIterator(page.TupleDesc(), hp.Tuples)
it.Err = it.iter.Open()
if err = it.Error(); err != nil {
return err
}
}
if !it.iter.HasNext() {
it.curPage
it.iter = nil
} else {
return it.Error()
}
}
return it.Error()
}
// Close close
func (it *HeapPageDbFileIterator) Close() {
it.curPage = -1
it.iter = nil
}
// HasNext has next
func (it *HeapPageDbFileIterator) HasNext() bool {
return int64(it.curPage) < it.hf.NumPagesInFile() && it.iter != nil && it.iter.HasNext()
}
// Next next
func (it *HeapPageDbFileIterator) Next() (ret *Tuple) {
if it.curPage == -1 {
it.Err = fmt.Errorf("no such element, iterator has closed")
return nil
}
if !it.iter.HasNext() {
it.curPage
for int64(it.curPage) < it.hf.NumPagesInFile() {
// next page
page, err := DB.B().GetPage(it.txID, NewHeapPageID(it.hf.ID(), it.curPage), PermReadOnly)
if it.Err = err; err != nil {
return nil
}
hp, ok := page.(*HeapPage)
if !ok {
it.Err = fmt.Errorf("page is not HeapPage: %T", page)
return nil
}
it.iter = NewTupleIterator(page.TupleDesc(), hp.Tuples)
it.Err = it.iter.Open()
if err = it.Error(); err != nil {
return nil
}
if !it.iter.HasNext() {
it.curPage
} else {
break
}
}
}
if it.iter.HasNext() {
ret = it.iter.Next()
}
if ret == nil {
it.Err = fmt.Errorf("no element exists")
}
return
}
// Rewind rewind the iterator
func (it *HeapPageDbFileIterator) Rewind() error {
it.Close()
return it.Open()
}
// Error return err
func (it HeapPageDbFileIterator) Error() error {
return it.Err
}
// HeapPageCreateEmptyPageData create emptyPageDate
func HeapPageCreateEmptyPageData() []byte {
return make([]byte, DB.B().PageSize())
}