GORM 的 FirstOrCreate() 方法(或 Django 的 get_or_create)如何确保只创建一行?
How can GORM's FirstOrCreate() method (or Django's get_or_create) ensure that just one row is created?
我正在考虑将 GORM 用于一个应用程序,并且正在研究 FirstOrCreate
是如何工作的,它似乎使用了两个数据库操作。考虑这个示例脚本:
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/sirupsen/logrus"
)
type User struct {
gorm.Model
Name string
Age uint
}
func main() {
db, err := gorm.Open("sqlite3", "examplegorm.db")
if err != nil {
logrus.Fatalf("open db: %v", err)
}
defer db.Close()
db.LogMode(true)
db.AutoMigrate(&User{})
var user User
db.Where(User{Name: "non_existing"}).Attrs(User{Age: 20}).FirstOrCreate(&user)
}
在 运行 执行此操作并检查日志后,我发现(除了自动迁移之外)它使用了两个查询,一个 SELECT
和一个 INSERT
:
kurt@Kurts-MacBook-Pro-13 ~/D/Scratch> go run gorm_example.go
(/Users/kurt/Documents/Scratch/gorm_example.go:23)
[2020-01-05 09:09:10] [1.03ms] CREATE TABLE "users" ("id" integer primary key autoincrement,"created_at" datetime,"updated_at" datetime,"deleted_at" datetime,"name" varchar(255),"age" integer )
[0 rows affected or returned ]
(/Users/kurt/Documents/Scratch/gorm_example.go:23)
[2020-01-05 09:09:10] [0.86ms] CREATE INDEX idx_users_deleted_at ON "users"(deleted_at)
[0 rows affected or returned ]
(/Users/kurt/Documents/Scratch/gorm_example.go:26)
[2020-01-05 09:09:10] [0.28ms] SELECT * FROM "users" WHERE "users"."deleted_at" IS NULL AND (("users"."name" = 'non_existing')) ORDER BY "users"."id" ASC LIMIT 1
[0 rows affected or returned ]
(/Users/kurt/Documents/Scratch/gorm_example.go:26)
[2020-01-05 09:09:10] [0.31ms] INSERT INTO "users" ("created_at","updated_at","deleted_at","name","age") VALUES ('2020-01-05 09:09:10','2020-01-05 09:09:10',NULL,'non_existing',20)
[1 rows affected or returned ]
据我了解 ,但是,
In a SQL DBMS, the select-test-insert approach is a mistake: nothing prevents another process from inserting the "missing" row between your select
and insert
statements.
Django 的 get_or_create()
似乎以类似的方式工作。鉴于此模型,
from django.db import models
class User(models.Model):
name = models.CharField(max_length=255)
age = models.PositiveIntegerField()
如果我启用数据库日志记录和运行一个get_or_create()
查询,我会看到
In [1]: from djangoapp.models import *
In [2]: User.objects.get_or_create(name="jinzhu", age=20)
(0.000) SELECT "djangoapp_user"."id", "djangoapp_user"."name", "djangoapp_user"."age" FROM "djangoapp_user" WHERE ("djangoapp_user"."age" = 20 AND "djangoapp_user"."name" = 'jinzhu') LIMIT 21; args=(20, 'jinzhu')
(0.000) BEGIN; args=None
(0.000) INSERT INTO "djangoapp_user" ("name", "age") VALUES ('jinzhu', 20); args=['jinzhu', 20]
Out[2]: (<User: User object (1)>, True)
简而言之,如果我想确保只创建一条记录,似乎我应该避免使用 ORM(例如 GORM 或 Django ORM)并编写自己的查询?
我的第二个问题是如何在 GORM 中获得 Django 的 created
布尔值的等价物。我是否应该确定结果 gorm.DB
的 RowsAffected
是否为 1
以确定是否实际创建了一行?
您应该只在查询模型字段上添加 UNIQUE 约束,这足以使其在数据库中保持一致
对于将向模型
添加元 class 的 Django
class Meta:
unique_together = ['name', 'age']
对于 GORM
Name string `gorm:"unique_index:idx_name_age"`
Age uint `gorm:"unique_index:idx_name_age"`
我正在考虑将 GORM 用于一个应用程序,并且正在研究 FirstOrCreate
是如何工作的,它似乎使用了两个数据库操作。考虑这个示例脚本:
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/sirupsen/logrus"
)
type User struct {
gorm.Model
Name string
Age uint
}
func main() {
db, err := gorm.Open("sqlite3", "examplegorm.db")
if err != nil {
logrus.Fatalf("open db: %v", err)
}
defer db.Close()
db.LogMode(true)
db.AutoMigrate(&User{})
var user User
db.Where(User{Name: "non_existing"}).Attrs(User{Age: 20}).FirstOrCreate(&user)
}
在 运行 执行此操作并检查日志后,我发现(除了自动迁移之外)它使用了两个查询,一个 SELECT
和一个 INSERT
:
kurt@Kurts-MacBook-Pro-13 ~/D/Scratch> go run gorm_example.go
(/Users/kurt/Documents/Scratch/gorm_example.go:23)
[2020-01-05 09:09:10] [1.03ms] CREATE TABLE "users" ("id" integer primary key autoincrement,"created_at" datetime,"updated_at" datetime,"deleted_at" datetime,"name" varchar(255),"age" integer )
[0 rows affected or returned ]
(/Users/kurt/Documents/Scratch/gorm_example.go:23)
[2020-01-05 09:09:10] [0.86ms] CREATE INDEX idx_users_deleted_at ON "users"(deleted_at)
[0 rows affected or returned ]
(/Users/kurt/Documents/Scratch/gorm_example.go:26)
[2020-01-05 09:09:10] [0.28ms] SELECT * FROM "users" WHERE "users"."deleted_at" IS NULL AND (("users"."name" = 'non_existing')) ORDER BY "users"."id" ASC LIMIT 1
[0 rows affected or returned ]
(/Users/kurt/Documents/Scratch/gorm_example.go:26)
[2020-01-05 09:09:10] [0.31ms] INSERT INTO "users" ("created_at","updated_at","deleted_at","name","age") VALUES ('2020-01-05 09:09:10','2020-01-05 09:09:10',NULL,'non_existing',20)
[1 rows affected or returned ]
据我了解 ,但是,
In a SQL DBMS, the select-test-insert approach is a mistake: nothing prevents another process from inserting the "missing" row between your
select
andinsert
statements.
Django 的 get_or_create()
似乎以类似的方式工作。鉴于此模型,
from django.db import models
class User(models.Model):
name = models.CharField(max_length=255)
age = models.PositiveIntegerField()
如果我启用数据库日志记录和运行一个get_or_create()
查询,我会看到
In [1]: from djangoapp.models import *
In [2]: User.objects.get_or_create(name="jinzhu", age=20)
(0.000) SELECT "djangoapp_user"."id", "djangoapp_user"."name", "djangoapp_user"."age" FROM "djangoapp_user" WHERE ("djangoapp_user"."age" = 20 AND "djangoapp_user"."name" = 'jinzhu') LIMIT 21; args=(20, 'jinzhu')
(0.000) BEGIN; args=None
(0.000) INSERT INTO "djangoapp_user" ("name", "age") VALUES ('jinzhu', 20); args=['jinzhu', 20]
Out[2]: (<User: User object (1)>, True)
简而言之,如果我想确保只创建一条记录,似乎我应该避免使用 ORM(例如 GORM 或 Django ORM)并编写自己的查询?
我的第二个问题是如何在 GORM 中获得 Django 的 created
布尔值的等价物。我是否应该确定结果 gorm.DB
的 RowsAffected
是否为 1
以确定是否实际创建了一行?
您应该只在查询模型字段上添加 UNIQUE 约束,这足以使其在数据库中保持一致
对于将向模型
添加元 class 的 Djangoclass Meta:
unique_together = ['name', 'age']
对于 GORM
Name string `gorm:"unique_index:idx_name_age"`
Age uint `gorm:"unique_index:idx_name_age"`