Documentation
¶
Index ¶
- Constants
- 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 FetchValue(target any) []any
- 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 Open[T any](drv model.Driver, logFile string) (*T, error)
- 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) IsInsertQuery() bool
- func (b *Builder) IsJoinQuery() bool
- func (b *Builder) ResetForSave()
- func (b *Builder) SetTable(table TableInfo, driver model.Driver) *Builder
- type Column
- 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 MatchFilter[T any](table *Table[T], obj T) 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 DeleteBuilder
- type Dict
- type Entity
- type FetchCreator
- type FetchFunc
- type Fetcher
- type Field
- type Foreign
- type ForeignType
- type GenScanFields
- type Group
- type Handler
- type Index
- type JoinTable
- type ManyToSomeRelation
- type Migration
- type NilMarker
- 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]) Take(i int) *StateDelete[T]
- func (s *StateDelete[T]) Where(where string, args ...any) *StateDelete[T]
- type StateDeleteWhere
- func (s *StateDeleteWhere) Filter(conds ...Condition) *StateDeleteWhere
- func (s *StateDeleteWhere) OnTransaction(tx model.Transaction) *StateDeleteWhere
- func (s *StateDeleteWhere) Prepare(drv model.Driver) (model.Connection, *model.DatabaseConfig)
- func (s *StateDeleteWhere) Where(where string, args ...any) *StateDeleteWhere
- type StateInsert
- type StateSave
- type StateSelect
- func (s *StateSelect[T, R]) All() (res []*R, err 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]) FetchRow(to FetchFunc) (*R, 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(to FetchFunc) 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() (obj *R, err 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]) 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 ¶
const TakeNoLimit = -1
TakeNoLimit is a constant indicating no limit on query results
Variables ¶
This section is empty.
Functions ¶
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 Close ¶
Close closes the database connection and cleans up the table registry It closes the underlying driver connection and resets the registry
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 It fetches multiple values from the query result 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 It fetches a single value from the query result Example: count, err := FetchSingleResult[int64](query)
func FetchValue ¶ added in v0.8.4
FetchValue returns a slice of pointers to the first field of the target struct.
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 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 // The type of query (SELECT, INSERT, UPDATE, DELETE)
Joins []*JoinTable // JOIN clauses for the query
InsertValues [][]any // Values for batch INSERT operations
VisitFields []*Field // Fields to select or insert
Changes map[*Field]any // Changes for UPDATE operations
Orders []*Order // ORDER BY clauses
Groups []*Group // GROUP BY clauses
Offset int // OFFSET clause value
Returning string // RETURNING clause for INSERT/UPDATE operations
RollUp string // ROLL UP clause for GROUP BY operations
ForUpdate bool // FOR UPDATE clause for transactional operations
DeleteBuilder // Embedded DeleteBuilder for DELETE operations
}
Builder builds SQL statements for SELECT, INSERT, UPDATE, and DELETE operations It handles complex query construction including joins, conditions, and pagination
func NewBuilder ¶ added in v0.8.4
func NewBuilder() *Builder
NewBuilder creates a new Builder instance It initializes the builder with default values and an empty changes map
func (*Builder) Build ¶
Build assembles the complete SQL query and returns it along with query arguments It builds all parts of the query including head, doing, joins, where, and tail
func (*Builder) BuildDoing ¶
BuildDoing builds the SET clause for UPDATE or VALUES clause for INSERT operations It processes the changes or values and returns the query arguments
func (*Builder) BuildHead ¶
BuildHead builds the SQL statement head for SELECT, INSERT, UPDATE, or DELETE operations It handles different query types and returns the initial query arguments
func (*Builder) BuildJoins ¶
BuildJoins builds the JOIN clauses for the query It processes all join tables and returns the query arguments
func (*Builder) BuildTail ¶
BuildTail builds the tail part of the query (GROUP BY, ORDER BY, LIMIT, OFFSET, RETURNING) It handles the trailing clauses for different query types
func (*Builder) IsInsertQuery ¶ added in v0.8.4
IsInsertQuery checks if the query is an insert query
func (*Builder) IsJoinQuery ¶ added in v0.8.4
IsJoinQuery checks if the query is a join query
func (*Builder) ResetForSave ¶
func (b *Builder) ResetForSave()
ResetForSave resets the Builder for INSERT/UPDATE operations It clears changes, insert values, visit fields, and other operation-specific settings
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 It contains information about the column's properties and mapping to Go struct fields
func GetTableColumn ¶
GetTableColumn returns the column info for a given table address and column name It looks up the column information from the table registry
type Condition ¶
type Condition struct {
Template string // SQL template with placeholders
Fields []*Field // Fields referenced in the condition
Values []*Value // Values to bind to the placeholders
}
Condition represents a SQL WHERE condition with a template and associated fields/values It is used to build WHERE clauses in queries
func And ¶
And combines multiple conditions with AND logic It creates a compound condition where all branches must be true
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 It generates an equality check, handling NULL values appropriately
Example: using Table with field name
goent.Equals(db.OrderDetail.Field("order_id"), 1)
func EqualsField ¶
EqualsField creates a condition that checks if one field is equal to another It generates an equality check between two fields
func EqualsMap ¶
EqualsMap creates a condition that checks if multiple fields equal specified values It generates AND conditions for each key-value pair in the 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 It allows for raw SQL conditions with placeholders
Example:
cond := goent.Expr("age > ? AND status = ?", 18, "active")
users, _ := db.User.Filter(cond).Select().All()
func Greater ¶
Greater creates a condition that checks if a field is greater than a value It generates a greater than comparison
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 creates a condition that checks if a field is greater than or equal to a value It generates a greater than or equal comparison
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 It generates a greater than or equal comparison between two fields
func GreaterField ¶
GreaterField creates a condition that checks if one field is greater than another It generates a greater than comparison between two fields
func ILike ¶
ILike creates a case-insensitive LIKE condition It generates an ILIKE clause for case-insensitive pattern matching
func In ¶
In creates a condition that checks if a field value is in a list of values It generates an IN clause for the field
func IsNotNull ¶
IsNotNull creates a condition that checks if a field is NOT NULL It generates an IS NOT NULL clause for the field
Example:
cond := goent.IsNotNull(db.User.Field("email"))
func IsNull ¶
IsNull creates a condition that checks if a field is NULL It generates an IS NULL clause for the field
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 It generates a less than comparison
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 It generates a less than or equal comparison
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 It generates a less than or equal comparison between two fields
func LessField ¶
LessField creates a condition that checks if one field is less than another It generates a less than comparison between two fields
func Like ¶
Like creates a condition that checks if a field matches a LIKE pattern It generates a LIKE clause for pattern matching
Example: get all animals that has a "at" in his name
goent.Like(db.Animal.Field("name"), "%at%")
func MatchFilter ¶ added in v0.8.4
MatchFilter generates a condition based on the non-zero fields of the given object It creates an EqualsMap condition from the object's non-zero fields
func Not ¶
Not creates a condition that negates another condition It wraps the condition in a NOT clause
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 It generates an inequality check, handling NULL values appropriately
Example:
cond := goent.NotEquals(db.User.Field("status"), "deleted")
func NotEqualsField ¶
NotEqualsField creates a condition that checks if one field is not equal to another It generates an inequality check between two fields
func NotILike ¶
NotILike creates a case-insensitive NOT LIKE condition It generates a NOT ILIKE clause for case-insensitive pattern matching
func NotIn ¶
NotIn creates a condition that checks if a field value is not in a list of values It generates a NOT IN clause for the field
func NotLike ¶
NotLike creates a condition that checks if a field does not match a LIKE pattern It generates a NOT LIKE clause for pattern matching
type DB ¶
type DB struct {
// contains filtered or unexported fields
}
DB represents a database connection with its driver It provides methods for executing queries and managing transactions
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 It 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.) It returns the name of the underlying driver
func (*DB) DropTables ¶ added in v0.8.2
DropTables drops all registered tables from the database It generates and executes DROP TABLE statements for all registered tables For PostgreSQL, it adds CASCADE to the DROP TABLE statement
func (*DB) NewTransaction ¶
func (db *DB) NewTransaction() (model.Transaction, error)
NewTransaction creates a new Transaction on the database using the default level It 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 It returns a transaction object that can be used for atomic operations
func (*DB) RawExecContext ¶
RawExecContext executes a raw SQL statement without returning rows It executes the provided SQL with the given arguments
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 It executes the provided SQL with the given arguments and returns the result set
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 DeleteBuilder ¶ added in v0.8.4
type DeleteBuilder struct {
Table *model.Table // The target table for the DELETE operation
Where Condition // The WHERE clause conditions
Limit int // The LIMIT clause value (only supported by SQLite)
// contains filtered or unexported fields
}
DeleteBuilder builds DELETE SQL statements It handles WHERE conditions and LIMIT clause for delete operations
func CreateDeleteBuilder ¶ added in v0.8.4
func CreateDeleteBuilder() DeleteBuilder
CreateDeleteBuilder creates a new DeleteBuilder instance It initializes the builder with no limit and a buffer from the pool
func NewDeleteBuilder ¶ added in v0.8.4
func NewDeleteBuilder() *DeleteBuilder
NewDeleteBuilder creates a new DeleteBuilder pointer It initializes the builder with default values
func (*DeleteBuilder) Build ¶ added in v0.8.4
func (b *DeleteBuilder) Build() (sql string, args []any)
Build assembles the complete DELETE SQL statement It builds the head, WHERE clause, and tail, then returns the SQL and arguments
func (*DeleteBuilder) BuildHead ¶ added in v0.8.4
func (b *DeleteBuilder) BuildHead() []any
BuildHead builds the DELETE statement head It writes "DELETE FROM table_name" to the buffer
func (*DeleteBuilder) BuildTail ¶ added in v0.8.4
func (b *DeleteBuilder) BuildTail() []any
BuildTail builds the DELETE statement tail It adds the LIMIT clause if specified
func (*DeleteBuilder) BuildWhere ¶ added in v0.8.4
func (b *DeleteBuilder) BuildWhere(full bool) []any
BuildWhere builds the WHERE clause for the DELETE statement It processes the conditions and returns the query arguments
func (*DeleteBuilder) SetTable ¶ added in v0.8.4
func (b *DeleteBuilder) SetTable(table TableInfo, driver model.Driver) *DeleteBuilder
SetTable sets the table for the DeleteBuilder It formats the full table name including schema using the driver
type Dict ¶
Dict is a type alias for a map of string keys to any values
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 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.
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)
}
type Field ¶
type Field struct {
TableAddr uintptr // Table address for table identification
FieldId int // Field ID for quick lookup
ColumnName string // Database column name
AliasName string // Alias name for the field
Function string // SQL function to apply to the field
}
Field represents a database field with its table reference and column name It is used to reference columns in queries and conditions
func (*Field) Func ¶
Func applies a SQL function to the field (e.g., "UPPER", "LOWER", "COUNT") It sets the function to be applied when the field is used in queries
Example:
field := goent.Expr("UPPER(name)").(*goent.Field)
users, _ := db.User.Filter(goent.Equals(field, "JOHN")).Select().All()
func (*Field) GetFid ¶
GetFid returns the field ID, resolving it from the table metadata if needed It looks up the field ID from the table registry if not already set
type Foreign ¶
type Foreign struct {
Type ForeignType // Type of foreign key relationship
MountField string // Field name where the related object is mounted
ForeignKey string // Foreign key column name
Reference *Field // Reference field in the related table
Middle *ThirdParty // Intermediate table for many-to-many relationships
Where Condition // WHERE clause for filtering
}
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 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) 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
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 It extends Column with index-specific properties
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 // Whether the relationship is the default one
// contains filtered or unexported fields
}
ManyToSomeRelation represents a many-to-one or many-to-many relationship between tables It extends attributeStrings with relationship-specific information
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 It is used to generate IS NULL conditions in WHERE clauses
type OneToSomeRelation ¶
type OneToSomeRelation struct {
IsOneToMany bool // Whether the relationship is one-to-many
// contains filtered or unexported fields
}
OneToSomeRelation represents a one-to-one or one-to-many relationship between tables It extends attributeStrings with relationship-specific information
type Pagination ¶
type Pagination[T, R any] struct { TotalValues int64 `json:"totalValues"` // Total number of values in the query result TotalPages int `json:"totalPages"` // Total number of pages in the pagination PageValues int `json:"pageValues"` // Number of values on the current page PageSize int `json:"pageSize"` // Maximum number of values per page CurrentPage int `json:"currentPage"` // Current page number HasPreviousPage bool `json:"hasPreviousPage"` // Whether there is a previous page PreviousPage int `json:"previousPage"` // Previous page number HasNextPage bool `json:"hasNextPage"` // Whether there is a next page NextPage int `json:"nextPage"` // Next page number StartIndex int `json:"startIndex"` // Index of the first value on the current page EndIndex int `json:"endIndex"` // Index of the last value on the current page Values []*R `json:"values"` // Slice of values on the current page }
Pagination holds paginated query results with metadata It provides information about total values, pages, and current page details
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 It is used to return single values from aggregate functions or scalar queries 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 { *StateDeleteWhere // Embedded StateDeleteWhere for WHERE clause construction // contains filtered or unexported fields }
StateDelete represents a DELETE query state for removing records from a table It provides methods for building and executing DELETE queries with various options
func (*StateDelete[T]) Exec ¶
func (s *StateDelete[T]) Exec() error
Exec executes the DELETE query It builds and runs the DELETE statement with the specified conditions
func (*StateDelete[T]) Filter ¶
func (s *StateDelete[T]) Filter(args ...Condition) *StateDelete[T]
Filter adds filter conditions to the DELETE query It appends the specified conditions to the WHERE clause
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 It automatically generates conditions for fields with non-zero values
func (*StateDelete[T]) OnTransaction ¶
func (s *StateDelete[T]) OnTransaction(tx model.Transaction) *StateDelete[T]
OnTransaction sets the transaction for the DELETE operation It ensures the delete runs within the specified transaction
func (*StateDelete[T]) Take ¶ added in v0.8.4
func (s *StateDelete[T]) Take(i int) *StateDelete[T]
Take limits the number of records to delete Note: PostgreSQL does not support LIMIT in DELETE statements
Example:
change := Pair{Key:"status", Value:"archived"}
err := db.Book.Delete().Take(1).Exec() // deletes only 1 record
func (*StateDelete[T]) Where ¶
func (s *StateDelete[T]) Where(where string, args ...any) *StateDelete[T]
Where adds a WHERE clause to the DELETE query It accepts a raw SQL WHERE clause with optional arguments
type StateDeleteWhere ¶ added in v0.8.4
type StateDeleteWhere struct {
// contains filtered or unexported fields
}
StateDeleteWhere represents a query state with WHERE clause building capabilities for DELETE queries It provides methods for constructing WHERE clauses specifically for DELETE operations
func MatchDeleteWhere ¶ added in v0.8.4
func MatchDeleteWhere[T any](s *StateDeleteWhere, table *Table[T], obj T) *StateDeleteWhere
MatchDeleteWhere creates a StateDeleteWhere with conditions matching the non-zero fields of the given object It generates conditions based on the object's non-zero fields
func NewStateDeleteWhere ¶ added in v0.8.4
func NewStateDeleteWhere(ctx context.Context) *StateDeleteWhere
NewStateDeleteWhere creates a new StateDeleteWhere with the given context It initializes the delete query builder and sets up the context
func (*StateDeleteWhere) Filter ¶ added in v0.8.4
func (s *StateDeleteWhere) Filter(conds ...Condition) *StateDeleteWhere
func (*StateDeleteWhere) OnTransaction ¶ added in v0.8.4
func (s *StateDeleteWhere) OnTransaction(tx model.Transaction) *StateDeleteWhere
func (*StateDeleteWhere) Prepare ¶ added in v0.8.4
func (s *StateDeleteWhere) Prepare(drv model.Driver) (model.Connection, *model.DatabaseConfig)
func (*StateDeleteWhere) Where ¶ added in v0.8.4
func (s *StateDeleteWhere) Where(where string, args ...any) *StateDeleteWhere
type StateInsert ¶
type StateInsert[T any] struct { *StateWhere // Embedded StateWhere for query context // contains filtered or unexported fields }
StateInsert represents an INSERT query state for inserting new records into a table It provides methods for inserting single and multiple records
func (*StateInsert[T]) All ¶
func (s *StateInsert[T]) All(retPK bool, data []*T) error
All inserts multiple records into the table It handles batch insertion and optionally returns auto-increment primary keys
func (*StateInsert[T]) OnTransaction ¶
func (s *StateInsert[T]) OnTransaction(tx model.Transaction) *StateInsert[T]
OnTransaction sets the transaction for the insert operation It ensures the insert runs within the specified transaction
func (*StateInsert[T]) One ¶
func (s *StateInsert[T]) One(obj *T) error
One inserts a single record into the table It handles auto-increment primary keys and returning values
type StateSave ¶
type StateSave[T any] struct { *StateWhere // Embedded StateWhere for query context // contains filtered or unexported fields }
func (*StateSave[T]) Map ¶
Map saves records from a map, inserting or updating based on primary key presence It extracts primary keys from the map to determine insert/update logic
func (*StateSave[T]) Match ¶
Match sets the WHERE conditions based on the non-zero fields of the given object It automatically generates conditions for fields with non-zero values
func (*StateSave[T]) OnTransaction ¶
func (s *StateSave[T]) OnTransaction(tx model.Transaction) *StateSave[T]
OnTransaction sets the transaction for the save operation It ensures the save runs within the specified transaction
type StateSelect ¶
type StateSelect[T, R any] struct { *StateWhere // Embedded StateWhere for WHERE clause construction // contains filtered or unexported fields }
StateSelect represents a SELECT query state with type parameters for table and result types It provides methods for building and executing SELECT queries with various options
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 It initializes the query state with the provided context and table
func NewStateSelectFrom ¶
func NewStateSelectFrom[T, R any](state *StateWhere, table *Table[T]) *StateSelect[T, R]
NewStateSelectFrom creates a new StateSelect from an existing StateWhere It sets up the query state for the specified table
func (*StateSelect[T, R]) All ¶
func (s *StateSelect[T, R]) All() (res []*R, err error)
All executes the query and returns all rows as a slice It pre-allocates the slice capacity if a limit is specified
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 It copies joins, conditions, orders, groups, limits, and offset
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]) FetchRow ¶ added in v0.8.4
func (s *StateSelect[T, R]) FetchRow(to FetchFunc) (*R, error)
FetchRow executes the query and returns a single row using the provided FetchFunc It handles the query execution and row scanning
func (*StateSelect[T, R]) Filter ¶
func (s *StateSelect[T, R]) Filter(args ...Condition) *StateSelect[T, R]
Filter adds filter conditions to the select query It appends the specified conditions to the WHERE clause
func (*StateSelect[T, R]) GetJoinForeign ¶
func (s *StateSelect[T, R]) GetJoinForeign() *Foreign
GetJoinForeign returns the foreign key relationship for the first joined table It looks up the foreign relationship in the table's foreign key registry
func (*StateSelect[T, R]) GetJoinForeigns ¶
func (s *StateSelect[T, R]) GetJoinForeigns() []*Foreign
GetJoinForeigns returns all foreign key relationships for the joined tables It looks up foreign relationships and creates them for joined tables
func (*StateSelect[T, R]) GroupBy ¶
func (s *StateSelect[T, R]) GroupBy(args ...string) *StateSelect[T, R]
GroupBy adds GROUP BY clauses to the query It groups results by the specified fields
func (*StateSelect[T, R]) IterRows ¶
func (s *StateSelect[T, R]) IterRows(to FetchFunc) iter.Seq2[*R, error]
IterRows returns an iterator over the query results It yields each row along with any error encountered
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 It adds a JOIN clause with the specified join type and condition
func (*StateSelect[T, R]) LeftJoin ¶
func (s *StateSelect[T, R]) LeftJoin(fkey string, refer *Field) *StateSelect[T, R]
LeftJoin performs a LEFT JOIN with another table It automatically adds the joined table's columns to the select list
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 The key must be an integer column that exists in the table
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 It automatically generates conditions for fields with non-zero values
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 It ensures the query runs within the specified transaction
func (*StateSelect[T, R]) One ¶
func (s *StateSelect[T, R]) One() (obj *R, err error)
One executes the query and returns the first row as a single result It automatically limits the query to one row for same-model queries
func (*StateSelect[T, R]) OrderBy ¶
func (s *StateSelect[T, R]) OrderBy(args ...string) *StateSelect[T, R]
OrderBy adds ORDER BY clauses to the query It accepts field names with optional DESC keyword for descending order
func (*StateSelect[T, R]) Pagination ¶
func (s *StateSelect[T, R]) Pagination(page, size int) (*Pagination[T, R], error)
Pagination returns a paginated query result It calculates total values, pages, and returns the current page data Default values for page and size are 1 and 10 respectively
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 Each key maps to a slice of results with that key value
func (*StateSelect[T, R]) RollUP ¶
func (s *StateSelect[T, R]) RollUP() *StateSelect[T, R]
RollUP enables rollup for aggregation queries It adds ROLL UP clause to GROUP BY operations
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 It accepts field names as strings or Field objects
func (*StateSelect[T, R]) Skip ¶
func (s *StateSelect[T, R]) Skip(i int) *StateSelect[T, R]
Skip skips the specified number of rows in the result It sets the OFFSET clause to the specified value
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 limits the number of rows returned by the query It sets the LIMIT clause to the specified value
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 It accepts a raw SQL WHERE clause with optional arguments
type StateUpdate ¶
type StateUpdate[T any] struct { *StateWhere // Embedded StateWhere for WHERE clause construction // contains filtered or unexported fields }
StateUpdate represents an UPDATE query state for modifying records in a table It provides methods for building and executing UPDATE queries with various options
func (*StateUpdate[T]) Exec ¶
func (s *StateUpdate[T]) Exec() error
Exec executes the UPDATE query and returns any error It builds and runs the UPDATE statement with the specified changes and conditions
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 It appends the specified conditions to the WHERE clause
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 It adds a JOIN clause to the UPDATE statement
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 It automatically creates the join condition based on the foreign key
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 It automatically generates conditions for fields with non-zero values
func (*StateUpdate[T]) OnTransaction ¶
func (s *StateUpdate[T]) OnTransaction(tx model.Transaction) *StateUpdate[T]
OnTransaction sets the transaction for the UPDATE operation It ensures the update runs within the specified 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 where key is the column name and value is the new value
Example:
changes := []Pair{
{Key:"name", Value:"John"},
{Key:"email", Value:"[email protected]"},
}
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 It updates columns based on the key-value pairs in the map
Example:
changes := map[string]any{"name": "John", "email": "[email protected]"}
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 Note: PostgreSQL does not support LIMIT in UPDATE statements
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 It accepts a raw SQL WHERE clause with optional arguments
type StateWhere ¶
type StateWhere struct {
// contains filtered or unexported fields
}
StateWhere represents a query state with WHERE clause building capabilities It provides methods for constructing WHERE clauses for various query types
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 It generates conditions based on the object's non-zero fields
func NewStateWhere ¶
func NewStateWhere(ctx context.Context) *StateWhere
NewStateWhere creates a new StateWhere with the given context It initializes the query builder and sets up the context
func (*StateWhere) Filter ¶
func (s *StateWhere) Filter(conds ...Condition) *StateWhere
func (*StateWhere) OnTransaction ¶
func (s *StateWhere) OnTransaction(tx model.Transaction) *StateWhere
func (*StateWhere) Prepare ¶
func (s *StateWhere) Prepare(drv model.Driver) (model.Connection, *model.DatabaseConfig)
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 StateDelete *StateDeleteWhere 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: "[email protected]"}
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.
ColumnNames []string // ColumnNames is a list of column names in the table.
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 It looks up the table information from the registry
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 ¶
type ThirdParty struct {
Table string // Junction table name
Left, Right string // Left and right column names
Where Condition // WHERE clause for filtering
}
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)
})