linq

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2023 License: MIT Imports: 9 Imported by: 0

README

Gorm-linq

licensecode sizeopen issuesclosed issuesgo versionlatest versionGo Report CardCoverage Status

Gorm-linq is a library that provides a LINQ-like interface for the GORM ORM library. It allows you to write more expressive queries and perform common database operations in a more concise and readable way.

Installation

To install Gorm-linq, use go get:

go get github.com/STRockefeller/gorm-linq

Usage

First, import the linq package:

import "github.com/STRockefeller/gorm-linq"

Then, create a new gorm.DB instance and pass it to linq.NewDB along with the struct type you want to work with:

db, err := gorm.Open(mysql.Open("dsn"), &gorm.Config{})
if err != nil {
    // handle error
}

type User struct {
    ID   int
    Name string
}

users := linq.NewDB[User](db)

You can then use gorm-linq methods to query the database:

// Find all users where Name starts with "A"
var result linq.Linq[User]
err := users.Where(User{Name: "A%"}).Find(context.Background(), &result)

// Find the first user where ID is 42
var user User
err := users.Where(User{ID: 42}).Take(context.Background(), &user)

// Update all users where Name starts with "A"
rowsAffected, err := users.Where(User{Name: "A%"}).Updates(context.Background(), User{Name: "NewName"})

// Delete all users where Name starts with "A"
rowsAffected, err := users.Delete(context.Background(), User{Name: "A%"})

// Find all users for update
var result linq.Linq[User]
err := users.FindForUpdate(context.Background(), linq.NoWait(), &result)

You can also chain multiple gorm-linq methods together to build more complex queries:

// Find all users where Name starts with "A" and ID is less than 100, ordered by Name
var result linq.Linq[User]
err := users.Where(User{Name: "A%"}).WhereRaw("ID < ?", 100).Order("Name").Find(context.Background(), &result)

gorm-linq also supports upserts:

// Upsert a single user
err := users.Upsert(context.Background(), []User{{ID: 42, Name: "NewName"}}, clause.OnConflict{
    Columns:   []clause.Column{{Name: "id"}},
    DoUpdates: clause.AssignmentColumns([]string{"name"}),
})

You can also use gorm-linq with GORM's Scope method to apply a function to the underlying gorm.DB instance:

users.Scope(func(db *gorm.DB) *gorm.DB {
    return db.Where("deleted_at IS NULL")
}).Find(context.Background(), &result)

License

Gorm-linq is released under the MIT License. See LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewJoinOn added in v0.2.0

func NewJoinOn(joinType JoinType, joinTable schema.Tabler, on string) joinSql

NewJoinOn returns a closure function that adds a join clause to a SQL query. The closure function takes a pointer to a 'gorm.DB' object as input and returns a pointer to the same object. The join clause is added using the 'Joins' method of the 'gorm.DB' object.

Parameters:

  • joinType: The type of join to be performed (e.g., InnerJoin, LeftJoin, RightJoin).
  • joinTable: The table to be joined with.
  • on: The condition for the join clause.

func NewJoinQuery added in v0.2.0

func NewJoinQuery(qs QueryString) joinSql

NewJoinQuery returns a closure function that can be used to join tables in a database query.

Parameters:

  • qs: A struct of type 'QueryString' that contains the query string and its arguments.

func NoWait

func NoWait() forUpdateOption

func WhereInCondition added in v0.2.0

func WhereInCondition[T any](columnName string) func([]T) QueryString

The `WhereInCondition` function returns a closure that takes a slice of any type `T` as input and returns a `QueryString` struct. The closure constructs a SQL query string with the provided `columnName` and the input items as arguments. If the `columnName` is empty, the function panics with an error message.

Types

type DB

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

DB is a generic struct that wraps around the 'gorm.DB' struct from the 'gorm' package.

func MockDB added in v0.3.0

func MockDB[T any]() (*DB[T], sqlmock.Sqlmock, error)

func NewDB

func NewDB[T any](db *gorm.DB) DB[T]

NewDB creates a new instance of 'DB' by initializing the 'db' field with the provided 'gorm.DB' instance.

func (DB[T]) Clauses added in v0.2.0

func (container DB[T]) Clauses(conditions ...clause.Expression) DB[T]

Clauses updates the container's db field by adding the provided conditions as clauses. It returns the updated container.

func (DB[T]) Count

func (container DB[T]) Count(ctx context.Context) (number int64, err error)

Count is a method that belongs to the DB type in the linq package. It takes a context.Context as input and returns the count of records in the database and any error that occurred during the count operation.

func (DB[T]) Create

func (container DB[T]) Create(ctx context.Context, instances ...T) error

Create creates new records in the database.

func (DB[T]) Delete

func (container DB[T]) Delete(ctx context.Context) (rawsAffected int64, err error)

Delete deletes all rows from the database. It takes a context as input and returns the number of rows affected and an error. This method internally calls DeleteWithCondition with a new instance of the generic type T as the condition.

func (DB[T]) Distinct added in v0.2.0

func (container DB[T]) Distinct(columns []string) DB[T]

func (DB[T]) Error

func (container DB[T]) Error() error

Error returns the error associated with the 'DB' instance.

func (DB[T]) Find

func (container DB[T]) Find(ctx context.Context) (result linq.Linq[T], err error)

func (DB[T]) FindForUpdate

func (container DB[T]) FindForUpdate(ctx context.Context, opts ...forUpdateOption) (result linq.Linq[T], err error)

func (DB[T]) FindWithoutError

func (container DB[T]) FindWithoutError(ctx context.Context) (result linq.Linq[T])

panics if something went wrong

func (DB[T]) ForUpdate

func (container DB[T]) ForUpdate(opts ...forUpdateOption) DB[T]

func (DB[T]) GroupBy added in v0.2.0

func (container DB[T]) GroupBy(columns []string) DB[T]

GroupBy groups the elements in the database container based on the specified columns. It takes a slice of strings representing the columns to group by. It returns the updated database container after grouping the elements based on the specified columns.

func (DB[T]) GroupByHaving added in v0.2.0

func (container DB[T]) GroupByHaving(columns []string, condition QueryString) DB[T]

GroupByHaving groups the elements in the database container based on the specified columns and condition. It takes a slice of strings representing the columns to group by and a QueryString representing the condition. It returns the updated database container after grouping the elements based on the specified columns and condition.

func (DB[T]) Join added in v0.2.0

func (container DB[T]) Join(ctx context.Context, selection QueryString, joinCondition joinSql) ([]map[string]any, error)

Join executes a join condition on the database and returns the result and any error that occurred.

Parameters:

  • ctx: The context for the database operation.
  • selection: A struct that contains the query string and its arguments.
  • joinCondition: A closure function that represents the join condition for the query.

func (DB[T]) LockByRequest added in v0.2.0

func (container DB[T]) LockByRequest(req LockableRequest) DB[T]

LockByRequest locks the container based on the provided LockableRequest. If a lock is required, it calls the ForUpdate method with the parsed lock option. If a lock is not required, it returns the original container.

func (DB[T]) Scope

func (container DB[T]) Scope(f func(*gorm.DB) *gorm.DB) DB[T]

Scope applies a scope to the query by calling the provided function 'f' with the 'db' field as an argument. It returns the modified 'DB' instance.

func (DB[T]) SelectRaw added in v0.1.1

func (container DB[T]) SelectRaw(selectedColumns []string) DB[T]

SelectRaw is a method defined in the DB struct. It takes a string slice parameter selectedColumns and returns the modified DB object.

func (DB[T]) Take

func (container DB[T]) Take(ctx context.Context) (result T, err error)

func (DB[T]) TakeForUpdate

func (container DB[T]) TakeForUpdate(ctx context.Context, opts ...forUpdateOption) (result T, err error)

func (DB[T]) UpdateByRequest added in v0.2.0

func (container DB[T]) UpdateByRequest(ctx context.Context, req UpdateRequest) (rowsAffected int64, err error)

UpdateByRequest updates the database with the provided request. It takes a context and an UpdateRequest object as inputs and returns the number of rows affected and an error.

Parameters:

  • ctx (context.Context): The context in which the update operation is performed.
  • req (UpdateRequest): An object that contains the necessary information for the update operation.

func (DB[T]) UpdateWithMap added in v0.2.0

func (container DB[T]) UpdateWithMap(ctx context.Context, columnValues map[string]any) (rowsAffected int64, err error)

UpdateWithMap updates the database with the provided column values. It takes a context and a map of column values as inputs, and it returns the number of rows affected and an error.

Parameters:

  • ctx (context.Context): The context in which the update operation is performed.
  • columnValues (map[string]any): A map of column names and their corresponding values to be updated in the database.

func (DB[T]) Updates

func (container DB[T]) Updates(ctx context.Context, instance T) (rowsAffected int64, err error)

Updates updates the data in the database with the provided instance. It takes a context and an instance of type T as inputs and returns the number of rows affected and an error.

func (DB[T]) Where

func (container DB[T]) Where(condition T) DB[T]

Where applies a condition to the db field of the container object and returns the modified container.

func (DB[T]) WhereByRequest added in v0.2.0

func (container DB[T]) WhereByRequest(req QueryRequest) DB[T]

WhereByRequest applies a series of WhereRaw queries to the container's db field based on the conditions specified in the QueryRequest.

Parameters:

  • req: A QueryRequest object that contains a function called Where which returns an array of QueryString objects. Each QueryString object represents a condition to be applied to the container's db field.

func (DB[T]) WhereRaw

func (container DB[T]) WhereRaw(qs QueryString) DB[T]

WhereRaw applies a query string to the db field of the container object.

type JoinType added in v0.2.0

type JoinType string
const (
	Unspecified JoinType = ""
	LeftJoin    JoinType = "LEFT JOIN"
	RightJoin   JoinType = "RIGHT JOIN"
	InnerJoin   JoinType = "INNER JOIN"
)

type LockOption added in v0.2.0

type LockOption int
const (
	OptionWait LockOption = iota
	OptionNoWait
)

type LockableRequest added in v0.2.0

type LockableRequest interface {
	// returns true if you want to lock the query data
	Lock() bool
	LockOption() LockOption
}

type QueryRequest added in v0.2.0

type QueryRequest interface {
	Where() []QueryString
}

Contains a function called Where which returns an array of QueryString objects. Each QueryString object represents a condition to be applied to the container's db field.

type QueryString added in v0.2.0

type QueryString struct {
	Query string
	Args  []any
}

QueryString is a struct that represents a SQL query string and its arguments.

func NewQueryString added in v0.2.0

func NewQueryString(sql string, vars ...any) QueryString

type UpdateRequest added in v0.2.0

type UpdateRequest interface {
	Update() map[string]any
}

Jump to

Keyboard shortcuts

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