db

package
v0.9.2 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2025 License: MIT Imports: 20 Imported by: 14

Documentation

Index

Constants

This section is empty.

Variables

View Source
var SupportDrivers = []string{"mysql", "pgx", "sqlite"}

SupportDrivers returns list of supported drivers.

Functions

func BindStruct added in v0.1.0

func BindStruct(src any, target any) error

func Create added in v0.1.0

func Create[T any](
	ctx context.Context,
	client Client,
	dataCreate any,
	schemas ...string,
) (T, error)

Create is a shortcut to mutation.Create

func CreateFromJSON added in v0.1.0

func CreateFromJSON[T any](
	ctx context.Context,
	client Client,
	json string,
	schemas ...string,
) (T, error)

CreateFromJSON is a shortcut to mutation.CreateFromJSON

func Delete added in v0.1.0

func Delete[T any](
	ctx context.Context,
	client Client,
	predicates []*Predicate,
	schemas ...string,
) (int, error)

Delete is a shortcut to mutation.Delete

func Exec added in v0.1.0

func Exec(ctx context.Context, client Client, query string, args ...any) (sql.Result, error)

func IsNotFound

func IsNotFound(err error) bool

func Query

func Query[T any](ctx context.Context, client Client, query string, args ...any) (ts []T, err error)

func Update added in v0.1.0

func Update[T any](
	ctx context.Context,
	client Client,
	dataUpdate any,
	predicates []*Predicate,
	schemas ...string,
) ([]T, error)

Update is a shortcut to mutation.Update

func WithTx added in v0.6.0

func WithTx(client Client, c context.Context, fn func(tx Client) error) (err error)

Types

type Client

type Client interface {
	Dialect() string
	// Exec executes a query that does not return records. For example, in SQL, INSERT or UPDATE.
	// It return a sql.Result and an error if any.
	Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
	// Query executes a query that returns rows, typically a SELECT in SQL.
	// It return a slice of *entity.Entity and an error if any.
	Query(ctx context.Context, query string, args ...any) ([]*entity.Entity, error)
	Rollback() error
	Commit() error
	Tx(ctx context.Context) (Client, error)
	IsTx() bool

	// Model return the model from given name.
	//
	//	Support finding model from name or types
	//	If the input model is a string, it will use the name to find the model
	//	Others, it will use the types of the input to find the model
	//
	//	entities: The entities that the model will be created from
	//  entities can be one of the following types:
	//		- []*entity.Entity: The first entity will be used to create the model
	//		- [][]byte: The first byte slice will be used to create the model by unmarshalling it
	Model(model any) (Model, error)
	Close() error
	SchemaBuilder() *schema.Builder
	Reload(
		ctx context.Context,
		newSchemaBuilder *schema.Builder,
		migration *Migration,
		disableForeignKeys bool,
		enableMigrations ...bool,
	) (Client, error)
	DB() *sql.DB
	Config() *Config
	Hooks() *Hooks
}

type Config added in v0.1.0

type Config struct {
	Driver             string        `json:"driver"`
	Name               string        `json:"name"`
	Host               string        `json:"host"`
	Port               string        `json:"port"`
	User               string        `json:"user"`
	Pass               string        `json:"pass"`
	Logger             logger.Logger `json:"-"`
	LogQueries         bool          `json:"log_queries"`
	MigrationDir       string        `json:"migration_dir"`
	IgnoreMigration    bool          `json:"ignore_migration"`
	DisableForeignKeys bool          `json:"disable_foreign_keys"`
	UseSoftDeletes     bool          `json:"use_soft_deletes"`
	Hooks              func() *Hooks `json:"-"`
}

func (*Config) Clone added in v0.1.0

func (c *Config) Clone() *Config

type Hooks

type Hooks struct {
	PreDBQuery   []PreDBQuery
	PostDBQuery  []PostDBQuery
	PreDBExec    []PreDBExec
	PostDBExec   []PostDBExec
	PreDBCreate  []PreDBCreate
	PostDBCreate []PostDBCreate
	PreDBUpdate  []PreDBUpdate
	PostDBUpdate []PostDBUpdate
	PreDBDelete  []PreDBDelete
	PostDBDelete []PostDBDelete
}

func (*Hooks) Clone added in v0.5.0

func (h *Hooks) Clone() *Hooks

type Migration

type Migration struct {
	Dir          string
	RenameTables []*RenameItem
	RenameFields []*RenameItem
}

type Model

type Model interface {
	Query(predicates ...*Predicate) Querier
	Mutation() Mutator
	Schema() *schema.Schema
	CreateFromJSON(ctx context.Context, json string) (id uint64, err error)
	Create(ctx context.Context, e *entity.Entity) (id uint64, err error)
	SetClient(client Client) Model
	Clone() Model
}

type Mutator added in v0.1.0

type Mutator interface {
	Where(predicates ...*Predicate) Mutator
	GetRelationEntityIDs(fieldName string, fieldValue any) ([]driver.Value, error)
	Create(ctx context.Context, e *entity.Entity) (id uint64, err error)
	Update(ctx context.Context, e *entity.Entity) (affected int, err error)
	Delete(ctx context.Context) (affected int, err error)
}

type NoopClient added in v0.6.0

type NoopClient struct{}

NoopClient implements the Client interface with no-op methods.

func (*NoopClient) Close added in v0.6.0

func (n *NoopClient) Close() error

func (*NoopClient) Commit added in v0.6.0

func (n *NoopClient) Commit() error

func (*NoopClient) Config added in v0.6.0

func (n *NoopClient) Config() *Config

func (*NoopClient) DB added in v0.6.0

func (n *NoopClient) DB() *sql.DB

func (*NoopClient) Dialect added in v0.6.0

func (n *NoopClient) Dialect() string

func (*NoopClient) Exec added in v0.6.0

func (n *NoopClient) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)

func (*NoopClient) Hooks added in v0.6.0

func (n *NoopClient) Hooks() *Hooks

func (*NoopClient) IsTx added in v0.6.0

func (n *NoopClient) IsTx() bool

func (*NoopClient) Model added in v0.6.0

func (n *NoopClient) Model(model any) (Model, error)

func (*NoopClient) Query added in v0.6.0

func (n *NoopClient) Query(ctx context.Context, query string, args ...any) ([]*entity.Entity, error)

func (*NoopClient) Reload added in v0.6.0

func (n *NoopClient) Reload(
	ctx context.Context,
	newSchemaBuilder *schema.Builder,
	migration *Migration,
	disableForeignKeys bool,
	enableMigrations ...bool,
) (Client, error)

func (*NoopClient) Rollback added in v0.6.0

func (n *NoopClient) Rollback() error

func (*NoopClient) SchemaBuilder added in v0.6.0

func (n *NoopClient) SchemaBuilder() *schema.Builder

func (*NoopClient) Tx added in v0.6.0

func (n *NoopClient) Tx(ctx context.Context) (Client, error)

type NotFoundError

type NotFoundError struct {
	Message string
}

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

type OperatorType

type OperatorType int

OperatorType is the type of the operator

const (
	OpInvalid OperatorType = iota
	OpEQ
	OpNEQ
	OpGT
	OpGTE
	OpLT
	OpLTE
	OpLike
	OpNotLike
	OpContains
	OpNotContains
	OpContainsFold
	OpNotContainsFold
	OpIN
	OpNIN
	OpNULL
)

func (OperatorType) MarshalJSON

func (t OperatorType) MarshalJSON() ([]byte, error)

MarshalJSON marshal an enum value to the quoted json string value

func (OperatorType) String

func (t OperatorType) String() string

String returns the string representation of a type.

func (*OperatorType) UnmarshalJSON

func (t *OperatorType) UnmarshalJSON(b []byte) error

UnmarshalJSON unmashals a quoted json string to the enum value

func (OperatorType) Valid

func (t OperatorType) Valid() bool

Valid reports if the given type if known type.

type PostDBCreate added in v0.3.0

type PostDBCreate = func(
	ctx context.Context,
	schema *schema.Schema,
	dataCreate *entity.Entity,
	id uint64,
) error

PostDBCreate is a hook that is called after a database create is executed.

type PostDBDelete added in v0.3.0

type PostDBDelete = func(
	ctx context.Context,
	schema *schema.Schema,
	predicates *[]*Predicate,
	originalEntities []*entity.Entity,
	affected int,
) error

PostDBDelete is a hook that is called after a database delete is executed.

type PostDBExec added in v0.5.0

type PostDBExec = func(
	ctx context.Context,
	option *QueryOption,
	result sql.Result,
) error

PostDBExec is a hook that is called after a database exec is executed.

type PostDBQuery added in v0.5.0

type PostDBQuery = func(
	ctx context.Context,
	option *QueryOption,
	entities []*entity.Entity,
) ([]*entity.Entity, error)

PostDBQuery is a hook that is called after a database query is executed.

type PostDBUpdate added in v0.3.0

type PostDBUpdate = func(
	ctx context.Context,
	schema *schema.Schema,
	predicates *[]*Predicate,
	updateData *entity.Entity,
	originalEntities []*entity.Entity,
	affected int,
) error

PostDBUpdate is a hook that is called after a database update is executed.

type PreDBCreate added in v0.5.0

type PreDBCreate = func(
	ctx context.Context,
	schema *schema.Schema,
	createData *entity.Entity,
) error

PreDBCreate is a hook that is called before a database create is executed.

type PreDBDelete added in v0.5.0

type PreDBDelete = func(
	ctx context.Context,
	schema *schema.Schema,
	predicates *[]*Predicate,
) error

PreDBDelete is a hook that is called before a database delete is executed.

type PreDBExec added in v0.5.0

type PreDBExec = func(
	ctx context.Context,
	option *QueryOption,
) error

PreDBExec is a hook that is called before a database exec is executed.

type PreDBQuery added in v0.5.0

type PreDBQuery = func(
	ctx context.Context,
	option *QueryOption,
) error

PreDBQuery is a hook that is called before a database query is executed.

type PreDBUpdate added in v0.5.0

type PreDBUpdate = func(
	ctx context.Context,
	schema *schema.Schema,
	predicates *[]*Predicate,
	updateData *entity.Entity,
) error

PreDBUpdate is a hook that is called before a database update is executed.

type Predicate

type Predicate struct {
	Field              string       `json:"field"`
	Operator           OperatorType `json:"operator"`
	Value              any          `json:"value"`
	RelationFieldNames []string     `json:"relationFieldNames"`
	And                []*Predicate `json:"and"`
	Or                 []*Predicate `json:"or"`
}

func And

func And(predicates ...*Predicate) *Predicate

func Contains added in v0.8.1

func Contains(field string, value string, relationFields ...string) *Predicate

func ContainsFold added in v0.8.1

func ContainsFold(field string, value string, relationFields ...string) *Predicate

func CreatePredicatesFromFilterMap added in v0.5.0

func CreatePredicatesFromFilterMap(
	sb *schema.Builder,
	s *schema.Schema,
	filterObject map[string]any,
) ([]*Predicate, error)

func CreatePredicatesFromFilterObject

func CreatePredicatesFromFilterObject(
	sb *schema.Builder,
	s *schema.Schema,
	filterObject string,
) ([]*Predicate, error)

CreatePredicatesFromFilterObject creates a predicate from a filter object A filter object is a JSON object that contains the filter for the query E.g.

{
	"approved": true,
	"status": "online",
	"name": {
		"$like": "test%",
		"$neq": "test2"
	},
	"age": {
		"$gt": 1,
		"$lt": 10
	},
	"$or": [
		{
			"age": 1
		},
		{
			"bio": {
				"$like": "test%",
				"$neq": "test2"
			}
		},
		{
			"status": "offline"
		},
		{
			"$and": [
				{
					"bio": {
						"$neq": "test",
						"$like": "%a"
					}
				},
				{
					"age": {
						"$gt": 1
					}
				}
			]
		}
	]
}

will be converted to "entgo.io/ent/dialect/sql" sql.And(

sql.EQ("approved", true),
sql.EQ("status", "online"),
sql.And(
	sql.Like("name", "test%"),
	sql.NEQ("name", "test2"),
),
sql.And(
	sql.GT("age", 1),
	sql.LT("age", 10),
),
sql.Or(
	sql.EQ("age", 1),
	sql.And(
		sql.Like("bio", "test%"),
		sql.NEQ("bio", "test2"),
	),
	sql.EQ("status", "offline"),
	sql.And(
		sql.NEQ("bio", "test"),
		sql.Like("bio", "%a"),
		sql.GT("age", 1),
	),
),

)

func EQ

func EQ(field string, value any, relationFields ...string) *Predicate

func GT

func GT(field string, value any, relationFields ...string) *Predicate

func GTE

func GTE(field string, value any, relationFields ...string) *Predicate

func In

func In[T any](field string, values []T, relationFields ...string) *Predicate

func IsFalse

func IsFalse(field string, relationFields ...string) *Predicate

func IsTrue

func IsTrue(field string, relationFields ...string) *Predicate

func LT

func LT(field string, value any, relationFields ...string) *Predicate

func LTE

func LTE(field string, value any, relationFields ...string) *Predicate

func Like

func Like(field string, value string, relationFields ...string) *Predicate

func NEQ

func NEQ(field string, value any, relationFields ...string) *Predicate

func NotContains added in v0.8.1

func NotContains(field string, value string, relationFields ...string) *Predicate

func NotContainsFold added in v0.8.1

func NotContainsFold(field string, value string, relationFields ...string) *Predicate

func NotIn

func NotIn[T any](field string, values []T, relationFields ...string) *Predicate

func NotLike added in v0.8.1

func NotLike(field string, value string, relationFields ...string) *Predicate

func Null

func Null(field string, value bool, relationFields ...string) *Predicate

func Or

func Or(predicates ...*Predicate) *Predicate

func (*Predicate) Clone

func (p *Predicate) Clone() *Predicate

type Querier added in v0.1.0

type Querier interface {
	// Find with soft-deleted records.
	WithTrashed() Querier
	// Find only soft-deleted records.
	OnlyTrashed() Querier
	Where(predicates ...*Predicate) Querier
	Limit(limit uint) Querier
	Offset(offset uint) Querier
	Select(columns ...string) Querier
	Order(order ...string) Querier
	Count(ctx context.Context, options ...*QueryOption) (int, error)
	Get(ctx context.Context) ([]*entity.Entity, error)
	First(ctx context.Context) (*entity.Entity, error)
	Only(ctx context.Context) (*entity.Entity, error)
	Options() *QueryOption
}

type QueryBuilder added in v0.5.0

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

func Builder added in v0.5.0

func Builder[T any](client Client, schemas ...string) *QueryBuilder[T]

func (*QueryBuilder[T]) Count added in v0.5.0

func (q *QueryBuilder[T]) Count(ctx context.Context, options ...*QueryOption) (int, error)

Count returns the number of entities that match the query.

func (*QueryBuilder[T]) Create added in v0.5.0

func (m *QueryBuilder[T]) Create(ctx context.Context, dataCreate any) (t T, err error)

Create creates a new entity and return the newly created entity

func (*QueryBuilder[T]) CreateFromJSON added in v0.5.0

func (m *QueryBuilder[T]) CreateFromJSON(ctx context.Context, json string) (t T, err error)

CreateFromJSON creates a new entity from JSON

func (*QueryBuilder[T]) Delete added in v0.5.0

func (m *QueryBuilder[T]) Delete(ctx context.Context) (affected int, err error)

Delete deletes entities from the database

func (*QueryBuilder[T]) First added in v0.5.0

func (q *QueryBuilder[T]) First(ctx context.Context) (t T, err error)

First returns the first entity that matches the query.

func (*QueryBuilder[T]) Get added in v0.5.0

func (q *QueryBuilder[T]) Get(ctx context.Context) ([]T, error)

Get returns the list of entities that match the query.

func (*QueryBuilder[T]) Limit added in v0.5.0

func (q *QueryBuilder[T]) Limit(limit uint) *QueryBuilder[T]

Limit sets the limit of the query.

func (*QueryBuilder[T]) Offset added in v0.5.0

func (q *QueryBuilder[T]) Offset(offset uint) *QueryBuilder[T]

Offset sets the offset of the query.

func (*QueryBuilder[T]) Only added in v0.5.0

func (q *QueryBuilder[T]) Only(ctx context.Context) (t T, err error)

Only returns the matched entity or an error if there is more than one.

func (*QueryBuilder[T]) Order added in v0.5.0

func (q *QueryBuilder[T]) Order(order ...string) *QueryBuilder[T]

Order sets the order of the query.

func (*QueryBuilder[T]) Select added in v0.5.0

func (q *QueryBuilder[T]) Select(fields ...string) *QueryBuilder[T]

Select sets the columns of the query.

func (*QueryBuilder[T]) Update added in v0.5.0

func (m *QueryBuilder[T]) Update(ctx context.Context, updateData any) (ts []T, err error)

Update updates the entity and returns the updated entities

func (*QueryBuilder[T]) Where added in v0.5.0

func (q *QueryBuilder[T]) Where(predicates ...*Predicate) *QueryBuilder[T]

Where adds the given predicates to the builder.

type QueryOption added in v0.1.0

type QueryOption struct {
	Schema     *schema.Schema `json:"schema"`
	Limit      uint           `json:"limit"`
	Offset     uint           `json:"offset"`
	Columns    *[]string      `json:"columns"`
	Order      []string       `json:"order"`
	Predicates *[]*Predicate  `json:"predicates"`
	Query      string         `json:"query"`
	Args       any            `json:"args"`
	// For count query
	Column string `json:"column"`
	Unique bool   `json:"unique"`
}

QueryOption is a struct that contains query options

Column and Unique are used for count query.

type RenameItem

type RenameItem struct {
	Type            string `json:"type"` // "column" or "table"
	From            string `json:"from"`
	To              string `json:"to"`
	IsJunctionTable bool   `json:"is_junction_table,omitempty"` // use in rename table: If the table is a junction table
	SchemaName      string `json:"schema,omitempty"`            // use in rename column: The schema name of the column
	SchemaNamespace string `json:"schema_namespace,omitempty"`  // use in rename column: The schema name of the column
}

type WrappedClient added in v0.6.0

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

WrappedClient implements the Client interface with a wrapped client.

func NewWrappedClient added in v0.6.0

func NewWrappedClient(client func() Client) *WrappedClient

func (*WrappedClient) Close added in v0.6.0

func (n *WrappedClient) Close() error

func (*WrappedClient) Commit added in v0.6.0

func (n *WrappedClient) Commit() error

func (*WrappedClient) Config added in v0.6.0

func (n *WrappedClient) Config() *Config

func (*WrappedClient) DB added in v0.6.0

func (n *WrappedClient) DB() *sql.DB

func (*WrappedClient) Dialect added in v0.6.0

func (n *WrappedClient) Dialect() string

func (*WrappedClient) Exec added in v0.6.0

func (n *WrappedClient) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)

func (*WrappedClient) Hooks added in v0.6.0

func (n *WrappedClient) Hooks() *Hooks

func (*WrappedClient) IsTx added in v0.6.0

func (n *WrappedClient) IsTx() bool

func (*WrappedClient) Model added in v0.6.0

func (n *WrappedClient) Model(model any) (Model, error)

func (*WrappedClient) Query added in v0.6.0

func (n *WrappedClient) Query(ctx context.Context, query string, args ...any) ([]*entity.Entity, error)

func (*WrappedClient) Reload added in v0.6.0

func (n *WrappedClient) Reload(
	ctx context.Context,
	newSchemaBuilder *schema.Builder,
	migration *Migration,
	disableForeignKeys bool,
	enableMigrations ...bool,
) (Client, error)

func (*WrappedClient) Rollback added in v0.6.0

func (n *WrappedClient) Rollback() error

func (*WrappedClient) SchemaBuilder added in v0.6.0

func (n *WrappedClient) SchemaBuilder() *schema.Builder

func (*WrappedClient) Tx added in v0.6.0

func (n *WrappedClient) Tx(ctx context.Context) (Client, error)

Jump to

Keyboard shortcuts

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