我正在尝试为我正在处理的数据应用程序设计基本的ORM。关于我想出的模型的问题有两个:
这是数据库跟踪的“最佳”,“最高效”模型吗?
这是惯用的Go吗?
这个想法是在应用程序启动时将数据库的完整模型加载到内存中。使用此模型来生成具有每个对象的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...")
}
在以下位置有可用的版本:http : //play.golang.org/p/XMTmynNy7t
浮云间
相关分类