db

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2024 License: MIT Imports: 18 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 RawQuery added in v0.1.0

func RawQuery[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

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 *schema.Entity and an error if any.
	Query(ctx context.Context, query string, args any) ([]*schema.Entity, error)
	Rollback() error
	Commit() error
	CreateDBModel(s *schema.Schema, rs ...*schema.Relation) Model
	Tx(ctx context.Context) (Client, error)
	IsTx() bool
	Model(name string, types ...any) (Model, error)
	Close() error
	SchemaBuilder() *schema.Builder
	Reload(ctx context.Context, newSchemaBuilder *schema.Builder, migration *Migration) (Client, error)
	DB() *sql.DB
	Config() *Config
	Hooks() *Hooks
}

type Config added in v0.1.0

type Config struct {
	Driver          string
	Name            string
	Host            string
	Port            string
	User            string
	Pass            string
	Logger          logger.Logger
	LogQueries      bool
	MigrationDir    string
	IgnoreMigration bool
	Hooks           func() *Hooks
}

func (*Config) Clone added in v0.1.0

func (c *Config) Clone() *Config

type CountOption

type CountOption struct {
	Column string
	Unique bool
}

type DBMutation added in v0.1.0

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

func Mutation

func Mutation[T any](client Client, schemas ...string) *DBMutation[T]

Mutation is a helper function to create a new mutation for a given schema

The schema is inferred from the type of the entity
T must be a pointer to a struct or a struct type

func (*DBMutation[T]) Create added in v0.1.0

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

Create creates a new entity and return the newly created entity

func (*DBMutation[T]) CreateFromJSON added in v0.1.0

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

CreateFromJSON creates a new entity from JSON

func (*DBMutation[T]) Delete added in v0.1.0

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

Delete deletes entities from the database

func (*DBMutation[T]) Model added in v0.1.0

func (q *DBMutation[T]) Model() (Model, error)

Model returns the actual model of the mutation.

func (*DBMutation[T]) Update added in v0.1.0

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

Update updates the entity and returns the updated entities

func (*DBMutation[T]) Where added in v0.1.0

func (m *DBMutation[T]) Where(predicates ...*Predicate) *DBMutation[T]

Where adds a predicate to the mutation

type DBQuery added in v0.1.0

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

func Query

func Query[T any](client Client, schemas ...string) *DBQuery[T]

func (*DBQuery[T]) Count added in v0.1.0

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

Count returns the number of entities that match the query.

func (*DBQuery[T]) First added in v0.1.0

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

First returns the first entity that matches the query.

func (*DBQuery[T]) Get added in v0.1.0

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

Get returns the list of entities that match the query.

func (*DBQuery[T]) Limit added in v0.1.0

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

Limit sets the limit of the query.

func (*DBQuery[T]) Model added in v0.1.0

func (q *DBQuery[T]) Model() (Model, error)

Model returns the actual model of the query.

func (*DBQuery[T]) Offset added in v0.1.0

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

Offset sets the offset of the query.

func (*DBQuery[T]) Only added in v0.1.0

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

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

func (*DBQuery[T]) Order added in v0.1.0

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

Order sets the order of the query.

func (*DBQuery[T]) Select added in v0.1.0

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

Select sets the columns of the query.

func (*DBQuery[T]) Where added in v0.1.0

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

Where adds the given predicates to the query.

type Hooks

type Hooks struct {
	PostDBGet    []PostDBGet
	PostDBCreate []PostDBCreate
	PostDBUpdate []PostDBUpdate
	PostDBDelete []PostDBDelete
}

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 *schema.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 *schema.Entity) (id uint64, err error)
	Update(ctx context.Context, e *schema.Entity) (affected int, err error)
	Delete(ctx context.Context) (affected int, err 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 added in v0.3.0

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

type PostDBDelete added in v0.3.0

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

type PostDBGet added in v0.1.0

type PostDBGet = func(
	query *QueryOption,
	entities []*schema.Entity,
) ([]*schema.Entity, error)

type PostDBUpdate added in v0.3.0

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

type Predicate

type Predicate struct {
	Field              string
	Operator           OperatorType
	Value              any
	RelationFieldNames []string
	And                []*Predicate
	Or                 []*Predicate
}

func And

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

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 added in v0.1.0

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 *CountOption) (int, error)
	Get(ctx context.Context) ([]*schema.Entity, error)
	First(ctx context.Context) (*schema.Entity, error)
	Only(ctx context.Context) (*schema.Entity, error)
	Options() *QueryOption
}

type QueryOption added in v0.1.0

type QueryOption struct {
	Limit      uint         `json:"limit"`
	Offset     uint         `json:"offset"`
	Columns    []string     `json:"columns"`
	Order      []string     `json:"order"`
	Predicates []*Predicate `json:"predicates"`
	Model      Model        `json:"-"`
}

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
}

Jump to

Keyboard shortcuts

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