db

package
v2.0.0-...-bd8bb20 Latest Latest
Warning

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

Go to latest
Published: May 8, 2024 License: MIT, MIT Imports: 6 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddError

func AddError(err error) error

AddError add error to db

func Assign

func Assign(attrs ...any) (tx *gorm.DB)

Assign provide attributes used in FirstOrCreate or FirstOrInit

Assign adds attributes even if the record is found. If using FirstOrCreate, this means that records will be updated even if they are found.

// assign an email regardless of if the record is not found
db.Where(User{Name: "non_existing"}).Assign(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "non_existing", Email: "fake@fake.org"}

// assign email regardless of if record is found
db.Where(User{Name: "jinzhu"}).Assign(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "jinzhu", Age: 20, Email: "fake@fake.org"}

func Attrs

func Attrs(attrs ...any) (tx *gorm.DB)

Attrs provide attributes used in FirstOrCreate or FirstOrInit

Attrs only adds attributes if the record is not found.

// assign an email if the record is not found
db.Where(User{Name: "non_existing"}).Attrs(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "non_existing", Email: "fake@fake.org"}

// assign an email if the record is not found, otherwise ignore provided email
db.Where(User{Name: "jinzhu"}).Attrs(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "jinzhu", Age: 20}

func Begin

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

Begin begins a transaction with any transaction options opts

func Clauses

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

Clauses Add clauses

This supports both standard clauses (clause.OrderBy, clause.Limit, clause.Where) and more advanced techniques like specifying lock strength and optimizer hints. See the docs for more depth.

// add a simple limit clause
db.Clauses(clause.Limit{Limit: 1}).Find(&User{})
// tell the optimizer to use the `idx_user_name` index
db.Clauses(hints.UseIndex("idx_user_name")).Find(&User{})
// specify the lock strength to UPDATE
db.Clauses(clause.Locking{Strength: "UPDATE"}).Find(&users)

func Commit

func Commit() *gorm.DB

Commit commits the changes in a transaction

func Connection

func Connection(fc func(tx *gorm.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 Count

func Count(count *int64) (tx *gorm.DB)

func Create

func Create(value any) (tx *gorm.DB)

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

func CreateInBatches

func CreateInBatches(value any, batchSize int) (tx *gorm.DB)

CreateInBatches inserts value in batches of batchSize

func DB

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

DB returns `*sql.DB`

func Debug

func Debug() (tx *gorm.DB)

Debug start debug mode

func Delete

func Delete(value any, conds ...any) (tx *gorm.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 Distinct

func Distinct(args ...any) (tx *gorm.DB)

Distinct specify distinct fields that you want querying

// Select distinct names of users
db.Distinct("name").Find(&results)
// Select distinct name/age pairs from users
db.Distinct("name", "age").Find(&results)

func DoMigration

func DoMigration() error

func Exec

func Exec(sql string, values ...any) (tx *gorm.DB)

Exec executes raw sql

func Find

func Find(dest any, conds ...any) (tx *gorm.DB)

Find finds all records matching given conditions conds

func FindInBatches

func FindInBatches(dest any, batchSize int, fc func(tx *gorm.DB, batch int) error) *gorm.DB

FindInBatches finds all records in batches of batchSize

func First

func First(dest any, conds ...any) (tx *gorm.DB)

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

func FirstOrCreate

func FirstOrCreate(dest any, conds ...any) (tx *gorm.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.

Using FirstOrCreate in conjunction with Assign will result in an update to the database even if the record exists.

// assign an email if the record is not found
result := db.Where(User{Name: "non_existing"}).Attrs(User{Email: "fake@fake.org"}).FirstOrCreate(&user)
// user -> User{Name: "non_existing", Email: "fake@fake.org"}
// result.RowsAffected -> 1

// assign email regardless of if record is found
result := db.Where(User{Name: "jinzhu"}).Assign(User{Email: "fake@fake.org"}).FirstOrCreate(&user)
// user -> User{Name: "jinzhu", Age: 20, Email: "fake@fake.org"}
// result.RowsAffected -> 1

func FirstOrInit

func FirstOrInit(dest any, conds ...any) (tx *gorm.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.

FirstOrInit never modifies the database. It is often used with Assign and Attrs.

// assign an email if the record is not found
db.Where(User{Name: "non_existing"}).Attrs(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "non_existing", Email: "fake@fake.org"}

// assign email regardless of if record is found
db.Where(User{Name: "jinzhu"}).Assign(User{Email: "fake@fake.org"}).FirstOrInit(&user)
// user -> User{Name: "jinzhu", Age: 20, Email: "fake@fake.org"}

func Get

func Get(key string) (any, bool)

Get value with key from current db instance's context

func GetMigrationScript

func GetMigrationScript() []string

func GetModel

func GetModel(name string) *schema.Model

func Group

func Group(name string) (tx *gorm.DB)

Group specify the group method on the find

// Select the sum age of users with given names
db.Model(&User{}).Select("name, sum(age) as total").Group("name").Find(&results)

func Having

func Having(query any, args ...any) (tx *gorm.DB)

Having specify HAVING conditions for GROUP BY

// Select the sum age of users with name jinzhu
db.Model(&User{}).Select("name, sum(age) as total").Group("name").Having("name = ?", "jinzhu").Find(&result)

func InnerJoins

func InnerJoins(query string, args ...any) (tx *gorm.DB)

InnerJoins specify inner joins conditions db.InnerJoins("Account").Find(&user)

func InstanceGet

func InstanceGet(key string) (any, bool)

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

func InstanceSet

func InstanceSet(key string, value any) *gorm.DB

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

func Joins

func Joins(query string, args ...any) (tx *gorm.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 Last

func Last(dest any, conds ...any) (tx *gorm.DB)

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

func Limit

func Limit(limit int) (tx *gorm.DB)

Limit specify the number of records to be retrieved

Limit conditions can be cancelled by using `Limit(-1)`.

// retrieve 3 users
db.Limit(3).Find(&users)
// retrieve 3 users into users1, and all users into users2
db.Limit(3).Find(&users1).Limit(-1).Find(&users2)

func Model

func Model(value any) (tx *gorm.DB)

Model specify the model you would like to run db operations

// update all user'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 that user's name to `hello`
db.Model(&user).Update("name", "hello")

func Models

func Models() []schema.Model

func Not

func Not(query any, args ...any) (tx *gorm.DB)

Not add NOT conditions

Not works similarly to where, and has the same syntax.

// Find the first user with name not equal to jinzhu
db.Not("name = ?", "jinzhu").First(&user)

func Offset

func Offset(offset int) (tx *gorm.DB)

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

Offset conditions can be cancelled by using `Offset(-1)`.

// select the third user
db.Offset(2).First(&user)
// select the first user by cancelling an earlier chained offset
db.Offset(5).Offset(-1).First(&user)

func Omit

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

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

func Or

func Or(query any, args ...any) (tx *gorm.DB)

Or add OR conditions

Or is used to chain together queries with an OR.

// Find the first user with name equal to jinzhu or john
db.Where("name = ?", "jinzhu").Or("name = ?", "john").First(&user)

func Order

func Order(value any) (tx *gorm.DB)

Order specify order when retrieving records from database

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

func Pluck

func Pluck(column string, dest any) (tx *gorm.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 Preload

func Preload(query string, args ...any) (tx *gorm.DB)

Preload preload associations with given conditions

// get all users, and preload all non-cancelled orders
db.Preload("Orders", "state NOT IN (?)", "cancelled").Find(&users)

func Raw

func Raw(sql string, values ...any) (tx *gorm.DB)

func Register

func Register(obj *gorm.DB)

func Rollback

func Rollback() *gorm.DB

Rollback rollbacks the changes in a transaction

func RollbackTo

func RollbackTo(name string) *gorm.DB

func Row

func Row() *sql.Row

func Rows

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

func Save

func Save(value any) (tx *gorm.DB)

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

func SavePoint

func SavePoint(name string) *gorm.DB

func Scan

func Scan(dest any) (tx *gorm.DB)

Scan scans selected value to the struct dest

func ScanRows

func ScanRows(rows *sql.Rows, dest any) error

func Scopes

func Scopes(funcs ...func(*gorm.DB) *gorm.DB) (tx *gorm.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  *gorm.DB {
    return func  *gorm.DB {
        return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status)
    }
}

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

func Select

func Select(query any, args ...any) (tx *gorm.DB)

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

Use Select when you only want a subset of the fields. By default, GORM will select all fields. Select accepts both string arguments and arrays.

// Select name and age of user using multiple arguments
db.Select("name", "age").Find(&users)
// Select name and age of user using an array
db.Select([]string{"name", "age"}).Find(&users)

func Session

func Session(config *gorm.Session) *gorm.DB

Session create new db session

func Set

func Set(key string, value any) *gorm.DB

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

func SetDefaultCharset

func SetDefaultCharset(charset string)

func SetDefaultCollation

func SetDefaultCollation(collation string)

func SetDefaultEngine

func SetDefaultEngine(engine string)

func SetupJoinTable

func SetupJoinTable(model any, field string, joinTable any) error

SetupJoinTable setup join table schema

func Table

func Table(name string, args ...any) (tx *gorm.DB)

Table specify the table you would like to run db operations

// Get a user
db.Table("users").take(&result)

func Take

func Take(dest any, conds ...any) (tx *gorm.DB)

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

func ToSQL

func ToSQL(queryFn func(tx *gorm.DB) *gorm.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 Transaction

func Transaction(fc func(tx *gorm.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 Unscoped

func Unscoped() (tx *gorm.DB)

func Update

func Update(column string, value any) (tx *gorm.DB)

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

func UpdateColumn

func UpdateColumn(column string, value any) (tx *gorm.DB)

func UpdateColumns

func UpdateColumns(values any) (tx *gorm.DB)

func Updates

func Updates(values any) (tx *gorm.DB)

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

func Use

func Use(plugin gorm.Plugin) error

Use plugin

func UseModel

func UseModel(models ...any)

func Where

func Where(query any, args ...any) (tx *gorm.DB)

Where add conditions

See the docs for details on the various formats that where clauses can take. By default, where clauses chain with AND.

// Find the first user with name jinzhu
db.Where("name = ?", "jinzhu").First(&user)
// Find the first user with name jinzhu and age 20
db.Where(&User{Name: "jinzhu", Age: 20}).First(&user)
// Find the first user with name jinzhu and age not equal to 20
db.Where("name = ?", "jinzhu").Where("age <> ?", "20").First(&user)

func WithContext

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

WithContext change current instance db's context to ctx

Types

This section is empty.

Directories

Path Synopsis
ddl

Jump to

Keyboard shortcuts

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