orm

package
v0.0.0-...-9d85d00 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2024 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoRows 代表没有找到数据
	ErrNoRows = errs.ErrNoRows
)

将内部的 sentinel error 暴露出去

Functions

This section is empty.

Types

type Aggregate

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

Aggregate 代表聚合函数, 例如 AVG, MAX, MIN 等 以及别名

func Avg

func Avg(c string) Aggregate

Avg

@Description: 求平均值
@param c column,聚合函数中填写的字段
@return Aggregate

func Count

func Count(c string) Aggregate

Count

@Description: 获取数量
@param c column,聚合函数中填写的字段
@return Aggregate

func Max

func Max(c string) Aggregate

Max

@Description: 求最大值
@param c column,聚合函数中填写的字段
@return Aggregate

func Min

func Min(c string) Aggregate

Min

@Description: 求聚合函数中填写的最小值
@param c column,聚合函数中填写的字段
@return Aggregate

func Sum

func Sum(c string) Aggregate

Sum

@Description: 求和
@param c
@return Aggregate

func (Aggregate) As

func (a Aggregate) As(alias string) Aggregate

As 这里使用 值 作为接收者,可以防止并发问题,每次都返回一个新的;也有小利于垃圾回收,局部之后,变量就会被回收

func (Aggregate) EQ

func (a Aggregate) EQ(arg any) Predicate

EQ 例如 AVG("id").EQ(12)

func (Aggregate) GT

func (a Aggregate) GT(arg any) Predicate

func (Aggregate) LT

func (a Aggregate) LT(arg any) Predicate

type Assignable

type Assignable interface {
	// contains filtered or unexported methods
}

Assignable 标记接口, 实现该接口意味着可以用于赋值语句, 用于在 UPDATE 和 UPSERT 中 Assign("FirstName", "DaMing") -> SET`first_name`=?

func AssignColumns

func AssignColumns(entity interface{}, filter func(typ reflect.StructField, val reflect.Value) bool) []Assignable

AssignColumns returns a list of Assignable values for the given entity, filtered by the provided filter function.

func AssignNotNilColumns

func AssignNotNilColumns(entity interface{}) []Assignable

AssignNotNilColumns

@Description: 判断是否是 Nil, 如果是 nil 那么调用 assign 的时候,就不处理这个字段
@param entity
@return []Assignable

func AssignNotZeroColumns

func AssignNotZeroColumns(entity interface{}) []Assignable

AssignNotZeroColumns

@Description: 判断是否是零值, 如果是零值 那么调用 assign 的时候,就不处理这个字段
@param entity
@return []Assignable

type Assignment

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

func Assign

func Assign(column string, val any) Assignment

type Column

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

func C

func C(name string) Column

func (Column) Add

func (c Column) Add(delta int) MathExpr

Add ...Set(Assign("Age", C("Age").Add(1))), -> SET `age`=`age` + ?;

func (Column) As

func (c Column) As(alias string) Column

func (Column) EQ

func (c Column) EQ(arg any) Predicate

EQ 例如 C("id").Eq(12)

func (Column) GT

func (c Column) GT(arg any) Predicate

func (Column) In

func (c Column) In(vals ...any) Predicate

In 有两种输入,一种是 IN 子查询 另外一种就是普通的值 这里我们可以定义两个方法,如 In 和 InQuery,也可以定义一个方法 这里我们使用一个方法

func (Column) InQuery

func (c Column) InQuery(sub Subquery) Predicate

func (Column) LT

func (c Column) LT(arg any) Predicate

LT 例如 C("id").LT(12)

func (Column) Multi

func (c Column) Multi(delta int) MathExpr

Multi ...Set(Assign("Age", C("Age").Multi(1))), -> SET `age`=`age` * ?;

type DB

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

func MustNewDB

func MustNewDB(driver string, dsn string, opts ...DBOption) *DB

MustNewDB creates a new DB with the provided options. If the creation fails, it panics.

func Open

func Open(driver string, dsn string, opts ...DBOption) (*DB, error)

Open opens a database connection using the specified driver and DSN. It also accepts optional DBOptions. 可以传入不同的 driver 连接不同的 db

func OpenDB

func OpenDB(db *sql.DB, opts ...DBOption) (*DB, error)

OpenDB 根据用户传递进来的 db 直接初始化 db 实例

func (*DB) BeginTx

func (db *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)

BeginTx 开启事务

func (*DB) Close

func (db *DB) Close() error

func (*DB) DoTx

func (db *DB) DoTx(ctx context.Context,
	fn func(ctx context.Context, tx *Tx) error,
	opts *sql.TxOptions) (err error)

DoTx 将会开启事务执行 fn。如果 fn 返回错误或者发生 panic,事务将会回滚, 否则提交事务

func (*DB) Wait

func (db *DB) Wait() error

Wait waits for the database connection to be established. It retries pinging the database until a successful connection is made. Returns an error if the connection cannot be established.

type DBOption

type DBOption func(*DB)

func DBUseReflectValuer

func DBUseReflectValuer() DBOption

DBUseReflectValuer 如果想使用反射进行获取相关信息,则调用这个 option

func DBWithDialect

func DBWithDialect(d Dialect) DBOption

DBWithRegistry 这里可以替换成不同的映射实例

func DBWithMiddlewares

func DBWithMiddlewares(mdls ...Middleware) DBOption

func DBWithRegistry

func DBWithRegistry(r model.Registry) DBOption

DBWithRegistry 这里可以替换成不同的映射实例

type Deleter

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

func NewDeleter

func NewDeleter[T any](sess Session) *Deleter[T]

NewSelector creates a new instance of Selector.

func (*Deleter[T]) Build

func (d *Deleter[T]) Build() (*Query, error)

Build generates a DELETE query based on the provided parameters. It returns the generated query string and any associated arguments, or an error if there was a problem building the query.

func (*Deleter[T]) Exec

func (d *Deleter[T]) Exec(ctx context.Context) Result

func (*Deleter[T]) From

func (d *Deleter[T]) From(table string) *Deleter[T]

From sets the table for the Deleter and returns a pointer to the Deleter. The table parameter specifies the name of the table to delete from.

func (*Deleter[T]) Where

func (d *Deleter[T]) Where(predicates ...Predicate) *Deleter[T]

Where accepts predicates and adds them to the Deleter's where clause.

Parameters: predicates: A list of predicates to add to the where clause.

Returns: *Deleter[T]: The Deleter object with the updated where clause.

type Dialect

type Dialect interface {
	// contains filtered or unexported methods
}
var (
	MySQL   Dialect = &mysqlDialect{}
	SQLite3 Dialect = &sqlite3Dialect{}
)

type Executor

type Executor interface {
	Exec(ctx context.Context) Result
}

type Expression

type Expression interface {
	// contains filtered or unexported methods
}

Expression 代表语句,或者语句的部分 暂时没想好怎么设计方法,所以直接做成标记接口

type Handler

type Handler func(ctx context.Context, qc *QueryContext) *QueryResult

type Inserter

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

func NewInserter

func NewInserter[T any](sess Session) *Inserter[T]

func (*Inserter[T]) Build

func (i *Inserter[T]) Build() (*Query, error)

func (*Inserter[T]) Columns

func (i *Inserter[T]) Columns(cols ...string) *Inserter[T]

Columns Fields 指定要插入的列 TODO 目前我们只支持指定具体的列,但是不支持复杂的表达式 例如不支持 VALUES(..., now(), now()) 这种在 MySQL 里面常用的

@Description: 更新指定的字段
@receiver i
@param cols
@return *Inserter[T]

func (*Inserter[T]) Exec

func (i *Inserter[T]) Exec(ctx context.Context) Result

func (*Inserter[T]) OnDuplicateKey

func (i *Inserter[T]) OnDuplicateKey() *UpsertBuilder[T]

func (*Inserter[T]) Values

func (i *Inserter[T]) Values(vals ...*T) *Inserter[T]

Values

@Description: 将插入数据库中的数据
@receiver i
@param val
@return *Inserter[T]

type Join

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

func (Join) Join

func (j Join) Join(target TableReference) *JoinBuilder

func (Join) LeftJoin

func (j Join) LeftJoin(target TableReference) *JoinBuilder

func (Join) RightJoin

func (j Join) RightJoin(target TableReference) *JoinBuilder

type JoinBuilder

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

func (*JoinBuilder) On

func (j *JoinBuilder) On(ps ...Predicate) Join

func (*JoinBuilder) Using

func (j *JoinBuilder) Using(cs ...string) Join

type MathExpr

type MathExpr binaryExpr

MathExpr 为非导出 struct 创建类型 update 过程中的计算方法

func (MathExpr) Add

func (m MathExpr) Add(val any) MathExpr

func (MathExpr) Multi

func (m MathExpr) Multi(val any) MathExpr

type Middleware

type Middleware func(next Handler) Handler

type OrderBy

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

func ASC

func ASC(col Column) OrderBy

func Desc

func Desc(col Column) OrderBy

type Predicate

type Predicate binaryExpr

Predicate 代表一个查询条件 Predicate 可以通过和 Predicate 组合构成复杂的查询条件

type Predicate struct {
	left  Expression
	op    op
	right Expression
}

func Exist

func Exist(sub Subquery) Predicate

func Not

func Not(p Predicate) Predicate

func (Predicate) And

func (p Predicate) And(r Predicate) Predicate

func (Predicate) Or

func (p Predicate) Or(r Predicate) Predicate

type Querier

type Querier[T any] interface {
	// Get retrieves a T object from the database.
	// It takes a context as input and returns a pointer to T and an error.
	Get(ctx context.Context) (*T, error)
	GetMulti(ctx context.Context) ([]*T, error)
}

type Query

type Query struct {
	SQL  string
	Args []any
}

type QueryBuilder

type QueryBuilder interface {
	Build() (*Query, error)
}

type QueryContext

type QueryContext struct {
	// Type 声明查询类型。即 SELECT, UPDATE, DELETE 和 INSERT
	Type string

	// builder 使用的时候,大多数情况下你需要转换到具体的类型
	// 才能篡改查询
	Builder QueryBuilder
	// qc.Model.TableName 为了有的中间件在拦截时需要 Model 信息
	// 所以需要冗余一份在 middleware 的上下文中
	Model *model.Model
}

QueryContext 中间件的上下文,冗余了 Builder model 等,是因为还没有执行 sql 前,有的中间件,需要使用这些信息, 这里优化还可以考虑 构建 builder 后的 sql 拼接结果,省的每次调用都需要调用 builder 进行拼接 sql, 这里没这么做,可能因为怕别人篡改?

type QueryResult

type QueryResult struct {
	// Result 在不同的查询里面,类型是不同的
	// Selector.Get 里面,这会是单个结果
	// Selector.GetMulti,这会是一个切片
	// 其它情况下,它会是 Result 类型
	Result any
	Err    error
}

type RawExpr

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

RawExpr 代表一个原生表达式 意味着 ORM 不会对它进行任何处理

func Raw

func Raw(expr string, args ...any) RawExpr

Raw 创建一个 RawExpr 执行原生sql 语句

func (RawExpr) AsPredicate

func (r RawExpr) AsPredicate() Predicate

type RawQuerier

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

func RawQuery

func RawQuery[T any](sess Session, query string, args ...any) *RawQuerier[T]

func (*RawQuerier[T]) Build

func (r *RawQuerier[T]) Build() (*Query, error)

func (*RawQuerier[T]) Exec

func (r *RawQuerier[T]) Exec(ctx context.Context) Result

func (*RawQuerier[T]) Get

func (r *RawQuerier[T]) Get(ctx context.Context) (*T, error)

Get RawQuery 创建一个 RawQuerier 实例 泛型参数 T 是目标类型。 例如,如果查询 User 的数据,那么 T 就是 User

func (*RawQuerier[T]) GetMulti

func (r *RawQuerier[T]) GetMulti(ctx context.Context) ([]*T, error)

type Result

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

func (Result) Err

func (r Result) Err() error

func (Result) LastInsertId

func (r Result) LastInsertId() (int64, error)

LastInsertId 重新 database sql 的 Result 方法 做一层拦截

func (Result) RowsAffected

func (r Result) RowsAffected() (int64, error)

type Selectable

type Selectable interface {
	// contains filtered or unexported methods
}

Selectable 暂时没什么作用只是用作标记,可检索指定字段的标记 让结构体实现这个接口,就可以传入 使用接口为的是:让 聚合函数, columns, 以及 RawExpr(原生sql) 都能作为参数传入统一个函数,做统一处理

type Selector

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

Selector represents a query selector that allows building SQL SELECT statements. It holds the necessary information to construct the query.

func NewSelector

func NewSelector[T any](sess Session) *Selector[T]

NewSelector creates a new instance of Selector.

func (*Selector[T]) Build

func (s *Selector[T]) Build() (*Query, error)

Build generates a SQL query for selecting all columns from a table. It returns the generated query as a *Query struct or an error if there was any.

func (*Selector[T]) From

func (s *Selector[T]) From(tbl TableReference) *Selector[T]

From sets the table name for the selector. It returns the updated selector.

func (*Selector[T]) Get

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

Get 根据拼接成的 sql 文,到 db 中获取数据

func (*Selector[T]) GetMulti

func (s *Selector[T]) GetMulti(ctx context.Context) ([]*T, error)

GetMulti TODO

func (*Selector[T]) GroupBy

func (s *Selector[T]) GroupBy(cols ...Column) *Selector[T]

func (*Selector[T]) Having

func (s *Selector[T]) Having(ps ...Predicate) *Selector[T]

func (*Selector[T]) Limit

func (s *Selector[T]) Limit(limit int) *Selector[T]

func (*Selector[T]) Offset

func (s *Selector[T]) Offset(offset int) *Selector[T]

func (*Selector[T]) OrderBy

func (s *Selector[T]) OrderBy(orderBys ...OrderBy) *Selector[T]

func (*Selector[T]) Select

func (s *Selector[T]) Select(cols ...Selectable) *Selector[T]

Select 检索指定 column

func (*Selector[T]) Where

func (s *Selector[T]) Where(ps ...Predicate) *Selector[T]

Where 用于构造 WHERE 查询条件。如果 ps 长度为 0,那么不会构造 WHERE 部分

type Session

type Session interface {
	// contains filtered or unexported methods
}

Session 代表一个抽象的概念,即会话 暂时做成私有的,后面考虑重构,因为这个东西用户可能有点难以理解

type Subquery

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

func (Subquery) C

func (s Subquery) C(name string) Column

func (Subquery) Join

func (s Subquery) Join(target TableReference) *JoinBuilder

func (Subquery) LeftJoin

func (s Subquery) LeftJoin(target TableReference) *JoinBuilder

func (Subquery) RightJoin

func (s Subquery) RightJoin(target TableReference) *JoinBuilder

type SubqueryExpr

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

SubqueryExpr 注意,这个谓词这种不是在所有的数据库里面都支持的 这里采取的是和 Upsert 不同的做法 Upsert 里面我们是属于用 dialect 来区别不同的实现 这里我们采用另外一种方案,就是直接生成,依赖于数据库来报错 实际中两种方案你可以自由替换

func All

func All(sub Subquery) SubqueryExpr

func Any

func Any(sub Subquery) SubqueryExpr

func Some

func Some(sub Subquery) SubqueryExpr

type Table

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

func TableOf

func TableOf(entity any) Table

func (Table) As

func (t Table) As(alias string) Table

func (Table) C

func (t Table) C(name string) Column

func (Table) Join

func (t Table) Join(target TableReference) *JoinBuilder

func (Table) LeftJoin

func (t Table) LeftJoin(target TableReference) *JoinBuilder

func (Table) RightJoin

func (t Table) RightJoin(target TableReference) *JoinBuilder

type TableReference

type TableReference interface {
	// contains filtered or unexported methods
}

type TestModel

type TestModel struct {
	Id        int64
	FirstName string
	Age       int8
	LastName  *sql.NullString
}

func (TestModel) CreateSQL

func (TestModel) CreateSQL() string

type TestModelWithTableName

type TestModelWithTableName struct {
	Id        int64
	FirstName string
	Age       int8
	LastName  *sql.NullString
}

func (TestModelWithTableName) TableName

func (t TestModelWithTableName) TableName() string

type Tx

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

func (*Tx) Commit

func (t *Tx) Commit() error

func (*Tx) Rollback

func (t *Tx) Rollback() error

func (*Tx) RollbackIfNotCommit

func (t *Tx) RollbackIfNotCommit() error

type Updater

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

func NewUpdater

func NewUpdater[T any](sess Session) *Updater[T]

func (*Updater[T]) Build

func (u *Updater[T]) Build() (*Query, error)

func (*Updater[T]) Exec

func (u *Updater[T]) Exec(ctx context.Context) Result

func (*Updater[T]) Set

func (u *Updater[T]) Set(assigns ...Assignable) *Updater[T]

func (*Updater[T]) Update

func (u *Updater[T]) Update(t *T) *Updater[T]

func (*Updater[T]) Where

func (u *Updater[T]) Where(ps ...Predicate) *Updater[T]

type Upsert

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

type UpsertBuilder

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

func (*UpsertBuilder[T]) ConflictColumns

func (o *UpsertBuilder[T]) ConflictColumns(cols ...string) *UpsertBuilder[T]

func (*UpsertBuilder[T]) Update

func (o *UpsertBuilder[T]) Update(assigns ...Assignable) *Inserter[T]

Update

@Description: 如果存在,则更新指定字段
@receiver o
@param assigns
@return *Inserter[T]

Directories

Path Synopsis
gen
internal
middlewares

Jump to

Keyboard shortcuts

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