欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

golang Gorm與數(shù)據(jù)庫完整性約束詳解

 更新時間:2020年12月21日 10:56:40   作者:edl7878  
這篇文章主要介紹了golang Gorm與數(shù)據(jù)庫完整性約束詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

數(shù)據(jù)庫約束要點:

主鍵約束(非空且唯一)外鍵約束 子表外鍵字段的值必須在主表被參照字段值得范圍內,或者為NULL;外鍵參照的必須是主表的主鍵或唯一鍵;主表主鍵/唯一鍵被子表參照時,主表相應記錄不允許被刪除

在golang中,采用orm對數(shù)據(jù)庫進行建模是比較方便的。grom是其中一個比較流行的orm工具。

本篇基于golang、grom1.91、和PostgreSQL來進行說明。

注:本文的例子是極端情況,一般情況只是單字段主鍵。

1、實體完整性:

每個關系(表)有且僅有一個主鍵,每一個主鍵值必須唯一,而且不允許為“空”(NULL)或重復。

type Product struct {
Code string `gorm:"primary_key"`
Price uint
UserID uint //`sql:"type:bigint REFERENCES users(id) on update no action on delete cascade"`
UserCode string //`sql:"type:bigint REFERENCES users(code) on update no action on delete cascade"`
User User //`gorm:"foreignkey:UserID;association_foreignkey:ID"`
gorm.Model
}

在利用gorm的db對象創(chuàng)建表,其使用的SQL如下:

CREATE TABLE public.products
(
 code text COLLATE pg_catalog."default" NOT NULL,
 price integer,
 user_id integer,
 user_code text COLLATE pg_catalog."default",
 id integer NOT NULL DEFAULT nextval('products_id_seq'::regclass),
 created_at timestamp with time zone,
 updated_at timestamp with time zone,
 deleted_at timestamp with time zone,
 CONSTRAINT products_pkey PRIMARY KEY (code, id)
)
WITH (
 OIDS = FALSE
)
TABLESPACE pg_default; 
ALTER TABLE public.products
 OWNER to postgres; 
 
-- Index: idx_products_deleted_at 
 
-- DROP INDEX public.idx_products_deleted_at; 
 
CREATE INDEX idx_products_deleted_at
 ON public.products USING btree
 (deleted_at)
 TABLESPACE pg_default;

說明:

1.1、grom.Model是gorm預定義的結構,用于實現(xiàn)軟刪除,定義如下:

type Model struct {
 ID uint `gorm:"primary_key"`
 CreatedAt time.Time
 UpdatedAt time.Time
 DeletedAt *time.Time `sql:"index"`
}

它里面已經定義了主鍵,在本例中,我們還定義了一個主鍵:

Code string `gorm:"primary_key"`

從SQL輸出我們看到:

CONSTRAINT products_pkey PRIMARY KEY (code, id)

因此,Gorm實現(xiàn)了完全的實體完整性支持,即可以支持字段主鍵,也可以支持聯(lián)合主鍵。

1.2、對比結構體和sql語句可以看出

1.2.1 表名=結構體名小寫的復數(shù) 例子:Product變?yōu)?products

1.2.2 字段名=結構體成員名大寫分隔的子串小寫形式用下劃線連接 例子:ID變?yōu)閕d CreatedAt變?yōu)閏reated_at

1.3、前述1.1和1.2構成了Gorm的convention,它的文檔里有,默認情況下,就是這么處理,但是用戶可以不用gorm.Model,自定義表名、字段名,都可以支持。

2、域完整性:

是指數(shù)據(jù)庫表中的列必須滿足某種特定的數(shù)據(jù)類型或約束,又叫用戶定義完整性。包括:字段類型、值域、小數(shù)位數(shù)、CHECK、FOREIGN KEY 約束和DEFAULT、 NOT NULL。它們有的定義在字段上,有的定義在表上。例如:FOREIGN KEY 約束在PostgresSQL中,就是在表級別定義的;而,字段類型、長度、小數(shù)位數(shù)就是在字段上定義的。

2.1 通過結構體tag

`gorm:"xxx"` ,在字段上可以使用:type、size、precision、not null、default,Gorm就可以完成這些域完整性的定義

2.2 FOREIGN KEY 約束

2.2.1 單字段外鍵約束

type Product struct {
 Code string //`gorm:"primary_key"`
 Price uint
 UserID uint //`sql:"type:bigint REFERENCES users(id) on update no action on delete cascade"`
  //UserCode string //`sql:"type:bigint REFERENCES users(code) on update no action on delete cascade"`
 User User //`gorm:"foreignkey:UserID;association_foreignkey:ID"`
 gorm.Model
}
type User struct {
  //Code string `gorm:"primary_key"`
 Name string
 gorm.Model
  //Product Product //`gorm:"EMBEDDED"`
}

上面的代碼按照gorm文檔,創(chuàng)建了一個products belongs to user關系。執(zhí)行的sql是:

CREATE TABLE "users" ("code" text,"name" text,"id" serial,"created_at" timestamp with time zone,"updated_at" timestamp with time zone,"deleted_at" timestamp with time zone , PRIMARY KEY ("code","id"))
CREATE TABLE "users" ("code" text,"name" text,"id" serial,"created_at" timestamp with time zone,"updated_at" timestamp with time zone,"deleted_at" timestamp with time zone , PRIMARY KEY ("code","id"))

我們看到,gorm沒有添加任何約束。按照Gorm文檔,這就是belongs to標準定義。

它不添加外鍵約束。

那么,改為顯式標準的形式,采用foreignkey tag呢?

type Product struct {
 Code string //`gorm:"primary_key"`
 Price uint
 UserID uint //`sql:"type:integer REFERENCES users(id)`// on update no action on delete cascade"`
  //UserCode string //`sql:"type:bigint REFERENCES users(code) on update no action on delete cascade"`
  //UserID uint
 User User `gorm:"foreignkey:UserID;association_foreignkey:ID"` //`gorm:"foreignkey:UserID;association_foreignkey:ID"`
 gorm.Model
}
type User struct {
  //Code string `gorm:"primary_key"`
 Name string
 gorm.Model
  //Product Product //`gorm:"EMBEDDED"`
}

執(zhí)行的sql是:

CREATE TABLE "users" ("name" text,"id" serial,"created_at" timestamp with time zone,"updated_at" timestamp with time zone,"deleted_at" timestamp with time zone , PRIMARY KEY ("id")) 
CREATE TABLE "products" ("code" text,"price" integer,"user_id" integer,"id" serial,"created_at" timestamp with time zone,"updated_at" timestamp with time zone,"deleted_at" timestamp with time zone , PRIMARY KEY ("id")) 

也沒有添加任何外鍵約束。

因此,gorm tag 的 foreignkey 和 association_foreignkey并不會添加外鍵約束。

但是,我們可以用sql tag來添加外鍵約束?。?!如下:

type Product struct {
 Code string //`gorm:"primary_key"`
 Price uint
 UserID uint `sql:"type:integer REFERENCES users(id) on update no action on delete no action"`
  //UserCode string //`sql:"type:bigint REFERENCES users(code) on update no action on delete cascade"`
  //UserID uint
 User User `gorm:"foreignkey:UserID;association_foreignkey:ID"` //`gorm:"foreignkey:UserID;association_foreignkey:ID"`
 gorm.Model
}
type User struct {
  //Code string `gorm:"primary_key"`
 Name string
 gorm.Model
  //Product Product //`gorm:"EMBEDDED"`
}

創(chuàng)建products表的語句:

 CREATE TABLE "products" ("code" text,"price" integer,"user_id" integer REFERENCES users(id) on update no action on delete no action,"id" serial,"created_at" timestamp with time zone,"updated_at" timestamp with time zone,"deleted_at" timestamp with time zone , PRIMARY KEY ("id"))

注意,當使用sql tag時,不像gorm tag,它要你用數(shù)據(jù)庫表名和字段名,而gorm就只需要你使用結構體和其成員名即可。

外鍵被定義了,此時,可以滿足外鍵約束,如前述,具體是:

子表外鍵字段的值必須在主表被參照字段值得范圍內,或者為NULL;外鍵參照的必須是主表的主鍵或唯一鍵;主表主鍵/唯一鍵被子表參照時,主表相應記錄不允許被刪除

此時外鍵約束的名字是數(shù)據(jù)庫自己取的,可能長了,你可以自定義:

UserID uint `sql:"type:integer constraint ref REFERENCES users(id) on update no action on delete no action"`

加上 constraint xxx,就可以為約束取名為xx了。

上述外鍵約束是在定義結構體時,在結構體成員上定義的,因此翻譯為sql語句就變成了對字段的外鍵約束,那如果要定義參照聯(lián)合主鍵之類的外鍵呢?就不能在結構體中定義,而要使用gorm的api了。

2.2.2 多字段外鍵約束

type Product struct {
 Code string //`gorm:"primary_key"`
 Price uint
  //UserID uint `sql:"type:integer REFERENCES users(id) on update no action on delete no action"`
  //UserCode string //`sql:"type:bigint REFERENCES users(code) on update no action on delete cascade"`
 UserCode string
 UserID uint
 User User //`gorm:"foreignkey:UserID;association_foreignkey:ID"`//`gorm:"foreignkey:UserID;association_foreignkey:ID"`
 gorm.Model
}
type User struct {
 Code string `gorm:"primary_key"`
 Name string
 gorm.Model
  //Product Product //`gorm:"EMBEDDED"`
}

在程序中使用:

postgres. Model( &Product{}). AddForeignKey( "user_id,user_code", "users(id,code)", "no action", "no action")

這樣,products表就有約束:

CONSTRAINT products_user_id_user_code_users_id_code_foreign FOREIGN KEY (user_code, user_id)
REFERENCES public.users (code, id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION

如此就OK了。這里約束的名字就很長了,api沒有給你自己取名字的機會。

2.3 check約束

type Product struct {
 Code string //`gorm:"primary_key"`
 Price uint
 UserID uint `sql:"type:integer check(code!='')"`
 UserCode string //`sql:"type:bigint constraint ref REFERENCES users(code) on update no action on delete cascade"`
  //UserCode string
  //UserID uint
 User User //`gorm:"foreignkey:UserID;association_foreignkey:ID"`//`gorm:"foreignkey:UserID;association_foreignkey:ID"`
 gorm.Model
}

這樣就行。看起來這個check和userID沒有什么關系,是的,check會被定義到表上:

ALTER TABLE public.products

ADD CONSTRAINT products CHECK (code <> ''::text);

因此,Check也完美了,找個結構體的字段,然后加上check就行了。

3、參照完整性:

對于永久關系的相關表,在更新、插入或刪除記錄時,如果只改其一,就會影響數(shù)據(jù)的完整性。對于更新、插入或刪除表間數(shù)據(jù)的完整性,統(tǒng)稱為參照完整性。

對于外鍵約束,插入參照完整性被滿足。因此,如前述:

UserID uint `sql:"type:integer REFERENCES users(id) on update no action on delete no action"`

定義好on update 和 on delete的參數(shù),就可以滿足參照完整性。

具體改為:

UserID uint `sql:"type:integer REFERENCES users(id) on update cascade on delete cascade"`

即可,而且數(shù)據(jù)庫還允許有別的選擇,這里是級聯(lián)更新和級聯(lián)刪除,主表已刪除,子表就跟著刪,這是數(shù)據(jù)庫參照完整性的原初定義。

ps. gorm不默認實施參照完整性,不加約束的原因查了其git issue,主要是因為postgresql要求被關聯(lián)的表要先存在。而這會導致創(chuàng)建表和自動升級表migration的順序依賴,所以用戶要sqltag或者調用api手動實施。

4、*1對多 和 多對多關系

這不屬于完整性范疇。

4.1 1對多

1對多不需要實施完整性約束,因為用戶可以對應0到多個產品。因此,表結構里無需添加額外的約束。

type Product struct {
 Code string //`gorm:"primary_key"`
 Price uint
  //UserID uint `sql:"type:integer constraint ref REFERENCES users(id) on update no action on delete no action check(code!='')"`
  //UserCode string //`sql:"type:bigint constraint ref REFERENCES users(code) on update no action on delete cascade"`
  //UserCode string
  //UserID uint
  //User User //`gorm:"foreignkey:UserID;association_foreignkey:ID"`//`gorm:"foreignkey:UserID;association_foreignkey:ID"`
 gorm.Model
 UserID uint
}
type User struct {
 Code string //`gorm:"primary_key"`
 Name string
 gorm.Model
 Products []Product
  //Product Product //`gorm:"EMBEDDED"`
}

上面是gorm一對多的典型定義,users表不會多任何字段,product表會多user_id字段。這里UserID是外鍵。也可以顯式定義,foreignkey 和Association ForeignKey 上例相當于:

type Product struct {
 Code string //`gorm:"primary_key"`
 Price uint
  //UserID uint `sql:"type:integer constraint ref REFERENCES users(id) on update no action on delete no action check(code!='')"`
  //UserCode string //`sql:"type:bigint constraint ref REFERENCES users(code) on update no action on delete cascade"`
  //UserCode string
  //UserID uint
  //User User //`gorm:"foreignkey:UserID;association_foreignkey:ID"`//`gorm:"foreignkey:UserID;association_foreignkey:ID"`
 gorm.Model
 UserID uint
}
type User struct {
 Code string //`gorm:"primary_key"`
 Name string
 gorm.Model
 Products []Product `gorm:"foreignkey:UserID"`
  //Product Product //`gorm:"EMBEDDED"`
}

4.2 多對多

在關系型數(shù)據(jù)庫中,多對多關系需要多一張表,總共3張表,完整性grom是如何保證的?

type Product struct {
 Code string //`gorm:"primary_key"`
 Price uint
  //UserID uint `sql:"type:integer constraint ref REFERENCES users(id) on update no action on delete no action check(code!='')"`
  //UserCode string //`sql:"type:bigint constraint ref REFERENCES users(code) on update no action on delete cascade"`
  //UserCode string
  //UserID uint
  //User User //`gorm:"foreignkey:UserID;association_foreignkey:ID"`//`gorm:"foreignkey:UserID;association_foreignkey:ID"`
 gorm.Model
  //UserID uint
}
type User struct {
 Code string //`gorm:"primary_key"`
 Name string
 gorm.Model
 Products []Product `gorm:"many2many:user_language"`
  //Product Product //`gorm:"EMBEDDED"`
}

此時,會多一個表(jointtable連接表):

CREATE TABLE "user_language" ("user_id" integer,"product_id" integer, PRIMARY KEY ("user_id","product_id"))

products和users表的主鍵,被聯(lián)合作為新表的主鍵。在新表中,user_id和product_id也是外鍵,在Gorm中,是可以在many2many關系中自定義外鍵、關聯(lián)外鍵的。當然,外鍵約束就不要想了。

那么,在上例中,按照grom的語法,對于Products成員,外鍵和關聯(lián)外鍵分別是什么呢?簡言之,在gorm所有情況下,將嵌入結構體和其父結構體關聯(lián)起來的那個字段,就是外鍵;關聯(lián)外鍵是寫入外鍵的值的來源對應的鍵,通常就是父結構體的主鍵。在多對多情況下,如上例,連接表的user_id是外鍵,而寫入時,并沒有將user_id寫入Products []Product,寫入的是product_id代表的數(shù)據(jù),因此product_id是associate_foreignkey,這是gorm的約定,很費解,解釋也牽強。

下面是多對多自引用:

type User struct {
 gorm.Model
 Friends []*User `gorm:"many2many:friendships;association_jointable_foreignkey:friend_id"`
}

用association_jointable_foreignkey在連接表里創(chuàng)建了一個字段。也比較費解。

綜上:

1、字段的基本約束,通過gorm tag基本都可以設置。

2、gorm支持實體完整性約束。

3、域完整性約束中,外鍵約束需要通過 sql tag或調用api實現(xiàn),check約束可以直接在字段上定義。

4、參照完整性gorm不能默認實現(xiàn),必須通過sql tag或者調用api實現(xiàn)。

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

相關文章

  • 對Go語言中的context包源碼分析

    對Go語言中的context包源碼分析

    這篇文章主要對Go語言中的context包源碼進行分析,context包析是1.15,context包定義了一個Context類型過這個Context接口類型,?就可以跨api邊界/跨進程傳遞一些值,下面我們就來對context包源碼進行分析,需要的小伙伴可以參考一下
    2022-02-02
  • Go語言基礎知識總結(語法、變量、數(shù)值類型、表達式、控制結構等)

    Go語言基礎知識總結(語法、變量、數(shù)值類型、表達式、控制結構等)

    這篇文章主要介紹了Go語言基礎知識總結(語法、變量、數(shù)值類型、表達式、控制結構等),本文匯總了Go語言的入門知識,需要的朋友可以參考下
    2014-10-10
  • go語言定時器Timer及Ticker的功能使用示例詳解

    go語言定時器Timer及Ticker的功能使用示例詳解

    這篇文章主要為大家介紹了go語言定時器的功能使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步早日升職加薪
    2022-04-04
  • GoLang channel底層代碼實現(xiàn)詳解

    GoLang channel底層代碼實現(xiàn)詳解

    Channel和goroutine的結合是Go并發(fā)編程的大殺器。而Channel的實際應用也經常讓人眼前一亮,通過與select,cancel,timer等結合,它能實現(xiàn)各種各樣的功能。接下來,我們就要梳理一下GoLang channel底層代碼實現(xiàn)
    2022-10-10
  • golang中的defer函數(shù)理解

    golang中的defer函數(shù)理解

    defer是Go語言中的延遲執(zhí)行語句,用來添加函數(shù)結束時執(zhí)行的代碼,常用于釋放某些已分配的資源、關閉數(shù)據(jù)庫連接、斷開socket連接、解鎖一個加鎖的資源,這篇文章主要介紹了golang中的defer函數(shù)理解,需要的朋友可以參考下
    2022-10-10
  • Golang生成Excel文檔的方法步驟

    Golang生成Excel文檔的方法步驟

    生成Excel是一個很常見的需求,本文將介紹如何使用Go的 Excelize庫去生成Excel文檔,以及一些具體場景下的代碼實現(xiàn),感興趣的可以參考一下
    2021-06-06
  • Golang中的錯誤處理深入分析

    Golang中的錯誤處理深入分析

    Go錯誤處理類似C語言,沒有提供任何異常,以及類java語言使用的try/catch異常處理機制。Go異常處理僅簡化為預定義的Error類型,Go沒有提供異常處理機制,不能拋出類似許多其他語言的異常。相反,Golang集成了新的錯誤處理機制,如panic和recovery
    2023-01-01
  • Go?對多個網絡命令空間中的端口進行監(jiān)聽的解決方案

    Go?對多個網絡命令空間中的端口進行監(jiān)聽的解決方案

    這篇文章主要介紹了Go?如何對多個網絡命令空間中的端口進行監(jiān)聽,本文給大家介紹的非常詳細,需要的朋友可以參考下
    2024-07-07
  • 解決go 生成的exe不在bin文件夾里的問題

    解決go 生成的exe不在bin文件夾里的問題

    這篇文章主要介紹了解決go 生成的exe不在bin文件夾里的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-12-12
  • Golang中可比較的數(shù)據(jù)類型詳解

    Golang中可比較的數(shù)據(jù)類型詳解

    在日常開發(fā)中,比較操作是最常用的基本操作之一,可以用來判斷變量之間是否相等或者對應的大小關系,本文將深入解析 Golang 中可比較的數(shù)據(jù)類型,并結合代碼示例來說明如何在不同情況下進行比較,需要的朋友可以參考下
    2024-01-01

最新評論