datatypes

package module
v1.2.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2024 License: MIT Imports: 18 Imported by: 948

README

GORM Data Types

JSON

sqlite, mysql, postgres supported

import "gorm.io/datatypes"

type UserWithJSON struct {
	gorm.Model
	Name       string
	Attributes datatypes.JSON
}

DB.Create(&UserWithJSON{
	Name:       "json-1",
	Attributes: datatypes.JSON([]byte(`{"name": "jinzhu", "age": 18, "tags": ["tag1", "tag2"], "orgs": {"orga": "orga"}}`)),
}

// Check JSON has keys
datatypes.JSONQuery("attributes").HasKey(value, keys...)

db.Find(&user, datatypes.JSONQuery("attributes").HasKey("role"))
db.Find(&user, datatypes.JSONQuery("attributes").HasKey("orgs", "orga"))
// MySQL
// SELECT * FROM `users` WHERE JSON_EXTRACT(`attributes`, '$.role') IS NOT NULL
// SELECT * FROM `users` WHERE JSON_EXTRACT(`attributes`, '$.orgs.orga') IS NOT NULL

// PostgreSQL
// SELECT * FROM "user" WHERE "attributes"::jsonb ? 'role'
// SELECT * FROM "user" WHERE "attributes"::jsonb -> 'orgs' ? 'orga'


// Check JSON extract value from keys equal to value
datatypes.JSONQuery("attributes").Equals(value, keys...)

DB.First(&user, datatypes.JSONQuery("attributes").Equals("jinzhu", "name"))
DB.First(&user, datatypes.JSONQuery("attributes").Equals("orgb", "orgs", "orgb"))
// MySQL
// SELECT * FROM `user` WHERE JSON_EXTRACT(`attributes`, '$.name') = "jinzhu"
// SELECT * FROM `user` WHERE JSON_EXTRACT(`attributes`, '$.orgs.orgb') = "orgb"

// PostgreSQL
// SELECT * FROM "user" WHERE json_extract_path_text("attributes"::json,'name') = 'jinzhu'
// SELECT * FROM "user" WHERE json_extract_path_text("attributes"::json,'orgs','orgb') = 'orgb'

NOTE: SQlite need to build with json1 tag, e.g: go build --tags json1, refer https://github.com/mattn/go-sqlite3#usage

Date

import "gorm.io/datatypes"

type UserWithDate struct {
	gorm.Model
	Name string
	Date datatypes.Date
}

user := UserWithDate{Name: "jinzhu", Date: datatypes.Date(time.Now())}
DB.Create(&user)
// INSERT INTO `user_with_dates` (`name`,`date`) VALUES ("jinzhu","2020-07-17 00:00:00")

DB.First(&result, "name = ? AND date = ?", "jinzhu", datatypes.Date(curTime))
// SELECT * FROM user_with_dates WHERE name = "jinzhu" AND date = "2020-07-17 00:00:00" ORDER BY `user_with_dates`.`id` LIMIT 1

Time

MySQL, PostgreSQL, SQLite, SQLServer are supported.

Time with nanoseconds is supported for some databases which support for time with fractional second scale.

import "gorm.io/datatypes"

type UserWithTime struct {
    gorm.Model
    Name string
    Time datatypes.Time
}

user := UserWithTime{Name: "jinzhu", Time: datatypes.NewTime(1, 2, 3, 0)}
DB.Create(&user)
// INSERT INTO `user_with_times` (`name`,`time`) VALUES ("jinzhu","01:02:03")

DB.First(&result, "name = ? AND time = ?", "jinzhu", datatypes.NewTime(1, 2, 3, 0))
// SELECT * FROM user_with_times WHERE name = "jinzhu" AND time = "01:02:03" ORDER BY `user_with_times`.`id` LIMIT 1

NOTE: If the current using database is SQLite, the field column type is defined as TEXT type when GORM AutoMigrate because SQLite doesn't have time type.

JSON_SET

sqlite, mysql, postgres supported

import (
	"gorm.io/datatypes"
	"gorm.io/gorm"
)

type UserWithJSON struct {
	gorm.Model
	Name       string
	Attributes datatypes.JSON
}

DB.Create(&UserWithJSON{
	Name:       "json-1",
	Attributes: datatypes.JSON([]byte(`{"name": "json-1", "age": 18, "tags": ["tag1", "tag2"], "orgs": {"orga": "orga"}}`)),
})

type User struct {
	Name string
	Age  int
}

friend := User{
	Name: "Bob",
	Age:  21,
}

// Set fields of JSON column
datatypes.JSONSet("attributes").Set("age", 20).Set("tags[0]", "tag2").Set("orgs.orga", "orgb")

DB.Model(&UserWithJSON{}).Where("name = ?", "json-1").UpdateColumn("attributes", datatypes.JSONSet("attributes").Set("age", 20).Set("tags[0]", "tag3").Set("orgs.orga", "orgb"))
DB.Model(&UserWithJSON{}).Where("name = ?", "json-1").UpdateColumn("attributes", datatypes.JSONSet("attributes").Set("phones", []string{"10085", "10086"}))
DB.Model(&UserWithJSON{}).Where("name = ?", "json-1").UpdateColumn("attributes", datatypes.JSONSet("attributes").Set("phones", gorm.Expr("CAST(? AS JSON)", `["10085", "10086"]`)))
DB.Model(&UserWithJSON{}).Where("name = ?", "json-1").UpdateColumn("attributes", datatypes.JSONSet("attributes").Set("friend", friend))
// MySQL
// UPDATE `user_with_jsons` SET `attributes` = JSON_SET(`attributes`, '$.tags[0]', 'tag3', '$.orgs.orga', 'orgb', '$.age', 20) WHERE name = 'json-1'
// UPDATE `user_with_jsons` SET `attributes` = JSON_SET(`attributes`, '$.phones', CAST('["10085", "10086"]' AS JSON)) WHERE name = 'json-1'
// UPDATE `user_with_jsons` SET `attributes` = JSON_SET(`attributes`, '$.phones', CAST('["10085", "10086"]' AS JSON)) WHERE name = 'json-1'
// UPDATE `user_with_jsons` SET `attributes` = JSON_SET(`attributes`, '$.friend', CAST('{"Name": "Bob", "Age": 21}' AS JSON)) WHERE name = 'json-1'

NOTE: MariaDB does not support CAST(? AS JSON).

NOTE: Path in PostgreSQL is different.

// Set fields of JSON column
datatypes.JSONSet("attributes").Set("{age}", 20).Set("{tags, 0}", "tag2").Set("{orgs, orga}", "orgb")

DB.Model(&UserWithJSON{}).Where("name = ?", "json-1").UpdateColumn("attributes", datatypes.JSONSet("attributes").Set("{age}", 20).Set("{tags, 0}", "tag2").Set("{orgs, orga}", "orgb"))
DB.Model(&UserWithJSON{}).Where("name = ?", "json-1").UpdateColumn("attributes", datatypes.JSONSet("attributes").Set("{phones}", []string{"10085", "10086"}))
DB.Model(&UserWithJSON{}).Where("name = ?", "json-1").UpdateColumn("attributes", datatypes.JSONSet("attributes").Set("{phones}", gorm.Expr("?::jsonb", `["10085", "10086"]`)))
DB.Model(&UserWithJSON{}).Where("name = ?", "json-1").UpdateColumn("attributes", datatypes.JSONSet("attributes").Set("{friend}", friend))
// PostgreSQL
// 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'
// UPDATE "user_with_jsons" SET "attributes" = JSONB_SET("attributes", '{phones}', '["10085","10086"]') WHERE name = 'json-1'
// UPDATE "user_with_jsons" SET "attributes" = JSONB_SET("attributes", '{phones}', '["10085","10086"]'::jsonb) WHERE name = 'json-1'
// UPDATE "user_with_jsons" SET "attributes" = JSONB_SET("attributes", '{friend}', '{"Name": "Bob", "Age": 21}') WHERE name = 'json-1'

JSONType[T]

sqlite, mysql, postgres supported

import "gorm.io/datatypes"

type Attribute struct {
	Sex   int
	Age   int
	Orgs  map[string]string
	Tags  []string
	Admin bool
	Role  string
}

type UserWithJSON struct {
	gorm.Model
	Name       string
	Attributes datatypes.JSONType[Attribute]
}

var user = UserWithJSON{
	Name: "hello",
	Attributes: datatypes.NewJSONType(Attribute{
        Age:  18,
        Sex:  1,
        Orgs: map[string]string{"orga": "orga"},
        Tags: []string{"tag1", "tag2", "tag3"},
    }),
}

// Create
DB.Create(&user)

// First
var result UserWithJSON
DB.First(&result, user.ID)

// Update
jsonMap = UserWithJSON{
	Attributes: datatypes.NewJSONType(Attribute{
        Age:  18,
        Sex:  1,
        Orgs: map[string]string{"orga": "orga"},
        Tags: []string{"tag1", "tag2", "tag3"},
    }),
}

DB.Model(&user).Updates(jsonMap)

NOTE: it's not support json query

JSONSlice[T]

sqlite, mysql, postgres supported

import "gorm.io/datatypes"

type Tag struct {
	Name  string
	Score float64
}

type UserWithJSON struct {
	gorm.Model
	Name       string
	Tags       datatypes.JSONSlice[Tag]
}

var tags = []Tag{{Name: "tag1", Score: 0.1}, {Name: "tag2", Score: 0.2}}
var user = UserWithJSON{
	Name: "hello",
	Tags: datatypes.NewJSONSlice(tags),
}

// Create
DB.Create(&user)

// First
var result UserWithJSON
DB.First(&result, user.ID)

// Update
var tags2 = []Tag{{Name: "tag3", Score: 10.1}, {Name: "tag4", Score: 10.2}}
jsonMap = UserWithJSON{
	Tags: datatypes.NewJSONSlice(tags2),
}

DB.Model(&user).Updates(jsonMap)

NOTE: it's not support json query and db.Pluck method

JSONArray

mysql supported

import "gorm.io/datatypes"

type Param struct {
    ID          int
    Letters     string
    Config      datatypes.JSON
}

//Create
DB.Create(&Param{
    Letters: "JSONArray-1",
    Config:      datatypes.JSON("[\"a\", \"b\"]"),
})

DB.Create(&Param{
    Letters: "JSONArray-2",
    Config:      datatypes.JSON("[\"a\", \"c\"]"),
})

//Query
var retMultiple []Param
DB.Where(datatypes.JSONArrayQuery("config").Contains("c")).Find(&retMultiple)
}

UUID

MySQL, PostgreSQL, SQLServer and SQLite are supported.

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)",
	)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Column added in v1.0.7

func Column(col string) columnExpression

Types

type BinUUID added in v1.2.2

type BinUUID uuid.UUID

This datatype is similar to datatypes.UUID, major difference being that this datatype stores the uuid in the database as a binary (byte) array instead of a string. Developers may use either as per their preference.

func BinUUIDFromString added in v1.2.2

func BinUUIDFromString(uuidStr string) BinUUID

BinUUIDFromString returns the BinUUID representation of the specified uuidStr.

func NewBinUUIDv1 added in v1.2.2

func NewBinUUIDv1() BinUUID

NewBinUUIDv1 generates a uuid version 1, panics on generation failure.

func NewBinUUIDv4 added in v1.2.2

func NewBinUUIDv4() BinUUID

NewBinUUIDv4 generates a uuid version 4, panics on generation failure.

func NewNilBinUUID added in v1.2.3

func NewNilBinUUID() BinUUID

NewNilBinUUID generates a nil uuid.

func (BinUUID) Bytes added in v1.2.2

func (u BinUUID) Bytes() []byte

String returns the string form of the UUID.

func (BinUUID) Equals added in v1.2.2

func (u BinUUID) Equals(other BinUUID) bool

Equals returns true if bytes form of BinUUID matches other, false otherwise.

func (BinUUID) GormDBDataType added in v1.2.2

func (BinUUID) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType gorm db data type.

func (BinUUID) GormDataType added in v1.2.2

func (BinUUID) GormDataType() string

GormDataType gorm common data type.

func (BinUUID) IsEmpty added in v1.2.2

func (u BinUUID) IsEmpty() bool

IsEmpty returns true if BinUUID is nil uuid or of zero length, false otherwise.

func (*BinUUID) IsEmptyPtr added in v1.2.2

func (u *BinUUID) IsEmptyPtr() bool

IsEmptyPtr returns true if caller BinUUID ptr is nil or it's value is empty.

func (BinUUID) IsNil added in v1.2.2

func (u BinUUID) IsNil() bool

IsNil returns true if the BinUUID is nil uuid (all zeroes), false otherwise.

func (*BinUUID) IsNilPtr added in v1.2.2

func (u *BinUUID) IsNilPtr() bool

IsNilPtr returns true if caller BinUUID ptr is nil, false otherwise.

func (BinUUID) Length added in v1.2.2

func (u BinUUID) Length() int

Length returns the number of characters in string form of UUID.

func (BinUUID) LengthBytes added in v1.2.2

func (u BinUUID) LengthBytes() int

Length returns the number of characters in string form of UUID.

func (*BinUUID) Scan added in v1.2.2

func (u *BinUUID) Scan(value interface{}) error

Scan is the scanner function for this datatype.

func (BinUUID) String added in v1.2.2

func (u BinUUID) String() string

String returns the string form of the UUID.

func (BinUUID) Value added in v1.2.2

func (u BinUUID) Value() (driver.Value, error)

Value is the valuer function for this datatype.

type Date

type Date time.Time

func (*Date) GobDecode

func (date *Date) GobDecode(b []byte) error

func (Date) GobEncode

func (date Date) GobEncode() ([]byte, error)

func (Date) GormDataType

func (date Date) GormDataType() string

GormDataType gorm common data type

func (Date) MarshalJSON

func (date Date) MarshalJSON() ([]byte, error)

func (*Date) Scan

func (date *Date) Scan(value interface{}) (err error)

func (*Date) UnmarshalJSON

func (date *Date) UnmarshalJSON(b []byte) error

func (Date) Value

func (date Date) Value() (driver.Value, error)

type JSON

type JSON json.RawMessage

JSON defined JSON data type, need to implements driver.Valuer, sql.Scanner interface

func (JSON) GormDBDataType

func (JSON) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType gorm db data type

func (JSON) GormDataType

func (JSON) GormDataType() string

GormDataType gorm common data type

func (JSON) GormValue added in v1.0.4

func (js JSON) GormValue(ctx context.Context, db *gorm.DB) clause.Expr

func (JSON) MarshalJSON

func (j JSON) MarshalJSON() ([]byte, error)

MarshalJSON to output non base64 encoded []byte

func (*JSON) Scan

func (j *JSON) Scan(value interface{}) error

Scan scan value into Jsonb, implements sql.Scanner interface

func (JSON) String

func (j JSON) String() string

func (*JSON) UnmarshalJSON

func (j *JSON) UnmarshalJSON(b []byte) error

UnmarshalJSON to deserialize []byte

func (JSON) Value

func (j JSON) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

type JSONArrayExpression added in v1.1.1

type JSONArrayExpression struct {
	// contains filtered or unexported fields
}

func JSONArrayQuery added in v1.1.1

func JSONArrayQuery(column string) *JSONArrayExpression

func (*JSONArrayExpression) Build added in v1.1.1

func (json *JSONArrayExpression) Build(builder clause.Builder)

Build implements clause.Expression

func (*JSONArrayExpression) Contains added in v1.1.1

func (json *JSONArrayExpression) Contains(value interface{}, keys ...string) *JSONArrayExpression

Contains checks if column[keys] contains the value given. The keys parameter is only supported for MySQL and SQLite.

func (*JSONArrayExpression) In added in v1.2.4

func (json *JSONArrayExpression) In(value interface{}, keys ...string) *JSONArrayExpression

In checks if columns[keys] is in the array value given. This method is only supported for MySQL and SQLite.

type JSONMap

type JSONMap map[string]interface{}

JSONMap defined JSON data type, need to implements driver.Valuer, sql.Scanner interface

func (JSONMap) GormDBDataType

func (JSONMap) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType gorm db data type

func (JSONMap) GormDataType

func (m JSONMap) GormDataType() string

GormDataType gorm common data type

func (JSONMap) GormValue added in v1.0.4

func (jm JSONMap) GormValue(ctx context.Context, db *gorm.DB) clause.Expr

func (JSONMap) MarshalJSON

func (m JSONMap) MarshalJSON() ([]byte, error)

MarshalJSON to output non base64 encoded []byte

func (*JSONMap) Scan

func (m *JSONMap) Scan(val interface{}) error

Scan scan value into Jsonb, implements sql.Scanner interface

func (*JSONMap) UnmarshalJSON

func (m *JSONMap) UnmarshalJSON(b []byte) error

UnmarshalJSON to deserialize []byte

func (JSONMap) Value

func (m JSONMap) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

type JSONOverlapsExpression added in v1.0.7

type JSONOverlapsExpression struct {
	// contains filtered or unexported fields
}

JSONOverlapsExpression JSON_OVERLAPS expression, implements clause.Expression interface to use as querier

func JSONOverlaps added in v1.0.7

func JSONOverlaps(column clause.Expression, value string) *JSONOverlapsExpression

JSONOverlaps query column as json

func (*JSONOverlapsExpression) Build added in v1.0.7

func (json *JSONOverlapsExpression) Build(builder clause.Builder)

Build implements clause.Expression only mysql support JSON_OVERLAPS

type JSONQueryExpression

type JSONQueryExpression struct {
	// contains filtered or unexported fields
}

JSONQueryExpression json query expression, implements clause.Expression interface to use as querier

func JSONQuery

func JSONQuery(column string) *JSONQueryExpression

JSONQuery query column as json

func (*JSONQueryExpression) Build

func (jsonQuery *JSONQueryExpression) Build(builder clause.Builder)

Build implements clause.Expression

func (*JSONQueryExpression) Equals

func (jsonQuery *JSONQueryExpression) Equals(value interface{}, keys ...string) *JSONQueryExpression

Keys returns clause.Expression

func (*JSONQueryExpression) Extract added in v1.0.7

func (jsonQuery *JSONQueryExpression) Extract(path string) *JSONQueryExpression

Extract extract json with path

func (*JSONQueryExpression) HasKey

func (jsonQuery *JSONQueryExpression) HasKey(keys ...string) *JSONQueryExpression

HasKey returns clause.Expression

func (*JSONQueryExpression) Likes added in v1.2.1

func (jsonQuery *JSONQueryExpression) Likes(value interface{}, keys ...string) *JSONQueryExpression

Likes return clause.Expression

type JSONSetExpression added in v1.1.0

type JSONSetExpression struct {
	// contains filtered or unexported fields
}

JSONSetExpression json set expression, implements clause.Expression interface to use as updater

func JSONSet added in v1.1.0

func JSONSet(column string) *JSONSetExpression

JSONSet update fields of json column

func (*JSONSetExpression) Build added in v1.1.0

func (jsonSet *JSONSetExpression) Build(builder clause.Builder)

Build implements clause.Expression support mysql, sqlite and postgres

func (*JSONSetExpression) Set added in v1.1.0

func (jsonSet *JSONSetExpression) Set(path string, value interface{}) *JSONSetExpression

Set return clause.Expression.

{
	"age": 20,
	"name": "json-1",
	"orgs": {"orga": "orgv"},
	"tags": ["tag1", "tag2"]
}

// In MySQL/SQLite, path is `age`, `name`, `orgs.orga`, `tags[0]`, `tags[1]`.
DB.UpdateColumn("attr", JSONSet("attr").Set("orgs.orga", 42))

// In PostgreSQL, path is `{age}`, `{name}`, `{orgs,orga}`, `{tags, 0}`, `{tags, 1}`.
DB.UpdateColumn("attr", JSONSet("attr").Set("{orgs, orga}", "bar"))

type JSONSlice added in v1.2.0

type JSONSlice[T any] []T

JSONSlice give a generic data type for json encoded slice data.

func NewJSONSlice added in v1.2.0

func NewJSONSlice[T any](s []T) JSONSlice[T]

func (JSONSlice[T]) GormDBDataType added in v1.2.0

func (JSONSlice[T]) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType gorm db data type

func (JSONSlice[T]) GormDataType added in v1.2.0

func (JSONSlice[T]) GormDataType() string

GormDataType gorm common data type

func (JSONSlice[T]) GormValue added in v1.2.0

func (j JSONSlice[T]) GormValue(ctx context.Context, db *gorm.DB) clause.Expr

func (*JSONSlice[T]) Scan added in v1.2.0

func (j *JSONSlice[T]) Scan(value interface{}) error

Scan scan value into JSONType[T], implements sql.Scanner interface

func (JSONSlice[T]) Value added in v1.2.0

func (j JSONSlice[T]) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

type JSONType added in v1.1.0

type JSONType[T any] struct {
	// contains filtered or unexported fields
}

JSONType give a generic data type for json encoded data.

func NewJSONType added in v1.2.0

func NewJSONType[T any](data T) JSONType[T]

func (JSONType[T]) Data added in v1.1.0

func (j JSONType[T]) Data() T

Data return data with generic Type T

func (JSONType[T]) GormDBDataType added in v1.1.0

func (JSONType[T]) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType gorm db data type

func (JSONType[T]) GormDataType added in v1.1.0

func (JSONType[T]) GormDataType() string

GormDataType gorm common data type

func (JSONType[T]) GormValue added in v1.1.0

func (js JSONType[T]) GormValue(ctx context.Context, db *gorm.DB) clause.Expr

func (JSONType[T]) MarshalJSON added in v1.1.0

func (j JSONType[T]) MarshalJSON() ([]byte, error)

MarshalJSON to output non base64 encoded []byte

func (*JSONType[T]) Scan added in v1.1.0

func (j *JSONType[T]) Scan(value interface{}) error

Scan scan value into JSONType[T], implements sql.Scanner interface

func (*JSONType[T]) UnmarshalJSON added in v1.1.0

func (j *JSONType[T]) UnmarshalJSON(b []byte) error

UnmarshalJSON to deserialize []byte

func (JSONType[T]) Value added in v1.1.0

func (j JSONType[T]) Value() (driver.Value, error)

Value return json value, implement driver.Valuer interface

type Null added in v1.2.4

type Null[T any] struct {
	V     T
	Valid bool
}

Null represents a value that may be null. Null implements the [Scanner] interface so it can be used as a scan destination:

var s Null[string]
err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
...
if s.Valid {
   // use s.V
} else {
   // NULL value
}

func NewNull added in v1.2.4

func NewNull[T any](v T) Null[T]

NewNull returns a new, non-null Null.

func (*Null[T]) Scan added in v1.2.4

func (n *Null[T]) Scan(value any) error

func (Null[T]) Value added in v1.2.4

func (n Null[T]) Value() (driver.Value, error)

type NullBool added in v1.2.4

type NullBool = Null[bool]

NullBool represents a bool that may be null. NullBool implements the [Scanner] interface so it can be used as a scan destination, similar to NullString.

type NullByte added in v1.2.4

type NullByte = Null[byte]

NullByte represents a byte that may be null. NullByte implements the [Scanner] interface so it can be used as a scan destination, similar to NullString.

type NullFloat64 added in v1.2.4

type NullFloat64 = Null[float64]

NullFloat64 represents a float64 that may be null. NullFloat64 implements the [Scanner] interface so it can be used as a scan destination, similar to NullString.

type NullInt16 added in v1.2.4

type NullInt16 = Null[int16]

NullInt16 represents an int16 that may be null. NullInt16 implements the [Scanner] interface so it can be used as a scan destination, similar to NullString.

type NullInt32 added in v1.2.4

type NullInt32 = Null[int32]

NullInt32 represents an int32 that may be null. NullInt32 implements the [Scanner] interface so it can be used as a scan destination, similar to NullString.

type NullInt64 added in v1.2.4

type NullInt64 = Null[int64]

NullInt64 represents an int64 that may be null. NullInt64 implements the [Scanner] interface so it can be used as a scan destination, similar to NullString.

type NullString added in v1.2.4

type NullString = Null[string]

NullString represents a string that may be null. NullString implements the [Scanner] interface so it can be used as a scan destination:

var s NullString
err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
...
if s.Valid {
   // use s.String
} else {
   // NULL value
}

type NullTime added in v1.2.4

type NullTime = Null[time.Time]

NullTime represents a time.Time that may be null. NullTime implements the [Scanner] interface so it can be used as a scan destination, similar to NullString.

type Time added in v1.0.4

type Time time.Duration

Time is time data type.

func NewTime added in v1.0.4

func NewTime(hour, min, sec, nsec int) Time

NewTime is a constructor for Time and returns new Time.

func (Time) GormDBDataType added in v1.0.4

func (Time) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType returns gorm DB data type based on the current using database.

func (Time) GormDataType added in v1.0.4

func (Time) GormDataType() string

GormDataType returns gorm common data type. This type is used for the field's column type.

func (Time) MarshalJSON added in v1.0.4

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler to convert Time to json serialization.

func (*Time) Scan added in v1.0.4

func (t *Time) Scan(src interface{}) error

Scan implements sql.Scanner interface and scans value into Time,

func (Time) String added in v1.0.4

func (t Time) String() string

String implements fmt.Stringer interface.

func (*Time) UnmarshalJSON added in v1.0.4

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler to deserialize json data.

func (Time) Value added in v1.0.4

func (t Time) Value() (driver.Value, error)

Value implements driver.Valuer interface and returns string format of Time.

type URL added in v1.0.7

type URL url.URL

func (URL) GormDBDataType added in v1.0.7

func (URL) GormDBDataType(db *gorm.DB, field *schema.Field) string

func (URL) GormDataType added in v1.0.7

func (URL) GormDataType() string

func (URL) MarshalJSON added in v1.0.7

func (u URL) MarshalJSON() ([]byte, error)

func (*URL) Scan added in v1.0.7

func (u *URL) Scan(value interface{}) error

func (*URL) String added in v1.0.7

func (u *URL) String() string

func (*URL) UnmarshalJSON added in v1.0.7

func (u *URL) UnmarshalJSON(data []byte) error

func (URL) Value added in v1.0.7

func (u URL) Value() (driver.Value, error)

type UUID added in v1.2.2

type UUID uuid.UUID

This datatype stores the uuid in the database as a string. To store the uuid in the database as a binary (byte) array, please refer to datatypes.BinUUID.

func NewUUIDv1 added in v1.2.2

func NewUUIDv1() UUID

NewUUIDv1 generates a UUID version 1, panics on generation failure.

func NewUUIDv4 added in v1.2.2

func NewUUIDv4() UUID

NewUUIDv4 generates a UUID version 4, panics on generation failure.

func (UUID) Equals added in v1.2.2

func (u UUID) Equals(other UUID) bool

Equals returns true if string form of UUID matches other, false otherwise.

func (UUID) GormDBDataType added in v1.2.2

func (UUID) GormDBDataType(db *gorm.DB, field *schema.Field) string

GormDBDataType gorm db data type.

func (UUID) GormDataType added in v1.2.2

func (UUID) GormDataType() string

GormDataType gorm common data type.

func (UUID) IsEmpty added in v1.2.2

func (u UUID) IsEmpty() bool

IsEmpty returns true if UUID is nil UUID or of zero length, false otherwise.

func (*UUID) IsEmptyPtr added in v1.2.2

func (u *UUID) IsEmptyPtr() bool

IsEmptyPtr returns true if caller UUID ptr is nil or it's value is empty.

func (UUID) IsNil added in v1.2.2

func (u UUID) IsNil() bool

IsNil returns true if the UUID is a nil UUID (all zeroes), false otherwise.

func (*UUID) IsNilPtr added in v1.2.2

func (u *UUID) IsNilPtr() bool

IsNilPtr returns true if caller UUID ptr is nil, false otherwise.

func (UUID) Length added in v1.2.2

func (u UUID) Length() int

Length returns the number of characters in string form of UUID.

func (*UUID) Scan added in v1.2.2

func (u *UUID) Scan(value interface{}) error

Scan is the scanner function for this datatype.

func (UUID) String added in v1.2.2

func (u UUID) String() string

String returns the string form of the UUID.

func (UUID) Value added in v1.2.2

func (u UUID) Value() (driver.Value, error)

Value is the valuer function for this datatype.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL