{"id":13600238,"url":"https://github.com/go-gorm/datatypes","last_synced_at":"2025-05-15T01:09:44.029Z","repository":{"id":37866800,"uuid":"269833946","full_name":"go-gorm/datatypes","owner":"go-gorm","description":"GORM Customized Data Types Collection","archived":false,"fork":false,"pushed_at":"2025-05-08T01:02:15.000Z","size":195,"stargazers_count":775,"open_issues_count":38,"forks_count":112,"subscribers_count":14,"default_branch":"master","last_synced_at":"2025-05-11T04:01:47.432Z","etag":null,"topics":["json"],"latest_commit_sha":null,"homepage":"https://gorm.io/docs/data_types.html","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/go-gorm.png","metadata":{"funding":{"github":["jinzhu"],"patreon":"jinzhu","open_collective":"gorm"},"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"License","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-06-06T01:46:45.000Z","updated_at":"2025-05-07T08:50:38.000Z","dependencies_parsed_at":"2023-02-10T00:31:49.772Z","dependency_job_id":"adf11dea-d7d9-4ea8-9b54-8dd39cefefa5","html_url":"https://github.com/go-gorm/datatypes","commit_stats":{"total_commits":126,"total_committers":32,"mean_commits":3.9375,"dds":0.6190476190476191,"last_synced_commit":"f9380c45460beb2c5cace1024dc11d81f511c056"},"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-gorm%2Fdatatypes","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-gorm%2Fdatatypes/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-gorm%2Fdatatypes/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/go-gorm%2Fdatatypes/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/go-gorm","download_url":"https://codeload.github.com/go-gorm/datatypes/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254254043,"owners_count":22039792,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["json"],"created_at":"2024-08-01T18:00:33.098Z","updated_at":"2025-05-15T01:09:39.022Z","avatar_url":"https://github.com/go-gorm.png","language":"Go","funding_links":["https://github.com/sponsors/jinzhu","https://patreon.com/jinzhu","https://opencollective.com/gorm"],"categories":["Go"],"sub_categories":[],"readme":"# GORM Data Types\n\n## JSON\n\nsqlite, mysql, postgres supported\n\n```go\nimport \"gorm.io/datatypes\"\n\ntype UserWithJSON struct {\n\tgorm.Model\n\tName       string\n\tAttributes datatypes.JSON\n}\n\nDB.Create(\u0026UserWithJSON{\n\tName:       \"json-1\",\n\tAttributes: datatypes.JSON([]byte(`{\"name\": \"jinzhu\", \"age\": 18, \"tags\": [\"tag1\", \"tag2\"], \"orgs\": {\"orga\": \"orga\"}}`)),\n}\n\n// Check JSON has keys\ndatatypes.JSONQuery(\"attributes\").HasKey(value, keys...)\n\ndb.Find(\u0026user, datatypes.JSONQuery(\"attributes\").HasKey(\"role\"))\ndb.Find(\u0026user, datatypes.JSONQuery(\"attributes\").HasKey(\"orgs\", \"orga\"))\n// MySQL\n// SELECT * FROM `users` WHERE JSON_EXTRACT(`attributes`, '$.role') IS NOT NULL\n// SELECT * FROM `users` WHERE JSON_EXTRACT(`attributes`, '$.orgs.orga') IS NOT NULL\n\n// PostgreSQL\n// SELECT * FROM \"user\" WHERE \"attributes\"::jsonb ? 'role'\n// SELECT * FROM \"user\" WHERE \"attributes\"::jsonb -\u003e 'orgs' ? 'orga'\n\n\n// Check JSON extract value from keys equal to value\ndatatypes.JSONQuery(\"attributes\").Equals(value, keys...)\n\nDB.First(\u0026user, datatypes.JSONQuery(\"attributes\").Equals(\"jinzhu\", \"name\"))\nDB.First(\u0026user, datatypes.JSONQuery(\"attributes\").Equals(\"orgb\", \"orgs\", \"orgb\"))\n// MySQL\n// SELECT * FROM `user` WHERE JSON_EXTRACT(`attributes`, '$.name') = \"jinzhu\"\n// SELECT * FROM `user` WHERE JSON_EXTRACT(`attributes`, '$.orgs.orgb') = \"orgb\"\n\n// PostgreSQL\n// SELECT * FROM \"user\" WHERE json_extract_path_text(\"attributes\"::json,'name') = 'jinzhu'\n// SELECT * FROM \"user\" WHERE json_extract_path_text(\"attributes\"::json,'orgs','orgb') = 'orgb'\n```\n\nNOTE: SQlite need to build with `json1` tag, e.g: `go build --tags json1`, refer https://github.com/mattn/go-sqlite3#usage\n\n## Date\n\n```go\nimport \"gorm.io/datatypes\"\n\ntype UserWithDate struct {\n\tgorm.Model\n\tName string\n\tDate datatypes.Date\n}\n\nuser := UserWithDate{Name: \"jinzhu\", Date: datatypes.Date(time.Now())}\nDB.Create(\u0026user)\n// INSERT INTO `user_with_dates` (`name`,`date`) VALUES (\"jinzhu\",\"2020-07-17 00:00:00\")\n\nDB.First(\u0026result, \"name = ? AND date = ?\", \"jinzhu\", datatypes.Date(curTime))\n// SELECT * FROM user_with_dates WHERE name = \"jinzhu\" AND date = \"2020-07-17 00:00:00\" ORDER BY `user_with_dates`.`id` LIMIT 1\n```\n\n## Time\n\nMySQL, PostgreSQL, SQLite, SQLServer are supported.\n\nTime with nanoseconds is supported for some databases which support for time with fractional second scale.\n\n```go\nimport \"gorm.io/datatypes\"\n\ntype UserWithTime struct {\n    gorm.Model\n    Name string\n    Time datatypes.Time\n}\n\nuser := UserWithTime{Name: \"jinzhu\", Time: datatypes.NewTime(1, 2, 3, 0)}\nDB.Create(\u0026user)\n// INSERT INTO `user_with_times` (`name`,`time`) VALUES (\"jinzhu\",\"01:02:03\")\n\nDB.First(\u0026result, \"name = ? AND time = ?\", \"jinzhu\", datatypes.NewTime(1, 2, 3, 0))\n// SELECT * FROM user_with_times WHERE name = \"jinzhu\" AND time = \"01:02:03\" ORDER BY `user_with_times`.`id` LIMIT 1\n```\n\nNOTE: If the current using database is SQLite, the field column type is defined as `TEXT` type\nwhen GORM AutoMigrate because SQLite doesn't have time type.\n\n## JSON_SET\n\nsqlite, mysql, postgres supported\n\n```go\nimport (\n\t\"gorm.io/datatypes\"\n\t\"gorm.io/gorm\"\n)\n\ntype UserWithJSON struct {\n\tgorm.Model\n\tName       string\n\tAttributes datatypes.JSON\n}\n\nDB.Create(\u0026UserWithJSON{\n\tName:       \"json-1\",\n\tAttributes: datatypes.JSON([]byte(`{\"name\": \"json-1\", \"age\": 18, \"tags\": [\"tag1\", \"tag2\"], \"orgs\": {\"orga\": \"orga\"}}`)),\n})\n\ntype User struct {\n\tName string\n\tAge  int\n}\n\nfriend := User{\n\tName: \"Bob\",\n\tAge:  21,\n}\n\n// Set fields of JSON column\ndatatypes.JSONSet(\"attributes\").Set(\"age\", 20).Set(\"tags[0]\", \"tag2\").Set(\"orgs.orga\", \"orgb\")\n\nDB.Model(\u0026UserWithJSON{}).Where(\"name = ?\", \"json-1\").UpdateColumn(\"attributes\", datatypes.JSONSet(\"attributes\").Set(\"age\", 20).Set(\"tags[0]\", \"tag3\").Set(\"orgs.orga\", \"orgb\"))\nDB.Model(\u0026UserWithJSON{}).Where(\"name = ?\", \"json-1\").UpdateColumn(\"attributes\", datatypes.JSONSet(\"attributes\").Set(\"phones\", []string{\"10085\", \"10086\"}))\nDB.Model(\u0026UserWithJSON{}).Where(\"name = ?\", \"json-1\").UpdateColumn(\"attributes\", datatypes.JSONSet(\"attributes\").Set(\"phones\", gorm.Expr(\"CAST(? AS JSON)\", `[\"10085\", \"10086\"]`)))\nDB.Model(\u0026UserWithJSON{}).Where(\"name = ?\", \"json-1\").UpdateColumn(\"attributes\", datatypes.JSONSet(\"attributes\").Set(\"friend\", friend))\n// MySQL\n// UPDATE `user_with_jsons` SET `attributes` = JSON_SET(`attributes`, '$.tags[0]', 'tag3', '$.orgs.orga', 'orgb', '$.age', 20) WHERE name = 'json-1'\n// UPDATE `user_with_jsons` SET `attributes` = JSON_SET(`attributes`, '$.phones', CAST('[\"10085\", \"10086\"]' AS JSON)) WHERE name = 'json-1'\n// UPDATE `user_with_jsons` SET `attributes` = JSON_SET(`attributes`, '$.phones', CAST('[\"10085\", \"10086\"]' AS JSON)) WHERE name = 'json-1'\n// UPDATE `user_with_jsons` SET `attributes` = JSON_SET(`attributes`, '$.friend', CAST('{\"Name\": \"Bob\", \"Age\": 21}' AS JSON)) WHERE name = 'json-1'\n```\nNOTE: MariaDB does not support CAST(? AS JSON).\n\nNOTE: Path in PostgreSQL is different.\n\n```go\n// Set fields of JSON column\ndatatypes.JSONSet(\"attributes\").Set(\"{age}\", 20).Set(\"{tags, 0}\", \"tag2\").Set(\"{orgs, orga}\", \"orgb\")\n\nDB.Model(\u0026UserWithJSON{}).Where(\"name = ?\", \"json-1\").UpdateColumn(\"attributes\", datatypes.JSONSet(\"attributes\").Set(\"{age}\", 20).Set(\"{tags, 0}\", \"tag2\").Set(\"{orgs, orga}\", \"orgb\"))\nDB.Model(\u0026UserWithJSON{}).Where(\"name = ?\", \"json-1\").UpdateColumn(\"attributes\", datatypes.JSONSet(\"attributes\").Set(\"{phones}\", []string{\"10085\", \"10086\"}))\nDB.Model(\u0026UserWithJSON{}).Where(\"name = ?\", \"json-1\").UpdateColumn(\"attributes\", datatypes.JSONSet(\"attributes\").Set(\"{phones}\", gorm.Expr(\"?::jsonb\", `[\"10085\", \"10086\"]`)))\nDB.Model(\u0026UserWithJSON{}).Where(\"name = ?\", \"json-1\").UpdateColumn(\"attributes\", datatypes.JSONSet(\"attributes\").Set(\"{friend}\", friend))\n// PostgreSQL\n// UPDATE \"user_with_jsons\" SET \"attributes\" = JSONB_SET(JSONB_SET(JSONB_SET(\"attributes\", '{age}', '20'), '{tags, 0}', '\"tag2\"'), '{orgs, orga}', '\"orgb\"') WHERE name = 'json-1'\n// UPDATE \"user_with_jsons\" SET \"attributes\" = JSONB_SET(\"attributes\", '{phones}', '[\"10085\",\"10086\"]') WHERE name = 'json-1'\n// UPDATE \"user_with_jsons\" SET \"attributes\" = JSONB_SET(\"attributes\", '{phones}', '[\"10085\",\"10086\"]'::jsonb) WHERE name = 'json-1'\n// UPDATE \"user_with_jsons\" SET \"attributes\" = JSONB_SET(\"attributes\", '{friend}', '{\"Name\": \"Bob\", \"Age\": 21}') WHERE name = 'json-1'\n```\n\n## JSONType[T]\n\nsqlite, mysql, postgres supported\n\n```go\nimport \"gorm.io/datatypes\"\n\ntype Attribute struct {\n\tSex   int\n\tAge   int\n\tOrgs  map[string]string\n\tTags  []string\n\tAdmin bool\n\tRole  string\n}\n\ntype UserWithJSON struct {\n\tgorm.Model\n\tName       string\n\tAttributes datatypes.JSONType[Attribute]\n}\n\nvar user = UserWithJSON{\n\tName: \"hello\",\n\tAttributes: datatypes.NewJSONType(Attribute{\n        Age:  18,\n        Sex:  1,\n        Orgs: map[string]string{\"orga\": \"orga\"},\n        Tags: []string{\"tag1\", \"tag2\", \"tag3\"},\n    }),\n}\n\n// Create\nDB.Create(\u0026user)\n\n// First\nvar result UserWithJSON\nDB.First(\u0026result, user.ID)\n\n// Update\njsonMap = UserWithJSON{\n\tAttributes: datatypes.NewJSONType(Attribute{\n        Age:  18,\n        Sex:  1,\n        Orgs: map[string]string{\"orga\": \"orga\"},\n        Tags: []string{\"tag1\", \"tag2\", \"tag3\"},\n    }),\n}\n\nDB.Model(\u0026user).Updates(jsonMap)\n```\n\nNOTE: it's not support json query\n\n## JSONSlice[T]\n\nsqlite, mysql, postgres supported\n\n```go\nimport \"gorm.io/datatypes\"\n\ntype Tag struct {\n\tName  string\n\tScore float64\n}\n\ntype UserWithJSON struct {\n\tgorm.Model\n\tName       string\n\tTags       datatypes.JSONSlice[Tag]\n}\n\nvar tags = []Tag{{Name: \"tag1\", Score: 0.1}, {Name: \"tag2\", Score: 0.2}}\nvar user = UserWithJSON{\n\tName: \"hello\",\n\tTags: datatypes.NewJSONSlice(tags),\n}\n\n// Create\nDB.Create(\u0026user)\n\n// First\nvar result UserWithJSON\nDB.First(\u0026result, user.ID)\n\n// Update\nvar tags2 = []Tag{{Name: \"tag3\", Score: 10.1}, {Name: \"tag4\", Score: 10.2}}\njsonMap = UserWithJSON{\n\tTags: datatypes.NewJSONSlice(tags2),\n}\n\nDB.Model(\u0026user).Updates(jsonMap)\n```\n\nNOTE: it's not support json query and `db.Pluck` method\n\n## JSONArray\n\nmysql supported\n\n```go\nimport \"gorm.io/datatypes\"\n\ntype Param struct {\n    ID          int\n    Letters     string\n    Config      datatypes.JSON\n}\n\n//Create\nDB.Create(\u0026Param{\n    Letters: \"JSONArray-1\",\n    Config:      datatypes.JSON(\"[\\\"a\\\", \\\"b\\\"]\"),\n})\n\nDB.Create(\u0026Param{\n    Letters: \"JSONArray-2\",\n    Config:      datatypes.JSON(\"[\\\"a\\\", \\\"c\\\"]\"),\n})\n\n//Query\nvar retMultiple []Param\nDB.Where(datatypes.JSONArrayQuery(\"config\").Contains(\"c\")).Find(\u0026retMultiple)\n}\n```\n\n## UUID\n\nMySQL, PostgreSQL, SQLServer and SQLite are supported.\n\n```go\nimport \"gorm.io/datatypes\"\n\ntype UserWithUUID struct {\n    gorm.Model\n    Name string\n    UserUUID datatypes.UUID\n}\n\n// Generate a new random UUID (version 4).\nuserUUID := datatypes.NewUUIDv4()\n\nuser := UserWithUUID{Name: \"jinzhu\", UserUUID: userUUID}\nDB.Create(\u0026user)\n// INSERT INTO `user_with_uuids` (`name`,`user_uuid`) VALUES (\"jinzhu\",\"ca95a578-816c-4812-babd-a7602b042460\")\n\nvar result UserWithUUID\nDB.First(\u0026result, \"name = ? AND user_uuid = ?\", \"jinzhu\", userUUID)\n// SELECT * FROM user_with_uuids WHERE name = \"jinzhu\" AND user_uuid = \"ca95a578-816c-4812-babd-a7602b042460\" ORDER BY `user_with_uuids`.`id` LIMIT 1\n\n// Use the datatype's Equals() to compare the UUIDs.\nif userCreate.UserUUID.Equals(userFound.UserUUID) {\n\tfmt.Println(\"User UUIDs match as expected.\")\n} else {\n\tfmt.Println(\"User UUIDs do not match. Something is wrong.\")\n}\n\n// Use the datatype's String() function to get the UUID as a string type.\nfmt.Printf(\"User UUID is %s\", userFound.UserUUID.String())\n\n// Check the UUID value with datatype's IsNil() and IsEmpty() functions.\nif userFound.UserUUID.IsNil() {\n\tfmt.Println(\"User UUID is a nil UUID (i.e. all bits are zero)\")\n}\nif userFound.UserUUID.IsEmpty() {\n\tfmt.Println(\n\t\t\"User UUID is empty (i.e. either a nil UUID or a zero length string)\",\n\t)\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgo-gorm%2Fdatatypes","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgo-gorm%2Fdatatypes","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgo-gorm%2Fdatatypes/lists"}