AnalogJ / thesparktree-blog

github pages.
https://blog.thesparktree.com
0 stars 1 forks source link

Gorm - Tips & Tricks #158

Open AnalogJ opened 1 year ago

AnalogJ commented 1 year ago

GoNative SQLite Driver

import (
  "github.com/glebarez/sqlite"
  "gorm.io/gorm"
)

UUID ID

type MyModel struct {
    ID        uuid.UUID `gorm:"type:uuid;primary_key;"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time `gorm:"index"`
}

func (base *MyModel) BeforeCreate(tx *gorm.DB) error {
    base.ID = uuid.New()
    return nil
}

Create Unique Composite Index (spanning multiple fields)

type MyModel struct {
    SourceID uuid.UUID `json:"source_id" gorm:"not null;uniqueIndex:idx_source_resource_id"`

    SourceResourceType string `json:"source_resource_type" gorm:"not null;uniqueIndex:idx_source_resource_id"`
    SourceResourceID   string `json:"source_resource_id" gorm:"not null;uniqueIndex:idx_source_resource_id"`
}

Unique Composite Index in Embedded Struct


Failed to automigrate! - SQL logic error: index idx_source_resource_id already exists (1) 

https://gorm.io/docs/indexes.html#Shared-composite-indexes

    SourceID uuid.UUID `json:"source_id" gorm:"not null;index:,unique,composite:source_resource_id"`

    SourceResourceType string `json:"source_resource_type" gorm:"not null;index:,unique,composite:source_resource_id"`
    SourceResourceID   string `json:"source_resource_id" gorm:"not null;index:,unique,composite:source_resource_id"`

Foreign Key references

type OriginBase struct {
    ModelBase
    User   User      `json:"user" gorm:"-"`
    UserID uuid.UUID `json:"user_id"`
}

https://gorm.io/docs/belongs_to.html

JSON storage for Objects/Arrays

type Profile struct {

    Demographics Demographics `json:"demographics" gorm:"serializer:json;default:'{}'"`
}

note: `default:'{}'` is required, otherwise saving Profile{Demographics{}} will throw an error.