Documentation
¶
Index ¶
- Variables
- func AppendDestFields(valueOf reflect.Value, fields []*Field, foreigns []*Foreign) []any
- func AppendDestTable(info TableInfo, valueOf reflect.Value) []any
- func AutoMigrate(ent any) error
- func AutoMigrateContext(ctx context.Context, ent any) error
- func Close(ent any) error
- func CreateForeignDest(valueOf reflect.Value, foreign *Foreign) []any
- func FetchArrayResult[T, V any](query *StateSelect[T, ResultFunc[V]]) ([]V, error)
- func FetchSingleResult[T, V any](query *StateSelect[T, ResultFunc[V]]) (V, error)
- func FlattenDest(valueOf reflect.Value) []any
- func GetFieldName(addr uintptr, name string) (string, error)
- func InitField(db *DB, schema *string, tableId int, tables, modelOf reflect.Value) error
- func NewColumnNotFoundError(column string) error
- func NewDuplicateIndexError(tableName, indexName string) error
- func NewFieldNotFoundError(field string) error
- func NewForeignKeyNotFoundError(fk string) error
- func NewNoPrimaryKeyError(typeName string) error
- func Open[T any](drv model.Driver, logFile string) (*T, error)
- func PutBuilder(b *Builder)
- func QueryForeign[T, R any](table *Table[T], refer *Table[R]) error
- func QueryMany2Many[T, R any](foreign *Foreign, table *Table[T], refer *Table[R]) (map[int64]*R, error)
- func QueryMiddleTable[T any](foreign *Foreign, table *Table[T], leftCol, rightCol string) (map[int64][]int64, error)
- func QueryOne2Many[T, R any](foreign *Foreign, table *Table[T], refer *Table[R]) (map[int64][]*R, error)
- func QuerySome2One[T, R any](foreign *Foreign, table *Table[T], refer *Table[R]) (map[int64]*R, error)
- func ResetRegistry()
- func SameTable(field, another *Field) bool
- type Builder
- func (b *Builder) Build(destroy bool) (sql string, args []any)
- func (b *Builder) BuildDoing() []any
- func (b *Builder) BuildHead() []any
- func (b *Builder) BuildJoins() []any
- func (b *Builder) BuildTail() []any
- func (b *Builder) BuildWhere() []any
- func (b *Builder) Reset()
- func (b *Builder) ResetForSave()
- func (b *Builder) SetTable(table TableInfo, driver model.Driver) *Builder
- type Column
- type ColumnNotFoundError
- type Condition
- func And(branches ...Condition) Condition
- func Equals(left *Field, value any) Condition
- func EqualsField(left, right *Field) Condition
- func EqualsMap(left *Field, data map[string]any) Condition
- func Expr(where string, args ...any) Condition
- func Greater(left *Field, value any) Condition
- func GreaterEquals(left *Field, value any) Condition
- func GreaterEqualsField(left, right *Field) Condition
- func GreaterField(left, right *Field) Condition
- func ILike(left *Field, value string) Condition
- func In(left *Field, value any) Condition
- func IsNotNull(left *Field) Condition
- func IsNull(left *Field) Condition
- func Less(left *Field, value any) Condition
- func LessEquals(left *Field, value any) Condition
- func LessEqualsField(left, right *Field) Condition
- func LessField(left, right *Field) Condition
- func Like(left *Field, value string) Condition
- func Not(cond Condition) Condition
- func NotEquals(left *Field, value any) Condition
- func NotEqualsField(left, right *Field) Condition
- func NotILike(left *Field, value string) Condition
- func NotIn(left *Field, value any) Condition
- func NotLike(left *Field, value string) Condition
- func Or(branches ...Condition) Condition
- type DB
- func (db *DB) BeginTransaction(txFunc func(Transaction) error) error
- func (db *DB) BeginTransactionContext(ctx context.Context, isolation sql.IsolationLevel, ...) (err error)
- func (db *DB) DriverName() string
- func (db *DB) DropTables() error
- func (db *DB) NewTransaction() (model.Transaction, error)
- func (db *DB) NewTransactionContext(ctx context.Context, isolation sql.IsolationLevel) (model.Transaction, error)
- func (db *DB) RawExecContext(ctx context.Context, rawSql string, args ...any) error
- func (db *DB) RawQueryContext(ctx context.Context, rawSql string, args ...any) (model.Rows, error)
- func (db *DB) SetDriver(driver model.Driver)
- func (db *DB) Stats() sql.DBStats
- type Dict
- type DuplicateIndexError
- type Entity
- type FetchCreator
- type FetchFunc
- type Fetcher
- type Field
- type FieldNotFoundError
- type Foreign
- type ForeignKeyNotFoundError
- type ForeignType
- type GenScanFields
- type Group
- type Handler
- func (h *Handler) BatchReturning(query model.Query, valueOf reflect.Value, returnFid int) error
- func (h *Handler) ErrHandler(query model.Query) error
- func (h *Handler) ExecuteNoReturn(query model.Query) error
- func (h *Handler) ExecuteReturning(query model.Query, valueOf reflect.Value, returnFid int) error
- func (h *Handler) InfoHandler(query model.Query)
- func (h *Handler) QueryResult(query model.Query) (model.Rows, error)
- type Index
- type JoinTable
- type ManyToSomeRelation
- type Migration
- type NilMarker
- type NoPrimaryKeyError
- type OneToSomeRelation
- type Order
- type Pagination
- type Pair
- type RelationFunc
- type ResultFloat
- type ResultFunc
- type ResultInt
- type ResultLong
- type ResultStr
- type SchemaMigration
- type StateDelete
- func (s *StateDelete[T]) Exec() error
- func (s *StateDelete[T]) Filter(args ...Condition) *StateDelete[T]
- func (s *StateDelete[T]) Match(obj T) *StateDelete[T]
- func (s *StateDelete[T]) OnTransaction(tx model.Transaction) *StateDelete[T]
- func (s *StateDelete[T]) Where(where string, args ...any) *StateDelete[T]
- type StateInsert
- type StateSave
- type StateSelect
- func (s *StateSelect[T, R]) All() ([]*R, error)
- func (s *StateSelect[T, R]) Avg(col string) (int64, error)
- func (s *StateSelect[T, R]) AvgFloat(col string) (float64, error)
- func (s *StateSelect[T, R]) CopyFrom(ob *Builder, conn model.Connection) *StateSelect[T, R]
- func (s *StateSelect[T, R]) Count(col string) (int64, error)
- func (s *StateSelect[T, R]) Filter(args ...Condition) *StateSelect[T, R]
- func (s *StateSelect[T, R]) GetJoinForeign() *Foreign
- func (s *StateSelect[T, R]) GetJoinForeigns() []*Foreign
- func (s *StateSelect[T, R]) GroupBy(args ...string) *StateSelect[T, R]
- func (s *StateSelect[T, R]) IterRows() iter.Seq2[*R, error]
- func (s *StateSelect[T, R]) Join(joinType model.JoinType, info TableInfo, on Condition) *StateSelect[T, R]
- func (s *StateSelect[T, R]) LeftJoin(fkey string, refer *Field) *StateSelect[T, R]
- func (s *StateSelect[T, R]) Map(key string) (map[int64]*R, error)
- func (s *StateSelect[T, R]) Match(obj T) *StateSelect[T, R]
- func (s *StateSelect[T, R]) Max(col string) (int64, error)
- func (s *StateSelect[T, R]) MaxFloat(col string) (float64, error)
- func (s *StateSelect[T, R]) Min(col string) (int64, error)
- func (s *StateSelect[T, R]) MinFloat(col string) (float64, error)
- func (s *StateSelect[T, R]) OnTransaction(tx model.Transaction) *StateSelect[T, R]
- func (s *StateSelect[T, R]) One() (*R, error)
- func (s *StateSelect[T, R]) OrderBy(args ...string) *StateSelect[T, R]
- func (s *StateSelect[T, R]) Pagination(page, size int) (*Pagination[T, R], error)
- func (s *StateSelect[T, R]) Query(creator FetchCreator) (*Fetcher[R], model.Query)
- func (s *StateSelect[T, R]) QueryFetch(to FetchFunc) (*Fetcher[R], model.Query)
- func (s *StateSelect[T, R]) QueryRows(to FetchFunc) (data []*R, err error)
- func (s *StateSelect[T, R]) Rank(key string) (map[int64][]*R, error)
- func (s *StateSelect[T, R]) RollUP() *StateSelect[T, R]
- func (s *StateSelect[T, R]) Select(fields ...any) *StateSelect[T, R]
- func (s *StateSelect[T, R]) Skip(i int) *StateSelect[T, R]
- func (s *StateSelect[T, R]) Sum(col string) (int64, error)
- func (s *StateSelect[T, R]) SumFloat(col string) (float64, error)
- func (s *StateSelect[T, R]) Take(i int) *StateSelect[T, R]
- func (s *StateSelect[T, R]) ToLower(col string) ([]string, error)
- func (s *StateSelect[T, R]) ToUpper(col string) ([]string, error)
- func (s *StateSelect[T, R]) Where(where string, args ...any) *StateSelect[T, R]
- type StateUpdate
- func (s *StateUpdate[T]) Exec() error
- func (s *StateUpdate[T]) Filter(args ...Condition) *StateUpdate[T]
- func (s *StateUpdate[T]) Join(joinType model.JoinType, info TableInfo, on Condition) *StateUpdate[T]
- func (s *StateUpdate[T]) LeftJoin(fkey string, refer *Field) *StateUpdate[T]
- func (s *StateUpdate[T]) Match(obj T) *StateUpdate[T]
- func (s *StateUpdate[T]) OnTransaction(tx model.Transaction) *StateUpdate[T]
- func (s *StateUpdate[T]) Set(pairs ...Pair) *StateUpdate[T]
- func (s *StateUpdate[T]) SetMap(changes Dict) *StateUpdate[T]
- func (s *StateUpdate[T]) Take(i int) *StateUpdate[T]
- func (s *StateUpdate[T]) Where(where string, args ...any) *StateUpdate[T]
- type StateWhere
- type Table
- func (t *Table[T]) Avg(col string) (int64, error)
- func (t *Table[T]) AvgFloat(col string) (float64, error)
- func (t *Table[T]) CacheOne(row any)
- func (t *Table[T]) Count(col string) (int64, error)
- func (t *Table[T]) Delete() *StateDelete[T]
- func (t *Table[T]) DeleteContext(ctx context.Context) *StateDelete[T]
- func (t *Table[T]) Dest() (*T, []any)
- func (t *Table[T]) Drop() error
- func (t *Table[T]) Filter(args ...Condition) *Table[T]
- func (t *Table[T]) FilterContext(ctx context.Context, args ...Condition) *Table[T]
- func (t *Table[T]) Insert() *StateInsert[T]
- func (t *Table[T]) InsertContext(ctx context.Context) *StateInsert[T]
- func (t *Table[T]) Max(col string) (int64, error)
- func (t *Table[T]) MaxFloat(col string) (float64, error)
- func (t *Table[T]) Min(col string) (int64, error)
- func (t *Table[T]) MinFloat(col string) (float64, error)
- func (t *Table[T]) Save() *StateSave[T]
- func (t *Table[T]) SaveContext(ctx context.Context) *StateSave[T]
- func (t *Table[T]) Select(fields ...any) *StateSelect[T, T]
- func (t *Table[T]) SelectContext(ctx context.Context, fields ...any) *StateSelect[T, T]
- func (t *Table[T]) SetDB(db *DB)
- func (t *Table[T]) Sum(col string) (int64, error)
- func (t *Table[T]) SumFloat(col string) (float64, error)
- func (t *Table[T]) ToLower(col string) ([]string, error)
- func (t *Table[T]) ToUpper(col string) ([]string, error)
- func (t *Table[T]) Update() *StateUpdate[T]
- func (t *Table[T]) UpdateContext(ctx context.Context) *StateUpdate[T]
- func (t *Table[T]) Where(where string, args ...any) *Table[T]
- func (t *Table[T]) WhereContext(ctx context.Context, where string, args ...any) *Table[T]
- type TableInfo
- func (info TableInfo) Check(col string) (int, bool)
- func (info TableInfo) ColumnInfo(name string) *Column
- func (info TableInfo) Field(col string) *Field
- func (info TableInfo) GetPrimaryInfo() (int, string, []string)
- func (info TableInfo) GetSortedFields() []*Field
- func (info TableInfo) String() string
- func (info TableInfo) Table() *model.Table
- type TableMigration
- type ThirdParty
- type Transaction
- type Value
Constants ¶
This section is empty.
Variables ¶
var ( ErrUniqueValue = errors.New("goent: unique constraint violation") ErrForeignKey = errors.New("goent: foreign key constraint violation") ErrBadRequest = errors.New("goent: bad request") ErrNotFound = errors.New("goent: not found any element on result set") ErrInvalidDatabase = errors.New("goent: invalid database, the target needs to be a struct") ErrInvalidDBField = errors.New("goent: invalid database, last struct field needs to be goent.DB") ErrDBNotFound = errors.New("goent: db not found") ErrFieldNotFound = errors.New("goent: field or table not found") ErrColumnNotFound = errors.New("goent: column not found") ErrNoPrimaryKey = errors.New("goent: struct does not have a primary key set") ErrSliceTypeMigration = errors.New("goent: cannot migrate slice type") ErrDuplicateIndex = errors.New("goent: struct has two or more indexes with same name but different uniqueness/function") ErrForeignKeyNotFound = errors.New("goent: foreign key not found") ErrMiddleTableNotSet = errors.New("goent: middle table not configured for M2M relation") )
Functions ¶
func AppendDestFields ¶
AppendDestFields returns a slice of pointers to the fields of a struct for database scanning. It handles both regular fields and wildcard (*) fields that expand to all table columns.
Example:
dest := AppendDestFields(valueOf, fields, nil) rows.Scan(dest...) // scan into struct fields
func AppendDestTable ¶
AppendDestTable returns a slice of pointers to the fields of a struct
func AutoMigrate ¶
AutoMigrate automatically migrates the database schema based on the entity struct definitions.
func AutoMigrateContext ¶
AutoMigrateContext automatically migrates the database schema with the given context.
func CreateForeignDest ¶
CreateForeignDest creates destination pointers for foreign key relationship fields. It initializes the related struct field and returns pointers to its columns for scanning.
func FetchArrayResult ¶
func FetchArrayResult[T, V any](query *StateSelect[T, ResultFunc[V]]) ([]V, error)
FetchArrayResult executes a multi-row query and returns the result array. Example: names, err := FetchArrayResult[string](query)
func FetchSingleResult ¶
func FetchSingleResult[T, V any](query *StateSelect[T, ResultFunc[V]]) (V, error)
FetchSingleResult executes a single-row query and returns the result. Example: count, err := FetchSingleResult[int64](query)
func FlattenDest ¶
FlattenDest returns a slice of pointers to the fields of a struct
func GetFieldName ¶
GetFieldName returns the qualified field name (table.column) for a given table address and column name. If the address is 0, it returns just the column name.
func InitField ¶
InitField initializes the fields of a model struct, setting up primary keys and attributes.
func NewColumnNotFoundError ¶
NewColumnNotFoundError creates an error indicating that the specified column was not found.
func NewDuplicateIndexError ¶
NewDuplicateIndexError creates an error indicating duplicate index definitions with conflicting settings.
func NewFieldNotFoundError ¶
NewFieldNotFoundError creates an error indicating that the specified field or table was not found.
func NewForeignKeyNotFoundError ¶
NewForeignKeyNotFoundError creates an error indicating that the specified foreign key was not found.
func NewNoPrimaryKeyError ¶
NewNoPrimaryKeyError creates an error indicating that the struct does not have a primary key set.
func Open ¶
Open opens a database connection
Example ¶
goent.Open[Database](pgsql.Open("user=postgres password=postgres host=localhost port=5432 database=postgres", pgsql.Config{}))
func QueryForeign ¶
QueryForeign queries and populates related records for a foreign key relationship. It automatically determines the relationship type and calls the appropriate query method. Returns nil if no foreign key relationship is found.
Example:
err := QueryForeign(orderTable, customerTable)
if err != nil {
log.Fatal(err)
}
for _, order := range orderTable.Cache.Each() {
fmt.Println(order.Customer) // populated Customer struct
}
func QueryMany2Many ¶
func QueryMany2Many[T, R any](foreign *Foreign, table *Table[T], refer *Table[R]) (map[int64]*R, error)
QueryMany2Many queries and populates many-to-many relationships. It uses the middle table to establish the relationship between two tables. Returns a map of left-side IDs to right-side records.
Example:
results, err := QueryMany2Many(foreign, studentTable, courseTable)
for studentId, courses := range results {
fmt.Printf("Student %d is enrolled in %d courses\n", studentId, len(courses))
}
func QueryMiddleTable ¶
func QueryMiddleTable[T any](foreign *Foreign, table *Table[T], leftCol, rightCol string) (map[int64][]int64, error)
QueryMiddleTable queries the middle junction table for many-to-many relationships. It returns a map of left-side IDs to slices of right-side IDs.
Example:
mapping, err := QueryMiddleTable(foreign, studentTable, "student_id", "course_id")
for studentId, courseIds := range mapping {
fmt.Printf("Student %d is in courses: %v\n", studentId, courseIds)
}
func QueryOne2Many ¶
func QueryOne2Many[T, R any](foreign *Foreign, table *Table[T], refer *Table[R]) (map[int64][]*R, error)
QueryOne2Many queries and populates one-to-many relationships. It returns a map of parent IDs to slices of child records.
Example:
results, err := QueryOne2Many(foreign, categoryTable, productTable)
for catId, products := range results {
fmt.Printf("Category %d has %d products\n", catId, len(products))
}
func QuerySome2One ¶
func QuerySome2One[T, R any](foreign *Foreign, table *Table[T], refer *Table[R]) (map[int64]*R, error)
QuerySome2One queries and populates many-to-one or one-to-one relationships. It returns a map of foreign key IDs to referenced records.
Example:
results, err := QuerySome2One(foreign, orderTable, customerTable)
for id, customer := range results {
fmt.Printf("Order %d: %s\n", id, customer.Name)
}
func ResetRegistry ¶
func ResetRegistry()
ResetRegistry clears all registered schemas and tables. This is useful for testing purposes.
Types ¶
type Builder ¶
type Builder struct {
Type model.QueryType
Table *model.Table
Joins []*JoinTable
Changes map[*Field]any
MoreRows [][]any
Where Condition
Selects []*Field
Orders []*Order
Groups []*Group
Limit int
Offset int
Returning string
RollUp string
ForUpdate bool
strings.Builder
// contains filtered or unexported fields
}
Builder constructs SQL queries with support for SELECT, INSERT, UPDATE, and DELETE operations.
func (*Builder) Build ¶
Build assembles the complete SQL query and returns it along with query arguments.
func (*Builder) BuildDoing ¶
BuildDoing builds the SET clause for UPDATE or VALUES clause for INSERT.
func (*Builder) BuildHead ¶
BuildHead builds the SELECT, INSERT, UPDATE, or DELETE statement head (e.g., "SELECT * FROM table").
func (*Builder) BuildJoins ¶
BuildJoins builds the JOIN clauses for the query.
func (*Builder) BuildTail ¶
BuildTail builds the tail part of the query (GROUP BY, ORDER BY, LIMIT, OFFSET, RETURNING).
func (*Builder) BuildWhere ¶
BuildWhere builds the WHERE clause for the query.
func (*Builder) ResetForSave ¶
func (b *Builder) ResetForSave()
ResetForSave resets the Builder for INSERT/UPDATE operations.
type Column ¶
type Column struct {
FieldName string // Go struct field name
FieldId int // Index of the field in the struct
ColumnName string // Database column name
ColumnType string // Database column type (e.g., "int", "varchar")
AllowNull bool // Whether the column allows NULL values
HasDefault bool // Whether the column has a default value
DefaultValue string // The default value from struct tag
// contains filtered or unexported fields
}
Column represents a database column with its metadata and field information.
func GetTableColumn ¶
GetTableColumn returns the column info for a given table address and column name.
type ColumnNotFoundError ¶
type ColumnNotFoundError struct {
Column string
}
ColumnNotFoundError is returned when a column cannot be found in a table.
func (*ColumnNotFoundError) Error ¶
func (e *ColumnNotFoundError) Error() string
type Condition ¶
Condition represents a SQL WHERE condition with a template and associated fields/values.
func And ¶
And Example
goent.And(
goent.Equals(db.Animal.Field("status"), "Eating"),
goent.Like(db.Animal.Field("name"), "%Cat%"),
goent.GreaterThan(db.Animal.Field("age"), 3),
)
func Equals ¶
Equals creates a condition that checks if a field is equal to a value.
Example: using Table with field name
goent.Equals(db.OrderDetail.Field("order_id"), 1)
func EqualsField ¶
func EqualsMap ¶
EqualsMap creates a condition that checks if a field equals multiple values (from a map).
Example:
cond := goent.EqualsMap(db.User.Field("status"), map[string]any{"active": true, "pending": nil})
func Expr ¶
Expr creates a condition with a custom template and associated values.
Example:
cond := goent.Expr("age > ? AND status = ?", 18, "active")
users, _ := db.User.Filter(cond).Select().All()
func Greater ¶
Greater Example
// get all animals that was created after this year
thisYear, _ := time.Parse(time.RFC3339, "2026-01-01T00:00:00Z08:00")
Filter(goent.Greater(db.Animal.Field("create_at"), thisYear))
func GreaterEquals ¶
GreaterEquals Example
// get all animals that was created in or after this year
Filter(goent.GreaterEquals(db.Animal.Field("create_at"), time.Parse(time.DateOnly, "2026-01-01")))
func GreaterEqualsField ¶
GreaterEqualsField creates a condition that checks if one field is greater than or equal to another.
func GreaterField ¶
func IsNotNull ¶
IsNotNull creates a condition that checks if a field is NOT NULL.
Example:
cond := goent.IsNotNull(db.User.Field("email"))
func IsNull ¶
IsNull creates a condition that checks if a field is NULL.
Example:
cond := goent.IsNull(db.User.Field("deleted_at"))
func Less ¶
Less creates a condition that checks if a field is less than a value.
Example: get all animals that was updated before this year
Filter(goent.Less(db.Animal.Field("update_at"), time.Parse(time.DateOnly, "2026-01-01")))
func LessEquals ¶
LessEquals creates a condition that checks if a field is less than or equal to a value.
Example: get all animals that was updated in or before this year
Filter(goent.LessEquals(db.Animal.Field("update_at"), time.Parse(time.DateOnly, "2026-01-01")))
func LessEqualsField ¶
LessEqualsField creates a condition that checks if one field is less than or equal to another.
func Like ¶
Like creates a condition that checks if a field matches a LIKE pattern.
Example: get all animals that has a "at" in his name
goent.Like(db.Animal.Field("name"), "%at%")
func Not ¶
Not creates a condition that negates another condition.
Example:
cond := goent.Not(goent.Equals(field, "active"))
func NotEquals ¶
NotEquals creates a condition that checks if a field is not equal to a value.
Example:
cond := goent.NotEquals(db.User.Field("status"), "deleted")
func NotEqualsField ¶
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB represents a database connection with its driver.
func (*DB) BeginTransaction ¶
func (db *DB) BeginTransaction(txFunc func(Transaction) error) error
BeginTransaction begins a Transaction with the database default level. Any panic or error will trigger a rollback.
BeginTransaction uses context.Background internally; to specify the context and the isolation level, use [BeginTransactionContext].
Example:
err = db.BeginTransaction(func(tx goent.Transaction) error {
cat := &Animal{Name: "Cat"}
if err = goent.Insert(db.Animal).OnTransaction(tx).One(cat); err != nil {
return err // triggers rollback
}
dog := &Animal{Name: "Dog"}
if err = goent.Insert(db.Animal).OnTransaction(tx).One(dog); err != nil {
return err // triggers rollback
}
return nil // commits transaction
})
func (*DB) BeginTransactionContext ¶
func (db *DB) BeginTransactionContext(ctx context.Context, isolation sql.IsolationLevel, txFunc func(Transaction) error) (err error)
BeginTransactionContext begins a Transaction with the specified context and isolation level. Any panic or error will trigger a rollback.
Example:
err = db.BeginTransactionContext(context.Background(), sql.LevelSerializable, func(tx goent.Transaction) error {
cat := &Animal{Name: "Cat"}
if err = goent.Insert(db.Animal).OnTransaction(tx).One(cat); err != nil {
return err // triggers rollback
}
dog := &Animal{Name: "Dog"}
if err = goent.Insert(db.Animal).OnTransaction(tx).One(dog); err != nil {
return err // triggers rollback
}
return nil // commits transaction
})
func (*DB) DriverName ¶ added in v0.8.2
DriverName returns the database name (SQLite, PostgreSQL, etc.).
func (*DB) DropTables ¶ added in v0.8.2
func (*DB) NewTransaction ¶
func (db *DB) NewTransaction() (model.Transaction, error)
NewTransaction creates a new Transaction on the database using the default level.
NewTransaction uses context.Background internally; to specify the context and the isolation level, use [NewTransactionContext].
func (*DB) NewTransactionContext ¶
func (db *DB) NewTransactionContext(ctx context.Context, isolation sql.IsolationLevel) (model.Transaction, error)
NewTransactionContext creates a new Transaction with the specified context and isolation level.
func (*DB) RawExecContext ¶
RawExecContext executes a raw SQL statement without returning rows.
Example:
err := db.RawExecContext(ctx, "UPDATE users SET name = ? WHERE id = ?", "John", 1)
func (*DB) RawQueryContext ¶
RawQueryContext executes a raw SQL query and returns rows.
Example:
rows, err := db.RawQueryContext(ctx, "SELECT * FROM users WHERE id = ?", 1)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
// scan rows
}
type Dict ¶
func CollectFields ¶
func CollectFields[T any](builder *Builder, table *Table[T], valueOf reflect.Value, ignores []string) (Dict, int)
CollectFields collects primary key and non-primary key fields from a struct value. It sets the builder's returning information for auto-increment primary keys and returns a map of primary key column names to their values.
type DuplicateIndexError ¶
DuplicateIndexError is returned when two or more indexes have the same name but different settings.
func (*DuplicateIndexError) Error ¶
func (e *DuplicateIndexError) Error() string
type FetchCreator ¶
FetchCreator is a function type that creates a FetchFunc based on table info, fields, and foreign.
type FetchFunc ¶
FetchFunc is a function type that returns a slice of pointers to struct fields for scanning.
func CreateFetchFunc ¶
CreateFetchFunc creates a FetchFunc based on the specified fields and foreign relationships. It handles both aggregate function results and regular table field scanning.
type Fetcher ¶
Fetcher handles fetching query results into typed structs.
func NewFetcher ¶
NewFetcher creates a new Fetcher with the given handler and target constructor.
Example:
fetcher := NewFetcher(handler, func() *User { return &User{} })
func (*Fetcher[R]) FetchResult ¶
FetchResult returns an iterator that yields typed results from the query result set. This is memory-efficient for processing large result sets.
Example:
for user, err := range fetcher.FetchResult(query) {
if err != nil {
return err
}
fmt.Println(user.Name)
}
func (*Fetcher[R]) FetchRows ¶
FetchRows fetches all rows from the result set into a slice of typed pointers. It closes the rows and returns the slice of results.
Example:
users, err := fetcher.FetchRows(rows, err, 100)
if err != nil {
return nil, err
}
fmt.Println(len(users)) // number of fetched records
type Field ¶
type Field struct {
TableAddr uintptr
FieldId int
ColumnName string
AliasName string
Function string
}
Field represents a database field with its table reference and column name.
func (*Field) Func ¶
Func applies a SQL function to the field (e.g., "UPPER", "LOWER", "COUNT").
Example:
field := goent.Expr("UPPER(name)").(*goent.Field)
users, _ := db.User.Filter(goent.Equals(field, "JOHN")).Select().All()
type FieldNotFoundError ¶
type FieldNotFoundError struct {
Field string
}
FieldNotFoundError is returned when a field or table cannot be found.
func (*FieldNotFoundError) Error ¶
func (e *FieldNotFoundError) Error() string
type Foreign ¶
type Foreign struct {
Type ForeignType
MountField string
ForeignKey string
Reference *Field
Middle *ThirdParty
Where Condition
}
Foreign represents a foreign key relationship between two tables. It contains the relationship type, mounting field, foreign key column, reference field, and optional middle table for many-to-many relationships.
func GetForeign ¶
GetForeign retrieves the foreign key relationship between two tables. It searches by table name first, then by table address. Returns nil if no foreign key relationship is found.
Example:
foreign := GetForeign(userTable, addressTable)
if foreign != nil {
fmt.Println(foreign.Type) // prints O2O, O2M, M2O, or M2M
}
type ForeignKeyNotFoundError ¶
type ForeignKeyNotFoundError struct {
ForeignKey string
}
ForeignKeyNotFoundError is returned when a foreign key column cannot be found.
func (*ForeignKeyNotFoundError) Error ¶
func (e *ForeignKeyNotFoundError) Error() string
type ForeignType ¶
type ForeignType uint
ForeignType represents the type of foreign key relationship. Values: O2O (one-to-one), O2M (one-to-many), M2O (many-to-one), M2M (many-to-many).
const ( O2O ForeignType // one-to-one O2M // one-to-many M2O // many-to-one M2M // many-to-many )
type GenScanFields ¶ added in v0.8.4
type GenScanFields interface {
ScanFields() []any
}
GenScanFields is an interface for Model which is modifiable by goent-gen.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler handles database query execution and result processing.
func NewHandler ¶
func NewHandler(ctx context.Context, conn model.Connection, cfg *model.DatabaseConfig) *Handler
NewHandler creates a new Handler with the given context, connection, and database config.
func (*Handler) BatchReturning ¶
BatchReturning executes a query with RETURNING clause for batch inserts. It scans multiple returned rows into successive elements of the slice.
Example:
err := hd.BatchReturning(query, valueOf, returnFid)
if err != nil {
return err
}
fmt.Println(valueOf.Len()) // number of inserted records
func (*Handler) ErrHandler ¶
ErrHandler handles query errors using the configured error handler.
func (*Handler) ExecuteNoReturn ¶
ExecuteNoReturn executes a query that does not return any rows (INSERT, UPDATE, DELETE). It logs the query execution time and handles any errors.
Example:
err := hd.ExecuteNoReturn(query)
if err != nil {
return err
}
func (*Handler) ExecuteReturning ¶
ExecuteReturning executes a query with RETURNING clause and scans the result into the specified field. It is used for INSERT statements that return auto-generated values like IDs.
Example:
err := hd.ExecuteReturning(query, valueOf, returnFid)
if err != nil {
return err
}
fmt.Println(valueOf.Field(returnFid).Int()) // printed generated ID
func (*Handler) InfoHandler ¶
InfoHandler logs the query information using the configured info handler.
func (*Handler) QueryResult ¶
QueryResult executes a query that returns rows (SELECT). It returns the rows iterator and any error encountered.
Example:
rows, err := hd.QueryResult(query)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
// scan rows
}
type Index ¶
type Index struct {
IsUnique bool // Whether the index is unique
IsAutoIncr bool // Whether the column is auto-increment
*Column // Embedded column information
}
Index represents a database index with uniqueness and auto-increment flags.
type JoinTable ¶
type JoinTable struct {
JoinType model.JoinType
Table *model.Table
On Condition
// contains filtered or unexported fields
}
JoinTable represents a JOIN clause with the join type, target table, and ON condition.
type ManyToSomeRelation ¶
type ManyToSomeRelation struct {
IsDefault bool
// contains filtered or unexported fields
}
ManyToSomeRelation represents a many-to-one or many-to-many relationship between tables.
type Migration ¶
type Migration struct {
// contains filtered or unexported fields
}
Migration provides methods for database schema migrations.
func (Migration) KeywordHandler ¶ added in v0.8.4
func (Migration) OnSchema ¶
func (m Migration) OnSchema(schema string) SchemaMigration
func (Migration) OnTable ¶
func (m Migration) OnTable(table string) TableMigration
type NilMarker ¶
type NilMarker struct{}
NilMarker is a special type to indicate a nil pointer field for IS NULL conditions.
type NoPrimaryKeyError ¶
type NoPrimaryKeyError struct {
TypeName string
}
NoPrimaryKeyError is returned when a struct does not have a primary key defined.
func (*NoPrimaryKeyError) Error ¶
func (e *NoPrimaryKeyError) Error() string
type OneToSomeRelation ¶
type OneToSomeRelation struct {
IsOneToMany bool
// contains filtered or unexported fields
}
OneToSomeRelation represents a one-to-one or one-to-many relationship between tables.
type Pagination ¶
type Pagination[T, R any] struct { TotalValues int64 `json:"totalValues"` // TotalValues is the total number of values in the query result. TotalPages int `json:"totalPages"` // TotalPages is the total number of pages in the pagination. PageValues int `json:"pageValues"` // PageValues is the number of values on the current page. PageSize int `json:"pageSize"` // PageSize is the maximum number of values per page. CurrentPage int `json:"currentPage"` // CurrentPage is the current page number. HasPreviousPage bool `json:"hasPreviousPage"` // HasPreviousPage is true if there is a previous page. PreviousPage int `json:"previousPage"` // PreviousPage is the number of the previous page. HasNextPage bool `json:"hasNextPage"` // HasNextPage is true if there is a next page. NextPage int `json:"nextPage"` // NextPage is the number of the next page. StartIndex int `json:"startIndex"` // StartIndex is the index of the first value on the current page. EndIndex int `json:"endIndex"` // EndIndex is the index of the last value on the current page. Values []*R `json:"values"` // Values is the slice of values on the current page. }
Pagination holds paginated query results with metadata.
type RelationFunc ¶
RelationFunc is a function type that defines how to handle a relation field. It takes a body struct and the type of the relation field as parameters. The function returns the value of the relation field.
type ResultFloat ¶
type ResultFloat = ResultFunc[float64] // Float64 result type
type ResultFunc ¶
type ResultFunc[T any] struct { Value T // The result value }
ResultFunc holds the result of a function query. Example: ResultStr = ResultFunc[string]
type ResultInt ¶
type ResultInt = ResultFunc[int] // Int result type
type ResultLong ¶
type ResultLong = ResultFunc[int64] // Int64 result type
type ResultStr ¶
type ResultStr = ResultFunc[string] // String result type
type SchemaMigration ¶
type SchemaMigration struct {
Migration
// contains filtered or unexported fields
}
SchemaMigration provides migration methods scoped to a specific schema.
func (SchemaMigration) OnTable ¶
func (m SchemaMigration) OnTable(table string) TableMigration
type StateDelete ¶
type StateDelete[T any] struct { *StateWhere // contains filtered or unexported fields }
StateDelete represents a DELETE query state for removing records from a table.
func (*StateDelete[T]) Filter ¶
func (s *StateDelete[T]) Filter(args ...Condition) *StateDelete[T]
Filter adds filter conditions to the DELETE query.
func (*StateDelete[T]) Match ¶
func (s *StateDelete[T]) Match(obj T) *StateDelete[T]
Match sets the WHERE conditions based on the non-zero fields of the given object.
func (*StateDelete[T]) OnTransaction ¶
func (s *StateDelete[T]) OnTransaction(tx model.Transaction) *StateDelete[T]
func (*StateDelete[T]) Where ¶
func (s *StateDelete[T]) Where(where string, args ...any) *StateDelete[T]
Where adds a WHERE clause to the DELETE query.
type StateInsert ¶
type StateInsert[T any] struct { *StateWhere // contains filtered or unexported fields }
StateInsert represents an INSERT query state for inserting new records into a table.
func (*StateInsert[T]) All ¶
func (s *StateInsert[T]) All(retPK bool, data []*T) error
All inserts multiple records into the table.
func (*StateInsert[T]) OnTransaction ¶
func (s *StateInsert[T]) OnTransaction(tx model.Transaction) *StateInsert[T]
OnTransaction sets the transaction for the insert operation.
func (*StateInsert[T]) One ¶
func (s *StateInsert[T]) One(obj *T) error
One inserts a single record into the table.
type StateSave ¶
type StateSave[T any] struct { *StateWhere // contains filtered or unexported fields }
StateSave represents a save state that intelligently inserts or updates records based on primary key presence.
func (*StateSave[T]) Map ¶
Map saves records from a map, inserting or updating based on primary key presence.
func (*StateSave[T]) Match ¶
Match sets the WHERE conditions based on the non-zero fields of the given object.
func (*StateSave[T]) OnTransaction ¶
func (s *StateSave[T]) OnTransaction(tx model.Transaction) *StateSave[T]
OnTransaction sets the transaction for the save operation.
type StateSelect ¶
type StateSelect[T, R any] struct { *StateWhere // contains filtered or unexported fields }
StateSelect represents a SELECT query state with type parameters for table and result types.
func NewSelectFunc ¶
func NewSelectFunc[T, R any](state *StateWhere, table *Table[T], col, fun string) *StateSelect[T, R]
NewSelectFunc creates a new StateSelect with a function applied to the specified column. T is the model type, R is the result type.
func NewStateSelect ¶
func NewStateSelect[T, R any](ctx context.Context, table *Table[T]) *StateSelect[T, R]
NewStateSelect creates a new StateSelect for querying data from a table.
func NewStateSelectFrom ¶
func NewStateSelectFrom[T, R any](state *StateWhere, table *Table[T]) *StateSelect[T, R]
NewStateSelectFrom creates a new StateSelect for querying data from a table
func (*StateSelect[T, R]) All ¶
func (s *StateSelect[T, R]) All() ([]*R, error)
All executes the query and returns all rows as a slice.
func (*StateSelect[T, R]) Avg ¶
func (s *StateSelect[T, R]) Avg(col string) (int64, error)
Avg returns the average value of the specified column. Example: avg, err := db.Animal.Select().Avg("price")
func (*StateSelect[T, R]) AvgFloat ¶
func (s *StateSelect[T, R]) AvgFloat(col string) (float64, error)
AvgFloat returns the average value of the specified column as float64. Example: avg, err := db.Animal.Select().AvgFloat("price")
func (*StateSelect[T, R]) CopyFrom ¶
func (s *StateSelect[T, R]) CopyFrom(ob *Builder, conn model.Connection) *StateSelect[T, R]
CopyFrom copies the query builder state from another builder and connection.
func (*StateSelect[T, R]) Count ¶
func (s *StateSelect[T, R]) Count(col string) (int64, error)
Count returns the count of rows matching the query. Example: count, err := db.Animal.Count("id")
func (*StateSelect[T, R]) Filter ¶
func (s *StateSelect[T, R]) Filter(args ...Condition) *StateSelect[T, R]
Filter adds filter conditions to the select query.
func (*StateSelect[T, R]) GetJoinForeign ¶
func (s *StateSelect[T, R]) GetJoinForeign() *Foreign
GetJoinForeign returns the foreign key relationship for the joined table.
func (*StateSelect[T, R]) GetJoinForeigns ¶
func (s *StateSelect[T, R]) GetJoinForeigns() []*Foreign
GetJoinForeigns returns all foreign key relationships for the joined tables.
func (*StateSelect[T, R]) GroupBy ¶
func (s *StateSelect[T, R]) GroupBy(args ...string) *StateSelect[T, R]
GroupBy makes a group by args query
func (*StateSelect[T, R]) IterRows ¶
func (s *StateSelect[T, R]) IterRows() iter.Seq2[*R, error]
IterRows return a iterator on rows.
func (*StateSelect[T, R]) Join ¶
func (s *StateSelect[T, R]) Join(joinType model.JoinType, info TableInfo, on Condition) *StateSelect[T, R]
Join joins another table with a condition
func (*StateSelect[T, R]) LeftJoin ¶
func (s *StateSelect[T, R]) LeftJoin(fkey string, refer *Field) *StateSelect[T, R]
LeftJoin joins another table with a condition on left table
func (*StateSelect[T, R]) Map ¶
func (s *StateSelect[T, R]) Map(key string) (map[int64]*R, error)
Map executes the query and returns results as a map keyed by the specified column.
func (*StateSelect[T, R]) Match ¶
func (s *StateSelect[T, R]) Match(obj T) *StateSelect[T, R]
Match sets the WHERE conditions based on the non-zero fields of the given object.
func (*StateSelect[T, R]) Max ¶
func (s *StateSelect[T, R]) Max(col string) (int64, error)
Max returns the maximum value of the specified column. Example: max, err := db.Animal.Select().Max("id")
func (*StateSelect[T, R]) MaxFloat ¶
func (s *StateSelect[T, R]) MaxFloat(col string) (float64, error)
MaxFloat returns the maximum value of the specified column as float64. Example: max, err := db.Animal.Select().MaxFloat("price")
func (*StateSelect[T, R]) Min ¶
func (s *StateSelect[T, R]) Min(col string) (int64, error)
Min returns the minimum value of the specified column. Example: min, err := db.Animal.Select().Min("id")
func (*StateSelect[T, R]) MinFloat ¶
func (s *StateSelect[T, R]) MinFloat(col string) (float64, error)
MinFloat returns the minimum value of the specified column as float64. Example: min, err := db.Animal.Select().MinFloat("price")
func (*StateSelect[T, R]) OnTransaction ¶
func (s *StateSelect[T, R]) OnTransaction(tx model.Transaction) *StateSelect[T, R]
OnTransaction sets a transaction for the select query and enables FOR UPDATE lock.
func (*StateSelect[T, R]) One ¶
func (s *StateSelect[T, R]) One() (*R, error)
One executes the query and returns the first row as a single result.
func (*StateSelect[T, R]) OrderBy ¶
func (s *StateSelect[T, R]) OrderBy(args ...string) *StateSelect[T, R]
OrderBy makes a ordained by args query
func (*StateSelect[T, R]) Pagination ¶
func (s *StateSelect[T, R]) Pagination(page, size int) (*Pagination[T, R], error)
Pagination return a paginated query as Pagination.
Default values for page and size are 1 and 10 respectively.
func (*StateSelect[T, R]) Query ¶
func (s *StateSelect[T, R]) Query(creator FetchCreator) (*Fetcher[R], model.Query)
Query returns a Fetcher and a Query.
func (*StateSelect[T, R]) QueryFetch ¶
func (s *StateSelect[T, R]) QueryFetch(to FetchFunc) (*Fetcher[R], model.Query)
QueryFetch returns a Fetcher and a Query.
func (*StateSelect[T, R]) QueryRows ¶
func (s *StateSelect[T, R]) QueryRows(to FetchFunc) (data []*R, err error)
QueryRows executes the query and returns all rows as a slice.
func (*StateSelect[T, R]) Rank ¶
func (s *StateSelect[T, R]) Rank(key string) (map[int64][]*R, error)
Rank executes the query and returns results as a map keyed by the specified column, with each key mapping to a slice of results.
func (*StateSelect[T, R]) RollUP ¶
func (s *StateSelect[T, R]) RollUP() *StateSelect[T, R]
RollUP enables rollup for aggregation queries.
Example:
results, _ := db.Order.Select("status", "total").GroupBy("status").RollUP().All()
func (*StateSelect[T, R]) Select ¶
func (s *StateSelect[T, R]) Select(fields ...any) *StateSelect[T, R]
Select specifies the fields to select from the table.
func (*StateSelect[T, R]) Skip ¶
func (s *StateSelect[T, R]) Skip(i int) *StateSelect[T, R]
Skip skips i elements
func (*StateSelect[T, R]) Sum ¶
func (s *StateSelect[T, R]) Sum(col string) (int64, error)
Sum returns the sum of values in the specified column. Example: sum, err := db.Animal.Select().Sum("price")
func (*StateSelect[T, R]) SumFloat ¶
func (s *StateSelect[T, R]) SumFloat(col string) (float64, error)
SumFloat returns the sum of values in the specified column as float64. Example: sum, err := db.Animal.Select().SumFloat("price")
func (*StateSelect[T, R]) Take ¶
func (s *StateSelect[T, R]) Take(i int) *StateSelect[T, R]
Take takes i elements
func (*StateSelect[T, R]) ToLower ¶
func (s *StateSelect[T, R]) ToLower(col string) ([]string, error)
ToLower returns the lowercase version of the specified column values. Example: names, err := db.Animal.Select().ToLower("name")
func (*StateSelect[T, R]) ToUpper ¶
func (s *StateSelect[T, R]) ToUpper(col string) ([]string, error)
ToUpper returns the uppercase version of the specified column values. Example: names, err := db.Animal.Select().ToUpper("name")
func (*StateSelect[T, R]) Where ¶
func (s *StateSelect[T, R]) Where(where string, args ...any) *StateSelect[T, R]
Where adds a WHERE clause to the select query.
type StateUpdate ¶
type StateUpdate[T any] struct { *StateWhere // contains filtered or unexported fields }
StateUpdate represents an UPDATE query state for modifying records in a table.
func (*StateUpdate[T]) Exec ¶
func (s *StateUpdate[T]) Exec() error
Exec executes the UPDATE query and returns any error.
Example:
change := Pair{Key:"name", Value:"John"}
err := db.User.Where("id = ?", 1).Update().Set(change).Exec()
func (*StateUpdate[T]) Filter ¶
func (s *StateUpdate[T]) Filter(args ...Condition) *StateUpdate[T]
Filter adds filter conditions to the UPDATE query.
func (*StateUpdate[T]) Join ¶
func (s *StateUpdate[T]) Join(joinType model.JoinType, info TableInfo, on Condition) *StateUpdate[T]
Join joins another table with a condition for UPDATE operations.
Example:
info := GetTableInfo(referAddr) err := db.User.Update().Join(model.InnerJoin, *info, EqualsField(...)).Set(...).Exec()
func (*StateUpdate[T]) LeftJoin ¶
func (s *StateUpdate[T]) LeftJoin(fkey string, refer *Field) *StateUpdate[T]
LeftJoin performs a LEFT JOIN with another table using a foreign key relationship.
Example:
refer := userTable.Field("role_id")
change := Pair{Key:"role_name", Value:"admin"}
err := db.User.Update().LeftJoin("role_id", refer).Set(change).Exec()
func (*StateUpdate[T]) Match ¶
func (s *StateUpdate[T]) Match(obj T) *StateUpdate[T]
Match sets the WHERE conditions based on the primary key and unique indexes of the given object.
func (*StateUpdate[T]) OnTransaction ¶
func (s *StateUpdate[T]) OnTransaction(tx model.Transaction) *StateUpdate[T]
OnTransaction executes the UPDATE query within a transaction.
func (*StateUpdate[T]) Set ¶
func (s *StateUpdate[T]) Set(pairs ...Pair) *StateUpdate[T]
Set sets the column values to update. Each pair is a key-value map.
Example:
changes := []Pair{
{Key:"name", Value:"John"},
{Key:"email", Value:"john@example.com"},
}
err := db.User.Where("id = ?", 1).Update().Set(changes...).Exec()
func (*StateUpdate[T]) SetMap ¶
func (s *StateUpdate[T]) SetMap(changes Dict) *StateUpdate[T]
SetMap sets multiple column values using a map.
Example:
changes := map[string]any{"name": "John", "email": "john@example.com"}
err := db.User.Where("id = ?", 1).Update().SetMap(changes).Exec()
func (*StateUpdate[T]) Take ¶
func (s *StateUpdate[T]) Take(i int) *StateUpdate[T]
Take limits the number of records to update.
Example:
change := Pair{Key:"status", Value:"archived"}
err := db.User.Update().Set(change).Take(100).Exec() // updates only 100 records
func (*StateUpdate[T]) Where ¶
func (s *StateUpdate[T]) Where(where string, args ...any) *StateUpdate[T]
Where adds a WHERE clause to the UPDATE query.
type StateWhere ¶
type StateWhere struct {
// contains filtered or unexported fields
}
StateWhere represents a query state with WHERE clause building capabilities.
func MatchWhere ¶
func MatchWhere[T any](s *StateWhere, table *Table[T], obj T) *StateWhere
MatchWhere creates a StateWhere with conditions matching the non-zero fields of the given object.
func NewStateWhere ¶
func NewStateWhere(ctx context.Context) *StateWhere
NewStateWhere creates a new StateWhere with the given context.
func (*StateWhere) Filter ¶
func (s *StateWhere) Filter(conds ...Condition) *StateWhere
func (*StateWhere) OnTransaction ¶
func (s *StateWhere) OnTransaction(tx model.Transaction) *StateWhere
func (*StateWhere) Where ¶
func (s *StateWhere) Where(where string, args ...any) *StateWhere
type Table ¶
type Table[T any] struct { Model *T Cache *utils.CoMap[int64, T] State *StateWhere TableInfo // contains filtered or unexported fields }
Table represents a database table with its model and metadata. It provides methods for querying, inserting, updating, and deleting records.
func SimpleTable ¶
SimpleTable creates a new Table instance for a simple table without foreign keys. It is useful for tables that do not have complex relationships with other tables.
Example:
type SimpleRecord struct {
ID int64
Name string
}
table := SimpleTable[SimpleRecord](db, "simple_record", "")
func (*Table[T]) Avg ¶
Avg returns the average value of the specified column across all rows. Example: avg, err := db.Animal.Avg("price")
func (*Table[T]) AvgFloat ¶
AvgFloat returns the average value of the specified column across all rows as float64. Example: avg, err := db.Animal.AvgFloat("price")
func (*Table[T]) CacheOne ¶
CacheOne caches a single row in the table's cache using its ID as the key.
func (*Table[T]) Count ¶
Count returns the count of all rows in the table. Example: count, err := db.Animal.Count("id")
func (*Table[T]) Delete ¶
func (t *Table[T]) Delete() *StateDelete[T]
Delete creates a new StateDelete for deleting records from the table.
Example:
err := db.User.Filter(goent.Equals("status", "deleted")).Delete().Exec()
func (*Table[T]) DeleteContext ¶
func (t *Table[T]) DeleteContext(ctx context.Context) *StateDelete[T]
DeleteContext creates a new StateDelete with a specific context.
func (*Table[T]) Dest ¶
Dest returns a new instance of T and a slice of destination pointers for scanning. The destination slice is sized to hold all columns.
func (*Table[T]) Drop ¶
Drop drops (deletes) the table from the database.
Example:
err := db.User.Drop()
if err != nil {
log.Fatal(err)
}
func (*Table[T]) Filter ¶
Filter adds filter conditions to the table's query using the default context.
Example:
users, err := db.User.Filter(goent.Equals("status", "active")).Select().All()
func (*Table[T]) FilterContext ¶
FilterContext adds filter conditions to the table's query with a specific context.
func (*Table[T]) Insert ¶
func (t *Table[T]) Insert() *StateInsert[T]
Insert creates a new StateInsert for inserting records into the table.
Example:
user := &User{Name: "John", Email: "john@example.com"}
err := db.User.Insert().One(user)
func (*Table[T]) InsertContext ¶
func (t *Table[T]) InsertContext(ctx context.Context) *StateInsert[T]
InsertContext creates a new StateInsert with a specific context.
func (*Table[T]) Max ¶
Max returns the maximum value of the specified column across all rows. Example: max, err := db.Animal.Max("id")
func (*Table[T]) MaxFloat ¶
MaxFloat returns the maximum value of the specified column across all rows as float64. Example: max, err := db.Animal.MaxFloat("price")
func (*Table[T]) Min ¶
Min returns the minimum value of the specified column across all rows. Example: min, err := db.Animal.Min("id")
func (*Table[T]) MinFloat ¶
MinFloat returns the minimum value of the specified column across all rows as float64. Example: min, err := db.Animal.MinFloat("price")
func (*Table[T]) Save ¶
Save creates a new StateSave for saving (insert or update) records to the table.
Example:
user := &User{ID: 1, Name: "John"} // ID > 0 means update
err := db.User.Save().One(user)
func (*Table[T]) SaveContext ¶
SaveContext creates a new StateSave with a specific context.
func (*Table[T]) Select ¶
func (t *Table[T]) Select(fields ...any) *StateSelect[T, T]
Select creates a new StateSelect for querying records from the table.
Example:
users, err := db.User.Select("id", "name", "email").All()
func (*Table[T]) SelectContext ¶
func (t *Table[T]) SelectContext(ctx context.Context, fields ...any) *StateSelect[T, T]
SelectContext creates a new StateSelect with a specific context.
func (*Table[T]) Sum ¶
Sum returns the sum of values in the specified column across all rows. Example: sum, err := db.Animal.Sum("price")
func (*Table[T]) SumFloat ¶
SumFloat returns the sum of values in the specified column across all rows as float64. Example: sum, err := db.Animal.SumFloat("price")
func (*Table[T]) ToLower ¶
ToLower returns the lowercase version of the specified column values across all rows. Example: names, err := db.Animal.ToLower("name")
func (*Table[T]) ToUpper ¶
ToUpper returns the uppercase version of the specified column values across all rows. Example: names, err := db.Animal.ToUpper("name")
func (*Table[T]) Update ¶
func (t *Table[T]) Update() *StateUpdate[T]
Update creates a new StateUpdate for updating records in the table.
Example:
change := goent.Pair{Key: "name", Value: "John"}
err := db.User.Filter(goent.Equals("status", "active")).Update().Set(change).Exec()
func (*Table[T]) UpdateContext ¶
func (t *Table[T]) UpdateContext(ctx context.Context) *StateUpdate[T]
UpdateContext creates a new StateUpdate with a specific context.
type TableInfo ¶
type TableInfo struct {
TableAddr uintptr // TableAddr is the unique address of the table type.
FieldName string // FieldName is the name of the field in the entity struct.
TableId int // TableId is the unique identifier for the table.
TableName string // TableName is the name of the table in the database schema.
SchemaId int // SchemaId is the unique identifier for the schema.
SchemaName string // SchemaName is the name of the schema in the database.
PrimaryKeys []*Index // PrimaryKeys is a list of primary key indexes.
Indexes []*Index // Indexes is a list of non-primary key indexes.
Columns map[string]*Column // Columns is a map of column names to Column metadata.
Foreigns map[string]*Foreign // Foreigns is a map of foreign key column names to Foreign metadata.
Ignores []string // Ignores is a list of column names to ignore.
// contains filtered or unexported fields
}
TableInfo contains metadata about a database table including columns, primary keys, and indexes. It is automatically populated when creating a Table using reflection.
func GetTableInfo ¶
GetTableInfo returns the table info for a given table address.
func NewTableReflect ¶
func NewTableReflect(db *DB, typeOf reflect.Type, addr uintptr, fieldName, schema string, schemaId, tableId int) (reflect.Value, TableInfo)
NewTableReflect creates a new Table instance using reflection. It analyzes the struct type to extract table metadata including columns, primary keys, and indexes.
Example:
value, info := NewTableReflect(db, reflect.TypeFor[User](), addr, "User", "", 0, 0) fmt.Println(info.TableName) // prints "user"
func (TableInfo) Check ¶
Check returns the field ID and whether the column exists in the table. It returns (-1, true) for wildcard (*) or simple tables.
func (TableInfo) ColumnInfo ¶
ColumnInfo returns the Column metadata for a given column name. It performs case-insensitive lookup.
func (TableInfo) Field ¶
Field returns a Field pointer for the specified column name. It panics if the column is not found in the table.
func (TableInfo) GetPrimaryInfo ¶
GetPrimaryInfo returns the primary key field ID, column name, and all primary key column names. It only returns valid field ID and column name for single-column primary keys.
func (TableInfo) GetSortedFields ¶
GetSortedFields returns the table's columns sorted by FieldId for SELECT queries. This ensures consistent column ordering between queries and struct fields. Example:
fields := table.GetSortedFields()
for _, field := range fields {
fmt.Println(field.ColumnName)
}
type TableMigration ¶
type TableMigration struct {
SchemaMigration
// contains filtered or unexported fields
}
TableMigration provides migration methods scoped to a specific table.
func (TableMigration) DropColumn ¶
func (m TableMigration) DropColumn(column string) error
func (TableMigration) DropTable ¶
func (m TableMigration) DropTable() error
func (TableMigration) RenameColumn ¶
func (m TableMigration) RenameColumn(column, newName string) error
func (TableMigration) RenameTable ¶
func (m TableMigration) RenameTable(newName string) error
func (TableMigration) SchemaTable ¶ added in v0.8.4
func (m TableMigration) SchemaTable() (schema, table string)
type ThirdParty ¶
ThirdParty represents an intermediate junction table for many-to-many relationships. It contains the table name and the left/right column mappings.
type Transaction ¶
type Transaction struct {
model.Transaction
}
Transaction wraps a database transaction and provides additional functionality.
func (Transaction) BeginTransaction ¶
func (t Transaction) BeginTransaction(txFunc func(Transaction) error) (err error)
BeginTransaction starts a nested transaction using a savepoint. Any panic or error will trigger a rollback of the savepoint.
Example:
err := tx.BeginTransaction(func(tx goent.Transaction) error {
user := &User{Name: "John"}
return goent.Insert(db.User).OnTransaction(tx).One(user)
})