搜尋
首頁後端開發GolangGorm:自訂資料類型先睹為快

歡迎回來,朋友? !今天,我們討論在資料庫之間來回移動資料時可能遇到的一個特定用例。首先,讓我為今天的挑戰設定界線。為了堅持現實生活中的例子,讓我們借用美國陸軍的一些概念?我們的任務是編寫一個小軟體來保存和讀取軍官在職業生涯中取得的成績。

Gorm 的自訂資料類型

我們的軟體需要處理軍官及其各自的等級。乍一看,這似乎很簡單,而且我們可能不需要任何自訂資料類型。但是,為了展示此功能,讓我們使用非常規方式來表示資料。因此,我們被要求定義 Go 結構和資料庫關係之間的自訂映射。此外,我們必須定義特定的邏輯來解析資料。讓我們透過查看該計劃的目標來擴展這一點? .

要處理的用例

為了方便起見,我們用一張圖來描述程式碼和 SQL 物件之間的關係:

Gorm: Sneak Peek of Custom Data Types

讓我們逐一關注每個容器。

Go 結構?

在這裡,我們定義了兩個結構體。 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 中翻譯為結構體)。

域/models.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
}

現在,讓我們突出顯示其中的相關部分? :

  1. Grade 結構只列出我們在軟體中預測的成績
  2. Officer 結構定義了實體的特徵。該實體是資料庫中的關係。我們應用了兩種 Gorm 符號:
    1. gorm:ID 欄位上的「primaryKey」將其定義為我們關係的主鍵
    2. gorm:"type:varchar[]" 將欄位 GradesAchieved 對應為資料庫中的 varchar 陣列。否則,它會轉換為單獨的資料庫表或軍官表中的附加列
  3. Grade 結構體實作了 Scan 函數。在這裡,我們取得原始值,調整它,在 g 變數上設定一些字段,然後返回
  4. Grade 結構體也將 Value 函數實作為值接收器類型(這次我們不需要更改接收器,我們不使用 * 引用)。我們傳回值寫入軍官表的 Grades_achieved 欄位

借助這兩種方法,我們可以控制在資料庫互動期間如何發送和檢索類型 Grade。現在,讓我們看一下 main.go 檔案。

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:

  • Removal of the table at the end of the main() function (when the program terminates, we would like to remove the table as well)
  • Seeding of some dummy data

Lastly, to ensure that everything works as expected, we do a couple of things:

  1. Fetching all the records in the DB
  2. Adding (and fetching back) a new officer

That's it for this file. Now, let's test our work ?.

The Truth Moment

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.

That's a Wrap

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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Golang行動:現實世界中的示例和應用程序Golang行動:現實世界中的示例和應用程序Apr 12, 2025 am 12:11 AM

Golang在实际应用中表现出色,以简洁、高效和并发性著称。1)通过Goroutines和Channels实现并发编程,2)利用接口和多态编写灵活代码,3)使用net/http包简化网络编程,4)构建高效并发爬虫,5)通过工具和最佳实践进行调试和优化。

Golang:Go編程語言解釋了Golang:Go編程語言解釋了Apr 10, 2025 am 11:18 AM

Go語言的核心特性包括垃圾回收、靜態鏈接和並發支持。 1.Go語言的並發模型通過goroutine和channel實現高效並發編程。 2.接口和多態性通過實現接口方法,使得不同類型可以統一處理。 3.基本用法展示了函數定義和調用的高效性。 4.高級用法中,切片提供了動態調整大小的強大功能。 5.常見錯誤如競態條件可以通過gotest-race檢測並解決。 6.性能優化通過sync.Pool重用對象,減少垃圾回收壓力。

Golang的目的:建立高效且可擴展的系統Golang的目的:建立高效且可擴展的系統Apr 09, 2025 pm 05:17 PM

Go語言在構建高效且可擴展的系統中表現出色,其優勢包括:1.高性能:編譯成機器碼,運行速度快;2.並發編程:通過goroutines和channels簡化多任務處理;3.簡潔性:語法簡潔,降低學習和維護成本;4.跨平台:支持跨平台編譯,方便部署。

SQL排序中ORDER BY語句結果為何有時看似隨機?SQL排序中ORDER BY語句結果為何有時看似隨機?Apr 02, 2025 pm 05:24 PM

關於SQL查詢結果排序的疑惑學習SQL的過程中,常常會遇到一些令人困惑的問題。最近,筆者在閱讀《MICK-SQL基礎�...

技術棧收斂是否僅僅是技術棧選型的過程?技術棧收斂是否僅僅是技術棧選型的過程?Apr 02, 2025 pm 05:21 PM

技術棧收斂與技術選型的關係在軟件開發中,技術棧的選擇和管理是一個非常關鍵的問題。最近,有讀者提出了...

如何在Go語言中使用反射對比並處理三個結構體的差異?如何在Go語言中使用反射對比並處理三個結構體的差異?Apr 02, 2025 pm 05:15 PM

Go語言中如何對比並處理三個結構體在Go語言編程中,有時需要對比兩個結構體的差異,並將這些差異應用到第�...

在Go語言中如何查看全局安裝的包?在Go語言中如何查看全局安裝的包?Apr 02, 2025 pm 05:12 PM

在Go語言中如何查看全局安裝的包?在使用Go語言開發過程中,經常會使用go...

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器