lorm

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2025 License: MIT Imports: 17 Imported by: 0

README

LORM - Lightweight ORM for Go

中文

LORM is a lightweight ORM (Object-Relational Mapping) library for Go. It provides a simple and efficient way to interact with databases while maintaining high performance.

Features

  • Simple and intuitive API design
  • Support for transactions
  • Code generation tools for automatic model creation
  • Support for multiple database drivers (MySQL, PostgreSQL, SQLite, etc.)
  • Query builder with type safety
  • Connection pooling and management
  • Structured logging

Installation

go get github.com/yvvlee/lorm

Quick Start

1. Initialize Engine
engine, err := lorm.NewEngine("mysql", "user:password@tcp(localhost:3306)/dbname")
if err != nil {
    log.Fatal(err)
}
defer engine.Close()
2. Define Models
type User struct {
    lorm.UnimplementedTable
    ID        int64  `lorm:"id,primary_key,auto_increment"`
    Name      string `lorm:"name"`
    Email     string `lorm:"email"`
    CreatedAt time.Time `lorm:"created_at,created"`
    UpdatedAt time.Time `lorm:"updated_at,updated"`
}
3. Generate Code with lormgen

Before performing any database operations, you need to generate code using the lormgen tool:

# Install lormgen
go install github.com/yvvlee/lorm/cmd/lormgen@latest

# Generate code for your models
lormgen ./...

This will generate files with the _lorm_gen.go suffix that contain the necessary methods for database operations.

4. CRUD Operations
Insert
// Insert single model
user := &User{
    Name:  "John Doe",
    Email: "john@example.com",
}
rowsAffected, err := lorm.Insert[*User](engine).AddModel(user).Exec(ctx)

// Insert multiple models
users := []*User{
    {Name: "John Doe", Email: "john@example.com"},
    {Name: "Jane Doe", Email: "jane@example.com"},
}
rowsAffected, err := lorm.Insert[*User](engine).AddModels(users...).Exec(ctx)
Query
// Get by ID
user, err := lorm.Query[*User](engine).
    Where(builder.Eq{u.Fields().ID(): 1}).
    Get(ctx)

// Query with conditions
users, err := lorm.Query[*User](engine).
    Where(builder.Eq{u.Fields().Name(): "John"}).
    Find(ctx)
Update
var u User
rowsAffected, err := lorm.Update(engine).
    Table(u.TableName()).
    ID(1).
    SetMap(map[string]any{
        u.Fields().Name(): "Jane Doe",
    }).
    Exec(ctx)
Delete
var u User
rowsAffected, err := lorm.Delete(engine).
    From(u.TableName()).
    Where(builder.Eq{u.Fields().ID(): 1}).
    Exec(ctx)

Note: These operations require the code generation step to be completed first.

lorm.Repository implements common single-table CRUD operations. You can embed lorm.Repository[*User] in UserRepositoryImpl, and then expose these common methods as needed through the UserRepository interface:

type UserRepository interface {
	// The following methods are common methods that lorm.Repository[*User] has implemented, expose as needed
	Get(ctx context.Context, id int64) (*User, error)
	GetByField(ctx context.Context, field string, value any) (*User, error)
	Lock(ctx context.Context, id int64) (*User, error)
	LockByField(ctx context.Context, field string, value any) (*User, error)
	Exist(ctx context.Context, id int64) (bool, error)
	ExistByField(ctx context.Context, field string, value any) (bool, error)
	Update(ctx context.Context, user *User) (rowsAffected int64, err error)
	UpdateMap(ctx context.Context, id int64, data map[string]any) (rowsAffected int64, err error)
	Insert(ctx context.Context, user *User) (rowsAffected int64, err error)
	InsertAll(ctx context.Context, users []*User) (rowsAffected int64, err error)
	Delete(ctx context.Context, id int64) (rowsAffected int64, err error)
	DeleteByField(ctx context.Context, field string, value any) (rowsAffected int64, err error)
    
	// You can also add custom methods that need to be implemented in UserRepositoryImpl
	PageGmailUsers(ctx context.Context, pageNum, pageSize uint64) ([]*User,uint64, error)
}

var _ UserRepository = (*UserRepositoryImpl).(nil)

type UserRepositoryImpl struct {
	lorm.Repository[*User]
}

func NewUserRepository(engine *lorm.Engine) *UserRepositoryImpl {
	return &UserRepositoryImpl{
		Repository: lorm.NewRepository[*User](engine),
	}
}

func (r *UserRepositoryImpl) PageGmailUsers(ctx context.Context, pageNum, pageSize uint64) ([]*User,uint64, error)  {
	var u User
	return lorm.Query[*User](r.Engine).
		From(u.TableName()).
		Where(builder.Like(u.Fields().Email(), "%@gmail.com")).
		OrderBy(r.Fields().ID()+" desc").
		Page(pageNum, pageSize)
}

Transaction Support

Through the TX method to start a transaction, the incoming ctx parameter of the callback function will carry the transaction session. All database operations in the callback function use this ctx, and lorm will automatically use the transaction session carried by this ctx. If the callback function returns an error, the transaction will be rolled back, otherwise the transaction will be automatically committed.

err := engine.TX(context.Background(), func(ctx context.Context) error {
    user1 := &User{Name: "User 1"}
    _, err := lorm.Insert[*User](engine).AddModel(user1).Exec(ctx)
    if err != nil {
        return err
    }
    
    user2 := &User{Name: "User 2"}
    _, err = lorm.Insert[*User](engine).AddModel(user2).Exec(ctx)
    if err != nil {
        return err
    }
    
    return nil
})

Configuration Options

LORM supports various configuration options:

engine, err := lorm.NewEngine("mysql", "user:password@tcp(localhost:3306)/dbname",
    lorm.WithPlaceholderFormat(builder.Dollar), // Set SQL placeholder, default is "?"
    lorm.WithEscaper(names.NewQuoter('"', '"')), // Set SQL escaper for table and column names, default is `` (e.g., select `id`,`desc`,`name` from `table`)
    lorm.WithMaxIdleConns(10), // Set maximum number of idle connections
    lorm.WithMaxOpenConns(100), // Set maximum number of open connections
    lorm.WithConnMaxLifetime(time.Hour), // Set maximum connection lifetime
    lorm.WithLogger(customLogger), // Set custom logger
)

lormgen Code Generator Usage

lormgen is Lorm's code generator for automatically generating database table structure related code.

Usage
lormgen [flags] <directory|file>...

It scans structures that embed lorm.UnimplementedTable and lorm.UnimplementedModel, and generates the necessary methods for using lorm.

Parameters
  • --field-mapper: Field name mapper, options: snake (snake_case), camel (camelCase), same (keep unchanged), default: snake
  • --table-mapper: Table name mapper, options: snake (snake_case), camel (camelCase), same (keep unchanged), default: snake
  • --table-prefix: Database table name prefix, default is empty
  • --table-suffix: Database table name suffix, default is empty
  • --tag-key: Field tag key name, default: lorm
  • --file-suffix: Generated file suffix, default: _lorm_gen
  • --ignore: Glob pattern for files to ignore, can be specified multiple times
Usage Examples
# Generate code for all Go files in current directory
lormgen .

# Recursively generate code for specified directory and subdirectories
lormgen ./models/...

# Generate code with custom parameters
lormgen --table-prefix=t_ --table-suffix=_tab --field-mapper=camel ./models

# Ignore specific files
lormgen --ignore="*_temp.go" --ignore="*_old.go" ./models
Model Definition

Define a database table model:

type User struct {
    lorm.UnimplementedTable 
    ID                      int `lorm:"primary_key,auto_increment"`
    Name                    string
    Age                     int
    CreatedAt               time.Time `lorm:"created"`
    UpdatedAt               time.Time `lorm:"updated"`
}

After running lormgen, the following code will be generated:

// TableName returns the table name
func (m *User) TableName() string {
    return "user"
}

// Fields returns User field accessor
func (m *User) Fields() *User_Fields {}

type User_Fields struct {
    alias string
}

func (f *User_Fields) WithAlias(alias string) *User_Fields {}
func (f *User_Fields) ID() string {}
// ...other field accessor methods

// All returns all field names
func (f *User_Fields) All() []string {}

By default, table names use snake_case naming of the model. You can modify the table name mapping rules by adding the --table-mapper parameter to lormgen, or explicitly specify it by adding a tag to the embedded lorm.UnimplementedTable.

For example:

type User struct {
    lorm.UnimplementedTable `lorm:"users"`
}
// This will generate the following code:
func (m *User) TableName() string {
    return "users"
}

By default, database field names use snake_case naming of the model. You can modify the field name mapping rules by adding the --field-mapper parameter to lormgen, or explicitly specify it by adding a tag to the field.

For example:

type User struct {
    lorm.UnimplementedTable
    Name string `lorm:"username"`
}
// This will generate the following code:
type User_Fields struct {
    alias string
}

func (f *User_Fields) Name() string {
    if f.alias == "" {
        return "username"
    }
    return f.alias + ".username"
}

Supports struct embedding:

type Metadata struct {
	ID int64
	Name string
}

type User struct {
    lorm.UnimplementedTable
	
    Metadata
    Age int
}

// This will generate the following code:
type User_Fields struct {
    alias string
}

func (f *User_Fields) ID() string {
    if f.alias == "" {
        return "id"
    }
    return f.alias + ".id"
}
func (f *User_Fields) Name() string {
    if f.alias == "" {
        return "name"
    }
    return f.alias + ".name"
}
func (f *User_Fields) Age() string {
    if f.alias == "" {
        return "age"
    }
    return f.alias + ".age"
}

Add a tag to the embedded struct to use as a prefix for nested fields:

type Metadata struct {
	ID int64
	Name string
}

type User struct {
    lorm.UnimplementedTable
	
    Metadata `lorm:"user_"`
    Age int
}

// This will generate the following code:
type User_Fields struct {
    alias string
}

func (f *User_Fields) ID() string {
    if f.alias == "" {
        return "user_id"
    }
    return f.alias + ".user_id"
}
func (f *User_Fields) Name() string {
    if f.alias == "" {
        return "user_name"
    }
    return f.alias + ".user_name"
}
func (f *User_Fields) Age() string {
    if f.alias == "" {
        return "age"
    }
    return f.alias + ".age"
}

Built-in tags:

lorm supports the following built-in tags to mark special field attributes:

  • primary_key: Mark field as primary key
  • auto_increment: Mark field as auto-increment
  • json: Mark field to be stored in JSON format
  • created: Mark field as creation time, automatically set to current time on insert
  • updated: Mark field as update time, automatically set to current time on insert and update
  • version: Mark field as optimistic lock version number, automatically incremented on update

Usage example:

type User struct {
    lorm.UnimplementedTable
    ID        int64     `lorm:"primary_key;auto_increment"`
    Name      string
    Profile   *Profile  `lorm:"json"`
    CreatedAt time.Time `lorm:"created"`
    UpdatedAt time.Time `lorm:"updated"`
    Version   int       `lorm:"version"`
}

type Profile struct {
    Avatar string
    Bio    string
}

When database query results need to be mapped to a custom model rather than a database table model, you just need to embed lorm.UnimplementedModel. It behaves almost identically to lorm.UnimplementedTable, but it won't generate a TableName() method, so you need to manually specify the table name when performing database operations with custom models.

type UserRole struct {
	lorm.UnimplementedModel
	UserID int64
	UserName string
	RoleID int64
	RoleName string
}

func main() {
    engine, err := lorm.NewEngine("mysql", "user:password@tcp(localhost:3306)/dbname")
    if err != nil {
        log.Fatal(err)
    }
    defer engine.Close()
    ctx := context.Background()
    models,err := Query[*UserRole](engine).
        Select("u.id user_id","u.name user_name","r.id role_id","r.name role_name").
        From("user").
        Alias("u").
        InnerJoin("role as r on u.role_id=r.id").
        Find(ctx)
	// SQL: select u.id user_id,u.name user_name,r.id role_id,r.name role_name
	//      from user u
	//      inner join role as r on u.role_id=r.id
	
}

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var FlagTagMap = map[FieldFlag]string{
	FlagPrimaryKey:    "primary_key",
	FlagAutoIncrement: "auto_increment",
	FlagJson:          "json",
	FlagCreated:       "created",
	FlagUpdated:       "updated",
	FlagVersion:       "version",
}

Functions

func Escaper

func Escaper(driverName string) names.Escaper

func ModelToInsertData

func ModelToInsertData[T Model](model T, ignoreFields ...string) (columns []string, values []any)

func ModelsToInsertData

func ModelsToInsertData[T Model](models []T, ignoreFields ...string) (columns []string, values [][]any)

func Placeholder

func Placeholder(driverName string) builder.PlaceholderFormat

func ScanCol

func ScanCol[T any](row *sql.Rows, t T) error

func ScanCols

func ScanCols[T any](rows *sql.Rows, v *[]T) error

func ScanModel

func ScanModel[T Model](row *sql.Rows, m T) error

func ScanModels

func ScanModels[T Model](rows *sql.Rows, models *[]T) error

Types

type Config

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

type DBProxy

type DBProxy interface {
	Execer
	Querier
}

type DeleteStmt

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

func Delete

func Delete(engine *Engine) *DeleteStmt

func (*DeleteStmt) Exec

func (s *DeleteStmt) Exec(ctx context.Context) (rowsAffected int64, err error)

func (*DeleteStmt) From

func (s *DeleteStmt) From(from string) *DeleteStmt

func (*DeleteStmt) ID

func (s *DeleteStmt) ID(id any) *DeleteStmt

func (*DeleteStmt) Limit

func (s *DeleteStmt) Limit(limit uint64) *DeleteStmt

Limit sets a LIMIT clause on the query.

func (*DeleteStmt) Offset

func (s *DeleteStmt) Offset(offset uint64) *DeleteStmt

Offset sets a OFFSET clause on the query.

func (*DeleteStmt) OrderBy

func (s *DeleteStmt) OrderBy(orderBys ...string) *DeleteStmt

OrderBy adds ORDER BY expressions to the query.

func (*DeleteStmt) Prefix

func (s *DeleteStmt) Prefix(sql string, args ...any) *DeleteStmt

Prefix adds an expression to the beginning of the query

func (*DeleteStmt) PrefixExpr

func (s *DeleteStmt) PrefixExpr(expr builder.Sqlizer) *DeleteStmt

PrefixExpr adds an expression to the very beginning of the query

func (*DeleteStmt) Suffix

func (s *DeleteStmt) Suffix(sql string, args ...any) *DeleteStmt

Suffix adds an expression to the end of the query

func (*DeleteStmt) SuffixExpr

func (s *DeleteStmt) SuffixExpr(expr builder.Sqlizer) *DeleteStmt

SuffixExpr adds an expression to the end of the query

func (*DeleteStmt) Where

func (s *DeleteStmt) Where(pred any, args ...any) *DeleteStmt

Where adds WHERE expressions to the query.

See SelectBuilder.Where for more information.

type Engine

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

func NewEngine

func NewEngine(driverName, dsn string, option ...Option) (*Engine, error)

func (*Engine) Close

func (e *Engine) Close() error

func (*Engine) DriverName

func (e *Engine) DriverName() string

func (*Engine) Escaper

func (e *Engine) Escaper() names.Escaper

func (*Engine) Exec

func (e *Engine) Exec(ctx context.Context, query string, args ...any) (result sql.Result, err error)

func (*Engine) Exist

func (e *Engine) Exist(ctx context.Context, query string, args ...any) (exist bool, err error)

func (*Engine) Placeholder

func (e *Engine) Placeholder() builder.PlaceholderFormat

func (*Engine) Query

func (e *Engine) Query(ctx context.Context, query string, args ...any) (rows *sql.Rows, err error)

func (*Engine) SupportsLastInsertId

func (e *Engine) SupportsLastInsertId() bool

SupportsLastInsertId returns true if the database driver supports LastInsertId

func (*Engine) SupportsReturning

func (e *Engine) SupportsReturning() bool

SupportsReturning returns true if the database driver supports RETURNING clause

func (*Engine) TX

func (e *Engine) TX(ctx context.Context, fn func(context.Context) error) error

type Execer

type Execer interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}

type FieldDescriptor

type FieldDescriptor struct {
	Name     string
	FullName string
	DBField  string
	Type     string
	Flag     FieldFlag
}

FieldDescriptor stores field information

type FieldFlag

type FieldFlag uint8
const (
	FlagPrimaryKey FieldFlag = 1 << iota
	FlagAutoIncrement
	FlagJson
	FlagCreated
	FlagUpdated
	FlagVersion
)

func (FieldFlag) HasFlag

func (f FieldFlag) HasFlag(flag FieldFlag) bool

type FileDescriptor

type FileDescriptor struct {
	Path            string
	LormImportAlias string
	Package         string
	Imports         []*Import
	Structs         []*ModelDescriptor
}

func (*FileDescriptor) JsonMarshal

func (d *FileDescriptor) JsonMarshal() string

func (*FileDescriptor) RawVarPrefix

func (d *FileDescriptor) RawVarPrefix() string

type Import

type Import struct {
	Path  string
	Alias string
}

type InsertStmt

type InsertStmt[T Table] struct {
	// contains filtered or unexported fields
}

func Insert

func Insert[T Table](engine *Engine) *InsertStmt[T]

func (*InsertStmt[T]) AddModel

func (s *InsertStmt[T]) AddModel(model T) *InsertStmt[T]

func (*InsertStmt[T]) AddModels

func (s *InsertStmt[T]) AddModels(models ...T) *InsertStmt[T]

func (*InsertStmt[T]) Columns

func (s *InsertStmt[T]) Columns(columns ...string) *InsertStmt[T]

func (*InsertStmt[T]) Exec

func (s *InsertStmt[T]) Exec(ctx context.Context) (rowsAffected int64, err error)

func (*InsertStmt[T]) Ignore

func (s *InsertStmt[T]) Ignore() *InsertStmt[T]

func (*InsertStmt[T]) Prefix

func (s *InsertStmt[T]) Prefix(sql string, args ...any) *InsertStmt[T]

func (*InsertStmt[T]) PrefixExpr

func (s *InsertStmt[T]) PrefixExpr(expr builder.Sqlizer) *InsertStmt[T]

func (*InsertStmt[T]) Suffix

func (s *InsertStmt[T]) Suffix(sql string, args ...any) *InsertStmt[T]

func (*InsertStmt[T]) SuffixExpr

func (s *InsertStmt[T]) SuffixExpr(expr builder.Sqlizer) *InsertStmt[T]

func (*InsertStmt[T]) Values

func (s *InsertStmt[T]) Values(values ...any) *InsertStmt[T]

type JSONFieldWrapper

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

func NewJSONFieldWrapper

func NewJSONFieldWrapper(v any) *JSONFieldWrapper

func (*JSONFieldWrapper) MarshalJSON

func (s *JSONFieldWrapper) MarshalJSON() ([]byte, error)

func (*JSONFieldWrapper) Scan

func (s *JSONFieldWrapper) Scan(src any) error

func (*JSONFieldWrapper) String

func (s *JSONFieldWrapper) String() string

func (*JSONFieldWrapper) UnmarshalJSON

func (s *JSONFieldWrapper) UnmarshalJSON(data []byte) error

func (*JSONFieldWrapper) Value

func (s *JSONFieldWrapper) Value() (driver.Value, error)

type Logger

type Logger interface {
	DebugContext(ctx context.Context, msg string, args ...any)
	InfoContext(ctx context.Context, msg string, args ...any)
	WarnContext(ctx context.Context, msg string, args ...any)
	ErrorContext(ctx context.Context, msg string, args ...any)
}

type Model

type Model interface {

	// New create a new model instance
	New() Model
	// LormFieldMap return field map, key is db field name, value is field value pointer
	LormFieldMap() map[string]any
	// LormModelDescriptor return db fields of this Model
	LormModelDescriptor() *ModelDescriptor
	// contains filtered or unexported methods
}

type ModelDescriptor

type ModelDescriptor struct {
	Name      string
	TableName string
	Fields    []*FieldDescriptor
}

ModelDescriptor stores struct information

func (*ModelDescriptor) AllFields

func (m *ModelDescriptor) AllFields() []string

func (*ModelDescriptor) FlagFields

func (m *ModelDescriptor) FlagFields(flag FieldFlag) []string

type Option

type Option func(*Config)

func WithConnMaxIdleTime

func WithConnMaxIdleTime(connMaxIdleTime time.Duration) Option

WithConnMaxIdleTime sets the maximum idle time of a connection

func WithConnMaxLifetime

func WithConnMaxLifetime(connMaxLifetime time.Duration) Option

WithConnMaxLifetime sets the maximum lifetime of a connection

func WithEscaper

func WithEscaper(escaper names.Escaper) Option

WithEscaper sets the escaper

func WithLogger

func WithLogger(logger Logger) Option

WithLogger sets the logger

func WithMaxIdleConns

func WithMaxIdleConns(maxIdleConns int) Option

WithMaxIdleConns sets the maximum number of idle connections

func WithMaxOpenConns

func WithMaxOpenConns(maxOpenConns int) Option

WithMaxOpenConns sets the maximum number of open connections

func WithPlaceholderFormat

func WithPlaceholderFormat(format builder.PlaceholderFormat) Option

WithPlaceholderFormat sets the placeholder format

type Querier

type Querier interface {
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
}

type QueryColStmt

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

func QueryCol

func QueryCol[T any](engine *Engine) *QueryColStmt[T]

func (*QueryColStmt[T]) AddColumn

func (s *QueryColStmt[T]) AddColumn(column any, args ...any) *QueryColStmt[T]

AddColumn adds a result column to the query. Unlike Select, AddColumn accepts args which will be bound to placeholders in the columns string, for example:

AddColumn("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3)

func (*QueryColStmt[T]) Column

func (s *QueryColStmt[T]) Column(column any, args ...any) *QueryColStmt[T]

Column adds a result column to the query. Unlike Select, Column accepts args which will be bound to placeholders in the columns string, for example:

AddColumn("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3)

func (*QueryColStmt[T]) CrossJoin

func (s *QueryColStmt[T]) CrossJoin(join string, rest ...any) *QueryColStmt[T]

CrossJoin adds a CROSS JOIN clause to the query.

func (*QueryColStmt[T]) Distinct

func (s *QueryColStmt[T]) Distinct() *QueryColStmt[T]

Distinct adds a DISTINCT clause to the query.

func (*QueryColStmt[T]) Find

func (s *QueryColStmt[T]) Find(ctx context.Context) ([]T, error)

func (*QueryColStmt[T]) From

func (s *QueryColStmt[T]) From(from string) *QueryColStmt[T]

From sets the FROM clause of the query.

func (*QueryColStmt[T]) FromSelect

func (s *QueryColStmt[T]) FromSelect(from *builder.SelectBuilder, alias string) *QueryColStmt[T]

FromSelect sets a subquery into the FROM clause of the query.

func (*QueryColStmt[T]) Get

func (s *QueryColStmt[T]) Get(ctx context.Context) (T, bool, error)

func (*QueryColStmt[T]) GroupBy

func (s *QueryColStmt[T]) GroupBy(groupBys ...string) *QueryColStmt[T]

GroupBy adds GROUP BY expressions to the query.

func (*QueryColStmt[T]) Having

func (s *QueryColStmt[T]) Having(pred any, rest ...any) *QueryColStmt[T]

Having adds an expression to the HAVING clause of the query.

See Where.

func (*QueryColStmt[T]) InnerJoin

func (s *QueryColStmt[T]) InnerJoin(join string, rest ...any) *QueryColStmt[T]

InnerJoin adds a INNER JOIN clause to the query.

func (*QueryColStmt[T]) Join

func (s *QueryColStmt[T]) Join(join string, rest ...any) *QueryColStmt[T]

Join adds a JOIN clause to the query.

func (*QueryColStmt[T]) JoinClause

func (s *QueryColStmt[T]) JoinClause(pred any, args ...any) *QueryColStmt[T]

JoinClause adds a join clause to the query.

func (*QueryColStmt[T]) LeftJoin

func (s *QueryColStmt[T]) LeftJoin(join string, rest ...any) *QueryColStmt[T]

LeftJoin adds a LEFT JOIN clause to the query.

func (*QueryColStmt[T]) Limit

func (s *QueryColStmt[T]) Limit(limit uint64) *QueryColStmt[T]

Limit sets a LIMIT clause on the query.

func (*QueryColStmt[T]) Offset

func (s *QueryColStmt[T]) Offset(offset uint64) *QueryColStmt[T]

Offset sets a OFFSET clause on the query.

func (*QueryColStmt[T]) Options

func (s *QueryColStmt[T]) Options(options ...string) *QueryColStmt[T]

Options adds select option to the query

func (*QueryColStmt[T]) OrderBy

func (s *QueryColStmt[T]) OrderBy(orderBys ...string) *QueryColStmt[T]

OrderBy adds ORDER BY expressions to the query.

func (*QueryColStmt[T]) OrderByClause

func (s *QueryColStmt[T]) OrderByClause(pred any, args ...any) *QueryColStmt[T]

OrderByClause adds ORDER BY clause to the query.

func (*QueryColStmt[T]) Prefix

func (s *QueryColStmt[T]) Prefix(sql string, args ...any) *QueryColStmt[T]

Prefix adds an expression to the beginning of the query

func (*QueryColStmt[T]) PrefixExpr

func (s *QueryColStmt[T]) PrefixExpr(expr builder.Sqlizer) *QueryColStmt[T]

PrefixExpr adds an expression to the very beginning of the query

func (*QueryColStmt[T]) RemoveColumns

func (s *QueryColStmt[T]) RemoveColumns() *QueryColStmt[T]

RemoveColumns remove all columns from query. Must add a new column with Column or Select methods, otherwise return a error.

func (*QueryColStmt[T]) RemoveLimit

func (s *QueryColStmt[T]) RemoveLimit() *QueryColStmt[T]

func (*QueryColStmt[T]) RemoveOffset

func (s *QueryColStmt[T]) RemoveOffset() *QueryColStmt[T]

RemoveOffset removes OFFSET clause.

func (*QueryColStmt[T]) RightJoin

func (s *QueryColStmt[T]) RightJoin(join string, rest ...any) *QueryColStmt[T]

RightJoin adds a RIGHT JOIN clause to the query.

func (*QueryColStmt[T]) Select

func (s *QueryColStmt[T]) Select(columns ...string) *QueryColStmt[T]

Select set result columns to the query.

func (*QueryColStmt[T]) Suffix

func (s *QueryColStmt[T]) Suffix(sql string, args ...any) *QueryColStmt[T]

Suffix adds an expression to the end of the query

func (*QueryColStmt[T]) SuffixExpr

func (s *QueryColStmt[T]) SuffixExpr(expr builder.Sqlizer) *QueryColStmt[T]

SuffixExpr adds an expression to the end of the query

func (*QueryColStmt[T]) Where

func (s *QueryColStmt[T]) Where(pred any, args ...any) *QueryColStmt[T]

Where adds an expression to the WHERE clause of the query.

Expressions are ANDed together in the generated SQL.

Where accepts several types for its pred argument:

nil OR "" - ignored.

string - SQL expression. If the expression has SQL placeholders then a set of arguments must be passed as well, one for each placeholder.

map[string]any OR Eq - map of SQL expressions to values. Each key is transformed into an expression like "<key> = ?", with the corresponding value bound to the placeholder. If the value is nil, the expression will be "<key> IS NULL". If the value is an array or slice, the expression will be "<key> IN (?,?,...)", with one placeholder for each item in the value. These expressions are ANDed together.

Where will panic if pred isn't any of the above types.

type QueryModelStmt

type QueryModelStmt[T Model] struct {
	// contains filtered or unexported fields
}

func Query

func Query[T Model](engine *Engine) *QueryModelStmt[T]

func (*QueryModelStmt[T]) AddColumn

func (s *QueryModelStmt[T]) AddColumn(column any, args ...any) *QueryModelStmt[T]

AddColumn adds a result column to the query. Unlike Select, AddColumn accepts args which will be bound to placeholders in the columns string, for example:

AddColumn("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3)

func (*QueryModelStmt[T]) Column

func (s *QueryModelStmt[T]) Column(column any, args ...any) *QueryModelStmt[T]

Column adds a result column to the query. Unlike Select, Column accepts args which will be bound to placeholders in the columns string, for example:

AddColumn("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3)

func (*QueryModelStmt[T]) CrossJoin

func (s *QueryModelStmt[T]) CrossJoin(join string, rest ...any) *QueryModelStmt[T]

CrossJoin adds a CROSS JOIN clause to the query.

func (*QueryModelStmt[T]) Distinct

func (s *QueryModelStmt[T]) Distinct() *QueryModelStmt[T]

Distinct adds a DISTINCT clause to the query.

func (*QueryModelStmt[T]) Exist

func (s *QueryModelStmt[T]) Exist(ctx context.Context) (bool, error)

func (*QueryModelStmt[T]) Find

func (s *QueryModelStmt[T]) Find(ctx context.Context) ([]T, error)

func (*QueryModelStmt[T]) From

func (s *QueryModelStmt[T]) From(from string) *QueryModelStmt[T]

From sets the FROM clause of the query.

func (*QueryModelStmt[T]) FromSelect

func (s *QueryModelStmt[T]) FromSelect(from *builder.SelectBuilder, alias string) *QueryModelStmt[T]

FromSelect sets a subquery into the FROM clause of the query.

func (*QueryModelStmt[T]) Get

func (s *QueryModelStmt[T]) Get(ctx context.Context) (T, error)

func (*QueryModelStmt[T]) GroupBy

func (s *QueryModelStmt[T]) GroupBy(groupBys ...string) *QueryModelStmt[T]

GroupBy adds GROUP BY expressions to the query.

func (*QueryModelStmt[T]) Having

func (s *QueryModelStmt[T]) Having(pred any, rest ...any) *QueryModelStmt[T]

Having adds an expression to the HAVING clause of the query.

See Where.

func (*QueryModelStmt[T]) ID

func (s *QueryModelStmt[T]) ID(id any) *QueryModelStmt[T]

func (*QueryModelStmt[T]) InnerJoin

func (s *QueryModelStmt[T]) InnerJoin(join string, rest ...any) *QueryModelStmt[T]

InnerJoin adds a INNER JOIN clause to the query.

func (*QueryModelStmt[T]) Join

func (s *QueryModelStmt[T]) Join(join string, rest ...any) *QueryModelStmt[T]

Join adds a JOIN clause to the query.

func (*QueryModelStmt[T]) JoinClause

func (s *QueryModelStmt[T]) JoinClause(pred any, args ...any) *QueryModelStmt[T]

JoinClause adds a join clause to the query.

func (*QueryModelStmt[T]) LeftJoin

func (s *QueryModelStmt[T]) LeftJoin(join string, rest ...any) *QueryModelStmt[T]

LeftJoin adds a LEFT JOIN clause to the query.

func (*QueryModelStmt[T]) Limit

func (s *QueryModelStmt[T]) Limit(limit uint64) *QueryModelStmt[T]

Limit sets a LIMIT clause on the query.

func (*QueryModelStmt[T]) Offset

func (s *QueryModelStmt[T]) Offset(offset uint64) *QueryModelStmt[T]

Offset sets a OFFSET clause on the query.

func (*QueryModelStmt[T]) Options

func (s *QueryModelStmt[T]) Options(options ...string) *QueryModelStmt[T]

Options adds select option to the query

func (*QueryModelStmt[T]) OrderBy

func (s *QueryModelStmt[T]) OrderBy(orderBys ...string) *QueryModelStmt[T]

OrderBy adds ORDER BY expressions to the query.

func (*QueryModelStmt[T]) OrderByClause

func (s *QueryModelStmt[T]) OrderByClause(pred any, args ...any) *QueryModelStmt[T]

OrderByClause adds ORDER BY clause to the query.

func (*QueryModelStmt[T]) Page

func (s *QueryModelStmt[T]) Page(ctx context.Context, page, size uint64) ([]T, uint64, error)

func (*QueryModelStmt[T]) Prefix

func (s *QueryModelStmt[T]) Prefix(sql string, args ...any) *QueryModelStmt[T]

Prefix adds an expression to the beginning of the query

func (*QueryModelStmt[T]) PrefixExpr

func (s *QueryModelStmt[T]) PrefixExpr(expr builder.Sqlizer) *QueryModelStmt[T]

PrefixExpr adds an expression to the very beginning of the query

func (*QueryModelStmt[T]) RemoveColumns

func (s *QueryModelStmt[T]) RemoveColumns() *QueryModelStmt[T]

RemoveColumns remove all columns from query. Must add a new column with Column or Select methods, otherwise return a error.

func (*QueryModelStmt[T]) RemoveLimit

func (s *QueryModelStmt[T]) RemoveLimit() *QueryModelStmt[T]

func (*QueryModelStmt[T]) RemoveOffset

func (s *QueryModelStmt[T]) RemoveOffset() *QueryModelStmt[T]

RemoveOffset removes OFFSET clause.

func (*QueryModelStmt[T]) RightJoin

func (s *QueryModelStmt[T]) RightJoin(join string, rest ...any) *QueryModelStmt[T]

RightJoin adds a RIGHT JOIN clause to the query.

func (*QueryModelStmt[T]) Select

func (s *QueryModelStmt[T]) Select(columns ...string) *QueryModelStmt[T]

Select set result columns to the query.

func (*QueryModelStmt[T]) Suffix

func (s *QueryModelStmt[T]) Suffix(sql string, args ...any) *QueryModelStmt[T]

Suffix adds an expression to the end of the query

func (*QueryModelStmt[T]) SuffixExpr

func (s *QueryModelStmt[T]) SuffixExpr(expr builder.Sqlizer) *QueryModelStmt[T]

SuffixExpr adds an expression to the end of the query

func (*QueryModelStmt[T]) Where

func (s *QueryModelStmt[T]) Where(pred any, args ...any) *QueryModelStmt[T]

Where adds an expression to the WHERE clause of the query.

Expressions are ANDed together in the generated SQL.

Where accepts several types for its pred argument:

nil OR "" - ignored.

string - SQL expression. If the expression has SQL placeholders then a set of arguments must be passed as well, one for each placeholder.

map[string]any OR Eq - map of SQL expressions to values. Each key is transformed into an expression like "<key> = ?", with the corresponding value bound to the placeholder. If the value is nil, the expression will be "<key> IS NULL". If the value is an array or slice, the expression will be "<key> IN (?,?,...)", with one placeholder for each item in the value. These expressions are ANDed together.

Where will panic if pred isn't any of the above types.

type Repository

type Repository[T Table] struct {
	Engine *Engine
}

func NewRepository

func NewRepository[T Table](engine *Engine) *Repository[T]

func (*Repository[T]) Delete

func (r *Repository[T]) Delete(ctx context.Context, id int64) (rowsAffected int64, err error)

func (*Repository[T]) DeleteByField

func (r *Repository[T]) DeleteByField(ctx context.Context, field string, value any) (rowsAffected int64, err error)

func (*Repository[T]) Exist

func (r *Repository[T]) Exist(ctx context.Context, id int64) (bool, error)

func (*Repository[T]) ExistByField

func (r *Repository[T]) ExistByField(ctx context.Context, field string, value any) (bool, error)

func (*Repository[T]) Get

func (r *Repository[T]) Get(ctx context.Context, id int64) (T, error)

func (*Repository[T]) GetByField

func (r *Repository[T]) GetByField(ctx context.Context, field string, value any) (T, error)

func (*Repository[T]) Insert

func (r *Repository[T]) Insert(ctx context.Context, model T) (rowsAffected int64, err error)

func (*Repository[T]) InsertAll

func (r *Repository[T]) InsertAll(ctx context.Context, models []T) (rowsAffected int64, err error)

func (*Repository[T]) InsertIgnore

func (r *Repository[T]) InsertIgnore(ctx context.Context, model T) (rowsAffected int64, err error)

func (*Repository[T]) InsertIgnoreAll

func (r *Repository[T]) InsertIgnoreAll(ctx context.Context, models []T) (rowsAffected int64, err error)

func (*Repository[T]) Lock

func (r *Repository[T]) Lock(ctx context.Context, id int64) (T, error)

func (*Repository[T]) LockByField

func (r *Repository[T]) LockByField(ctx context.Context, field string, value any) (T, error)

func (*Repository[T]) Update

func (r *Repository[T]) Update(ctx context.Context, model T) (rowsAffected int64, err error)

func (*Repository[T]) UpdateMap

func (r *Repository[T]) UpdateMap(ctx context.Context, id int64, data map[string]any) (rowsAffected int64, err error)

type Table

type Table interface {
	TableName
	Model
	// contains filtered or unexported methods
}

type TableName

type TableName interface {
	TableName() string
}

TableName table name interface to define customerize table name

type UnimplementedModel

type UnimplementedModel struct{}

type UnimplementedTable

type UnimplementedTable struct{}

type UpdateStmt

type UpdateStmt[T Table] struct {
	// contains filtered or unexported fields
}

func Update

func Update[T Table](engine *Engine) *UpdateStmt[T]

func (*UpdateStmt[T]) Exec

func (s *UpdateStmt[T]) Exec(ctx context.Context) (rowsAffected int64, err error)

func (*UpdateStmt[T]) ID

func (s *UpdateStmt[T]) ID(id any) *UpdateStmt[T]

func (*UpdateStmt[T]) Limit

func (s *UpdateStmt[T]) Limit(limit uint64) *UpdateStmt[T]

Limit sets a LIMIT clause on the query.

func (*UpdateStmt[T]) Offset

func (s *UpdateStmt[T]) Offset(offset uint64) *UpdateStmt[T]

Offset sets a OFFSET clause on the query.

func (*UpdateStmt[T]) OrderBy

func (s *UpdateStmt[T]) OrderBy(orderBys ...string) *UpdateStmt[T]

OrderBy adds ORDER BY expressions to the query.

func (*UpdateStmt[T]) Prefix

func (s *UpdateStmt[T]) Prefix(sql string, args ...any) *UpdateStmt[T]

Prefix adds an expression to the beginning of the query

func (*UpdateStmt[T]) PrefixExpr

func (s *UpdateStmt[T]) PrefixExpr(expr builder.Sqlizer) *UpdateStmt[T]

PrefixExpr adds an expression to the very beginning of the query

func (*UpdateStmt[T]) Set

func (s *UpdateStmt[T]) Set(column string, value any) *UpdateStmt[T]

Set adds SET clauses to the query.

func (*UpdateStmt[T]) SetMap

func (s *UpdateStmt[T]) SetMap(clauses map[string]any) *UpdateStmt[T]

SetMap is a convenience method which calls .Set for each key/value pair in clauses.

func (*UpdateStmt[T]) SetModel

func (s *UpdateStmt[T]) SetModel(t T) *UpdateStmt[T]

func (*UpdateStmt[T]) Suffix

func (s *UpdateStmt[T]) Suffix(sql string, args ...any) *UpdateStmt[T]

Suffix adds an expression to the end of the query

func (*UpdateStmt[T]) SuffixExpr

func (s *UpdateStmt[T]) SuffixExpr(expr builder.Sqlizer) *UpdateStmt[T]

SuffixExpr adds an expression to the end of the query

func (*UpdateStmt[T]) Table

func (s *UpdateStmt[T]) Table(table string) *UpdateStmt[T]

func (*UpdateStmt[T]) Where

func (s *UpdateStmt[T]) Where(pred any, args ...any) *UpdateStmt[T]

Where adds WHERE expressions to the query.

See SelectBuilder.Where for more information.

Directories

Path Synopsis
try
cmd
lormgen command

Jump to

Keyboard shortcuts

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