db

package
v0.0.0-...-75e7317 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2024 License: MIT Imports: 19 Imported by: 0

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

func BindStruct(src any, target any) error

func Create

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

Create is a shortcut to mutation.Create

func CreateFromJSON

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

CreateFromJSON is a shortcut to mutation.CreateFromJSON

func Delete

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

Delete is a shortcut to mutation.Delete

func Exec

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

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

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

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"`
	Hooks              func() *Hooks `json:"-"`
}

func (*Config) Clone

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

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

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

type NoopClient struct{}

NoopClient implements the Client interface with no-op methods.

func (*NoopClient) Close

func (n *NoopClient) Close() error

func (*NoopClient) Commit

func (n *NoopClient) Commit() error

func (*NoopClient) Config

func (n *NoopClient) Config() *Config

func (*NoopClient) DB

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

func (*NoopClient) Dialect

func (n *NoopClient) Dialect() string

func (*NoopClient) Exec

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

func (*NoopClient) Hooks

func (n *NoopClient) Hooks() *Hooks

func (*NoopClient) IsTx

func (n *NoopClient) IsTx() bool

func (*NoopClient) Model

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

func (*NoopClient) Query

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

func (*NoopClient) Reload

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

func (*NoopClient) Rollback

func (n *NoopClient) Rollback() error

func (*NoopClient) SchemaBuilder

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

func (*NoopClient) Tx

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
	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

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

type PostDBDelete

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

type PostDBExec

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

type PostDBQuery

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

type PostDBUpdate

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

type PreDBCreate

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

Create hooks

type PreDBDelete

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

Delete hooks

type PreDBExec

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

Exec hooks

type PreDBQuery

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

Query hooks

type PreDBUpdate

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

Update hooks

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 CreatePredicatesFromFilterMap

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)

CreatePredicateFromFilterObject 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(field string, values []any, 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 NotIn

func NotIn(field string, values []any, 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

type Querier interface {
	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

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

func Builder

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

func (*QueryBuilder[T]) Count

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

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

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

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

Delete deletes entities from the database

func (*QueryBuilder[T]) First

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

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

Get returns the list of entities that match the query.

func (*QueryBuilder[T]) Limit

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

Limit sets the limit of the query.

func (*QueryBuilder[T]) Offset

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

Offset sets the offset of the query.

func (*QueryBuilder[T]) Only

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

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

Order sets the order of the query.

func (*QueryBuilder[T]) Select

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

Select sets the columns of the query.

func (*QueryBuilder[T]) Update

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

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

Where adds the given predicates to the builder.

type QueryOption

type QueryOption struct {
	// Model      Model        `json:"model"`
	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

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

WrappedClient implements the Client interface with a wrapped client.

func NewWrappedClient

func NewWrappedClient(client func() Client) *WrappedClient

func (*WrappedClient) Close

func (n *WrappedClient) Close() error

func (*WrappedClient) Commit

func (n *WrappedClient) Commit() error

func (*WrappedClient) Config

func (n *WrappedClient) Config() *Config

func (*WrappedClient) DB

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

func (*WrappedClient) Dialect

func (n *WrappedClient) Dialect() string

func (*WrappedClient) Exec

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

func (*WrappedClient) Hooks

func (n *WrappedClient) Hooks() *Hooks

func (*WrappedClient) IsTx

func (n *WrappedClient) IsTx() bool

func (*WrappedClient) Model

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

func (*WrappedClient) Query

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

func (*WrappedClient) Reload

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

func (*WrappedClient) Rollback

func (n *WrappedClient) Rollback() error

func (*WrappedClient) SchemaBuilder

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

func (*WrappedClient) Tx

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