Documentation
¶
Index ¶
- Constants
- Variables
- func Asc(fields ...string) func(*sql.Selector)
- func DeleteBatchDocs(ctx context.Context, db *Client, ids []uuid.UUID) (int, error)
- func DeleteDoc(ctx context.Context, db *Client, id uuid.UUID) error
- func Desc(fields ...string) func(*sql.Selector)
- func DocCreateRequestTags() []string
- func DocOrder(r entapi.ListRequest) ([]doc.OrderOption, error)
- func DocPatchRequestTags() []string
- func IsConstraintError(err error) bool
- func IsNotFound(err error) bool
- func IsNotLoaded(err error) bool
- func IsNotSingular(err error) bool
- func IsValidationError(err error) bool
- func ListDocs(ctx context.Context, db *Client, f *DocFilter, r entapi.ListRequest) (*entapi.Page[DocResponse], error)
- func MaskNotFound(err error) error
- func NewContext(parent context.Context, c *Client) context.Context
- func NewTxContext(parent context.Context, tx *Tx) context.Context
- type APIHandler
- func (h *APIHandler) CreateDocEndpoint() entapi.Endpoint
- func (h *APIHandler) DeleteDocEndpoint() entapi.Endpoint
- func (h *APIHandler) Endpoints() []entapi.Endpoint
- func (h *APIHandler) GetDocEndpoint() entapi.Endpoint
- func (h *APIHandler) ListDocsEndpoint() entapi.Endpoint
- func (h *APIHandler) Mount(mux *http.ServeMux)
- func (h *APIHandler) OpenAPIEndpoint() entapi.Endpoint
- func (h *APIHandler) PatchDocEndpoint() entapi.Endpoint
- func (h *APIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (h *APIHandler) With(opts ...APIOption) *APIHandler
- type APIOption
- type AggregateFunc
- type Client
- func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
- func (c *Client) Close() error
- func (c *Client) Debug() *Client
- func (c *Client) Intercept(interceptors ...Interceptor)
- func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error)
- func (c *Client) Tx(ctx context.Context) (*Tx, error)
- func (c *Client) Use(hooks ...Hook)
- type CommitFunc
- type CommitHook
- type Committer
- type ConstraintError
- type CreateDocFn
- type DeleteDocFn
- type Doc
- type DocClient
- func (c *DocClient) Create() *DocCreate
- func (c *DocClient) CreateBulk(builders ...*DocCreate) *DocCreateBulk
- func (c *DocClient) Delete() *DocDelete
- func (c *DocClient) DeleteOne(d *Doc) *DocDeleteOne
- func (c *DocClient) DeleteOneID(id uuid.UUID) *DocDeleteOne
- func (c *DocClient) Get(ctx context.Context, id uuid.UUID) (*Doc, error)
- func (c *DocClient) GetX(ctx context.Context, id uuid.UUID) *Doc
- func (c *DocClient) Hooks() []Hook
- func (c *DocClient) Intercept(interceptors ...Interceptor)
- func (c *DocClient) Interceptors() []Interceptor
- func (c *DocClient) MapCreateBulk(slice any, setFunc func(*DocCreate, int)) *DocCreateBulk
- func (c *DocClient) Query() *DocQuery
- func (c *DocClient) Update() *DocUpdate
- func (c *DocClient) UpdateOne(d *Doc) *DocUpdateOne
- func (c *DocClient) UpdateOneID(id uuid.UUID) *DocUpdateOne
- func (c *DocClient) Use(hooks ...Hook)
- type DocCreate
- func (dc *DocCreate) Exec(ctx context.Context) error
- func (dc *DocCreate) ExecX(ctx context.Context)
- func (dc *DocCreate) Mutation() *DocMutation
- func (dc *DocCreate) Save(ctx context.Context) (*Doc, error)
- func (dc *DocCreate) SaveX(ctx context.Context) *Doc
- func (dc *DocCreate) SetCreatedAt(t time.Time) *DocCreate
- func (dc *DocCreate) SetID(u uuid.UUID) *DocCreate
- func (dc *DocCreate) SetNillableCreatedAt(t *time.Time) *DocCreate
- func (dc *DocCreate) SetNillableID(u *uuid.UUID) *DocCreate
- func (dc *DocCreate) SetNillableSource(s *string) *DocCreate
- func (dc *DocCreate) SetOrigin(s string) *DocCreate
- func (dc *DocCreate) SetSource(s string) *DocCreate
- func (dc *DocCreate) SetTitle(s string) *DocCreate
- type DocCreateBulk
- type DocCreateRequest
- type DocDelete
- type DocDeleteOne
- type DocFilter
- type DocGroupBy
- func (dgb *DocGroupBy) Aggregate(fns ...AggregateFunc) *DocGroupBy
- func (s *DocGroupBy) Bool(ctx context.Context) (_ bool, err error)
- func (s *DocGroupBy) BoolX(ctx context.Context) bool
- func (s *DocGroupBy) Bools(ctx context.Context) ([]bool, error)
- func (s *DocGroupBy) BoolsX(ctx context.Context) []bool
- func (s *DocGroupBy) Float64(ctx context.Context) (_ float64, err error)
- func (s *DocGroupBy) Float64X(ctx context.Context) float64
- func (s *DocGroupBy) Float64s(ctx context.Context) ([]float64, error)
- func (s *DocGroupBy) Float64sX(ctx context.Context) []float64
- func (s *DocGroupBy) Int(ctx context.Context) (_ int, err error)
- func (s *DocGroupBy) IntX(ctx context.Context) int
- func (s *DocGroupBy) Ints(ctx context.Context) ([]int, error)
- func (s *DocGroupBy) IntsX(ctx context.Context) []int
- func (dgb *DocGroupBy) Scan(ctx context.Context, v any) error
- func (s *DocGroupBy) ScanX(ctx context.Context, v any)
- func (s *DocGroupBy) String(ctx context.Context) (_ string, err error)
- func (s *DocGroupBy) StringX(ctx context.Context) string
- func (s *DocGroupBy) Strings(ctx context.Context) ([]string, error)
- func (s *DocGroupBy) StringsX(ctx context.Context) []string
- type DocListResponse
- type DocMutation
- func (m *DocMutation) AddField(name string, value ent.Value) error
- func (m *DocMutation) AddedEdges() []string
- func (m *DocMutation) AddedField(name string) (ent.Value, bool)
- func (m *DocMutation) AddedFields() []string
- func (m *DocMutation) AddedIDs(name string) []ent.Value
- func (m *DocMutation) ClearEdge(name string) error
- func (m *DocMutation) ClearField(name string) error
- func (m *DocMutation) ClearSource()
- func (m *DocMutation) ClearedEdges() []string
- func (m *DocMutation) ClearedFields() []string
- func (m DocMutation) Client() *Client
- func (m *DocMutation) CreatedAt() (r time.Time, exists bool)
- func (m *DocMutation) EdgeCleared(name string) bool
- func (m *DocMutation) Field(name string) (ent.Value, bool)
- func (m *DocMutation) FieldCleared(name string) bool
- func (m *DocMutation) Fields() []string
- func (m *DocMutation) ID() (id uuid.UUID, exists bool)
- func (m *DocMutation) IDs(ctx context.Context) ([]uuid.UUID, error)
- func (m *DocMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error)
- func (m *DocMutation) OldField(ctx context.Context, name string) (ent.Value, error)
- func (m *DocMutation) OldOrigin(ctx context.Context) (v string, err error)
- func (m *DocMutation) OldSource(ctx context.Context) (v string, err error)
- func (m *DocMutation) OldTitle(ctx context.Context) (v string, err error)
- func (m *DocMutation) Op() Op
- func (m *DocMutation) Origin() (r string, exists bool)
- func (m *DocMutation) RemovedEdges() []string
- func (m *DocMutation) RemovedIDs(name string) []ent.Value
- func (m *DocMutation) ResetCreatedAt()
- func (m *DocMutation) ResetEdge(name string) error
- func (m *DocMutation) ResetField(name string) error
- func (m *DocMutation) ResetOrigin()
- func (m *DocMutation) ResetSource()
- func (m *DocMutation) ResetTitle()
- func (m *DocMutation) SetCreatedAt(t time.Time)
- func (m *DocMutation) SetField(name string, value ent.Value) error
- func (m *DocMutation) SetID(id uuid.UUID)
- func (m *DocMutation) SetOp(op Op)
- func (m *DocMutation) SetOrigin(s string)
- func (m *DocMutation) SetSource(s string)
- func (m *DocMutation) SetTitle(s string)
- func (m *DocMutation) Source() (r string, exists bool)
- func (m *DocMutation) SourceCleared() bool
- func (m *DocMutation) Title() (r string, exists bool)
- func (m DocMutation) Tx() (*Tx, error)
- func (m *DocMutation) Type() string
- func (m *DocMutation) Where(ps ...predicate.Doc)
- func (m *DocMutation) WhereP(ps ...func(*sql.Selector))
- type DocPatchRequest
- type DocQuery
- func (dq *DocQuery) Aggregate(fns ...AggregateFunc) *DocSelect
- func (dq *DocQuery) All(ctx context.Context) ([]*Doc, error)
- func (dq *DocQuery) AllX(ctx context.Context) []*Doc
- func (dq *DocQuery) Clone() *DocQuery
- func (dq *DocQuery) Count(ctx context.Context) (int, error)
- func (dq *DocQuery) CountX(ctx context.Context) int
- func (dq *DocQuery) Exist(ctx context.Context) (bool, error)
- func (dq *DocQuery) ExistX(ctx context.Context) bool
- func (dq *DocQuery) First(ctx context.Context) (*Doc, error)
- func (dq *DocQuery) FirstID(ctx context.Context) (id uuid.UUID, err error)
- func (dq *DocQuery) FirstIDX(ctx context.Context) uuid.UUID
- func (dq *DocQuery) FirstX(ctx context.Context) *Doc
- func (dq *DocQuery) GroupBy(field string, fields ...string) *DocGroupBy
- func (dq *DocQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error)
- func (dq *DocQuery) IDsX(ctx context.Context) []uuid.UUID
- func (dq *DocQuery) Limit(limit int) *DocQuery
- func (dq *DocQuery) Offset(offset int) *DocQuery
- func (dq *DocQuery) Only(ctx context.Context) (*Doc, error)
- func (dq *DocQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error)
- func (dq *DocQuery) OnlyIDX(ctx context.Context) uuid.UUID
- func (dq *DocQuery) OnlyX(ctx context.Context) *Doc
- func (dq *DocQuery) Order(o ...doc.OrderOption) *DocQuery
- func (dq *DocQuery) Select(fields ...string) *DocSelect
- func (dq *DocQuery) Unique(unique bool) *DocQuery
- func (dq *DocQuery) Where(ps ...predicate.Doc) *DocQuery
- type DocResponse
- func CreateDoc(ctx context.Context, db *Client, v *ValidDocCreateRequest) (*DocResponse, error)
- func GetDoc(ctx context.Context, db *Client, id uuid.UUID) (*DocResponse, error)
- func NewDocResponse(e *Doc) (*DocResponse, error)
- func PatchDoc(ctx context.Context, db *Client, id uuid.UUID, v *ValidDocPatchRequest) (*DocResponse, error)
- type DocSelect
- func (ds *DocSelect) Aggregate(fns ...AggregateFunc) *DocSelect
- func (s *DocSelect) Bool(ctx context.Context) (_ bool, err error)
- func (s *DocSelect) BoolX(ctx context.Context) bool
- func (s *DocSelect) Bools(ctx context.Context) ([]bool, error)
- func (s *DocSelect) BoolsX(ctx context.Context) []bool
- func (s *DocSelect) Float64(ctx context.Context) (_ float64, err error)
- func (s *DocSelect) Float64X(ctx context.Context) float64
- func (s *DocSelect) Float64s(ctx context.Context) ([]float64, error)
- func (s *DocSelect) Float64sX(ctx context.Context) []float64
- func (s *DocSelect) Int(ctx context.Context) (_ int, err error)
- func (s *DocSelect) IntX(ctx context.Context) int
- func (s *DocSelect) Ints(ctx context.Context) ([]int, error)
- func (s *DocSelect) IntsX(ctx context.Context) []int
- func (ds *DocSelect) Scan(ctx context.Context, v any) error
- func (s *DocSelect) ScanX(ctx context.Context, v any)
- func (s *DocSelect) String(ctx context.Context) (_ string, err error)
- func (s *DocSelect) StringX(ctx context.Context) string
- func (s *DocSelect) Strings(ctx context.Context) ([]string, error)
- func (s *DocSelect) StringsX(ctx context.Context) []string
- type DocSummary
- type DocUpdate
- func (du *DocUpdate) Exec(ctx context.Context) error
- func (du *DocUpdate) ExecX(ctx context.Context)
- func (du *DocUpdate) Mutation() *DocMutation
- func (du *DocUpdate) Save(ctx context.Context) (int, error)
- func (du *DocUpdate) SaveX(ctx context.Context) int
- func (du *DocUpdate) SetNillableTitle(s *string) *DocUpdate
- func (du *DocUpdate) SetTitle(s string) *DocUpdate
- func (du *DocUpdate) Where(ps ...predicate.Doc) *DocUpdate
- type DocUpdateOne
- func (duo *DocUpdateOne) Exec(ctx context.Context) error
- func (duo *DocUpdateOne) ExecX(ctx context.Context)
- func (duo *DocUpdateOne) Mutation() *DocMutation
- func (duo *DocUpdateOne) Save(ctx context.Context) (*Doc, error)
- func (duo *DocUpdateOne) SaveX(ctx context.Context) *Doc
- func (duo *DocUpdateOne) Select(field string, fields ...string) *DocUpdateOne
- func (duo *DocUpdateOne) SetNillableTitle(s *string) *DocUpdateOne
- func (duo *DocUpdateOne) SetTitle(s string) *DocUpdateOne
- func (duo *DocUpdateOne) Where(ps ...predicate.Doc) *DocUpdateOne
- type Docs
- type GetDocFn
- type Hook
- type InterceptFunc
- type Interceptor
- type ListDocsFn
- type MutateFunc
- type Mutation
- type Mutator
- type NotFoundError
- type NotLoadedError
- type NotSingularError
- type Op
- type Option
- type OrderFunc
- type PatchDocFn
- type Policy
- type Querier
- type QuerierFunc
- type Query
- type QueryContext
- type RollbackFunc
- type RollbackHook
- type Rollbacker
- type TraverseFunc
- type Traverser
- type Tx
- type ValidDocCreateRequest
- type ValidDocPatchRequest
- type ValidationError
- type Value
Constants ¶
const ( // Operation types. OpCreate = ent.OpCreate OpDelete = ent.OpDelete OpDeleteOne = ent.OpDeleteOne OpUpdate = ent.OpUpdate OpUpdateOne = ent.OpUpdateOne // Node types. TypeDoc = "Doc" )
Variables ¶
var DocSortKeys = []string{
"id",
}
DocSortKeys is the complete sort allow-list. The primary key is naturally Sortable; every other key requires api.Sortable().
var ErrTxStarted = errors.New("immutableent: cannot start a transaction within a transaction")
ErrTxStarted is returned when trying to start a new transaction from a transactional client.
var ErrorMap = entapi.NewErrorMapper(IsNotFound, IsConstraintError). WithValidation(IsValidationError, func(err error) (string, bool) { var ve *ValidationError if errors.As(err, &ve) { return ve.Name, true } return "", false })
ErrorMap is the classifier every generated wiring function passes its error through before returning it.
One variable for the whole package, rather than a parameter on each operation. That is what makes entapi.IsNotFound answer the same way whichever function produced the error: a mapper threaded through as an argument would hold that property only for as long as every call site kept passing the same one, and there is no way to check that from here.
IsNotFound, IsConstraintError and IsValidationError are ent's own, generated into THIS package. The framework does not export them and cannot: ent generates NotFoundError and ConstraintError per project. That is why the runtime takes its classification as function values and never names an ent type — see entapi.ErrorMapper.
ValidationError is generated in this package too. The extractor keeps that type out of the stdlib-only runtime while preserving its field name for an RFC 9457 response.
API installs the runtime determination for the client's dialect unless the consumer already supplied one. ErrorMap is an ordinary package-level variable and carries no synchronisation of its own; configure overrides while building the client, before serving requests.
Functions ¶
func DeleteBatchDocs ¶
DeleteBatchDocs removes several Docs in one statement and returns how many rows it deleted.
The count is returned rather than discarded because ent computes it and the caller cannot recover it afterwards: a batch delete reports no error for an id that matched nothing, so "how many of the ids existed" is answerable here and nowhere else.
An empty list deletes nothing. That is ent's own reading of IDIn with no arguments, not a guard written here — a guard would be a second place for the rule to live, and the failure it protects against is unrecoverable.
An id that matched nothing is not an error here, so this operation never produces a not-found — but it can still fail a foreign-key check, which is exactly the case the mapping must NOT report as already-exists.
func DeleteDoc ¶
DeleteDoc removes one Doc.
No runtime routine is involved: ent's own builder is already the single line, and there is nothing to convert. What "delete" means for an entity with a soft-delete column is decided by an ent interceptor or mixin, not by a filename convention read out of the schema.
func DocCreateRequestTags ¶
func DocCreateRequestTags() []string
DocCreateRequestTags returns the canonical JSON key of every field on DocCreateRequest, in declaration order. Generated handlers compare raw request keys against this data to reject unknown keys.
Like Endpoints(), it returns a fresh copy on every call: slices are mutable, so exporting the variable would let any consumer mutate validation data that every generated handler in the process reads. The unexported variable remains the source of truth; this accessor is for consumers that decline the generated handler and write their own bind step.
func DocOrder ¶
func DocOrder(r entapi.ListRequest) ([]doc.OrderOption, error)
DocOrder is the single sort allow-list seam.
func DocPatchRequestTags ¶
func DocPatchRequestTags() []string
DocPatchRequestTags returns the canonical JSON key of every field on DocPatchRequest, in declaration order. Generated handlers compare raw request keys against this data to reject unknown keys.
Like Endpoints(), it returns a fresh copy on every call: slices are mutable, so exporting the variable would let any consumer mutate validation data that every generated handler in the process reads. The unexported variable remains the source of truth; this accessor is for consumers that decline the generated handler and write their own bind step.
func IsConstraintError ¶
IsConstraintError returns a boolean indicating whether the error is a constraint failure.
func IsNotFound ¶
IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotLoaded ¶
IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
func IsNotSingular ¶
IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsValidationError ¶
IsValidationError returns a boolean indicating whether the error is a validation error.
func ListDocs ¶
func ListDocs(ctx context.Context, db *Client, f *DocFilter, r entapi.ListRequest) (*entapi.Page[DocResponse], error)
ListDocs runs a filtered, ordered, paginated query.
This is the one operation whose body is not a single call, and the reason is worth stating rather than hiding: DocOrder can fail, because a sort key outside DocSortKeys has no correct answer and serving a differently-ordered page instead is worse than refusing. entapi.ListPage takes resolved order options, not a fallible producer of them, so the check happens here.
A nil filter contributes no predicates, so a caller with nothing to filter by does not need a branch of its own.
The sort-key failure returns before the mapping. It is already an entapi.ErrValidation and never reached the database, so there is nothing for a persistence-layer classifier to say about it.
func NewContext ¶
NewContext returns a new context with the given Client attached.
Types ¶
type APIHandler ¶
type APIHandler struct {
// contains filtered or unexported fields
}
APIHandler is the generated CRUD HTTP surface.
func API ¶
func API(client *Client) *APIHandler
API builds the generated CRUD HTTP surface for client.
func (*APIHandler) CreateDocEndpoint ¶
func (h *APIHandler) CreateDocEndpoint() entapi.Endpoint
CreateDocEndpoint returns the generated POST /docs endpoint.
func (*APIHandler) DeleteDocEndpoint ¶
func (h *APIHandler) DeleteDocEndpoint() entapi.Endpoint
DeleteDocEndpoint returns the generated DELETE /docs/{id} endpoint.
func (*APIHandler) Endpoints ¶
func (h *APIHandler) Endpoints() []entapi.Endpoint
Endpoints returns the generated endpoint manifest in deterministic registration order. It is data to compose into a router of your choosing; ServeHTTP and Mount are the convenience built from the same manifest.
It is the batch half of the composition surface. The per-operation accessors below are the take-one-by-name half: this slice is built by calling them, so the two cannot describe different endpoints, and every handler reads the current implementation through h, so a With after the call still takes effect. Endpoint values are not comparable; to skip or deduplicate rows, key on Method plus Path, or on Op. Except removes the method along with the endpoint, so naming an operation that is not exposed is a compile error.
func (*APIHandler) GetDocEndpoint ¶
func (h *APIHandler) GetDocEndpoint() entapi.Endpoint
GetDocEndpoint returns the generated GET /docs/{id} endpoint.
func (*APIHandler) ListDocsEndpoint ¶
func (h *APIHandler) ListDocsEndpoint() entapi.Endpoint
ListDocsEndpoint returns the generated GET /docs endpoint.
func (*APIHandler) Mount ¶
func (h *APIHandler) Mount(mux *http.ServeMux)
Mount registers every generated endpoint on mux.
func (*APIHandler) OpenAPIEndpoint ¶
func (h *APIHandler) OpenAPIEndpoint() entapi.Endpoint
OpenAPIEndpoint returns the generated GET /openapi.yaml endpoint serving the generated document. It is the manifest's one entry with no Entity and no Op: it describes the resource surface rather than belonging to it.
func (*APIHandler) PatchDocEndpoint ¶
func (h *APIHandler) PatchDocEndpoint() entapi.Endpoint
PatchDocEndpoint returns the generated PATCH /docs/{id} endpoint.
func (*APIHandler) ServeHTTP ¶
func (h *APIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves every generated endpoint through the internal mux.
func (*APIHandler) With ¶
func (h *APIHandler) With(opts ...APIOption) *APIHandler
With replaces generated operation implementations before serving begins.
type APIOption ¶
type APIOption interface {
// contains filtered or unexported methods
}
APIOption replaces one generated operation implementation.
type AggregateFunc ¶
AggregateFunc applies an aggregation step on the group-by traversal/selector.
func As ¶
func As(fn AggregateFunc, end string) AggregateFunc
As is a pseudo aggregation function for renaming another other functions with custom names. For example:
GroupBy(field1, field2). Aggregate(immutableent.As(immutableent.Sum(field1), "sum_field1"), (immutableent.As(immutableent.Sum(field2), "sum_field2")). Scan(ctx, &v)
func Count ¶
func Count() AggregateFunc
Count applies the "count" aggregation function on each group.
func Max ¶
func Max(field string) AggregateFunc
Max applies the "max" aggregation function on the given field of each group.
func Mean ¶
func Mean(field string) AggregateFunc
Mean applies the "mean" aggregation function on the given field of each group.
func Min ¶
func Min(field string) AggregateFunc
Min applies the "min" aggregation function on the given field of each group.
func Sum ¶
func Sum(field string) AggregateFunc
Sum applies the "sum" aggregation function on the given field of each group.
type Client ¶
type Client struct {
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Doc is the client for interacting with the Doc builders.
Doc *DocClient
// contains filtered or unexported fields
}
Client is the client that holds all ent builders.
func FromContext ¶
FromContext returns a Client stored inside a context, or nil if there isn't one.
func Open ¶
Open opens a database/sql.DB specified by the driver name and the data source name, and returns a new client attached to it. Optional parameters can be added for configuring the client.
func (*Client) Debug ¶
Debug returns a new debug-client. It's used to get verbose logging on specific operations.
client.Debug(). Doc. Query(). Count(ctx)
func (*Client) Intercept ¶
func (c *Client) Intercept(interceptors ...Interceptor)
Intercept adds the query interceptors to all the entity clients. In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
type CommitFunc ¶
The CommitFunc type is an adapter to allow the use of ordinary function as a Committer. If f is a function with the appropriate signature, CommitFunc(f) is a Committer that calls f.
type CommitHook ¶
CommitHook defines the "commit middleware". A function that gets a Committer and returns a Committer. For example:
hook := func(next ent.Committer) ent.Committer {
return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
// Do some stuff before.
if err := next.Commit(ctx, tx); err != nil {
return err
}
// Do some stuff after.
return nil
})
}
type ConstraintError ¶
type ConstraintError struct {
// contains filtered or unexported fields
}
ConstraintError returns when trying to create/update one or more entities and one or more of their constraints failed. For example, violation of edge or field uniqueness.
func (ConstraintError) Error ¶
func (e ConstraintError) Error() string
Error implements the error interface.
func (*ConstraintError) Unwrap ¶
func (e *ConstraintError) Unwrap() error
Unwrap implements the errors.Wrapper interface.
type CreateDocFn ¶
type CreateDocFn func(context.Context, *Client, *ValidDocCreateRequest) (*DocResponse, error)
CreateDocFn is byte-identical to CreateDoc.
type DeleteDocFn ¶
DeleteDocFn is byte-identical to DeleteDoc.
type Doc ¶
type Doc struct {
// ID of the ent.
ID uuid.UUID `json:"id,omitempty"`
// Title holds the value of the "title" field.
Title string `json:"title,omitempty"`
// Origin holds the value of the "origin" field.
Origin string `json:"origin,omitempty"`
// Source holds the value of the "source" field.
Source string `json:"source,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// contains filtered or unexported fields
}
Doc is the model entity for the Doc schema.
func (*Doc) Unwrap ¶
Unwrap unwraps the Doc entity that was returned from a transaction after it was closed, so that all future queries will be executed through the driver which created the transaction.
func (*Doc) Update ¶
func (d *Doc) Update() *DocUpdateOne
Update returns a builder for updating this Doc. Note that you need to call Doc.Unwrap() before calling this method if this Doc was returned from a transaction, and the transaction was committed or rolled back.
type DocClient ¶
type DocClient struct {
// contains filtered or unexported fields
}
DocClient is a client for the Doc schema.
func NewDocClient ¶
func NewDocClient(c config) *DocClient
NewDocClient returns a client for the Doc from the given config.
func (*DocClient) CreateBulk ¶
func (c *DocClient) CreateBulk(builders ...*DocCreate) *DocCreateBulk
CreateBulk returns a builder for creating a bulk of Doc entities.
func (*DocClient) DeleteOne ¶
func (c *DocClient) DeleteOne(d *Doc) *DocDeleteOne
DeleteOne returns a builder for deleting the given entity.
func (*DocClient) DeleteOneID ¶
func (c *DocClient) DeleteOneID(id uuid.UUID) *DocDeleteOne
DeleteOneID returns a builder for deleting the given entity by its id.
func (*DocClient) Intercept ¶
func (c *DocClient) Intercept(interceptors ...Interceptor)
Intercept adds a list of query interceptors to the interceptors stack. A call to `Intercept(f, g, h)` equals to `doc.Intercept(f(g(h())))`.
func (*DocClient) Interceptors ¶
func (c *DocClient) Interceptors() []Interceptor
Interceptors returns the client interceptors.
func (*DocClient) MapCreateBulk ¶
func (c *DocClient) MapCreateBulk(slice any, setFunc func(*DocCreate, int)) *DocCreateBulk
MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates a builder and applies setFunc on it.
func (*DocClient) UpdateOne ¶
func (c *DocClient) UpdateOne(d *Doc) *DocUpdateOne
UpdateOne returns an update builder for the given entity.
func (*DocClient) UpdateOneID ¶
func (c *DocClient) UpdateOneID(id uuid.UUID) *DocUpdateOne
UpdateOneID returns an update builder for the given id.
type DocCreate ¶
type DocCreate struct {
// contains filtered or unexported fields
}
DocCreate is the builder for creating a Doc entity.
func (*DocCreate) Mutation ¶
func (dc *DocCreate) Mutation() *DocMutation
Mutation returns the DocMutation object of the builder.
func (*DocCreate) SetCreatedAt ¶
SetCreatedAt sets the "created_at" field.
func (*DocCreate) SetNillableCreatedAt ¶
SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (*DocCreate) SetNillableID ¶
SetNillableID sets the "id" field if the given value is not nil.
func (*DocCreate) SetNillableSource ¶
SetNillableSource sets the "source" field if the given value is not nil.
type DocCreateBulk ¶
type DocCreateBulk struct {
// contains filtered or unexported fields
}
DocCreateBulk is the builder for creating many Doc entities in bulk.
func (*DocCreateBulk) Exec ¶
func (dcb *DocCreateBulk) Exec(ctx context.Context) error
Exec executes the query.
func (*DocCreateBulk) ExecX ¶
func (dcb *DocCreateBulk) ExecX(ctx context.Context)
ExecX is like Exec, but panics if an error occurs.
type DocCreateRequest ¶
type DocCreateRequest struct {
Title string `json:"title"`
Origin string `json:"origin"`
Source *string `json:"source,omitempty"`
// contains filtered or unexported fields
}
DocCreateRequest is the create request for Doc.
Field shape follows ent's schema rather than a parallel set of booleans. A field ent can fill by itself — Optional, or carrying a Default() — is a pointer here and is written to the builder only when the caller supplied a value, so an omitted key leaves the schema's default in effect. A field ent requires and cannot default is a value type and is always written.
func (*DocCreateRequest) HasOrigin ¶
func (r *DocCreateRequest) HasOrigin() bool
HasOrigin reports whether the payload carried "origin".
func (*DocCreateRequest) HasSource ¶
func (r *DocCreateRequest) HasSource() bool
HasSource reports whether the payload carried "source".
func (*DocCreateRequest) HasTitle ¶
func (r *DocCreateRequest) HasTitle() bool
HasTitle reports whether the payload carried "title".
func (*DocCreateRequest) UnmarshalJSON ¶
func (r *DocCreateRequest) UnmarshalJSON(b []byte) error
UnmarshalJSON records presence, then decodes normally.
The wire format is unchanged: every exported field keeps its ordinary type and tag, so marshalling, form binders, validators and spec generators all see the struct they saw before. That is the property a generic Optional[T] wrapper could not keep.
A key that case-folds to a canonical tag without matching it exactly is rejected (#58, ADR-0001): encoding/json would fill the field from it while presence — recorded by raw key — would not, so the value decoded and then went unwritten. The check runs after raw decodes and BEFORE the alias decode, so a rejected request leaves the receiver untouched. A key that folds to no tag keeps its old behaviour and is ignored; refusing those is DisallowUnknownFields, which stays the consumer handler's decision.
func (*DocCreateRequest) Validate ¶
func (r *DocCreateRequest) Validate() (*ValidDocCreateRequest, error)
Validate checks the request and returns the only type Apply accepts.
type DocDelete ¶
type DocDelete struct {
// contains filtered or unexported fields
}
DocDelete is the builder for deleting a Doc entity.
func (*DocDelete) Exec ¶
Exec executes the deletion query and returns how many vertices were deleted.
type DocDeleteOne ¶
type DocDeleteOne struct {
// contains filtered or unexported fields
}
DocDeleteOne is the builder for deleting a single Doc entity.
func (*DocDeleteOne) Exec ¶
func (ddo *DocDeleteOne) Exec(ctx context.Context) error
Exec executes the deletion query.
func (*DocDeleteOne) ExecX ¶
func (ddo *DocDeleteOne) ExecX(ctx context.Context)
ExecX is like Exec, but panics if an error occurs.
func (*DocDeleteOne) Where ¶
func (ddo *DocDeleteOne) Where(ps ...predicate.Doc) *DocDeleteOne
Where appends a list predicates to the DocDelete builder.
type DocFilter ¶
type DocFilter struct {
// id: uuid.UUID
ID []uuid.UUID `json:"id,omitempty"`
IDNEQ []uuid.UUID `json:"id_neq,omitempty"`
IDIn [][]uuid.UUID `json:"id_in,omitempty"`
IDNotIn [][]uuid.UUID `json:"id_not_in,omitempty"`
IDGT []uuid.UUID `json:"id_gt,omitempty"`
IDGTE []uuid.UUID `json:"id_gte,omitempty"`
IDLT []uuid.UUID `json:"id_lt,omitempty"`
IDLTE []uuid.UUID `json:"id_lte,omitempty"`
}
DocFilter is the typed query representation for Doc. Repeated URL parameters occupy repeated slots and Predicates ANDs them.
func ParseDocQuery ¶
ParseDocQuery parses the complete URL query contract in sorted-key order. Runtime code owns lexical grammar; the generated operator tables own the field-local operator set, conversion and predicate slots.
func (*DocFilter) Predicates ¶
Predicates converts the typed filter into conjunctive ent predicates.
type DocGroupBy ¶
type DocGroupBy struct {
// contains filtered or unexported fields
}
DocGroupBy is the group-by builder for Doc entities.
func (*DocGroupBy) Aggregate ¶
func (dgb *DocGroupBy) Aggregate(fns ...AggregateFunc) *DocGroupBy
Aggregate adds the given aggregation functions to the group-by query.
func (*DocGroupBy) Bool ¶
Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (*DocGroupBy) Bools ¶
Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (*DocGroupBy) Float64 ¶
Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (*DocGroupBy) Float64s ¶
Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (*DocGroupBy) Int ¶
Int returns a single int from a selector. It is only allowed when selecting one field.
func (*DocGroupBy) Ints ¶
Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (*DocGroupBy) Scan ¶
func (dgb *DocGroupBy) Scan(ctx context.Context, v any) error
Scan applies the selector query and scans the result into the given value.
func (*DocGroupBy) String ¶
String returns a single string from a selector. It is only allowed when selecting one field.
type DocListResponse ¶
type DocListResponse struct {
Data []*DocResponse `json:"data"`
Total int `json:"total"`
Page int `json:"page"`
Size int `json:"size"`
}
DocListResponse is the NAMED, non-generic shape of one list page — for OpenAPI/swaggo-class annotation tooling, which cannot express the generic entapi.Page[DocResponse] that ListDocs returns. Convert at the handler boundary with NewDocListResponse. (A fifth field, PageInfo, carried cursor metadata until #6 removed it.)
func NewDocListResponse ¶
func NewDocListResponse(p *entapi.Page[DocResponse]) *DocListResponse
NewDocListResponse converts the page ListDocs returns into the named list shape. The conversion expression is the shape contract: if DocListResponse and entapi.Page ever diverge in field set, type or order, this line stops compiling in every generated package. JSON tags are outside what a conversion checks; the wire-format golden test in the basic fixture guards those.
type DocMutation ¶
type DocMutation struct {
// contains filtered or unexported fields
}
DocMutation represents an operation that mutates the Doc nodes in the graph.
func (*DocMutation) AddField ¶
func (m *DocMutation) AddField(name string, value ent.Value) error
AddField adds the value to the field with the given name. It returns an error if the field is not defined in the schema, or if the type mismatched the field type.
func (*DocMutation) AddedEdges ¶
func (m *DocMutation) AddedEdges() []string
AddedEdges returns all edge names that were set/added in this mutation.
func (*DocMutation) AddedField ¶
func (m *DocMutation) AddedField(name string) (ent.Value, bool)
AddedField returns the numeric value that was incremented/decremented on a field with the given name. The second boolean return value indicates that this field was not set, or was not defined in the schema.
func (*DocMutation) AddedFields ¶
func (m *DocMutation) AddedFields() []string
AddedFields returns all numeric fields that were incremented/decremented during this mutation.
func (*DocMutation) AddedIDs ¶
func (m *DocMutation) AddedIDs(name string) []ent.Value
AddedIDs returns all IDs (to other nodes) that were added for the given edge name in this mutation.
func (*DocMutation) ClearEdge ¶
func (m *DocMutation) ClearEdge(name string) error
ClearEdge clears the value of the edge with the given name. It returns an error if that edge is not defined in the schema.
func (*DocMutation) ClearField ¶
func (m *DocMutation) ClearField(name string) error
ClearField clears the value of the field with the given name. It returns an error if the field is not defined in the schema.
func (*DocMutation) ClearSource ¶
func (m *DocMutation) ClearSource()
ClearSource clears the value of the "source" field.
func (*DocMutation) ClearedEdges ¶
func (m *DocMutation) ClearedEdges() []string
ClearedEdges returns all edge names that were cleared in this mutation.
func (*DocMutation) ClearedFields ¶
func (m *DocMutation) ClearedFields() []string
ClearedFields returns all nullable fields that were cleared during this mutation.
func (DocMutation) Client ¶
func (m DocMutation) Client() *Client
Client returns a new `ent.Client` from the mutation. If the mutation was executed in a transaction (ent.Tx), a transactional client is returned.
func (*DocMutation) CreatedAt ¶
func (m *DocMutation) CreatedAt() (r time.Time, exists bool)
CreatedAt returns the value of the "created_at" field in the mutation.
func (*DocMutation) EdgeCleared ¶
func (m *DocMutation) EdgeCleared(name string) bool
EdgeCleared returns a boolean which indicates if the edge with the given name was cleared in this mutation.
func (*DocMutation) Field ¶
func (m *DocMutation) Field(name string) (ent.Value, bool)
Field returns the value of a field with the given name. The second boolean return value indicates that this field was not set, or was not defined in the schema.
func (*DocMutation) FieldCleared ¶
func (m *DocMutation) FieldCleared(name string) bool
FieldCleared returns a boolean indicating if a field with the given name was cleared in this mutation.
func (*DocMutation) Fields ¶
func (m *DocMutation) Fields() []string
Fields returns all fields that were changed during this mutation. Note that in order to get all numeric fields that were incremented/decremented, call AddedFields().
func (*DocMutation) ID ¶
func (m *DocMutation) ID() (id uuid.UUID, exists bool)
ID returns the ID value in the mutation. Note that the ID is only available if it was provided to the builder or after it was returned from the database.
func (*DocMutation) IDs ¶
IDs queries the database and returns the entity ids that match the mutation's predicate. That means, if the mutation is applied within a transaction with an isolation level such as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated or updated by the mutation.
func (*DocMutation) OldCreatedAt ¶
OldCreatedAt returns the old "created_at" field's value of the Doc entity. If the Doc object wasn't provided to the builder, the object is fetched from the database. An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (*DocMutation) OldField ¶
OldField returns the old value of the field from the database. An error is returned if the mutation operation is not UpdateOne, or the query to the database failed.
func (*DocMutation) OldOrigin ¶
func (m *DocMutation) OldOrigin(ctx context.Context) (v string, err error)
OldOrigin returns the old "origin" field's value of the Doc entity. If the Doc object wasn't provided to the builder, the object is fetched from the database. An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (*DocMutation) OldSource ¶
func (m *DocMutation) OldSource(ctx context.Context) (v string, err error)
OldSource returns the old "source" field's value of the Doc entity. If the Doc object wasn't provided to the builder, the object is fetched from the database. An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (*DocMutation) OldTitle ¶
func (m *DocMutation) OldTitle(ctx context.Context) (v string, err error)
OldTitle returns the old "title" field's value of the Doc entity. If the Doc object wasn't provided to the builder, the object is fetched from the database. An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (*DocMutation) Origin ¶
func (m *DocMutation) Origin() (r string, exists bool)
Origin returns the value of the "origin" field in the mutation.
func (*DocMutation) RemovedEdges ¶
func (m *DocMutation) RemovedEdges() []string
RemovedEdges returns all edge names that were removed in this mutation.
func (*DocMutation) RemovedIDs ¶
func (m *DocMutation) RemovedIDs(name string) []ent.Value
RemovedIDs returns all IDs (to other nodes) that were removed for the edge with the given name in this mutation.
func (*DocMutation) ResetCreatedAt ¶
func (m *DocMutation) ResetCreatedAt()
ResetCreatedAt resets all changes to the "created_at" field.
func (*DocMutation) ResetEdge ¶
func (m *DocMutation) ResetEdge(name string) error
ResetEdge resets all changes to the edge with the given name in this mutation. It returns an error if the edge is not defined in the schema.
func (*DocMutation) ResetField ¶
func (m *DocMutation) ResetField(name string) error
ResetField resets all changes in the mutation for the field with the given name. It returns an error if the field is not defined in the schema.
func (*DocMutation) ResetOrigin ¶
func (m *DocMutation) ResetOrigin()
ResetOrigin resets all changes to the "origin" field.
func (*DocMutation) ResetSource ¶
func (m *DocMutation) ResetSource()
ResetSource resets all changes to the "source" field.
func (*DocMutation) ResetTitle ¶
func (m *DocMutation) ResetTitle()
ResetTitle resets all changes to the "title" field.
func (*DocMutation) SetCreatedAt ¶
func (m *DocMutation) SetCreatedAt(t time.Time)
SetCreatedAt sets the "created_at" field.
func (*DocMutation) SetField ¶
func (m *DocMutation) SetField(name string, value ent.Value) error
SetField sets the value of a field with the given name. It returns an error if the field is not defined in the schema, or if the type mismatched the field type.
func (*DocMutation) SetID ¶
func (m *DocMutation) SetID(id uuid.UUID)
SetID sets the value of the id field. Note that this operation is only accepted on creation of Doc entities.
func (*DocMutation) SetOp ¶
func (m *DocMutation) SetOp(op Op)
SetOp allows setting the mutation operation.
func (*DocMutation) SetOrigin ¶
func (m *DocMutation) SetOrigin(s string)
SetOrigin sets the "origin" field.
func (*DocMutation) SetSource ¶
func (m *DocMutation) SetSource(s string)
SetSource sets the "source" field.
func (*DocMutation) SetTitle ¶
func (m *DocMutation) SetTitle(s string)
SetTitle sets the "title" field.
func (*DocMutation) Source ¶
func (m *DocMutation) Source() (r string, exists bool)
Source returns the value of the "source" field in the mutation.
func (*DocMutation) SourceCleared ¶
func (m *DocMutation) SourceCleared() bool
SourceCleared returns if the "source" field was cleared in this mutation.
func (*DocMutation) Title ¶
func (m *DocMutation) Title() (r string, exists bool)
Title returns the value of the "title" field in the mutation.
func (DocMutation) Tx ¶
func (m DocMutation) Tx() (*Tx, error)
Tx returns an `ent.Tx` for mutations that were executed in transactions; it returns an error otherwise.
func (*DocMutation) Type ¶
func (m *DocMutation) Type() string
Type returns the node type of this mutation (Doc).
func (*DocMutation) Where ¶
func (m *DocMutation) Where(ps ...predicate.Doc)
Where appends a list predicates to the DocMutation builder.
func (*DocMutation) WhereP ¶
func (m *DocMutation) WhereP(ps ...func(*sql.Selector))
WhereP appends storage-level predicates to the DocMutation builder. Using this method, users can use type-assertion to append predicates that do not depend on any generated package.
type DocPatchRequest ¶
type DocPatchRequest struct {
Title *string `json:"title,omitempty"`
// contains filtered or unexported fields
}
DocPatchRequest is the partial-update request for Doc.
Every field is a pointer and presence is recorded separately, which is what separates the three states a PATCH has to express: absent means "leave it alone", an explicit null means "clear it", and a value means "set it". With bare pointers the first two are the same value, and clearing a field cannot be expressed at all.
A field the ent schema marks Immutable() is absent from this struct, because ent's update builders iterate MutableFields and generate no setter for one. encoding/json discards the key before any validator can see it, so a caller who sends it gets silence — rejecting that needs DisallowUnknownFields, which belongs to the consumer's handler.
func (*DocPatchRequest) HasTitle ¶
func (r *DocPatchRequest) HasTitle() bool
HasTitle reports whether the payload carried "title".
func (*DocPatchRequest) UnmarshalJSON ¶
func (r *DocPatchRequest) UnmarshalJSON(b []byte) error
UnmarshalJSON records which keys the payload carried, including the ones whose value was null — that is the whole point here, and the difference from the create request, where a null has nothing to clear.
A key that case-folds to a canonical tag without matching it exactly is rejected (#58, ADR-0001). The patch side is where that mattered most: a case-variant key decoded into the field while Has<Field>() stayed false, so Apply wrote nothing and the update reported success having changed no row — and a payload carrying BOTH spellings could clear a field the exact key had just set. The check runs after raw decodes and BEFORE the alias decode, so a rejected request leaves the receiver untouched.
func (*DocPatchRequest) Validate ¶
func (r *DocPatchRequest) Validate() (*ValidDocPatchRequest, error)
Validate rejects an explicit null on a field that cannot be cleared.
ent emits Clear<Field>() for Optional fields and for no others, so a null on anything else has no correct translation: the column is NOT NULL and there is no method to call. The field is named in the error, because "invalid request" tells the caller nothing about which key to fix.
type DocQuery ¶
type DocQuery struct {
// contains filtered or unexported fields
}
DocQuery is the builder for querying Doc entities.
func DocQueryWithResponseEdges ¶
DocQueryWithResponseEdges applies the eager-load plan for DocResponse.
The plan is generated from the response type's own edge set, so no individual edge can be omitted from it. Generated wiring always routes through this function.
For a hand-written query, using this function is a convention the type system does not enforce. An entity loaded without this plan makes NewDocResponse return a not-loaded-edge error at run time. It fails loudly; it never silently narrows the response.
With no expanded edges, this function is the identity function. It exists so every entity has the same call shape.
func (*DocQuery) Aggregate ¶
func (dq *DocQuery) Aggregate(fns ...AggregateFunc) *DocSelect
Aggregate returns a DocSelect configured with the given aggregations.
func (*DocQuery) Clone ¶
Clone returns a duplicate of the DocQuery builder, including all associated steps. It can be used to prepare common query builders and use them differently after the clone is made.
func (*DocQuery) First ¶
First returns the first Doc entity from the query. Returns a *NotFoundError when no Doc was found.
func (*DocQuery) FirstID ¶
FirstID returns the first Doc ID from the query. Returns a *NotFoundError when no Doc ID was found.
func (*DocQuery) GroupBy ¶
func (dq *DocQuery) GroupBy(field string, fields ...string) *DocGroupBy
GroupBy is used to group vertices by one or more fields/columns. It is often used with aggregate functions, like: count, max, mean, min, sum.
Example:
var v []struct {
Title string `json:"title,omitempty"`
Count int `json:"count,omitempty"`
}
client.Doc.Query().
GroupBy(doc.FieldTitle).
Aggregate(immutableent.Count()).
Scan(ctx, &v)
func (*DocQuery) Only ¶
Only returns a single Doc entity found by the query, ensuring it only returns one. Returns a *NotSingularError when more than one Doc entity is found. Returns a *NotFoundError when no Doc entities are found.
func (*DocQuery) OnlyID ¶
OnlyID is like Only, but returns the only Doc ID in the query. Returns a *NotSingularError when more than one Doc ID is found. Returns a *NotFoundError when no entities are found.
func (*DocQuery) Order ¶
func (dq *DocQuery) Order(o ...doc.OrderOption) *DocQuery
Order specifies how the records should be ordered.
func (*DocQuery) Select ¶
Select allows the selection one or more fields/columns for the given query, instead of selecting all fields in the entity.
Example:
var v []struct {
Title string `json:"title,omitempty"`
}
client.Doc.Query().
Select(doc.FieldTitle).
Scan(ctx, &v)
type DocResponse ¶
type DocResponse struct {
// ID field is always included in responses
ID uuid.UUID `json:"id"`
Title string `json:"title"`
Origin string `json:"origin"`
Source *string `json:"source,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
DocResponse represents the response for Doc.
It is emitted unconditionally: an entity whose every scalar field is Sensitive still has a meaningful response carrying its ID, and DocListResponse below refers to this type either way.
func CreateDoc ¶
func CreateDoc(ctx context.Context, db *Client, v *ValidDocCreateRequest) (*DocResponse, error)
CreateDoc inserts one Doc and returns its response.
It takes the VALIDATED request. Apply is defined on that type and nowhere else, so validation is a compile-time requirement here rather than a step this function could forget on the caller's behalf.
func NewDocResponse ¶
func NewDocResponse(e *Doc) (*DocResponse, error)
NewDocResponse converts an entity to its response DTO.
This entity declares no response edges, so the error is always nil. The signature is kept uniform so callers do not need two shapes.
func PatchDoc ¶
func PatchDoc(ctx context.Context, db *Client, id uuid.UUID, v *ValidDocPatchRequest) (*DocResponse, error)
PatchDoc applies a validated patch to one Doc.
Fields the patch did not carry are not written at all, so a partial update stays partial — that property belongs to Apply, and this function does not re-decide it.
type DocSelect ¶
type DocSelect struct {
*DocQuery
// contains filtered or unexported fields
}
DocSelect is the builder for selecting fields of Doc entities.
func (*DocSelect) Aggregate ¶
func (ds *DocSelect) Aggregate(fns ...AggregateFunc) *DocSelect
Aggregate adds the given aggregation functions to the selector query.
func (*DocSelect) Bool ¶
Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (*DocSelect) Bools ¶
Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (*DocSelect) Float64 ¶
Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (*DocSelect) Float64s ¶
Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (*DocSelect) Int ¶
Int returns a single int from a selector. It is only allowed when selecting one field.
func (*DocSelect) Ints ¶
Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (*DocSelect) String ¶
String returns a single string from a selector. It is only allowed when selecting one field.
type DocSummary ¶
type DocSummary struct {
// ID field is always included in summaries
ID uuid.UUID `json:"id"`
Title string `json:"title"`
Origin string `json:"origin"`
Source *string `json:"source,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
DocSummary is the shape Doc takes on another entity's response.
It carries the same scalar fields as DocResponse and no edges at all. That is what bounds expansion: NewDocResponse calls summary constructors, and a summary constructor calls nothing, so there is no second level for a cycle to close through and no runtime depth counter is needed.
The cost is real rather than hidden: a three-level tree comes back one level deep, and a deeper one needs another round trip per level.
func NewDocSummary ¶
func NewDocSummary(e *Doc) *DocSummary
NewDocSummary converts an entity to its summary DTO. It cannot fail: a summary reads no edges.
type DocUpdate ¶
type DocUpdate struct {
// contains filtered or unexported fields
}
DocUpdate is the builder for updating Doc entities.
func (*DocUpdate) Mutation ¶
func (du *DocUpdate) Mutation() *DocMutation
Mutation returns the DocMutation object of the builder.
func (*DocUpdate) Save ¶
Save executes the query and returns the number of nodes affected by the update operation.
func (*DocUpdate) SetNillableTitle ¶
SetNillableTitle sets the "title" field if the given value is not nil.
type DocUpdateOne ¶
type DocUpdateOne struct {
// contains filtered or unexported fields
}
DocUpdateOne is the builder for updating a single Doc entity.
func (*DocUpdateOne) Exec ¶
func (duo *DocUpdateOne) Exec(ctx context.Context) error
Exec executes the query on the entity.
func (*DocUpdateOne) ExecX ¶
func (duo *DocUpdateOne) ExecX(ctx context.Context)
ExecX is like Exec, but panics if an error occurs.
func (*DocUpdateOne) Mutation ¶
func (duo *DocUpdateOne) Mutation() *DocMutation
Mutation returns the DocMutation object of the builder.
func (*DocUpdateOne) Save ¶
func (duo *DocUpdateOne) Save(ctx context.Context) (*Doc, error)
Save executes the query and returns the updated Doc entity.
func (*DocUpdateOne) SaveX ¶
func (duo *DocUpdateOne) SaveX(ctx context.Context) *Doc
SaveX is like Save, but panics if an error occurs.
func (*DocUpdateOne) Select ¶
func (duo *DocUpdateOne) Select(field string, fields ...string) *DocUpdateOne
Select allows selecting one or more fields (columns) of the returned entity. The default is selecting all fields defined in the entity schema.
func (*DocUpdateOne) SetNillableTitle ¶
func (duo *DocUpdateOne) SetNillableTitle(s *string) *DocUpdateOne
SetNillableTitle sets the "title" field if the given value is not nil.
func (*DocUpdateOne) SetTitle ¶
func (duo *DocUpdateOne) SetTitle(s string) *DocUpdateOne
SetTitle sets the "title" field.
func (*DocUpdateOne) Where ¶
func (duo *DocUpdateOne) Where(ps ...predicate.Doc) *DocUpdateOne
Where appends a list predicates to the DocUpdate builder.
type InterceptFunc ¶
type InterceptFunc = ent.InterceptFunc
ent aliases to avoid import conflicts in user's code.
type Interceptor ¶
type Interceptor = ent.Interceptor
ent aliases to avoid import conflicts in user's code.
type ListDocsFn ¶
type ListDocsFn func(context.Context, *Client, *DocFilter, entapi.ListRequest) (*entapi.Page[DocResponse], error)
ListDocsFn is byte-identical to ListDocs.
type MutateFunc ¶
type MutateFunc = ent.MutateFunc
ent aliases to avoid import conflicts in user's code.
type NotFoundError ¶
type NotFoundError struct {
// contains filtered or unexported fields
}
NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
func (*NotFoundError) Error ¶
func (e *NotFoundError) Error() string
Error implements the error interface.
type NotLoadedError ¶
type NotLoadedError struct {
// contains filtered or unexported fields
}
NotLoadedError returns when trying to get a node that was not loaded by the query.
func (*NotLoadedError) Error ¶
func (e *NotLoadedError) Error() string
Error implements the error interface.
type NotSingularError ¶
type NotSingularError struct {
// contains filtered or unexported fields
}
NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
func (*NotSingularError) Error ¶
func (e *NotSingularError) Error() string
Error implements the error interface.
type OrderFunc ¶
OrderFunc applies an ordering on the sql selector. Deprecated: Use Asc/Desc functions or the package builders instead.
type PatchDocFn ¶
type PatchDocFn func(context.Context, *Client, uuid.UUID, *ValidDocPatchRequest) (*DocResponse, error)
PatchDocFn is byte-identical to PatchDoc.
type QuerierFunc ¶
type QuerierFunc = ent.QuerierFunc
ent aliases to avoid import conflicts in user's code.
type QueryContext ¶
type QueryContext = ent.QueryContext
ent aliases to avoid import conflicts in user's code.
type RollbackFunc ¶
The RollbackFunc type is an adapter to allow the use of ordinary function as a Rollbacker. If f is a function with the appropriate signature, RollbackFunc(f) is a Rollbacker that calls f.
type RollbackHook ¶
type RollbackHook func(Rollbacker) Rollbacker
RollbackHook defines the "rollback middleware". A function that gets a Rollbacker and returns a Rollbacker. For example:
hook := func(next ent.Rollbacker) ent.Rollbacker {
return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
// Do some stuff before.
if err := next.Rollback(ctx, tx); err != nil {
return err
}
// Do some stuff after.
return nil
})
}
type Rollbacker ¶
Rollbacker is the interface that wraps the Rollback method.
type TraverseFunc ¶
type TraverseFunc = ent.TraverseFunc
ent aliases to avoid import conflicts in user's code.
type Tx ¶
type Tx struct {
// Doc is the client for interacting with the Doc builders.
Doc *DocClient
// contains filtered or unexported fields
}
Tx is a transactional client that is created by calling Client.Tx().
func TxFromContext ¶
TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
func (*Tx) OnRollback ¶
func (tx *Tx) OnRollback(f RollbackHook)
OnRollback adds a hook to call on rollback.
type ValidDocCreateRequest ¶
type ValidDocCreateRequest struct {
// contains filtered or unexported fields
}
ValidDocCreateRequest wraps a DocCreateRequest that has passed Validate. Apply is defined on this type and nowhere else, so a caller who skips validation has no method to call — a compile error rather than a validator that runs only when someone remembers it.
func (*ValidDocCreateRequest) Apply ¶
func (v *ValidDocCreateRequest) Apply(b *DocCreate) *DocCreate
Apply writes the request onto a create builder.
A field the caller omitted is not written at all, so the schema's Default() still applies. Writing the zero value unconditionally is what silently defeated every schema default.
func (*ValidDocCreateRequest) HasOrigin ¶
func (v *ValidDocCreateRequest) HasOrigin() bool
HasOrigin reports whether the payload carried "origin".
func (*ValidDocCreateRequest) HasSource ¶
func (v *ValidDocCreateRequest) HasSource() bool
HasSource reports whether the payload carried "source".
func (*ValidDocCreateRequest) HasTitle ¶
func (v *ValidDocCreateRequest) HasTitle() bool
HasTitle reports whether the payload carried "title".
type ValidDocPatchRequest ¶
type ValidDocPatchRequest struct {
// contains filtered or unexported fields
}
ValidDocPatchRequest wraps a DocPatchRequest that has passed Validate. It is the only type Apply is defined on.
func (*ValidDocPatchRequest) Apply ¶
func (v *ValidDocPatchRequest) Apply(b *DocUpdateOne) *DocUpdateOne
Apply writes the request onto an update builder. Absent fields are not touched; the rest are set, or cleared when the caller sent an explicit null.
func (*ValidDocPatchRequest) HasTitle ¶
func (v *ValidDocPatchRequest) HasTitle() bool
HasTitle reports whether the payload carried "title".
A custom implementation receives only the validated type, so without this forwarder the patch's presence — the one thing that distinguishes "clear it" from "leave it alone" — is unreachable from the customization point that is supposed to act on it.
func (*ValidDocPatchRequest) Title ¶
func (v *ValidDocPatchRequest) Title() (string, bool)
Title reports the value the payload carried for "title", and whether Apply will Set it.
Presence is two of the three states a PATCH field has; this reads the third. Paired with HasTitle(), which is "present" below:
ok the payload carried a value; Apply will Set it
!ok, present the payload carried an explicit null; Apply will
Clear it. Reachable only for a clearable field —
Validate refuses a null on anything else
!ok, absent the key was not in the payload; Apply writes nothing
Without it a cross-field rule cannot tell "clear this" from "set this", and the customization point is forced to allocate an update builder it never executes, Apply the request to it and read back Mutation() (#113).
type ValidationError ¶
type ValidationError struct {
Name string // Field or edge name.
// contains filtered or unexported fields
}
ValidationError returns when validating a field or edge fails.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error implements the error interface.
func (*ValidationError) Unwrap ¶
func (e *ValidationError) Unwrap() error
Unwrap implements the errors.Wrapper interface.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package schema holds the hand-written ent schema for the "immutable" codegen fixture: Ent Immutable fields derive out of PATCH without a second opinion.
|
Package schema holds the hand-written ent schema for the "immutable" codegen fixture: Ent Immutable fields derive out of PATCH without a second opinion. |