在Go中实现一个基本的ORM

huangapple go评论89阅读模式
英文:

Implementing a basic ORM in Go

问题

我正在尝试为我正在开发的数据应用设计一个基本的ORM。我对我设计的模型有两个问题:

  • 这是数据库跟踪的“最佳”和“最高效”的模型吗?
  • 这符合Go的惯用方式吗?

这个想法是在应用程序启动时将完整的数据库模型加载到内存中。使用这个模型生成一个包含每个对象(对应数据库中的一行)的crc32哈希的映射。这是我们用来与模型进行比较,找出在调用.save()时发生了哪些具体的更改。

以下代码的第一部分生成crc32映射,第二部分引入了一个随机更改,最后一部分将是.save()的一部分,用于将数据库更改写入磁盘。

代码:

func main() {
	// 从磁盘读取数据到内存
	memDB := ddb

	// 创建memDB的哈希映射
	peopleMap := make(map[int]uint32)
	for _, v := range memDB.people {
		// 将行转换为字节数组,看起来有点笨拙
		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内存中的人数:", len(memDB.people))

	// 以后的某个时候,我们需要删除Danielle,所以
	// 在内存中删除:
	var tmpSlice []ddPerson
	for _, v := range memDB.people {
		if v.fName == "Danielle" {
			continue
		}
		tmpSlice = append(tmpSlice, v)
	}
	memDB.people = tmpSlice
	fmt.Println("内存中的人数:", len(memDB.people))

	// 好的,我们使用某种.save()断言将内存中的表示mem.DB保存回磁盘
	// 通过比较len(peopleMap)和len(memDB.people)来判断是否有更改
	// 对于插入和删除,但它不会告诉我们有关更新的信息或插入或删除的记录是哪个

	// 首先,检查是否有添加
	if len(peopleMap) < len(memDB.people) {
		// 在此处查找并将人员添加到磁盘数据库ddb的代码
		fmt.Println("向磁盘数据库添加人员...")
	} else if len(peopleMap) > len(memDB.people) {
		// 检查是否有删除
		fmt.Println("从磁盘数据库中删除人员...")
	}

	// 无论如何,重新检查哈希值
	tMap := make(map[int]uint32)
	for _, v := range memDB.people {
		hash := []byte(fmt.Sprintf("%#v", v))
		t := crc32.ChecksumIEEE(hash)
		// 添加到临时映射
		tMap[v.pID] = t
		// 并检查更改
		if t != peopleMap[v.pID] {
			fmt.Println("检测到内存模型中的更改...")
			fmt.Println("现在将更改写入磁盘数据库")
			// 在此处写入任何更改到数据库
			ddb.people = memDB.people
		}
	}

	// 修复我们的哈希映射检查器
	peopleMap = tMap

	// 继续
}

可以在此处找到一个可工作的版本:http://play.golang.org/p/XMTmynNy7t

英文:

I'm trying to design a basic ORM for a data app that I'm working on. My question about the model I came up with is 2-fold:

  • Is this the 'best' most 'efficient' model for database tracking?
  • Is this idiomatic Go?

The idea is to load a complete model of the db into memory at app start. Use this model to generate a map with a crc32 hash of each object (corresponding to a row in the database). This is what we use to compare with model to find specifically where changes have been made when .save() is called.

The first part of the following generates the crc32 map, the second part introduces a random change, and the last part would be part of .save() to write db changes to disk

The code:

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(&quot;%#v&quot;, v))
		peopleMap[v.pID] = crc32.ChecksumIEEE(hash)
		fmt.Printf(&quot;%v: %v %v \t(%v %v) - crc sum: %v\n&quot;,
			v.pID, v.fName, v.lName, v.job, v.location,
			peopleMap[v.pID])
	}
	fmt.Println(&quot;\n# of people in memory:&quot;, 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 == &quot;Danielle&quot; {
			continue
		}
		tmpSlice = append(tmpSlice, v)
	}
	memDB.people = tmpSlice
	fmt.Println(&quot;# of people in memory:&quot;, 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&#39;t tell us about updates or which
	// record was inserted or deleted

	// First, check for additions
	if len(peopleMap) &lt; len(memDB.people) {
		// Code to find and add person to disk db ddb here
		fmt.Println(&quot;Adding someone to disk database...&quot;)
	} else if len(peopleMap) &gt; len(memDB.people) {
		// Check for deletions
		fmt.Println(&quot;Purging someone from disk database...&quot;)
	}

	// in any case, recheck hashes
	tMap := make(map[int]uint32)
	for _, v := range memDB.people {
		hash := []byte(fmt.Sprintf(&quot;%#v&quot;, v))
		t := crc32.ChecksumIEEE(hash)
		// Add to temporary map
		tMap[v.pID] = t
		// And check for changes
		if t != peopleMap[v.pID] {
			fmt.Println(&quot;Change detected in in-memory model...&quot;)
			fmt.Println(&quot;Writing changes to disk db now&quot;)
			// Writing any changes to DB here
			ddb.people = memDB.people
		}
	}

	// &#39;Fix&#39; our hashmap checker deal
	peopleMap = tMap

	// Carry on
}

There is a working version at: http://play.golang.org/p/XMTmynNy7t

答案1

得分: 1

你已经实现了一个内存缓存的数据库,但这并不是一个对象关系映射(ORM)。

你的实现存在几个问题:

  • 如果其他进程/应用程序修改了数据库,你的内存模型将会过时。这可能导致你的写操作覆盖了数据库的写操作,因为你不知道缓存已经过时了。
  • 如果数据库变得很大,你的应用程序也会变得很大。

大多数ORM提供了一种将类型(例如结构体)映射到数据库读写的方式。这样可以从数据库中读取一个对象,修改它,然后将该对象写回数据库。这可能是一个更好的方法。

至于你的Go代码是否符合惯用写法,我没有看到明显的非惯用写法,但代码中也没有太多内容。在顶部的memDb := ddb是一个函数调用,但你没有在它后面加上括号。这是一个语法错误。

英文:

You've implemented an in memory cache of your db which isn't really the same thing as an ORM.

There are several problems with what you have:

  • If some other process/application ever modifies the database your in memory model will be out of date. This could cause your writes to clobber writes to the db because you didn't know your cache was stale.
  • If the db gets large you're application will get correspondingly large.

Most ORM's provide a way to map a type (eg. structs) to a db read and write. This allows you to read a single object from the database modify it and then write that object back to the database. That is probably a better approach for this.

As for how idiomatic your go is I didn't see obviously non idiomatic go but there also isn't much going on in it. At the top memDb := ddb is a function call but you don't have parens after it. This is a syntax error.

答案2

得分: 0

在加载数据时生成校验和,然后在保存数据时再次生成校验和,对我来说似乎效率很低。

大多数使用数据库后端的Web应用程序直接对数据库进行更改。但显然你想要一个单独的“保存”操作,以便用户可以撤销他的更改...?

你考虑过使用事务吗?当用户开始编辑数据时,你可以发出一个BEGIN TRANSACTION命令。然后当他按下“保存”时,你会发出一个COMMIT命令,将更改永久存储在数据库中。如果用户撤销了他的更改或者在没有保存的情况下退出,你会发出一个ROLLBACK命令。

这里的问题与Go的惯用用法关系不大,而与SQL的惯用用法有关。

英文:

Generating a checksum when loading the data and again when saving it seems pretty inefficient to me.

Most web applications that use a database backend make changes directly to the database. But apparently you want to have a separate "Save" operation so that the user can back out of his changes…?

Have you considered using transactions? You could issue a BEGIN TRANSACTION command when the user starts editing the data. Then when he presses "Save", you would issue a COMMIT command, permanently storing the changes in the database. If the user backs out of his changes or quits without saving, you would issue a ROLLBACK command instead.

The issue here isn't so much about idiomatic use of Go as about idiomatic use of SQL.

huangapple
  • 本文由 发表于 2012年8月3日 11:49:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/11789012.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定