gorm

package module
v0.0.0-...-e658000 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2022 License: MIT Imports: 23 Imported by: 14

README

GORM

The fantastic ORM library for Golang, aims to be developer friendly.

go report card test status Open Collective Backer Open Collective Sponsor MIT license Go.Dev reference

Overview

  • Full-Featured ORM
  • Associations (Has One, Has Many, Belongs To, Many To Many, Polymorphism, Single-table inheritance)
  • Hooks (Before/After Create/Save/Update/Delete/Find)
  • Eager loading with Preload, Joins
  • Transactions, Nested Transactions, Save Point, RollbackTo to Saved Point
  • Context, Prepared Statement Mode, DryRun Mode
  • Batch Insert, FindInBatches, Find To Map
  • SQL Builder, Upsert, Locking, Optimizer/Index/Comment Hints, NamedArg, Search/Update/Create with SQL Expr
  • Composite Primary Key
  • Auto Migrations
  • Logger
  • Extendable, flexible plugin API: Database Resolver (Multiple Databases, Read/Write Splitting) / Prometheus…
  • Every feature comes with tests
  • Developer Friendly

Getting Started

Contributing

You can help to deliver a better GORM, check out things you can do

License

© Jinzhu, 2013~time.Now

Released under the MIT License

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrRecordNotFound record not found error
	ErrRecordNotFound = logger.ErrRecordNotFound
	// ErrInvalidTransaction invalid transaction when you are trying to `Commit` or `Rollback`
	ErrInvalidTransaction = errors.New("invalid transaction")
	// ErrNotImplemented not implemented
	ErrNotImplemented = errors.New("not implemented")
	// ErrMissingWhereClause missing where clause
	ErrMissingWhereClause = errors.New("WHERE conditions required")
	// ErrUnsupportedRelation unsupported relations
	ErrUnsupportedRelation = errors.New("unsupported relations")
	// ErrPrimaryKeyRequired primary keys required
	ErrPrimaryKeyRequired = errors.New("primary key required")
	// ErrModelValueRequired model value required
	ErrModelValueRequired = errors.New("model value required")
	// ErrInvalidData unsupported data
	ErrInvalidData = errors.New("unsupported data")
	// ErrUnsupportedDriver unsupported driver
	ErrUnsupportedDriver = errors.New("unsupported driver")
	// ErrRegistered registered
	ErrRegistered = errors.New("registered")
	// ErrInvalidField invalid field
	ErrInvalidField = errors.New("invalid field")
	// ErrEmptySlice empty slice found
	ErrEmptySlice = errors.New("empty slice found")
	// ErrDryRunModeUnsupported dry run mode unsupported
	ErrDryRunModeUnsupported = errors.New("dry run mode unsupported")
	// ErrInvalidDB invalid db
	ErrInvalidDB = errors.New("invalid db")
	// ErrInvalidValue invalid value
	ErrInvalidValue = errors.New("invalid value, should be pointer to struct or slice")
	// ErrInvalidValueOfLength invalid values do not match length
	ErrInvalidValueOfLength = errors.New("invalid association values, length doesn't match")
	// ErrPreloadNotAllowed preload is not allowed when count is used
	ErrPreloadNotAllowed = errors.New("preload is not allowed when count is used")
)
View Source
var (
	TimeReflectType    = reflect.TypeOf(time.Time{})
	TimePtrReflectType = reflect.TypeOf(&time.Time{})
	ByteReflectType    = reflect.TypeOf(uint8(0))
)

special types' reflect type

View Source
var ErrUnsupportedDataType = errors.New("unsupported data type")

ErrUnsupportedDataType unsupported data type

Functions

func DeletedAtDeleteClauses

func DeletedAtDeleteClauses(f *Field) []clause.Interface

func DeletedAtQueryClauses

func DeletedAtQueryClauses(f *Field) []clause.Interface

func DeletedAtUpdateClauses

func DeletedAtUpdateClauses(f *Field) []clause.Interface

func Expr

func Expr(expr string, args ...interface{}) clause.Expr

Expr returns clause.Expr, which can be used to pass SQL expression as params

func GetIdentityFieldValuesMap

func GetIdentityFieldValuesMap(ctx context.Context, reflectValue reflect.Value, fields []*Field) (map[string][]reflect.Value, [][]interface{})

GetIdentityFieldValuesMap get identity map from fields

func GetIdentityFieldValuesMapFromValues

func GetIdentityFieldValuesMapFromValues(ctx context.Context, values []interface{}, fields []*Field) (map[string][]reflect.Value, [][]interface{})

GetIdentityFieldValuesMapFromValues get identity map from fields

func GetRelationsValues

func GetRelationsValues(ctx context.Context, reflectValue reflect.Value, rels []*Relationship) (reflectResults reflect.Value)

GetRelationsValues get relations's values from a reflect value

func ParseTagSetting

func ParseTagSetting(str string, sep string) map[string]string

func RegisterSerializer

func RegisterSerializer(name string, serializer SerializerInterface)

RegisterSerializer register serializer

func Scan

func Scan(rows Rows, db *DB, mode ScanMode)

Scan scan rows into db statement

func ToQueryValues

func ToQueryValues(table string, foreignKeys []string, foreignValues [][]interface{}) (interface{}, []interface{})

ToQueryValues to query values

Types

type Association

type Association struct {
	DB           *DB
	Relationship *Relationship
	Error        error
}

Association Mode contains some helper methods to handle relationship things easily.

func (*Association) Append

func (association *Association) Append(values ...interface{}) error

func (*Association) Clear

func (association *Association) Clear() error

func (*Association) Count

func (association *Association) Count() (count int64)

func (*Association) Delete

func (association *Association) Delete(values ...interface{}) error

func (*Association) Find

func (association *Association) Find(out interface{}, conds ...interface{}) error

func (*Association) Replace

func (association *Association) Replace(values ...interface{}) error

type Check

type Check struct {
	Name       string
	Constraint string // length(phone) >= 10
	*Field
}

type ColumnType

type ColumnType interface {
	Name() string
	DatabaseTypeName() string                 // varchar
	ColumnType() (columnType string, ok bool) // varchar(64)
	PrimaryKey() (isPrimaryKey bool, ok bool)
	AutoIncrement() (isAutoIncrement bool, ok bool)
	Length() (length int64, ok bool)
	DecimalSize() (precision int64, scale int64, ok bool)
	Nullable() (nullable bool, ok bool)
	Unique() (unique bool, ok bool)
	ScanType() reflect.Type
	Comment() (value string, ok bool)
	DefaultValue() (value string, ok bool)
}

ColumnType column type interface

type Config

type Config struct {
	// GORM perform single create, update, delete operations in transactions by default to ensure database data integrity
	// You can disable it by setting `SkipDefaultTransaction` to true
	SkipDefaultTransaction bool
	// NamingStrategy tables, columns naming strategy
	NamingStrategy Namer
	// FullSaveAssociations full save associations
	FullSaveAssociations bool
	// Logger
	Logger logger.Interface
	// NowFunc the function to be used when creating a new timestamp
	NowFunc func() int32
	// DryRun generate sql without execute
	DryRun bool
	// PrepareStmt executes the given query in cached statement
	PrepareStmt bool
	// DisableAutomaticPing
	DisableAutomaticPing bool
	// DisableForeignKeyConstraintWhenMigrating
	DisableForeignKeyConstraintWhenMigrating bool
	// DisableNestedTransaction disable nested transaction
	DisableNestedTransaction bool
	// AllowGlobalUpdate allow global update
	AllowGlobalUpdate bool
	// QueryFields executes the SQL query with all fields of the table
	QueryFields bool
	// CreateBatchSize default create batch size
	CreateBatchSize int

	// ClauseBuilders clause builder
	ClauseBuilders map[string]clause.ClauseBuilder
	// ConnPool db conn pool
	ConnPool ConnPool
	// Dialector database dialector
	Dialector
	// Plugins registered plugins
	Plugins map[string]Plugin
	// contains filtered or unexported fields
}

Config GORM config

func (*Config) AfterInitialize

func (c *Config) AfterInitialize(db *DB) error

AfterInitialize initialize plugins after db connected

func (*Config) Apply

func (c *Config) Apply(config *Config) error

Apply update config to new config

type ConnPool

type ConnPool interface {
	PrepareContext(ctx context.Context, query string) (*sql.Stmt, error)
	ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
}

ConnPool db conns pool interface

type ConnPoolBeginner

type ConnPoolBeginner interface {
	BeginTx(ctx context.Context, opts *sql.TxOptions) (ConnPool, error)
}

ConnPoolBeginner conn pool beginner

type Constraint

type Constraint struct {
	Name            string
	Field           *Field
	Schema          *Schema
	ForeignKeys     []*Field
	ReferenceSchema *Schema
	References      []*Field
	OnDelete        string
	OnUpdate        string
}

type CreateClausesInterface

type CreateClausesInterface interface {
	CreateClauses(*Field) []clause.Interface
}

CreateClausesInterface create clauses interface

type DB

type DB struct {
	*Config
	Error        error
	RowsAffected int64
	Statement    *Statement
	// contains filtered or unexported fields
}

DB GORM DB definition

func Open

func Open(dialector Dialector, opts ...Option) (db *DB, err error)

Open initialize db session based on dialector

func (*DB) AddError

func (db *DB) AddError(err error) error

AddError add error to db

func (*DB) Assign

func (db *DB) Assign(attrs ...interface{}) (tx *DB)

func (*DB) Association

func (db *DB) Association(column string) *Association

func (*DB) Attrs

func (db *DB) Attrs(attrs ...interface{}) (tx *DB)

func (*DB) AutoMigrate

func (db *DB) AutoMigrate(dst ...interface{}) error

AutoMigrate run auto migration for given models

func (*DB) Begin

func (db *DB) Begin(opts ...*sql.TxOptions) *DB

Begin begins a transaction with any transaction options opts

func (*DB) Callback

func (db *DB) Callback() *callbacks

Callback returns callback manager

func (*DB) Clauses

func (db *DB) Clauses(conds ...clause.Expression) (tx *DB)

Clauses Add clauses

func (*DB) Commit

func (db *DB) Commit() *DB

Commit commits the changes in a transaction

func (*DB) Connection

func (db *DB) Connection(fc func(tx *DB) error) (err error)

Connection uses a db connection to execute an arbitrary number of commands in fc. When finished, the connection is returned to the connection pool.

func (*DB) Count

func (db *DB) Count(count *int64) (tx *DB)

func (*DB) Create

func (db *DB) Create(value interface{}) (tx *DB)

Create inserts value, returning the inserted data's primary key in value's id

func (*DB) CreateInBatches

func (db *DB) CreateInBatches(value interface{}, batchSize int) (tx *DB)

CreateInBatches inserts value in batches of batchSize

func (*DB) DB

func (db *DB) DB() (*sql.DB, error)

DB returns `*sql.DB`

func (*DB) Debug

func (db *DB) Debug() (tx *DB)

Debug start debug mode

func (*DB) Delete

func (db *DB) Delete(value interface{}, conds ...interface{}) (tx *DB)

Delete deletes value matching given conditions. If value contains primary key it is included in the conditions. If value includes a deleted_at field, then Delete performs a soft delete instead by setting deleted_at with the current time if null.

func (*DB) Distinct

func (db *DB) Distinct(args ...interface{}) (tx *DB)

Distinct specify distinct fields that you want querying

func (*DB) Exec

func (db *DB) Exec(sql string, values ...interface{}) (tx *DB)

Exec executes raw sql

func (*DB) Find

func (db *DB) Find(dest interface{}, conds ...interface{}) (tx *DB)

Find finds all records matching given conditions conds

func (*DB) FindInBatches

func (db *DB) FindInBatches(dest interface{}, batchSize int, fc func(tx *DB, batch int) error) *DB

FindInBatches finds all records in batches of batchSize

func (*DB) First

func (db *DB) First(dest interface{}, conds ...interface{}) (tx *DB)

First finds the first record ordered by primary key, matching given conditions conds

func (*DB) FirstOrCreate

func (db *DB) FirstOrCreate(dest interface{}, conds ...interface{}) (tx *DB)

FirstOrCreate finds the first matching record, otherwise if not found creates a new instance with given conds. Each conds must be a struct or map.

func (*DB) FirstOrInit

func (db *DB) FirstOrInit(dest interface{}, conds ...interface{}) (tx *DB)

FirstOrInit finds the first matching record, otherwise if not found initializes a new instance with given conds. Each conds must be a struct or map.

func (*DB) Get

func (db *DB) Get(key string) (interface{}, bool)

Get get value with key from current db instance's context

func (*DB) Group

func (db *DB) Group(name string) (tx *DB)

Group specify the group method on the find

func (*DB) Having

func (db *DB) Having(query interface{}, args ...interface{}) (tx *DB)

Having specify HAVING conditions for GROUP BY

func (*DB) InstanceGet

func (db *DB) InstanceGet(key string) (interface{}, bool)

InstanceGet get value with key from current db instance's context

func (*DB) InstanceSet

func (db *DB) InstanceSet(key string, value interface{}) *DB

InstanceSet store value with key into current db instance's context

func (*DB) Joins

func (db *DB) Joins(query string, args ...interface{}) (tx *DB)

Joins specify Joins conditions

db.Joins("Account").Find(&user)
db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Find(&user)
db.Joins("Account", DB.Select("id").Where("user_id = users.id AND name = ?", "someName").Model(&Account{}))

func (*DB) Last

func (db *DB) Last(dest interface{}, conds ...interface{}) (tx *DB)

Last finds the last record ordered by primary key, matching given conditions conds

func (*DB) Limit

func (db *DB) Limit(limit int) (tx *DB)

Limit specify the number of records to be retrieved

func (*DB) Migrator

func (db *DB) Migrator() Migrator

Migrator returns migrator

func (*DB) Model

func (db *DB) Model(value interface{}) (tx *DB)

Model specify the model you would like to run db operations

// update all users's name to `hello`
db.Model(&User{}).Update("name", "hello")
// if user's primary key is non-blank, will use it as condition, then will only update the user's name to `hello`
db.Model(&user).Update("name", "hello")

func (*DB) Not

func (db *DB) Not(query interface{}, args ...interface{}) (tx *DB)

Not add NOT conditions

func (*DB) Offset

func (db *DB) Offset(offset int) (tx *DB)

Offset specify the number of records to skip before starting to return the records

func (*DB) Omit

func (db *DB) Omit(columns ...string) (tx *DB)

Omit specify fields that you want to ignore when creating, updating and querying

func (*DB) Or

func (db *DB) Or(query interface{}, args ...interface{}) (tx *DB)

Or add OR conditions

func (*DB) Order

func (db *DB) Order(value interface{}) (tx *DB)

Order specify order when retrieve records from database

db.Order("name DESC")
db.Order(clause.OrderByColumn{Column: clause.Column{Name: "name"}, Desc: true})

func (*DB) Pluck

func (db *DB) Pluck(column string, dest interface{}) (tx *DB)

Pluck queries a single column from a model, returning in the slice dest. E.g.:

var ages []int64
db.Model(&users).Pluck("age", &ages)

func (*DB) Preload

func (db *DB) Preload(query string, args ...interface{}) (tx *DB)

Preload preload associations with given conditions

db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)

func (*DB) Raw

func (db *DB) Raw(sql string, values ...interface{}) (tx *DB)

func (*DB) Rollback

func (db *DB) Rollback() *DB

Rollback rollbacks the changes in a transaction

func (*DB) RollbackTo

func (db *DB) RollbackTo(name string) *DB

func (*DB) Row

func (db *DB) Row() *sql.Row

func (*DB) Rows

func (db *DB) Rows() (*sql.Rows, error)

func (*DB) Save

func (db *DB) Save(value interface{}) (tx *DB)

Save updates value in database. If value doesn't contain a matching primary key, value is inserted.

func (*DB) SavePoint

func (db *DB) SavePoint(name string) *DB

func (*DB) Scan

func (db *DB) Scan(dest interface{}) (tx *DB)

Scan scans selected value to the struct dest

func (*DB) ScanRows

func (db *DB) ScanRows(rows *sql.Rows, dest interface{}) error

func (*DB) Scopes

func (db *DB) Scopes(funcs ...func(*DB) *DB) (tx *DB)

Scopes pass current database connection to arguments `func(DB) DB`, which could be used to add conditions dynamically

func AmountGreaterThan1000(db *gorm.DB) *gorm.DB {
    return db.Where("amount > ?", 1000)
}

func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB {
    return func (db *gorm.DB) *gorm.DB {
        return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status)
    }
}

db.Scopes(AmountGreaterThan1000, OrderStatus([]string{"paid", "shipped"})).Find(&orders)

func (*DB) Select

func (db *DB) Select(query interface{}, args ...interface{}) (tx *DB)

Select specify fields that you want when querying, creating, updating

func (*DB) Session

func (db *DB) Session(config *Session) *DB

Session create new db session

func (*DB) Set

func (db *DB) Set(key string, value interface{}) *DB

Set store value with key into current db instance's context

func (*DB) SetupJoinTable

func (db *DB) SetupJoinTable(model interface{}, field string, joinTable interface{}) error

SetupJoinTable setup join table schema

func (*DB) Table

func (db *DB) Table(name string, args ...interface{}) (tx *DB)

Table specify the table you would like to run db operations

func (*DB) Take

func (db *DB) Take(dest interface{}, conds ...interface{}) (tx *DB)

Take finds the first record returned by the database in no specified order, matching given conditions conds

func (*DB) ToSQL

func (db *DB) ToSQL(queryFn func(tx *DB) *DB) string

ToSQL for generate SQL string.

db.ToSQL(func(tx *gorm.DB) *gorm.DB {
		return tx.Model(&User{}).Where(&User{Name: "foo", Age: 20})
			.Limit(10).Offset(5)
			.Order("name ASC")
			.First(&User{})
})

func (*DB) Transaction

func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err error)

Transaction start a transaction as a block, return error will rollback, otherwise to commit. Transaction executes an arbitrary number of commands in fc within a transaction. On success the changes are committed; if an error occurs they are rolled back.

func (*DB) Unscoped

func (db *DB) Unscoped() (tx *DB)

func (*DB) Update

func (db *DB) Update(column string, value interface{}) (tx *DB)

Update updates column with value using callbacks. Reference: https://gorm.io/docs/update.html#Update-Changed-Fields

func (*DB) UpdateColumn

func (db *DB) UpdateColumn(column string, value interface{}) (tx *DB)

func (*DB) UpdateColumns

func (db *DB) UpdateColumns(values interface{}) (tx *DB)

func (*DB) Updates

func (db *DB) Updates(values interface{}) (tx *DB)

Updates updates attributes using callbacks. values must be a struct or map. Reference: https://gorm.io/docs/update.html#Update-Changed-Fields

func (*DB) Use

func (db *DB) Use(plugin Plugin) error

Use use plugin

func (*DB) Where

func (db *DB) Where(query interface{}, args ...interface{}) (tx *DB)

Where add conditions

func (*DB) WithContext

func (db *DB) WithContext(ctx context.Context) *DB

WithContext change current instance db's context to ctx

type DataType

type DataType string

DataType GORM data type

const (
	Bool   DataType = "bool"
	Int    DataType = "int"
	Uint   DataType = "uint"
	Float  DataType = "float"
	String DataType = "string"
	Time   DataType = "time"
	Bytes  DataType = "bytes"
)

GORM fields types

type DeleteClausesInterface

type DeleteClausesInterface interface {
	DeleteClauses(*Field) []clause.Interface
}

DeleteClausesInterface delete clauses interface

type DeletedAt

type DeletedAt int32

type Dialector

type Dialector interface {
	Name() string
	Initialize(*DB) error
	Migrator(db *DB) Migrator
	DataTypeOf(*Field) string
	DefaultValueOf(*Field) clause.Expression
	BindVarTo(writer clause.Writer, stmt *Statement, v interface{})
	QuoteTo(clause.Writer, string)
	Explain(sql string, vars ...interface{}) string
}

Dialector GORM database dialector

type Field

type Field struct {
	Name                   string
	DBName                 string
	BindNames              []string
	DataType               DataType
	GORMDataType           DataType
	PrimaryKey             bool
	AutoIncrement          bool
	AutoIncrementIncrement int64
	Creatable              bool
	Updatable              bool
	Readable               bool
	AutoCreateTime         TimeType
	AutoUpdateTime         TimeType
	HasDefaultValue        bool
	DefaultValue           string
	DefaultValueInterface  interface{}
	NotNull                bool
	Unique                 bool
	Comment                string
	Size                   int
	Precision              int
	Scale                  int
	IgnoreMigration        bool
	FieldType              reflect.Type
	IndirectFieldType      reflect.Type
	StructField            reflect.StructField
	Tag                    reflect.StructTag
	TagSettings            map[string]string
	Schema                 *Schema
	EmbeddedSchema         *Schema
	OwnerSchema            *Schema
	ReflectValueOf         func(context.Context, reflect.Value) reflect.Value
	ValueOf                func(context.Context, reflect.Value) (value interface{}, zero bool)
	Set                    func(context.Context, reflect.Value, interface{}) error
	Serializer             SerializerInterface
	NewValuePool           FieldNewValuePool
}

Field is the representation of model schema's field

type FieldNewValuePool

type FieldNewValuePool interface {
	Get() interface{}
	Put(interface{})
}

FieldNewValuePool field new scan value pool

type GetDBConnector

type GetDBConnector interface {
	GetDBConn() (*sql.DB, error)
}

GetDBConnector SQL db connector

type GobSerializer

type GobSerializer struct {
}

GobSerializer gob serializer

func (GobSerializer) Scan

func (GobSerializer) Scan(ctx context.Context, field *Field, dst reflect.Value, dbValue interface{}) (err error)

Scan implements serializer interface

func (GobSerializer) Value

func (GobSerializer) Value(ctx context.Context, field *Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)

Value implements serializer interface

type GormDataTypeInterface

type GormDataTypeInterface interface {
	GormDataType() string
}

GormDataTypeInterface gorm data type interface

type Index

type Index struct {
	Name    string
	Class   string // UNIQUE | FULLTEXT | SPATIAL
	Type    string // btree, hash, gist, spgist, gin, and brin
	Where   string
	Comment string
	Option  string // WITH PARSER parser_name
	Fields  []IndexOption
}

type IndexOption

type IndexOption struct {
	*Field
	Expression string
	Sort       string // DESC, ASC
	Collate    string
	Length     int
	// contains filtered or unexported fields
}

type JSONSerializer

type JSONSerializer struct {
}

JSONSerializer json serializer

func (JSONSerializer) Scan

func (JSONSerializer) Scan(ctx context.Context, field *Field, dst reflect.Value, dbValue interface{}) (err error)

Scan implements serializer interface

func (JSONSerializer) Value

func (JSONSerializer) Value(ctx context.Context, field *Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)

Value implements serializer interface

type Migrator

type Migrator interface {
	// AutoMigrate
	AutoMigrate(dst ...interface{}) error

	// Database
	CurrentDatabase() string
	FullDataTypeOf(*Field) clause.Expr
	GetTypeAliases(databaseTypeName string) []string

	// Tables
	CreateTable(dst ...interface{}) error
	DropTable(dst ...interface{}) error
	HasTable(dst interface{}) bool
	RenameTable(oldName, newName interface{}) error
	GetTables() (tableList []string, err error)

	// Columns
	AddColumn(dst interface{}, field string) error
	DropColumn(dst interface{}, field string) error
	AlterColumn(dst interface{}, field string) error
	MigrateColumn(dst interface{}, field *Field, columnType ColumnType) error
	HasColumn(dst interface{}, field string) bool
	RenameColumn(dst interface{}, oldName, field string) error
	ColumnTypes(dst interface{}) ([]ColumnType, error)

	// Views
	CreateView(name string, option ViewOption) error
	DropView(name string) error

	// Constraints
	CreateConstraint(dst interface{}, name string) error
	DropConstraint(dst interface{}, name string) error
	HasConstraint(dst interface{}, name string) bool

	// Indexes
	CreateIndex(dst interface{}, name string) error
	DropIndex(dst interface{}, name string) error
	HasIndex(dst interface{}, name string) bool
	RenameIndex(dst interface{}, oldName, newName string) error
	GetIndexes(dst interface{}) ([]SchemaIndex, error)
}

Migrator migrator interface

type Model

type Model struct {
	ID        uint `gorm:"primarykey"`
	CreatedAt int32
	UpdatedAt int32
	DeletedAt int32 `gorm:"index;default:0"`
}

Model a basic GoLang struct which includes the following fields: ID, CreatedAt, UpdatedAt, DeletedAt It may be embedded into your model or you may build your own model without it

type User struct {
  gorm.Model
}

type Namer

type Namer interface {
	TableName(table string) string
	SchemaName(table string) string
	ColumnName(table, column string) string
	JoinTableName(joinTable string) string
	RelationshipFKName(Relationship) string
	CheckerName(table, column string) string
	IndexName(table, column string) string
}

Namer namer interface

type NamingStrategy

type NamingStrategy struct {
	TablePrefix   string
	SingularTable bool
	NameReplacer  Replacer
	NoLowerCase   bool
}

NamingStrategy tables, columns naming strategy

func (NamingStrategy) CheckerName

func (ns NamingStrategy) CheckerName(table, column string) string

CheckerName generate checker name

func (NamingStrategy) ColumnName

func (ns NamingStrategy) ColumnName(table, column string) string

ColumnName convert string to column name

func (NamingStrategy) IndexName

func (ns NamingStrategy) IndexName(table, column string) string

IndexName generate index name

func (NamingStrategy) JoinTableName

func (ns NamingStrategy) JoinTableName(str string) string

JoinTableName convert string to join table name

func (NamingStrategy) RelationshipFKName

func (ns NamingStrategy) RelationshipFKName(rel Relationship) string

RelationshipFKName generate fk name for relation

func (NamingStrategy) SchemaName

func (ns NamingStrategy) SchemaName(table string) string

SchemaName generate schema name from table name, don't guarantee it is the reverse value of TableName

func (NamingStrategy) TableName

func (ns NamingStrategy) TableName(str string) string

TableName convert string to table name

type Option

type Option interface {
	Apply(*Config) error
	AfterInitialize(*DB) error
}

Option gorm option interface

type Plugin

type Plugin interface {
	Name() string
	Initialize(*DB) error
}

Plugin GORM plugin interface

type Polymorphic

type Polymorphic struct {
	PolymorphicID   *Field
	PolymorphicType *Field
	Value           string
}

type PreparedStmtDB

type PreparedStmtDB struct {
	Stmts       map[string]Stmt
	PreparedSQL []string
	Mux         *sync.RWMutex
	ConnPool
}

func (*PreparedStmtDB) BeginTx

func (db *PreparedStmtDB) BeginTx(ctx context.Context, opt *sql.TxOptions) (ConnPool, error)

func (*PreparedStmtDB) Close

func (db *PreparedStmtDB) Close()

func (*PreparedStmtDB) ExecContext

func (db *PreparedStmtDB) ExecContext(ctx context.Context, query string, args ...interface{}) (result sql.Result, err error)

func (*PreparedStmtDB) GetDBConn

func (db *PreparedStmtDB) GetDBConn() (*sql.DB, error)

func (*PreparedStmtDB) QueryContext

func (db *PreparedStmtDB) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error)

func (*PreparedStmtDB) QueryRowContext

func (db *PreparedStmtDB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row

type PreparedStmtTX

type PreparedStmtTX struct {
	Tx
	PreparedStmtDB *PreparedStmtDB
}

func (*PreparedStmtTX) Commit

func (tx *PreparedStmtTX) Commit() error

func (*PreparedStmtTX) ExecContext

func (tx *PreparedStmtTX) ExecContext(ctx context.Context, query string, args ...interface{}) (result sql.Result, err error)

func (*PreparedStmtTX) QueryContext

func (tx *PreparedStmtTX) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error)

func (*PreparedStmtTX) QueryRowContext

func (tx *PreparedStmtTX) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row

func (*PreparedStmtTX) Rollback

func (tx *PreparedStmtTX) Rollback() error

type QueryClausesInterface

type QueryClausesInterface interface {
	QueryClauses(*Field) []clause.Interface
}

QueryClausesInterface query clauses interface

type Reference

type Reference struct {
	PrimaryKey    *Field
	PrimaryValue  string
	ForeignKey    *Field
	OwnPrimaryKey bool
}

type Relationship

type Relationship struct {
	Name        string
	Type        RelationshipType
	Field       *Field
	Polymorphic *Polymorphic
	References  []*Reference
	Schema      *Schema
	FieldSchema *Schema
	JoinTable   *Schema
	// contains filtered or unexported fields
}

func (*Relationship) ParseConstraint

func (rel *Relationship) ParseConstraint() *Constraint

func (*Relationship) ToQueryConditions

func (rel *Relationship) ToQueryConditions(ctx context.Context, reflectValue reflect.Value) (conds []clause.Expression)

type RelationshipType

type RelationshipType string

RelationshipType relationship type

const (
	HasOne    RelationshipType = "has_one"      // HasOneRel has one relationship
	HasMany   RelationshipType = "has_many"     // HasManyRel has many relationship
	BelongsTo RelationshipType = "belongs_to"   // BelongsToRel belongs to relationship
	Many2Many RelationshipType = "many_to_many" // Many2ManyRel many to many relationship

)

type Relationships

type Relationships struct {
	HasOne    []*Relationship
	BelongsTo []*Relationship
	HasMany   []*Relationship
	Many2Many []*Relationship
	Relations map[string]*Relationship
}

type Replacer

type Replacer interface {
	Replace(name string) string
}

Replacer replacer interface like strings.Replacer

type Rows

type Rows interface {
	Columns() ([]string, error)
	ColumnTypes() ([]*sql.ColumnType, error)
	Next() bool
	Scan(dest ...interface{}) error
	Err() error
	Close() error
}

Rows rows interface

type SavePointerDialectorInterface

type SavePointerDialectorInterface interface {
	SavePoint(tx *DB, name string) error
	RollbackTo(tx *DB, name string) error
}

SavePointerDialectorInterface save pointer interface

type ScanMode

type ScanMode uint8

ScanMode scan data mode

const (
	ScanInitialized         ScanMode = 1 << 0 // 1
	ScanUpdate              ScanMode = 1 << 1 // 2
	ScanOnConflictDoNothing ScanMode = 1 << 2 // 4
)

scan modes

type Schema

type Schema struct {
	Name                      string
	ModelType                 reflect.Type
	Table                     string
	PrioritizedPrimaryField   *Field
	DBNames                   []string
	PrimaryFields             []*Field
	PrimaryFieldDBNames       []string
	Fields                    []*Field
	FieldsByName              map[string]*Field
	FieldsByDBName            map[string]*Field
	FieldsWithDefaultDBValue  []*Field // fields with default value assigned by database
	Relationships             Relationships
	CreateClauses             []clause.Interface
	QueryClauses              []clause.Interface
	UpdateClauses             []clause.Interface
	DeleteClauses             []clause.Interface
	BeforeCreate, AfterCreate bool
	BeforeUpdate, AfterUpdate bool
	BeforeDelete, AfterDelete bool
	BeforeSave, AfterSave     bool
	AfterFind                 bool
	// contains filtered or unexported fields
}

func Parse

func Parse(dest interface{}, cacheStore *sync.Map, namer Namer) (*Schema, error)

Parse get data type from dialector

func ParseWithSpecialTableName

func ParseWithSpecialTableName(dest interface{}, cacheStore *sync.Map, namer Namer, specialTableName string) (*Schema, error)

ParseWithSpecialTableName get data type from dialector with extra schema table

func (*Schema) LookIndex

func (schema *Schema) LookIndex(name string) *Index

func (Schema) LookUpField

func (schema Schema) LookUpField(name string) *Field

func (Schema) MakeSlice

func (schema Schema) MakeSlice() reflect.Value

func (*Schema) ParseCheckConstraints

func (schema *Schema) ParseCheckConstraints() map[string]Check

ParseCheckConstraints parse schema check constraints

func (*Schema) ParseField

func (schema *Schema) ParseField(fieldStruct reflect.StructField) *Field

ParseField parses reflect.StructField to Field

func (*Schema) ParseIndexes

func (schema *Schema) ParseIndexes() map[string]Index

ParseIndexes parse schema indexes

func (Schema) String

func (schema Schema) String() string

type SchemaIndex

type SchemaIndex interface {
	Table() string
	Name() string
	Columns() []string
	PrimaryKey() (isPrimaryKey bool, ok bool)
	Unique() (unique bool, ok bool)
	Option() string
}

type SerializerInterface

type SerializerInterface interface {
	Scan(ctx context.Context, field *Field, dst reflect.Value, dbValue interface{}) error
	SerializerValuerInterface
}

SerializerInterface serializer interface

func GetSerializer

func GetSerializer(name string) (serializer SerializerInterface, ok bool)

GetSerializer get serializer

type SerializerValuerInterface

type SerializerValuerInterface interface {
	Value(ctx context.Context, field *Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)
}

SerializerValuerInterface serializer valuer interface

type Session

type Session struct {
	DryRun                   bool
	PrepareStmt              bool
	NewDB                    bool
	Initialized              bool
	SkipHooks                bool
	SkipDefaultTransaction   bool
	DisableNestedTransaction bool
	AllowGlobalUpdate        bool
	FullSaveAssociations     bool
	QueryFields              bool
	Context                  context.Context
	Logger                   logger.Interface
	NowFunc                  func() int32
	CreateBatchSize          int
}

Session session config when create session with Session() method

type SoftDeleteDeleteClause

type SoftDeleteDeleteClause struct {
	Field *Field
}

func (SoftDeleteDeleteClause) Build

func (SoftDeleteDeleteClause) MergeClause

func (sd SoftDeleteDeleteClause) MergeClause(*clause.Clause)

func (SoftDeleteDeleteClause) ModifyStatement

func (sd SoftDeleteDeleteClause) ModifyStatement(stmt *Statement)

func (SoftDeleteDeleteClause) Name

func (sd SoftDeleteDeleteClause) Name() string

type SoftDeleteQueryClause

type SoftDeleteQueryClause struct {
	Field *Field
}

func (SoftDeleteQueryClause) Build

func (SoftDeleteQueryClause) MergeClause

func (sd SoftDeleteQueryClause) MergeClause(*clause.Clause)

func (SoftDeleteQueryClause) ModifyStatement

func (sd SoftDeleteQueryClause) ModifyStatement(stmt *Statement)

func (SoftDeleteQueryClause) Name

func (sd SoftDeleteQueryClause) Name() string

type SoftDeleteUpdateClause

type SoftDeleteUpdateClause struct {
	Field *Field
}

func (SoftDeleteUpdateClause) Build

func (SoftDeleteUpdateClause) MergeClause

func (sd SoftDeleteUpdateClause) MergeClause(*clause.Clause)

func (SoftDeleteUpdateClause) ModifyStatement

func (sd SoftDeleteUpdateClause) ModifyStatement(stmt *Statement)

func (SoftDeleteUpdateClause) Name

func (sd SoftDeleteUpdateClause) Name() string

type Statement

type Statement struct {
	*DB
	TableExpr            *clause.Expr
	Table                string
	Model                interface{}
	Unscoped             bool
	Dest                 interface{}
	ReflectValue         reflect.Value
	Clauses              map[string]clause.Clause
	BuildClauses         []string
	Distinct             bool
	Selects              []string // selected columns
	Omits                []string // omit columns
	Joins                []join
	Preloads             map[string][]interface{}
	Settings             sync.Map
	ConnPool             ConnPool
	Schema               *Schema
	Context              context.Context
	RaiseErrorOnNotFound bool
	SkipHooks            bool
	SQL                  strings.Builder
	Vars                 []interface{}
	CurDestIndex         int
	// contains filtered or unexported fields
}

Statement statement

func (*Statement) AddClause

func (stmt *Statement) AddClause(v clause.Interface)

AddClause add clause

func (*Statement) AddClauseIfNotExists

func (stmt *Statement) AddClauseIfNotExists(v clause.Interface)

AddClauseIfNotExists add clause if not exists

func (*Statement) AddVar

func (stmt *Statement) AddVar(writer clause.Writer, vars ...interface{})

AddVar add var

func (*Statement) Build

func (stmt *Statement) Build(clauses ...string)

Build build sql with clauses names

func (*Statement) BuildCondition

func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) []clause.Expression

BuildCondition build condition

func (*Statement) Changed

func (stmt *Statement) Changed(fields ...string) bool

Changed check model changed or not when updating

func (*Statement) Parse

func (stmt *Statement) Parse(value interface{}) (err error)

func (*Statement) ParseWithSpecialTableName

func (stmt *Statement) ParseWithSpecialTableName(value interface{}, specialTableName string) (err error)

func (*Statement) Quote

func (stmt *Statement) Quote(field interface{}) string

Quote returns quoted value

func (*Statement) QuoteTo

func (stmt *Statement) QuoteTo(writer clause.Writer, field interface{})

QuoteTo write quoted value to writer

func (*Statement) SelectAndOmitColumns

func (stmt *Statement) SelectAndOmitColumns(requireCreate, requireUpdate bool) (map[string]bool, bool)

SelectAndOmitColumns get select and omit columns, select -> true, omit -> false

func (*Statement) SetColumn

func (stmt *Statement) SetColumn(name string, value interface{}, fromCallbacks ...bool)

SetColumn set column's value

stmt.SetColumn("Name", "jinzhu") // Hooks Method
stmt.SetColumn("Name", "jinzhu", true) // Callbacks Method

func (*Statement) WriteByte

func (stmt *Statement) WriteByte(c byte) error

WriteByte write byte

func (*Statement) WriteQuoted

func (stmt *Statement) WriteQuoted(value interface{})

WriteQuoted write quoted value

func (*Statement) WriteString

func (stmt *Statement) WriteString(str string) (int, error)

WriteString write string

type StatementModifier

type StatementModifier interface {
	ModifyStatement(*Statement)
}

StatementModifier statement modifier interface

type Stmt

type Stmt struct {
	*sql.Stmt
	Transaction bool
}

type Tabler

type Tabler interface {
	TableName() string
}

type TimeType

type TimeType int64

TimeType GORM time type

const (
	UnixTime        TimeType = 1
	UnixSecond      TimeType = 2
	UnixMillisecond TimeType = 3
	UnixNanosecond  TimeType = 4
)

GORM time types

type Tx

type Tx interface {
	ConnPool
	TxCommitter
	StmtContext(ctx context.Context, stmt *sql.Stmt) *sql.Stmt
}

Tx sql.Tx interface

type TxBeginner

type TxBeginner interface {
	BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}

TxBeginner tx beginner

type TxCommitter

type TxCommitter interface {
	Commit() error
	Rollback() error
}

TxCommitter tx committer

type UnixSecondSerializer

type UnixSecondSerializer struct {
}

UnixSecondSerializer json serializer

func (UnixSecondSerializer) Scan

func (UnixSecondSerializer) Scan(ctx context.Context, field *Field, dst reflect.Value, dbValue interface{}) (err error)

Scan implements serializer interface

func (UnixSecondSerializer) Value

func (UnixSecondSerializer) Value(ctx context.Context, field *Field, dst reflect.Value, fieldValue interface{}) (result interface{}, err error)

Value implements serializer interface

type UpdateClausesInterface

type UpdateClausesInterface interface {
	UpdateClauses(*Field) []clause.Interface
}

UpdateClausesInterface update clauses interface

type Valuer

type Valuer interface {
	GormValue(context.Context, *DB) clause.Expr
}

Valuer gorm valuer interface

type ViewOption

type ViewOption struct {
	Replace     bool
	CheckOption string
	Query       *DB
}

ViewOption view option

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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