我正在尝试为我正在开发的数据应用程序设计一个基本的 ORM。我对我提出的模型的问题有两个:
- 这是数据库跟踪的“最佳”最“有效”模型吗?
- 这是惯用的围棋吗?
这个想法是在应用程序启动时将数据库的完整模型加载到内存中。使用此模型生成一个带有每个对象的 crc32 散列的映射(对应于数据库中的一行)。这就是我们用来与模型进行比较的方法,以明确在调用 .save() 时所做的更改。
以下第一部分生成 crc32 映射,第二部分引入随机更改,最后一部分将是 .save() 的一部分,用于将 db 更改写入磁盘
编码:
func main() {
// Read data off of disk into memory
memDB := ddb
// Create hash map of memDB
peopleMap := make(map[int]uint32)
for _, v := range memDB.people {
// make row into byte array, looks kludgy
hash := []byte(fmt.Sprintf("%#v", v))
peopleMap[v.pID] = crc32.ChecksumIEEE(hash)
fmt.Printf("%v: %v %v \t(%v %v) - crc sum: %v\n",
v.pID, v.fName, v.lName, v.job, v.location,
peopleMap[v.pID])
}
fmt.Println("\n# of people in memory:", len(memDB.people))
// Sometime later, we need to delete Danielle, so
// Delete in memory:
var tmpSlice []ddPerson
for _, v := range memDB.people {
if v.fName == "Danielle" {
continue
}
tmpSlice = append(tmpSlice, v)
}
memDB.people = tmpSlice
fmt.Println("# of people in memory:", len(memDB.people))
// Okay, we save in-memory representation mem.DB back
// to disk with some kind of .save() assertion
// a len(peopleMap) comparison to len(memDB.people) will
// tell us there has been a change for INSERTS and
// DELETES, but it won't tell us about updates or which
// record was inserted or deleted
// First, check for additions
if len(peopleMap) < len(memDB.people) {
// Code to find and add person to disk db ddb here
fmt.Println("Adding someone to disk database...")
} else if len(peopleMap) > len(memDB.people) {
// Check for deletions
fmt.Println("Purging someone from disk database...")
}
// in any case, recheck hashes
tMap := make(map[int]uint32)
for _, v := range memDB.people {
hash := []byte(fmt.Sprintf("%#v", v))
t := crc32.ChecksumIEEE(hash)
// Add to temporary map
tMap[v.pID] = t
// And check for changes
if t != peopleMap[v.pID] {
fmt.Println("Change detected in in-memory model...")
fmt.Println("Writing changes to disk db now")
// Writing any changes to DB here
ddb.people = memDB.people
}
}
// 'Fix' our hashmap checker deal
peopleMap = tMap
// Carry on
}