Skip to content

Commit e8a383d

Browse files
authored
doc: Update README with UUID usage examples (#263)
1 parent f585a5e commit e8a383d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

README.md

+43
Original file line numberDiff line numberDiff line change
@@ -282,4 +282,47 @@ DB.Where(datatypes.JSONArrayQuery("config").Contains("c")).Find(&retMultiple)
282282
}
283283
```
284284

285+
## UUID
285286

287+
MySQL, PostgreSQL, SQLServer and SQLite are supported.
288+
289+
```go
290+
import "gorm.io/datatypes"
291+
292+
type UserWithUUID struct {
293+
gorm.Model
294+
Name string
295+
UserUUID datatypes.UUID
296+
}
297+
298+
// Generate a new random UUID (version 4).
299+
userUUID := datatypes.NewUUIDv4()
300+
301+
user := UserWithUUID{Name: "jinzhu", UserUUID: userUUID}
302+
DB.Create(&user)
303+
// INSERT INTO `user_with_uuids` (`name`,`user_uuid`) VALUES ("jinzhu","ca95a578-816c-4812-babd-a7602b042460")
304+
305+
var result UserWithUUID
306+
DB.First(&result, "name = ? AND user_uuid = ?", "jinzhu", userUUID)
307+
// SELECT * FROM user_with_uuids WHERE name = "jinzhu" AND user_uuid = "ca95a578-816c-4812-babd-a7602b042460" ORDER BY `user_with_uuids`.`id` LIMIT 1
308+
309+
// Use the datatype's Equals() to compare the UUIDs.
310+
if userCreate.UserUUID.Equals(userFound.UserUUID) {
311+
fmt.Println("User UUIDs match as expected.")
312+
} else {
313+
fmt.Println("User UUIDs do not match. Something is wrong.")
314+
}
315+
316+
// Use the datatype's String() function to get the UUID as a string type.
317+
fmt.Printf("User UUID is %s", userFound.UserUUID.String())
318+
319+
// Check the UUID value with datatype's IsNil() and IsEmpty() functions.
320+
if userFound.UserUUID.IsNil() {
321+
fmt.Println("User UUID is a nil UUID (i.e. all bits are zero)")
322+
}
323+
if userFound.UserUUID.IsEmpty() {
324+
fmt.Println(
325+
"User UUID is empty (i.e. either a nil UUID or a zero length string)",
326+
)
327+
}
328+
```

0 commit comments

Comments
 (0)