⚠
The web version only has simple instructions since chapter 04, while the full book has detailed explanations and background info.
0204: CRUD
Add CRUD APIs
This step implements primary-key based CRUD (create, read, update, delete), matching insert, select, update, delete.
type DB struct {
KV KV
}
func (db *DB) Open() error { return db.KV.Open() }
func (db *DB) Close() error { return db.KV.Close() }Use KV get, set, del to implement:
func (db *DB) Select(schema *Schema, row Row) (ok bool, err error)
func (db *DB) Insert(schema *Schema, row Row) (updated bool, err error)
func (db *DB) Upsert(schema *Schema, row Row) (updated bool, err error)
func (db *DB) Update(schema *Schema, row Row) (updated bool, err error)
func (db *DB) Delete(schema *Schema, row Row) (deleted bool, err error)Requirements:
- select, delete: input row contains the primary key.
- insert, upsert, update: input row is complete.
For example, insert:
func (db *DB) Insert(schema *Schema, row Row) (updated bool, err error) {
key := row.EncodeKey(schema)
val := row.EncodeVal(schema)
return db.KV.SetEx(key, val, ModeInsert)
}For table create table t (a int64, b int64, primary key (b)), Select() takes a Row of length 2. Column 2 is the primary key. Column 1 is the value returned from KV.
Major Features of Relational Databases
Besides single-row access by primary key, later steps may add:
- Full table scan.
- Query by index.
- Range query by index or primary key.
- Filter query results.
ⓘ
CodeCrafters.io has similar courses in many programming languages, including build your own Redis, SQLite, Docker, etc. It’s worth checking out.