Skip to content

Commit

Permalink
doc: Update README with UUID usage examples (#263)
Browse files Browse the repository at this point in the history
  • Loading branch information
omkar-foss authored Jul 18, 2024
1 parent f585a5e commit e8a383d
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -282,4 +282,47 @@ DB.Where(datatypes.JSONArrayQuery("config").Contains("c")).Find(&retMultiple)
}
```

## UUID

MySQL, PostgreSQL, SQLServer and SQLite are supported.

```go
import "gorm.io/datatypes"

type UserWithUUID struct {
gorm.Model
Name string
UserUUID datatypes.UUID
}

// Generate a new random UUID (version 4).
userUUID := datatypes.NewUUIDv4()

user := UserWithUUID{Name: "jinzhu", UserUUID: userUUID}
DB.Create(&user)
// INSERT INTO `user_with_uuids` (`name`,`user_uuid`) VALUES ("jinzhu","ca95a578-816c-4812-babd-a7602b042460")

var result UserWithUUID
DB.First(&result, "name = ? AND user_uuid = ?", "jinzhu", userUUID)
// SELECT * FROM user_with_uuids WHERE name = "jinzhu" AND user_uuid = "ca95a578-816c-4812-babd-a7602b042460" ORDER BY `user_with_uuids`.`id` LIMIT 1

// Use the datatype's Equals() to compare the UUIDs.
if userCreate.UserUUID.Equals(userFound.UserUUID) {
fmt.Println("User UUIDs match as expected.")
} else {
fmt.Println("User UUIDs do not match. Something is wrong.")
}

// Use the datatype's String() function to get the UUID as a string type.
fmt.Printf("User UUID is %s", userFound.UserUUID.String())

// Check the UUID value with datatype's IsNil() and IsEmpty() functions.
if userFound.UserUUID.IsNil() {
fmt.Println("User UUID is a nil UUID (i.e. all bits are zero)")
}
if userFound.UserUUID.IsEmpty() {
fmt.Println(
"User UUID is empty (i.e. either a nil UUID or a zero length string)",
)
}
```

0 comments on commit e8a383d

Please sign in to comment.