歡迎回來,朋友? !今天,我們討論在資料庫之間來回移動資料時可能遇到的一個特定用例。首先,讓我為今天的挑戰設定界線。為了堅持現實生活中的例子,讓我們借用美國陸軍的一些概念?我們的任務是編寫一個小軟體來保存和讀取軍官在職業生涯中取得的成績。
我們的軟體需要處理軍官及其各自的等級。乍一看,這似乎很簡單,而且我們可能不需要任何自訂資料類型。但是,為了展示此功能,讓我們使用非常規方式來表示資料。因此,我們被要求定義 Go 結構和資料庫關係之間的自訂映射。此外,我們必須定義特定的邏輯來解析資料。讓我們透過查看該計劃的目標來擴展這一點? .
為了方便起見,我們用一張圖來描述程式碼和 SQL 物件之間的關係:
讓我們逐一關注每個容器。
在這裡,我們定義了兩個結構體。 Grade 結構體包含軍事等級的非詳盡清單? ️。該結構不會是資料庫中的表。相反,Officer 結構體包含 ID、姓名和指向 Grade 結構體的指針,指示該軍官到目前為止已取得的成績。
每當我們寫入資料庫到資料庫時,grades_achieved 欄位必須包含一個字串數組,其中填入了所達到的成績(Grade 結構中具有 true 的成績)。
關於 SQL 對象,我們只有軍官表。 id 和 name 欄位是不言自明的。然後,我們有 Grades_achieved 列,將軍官的成績保存在字串集合中。
每當我們從資料庫解碼官員時,我們都會解析 Grades_achieved 列並建立 Grade 結構的匹配「實例」。
您可能已經注意到這種行為不是標準行為。我們必須做出一些安排,以理想的方式實現它。
這裡,模型的佈局故意過於複雜。請盡可能堅持使用更簡單的解決方案。
Gorm 為我們提供了自訂資料類型。它們為我們定義資料庫的檢索和保存提供了極大的靈活性。我們必須實作兩個介面:Scanner 和 Valuer? 。前者指定從資料庫取得資料時要套用的自訂行為。後者指示如何將值寫入資料庫。兩者都幫助我們實現我們需要的非常規映射邏輯。
我們必須實作的函數簽章是 Scan(value interface{}) error 和 Value() (driver.Value, error)。現在,讓我們來看看程式碼。
此範例的程式碼位於兩個檔案中:domain/models.go 和 main.go。讓我們從第一個開始,處理模型(在 Go 中翻譯為結構體)。
首先,讓我先展示這個檔案的程式碼:
package models import ( "database/sql/driver" "slices" "strings" ) type Grade struct { Lieutenant bool Captain bool Colonel bool General bool } type Officer struct { ID uint64 `gorm:"primaryKey"` Name string GradesAchieved *Grade `gorm:"type:varchar[]"` } func (g *Grade) Scan(value interface{}) error { // we should have utilized the "comma, ok" idiom valueRaw := value.(string) valueRaw = strings.Replace(strings.Replace(valueRaw, "{", "", -1), "}", "", -1) grades := strings.Split(valueRaw, ",") if slices.Contains(grades, "lieutenant") { g.Lieutenant = true } if slices.Contains(grades, "captain") { g.Captain = true } if slices.Contains(grades, "colonel") { g.Colonel = true } if slices.Contains(grades, "general") { g.General = true } return nil } func (g Grade) Value() (driver.Value, error) { grades := make([]string, 0, 4) if g.Lieutenant { grades = append(grades, "lieutenant") } if g.Captain { grades = append(grades, "captain") } if g.Colonel { grades = append(grades, "colonel") } if g.General { grades = append(grades, "general") } return grades, nil }
現在,讓我們突出顯示其中的相關部分? :
借助這兩種方法,我們可以控制在資料庫互動期間如何發送和檢索類型 Grade。現在,讓我們看一下 main.go 檔案。
在這裡,我們準備資料庫連接,將物件遷移到關係中(ORM 代表Object Relation Mapping),然後插入和取得記錄下來測試邏輯。下面是程式碼:
package main import ( "encoding/json" "fmt" "os" "gormcustomdatatype/models" "gorm.io/driver/postgres" "gorm.io/gorm" ) func seedDB(db *gorm.DB, file string) error { data, err := os.ReadFile(file) if err != nil { return err } if err := db.Exec(string(data)).Error; err != nil { return err } return nil } // docker run -d -p 54322:5432 -e POSTGRES_PASSWORD=postgres postgres func main() { dsn := "host=localhost port=54322 user=postgres password=postgres dbname=postgres sslmode=disable" db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) if err != nil { fmt.Fprintf(os.Stderr, "could not connect to DB: %v", err) return } db.AutoMigrate(&models.Officer{}) defer func() { db.Migrator().DropTable(&models.Officer{}) }() if err := seedDB(db, "data.sql"); err != nil { fmt.Fprintf(os.Stderr, "failed to seed DB: %v", err) return } // print all the officers var officers []models.Officer if err := db.Find(&officers).Error; err != nil { fmt.Fprintf(os.Stderr, "could not get the officers from the DB: %v", err) return } data, _ := json.MarshalIndent(officers, "", "\t") fmt.Fprintln(os.Stdout, string(data)) // add a new officer db.Create(&models.Officer{ Name: "Monkey D. Garp", GradesAchieved: &models.Grade{ Lieutenant: true, Captain: true, Colonel: true, General: true, }, }) var garpTheHero models.Officer if err := db.First(&garpTheHero, 4).Error; err != nil { fmt.Fprintf(os.Stderr, "failed to get officer from the DB: %v", err) return } data, _ = json.MarshalIndent(&garpTheHero, "", "\t") fmt.Fprintln(os.Stdout, string(data)) }
Now, let's see the relevant sections of this file. First, we define the seedDB function to add dummy data in the DB. The data lives in the data.sql file with the following content:
INSERT INTO public.officers (id, "name", grades_achieved) VALUES(nextval('officers_id_seq'::regclass), 'john doe', '{captain,lieutenant}'), (nextval('officers_id_seq'::regclass), 'gerard butler', '{general}'), (nextval('officers_id_seq'::regclass), 'chuck norris', '{lieutenant,captain,colonel}');
The main() function starts by setting up a DB connection. For this demo, we used PostgreSQL. Then, we ensure the officers table exists in the database and is up-to-date with the newest version of the models.Officer struct. Since this program is a sample, we did two additional things:
Lastly, to ensure that everything works as expected, we do a couple of things:
That's it for this file. Now, let's test our work ?.
Before running the code, please ensure that a PostgreSQL instance is running on your machine. With Docker ?, you can run this command:
docker run -d -p 54322:5432 -e POSTGRES_PASSWORD=postgres postgres
Now, we can safely run our application by issuing the command: go run . ?
The output is:
[ { "ID": 1, "Name": "john doe", "GradesAchieved": { "Lieutenant": true, "Captain": true, "Colonel": false, "General": false } }, { "ID": 2, "Name": "gerard butler", "GradesAchieved": { "Lieutenant": false, "Captain": false, "Colonel": false, "General": true } }, { "ID": 3, "Name": "chuck norris", "GradesAchieved": { "Lieutenant": true, "Captain": true, "Colonel": true, "General": false } } ] { "ID": 4, "Name": "Monkey D. Garp", "GradesAchieved": { "Lieutenant": true, "Captain": true, "Colonel": true, "General": true } }
Voilà! Everything works as expected. We can re-run the code several times and always have the same output.
I hope you enjoyed this blog post regarding Gorm and the Custom Data Types. I always recommend you stick to the most straightforward approach. Opt for this only if you eventually need it. This approach adds flexibility in exchange for making the code more complex and less robust (a tiny change in the structs' definitions might lead to errors and extra work needed).
Keep this in mind. If you stick to conventions, you can be less verbose throughout your codebase.
That's a great quote to end this blog post.
If you realize that Custom Data Types are needed, this blog post should be a good starting point to present you with a working solution.
Please let me know your feelings and thoughts. Any feedback is always appreciated! If you're interested in a specific topic, reach out, and I'll shortlist it. Until next time, stay safe, and see you soon!
以上是Gorm:自訂資料類型先睹為快的詳細內容。更多資訊請關注PHP中文網其他相關文章!